Debian Codegraph @

cluster_test.go

raw
1 package redis_test
2
3 import (
4 "fmt"
5 "net"
6 "strconv"
7 "strings"
8 "sync"
9 "testing"
10 "time"
11
12 "gopkg.in/redis.v5"
13 "gopkg.in/redis.v5/internal/hashtag"
14
15 . "github.com/onsi/ginkgo"
16 . "github.com/onsi/gomega"
17 )
18
19 type clusterScenario struct {
20 ports []string
21 nodeIds []string
22 processes map[string]*redisProcess
23 clients map[string]*redis.Client
24 }
25
26 func (s *clusterScenario) masters() []*redis.Client {
27 result := make([]*redis.Client, 3)
28 for pos, port := range s.ports[:3] {
29 result[pos] = s.clients[port]
30 }
31 return result
32 }
33
34 func (s *clusterScenario) slaves() []*redis.Client {
35 result := make([]*redis.Client, 3)
36 for pos, port := range s.ports[3:] {
37 result[pos] = s.clients[port]
38 }
39 return result
40 }
41
42 func (s *clusterScenario) clusterClient(opt *redis.ClusterOptions) *redis.ClusterClient {
43 addrs := make([]string, len(s.ports))
44 for i, port := range s.ports {
45 addrs[i] = net.JoinHostPort("127.0.0.1", port)
46 }
47 opt.Addrs = addrs
48 return redis.NewClusterClient(opt)
49 }
50
51 func startCluster(scenario *clusterScenario) error {
52 // Start processes and collect node ids
53 for pos, port := range scenario.ports {
54 process, err := startRedis(port, "--cluster-enabled", "yes")
55 if err != nil {
56 return err
57 }
58
59 client := redis.NewClient(&redis.Options{
60 Addr: ":" + port,
61 })
62
63 info, err := client.ClusterNodes().Result()
64 if err != nil {
65 return err
66 }
67
68 scenario.processes[port] = process
69 scenario.clients[port] = client
70 scenario.nodeIds[pos] = info[:40]
71 }
72
73 // Meet cluster nodes
74 for _, client := range scenario.clients {
75 err := client.ClusterMeet("127.0.0.1", scenario.ports[0]).Err()
76 if err != nil {
77 return err
78 }
79 }
80
81 // Bootstrap masters
82 slots := []int{0, 5000, 10000, 16384}
83 for pos, master := range scenario.masters() {
84 err := master.ClusterAddSlotsRange(slots[pos], slots[pos+1]-1).Err()
85 if err != nil {
86 return err
87 }
88 }
89
90 // Bootstrap slaves
91 for idx, slave := range scenario.slaves() {
92 masterId := scenario.nodeIds[idx]
93
94 // Wait until master is available
95 err := eventually(func() error {
96 s := slave.ClusterNodes().Val()
97 wanted := masterId
98 if !strings.Contains(s, wanted) {
99 return fmt.Errorf("%q does not contain %q", s, wanted)
100 }
101 return nil
102 }, 10*time.Second)
103 if err != nil {
104 return err
105 }
106
107 err = slave.ClusterReplicate(masterId).Err()
108 if err != nil {
109 return err
110 }
111 }
112
113 // Wait until all nodes have consistent info
114 for _, client := range scenario.clients {
115 err := eventually(func() error {
116 res, err := client.ClusterSlots().Result()
117 if err != nil {
118 return err
119 }
120 wanted := []redis.ClusterSlot{
121 {0, 4999, []redis.ClusterNode{{"", "127.0.0.1:8220"}, {"", "127.0.0.1:8223"}}},
122 {5000, 9999, []redis.ClusterNode{{"", "127.0.0.1:8221"}, {"", "127.0.0.1:8224"}}},
123 {10000, 16383, []redis.ClusterNode{{"", "127.0.0.1:8222"}, {"", "127.0.0.1:8225"}}},
124 }
125 return assertSlotsEqual(res, wanted)
126 }, 30*time.Second)
127 if err != nil {
128 return err
129 }
130 }
131
132 return nil
133 }
134
135 func assertSlotsEqual(slots, wanted []redis.ClusterSlot) error {
136 outer_loop:
137 for _, s2 := range wanted {
138 for _, s1 := range slots {
139 if slotEqual(s1, s2) {
140 continue outer_loop
141 }
142 }
143 return fmt.Errorf("%v not found in %v", s2, slots)
144 }
145 return nil
146 }
147
148 func slotEqual(s1, s2 redis.ClusterSlot) bool {
149 if s1.Start != s2.Start {
150 return false
151 }
152 if s1.End != s2.End {
153 return false
154 }
155 if len(s1.Nodes) != len(s2.Nodes) {
156 return false
157 }
158 for i, n1 := range s1.Nodes {
159 if n1.Addr != s2.Nodes[i].Addr {
160 return false
161 }
162 }
163 return true
164 }
165
166 func stopCluster(scenario *clusterScenario) error {
167 for _, client := range scenario.clients {
168 if err := client.Close(); err != nil {
169 return err
170 }
171 }
172 for _, process := range scenario.processes {
173 if err := process.Close(); err != nil {
174 return err
175 }
176 }
177 return nil
178 }
179
180 //------------------------------------------------------------------------------
181
182 var _ = Describe("ClusterClient", func() {
183 var opt *redis.ClusterOptions
184 var client *redis.ClusterClient
185
186 assertClusterClient := func() {
187 It("should CLUSTER SLOTS", func() {
188 res, err := client.ClusterSlots().Result()
189 Expect(err).NotTo(HaveOccurred())
190 Expect(res).To(HaveLen(3))
191
192 wanted := []redis.ClusterSlot{
193 {0, 4999, []redis.ClusterNode{{"", "127.0.0.1:8220"}, {"", "127.0.0.1:8223"}}},
194 {5000, 9999, []redis.ClusterNode{{"", "127.0.0.1:8221"}, {"", "127.0.0.1:8224"}}},
195 {10000, 16383, []redis.ClusterNode{{"", "127.0.0.1:8222"}, {"", "127.0.0.1:8225"}}},
196 }
197 Expect(assertSlotsEqual(res, wanted)).NotTo(HaveOccurred())
198 })
199
200 It("should CLUSTER NODES", func() {
201 res, err := client.ClusterNodes().Result()
202 Expect(err).NotTo(HaveOccurred())
203 Expect(len(res)).To(BeNumerically(">", 400))
204 })
205
206 It("should CLUSTER INFO", func() {
207 res, err := client.ClusterInfo().Result()
208 Expect(err).NotTo(HaveOccurred())
209 Expect(res).To(ContainSubstring("cluster_known_nodes:6"))
210 })
211
212 It("should CLUSTER KEYSLOT", func() {
213 hashSlot, err := client.ClusterKeySlot("somekey").Result()
214 Expect(err).NotTo(HaveOccurred())
215 Expect(hashSlot).To(Equal(int64(hashtag.Slot("somekey"))))
216 })
217
218 It("should CLUSTER COUNT-FAILURE-REPORTS", func() {
219 n, err := client.ClusterCountFailureReports(cluster.nodeIds[0]).Result()
220 Expect(err).NotTo(HaveOccurred())
221 Expect(n).To(Equal(int64(0)))
222 })
223
224 It("should CLUSTER COUNTKEYSINSLOT", func() {
225 n, err := client.ClusterCountKeysInSlot(10).Result()
226 Expect(err).NotTo(HaveOccurred())
227 Expect(n).To(Equal(int64(0)))
228 })
229
230 It("should CLUSTER SAVECONFIG", func() {
231 res, err := client.ClusterSaveConfig().Result()
232 Expect(err).NotTo(HaveOccurred())
233 Expect(res).To(Equal("OK"))
234 })
235
236 It("should CLUSTER SLAVES", func() {
237 nodesList, err := client.ClusterSlaves(cluster.nodeIds[0]).Result()
238 Expect(err).NotTo(HaveOccurred())
239 Expect(nodesList).Should(ContainElement(ContainSubstring("slave")))
240 Expect(nodesList).Should(HaveLen(1))
241 })
242
243 It("should GET/SET/DEL", func() {
244 val, err := client.Get("A").Result()
245 Expect(err).To(Equal(redis.Nil))
246 Expect(val).To(Equal(""))
247
248 val, err = client.Set("A", "VALUE", 0).Result()
249 Expect(err).NotTo(HaveOccurred())
250 Expect(val).To(Equal("OK"))
251
252 val, err = client.Get("A").Result()
253 Expect(err).NotTo(HaveOccurred())
254 Expect(val).To(Equal("VALUE"))
255
256 cnt, err := client.Del("A").Result()
257 Expect(err).NotTo(HaveOccurred())
258 Expect(cnt).To(Equal(int64(1)))
259 })
260
261 It("returns pool stats", func() {
262 Expect(client.PoolStats()).To(BeAssignableToTypeOf(&redis.PoolStats{}))
263 })
264
265 It("removes idle connections", func() {
266 stats := client.PoolStats()
267 Expect(stats.TotalConns).NotTo(BeZero())
268 Expect(stats.FreeConns).NotTo(BeZero())
269
270 time.Sleep(2 * time.Second)
271
272 stats = client.PoolStats()
273 Expect(stats.TotalConns).To(BeZero())
274 Expect(stats.FreeConns).To(BeZero())
275 })
276
277 It("follows redirects", func() {
278 Expect(client.Set("A", "VALUE", 0).Err()).NotTo(HaveOccurred())
279
280 slot := hashtag.Slot("A")
281 Expect(client.SwapSlotNodes(slot)).To(Equal([]string{"127.0.0.1:8224", "127.0.0.1:8221"}))
282
283 val, err := client.Get("A").Result()
284 Expect(err).NotTo(HaveOccurred())
285 Expect(val).To(Equal("VALUE"))
286 })
287
288 It("returns an error when there are no attempts left", func() {
289 opt := redisClusterOptions()
290 opt.MaxRedirects = -1
291 client := cluster.clusterClient(opt)
292
293 slot := hashtag.Slot("A")
294 Expect(client.SwapSlotNodes(slot)).To(Equal([]string{"127.0.0.1:8224", "127.0.0.1:8221"}))
295
296 err := client.Get("A").Err()
297 Expect(err).To(HaveOccurred())
298 Expect(err.Error()).To(ContainSubstring("MOVED"))
299
300 Expect(client.Close()).NotTo(HaveOccurred())
301 })
302
303 It("distributes keys", func() {
304 for i := 0; i < 100; i++ {
305 err := client.Set(fmt.Sprintf("key%d", i), "value", 0).Err()
306 Expect(err).NotTo(HaveOccurred())
307 }
308
309 wanted := []string{"keys=31", "keys=29", "keys=40"}
310 for i, master := range cluster.masters() {
311 Expect(master.Info().Val()).To(ContainSubstring(wanted[i]))
312 }
313 })
314
315 It("distributes keys when using EVAL", func() {
316 script := redis.NewScript(`
317 local r = redis.call('SET', KEYS[1], ARGV[1])
318 return r
319 `)
320
321 var key string
322 for i := 0; i < 100; i++ {
323 key = fmt.Sprintf("key%d", i)
324 err := script.Run(client, []string{key}, "value").Err()
325 Expect(err).NotTo(HaveOccurred())
326 }
327
328 wanted := []string{"keys=31", "keys=29", "keys=40"}
329 for i, master := range cluster.masters() {
330 Expect(master.Info().Val()).To(ContainSubstring(wanted[i]))
331 }
332 })
333
334 It("supports Watch", func() {
335 var incr func(string) error
336
337 // Transactionally increments key using GET and SET commands.
338 incr = func(key string) error {
339 err := client.Watch(func(tx *redis.Tx) error {
340 n, err := tx.Get(key).Int64()
341 if err != nil && err != redis.Nil {
342 return err
343 }
344
345 _, err = tx.Pipelined(func(pipe *redis.Pipeline) error {
346 pipe.Set(key, strconv.FormatInt(n+1, 10), 0)
347 return nil
348 })
349 return err
350 }, key)
351 if err == redis.TxFailedErr {
352 return incr(key)
353 }
354 return err
355 }
356
357 var wg sync.WaitGroup
358 for i := 0; i < 100; i++ {
359 wg.Add(1)
360 go func() {
361 defer GinkgoRecover()
362 defer wg.Done()
363
364 err := incr("key")
365 Expect(err).NotTo(HaveOccurred())
366 }()
367 }
368 wg.Wait()
369
370 n, err := client.Get("key").Int64()
371 Expect(err).NotTo(HaveOccurred())
372 Expect(n).To(Equal(int64(100)))
373 })
374
375 Describe("pipelining", func() {
376 var pipe *redis.Pipeline
377
378 assertPipeline := func() {
379 keys := []string{"A", "B", "C", "D", "E", "F", "G"}
380
381 It("follows redirects", func() {
382 for _, key := range keys {
383 slot := hashtag.Slot(key)
384 client.SwapSlotNodes(slot)
385 }
386
387 for i, key := range keys {
388 pipe.Set(key, key+"_value", 0)
389 pipe.Expire(key, time.Duration(i+1)*time.Hour)
390 }
391 cmds, err := pipe.Exec()
392 Expect(err).NotTo(HaveOccurred())
393 Expect(cmds).To(HaveLen(14))
394
395 if opt.RouteByLatency {
396 return
397 }
398
399 for _, key := range keys {
400 slot := hashtag.Slot(key)
401 client.SwapSlotNodes(slot)
402 }
403
404 for _, key := range keys {
405 pipe.Get(key)
406 pipe.TTL(key)
407 }
408 cmds, err = pipe.Exec()
409 Expect(err).NotTo(HaveOccurred())
410 Expect(cmds).To(HaveLen(14))
411
412 for i, key := range keys {
413 get := cmds[i*2].(*redis.StringCmd)
414 Expect(get.Val()).To(Equal(key + "_value"))
415
416 ttl := cmds[(i*2)+1].(*redis.DurationCmd)
417 Expect(ttl.Val()).To(BeNumerically("~", time.Duration(i+1)*time.Hour, time.Second))
418 }
419 })
420
421 It("works with missing keys", func() {
422 pipe.Set("A", "A_value", 0)
423 pipe.Set("C", "C_value", 0)
424 _, err := pipe.Exec()
425 Expect(err).NotTo(HaveOccurred())
426
427 a := pipe.Get("A")
428 b := pipe.Get("B")
429 c := pipe.Get("C")
430 cmds, err := pipe.Exec()
431 Expect(err).To(Equal(redis.Nil))
432 Expect(cmds).To(HaveLen(3))
433
434 Expect(a.Err()).NotTo(HaveOccurred())
435 Expect(a.Val()).To(Equal("A_value"))
436
437 Expect(b.Err()).To(Equal(redis.Nil))
438 Expect(b.Val()).To(Equal(""))
439
440 Expect(c.Err()).NotTo(HaveOccurred())
441 Expect(c.Val()).To(Equal("C_value"))
442 })
443 }
444
445 Describe("Pipeline", func() {
446 BeforeEach(func() {
447 pipe = client.Pipeline()
448 })
449
450 AfterEach(func() {
451 Expect(pipe.Close()).NotTo(HaveOccurred())
452 })
453
454 assertPipeline()
455 })
456
457 Describe("TxPipeline", func() {
458 BeforeEach(func() {
459 pipe = client.TxPipeline()
460 })
461
462 AfterEach(func() {
463 Expect(pipe.Close()).NotTo(HaveOccurred())
464 })
465
466 assertPipeline()
467 })
468 })
469
470 It("calls fn for every master node", func() {
471 for i := 0; i < 10; i++ {
472 Expect(client.Set(strconv.Itoa(i), "", 0).Err()).NotTo(HaveOccurred())
473 }
474
475 err := client.ForEachMaster(func(master *redis.Client) error {
476 return master.FlushDb().Err()
477 })
478 Expect(err).NotTo(HaveOccurred())
479
480 for _, client := range cluster.masters() {
481 keys, err := client.Keys("*").Result()
482 Expect(err).NotTo(HaveOccurred())
483 Expect(keys).To(HaveLen(0))
484 }
485 })
486 }
487
488 Describe("default ClusterClient", func() {
489 BeforeEach(func() {
490 opt = redisClusterOptions()
491 client = cluster.clusterClient(opt)
492
493 _ = client.ForEachMaster(func(master *redis.Client) error {
494 return master.FlushDb().Err()
495 })
496 })
497
498 AfterEach(func() {
499 Expect(client.Close()).NotTo(HaveOccurred())
500 })
501
502 assertClusterClient()
503 })
504
505 Describe("ClusterClient with RouteByLatency", func() {
506 BeforeEach(func() {
507 opt = redisClusterOptions()
508 opt.RouteByLatency = true
509 client = cluster.clusterClient(opt)
510
511 _ = client.ForEachMaster(func(master *redis.Client) error {
512 return master.FlushDb().Err()
513 })
514 })
515
516 AfterEach(func() {
517 client.FlushDb()
518 Expect(client.Close()).NotTo(HaveOccurred())
519 })
520
521 assertClusterClient()
522 })
523 })
524
525 var _ = Describe("ClusterClient without nodes", func() {
526 var client *redis.ClusterClient
527
528 BeforeEach(func() {
529 client = redis.NewClusterClient(&redis.ClusterOptions{})
530 })
531
532 AfterEach(func() {
533 Expect(client.Close()).NotTo(HaveOccurred())
534 })
535
536 It("returns an error", func() {
537 err := client.Ping().Err()
538 Expect(err).To(MatchError("redis: cluster has no nodes"))
539 })
540
541 It("pipeline returns an error", func() {
542 _, err := client.Pipelined(func(pipe *redis.Pipeline) error {
543 pipe.Ping()
544 return nil
545 })
546 Expect(err).To(MatchError("redis: cluster has no nodes"))
547 })
548 })
549
550 var _ = Describe("ClusterClient without valid nodes", func() {
551 var client *redis.ClusterClient
552
553 BeforeEach(func() {
554 client = redis.NewClusterClient(&redis.ClusterOptions{
555 Addrs: []string{redisAddr},
556 })
557 })
558
559 AfterEach(func() {
560 Expect(client.Close()).NotTo(HaveOccurred())
561 })
562
563 It("returns an error", func() {
564 err := client.Ping().Err()
565 Expect(err).To(MatchError("ERR This instance has cluster support disabled"))
566 })
567
568 It("pipeline returns an error", func() {
569 _, err := client.Pipelined(func(pipe *redis.Pipeline) error {
570 pipe.Ping()
571 return nil
572 })
573 Expect(err).To(MatchError("ERR This instance has cluster support disabled"))
574 })
575 })
576
577 var _ = Describe("ClusterClient timeout", func() {
578 var client *redis.ClusterClient
579
580 AfterEach(func() {
581 _ = client.Close()
582 })
583
584 testTimeout := func() {
585 It("Ping timeouts", func() {
586 err := client.Ping().Err()
587 Expect(err).To(HaveOccurred())
588 Expect(err.(net.Error).Timeout()).To(BeTrue())
589 })
590
591 It("Pipeline timeouts", func() {
592 _, err := client.Pipelined(func(pipe *redis.Pipeline) error {
593 pipe.Ping()
594 return nil
595 })
596 Expect(err).To(HaveOccurred())
597 Expect(err.(net.Error).Timeout()).To(BeTrue())
598 })
599
600 It("Tx timeouts", func() {
601 err := client.Watch(func(tx *redis.Tx) error {
602 return tx.Ping().Err()
603 })
604 Expect(err).To(HaveOccurred())
605 Expect(err.(net.Error).Timeout()).To(BeTrue())
606 })
607
608 It("Tx Pipeline timeouts", func() {
609 err := client.Watch(func(tx *redis.Tx) error {
610 _, err := tx.Pipelined(func(pipe *redis.Pipeline) error {
611 pipe.Ping()
612 return nil
613 })
614 return err
615 })
616 Expect(err).To(HaveOccurred())
617 Expect(err.(net.Error).Timeout()).To(BeTrue())
618 })
619 }
620
621 Context("read timeout", func() {
622 BeforeEach(func() {
623 opt := redisClusterOptions()
624 opt.ReadTimeout = time.Nanosecond
625 opt.WriteTimeout = -1
626 client = cluster.clusterClient(opt)
627 })
628
629 testTimeout()
630 })
631
632 Context("write timeout", func() {
633 BeforeEach(func() {
634 opt := redisClusterOptions()
635 opt.ReadTimeout = time.Nanosecond
636 opt.WriteTimeout = -1
637 client = cluster.clusterClient(opt)
638 })
639
640 testTimeout()
641 })
642
643 Context("network timeout", func() {
644 const pause = time.Second
645
646 BeforeEach(func() {
647 opt := redisClusterOptions()
648 opt.ReadTimeout = 100 * time.Millisecond
649 opt.WriteTimeout = 100 * time.Millisecond
650 opt.MaxRedirects = 1
651 client = cluster.clusterClient(opt)
652
653 err := client.ForEachNode(func(client *redis.Client) error {
654 return client.ClientPause(pause).Err()
655 })
656 Expect(err).NotTo(HaveOccurred())
657 })
658
659 AfterEach(func() {
660 Eventually(func() error {
661 return client.ForEachNode(func(client *redis.Client) error {
662 return client.Ping().Err()
663 })
664 }, 2*pause).ShouldNot(HaveOccurred())
665 })
666
667 testTimeout()
668 })
669 })
670
671 //------------------------------------------------------------------------------
672
673 func BenchmarkRedisClusterPing(b *testing.B) {
674 if testing.Short() {
675 b.Skip("skipping in short mode")
676 }
677
678 cluster := &clusterScenario{
679 ports: []string{"8220", "8221", "8222", "8223", "8224", "8225"},
680 nodeIds: make([]string, 6),
681 processes: make(map[string]*redisProcess, 6),
682 clients: make(map[string]*redis.Client, 6),
683 }
684
685 if err := startCluster(cluster); err != nil {
686 b.Fatal(err)
687 }
688 defer stopCluster(cluster)
689
690 client := cluster.clusterClient(redisClusterOptions())
691 defer client.Close()
692
693 b.ResetTimer()
694
695 b.RunParallel(func(pb *testing.PB) {
696 for pb.Next() {
697 if err := client.Ping().Err(); err != nil {
698 b.Fatal(err)
699 }
700 }
701 })
702 }