forked from ebhomengo/niki
1
0
Fork 0
niki/vendor/github.com/redis/go-redis/v9/osscluster.go

3175 lines
43 KiB
Go
Raw Normal View History

2024-02-18 10:42:21 +00:00
package redis
import (
"context"
"crypto/tls"
"fmt"
"math"
"net"
"net/url"
"runtime"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/redis/go-redis/v9/internal"
"github.com/redis/go-redis/v9/internal/hashtag"
"github.com/redis/go-redis/v9/internal/pool"
"github.com/redis/go-redis/v9/internal/proto"
"github.com/redis/go-redis/v9/internal/rand"
)
var errClusterNoNodes = fmt.Errorf("redis: cluster has no nodes")
// ClusterOptions are used to configure a cluster client and should be
2024-02-18 10:42:21 +00:00
// passed to NewClusterClient.
2024-02-18 10:42:21 +00:00
type ClusterOptions struct {
2024-02-18 10:42:21 +00:00
// A seed list of host:port addresses of cluster nodes.
2024-02-18 10:42:21 +00:00
Addrs []string
// ClientName will execute the `CLIENT SETNAME ClientName` command for each conn.
2024-02-18 10:42:21 +00:00
ClientName string
// NewClient creates a cluster node client with provided name and options.
2024-02-18 10:42:21 +00:00
NewClient func(opt *Options) *Client
// The maximum number of retries before giving up. Command is retried
2024-02-18 10:42:21 +00:00
// on network errors and MOVED/ASK redirects.
2024-02-18 10:42:21 +00:00
// Default is 3 retries.
2024-02-18 10:42:21 +00:00
MaxRedirects int
// Enables read-only commands on slave nodes.
2024-02-18 10:42:21 +00:00
ReadOnly bool
2024-02-18 10:42:21 +00:00
// Allows routing read-only commands to the closest master or slave node.
2024-02-18 10:42:21 +00:00
// It automatically enables ReadOnly.
2024-02-18 10:42:21 +00:00
RouteByLatency bool
2024-02-18 10:42:21 +00:00
// Allows routing read-only commands to the random master or slave node.
2024-02-18 10:42:21 +00:00
// It automatically enables ReadOnly.
2024-02-18 10:42:21 +00:00
RouteRandomly bool
// Optional function that returns cluster slots information.
2024-02-18 10:42:21 +00:00
// It is useful to manually create cluster of standalone Redis servers
2024-02-18 10:42:21 +00:00
// and load-balance read/write operations between master and slaves.
2024-02-18 10:42:21 +00:00
// It can use service like ZooKeeper to maintain configuration information
2024-02-18 10:42:21 +00:00
// and Cluster.ReloadState to manually trigger state reloading.
2024-02-18 10:42:21 +00:00
ClusterSlots func(context.Context) ([]ClusterSlot, error)
// Following options are copied from Options struct.
Dialer func(ctx context.Context, network, addr string) (net.Conn, error)
OnConnect func(ctx context.Context, cn *Conn) error
Protocol int
2024-02-18 10:42:21 +00:00
Username string
2024-02-18 10:42:21 +00:00
Password string
MaxRetries int
2024-02-18 10:42:21 +00:00
MinRetryBackoff time.Duration
2024-02-18 10:42:21 +00:00
MaxRetryBackoff time.Duration
DialTimeout time.Duration
ReadTimeout time.Duration
WriteTimeout time.Duration
2024-02-18 10:42:21 +00:00
ContextTimeoutEnabled bool
PoolFIFO bool
PoolSize int // applies per cluster node and not for the whole cluster
PoolTimeout time.Duration
MinIdleConns int
MaxIdleConns int
MaxActiveConns int // applies per cluster node and not for the whole cluster
2024-02-18 10:42:21 +00:00
ConnMaxIdleTime time.Duration
2024-02-18 10:42:21 +00:00
ConnMaxLifetime time.Duration
TLSConfig *tls.Config
2024-02-18 10:42:21 +00:00
DisableIndentity bool // Disable set-lib on connect. Default is false.
IdentitySuffix string // Add suffix to client name. Default is empty.
2024-02-18 10:42:21 +00:00
}
func (opt *ClusterOptions) init() {
2024-02-18 10:42:21 +00:00
if opt.MaxRedirects == -1 {
2024-02-18 10:42:21 +00:00
opt.MaxRedirects = 0
2024-02-18 10:42:21 +00:00
} else if opt.MaxRedirects == 0 {
2024-02-18 10:42:21 +00:00
opt.MaxRedirects = 3
2024-02-18 10:42:21 +00:00
}
if opt.RouteByLatency || opt.RouteRandomly {
2024-02-18 10:42:21 +00:00
opt.ReadOnly = true
2024-02-18 10:42:21 +00:00
}
if opt.PoolSize == 0 {
2024-02-18 10:42:21 +00:00
opt.PoolSize = 5 * runtime.GOMAXPROCS(0)
2024-02-18 10:42:21 +00:00
}
switch opt.ReadTimeout {
2024-02-18 10:42:21 +00:00
case -1:
2024-02-18 10:42:21 +00:00
opt.ReadTimeout = 0
2024-02-18 10:42:21 +00:00
case 0:
2024-02-18 10:42:21 +00:00
opt.ReadTimeout = 3 * time.Second
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
switch opt.WriteTimeout {
2024-02-18 10:42:21 +00:00
case -1:
2024-02-18 10:42:21 +00:00
opt.WriteTimeout = 0
2024-02-18 10:42:21 +00:00
case 0:
2024-02-18 10:42:21 +00:00
opt.WriteTimeout = opt.ReadTimeout
2024-02-18 10:42:21 +00:00
}
if opt.MaxRetries == 0 {
2024-02-18 10:42:21 +00:00
opt.MaxRetries = -1
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
switch opt.MinRetryBackoff {
2024-02-18 10:42:21 +00:00
case -1:
2024-02-18 10:42:21 +00:00
opt.MinRetryBackoff = 0
2024-02-18 10:42:21 +00:00
case 0:
2024-02-18 10:42:21 +00:00
opt.MinRetryBackoff = 8 * time.Millisecond
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
switch opt.MaxRetryBackoff {
2024-02-18 10:42:21 +00:00
case -1:
2024-02-18 10:42:21 +00:00
opt.MaxRetryBackoff = 0
2024-02-18 10:42:21 +00:00
case 0:
2024-02-18 10:42:21 +00:00
opt.MaxRetryBackoff = 512 * time.Millisecond
2024-02-18 10:42:21 +00:00
}
if opt.NewClient == nil {
2024-02-18 10:42:21 +00:00
opt.NewClient = NewClient
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
// ParseClusterURL parses a URL into ClusterOptions that can be used to connect to Redis.
2024-02-18 10:42:21 +00:00
// The URL must be in the form:
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// redis://<user>:<password>@<host>:<port>
2024-02-18 10:42:21 +00:00
// or
2024-02-18 10:42:21 +00:00
// rediss://<user>:<password>@<host>:<port>
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// To add additional addresses, specify the query parameter, "addr" one or more times. e.g:
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// redis://<user>:<password>@<host>:<port>?addr=<host2>:<port2>&addr=<host3>:<port3>
2024-02-18 10:42:21 +00:00
// or
2024-02-18 10:42:21 +00:00
// rediss://<user>:<password>@<host>:<port>?addr=<host2>:<port2>&addr=<host3>:<port3>
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// Most Option fields can be set using query parameters, with the following restrictions:
2024-02-18 10:42:21 +00:00
// - field names are mapped using snake-case conversion: to set MaxRetries, use max_retries
2024-02-18 10:42:21 +00:00
// - only scalar type fields are supported (bool, int, time.Duration)
2024-02-18 10:42:21 +00:00
// - for time.Duration fields, values must be a valid input for time.ParseDuration();
2024-02-18 10:42:21 +00:00
// additionally a plain integer as value (i.e. without unit) is intepreted as seconds
2024-02-18 10:42:21 +00:00
// - to disable a duration field, use value less than or equal to 0; to use the default
2024-02-18 10:42:21 +00:00
// value, leave the value blank or remove the parameter
2024-02-18 10:42:21 +00:00
// - only the last value is interpreted if a parameter is given multiple times
2024-02-18 10:42:21 +00:00
// - fields "network", "addr", "username" and "password" can only be set using other
2024-02-18 10:42:21 +00:00
// URL attributes (scheme, host, userinfo, resp.), query paremeters using these
2024-02-18 10:42:21 +00:00
// names will be treated as unknown parameters
2024-02-18 10:42:21 +00:00
// - unknown parameter names will result in an error
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// Example:
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// redis://user:password@localhost:6789?dial_timeout=3&read_timeout=6s&addr=localhost:6790&addr=localhost:6791
2024-02-18 10:42:21 +00:00
// is equivalent to:
2024-02-18 10:42:21 +00:00
// &ClusterOptions{
2024-02-18 10:42:21 +00:00
// Addr: ["localhost:6789", "localhost:6790", "localhost:6791"]
2024-02-18 10:42:21 +00:00
// DialTimeout: 3 * time.Second, // no time unit = seconds
2024-02-18 10:42:21 +00:00
// ReadTimeout: 6 * time.Second,
2024-02-18 10:42:21 +00:00
// }
2024-02-18 10:42:21 +00:00
func ParseClusterURL(redisURL string) (*ClusterOptions, error) {
2024-02-18 10:42:21 +00:00
o := &ClusterOptions{}
u, err := url.Parse(redisURL)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return nil, err
2024-02-18 10:42:21 +00:00
}
// add base URL to the array of addresses
2024-02-18 10:42:21 +00:00
// more addresses may be added through the URL params
2024-02-18 10:42:21 +00:00
h, p := getHostPortWithDefaults(u)
2024-02-18 10:42:21 +00:00
o.Addrs = append(o.Addrs, net.JoinHostPort(h, p))
// setup username, password, and other configurations
2024-02-18 10:42:21 +00:00
o, err = setupClusterConn(u, h, o)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return nil, err
2024-02-18 10:42:21 +00:00
}
return o, nil
2024-02-18 10:42:21 +00:00
}
// setupClusterConn gets the username and password from the URL and the query parameters.
2024-02-18 10:42:21 +00:00
func setupClusterConn(u *url.URL, host string, o *ClusterOptions) (*ClusterOptions, error) {
2024-02-18 10:42:21 +00:00
switch u.Scheme {
2024-02-18 10:42:21 +00:00
case "rediss":
2024-02-18 10:42:21 +00:00
o.TLSConfig = &tls.Config{ServerName: host}
2024-02-18 10:42:21 +00:00
fallthrough
2024-02-18 10:42:21 +00:00
case "redis":
2024-02-18 10:42:21 +00:00
o.Username, o.Password = getUserPassword(u)
2024-02-18 10:42:21 +00:00
default:
2024-02-18 10:42:21 +00:00
return nil, fmt.Errorf("redis: invalid URL scheme: %s", u.Scheme)
2024-02-18 10:42:21 +00:00
}
// retrieve the configuration from the query parameters
2024-02-18 10:42:21 +00:00
o, err := setupClusterQueryParams(u, o)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return nil, err
2024-02-18 10:42:21 +00:00
}
return o, nil
2024-02-18 10:42:21 +00:00
}
// setupClusterQueryParams converts query parameters in u to option value in o.
2024-02-18 10:42:21 +00:00
func setupClusterQueryParams(u *url.URL, o *ClusterOptions) (*ClusterOptions, error) {
2024-02-18 10:42:21 +00:00
q := queryOptions{q: u.Query()}
o.Protocol = q.int("protocol")
2024-02-18 10:42:21 +00:00
o.ClientName = q.string("client_name")
2024-02-18 10:42:21 +00:00
o.MaxRedirects = q.int("max_redirects")
2024-02-18 10:42:21 +00:00
o.ReadOnly = q.bool("read_only")
2024-02-18 10:42:21 +00:00
o.RouteByLatency = q.bool("route_by_latency")
2024-02-18 10:42:21 +00:00
o.RouteRandomly = q.bool("route_randomly")
2024-02-18 10:42:21 +00:00
o.MaxRetries = q.int("max_retries")
2024-02-18 10:42:21 +00:00
o.MinRetryBackoff = q.duration("min_retry_backoff")
2024-02-18 10:42:21 +00:00
o.MaxRetryBackoff = q.duration("max_retry_backoff")
2024-02-18 10:42:21 +00:00
o.DialTimeout = q.duration("dial_timeout")
2024-02-18 10:42:21 +00:00
o.ReadTimeout = q.duration("read_timeout")
2024-02-18 10:42:21 +00:00
o.WriteTimeout = q.duration("write_timeout")
2024-02-18 10:42:21 +00:00
o.PoolFIFO = q.bool("pool_fifo")
2024-02-18 10:42:21 +00:00
o.PoolSize = q.int("pool_size")
2024-02-18 10:42:21 +00:00
o.MinIdleConns = q.int("min_idle_conns")
2024-02-18 10:42:21 +00:00
o.MaxIdleConns = q.int("max_idle_conns")
2024-02-18 10:42:21 +00:00
o.MaxActiveConns = q.int("max_active_conns")
2024-02-18 10:42:21 +00:00
o.PoolTimeout = q.duration("pool_timeout")
2024-02-18 10:42:21 +00:00
o.ConnMaxLifetime = q.duration("conn_max_lifetime")
2024-02-18 10:42:21 +00:00
o.ConnMaxIdleTime = q.duration("conn_max_idle_time")
if q.err != nil {
2024-02-18 10:42:21 +00:00
return nil, q.err
2024-02-18 10:42:21 +00:00
}
// addr can be specified as many times as needed
2024-02-18 10:42:21 +00:00
addrs := q.strings("addr")
2024-02-18 10:42:21 +00:00
for _, addr := range addrs {
2024-02-18 10:42:21 +00:00
h, p, err := net.SplitHostPort(addr)
2024-02-18 10:42:21 +00:00
if err != nil || h == "" || p == "" {
2024-02-18 10:42:21 +00:00
return nil, fmt.Errorf("redis: unable to parse addr param: %s", addr)
2024-02-18 10:42:21 +00:00
}
o.Addrs = append(o.Addrs, net.JoinHostPort(h, p))
2024-02-18 10:42:21 +00:00
}
// any parameters left?
2024-02-18 10:42:21 +00:00
if r := q.remaining(); len(r) > 0 {
2024-02-18 10:42:21 +00:00
return nil, fmt.Errorf("redis: unexpected option: %s", strings.Join(r, ", "))
2024-02-18 10:42:21 +00:00
}
return o, nil
2024-02-18 10:42:21 +00:00
}
func (opt *ClusterOptions) clientOptions() *Options {
2024-02-18 10:42:21 +00:00
return &Options{
2024-02-18 10:42:21 +00:00
ClientName: opt.ClientName,
Dialer: opt.Dialer,
OnConnect: opt.OnConnect,
2024-02-18 10:42:21 +00:00
Protocol: opt.Protocol,
2024-02-18 10:42:21 +00:00
Username: opt.Username,
2024-02-18 10:42:21 +00:00
Password: opt.Password,
MaxRetries: opt.MaxRetries,
2024-02-18 10:42:21 +00:00
MinRetryBackoff: opt.MinRetryBackoff,
2024-02-18 10:42:21 +00:00
MaxRetryBackoff: opt.MaxRetryBackoff,
DialTimeout: opt.DialTimeout,
ReadTimeout: opt.ReadTimeout,
WriteTimeout: opt.WriteTimeout,
2024-02-18 10:42:21 +00:00
ContextTimeoutEnabled: opt.ContextTimeoutEnabled,
PoolFIFO: opt.PoolFIFO,
PoolSize: opt.PoolSize,
PoolTimeout: opt.PoolTimeout,
MinIdleConns: opt.MinIdleConns,
MaxIdleConns: opt.MaxIdleConns,
MaxActiveConns: opt.MaxActiveConns,
ConnMaxIdleTime: opt.ConnMaxIdleTime,
ConnMaxLifetime: opt.ConnMaxLifetime,
2024-02-18 10:42:21 +00:00
DisableIndentity: opt.DisableIndentity,
IdentitySuffix: opt.IdentitySuffix,
TLSConfig: opt.TLSConfig,
2024-02-18 10:42:21 +00:00
// If ClusterSlots is populated, then we probably have an artificial
2024-02-18 10:42:21 +00:00
// cluster whose nodes are not in clustering mode (otherwise there isn't
2024-02-18 10:42:21 +00:00
// much use for ClusterSlots config). This means we cannot execute the
2024-02-18 10:42:21 +00:00
// READONLY command against that node -- setting readOnly to false in such
2024-02-18 10:42:21 +00:00
// situations in the options below will prevent that from happening.
2024-02-18 10:42:21 +00:00
readOnly: opt.ReadOnly && opt.ClusterSlots == nil,
}
2024-02-18 10:42:21 +00:00
}
//------------------------------------------------------------------------------
type clusterNode struct {
Client *Client
latency uint32 // atomic
2024-02-18 10:42:21 +00:00
generation uint32 // atomic
failing uint32 // atomic
2024-02-18 10:42:21 +00:00
}
func newClusterNode(clOpt *ClusterOptions, addr string) *clusterNode {
2024-02-18 10:42:21 +00:00
opt := clOpt.clientOptions()
2024-02-18 10:42:21 +00:00
opt.Addr = addr
2024-02-18 10:42:21 +00:00
node := clusterNode{
2024-02-18 10:42:21 +00:00
Client: clOpt.NewClient(opt),
}
node.latency = math.MaxUint32
2024-02-18 10:42:21 +00:00
if clOpt.RouteByLatency {
2024-02-18 10:42:21 +00:00
go node.updateLatency()
2024-02-18 10:42:21 +00:00
}
return &node
2024-02-18 10:42:21 +00:00
}
func (n *clusterNode) String() string {
2024-02-18 10:42:21 +00:00
return n.Client.String()
2024-02-18 10:42:21 +00:00
}
func (n *clusterNode) Close() error {
2024-02-18 10:42:21 +00:00
return n.Client.Close()
2024-02-18 10:42:21 +00:00
}
func (n *clusterNode) updateLatency() {
2024-02-18 10:42:21 +00:00
const numProbe = 10
2024-02-18 10:42:21 +00:00
var dur uint64
successes := 0
2024-02-18 10:42:21 +00:00
for i := 0; i < numProbe; i++ {
2024-02-18 10:42:21 +00:00
time.Sleep(time.Duration(10+rand.Intn(10)) * time.Millisecond)
start := time.Now()
2024-02-18 10:42:21 +00:00
err := n.Client.Ping(context.TODO()).Err()
2024-02-18 10:42:21 +00:00
if err == nil {
2024-02-18 10:42:21 +00:00
dur += uint64(time.Since(start) / time.Microsecond)
2024-02-18 10:42:21 +00:00
successes++
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
var latency float64
2024-02-18 10:42:21 +00:00
if successes == 0 {
2024-02-18 10:42:21 +00:00
// If none of the pings worked, set latency to some arbitrarily high value so this node gets
2024-02-18 10:42:21 +00:00
// least priority.
2024-02-18 10:42:21 +00:00
latency = float64((1 * time.Minute) / time.Microsecond)
2024-02-18 10:42:21 +00:00
} else {
2024-02-18 10:42:21 +00:00
latency = float64(dur) / float64(successes)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
atomic.StoreUint32(&n.latency, uint32(latency+0.5))
2024-02-18 10:42:21 +00:00
}
func (n *clusterNode) Latency() time.Duration {
2024-02-18 10:42:21 +00:00
latency := atomic.LoadUint32(&n.latency)
2024-02-18 10:42:21 +00:00
return time.Duration(latency) * time.Microsecond
2024-02-18 10:42:21 +00:00
}
func (n *clusterNode) MarkAsFailing() {
2024-02-18 10:42:21 +00:00
atomic.StoreUint32(&n.failing, uint32(time.Now().Unix()))
2024-02-18 10:42:21 +00:00
}
func (n *clusterNode) Failing() bool {
2024-02-18 10:42:21 +00:00
const timeout = 15 // 15 seconds
failing := atomic.LoadUint32(&n.failing)
2024-02-18 10:42:21 +00:00
if failing == 0 {
2024-02-18 10:42:21 +00:00
return false
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if time.Now().Unix()-int64(failing) < timeout {
2024-02-18 10:42:21 +00:00
return true
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
atomic.StoreUint32(&n.failing, 0)
2024-02-18 10:42:21 +00:00
return false
2024-02-18 10:42:21 +00:00
}
func (n *clusterNode) Generation() uint32 {
2024-02-18 10:42:21 +00:00
return atomic.LoadUint32(&n.generation)
2024-02-18 10:42:21 +00:00
}
func (n *clusterNode) SetGeneration(gen uint32) {
2024-02-18 10:42:21 +00:00
for {
2024-02-18 10:42:21 +00:00
v := atomic.LoadUint32(&n.generation)
2024-02-18 10:42:21 +00:00
if gen < v || atomic.CompareAndSwapUint32(&n.generation, v, gen) {
2024-02-18 10:42:21 +00:00
break
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
//------------------------------------------------------------------------------
type clusterNodes struct {
opt *ClusterOptions
mu sync.RWMutex
addrs []string
nodes map[string]*clusterNode
2024-02-18 10:42:21 +00:00
activeAddrs []string
closed bool
onNewNode []func(rdb *Client)
2024-02-18 10:42:21 +00:00
_generation uint32 // atomic
2024-02-18 10:42:21 +00:00
}
func newClusterNodes(opt *ClusterOptions) *clusterNodes {
2024-02-18 10:42:21 +00:00
return &clusterNodes{
2024-02-18 10:42:21 +00:00
opt: opt,
addrs: opt.Addrs,
2024-02-18 10:42:21 +00:00
nodes: make(map[string]*clusterNode),
}
2024-02-18 10:42:21 +00:00
}
func (c *clusterNodes) Close() error {
2024-02-18 10:42:21 +00:00
c.mu.Lock()
2024-02-18 10:42:21 +00:00
defer c.mu.Unlock()
if c.closed {
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
c.closed = true
var firstErr error
2024-02-18 10:42:21 +00:00
for _, node := range c.nodes {
2024-02-18 10:42:21 +00:00
if err := node.Client.Close(); err != nil && firstErr == nil {
2024-02-18 10:42:21 +00:00
firstErr = err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
c.nodes = nil
2024-02-18 10:42:21 +00:00
c.activeAddrs = nil
return firstErr
2024-02-18 10:42:21 +00:00
}
func (c *clusterNodes) OnNewNode(fn func(rdb *Client)) {
2024-02-18 10:42:21 +00:00
c.mu.Lock()
2024-02-18 10:42:21 +00:00
c.onNewNode = append(c.onNewNode, fn)
2024-02-18 10:42:21 +00:00
c.mu.Unlock()
2024-02-18 10:42:21 +00:00
}
func (c *clusterNodes) Addrs() ([]string, error) {
2024-02-18 10:42:21 +00:00
var addrs []string
c.mu.RLock()
2024-02-18 10:42:21 +00:00
closed := c.closed //nolint:ifshort
2024-02-18 10:42:21 +00:00
if !closed {
2024-02-18 10:42:21 +00:00
if len(c.activeAddrs) > 0 {
2024-02-18 10:42:21 +00:00
addrs = c.activeAddrs
2024-02-18 10:42:21 +00:00
} else {
2024-02-18 10:42:21 +00:00
addrs = c.addrs
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
c.mu.RUnlock()
if closed {
2024-02-18 10:42:21 +00:00
return nil, pool.ErrClosed
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if len(addrs) == 0 {
2024-02-18 10:42:21 +00:00
return nil, errClusterNoNodes
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return addrs, nil
2024-02-18 10:42:21 +00:00
}
func (c *clusterNodes) NextGeneration() uint32 {
2024-02-18 10:42:21 +00:00
return atomic.AddUint32(&c._generation, 1)
2024-02-18 10:42:21 +00:00
}
// GC removes unused nodes.
2024-02-18 10:42:21 +00:00
func (c *clusterNodes) GC(generation uint32) {
2024-02-18 10:42:21 +00:00
//nolint:prealloc
2024-02-18 10:42:21 +00:00
var collected []*clusterNode
c.mu.Lock()
c.activeAddrs = c.activeAddrs[:0]
2024-02-18 10:42:21 +00:00
for addr, node := range c.nodes {
2024-02-18 10:42:21 +00:00
if node.Generation() >= generation {
2024-02-18 10:42:21 +00:00
c.activeAddrs = append(c.activeAddrs, addr)
2024-02-18 10:42:21 +00:00
if c.opt.RouteByLatency {
2024-02-18 10:42:21 +00:00
go node.updateLatency()
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
continue
2024-02-18 10:42:21 +00:00
}
delete(c.nodes, addr)
2024-02-18 10:42:21 +00:00
collected = append(collected, node)
2024-02-18 10:42:21 +00:00
}
c.mu.Unlock()
for _, node := range collected {
2024-02-18 10:42:21 +00:00
_ = node.Client.Close()
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
func (c *clusterNodes) GetOrCreate(addr string) (*clusterNode, error) {
2024-02-18 10:42:21 +00:00
node, err := c.get(addr)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return nil, err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if node != nil {
2024-02-18 10:42:21 +00:00
return node, nil
2024-02-18 10:42:21 +00:00
}
c.mu.Lock()
2024-02-18 10:42:21 +00:00
defer c.mu.Unlock()
if c.closed {
2024-02-18 10:42:21 +00:00
return nil, pool.ErrClosed
2024-02-18 10:42:21 +00:00
}
node, ok := c.nodes[addr]
2024-02-18 10:42:21 +00:00
if ok {
2024-02-18 10:42:21 +00:00
return node, nil
2024-02-18 10:42:21 +00:00
}
node = newClusterNode(c.opt, addr)
2024-02-18 10:42:21 +00:00
for _, fn := range c.onNewNode {
2024-02-18 10:42:21 +00:00
fn(node.Client)
2024-02-18 10:42:21 +00:00
}
c.addrs = appendIfNotExists(c.addrs, addr)
2024-02-18 10:42:21 +00:00
c.nodes[addr] = node
return node, nil
2024-02-18 10:42:21 +00:00
}
func (c *clusterNodes) get(addr string) (*clusterNode, error) {
2024-02-18 10:42:21 +00:00
var node *clusterNode
2024-02-18 10:42:21 +00:00
var err error
2024-02-18 10:42:21 +00:00
c.mu.RLock()
2024-02-18 10:42:21 +00:00
if c.closed {
2024-02-18 10:42:21 +00:00
err = pool.ErrClosed
2024-02-18 10:42:21 +00:00
} else {
2024-02-18 10:42:21 +00:00
node = c.nodes[addr]
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
c.mu.RUnlock()
2024-02-18 10:42:21 +00:00
return node, err
2024-02-18 10:42:21 +00:00
}
func (c *clusterNodes) All() ([]*clusterNode, error) {
2024-02-18 10:42:21 +00:00
c.mu.RLock()
2024-02-18 10:42:21 +00:00
defer c.mu.RUnlock()
if c.closed {
2024-02-18 10:42:21 +00:00
return nil, pool.ErrClosed
2024-02-18 10:42:21 +00:00
}
cp := make([]*clusterNode, 0, len(c.nodes))
2024-02-18 10:42:21 +00:00
for _, node := range c.nodes {
2024-02-18 10:42:21 +00:00
cp = append(cp, node)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return cp, nil
2024-02-18 10:42:21 +00:00
}
func (c *clusterNodes) Random() (*clusterNode, error) {
2024-02-18 10:42:21 +00:00
addrs, err := c.Addrs()
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return nil, err
2024-02-18 10:42:21 +00:00
}
n := rand.Intn(len(addrs))
2024-02-18 10:42:21 +00:00
return c.GetOrCreate(addrs[n])
2024-02-18 10:42:21 +00:00
}
//------------------------------------------------------------------------------
type clusterSlot struct {
start, end int
nodes []*clusterNode
2024-02-18 10:42:21 +00:00
}
type clusterSlotSlice []*clusterSlot
func (p clusterSlotSlice) Len() int {
2024-02-18 10:42:21 +00:00
return len(p)
2024-02-18 10:42:21 +00:00
}
func (p clusterSlotSlice) Less(i, j int) bool {
2024-02-18 10:42:21 +00:00
return p[i].start < p[j].start
2024-02-18 10:42:21 +00:00
}
func (p clusterSlotSlice) Swap(i, j int) {
2024-02-18 10:42:21 +00:00
p[i], p[j] = p[j], p[i]
2024-02-18 10:42:21 +00:00
}
type clusterState struct {
nodes *clusterNodes
2024-02-18 10:42:21 +00:00
Masters []*clusterNode
Slaves []*clusterNode
2024-02-18 10:42:21 +00:00
slots []*clusterSlot
generation uint32
createdAt time.Time
2024-02-18 10:42:21 +00:00
}
func newClusterState(
2024-02-18 10:42:21 +00:00
nodes *clusterNodes, slots []ClusterSlot, origin string,
2024-02-18 10:42:21 +00:00
) (*clusterState, error) {
2024-02-18 10:42:21 +00:00
c := clusterState{
2024-02-18 10:42:21 +00:00
nodes: nodes,
slots: make([]*clusterSlot, 0, len(slots)),
generation: nodes.NextGeneration(),
createdAt: time.Now(),
2024-02-18 10:42:21 +00:00
}
originHost, _, _ := net.SplitHostPort(origin)
2024-02-18 10:42:21 +00:00
isLoopbackOrigin := isLoopback(originHost)
for _, slot := range slots {
2024-02-18 10:42:21 +00:00
var nodes []*clusterNode
2024-02-18 10:42:21 +00:00
for i, slotNode := range slot.Nodes {
2024-02-18 10:42:21 +00:00
addr := slotNode.Addr
2024-02-18 10:42:21 +00:00
if !isLoopbackOrigin {
2024-02-18 10:42:21 +00:00
addr = replaceLoopbackHost(addr, originHost)
2024-02-18 10:42:21 +00:00
}
node, err := c.nodes.GetOrCreate(addr)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return nil, err
2024-02-18 10:42:21 +00:00
}
node.SetGeneration(c.generation)
2024-02-18 10:42:21 +00:00
nodes = append(nodes, node)
if i == 0 {
2024-02-18 10:42:21 +00:00
c.Masters = appendUniqueNode(c.Masters, node)
2024-02-18 10:42:21 +00:00
} else {
2024-02-18 10:42:21 +00:00
c.Slaves = appendUniqueNode(c.Slaves, node)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
c.slots = append(c.slots, &clusterSlot{
2024-02-18 10:42:21 +00:00
start: slot.Start,
end: slot.End,
2024-02-18 10:42:21 +00:00
nodes: nodes,
})
2024-02-18 10:42:21 +00:00
}
sort.Sort(clusterSlotSlice(c.slots))
time.AfterFunc(time.Minute, func() {
2024-02-18 10:42:21 +00:00
nodes.GC(c.generation)
2024-02-18 10:42:21 +00:00
})
return &c, nil
2024-02-18 10:42:21 +00:00
}
func replaceLoopbackHost(nodeAddr, originHost string) string {
2024-02-18 10:42:21 +00:00
nodeHost, nodePort, err := net.SplitHostPort(nodeAddr)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return nodeAddr
2024-02-18 10:42:21 +00:00
}
nodeIP := net.ParseIP(nodeHost)
2024-02-18 10:42:21 +00:00
if nodeIP == nil {
2024-02-18 10:42:21 +00:00
return nodeAddr
2024-02-18 10:42:21 +00:00
}
if !nodeIP.IsLoopback() {
2024-02-18 10:42:21 +00:00
return nodeAddr
2024-02-18 10:42:21 +00:00
}
// Use origin host which is not loopback and node port.
2024-02-18 10:42:21 +00:00
return net.JoinHostPort(originHost, nodePort)
2024-02-18 10:42:21 +00:00
}
func isLoopback(host string) bool {
2024-02-18 10:42:21 +00:00
ip := net.ParseIP(host)
2024-02-18 10:42:21 +00:00
if ip == nil {
2024-02-18 10:42:21 +00:00
return true
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return ip.IsLoopback()
2024-02-18 10:42:21 +00:00
}
func (c *clusterState) slotMasterNode(slot int) (*clusterNode, error) {
2024-02-18 10:42:21 +00:00
nodes := c.slotNodes(slot)
2024-02-18 10:42:21 +00:00
if len(nodes) > 0 {
2024-02-18 10:42:21 +00:00
return nodes[0], nil
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return c.nodes.Random()
2024-02-18 10:42:21 +00:00
}
func (c *clusterState) slotSlaveNode(slot int) (*clusterNode, error) {
2024-02-18 10:42:21 +00:00
nodes := c.slotNodes(slot)
2024-02-18 10:42:21 +00:00
switch len(nodes) {
2024-02-18 10:42:21 +00:00
case 0:
2024-02-18 10:42:21 +00:00
return c.nodes.Random()
2024-02-18 10:42:21 +00:00
case 1:
2024-02-18 10:42:21 +00:00
return nodes[0], nil
2024-02-18 10:42:21 +00:00
case 2:
2024-02-18 10:42:21 +00:00
if slave := nodes[1]; !slave.Failing() {
2024-02-18 10:42:21 +00:00
return slave, nil
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return nodes[0], nil
2024-02-18 10:42:21 +00:00
default:
2024-02-18 10:42:21 +00:00
var slave *clusterNode
2024-02-18 10:42:21 +00:00
for i := 0; i < 10; i++ {
2024-02-18 10:42:21 +00:00
n := rand.Intn(len(nodes)-1) + 1
2024-02-18 10:42:21 +00:00
slave = nodes[n]
2024-02-18 10:42:21 +00:00
if !slave.Failing() {
2024-02-18 10:42:21 +00:00
return slave, nil
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
// All slaves are loading - use master.
2024-02-18 10:42:21 +00:00
return nodes[0], nil
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
func (c *clusterState) slotClosestNode(slot int) (*clusterNode, error) {
2024-02-18 10:42:21 +00:00
nodes := c.slotNodes(slot)
2024-02-18 10:42:21 +00:00
if len(nodes) == 0 {
2024-02-18 10:42:21 +00:00
return c.nodes.Random()
2024-02-18 10:42:21 +00:00
}
var node *clusterNode
2024-02-18 10:42:21 +00:00
for _, n := range nodes {
2024-02-18 10:42:21 +00:00
if n.Failing() {
2024-02-18 10:42:21 +00:00
continue
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if node == nil || n.Latency() < node.Latency() {
2024-02-18 10:42:21 +00:00
node = n
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if node != nil {
2024-02-18 10:42:21 +00:00
return node, nil
2024-02-18 10:42:21 +00:00
}
// If all nodes are failing - return random node
2024-02-18 10:42:21 +00:00
return c.nodes.Random()
2024-02-18 10:42:21 +00:00
}
func (c *clusterState) slotRandomNode(slot int) (*clusterNode, error) {
2024-02-18 10:42:21 +00:00
nodes := c.slotNodes(slot)
2024-02-18 10:42:21 +00:00
if len(nodes) == 0 {
2024-02-18 10:42:21 +00:00
return c.nodes.Random()
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if len(nodes) == 1 {
2024-02-18 10:42:21 +00:00
return nodes[0], nil
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
randomNodes := rand.Perm(len(nodes))
2024-02-18 10:42:21 +00:00
for _, idx := range randomNodes {
2024-02-18 10:42:21 +00:00
if node := nodes[idx]; !node.Failing() {
2024-02-18 10:42:21 +00:00
return node, nil
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return nodes[randomNodes[0]], nil
2024-02-18 10:42:21 +00:00
}
func (c *clusterState) slotNodes(slot int) []*clusterNode {
2024-02-18 10:42:21 +00:00
i := sort.Search(len(c.slots), func(i int) bool {
2024-02-18 10:42:21 +00:00
return c.slots[i].end >= slot
2024-02-18 10:42:21 +00:00
})
2024-02-18 10:42:21 +00:00
if i >= len(c.slots) {
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
x := c.slots[i]
2024-02-18 10:42:21 +00:00
if slot >= x.start && slot <= x.end {
2024-02-18 10:42:21 +00:00
return x.nodes
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
//------------------------------------------------------------------------------
type clusterStateHolder struct {
load func(ctx context.Context) (*clusterState, error)
state atomic.Value
2024-02-18 10:42:21 +00:00
reloading uint32 // atomic
2024-02-18 10:42:21 +00:00
}
func newClusterStateHolder(fn func(ctx context.Context) (*clusterState, error)) *clusterStateHolder {
2024-02-18 10:42:21 +00:00
return &clusterStateHolder{
2024-02-18 10:42:21 +00:00
load: fn,
}
2024-02-18 10:42:21 +00:00
}
func (c *clusterStateHolder) Reload(ctx context.Context) (*clusterState, error) {
2024-02-18 10:42:21 +00:00
state, err := c.load(ctx)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return nil, err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
c.state.Store(state)
2024-02-18 10:42:21 +00:00
return state, nil
2024-02-18 10:42:21 +00:00
}
func (c *clusterStateHolder) LazyReload() {
2024-02-18 10:42:21 +00:00
if !atomic.CompareAndSwapUint32(&c.reloading, 0, 1) {
2024-02-18 10:42:21 +00:00
return
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
go func() {
2024-02-18 10:42:21 +00:00
defer atomic.StoreUint32(&c.reloading, 0)
_, err := c.Reload(context.Background())
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
time.Sleep(200 * time.Millisecond)
2024-02-18 10:42:21 +00:00
}()
2024-02-18 10:42:21 +00:00
}
func (c *clusterStateHolder) Get(ctx context.Context) (*clusterState, error) {
2024-02-18 10:42:21 +00:00
v := c.state.Load()
2024-02-18 10:42:21 +00:00
if v == nil {
2024-02-18 10:42:21 +00:00
return c.Reload(ctx)
2024-02-18 10:42:21 +00:00
}
state := v.(*clusterState)
2024-02-18 10:42:21 +00:00
if time.Since(state.createdAt) > 10*time.Second {
2024-02-18 10:42:21 +00:00
c.LazyReload()
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return state, nil
2024-02-18 10:42:21 +00:00
}
func (c *clusterStateHolder) ReloadOrGet(ctx context.Context) (*clusterState, error) {
2024-02-18 10:42:21 +00:00
state, err := c.Reload(ctx)
2024-02-18 10:42:21 +00:00
if err == nil {
2024-02-18 10:42:21 +00:00
return state, nil
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return c.Get(ctx)
2024-02-18 10:42:21 +00:00
}
//------------------------------------------------------------------------------
// ClusterClient is a Redis Cluster client representing a pool of zero
2024-02-18 10:42:21 +00:00
// or more underlying connections. It's safe for concurrent use by
2024-02-18 10:42:21 +00:00
// multiple goroutines.
2024-02-18 10:42:21 +00:00
type ClusterClient struct {
opt *ClusterOptions
nodes *clusterNodes
state *clusterStateHolder
2024-02-18 10:42:21 +00:00
cmdsInfoCache *cmdsInfoCache
2024-02-18 10:42:21 +00:00
cmdable
2024-02-18 10:42:21 +00:00
hooksMixin
}
// NewClusterClient returns a Redis Cluster client as described in
2024-02-18 10:42:21 +00:00
// http://redis.io/topics/cluster-spec.
2024-02-18 10:42:21 +00:00
func NewClusterClient(opt *ClusterOptions) *ClusterClient {
2024-02-18 10:42:21 +00:00
opt.init()
c := &ClusterClient{
opt: opt,
2024-02-18 10:42:21 +00:00
nodes: newClusterNodes(opt),
}
c.state = newClusterStateHolder(c.loadState)
2024-02-18 10:42:21 +00:00
c.cmdsInfoCache = newCmdsInfoCache(c.cmdsInfo)
2024-02-18 10:42:21 +00:00
c.cmdable = c.Process
c.initHooks(hooks{
dial: nil,
process: c.process,
pipeline: c.processPipeline,
2024-02-18 10:42:21 +00:00
txPipeline: c.processTxPipeline,
})
return c
2024-02-18 10:42:21 +00:00
}
// Options returns read-only Options that were used to create the client.
2024-02-18 10:42:21 +00:00
func (c *ClusterClient) Options() *ClusterOptions {
2024-02-18 10:42:21 +00:00
return c.opt
2024-02-18 10:42:21 +00:00
}
// ReloadState reloads cluster state. If available it calls ClusterSlots func
2024-02-18 10:42:21 +00:00
// to get cluster slots information.
2024-02-18 10:42:21 +00:00
func (c *ClusterClient) ReloadState(ctx context.Context) {
2024-02-18 10:42:21 +00:00
c.state.LazyReload()
2024-02-18 10:42:21 +00:00
}
// Close closes the cluster client, releasing any open resources.
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// It is rare to Close a ClusterClient, as the ClusterClient is meant
2024-02-18 10:42:21 +00:00
// to be long-lived and shared between many goroutines.
2024-02-18 10:42:21 +00:00
func (c *ClusterClient) Close() error {
2024-02-18 10:42:21 +00:00
return c.nodes.Close()
2024-02-18 10:42:21 +00:00
}
// Do create a Cmd from the args and processes the cmd.
2024-02-18 10:42:21 +00:00
func (c *ClusterClient) Do(ctx context.Context, args ...interface{}) *Cmd {
2024-02-18 10:42:21 +00:00
cmd := NewCmd(ctx, args...)
2024-02-18 10:42:21 +00:00
_ = c.Process(ctx, cmd)
2024-02-18 10:42:21 +00:00
return cmd
2024-02-18 10:42:21 +00:00
}
func (c *ClusterClient) Process(ctx context.Context, cmd Cmder) error {
2024-02-18 10:42:21 +00:00
err := c.processHook(ctx, cmd)
2024-02-18 10:42:21 +00:00
cmd.SetErr(err)
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
func (c *ClusterClient) process(ctx context.Context, cmd Cmder) error {
2024-02-18 10:42:21 +00:00
slot := c.cmdSlot(ctx, cmd)
2024-02-18 10:42:21 +00:00
var node *clusterNode
2024-02-18 10:42:21 +00:00
var ask bool
2024-02-18 10:42:21 +00:00
var lastErr error
2024-02-18 10:42:21 +00:00
for attempt := 0; attempt <= c.opt.MaxRedirects; attempt++ {
2024-02-18 10:42:21 +00:00
if attempt > 0 {
2024-02-18 10:42:21 +00:00
if err := internal.Sleep(ctx, c.retryBackoff(attempt)); err != nil {
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
if node == nil {
2024-02-18 10:42:21 +00:00
var err error
2024-02-18 10:42:21 +00:00
node, err = c.cmdNode(ctx, cmd.Name(), slot)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
if ask {
2024-02-18 10:42:21 +00:00
ask = false
pipe := node.Client.Pipeline()
2024-02-18 10:42:21 +00:00
_ = pipe.Process(ctx, NewCmd(ctx, "asking"))
2024-02-18 10:42:21 +00:00
_ = pipe.Process(ctx, cmd)
2024-02-18 10:42:21 +00:00
_, lastErr = pipe.Exec(ctx)
2024-02-18 10:42:21 +00:00
} else {
2024-02-18 10:42:21 +00:00
lastErr = node.Client.Process(ctx, cmd)
2024-02-18 10:42:21 +00:00
}
// If there is no error - we are done.
2024-02-18 10:42:21 +00:00
if lastErr == nil {
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if isReadOnly := isReadOnlyError(lastErr); isReadOnly || lastErr == pool.ErrClosed {
2024-02-18 10:42:21 +00:00
if isReadOnly {
2024-02-18 10:42:21 +00:00
c.state.LazyReload()
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
node = nil
2024-02-18 10:42:21 +00:00
continue
2024-02-18 10:42:21 +00:00
}
// If slave is loading - pick another node.
2024-02-18 10:42:21 +00:00
if c.opt.ReadOnly && isLoadingError(lastErr) {
2024-02-18 10:42:21 +00:00
node.MarkAsFailing()
2024-02-18 10:42:21 +00:00
node = nil
2024-02-18 10:42:21 +00:00
continue
2024-02-18 10:42:21 +00:00
}
var moved bool
2024-02-18 10:42:21 +00:00
var addr string
2024-02-18 10:42:21 +00:00
moved, ask, addr = isMovedError(lastErr)
2024-02-18 10:42:21 +00:00
if moved || ask {
2024-02-18 10:42:21 +00:00
c.state.LazyReload()
var err error
2024-02-18 10:42:21 +00:00
node, err = c.nodes.GetOrCreate(addr)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
continue
2024-02-18 10:42:21 +00:00
}
if shouldRetry(lastErr, cmd.readTimeout() == nil) {
2024-02-18 10:42:21 +00:00
// First retry the same node.
2024-02-18 10:42:21 +00:00
if attempt == 0 {
2024-02-18 10:42:21 +00:00
continue
2024-02-18 10:42:21 +00:00
}
// Second try another node.
2024-02-18 10:42:21 +00:00
node.MarkAsFailing()
2024-02-18 10:42:21 +00:00
node = nil
2024-02-18 10:42:21 +00:00
continue
2024-02-18 10:42:21 +00:00
}
return lastErr
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return lastErr
2024-02-18 10:42:21 +00:00
}
func (c *ClusterClient) OnNewNode(fn func(rdb *Client)) {
2024-02-18 10:42:21 +00:00
c.nodes.OnNewNode(fn)
2024-02-18 10:42:21 +00:00
}
// ForEachMaster concurrently calls the fn on each master node in the cluster.
2024-02-18 10:42:21 +00:00
// It returns the first error if any.
2024-02-18 10:42:21 +00:00
func (c *ClusterClient) ForEachMaster(
2024-02-18 10:42:21 +00:00
ctx context.Context,
2024-02-18 10:42:21 +00:00
fn func(ctx context.Context, client *Client) error,
2024-02-18 10:42:21 +00:00
) error {
2024-02-18 10:42:21 +00:00
state, err := c.state.ReloadOrGet(ctx)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
var wg sync.WaitGroup
2024-02-18 10:42:21 +00:00
errCh := make(chan error, 1)
for _, master := range state.Masters {
2024-02-18 10:42:21 +00:00
wg.Add(1)
2024-02-18 10:42:21 +00:00
go func(node *clusterNode) {
2024-02-18 10:42:21 +00:00
defer wg.Done()
2024-02-18 10:42:21 +00:00
err := fn(ctx, node.Client)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
select {
2024-02-18 10:42:21 +00:00
case errCh <- err:
2024-02-18 10:42:21 +00:00
default:
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}(master)
2024-02-18 10:42:21 +00:00
}
wg.Wait()
select {
2024-02-18 10:42:21 +00:00
case err := <-errCh:
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
default:
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
// ForEachSlave concurrently calls the fn on each slave node in the cluster.
2024-02-18 10:42:21 +00:00
// It returns the first error if any.
2024-02-18 10:42:21 +00:00
func (c *ClusterClient) ForEachSlave(
2024-02-18 10:42:21 +00:00
ctx context.Context,
2024-02-18 10:42:21 +00:00
fn func(ctx context.Context, client *Client) error,
2024-02-18 10:42:21 +00:00
) error {
2024-02-18 10:42:21 +00:00
state, err := c.state.ReloadOrGet(ctx)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
var wg sync.WaitGroup
2024-02-18 10:42:21 +00:00
errCh := make(chan error, 1)
for _, slave := range state.Slaves {
2024-02-18 10:42:21 +00:00
wg.Add(1)
2024-02-18 10:42:21 +00:00
go func(node *clusterNode) {
2024-02-18 10:42:21 +00:00
defer wg.Done()
2024-02-18 10:42:21 +00:00
err := fn(ctx, node.Client)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
select {
2024-02-18 10:42:21 +00:00
case errCh <- err:
2024-02-18 10:42:21 +00:00
default:
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}(slave)
2024-02-18 10:42:21 +00:00
}
wg.Wait()
select {
2024-02-18 10:42:21 +00:00
case err := <-errCh:
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
default:
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
// ForEachShard concurrently calls the fn on each known node in the cluster.
2024-02-18 10:42:21 +00:00
// It returns the first error if any.
2024-02-18 10:42:21 +00:00
func (c *ClusterClient) ForEachShard(
2024-02-18 10:42:21 +00:00
ctx context.Context,
2024-02-18 10:42:21 +00:00
fn func(ctx context.Context, client *Client) error,
2024-02-18 10:42:21 +00:00
) error {
2024-02-18 10:42:21 +00:00
state, err := c.state.ReloadOrGet(ctx)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
var wg sync.WaitGroup
2024-02-18 10:42:21 +00:00
errCh := make(chan error, 1)
worker := func(node *clusterNode) {
2024-02-18 10:42:21 +00:00
defer wg.Done()
2024-02-18 10:42:21 +00:00
err := fn(ctx, node.Client)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
select {
2024-02-18 10:42:21 +00:00
case errCh <- err:
2024-02-18 10:42:21 +00:00
default:
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
for _, node := range state.Masters {
2024-02-18 10:42:21 +00:00
wg.Add(1)
2024-02-18 10:42:21 +00:00
go worker(node)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
for _, node := range state.Slaves {
2024-02-18 10:42:21 +00:00
wg.Add(1)
2024-02-18 10:42:21 +00:00
go worker(node)
2024-02-18 10:42:21 +00:00
}
wg.Wait()
select {
2024-02-18 10:42:21 +00:00
case err := <-errCh:
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
default:
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
// PoolStats returns accumulated connection pool stats.
2024-02-18 10:42:21 +00:00
func (c *ClusterClient) PoolStats() *PoolStats {
2024-02-18 10:42:21 +00:00
var acc PoolStats
state, _ := c.state.Get(context.TODO())
2024-02-18 10:42:21 +00:00
if state == nil {
2024-02-18 10:42:21 +00:00
return &acc
2024-02-18 10:42:21 +00:00
}
for _, node := range state.Masters {
2024-02-18 10:42:21 +00:00
s := node.Client.connPool.Stats()
2024-02-18 10:42:21 +00:00
acc.Hits += s.Hits
2024-02-18 10:42:21 +00:00
acc.Misses += s.Misses
2024-02-18 10:42:21 +00:00
acc.Timeouts += s.Timeouts
acc.TotalConns += s.TotalConns
2024-02-18 10:42:21 +00:00
acc.IdleConns += s.IdleConns
2024-02-18 10:42:21 +00:00
acc.StaleConns += s.StaleConns
2024-02-18 10:42:21 +00:00
}
for _, node := range state.Slaves {
2024-02-18 10:42:21 +00:00
s := node.Client.connPool.Stats()
2024-02-18 10:42:21 +00:00
acc.Hits += s.Hits
2024-02-18 10:42:21 +00:00
acc.Misses += s.Misses
2024-02-18 10:42:21 +00:00
acc.Timeouts += s.Timeouts
acc.TotalConns += s.TotalConns
2024-02-18 10:42:21 +00:00
acc.IdleConns += s.IdleConns
2024-02-18 10:42:21 +00:00
acc.StaleConns += s.StaleConns
2024-02-18 10:42:21 +00:00
}
return &acc
2024-02-18 10:42:21 +00:00
}
func (c *ClusterClient) loadState(ctx context.Context) (*clusterState, error) {
2024-02-18 10:42:21 +00:00
if c.opt.ClusterSlots != nil {
2024-02-18 10:42:21 +00:00
slots, err := c.opt.ClusterSlots(ctx)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return nil, err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return newClusterState(c.nodes, slots, "")
2024-02-18 10:42:21 +00:00
}
addrs, err := c.nodes.Addrs()
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return nil, err
2024-02-18 10:42:21 +00:00
}
var firstErr error
for _, idx := range rand.Perm(len(addrs)) {
2024-02-18 10:42:21 +00:00
addr := addrs[idx]
node, err := c.nodes.GetOrCreate(addr)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
if firstErr == nil {
2024-02-18 10:42:21 +00:00
firstErr = err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
continue
2024-02-18 10:42:21 +00:00
}
slots, err := node.Client.ClusterSlots(ctx).Result()
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
if firstErr == nil {
2024-02-18 10:42:21 +00:00
firstErr = err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
continue
2024-02-18 10:42:21 +00:00
}
return newClusterState(c.nodes, slots, node.Client.opt.Addr)
2024-02-18 10:42:21 +00:00
}
/*
2024-02-18 10:42:21 +00:00
* No node is connectable. It's possible that all nodes' IP has changed.
2024-02-18 10:42:21 +00:00
* Clear activeAddrs to let client be able to re-connect using the initial
2024-02-18 10:42:21 +00:00
* setting of the addresses (e.g. [redis-cluster-0:6379, redis-cluster-1:6379]),
2024-02-18 10:42:21 +00:00
* which might have chance to resolve domain name and get updated IP address.
2024-02-18 10:42:21 +00:00
*/
2024-02-18 10:42:21 +00:00
c.nodes.mu.Lock()
2024-02-18 10:42:21 +00:00
c.nodes.activeAddrs = nil
2024-02-18 10:42:21 +00:00
c.nodes.mu.Unlock()
return nil, firstErr
2024-02-18 10:42:21 +00:00
}
func (c *ClusterClient) Pipeline() Pipeliner {
2024-02-18 10:42:21 +00:00
pipe := Pipeline{
2024-02-18 10:42:21 +00:00
exec: pipelineExecer(c.processPipelineHook),
}
2024-02-18 10:42:21 +00:00
pipe.init()
2024-02-18 10:42:21 +00:00
return &pipe
2024-02-18 10:42:21 +00:00
}
func (c *ClusterClient) Pipelined(ctx context.Context, fn func(Pipeliner) error) ([]Cmder, error) {
2024-02-18 10:42:21 +00:00
return c.Pipeline().Pipelined(ctx, fn)
2024-02-18 10:42:21 +00:00
}
func (c *ClusterClient) processPipeline(ctx context.Context, cmds []Cmder) error {
2024-02-18 10:42:21 +00:00
cmdsMap := newCmdsMap()
if err := c.mapCmdsByNode(ctx, cmdsMap, cmds); err != nil {
2024-02-18 10:42:21 +00:00
setCmdsErr(cmds, err)
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
for attempt := 0; attempt <= c.opt.MaxRedirects; attempt++ {
2024-02-18 10:42:21 +00:00
if attempt > 0 {
2024-02-18 10:42:21 +00:00
if err := internal.Sleep(ctx, c.retryBackoff(attempt)); err != nil {
2024-02-18 10:42:21 +00:00
setCmdsErr(cmds, err)
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
failedCmds := newCmdsMap()
2024-02-18 10:42:21 +00:00
var wg sync.WaitGroup
for node, cmds := range cmdsMap.m {
2024-02-18 10:42:21 +00:00
wg.Add(1)
2024-02-18 10:42:21 +00:00
go func(node *clusterNode, cmds []Cmder) {
2024-02-18 10:42:21 +00:00
defer wg.Done()
2024-02-18 10:42:21 +00:00
c.processPipelineNode(ctx, node, cmds, failedCmds)
2024-02-18 10:42:21 +00:00
}(node, cmds)
2024-02-18 10:42:21 +00:00
}
wg.Wait()
2024-02-18 10:42:21 +00:00
if len(failedCmds.m) == 0 {
2024-02-18 10:42:21 +00:00
break
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
cmdsMap = failedCmds
2024-02-18 10:42:21 +00:00
}
return cmdsFirstErr(cmds)
2024-02-18 10:42:21 +00:00
}
func (c *ClusterClient) mapCmdsByNode(ctx context.Context, cmdsMap *cmdsMap, cmds []Cmder) error {
2024-02-18 10:42:21 +00:00
state, err := c.state.Get(ctx)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
if c.opt.ReadOnly && c.cmdsAreReadOnly(ctx, cmds) {
2024-02-18 10:42:21 +00:00
for _, cmd := range cmds {
2024-02-18 10:42:21 +00:00
slot := c.cmdSlot(ctx, cmd)
2024-02-18 10:42:21 +00:00
node, err := c.slotReadOnlyNode(state, slot)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
cmdsMap.Add(node, cmd)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
for _, cmd := range cmds {
2024-02-18 10:42:21 +00:00
slot := c.cmdSlot(ctx, cmd)
2024-02-18 10:42:21 +00:00
node, err := state.slotMasterNode(slot)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
cmdsMap.Add(node, cmd)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
func (c *ClusterClient) cmdsAreReadOnly(ctx context.Context, cmds []Cmder) bool {
2024-02-18 10:42:21 +00:00
for _, cmd := range cmds {
2024-02-18 10:42:21 +00:00
cmdInfo := c.cmdInfo(ctx, cmd.Name())
2024-02-18 10:42:21 +00:00
if cmdInfo == nil || !cmdInfo.ReadOnly {
2024-02-18 10:42:21 +00:00
return false
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return true
2024-02-18 10:42:21 +00:00
}
func (c *ClusterClient) processPipelineNode(
2024-02-18 10:42:21 +00:00
ctx context.Context, node *clusterNode, cmds []Cmder, failedCmds *cmdsMap,
2024-02-18 10:42:21 +00:00
) {
2024-02-18 10:42:21 +00:00
_ = node.Client.withProcessPipelineHook(ctx, cmds, func(ctx context.Context, cmds []Cmder) error {
2024-02-18 10:42:21 +00:00
cn, err := node.Client.getConn(ctx)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
_ = c.mapCmdsByNode(ctx, failedCmds, cmds)
2024-02-18 10:42:21 +00:00
setCmdsErr(cmds, err)
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
var processErr error
2024-02-18 10:42:21 +00:00
defer func() {
2024-02-18 10:42:21 +00:00
node.Client.releaseConn(ctx, cn, processErr)
2024-02-18 10:42:21 +00:00
}()
2024-02-18 10:42:21 +00:00
processErr = c.processPipelineNodeConn(ctx, node, cn, cmds, failedCmds)
return processErr
2024-02-18 10:42:21 +00:00
})
2024-02-18 10:42:21 +00:00
}
func (c *ClusterClient) processPipelineNodeConn(
2024-02-18 10:42:21 +00:00
ctx context.Context, node *clusterNode, cn *pool.Conn, cmds []Cmder, failedCmds *cmdsMap,
2024-02-18 10:42:21 +00:00
) error {
2024-02-18 10:42:21 +00:00
if err := cn.WithWriter(c.context(ctx), c.opt.WriteTimeout, func(wr *proto.Writer) error {
2024-02-18 10:42:21 +00:00
return writeCmds(wr, cmds)
2024-02-18 10:42:21 +00:00
}); err != nil {
2024-02-18 10:42:21 +00:00
if shouldRetry(err, true) {
2024-02-18 10:42:21 +00:00
_ = c.mapCmdsByNode(ctx, failedCmds, cmds)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
setCmdsErr(cmds, err)
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
return cn.WithReader(c.context(ctx), c.opt.ReadTimeout, func(rd *proto.Reader) error {
2024-02-18 10:42:21 +00:00
return c.pipelineReadCmds(ctx, node, rd, cmds, failedCmds)
2024-02-18 10:42:21 +00:00
})
2024-02-18 10:42:21 +00:00
}
func (c *ClusterClient) pipelineReadCmds(
2024-02-18 10:42:21 +00:00
ctx context.Context,
2024-02-18 10:42:21 +00:00
node *clusterNode,
2024-02-18 10:42:21 +00:00
rd *proto.Reader,
2024-02-18 10:42:21 +00:00
cmds []Cmder,
2024-02-18 10:42:21 +00:00
failedCmds *cmdsMap,
2024-02-18 10:42:21 +00:00
) error {
2024-02-18 10:42:21 +00:00
for i, cmd := range cmds {
2024-02-18 10:42:21 +00:00
err := cmd.readReply(rd)
2024-02-18 10:42:21 +00:00
cmd.SetErr(err)
if err == nil {
2024-02-18 10:42:21 +00:00
continue
2024-02-18 10:42:21 +00:00
}
if c.checkMovedErr(ctx, cmd, err, failedCmds) {
2024-02-18 10:42:21 +00:00
continue
2024-02-18 10:42:21 +00:00
}
if c.opt.ReadOnly {
2024-02-18 10:42:21 +00:00
node.MarkAsFailing()
2024-02-18 10:42:21 +00:00
}
if !isRedisError(err) {
2024-02-18 10:42:21 +00:00
if shouldRetry(err, true) {
2024-02-18 10:42:21 +00:00
_ = c.mapCmdsByNode(ctx, failedCmds, cmds)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
setCmdsErr(cmds[i+1:], err)
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
if err := cmds[0].Err(); err != nil && shouldRetry(err, true) {
2024-02-18 10:42:21 +00:00
_ = c.mapCmdsByNode(ctx, failedCmds, cmds)
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
return nil
2024-02-18 10:42:21 +00:00
}
func (c *ClusterClient) checkMovedErr(
2024-02-18 10:42:21 +00:00
ctx context.Context, cmd Cmder, err error, failedCmds *cmdsMap,
2024-02-18 10:42:21 +00:00
) bool {
2024-02-18 10:42:21 +00:00
moved, ask, addr := isMovedError(err)
2024-02-18 10:42:21 +00:00
if !moved && !ask {
2024-02-18 10:42:21 +00:00
return false
2024-02-18 10:42:21 +00:00
}
node, err := c.nodes.GetOrCreate(addr)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return false
2024-02-18 10:42:21 +00:00
}
if moved {
2024-02-18 10:42:21 +00:00
c.state.LazyReload()
2024-02-18 10:42:21 +00:00
failedCmds.Add(node, cmd)
2024-02-18 10:42:21 +00:00
return true
2024-02-18 10:42:21 +00:00
}
if ask {
2024-02-18 10:42:21 +00:00
failedCmds.Add(node, NewCmd(ctx, "asking"), cmd)
2024-02-18 10:42:21 +00:00
return true
2024-02-18 10:42:21 +00:00
}
panic("not reached")
2024-02-18 10:42:21 +00:00
}
// TxPipeline acts like Pipeline, but wraps queued commands with MULTI/EXEC.
2024-02-18 10:42:21 +00:00
func (c *ClusterClient) TxPipeline() Pipeliner {
2024-02-18 10:42:21 +00:00
pipe := Pipeline{
2024-02-18 10:42:21 +00:00
exec: func(ctx context.Context, cmds []Cmder) error {
2024-02-18 10:42:21 +00:00
cmds = wrapMultiExec(ctx, cmds)
2024-02-18 10:42:21 +00:00
return c.processTxPipelineHook(ctx, cmds)
2024-02-18 10:42:21 +00:00
},
}
2024-02-18 10:42:21 +00:00
pipe.init()
2024-02-18 10:42:21 +00:00
return &pipe
2024-02-18 10:42:21 +00:00
}
func (c *ClusterClient) TxPipelined(ctx context.Context, fn func(Pipeliner) error) ([]Cmder, error) {
2024-02-18 10:42:21 +00:00
return c.TxPipeline().Pipelined(ctx, fn)
2024-02-18 10:42:21 +00:00
}
func (c *ClusterClient) processTxPipeline(ctx context.Context, cmds []Cmder) error {
2024-02-18 10:42:21 +00:00
// Trim multi .. exec.
2024-02-18 10:42:21 +00:00
cmds = cmds[1 : len(cmds)-1]
state, err := c.state.Get(ctx)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
setCmdsErr(cmds, err)
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
cmdsMap := c.mapCmdsBySlot(ctx, cmds)
2024-02-18 10:42:21 +00:00
for slot, cmds := range cmdsMap {
2024-02-18 10:42:21 +00:00
node, err := state.slotMasterNode(slot)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
setCmdsErr(cmds, err)
2024-02-18 10:42:21 +00:00
continue
2024-02-18 10:42:21 +00:00
}
cmdsMap := map[*clusterNode][]Cmder{node: cmds}
2024-02-18 10:42:21 +00:00
for attempt := 0; attempt <= c.opt.MaxRedirects; attempt++ {
2024-02-18 10:42:21 +00:00
if attempt > 0 {
2024-02-18 10:42:21 +00:00
if err := internal.Sleep(ctx, c.retryBackoff(attempt)); err != nil {
2024-02-18 10:42:21 +00:00
setCmdsErr(cmds, err)
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
failedCmds := newCmdsMap()
2024-02-18 10:42:21 +00:00
var wg sync.WaitGroup
for node, cmds := range cmdsMap {
2024-02-18 10:42:21 +00:00
wg.Add(1)
2024-02-18 10:42:21 +00:00
go func(node *clusterNode, cmds []Cmder) {
2024-02-18 10:42:21 +00:00
defer wg.Done()
2024-02-18 10:42:21 +00:00
c.processTxPipelineNode(ctx, node, cmds, failedCmds)
2024-02-18 10:42:21 +00:00
}(node, cmds)
2024-02-18 10:42:21 +00:00
}
wg.Wait()
2024-02-18 10:42:21 +00:00
if len(failedCmds.m) == 0 {
2024-02-18 10:42:21 +00:00
break
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
cmdsMap = failedCmds.m
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
return cmdsFirstErr(cmds)
2024-02-18 10:42:21 +00:00
}
func (c *ClusterClient) mapCmdsBySlot(ctx context.Context, cmds []Cmder) map[int][]Cmder {
2024-02-18 10:42:21 +00:00
cmdsMap := make(map[int][]Cmder)
2024-02-18 10:42:21 +00:00
for _, cmd := range cmds {
2024-02-18 10:42:21 +00:00
slot := c.cmdSlot(ctx, cmd)
2024-02-18 10:42:21 +00:00
cmdsMap[slot] = append(cmdsMap[slot], cmd)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return cmdsMap
2024-02-18 10:42:21 +00:00
}
func (c *ClusterClient) processTxPipelineNode(
2024-02-18 10:42:21 +00:00
ctx context.Context, node *clusterNode, cmds []Cmder, failedCmds *cmdsMap,
2024-02-18 10:42:21 +00:00
) {
2024-02-18 10:42:21 +00:00
cmds = wrapMultiExec(ctx, cmds)
2024-02-18 10:42:21 +00:00
_ = node.Client.withProcessPipelineHook(ctx, cmds, func(ctx context.Context, cmds []Cmder) error {
2024-02-18 10:42:21 +00:00
cn, err := node.Client.getConn(ctx)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
_ = c.mapCmdsByNode(ctx, failedCmds, cmds)
2024-02-18 10:42:21 +00:00
setCmdsErr(cmds, err)
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
var processErr error
2024-02-18 10:42:21 +00:00
defer func() {
2024-02-18 10:42:21 +00:00
node.Client.releaseConn(ctx, cn, processErr)
2024-02-18 10:42:21 +00:00
}()
2024-02-18 10:42:21 +00:00
processErr = c.processTxPipelineNodeConn(ctx, node, cn, cmds, failedCmds)
return processErr
2024-02-18 10:42:21 +00:00
})
2024-02-18 10:42:21 +00:00
}
func (c *ClusterClient) processTxPipelineNodeConn(
2024-02-18 10:42:21 +00:00
ctx context.Context, node *clusterNode, cn *pool.Conn, cmds []Cmder, failedCmds *cmdsMap,
2024-02-18 10:42:21 +00:00
) error {
2024-02-18 10:42:21 +00:00
if err := cn.WithWriter(c.context(ctx), c.opt.WriteTimeout, func(wr *proto.Writer) error {
2024-02-18 10:42:21 +00:00
return writeCmds(wr, cmds)
2024-02-18 10:42:21 +00:00
}); err != nil {
2024-02-18 10:42:21 +00:00
if shouldRetry(err, true) {
2024-02-18 10:42:21 +00:00
_ = c.mapCmdsByNode(ctx, failedCmds, cmds)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
setCmdsErr(cmds, err)
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
return cn.WithReader(c.context(ctx), c.opt.ReadTimeout, func(rd *proto.Reader) error {
2024-02-18 10:42:21 +00:00
statusCmd := cmds[0].(*StatusCmd)
2024-02-18 10:42:21 +00:00
// Trim multi and exec.
2024-02-18 10:42:21 +00:00
trimmedCmds := cmds[1 : len(cmds)-1]
if err := c.txPipelineReadQueued(
2024-02-18 10:42:21 +00:00
ctx, rd, statusCmd, trimmedCmds, failedCmds,
); err != nil {
2024-02-18 10:42:21 +00:00
setCmdsErr(cmds, err)
moved, ask, addr := isMovedError(err)
2024-02-18 10:42:21 +00:00
if moved || ask {
2024-02-18 10:42:21 +00:00
return c.cmdsMoved(ctx, trimmedCmds, moved, ask, addr, failedCmds)
2024-02-18 10:42:21 +00:00
}
return err
2024-02-18 10:42:21 +00:00
}
return pipelineReadCmds(rd, trimmedCmds)
2024-02-18 10:42:21 +00:00
})
2024-02-18 10:42:21 +00:00
}
func (c *ClusterClient) txPipelineReadQueued(
2024-02-18 10:42:21 +00:00
ctx context.Context,
2024-02-18 10:42:21 +00:00
rd *proto.Reader,
2024-02-18 10:42:21 +00:00
statusCmd *StatusCmd,
2024-02-18 10:42:21 +00:00
cmds []Cmder,
2024-02-18 10:42:21 +00:00
failedCmds *cmdsMap,
2024-02-18 10:42:21 +00:00
) error {
2024-02-18 10:42:21 +00:00
// Parse queued replies.
2024-02-18 10:42:21 +00:00
if err := statusCmd.readReply(rd); err != nil {
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
for _, cmd := range cmds {
2024-02-18 10:42:21 +00:00
err := statusCmd.readReply(rd)
2024-02-18 10:42:21 +00:00
if err == nil || c.checkMovedErr(ctx, cmd, err, failedCmds) || isRedisError(err) {
2024-02-18 10:42:21 +00:00
continue
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
// Parse number of replies.
2024-02-18 10:42:21 +00:00
line, err := rd.ReadLine()
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
if err == Nil {
2024-02-18 10:42:21 +00:00
err = TxFailedErr
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
if line[0] != proto.RespArray {
2024-02-18 10:42:21 +00:00
return fmt.Errorf("redis: expected '*', but got line %q", line)
2024-02-18 10:42:21 +00:00
}
return nil
2024-02-18 10:42:21 +00:00
}
func (c *ClusterClient) cmdsMoved(
2024-02-18 10:42:21 +00:00
ctx context.Context, cmds []Cmder,
2024-02-18 10:42:21 +00:00
moved, ask bool,
2024-02-18 10:42:21 +00:00
addr string,
2024-02-18 10:42:21 +00:00
failedCmds *cmdsMap,
2024-02-18 10:42:21 +00:00
) error {
2024-02-18 10:42:21 +00:00
node, err := c.nodes.GetOrCreate(addr)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
if moved {
2024-02-18 10:42:21 +00:00
c.state.LazyReload()
2024-02-18 10:42:21 +00:00
for _, cmd := range cmds {
2024-02-18 10:42:21 +00:00
failedCmds.Add(node, cmd)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
if ask {
2024-02-18 10:42:21 +00:00
for _, cmd := range cmds {
2024-02-18 10:42:21 +00:00
failedCmds.Add(node, NewCmd(ctx, "asking"), cmd)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
return nil
2024-02-18 10:42:21 +00:00
}
func (c *ClusterClient) Watch(ctx context.Context, fn func(*Tx) error, keys ...string) error {
2024-02-18 10:42:21 +00:00
if len(keys) == 0 {
2024-02-18 10:42:21 +00:00
return fmt.Errorf("redis: Watch requires at least one key")
2024-02-18 10:42:21 +00:00
}
slot := hashtag.Slot(keys[0])
2024-02-18 10:42:21 +00:00
for _, key := range keys[1:] {
2024-02-18 10:42:21 +00:00
if hashtag.Slot(key) != slot {
2024-02-18 10:42:21 +00:00
err := fmt.Errorf("redis: Watch requires all keys to be in the same slot")
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
node, err := c.slotMasterNode(ctx, slot)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
for attempt := 0; attempt <= c.opt.MaxRedirects; attempt++ {
2024-02-18 10:42:21 +00:00
if attempt > 0 {
2024-02-18 10:42:21 +00:00
if err := internal.Sleep(ctx, c.retryBackoff(attempt)); err != nil {
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
err = node.Client.Watch(ctx, fn, keys...)
2024-02-18 10:42:21 +00:00
if err == nil {
2024-02-18 10:42:21 +00:00
break
2024-02-18 10:42:21 +00:00
}
moved, ask, addr := isMovedError(err)
2024-02-18 10:42:21 +00:00
if moved || ask {
2024-02-18 10:42:21 +00:00
node, err = c.nodes.GetOrCreate(addr)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
continue
2024-02-18 10:42:21 +00:00
}
if isReadOnly := isReadOnlyError(err); isReadOnly || err == pool.ErrClosed {
2024-02-18 10:42:21 +00:00
if isReadOnly {
2024-02-18 10:42:21 +00:00
c.state.LazyReload()
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
node, err = c.slotMasterNode(ctx, slot)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
continue
2024-02-18 10:42:21 +00:00
}
if shouldRetry(err, true) {
2024-02-18 10:42:21 +00:00
continue
2024-02-18 10:42:21 +00:00
}
return err
2024-02-18 10:42:21 +00:00
}
return err
2024-02-18 10:42:21 +00:00
}
func (c *ClusterClient) pubSub() *PubSub {
2024-02-18 10:42:21 +00:00
var node *clusterNode
2024-02-18 10:42:21 +00:00
pubsub := &PubSub{
2024-02-18 10:42:21 +00:00
opt: c.opt.clientOptions(),
newConn: func(ctx context.Context, channels []string) (*pool.Conn, error) {
2024-02-18 10:42:21 +00:00
if node != nil {
2024-02-18 10:42:21 +00:00
panic("node != nil")
2024-02-18 10:42:21 +00:00
}
var err error
2024-02-18 10:42:21 +00:00
if len(channels) > 0 {
2024-02-18 10:42:21 +00:00
slot := hashtag.Slot(channels[0])
2024-02-18 10:42:21 +00:00
node, err = c.slotMasterNode(ctx, slot)
2024-02-18 10:42:21 +00:00
} else {
2024-02-18 10:42:21 +00:00
node, err = c.nodes.Random()
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return nil, err
2024-02-18 10:42:21 +00:00
}
cn, err := node.Client.newConn(context.TODO())
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
node = nil
return nil, err
2024-02-18 10:42:21 +00:00
}
return cn, nil
2024-02-18 10:42:21 +00:00
},
2024-02-18 10:42:21 +00:00
closeConn: func(cn *pool.Conn) error {
2024-02-18 10:42:21 +00:00
err := node.Client.connPool.CloseConn(cn)
2024-02-18 10:42:21 +00:00
node = nil
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
},
}
2024-02-18 10:42:21 +00:00
pubsub.init()
return pubsub
2024-02-18 10:42:21 +00:00
}
// Subscribe subscribes the client to the specified channels.
2024-02-18 10:42:21 +00:00
// Channels can be omitted to create empty subscription.
2024-02-18 10:42:21 +00:00
func (c *ClusterClient) Subscribe(ctx context.Context, channels ...string) *PubSub {
2024-02-18 10:42:21 +00:00
pubsub := c.pubSub()
2024-02-18 10:42:21 +00:00
if len(channels) > 0 {
2024-02-18 10:42:21 +00:00
_ = pubsub.Subscribe(ctx, channels...)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return pubsub
2024-02-18 10:42:21 +00:00
}
// PSubscribe subscribes the client to the given patterns.
2024-02-18 10:42:21 +00:00
// Patterns can be omitted to create empty subscription.
2024-02-18 10:42:21 +00:00
func (c *ClusterClient) PSubscribe(ctx context.Context, channels ...string) *PubSub {
2024-02-18 10:42:21 +00:00
pubsub := c.pubSub()
2024-02-18 10:42:21 +00:00
if len(channels) > 0 {
2024-02-18 10:42:21 +00:00
_ = pubsub.PSubscribe(ctx, channels...)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return pubsub
2024-02-18 10:42:21 +00:00
}
// SSubscribe Subscribes the client to the specified shard channels.
2024-02-18 10:42:21 +00:00
func (c *ClusterClient) SSubscribe(ctx context.Context, channels ...string) *PubSub {
2024-02-18 10:42:21 +00:00
pubsub := c.pubSub()
2024-02-18 10:42:21 +00:00
if len(channels) > 0 {
2024-02-18 10:42:21 +00:00
_ = pubsub.SSubscribe(ctx, channels...)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return pubsub
2024-02-18 10:42:21 +00:00
}
func (c *ClusterClient) retryBackoff(attempt int) time.Duration {
2024-02-18 10:42:21 +00:00
return internal.RetryBackoff(attempt, c.opt.MinRetryBackoff, c.opt.MaxRetryBackoff)
2024-02-18 10:42:21 +00:00
}
func (c *ClusterClient) cmdsInfo(ctx context.Context) (map[string]*CommandInfo, error) {
2024-02-18 10:42:21 +00:00
// Try 3 random nodes.
2024-02-18 10:42:21 +00:00
const nodeLimit = 3
addrs, err := c.nodes.Addrs()
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return nil, err
2024-02-18 10:42:21 +00:00
}
var firstErr error
perm := rand.Perm(len(addrs))
2024-02-18 10:42:21 +00:00
if len(perm) > nodeLimit {
2024-02-18 10:42:21 +00:00
perm = perm[:nodeLimit]
2024-02-18 10:42:21 +00:00
}
for _, idx := range perm {
2024-02-18 10:42:21 +00:00
addr := addrs[idx]
node, err := c.nodes.GetOrCreate(addr)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
if firstErr == nil {
2024-02-18 10:42:21 +00:00
firstErr = err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
continue
2024-02-18 10:42:21 +00:00
}
info, err := node.Client.Command(ctx).Result()
2024-02-18 10:42:21 +00:00
if err == nil {
2024-02-18 10:42:21 +00:00
return info, nil
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if firstErr == nil {
2024-02-18 10:42:21 +00:00
firstErr = err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
if firstErr == nil {
2024-02-18 10:42:21 +00:00
panic("not reached")
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return nil, firstErr
2024-02-18 10:42:21 +00:00
}
func (c *ClusterClient) cmdInfo(ctx context.Context, name string) *CommandInfo {
2024-02-18 10:42:21 +00:00
cmdsInfo, err := c.cmdsInfoCache.Get(ctx)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
internal.Logger.Printf(context.TODO(), "getting command info: %s", err)
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
info := cmdsInfo[name]
2024-02-18 10:42:21 +00:00
if info == nil {
2024-02-18 10:42:21 +00:00
internal.Logger.Printf(context.TODO(), "info for cmd=%s not found", name)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return info
2024-02-18 10:42:21 +00:00
}
func (c *ClusterClient) cmdSlot(ctx context.Context, cmd Cmder) int {
2024-02-18 10:42:21 +00:00
args := cmd.Args()
2024-02-18 10:42:21 +00:00
if args[0] == "cluster" && args[1] == "getkeysinslot" {
2024-02-18 10:42:21 +00:00
return args[2].(int)
2024-02-18 10:42:21 +00:00
}
return cmdSlot(cmd, cmdFirstKeyPos(cmd))
2024-02-18 10:42:21 +00:00
}
func cmdSlot(cmd Cmder, pos int) int {
2024-02-18 10:42:21 +00:00
if pos == 0 {
2024-02-18 10:42:21 +00:00
return hashtag.RandomSlot()
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
firstKey := cmd.stringArg(pos)
2024-02-18 10:42:21 +00:00
return hashtag.Slot(firstKey)
2024-02-18 10:42:21 +00:00
}
func (c *ClusterClient) cmdNode(
2024-02-18 10:42:21 +00:00
ctx context.Context,
2024-02-18 10:42:21 +00:00
cmdName string,
2024-02-18 10:42:21 +00:00
slot int,
2024-02-18 10:42:21 +00:00
) (*clusterNode, error) {
2024-02-18 10:42:21 +00:00
state, err := c.state.Get(ctx)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return nil, err
2024-02-18 10:42:21 +00:00
}
if c.opt.ReadOnly {
2024-02-18 10:42:21 +00:00
cmdInfo := c.cmdInfo(ctx, cmdName)
2024-02-18 10:42:21 +00:00
if cmdInfo != nil && cmdInfo.ReadOnly {
2024-02-18 10:42:21 +00:00
return c.slotReadOnlyNode(state, slot)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return state.slotMasterNode(slot)
2024-02-18 10:42:21 +00:00
}
func (c *ClusterClient) slotReadOnlyNode(state *clusterState, slot int) (*clusterNode, error) {
2024-02-18 10:42:21 +00:00
if c.opt.RouteByLatency {
2024-02-18 10:42:21 +00:00
return state.slotClosestNode(slot)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if c.opt.RouteRandomly {
2024-02-18 10:42:21 +00:00
return state.slotRandomNode(slot)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return state.slotSlaveNode(slot)
2024-02-18 10:42:21 +00:00
}
func (c *ClusterClient) slotMasterNode(ctx context.Context, slot int) (*clusterNode, error) {
2024-02-18 10:42:21 +00:00
state, err := c.state.Get(ctx)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return nil, err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return state.slotMasterNode(slot)
2024-02-18 10:42:21 +00:00
}
// SlaveForKey gets a client for a replica node to run any command on it.
2024-02-18 10:42:21 +00:00
// This is especially useful if we want to run a particular lua script which has
2024-02-18 10:42:21 +00:00
// only read only commands on the replica.
2024-02-18 10:42:21 +00:00
// This is because other redis commands generally have a flag that points that
2024-02-18 10:42:21 +00:00
// they are read only and automatically run on the replica nodes
2024-02-18 10:42:21 +00:00
// if ClusterOptions.ReadOnly flag is set to true.
2024-02-18 10:42:21 +00:00
func (c *ClusterClient) SlaveForKey(ctx context.Context, key string) (*Client, error) {
2024-02-18 10:42:21 +00:00
state, err := c.state.Get(ctx)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return nil, err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
slot := hashtag.Slot(key)
2024-02-18 10:42:21 +00:00
node, err := c.slotReadOnlyNode(state, slot)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return nil, err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return node.Client, err
2024-02-18 10:42:21 +00:00
}
// MasterForKey return a client to the master node for a particular key.
2024-02-18 10:42:21 +00:00
func (c *ClusterClient) MasterForKey(ctx context.Context, key string) (*Client, error) {
2024-02-18 10:42:21 +00:00
slot := hashtag.Slot(key)
2024-02-18 10:42:21 +00:00
node, err := c.slotMasterNode(ctx, slot)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return nil, err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return node.Client, err
2024-02-18 10:42:21 +00:00
}
func (c *ClusterClient) context(ctx context.Context) context.Context {
2024-02-18 10:42:21 +00:00
if c.opt.ContextTimeoutEnabled {
2024-02-18 10:42:21 +00:00
return ctx
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return context.Background()
2024-02-18 10:42:21 +00:00
}
func appendUniqueNode(nodes []*clusterNode, node *clusterNode) []*clusterNode {
2024-02-18 10:42:21 +00:00
for _, n := range nodes {
2024-02-18 10:42:21 +00:00
if n == node {
2024-02-18 10:42:21 +00:00
return nodes
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return append(nodes, node)
2024-02-18 10:42:21 +00:00
}
func appendIfNotExists(ss []string, es ...string) []string {
2024-02-18 10:42:21 +00:00
loop:
2024-02-18 10:42:21 +00:00
for _, e := range es {
2024-02-18 10:42:21 +00:00
for _, s := range ss {
2024-02-18 10:42:21 +00:00
if s == e {
2024-02-18 10:42:21 +00:00
continue loop
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
ss = append(ss, e)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return ss
2024-02-18 10:42:21 +00:00
}
//------------------------------------------------------------------------------
type cmdsMap struct {
mu sync.Mutex
m map[*clusterNode][]Cmder
2024-02-18 10:42:21 +00:00
}
func newCmdsMap() *cmdsMap {
2024-02-18 10:42:21 +00:00
return &cmdsMap{
2024-02-18 10:42:21 +00:00
m: make(map[*clusterNode][]Cmder),
}
2024-02-18 10:42:21 +00:00
}
func (m *cmdsMap) Add(node *clusterNode, cmds ...Cmder) {
2024-02-18 10:42:21 +00:00
m.mu.Lock()
2024-02-18 10:42:21 +00:00
m.m[node] = append(m.m[node], cmds...)
2024-02-18 10:42:21 +00:00
m.mu.Unlock()
2024-02-18 10:42:21 +00:00
}