2019-04-08 11:05:15 +02:00
|
|
|
package redis
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"crypto/tls"
|
|
|
|
"fmt"
|
|
|
|
"math"
|
|
|
|
"net"
|
|
|
|
"runtime"
|
|
|
|
"sort"
|
|
|
|
"sync"
|
|
|
|
"sync/atomic"
|
|
|
|
"time"
|
|
|
|
|
2021-02-10 22:28:32 +01:00
|
|
|
"github.com/go-redis/redis/v8/internal"
|
|
|
|
"github.com/go-redis/redis/v8/internal/hashtag"
|
|
|
|
"github.com/go-redis/redis/v8/internal/pool"
|
|
|
|
"github.com/go-redis/redis/v8/internal/proto"
|
|
|
|
"github.com/go-redis/redis/v8/internal/rand"
|
2019-04-08 11:05:15 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
var errClusterNoNodes = fmt.Errorf("redis: cluster has no nodes")
|
|
|
|
|
|
|
|
// ClusterOptions are used to configure a cluster client and should be
|
|
|
|
// passed to NewClusterClient.
|
|
|
|
type ClusterOptions struct {
|
|
|
|
// A seed list of host:port addresses of cluster nodes.
|
|
|
|
Addrs []string
|
|
|
|
|
2021-02-10 22:28:32 +01:00
|
|
|
// NewClient creates a cluster node client with provided name and options.
|
|
|
|
NewClient func(opt *Options) *Client
|
|
|
|
|
2019-04-08 11:05:15 +02:00
|
|
|
// The maximum number of retries before giving up. Command is retried
|
|
|
|
// on network errors and MOVED/ASK redirects.
|
2021-02-10 22:28:32 +01:00
|
|
|
// Default is 3 retries.
|
2019-04-08 11:05:15 +02:00
|
|
|
MaxRedirects int
|
|
|
|
|
|
|
|
// Enables read-only commands on slave nodes.
|
|
|
|
ReadOnly bool
|
|
|
|
// Allows routing read-only commands to the closest master or slave node.
|
|
|
|
// It automatically enables ReadOnly.
|
|
|
|
RouteByLatency bool
|
|
|
|
// Allows routing read-only commands to the random master or slave node.
|
|
|
|
// It automatically enables ReadOnly.
|
|
|
|
RouteRandomly bool
|
|
|
|
|
|
|
|
// Optional function that returns cluster slots information.
|
|
|
|
// It is useful to manually create cluster of standalone Redis servers
|
|
|
|
// and load-balance read/write operations between master and slaves.
|
|
|
|
// It can use service like ZooKeeper to maintain configuration information
|
|
|
|
// and Cluster.ReloadState to manually trigger state reloading.
|
2021-02-10 22:28:32 +01:00
|
|
|
ClusterSlots func(context.Context) ([]ClusterSlot, error)
|
2019-04-08 11:05:15 +02:00
|
|
|
|
|
|
|
// Following options are copied from Options struct.
|
|
|
|
|
2020-09-27 23:09:46 +02:00
|
|
|
Dialer func(ctx context.Context, network, addr string) (net.Conn, error)
|
|
|
|
|
2021-02-10 22:28:32 +01:00
|
|
|
OnConnect func(ctx context.Context, cn *Conn) error
|
2019-04-08 11:05:15 +02:00
|
|
|
|
2020-09-27 23:09:46 +02:00
|
|
|
Username string
|
2019-04-08 11:05:15 +02:00
|
|
|
Password string
|
|
|
|
|
|
|
|
MaxRetries int
|
|
|
|
MinRetryBackoff time.Duration
|
|
|
|
MaxRetryBackoff time.Duration
|
|
|
|
|
|
|
|
DialTimeout time.Duration
|
|
|
|
ReadTimeout time.Duration
|
|
|
|
WriteTimeout time.Duration
|
|
|
|
|
|
|
|
// PoolSize applies per cluster node and not for the whole cluster.
|
|
|
|
PoolSize int
|
|
|
|
MinIdleConns int
|
|
|
|
MaxConnAge time.Duration
|
|
|
|
PoolTimeout time.Duration
|
|
|
|
IdleTimeout time.Duration
|
|
|
|
IdleCheckFrequency time.Duration
|
|
|
|
|
|
|
|
TLSConfig *tls.Config
|
|
|
|
}
|
|
|
|
|
|
|
|
func (opt *ClusterOptions) init() {
|
|
|
|
if opt.MaxRedirects == -1 {
|
|
|
|
opt.MaxRedirects = 0
|
|
|
|
} else if opt.MaxRedirects == 0 {
|
2021-02-10 22:28:32 +01:00
|
|
|
opt.MaxRedirects = 3
|
2019-04-08 11:05:15 +02:00
|
|
|
}
|
|
|
|
|
2021-02-10 22:28:32 +01:00
|
|
|
if opt.RouteByLatency || opt.RouteRandomly {
|
2019-04-08 11:05:15 +02:00
|
|
|
opt.ReadOnly = true
|
|
|
|
}
|
|
|
|
|
|
|
|
if opt.PoolSize == 0 {
|
2021-07-04 04:06:10 +02:00
|
|
|
opt.PoolSize = 5 * runtime.GOMAXPROCS(0)
|
2019-04-08 11:05:15 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
switch opt.ReadTimeout {
|
|
|
|
case -1:
|
|
|
|
opt.ReadTimeout = 0
|
|
|
|
case 0:
|
|
|
|
opt.ReadTimeout = 3 * time.Second
|
|
|
|
}
|
|
|
|
switch opt.WriteTimeout {
|
|
|
|
case -1:
|
|
|
|
opt.WriteTimeout = 0
|
|
|
|
case 0:
|
|
|
|
opt.WriteTimeout = opt.ReadTimeout
|
|
|
|
}
|
|
|
|
|
2021-02-10 22:28:32 +01:00
|
|
|
if opt.MaxRetries == 0 {
|
|
|
|
opt.MaxRetries = -1
|
|
|
|
}
|
2019-04-08 11:05:15 +02:00
|
|
|
switch opt.MinRetryBackoff {
|
|
|
|
case -1:
|
|
|
|
opt.MinRetryBackoff = 0
|
|
|
|
case 0:
|
|
|
|
opt.MinRetryBackoff = 8 * time.Millisecond
|
|
|
|
}
|
|
|
|
switch opt.MaxRetryBackoff {
|
|
|
|
case -1:
|
|
|
|
opt.MaxRetryBackoff = 0
|
|
|
|
case 0:
|
|
|
|
opt.MaxRetryBackoff = 512 * time.Millisecond
|
|
|
|
}
|
2020-09-27 23:09:46 +02:00
|
|
|
|
|
|
|
if opt.NewClient == nil {
|
|
|
|
opt.NewClient = NewClient
|
|
|
|
}
|
2019-04-08 11:05:15 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func (opt *ClusterOptions) clientOptions() *Options {
|
|
|
|
const disableIdleCheck = -1
|
|
|
|
|
|
|
|
return &Options{
|
2020-09-27 23:09:46 +02:00
|
|
|
Dialer: opt.Dialer,
|
2019-04-08 11:05:15 +02:00
|
|
|
OnConnect: opt.OnConnect,
|
|
|
|
|
2021-02-10 22:28:32 +01:00
|
|
|
Username: opt.Username,
|
|
|
|
Password: opt.Password,
|
|
|
|
|
2019-04-08 11:05:15 +02:00
|
|
|
MaxRetries: opt.MaxRetries,
|
|
|
|
MinRetryBackoff: opt.MinRetryBackoff,
|
|
|
|
MaxRetryBackoff: opt.MaxRetryBackoff,
|
|
|
|
|
|
|
|
DialTimeout: opt.DialTimeout,
|
|
|
|
ReadTimeout: opt.ReadTimeout,
|
|
|
|
WriteTimeout: opt.WriteTimeout,
|
|
|
|
|
|
|
|
PoolSize: opt.PoolSize,
|
|
|
|
MinIdleConns: opt.MinIdleConns,
|
|
|
|
MaxConnAge: opt.MaxConnAge,
|
|
|
|
PoolTimeout: opt.PoolTimeout,
|
|
|
|
IdleTimeout: opt.IdleTimeout,
|
|
|
|
IdleCheckFrequency: disableIdleCheck,
|
|
|
|
|
|
|
|
TLSConfig: opt.TLSConfig,
|
2021-02-10 22:28:32 +01:00
|
|
|
// If ClusterSlots is populated, then we probably have an artificial
|
|
|
|
// cluster whose nodes are not in clustering mode (otherwise there isn't
|
|
|
|
// much use for ClusterSlots config). This means we cannot execute the
|
|
|
|
// READONLY command against that node -- setting readOnly to false in such
|
|
|
|
// situations in the options below will prevent that from happening.
|
|
|
|
readOnly: opt.ReadOnly && opt.ClusterSlots == nil,
|
2019-04-08 11:05:15 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
//------------------------------------------------------------------------------
|
|
|
|
|
|
|
|
type clusterNode struct {
|
|
|
|
Client *Client
|
|
|
|
|
|
|
|
latency uint32 // atomic
|
|
|
|
generation uint32 // atomic
|
2020-09-27 23:09:46 +02:00
|
|
|
failing uint32 // atomic
|
2019-04-08 11:05:15 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func newClusterNode(clOpt *ClusterOptions, addr string) *clusterNode {
|
|
|
|
opt := clOpt.clientOptions()
|
|
|
|
opt.Addr = addr
|
|
|
|
node := clusterNode{
|
2020-09-27 23:09:46 +02:00
|
|
|
Client: clOpt.NewClient(opt),
|
2019-04-08 11:05:15 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
node.latency = math.MaxUint32
|
|
|
|
if clOpt.RouteByLatency {
|
|
|
|
go node.updateLatency()
|
|
|
|
}
|
|
|
|
|
|
|
|
return &node
|
|
|
|
}
|
|
|
|
|
|
|
|
func (n *clusterNode) String() string {
|
|
|
|
return n.Client.String()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (n *clusterNode) Close() error {
|
|
|
|
return n.Client.Close()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (n *clusterNode) updateLatency() {
|
2021-02-10 22:28:32 +01:00
|
|
|
const numProbe = 10
|
|
|
|
var dur uint64
|
|
|
|
|
|
|
|
for i := 0; i < numProbe; i++ {
|
|
|
|
time.Sleep(time.Duration(10+rand.Intn(10)) * time.Millisecond)
|
2019-04-08 11:05:15 +02:00
|
|
|
|
|
|
|
start := time.Now()
|
2021-02-10 22:28:32 +01:00
|
|
|
n.Client.Ping(context.TODO())
|
|
|
|
dur += uint64(time.Since(start) / time.Microsecond)
|
2019-04-08 11:05:15 +02:00
|
|
|
}
|
2021-02-10 22:28:32 +01:00
|
|
|
|
|
|
|
latency := float64(dur) / float64(numProbe)
|
|
|
|
atomic.StoreUint32(&n.latency, uint32(latency+0.5))
|
2019-04-08 11:05:15 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func (n *clusterNode) Latency() time.Duration {
|
|
|
|
latency := atomic.LoadUint32(&n.latency)
|
|
|
|
return time.Duration(latency) * time.Microsecond
|
|
|
|
}
|
|
|
|
|
2020-09-27 23:09:46 +02:00
|
|
|
func (n *clusterNode) MarkAsFailing() {
|
|
|
|
atomic.StoreUint32(&n.failing, uint32(time.Now().Unix()))
|
2019-04-08 11:05:15 +02:00
|
|
|
}
|
|
|
|
|
2020-09-27 23:09:46 +02:00
|
|
|
func (n *clusterNode) Failing() bool {
|
|
|
|
const timeout = 15 // 15 seconds
|
2019-04-08 11:05:15 +02:00
|
|
|
|
2020-09-27 23:09:46 +02:00
|
|
|
failing := atomic.LoadUint32(&n.failing)
|
|
|
|
if failing == 0 {
|
2019-04-08 11:05:15 +02:00
|
|
|
return false
|
|
|
|
}
|
2020-09-27 23:09:46 +02:00
|
|
|
if time.Now().Unix()-int64(failing) < timeout {
|
2019-04-08 11:05:15 +02:00
|
|
|
return true
|
|
|
|
}
|
2020-09-27 23:09:46 +02:00
|
|
|
atomic.StoreUint32(&n.failing, 0)
|
2019-04-08 11:05:15 +02:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
func (n *clusterNode) Generation() uint32 {
|
|
|
|
return atomic.LoadUint32(&n.generation)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (n *clusterNode) SetGeneration(gen uint32) {
|
|
|
|
for {
|
|
|
|
v := atomic.LoadUint32(&n.generation)
|
|
|
|
if gen < v || atomic.CompareAndSwapUint32(&n.generation, v, gen) {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
//------------------------------------------------------------------------------
|
|
|
|
|
|
|
|
type clusterNodes struct {
|
|
|
|
opt *ClusterOptions
|
|
|
|
|
2021-02-10 22:28:32 +01:00
|
|
|
mu sync.RWMutex
|
|
|
|
addrs []string
|
|
|
|
nodes map[string]*clusterNode
|
|
|
|
activeAddrs []string
|
|
|
|
closed bool
|
2019-04-08 11:05:15 +02:00
|
|
|
|
|
|
|
_generation uint32 // atomic
|
|
|
|
}
|
|
|
|
|
|
|
|
func newClusterNodes(opt *ClusterOptions) *clusterNodes {
|
|
|
|
return &clusterNodes{
|
|
|
|
opt: opt,
|
|
|
|
|
2021-02-10 22:28:32 +01:00
|
|
|
addrs: opt.Addrs,
|
|
|
|
nodes: make(map[string]*clusterNode),
|
2019-04-08 11:05:15 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *clusterNodes) Close() error {
|
|
|
|
c.mu.Lock()
|
|
|
|
defer c.mu.Unlock()
|
|
|
|
|
|
|
|
if c.closed {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
c.closed = true
|
|
|
|
|
|
|
|
var firstErr error
|
2021-02-10 22:28:32 +01:00
|
|
|
for _, node := range c.nodes {
|
2019-04-08 11:05:15 +02:00
|
|
|
if err := node.Client.Close(); err != nil && firstErr == nil {
|
|
|
|
firstErr = err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-10 22:28:32 +01:00
|
|
|
c.nodes = nil
|
|
|
|
c.activeAddrs = nil
|
2019-04-08 11:05:15 +02:00
|
|
|
|
|
|
|
return firstErr
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *clusterNodes) Addrs() ([]string, error) {
|
|
|
|
var addrs []string
|
2021-04-23 02:08:53 +02:00
|
|
|
|
2019-04-08 11:05:15 +02:00
|
|
|
c.mu.RLock()
|
2021-04-23 02:08:53 +02:00
|
|
|
closed := c.closed //nolint:ifshort
|
2019-04-08 11:05:15 +02:00
|
|
|
if !closed {
|
2021-02-10 22:28:32 +01:00
|
|
|
if len(c.activeAddrs) > 0 {
|
|
|
|
addrs = c.activeAddrs
|
2019-04-08 11:05:15 +02:00
|
|
|
} else {
|
2021-02-10 22:28:32 +01:00
|
|
|
addrs = c.addrs
|
2019-04-08 11:05:15 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
c.mu.RUnlock()
|
|
|
|
|
|
|
|
if closed {
|
|
|
|
return nil, pool.ErrClosed
|
|
|
|
}
|
|
|
|
if len(addrs) == 0 {
|
|
|
|
return nil, errClusterNoNodes
|
|
|
|
}
|
|
|
|
return addrs, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *clusterNodes) NextGeneration() uint32 {
|
|
|
|
return atomic.AddUint32(&c._generation, 1)
|
|
|
|
}
|
|
|
|
|
|
|
|
// GC removes unused nodes.
|
|
|
|
func (c *clusterNodes) GC(generation uint32) {
|
2020-09-27 23:09:46 +02:00
|
|
|
//nolint:prealloc
|
2019-04-08 11:05:15 +02:00
|
|
|
var collected []*clusterNode
|
2021-02-10 22:28:32 +01:00
|
|
|
|
2019-04-08 11:05:15 +02:00
|
|
|
c.mu.Lock()
|
2021-02-10 22:28:32 +01:00
|
|
|
|
|
|
|
c.activeAddrs = c.activeAddrs[:0]
|
|
|
|
for addr, node := range c.nodes {
|
2019-04-08 11:05:15 +02:00
|
|
|
if node.Generation() >= generation {
|
2021-02-10 22:28:32 +01:00
|
|
|
c.activeAddrs = append(c.activeAddrs, addr)
|
|
|
|
if c.opt.RouteByLatency {
|
|
|
|
go node.updateLatency()
|
|
|
|
}
|
2019-04-08 11:05:15 +02:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2021-02-10 22:28:32 +01:00
|
|
|
delete(c.nodes, addr)
|
2019-04-08 11:05:15 +02:00
|
|
|
collected = append(collected, node)
|
|
|
|
}
|
2021-02-10 22:28:32 +01:00
|
|
|
|
2019-04-08 11:05:15 +02:00
|
|
|
c.mu.Unlock()
|
|
|
|
|
|
|
|
for _, node := range collected {
|
|
|
|
_ = node.Client.Close()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *clusterNodes) Get(addr string) (*clusterNode, error) {
|
2020-09-27 23:09:46 +02:00
|
|
|
node, err := c.get(addr)
|
2019-04-08 11:05:15 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
if node != nil {
|
|
|
|
return node, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
c.mu.Lock()
|
|
|
|
defer c.mu.Unlock()
|
|
|
|
|
|
|
|
if c.closed {
|
|
|
|
return nil, pool.ErrClosed
|
|
|
|
}
|
|
|
|
|
2021-02-10 22:28:32 +01:00
|
|
|
node, ok := c.nodes[addr]
|
2019-04-08 11:05:15 +02:00
|
|
|
if ok {
|
2021-02-10 22:28:32 +01:00
|
|
|
return node, nil
|
2019-04-08 11:05:15 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
node = newClusterNode(c.opt, addr)
|
|
|
|
|
2021-02-10 22:28:32 +01:00
|
|
|
c.addrs = appendIfNotExists(c.addrs, addr)
|
|
|
|
c.nodes[addr] = node
|
2019-04-08 11:05:15 +02:00
|
|
|
|
2021-02-10 22:28:32 +01:00
|
|
|
return node, nil
|
2019-04-08 11:05:15 +02:00
|
|
|
}
|
|
|
|
|
2020-09-27 23:09:46 +02:00
|
|
|
func (c *clusterNodes) get(addr string) (*clusterNode, error) {
|
|
|
|
var node *clusterNode
|
|
|
|
var err error
|
|
|
|
c.mu.RLock()
|
|
|
|
if c.closed {
|
|
|
|
err = pool.ErrClosed
|
|
|
|
} else {
|
2021-02-10 22:28:32 +01:00
|
|
|
node = c.nodes[addr]
|
2020-09-27 23:09:46 +02:00
|
|
|
}
|
|
|
|
c.mu.RUnlock()
|
|
|
|
return node, err
|
|
|
|
}
|
|
|
|
|
2019-04-08 11:05:15 +02:00
|
|
|
func (c *clusterNodes) All() ([]*clusterNode, error) {
|
|
|
|
c.mu.RLock()
|
|
|
|
defer c.mu.RUnlock()
|
|
|
|
|
|
|
|
if c.closed {
|
|
|
|
return nil, pool.ErrClosed
|
|
|
|
}
|
|
|
|
|
2021-02-10 22:28:32 +01:00
|
|
|
cp := make([]*clusterNode, 0, len(c.nodes))
|
|
|
|
for _, node := range c.nodes {
|
2019-04-08 11:05:15 +02:00
|
|
|
cp = append(cp, node)
|
|
|
|
}
|
|
|
|
return cp, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *clusterNodes) Random() (*clusterNode, error) {
|
|
|
|
addrs, err := c.Addrs()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
n := rand.Intn(len(addrs))
|
2020-09-27 23:09:46 +02:00
|
|
|
return c.Get(addrs[n])
|
2019-04-08 11:05:15 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
//------------------------------------------------------------------------------
|
|
|
|
|
|
|
|
type clusterSlot struct {
|
|
|
|
start, end int
|
|
|
|
nodes []*clusterNode
|
|
|
|
}
|
|
|
|
|
|
|
|
type clusterSlotSlice []*clusterSlot
|
|
|
|
|
|
|
|
func (p clusterSlotSlice) Len() int {
|
|
|
|
return len(p)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p clusterSlotSlice) Less(i, j int) bool {
|
|
|
|
return p[i].start < p[j].start
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p clusterSlotSlice) Swap(i, j int) {
|
|
|
|
p[i], p[j] = p[j], p[i]
|
|
|
|
}
|
|
|
|
|
|
|
|
type clusterState struct {
|
|
|
|
nodes *clusterNodes
|
|
|
|
Masters []*clusterNode
|
|
|
|
Slaves []*clusterNode
|
|
|
|
|
|
|
|
slots []*clusterSlot
|
|
|
|
|
|
|
|
generation uint32
|
|
|
|
createdAt time.Time
|
|
|
|
}
|
|
|
|
|
|
|
|
func newClusterState(
|
|
|
|
nodes *clusterNodes, slots []ClusterSlot, origin string,
|
|
|
|
) (*clusterState, error) {
|
|
|
|
c := clusterState{
|
|
|
|
nodes: nodes,
|
|
|
|
|
|
|
|
slots: make([]*clusterSlot, 0, len(slots)),
|
|
|
|
|
|
|
|
generation: nodes.NextGeneration(),
|
|
|
|
createdAt: time.Now(),
|
|
|
|
}
|
|
|
|
|
|
|
|
originHost, _, _ := net.SplitHostPort(origin)
|
|
|
|
isLoopbackOrigin := isLoopback(originHost)
|
|
|
|
|
|
|
|
for _, slot := range slots {
|
|
|
|
var nodes []*clusterNode
|
|
|
|
for i, slotNode := range slot.Nodes {
|
|
|
|
addr := slotNode.Addr
|
|
|
|
if !isLoopbackOrigin {
|
|
|
|
addr = replaceLoopbackHost(addr, originHost)
|
|
|
|
}
|
|
|
|
|
2020-09-27 23:09:46 +02:00
|
|
|
node, err := c.nodes.Get(addr)
|
2019-04-08 11:05:15 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
node.SetGeneration(c.generation)
|
|
|
|
nodes = append(nodes, node)
|
|
|
|
|
|
|
|
if i == 0 {
|
|
|
|
c.Masters = appendUniqueNode(c.Masters, node)
|
|
|
|
} else {
|
|
|
|
c.Slaves = appendUniqueNode(c.Slaves, node)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
c.slots = append(c.slots, &clusterSlot{
|
|
|
|
start: slot.Start,
|
|
|
|
end: slot.End,
|
|
|
|
nodes: nodes,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
sort.Sort(clusterSlotSlice(c.slots))
|
|
|
|
|
|
|
|
time.AfterFunc(time.Minute, func() {
|
|
|
|
nodes.GC(c.generation)
|
|
|
|
})
|
|
|
|
|
|
|
|
return &c, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func replaceLoopbackHost(nodeAddr, originHost string) string {
|
|
|
|
nodeHost, nodePort, err := net.SplitHostPort(nodeAddr)
|
|
|
|
if err != nil {
|
|
|
|
return nodeAddr
|
|
|
|
}
|
|
|
|
|
|
|
|
nodeIP := net.ParseIP(nodeHost)
|
|
|
|
if nodeIP == nil {
|
|
|
|
return nodeAddr
|
|
|
|
}
|
|
|
|
|
|
|
|
if !nodeIP.IsLoopback() {
|
|
|
|
return nodeAddr
|
|
|
|
}
|
|
|
|
|
|
|
|
// Use origin host which is not loopback and node port.
|
|
|
|
return net.JoinHostPort(originHost, nodePort)
|
|
|
|
}
|
|
|
|
|
|
|
|
func isLoopback(host string) bool {
|
|
|
|
ip := net.ParseIP(host)
|
|
|
|
if ip == nil {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
return ip.IsLoopback()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *clusterState) slotMasterNode(slot int) (*clusterNode, error) {
|
|
|
|
nodes := c.slotNodes(slot)
|
|
|
|
if len(nodes) > 0 {
|
|
|
|
return nodes[0], nil
|
|
|
|
}
|
|
|
|
return c.nodes.Random()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *clusterState) slotSlaveNode(slot int) (*clusterNode, error) {
|
|
|
|
nodes := c.slotNodes(slot)
|
|
|
|
switch len(nodes) {
|
|
|
|
case 0:
|
|
|
|
return c.nodes.Random()
|
|
|
|
case 1:
|
|
|
|
return nodes[0], nil
|
|
|
|
case 2:
|
2020-09-27 23:09:46 +02:00
|
|
|
if slave := nodes[1]; !slave.Failing() {
|
2019-04-08 11:05:15 +02:00
|
|
|
return slave, nil
|
|
|
|
}
|
|
|
|
return nodes[0], nil
|
|
|
|
default:
|
|
|
|
var slave *clusterNode
|
|
|
|
for i := 0; i < 10; i++ {
|
|
|
|
n := rand.Intn(len(nodes)-1) + 1
|
|
|
|
slave = nodes[n]
|
2020-09-27 23:09:46 +02:00
|
|
|
if !slave.Failing() {
|
2019-04-08 11:05:15 +02:00
|
|
|
return slave, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// All slaves are loading - use master.
|
|
|
|
return nodes[0], nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *clusterState) slotClosestNode(slot int) (*clusterNode, error) {
|
|
|
|
nodes := c.slotNodes(slot)
|
|
|
|
if len(nodes) == 0 {
|
|
|
|
return c.nodes.Random()
|
|
|
|
}
|
|
|
|
|
|
|
|
var node *clusterNode
|
|
|
|
for _, n := range nodes {
|
2020-09-27 23:09:46 +02:00
|
|
|
if n.Failing() {
|
2019-04-08 11:05:15 +02:00
|
|
|
continue
|
|
|
|
}
|
2021-02-10 22:28:32 +01:00
|
|
|
if node == nil || n.Latency() < node.Latency() {
|
2019-04-08 11:05:15 +02:00
|
|
|
node = n
|
|
|
|
}
|
|
|
|
}
|
2021-02-10 22:28:32 +01:00
|
|
|
if node != nil {
|
|
|
|
return node, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// If all nodes are failing - return random node
|
|
|
|
return c.nodes.Random()
|
2019-04-08 11:05:15 +02:00
|
|
|
}
|
|
|
|
|
2020-09-27 23:09:46 +02:00
|
|
|
func (c *clusterState) slotRandomNode(slot int) (*clusterNode, error) {
|
2019-04-08 11:05:15 +02:00
|
|
|
nodes := c.slotNodes(slot)
|
2020-09-27 23:09:46 +02:00
|
|
|
if len(nodes) == 0 {
|
|
|
|
return c.nodes.Random()
|
|
|
|
}
|
2019-04-08 11:05:15 +02:00
|
|
|
n := rand.Intn(len(nodes))
|
2020-09-27 23:09:46 +02:00
|
|
|
return nodes[n], nil
|
2019-04-08 11:05:15 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func (c *clusterState) slotNodes(slot int) []*clusterNode {
|
|
|
|
i := sort.Search(len(c.slots), func(i int) bool {
|
|
|
|
return c.slots[i].end >= slot
|
|
|
|
})
|
|
|
|
if i >= len(c.slots) {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
x := c.slots[i]
|
|
|
|
if slot >= x.start && slot <= x.end {
|
|
|
|
return x.nodes
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
//------------------------------------------------------------------------------
|
|
|
|
|
|
|
|
type clusterStateHolder struct {
|
2021-02-10 22:28:32 +01:00
|
|
|
load func(ctx context.Context) (*clusterState, error)
|
2019-04-08 11:05:15 +02:00
|
|
|
|
|
|
|
state atomic.Value
|
|
|
|
reloading uint32 // atomic
|
|
|
|
}
|
|
|
|
|
2021-02-10 22:28:32 +01:00
|
|
|
func newClusterStateHolder(fn func(ctx context.Context) (*clusterState, error)) *clusterStateHolder {
|
2019-04-08 11:05:15 +02:00
|
|
|
return &clusterStateHolder{
|
|
|
|
load: fn,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-10 22:28:32 +01:00
|
|
|
func (c *clusterStateHolder) Reload(ctx context.Context) (*clusterState, error) {
|
|
|
|
state, err := c.load(ctx)
|
2019-04-08 11:05:15 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
c.state.Store(state)
|
|
|
|
return state, nil
|
|
|
|
}
|
|
|
|
|
2021-04-23 02:08:53 +02:00
|
|
|
func (c *clusterStateHolder) LazyReload() {
|
2019-04-08 11:05:15 +02:00
|
|
|
if !atomic.CompareAndSwapUint32(&c.reloading, 0, 1) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
go func() {
|
|
|
|
defer atomic.StoreUint32(&c.reloading, 0)
|
|
|
|
|
2021-04-23 02:08:53 +02:00
|
|
|
_, err := c.Reload(context.Background())
|
2019-04-08 11:05:15 +02:00
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
2021-02-10 22:28:32 +01:00
|
|
|
time.Sleep(200 * time.Millisecond)
|
2019-04-08 11:05:15 +02:00
|
|
|
}()
|
|
|
|
}
|
|
|
|
|
2021-02-10 22:28:32 +01:00
|
|
|
func (c *clusterStateHolder) Get(ctx context.Context) (*clusterState, error) {
|
2019-04-08 11:05:15 +02:00
|
|
|
v := c.state.Load()
|
2021-04-23 02:08:53 +02:00
|
|
|
if v == nil {
|
|
|
|
return c.Reload(ctx)
|
2019-04-08 11:05:15 +02:00
|
|
|
}
|
2021-04-23 02:08:53 +02:00
|
|
|
|
|
|
|
state := v.(*clusterState)
|
|
|
|
if time.Since(state.createdAt) > 10*time.Second {
|
|
|
|
c.LazyReload()
|
|
|
|
}
|
|
|
|
return state, nil
|
2019-04-08 11:05:15 +02:00
|
|
|
}
|
|
|
|
|
2021-02-10 22:28:32 +01:00
|
|
|
func (c *clusterStateHolder) ReloadOrGet(ctx context.Context) (*clusterState, error) {
|
|
|
|
state, err := c.Reload(ctx)
|
2019-04-08 11:05:15 +02:00
|
|
|
if err == nil {
|
|
|
|
return state, nil
|
|
|
|
}
|
2021-02-10 22:28:32 +01:00
|
|
|
return c.Get(ctx)
|
2019-04-08 11:05:15 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
//------------------------------------------------------------------------------
|
|
|
|
|
2020-09-27 23:09:46 +02:00
|
|
|
type clusterClient struct {
|
|
|
|
opt *ClusterOptions
|
|
|
|
nodes *clusterNodes
|
|
|
|
state *clusterStateHolder //nolint:structcheck
|
|
|
|
cmdsInfoCache *cmdsInfoCache //nolint:structcheck
|
|
|
|
}
|
|
|
|
|
2019-04-08 11:05:15 +02:00
|
|
|
// ClusterClient is a Redis Cluster client representing a pool of zero
|
|
|
|
// or more underlying connections. It's safe for concurrent use by
|
|
|
|
// multiple goroutines.
|
|
|
|
type ClusterClient struct {
|
2020-09-27 23:09:46 +02:00
|
|
|
*clusterClient
|
2019-04-08 11:05:15 +02:00
|
|
|
cmdable
|
2020-09-27 23:09:46 +02:00
|
|
|
hooks
|
2019-04-08 11:05:15 +02:00
|
|
|
ctx context.Context
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewClusterClient returns a Redis Cluster client as described in
|
|
|
|
// http://redis.io/topics/cluster-spec.
|
|
|
|
func NewClusterClient(opt *ClusterOptions) *ClusterClient {
|
|
|
|
opt.init()
|
|
|
|
|
|
|
|
c := &ClusterClient{
|
2020-09-27 23:09:46 +02:00
|
|
|
clusterClient: &clusterClient{
|
|
|
|
opt: opt,
|
|
|
|
nodes: newClusterNodes(opt),
|
|
|
|
},
|
|
|
|
ctx: context.Background(),
|
2019-04-08 11:05:15 +02:00
|
|
|
}
|
|
|
|
c.state = newClusterStateHolder(c.loadState)
|
|
|
|
c.cmdsInfoCache = newCmdsInfoCache(c.cmdsInfo)
|
2020-09-27 23:09:46 +02:00
|
|
|
c.cmdable = c.Process
|
2019-04-08 11:05:15 +02:00
|
|
|
|
|
|
|
if opt.IdleCheckFrequency > 0 {
|
|
|
|
go c.reaper(opt.IdleCheckFrequency)
|
|
|
|
}
|
|
|
|
|
|
|
|
return c
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *ClusterClient) Context() context.Context {
|
2020-09-27 23:09:46 +02:00
|
|
|
return c.ctx
|
2019-04-08 11:05:15 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func (c *ClusterClient) WithContext(ctx context.Context) *ClusterClient {
|
|
|
|
if ctx == nil {
|
|
|
|
panic("nil context")
|
|
|
|
}
|
2020-09-27 23:09:46 +02:00
|
|
|
clone := *c
|
|
|
|
clone.cmdable = clone.Process
|
|
|
|
clone.hooks.lock()
|
|
|
|
clone.ctx = ctx
|
|
|
|
return &clone
|
2019-04-08 11:05:15 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Options returns read-only Options that were used to create the client.
|
|
|
|
func (c *ClusterClient) Options() *ClusterOptions {
|
|
|
|
return c.opt
|
|
|
|
}
|
|
|
|
|
2020-09-27 23:09:46 +02:00
|
|
|
// ReloadState reloads cluster state. If available it calls ClusterSlots func
|
|
|
|
// to get cluster slots information.
|
2021-02-10 22:28:32 +01:00
|
|
|
func (c *ClusterClient) ReloadState(ctx context.Context) {
|
2021-04-23 02:08:53 +02:00
|
|
|
c.state.LazyReload()
|
2019-04-08 11:05:15 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Close closes the cluster client, releasing any open resources.
|
|
|
|
//
|
|
|
|
// It is rare to Close a ClusterClient, as the ClusterClient is meant
|
|
|
|
// to be long-lived and shared between many goroutines.
|
|
|
|
func (c *ClusterClient) Close() error {
|
|
|
|
return c.nodes.Close()
|
|
|
|
}
|
|
|
|
|
|
|
|
// Do creates a Cmd from the args and processes the cmd.
|
2021-02-10 22:28:32 +01:00
|
|
|
func (c *ClusterClient) Do(ctx context.Context, args ...interface{}) *Cmd {
|
|
|
|
cmd := NewCmd(ctx, args...)
|
|
|
|
_ = c.Process(ctx, cmd)
|
2019-04-08 11:05:15 +02:00
|
|
|
return cmd
|
|
|
|
}
|
|
|
|
|
2021-02-10 22:28:32 +01:00
|
|
|
func (c *ClusterClient) Process(ctx context.Context, cmd Cmder) error {
|
2020-09-27 23:09:46 +02:00
|
|
|
return c.hooks.process(ctx, cmd, c.process)
|
2019-04-08 11:05:15 +02:00
|
|
|
}
|
|
|
|
|
2020-09-27 23:09:46 +02:00
|
|
|
func (c *ClusterClient) process(ctx context.Context, cmd Cmder) error {
|
|
|
|
cmdInfo := c.cmdInfo(cmd.Name())
|
|
|
|
slot := c.cmdSlot(cmd)
|
|
|
|
|
2019-04-08 11:05:15 +02:00
|
|
|
var node *clusterNode
|
|
|
|
var ask bool
|
2020-09-27 23:09:46 +02:00
|
|
|
var lastErr error
|
2019-04-08 11:05:15 +02:00
|
|
|
for attempt := 0; attempt <= c.opt.MaxRedirects; attempt++ {
|
|
|
|
if attempt > 0 {
|
2020-09-27 23:09:46 +02:00
|
|
|
if err := internal.Sleep(ctx, c.retryBackoff(attempt)); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2019-04-08 11:05:15 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
if node == nil {
|
|
|
|
var err error
|
2021-02-10 22:28:32 +01:00
|
|
|
node, err = c.cmdNode(ctx, cmdInfo, slot)
|
2019-04-08 11:05:15 +02:00
|
|
|
if err != nil {
|
2020-09-27 23:09:46 +02:00
|
|
|
return err
|
2019-04-08 11:05:15 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if ask {
|
|
|
|
pipe := node.Client.Pipeline()
|
2021-02-10 22:28:32 +01:00
|
|
|
_ = pipe.Process(ctx, NewCmd(ctx, "asking"))
|
|
|
|
_ = pipe.Process(ctx, cmd)
|
|
|
|
_, lastErr = pipe.Exec(ctx)
|
2019-04-08 11:05:15 +02:00
|
|
|
_ = pipe.Close()
|
|
|
|
ask = false
|
|
|
|
} else {
|
2021-02-10 22:28:32 +01:00
|
|
|
lastErr = node.Client.Process(ctx, cmd)
|
2019-04-08 11:05:15 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// If there is no error - we are done.
|
2020-09-27 23:09:46 +02:00
|
|
|
if lastErr == nil {
|
|
|
|
return nil
|
2019-04-08 11:05:15 +02:00
|
|
|
}
|
2021-02-10 22:28:32 +01:00
|
|
|
if isReadOnly := isReadOnlyError(lastErr); isReadOnly || lastErr == pool.ErrClosed {
|
|
|
|
if isReadOnly {
|
2021-04-23 02:08:53 +02:00
|
|
|
c.state.LazyReload()
|
2021-02-10 22:28:32 +01:00
|
|
|
}
|
2020-09-27 23:09:46 +02:00
|
|
|
node = nil
|
|
|
|
continue
|
|
|
|
}
|
2019-04-08 11:05:15 +02:00
|
|
|
|
|
|
|
// If slave is loading - pick another node.
|
2020-09-27 23:09:46 +02:00
|
|
|
if c.opt.ReadOnly && isLoadingError(lastErr) {
|
|
|
|
node.MarkAsFailing()
|
2019-04-08 11:05:15 +02:00
|
|
|
node = nil
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
var moved bool
|
|
|
|
var addr string
|
2020-09-27 23:09:46 +02:00
|
|
|
moved, ask, addr = isMovedError(lastErr)
|
2019-04-08 11:05:15 +02:00
|
|
|
if moved || ask {
|
2020-09-27 23:09:46 +02:00
|
|
|
var err error
|
|
|
|
node, err = c.nodes.Get(addr)
|
2019-04-08 11:05:15 +02:00
|
|
|
if err != nil {
|
2020-09-27 23:09:46 +02:00
|
|
|
return err
|
2019-04-08 11:05:15 +02:00
|
|
|
}
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2021-02-10 22:28:32 +01:00
|
|
|
if shouldRetry(lastErr, cmd.readTimeout() == nil) {
|
2019-04-08 11:05:15 +02:00
|
|
|
// First retry the same node.
|
|
|
|
if attempt == 0 {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2020-09-27 23:09:46 +02:00
|
|
|
// Second try another node.
|
|
|
|
node.MarkAsFailing()
|
|
|
|
node = nil
|
2019-04-08 11:05:15 +02:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2020-09-27 23:09:46 +02:00
|
|
|
return lastErr
|
2019-04-08 11:05:15 +02:00
|
|
|
}
|
2020-09-27 23:09:46 +02:00
|
|
|
return lastErr
|
2019-04-08 11:05:15 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// ForEachMaster concurrently calls the fn on each master node in the cluster.
|
|
|
|
// It returns the first error if any.
|
2021-02-10 22:28:32 +01:00
|
|
|
func (c *ClusterClient) ForEachMaster(
|
|
|
|
ctx context.Context,
|
|
|
|
fn func(ctx context.Context, client *Client) error,
|
|
|
|
) error {
|
|
|
|
state, err := c.state.ReloadOrGet(ctx)
|
2019-04-08 11:05:15 +02:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
var wg sync.WaitGroup
|
|
|
|
errCh := make(chan error, 1)
|
2020-09-27 23:09:46 +02:00
|
|
|
|
2019-04-08 11:05:15 +02:00
|
|
|
for _, master := range state.Masters {
|
|
|
|
wg.Add(1)
|
|
|
|
go func(node *clusterNode) {
|
|
|
|
defer wg.Done()
|
2021-02-10 22:28:32 +01:00
|
|
|
err := fn(ctx, node.Client)
|
2019-04-08 11:05:15 +02:00
|
|
|
if err != nil {
|
|
|
|
select {
|
|
|
|
case errCh <- err:
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}(master)
|
|
|
|
}
|
2020-09-27 23:09:46 +02:00
|
|
|
|
2019-04-08 11:05:15 +02:00
|
|
|
wg.Wait()
|
|
|
|
|
|
|
|
select {
|
|
|
|
case err := <-errCh:
|
|
|
|
return err
|
|
|
|
default:
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// ForEachSlave concurrently calls the fn on each slave node in the cluster.
|
|
|
|
// It returns the first error if any.
|
2021-02-10 22:28:32 +01:00
|
|
|
func (c *ClusterClient) ForEachSlave(
|
|
|
|
ctx context.Context,
|
|
|
|
fn func(ctx context.Context, client *Client) error,
|
|
|
|
) error {
|
|
|
|
state, err := c.state.ReloadOrGet(ctx)
|
2019-04-08 11:05:15 +02:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
var wg sync.WaitGroup
|
|
|
|
errCh := make(chan error, 1)
|
2020-09-27 23:09:46 +02:00
|
|
|
|
2019-04-08 11:05:15 +02:00
|
|
|
for _, slave := range state.Slaves {
|
|
|
|
wg.Add(1)
|
|
|
|
go func(node *clusterNode) {
|
|
|
|
defer wg.Done()
|
2021-02-10 22:28:32 +01:00
|
|
|
err := fn(ctx, node.Client)
|
2019-04-08 11:05:15 +02:00
|
|
|
if err != nil {
|
|
|
|
select {
|
|
|
|
case errCh <- err:
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}(slave)
|
|
|
|
}
|
2020-09-27 23:09:46 +02:00
|
|
|
|
2019-04-08 11:05:15 +02:00
|
|
|
wg.Wait()
|
|
|
|
|
|
|
|
select {
|
|
|
|
case err := <-errCh:
|
|
|
|
return err
|
|
|
|
default:
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-10 22:28:32 +01:00
|
|
|
// ForEachShard concurrently calls the fn on each known node in the cluster.
|
2019-04-08 11:05:15 +02:00
|
|
|
// It returns the first error if any.
|
2021-02-10 22:28:32 +01:00
|
|
|
func (c *ClusterClient) ForEachShard(
|
|
|
|
ctx context.Context,
|
|
|
|
fn func(ctx context.Context, client *Client) error,
|
|
|
|
) error {
|
|
|
|
state, err := c.state.ReloadOrGet(ctx)
|
2019-04-08 11:05:15 +02:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
var wg sync.WaitGroup
|
|
|
|
errCh := make(chan error, 1)
|
2020-09-27 23:09:46 +02:00
|
|
|
|
2019-04-08 11:05:15 +02:00
|
|
|
worker := func(node *clusterNode) {
|
|
|
|
defer wg.Done()
|
2021-02-10 22:28:32 +01:00
|
|
|
err := fn(ctx, node.Client)
|
2019-04-08 11:05:15 +02:00
|
|
|
if err != nil {
|
|
|
|
select {
|
|
|
|
case errCh <- err:
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, node := range state.Masters {
|
|
|
|
wg.Add(1)
|
|
|
|
go worker(node)
|
|
|
|
}
|
|
|
|
for _, node := range state.Slaves {
|
|
|
|
wg.Add(1)
|
|
|
|
go worker(node)
|
|
|
|
}
|
|
|
|
|
|
|
|
wg.Wait()
|
2020-09-27 23:09:46 +02:00
|
|
|
|
2019-04-08 11:05:15 +02:00
|
|
|
select {
|
|
|
|
case err := <-errCh:
|
|
|
|
return err
|
|
|
|
default:
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// PoolStats returns accumulated connection pool stats.
|
|
|
|
func (c *ClusterClient) PoolStats() *PoolStats {
|
|
|
|
var acc PoolStats
|
|
|
|
|
2021-02-10 22:28:32 +01:00
|
|
|
state, _ := c.state.Get(context.TODO())
|
2019-04-08 11:05:15 +02:00
|
|
|
if state == nil {
|
|
|
|
return &acc
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, node := range state.Masters {
|
|
|
|
s := node.Client.connPool.Stats()
|
|
|
|
acc.Hits += s.Hits
|
|
|
|
acc.Misses += s.Misses
|
|
|
|
acc.Timeouts += s.Timeouts
|
|
|
|
|
|
|
|
acc.TotalConns += s.TotalConns
|
|
|
|
acc.IdleConns += s.IdleConns
|
|
|
|
acc.StaleConns += s.StaleConns
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, node := range state.Slaves {
|
|
|
|
s := node.Client.connPool.Stats()
|
|
|
|
acc.Hits += s.Hits
|
|
|
|
acc.Misses += s.Misses
|
|
|
|
acc.Timeouts += s.Timeouts
|
|
|
|
|
|
|
|
acc.TotalConns += s.TotalConns
|
|
|
|
acc.IdleConns += s.IdleConns
|
|
|
|
acc.StaleConns += s.StaleConns
|
|
|
|
}
|
|
|
|
|
|
|
|
return &acc
|
|
|
|
}
|
|
|
|
|
2021-02-10 22:28:32 +01:00
|
|
|
func (c *ClusterClient) loadState(ctx context.Context) (*clusterState, error) {
|
2019-04-08 11:05:15 +02:00
|
|
|
if c.opt.ClusterSlots != nil {
|
2021-02-10 22:28:32 +01:00
|
|
|
slots, err := c.opt.ClusterSlots(ctx)
|
2019-04-08 11:05:15 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return newClusterState(c.nodes, slots, "")
|
|
|
|
}
|
|
|
|
|
|
|
|
addrs, err := c.nodes.Addrs()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
var firstErr error
|
2021-02-10 22:28:32 +01:00
|
|
|
|
|
|
|
for _, idx := range rand.Perm(len(addrs)) {
|
|
|
|
addr := addrs[idx]
|
|
|
|
|
2020-09-27 23:09:46 +02:00
|
|
|
node, err := c.nodes.Get(addr)
|
2019-04-08 11:05:15 +02:00
|
|
|
if err != nil {
|
|
|
|
if firstErr == nil {
|
|
|
|
firstErr = err
|
|
|
|
}
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2021-02-10 22:28:32 +01:00
|
|
|
slots, err := node.Client.ClusterSlots(ctx).Result()
|
2019-04-08 11:05:15 +02:00
|
|
|
if err != nil {
|
|
|
|
if firstErr == nil {
|
|
|
|
firstErr = err
|
|
|
|
}
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
return newClusterState(c.nodes, slots, node.Client.opt.Addr)
|
|
|
|
}
|
|
|
|
|
2021-02-10 22:28:32 +01:00
|
|
|
/*
|
|
|
|
* No node is connectable. It's possible that all nodes' IP has changed.
|
|
|
|
* Clear activeAddrs to let client be able to re-connect using the initial
|
|
|
|
* setting of the addresses (e.g. [redis-cluster-0:6379, redis-cluster-1:6379]),
|
|
|
|
* which might have chance to resolve domain name and get updated IP address.
|
|
|
|
*/
|
|
|
|
c.nodes.mu.Lock()
|
|
|
|
c.nodes.activeAddrs = nil
|
|
|
|
c.nodes.mu.Unlock()
|
|
|
|
|
2019-04-08 11:05:15 +02:00
|
|
|
return nil, firstErr
|
|
|
|
}
|
|
|
|
|
|
|
|
// reaper closes idle connections to the cluster.
|
|
|
|
func (c *ClusterClient) reaper(idleCheckFrequency time.Duration) {
|
|
|
|
ticker := time.NewTicker(idleCheckFrequency)
|
|
|
|
defer ticker.Stop()
|
|
|
|
|
|
|
|
for range ticker.C {
|
|
|
|
nodes, err := c.nodes.All()
|
|
|
|
if err != nil {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, node := range nodes {
|
|
|
|
_, err := node.Client.connPool.(*pool.ConnPool).ReapStaleConns()
|
|
|
|
if err != nil {
|
2021-02-10 22:28:32 +01:00
|
|
|
internal.Logger.Printf(c.Context(), "ReapStaleConns failed: %s", err)
|
2019-04-08 11:05:15 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *ClusterClient) Pipeline() Pipeliner {
|
|
|
|
pipe := Pipeline{
|
2020-09-27 23:09:46 +02:00
|
|
|
ctx: c.ctx,
|
2019-04-08 11:05:15 +02:00
|
|
|
exec: c.processPipeline,
|
|
|
|
}
|
2020-09-27 23:09:46 +02:00
|
|
|
pipe.init()
|
2019-04-08 11:05:15 +02:00
|
|
|
return &pipe
|
|
|
|
}
|
|
|
|
|
2021-02-10 22:28:32 +01:00
|
|
|
func (c *ClusterClient) Pipelined(ctx context.Context, fn func(Pipeliner) error) ([]Cmder, error) {
|
|
|
|
return c.Pipeline().Pipelined(ctx, fn)
|
2019-04-08 11:05:15 +02:00
|
|
|
}
|
|
|
|
|
2020-09-27 23:09:46 +02:00
|
|
|
func (c *ClusterClient) processPipeline(ctx context.Context, cmds []Cmder) error {
|
|
|
|
return c.hooks.processPipeline(ctx, cmds, c._processPipeline)
|
2019-04-08 11:05:15 +02:00
|
|
|
}
|
|
|
|
|
2020-09-27 23:09:46 +02:00
|
|
|
func (c *ClusterClient) _processPipeline(ctx context.Context, cmds []Cmder) error {
|
2019-04-08 11:05:15 +02:00
|
|
|
cmdsMap := newCmdsMap()
|
2021-02-10 22:28:32 +01:00
|
|
|
err := c.mapCmdsByNode(ctx, cmdsMap, cmds)
|
2019-04-08 11:05:15 +02:00
|
|
|
if err != nil {
|
|
|
|
setCmdsErr(cmds, err)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
for attempt := 0; attempt <= c.opt.MaxRedirects; attempt++ {
|
|
|
|
if attempt > 0 {
|
2020-09-27 23:09:46 +02:00
|
|
|
if err := internal.Sleep(ctx, c.retryBackoff(attempt)); err != nil {
|
|
|
|
setCmdsErr(cmds, err)
|
|
|
|
return err
|
|
|
|
}
|
2019-04-08 11:05:15 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
failedCmds := newCmdsMap()
|
|
|
|
var wg sync.WaitGroup
|
|
|
|
|
|
|
|
for node, cmds := range cmdsMap.m {
|
|
|
|
wg.Add(1)
|
|
|
|
go func(node *clusterNode, cmds []Cmder) {
|
|
|
|
defer wg.Done()
|
|
|
|
|
2020-09-27 23:09:46 +02:00
|
|
|
err := c._processPipelineNode(ctx, node, cmds, failedCmds)
|
|
|
|
if err == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if attempt < c.opt.MaxRedirects {
|
2021-02-10 22:28:32 +01:00
|
|
|
if err := c.mapCmdsByNode(ctx, failedCmds, cmds); err != nil {
|
2019-04-08 11:05:15 +02:00
|
|
|
setCmdsErr(cmds, err)
|
|
|
|
}
|
2020-09-27 23:09:46 +02:00
|
|
|
} else {
|
|
|
|
setCmdsErr(cmds, err)
|
2019-04-08 11:05:15 +02:00
|
|
|
}
|
|
|
|
}(node, cmds)
|
|
|
|
}
|
|
|
|
|
|
|
|
wg.Wait()
|
|
|
|
if len(failedCmds.m) == 0 {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
cmdsMap = failedCmds
|
|
|
|
}
|
|
|
|
|
|
|
|
return cmdsFirstErr(cmds)
|
|
|
|
}
|
|
|
|
|
2021-02-10 22:28:32 +01:00
|
|
|
func (c *ClusterClient) mapCmdsByNode(ctx context.Context, cmdsMap *cmdsMap, cmds []Cmder) error {
|
|
|
|
state, err := c.state.Get(ctx)
|
2020-09-27 23:09:46 +02:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2019-04-08 11:05:15 +02:00
|
|
|
|
2020-09-27 23:09:46 +02:00
|
|
|
if c.opt.ReadOnly && c.cmdsAreReadOnly(cmds) {
|
|
|
|
for _, cmd := range cmds {
|
|
|
|
slot := c.cmdSlot(cmd)
|
|
|
|
node, err := c.slotReadOnlyNode(state, slot)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
cmdsMap.Add(node, cmd)
|
|
|
|
}
|
|
|
|
return nil
|
2019-04-08 11:05:15 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
for _, cmd := range cmds {
|
2020-09-27 23:09:46 +02:00
|
|
|
slot := c.cmdSlot(cmd)
|
|
|
|
node, err := state.slotMasterNode(slot)
|
2019-04-08 11:05:15 +02:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2020-09-27 23:09:46 +02:00
|
|
|
cmdsMap.Add(node, cmd)
|
2019-04-08 11:05:15 +02:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *ClusterClient) cmdsAreReadOnly(cmds []Cmder) bool {
|
|
|
|
for _, cmd := range cmds {
|
|
|
|
cmdInfo := c.cmdInfo(cmd.Name())
|
|
|
|
if cmdInfo == nil || !cmdInfo.ReadOnly {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2020-09-27 23:09:46 +02:00
|
|
|
func (c *ClusterClient) _processPipelineNode(
|
|
|
|
ctx context.Context, node *clusterNode, cmds []Cmder, failedCmds *cmdsMap,
|
2019-04-08 11:05:15 +02:00
|
|
|
) error {
|
2020-09-27 23:09:46 +02:00
|
|
|
return node.Client.hooks.processPipeline(ctx, cmds, func(ctx context.Context, cmds []Cmder) error {
|
|
|
|
return node.Client.withConn(ctx, func(ctx context.Context, cn *pool.Conn) error {
|
|
|
|
err := cn.WithWriter(ctx, c.opt.WriteTimeout, func(wr *proto.Writer) error {
|
|
|
|
return writeCmds(wr, cmds)
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2019-04-08 11:05:15 +02:00
|
|
|
|
2020-09-27 23:09:46 +02:00
|
|
|
return cn.WithReader(ctx, c.opt.ReadTimeout, func(rd *proto.Reader) error {
|
2021-02-10 22:28:32 +01:00
|
|
|
return c.pipelineReadCmds(ctx, node, rd, cmds, failedCmds)
|
2020-09-27 23:09:46 +02:00
|
|
|
})
|
|
|
|
})
|
2019-04-08 11:05:15 +02:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *ClusterClient) pipelineReadCmds(
|
2021-02-10 22:28:32 +01:00
|
|
|
ctx context.Context,
|
|
|
|
node *clusterNode,
|
|
|
|
rd *proto.Reader,
|
|
|
|
cmds []Cmder,
|
|
|
|
failedCmds *cmdsMap,
|
2019-04-08 11:05:15 +02:00
|
|
|
) error {
|
|
|
|
for _, cmd := range cmds {
|
|
|
|
err := cmd.readReply(rd)
|
2021-02-10 22:28:32 +01:00
|
|
|
cmd.SetErr(err)
|
|
|
|
|
2019-04-08 11:05:15 +02:00
|
|
|
if err == nil {
|
|
|
|
continue
|
|
|
|
}
|
2021-02-10 22:28:32 +01:00
|
|
|
|
|
|
|
if c.checkMovedErr(ctx, cmd, err, failedCmds) {
|
2019-04-08 11:05:15 +02:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2020-09-27 23:09:46 +02:00
|
|
|
if c.opt.ReadOnly && isLoadingError(err) {
|
|
|
|
node.MarkAsFailing()
|
|
|
|
return err
|
2019-04-08 11:05:15 +02:00
|
|
|
}
|
2020-09-27 23:09:46 +02:00
|
|
|
if isRedisError(err) {
|
|
|
|
continue
|
2019-04-08 11:05:15 +02:00
|
|
|
}
|
2020-09-27 23:09:46 +02:00
|
|
|
return err
|
2019-04-08 11:05:15 +02:00
|
|
|
}
|
2020-09-27 23:09:46 +02:00
|
|
|
return nil
|
2019-04-08 11:05:15 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func (c *ClusterClient) checkMovedErr(
|
2021-02-10 22:28:32 +01:00
|
|
|
ctx context.Context, cmd Cmder, err error, failedCmds *cmdsMap,
|
2019-04-08 11:05:15 +02:00
|
|
|
) bool {
|
2020-09-27 23:09:46 +02:00
|
|
|
moved, ask, addr := isMovedError(err)
|
|
|
|
if !moved && !ask {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
node, err := c.nodes.Get(addr)
|
|
|
|
if err != nil {
|
|
|
|
return false
|
|
|
|
}
|
2019-04-08 11:05:15 +02:00
|
|
|
|
|
|
|
if moved {
|
2021-04-23 02:08:53 +02:00
|
|
|
c.state.LazyReload()
|
2020-09-27 23:09:46 +02:00
|
|
|
failedCmds.Add(node, cmd)
|
2019-04-08 11:05:15 +02:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
if ask {
|
2021-02-10 22:28:32 +01:00
|
|
|
failedCmds.Add(node, NewCmd(ctx, "asking"), cmd)
|
2019-04-08 11:05:15 +02:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2020-09-27 23:09:46 +02:00
|
|
|
panic("not reached")
|
2019-04-08 11:05:15 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// TxPipeline acts like Pipeline, but wraps queued commands with MULTI/EXEC.
|
|
|
|
func (c *ClusterClient) TxPipeline() Pipeliner {
|
|
|
|
pipe := Pipeline{
|
2020-09-27 23:09:46 +02:00
|
|
|
ctx: c.ctx,
|
2019-04-08 11:05:15 +02:00
|
|
|
exec: c.processTxPipeline,
|
|
|
|
}
|
2020-09-27 23:09:46 +02:00
|
|
|
pipe.init()
|
2019-04-08 11:05:15 +02:00
|
|
|
return &pipe
|
|
|
|
}
|
|
|
|
|
2021-02-10 22:28:32 +01:00
|
|
|
func (c *ClusterClient) TxPipelined(ctx context.Context, fn func(Pipeliner) error) ([]Cmder, error) {
|
|
|
|
return c.TxPipeline().Pipelined(ctx, fn)
|
2019-04-08 11:05:15 +02:00
|
|
|
}
|
|
|
|
|
2020-09-27 23:09:46 +02:00
|
|
|
func (c *ClusterClient) processTxPipeline(ctx context.Context, cmds []Cmder) error {
|
2021-02-10 22:28:32 +01:00
|
|
|
return c.hooks.processTxPipeline(ctx, cmds, c._processTxPipeline)
|
2020-09-27 23:09:46 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func (c *ClusterClient) _processTxPipeline(ctx context.Context, cmds []Cmder) error {
|
2021-02-10 22:28:32 +01:00
|
|
|
// Trim multi .. exec.
|
|
|
|
cmds = cmds[1 : len(cmds)-1]
|
|
|
|
|
|
|
|
state, err := c.state.Get(ctx)
|
2019-04-08 11:05:15 +02:00
|
|
|
if err != nil {
|
2020-09-27 23:09:46 +02:00
|
|
|
setCmdsErr(cmds, err)
|
2019-04-08 11:05:15 +02:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
cmdsMap := c.mapCmdsBySlot(cmds)
|
|
|
|
for slot, cmds := range cmdsMap {
|
|
|
|
node, err := state.slotMasterNode(slot)
|
|
|
|
if err != nil {
|
|
|
|
setCmdsErr(cmds, err)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2020-09-27 23:09:46 +02:00
|
|
|
cmdsMap := map[*clusterNode][]Cmder{node: cmds}
|
2019-04-08 11:05:15 +02:00
|
|
|
for attempt := 0; attempt <= c.opt.MaxRedirects; attempt++ {
|
|
|
|
if attempt > 0 {
|
2020-09-27 23:09:46 +02:00
|
|
|
if err := internal.Sleep(ctx, c.retryBackoff(attempt)); err != nil {
|
|
|
|
setCmdsErr(cmds, err)
|
|
|
|
return err
|
|
|
|
}
|
2019-04-08 11:05:15 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
failedCmds := newCmdsMap()
|
|
|
|
var wg sync.WaitGroup
|
|
|
|
|
|
|
|
for node, cmds := range cmdsMap {
|
|
|
|
wg.Add(1)
|
|
|
|
go func(node *clusterNode, cmds []Cmder) {
|
|
|
|
defer wg.Done()
|
|
|
|
|
2020-09-27 23:09:46 +02:00
|
|
|
err := c._processTxPipelineNode(ctx, node, cmds, failedCmds)
|
|
|
|
if err == nil {
|
|
|
|
return
|
|
|
|
}
|
2021-02-10 22:28:32 +01:00
|
|
|
|
2020-09-27 23:09:46 +02:00
|
|
|
if attempt < c.opt.MaxRedirects {
|
2021-02-10 22:28:32 +01:00
|
|
|
if err := c.mapCmdsByNode(ctx, failedCmds, cmds); err != nil {
|
2019-04-08 11:05:15 +02:00
|
|
|
setCmdsErr(cmds, err)
|
|
|
|
}
|
2020-09-27 23:09:46 +02:00
|
|
|
} else {
|
|
|
|
setCmdsErr(cmds, err)
|
2019-04-08 11:05:15 +02:00
|
|
|
}
|
|
|
|
}(node, cmds)
|
|
|
|
}
|
|
|
|
|
|
|
|
wg.Wait()
|
|
|
|
if len(failedCmds.m) == 0 {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
cmdsMap = failedCmds.m
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return cmdsFirstErr(cmds)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *ClusterClient) mapCmdsBySlot(cmds []Cmder) map[int][]Cmder {
|
|
|
|
cmdsMap := make(map[int][]Cmder)
|
|
|
|
for _, cmd := range cmds {
|
|
|
|
slot := c.cmdSlot(cmd)
|
|
|
|
cmdsMap[slot] = append(cmdsMap[slot], cmd)
|
|
|
|
}
|
|
|
|
return cmdsMap
|
|
|
|
}
|
|
|
|
|
2020-09-27 23:09:46 +02:00
|
|
|
func (c *ClusterClient) _processTxPipelineNode(
|
|
|
|
ctx context.Context, node *clusterNode, cmds []Cmder, failedCmds *cmdsMap,
|
2019-04-08 11:05:15 +02:00
|
|
|
) error {
|
2020-09-27 23:09:46 +02:00
|
|
|
return node.Client.hooks.processTxPipeline(ctx, cmds, func(ctx context.Context, cmds []Cmder) error {
|
|
|
|
return node.Client.withConn(ctx, func(ctx context.Context, cn *pool.Conn) error {
|
|
|
|
err := cn.WithWriter(ctx, c.opt.WriteTimeout, func(wr *proto.Writer) error {
|
|
|
|
return writeCmds(wr, cmds)
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2019-04-08 11:05:15 +02:00
|
|
|
|
2020-09-27 23:09:46 +02:00
|
|
|
return cn.WithReader(ctx, c.opt.ReadTimeout, func(rd *proto.Reader) error {
|
|
|
|
statusCmd := cmds[0].(*StatusCmd)
|
|
|
|
// Trim multi and exec.
|
|
|
|
cmds = cmds[1 : len(cmds)-1]
|
|
|
|
|
2021-02-10 22:28:32 +01:00
|
|
|
err := c.txPipelineReadQueued(ctx, rd, statusCmd, cmds, failedCmds)
|
2020-09-27 23:09:46 +02:00
|
|
|
if err != nil {
|
|
|
|
moved, ask, addr := isMovedError(err)
|
|
|
|
if moved || ask {
|
2021-02-10 22:28:32 +01:00
|
|
|
return c.cmdsMoved(ctx, cmds, moved, ask, addr, failedCmds)
|
2020-09-27 23:09:46 +02:00
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return pipelineReadCmds(rd, cmds)
|
|
|
|
})
|
|
|
|
})
|
2019-04-08 11:05:15 +02:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *ClusterClient) txPipelineReadQueued(
|
2021-02-10 22:28:32 +01:00
|
|
|
ctx context.Context,
|
|
|
|
rd *proto.Reader,
|
|
|
|
statusCmd *StatusCmd,
|
|
|
|
cmds []Cmder,
|
|
|
|
failedCmds *cmdsMap,
|
2019-04-08 11:05:15 +02:00
|
|
|
) error {
|
|
|
|
// Parse queued replies.
|
|
|
|
if err := statusCmd.readReply(rd); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, cmd := range cmds {
|
|
|
|
err := statusCmd.readReply(rd)
|
2021-02-10 22:28:32 +01:00
|
|
|
if err == nil || c.checkMovedErr(ctx, cmd, err, failedCmds) || isRedisError(err) {
|
2019-04-08 11:05:15 +02:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Parse number of replies.
|
|
|
|
line, err := rd.ReadLine()
|
|
|
|
if err != nil {
|
|
|
|
if err == Nil {
|
|
|
|
err = TxFailedErr
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
switch line[0] {
|
|
|
|
case proto.ErrorReply:
|
2020-09-27 23:09:46 +02:00
|
|
|
return proto.ParseErrorReply(line)
|
2019-04-08 11:05:15 +02:00
|
|
|
case proto.ArrayReply:
|
|
|
|
// ok
|
|
|
|
default:
|
2020-09-27 23:09:46 +02:00
|
|
|
return fmt.Errorf("redis: expected '*', but got line %q", line)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *ClusterClient) cmdsMoved(
|
2021-02-10 22:28:32 +01:00
|
|
|
ctx context.Context, cmds []Cmder,
|
|
|
|
moved, ask bool,
|
|
|
|
addr string,
|
|
|
|
failedCmds *cmdsMap,
|
2020-09-27 23:09:46 +02:00
|
|
|
) error {
|
|
|
|
node, err := c.nodes.Get(addr)
|
|
|
|
if err != nil {
|
2019-04-08 11:05:15 +02:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2020-09-27 23:09:46 +02:00
|
|
|
if moved {
|
2021-04-23 02:08:53 +02:00
|
|
|
c.state.LazyReload()
|
2020-09-27 23:09:46 +02:00
|
|
|
for _, cmd := range cmds {
|
|
|
|
failedCmds.Add(node, cmd)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
if ask {
|
|
|
|
for _, cmd := range cmds {
|
2021-02-10 22:28:32 +01:00
|
|
|
failedCmds.Add(node, NewCmd(ctx, "asking"), cmd)
|
2020-09-27 23:09:46 +02:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-04-08 11:05:15 +02:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-02-10 22:28:32 +01:00
|
|
|
func (c *ClusterClient) Watch(ctx context.Context, fn func(*Tx) error, keys ...string) error {
|
2020-09-27 23:09:46 +02:00
|
|
|
if len(keys) == 0 {
|
|
|
|
return fmt.Errorf("redis: Watch requires at least one key")
|
|
|
|
}
|
|
|
|
|
|
|
|
slot := hashtag.Slot(keys[0])
|
|
|
|
for _, key := range keys[1:] {
|
|
|
|
if hashtag.Slot(key) != slot {
|
|
|
|
err := fmt.Errorf("redis: Watch requires all keys to be in the same slot")
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-10 22:28:32 +01:00
|
|
|
node, err := c.slotMasterNode(ctx, slot)
|
2020-09-27 23:09:46 +02:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
for attempt := 0; attempt <= c.opt.MaxRedirects; attempt++ {
|
|
|
|
if attempt > 0 {
|
|
|
|
if err := internal.Sleep(ctx, c.retryBackoff(attempt)); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-10 22:28:32 +01:00
|
|
|
err = node.Client.Watch(ctx, fn, keys...)
|
2020-09-27 23:09:46 +02:00
|
|
|
if err == nil {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
|
|
|
|
moved, ask, addr := isMovedError(err)
|
|
|
|
if moved || ask {
|
|
|
|
node, err = c.nodes.Get(addr)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2021-02-10 22:28:32 +01:00
|
|
|
if isReadOnly := isReadOnlyError(err); isReadOnly || err == pool.ErrClosed {
|
|
|
|
if isReadOnly {
|
2021-04-23 02:08:53 +02:00
|
|
|
c.state.LazyReload()
|
2021-02-10 22:28:32 +01:00
|
|
|
}
|
|
|
|
node, err = c.slotMasterNode(ctx, slot)
|
2020-09-27 23:09:46 +02:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2021-02-10 22:28:32 +01:00
|
|
|
if shouldRetry(err, true) {
|
2020-09-27 23:09:46 +02:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2019-04-08 11:05:15 +02:00
|
|
|
func (c *ClusterClient) pubSub() *PubSub {
|
|
|
|
var node *clusterNode
|
|
|
|
pubsub := &PubSub{
|
|
|
|
opt: c.opt.clientOptions(),
|
|
|
|
|
2021-02-10 22:28:32 +01:00
|
|
|
newConn: func(ctx context.Context, channels []string) (*pool.Conn, error) {
|
2019-04-08 11:05:15 +02:00
|
|
|
if node != nil {
|
|
|
|
panic("node != nil")
|
|
|
|
}
|
|
|
|
|
|
|
|
var err error
|
2020-09-27 23:09:46 +02:00
|
|
|
if len(channels) > 0 {
|
|
|
|
slot := hashtag.Slot(channels[0])
|
2021-02-10 22:28:32 +01:00
|
|
|
node, err = c.slotMasterNode(ctx, slot)
|
2020-09-27 23:09:46 +02:00
|
|
|
} else {
|
|
|
|
node, err = c.nodes.Random()
|
|
|
|
}
|
2019-04-08 11:05:15 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2020-09-27 23:09:46 +02:00
|
|
|
cn, err := node.Client.newConn(context.TODO())
|
2019-04-08 11:05:15 +02:00
|
|
|
if err != nil {
|
2020-09-27 23:09:46 +02:00
|
|
|
node = nil
|
|
|
|
|
2019-04-08 11:05:15 +02:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return cn, nil
|
|
|
|
},
|
|
|
|
closeConn: func(cn *pool.Conn) error {
|
|
|
|
err := node.Client.connPool.CloseConn(cn)
|
|
|
|
node = nil
|
|
|
|
return err
|
|
|
|
},
|
|
|
|
}
|
|
|
|
pubsub.init()
|
|
|
|
|
|
|
|
return pubsub
|
|
|
|
}
|
|
|
|
|
|
|
|
// Subscribe subscribes the client to the specified channels.
|
|
|
|
// Channels can be omitted to create empty subscription.
|
2021-02-10 22:28:32 +01:00
|
|
|
func (c *ClusterClient) Subscribe(ctx context.Context, channels ...string) *PubSub {
|
2019-04-08 11:05:15 +02:00
|
|
|
pubsub := c.pubSub()
|
|
|
|
if len(channels) > 0 {
|
2021-02-10 22:28:32 +01:00
|
|
|
_ = pubsub.Subscribe(ctx, channels...)
|
2019-04-08 11:05:15 +02:00
|
|
|
}
|
|
|
|
return pubsub
|
|
|
|
}
|
|
|
|
|
|
|
|
// PSubscribe subscribes the client to the given patterns.
|
|
|
|
// Patterns can be omitted to create empty subscription.
|
2021-02-10 22:28:32 +01:00
|
|
|
func (c *ClusterClient) PSubscribe(ctx context.Context, channels ...string) *PubSub {
|
2019-04-08 11:05:15 +02:00
|
|
|
pubsub := c.pubSub()
|
|
|
|
if len(channels) > 0 {
|
2021-02-10 22:28:32 +01:00
|
|
|
_ = pubsub.PSubscribe(ctx, channels...)
|
2019-04-08 11:05:15 +02:00
|
|
|
}
|
|
|
|
return pubsub
|
|
|
|
}
|
|
|
|
|
2020-09-27 23:09:46 +02:00
|
|
|
func (c *ClusterClient) retryBackoff(attempt int) time.Duration {
|
|
|
|
return internal.RetryBackoff(attempt, c.opt.MinRetryBackoff, c.opt.MaxRetryBackoff)
|
|
|
|
}
|
|
|
|
|
2021-02-10 22:28:32 +01:00
|
|
|
func (c *ClusterClient) cmdsInfo(ctx context.Context) (map[string]*CommandInfo, error) {
|
|
|
|
// Try 3 random nodes.
|
|
|
|
const nodeLimit = 3
|
|
|
|
|
2020-09-27 23:09:46 +02:00
|
|
|
addrs, err := c.nodes.Addrs()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
var firstErr error
|
2021-02-10 22:28:32 +01:00
|
|
|
|
|
|
|
perm := rand.Perm(len(addrs))
|
|
|
|
if len(perm) > nodeLimit {
|
|
|
|
perm = perm[:nodeLimit]
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, idx := range perm {
|
|
|
|
addr := addrs[idx]
|
|
|
|
|
2020-09-27 23:09:46 +02:00
|
|
|
node, err := c.nodes.Get(addr)
|
|
|
|
if err != nil {
|
2021-02-10 22:28:32 +01:00
|
|
|
if firstErr == nil {
|
|
|
|
firstErr = err
|
|
|
|
}
|
2020-09-27 23:09:46 +02:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2021-02-10 22:28:32 +01:00
|
|
|
info, err := node.Client.Command(ctx).Result()
|
2020-09-27 23:09:46 +02:00
|
|
|
if err == nil {
|
|
|
|
return info, nil
|
|
|
|
}
|
|
|
|
if firstErr == nil {
|
|
|
|
firstErr = err
|
|
|
|
}
|
|
|
|
}
|
2021-02-10 22:28:32 +01:00
|
|
|
|
|
|
|
if firstErr == nil {
|
|
|
|
panic("not reached")
|
|
|
|
}
|
2020-09-27 23:09:46 +02:00
|
|
|
return nil, firstErr
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *ClusterClient) cmdInfo(name string) *CommandInfo {
|
2021-02-10 22:28:32 +01:00
|
|
|
cmdsInfo, err := c.cmdsInfoCache.Get(c.ctx)
|
2020-09-27 23:09:46 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
info := cmdsInfo[name]
|
|
|
|
if info == nil {
|
2021-02-10 22:28:32 +01:00
|
|
|
internal.Logger.Printf(c.Context(), "info for cmd=%s not found", name)
|
2020-09-27 23:09:46 +02:00
|
|
|
}
|
|
|
|
return info
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *ClusterClient) cmdSlot(cmd Cmder) int {
|
|
|
|
args := cmd.Args()
|
|
|
|
if args[0] == "cluster" && args[1] == "getkeysinslot" {
|
|
|
|
return args[2].(int)
|
|
|
|
}
|
|
|
|
|
|
|
|
cmdInfo := c.cmdInfo(cmd.Name())
|
|
|
|
return cmdSlot(cmd, cmdFirstKeyPos(cmd, cmdInfo))
|
|
|
|
}
|
|
|
|
|
|
|
|
func cmdSlot(cmd Cmder, pos int) int {
|
|
|
|
if pos == 0 {
|
|
|
|
return hashtag.RandomSlot()
|
|
|
|
}
|
|
|
|
firstKey := cmd.stringArg(pos)
|
|
|
|
return hashtag.Slot(firstKey)
|
|
|
|
}
|
|
|
|
|
2021-02-10 22:28:32 +01:00
|
|
|
func (c *ClusterClient) cmdNode(
|
|
|
|
ctx context.Context,
|
|
|
|
cmdInfo *CommandInfo,
|
|
|
|
slot int,
|
|
|
|
) (*clusterNode, error) {
|
|
|
|
state, err := c.state.Get(ctx)
|
2020-09-27 23:09:46 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if c.opt.ReadOnly && cmdInfo != nil && cmdInfo.ReadOnly {
|
|
|
|
return c.slotReadOnlyNode(state, slot)
|
|
|
|
}
|
|
|
|
return state.slotMasterNode(slot)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *clusterClient) slotReadOnlyNode(state *clusterState, slot int) (*clusterNode, error) {
|
|
|
|
if c.opt.RouteByLatency {
|
|
|
|
return state.slotClosestNode(slot)
|
|
|
|
}
|
|
|
|
if c.opt.RouteRandomly {
|
|
|
|
return state.slotRandomNode(slot)
|
|
|
|
}
|
|
|
|
return state.slotSlaveNode(slot)
|
|
|
|
}
|
|
|
|
|
2021-02-10 22:28:32 +01:00
|
|
|
func (c *ClusterClient) slotMasterNode(ctx context.Context, slot int) (*clusterNode, error) {
|
|
|
|
state, err := c.state.Get(ctx)
|
2020-09-27 23:09:46 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return state.slotMasterNode(slot)
|
|
|
|
}
|
|
|
|
|
2021-02-10 22:28:32 +01:00
|
|
|
// SlaveForKey gets a client for a replica node to run any command on it.
|
|
|
|
// This is especially useful if we want to run a particular lua script which has
|
|
|
|
// only read only commands on the replica.
|
|
|
|
// This is because other redis commands generally have a flag that points that
|
|
|
|
// they are read only and automatically run on the replica nodes
|
|
|
|
// if ClusterOptions.ReadOnly flag is set to true.
|
|
|
|
func (c *ClusterClient) SlaveForKey(ctx context.Context, key string) (*Client, error) {
|
|
|
|
state, err := c.state.Get(ctx)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
slot := hashtag.Slot(key)
|
|
|
|
node, err := c.slotReadOnlyNode(state, slot)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return node.Client, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// MasterForKey return a client to the master node for a particular key.
|
|
|
|
func (c *ClusterClient) MasterForKey(ctx context.Context, key string) (*Client, error) {
|
|
|
|
slot := hashtag.Slot(key)
|
|
|
|
node, err := c.slotMasterNode(ctx, slot)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return node.Client, err
|
|
|
|
}
|
|
|
|
|
2019-04-08 11:05:15 +02:00
|
|
|
func appendUniqueNode(nodes []*clusterNode, node *clusterNode) []*clusterNode {
|
|
|
|
for _, n := range nodes {
|
|
|
|
if n == node {
|
|
|
|
return nodes
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return append(nodes, node)
|
|
|
|
}
|
|
|
|
|
|
|
|
func appendIfNotExists(ss []string, es ...string) []string {
|
|
|
|
loop:
|
|
|
|
for _, e := range es {
|
|
|
|
for _, s := range ss {
|
|
|
|
if s == e {
|
|
|
|
continue loop
|
|
|
|
}
|
|
|
|
}
|
|
|
|
ss = append(ss, e)
|
|
|
|
}
|
|
|
|
return ss
|
|
|
|
}
|
|
|
|
|
2020-09-27 23:09:46 +02:00
|
|
|
//------------------------------------------------------------------------------
|
|
|
|
|
|
|
|
type cmdsMap struct {
|
|
|
|
mu sync.Mutex
|
|
|
|
m map[*clusterNode][]Cmder
|
|
|
|
}
|
|
|
|
|
|
|
|
func newCmdsMap() *cmdsMap {
|
|
|
|
return &cmdsMap{
|
|
|
|
m: make(map[*clusterNode][]Cmder),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *cmdsMap) Add(node *clusterNode, cmds ...Cmder) {
|
|
|
|
m.mu.Lock()
|
|
|
|
m.m[node] = append(m.m[node], cmds...)
|
|
|
|
m.mu.Unlock()
|
|
|
|
}
|