Debian Codegraph @

database/redis.go

raw
1 // Copyright (c) 2014-2019 Ludovic Fauvet
2 // Licensed under the MIT license
3
4 package database
5
6 import (
7 "errors"
8 "fmt"
9 "strconv"
10 "strings"
11 "sync"
12 "time"
13
14 . "github.com/etix/mirrorbits/config"
15 "github.com/etix/mirrorbits/core"
16 "github.com/gomodule/redigo/redis"
17 "github.com/rafaeljusto/redigomock"
18 )
19
20 const (
21 redisConnectionTimeout = 200 * time.Millisecond
22 redisReadWriteTimeout = 300 * time.Second
23 )
24
25 var (
26 // ErrUnreachable is returned when the endpoint is not reachable
27 ErrUnreachable = errors.New("redis endpoint unreachable")
28 )
29
30 type redisPool interface {
31 Get() redis.Conn
32 Close() error
33 }
34
35 // Redis is the instance object of the redis database
36 type Redis struct {
37 pool redisPool
38 Pubsub *Pubsub
39 failure bool
40 failureState sync.RWMutex
41 knownMaster string
42 knownMasterLock sync.Mutex
43 stop chan bool
44 ready chan struct{}
45 version string
46 }
47
48 // NewRedis returns a new instance of the redis database
49 func NewRedis() *Redis {
50 r := NewRedisCustomPool(nil)
51
52 // Asynchronous db update handler
53 go r.dbUpdateHandler()
54
55 return r
56 }
57
58 // NewRedisCustomPool returns a new instance of the redis database
59 // using a custom pool
60 func NewRedisCustomPool(pool redisPool) *Redis {
61 r := &Redis{
62 stop: make(chan bool),
63 ready: make(chan struct{}),
64 }
65
66 if pool != nil {
67 // Check if we are running inside `go test`
68 if _, ok := pool.Get().(*redigomock.Conn); ok {
69 // Close ready since we are running a mock
70 close(r.ready)
71 }
72 r.pool = pool
73 } else {
74 r.pool = &redis.Pool{
75 MaxIdle: 10,
76 IdleTimeout: 240 * time.Second,
77 Dial: func() (redis.Conn, error) {
78 conn, err := r.Connect()
79
80 switch err {
81 case nil:
82 r.setFailureState(false)
83 default:
84 r.setFailureState(true)
85 }
86
87 if r.version != "" && ! r.IsAtLeastVersion(core.RedisMinimumVersion) {
88 log.Fatalf("Unsupported Redis version, please upgrade to Redis >= %s", core.RedisMinimumVersion)
89 }
90
91 return conn, err
92 },
93 TestOnBorrow: func(c redis.Conn, t time.Time) error {
94 _, err := c.Do("PING")
95 if RedisIsLoading(err) {
96 return nil
97 }
98 return err
99 },
100 }
101 }
102
103 go r.connRecover()
104
105 return r
106 }
107
108 // Get returns a redis connection from the pool
109 func (r *Redis) Get() redis.Conn {
110 select {
111 case <-r.ready:
112 default:
113 return &NotReadyError{}
114 }
115 return r.pool.Get()
116 }
117
118 // UnblockedGet returns a redis connection from the pool even
119 // if the database checks and/or upgrade are not finished.
120 func (r *Redis) UnblockedGet() redis.Conn {
121 return r.pool.Get()
122 }
123
124 // Close closes all connections to the redis database
125 func (r *Redis) Close() {
126 select {
127 case _, _ = <-r.stop:
128 return
129 default:
130 log.Debug("Closing databases connections")
131 r.Pubsub.Close()
132 r.pool.Close()
133 close(r.stop)
134 }
135 }
136
137 // ConnectPubsub initiates the connection to the pubsub
138 func (r *Redis) ConnectPubsub() {
139 if r.Pubsub == nil {
140 r.Pubsub = NewPubsub(r)
141 }
142 }
143
144 func (r *Redis) IsAtLeastVersion(version string) bool {
145 return parseVersion(r.version) >= parseVersion(version)
146 }
147
148 func (r *Redis) askVersion (conn redis.Conn) (string, error) {
149 if conn == nil {
150 return "", ErrUnreachable
151 }
152
153 info, err := parseInfo(conn.Do("INFO", "server"))
154 if err != nil {
155 return "", err
156 }
157
158 return info["redis_version"], nil
159 }
160
161 // Connect initiates a new connection to the redis server
162 func (r *Redis) Connect() (redis.Conn, error) {
163 sentinels := GetConfig().RedisSentinels
164
165 if len(sentinels) > 0 {
166
167 if len(GetConfig().RedisSentinelMasterName) == 0 {
168 r.logError("Config: RedisSentinelMasterName cannot be empty!")
169 goto single
170 }
171
172 for _, s := range sentinels {
173 log.Debugf("Connecting to redis sentinel %s", s.Host)
174 var master []string
175 var masterhost string
176 var cm redis.Conn
177
178 c, err := r.connectTo(s.Host)
179 if err != nil {
180 r.logError("Sentinel: %s", err.Error())
181 continue
182 }
183 //AUTH?
184 role, err := r.askRole(c)
185 if err != nil {
186 r.logError("Sentinel: %s", err.Error())
187 goto closeSentinel
188 }
189 if role != "sentinel" {
190 r.logError("Sentinel: %s is not a sentinel but a %s", s.Host, role)
191 goto closeSentinel
192 }
193
194 master, err = redis.Strings(c.Do("SENTINEL", "get-master-addr-by-name", GetConfig().RedisSentinelMasterName))
195 if err == redis.ErrNil {
196 r.logError("Sentinel: %s doesn't know the master-name %s", s.Host, GetConfig().RedisSentinelMasterName)
197 goto closeSentinel
198 } else if err != nil {
199 r.logError("Sentinel: %s", err.Error())
200 goto closeSentinel
201 }
202
203 masterhost = fmt.Sprintf("%s:%s", master[0], master[1])
204
205 cm, err = r.connectTo(masterhost)
206 if err != nil {
207 r.logError("Redis master: %s", err.Error())
208 goto closeSentinel
209 }
210
211 if r.auth(cm) != nil {
212 r.logError("Redis master: auth failed")
213 goto closeMaster
214 }
215 if err = r.selectDB(cm); err != nil {
216 c.Close()
217 return nil, err
218 }
219
220 role, err = r.askRole(cm)
221 if err != nil {
222 r.logError("Redis master: %s", err.Error())
223 goto closeMaster
224 }
225 if role != "master" {
226 r.logError("Redis master: %s is not a master but a %s", masterhost, role)
227 goto closeMaster
228 }
229
230 // Close the connection to the sentinel
231 c.Close()
232
233 r.printConnectedMaster(masterhost)
234 return cm, nil
235
236 closeMaster:
237 cm.Close()
238
239 closeSentinel:
240 c.Close()
241 }
242 }
243
244 single:
245
246 if len(GetConfig().RedisAddress) == 0 {
247 if len(sentinels) == 0 {
248 log.Error("No redis master available")
249 }
250 return nil, ErrUnreachable
251 }
252
253 if len(sentinels) > 0 && r.Failure() == false {
254 log.Warning("No redis master available, trying using the configured RedisAddress as fallback")
255 }
256
257 c, err := r.connectTo(GetConfig().RedisAddress)
258 if err != nil {
259 return nil, err
260 }
261 if err = r.auth(c); err != nil {
262 c.Close()
263 return nil, err
264 }
265 if err = r.selectDB(c); err != nil {
266 c.Close()
267 return nil, err
268 }
269 role, err := r.askRole(c)
270 if err != nil {
271 r.logError("Redis master: %s", err.Error())
272 return nil, ErrUnreachable
273 }
274 if role != "master" {
275 r.logError("Redis master: %s is not a master but a %s", GetConfig().RedisAddress, role)
276 return nil, ErrUnreachable
277 }
278
279 r.version, err = r.askVersion(c)
280
281 r.printConnectedMaster(GetConfig().RedisAddress)
282
283 return c, err
284
285 }
286
287 func (r *Redis) connectTo(address string) (redis.Conn, error) {
288 return redis.Dial("tcp", address,
289 redis.DialConnectTimeout(redisConnectionTimeout),
290 redis.DialReadTimeout(redisReadWriteTimeout),
291 redis.DialWriteTimeout(redisReadWriteTimeout))
292 }
293
294 func (r *Redis) askRole(c redis.Conn) (string, error) {
295 roleReply, err := redis.Values(c.Do("ROLE"))
296 if err != nil {
297 return "", err
298 }
299 role, err := redis.String(roleReply[0], err)
300 return role, err
301 }
302
303 func (r *Redis) auth(c redis.Conn) (err error) {
304 if GetConfig().RedisPassword != "" {
305 _, err = c.Do("AUTH", GetConfig().RedisPassword)
306 }
307 return
308 }
309
310 func (r *Redis) selectDB(c redis.Conn) (err error) {
311 _, err = c.Do("SELECT", GetConfig().RedisDB)
312 return
313 }
314
315 func (r *Redis) logError(format string, args ...any) {
316 if r.Failure() {
317 log.Debugf(format, args...)
318 } else {
319 log.Errorf(format, args...)
320 }
321 }
322
323 func (r *Redis) printConnectedMaster(address string) {
324 r.knownMasterLock.Lock()
325 defer r.knownMasterLock.Unlock()
326 if address != r.knownMaster && core.Daemon {
327 r.knownMaster = address
328 log.Infof("Connected to redis master %s (version %s)", address, r.version)
329 } else {
330 log.Debugf("Connected to redis master %s (version %s)", address, r.version)
331 }
332 }
333
334 func (r *Redis) setFailureState(failure bool) {
335 r.failureState.Lock()
336 r.failure = failure
337 r.failureState.Unlock()
338 }
339
340 // Failure returns true if the connection is in a failure state
341 func (r *Redis) Failure() bool {
342 r.failureState.RLock()
343 defer r.failureState.RUnlock()
344 return r.failure
345 }
346
347 func (r *Redis) connRecover() {
348 ticker := time.NewTicker(1 * time.Second)
349
350 for {
351 select {
352 case <-r.stop:
353 return
354 case <-ticker.C:
355 if r.Failure() {
356 if conn := r.Get(); conn != nil {
357 // A successful Get() request will automatically unlock
358 // other services waiting for a working connection.
359 // This is only a way to ensure they wont wait forever.
360 if conn.Err() != nil {
361 log.Warningf("Database is down: %s", conn.Err().Error())
362 }
363 conn.Close()
364 }
365 }
366 }
367 }
368 }
369
370 func (r *Redis) dbUpdateHandler() {
371 var logOnce sync.Once
372
373 again:
374 upneeded, err := r.UpgradeNeeded()
375 if err != nil {
376 time.Sleep(100 * time.Millisecond)
377 goto again
378 }
379 if upneeded {
380 t := time.Now()
381 err = r.Upgrade()
382 if err == ErrAlreadyLocked {
383 logOnce.Do(func() {
384 log.Warning("Database upgrade running. Waiting for completion...")
385 })
386 time.Sleep(100 * time.Millisecond)
387 goto again
388 } else if err != nil {
389 log.Fatalf("Upgrade failed: %v", err)
390 }
391 log.Infof("Database upgrade successful (took %s), starting normally", time.Since(t).Round(time.Millisecond))
392 }
393 close(r.ready)
394 }
395
396 // RedisIsLoading returns true if the error is of type LOADING
397 func RedisIsLoading(err error) bool {
398 // PARSING: "LOADING Redis is loading the dataset in memory"
399 if err != nil && strings.HasPrefix(err.Error(), "LOADING") {
400 return true
401 }
402 return false
403 }
404
405 func parseVersion(version string) int64 {
406 // We suppport up to 3 components (major, minor, patch) in the version
407 s := strings.Split(version, ".")
408 for len(s) < 3 {
409 s = append(s, "0")
410 }
411
412 format := fmt.Sprintf("%%s%%0%ds", 2)
413
414 var v string
415 for _, value := range s {
416 v = fmt.Sprintf(format, v, value)
417 }
418
419 var result int64
420 var err error
421 if result, err = strconv.ParseInt(v, 10, 64); err != nil {
422 return -1
423 }
424 return result
425 }
426
427 func parseInfo(i any, err error) (map[string]string, error) {
428 v, err := redis.String(i, err)
429 if err != nil {
430 return nil, err
431 }
432
433 m := make(map[string]string)
434 lines := strings.Split(v, "\r\n")
435
436 for _, l := range lines {
437 if strings.HasPrefix(l, "#") {
438 continue
439 }
440
441 kv := strings.SplitN(l, ":", 2)
442 if len(kv) < 2 {
443 continue
444 }
445
446 m[kv[0]] = kv[1]
447 }
448
449 return m, nil
450 }