From c0b792a0592d1a509f04c35f7dc3515739d78c94 Mon Sep 17 00:00:00 2001 From: Vladimir Mihailenco Date: Fri, 23 Sep 2016 11:52:19 +0000 Subject: [PATCH] Don't panic when cluster does not have valid nodes. --- cluster.go | 19 +++++++++++-------- cluster_test.go | 13 +++++++++++++ 2 files changed, 24 insertions(+), 8 deletions(-) diff --git a/cluster.go b/cluster.go index 07de9932..8290db0c 100644 --- a/cluster.go +++ b/cluster.go @@ -160,17 +160,18 @@ func (c *ClusterClient) newNode(addr string) *clusterNode { } } -func (c *ClusterClient) slotNodes(slot int) []*clusterNode { +func (c *ClusterClient) slotNodes(slot int) (nodes []*clusterNode) { c.mu.RLock() - nodes := c.slots[slot] + if slot < len(c.slots) { + nodes = c.slots[slot] + } c.mu.RUnlock() return nodes } // randomNode returns random live node. func (c *ClusterClient) randomNode() (*clusterNode, error) { - var node *clusterNode - var err error + var nodeErr error for i := 0; i < 10; i++ { c.mu.RLock() closed := c.closed @@ -182,16 +183,18 @@ func (c *ClusterClient) randomNode() (*clusterNode, error) { } n := rand.Intn(len(addrs)) - node, err = c.nodeByAddr(addrs[n]) + + node, err := c.nodeByAddr(addrs[n]) if err != nil { return nil, err } - if node.Client.ClusterInfo().Err() == nil { - break + nodeErr = node.Client.ClusterInfo().Err() + if nodeErr == nil { + return node, nil } } - return node, nil + return nil, nodeErr } func (c *ClusterClient) slotMasterNode(slot int) (*clusterNode, error) { diff --git a/cluster_test.go b/cluster_test.go index 17d51133..659e134e 100644 --- a/cluster_test.go +++ b/cluster_test.go @@ -515,6 +515,19 @@ var _ = Describe("ClusterClient", func() { describeClusterClient() }) + + Describe("ClusterClient without valid nodes", func() { + BeforeEach(func() { + client = redis.NewClusterClient(&redis.ClusterOptions{ + Addrs: []string{redisAddr}, + }) + }) + + It("returns an error", func() { + err := client.Ping().Err() + Expect(err).To(MatchError("ERR This instance has cluster support disabled")) + }) + }) }) //------------------------------------------------------------------------------