| 1 |
package redis |
| 2 |
|
| 3 |
import ( |
| 4 |
"errors" |
| 5 |
"fmt" |
| 6 |
"net" |
| 7 |
"strings" |
| 8 |
"sync" |
| 9 |
"time" |
| 10 |
|
| 11 |
"gopkg.in/redis.v5/internal" |
| 12 |
"gopkg.in/redis.v5/internal/pool" |
| 13 |
) |
| 14 |
|
| 15 |
//------------------------------------------------------------------------------ |
| 16 |
|
| 17 |
// FailoverOptions are used to configure a failover client and should |
| 18 |
// be passed to NewFailoverClient. |
| 19 |
type FailoverOptions struct { |
| 20 |
// The master name. |
| 21 |
MasterName string |
| 22 |
// A seed list of host:port addresses of sentinel nodes. |
| 23 |
SentinelAddrs []string |
| 24 |
|
| 25 |
// Following options are copied from Options struct. |
| 26 |
|
| 27 |
Password string |
| 28 |
DB int |
| 29 |
|
| 30 |
MaxRetries int |
| 31 |
|
| 32 |
DialTimeout time.Duration |
| 33 |
ReadTimeout time.Duration |
| 34 |
WriteTimeout time.Duration |
| 35 |
|
| 36 |
PoolSize int |
| 37 |
PoolTimeout time.Duration |
| 38 |
IdleTimeout time.Duration |
| 39 |
IdleCheckFrequency time.Duration |
| 40 |
} |
| 41 |
|
| 42 |
func (opt *FailoverOptions) options() *Options { |
| 43 |
return &Options{ |
| 44 |
Addr: "FailoverClient", |
| 45 |
|
| 46 |
DB: opt.DB, |
| 47 |
Password: opt.Password, |
| 48 |
|
| 49 |
MaxRetries: opt.MaxRetries, |
| 50 |
|
| 51 |
DialTimeout: opt.DialTimeout, |
| 52 |
ReadTimeout: opt.ReadTimeout, |
| 53 |
WriteTimeout: opt.WriteTimeout, |
| 54 |
|
| 55 |
PoolSize: opt.PoolSize, |
| 56 |
PoolTimeout: opt.PoolTimeout, |
| 57 |
IdleTimeout: opt.IdleTimeout, |
| 58 |
IdleCheckFrequency: opt.IdleCheckFrequency, |
| 59 |
} |
| 60 |
} |
| 61 |
|
| 62 |
// NewFailoverClient returns a Redis client that uses Redis Sentinel |
| 63 |
// for automatic failover. It's safe for concurrent use by multiple |
| 64 |
// goroutines. |
| 65 |
func NewFailoverClient(failoverOpt *FailoverOptions) *Client { |
| 66 |
opt := failoverOpt.options() |
| 67 |
opt.init() |
| 68 |
|
| 69 |
failover := &sentinelFailover{ |
| 70 |
masterName: failoverOpt.MasterName, |
| 71 |
sentinelAddrs: failoverOpt.SentinelAddrs, |
| 72 |
|
| 73 |
opt: opt, |
| 74 |
} |
| 75 |
|
| 76 |
client := Client{ |
| 77 |
baseClient: baseClient{ |
| 78 |
opt: opt, |
| 79 |
connPool: failover.Pool(), |
| 80 |
|
| 81 |
onClose: func() error { |
| 82 |
return failover.Close() |
| 83 |
}, |
| 84 |
}, |
| 85 |
} |
| 86 |
client.cmdable.process = client.Process |
| 87 |
|
| 88 |
return &client |
| 89 |
} |
| 90 |
|
| 91 |
//------------------------------------------------------------------------------ |
| 92 |
|
| 93 |
type sentinelClient struct { |
| 94 |
cmdable |
| 95 |
baseClient |
| 96 |
} |
| 97 |
|
| 98 |
func newSentinel(opt *Options) *sentinelClient { |
| 99 |
opt.init() |
| 100 |
client := sentinelClient{ |
| 101 |
baseClient: baseClient{ |
| 102 |
opt: opt, |
| 103 |
connPool: newConnPool(opt), |
| 104 |
}, |
| 105 |
} |
| 106 |
client.cmdable = cmdable{client.Process} |
| 107 |
return &client |
| 108 |
} |
| 109 |
|
| 110 |
func (c *sentinelClient) PubSub() *PubSub { |
| 111 |
return &PubSub{ |
| 112 |
base: baseClient{ |
| 113 |
opt: c.opt, |
| 114 |
connPool: pool.NewStickyConnPool(c.connPool.(*pool.ConnPool), false), |
| 115 |
}, |
| 116 |
} |
| 117 |
} |
| 118 |
|
| 119 |
func (c *sentinelClient) GetMasterAddrByName(name string) *StringSliceCmd { |
| 120 |
cmd := NewStringSliceCmd("SENTINEL", "get-master-addr-by-name", name) |
| 121 |
c.Process(cmd) |
| 122 |
return cmd |
| 123 |
} |
| 124 |
|
| 125 |
func (c *sentinelClient) Sentinels(name string) *SliceCmd { |
| 126 |
cmd := NewSliceCmd("SENTINEL", "sentinels", name) |
| 127 |
c.Process(cmd) |
| 128 |
return cmd |
| 129 |
} |
| 130 |
|
| 131 |
type sentinelFailover struct { |
| 132 |
masterName string |
| 133 |
sentinelAddrs []string |
| 134 |
|
| 135 |
opt *Options |
| 136 |
|
| 137 |
pool *pool.ConnPool |
| 138 |
poolOnce sync.Once |
| 139 |
|
| 140 |
mu sync.RWMutex |
| 141 |
sentinel *sentinelClient |
| 142 |
} |
| 143 |
|
| 144 |
func (d *sentinelFailover) Close() error { |
| 145 |
return d.resetSentinel() |
| 146 |
} |
| 147 |
|
| 148 |
func (d *sentinelFailover) dial() (net.Conn, error) { |
| 149 |
addr, err := d.MasterAddr() |
| 150 |
if err != nil { |
| 151 |
return nil, err |
| 152 |
} |
| 153 |
return net.DialTimeout("tcp", addr, d.opt.DialTimeout) |
| 154 |
} |
| 155 |
|
| 156 |
func (d *sentinelFailover) Pool() *pool.ConnPool { |
| 157 |
d.poolOnce.Do(func() { |
| 158 |
d.opt.Dialer = d.dial |
| 159 |
d.pool = newConnPool(d.opt) |
| 160 |
}) |
| 161 |
return d.pool |
| 162 |
} |
| 163 |
|
| 164 |
func (d *sentinelFailover) MasterAddr() (string, error) { |
| 165 |
d.mu.Lock() |
| 166 |
defer d.mu.Unlock() |
| 167 |
|
| 168 |
// Try last working sentinel. |
| 169 |
if d.sentinel != nil { |
| 170 |
addr, err := d.sentinel.GetMasterAddrByName(d.masterName).Result() |
| 171 |
if err != nil { |
| 172 |
internal.Logf("sentinel: GetMasterAddrByName %q failed: %s", d.masterName, err) |
| 173 |
d._resetSentinel() |
| 174 |
} else { |
| 175 |
addr := net.JoinHostPort(addr[0], addr[1]) |
| 176 |
internal.Logf("sentinel: %q addr is %s", d.masterName, addr) |
| 177 |
return addr, nil |
| 178 |
} |
| 179 |
} |
| 180 |
|
| 181 |
for i, sentinelAddr := range d.sentinelAddrs { |
| 182 |
sentinel := newSentinel(&Options{ |
| 183 |
Addr: sentinelAddr, |
| 184 |
|
| 185 |
DialTimeout: d.opt.DialTimeout, |
| 186 |
ReadTimeout: d.opt.ReadTimeout, |
| 187 |
WriteTimeout: d.opt.WriteTimeout, |
| 188 |
|
| 189 |
PoolSize: d.opt.PoolSize, |
| 190 |
PoolTimeout: d.opt.PoolTimeout, |
| 191 |
IdleTimeout: d.opt.IdleTimeout, |
| 192 |
}) |
| 193 |
masterAddr, err := sentinel.GetMasterAddrByName(d.masterName).Result() |
| 194 |
if err != nil { |
| 195 |
internal.Logf("sentinel: GetMasterAddrByName %q failed: %s", d.masterName, err) |
| 196 |
sentinel.Close() |
| 197 |
continue |
| 198 |
} |
| 199 |
|
| 200 |
// Push working sentinel to the top. |
| 201 |
d.sentinelAddrs[0], d.sentinelAddrs[i] = d.sentinelAddrs[i], d.sentinelAddrs[0] |
| 202 |
|
| 203 |
d.setSentinel(sentinel) |
| 204 |
addr := net.JoinHostPort(masterAddr[0], masterAddr[1]) |
| 205 |
internal.Logf("sentinel: %q addr is %s", d.masterName, addr) |
| 206 |
return addr, nil |
| 207 |
} |
| 208 |
|
| 209 |
return "", errors.New("redis: all sentinels are unreachable") |
| 210 |
} |
| 211 |
|
| 212 |
func (d *sentinelFailover) setSentinel(sentinel *sentinelClient) { |
| 213 |
d.discoverSentinels(sentinel) |
| 214 |
d.sentinel = sentinel |
| 215 |
go d.listen(sentinel) |
| 216 |
} |
| 217 |
|
| 218 |
func (d *sentinelFailover) resetSentinel() error { |
| 219 |
d.mu.Lock() |
| 220 |
err := d._resetSentinel() |
| 221 |
d.mu.Unlock() |
| 222 |
return err |
| 223 |
} |
| 224 |
|
| 225 |
func (d *sentinelFailover) _resetSentinel() error { |
| 226 |
var err error |
| 227 |
if d.sentinel != nil { |
| 228 |
err = d.sentinel.Close() |
| 229 |
d.sentinel = nil |
| 230 |
} |
| 231 |
return err |
| 232 |
} |
| 233 |
|
| 234 |
func (d *sentinelFailover) discoverSentinels(sentinel *sentinelClient) { |
| 235 |
sentinels, err := sentinel.Sentinels(d.masterName).Result() |
| 236 |
if err != nil { |
| 237 |
internal.Logf("sentinel: Sentinels %q failed: %s", d.masterName, err) |
| 238 |
return |
| 239 |
} |
| 240 |
for _, sentinel := range sentinels { |
| 241 |
vals := sentinel.([]interface{}) |
| 242 |
for i := 0; i < len(vals); i += 2 { |
| 243 |
key := vals[i].(string) |
| 244 |
if key == "name" { |
| 245 |
sentinelAddr := vals[i+1].(string) |
| 246 |
if !contains(d.sentinelAddrs, sentinelAddr) { |
| 247 |
internal.Logf( |
| 248 |
"sentinel: discovered new %q sentinel: %s", |
| 249 |
d.masterName, sentinelAddr, |
| 250 |
) |
| 251 |
d.sentinelAddrs = append(d.sentinelAddrs, sentinelAddr) |
| 252 |
} |
| 253 |
} |
| 254 |
} |
| 255 |
} |
| 256 |
} |
| 257 |
|
| 258 |
// closeOldConns closes connections to the old master after failover switch. |
| 259 |
func (d *sentinelFailover) closeOldConns(newMaster string) { |
| 260 |
// Good connections that should be put back to the pool. They |
| 261 |
// can't be put immediately, because pool.PopFree will return them |
| 262 |
// again on next iteration. |
| 263 |
cnsToPut := make([]*pool.Conn, 0) |
| 264 |
|
| 265 |
for { |
| 266 |
cn := d.pool.PopFree() |
| 267 |
if cn == nil { |
| 268 |
break |
| 269 |
} |
| 270 |
if cn.RemoteAddr().String() != newMaster { |
| 271 |
err := fmt.Errorf( |
| 272 |
"sentinel: closing connection to the old master %s", |
| 273 |
cn.RemoteAddr(), |
| 274 |
) |
| 275 |
internal.Logf(err.Error()) |
| 276 |
d.pool.Remove(cn, err) |
| 277 |
} else { |
| 278 |
cnsToPut = append(cnsToPut, cn) |
| 279 |
} |
| 280 |
} |
| 281 |
|
| 282 |
for _, cn := range cnsToPut { |
| 283 |
d.pool.Put(cn) |
| 284 |
} |
| 285 |
} |
| 286 |
|
| 287 |
func (d *sentinelFailover) listen(sentinel *sentinelClient) { |
| 288 |
var pubsub *PubSub |
| 289 |
for { |
| 290 |
if pubsub == nil { |
| 291 |
pubsub = sentinel.PubSub() |
| 292 |
|
| 293 |
if err := pubsub.Subscribe("+switch-master"); err != nil { |
| 294 |
internal.Logf("sentinel: Subscribe failed: %s", err) |
| 295 |
pubsub.Close() |
| 296 |
d.resetSentinel() |
| 297 |
return |
| 298 |
} |
| 299 |
} |
| 300 |
|
| 301 |
msg, err := pubsub.ReceiveMessage() |
| 302 |
if err != nil { |
| 303 |
internal.Logf("sentinel: ReceiveMessage failed: %s", err) |
| 304 |
pubsub.Close() |
| 305 |
d.resetSentinel() |
| 306 |
return |
| 307 |
} |
| 308 |
|
| 309 |
switch msg.Channel { |
| 310 |
case "+switch-master": |
| 311 |
parts := strings.Split(msg.Payload, " ") |
| 312 |
if parts[0] != d.masterName { |
| 313 |
internal.Logf("sentinel: ignore new %s addr", parts[0]) |
| 314 |
continue |
| 315 |
} |
| 316 |
|
| 317 |
addr := net.JoinHostPort(parts[3], parts[4]) |
| 318 |
internal.Logf( |
| 319 |
"sentinel: new %q addr is %s", |
| 320 |
d.masterName, addr, |
| 321 |
) |
| 322 |
|
| 323 |
d.closeOldConns(addr) |
| 324 |
} |
| 325 |
} |
| 326 |
} |
| 327 |
|
| 328 |
func contains(slice []string, str string) bool { |
| 329 |
for _, s := range slice { |
| 330 |
if s == str { |
| 331 |
return true |
| 332 |
} |
| 333 |
} |
| 334 |
return false |
| 335 |
} |