forked from redis/redis-py
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_cluster.py
3549 lines (3118 loc) · 131 KB
/
test_cluster.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import binascii
import datetime
import select
import socket
import socketserver
import threading
from typing import List
import warnings
from queue import LifoQueue, Queue
from time import sleep
from unittest.mock import DEFAULT, Mock, call, patch
import pytest
import redis
from redis import Redis
from redis._parsers import CommandsParser
from redis.backoff import ExponentialBackoff, NoBackoff, default_backoff
from redis.cluster import (
PRIMARY,
REDIS_CLUSTER_HASH_SLOTS,
REPLICA,
ClusterNode,
LoadBalancingStrategy,
NodesManager,
RedisCluster,
get_node_name,
)
from redis.connection import BlockingConnectionPool, Connection, ConnectionPool
from redis.crc import key_slot
from redis.exceptions import (
AskError,
ClusterDownError,
ConnectionError,
DataError,
MovedError,
NoPermissionError,
RedisClusterException,
RedisError,
ResponseError,
TimeoutError,
)
from redis.retry import Retry
from redis.utils import str_if_bytes
from tests.test_pubsub import wait_for_message
from .conftest import (
_get_client,
assert_resp_response,
is_resp2_connection,
skip_if_redis_enterprise,
skip_if_server_version_lt,
skip_unless_arch_bits,
wait_for_command,
)
default_host = "127.0.0.1"
default_port = 7000
default_cluster_slots = [
[0, 8191, ["127.0.0.1", 7000, "node_0"], ["127.0.0.1", 7003, "node_3"]],
[8192, 16383, ["127.0.0.1", 7001, "node_1"], ["127.0.0.1", 7002, "node_2"]],
]
class ProxyRequestHandler(socketserver.BaseRequestHandler):
def recv(self, sock):
"""A recv with a timeout"""
r = select.select([sock], [], [], 0.01)
if not r[0]:
return None
return sock.recv(1000)
def handle(self):
self.server.proxy.n_connections += 1
conn = socket.create_connection(self.server.proxy.redis_addr)
stop = False
def from_server():
# read from server and pass to client
while not stop:
data = self.recv(conn)
if data is None:
continue
if not data:
self.request.shutdown(socket.SHUT_WR)
return
self.request.sendall(data)
thread = threading.Thread(target=from_server)
thread.start()
try:
while True:
# read from client and send to server
data = self.request.recv(1000)
if not data:
return
conn.sendall(data)
finally:
conn.shutdown(socket.SHUT_WR)
stop = True # for safety
thread.join()
conn.close()
class NodeProxy:
"""A class to proxy a node connection to a different port"""
def __init__(self, addr, redis_addr):
self.addr = addr
self.redis_addr = redis_addr
self.server = socketserver.ThreadingTCPServer(self.addr, ProxyRequestHandler)
self.server.proxy = self
self.server.socket_reuse_address = True
self.thread = None
self.n_connections = 0
def start(self):
# test that we can connect to redis
s = socket.create_connection(self.redis_addr, timeout=2)
s.close()
# Start a thread with the server -- that thread will then start one
# more thread for each request
self.thread = threading.Thread(target=self.server.serve_forever)
# Exit the server thread when the main thread terminates
self.thread.daemon = True
self.thread.start()
def close(self):
self.server.shutdown()
@pytest.fixture()
def slowlog(request, r):
"""
Set the slowlog threshold to 0, and the
max length to 128. This will force every
command into the slowlog and allow us
to test it
"""
# Save old values
current_config = r.config_get(target_nodes=r.get_primaries()[0])
old_slower_than_value = current_config["slowlog-log-slower-than"]
old_max_legnth_value = current_config["slowlog-max-len"]
# Function to restore the old values
def cleanup():
r.config_set("slowlog-log-slower-than", old_slower_than_value)
r.config_set("slowlog-max-len", old_max_legnth_value)
request.addfinalizer(cleanup)
# Set the new values
r.config_set("slowlog-log-slower-than", 0)
r.config_set("slowlog-max-len", 128)
def get_mocked_redis_client(
func=None, cluster_slots_raise_error=False, *args, **kwargs
):
"""
Return a stable RedisCluster object that have deterministic
nodes and slots setup to remove the problem of different IP addresses
on different installations and machines.
"""
cluster_slots = kwargs.pop("cluster_slots", default_cluster_slots)
coverage_res = kwargs.pop("coverage_result", "yes")
cluster_enabled = kwargs.pop("cluster_enabled", True)
with patch.object(Redis, "execute_command") as execute_command_mock:
def execute_command(*_args, **_kwargs):
if _args[0] == "CLUSTER SLOTS":
if cluster_slots_raise_error:
raise ResponseError()
else:
mock_cluster_slots = cluster_slots
return mock_cluster_slots
elif _args[0] == "COMMAND":
return {"get": [], "set": []}
elif _args[0] == "INFO":
return {"cluster_enabled": cluster_enabled}
elif len(_args) > 1 and _args[1] == "cluster-require-full-coverage":
return {"cluster-require-full-coverage": coverage_res}
elif func is not None:
return func(*args, **kwargs)
else:
return execute_command_mock(*_args, **_kwargs)
execute_command_mock.side_effect = execute_command
with patch.object(
CommandsParser, "initialize", autospec=True
) as cmd_parser_initialize:
def cmd_init_mock(self, r):
self.commands = {
"get": {
"name": "get",
"arity": 2,
"flags": ["readonly", "fast"],
"first_key_pos": 1,
"last_key_pos": 1,
"step_count": 1,
}
}
cmd_parser_initialize.side_effect = cmd_init_mock
# Create a subclass of RedisCluster that overrides __del__
class MockedRedisCluster(RedisCluster):
def __del__(self):
# Override to prevent connection cleanup attempts
pass
@property
def connection_pool(self):
# Required abstract property implementation
return self.nodes_manager.get_default_node().redis_connection.connection_pool
return MockedRedisCluster(*args, **kwargs)
def mock_node_resp(node, response):
connection = Mock()
connection.read_response.return_value = response
node.redis_connection.connection = connection
return node
def mock_node_resp_func(node, func):
connection = Mock()
connection.read_response.side_effect = func
node.redis_connection.connection = connection
return node
def mock_all_nodes_resp(rc, response):
for node in rc.get_nodes():
mock_node_resp(node, response)
return rc
def find_node_ip_based_on_port(cluster_client, port):
for node in cluster_client.get_nodes():
if node.port == port:
return node.host
def moved_redirection_helper(request, failover=False):
"""
Test that the client handles MOVED response after a failover.
Redirection after a failover means that the redirection address is of a
replica that was promoted to a primary.
At first call it should return a MOVED ResponseError that will point
the client to the next server it should talk to.
Verify that:
1. it tries to talk to the redirected node
2. it updates the slot's primary to the redirected node
For a failover, also verify:
3. the redirected node's server type updated to 'primary'
4. the server type of the previous slot owner updated to 'replica'
"""
rc = _get_client(RedisCluster, request, flushdb=False)
slot = 12182
redirect_node = None
# Get the current primary that holds this slot
prev_primary = rc.nodes_manager.get_node_from_slot(slot)
if failover:
if len(rc.nodes_manager.slots_cache[slot]) < 2:
warnings.warn("Skipping this test since it requires to have a replica")
return
redirect_node = rc.nodes_manager.slots_cache[slot][1]
else:
# Use one of the primaries to be the redirected node
redirect_node = rc.get_primaries()[0]
r_host = redirect_node.host
r_port = redirect_node.port
with patch.object(Redis, "parse_response") as parse_response:
def moved_redirect_effect(connection, *args, **options):
def ok_response(connection, *args, **options):
assert connection.host == r_host
assert connection.port == r_port
return "MOCK_OK"
parse_response.side_effect = ok_response
raise MovedError(f"{slot} {r_host}:{r_port}")
parse_response.side_effect = moved_redirect_effect
assert rc.execute_command("SET", "foo", "bar") == "MOCK_OK"
slot_primary = rc.nodes_manager.slots_cache[slot][0]
assert slot_primary == redirect_node
if failover:
assert rc.get_node(host=r_host, port=r_port).server_type == PRIMARY
assert prev_primary.server_type == REPLICA
@pytest.mark.onlycluster
class TestRedisClusterObj:
"""
Tests for the RedisCluster class
"""
def test_host_port_startup_node(self):
"""
Test that it is possible to use host & port arguments as startup node
args
"""
cluster = get_mocked_redis_client(host=default_host, port=default_port)
assert cluster.get_node(host=default_host, port=default_port) is not None
def test_startup_nodes(self):
"""
Test that it is possible to use startup_nodes
argument to init the cluster
"""
port_1 = 7000
port_2 = 7001
startup_nodes = [
ClusterNode(default_host, port_1),
ClusterNode(default_host, port_2),
]
cluster = get_mocked_redis_client(startup_nodes=startup_nodes)
assert (
cluster.get_node(host=default_host, port=port_1) is not None
and cluster.get_node(host=default_host, port=port_2) is not None
)
def test_empty_startup_nodes(self):
"""
Test that exception is raised when empty providing empty startup_nodes
"""
with pytest.raises(RedisClusterException) as ex:
RedisCluster(startup_nodes=[])
assert str(ex.value).startswith(
"RedisCluster requires at least one node to discover the cluster"
), str_if_bytes(ex.value)
def test_from_url(self, r):
redis_url = f"redis://{default_host}:{default_port}/0"
with patch.object(RedisCluster, "from_url") as from_url:
def from_url_mocked(_url, **_kwargs):
return get_mocked_redis_client(url=_url, **_kwargs)
from_url.side_effect = from_url_mocked
cluster = RedisCluster.from_url(redis_url)
assert cluster.get_node(host=default_host, port=default_port) is not None
def test_execute_command_errors(self, r):
"""
Test that if no key is provided then exception should be raised.
"""
with pytest.raises(RedisClusterException) as ex:
r.execute_command("GET")
assert str(ex.value).startswith(
"No way to dispatch this command to Redis Cluster. Missing key."
)
def test_execute_command_node_flag_primaries(self, r):
"""
Test command execution with nodes flag PRIMARIES
"""
primaries = r.get_primaries()
replicas = r.get_replicas()
mock_all_nodes_resp(r, "PONG")
assert r.ping(target_nodes=RedisCluster.PRIMARIES) is True
for primary in primaries:
conn = primary.redis_connection.connection
assert conn.read_response.called is True
for replica in replicas:
conn = replica.redis_connection.connection
assert conn.read_response.called is not True
def test_execute_command_node_flag_replicas(self, r):
"""
Test command execution with nodes flag REPLICAS
"""
replicas = r.get_replicas()
if not replicas:
r = get_mocked_redis_client(default_host, default_port)
primaries = r.get_primaries()
mock_all_nodes_resp(r, "PONG")
assert r.ping(target_nodes=RedisCluster.REPLICAS) is True
for replica in replicas:
conn = replica.redis_connection.connection
assert conn.read_response.called is True
for primary in primaries:
conn = primary.redis_connection.connection
assert conn.read_response.called is not True
def test_execute_command_node_flag_all_nodes(self, r):
"""
Test command execution with nodes flag ALL_NODES
"""
mock_all_nodes_resp(r, "PONG")
assert r.ping(target_nodes=RedisCluster.ALL_NODES) is True
for node in r.get_nodes():
conn = node.redis_connection.connection
assert conn.read_response.called is True
def test_execute_command_node_flag_random(self, r):
"""
Test command execution with nodes flag RANDOM
"""
mock_all_nodes_resp(r, "PONG")
assert r.ping(target_nodes=RedisCluster.RANDOM) is True
called_count = 0
for node in r.get_nodes():
conn = node.redis_connection.connection
if conn.read_response.called is True:
called_count += 1
assert called_count == 1
def test_execute_command_default_node(self, r):
"""
Test command execution without node flag is being executed on the
default node
"""
def_node = r.get_default_node()
mock_node_resp(def_node, "PONG")
assert r.ping() is True
conn = def_node.redis_connection.connection
assert conn.read_response.called
def test_ask_redirection(self, r):
"""
Test that the server handles ASK response.
At first call it should return a ASK ResponseError that will point
the client to the next server it should talk to.
Important thing to verify is that it tries to talk to the second node.
"""
redirect_node = r.get_nodes()[0]
with patch.object(Redis, "parse_response") as parse_response:
def ask_redirect_effect(connection, *args, **options):
def ok_response(connection, *args, **options):
assert connection.host == redirect_node.host
assert connection.port == redirect_node.port
return "MOCK_OK"
parse_response.side_effect = ok_response
raise AskError(f"12182 {redirect_node.host}:{redirect_node.port}")
parse_response.side_effect = ask_redirect_effect
assert r.execute_command("SET", "foo", "bar") == "MOCK_OK"
def test_handling_cluster_failover_to_a_replica(self, r):
# Set the key we'll test for
key = "key"
r.set("key", "value")
primary = r.get_node_from_key(key, replica=False)
assert str_if_bytes(r.get("key")) == "value"
# Get the current output of cluster slots
cluster_slots = primary.redis_connection.execute_command("CLUSTER SLOTS")
replica_host = ""
replica_port = 0
# Replace one of the replicas to be the new primary based on the
# cluster slots output
for slot_range in cluster_slots:
primary_port = slot_range[2][1]
if primary_port == primary.port:
if len(slot_range) <= 3:
# cluster doesn't have a replica, return
return
replica_host = str_if_bytes(slot_range[3][0])
replica_port = slot_range[3][1]
# replace replica and primary in the cluster slots output
tmp_node = slot_range[2]
slot_range[2] = slot_range[3]
slot_range[3] = tmp_node
break
def raise_connection_error():
raise ConnectionError("error")
def mock_execute_command(*_args, **_kwargs):
if _args[0] == "CLUSTER SLOTS":
return cluster_slots
else:
raise Exception("Failed to mock cluster slots")
# Mock connection error for the current primary
mock_node_resp_func(primary, raise_connection_error)
primary.redis_connection.set_retry(Retry(NoBackoff(), 1))
# Mock the cluster slots response for all other nodes
redis_mock_node = Mock()
redis_mock_node.execute_command.side_effect = mock_execute_command
# Mock response value for all other commands
redis_mock_node.parse_response.return_value = "MOCK_OK"
for node in r.get_nodes():
if node.port != primary.port:
node.redis_connection = redis_mock_node
assert r.get(key) == "MOCK_OK"
new_primary = r.get_node_from_key(key, replica=False)
assert new_primary.host == replica_host
assert new_primary.port == replica_port
assert r.get_node(primary.host, primary.port).server_type == REPLICA
def test_moved_redirection(self, request):
"""
Test that the client handles MOVED response.
"""
moved_redirection_helper(request, failover=False)
def test_moved_redirection_after_failover(self, request):
"""
Test that the client handles MOVED response after a failover.
"""
moved_redirection_helper(request, failover=True)
def test_refresh_using_specific_nodes(self, request):
"""
Test making calls on specific nodes when the cluster has failed over to
another node
"""
node_7006 = ClusterNode(host=default_host, port=7006, server_type=PRIMARY)
node_7007 = ClusterNode(host=default_host, port=7007, server_type=PRIMARY)
with patch.object(Redis, "parse_response") as parse_response:
with patch.object(NodesManager, "initialize", autospec=True) as initialize:
with patch.multiple(
Connection, send_command=DEFAULT, connect=DEFAULT, can_read=DEFAULT
) as mocks:
# simulate 7006 as a failed node
def parse_response_mock(connection, command_name, **options):
if connection.port == 7006:
parse_response.failed_calls += 1
raise ClusterDownError(
"CLUSTERDOWN The cluster is "
"down. Use CLUSTER INFO for "
"more information"
)
elif connection.port == 7007:
parse_response.successful_calls += 1
def initialize_mock(self):
# start with all slots mapped to 7006
self.nodes_cache = {node_7006.name: node_7006}
self.default_node = node_7006
self.slots_cache = {}
for i in range(0, 16383):
self.slots_cache[i] = [node_7006]
# After the first connection fails, a reinitialize
# should follow the cluster to 7007
def map_7007(self):
self.nodes_cache = {node_7007.name: node_7007}
self.default_node = node_7007
self.slots_cache = {}
for i in range(0, 16383):
self.slots_cache[i] = [node_7007]
# Change initialize side effect for the second call
initialize.side_effect = map_7007
parse_response.side_effect = parse_response_mock
parse_response.successful_calls = 0
parse_response.failed_calls = 0
initialize.side_effect = initialize_mock
mocks["can_read"].return_value = False
mocks["send_command"].return_value = "MOCK_OK"
mocks["connect"].return_value = None
with patch.object(
CommandsParser, "initialize", autospec=True
) as cmd_parser_initialize:
def cmd_init_mock(self, r):
self.commands = {
"get": {
"name": "get",
"arity": 2,
"flags": ["readonly", "fast"],
"first_key_pos": 1,
"last_key_pos": 1,
"step_count": 1,
}
}
cmd_parser_initialize.side_effect = cmd_init_mock
rc = _get_client(RedisCluster, request, flushdb=False)
assert len(rc.get_nodes()) == 1
assert rc.get_node(node_name=node_7006.name) is not None
rc.get("foo")
# Cluster should now point to 7007, and there should be
# one failed and one successful call
assert len(rc.get_nodes()) == 1
assert rc.get_node(node_name=node_7007.name) is not None
assert rc.get_node(node_name=node_7006.name) is None
assert parse_response.failed_calls == 1
assert parse_response.successful_calls == 1
@pytest.mark.parametrize(
"read_from_replicas,load_balancing_strategy,mocks_srv_ports",
[
(True, None, [7001, 7002, 7001]),
(True, LoadBalancingStrategy.ROUND_ROBIN, [7001, 7002, 7001]),
(True, LoadBalancingStrategy.ROUND_ROBIN_REPLICAS, [7002, 7002, 7002]),
(True, LoadBalancingStrategy.RANDOM_REPLICA, [7002, 7002, 7002]),
(False, LoadBalancingStrategy.ROUND_ROBIN, [7001, 7002, 7001]),
(False, LoadBalancingStrategy.ROUND_ROBIN_REPLICAS, [7002, 7002, 7002]),
(False, LoadBalancingStrategy.RANDOM_REPLICA, [7002, 7002, 7002]),
],
)
def test_reading_with_load_balancing_strategies(
self,
read_from_replicas: bool,
load_balancing_strategy: LoadBalancingStrategy,
mocks_srv_ports: List[int],
):
with patch.multiple(
Connection,
send_command=DEFAULT,
read_response=DEFAULT,
_connect=DEFAULT,
can_read=DEFAULT,
on_connect=DEFAULT,
) as mocks:
with patch.object(Redis, "parse_response") as parse_response:
def parse_response_mock_first(connection, *args, **options):
# Primary
assert connection.port == mocks_srv_ports[0]
parse_response.side_effect = parse_response_mock_second
return "MOCK_OK"
def parse_response_mock_second(connection, *args, **options):
# Replica
assert connection.port == mocks_srv_ports[1]
parse_response.side_effect = parse_response_mock_third
return "MOCK_OK"
def parse_response_mock_third(connection, *args, **options):
# Primary
assert connection.port == mocks_srv_ports[2]
return "MOCK_OK"
# We don't need to create a real cluster connection but we
# do want RedisCluster.on_connect function to get called,
# so we'll mock some of the Connection's functions to allow it
parse_response.side_effect = parse_response_mock_first
mocks["send_command"].return_value = True
mocks["read_response"].return_value = "OK"
mocks["_connect"].return_value = True
mocks["can_read"].return_value = False
mocks["on_connect"].return_value = True
# Create a cluster with reading from replications
read_cluster = get_mocked_redis_client(
host=default_host,
port=default_port,
read_from_replicas=read_from_replicas,
load_balancing_strategy=load_balancing_strategy,
)
assert read_cluster.read_from_replicas is read_from_replicas
assert read_cluster.load_balancing_strategy is load_balancing_strategy
# Check that we read from the slot's nodes in a round robin
# matter.
# 'foo' belongs to slot 12182 and the slot's nodes are:
# [(127.0.0.1,7001,primary), (127.0.0.1,7002,replica)]
read_cluster.get("foo")
read_cluster.get("foo")
read_cluster.get("foo")
expected_calls_list = []
expected_calls_list.append(call("READONLY"))
expected_calls_list.append(call("GET", "foo", keys=["foo"]))
if (
load_balancing_strategy is None
or load_balancing_strategy == LoadBalancingStrategy.ROUND_ROBIN
):
# in the round robin strategy the primary node can also receive read
# requests and this means that there will be second node connected
expected_calls_list.append(call("READONLY"))
expected_calls_list.extend(
[
call("GET", "foo", keys=["foo"]),
call("GET", "foo", keys=["foo"]),
]
)
mocks["send_command"].assert_has_calls(expected_calls_list)
def test_keyslot(self, r):
"""
Test that method will compute correct key in all supported cases
"""
assert r.keyslot("foo") == 12182
assert r.keyslot("{foo}bar") == 12182
assert r.keyslot("{foo}") == 12182
assert r.keyslot(1337) == 4314
assert r.keyslot(125) == r.keyslot(b"125")
assert r.keyslot(125) == r.keyslot("\x31\x32\x35")
assert r.keyslot("大奖") == r.keyslot(b"\xe5\xa4\xa7\xe5\xa5\x96")
assert r.keyslot("大奖") == r.keyslot(b"\xe5\xa4\xa7\xe5\xa5\x96")
assert r.keyslot(1337.1234) == r.keyslot("1337.1234")
assert r.keyslot(1337) == r.keyslot("1337")
assert r.keyslot(b"abc") == r.keyslot("abc")
def test_get_node_name(self):
assert (
get_node_name(default_host, default_port)
== f"{default_host}:{default_port}"
)
def test_all_nodes(self, r):
"""
Set a list of nodes and it should be possible to iterate over all
"""
nodes = [node for node in r.nodes_manager.nodes_cache.values()]
for i, node in enumerate(r.get_nodes()):
assert node in nodes
def test_all_nodes_masters(self, r):
"""
Set a list of nodes with random primaries/replicas config and it shold
be possible to iterate over all of them.
"""
nodes = [
node
for node in r.nodes_manager.nodes_cache.values()
if node.server_type == PRIMARY
]
for node in r.get_primaries():
assert node in nodes
@pytest.mark.parametrize("error", RedisCluster.ERRORS_ALLOW_RETRY)
def test_cluster_down_overreaches_retry_attempts(self, error):
"""
When error that allows retry is thrown, test that we retry executing
the command as many times as configured in cluster_error_retry_attempts
and then raise the exception
"""
with patch.object(RedisCluster, "_execute_command") as execute_command:
def raise_error(target_node, *args, **kwargs):
execute_command.failed_calls += 1
raise error("mocked error")
execute_command.side_effect = raise_error
rc = get_mocked_redis_client(host=default_host, port=default_port)
with pytest.raises(error):
rc.get("bar")
assert execute_command.failed_calls == rc.cluster_error_retry_attempts
def test_user_on_connect_function(self, request):
"""
Test support in passing on_connect function by the user
"""
def on_connect(connection):
assert connection is not None
mock = Mock(side_effect=on_connect)
_get_client(RedisCluster, request, redis_connect_func=mock)
assert mock.called is True
def test_set_default_node_success(self, r):
"""
test successful replacement of the default cluster node
"""
default_node = r.get_default_node()
# get a different node
new_def_node = None
for node in r.get_nodes():
if node != default_node:
new_def_node = node
break
assert r.set_default_node(new_def_node) is True
assert r.get_default_node() == new_def_node
def test_set_default_node_failure(self, r):
"""
test failed replacement of the default cluster node
"""
default_node = r.get_default_node()
new_def_node = ClusterNode("1.1.1.1", 1111)
assert r.set_default_node(None) is False
assert r.set_default_node(new_def_node) is False
assert r.get_default_node() == default_node
def test_get_node_from_key(self, r):
"""
Test that get_node_from_key function returns the correct node
"""
key = "bar"
slot = r.keyslot(key)
slot_nodes = r.nodes_manager.slots_cache.get(slot)
primary = slot_nodes[0]
assert r.get_node_from_key(key, replica=False) == primary
replica = r.get_node_from_key(key, replica=True)
if replica is not None:
assert replica.server_type == REPLICA
assert replica in slot_nodes
@skip_if_redis_enterprise()
def test_not_require_full_coverage_cluster_down_error(self, r):
"""
When require_full_coverage is set to False (default client config) and not
all slots are covered, if one of the nodes has 'cluster-require_full_coverage'
config set to 'yes' some key-based commands should throw ClusterDownError
"""
node = r.get_node_from_key("foo")
missing_slot = r.keyslot("foo")
assert r.set("foo", "bar") is True
try:
assert all(r.cluster_delslots(missing_slot))
with pytest.raises(ClusterDownError):
r.exists("foo")
except ResponseError as e:
assert "CLUSTERDOWN" in str(e)
finally:
try:
# Add back the missing slot
assert r.cluster_addslots(node, missing_slot) is True
# Make sure we are not getting ClusterDownError anymore
assert r.exists("foo") == 1
except ResponseError as e:
if f"Slot {missing_slot} is already busy" in str(e):
# It can happen if the test failed to delete this slot
pass
else:
raise e
def test_timeout_error_topology_refresh_reuse_connections(self, r):
"""
By mucking TIMEOUT errors, we'll force the cluster topology to be reinitialized,
and then ensure that only the impacted connection is replaced
"""
node = r.get_node_from_key("key")
r.set("key", "value")
node_conn_origin = {}
for n in r.get_nodes():
node_conn_origin[n.name] = n.redis_connection
real_func = r.get_redis_connection(node).parse_response
class counter:
def __init__(self, val=0):
self.val = int(val)
count = counter(0)
with patch.object(Redis, "parse_response") as parse_response:
def moved_redirect_effect(connection, *args, **options):
# raise a timeout for 5 times so we'll need to reinitialize the topology
if count.val == 4:
parse_response.side_effect = real_func
count.val += 1
raise TimeoutError()
parse_response.side_effect = moved_redirect_effect
assert r.get("key") == b"value"
for node_name, conn in node_conn_origin.items():
if node_name == node.name:
# The old redis connection of the timed out node should have been
# deleted and replaced
assert conn != r.get_redis_connection(node)
else:
# other nodes' redis connection should have been reused during the
# topology refresh
cur_node = r.get_node(node_name=node_name)
assert conn == r.get_redis_connection(cur_node)
def test_cluster_get_set_retry_object(self, request):
retry = Retry(NoBackoff(), 2)
r = _get_client(RedisCluster, request, retry=retry)
assert r.get_retry()._retries == retry._retries
assert isinstance(r.get_retry()._backoff, NoBackoff)
for node in r.get_nodes():
assert node.redis_connection.get_retry()._retries == retry._retries
assert isinstance(node.redis_connection.get_retry()._backoff, NoBackoff)
rand_node = r.get_random_node()
existing_conn = rand_node.redis_connection.connection_pool.get_connection()
# Change retry policy
new_retry = Retry(ExponentialBackoff(), 3)
r.set_retry(new_retry)
assert r.get_retry()._retries == new_retry._retries
assert isinstance(r.get_retry()._backoff, ExponentialBackoff)
for node in r.get_nodes():
assert node.redis_connection.get_retry()._retries == new_retry._retries
assert isinstance(
node.redis_connection.get_retry()._backoff, ExponentialBackoff
)
assert existing_conn.retry._retries == new_retry._retries
new_conn = rand_node.redis_connection.connection_pool.get_connection()
assert new_conn.retry._retries == new_retry._retries
def test_cluster_retry_object(self, r) -> None:
# Test default retry
# FIXME: Workaround for https://github.com/redis/redis-py/issues/3030
host = r.get_default_node().host
retry = r.get_connection_kwargs().get("retry")
assert isinstance(retry, Retry)
assert retry._retries == 0
assert isinstance(retry._backoff, type(default_backoff()))
node1 = r.get_node(host, 16379).redis_connection
node2 = r.get_node(host, 16380).redis_connection
assert node1.get_retry()._retries == node2.get_retry()._retries
# Test custom retry
retry = Retry(ExponentialBackoff(10, 5), 5)
rc_custom_retry = RedisCluster(host, 16379, retry=retry)
assert (
rc_custom_retry.get_node(host, 16379).redis_connection.get_retry()._retries
== retry._retries
)
def test_replace_cluster_node(self, r) -> None:
prev_default_node = r.get_default_node()
r.replace_default_node()
assert r.get_default_node() != prev_default_node
r.replace_default_node(prev_default_node)
assert r.get_default_node() == prev_default_node
def test_default_node_is_replaced_after_exception(self, r):
curr_default_node = r.get_default_node()
# CLUSTER NODES command is being executed on the default node
nodes = r.cluster_nodes()
assert "myself" in nodes.get(curr_default_node.name).get("flags")
def raise_connection_error():
raise ConnectionError("error")
# Mock connection error for the default node
mock_node_resp_func(curr_default_node, raise_connection_error)
# Test that the command succeed from a different node
nodes = r.cluster_nodes()
assert "myself" not in nodes.get(curr_default_node.name).get("flags")
assert r.get_default_node() != curr_default_node
def test_address_remap(self, request, master_host):
"""Test that we can create a rediscluster object with
a host-port remapper and map connections through proxy objects
"""
# we remap the first n nodes
offset = 1000
n = 6
hostname, master_port = master_host
ports = [master_port + i for i in range(n)]
def address_remap(address):
# remap first three nodes to our local proxy
# old = host, port
host, port = address
if int(port) in ports:
host, port = "127.0.0.1", int(port) + offset
# print(f"{old} {host, port}")
return host, port
# create the proxies
proxies = [
NodeProxy(("127.0.0.1", port + offset), (hostname, port)) for port in ports
]
for p in proxies:
p.start()
try:
# create cluster:
r = _get_client(
RedisCluster, request, flushdb=False, address_remap=address_remap
)
try:
assert r.ping() is True
assert r.set("byte_string", b"giraffe")
assert r.get("byte_string") == b"giraffe"
finally:
r.close()
finally:
for p in proxies:
p.close()
# verify that the proxies were indeed used
n_used = sum((1 if p.n_connections else 0) for p in proxies)
assert n_used > 1
@pytest.mark.onlycluster
class TestClusterRedisCommands:
"""