redis/sentinel.go

640 lines
16 KiB
Go
Raw Normal View History

2014-05-11 18:11:55 +04:00
package redis
import (
"context"
"crypto/tls"
2014-05-11 18:11:55 +04:00
"errors"
"math/rand"
2014-05-11 18:11:55 +04:00
"net"
"strings"
"sync"
"time"
2020-03-11 17:29:16 +03:00
"github.com/go-redis/redis/v8/internal"
"github.com/go-redis/redis/v8/internal/pool"
2014-05-11 18:11:55 +04:00
)
//------------------------------------------------------------------------------
// FailoverOptions are used to configure a failover client and should
// be passed to NewFailoverClient.
2014-05-11 18:11:55 +04:00
type FailoverOptions struct {
2015-01-31 17:54:37 +03:00
// The master name.
MasterName string
// A seed list of host:port addresses of sentinel nodes.
SentinelAddrs []string
// Sentinel password from "requirepass <password>" (if enabled) in Sentinel configuration
2019-06-04 14:05:29 +03:00
SentinelPassword string
2014-05-11 18:11:55 +04:00
2020-09-05 17:39:26 +03:00
// Enables read-only commands on slave nodes.
ReadOnly bool
// Following options are copied from Options struct.
2019-06-04 14:05:29 +03:00
Dialer func(ctx context.Context, network, addr string) (net.Conn, error)
2020-06-10 10:36:22 +03:00
OnConnect func(ctx context.Context, cn *Conn) error
2017-05-25 14:16:39 +03:00
2020-05-21 08:59:20 +03:00
Username string
2019-06-04 14:05:29 +03:00
Password string
DB int
MaxRetries int
MinRetryBackoff time.Duration
MaxRetryBackoff time.Duration
2016-03-17 19:00:47 +03:00
DialTimeout time.Duration
ReadTimeout time.Duration
2015-01-31 17:54:37 +03:00
WriteTimeout time.Duration
2014-05-11 18:11:55 +04:00
2016-03-17 19:00:47 +03:00
PoolSize int
MinIdleConns int
MaxConnAge time.Duration
2016-03-17 19:00:47 +03:00
PoolTimeout time.Duration
IdleTimeout time.Duration
IdleCheckFrequency time.Duration
TLSConfig *tls.Config
2014-05-11 18:11:55 +04:00
}
func (opt *FailoverOptions) options() *Options {
return &Options{
2020-06-10 10:36:22 +03:00
Addr: "FailoverClient",
2019-05-18 14:00:07 +03:00
Dialer: opt.Dialer,
2017-05-25 14:16:39 +03:00
OnConnect: opt.OnConnect,
2014-05-11 18:11:55 +04:00
DB: opt.DB,
2020-05-21 08:59:20 +03:00
Username: opt.Username,
2014-05-11 18:11:55 +04:00
Password: opt.Password,
MaxRetries: opt.MaxRetries,
MinRetryBackoff: opt.MinRetryBackoff,
MaxRetryBackoff: opt.MaxRetryBackoff,
2016-03-17 19:00:47 +03:00
DialTimeout: opt.DialTimeout,
2014-05-11 18:11:55 +04:00
ReadTimeout: opt.ReadTimeout,
WriteTimeout: opt.WriteTimeout,
2016-03-17 19:00:47 +03:00
PoolSize: opt.PoolSize,
PoolTimeout: opt.PoolTimeout,
IdleTimeout: opt.IdleTimeout,
IdleCheckFrequency: opt.IdleCheckFrequency,
MinIdleConns: opt.MinIdleConns,
MaxConnAge: opt.MaxConnAge,
TLSConfig: opt.TLSConfig,
sentinelReadOnly: opt.ReadOnly,
2014-05-11 18:11:55 +04:00
}
}
2015-09-12 09:36:03 +03:00
// NewFailoverClient returns a Redis client that uses Redis Sentinel
// for automatic failover. It's safe for concurrent use by multiple
// goroutines.
2014-05-11 18:11:55 +04:00
func NewFailoverClient(failoverOpt *FailoverOptions) *Client {
opt := failoverOpt.options()
2016-06-05 14:10:30 +03:00
opt.init()
2014-05-11 18:11:55 +04:00
failover := &sentinelFailover{
masterName: failoverOpt.MasterName,
sentinelAddrs: failoverOpt.SentinelAddrs,
sentinelPassword: failoverOpt.SentinelPassword,
2014-05-11 18:11:55 +04:00
opt: opt,
}
2016-06-05 14:10:30 +03:00
2018-01-20 13:26:33 +03:00
c := Client{
2020-02-02 15:59:27 +03:00
baseClient: newBaseClient(opt, failover.Pool()),
ctx: context.Background(),
}
2019-08-24 12:22:52 +03:00
c.cmdable = c.Process
2020-02-02 15:59:27 +03:00
c.onClose = failover.Close
2016-06-05 14:10:30 +03:00
2018-01-20 13:26:33 +03:00
return &c
2014-05-11 18:11:55 +04:00
}
//------------------------------------------------------------------------------
2018-05-31 13:15:52 +03:00
type SentinelClient struct {
2019-05-31 17:37:34 +03:00
*baseClient
ctx context.Context
2014-05-11 18:11:55 +04:00
}
2018-05-31 13:15:52 +03:00
func NewSentinelClient(opt *Options) *SentinelClient {
2016-06-05 14:10:30 +03:00
opt.init()
2018-05-31 13:15:52 +03:00
c := &SentinelClient{
2019-05-31 17:37:34 +03:00
baseClient: &baseClient{
opt: opt,
connPool: newConnPool(opt),
},
2019-07-04 11:18:06 +03:00
ctx: context.Background(),
2014-05-11 18:11:55 +04:00
}
2018-05-31 13:15:52 +03:00
return c
2014-05-11 18:11:55 +04:00
}
func (c *SentinelClient) Context() context.Context {
2019-07-04 11:18:06 +03:00
return c.ctx
}
func (c *SentinelClient) WithContext(ctx context.Context) *SentinelClient {
if ctx == nil {
panic("nil context")
}
clone := *c
2019-05-31 17:03:20 +03:00
clone.ctx = ctx
return &clone
}
2020-03-11 17:26:42 +03:00
func (c *SentinelClient) Process(ctx context.Context, cmd Cmder) error {
2019-06-04 13:30:47 +03:00
return c.baseClient.process(ctx, cmd)
}
func (c *SentinelClient) pubSub() *PubSub {
2018-07-23 15:55:13 +03:00
pubsub := &PubSub{
2017-07-09 10:07:20 +03:00
opt: c.opt,
2020-03-11 17:26:42 +03:00
newConn: func(ctx context.Context, channels []string) (*pool.Conn, error) {
return c.newConn(ctx)
2014-05-11 18:11:55 +04:00
},
2017-07-09 10:07:20 +03:00
closeConn: c.connPool.CloseConn,
2014-05-11 18:11:55 +04:00
}
2018-07-23 15:55:13 +03:00
pubsub.init()
return pubsub
2014-05-11 18:11:55 +04:00
}
// Ping is used to test if a connection is still alive, or to
// measure latency.
2020-03-11 17:26:42 +03:00
func (c *SentinelClient) Ping(ctx context.Context) *StringCmd {
cmd := NewStringCmd(ctx, "ping")
_ = c.Process(ctx, cmd)
return cmd
}
// Subscribe subscribes the client to the specified channels.
// Channels can be omitted to create empty subscription.
2020-03-11 17:26:42 +03:00
func (c *SentinelClient) Subscribe(ctx context.Context, channels ...string) *PubSub {
pubsub := c.pubSub()
if len(channels) > 0 {
2020-03-11 17:26:42 +03:00
_ = pubsub.Subscribe(ctx, channels...)
}
return pubsub
}
// PSubscribe subscribes the client to the given patterns.
// Patterns can be omitted to create empty subscription.
2020-03-11 17:26:42 +03:00
func (c *SentinelClient) PSubscribe(ctx context.Context, channels ...string) *PubSub {
pubsub := c.pubSub()
if len(channels) > 0 {
2020-03-11 17:26:42 +03:00
_ = pubsub.PSubscribe(ctx, channels...)
}
return pubsub
}
2020-03-11 17:26:42 +03:00
func (c *SentinelClient) GetMasterAddrByName(ctx context.Context, name string) *StringSliceCmd {
cmd := NewStringSliceCmd(ctx, "sentinel", "get-master-addr-by-name", name)
_ = c.Process(ctx, cmd)
2014-05-11 18:11:55 +04:00
return cmd
}
2020-03-11 17:26:42 +03:00
func (c *SentinelClient) Sentinels(ctx context.Context, name string) *SliceCmd {
cmd := NewSliceCmd(ctx, "sentinel", "sentinels", name)
_ = c.Process(ctx, cmd)
2014-05-11 18:11:55 +04:00
return cmd
}
2019-02-20 13:39:33 +03:00
// Failover forces a failover as if the master was not reachable, and without
// asking for agreement to other Sentinels.
2020-03-11 17:26:42 +03:00
func (c *SentinelClient) Failover(ctx context.Context, name string) *StatusCmd {
cmd := NewStatusCmd(ctx, "sentinel", "failover", name)
_ = c.Process(ctx, cmd)
2019-02-20 13:39:33 +03:00
return cmd
}
2019-02-20 18:19:42 +03:00
// Reset resets all the masters with matching name. The pattern argument is a
// glob-style pattern. The reset process clears any previous state in a master
// (including a failover in progress), and removes every slave and sentinel
// already discovered and associated with the master.
2020-03-11 17:26:42 +03:00
func (c *SentinelClient) Reset(ctx context.Context, pattern string) *IntCmd {
cmd := NewIntCmd(ctx, "sentinel", "reset", pattern)
_ = c.Process(ctx, cmd)
2019-02-20 18:19:42 +03:00
return cmd
}
2019-02-21 13:28:23 +03:00
// FlushConfig forces Sentinel to rewrite its configuration on disk, including
// the current Sentinel state.
2020-03-11 17:26:42 +03:00
func (c *SentinelClient) FlushConfig(ctx context.Context) *StatusCmd {
cmd := NewStatusCmd(ctx, "sentinel", "flushconfig")
_ = c.Process(ctx, cmd)
2019-02-21 13:28:23 +03:00
return cmd
}
2019-02-21 20:13:04 +03:00
// Master shows the state and info of the specified master.
2020-03-11 17:26:42 +03:00
func (c *SentinelClient) Master(ctx context.Context, name string) *StringStringMapCmd {
cmd := NewStringStringMapCmd(ctx, "sentinel", "master", name)
_ = c.Process(ctx, cmd)
2019-02-21 20:13:04 +03:00
return cmd
}
2019-05-25 23:31:06 +03:00
// Masters shows a list of monitored masters and their state.
2020-03-11 17:26:42 +03:00
func (c *SentinelClient) Masters(ctx context.Context) *SliceCmd {
cmd := NewSliceCmd(ctx, "sentinel", "masters")
_ = c.Process(ctx, cmd)
2019-05-25 23:31:06 +03:00
return cmd
}
// Slaves shows a list of slaves for the specified master and their state.
2020-03-11 17:26:42 +03:00
func (c *SentinelClient) Slaves(ctx context.Context, name string) *SliceCmd {
cmd := NewSliceCmd(ctx, "sentinel", "slaves", name)
_ = c.Process(ctx, cmd)
2019-05-25 23:31:06 +03:00
return cmd
}
// CkQuorum checks if the current Sentinel configuration is able to reach the
// quorum needed to failover a master, and the majority needed to authorize the
// failover. This command should be used in monitoring systems to check if a
// Sentinel deployment is ok.
2020-03-11 17:26:42 +03:00
func (c *SentinelClient) CkQuorum(ctx context.Context, name string) *StringCmd {
cmd := NewStringCmd(ctx, "sentinel", "ckquorum", name)
_ = c.Process(ctx, cmd)
2019-05-25 23:31:06 +03:00
return cmd
}
// Monitor tells the Sentinel to start monitoring a new master with the specified
2019-05-25 23:58:27 +03:00
// name, ip, port, and quorum.
2020-03-11 17:26:42 +03:00
func (c *SentinelClient) Monitor(ctx context.Context, name, ip, port, quorum string) *StringCmd {
cmd := NewStringCmd(ctx, "sentinel", "monitor", name, ip, port, quorum)
_ = c.Process(ctx, cmd)
return cmd
}
// Set is used in order to change configuration parameters of a specific master.
2020-03-11 17:26:42 +03:00
func (c *SentinelClient) Set(ctx context.Context, name, option, value string) *StringCmd {
cmd := NewStringCmd(ctx, "sentinel", "set", name, option, value)
_ = c.Process(ctx, cmd)
return cmd
}
// Remove is used in order to remove the specified master: the master will no
// longer be monitored, and will totally be removed from the internal state of
2019-05-25 23:58:27 +03:00
// the Sentinel.
2020-03-11 17:26:42 +03:00
func (c *SentinelClient) Remove(ctx context.Context, name string) *StringCmd {
cmd := NewStringCmd(ctx, "sentinel", "remove", name)
_ = c.Process(ctx, cmd)
return cmd
}
2014-05-11 18:11:55 +04:00
type sentinelFailover struct {
sentinelAddrs []string
sentinelPassword string
2014-05-11 18:11:55 +04:00
opt *Options
2014-05-11 18:11:55 +04:00
pool *pool.ConnPool
2014-05-11 18:11:55 +04:00
poolOnce sync.Once
mu sync.RWMutex
masterName string
_masterAddr string
2018-05-31 13:15:52 +03:00
sentinel *SentinelClient
pubsub *PubSub
}
func (c *sentinelFailover) Close() error {
c.mu.Lock()
defer c.mu.Unlock()
2018-10-25 09:42:56 +03:00
if c.sentinel != nil {
return c.closeSentinel()
}
return nil
2014-05-11 18:11:55 +04:00
}
2019-10-08 12:43:00 +03:00
func (c *sentinelFailover) closeSentinel() error {
firstErr := c.pubsub.Close()
c.pubsub = nil
err := c.sentinel.Close()
if err != nil && firstErr == nil {
firstErr = err
}
c.sentinel = nil
return firstErr
}
func (c *sentinelFailover) Pool() *pool.ConnPool {
c.poolOnce.Do(func() {
opt := *c.opt
opt.Dialer = c.dial
c.pool = newConnPool(&opt)
2014-05-11 18:11:55 +04:00
})
return c.pool
2014-05-11 18:11:55 +04:00
}
2019-07-04 11:18:06 +03:00
func (c *sentinelFailover) dial(ctx context.Context, network, _ string) (net.Conn, error) {
var addr string
var err error
if c.opt.sentinelReadOnly {
addr, err = c.RandomSlaveAddr(ctx)
} else {
addr, err = c.MasterAddr(ctx)
}
2017-07-09 10:07:20 +03:00
if err != nil {
return nil, err
}
if c.opt.Dialer != nil {
return c.opt.Dialer(ctx, network, addr)
}
return net.DialTimeout("tcp", addr, c.opt.DialTimeout)
2017-07-09 10:07:20 +03:00
}
2020-03-11 17:26:42 +03:00
func (c *sentinelFailover) MasterAddr(ctx context.Context) (string, error) {
addr, err := c.masterAddr(ctx)
if err != nil {
return "", err
}
c.switchMaster(ctx, addr)
return addr, nil
}
func (c *sentinelFailover) RandomSlaveAddr(ctx context.Context) (string, error) {
addresses, err := c.slaveAddresses(ctx)
if err != nil {
return "", err
}
if len(addresses) < 1 {
return c.MasterAddr(ctx)
}
return addresses[rand.Intn(len(addresses))], nil
}
2020-03-11 17:26:42 +03:00
func (c *sentinelFailover) masterAddr(ctx context.Context) (string, error) {
2019-10-08 12:43:00 +03:00
c.mu.RLock()
sentinel := c.sentinel
c.mu.RUnlock()
if sentinel != nil {
2020-03-11 17:26:42 +03:00
addr := c.getMasterAddr(ctx, sentinel)
2019-10-08 12:43:00 +03:00
if addr != "" {
return addr, nil
}
2014-05-11 18:11:55 +04:00
}
c.mu.Lock()
defer c.mu.Unlock()
2019-10-08 12:43:00 +03:00
if c.sentinel != nil {
2020-03-11 17:26:42 +03:00
addr := c.getMasterAddr(ctx, c.sentinel)
2019-10-08 12:43:00 +03:00
if addr != "" {
return addr, nil
}
_ = c.closeSentinel()
}
for i, sentinelAddr := range c.sentinelAddrs {
2018-05-31 13:15:52 +03:00
sentinel := NewSentinelClient(&Options{
Addr: sentinelAddr,
Dialer: c.opt.Dialer,
2014-05-11 18:11:55 +04:00
Username: c.opt.Username,
Password: c.opt.Password,
2019-06-02 19:27:33 +03:00
MaxRetries: c.opt.MaxRetries,
DialTimeout: c.opt.DialTimeout,
ReadTimeout: c.opt.ReadTimeout,
WriteTimeout: c.opt.WriteTimeout,
2014-05-11 18:11:55 +04:00
PoolSize: c.opt.PoolSize,
PoolTimeout: c.opt.PoolTimeout,
IdleTimeout: c.opt.IdleTimeout,
IdleCheckFrequency: c.opt.IdleCheckFrequency,
TLSConfig: c.opt.TLSConfig,
2014-05-11 18:11:55 +04:00
})
2020-03-11 17:26:42 +03:00
masterAddr, err := sentinel.GetMasterAddrByName(ctx, c.masterName).Result()
2014-05-11 18:11:55 +04:00
if err != nil {
internal.Logger.Printf(ctx, "sentinel: GetMasterAddrByName master=%q failed: %s",
c.masterName, err)
2018-10-25 09:42:56 +03:00
_ = sentinel.Close()
continue
2014-05-11 18:11:55 +04:00
}
// Push working sentinel to the top.
c.sentinelAddrs[0], c.sentinelAddrs[i] = c.sentinelAddrs[i], c.sentinelAddrs[0]
2020-03-11 17:26:42 +03:00
c.setSentinel(ctx, sentinel)
addr := net.JoinHostPort(masterAddr[0], masterAddr[1])
return addr, nil
2014-05-11 18:11:55 +04:00
}
return "", errors.New("redis: all sentinels are unreachable")
}
func (c *sentinelFailover) slaveAddresses(ctx context.Context) ([]string, error) {
c.mu.RLock()
sentinel := c.sentinel
c.mu.RUnlock()
if sentinel != nil {
addrs := c.getSlaveAddrs(ctx, sentinel)
if len(addrs) > 0 {
return addrs, nil
}
}
c.mu.Lock()
defer c.mu.Unlock()
if c.sentinel != nil {
addrs := c.getSlaveAddrs(ctx, c.sentinel)
if len(addrs) > 0 {
return addrs, nil
}
_ = c.closeSentinel()
}
for i, sentinelAddr := range c.sentinelAddrs {
sentinel := NewSentinelClient(&Options{
Addr: sentinelAddr,
Dialer: c.opt.Dialer,
Username: c.opt.Username,
Password: c.opt.Password,
MaxRetries: c.opt.MaxRetries,
DialTimeout: c.opt.DialTimeout,
ReadTimeout: c.opt.ReadTimeout,
WriteTimeout: c.opt.WriteTimeout,
PoolSize: c.opt.PoolSize,
PoolTimeout: c.opt.PoolTimeout,
IdleTimeout: c.opt.IdleTimeout,
IdleCheckFrequency: c.opt.IdleCheckFrequency,
TLSConfig: c.opt.TLSConfig,
})
slaves, err := sentinel.Slaves(ctx, c.masterName).Result()
if err != nil {
internal.Logger.Printf(ctx, "sentinel: Slaves master=%q failed: %s",
c.masterName, err)
_ = sentinel.Close()
continue
}
// Push working sentinel to the top.
c.sentinelAddrs[0], c.sentinelAddrs[i] = c.sentinelAddrs[i], c.sentinelAddrs[0]
c.setSentinel(ctx, sentinel)
addrs := parseSlaveAddresses(slaves)
return addrs, nil
}
return []string{}, errors.New("redis: all sentinels are unreachable")
}
2020-03-11 17:26:42 +03:00
func (c *sentinelFailover) getMasterAddr(ctx context.Context, sentinel *SentinelClient) string {
addr, err := sentinel.GetMasterAddrByName(ctx, c.masterName).Result()
if err != nil {
internal.Logger.Printf(ctx, "sentinel: GetMasterAddrByName name=%q failed: %s",
c.masterName, err)
return ""
}
return net.JoinHostPort(addr[0], addr[1])
2018-07-23 15:55:13 +03:00
}
func (c *sentinelFailover) getSlaveAddrs(ctx context.Context, sentinel *SentinelClient) []string {
addrs, err := sentinel.Slaves(ctx, c.masterName).Result()
if err != nil {
internal.Logger.Printf(ctx, "sentinel: Slaves name=%q failed: %s",
c.masterName, err)
return []string{}
}
return parseSlaveAddresses(addrs)
}
func parseSlaveAddresses(addrs []interface{}) []string {
nodes := []string{}
for _, node := range addrs {
ip := ""
port := ""
flags := []string{}
lastkey := ""
isDown := false
for _, key := range node.([]interface{}) {
switch lastkey {
case "ip":
ip = key.(string)
case "port":
port = key.(string)
case "flags":
flags = strings.Split(key.(string), ",")
}
lastkey = key.(string)
}
for _, flag := range flags {
switch flag {
case "s_down", "o_down", "disconnected":
isDown = true
}
}
if !isDown {
nodes = append(nodes, net.JoinHostPort(ip, port))
}
}
return nodes
}
func (c *sentinelFailover) switchMaster(ctx context.Context, addr string) {
c.mu.RLock()
masterAddr := c._masterAddr
c.mu.RUnlock()
if masterAddr == addr {
2018-07-23 15:55:13 +03:00
return
}
c.mu.Lock()
defer c.mu.Unlock()
2019-10-08 12:43:00 +03:00
if c._masterAddr == addr {
return
}
internal.Logger.Printf(ctx, "sentinel: new master=%q addr=%q",
2018-07-23 15:55:13 +03:00
c.masterName, addr)
_ = c.Pool().Filter(func(cn *pool.Conn) bool {
return cn.RemoteAddr().String() != addr
})
2018-07-23 15:55:13 +03:00
c._masterAddr = addr
}
2020-03-11 17:26:42 +03:00
func (c *sentinelFailover) setSentinel(ctx context.Context, sentinel *SentinelClient) {
2019-10-08 12:43:00 +03:00
if c.sentinel != nil {
panic("not reached")
}
c.sentinel = sentinel
2020-03-11 17:26:42 +03:00
c.discoverSentinels(ctx)
2018-11-11 13:13:00 +03:00
2020-03-11 17:26:42 +03:00
c.pubsub = sentinel.Subscribe(ctx, "+switch-master")
2018-11-11 13:13:00 +03:00
go c.listen(c.pubsub)
}
2020-03-11 17:26:42 +03:00
func (c *sentinelFailover) discoverSentinels(ctx context.Context) {
sentinels, err := c.sentinel.Sentinels(ctx, c.masterName).Result()
2014-05-11 18:11:55 +04:00
if err != nil {
internal.Logger.Printf(ctx, "sentinel: Sentinels master=%q failed: %s", c.masterName, err)
2014-05-11 18:11:55 +04:00
return
}
for _, sentinel := range sentinels {
vals := sentinel.([]interface{})
for i := 0; i < len(vals); i += 2 {
key := vals[i].(string)
if key == "name" {
sentinelAddr := vals[i+1].(string)
if !contains(c.sentinelAddrs, sentinelAddr) {
internal.Logger.Printf(ctx, "sentinel: discovered new sentinel=%q for master=%q",
sentinelAddr, c.masterName)
c.sentinelAddrs = append(c.sentinelAddrs, sentinelAddr)
2014-05-11 18:11:55 +04:00
}
}
}
}
}
2018-11-11 13:13:00 +03:00
func (c *sentinelFailover) listen(pubsub *PubSub) {
ch := pubsub.Channel()
2018-07-23 15:55:13 +03:00
for {
msg, ok := <-ch
if !ok {
break
2014-05-11 18:11:55 +04:00
}
if msg.Channel == "+switch-master" {
parts := strings.Split(msg.Payload, " ")
if parts[0] != c.masterName {
internal.Logger.Printf(pubsub.getContext(), "sentinel: ignore addr for master=%q", parts[0])
continue
2014-05-11 18:11:55 +04:00
}
addr := net.JoinHostPort(parts[3], parts[4])
c.switchMaster(pubsub.getContext(), addr)
2014-05-11 18:11:55 +04:00
}
}
}
func contains(slice []string, str string) bool {
for _, s := range slice {
if s == str {
return true
}
}
return false
}