| 1 |
package redis |
| 2 |
|
| 3 |
import ( |
| 4 |
"errors" |
| 5 |
"fmt" |
| 6 |
"math/rand" |
| 7 |
"strconv" |
| 8 |
"sync" |
| 9 |
"sync/atomic" |
| 10 |
"time" |
| 11 |
|
| 12 |
"gopkg.in/redis.v5/internal" |
| 13 |
"gopkg.in/redis.v5/internal/consistenthash" |
| 14 |
"gopkg.in/redis.v5/internal/hashtag" |
| 15 |
"gopkg.in/redis.v5/internal/pool" |
| 16 |
) |
| 17 |
|
| 18 |
var errRingShardsDown = errors.New("redis: all ring shards are down") |
| 19 |
|
| 20 |
// RingOptions are used to configure a ring client and should be |
| 21 |
// passed to NewRing. |
| 22 |
type RingOptions struct { |
| 23 |
// Map of name => host:port addresses of ring shards. |
| 24 |
Addrs map[string]string |
| 25 |
|
| 26 |
// Frequency of PING commands sent to check shards availability. |
| 27 |
// Shard is considered down after 3 subsequent failed checks. |
| 28 |
HeartbeatFrequency time.Duration |
| 29 |
|
| 30 |
// Following options are copied from Options struct. |
| 31 |
|
| 32 |
DB int |
| 33 |
Password string |
| 34 |
|
| 35 |
MaxRetries int |
| 36 |
|
| 37 |
DialTimeout time.Duration |
| 38 |
ReadTimeout time.Duration |
| 39 |
WriteTimeout time.Duration |
| 40 |
|
| 41 |
PoolSize int |
| 42 |
PoolTimeout time.Duration |
| 43 |
IdleTimeout time.Duration |
| 44 |
IdleCheckFrequency time.Duration |
| 45 |
} |
| 46 |
|
| 47 |
func (opt *RingOptions) init() { |
| 48 |
if opt.HeartbeatFrequency == 0 { |
| 49 |
opt.HeartbeatFrequency = 500 * time.Millisecond |
| 50 |
} |
| 51 |
} |
| 52 |
|
| 53 |
func (opt *RingOptions) clientOptions() *Options { |
| 54 |
return &Options{ |
| 55 |
DB: opt.DB, |
| 56 |
Password: opt.Password, |
| 57 |
|
| 58 |
DialTimeout: opt.DialTimeout, |
| 59 |
ReadTimeout: opt.ReadTimeout, |
| 60 |
WriteTimeout: opt.WriteTimeout, |
| 61 |
|
| 62 |
PoolSize: opt.PoolSize, |
| 63 |
PoolTimeout: opt.PoolTimeout, |
| 64 |
IdleTimeout: opt.IdleTimeout, |
| 65 |
IdleCheckFrequency: opt.IdleCheckFrequency, |
| 66 |
} |
| 67 |
} |
| 68 |
|
| 69 |
type ringShard struct { |
| 70 |
Client *Client |
| 71 |
down int32 |
| 72 |
} |
| 73 |
|
| 74 |
func (shard *ringShard) String() string { |
| 75 |
var state string |
| 76 |
if shard.IsUp() { |
| 77 |
state = "up" |
| 78 |
} else { |
| 79 |
state = "down" |
| 80 |
} |
| 81 |
return fmt.Sprintf("%s is %s", shard.Client, state) |
| 82 |
} |
| 83 |
|
| 84 |
func (shard *ringShard) IsDown() bool { |
| 85 |
const threshold = 3 |
| 86 |
return atomic.LoadInt32(&shard.down) >= threshold |
| 87 |
} |
| 88 |
|
| 89 |
func (shard *ringShard) IsUp() bool { |
| 90 |
return !shard.IsDown() |
| 91 |
} |
| 92 |
|
| 93 |
// Vote votes to set shard state and returns true if state was changed. |
| 94 |
func (shard *ringShard) Vote(up bool) bool { |
| 95 |
if up { |
| 96 |
changed := shard.IsDown() |
| 97 |
atomic.StoreInt32(&shard.down, 0) |
| 98 |
return changed |
| 99 |
} |
| 100 |
|
| 101 |
if shard.IsDown() { |
| 102 |
return false |
| 103 |
} |
| 104 |
|
| 105 |
atomic.AddInt32(&shard.down, 1) |
| 106 |
return shard.IsDown() |
| 107 |
} |
| 108 |
|
| 109 |
// Ring is a Redis client that uses constistent hashing to distribute |
| 110 |
// keys across multiple Redis servers (shards). It's safe for |
| 111 |
// concurrent use by multiple goroutines. |
| 112 |
// |
| 113 |
// Ring monitors the state of each shard and removes dead shards from |
| 114 |
// the ring. When shard comes online it is added back to the ring. This |
| 115 |
// gives you maximum availability and partition tolerance, but no |
| 116 |
// consistency between different shards or even clients. Each client |
| 117 |
// uses shards that are available to the client and does not do any |
| 118 |
// coordination when shard state is changed. |
| 119 |
// |
| 120 |
// Ring should be used when you need multiple Redis servers for caching |
| 121 |
// and can tolerate losing data when one of the servers dies. |
| 122 |
// Otherwise you should use Redis Cluster. |
| 123 |
type Ring struct { |
| 124 |
cmdable |
| 125 |
|
| 126 |
opt *RingOptions |
| 127 |
nreplicas int |
| 128 |
|
| 129 |
mu sync.RWMutex |
| 130 |
hash *consistenthash.Map |
| 131 |
shards map[string]*ringShard |
| 132 |
|
| 133 |
cmdsInfoOnce *sync.Once |
| 134 |
cmdsInfo map[string]*CommandInfo |
| 135 |
|
| 136 |
closed bool |
| 137 |
} |
| 138 |
|
| 139 |
func NewRing(opt *RingOptions) *Ring { |
| 140 |
const nreplicas = 100 |
| 141 |
opt.init() |
| 142 |
ring := &Ring{ |
| 143 |
opt: opt, |
| 144 |
nreplicas: nreplicas, |
| 145 |
|
| 146 |
hash: consistenthash.New(nreplicas, nil), |
| 147 |
shards: make(map[string]*ringShard), |
| 148 |
|
| 149 |
cmdsInfoOnce: new(sync.Once), |
| 150 |
} |
| 151 |
ring.cmdable.process = ring.Process |
| 152 |
for name, addr := range opt.Addrs { |
| 153 |
clopt := opt.clientOptions() |
| 154 |
clopt.Addr = addr |
| 155 |
ring.addClient(name, NewClient(clopt)) |
| 156 |
} |
| 157 |
go ring.heartbeat() |
| 158 |
return ring |
| 159 |
} |
| 160 |
|
| 161 |
// PoolStats returns accumulated connection pool stats. |
| 162 |
func (c *Ring) PoolStats() *PoolStats { |
| 163 |
var acc PoolStats |
| 164 |
for _, shard := range c.shards { |
| 165 |
s := shard.Client.connPool.Stats() |
| 166 |
acc.Requests += s.Requests |
| 167 |
acc.Hits += s.Hits |
| 168 |
acc.Timeouts += s.Timeouts |
| 169 |
acc.TotalConns += s.TotalConns |
| 170 |
acc.FreeConns += s.FreeConns |
| 171 |
} |
| 172 |
return &acc |
| 173 |
} |
| 174 |
|
| 175 |
// ForEachShard concurrently calls the fn on each live shard in the ring. |
| 176 |
// It returns the first error if any. |
| 177 |
func (c *Ring) ForEachShard(fn func(client *Client) error) error { |
| 178 |
var wg sync.WaitGroup |
| 179 |
errCh := make(chan error, 1) |
| 180 |
for _, shard := range c.shards { |
| 181 |
if shard.IsDown() { |
| 182 |
continue |
| 183 |
} |
| 184 |
|
| 185 |
wg.Add(1) |
| 186 |
go func(shard *ringShard) { |
| 187 |
defer wg.Done() |
| 188 |
err := fn(shard.Client) |
| 189 |
if err != nil { |
| 190 |
select { |
| 191 |
case errCh <- err: |
| 192 |
default: |
| 193 |
} |
| 194 |
} |
| 195 |
}(shard) |
| 196 |
} |
| 197 |
wg.Wait() |
| 198 |
|
| 199 |
select { |
| 200 |
case err := <-errCh: |
| 201 |
return err |
| 202 |
default: |
| 203 |
return nil |
| 204 |
} |
| 205 |
} |
| 206 |
|
| 207 |
func (c *Ring) cmdInfo(name string) *CommandInfo { |
| 208 |
c.cmdsInfoOnce.Do(func() { |
| 209 |
for _, shard := range c.shards { |
| 210 |
cmdsInfo, err := shard.Client.Command().Result() |
| 211 |
if err == nil { |
| 212 |
c.cmdsInfo = cmdsInfo |
| 213 |
return |
| 214 |
} |
| 215 |
} |
| 216 |
c.cmdsInfoOnce = &sync.Once{} |
| 217 |
}) |
| 218 |
if c.cmdsInfo == nil { |
| 219 |
return nil |
| 220 |
} |
| 221 |
return c.cmdsInfo[name] |
| 222 |
} |
| 223 |
|
| 224 |
func (c *Ring) addClient(name string, cl *Client) { |
| 225 |
c.mu.Lock() |
| 226 |
c.hash.Add(name) |
| 227 |
c.shards[name] = &ringShard{Client: cl} |
| 228 |
c.mu.Unlock() |
| 229 |
} |
| 230 |
|
| 231 |
func (c *Ring) shardByKey(key string) (*ringShard, error) { |
| 232 |
key = hashtag.Key(key) |
| 233 |
|
| 234 |
c.mu.RLock() |
| 235 |
|
| 236 |
if c.closed { |
| 237 |
c.mu.RUnlock() |
| 238 |
return nil, pool.ErrClosed |
| 239 |
} |
| 240 |
|
| 241 |
name := c.hash.Get(key) |
| 242 |
if name == "" { |
| 243 |
c.mu.RUnlock() |
| 244 |
return nil, errRingShardsDown |
| 245 |
} |
| 246 |
|
| 247 |
shard := c.shards[name] |
| 248 |
c.mu.RUnlock() |
| 249 |
return shard, nil |
| 250 |
} |
| 251 |
|
| 252 |
func (c *Ring) randomShard() (*ringShard, error) { |
| 253 |
return c.shardByKey(strconv.Itoa(rand.Int())) |
| 254 |
} |
| 255 |
|
| 256 |
func (c *Ring) shardByName(name string) (*ringShard, error) { |
| 257 |
if name == "" { |
| 258 |
return c.randomShard() |
| 259 |
} |
| 260 |
|
| 261 |
c.mu.RLock() |
| 262 |
shard := c.shards[name] |
| 263 |
c.mu.RUnlock() |
| 264 |
return shard, nil |
| 265 |
} |
| 266 |
|
| 267 |
func (c *Ring) cmdShard(cmd Cmder) (*ringShard, error) { |
| 268 |
cmdInfo := c.cmdInfo(cmd.name()) |
| 269 |
firstKey := cmd.arg(cmdFirstKeyPos(cmd, cmdInfo)) |
| 270 |
return c.shardByKey(firstKey) |
| 271 |
} |
| 272 |
|
| 273 |
func (c *Ring) Process(cmd Cmder) error { |
| 274 |
shard, err := c.cmdShard(cmd) |
| 275 |
if err != nil { |
| 276 |
cmd.setErr(err) |
| 277 |
return err |
| 278 |
} |
| 279 |
return shard.Client.Process(cmd) |
| 280 |
} |
| 281 |
|
| 282 |
// rebalance removes dead shards from the Ring. |
| 283 |
func (c *Ring) rebalance() { |
| 284 |
hash := consistenthash.New(c.nreplicas, nil) |
| 285 |
for name, shard := range c.shards { |
| 286 |
if shard.IsUp() { |
| 287 |
hash.Add(name) |
| 288 |
} |
| 289 |
} |
| 290 |
|
| 291 |
c.mu.Lock() |
| 292 |
c.hash = hash |
| 293 |
c.mu.Unlock() |
| 294 |
} |
| 295 |
|
| 296 |
// heartbeat monitors state of each shard in the ring. |
| 297 |
func (c *Ring) heartbeat() { |
| 298 |
ticker := time.NewTicker(c.opt.HeartbeatFrequency) |
| 299 |
defer ticker.Stop() |
| 300 |
for _ = range ticker.C { |
| 301 |
var rebalance bool |
| 302 |
|
| 303 |
c.mu.RLock() |
| 304 |
|
| 305 |
if c.closed { |
| 306 |
c.mu.RUnlock() |
| 307 |
break |
| 308 |
} |
| 309 |
|
| 310 |
for _, shard := range c.shards { |
| 311 |
err := shard.Client.Ping().Err() |
| 312 |
if shard.Vote(err == nil || err == pool.ErrPoolTimeout) { |
| 313 |
internal.Logf("ring shard state changed: %s", shard) |
| 314 |
rebalance = true |
| 315 |
} |
| 316 |
} |
| 317 |
|
| 318 |
c.mu.RUnlock() |
| 319 |
|
| 320 |
if rebalance { |
| 321 |
c.rebalance() |
| 322 |
} |
| 323 |
} |
| 324 |
} |
| 325 |
|
| 326 |
// Close closes the ring client, releasing any open resources. |
| 327 |
// |
| 328 |
// It is rare to Close a Ring, as the Ring is meant to be long-lived |
| 329 |
// and shared between many goroutines. |
| 330 |
func (c *Ring) Close() error { |
| 331 |
c.mu.Lock() |
| 332 |
defer c.mu.Unlock() |
| 333 |
|
| 334 |
if c.closed { |
| 335 |
return nil |
| 336 |
} |
| 337 |
c.closed = true |
| 338 |
|
| 339 |
var firstErr error |
| 340 |
for _, shard := range c.shards { |
| 341 |
if err := shard.Client.Close(); err != nil && firstErr == nil { |
| 342 |
firstErr = err |
| 343 |
} |
| 344 |
} |
| 345 |
c.hash = nil |
| 346 |
c.shards = nil |
| 347 |
|
| 348 |
return firstErr |
| 349 |
} |
| 350 |
|
| 351 |
func (c *Ring) Pipeline() *Pipeline { |
| 352 |
pipe := Pipeline{ |
| 353 |
exec: c.pipelineExec, |
| 354 |
} |
| 355 |
pipe.cmdable.process = pipe.Process |
| 356 |
pipe.statefulCmdable.process = pipe.Process |
| 357 |
return &pipe |
| 358 |
} |
| 359 |
|
| 360 |
func (c *Ring) Pipelined(fn func(*Pipeline) error) ([]Cmder, error) { |
| 361 |
return c.Pipeline().pipelined(fn) |
| 362 |
} |
| 363 |
|
| 364 |
func (c *Ring) pipelineExec(cmds []Cmder) (firstErr error) { |
| 365 |
cmdsMap := make(map[string][]Cmder) |
| 366 |
for _, cmd := range cmds { |
| 367 |
cmdInfo := c.cmdInfo(cmd.name()) |
| 368 |
name := cmd.arg(cmdFirstKeyPos(cmd, cmdInfo)) |
| 369 |
if name != "" { |
| 370 |
name = c.hash.Get(hashtag.Key(name)) |
| 371 |
} |
| 372 |
cmdsMap[name] = append(cmdsMap[name], cmd) |
| 373 |
} |
| 374 |
|
| 375 |
for i := 0; i <= c.opt.MaxRetries; i++ { |
| 376 |
var failedCmdsMap map[string][]Cmder |
| 377 |
|
| 378 |
for name, cmds := range cmdsMap { |
| 379 |
shard, err := c.shardByName(name) |
| 380 |
if err != nil { |
| 381 |
setCmdsErr(cmds, err) |
| 382 |
if firstErr == nil { |
| 383 |
firstErr = err |
| 384 |
} |
| 385 |
continue |
| 386 |
} |
| 387 |
|
| 388 |
cn, _, err := shard.Client.conn() |
| 389 |
if err != nil { |
| 390 |
setCmdsErr(cmds, err) |
| 391 |
if firstErr == nil { |
| 392 |
firstErr = err |
| 393 |
} |
| 394 |
continue |
| 395 |
} |
| 396 |
|
| 397 |
canRetry, err := shard.Client.pipelineProcessCmds(cn, cmds) |
| 398 |
shard.Client.putConn(cn, err, false) |
| 399 |
if err == nil { |
| 400 |
continue |
| 401 |
} |
| 402 |
if firstErr == nil { |
| 403 |
firstErr = err |
| 404 |
} |
| 405 |
if canRetry && internal.IsRetryableError(err) { |
| 406 |
if failedCmdsMap == nil { |
| 407 |
failedCmdsMap = make(map[string][]Cmder) |
| 408 |
} |
| 409 |
failedCmdsMap[name] = cmds |
| 410 |
} |
| 411 |
} |
| 412 |
|
| 413 |
if len(failedCmdsMap) == 0 { |
| 414 |
break |
| 415 |
} |
| 416 |
cmdsMap = failedCmdsMap |
| 417 |
} |
| 418 |
|
| 419 |
return firstErr |
| 420 |
} |