Debian Codegraph @

redis_shard.go

raw
1 package centrifuge
2
3 import (
4 "crypto/tls"
5 "errors"
6 "fmt"
7 "hash/fnv"
8 "net"
9 "net/url"
10 "strconv"
11 "strings"
12 "sync"
13 "time"
14
15 "github.com/centrifugal/centrifuge/internal/timers"
16
17 "github.com/FZambia/sentinel"
18 "github.com/gomodule/redigo/redis"
19 "github.com/mna/redisc"
20 )
21
22 type (
23 // channelID is unique channel identifier in Redis.
24 channelID string
25 )
26
27 var errRedisOpTimeout = errors.New("operation timed out")
28
29 const (
30 DefaultRedisReadTimeout = time.Second
31 DefaultRedisWriteTimeout = time.Second
32 DefaultRedisConnectTimeout = time.Second
33 )
34
35 const (
36 defaultRedisPoolSize = 128
37 // redisDataBatchLimit is a max amount of data requests in one batch.
38 redisDataBatchLimit = 64
39 )
40
41 type redisConnPool interface {
42 Get() redis.Conn
43 }
44
45 type RedisShard struct {
46 config RedisShardConfig
47 pool redisConnPool
48 subCh chan subRequest
49 pubCh chan pubRequest
50 dataCh chan *dataRequest
51 useCluster bool
52 scriptsMu sync.RWMutex
53 scripts []*redis.Script
54 scriptsCh chan struct{}
55 }
56
57 func confFromAddress(address string, conf RedisShardConfig) (RedisShardConfig, error) {
58 if !strings.HasPrefix(address, "tcp://") && !strings.HasPrefix(address, "redis://") && !strings.HasPrefix(address, "unix://") {
59 if host, port, err := net.SplitHostPort(address); err == nil && host != "" && port != "" {
60 conf.network = "tcp"
61 conf.address = address
62 return conf, nil
63 }
64 return conf, errors.New("malformed connection address")
65 }
66 u, err := url.Parse(address)
67 if err != nil {
68 return conf, errors.New("malformed connection address")
69 }
70 switch u.Scheme {
71 case "tcp", "redis":
72 conf.network = "tcp"
73 conf.address = u.Host
74 if u.Path != "" {
75 db, err := strconv.Atoi(strings.TrimPrefix(u.Path, "/"))
76 if err != nil {
77 return conf, fmt.Errorf("can't parse Redis DB number from connection address")
78 }
79 conf.DB = db
80 }
81 case "unix":
82 conf.network = "unix"
83 conf.address = u.Path
84 default:
85 return conf, errors.New("connection address should have tcp://, redis:// or unix:// scheme")
86 }
87 if u.User != nil {
88 if pass, ok := u.User.Password(); ok {
89 conf.Password = pass
90 }
91 }
92 return conf, nil
93 }
94
95 // NewRedisShard initializes new Redis shard.
96 func NewRedisShard(n *Node, conf RedisShardConfig) (*RedisShard, error) {
97 var err error
98 if conf.Address != "" {
99 conf, err = confFromAddress(conf.Address, conf)
100 if err != nil {
101 return nil, err
102 }
103 }
104 shard := &RedisShard{
105 config: conf,
106 scriptsCh: make(chan struct{}, 1),
107 useCluster: len(conf.ClusterAddresses) > 0,
108 }
109 pool, err := newPool(shard, n, conf)
110 if err != nil {
111 return nil, err
112 }
113 shard.scripts = []*redis.Script{}
114 shard.pool = pool
115 shard.subCh = make(chan subRequest)
116 shard.pubCh = make(chan pubRequest)
117 shard.dataCh = make(chan *dataRequest)
118 if !shard.useCluster {
119 // Only need data pipeline in non-cluster scenario.
120 go func() {
121 for {
122 err := shard.runDataPipeline()
123 if err != nil {
124 n.Log(NewLogEntry(LogLevelError, "data pipeline error", map[string]interface{}{"error": err.Error()}))
125 time.Sleep(300 * time.Millisecond)
126 }
127 }
128 }()
129 }
130 return shard, nil
131 }
132
133 // RedisShardConfig contains Redis connection options.
134 type RedisShardConfig struct {
135 // Address is a Redis server connection address.
136 // This can be:
137 // - host:port
138 // - tcp://[[:password]@]host:port[/db][?option1=value1&optionN=valueN]
139 // - redis://[[:password]@]host:port[/db][?option1=value1&optionN=valueN]
140 // - unix://[[:password]@]path[?option1=value1&optionN=valueN]
141 Address string
142
143 // ClusterAddresses is a slice of seed cluster addrs for this shard.
144 // Each address should be in form of host:port. If ClusterAddresses set then
145 // RedisShardConfig.Address not used.
146 ClusterAddresses []string
147
148 // SentinelAddresses is a slice of Sentinel addresses. Each address should
149 // be in form of host:port. If set then Redis address will be automatically
150 // discovered from Sentinel.
151 SentinelAddresses []string
152 // SentinelMasterName is a name of Redis instance master Sentinel monitors.
153 SentinelMasterName string
154 // SentinelPassword is a password for Sentinel. Works with Sentinel >= 5.0.1.
155 SentinelPassword string
156
157 // DB is Redis database number. If not set then database 0 used.
158 DB int
159 // Password is password to use when connecting to Redis database.
160 // If zero then password not used.
161 Password string
162 // Whether to use TLS connection or not.
163 UseTLS bool
164 // Whether to skip hostname verification as part of TLS handshake.
165 TLSSkipVerify bool
166 // Connection TLS configuration.
167 TLSConfig *tls.Config
168 // IdleTimeout is timeout after which idle connections to Redis will be closed.
169 // If the value is zero, then idle connections are not closed.
170 IdleTimeout time.Duration
171 // ReadTimeout is a timeout on read operations. Note that at moment it should be greater
172 // than node ping publish interval in order to prevent timing out Pub/Sub connection's
173 // Receive call.
174 // By default DefaultRedisReadTimeout used.
175 ReadTimeout time.Duration
176 // WriteTimeout is a timeout on write operations.
177 // By default DefaultRedisWriteTimeout used.
178 WriteTimeout time.Duration
179 // ConnectTimeout is a timeout on connect operation.
180 // By default DefaultRedisConnectTimeout used.
181 ConnectTimeout time.Duration
182
183 network string
184 address string
185 }
186
187 type pubRequest struct {
188 channel channelID
189 message []byte
190 err chan error
191 }
192
193 func (pr *pubRequest) done(err error) {
194 pr.err <- err
195 }
196
197 type dataResponse struct {
198 reply interface{}
199 err error
200 }
201
202 type dataRequest struct {
203 command string
204 script *redis.Script
205 args []interface{}
206 resp chan *dataResponse
207 clusterKey string
208 }
209
210 func (s *RedisShard) newDataRequest(command string, script *redis.Script, clusterKey channelID, args []interface{}) *dataRequest {
211 dr := &dataRequest{command: command, script: script, args: args, resp: make(chan *dataResponse, 1)}
212 if s.useCluster {
213 dr.setClusterKey(string(clusterKey))
214 }
215 return dr
216 }
217
218 func (s *RedisShard) string() string {
219 return s.config.address
220 }
221
222 func (dr *dataRequest) setClusterKey(key string) {
223 dr.clusterKey = key
224 }
225
226 func (dr *dataRequest) done(reply interface{}, err error) {
227 if dr.resp == nil {
228 return
229 }
230 dr.resp <- &dataResponse{reply: reply, err: err}
231 }
232
233 func (dr *dataRequest) result() *dataResponse {
234 if dr.resp == nil {
235 // No waiting, as caller didn't care about response.
236 return &dataResponse{}
237 }
238 return <-dr.resp
239 }
240
241 func (s *RedisShard) registerScripts(scripts ...*redis.Script) {
242 s.scriptsMu.Lock()
243 defer s.scriptsMu.Unlock()
244 s.scripts = append(s.scripts, scripts...)
245 select {
246 case s.scriptsCh <- struct{}{}:
247 // Trigger script loading.
248 default:
249 }
250 }
251
252 func (s *RedisShard) getDataResponse(r *dataRequest) *dataResponse {
253 if s.useCluster {
254 reply, err := s.processClusterDataRequest(r)
255 return &dataResponse{
256 reply: reply,
257 err: err,
258 }
259 }
260 select {
261 case s.dataCh <- r:
262 default:
263 timer := timers.AcquireTimer(s.readTimeout())
264 defer timers.ReleaseTimer(timer)
265 select {
266 case s.dataCh <- r:
267 case <-timer.C:
268 return &dataResponse{nil, errRedisOpTimeout}
269 }
270 }
271 return r.result()
272 }
273
274 func (s *RedisShard) processClusterDataRequest(dr *dataRequest) (interface{}, error) {
275 conn := s.pool.Get()
276 defer func() { _ = conn.Close() }()
277
278 var err error
279
280 if dr.clusterKey != "" {
281 if c, ok := conn.(*redisc.Conn); ok {
282 err := c.Bind(dr.clusterKey)
283 if err != nil {
284 return nil, err
285 }
286 }
287 }
288
289 // Handle redirects automatically.
290 conn, err = redisc.RetryConn(conn, 3, 50*time.Millisecond)
291 if err != nil {
292 return nil, err
293 }
294
295 if dr.script != nil {
296 return dr.script.Do(conn, dr.args...)
297 }
298 return conn.Do(dr.command, dr.args...)
299 }
300
301 func (s *RedisShard) runDataPipeline() error {
302 conn := s.pool.Get()
303 s.scriptsMu.RLock()
304 scripts := make([]*redis.Script, len(s.scripts))
305 copy(scripts, s.scripts)
306 s.scriptsMu.RUnlock()
307 for _, script := range scripts {
308 err := script.Load(conn)
309 if err != nil {
310 // Can not proceed if script has not been loaded.
311 _ = conn.Close()
312 return fmt.Errorf("error loading Lua script: %w", err)
313 }
314 }
315 _ = conn.Close()
316
317 var drs []*dataRequest
318
319 for {
320 select {
321 case <-s.scriptsCh:
322 s.scriptsMu.RLock()
323 if len(s.scripts) == len(scripts) {
324 s.scriptsMu.RUnlock()
325 continue
326 }
327 s.scriptsMu.RUnlock()
328 return nil
329 case dr := <-s.dataCh:
330 drs = append(drs, dr)
331 loop:
332 for len(drs) < redisDataBatchLimit {
333 select {
334 case req := <-s.dataCh:
335 drs = append(drs, req)
336 default:
337 break loop
338 }
339 }
340
341 conn := s.pool.Get()
342
343 for i := range drs {
344 if drs[i].script != nil {
345 _ = drs[i].script.SendHash(conn, drs[i].args...)
346 } else {
347 _ = conn.Send(drs[i].command, drs[i].args...)
348 }
349 }
350
351 err := conn.Flush()
352 if err != nil {
353 for i := range drs {
354 drs[i].done(nil, err)
355 }
356 _ = conn.Close()
357 return fmt.Errorf("error flushing data pipeline: %w", err)
358 }
359 var noScriptError bool
360 for i := range drs {
361 reply, err := conn.Receive()
362 if err != nil {
363 // Check for NOSCRIPT error. In normal circumstances this should never happen.
364 // The only possible situation is when Redis scripts were flushed. In this case
365 // we will return from this func and load publish script from scratch.
366 // Redigo does the same check but for single EVALSHA command: see
367 // https://github.com/garyburd/redigo/blob/master/redis/script.go#L64
368 if e, ok := err.(redis.Error); ok && strings.HasPrefix(string(e), "NOSCRIPT ") {
369 noScriptError = true
370 }
371 }
372 drs[i].done(reply, err)
373 }
374 if conn.Err() != nil {
375 _ = conn.Close()
376 return nil
377 }
378 if noScriptError {
379 // Start this func from the beginning and LOAD missing script.
380 _ = conn.Close()
381 return nil
382 }
383 _ = conn.Close()
384 drs = nil
385 }
386 }
387 }
388
389 // subRequest is an internal request to subscribe or unsubscribe from one or more channels.
390 type subRequest struct {
391 channels []channelID
392 subscribe bool
393 err chan error
394 }
395
396 // newSubRequest creates a new request to subscribe or unsubscribe form a channel.
397 func newSubRequest(chIDs []channelID, subscribe bool) subRequest {
398 return subRequest{
399 channels: chIDs,
400 subscribe: subscribe,
401 err: make(chan error, 1),
402 }
403 }
404
405 // done should only be called once for subRequest.
406 func (sr *subRequest) done(err error) {
407 sr.err <- err
408 }
409
410 func (sr *subRequest) result() error {
411 return <-sr.err
412 }
413
414 func makePoolFactory(s *RedisShard, n *Node, conf RedisShardConfig) func(addr string, options ...redis.DialOption) (*redis.Pool, error) {
415 password := conf.Password
416 db := conf.DB
417
418 useSentinel := conf.SentinelMasterName != "" && len(conf.SentinelAddresses) > 0
419
420 var lastMu sync.Mutex
421 var lastMaster string
422
423 poolSize := defaultRedisPoolSize
424 maxIdle := poolSize
425
426 var sntnl *sentinel.Sentinel
427 if useSentinel {
428 sntnl = &sentinel.Sentinel{
429 Addrs: conf.SentinelAddresses,
430 MasterName: conf.SentinelMasterName,
431 Dial: func(addr string) (redis.Conn, error) {
432 timeout := 300 * time.Millisecond
433 opts := []redis.DialOption{
434 redis.DialConnectTimeout(timeout),
435 redis.DialReadTimeout(timeout),
436 redis.DialWriteTimeout(timeout),
437 }
438 c, err := redis.Dial("tcp", addr, opts...)
439 if err != nil {
440 n.Log(NewLogEntry(LogLevelError, "error dialing to Sentinel", map[string]interface{}{"error": err.Error()}))
441 return nil, err
442 }
443 if conf.SentinelPassword != "" {
444 if _, err := c.Do("AUTH", conf.SentinelPassword); err != nil {
445 _ = c.Close()
446 n.Log(NewLogEntry(LogLevelError, "error auth in Redis Sentinel", map[string]interface{}{"error": err.Error()}))
447 return nil, err
448 }
449 }
450 return c, nil
451 },
452 }
453
454 // Periodically discover new Sentinels.
455 go func() {
456 if err := sntnl.Discover(); err != nil {
457 n.Log(NewLogEntry(LogLevelError, "error discover Sentinel", map[string]interface{}{"error": err.Error()}))
458 }
459 for {
460 <-time.After(30 * time.Second)
461 if err := sntnl.Discover(); err != nil {
462 n.Log(NewLogEntry(LogLevelError, "error discover Sentinel", map[string]interface{}{"error": err.Error()}))
463 }
464 }
465 }()
466 }
467
468 return func(serverAddr string, dialOpts ...redis.DialOption) (*redis.Pool, error) {
469 pool := &redis.Pool{
470 MaxIdle: maxIdle,
471 MaxActive: poolSize,
472 Wait: true,
473 IdleTimeout: conf.IdleTimeout,
474 Dial: func() (redis.Conn, error) {
475 var c redis.Conn
476 if useSentinel {
477 masterAddr, err := sntnl.MasterAddr()
478 if err != nil {
479 return nil, err
480 }
481 lastMu.Lock()
482 if masterAddr != lastMaster {
483 n.Log(NewLogEntry(LogLevelInfo, "Redis master discovered", map[string]interface{}{"addr": masterAddr}))
484 lastMaster = masterAddr
485 }
486 lastMu.Unlock()
487 c, err = redis.Dial("tcp", masterAddr, dialOpts...)
488 if err != nil {
489 n.Log(NewLogEntry(LogLevelError, "error dialing to Redis", map[string]interface{}{"error": err.Error(), "addr": masterAddr}))
490 return nil, err
491 }
492 } else {
493 var err error
494 network := s.config.network
495 if network == "" {
496 // In case of Redis Cluster network can be empty since we don't set it.
497 network = "tcp"
498 }
499 c, err = redis.Dial(network, serverAddr, dialOpts...)
500 if err != nil {
501 n.Log(NewLogEntry(LogLevelError, "error dialing to Redis", map[string]interface{}{"error": err.Error(), "addr": serverAddr}))
502 return nil, err
503 }
504 }
505
506 if password != "" {
507 if _, err := c.Do("AUTH", password); err != nil {
508 _ = c.Close()
509 n.Log(NewLogEntry(LogLevelError, "error auth in Redis", map[string]interface{}{"error": err.Error()}))
510 return nil, err
511 }
512 }
513
514 if db != 0 {
515 if _, err := c.Do("SELECT", db); err != nil {
516 _ = c.Close()
517 n.Log(NewLogEntry(LogLevelError, "error selecting Redis db", map[string]interface{}{"error": err.Error()}))
518 return nil, err
519 }
520 }
521 return c, nil
522 },
523 TestOnBorrow: func(c redis.Conn, t time.Time) error {
524 if useSentinel {
525 if !sentinel.TestRole(c, "master") {
526 return errors.New("failed master role check")
527 }
528 return nil
529 }
530 if s.useCluster {
531 // No need in this optimization outside cluster
532 // use case due to utilization of pipelining.
533 if time.Since(t) < time.Second {
534 return nil
535 }
536 }
537 _, err := c.Do("PING")
538 return err
539 },
540 }
541 return pool, nil
542 }
543 }
544
545 func getDialOpts(conf RedisShardConfig) []redis.DialOption {
546 var readTimeout = DefaultRedisReadTimeout
547 if conf.ReadTimeout != 0 {
548 readTimeout = conf.ReadTimeout
549 }
550 var writeTimeout = DefaultRedisWriteTimeout
551 if conf.WriteTimeout != 0 {
552 writeTimeout = conf.WriteTimeout
553 }
554 var connectTimeout = DefaultRedisConnectTimeout
555 if conf.ConnectTimeout != 0 {
556 connectTimeout = conf.ConnectTimeout
557 }
558
559 dialOpts := []redis.DialOption{
560 redis.DialConnectTimeout(connectTimeout),
561 redis.DialReadTimeout(readTimeout),
562 redis.DialWriteTimeout(writeTimeout),
563 }
564 if conf.UseTLS {
565 dialOpts = append(dialOpts, redis.DialUseTLS(true))
566 if conf.TLSConfig != nil {
567 dialOpts = append(dialOpts, redis.DialTLSConfig(conf.TLSConfig))
568 }
569 if conf.TLSSkipVerify {
570 dialOpts = append(dialOpts, redis.DialTLSSkipVerify(true))
571 }
572 }
573 return dialOpts
574 }
575
576 func newPool(s *RedisShard, n *Node, conf RedisShardConfig) (redisConnPool, error) {
577 password := conf.Password
578 db := conf.DB
579
580 useSentinel := conf.SentinelMasterName != "" && len(conf.SentinelAddresses) > 0
581 usingPassword := password != ""
582
583 poolFactory := makePoolFactory(s, n, conf)
584
585 if !s.useCluster {
586 serverAddr := conf.address
587 if !useSentinel {
588 n.Log(NewLogEntry(LogLevelInfo, fmt.Sprintf("Redis: %s/%d, using password: %v", serverAddr, db, usingPassword)))
589 } else {
590 n.Log(NewLogEntry(LogLevelInfo, fmt.Sprintf("Redis: Sentinel for name: %s, db: %d, using password: %v", conf.SentinelMasterName, db, usingPassword)))
591 }
592 pool, _ := poolFactory(serverAddr, getDialOpts(conf)...)
593 return pool, nil
594 }
595 // OK, we should work with cluster.
596 n.Log(NewLogEntry(LogLevelInfo, fmt.Sprintf("Redis: cluster addrs: %+v, using password: %v", conf.ClusterAddresses, usingPassword)))
597 cluster := &redisc.Cluster{
598 DialOptions: getDialOpts(conf),
599 StartupNodes: conf.ClusterAddresses,
600 CreatePool: poolFactory,
601 }
602 // Initialize cluster mapping.
603 if err := cluster.Refresh(); err != nil {
604 return nil, err
605 }
606 return cluster, nil
607 }
608
609 func (s *RedisShard) readTimeout() time.Duration {
610 var readTimeout = DefaultRedisReadTimeout
611 if s.config.ReadTimeout != 0 {
612 readTimeout = s.config.ReadTimeout
613 }
614 return readTimeout
615 }
616
617 // runForever keeps another function running indefinitely.
618 // The reason this loop is not inside the function itself is
619 // so that defer can be used to cleanup nicely.
620 func runForever(fn func()) {
621 for {
622 fn()
623 // Sleep for a while to prevent busy loop when reconnecting to Redis.
624 time.Sleep(300 * time.Millisecond)
625 }
626 }
627
628 // consistentIndex is an adapted function from https://github.com/dgryski/go-jump
629 // package by Damian Gryski. It consistently chooses a hash bucket number in the
630 // range [0, numBuckets) for the given string. numBuckets must be >= 1.
631 func consistentIndex(s string, numBuckets int) int {
632 hash := fnv.New64a()
633 _, _ = hash.Write([]byte(s))
634 key := hash.Sum64()
635
636 var (
637 b int64 = -1
638 j int64
639 )
640
641 for j < int64(numBuckets) {
642 b = j
643 key = key*2862933555777941757 + 1
644 j = int64(float64(b+1) * (float64(int64(1)<<31) / float64((key>>33)+1)))
645 }
646
647 return int(b)
648 }