-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
Copy pathcluster.py
2325 lines (2076 loc) · 84.5 KB
/
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 random
import socket
import sys
import threading
import time
from collections import OrderedDict
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
from redis.backoff import default_backoff
from redis.client import CaseInsensitiveDict, PubSub, Redis, parse_scan
from redis.commands import READ_COMMANDS, CommandsParser, RedisClusterCommands
from redis.connection import ConnectionPool, DefaultParser, Encoder, parse_url
from redis.crc import REDIS_CLUSTER_HASH_SLOTS, key_slot
from redis.exceptions import (
AskError,
AuthenticationError,
ClusterCrossSlotError,
ClusterDownError,
ClusterError,
ConnectionError,
DataError,
MasterDownError,
MovedError,
RedisClusterException,
RedisError,
ResponseError,
SlotNotCoveredError,
TimeoutError,
TryAgainError,
)
from redis.lock import Lock
from redis.retry import Retry
from redis.utils import (
dict_merge,
list_keys_to_dict,
merge_result,
safe_str,
str_if_bytes,
)
def get_node_name(host: str, port: Union[str, int]) -> str:
return f"{host}:{port}"
def get_connection(redis_node, *args, **options):
return redis_node.connection or redis_node.connection_pool.get_connection(
args[0], **options
)
def parse_scan_result(command, res, **options):
cursors = {}
ret = []
for node_name, response in res.items():
cursor, r = parse_scan(response, **options)
cursors[node_name] = cursor
ret += r
return cursors, ret
def parse_pubsub_numsub(command, res, **options):
numsub_d = OrderedDict()
for numsub_tups in res.values():
for channel, numsubbed in numsub_tups:
try:
numsub_d[channel] += numsubbed
except KeyError:
numsub_d[channel] = numsubbed
ret_numsub = [(channel, numsub) for channel, numsub in numsub_d.items()]
return ret_numsub
def parse_cluster_slots(
resp: Any, **options: Any
) -> Dict[Tuple[int, int], Dict[str, Any]]:
current_host = options.get("current_host", "")
def fix_server(*args: Any) -> Tuple[str, Any]:
return str_if_bytes(args[0]) or current_host, args[1]
slots = {}
for slot in resp:
start, end, primary = slot[:3]
replicas = slot[3:]
slots[start, end] = {
"primary": fix_server(*primary),
"replicas": [fix_server(*replica) for replica in replicas],
}
return slots
def parse_cluster_shards(resp, **options):
"""
Parse CLUSTER SHARDS response.
"""
shards = []
for x in resp:
shard = {"slots": [], "nodes": []}
for i in range(0, len(x[1]), 2):
shard["slots"].append((x[1][i], (x[1][i + 1])))
nodes = x[3]
for node in nodes:
dict_node = {}
for i in range(0, len(node), 2):
dict_node[node[i]] = node[i + 1]
shard["nodes"].append(dict_node)
shards.append(shard)
return shards
PRIMARY = "primary"
REPLICA = "replica"
SLOT_ID = "slot-id"
REDIS_ALLOWED_KEYS = (
"charset",
"connection_class",
"connection_pool",
"connection_pool_class",
"client_name",
"credential_provider",
"db",
"decode_responses",
"encoding",
"encoding_errors",
"errors",
"host",
"max_connections",
"nodes_flag",
"redis_connect_func",
"password",
"port",
"retry",
"retry_on_timeout",
"socket_connect_timeout",
"socket_keepalive",
"socket_keepalive_options",
"socket_timeout",
"ssl",
"ssl_ca_certs",
"ssl_ca_data",
"ssl_certfile",
"ssl_cert_reqs",
"ssl_keyfile",
"ssl_password",
"unix_socket_path",
"username",
)
KWARGS_DISABLED_KEYS = ("host", "port")
def cleanup_kwargs(**kwargs):
"""
Remove unsupported or disabled keys from kwargs
"""
connection_kwargs = {
k: v
for k, v in kwargs.items()
if k in REDIS_ALLOWED_KEYS and k not in KWARGS_DISABLED_KEYS
}
return connection_kwargs
class ClusterParser(DefaultParser):
EXCEPTION_CLASSES = dict_merge(
DefaultParser.EXCEPTION_CLASSES,
{
"ASK": AskError,
"TRYAGAIN": TryAgainError,
"MOVED": MovedError,
"CLUSTERDOWN": ClusterDownError,
"CROSSSLOT": ClusterCrossSlotError,
"MASTERDOWN": MasterDownError,
},
)
class AbstractRedisCluster:
RedisClusterRequestTTL = 16
PRIMARIES = "primaries"
REPLICAS = "replicas"
ALL_NODES = "all"
RANDOM = "random"
DEFAULT_NODE = "default-node"
NODE_FLAGS = {PRIMARIES, REPLICAS, ALL_NODES, RANDOM, DEFAULT_NODE}
COMMAND_FLAGS = dict_merge(
list_keys_to_dict(
[
"ACL CAT",
"ACL DELUSER",
"ACL DRYRUN",
"ACL GENPASS",
"ACL GETUSER",
"ACL HELP",
"ACL LIST",
"ACL LOG",
"ACL LOAD",
"ACL SAVE",
"ACL SETUSER",
"ACL USERS",
"ACL WHOAMI",
"AUTH",
"CLIENT LIST",
"CLIENT SETNAME",
"CLIENT GETNAME",
"CONFIG SET",
"CONFIG REWRITE",
"CONFIG RESETSTAT",
"TIME",
"PUBSUB CHANNELS",
"PUBSUB NUMPAT",
"PUBSUB NUMSUB",
"PING",
"INFO",
"SHUTDOWN",
"KEYS",
"DBSIZE",
"BGSAVE",
"SLOWLOG GET",
"SLOWLOG LEN",
"SLOWLOG RESET",
"WAIT",
"SAVE",
"MEMORY PURGE",
"MEMORY MALLOC-STATS",
"MEMORY STATS",
"LASTSAVE",
"CLIENT TRACKINGINFO",
"CLIENT PAUSE",
"CLIENT UNPAUSE",
"CLIENT UNBLOCK",
"CLIENT ID",
"CLIENT REPLY",
"CLIENT GETREDIR",
"CLIENT INFO",
"CLIENT KILL",
"READONLY",
"READWRITE",
"CLUSTER INFO",
"CLUSTER MEET",
"CLUSTER NODES",
"CLUSTER REPLICAS",
"CLUSTER RESET",
"CLUSTER SET-CONFIG-EPOCH",
"CLUSTER SLOTS",
"CLUSTER SHARDS",
"CLUSTER COUNT-FAILURE-REPORTS",
"CLUSTER KEYSLOT",
"COMMAND",
"COMMAND COUNT",
"COMMAND LIST",
"COMMAND GETKEYS",
"CONFIG GET",
"DEBUG",
"RANDOMKEY",
"READONLY",
"READWRITE",
"TIME",
"GRAPH.CONFIG",
"LATENCY HISTORY",
"LATENCY LATEST",
"LATENCY RESET",
],
DEFAULT_NODE,
),
list_keys_to_dict(
[
"FLUSHALL",
"FLUSHDB",
"FUNCTION DELETE",
"FUNCTION FLUSH",
"FUNCTION LIST",
"FUNCTION LOAD",
"FUNCTION RESTORE",
"SCAN",
"SCRIPT EXISTS",
"SCRIPT FLUSH",
"SCRIPT LOAD",
],
PRIMARIES,
),
list_keys_to_dict(["FUNCTION DUMP"], RANDOM),
list_keys_to_dict(
[
"CLUSTER COUNTKEYSINSLOT",
"CLUSTER DELSLOTS",
"CLUSTER DELSLOTSRANGE",
"CLUSTER GETKEYSINSLOT",
"CLUSTER SETSLOT",
],
SLOT_ID,
),
)
SEARCH_COMMANDS = (
[
"FT.CREATE",
"FT.SEARCH",
"FT.AGGREGATE",
"FT.EXPLAIN",
"FT.EXPLAINCLI",
"FT,PROFILE",
"FT.ALTER",
"FT.DROPINDEX",
"FT.ALIASADD",
"FT.ALIASUPDATE",
"FT.ALIASDEL",
"FT.TAGVALS",
"FT.SUGADD",
"FT.SUGGET",
"FT.SUGDEL",
"FT.SUGLEN",
"FT.SYNUPDATE",
"FT.SYNDUMP",
"FT.SPELLCHECK",
"FT.DICTADD",
"FT.DICTDEL",
"FT.DICTDUMP",
"FT.INFO",
"FT._LIST",
"FT.CONFIG",
"FT.ADD",
"FT.DEL",
"FT.DROP",
"FT.GET",
"FT.MGET",
"FT.SYNADD",
],
)
CLUSTER_COMMANDS_RESPONSE_CALLBACKS = {
"CLUSTER SLOTS": parse_cluster_slots,
"CLUSTER SHARDS": parse_cluster_shards,
}
RESULT_CALLBACKS = dict_merge(
list_keys_to_dict(["PUBSUB NUMSUB"], parse_pubsub_numsub),
list_keys_to_dict(
["PUBSUB NUMPAT"], lambda command, res: sum(list(res.values()))
),
list_keys_to_dict(["KEYS", "PUBSUB CHANNELS"], merge_result),
list_keys_to_dict(
[
"PING",
"CONFIG SET",
"CONFIG REWRITE",
"CONFIG RESETSTAT",
"CLIENT SETNAME",
"BGSAVE",
"SLOWLOG RESET",
"SAVE",
"MEMORY PURGE",
"CLIENT PAUSE",
"CLIENT UNPAUSE",
],
lambda command, res: all(res.values()) if isinstance(res, dict) else res,
),
list_keys_to_dict(
["DBSIZE", "WAIT"],
lambda command, res: sum(res.values()) if isinstance(res, dict) else res,
),
list_keys_to_dict(
["CLIENT UNBLOCK"], lambda command, res: 1 if sum(res.values()) > 0 else 0
),
list_keys_to_dict(["SCAN"], parse_scan_result),
list_keys_to_dict(
["SCRIPT LOAD"], lambda command, res: list(res.values()).pop()
),
list_keys_to_dict(
["SCRIPT EXISTS"], lambda command, res: [all(k) for k in zip(*res.values())]
),
list_keys_to_dict(["SCRIPT FLUSH"], lambda command, res: all(res.values())),
)
ERRORS_ALLOW_RETRY = (ConnectionError, TimeoutError, ClusterDownError)
def replace_default_node(self, target_node: "ClusterNode" = None) -> None:
"""Replace the default cluster node.
A random cluster node will be chosen if target_node isn't passed, and primaries
will be prioritized. The default node will not be changed if there are no other
nodes in the cluster.
Args:
target_node (ClusterNode, optional): Target node to replace the default
node. Defaults to None.
"""
if target_node:
self.nodes_manager.default_node = target_node
else:
curr_node = self.get_default_node()
primaries = [node for node in self.get_primaries() if node != curr_node]
if primaries:
# Choose a primary if the cluster contains different primaries
self.nodes_manager.default_node = random.choice(primaries)
else:
# Otherwise, hoose a primary if the cluster contains different primaries
replicas = [node for node in self.get_replicas() if node != curr_node]
if replicas:
self.nodes_manager.default_node = random.choice(replicas)
class RedisCluster(AbstractRedisCluster, RedisClusterCommands):
@classmethod
def from_url(cls, url, **kwargs):
"""
Return a Redis client object configured from the given URL
For example::
redis://[[username]:[password]]@localhost:6379/0
rediss://[[username]:[password]]@localhost:6379/0
unix://[username@]/path/to/socket.sock?db=0[&password=password]
Three URL schemes are supported:
- `redis://` creates a TCP socket connection. See more at:
<https://www.iana.org/assignments/uri-schemes/prov/redis>
- `rediss://` creates a SSL wrapped TCP socket connection. See more at:
<https://www.iana.org/assignments/uri-schemes/prov/rediss>
- ``unix://``: creates a Unix Domain Socket connection.
The username, password, hostname, path and all querystring values
are passed through urllib.parse.unquote in order to replace any
percent-encoded values with their corresponding characters.
There are several ways to specify a database number. The first value
found will be used:
1. A ``db`` querystring option, e.g. redis://localhost?db=0
2. If using the redis:// or rediss:// schemes, the path argument
of the url, e.g. redis://localhost/0
3. A ``db`` keyword argument to this function.
If none of these options are specified, the default db=0 is used.
All querystring options are cast to their appropriate Python types.
Boolean arguments can be specified with string values "True"/"False"
or "Yes"/"No". Values that cannot be properly cast cause a
``ValueError`` to be raised. Once parsed, the querystring arguments
and keyword arguments are passed to the ``ConnectionPool``'s
class initializer. In the case of conflicting arguments, querystring
arguments always win.
"""
return cls(url=url, **kwargs)
def __init__(
self,
host: Optional[str] = None,
port: int = 6379,
startup_nodes: Optional[List["ClusterNode"]] = None,
cluster_error_retry_attempts: int = 3,
retry: Optional["Retry"] = None,
require_full_coverage: bool = False,
reinitialize_steps: int = 5,
read_from_replicas: bool = False,
dynamic_startup_nodes: bool = True,
url: Optional[str] = None,
**kwargs,
):
"""
Initialize a new RedisCluster client.
:param startup_nodes:
List of nodes from which initial bootstrapping can be done
:param host:
Can be used to point to a startup node
:param port:
Can be used to point to a startup node
:param require_full_coverage:
When set to False (default value): the client will not require a
full coverage of the slots. However, if not all slots are covered,
and at least one node has 'cluster-require-full-coverage' set to
'yes,' the server will throw a ClusterDownError for some key-based
commands. See -
https://redis.io/topics/cluster-tutorial#redis-cluster-configuration-parameters
When set to True: all slots must be covered to construct the
cluster client. If not all slots are covered, RedisClusterException
will be thrown.
:param read_from_replicas:
Enable read from replicas in READONLY mode. You can read possibly
stale data.
When set to true, read commands will be assigned between the
primary and its replications in a Round-Robin manner.
:param dynamic_startup_nodes:
Set the RedisCluster's startup nodes to all of the discovered nodes.
If true (default value), the cluster's discovered nodes will be used to
determine the cluster nodes-slots mapping in the next topology refresh.
It will remove the initial passed startup nodes if their endpoints aren't
listed in the CLUSTER SLOTS output.
If you use dynamic DNS endpoints for startup nodes but CLUSTER SLOTS lists
specific IP addresses, it is best to set it to false.
:param cluster_error_retry_attempts:
Number of times to retry before raising an error when
:class:`~.TimeoutError` or :class:`~.ConnectionError` or
:class:`~.ClusterDownError` are encountered
:param reinitialize_steps:
Specifies the number of MOVED errors that need to occur before
reinitializing the whole cluster topology. If a MOVED error occurs
and the cluster does not need to be reinitialized on this current
error handling, only the MOVED slot will be patched with the
redirected node.
To reinitialize the cluster on every MOVED error, set
reinitialize_steps to 1.
To avoid reinitializing the cluster on moved errors, set
reinitialize_steps to 0.
:**kwargs:
Extra arguments that will be sent into Redis instance when created
(See Official redis-py doc for supported kwargs
[https://github.com/andymccurdy/redis-py/blob/master/redis/client.py])
Some kwargs are not supported and will raise a
RedisClusterException:
- db (Redis do not support database SELECT in cluster mode)
"""
if startup_nodes is None:
startup_nodes = []
if "db" in kwargs:
# Argument 'db' is not possible to use in cluster mode
raise RedisClusterException(
"Argument 'db' is not possible to use in cluster mode"
)
# Get the startup node/s
from_url = False
if url is not None:
from_url = True
url_options = parse_url(url)
if "path" in url_options:
raise RedisClusterException(
"RedisCluster does not currently support Unix Domain "
"Socket connections"
)
if "db" in url_options and url_options["db"] != 0:
# Argument 'db' is not possible to use in cluster mode
raise RedisClusterException(
"A ``db`` querystring option can only be 0 in cluster mode"
)
kwargs.update(url_options)
host = kwargs.get("host")
port = kwargs.get("port", port)
startup_nodes.append(ClusterNode(host, port))
elif host is not None and port is not None:
startup_nodes.append(ClusterNode(host, port))
elif len(startup_nodes) == 0:
# No startup node was provided
raise RedisClusterException(
"RedisCluster requires at least one node to discover the "
"cluster. Please provide one of the followings:\n"
"1. host and port, for example:\n"
" RedisCluster(host='localhost', port=6379)\n"
"2. list of startup nodes, for example:\n"
" RedisCluster(startup_nodes=[ClusterNode('localhost', 6379),"
" ClusterNode('localhost', 6378)])"
)
# Update the connection arguments
# Whenever a new connection is established, RedisCluster's on_connect
# method should be run
# If the user passed on_connect function we'll save it and run it
# inside the RedisCluster.on_connect() function
self.user_on_connect_func = kwargs.pop("redis_connect_func", None)
kwargs.update({"redis_connect_func": self.on_connect})
kwargs = cleanup_kwargs(**kwargs)
if retry:
self.retry = retry
kwargs.update({"retry": self.retry})
else:
kwargs.update({"retry": Retry(default_backoff(), 0)})
self.encoder = Encoder(
kwargs.get("encoding", "utf-8"),
kwargs.get("encoding_errors", "strict"),
kwargs.get("decode_responses", False),
)
self.cluster_error_retry_attempts = cluster_error_retry_attempts
self.command_flags = self.__class__.COMMAND_FLAGS.copy()
self.node_flags = self.__class__.NODE_FLAGS.copy()
self.read_from_replicas = read_from_replicas
self.reinitialize_counter = 0
self.reinitialize_steps = reinitialize_steps
self.nodes_manager = None
self.nodes_manager = NodesManager(
startup_nodes=startup_nodes,
from_url=from_url,
require_full_coverage=require_full_coverage,
dynamic_startup_nodes=dynamic_startup_nodes,
**kwargs,
)
self.cluster_response_callbacks = CaseInsensitiveDict(
self.__class__.CLUSTER_COMMANDS_RESPONSE_CALLBACKS
)
self.result_callbacks = CaseInsensitiveDict(self.__class__.RESULT_CALLBACKS)
self.commands_parser = CommandsParser(self)
self._lock = threading.Lock()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
def __del__(self):
self.close()
def disconnect_connection_pools(self):
for node in self.get_nodes():
if node.redis_connection:
try:
node.redis_connection.connection_pool.disconnect()
except OSError:
# Client was already disconnected. do nothing
pass
def on_connect(self, connection):
"""
Initialize the connection, authenticate and select a database and send
READONLY if it is set during object initialization.
"""
connection.set_parser(ClusterParser)
connection.on_connect()
if self.read_from_replicas:
# Sending READONLY command to server to configure connection as
# readonly. Since each cluster node may change its server type due
# to a failover, we should establish a READONLY connection
# regardless of the server type. If this is a primary connection,
# READONLY would not affect executing write commands.
connection.send_command("READONLY")
if str_if_bytes(connection.read_response()) != "OK":
raise ConnectionError("READONLY command failed")
if self.user_on_connect_func is not None:
self.user_on_connect_func(connection)
def get_redis_connection(self, node):
if not node.redis_connection:
with self._lock:
if not node.redis_connection:
self.nodes_manager.create_redis_connections([node])
return node.redis_connection
def get_node(self, host=None, port=None, node_name=None):
return self.nodes_manager.get_node(host, port, node_name)
def get_primaries(self):
return self.nodes_manager.get_nodes_by_server_type(PRIMARY)
def get_replicas(self):
return self.nodes_manager.get_nodes_by_server_type(REPLICA)
def get_random_node(self):
return random.choice(list(self.nodes_manager.nodes_cache.values()))
def get_nodes(self):
return list(self.nodes_manager.nodes_cache.values())
def get_node_from_key(self, key, replica=False):
"""
Get the node that holds the key's slot.
If replica set to True but the slot doesn't have any replicas, None is
returned.
"""
slot = self.keyslot(key)
slot_cache = self.nodes_manager.slots_cache.get(slot)
if slot_cache is None or len(slot_cache) == 0:
raise SlotNotCoveredError(f'Slot "{slot}" is not covered by the cluster.')
if replica and len(self.nodes_manager.slots_cache[slot]) < 2:
return None
elif replica:
node_idx = 1
else:
# primary
node_idx = 0
return slot_cache[node_idx]
def get_default_node(self):
"""
Get the cluster's default node
"""
return self.nodes_manager.default_node
def set_default_node(self, node):
"""
Set the default node of the cluster.
:param node: 'ClusterNode'
:return True if the default node was set, else False
"""
if node is None or self.get_node(node_name=node.name) is None:
return False
self.nodes_manager.default_node = node
return True
def get_retry(self) -> Optional["Retry"]:
return self.retry
def set_retry(self, retry: "Retry") -> None:
self.retry = retry
for node in self.get_nodes():
node.redis_connection.set_retry(retry)
def monitor(self, target_node=None):
"""
Returns a Monitor object for the specified target node.
The default cluster node will be selected if no target node was
specified.
Monitor is useful for handling the MONITOR command to the redis server.
next_command() method returns one command from monitor
listen() method yields commands from monitor.
"""
if target_node is None:
target_node = self.get_default_node()
if target_node.redis_connection is None:
raise RedisClusterException(
f"Cluster Node {target_node.name} has no redis_connection"
)
return target_node.redis_connection.monitor()
def pubsub(self, node=None, host=None, port=None, **kwargs):
"""
Allows passing a ClusterNode, or host&port, to get a pubsub instance
connected to the specified node
"""
return ClusterPubSub(self, node=node, host=host, port=port, **kwargs)
def pipeline(self, transaction=None, shard_hint=None):
"""
Cluster impl:
Pipelines do not work in cluster mode the same way they
do in normal mode. Create a clone of this object so
that simulating pipelines will work correctly. Each
command will be called directly when used and
when calling execute() will only return the result stack.
"""
if shard_hint:
raise RedisClusterException("shard_hint is deprecated in cluster mode")
if transaction:
raise RedisClusterException("transaction is deprecated in cluster mode")
return ClusterPipeline(
nodes_manager=self.nodes_manager,
commands_parser=self.commands_parser,
startup_nodes=self.nodes_manager.startup_nodes,
result_callbacks=self.result_callbacks,
cluster_response_callbacks=self.cluster_response_callbacks,
cluster_error_retry_attempts=self.cluster_error_retry_attempts,
read_from_replicas=self.read_from_replicas,
reinitialize_steps=self.reinitialize_steps,
lock=self._lock,
)
def lock(
self,
name,
timeout=None,
sleep=0.1,
blocking=True,
blocking_timeout=None,
lock_class=None,
thread_local=True,
):
"""
Return a new Lock object using key ``name`` that mimics
the behavior of threading.Lock.
If specified, ``timeout`` indicates a maximum life for the lock.
By default, it will remain locked until release() is called.
``sleep`` indicates the amount of time to sleep per loop iteration
when the lock is in blocking mode and another client is currently
holding the lock.
``blocking`` indicates whether calling ``acquire`` should block until
the lock has been acquired or to fail immediately, causing ``acquire``
to return False and the lock not being acquired. Defaults to True.
Note this value can be overridden by passing a ``blocking``
argument to ``acquire``.
``blocking_timeout`` indicates the maximum amount of time in seconds to
spend trying to acquire the lock. A value of ``None`` indicates
continue trying forever. ``blocking_timeout`` can be specified as a
float or integer, both representing the number of seconds to wait.
``lock_class`` forces the specified lock implementation. Note that as
of redis-py 3.0, the only lock class we implement is ``Lock`` (which is
a Lua-based lock). So, it's unlikely you'll need this parameter, unless
you have created your own custom lock class.
``thread_local`` indicates whether the lock token is placed in
thread-local storage. By default, the token is placed in thread local
storage so that a thread only sees its token, not a token set by
another thread. Consider the following timeline:
time: 0, thread-1 acquires `my-lock`, with a timeout of 5 seconds.
thread-1 sets the token to "abc"
time: 1, thread-2 blocks trying to acquire `my-lock` using the
Lock instance.
time: 5, thread-1 has not yet completed. redis expires the lock
key.
time: 5, thread-2 acquired `my-lock` now that it's available.
thread-2 sets the token to "xyz"
time: 6, thread-1 finishes its work and calls release(). if the
token is *not* stored in thread local storage, then
thread-1 would see the token value as "xyz" and would be
able to successfully release the thread-2's lock.
In some use cases it's necessary to disable thread local storage. For
example, if you have code where one thread acquires a lock and passes
that lock instance to a worker thread to release later. If thread
local storage isn't disabled in this case, the worker thread won't see
the token set by the thread that acquired the lock. Our assumption
is that these cases aren't common and as such default to using
thread local storage."""
if lock_class is None:
lock_class = Lock
return lock_class(
self,
name,
timeout=timeout,
sleep=sleep,
blocking=blocking,
blocking_timeout=blocking_timeout,
thread_local=thread_local,
)
def set_response_callback(self, command, callback):
"""Set a custom Response Callback"""
self.cluster_response_callbacks[command] = callback
def _determine_nodes(self, *args, **kwargs) -> List["ClusterNode"]:
# Determine which nodes should be executed the command on.
# Returns a list of target nodes.
command = args[0].upper()
if len(args) >= 2 and f"{args[0]} {args[1]}".upper() in self.command_flags:
command = f"{args[0]} {args[1]}".upper()
nodes_flag = kwargs.pop("nodes_flag", None)
if nodes_flag is not None:
# nodes flag passed by the user
command_flag = nodes_flag
else:
# get the nodes group for this command if it was predefined
command_flag = self.command_flags.get(command)
if command_flag == self.__class__.RANDOM:
# return a random node
return [self.get_random_node()]
elif command_flag == self.__class__.PRIMARIES:
# return all primaries
return self.get_primaries()
elif command_flag == self.__class__.REPLICAS:
# return all replicas
return self.get_replicas()
elif command_flag == self.__class__.ALL_NODES:
# return all nodes
return self.get_nodes()
elif command_flag == self.__class__.DEFAULT_NODE:
# return the cluster's default node
return [self.nodes_manager.default_node]
elif command in self.__class__.SEARCH_COMMANDS[0]:
return [self.nodes_manager.default_node]
else:
# get the node that holds the key's slot
slot = self.determine_slot(*args)
node = self.nodes_manager.get_node_from_slot(
slot, self.read_from_replicas and command in READ_COMMANDS
)
return [node]
def _should_reinitialized(self):
# To reinitialize the cluster on every MOVED error,
# set reinitialize_steps to 1.
# To avoid reinitializing the cluster on moved errors, set
# reinitialize_steps to 0.
if self.reinitialize_steps == 0:
return False
else:
return self.reinitialize_counter % self.reinitialize_steps == 0
def keyslot(self, key):
"""
Calculate keyslot for a given key.
See Keys distribution model in https://redis.io/topics/cluster-spec
"""
k = self.encoder.encode(key)
return key_slot(k)
def _get_command_keys(self, *args):
"""
Get the keys in the command. If the command has no keys in in, None is
returned.
NOTE: Due to a bug in redis<7.0, this function does not work properly
for EVAL or EVALSHA when the `numkeys` arg is 0.
- issue: https://github.com/redis/redis/issues/9493
- fix: https://github.com/redis/redis/pull/9733
So, don't use this function with EVAL or EVALSHA.
"""
redis_conn = self.get_default_node().redis_connection
return self.commands_parser.get_keys(redis_conn, *args)
def determine_slot(self, *args):
"""
Figure out what slot to use based on args.
Raises a RedisClusterException if there's a missing key and we can't
determine what slots to map the command to; or, if the keys don't
all map to the same key slot.
"""
command = args[0]
if self.command_flags.get(command) == SLOT_ID:
# The command contains the slot ID
return args[1]
# Get the keys in the command
# EVAL and EVALSHA are common enough that it's wasteful to go to the
# redis server to parse the keys. Besides, there is a bug in redis<7.0
# where `self._get_command_keys()` fails anyway. So, we special case
# EVAL/EVALSHA.
if command in ("EVAL", "EVALSHA"):
# command syntax: EVAL "script body" num_keys ...
if len(args) <= 2:
raise RedisClusterException(f"Invalid args in command: {args}")
num_actual_keys = args[2]
eval_keys = args[3 : 3 + num_actual_keys]
# if there are 0 keys, that means the script can be run on any node
# so we can just return a random slot
if len(eval_keys) == 0:
return random.randrange(0, REDIS_CLUSTER_HASH_SLOTS)
keys = eval_keys
else:
keys = self._get_command_keys(*args)
if keys is None or len(keys) == 0:
# FCALL can call a function with 0 keys, that means the function
# can be run on any node so we can just return a random slot
if command in ("FCALL", "FCALL_RO"):
return random.randrange(0, REDIS_CLUSTER_HASH_SLOTS)
raise RedisClusterException(
"No way to dispatch this command to Redis Cluster. "
"Missing key.\nYou can execute the command by specifying "
f"target nodes.\nCommand: {args}"
)
# single key command
if len(keys) == 1:
return self.keyslot(keys[0])
# multi-key command; we need to make sure all keys are mapped to
# the same slot
slots = {self.keyslot(key) for key in keys}
if len(slots) != 1:
raise RedisClusterException(
f"{command} - all keys must map to the same key slot"
)
return slots.pop()
def get_encoder(self):
"""
Get the connections' encoder
"""
return self.encoder
def get_connection_kwargs(self):
"""
Get the connections' key-word arguments
"""
return self.nodes_manager.connection_kwargs
def _is_nodes_flag(self, target_nodes):
return isinstance(target_nodes, str) and target_nodes in self.node_flags
def _parse_target_nodes(self, target_nodes):
if isinstance(target_nodes, list):
nodes = target_nodes
elif isinstance(target_nodes, ClusterNode):
# Supports passing a single ClusterNode as a variable
nodes = [target_nodes]
elif isinstance(target_nodes, dict):
# Supports dictionaries of the format {node_name: node}.
# It enables to execute commands with multi nodes as follows:
# rc.cluster_save_config(rc.get_primaries())
nodes = target_nodes.values()
else:
raise TypeError(
"target_nodes type can be one of the following: "
"node_flag (PRIMARIES, REPLICAS, RANDOM, ALL_NODES),"