Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/redis/cluster.py: 16%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1import logging
2import math
3import random
4import socket
5import sys
6import threading
7import time
8import weakref
9from abc import ABC, abstractmethod
10from collections import OrderedDict, defaultdict
11from concurrent.futures import Future, ThreadPoolExecutor
12from contextlib import contextmanager, nullcontext
13from copy import copy
14from enum import Enum
15from functools import cache, partial
16from itertools import chain
17from types import MethodType
18from typing import (
19 TYPE_CHECKING,
20 Any,
21 Callable,
22 Dict,
23 Iterable,
24 Iterator,
25 List,
26 Literal,
27 Optional,
28 Set,
29 Tuple,
30 Type,
31 Union,
32)
34if TYPE_CHECKING:
35 from redis.keyspace_notifications import ClusterKeyspaceNotifications
37from redis import _himport_exec
38from redis._defaults import DEFAULT_RETRY_BASE, DEFAULT_RETRY_CAP, DEFAULT_RETRY_COUNT
39from redis._parsers import CommandsParser, Encoder
40from redis._parsers.helpers import parse_scan
41from redis.backoff import ExponentialWithJitterBackoff, NoBackoff
42from redis.cache import CacheConfig, CacheFactory, CacheFactoryInterface, CacheInterface
43from redis.client import EMPTY_RESPONSE, CaseInsensitiveDict, PubSub, Redis
44from redis.commands import RedisClusterCommands
45from redis.commands.helpers import list_or_args, parse_pubsub_subscriptions
46from redis.commands.metadata import (
47 _DEFAULT_KEYED_METADATA,
48 _DEFAULT_KEYLESS_METADATA,
49 _METADATA_BY_REQUEST_POLICY,
50 CommandMetadata,
51 CommandPolicies,
52 MetadataResolver,
53 RequestPolicy,
54 ResponsePolicy,
55 StaticMetadataResolver,
56)
57from redis.commands.policies import PolicyResolver, StaticPolicyResolver
58from redis.connection import (
59 Connection,
60 ConnectionPool,
61 SSLConnection,
62 parse_url,
63)
64from redis.crc import REDIS_CLUSTER_HASH_SLOTS, key_slot
65from redis.event import (
66 AfterPooledConnectionsInstantiationEvent,
67 AfterPubSubConnectionInstantiationEvent,
68 AfterSlotsCacheRefreshEvent,
69 ClientType,
70 EventDispatcher,
71 EventListenerInterface,
72)
73from redis.exceptions import (
74 AskError,
75 AuthenticationError,
76 AuthorizationError,
77 ClusterDownError,
78 ClusterError,
79 ConnectionError,
80 CrossSlotTransactionError,
81 DataError,
82 ExecAbortError,
83 InvalidPipelineStack,
84 MaxClientsReachedError,
85 MaxConnectionsError,
86 MovedError,
87 ReadOnlyError,
88 RedisClusterException,
89 RedisClusterUnreachableError,
90 RedisError,
91 ResponseError,
92 SlotNotCoveredError,
93 TimeoutError,
94 TryAgainError,
95 WatchError,
96)
97from redis.himport import HImportRegistry, parse_himport_set_args
98from redis.lock import Lock
99from redis.maint_notifications import (
100 MaintNotificationsConfig,
101 OSSMaintNotificationsHandler,
102)
103from redis.observability.recorder import (
104 record_error_count,
105 record_operation_duration,
106)
107from redis.retry import AbstractRetry, Retry
108from redis.typing import (
109 ChannelT,
110 FieldT,
111 PubSubHandler,
112 Subscription,
113)
114from redis.utils import (
115 check_protocol_version,
116 command_text,
117 deprecated_args,
118 deprecated_function,
119 dict_merge,
120 experimental_method,
121 list_keys_to_dict,
122 merge_result,
123 safe_str,
124 str_if_bytes,
125 truncate_text,
126)
128logger = logging.getLogger(__name__)
131def is_debug_log_enabled():
132 return logger.isEnabledFor(logging.DEBUG)
135def get_node_name(host: str, port: Union[str, int]) -> str:
136 return f"{host}:{port}"
139@cache
140def _resolve_localhost() -> str:
141 """
142 The address a node given as ``localhost`` is cached under. Resolved once,
143 so lookups such as the one on every MOVED or ASK redirect don't each pay
144 for a resolver call.
145 """
146 return socket.gethostbyname("localhost")
149def _fill_missing_redirect_host(error: AskError, origin_host: str) -> None:
150 """
151 Give a MOVED or ASK redirect that came without a host the host of the node
152 that sent it. A node whose endpoint is unknown
153 (``cluster-preferred-endpoint-type unknown-endpoint``) redirects with only a
154 port, as in ``MOVED 3999 :6381``, and expects the client to reach out on
155 the endpoint it sent the command to.
157 ``origin_host`` is the host the client connected to, which has already been
158 through ``address_remap``, so the redirect is remapped a second time when it
159 is followed. That is harmless for a remap that only picks the port, as for a
160 proxy, but not for one that changes the host.
161 """
162 if not error.host:
163 error.host = origin_host
164 error.node_addr = error.host, error.port
167@deprecated_args(
168 allowed_args=["redis_node"],
169 reason="Use get_connection(redis_node) instead",
170 version="5.3.0",
171)
172def get_connection(redis_node: Redis, *args, **options) -> Connection:
173 return redis_node.connection or redis_node.connection_pool.get_connection()
176def parse_scan_result(command, res, **options):
177 cursors = {}
178 ret = []
179 for node_name, response in res.items():
180 cursor, r = parse_scan(response, **options)
181 cursors[node_name] = cursor
182 ret += r
184 return cursors, ret
187def parse_pubsub_numsub(command, res, **options):
188 numsub_d = OrderedDict()
189 for numsub_tups in res.values():
190 for channel, numsubbed in numsub_tups:
191 try:
192 numsub_d[channel] += numsubbed
193 except KeyError:
194 numsub_d[channel] = numsubbed
196 ret_numsub = [(channel, numsub) for channel, numsub in numsub_d.items()]
197 return ret_numsub
200def _first_successful_reply(res: Dict[str, Any]) -> Any:
201 """
202 Any reply will do: the errors were already raised or dropped, so every reply left is
203 an equal success.
204 """
205 return next(iter(res.values()))
208def _aggregate_replies(res: Dict[str, Any], aggregate: Callable[[Any], Any]) -> Any:
209 """
210 Fold the replies of several nodes into one, the way an ``agg_*`` response policy asks.
212 An array reply is folded element-wise - SCRIPT EXISTS answers one flag per SHA1, WAITAOF
213 a pair of counts - and any other reply is folded as a whole.
214 """
215 replies = list(res.values())
216 if isinstance(replies[0], (list, tuple)):
217 return [aggregate(column) for column in zip(*replies)]
218 return aggregate(replies)
221def _logical_and(values: Any) -> Any:
222 # Keeps the type the replies were parsed into: integer flags stay integers, and the
223 # booleans a response callback produced stay booleans.
224 return type(values[0])(all(values))
227def _logical_or(values: Any) -> Any:
228 return type(values[0])(any(values))
231# How the nodes a command is sent to are picked, by the command's request policy. Each
232# callback is handed the cluster client, the name the command is routed by and the command's
233# arguments, ``args[0]`` included. A MULTI_SHARD command routed here was not split - its keys
234# share a slot, or are not at fixed positions - so it is routed by its keys as a whole.
235_REQUEST_POLICY_CALLBACKS: Dict[RequestPolicy, Callable[..., List["ClusterNode"]]] = {
236 RequestPolicy.DEFAULT_KEYLESS: lambda cluster, command, *args: [
237 cluster.get_keyless_target_node(args[0])
238 ],
239 RequestPolicy.DEFAULT_KEYED: lambda cluster, command, *args: (
240 cluster.get_nodes_from_slot(command, *args)
241 ),
242 RequestPolicy.DEFAULT_NODE: lambda cluster, command, *args: [
243 cluster.get_default_node()
244 ],
245 RequestPolicy.ALL_SHARDS: lambda cluster, command, *args: cluster.get_primaries(),
246 RequestPolicy.ALL_NODES: lambda cluster, command, *args: cluster.get_nodes(),
247 RequestPolicy.ALL_REPLICAS: lambda cluster, command, *args: cluster.get_replicas(),
248 RequestPolicy.MULTI_SHARD: lambda cluster, command, *args: (
249 cluster.get_nodes_from_slot(command, *args)
250 ),
251 RequestPolicy.SPECIAL: lambda cluster, command, *args: cluster.get_special_nodes(),
252}
255# How the replies of a command sent to several nodes are folded into the one reply the caller
256# gets, by the command's response policy. Each callback is handed the replies keyed by node
257# name, and only once the command has no result callback of its own to merge them with - see
258# ``RedisCluster._process_result``. The keyless and keyed defaults, and SPECIAL, leave the
259# replies as they are: a SPECIAL command needs a result callback that knows its reply.
260_RESPONSE_POLICY_CALLBACKS: Dict[ResponsePolicy, Callable[[Dict[str, Any]], Any]] = {
261 ResponsePolicy.ONE_SUCCEEDED: _first_successful_reply,
262 ResponsePolicy.ALL_SUCCEEDED: _first_successful_reply,
263 ResponsePolicy.AGG_LOGICAL_AND: partial(_aggregate_replies, aggregate=_logical_and),
264 ResponsePolicy.AGG_LOGICAL_OR: partial(_aggregate_replies, aggregate=_logical_or),
265 ResponsePolicy.AGG_MIN: partial(_aggregate_replies, aggregate=min),
266 ResponsePolicy.AGG_MAX: partial(_aggregate_replies, aggregate=max),
267 ResponsePolicy.AGG_SUM: partial(_aggregate_replies, aggregate=sum),
268 ResponsePolicy.SPECIAL: lambda res: res,
269 ResponsePolicy.DEFAULT_KEYLESS: lambda res: res,
270 ResponsePolicy.DEFAULT_KEYED: lambda res: res,
271}
274def _is_expected_node_error(error: BaseException) -> bool:
275 """
276 Whether the error is the answer a ``ONE_SUCCEEDED`` command expects from the shards
277 that do not succeed: SCRIPT KILL is answered NOTBUSY by each shard that runs no script.
278 An error that leaves the command in doubt - a connection error, CLUSTERDOWN, a
279 redirection - is not.
280 """
281 return isinstance(error, ResponseError) and not isinstance(
282 error, (ClusterDownError, AskError, TryAgainError)
283 )
286def _is_idle_node_error(error: BaseException) -> bool:
287 """
288 Whether the error only says the node had nothing to do: NOTBUSY, the answer of a shard
289 that runs no script or function, which SCRIPT KILL and FUNCTION KILL get from all of
290 them but the one running it.
291 """
292 return str(error).startswith("NOTBUSY")
295def _one_succeeded_error_rank(error: BaseException) -> int:
296 """
297 How well an error explains why no node of a ``ONE_SUCCEEDED`` command succeeded, lowest
298 first. An error that leaves the command in doubt comes first, as it keeps the command
299 eligible for the retry it would otherwise get. An error from the node that runs the
300 script - UNKILLABLE, as the script already wrote - comes next, as it says why the command
301 failed. NOTBUSY comes last: it says only that the node had nothing to stop.
302 """
303 if not _is_expected_node_error(error):
304 return 0
305 return 2 if _is_idle_node_error(error) else 1
308def _split_successes_and_failure(
309 res: Dict[str, Any], response_policy: ResponsePolicy
310) -> Tuple[Dict[str, Any], Optional[BaseException]]:
311 """
312 Separate the replies of a command sent to several nodes from the errors some answered with.
314 Returns the replies to process and the error that fails the command instead, if any. Any
315 error fails it, except under ``ONE_SUCCEEDED``, which fails only when no node succeeded,
316 as the server's ``one_succeeded`` tip asks: there the Redis errors of the other nodes are
317 dropped, even one that leaves its node in doubt, and when nothing else is left the error
318 that best explains the failure is reported - see ``_one_succeeded_error_rank``. An error
319 that is not a Redis error is a client fault, and fails the command either way.
320 """
321 replies = {}
322 reported_error = None
323 one_succeeded = response_policy is ResponsePolicy.ONE_SUCCEEDED
324 for node_name, reply in res.items():
325 if not isinstance(reply, BaseException):
326 replies[node_name] = reply
327 elif not one_succeeded or not isinstance(reply, RedisError):
328 return replies, reply
329 elif reported_error is None or _one_succeeded_error_rank(
330 reply
331 ) < _one_succeeded_error_rank(reported_error):
332 reported_error = reply
334 return replies, None if replies else reported_error
337def _random_reply(res: Dict[str, Any]) -> Any:
338 """
339 RANDOMKEY: a key from any shard that has one, so the reply is None only when every
340 shard is empty - which a single shard's reply cannot tell.
341 """
342 keys = [key for key in res.values() if key is not None]
343 return random.choice(keys) if keys else None
346# How the replies of a ``response_policy:special`` command are merged, by the routed command
347# name. A SPECIAL command without an entry here keeps its replies keyed by node. INFO and the
348# diagnostics commands - FUNCTION STATS, MEMORY DOCTOR, the LATENCY reports - rely on that:
349# each node describes itself, and a section such as ``replication`` or ``server`` is about one
350# process, so no field merges meaningfully across nodes.
351_SPECIAL_RESPONSE_CALLBACKS: Dict[str, Callable[[Dict[str, Any]], Any]] = {
352 "RANDOMKEY": _random_reply,
353}
356# One command of a ``MULTI_SHARD`` command split by hash slot: the slot, the arguments of the
357# command that carries that slot's keys, the ordinals of those keys among the keys of the whole
358# command, and the keys themselves.
359_MultiShardSplit = Tuple[int, Tuple[Any, ...], List[int], List[Any]]
362def _split_by_slot(
363 args: Tuple[Any, ...],
364 command_details: Optional[Dict[str, Any]],
365 keyslot: Callable[[Any], int],
366) -> Optional[List[_MultiShardSplit]]:
367 """
368 Split a ``MULTI_SHARD`` command into one command per hash slot its keys map to.
370 The keys are located by the command's fixed key positions - ``first_key_pos``,
371 ``last_key_pos`` and ``step_count`` of its ``COMMAND`` entry - so a key travels with the
372 arguments of its step (MSET's value), and the arguments before the first key and after
373 the last are repeated in every command. Each command keeps its keys in the order the
374 caller gave them, and the commands are ordered by the slot's first key.
376 When every key maps to one slot, the one command returned is the command as the caller
377 sent it, and the caller routes it by that slot, so its keys are not hashed again.
379 Returns None when the keys cannot be located that way - a ``movablekeys`` command, whose
380 ``first_key_pos`` is 0, or a command the parser does not know - which leaves the command
381 to be routed by its keys as a whole. Returns None for a single key too, which has nothing
382 to split, before its slot is computed.
383 """
384 if not command_details:
385 return None
387 first = command_details["first_key_pos"]
388 last = command_details["last_key_pos"]
389 step = command_details["step_count"]
390 if first <= 0 or step <= 0:
391 return None
393 last_index = last if last >= 0 else len(args) + last
394 positions = range(first, last_index + 1, step)
395 if len(positions) < 2 or positions[-1] + step > len(args):
396 return None
398 slots = [keyslot(args[position]) for position in positions]
399 if slots.count(slots[0]) == len(slots):
400 return [
401 (
402 slots[0],
403 args,
404 list(range(len(positions))),
405 [args[position] for position in positions],
406 )
407 ]
409 prefix = args[:first]
410 suffix = args[positions[-1] + step :]
411 by_slot: Dict[int, Tuple[List[Any], List[int], List[Any]]] = {}
412 for ordinal, (position, slot) in enumerate(zip(positions, slots)):
413 key = args[position]
414 slot_args, ordinals, keys = by_slot.setdefault(slot, ([], [], []))
415 slot_args.extend(args[position : position + step])
416 ordinals.append(ordinal)
417 keys.append(key)
419 return [
420 (slot, (*prefix, *slot_args, *suffix), ordinals, keys)
421 for slot, (slot_args, ordinals, keys) in by_slot.items()
422 ]
425def _merge_multi_shard_replies(
426 res: Dict[int, Any],
427 splits: List[_MultiShardSplit],
428 response_policy: ResponsePolicy,
429) -> Any:
430 """
431 Merge the per-slot replies of a ``MULTI_SHARD`` command into the reply of the command
432 the caller sent.
434 A command with an aggregating response policy is folded by it - EXISTS and TOUCH sum
435 their counts, MSET answers with one of its successes. Without one, the command answers
436 with one value per key, as MGET does, and the values are put back in the caller's key
437 order.
438 """
439 if response_policy not in (
440 ResponsePolicy.DEFAULT_KEYED,
441 ResponsePolicy.DEFAULT_KEYLESS,
442 ):
443 return _RESPONSE_POLICY_CALLBACKS[response_policy](res)
445 merged: List[Any] = [None] * sum(len(ordinals) for _, _, ordinals, _ in splits)
446 for slot, _, ordinals, _ in splits:
447 for ordinal, value in zip(ordinals, res[slot]):
448 merged[ordinal] = value
449 return merged
452def _record_replies(
453 kept: Dict[Any, Any], replies: Iterable[Tuple[Any, Any]]
454) -> Optional[BaseException]:
455 """
456 Record the replies that succeeded - keyed by slot for a split ``MULTI_SHARD`` command,
457 by node name for a command sent to several nodes - and return the first error another
458 one answered with, if any.
460 A success is kept even when another slot or node fails, so a retry sends the command
461 only where it has not been answered: sending it again would run a write twice and
462 change what a summed reply counts.
463 """
464 error = None
465 for key, reply in replies:
466 if not isinstance(reply, BaseException):
467 kept[key] = reply
468 elif error is None:
469 error = reply
470 return error
473def _keep_target_replies(
474 replies: Dict[str, Any], target_nodes: Iterable["ClusterNode"]
475) -> None:
476 """
477 Drop the kept replies of the nodes that are no longer among the targets of a command
478 sent to several nodes, so a retry merges the replies of the current targets only - as
479 the main path does. A node the topology refresh replaced has answered for a shard its
480 replacement is asked about again.
481 """
482 names = {node.name for node in target_nodes}
483 for name in [name for name in replies if name not in names]:
484 del replies[name]
487def _with_keys(options: Dict[str, Any], keys: List[Any]) -> Dict[str, Any]:
488 """
489 The options of one command of a split, which must carry that command's keys: the
490 client-side cache stores a reply under the ``keys`` option it was sent with.
491 """
492 if "keys" not in options:
493 return options
494 return {**options, "keys": keys}
497def parse_cluster_slots(
498 resp: Any, **options: Any
499) -> Dict[Tuple[int, int], Dict[str, Any]]:
500 current_host = options.get("current_host", "")
502 def fix_server(*args: Any) -> Tuple[str, Any]:
503 return str_if_bytes(args[0]) or current_host, args[1]
505 slots = {}
506 for slot in resp:
507 start, end, primary = slot[:3]
508 replicas = slot[3:]
509 slots[start, end] = {
510 "primary": fix_server(*primary),
511 "replicas": [fix_server(*replica) for replica in replicas],
512 }
514 return slots
517def _pair_cluster_slots(slots):
518 """Pair a CLUSTER SHARDS flat ``[start, end, start, end, ...]`` slot array
519 into ``[(start, end), ...]``.
521 CLUSTER SHARDS returns each shard's slots as a flat integer array in both
522 RESP2 and RESP3; only the outer shard container differs between protocols.
523 """
524 return [(slots[i], slots[i + 1]) for i in range(0, len(slots), 2)]
527def parse_cluster_shards(resp, **options):
528 """
529 Parse CLUSTER SHARDS response.
530 """
531 if not resp:
532 return resp
533 if isinstance(resp[0], dict):
534 return resp
535 shards = []
536 for x in resp:
537 shard = {"slots": [], "nodes": []}
538 for i in range(0, len(x[1]), 2):
539 shard["slots"].append((x[1][i], (x[1][i + 1])))
540 nodes = x[3]
541 for node in nodes:
542 dict_node = {}
543 for i in range(0, len(node), 2):
544 dict_node[node[i]] = node[i + 1]
545 shard["nodes"].append(dict_node)
546 shards.append(shard)
548 return shards
551def parse_cluster_shards_with_str_keys(resp, **options):
552 """
553 Parse CLUSTER SHARDS with string top-level structural keys.
555 RESP2 parsing exposes top-level shard keys as ``"slots"``/``"nodes"``
556 while node attribute keys keep the connection's decoded/raw form. RESP3 can
557 return top-level shard dictionaries directly, so normalize only the
558 structural shard keys and preserve nested node dictionaries as delivered.
559 """
560 if not resp:
561 return resp
562 if not isinstance(resp[0], dict):
563 return parse_cluster_shards(resp, **options)
565 shards = []
566 for shard_resp in resp:
567 slots = shard_resp.get(b"slots", shard_resp.get("slots", []))
568 nodes = shard_resp.get(b"nodes", shard_resp.get("nodes", []))
569 shard = {
570 "slots": _pair_cluster_slots(slots),
571 "nodes": [dict(node) if isinstance(node, dict) else node for node in nodes],
572 }
573 shards.append(shard)
574 return shards
577def parse_cluster_shards_unified(resp, **options):
578 """
579 Parse CLUSTER SHARDS into the approved unified shape.
581 Top-level shard keys and nested node attribute keys are strings for both
582 RESP2 and RESP3 wire responses.
583 """
584 if not resp:
585 return resp
586 if isinstance(resp[0], dict):
587 shards = []
588 for shard_resp in resp:
589 slots = shard_resp.get(b"slots", shard_resp.get("slots", []))
590 nodes = shard_resp.get(b"nodes", shard_resp.get("nodes", []))
591 shard = {
592 "slots": _pair_cluster_slots(slots),
593 "nodes": [
594 {str_if_bytes(k): v for k, v in node.items()}
595 if isinstance(node, dict)
596 else node
597 for node in nodes
598 ],
599 }
600 shards.append(shard)
601 return shards
603 shards = []
604 for x in resp:
605 shard = {"slots": [], "nodes": []}
606 for i in range(0, len(x[1]), 2):
607 shard["slots"].append((x[1][i], x[1][i + 1]))
608 nodes = x[3]
609 for node in nodes:
610 dict_node = {}
611 for i in range(0, len(node), 2):
612 dict_node[str_if_bytes(node[i])] = node[i + 1]
613 shard["nodes"].append(dict_node)
614 shards.append(shard)
615 return shards
618def parse_cluster_myshardid(resp, **options):
619 """
620 Parse CLUSTER MYSHARDID response.
621 """
622 return str_if_bytes(resp)
625PRIMARY = "primary"
626REPLICA = "replica"
627SLOT_ID = "slot-id"
629REDIS_ALLOWED_KEYS = (
630 "connection_class",
631 "connection_pool",
632 "connection_pool_class",
633 "client_name",
634 "credential_provider",
635 "db",
636 "decode_responses",
637 "encoding",
638 "encoding_errors",
639 "host",
640 "driver_info",
641 "lib_name",
642 "lib_version",
643 "max_connections",
644 "nodes_flag",
645 "redis_connect_func",
646 "password",
647 "port",
648 "timeout",
649 "queue_class",
650 "retry",
651 "retry_on_timeout",
652 "protocol",
653 "legacy_responses",
654 "socket_connect_timeout",
655 "socket_keepalive",
656 "socket_keepalive_options",
657 "socket_read_size",
658 "socket_timeout",
659 "ssl",
660 "ssl_ca_certs",
661 "ssl_ca_data",
662 "ssl_ca_path",
663 "ssl_certfile",
664 "ssl_cert_reqs",
665 "ssl_include_verify_flags",
666 "ssl_exclude_verify_flags",
667 "ssl_keyfile",
668 "ssl_password",
669 "ssl_check_hostname",
670 "ssl_validate_ocsp",
671 "ssl_validate_ocsp_stapled",
672 "ssl_ocsp_context",
673 "ssl_ocsp_expected_cert",
674 "ssl_min_version",
675 "ssl_ciphers",
676 "unix_socket_path",
677 "username",
678 "cache",
679 "cache_config",
680 "maint_notifications_config",
681)
682KWARGS_DISABLED_KEYS = ("host", "port", "retry")
685def cleanup_kwargs(**kwargs):
686 """
687 Remove unsupported or disabled keys from kwargs
688 """
689 connection_kwargs = {
690 k: v
691 for k, v in kwargs.items()
692 if k in REDIS_ALLOWED_KEYS and k not in KWARGS_DISABLED_KEYS
693 }
695 return connection_kwargs
698class MaintNotificationsAbstractRedisCluster:
699 """
700 Abstract class for handling maintenance notifications logic.
701 This class is expected to be used as base class together with RedisCluster.
703 This class is intended to be used with multiple inheritance!
705 All logic related to maintenance notifications is encapsulated in this class.
706 """
708 def __init__(
709 self,
710 maint_notifications_config: Optional[MaintNotificationsConfig],
711 **kwargs,
712 ):
713 # Initialize maintenance notifications.
714 # The RESP3 requirement is validated in RedisCluster.__init__ before the
715 # NodesManager is constructed; this mixin is only ever run from there, so
716 # the config it receives has already been validated.
717 is_protocol_supported = check_protocol_version(kwargs.get("protocol"), 3)
719 if maint_notifications_config is None and is_protocol_supported:
720 maint_notifications_config = MaintNotificationsConfig()
722 self.maint_notifications_config = maint_notifications_config
724 if self.maint_notifications_config and self.maint_notifications_config.enabled:
725 self._oss_cluster_maint_notifications_handler = (
726 OSSMaintNotificationsHandler(self, self.maint_notifications_config)
727 )
728 # Update connection kwargs for all future nodes connections
729 self._update_connection_kwargs_for_maint_notifications(
730 self._oss_cluster_maint_notifications_handler
731 )
732 # Update existing nodes connections - they are created as part of the RedisCluster constructor
733 for node in self.get_nodes():
734 if node.redis_connection is None:
735 continue
736 node.redis_connection.connection_pool.update_maint_notifications_config(
737 self.maint_notifications_config,
738 oss_cluster_maint_notifications_handler=self._oss_cluster_maint_notifications_handler,
739 )
740 else:
741 self._oss_cluster_maint_notifications_handler = None
743 def _update_connection_kwargs_for_maint_notifications(
744 self, oss_cluster_maint_notifications_handler: OSSMaintNotificationsHandler
745 ):
746 """
747 Update the connection kwargs for all future connections.
748 """
749 self.nodes_manager.connection_kwargs.update(
750 {
751 "oss_cluster_maint_notifications_handler": oss_cluster_maint_notifications_handler,
752 }
753 )
756# Topology refreshes triggered by errors (connection errors, the MOVED
757# threshold, pipeline failures, pubsub repair) run at most once per this many
758# seconds per client. Requests in between are collapsed into one refresh, run by
759# the next command once the interval has passed. After refreshes that failed in
760# a row, the next one waits as long as the client's retry backoff says for that
761# many failures, but never less than this. Server-pushed refreshes (SMIGRATED),
762# the first initialize and direct ``NodesManager.initialize()`` calls, such as
763# the one a CLUSTERDOWN or an uncovered slot runs, are not limited. This is the
764# default of the cluster clients' ``topology_refresh_min_interval`` argument.
765_TOPOLOGY_REFRESH_MIN_INTERVAL_SECONDS = 1.0
768def _topology_refresh_delay(
769 retry: AbstractRetry | None,
770 failed_refreshes: int,
771 min_interval: float | None = None,
772) -> float:
773 """
774 How long an error-triggered topology refresh waits after the previous one:
775 the minimum interval, or what the retry backoff gives for that many failed
776 refreshes in a row, whichever is longer. A :min_interval: of None stands for
777 _TOPOLOGY_REFRESH_MIN_INTERVAL_SECONDS.
778 """
779 if min_interval is None:
780 min_interval = _TOPOLOGY_REFRESH_MIN_INTERVAL_SECONDS
781 delay = min_interval
782 # A duck-typed retry policy may have no backoff to compute a delay from
783 backoff = getattr(retry, "_backoff", None)
784 if failed_refreshes and backoff is not None:
785 delay = max(delay, backoff.compute(failed_refreshes))
786 return delay
789def _should_request_refresh(reinitialize_steps: int, reinitialize_counter: int) -> bool:
790 """
791 Whether the error just counted reached the ``reinitialize_steps`` threshold,
792 so a topology refresh should be asked for. With ``reinitialize_steps`` 1 a
793 refresh is asked for on every MOVED error, with 0 never on MOVED errors. A
794 negative value works like its absolute value.
795 """
796 return bool(reinitialize_steps) and reinitialize_counter % reinitialize_steps == 0
799def _is_demoted_primary(error: Any, node: "ClusterNode") -> bool:
800 """
801 Return whether :error:, read from :node:, shows that the node is no longer
802 the primary the client takes it for. Only a replica answers READONLY, so a
803 node cached as a primary that does was demoted by a failover the client has
804 not seen yet, and a command without keys gets no MOVED to learn that from.
806 The caller sets ``demoted_primary`` on the error and asks for a topology
807 refresh, and the retry loops of the commands and pipelines retry such an
808 error like one of ``ERRORS_ALLOW_RETRY``. A READONLY from a node cached as a
809 replica does not count: the write was sent there, and no refresh changes
810 its answer.
811 """
812 return isinstance(error, ReadOnlyError) and node.server_type == PRIMARY
815def _error_to_raise(
816 last_refresh_unreachable_args: Optional[Tuple[Any, ...]],
817 error: Exception,
818) -> Exception:
819 """
820 The error a command, pipeline or transaction that gave up on :error:
821 raises. While the last topology refresh reached no node (it raised a
822 :class:`~.RedisClusterUnreachableError` with
823 :last_refresh_unreachable_args:), a connection or timeout error is raised
824 as a new :class:`~.RedisClusterUnreachableError` with those args and
825 :error: as its cause, so a cluster that cannot be reached fails as a
826 :class:`~.RedisClusterException`, whichever command ran the refresh.
827 """
828 if not isinstance(last_refresh_unreachable_args, tuple) or (
829 type(error) not in (ConnectionError, TimeoutError)
830 ):
831 return error
832 outage_error = RedisClusterUnreachableError(*last_refresh_unreachable_args)
833 outage_error.__cause__ = error
834 outage_error.__suppress_context__ = True
835 return outage_error
838class AbstractRedisCluster:
839 RedisClusterRequestTTL = 16
841 PRIMARIES = "primaries"
842 REPLICAS = "replicas"
843 ALL_NODES = "all"
844 RANDOM = "random"
845 DEFAULT_NODE = "default-node"
847 NODE_FLAGS = {PRIMARIES, REPLICAS, ALL_NODES, RANDOM, DEFAULT_NODE}
849 COMMAND_FLAGS = dict_merge(
850 list_keys_to_dict(
851 [
852 "ACL CAT",
853 "ACL DELUSER",
854 "ACL DRYRUN",
855 "ACL GENPASS",
856 "ACL GETUSER",
857 "ACL HELP",
858 "ACL LIST",
859 "ACL LOG",
860 "ACL LOAD",
861 "ACL SAVE",
862 "ACL SETUSER",
863 "ACL USERS",
864 "ACL WHOAMI",
865 "AUTH",
866 "BACKUP ABORT",
867 "BACKUP CLEANUP",
868 "BACKUP LIST",
869 "BACKUP SEAL",
870 "BACKUP START",
871 "BACKUP STATUS",
872 "CLIENT LIST",
873 "CLIENT SETINFO",
874 "CLIENT SETNAME",
875 "CLIENT GETNAME",
876 "CONFIG SET",
877 "CONFIG REWRITE",
878 "CONFIG RESETSTAT",
879 "TIME",
880 "PUBSUB CHANNELS",
881 "PUBSUB NUMPAT",
882 "PUBSUB NUMSUB",
883 "PUBSUB SHARDCHANNELS",
884 "PUBSUB SHARDNUMSUB",
885 "PING",
886 "INFO",
887 "SHUTDOWN",
888 "KEYS",
889 "DBSIZE",
890 "BGSAVE",
891 "SLOWLOG GET",
892 "SLOWLOG LEN",
893 "SLOWLOG RESET",
894 "WAIT",
895 "WAITAOF",
896 "SAVE",
897 "MEMORY PURGE",
898 "MEMORY MALLOC-STATS",
899 "MEMORY STATS",
900 "LASTSAVE",
901 "CLIENT TRACKINGINFO",
902 "CLIENT PAUSE",
903 "CLIENT UNPAUSE",
904 "CLIENT UNBLOCK",
905 "CLIENT ID",
906 "CLIENT REPLY",
907 "CLIENT GETREDIR",
908 "CLIENT INFO",
909 "CLIENT KILL",
910 "READONLY",
911 "CLUSTER INFO",
912 "CLUSTER MEET",
913 "CLUSTER MYSHARDID",
914 "CLUSTER NODES",
915 "CLUSTER REPLICAS",
916 "CLUSTER RESET",
917 "CLUSTER SET-CONFIG-EPOCH",
918 "CLUSTER SLOTS",
919 "CLUSTER SHARDS",
920 "CLUSTER COUNT-FAILURE-REPORTS",
921 "CLUSTER KEYSLOT",
922 "COMMAND",
923 "COMMAND COUNT",
924 "COMMAND LIST",
925 "COMMAND GETKEYS",
926 "COMMAND GETKEYSANDFLAGS",
927 "CONFIG GET",
928 "DEBUG",
929 "RANDOMKEY",
930 "READONLY",
931 "READWRITE",
932 "TIME",
933 "TFUNCTION LOAD",
934 "TFUNCTION DELETE",
935 "TFUNCTION LIST",
936 "TFCALL",
937 "TFCALLASYNC",
938 "LATENCY HISTORY",
939 "LATENCY LATEST",
940 "LATENCY RESET",
941 "MODULE LIST",
942 "MODULE LOAD",
943 "MODULE UNLOAD",
944 "MODULE LOADEX",
945 ],
946 DEFAULT_NODE,
947 ),
948 list_keys_to_dict(
949 [
950 "BLESS SCAN",
951 "FLUSHALL",
952 "FLUSHDB",
953 "FUNCTION DELETE",
954 "FUNCTION FLUSH",
955 "FUNCTION LIST",
956 "FUNCTION LOAD",
957 "FUNCTION RESTORE",
958 "SCAN",
959 "SCRIPT EXISTS",
960 "SCRIPT FLUSH",
961 "SCRIPT LOAD",
962 ],
963 PRIMARIES,
964 ),
965 list_keys_to_dict(["FUNCTION DUMP"], RANDOM),
966 list_keys_to_dict(
967 [
968 "CLUSTER COUNTKEYSINSLOT",
969 "CLUSTER DELSLOTS",
970 "CLUSTER DELSLOTSRANGE",
971 "CLUSTER GETKEYSINSLOT",
972 "CLUSTER SETSLOT",
973 ],
974 SLOT_ID,
975 ),
976 )
978 SEARCH_COMMANDS = (
979 [
980 "FT.CREATE",
981 "FT.SEARCH",
982 "FT.AGGREGATE",
983 "FT.EXPLAIN",
984 "FT.EXPLAINCLI",
985 "FT,PROFILE",
986 "FT.ALTER",
987 "FT.DROPINDEX",
988 "FT.ALIASADD",
989 "FT.ALIASUPDATE",
990 "FT.ALIASDEL",
991 "FT.ALIASLIST",
992 "FT.TAGVALS",
993 "FT.SUGADD",
994 "FT.SUGGET",
995 "FT.SUGDEL",
996 "FT.SUGLEN",
997 "FT.SYNUPDATE",
998 "FT.SYNDUMP",
999 "FT.SPELLCHECK",
1000 "FT.DICTADD",
1001 "FT.DICTDEL",
1002 "FT.DICTDUMP",
1003 "FT.INFO",
1004 "FT._LIST",
1005 "FT.CONFIG",
1006 "FT.ADD",
1007 "FT.DEL",
1008 "FT.DROP",
1009 "FT.GET",
1010 "FT.MGET",
1011 "FT.SYNADD",
1012 ],
1013 )
1015 CLUSTER_COMMANDS_RESPONSE_CALLBACKS = {
1016 "CLUSTER SLOTS": parse_cluster_slots,
1017 "CLUSTER SHARDS": parse_cluster_shards,
1018 "CLUSTER MYSHARDID": parse_cluster_myshardid,
1019 }
1021 RESULT_CALLBACKS = dict_merge(
1022 list_keys_to_dict(["PUBSUB NUMSUB", "PUBSUB SHARDNUMSUB"], parse_pubsub_numsub),
1023 list_keys_to_dict(
1024 ["PUBSUB NUMPAT"], lambda command, res: sum(list(res.values()))
1025 ),
1026 list_keys_to_dict(
1027 ["KEYS", "PUBSUB CHANNELS", "PUBSUB SHARDCHANNELS"], merge_result
1028 ),
1029 list_keys_to_dict(
1030 [
1031 "PING",
1032 "CONFIG SET",
1033 "CONFIG REWRITE",
1034 "CONFIG RESETSTAT",
1035 "CLIENT SETNAME",
1036 "BGSAVE",
1037 "SLOWLOG RESET",
1038 "SAVE",
1039 "MEMORY PURGE",
1040 "CLIENT PAUSE",
1041 "CLIENT UNPAUSE",
1042 ],
1043 lambda command, res: all(res.values()) if isinstance(res, dict) else res,
1044 ),
1045 list_keys_to_dict(
1046 ["DBSIZE", "WAIT"],
1047 lambda command, res: sum(res.values()) if isinstance(res, dict) else res,
1048 ),
1049 list_keys_to_dict(
1050 ["CLIENT UNBLOCK"], lambda command, res: 1 if sum(res.values()) > 0 else 0
1051 ),
1052 list_keys_to_dict(["BLESS SCAN", "SCAN"], parse_scan_result),
1053 list_keys_to_dict(
1054 ["SCRIPT LOAD"], lambda command, res: list(res.values()).pop()
1055 ),
1056 list_keys_to_dict(
1057 ["SCRIPT EXISTS"], lambda command, res: [all(k) for k in zip(*res.values())]
1058 ),
1059 list_keys_to_dict(["SCRIPT FLUSH"], lambda command, res: all(res.values())),
1060 )
1062 ERRORS_ALLOW_RETRY = (
1063 ConnectionError,
1064 TimeoutError,
1065 ClusterDownError,
1066 SlotNotCoveredError,
1067 )
1069 # Connection errors that do not mean the node failed: the client's own pool
1070 # is exhausted, the server is at its maxclients limit, or the credentials
1071 # were rejected. Recycling connections or refreshing the topology cannot
1072 # repair them, so the cluster clients and their pipelines re-raise them
1073 # without either, and without a retry.
1074 NOT_NODE_FAILURE_ERRORS = (
1075 AuthenticationError,
1076 MaxConnectionsError,
1077 MaxClientsReachedError,
1078 )
1080 @staticmethod
1081 def _is_retryable_cluster_error(error: Exception) -> bool:
1082 """
1083 ``is_retryable`` for a cluster retry: never retry one of
1084 ``NOT_NODE_FAILURE_ERRORS``.
1085 """
1086 return not isinstance(error, AbstractRedisCluster.NOT_NODE_FAILURE_ERRORS)
1088 @staticmethod
1089 def _retry_backoff_delay(retry: AbstractRetry, failures: int) -> float:
1090 """
1091 The delay before the next attempt of a cluster retry loop, after
1092 ``failures`` failed attempts, as computed by the retry's backoff. A
1093 duck-typed retry policy with no backoff gives no delay.
1094 """
1095 backoff = getattr(retry, "_backoff", None)
1096 if backoff is None:
1097 return 0
1098 if failures == 1:
1099 # A new run of failures starts, as in Retry.call_with_retry
1100 backoff.reset()
1101 return backoff.compute(failures)
1103 def replace_default_node(self, target_node: "ClusterNode" = None) -> None:
1104 """Replace the default cluster node.
1105 A random cluster node will be chosen if target_node isn't passed, and primaries
1106 will be prioritized. The default node will not be changed if there are no other
1107 nodes in the cluster.
1109 Args:
1110 target_node (ClusterNode, optional): Target node to replace the default
1111 node. Defaults to None.
1112 """
1113 if target_node:
1114 self.nodes_manager.default_node = target_node
1115 else:
1116 curr_node = self.get_default_node()
1117 primaries = [node for node in self.get_primaries() if node != curr_node]
1118 if primaries:
1119 # Choose a primary if the cluster contains different primaries
1120 self.nodes_manager.default_node = random.choice(primaries)
1121 else:
1122 # Otherwise, choose a primary if the cluster contains different primaries
1123 replicas = [node for node in self.get_replicas() if node != curr_node]
1124 if replicas:
1125 self.nodes_manager.default_node = random.choice(replicas)
1128class RedisCluster(
1129 AbstractRedisCluster, MaintNotificationsAbstractRedisCluster, RedisClusterCommands
1130):
1131 # Type discrimination marker for @overload self-type pattern
1132 _is_async_client: Literal[False] = False
1134 @classmethod
1135 def from_url(cls, url: str, **kwargs: Any) -> "RedisCluster":
1136 """
1137 Return a Redis client object configured from the given URL
1139 For example::
1141 redis://[[username]:[password]]@localhost:6379/0
1142 rediss://[[username]:[password]]@localhost:6379/0
1143 unix://[username@]/path/to/socket.sock?db=0[&password=password]
1145 Three URL schemes are supported:
1147 - `redis://` creates a TCP socket connection. See more at:
1148 <https://www.iana.org/assignments/uri-schemes/prov/redis>
1149 - `rediss://` creates a SSL wrapped TCP socket connection. See more at:
1150 <https://www.iana.org/assignments/uri-schemes/prov/rediss>
1151 - ``unix://``: creates a Unix Domain Socket connection.
1153 The username, password, hostname and path are passed through
1154 urllib.parse.unquote in order to replace any percent-encoded values
1155 with their corresponding characters. Querystring values are decoded
1156 by urllib.parse.parse_qs and are not unquoted again.
1158 There are several ways to specify a database number. The first value
1159 found will be used:
1161 1. A ``db`` querystring option, e.g. redis://localhost?db=0
1162 2. If using the redis:// or rediss:// schemes, the path argument
1163 of the url, e.g. redis://localhost/0
1164 3. A ``db`` keyword argument to this function.
1166 If none of these options are specified, the default db=0 is used.
1168 All querystring options are cast to their appropriate Python types.
1169 Boolean arguments can be specified with string values "True"/"False"
1170 or "Yes"/"No". Values that cannot be properly cast cause a
1171 ``ValueError`` to be raised. Once parsed, the querystring arguments
1172 and keyword arguments are passed to the ``ConnectionPool``'s
1173 class initializer. In the case of conflicting arguments, querystring
1174 arguments always win.
1176 """
1177 return cls(url=url, **kwargs)
1179 @deprecated_args(
1180 args_to_warn=["read_from_replicas"],
1181 reason="Please configure the 'load_balancing_strategy' instead",
1182 version="5.3.0",
1183 )
1184 @deprecated_args(
1185 args_to_warn=[
1186 "cluster_error_retry_attempts",
1187 ],
1188 reason="Please configure the 'retry' object instead",
1189 version="6.0.0",
1190 )
1191 def __init__(
1192 self,
1193 host: str | None = None,
1194 port: int = 6379,
1195 startup_nodes: List["ClusterNode"] | None = None,
1196 cluster_error_retry_attempts: int = DEFAULT_RETRY_COUNT,
1197 retry: Retry | None = None,
1198 require_full_coverage: bool = True,
1199 reinitialize_steps: int = 5,
1200 read_from_replicas: bool = False,
1201 load_balancing_strategy: "LoadBalancingStrategy | None" = None,
1202 dynamic_startup_nodes: bool = True,
1203 url: str | None = None,
1204 address_remap: Callable[[Tuple[str, int]], Tuple[str, int]] | None = None,
1205 cache: CacheInterface | None = None,
1206 cache_config: CacheConfig | None = None,
1207 event_dispatcher: EventDispatcher | None = None,
1208 policy_resolver: PolicyResolver | None = None,
1209 maint_notifications_config: MaintNotificationsConfig | None = None,
1210 metadata_resolver: MetadataResolver | None = None,
1211 topology_refresh_min_interval: float | None = None,
1212 **kwargs,
1213 ):
1214 """
1215 Initialize a new RedisCluster client.
1217 :param startup_nodes:
1218 List of nodes from which initial bootstrapping can be done
1219 :param host:
1220 Can be used to point to a startup node
1221 :param port:
1222 Can be used to point to a startup node
1223 :param require_full_coverage:
1224 When set to False (default value): the client will not require a
1225 full coverage of the slots. However, if not all slots are covered,
1226 and at least one node has 'cluster-require-full-coverage' set to
1227 'yes,' the server will throw a ClusterDownError for some key-based
1228 commands. See -
1229 https://redis.io/topics/cluster-tutorial#redis-cluster-configuration-parameters
1230 When set to True: all slots must be covered to construct the
1231 cluster client. If not all slots are covered, RedisClusterException
1232 will be thrown.
1233 :param read_from_replicas:
1234 @deprecated - please use load_balancing_strategy instead
1235 Enable read from replicas in READONLY mode. You can read possibly
1236 stale data.
1237 When set to true, read commands will be assigned between the
1238 primary and its replications in a Round-Robin manner.
1239 :param load_balancing_strategy:
1240 Enable read from replicas in READONLY mode and defines the load balancing
1241 strategy that will be used for cluster node selection.
1242 The data read from replicas is eventually consistent with the data in primary nodes.
1243 :param dynamic_startup_nodes:
1244 Set the RedisCluster's startup nodes to all of the discovered nodes.
1245 If true (default value), the cluster's discovered nodes will be used to
1246 determine the cluster nodes-slots mapping in the next topology refresh.
1247 It will remove the initial passed startup nodes if their endpoints aren't
1248 listed in the CLUSTER SLOTS output.
1249 If you use dynamic DNS endpoints for startup nodes but CLUSTER SLOTS lists
1250 specific IP addresses, it is best to set it to false.
1251 Either way, a topology refresh that gets no slot map covering all
1252 slots from the startup nodes also asks the nodes of the current
1253 topology.
1254 :param cluster_error_retry_attempts:
1255 @deprecated - Please configure the 'retry' object instead
1256 In case 'retry' object is set - this argument is ignored!
1258 Number of times to retry before raising an error when
1259 :class:`~.TimeoutError` or :class:`~.ConnectionError`, :class:`~.SlotNotCoveredError` or
1260 :class:`~.ClusterDownError` are encountered, or when a node cached as a
1261 primary answers with :class:`~.ReadOnlyError`
1262 :param retry:
1263 A retry object that defines the retry strategy and the number of
1264 retries for the cluster client. Its backoff sets the delay before
1265 each retry of a command or a pipeline; one that failed with
1266 :class:`~.ClusterDownError` or :class:`~.SlotNotCoveredError` also
1267 waits a fixed 0.25 seconds before it. A topology refresh triggered
1268 by an error (connection errors, the ``reinitialize_steps`` MOVED
1269 threshold) is run by the first command attempt to start once it is
1270 due, at most once per ``topology_refresh_min_interval``; after
1271 refreshes that failed in a row, the next one waits as long as the
1272 backoff gives for that many failures, but at least
1273 ``topology_refresh_min_interval``. A command that failed with a
1274 connection error or a timeout gives up with
1275 :class:`~.RedisClusterUnreachableError` once a refresh that ended
1276 since reached no node, or when it runs out of retries while the
1277 last refresh did.
1278 Backoffs that keep state between calls
1279 (:class:`~.DecorrelatedJitterBackoff`) are not fully supported: the
1280 retry object is shared by every command and pipeline of the client,
1281 so concurrent retries reset and advance each other's backoff, and
1282 the delays can come out shorter or longer than configured.
1283 :param reinitialize_steps:
1284 Specifies the number of MOVED errors that need to occur before
1285 reinitializing the whole cluster topology. If a MOVED error occurs
1286 and the cluster does not need to be reinitialized on this current
1287 error handling, only the MOVED slot will be patched with the
1288 redirected node.
1289 To reinitialize the cluster on every MOVED error, set
1290 reinitialize_steps to 1.
1291 To avoid reinitializing the cluster on moved errors, set
1292 reinitialize_steps to 0. A negative value is not the same as 0: it
1293 works like its absolute value (-3 is the same as 3).
1294 Every MOVED error patches its slot, so the redirect goes to the new
1295 owner; the refresh is only asked for, and like every refresh
1296 triggered by an error, it is run by the next command attempt once
1297 due, at most once per ``topology_refresh_min_interval``.
1298 :param address_remap:
1299 An optional callable which, when provided with an internal network
1300 address of a node, e.g. a `(host, port)` tuple, will return the address
1301 where the node is reachable. This can be used to map the addresses at
1302 which the nodes _think_ they are, to addresses at which a client may
1303 reach them, such as when they sit behind a proxy.
1305 :param policy_resolver:
1306 Decides the request/response policies each command is routed by - see
1307 `redis.commands.policies.PolicyResolver`. Defaults to a
1308 `StaticPolicyResolver` built for this client, which resolves the command
1309 metadata this library ships. A resolver built from a live `COMMAND` reply is a
1310 snapshot of the server it was read from, so give each client its own rather
1311 than sharing one across clients on different servers.
1312 This is the narrow routing view of `metadata_resolver`, which supersedes it:
1313 prefer `metadata_resolver`, which serves routing and every other
1314 command-metadata consumer from one object. When both are given this one still
1315 decides which nodes a command targets, so that its 7.1.0 behavior does not
1316 move. It does not decide anything the routing view cannot express: replica
1317 safety and client-side-cache eligibility keep coming from `metadata_resolver`,
1318 because a `CommandPolicies` record carries no `is_readonly` flag to answer them
1319 with.
1320 :param metadata_resolver:
1321 Serves the command metadata this client reads - see
1322 `redis.commands.metadata.MetadataResolver`. Routing is derived from it, and it
1323 is handed to every node's client, where it also decides which commands are
1324 eligible for client-side caching. Defaults to a `StaticMetadataResolver` built
1325 for this client, which resolves the command metadata this library ships; the
1326 library never reads `COMMAND` on its own behalf for this, so the default adds no
1327 round trips. Resolvers chain through `with_fallback`, first match wins, so one
1328 placed in front of `StaticMetadataResolver` overrides the commands it carries
1329 while the static records answer for everything else. To decide eligibility and
1330 routing from the connected server, pass a `DynamicMetadataResolver` built from a
1331 live `COMMAND` reply - use it with care, because reading that reply relies on a
1332 class in the private `redis._parsers` package. Note that a server-derived resolver
1333 decides routing here too, and the live tips route some commands differently from
1334 the shipped records. `MGET` is split by hash slot instead of raising for keys in
1335 different slots. `MSET`, `DEL` and `UNLINK` are split by hash slot too. A split
1336 `MSET` is not atomic: if one slot fails, the keys of the other slots are still
1337 written. `DBSIZE` and `KEYS` are sent to every primary instead of the default
1338 node. So pair such a resolver with an explicit
1339 `policy_resolver=StaticPolicyResolver()` to keep routing on the shipped records.
1340 :param maint_notifications_config:
1341 Configures the nodes connections to support maintenance notifications - see
1342 `redis.maint_notifications.MaintNotificationsConfig` for details.
1343 Only supported with RESP3.
1344 If not provided and protocol is RESP3, the maintenance notifications
1345 will be enabled by default (logic is included in the NodesManager
1346 initialization).
1347 :param topology_refresh_min_interval:
1348 The minimum number of seconds between two topology refreshes
1349 triggered by errors (connection errors, the ``reinitialize_steps``
1350 MOVED threshold, pipeline failures, pubsub repair). Requests made in
1351 between are collapsed into one refresh, run by the next command
1352 attempt once the interval has passed. After refreshes that failed in
1353 a row, the ``retry`` backoff can make the wait longer, never shorter.
1354 0 lets every requested refresh run at once. Must be finite and not negative.
1355 Server-pushed refreshes (SMIGRATED), the first initialization and the
1356 refresh a ``CLUSTERDOWN`` or an uncovered slot runs are not limited.
1357 Defaults to one second when not set.
1358 :**kwargs:
1359 Extra arguments that will be sent into Redis instance when created
1360 (See Official redis-py doc for supported kwargs - the only limitation
1361 is that you can't provide 'retry' object as part of kwargs.
1362 [https://github.com/andymccurdy/redis-py/blob/master/redis/client.py])
1363 Some kwargs are not supported and will raise a
1364 RedisClusterException:
1365 - db (Redis do not support database SELECT in cluster mode)
1367 """
1368 if startup_nodes is None:
1369 startup_nodes = []
1371 if "db" in kwargs:
1372 # Argument 'db' is not possible to use in cluster mode
1373 raise RedisClusterException(
1374 "Argument 'db' is not possible to use in cluster mode"
1375 )
1377 if "retry" in kwargs:
1378 # Argument 'retry' is not possible to be used in kwargs when in cluster mode
1379 # the kwargs are set to the lower level connections to the cluster nodes
1380 # and there we provide retry configuration without retries allowed.
1381 # The retries should be handled on cluster client level.
1382 raise RedisClusterException(
1383 "The 'retry' argument cannot be used in kwargs when running in cluster mode."
1384 )
1386 if kwargs.get("ssl") and not issubclass(
1387 kwargs.get("connection_class", SSLConnection), SSLConnection
1388 ):
1389 raise RedisClusterException(
1390 "The 'ssl' argument requires 'connection_class' to be an "
1391 "SSLConnection subclass"
1392 )
1394 if kwargs.pop("unix_socket_path", None) is not None:
1395 raise RedisClusterException(
1396 "RedisCluster does not currently support Unix Domain Socket connections"
1397 )
1399 if topology_refresh_min_interval is not None and (
1400 not math.isfinite(topology_refresh_min_interval)
1401 or topology_refresh_min_interval < 0
1402 ):
1403 raise RedisClusterException(
1404 "Argument 'topology_refresh_min_interval' must be a finite,"
1405 " non-negative number"
1406 )
1408 # Get the startup node/s
1409 from_url = False
1410 if url is not None:
1411 from_url = True
1412 url_options = parse_url(url)
1413 if "path" in url_options:
1414 raise RedisClusterException(
1415 "RedisCluster does not currently support Unix Domain "
1416 "Socket connections"
1417 )
1418 if "db" in url_options and url_options["db"] != 0:
1419 # Argument 'db' is not possible to use in cluster mode
1420 raise RedisClusterException(
1421 "A ``db`` querystring option can only be 0 in cluster mode"
1422 )
1423 kwargs.update(url_options)
1424 host = kwargs.get("host")
1425 port = kwargs.get("port", port)
1426 startup_nodes.append(ClusterNode(host, port))
1427 elif host is not None and port is not None:
1428 startup_nodes.append(ClusterNode(host, port))
1429 elif len(startup_nodes) == 0:
1430 # No startup node was provided
1431 raise RedisClusterException(
1432 "RedisCluster requires at least one node to discover the "
1433 "cluster. Please provide one of the following:\n"
1434 "1. host and port, for example:\n"
1435 " RedisCluster(host='localhost', port=6379)\n"
1436 "2. list of startup nodes, for example:\n"
1437 " RedisCluster(startup_nodes=[ClusterNode('localhost', 6379),"
1438 " ClusterNode('localhost', 6378)])"
1439 )
1440 # Update the connection arguments
1441 # Whenever a new connection is established, RedisCluster's on_connect
1442 # method should be run
1443 # If the user passed on_connect function we'll save it and run it
1444 # inside the RedisCluster.on_connect() function
1445 self.user_on_connect_func = kwargs.pop("redis_connect_func", None)
1446 kwargs.update({"redis_connect_func": self.on_connect})
1447 kwargs = cleanup_kwargs(**kwargs)
1448 if retry:
1449 self.retry = retry
1450 else:
1451 self.retry = Retry(
1452 backoff=ExponentialWithJitterBackoff(
1453 base=DEFAULT_RETRY_BASE, cap=DEFAULT_RETRY_CAP
1454 ),
1455 retries=cluster_error_retry_attempts,
1456 )
1458 self.encoder = Encoder(
1459 kwargs.get("encoding", "utf-8"),
1460 kwargs.get("encoding_errors", "strict"),
1461 kwargs.get("decode_responses", False),
1462 )
1463 protocol = kwargs.get("protocol", None)
1464 if (cache_config or cache) and not check_protocol_version(protocol, 3):
1465 raise RedisError("Client caching is only supported with RESP version 3")
1467 if (
1468 maint_notifications_config
1469 and maint_notifications_config.enabled
1470 and not check_protocol_version(protocol, 3)
1471 ):
1472 raise RedisError(
1473 "Maintenance notifications are only supported with RESP version 3"
1474 )
1475 if check_protocol_version(protocol, 3) and maint_notifications_config is None:
1476 maint_notifications_config = MaintNotificationsConfig()
1478 # Build the client-level HIMPORT registry once (always empty at construction)
1479 # and share the same object with every node pool, so the fieldset registry is
1480 # shared cluster-wide and runtime himport_prepare mutates one object. It is
1481 # handed to the NodesManager and injected onto each node's pool in
1482 # create_redis_node; it is deliberately NOT forwarded through connection_kwargs,
1483 # so nodes reuse the one shared object rather than each rebuilding their own.
1484 self._himport_registry = HImportRegistry()
1486 self.command_flags = self.__class__.COMMAND_FLAGS.copy()
1487 self.node_flags = self.__class__.NODE_FLAGS.copy()
1488 self.read_from_replicas = read_from_replicas
1489 self.load_balancing_strategy = load_balancing_strategy
1490 self.reinitialize_counter = 0
1491 self.reinitialize_steps = reinitialize_steps
1492 if event_dispatcher is None:
1493 self._event_dispatcher = EventDispatcher()
1494 else:
1495 self._event_dispatcher = event_dispatcher
1496 self.startup_nodes = startup_nodes
1498 # Built here rather than defaulted in the signature, so that each client owns its
1499 # resolver and the memos it accumulates are released with the client. The one object
1500 # is shared with every node's client below, so a cluster resolves command metadata -
1501 # routing and cache eligibility both - from a single source of truth.
1502 if metadata_resolver is None:
1503 self._metadata_resolver: MetadataResolver = StaticMetadataResolver()
1504 else:
1505 self._metadata_resolver = metadata_resolver
1507 self.nodes_manager = NodesManager(
1508 startup_nodes=startup_nodes,
1509 from_url=from_url,
1510 require_full_coverage=require_full_coverage,
1511 dynamic_startup_nodes=dynamic_startup_nodes,
1512 address_remap=address_remap,
1513 cache=cache,
1514 cache_config=cache_config,
1515 metadata_resolver=self._metadata_resolver,
1516 event_dispatcher=self._event_dispatcher,
1517 maint_notifications_config=maint_notifications_config,
1518 himport_registry=self._himport_registry,
1519 topology_refresh_min_interval=topology_refresh_min_interval,
1520 **kwargs,
1521 )
1523 cluster_response_callbacks = dict(
1524 self.__class__.CLUSTER_COMMANDS_RESPONSE_CALLBACKS
1525 )
1526 legacy_responses = kwargs.get("legacy_responses", True)
1527 protocol = kwargs.get("protocol")
1528 if not legacy_responses:
1529 cluster_response_callbacks["CLUSTER SHARDS"] = parse_cluster_shards_unified
1530 elif protocol is None:
1531 cluster_response_callbacks["CLUSTER SHARDS"] = (
1532 parse_cluster_shards_with_str_keys
1533 )
1534 self.cluster_response_callbacks = CaseInsensitiveDict(
1535 cluster_response_callbacks
1536 )
1537 self.result_callbacks = CaseInsensitiveDict(self.__class__.RESULT_CALLBACKS)
1539 # For backward compatibility, mapping from existing policies to new one
1540 self._command_flags_mapping: dict[str, Union[RequestPolicy, ResponsePolicy]] = {
1541 self.__class__.RANDOM: RequestPolicy.DEFAULT_KEYLESS,
1542 self.__class__.PRIMARIES: RequestPolicy.ALL_SHARDS,
1543 self.__class__.ALL_NODES: RequestPolicy.ALL_NODES,
1544 self.__class__.REPLICAS: RequestPolicy.ALL_REPLICAS,
1545 self.__class__.DEFAULT_NODE: RequestPolicy.DEFAULT_NODE,
1546 SLOT_ID: RequestPolicy.DEFAULT_KEYED,
1547 }
1549 # ``policy_resolver`` is the routing view of a metadata resolver, so the two
1550 # arguments overlap. Resolved by precedence rather than by rejecting the
1551 # combination, because a user migrating from one to the other will legitimately pass
1552 # both: an explicit ``policy_resolver`` - the extension point that shipped in 7.1.0
1553 # - keeps deciding which nodes a command targets, and otherwise those policies are
1554 # derived from the metadata resolver.
1555 #
1556 # The precedence covers the routing view only. Replica safety and cache eligibility
1557 # are read from ``_metadata_resolver`` either way, because the projection a policy
1558 # resolver serves drops the flags they are decided from - a ``CommandPolicies``
1559 # record has no ``is_readonly``. So "ignores metadata_resolver" below means for the
1560 # target-node decision, not for the record as a whole.
1561 if policy_resolver is None:
1562 self._policy_resolver: PolicyResolver = StaticPolicyResolver(
1563 metadata_resolver=self._metadata_resolver
1564 )
1565 else:
1566 self._policy_resolver = policy_resolver
1567 if metadata_resolver is not None:
1568 logger.debug(
1569 "Both policy_resolver and metadata_resolver were given; the nodes a "
1570 "command targets resolve through policy_resolver and ignore "
1571 "metadata_resolver. Replica safety and client-side-cache eligibility "
1572 "still resolve through metadata_resolver."
1573 )
1574 self.commands_parser = CommandsParser(self)
1576 # Node where FT.AGGREGATE command is executed.
1577 self._aggregate_nodes = None
1578 self._lock = threading.RLock()
1580 MaintNotificationsAbstractRedisCluster.__init__(
1581 self, maint_notifications_config, **kwargs
1582 )
1584 def __enter__(self):
1585 return self
1587 def __exit__(self, exc_type, exc_value, traceback):
1588 self.close()
1590 def __del__(self):
1591 try:
1592 self.close()
1593 except Exception:
1594 pass
1596 def disconnect_connection_pools(self):
1597 for node in self.get_nodes():
1598 if node.redis_connection:
1599 try:
1600 node.redis_connection.connection_pool.disconnect()
1601 except OSError:
1602 # Client was already disconnected. do nothing
1603 pass
1605 def on_connect(self, connection):
1606 """
1607 Initialize the connection, authenticate and select a database and send
1608 READONLY if it is set during object initialization.
1609 """
1610 connection.on_connect()
1612 if self.read_from_replicas or self.load_balancing_strategy:
1613 # Sending READONLY command to server to configure connection as
1614 # readonly. Since each cluster node may change its server type due
1615 # to a failover, we should establish a READONLY connection
1616 # regardless of the server type. If this is a primary connection,
1617 # READONLY would not affect executing write commands.
1618 connection.send_command("READONLY")
1619 if str_if_bytes(connection.read_response()) != "OK":
1620 raise ConnectionError("READONLY command failed")
1622 if self.user_on_connect_func is not None:
1623 self.user_on_connect_func(connection)
1625 def get_redis_connection(self, node: "ClusterNode") -> Redis:
1626 if not node.redis_connection:
1627 with self._lock:
1628 if not node.redis_connection:
1629 self.nodes_manager.create_redis_connections([node])
1630 return node.redis_connection
1632 def get_node(self, host=None, port=None, node_name=None):
1633 return self.nodes_manager.get_node(host, port, node_name)
1635 def get_primaries(self):
1636 return self.nodes_manager.get_nodes_by_server_type(PRIMARY)
1638 def get_replicas(self):
1639 return self.nodes_manager.get_nodes_by_server_type(REPLICA)
1641 def get_random_node(self):
1642 return random.choice(list(self.nodes_manager.nodes_cache.values()))
1644 def get_keyless_target_node(self, command_name: str) -> "ClusterNode":
1645 """
1646 Returns the node a keyless command is routed to: a random node when replica reads
1647 are enabled and the command is safe to serve from a replica, a random primary
1648 otherwise.
1650 A replicas-only ``load_balancing_strategy`` is honored by picking from the replicas
1651 alone, so a strategy that asks for replicas cannot land on a primary here. The
1652 strategy is not applied any further than that: the rest of it is an index into one
1653 shard's node list and a round-robin counter kept per primary name, and a keyless
1654 command has no shard to index - so the pick is uniform over the eligible nodes.
1656 Falls back to the whole node set when the cluster has no replicas to pick from,
1657 which is every primary. That is also the answer for the two strategies that
1658 include the primary, and for ``read_from_replicas`` on its own, which is what this
1659 method has returned for a replica-safe command since 7.1.0.
1660 """
1661 replica_safe = (
1662 self.read_from_replicas or self.load_balancing_strategy is not None
1663 ) and self._is_replica_safe(command_name)
1664 if replica_safe:
1665 if self.load_balancing_strategy in _REPLICAS_ONLY_STRATEGIES:
1666 replicas = self.get_replicas()
1667 if replicas:
1668 return random.choice(replicas)
1670 return self.get_random_node()
1672 return self.get_random_primary_node()
1674 @deprecated_function(
1675 version="8.2.0",
1676 reason="Use get_keyless_target_node() instead.",
1677 )
1678 def get_random_primary_or_all_nodes(self, command_name: str) -> "ClusterNode":
1679 """
1680 Returns random primary or all nodes depends on READONLY mode.
1682 Deprecated alias of :meth:`get_keyless_target_node`. Kept so the name that has
1683 been public since 7.1.0 keeps working; it answers from the metadata resolver just
1684 as the new name does.
1685 """
1686 return self.get_keyless_target_node(command_name)
1688 def _is_replica_safe(self, command_name: str) -> bool:
1689 return self._metadata_resolver.is_replica_safe(command_name)
1691 def get_nodes(self):
1692 return list(self.nodes_manager.nodes_cache.values())
1694 def get_node_from_key(self, key, replica=False):
1695 """
1696 Get the node that holds the key's slot.
1697 If replica set to True but the slot doesn't have any replicas, None is
1698 returned.
1699 """
1700 slot = self.keyslot(key)
1701 slot_cache = self.nodes_manager.slots_cache.get(slot)
1702 if slot_cache is None or len(slot_cache) == 0:
1703 raise SlotNotCoveredError(f'Slot "{slot}" is not covered by the cluster.')
1704 if replica and len(self.nodes_manager.slots_cache[slot]) < 2:
1705 return None
1706 elif replica:
1707 node_idx = 1
1708 else:
1709 # primary
1710 node_idx = 0
1712 return slot_cache[node_idx]
1714 def get_default_node(self):
1715 """
1716 Get the cluster's default node
1717 """
1718 return self.nodes_manager.default_node
1720 def get_nodes_from_slot(self, command: str, *args):
1721 """
1722 Returns a list of nodes that hold the specified keys' slots.
1723 """
1724 # get the node that holds the key's slot
1725 slot = self.determine_slot(*args)
1726 replica_safe = (
1727 self.read_from_replicas or self.load_balancing_strategy is not None
1728 ) and self._is_replica_safe(command)
1729 return [
1730 self.nodes_manager.get_node_from_slot(
1731 slot,
1732 replica_safe,
1733 self.load_balancing_strategy if replica_safe else None,
1734 )
1735 ]
1737 def _get_node_from_slot(self, command: str, slot: int) -> "ClusterNode":
1738 """
1739 Returns the node a command for the given slot is sent to, a replica when the
1740 command is replica safe and the client reads from replicas - for a command whose
1741 slot is already known, so its keys are not hashed again.
1742 """
1743 replica_safe = (
1744 self.read_from_replicas or self.load_balancing_strategy is not None
1745 ) and self._is_replica_safe(command)
1746 return self.nodes_manager.get_node_from_slot(
1747 slot,
1748 replica_safe,
1749 self.load_balancing_strategy if replica_safe else None,
1750 )
1752 def _split_multi_shard_command(self, *args) -> Optional[List[_MultiShardSplit]]:
1753 """
1754 Splits a command with the MULTI_SHARD request policy into one command per hash
1755 slot of its keys - see ``_split_by_slot``.
1756 """
1757 return _split_by_slot(
1758 args, self.commands_parser.commands.get(args[0].lower()), self.keyslot
1759 )
1761 def _execute_multi_shard_command(
1762 self,
1763 command: str,
1764 splits: List[_MultiShardSplit],
1765 response_policy: ResponsePolicy,
1766 **kwargs,
1767 ):
1768 """
1769 Sends the commands of a split MULTI_SHARD command in one pipeline and merges the
1770 replies - see ``_merge_multi_shard_replies``.
1772 The pipeline batches the commands per node, so the command costs one round trip
1773 per node rather than one per slot. Each command names the node holding its slot,
1774 so the pipeline does not split it again, and a command that fails is retried on its
1775 own, routed by its keys: the pipeline retries a connection error or a redirection,
1776 and the errors only the client retries - CLUSTERDOWN, or a slot the client knows
1777 no node for - are resent here, with the retries of a command sent on its own. A
1778 slot that succeeded is therefore not sent again, which would run a write twice
1779 and change what a summed reply counts. The failed slots are resent one at a time.
1780 """
1781 # Run a topology refresh an earlier error asked for first, as the retry loop of a
1782 # command sent on its own does, so the slots are routed by the refreshed topology
1783 if self.nodes_manager._refresh_requested:
1784 self.nodes_manager._run_requested_refresh(self.retry)
1785 replica_safe = (
1786 self.read_from_replicas or self.load_balancing_strategy is not None
1787 ) and self._is_replica_safe(command)
1788 load_balancing_strategy = self.load_balancing_strategy if replica_safe else None
1789 pipe = self.pipeline()
1790 replies: List[Any] = [None] * len(splits)
1791 # The node each slot's command is queued for. None for a slot that is not queued
1792 # or is resent: its error is recorded by the command that raised it.
1793 nodes: List[Optional[ClusterNode]] = [None] * len(splits)
1794 for index, (slot, slot_args, _, keys) in enumerate(splits):
1795 try:
1796 nodes[index] = self.nodes_manager.get_node_from_slot(
1797 slot, replica_safe, load_balancing_strategy
1798 )
1799 except SlotNotCoveredError as e:
1800 replies[index] = e
1801 continue
1802 pipe.execute_command(
1803 *slot_args, target_nodes=[nodes[index]], **_with_keys(kwargs, keys)
1804 )
1806 queued = [index for index, node in enumerate(nodes) if node is not None]
1807 for index, reply in zip(queued, pipe.execute(raise_on_error=False)):
1808 replies[index] = reply
1809 for index, ((_, slot_args, _, keys), reply) in enumerate(zip(splits, replies)):
1810 if isinstance(reply, self.ERRORS_ALLOW_RETRY) and not isinstance(
1811 reply, ClusterPipeline.ERRORS_ALLOW_RETRY
1812 ):
1813 nodes[index] = None
1814 try:
1815 replies[index] = self.execute_command(
1816 *slot_args, **_with_keys(kwargs, keys)
1817 )
1818 except RedisError as e:
1819 replies[index] = e
1821 slot_replies: Dict[int, Any] = {}
1822 for index, ((slot, _, _, _), reply) in enumerate(zip(splits, replies)):
1823 if isinstance(reply, BaseException):
1824 # A command sent on its own counts the error it fails with. The pipeline
1825 # counts none, so an error read from it is counted here; one a retry
1826 # raised carries the connection its command already counted it on.
1827 node = nodes[index]
1828 if node is not None and not hasattr(reply, "connection"):
1829 self._record_error_metric(
1830 error=reply, connection=node, is_internal=False
1831 )
1832 raise reply
1833 slot_replies[slot] = reply
1834 return _merge_multi_shard_replies(slot_replies, splits, response_policy)
1836 def _execute_multi_shard_command_per_slot(
1837 self,
1838 command: str,
1839 splits: List[_MultiShardSplit],
1840 response_policy: ResponsePolicy,
1841 slot_replies: Dict[int, Any],
1842 **kwargs,
1843 ):
1844 """
1845 Sends each command of a split MULTI_SHARD command to the node holding its slot on
1846 its own, and merges the replies - see ``_merge_multi_shard_replies``. Used instead
1847 of ``_execute_multi_shard_command`` when the client caches replies: a pipeline
1848 never reads the client-side cache, while a command sent on its own may be answered
1849 from it.
1851 ``slot_replies`` holds the replies of the slots that already succeeded. The caller
1852 keeps it across its retry attempts, so a retry resends only the slots that failed:
1853 resending one that succeeded would run a write twice and change what a summed reply
1854 counts. A slot is fixed by its keys, so it names the same command on every attempt,
1855 while its node is looked up again in case the topology changed.
1856 """
1857 replica_safe = (
1858 self.read_from_replicas or self.load_balancing_strategy is not None
1859 ) and self._is_replica_safe(command)
1860 load_balancing_strategy = self.load_balancing_strategy if replica_safe else None
1861 for slot, slot_args, _, keys in splits:
1862 if slot in slot_replies:
1863 continue
1864 node = self.nodes_manager.get_node_from_slot(
1865 slot, replica_safe, load_balancing_strategy
1866 )
1867 slot_replies[slot] = self._execute_command(
1868 node, *slot_args, **_with_keys(kwargs, keys)
1869 )
1871 return _merge_multi_shard_replies(slot_replies, splits, response_policy)
1873 def get_special_nodes(self) -> Optional[list["ClusterNode"]]:
1874 """
1875 Returns a list of nodes for commands with a special policy.
1876 """
1877 if not self._aggregate_nodes:
1878 raise RedisClusterException(
1879 "Cannot execute FT.CURSOR commands without FT.AGGREGATE"
1880 )
1882 return self._aggregate_nodes
1884 def get_random_primary_node(self) -> "ClusterNode":
1885 """
1886 Returns a random primary node
1887 """
1888 return random.choice(self.get_primaries())
1890 def set_default_node(self, node):
1891 """
1892 Set the default node of the cluster.
1893 :param node: 'ClusterNode'
1894 :return True if the default node was set, else False
1895 """
1896 if node is None or self.get_node(node_name=node.name) is None:
1897 return False
1898 self.nodes_manager.default_node = node
1899 return True
1901 def set_retry(self, retry: Retry) -> None:
1902 self.retry = retry
1904 def monitor(self, target_node=None):
1905 """
1906 Returns a Monitor object for the specified target node.
1907 The default cluster node will be selected if no target node was
1908 specified.
1909 Monitor is useful for handling the MONITOR command to the redis server.
1910 next_command() method returns one command from monitor
1911 listen() method yields commands from monitor.
1912 """
1913 if target_node is None:
1914 target_node = self.get_default_node()
1915 if target_node.redis_connection is None:
1916 raise RedisClusterException(
1917 f"Cluster Node {target_node.name} has no redis_connection"
1918 )
1919 return target_node.redis_connection.monitor()
1921 def pubsub(
1922 self,
1923 node: "ClusterNode | None" = None,
1924 host: str | None = None,
1925 port: int | None = None,
1926 **kwargs: Any,
1927 ) -> "ClusterPubSub":
1928 """
1929 Allows passing a ClusterNode, or host&port, to get a pubsub instance
1930 connected to the specified node
1931 """
1932 return ClusterPubSub(self, node=node, host=host, port=port, **kwargs)
1934 def keyspace_notifications(
1935 self,
1936 key_prefix: Union[str, bytes, None] = None,
1937 ignore_subscribe_messages: bool = True,
1938 ) -> "ClusterKeyspaceNotifications":
1939 """
1940 Return a :class:`~redis.keyspace_notifications.ClusterKeyspaceNotifications`
1941 object for subscribing to keyspace and keyevent notifications across
1942 all primary nodes in the cluster.
1944 Note: Keyspace notifications must be enabled on all Redis cluster nodes
1945 via the ``notify-keyspace-events`` configuration option.
1947 Args:
1948 key_prefix: Optional prefix to filter and strip from keys in
1949 notifications.
1950 ignore_subscribe_messages: If True, subscribe/unsubscribe
1951 confirmations are not returned by
1952 get_message/listen.
1953 """
1954 from redis.keyspace_notifications import ClusterKeyspaceNotifications
1956 return ClusterKeyspaceNotifications(
1957 self,
1958 key_prefix=key_prefix,
1959 ignore_subscribe_messages=ignore_subscribe_messages,
1960 )
1962 def pipeline(self, transaction=None, shard_hint=None):
1963 """
1964 Cluster impl:
1965 Pipelines do not work in cluster mode the same way they
1966 do in normal mode. Create a clone of this object so
1967 that simulating pipelines will work correctly. Each
1968 command will be called directly when used and
1969 when calling execute() will only return the result stack.
1970 """
1971 if shard_hint:
1972 raise RedisClusterException("shard_hint is deprecated in cluster mode")
1974 return ClusterPipeline(
1975 nodes_manager=self.nodes_manager,
1976 commands_parser=self.commands_parser,
1977 startup_nodes=self.nodes_manager.startup_nodes,
1978 result_callbacks=self.result_callbacks,
1979 cluster_response_callbacks=self.cluster_response_callbacks,
1980 read_from_replicas=self.read_from_replicas,
1981 load_balancing_strategy=self.load_balancing_strategy,
1982 reinitialize_steps=self.reinitialize_steps,
1983 retry=self.retry,
1984 lock=self._lock,
1985 transaction=transaction,
1986 # Routing must not change just because the commands go through a pipeline, so the
1987 # pipeline resolves through the same objects the client does.
1988 policy_resolver=self._policy_resolver,
1989 metadata_resolver=self._metadata_resolver,
1990 event_dispatcher=self._event_dispatcher,
1991 )
1993 def lock(
1994 self,
1995 name,
1996 timeout=None,
1997 sleep=0.1,
1998 blocking=True,
1999 blocking_timeout=None,
2000 lock_class=None,
2001 thread_local=True,
2002 raise_on_release_error: bool = True,
2003 ):
2004 """
2005 Return a new Lock object using key ``name`` that mimics
2006 the behavior of threading.Lock.
2008 If specified, ``timeout`` indicates a maximum life for the lock.
2009 By default, it will remain locked until release() is called.
2011 ``sleep`` indicates the amount of time to sleep per loop iteration
2012 when the lock is in blocking mode and another client is currently
2013 holding the lock.
2015 ``blocking`` indicates whether calling ``acquire`` should block until
2016 the lock has been acquired or to fail immediately, causing ``acquire``
2017 to return False and the lock not being acquired. Defaults to True.
2018 Note this value can be overridden by passing a ``blocking``
2019 argument to ``acquire``.
2021 ``blocking_timeout`` indicates the maximum amount of time in seconds to
2022 spend trying to acquire the lock. A value of ``None`` indicates
2023 continue trying forever. ``blocking_timeout`` can be specified as a
2024 float or integer, both representing the number of seconds to wait.
2026 ``lock_class`` forces the specified lock implementation. Note that as
2027 of redis-py 3.0, the only lock class we implement is ``Lock`` (which is
2028 a Lua-based lock). So, it's unlikely you'll need this parameter, unless
2029 you have created your own custom lock class.
2031 ``thread_local`` indicates whether the lock token is placed in
2032 thread-local storage. By default, the token is placed in thread local
2033 storage so that a thread only sees its token, not a token set by
2034 another thread. Consider the following timeline:
2036 time: 0, thread-1 acquires `my-lock`, with a timeout of 5 seconds.
2037 thread-1 sets the token to "abc"
2038 time: 1, thread-2 blocks trying to acquire `my-lock` using the
2039 Lock instance.
2040 time: 5, thread-1 has not yet completed. redis expires the lock
2041 key.
2042 time: 5, thread-2 acquired `my-lock` now that it's available.
2043 thread-2 sets the token to "xyz"
2044 time: 6, thread-1 finishes its work and calls release(). if the
2045 token is *not* stored in thread local storage, then
2046 thread-1 would see the token value as "xyz" and would be
2047 able to successfully release the thread-2's lock.
2049 ``raise_on_release_error`` indicates whether to raise an exception when
2050 the lock is no longer owned when exiting the context manager. By default,
2051 this is True, meaning an exception will be raised. If False, the warning
2052 will be logged and the exception will be suppressed.
2054 In some use cases it's necessary to disable thread local storage. For
2055 example, if you have code where one thread acquires a lock and passes
2056 that lock instance to a worker thread to release later. If thread
2057 local storage isn't disabled in this case, the worker thread won't see
2058 the token set by the thread that acquired the lock. Our assumption
2059 is that these cases aren't common and as such default to using
2060 thread local storage."""
2061 if lock_class is None:
2062 lock_class = Lock
2063 return lock_class(
2064 self,
2065 name,
2066 timeout=timeout,
2067 sleep=sleep,
2068 blocking=blocking,
2069 blocking_timeout=blocking_timeout,
2070 thread_local=thread_local,
2071 raise_on_release_error=raise_on_release_error,
2072 )
2074 def set_response_callback(self, command, callback):
2075 """Set a custom Response Callback"""
2076 self.cluster_response_callbacks[command] = callback
2078 def _resolve_command_policies(
2079 self, *args, target_nodes_specified: bool = False
2080 ) -> Tuple[str, CommandPolicies | CommandMetadata, int | None]:
2081 """
2082 Resolves the policies a command routes and aggregates by, and the slot of its
2083 keys when finding the policies took computing it.
2085 Returns the name the policies were decided by along with the record, because the
2086 name a command is known by is not always ``args[0]``: a container command is
2087 keyed by both of its words, and the flag tables are keyed in upper case.
2089 The name is normalized before any branch, so one command answers with one name
2090 however it got here. The result callbacks are keyed in upper case, so a name that
2091 kept the caller's spelling on only some paths would fire them on only some paths -
2092 ``execute_command("dbsize")`` would be summed and ``execute_command("dbsize",
2093 target_nodes=...)`` would not.
2095 First choice is the policy resolver. When it does not know the command, the
2096 fallbacks are the command's ``COMMAND_FLAGS`` entry and then whether the command
2097 carries a key. ``target_nodes_specified`` says the caller picked the targets, as
2098 named nodes or as a nodes flag.
2100 That last fallback computes the command's slot, which is returned so the caller
2101 can pass it to ``_determine_nodes`` instead of computing it again. Every other
2102 branch returns ``None`` for the slot.
2103 """
2104 command = args[0].upper()
2105 if len(args) >= 2 and f"{args[0]} {args[1]}".upper() in self.command_flags:
2106 command = f"{args[0]} {args[1]}".upper()
2108 if target_nodes_specified:
2109 # The caller picked its targets - named nodes, or a nodes flag that
2110 # ``_determine_nodes`` resolves - so nothing is routed from here, and the
2111 # command's own aggregation must not apply either. A response policy resolved
2112 # for the whole cluster (``ONE_SUCCEEDED``, an ``AGG_*``) would short-circuit
2113 # the loop over the nodes the caller picked, or fold their replies into one.
2114 # Answer with the record that aggregates nothing, and skip the resolver: with
2115 # the targets given, neither of its answers is used.
2116 return command, _DEFAULT_KEYLESS_METADATA, None
2118 policies = self._policy_resolver.resolve(args[0].lower())
2119 if policies:
2120 return command, policies, None
2122 command_flag = self.command_flags.get(command)
2123 if command_flag:
2124 if command_flag in self._command_flags_mapping:
2125 return (
2126 command,
2127 _METADATA_BY_REQUEST_POLICY[
2128 self._command_flags_mapping[command_flag]
2129 ],
2130 None,
2131 )
2132 return command, _DEFAULT_KEYLESS_METADATA, None
2134 # Unflagged and unresolved, so the command routes by its key. Without a default
2135 # node the topology is not known yet and there is no slot to route by.
2136 if not self.get_default_node():
2137 return command, _DEFAULT_KEYLESS_METADATA, None
2139 slot = self.determine_slot(*args)
2140 if slot is None:
2141 return command, _DEFAULT_KEYLESS_METADATA, None
2143 return command, _DEFAULT_KEYED_METADATA, slot
2145 def _determine_nodes(
2146 self,
2147 *args,
2148 request_policy: RequestPolicy | None = None,
2149 slot: int | None = None,
2150 **kwargs,
2151 ) -> List["ClusterNode"]:
2152 """
2153 Determines a nodes the command should be executed on.
2155 The caller resolves the command's own policy - see
2156 ``_resolve_command_policies`` - so the only decision left here is an explicit
2157 nodes flag, which overrides it. ``slot`` is the slot that resolution already
2158 computed, if it did, so a keyed command is not hashed twice.
2159 """
2160 command = args[0].upper()
2161 if len(args) >= 2 and f"{args[0]} {args[1]}".upper() in self.command_flags:
2162 command = f"{args[0]} {args[1]}".upper()
2164 nodes_flag = kwargs.pop("nodes_flag", None)
2165 if nodes_flag and self._is_nodes_flag(nodes_flag):
2166 # nodes flag passed by the user
2167 if nodes_flag in self._command_flags_mapping:
2168 request_policy = self._command_flags_mapping[nodes_flag]
2170 if request_policy is None:
2171 raise RedisClusterException(
2172 "No targets were found to execute "
2173 f"{truncate_text(command_text(args))} command on"
2174 )
2176 if slot is not None:
2177 # Only the keyed fallback of ``_resolve_command_policies`` computes a slot
2178 nodes = [self._get_node_from_slot(command, slot)]
2179 else:
2180 nodes = _REQUEST_POLICY_CALLBACKS[request_policy](self, command, *args)
2182 if args[0].lower() == "ft.aggregate":
2183 self._aggregate_nodes = nodes
2185 return nodes
2187 def keyslot(self, key):
2188 """
2189 Calculate keyslot for a given key.
2190 See Keys distribution model in https://redis.io/topics/cluster-spec
2191 """
2192 k = self.encoder.encode(key)
2193 return key_slot(k)
2195 # HIMPORT orchestration. PREPARE/DISCARD/DISCARDALL mutate the one shared
2196 # HImportRegistry exactly once (every node pool references the same object, so the
2197 # change is visible cluster-wide and applied lazily per node). SET routes by key
2198 # slot to the owning primary and reuses that node's standalone himport_set (lazy
2199 # PREPARE bundled with SET). See ``.agents/himport_client_support_spec.md``.
2201 @property
2202 def himport_registry(self) -> HImportRegistry:
2203 """The cluster-wide HIMPORT fieldset registry (empty if none was declared).
2205 Read-only: the registry is mutated only through the HIMPORT command methods.
2206 """
2207 return self._himport_registry
2209 @experimental_method()
2210 def himport_prepare(self, fieldset_name: str, fields: Iterable[FieldT]) -> bool:
2211 """Declare an HIMPORT fieldset cluster-wide (shared registry, applied lazily)."""
2212 self._himport_registry.prepare(fieldset_name, fields)
2213 return True
2215 @experimental_method()
2216 def himport_discard(self, fieldset_name: str) -> int:
2217 """Remove an HIMPORT fieldset cluster-wide (shared registry, applied lazily)."""
2218 return 1 if self._himport_registry.discard(fieldset_name) else 0
2220 @experimental_method()
2221 def himport_discard_all(self) -> int:
2222 """Remove all HIMPORT fieldsets cluster-wide (shared registry, applied lazily)."""
2223 return self._himport_registry.discard_all()
2225 def _get_command_keys(self, *args):
2226 """
2227 Get the keys in the command. If the command has no keys in it, None is
2228 returned.
2230 NOTE: Due to a bug in redis<7.0, this function does not work properly
2231 for EVAL or EVALSHA when the `numkeys` arg is 0.
2232 - issue: https://github.com/redis/redis/issues/9493
2233 - fix: https://github.com/redis/redis/pull/9733
2235 So, don't use this function with EVAL or EVALSHA.
2237 Raises:
2238 RedisClusterException: If the cluster has no default node to resolve
2239 the keys against, which is the case before the slots cache is
2240 first populated and after the client is closed.
2241 """
2242 default_node = self.get_default_node()
2243 if default_node is None:
2244 # The keys are unknown rather than absent: there is no node to resolve them
2245 # against. Say that, rather than reporting a missing key the caller did
2246 # supply, or raising AttributeError from in here.
2247 #
2248 # The async stack needs no counterpart: its parser holds the node it
2249 # was initialized with and never reads the default node.
2250 raise RedisClusterException(
2251 "The cluster has no default node to resolve the keys of this "
2252 "command against. The client may be closed, or not initialized "
2253 f"yet.\nCommand: {truncate_text(command_text(args))}"
2254 )
2256 return self.commands_parser.get_keys(default_node.redis_connection, *args)
2258 def determine_slot(self, *args) -> Optional[int]:
2259 """
2260 Figure out what slot to use based on args.
2262 Raises a RedisClusterException if there's a missing key and we can't
2263 determine what slots to map the command to; or, if the keys don't
2264 all map to the same key slot; or, when the keys have to be resolved
2265 through ``_get_command_keys``, if the cluster has no default node to
2266 resolve them against.
2268 Returns the slot as an ``int``, which is what the declared return type has always
2269 promised and what the slot map is keyed by. A command carrying its slot as an
2270 argument - the ``SLOT_ID`` group - is therefore cast rather than returned verbatim,
2271 so a caller that spelled the slot as a string gets a usable slot instead of a
2272 ``KeyError`` from ``get_node_from_slot``.
2273 """
2274 command = args[0]
2275 if self.command_flags.get(command.upper()) == SLOT_ID:
2276 # The command contains the slot ID. The flag table is keyed in upper case, so
2277 # the lookup is normalized - a raw ``execute_command("cluster countkeysinslot",
2278 # ...)`` names the same command as the spelling the command method sends.
2279 return int(args[1])
2281 # Get the keys in the command
2283 # CLIENT TRACKING is a special case.
2284 # It doesn't have any keys, it needs to be sent to the provided nodes
2285 # By default it will be sent to all nodes.
2286 if command.upper() == "CLIENT TRACKING":
2287 return None
2289 # EVAL and EVALSHA are common enough that it's wasteful to go to the
2290 # redis server to parse the keys. Besides, there is a bug in redis<7.0
2291 # where `self._get_command_keys()` fails anyway. So, we special case
2292 # EVAL/EVALSHA, and their read-only variants, which take the same arguments.
2293 if command.upper() in _EVAL_COMMANDS:
2294 # command syntax: EVAL "script body" num_keys ...
2295 if len(args) <= 2:
2296 raise RedisClusterException(
2297 f"Invalid args in command: {truncate_text(command_text(args))}"
2298 )
2299 num_actual_keys = int(args[2])
2300 eval_keys = args[3 : 3 + num_actual_keys]
2301 # if there are 0 keys, that means the script can be run on any node
2302 # so we can just return a random slot
2303 if len(eval_keys) == 0:
2304 return random.randrange(0, REDIS_CLUSTER_HASH_SLOTS)
2305 keys = eval_keys
2306 else:
2307 keys = self._get_command_keys(*args)
2308 if keys is None or len(keys) == 0:
2309 # FCALL can call a function with 0 keys, that means the function
2310 # can be run on any node so we can just return a random slot
2311 if command.upper() in ("FCALL", "FCALL_RO"):
2312 return random.randrange(0, REDIS_CLUSTER_HASH_SLOTS)
2313 raise RedisClusterException(
2314 "No way to dispatch this command to Redis Cluster. "
2315 "Missing key.\nYou can execute the command by specifying "
2316 f"target nodes.\nCommand: {truncate_text(command_text(args))}"
2317 )
2319 return self._slot_of_keys(command, keys)
2321 def _slot_of_keys(self, command: str, keys: List[Any] | Tuple[Any, ...]) -> int:
2322 """
2323 Returns the slot the given keys of a command map to.
2325 Raises a RedisClusterException if the keys don't all map to the same key slot.
2326 """
2327 # single key command
2328 if len(keys) == 1:
2329 return self.keyslot(keys[0])
2331 # multi-key command; we need to make sure all keys are mapped to
2332 # the same slot
2333 slots = {self.keyslot(key) for key in keys}
2334 if len(slots) != 1:
2335 raise RedisClusterException(
2336 f"{command} - all keys must map to the same key slot"
2337 )
2339 return slots.pop()
2341 def get_encoder(self):
2342 """
2343 Get the connections' encoder
2344 """
2345 return self.encoder
2347 def get_connection_kwargs(self):
2348 """
2349 Get the connections' key-word arguments
2350 """
2351 return self.nodes_manager.connection_kwargs
2353 def _is_nodes_flag(self, target_nodes):
2354 return isinstance(target_nodes, str) and target_nodes in self.node_flags
2356 def _parse_target_nodes(self, target_nodes):
2357 if isinstance(target_nodes, list):
2358 nodes = target_nodes
2359 elif isinstance(target_nodes, ClusterNode):
2360 # Supports passing a single ClusterNode as a variable
2361 nodes = [target_nodes]
2362 elif isinstance(target_nodes, dict):
2363 # Supports dictionaries of the format {node_name: node}.
2364 # It enables to execute commands with multi nodes as follows:
2365 # rc.cluster_save_config(rc.get_primaries())
2366 nodes = target_nodes.values()
2367 else:
2368 raise TypeError(
2369 "target_nodes type can be one of the following: "
2370 "node_flag (PRIMARIES, REPLICAS, RANDOM, ALL_NODES),"
2371 "ClusterNode, list<ClusterNode>, or dict<any, ClusterNode>. "
2372 f"The passed type is {type(target_nodes)}"
2373 )
2374 return nodes
2376 def execute_command(self, *args, **kwargs):
2377 return self._internal_execute_command(*args, **kwargs)
2379 def _internal_execute_command(self, *args, **kwargs):
2380 """
2381 Wrapper for ERRORS_ALLOW_RETRY error handling.
2383 It will try the number of times specified by the retries property from
2384 config option "self.retry" which defaults to 10 unless manually
2385 configured.
2387 If it reaches the number of times, the command will raise the exception
2389 Key argument :target_nodes: can be passed with the following types:
2390 nodes_flag: PRIMARIES, REPLICAS, ALL_NODES, RANDOM
2391 ClusterNode
2392 list<ClusterNode>
2393 dict<Any, ClusterNode>
2394 """
2395 target_nodes_specified = False
2396 is_default_node = False
2397 target_nodes = None
2398 passed_targets = kwargs.pop("target_nodes", None)
2399 nodes_flag = False
2400 if passed_targets is not None:
2401 nodes_flag = self._is_nodes_flag(passed_targets)
2402 if not nodes_flag and not (
2403 isinstance(passed_targets, (list, dict, str)) and not passed_targets
2404 ):
2405 target_nodes = self._parse_target_nodes(passed_targets)
2406 target_nodes_specified = True
2408 # A nodes flag picks the targets too: ``_determine_nodes`` resolves it, and the
2409 # command's own aggregation must not apply to the replies
2410 command, command_policies, slot = self._resolve_command_policies(
2411 *args, target_nodes_specified=target_nodes_specified or nodes_flag
2412 )
2414 # If an error that allows retrying was thrown, a refresh of the nodes
2415 # and slots cache was requested; it is run by the next attempt, of any
2416 # command, once due. We will retry executing the command with
2417 # the updated cluster setup only when the target nodes can be
2418 # determined again with the new cache tables. Therefore, when target
2419 # nodes were passed to this function, we cannot retry the command
2420 # execution since the nodes may not be valid anymore after the tables
2421 # were reinitialized. So in case of passed target nodes,
2422 # retry_attempts will be set to 0.
2423 retry_attempts = 0 if target_nodes_specified else self.retry.get_retries()
2424 # Add one for the first execution
2425 execute_attempts = 1 + retry_attempts
2426 failure_count = 0
2428 # Start timing for observability
2429 start_time = time.monotonic()
2431 # The error the previous attempt failed with, and when the last refresh
2432 # had ended by then: a refresh since that reached no node ends the
2433 # retries (see NodesManager._error_instead_of_retry)
2434 last_error: Optional[Exception] = None
2435 last_refresh_at: Optional[float] = None
2437 # A MULTI_SHARD command whose keys span several slots is split once, as a slot is
2438 # fixed by its keys. Without a client-side cache the split is sent in one pipeline,
2439 # which retries the failed slots itself, so it is not retried here as well.
2440 splits = None
2441 if (
2442 not target_nodes_specified
2443 and command_policies.request_policy == RequestPolicy.MULTI_SHARD
2444 ):
2445 splits = self._split_multi_shard_command(*args)
2446 if (
2447 splits is not None
2448 and len(splits) > 1
2449 and self.nodes_manager._cache is None
2450 ):
2451 return self._execute_multi_shard_command(
2452 command, splits, command_policies.response_policy, **kwargs
2453 )
2455 # The replies already got, kept across the attempts so a retry sends the command
2456 # only where it has not been answered: sending it again would run a write twice,
2457 # and change what a summed reply counts. Keyed by slot for a split MULTI_SHARD
2458 # command, by node name for a command sent to several nodes. Allocated only for
2459 # those: a command sent to one node is retried whole.
2460 replies: Optional[Dict[Any, Any]] = None
2462 for _ in range(execute_attempts):
2463 # Run a topology refresh an earlier error asked for, once due. The
2464 # flag is read inline: this runs before every attempt.
2465 if self.nodes_manager._refresh_requested:
2466 self.nodes_manager._run_requested_refresh(self.retry)
2467 if last_error is not None:
2468 outage_error = self.nodes_manager._error_instead_of_retry(
2469 last_error, last_refresh_at
2470 )
2471 if outage_error is not None:
2472 raise outage_error
2473 try:
2474 res = {}
2475 if not target_nodes_specified:
2476 if splits is None:
2477 # Only the first attempt reuses the slot. A retry computes it
2478 # again, as a command without keys gets a new random slot on
2479 # each attempt - also after an attempt that found no node for it
2480 attempt_slot, slot = slot, None
2481 # Determine the nodes to execute the command on
2482 target_nodes = self._determine_nodes(
2483 *args,
2484 request_policy=command_policies.request_policy,
2485 nodes_flag=passed_targets,
2486 slot=attempt_slot,
2487 )
2488 elif len(splits) > 1:
2489 if replies is None:
2490 replies = {}
2491 return self._execute_multi_shard_command_per_slot(
2492 command,
2493 splits,
2494 command_policies.response_policy,
2495 replies,
2496 **kwargs,
2497 )
2498 else:
2499 # One slot: sent as it is, to the node of the slot the split
2500 # already computed
2501 target_nodes = [self._get_node_from_slot(command, splits[0][0])]
2503 if not target_nodes:
2504 raise RedisClusterException(
2505 "No targets were found to execute "
2506 f"{truncate_text(command_text(args))} command on"
2507 )
2508 # Per attempt: only an attempt that failed on the default
2509 # node replaces it
2510 is_default_node = (
2511 len(target_nodes) == 1
2512 and target_nodes[0] == self.get_default_node()
2513 )
2514 one_succeeded = (
2515 command_policies.response_policy == ResponsePolicy.ONE_SUCCEEDED
2516 )
2517 fan_out = len(target_nodes) > 1
2518 if fan_out and replies is None:
2519 replies = {}
2520 for node in target_nodes:
2521 if fan_out and node.name in replies:
2522 # Answered on an earlier attempt
2523 res[node.name] = replies[node.name]
2524 continue
2525 try:
2526 reply = self._execute_command(node, *args, **kwargs)
2527 except RedisError as e:
2528 # Every node is asked: the one that succeeds is not known up front.
2529 # SCRIPT KILL succeeds only on the shard running the script.
2530 if not one_succeeded:
2531 raise
2532 res[node.name] = e
2533 continue
2534 res[node.name] = reply
2535 if fan_out:
2536 replies[node.name] = reply
2538 if one_succeeded:
2539 res, error = _split_successes_and_failure(
2540 res, command_policies.response_policy
2541 )
2542 if error is not None:
2543 raise error
2545 # Return the processed result
2546 # ``command``, not ``args[0]``: the result callbacks are keyed by the name
2547 # the policies were decided by, so a container command passed as two words
2548 # - ``execute_command("command", "count")`` - is dispatched as the command
2549 # that was actually routed. Telemetry deliberately does not follow; see the
2550 # note on the metric in the retry branch below.
2551 return self._process_result(
2552 command,
2553 res,
2554 response_policy=command_policies.response_policy,
2555 **kwargs,
2556 )
2557 except Exception as e:
2558 if retry_attempts > 0 and (
2559 type(e) in self.__class__.ERRORS_ALLOW_RETRY
2560 or getattr(e, "demoted_primary", False)
2561 ):
2562 if is_default_node:
2563 # Replace the default cluster node
2564 self.replace_default_node()
2565 # The nodes and slots cache were reinitialized.
2566 # Try again with the new cluster setup.
2567 retry_attempts -= 1
2568 failure_count += 1
2569 last_error = e
2570 last_refresh_at = self.nodes_manager._last_refresh_at
2572 if hasattr(e, "connection"):
2573 # ``args[0]``, not the resolved ``command``: every other metric in
2574 # this class - including the per-command one ``_execute_command``
2575 # records on success - names the command the caller spelled. Using
2576 # the routed name only here would report one command under two
2577 # names depending on whether it was retried.
2578 self._record_command_metric(
2579 command_name=args[0],
2580 duration_seconds=time.monotonic() - start_time,
2581 connection=e.connection,
2582 error=e,
2583 )
2585 self._record_error_metric(
2586 error=e,
2587 connection=e.connection,
2588 retry_attempts=failure_count,
2589 )
2590 # Space the attempts out as the retry backoff says; the
2591 # refresh the error asked for runs after this delay
2592 delay = self._retry_backoff_delay(self.retry, failure_count)
2593 if delay > 0:
2594 time.sleep(delay)
2595 continue
2596 else:
2597 # raise the exception
2598 if hasattr(e, "connection"):
2599 self._record_error_metric(
2600 error=e,
2601 connection=e.connection,
2602 retry_attempts=failure_count,
2603 is_internal=False,
2604 )
2605 raise _error_to_raise(
2606 self.nodes_manager._last_refresh_unreachable_args, e
2607 )
2609 def _himport_reconcile_discards(self, redis_node, connection):
2610 """Delegate to the shared sync HIMPORT executor."""
2611 return _himport_exec.reconcile_discards(redis_node, connection)
2613 def _himport_prepare_and_set(
2614 self,
2615 redis_node,
2616 connection,
2617 key,
2618 fieldset_name,
2619 values,
2620 fieldset,
2621 asking: bool = False,
2622 ):
2623 """Delegate to the shared sync HIMPORT executor."""
2624 return _himport_exec.prepare_and_set(
2625 redis_node,
2626 connection,
2627 key,
2628 fieldset_name,
2629 values,
2630 fieldset,
2631 asking=asking,
2632 )
2634 def _himport_execute_set(
2635 self,
2636 redis_node,
2637 connection,
2638 key,
2639 fieldset_name,
2640 values,
2641 asking: bool = False,
2642 ):
2643 """Delegate to the shared sync HIMPORT executor."""
2644 return _himport_exec.execute_set(
2645 redis_node, connection, key, fieldset_name, values, asking=asking
2646 )
2648 def _execute_command(self, target_node, *args, **kwargs):
2649 """
2650 Send a command to a node in the cluster
2651 """
2652 command = args[0]
2653 redis_node = None
2654 connection = None
2655 redirect_addr = None
2656 asking = False
2657 moved = False
2658 ttl = int(self.RedisClusterRequestTTL)
2660 # Start timing for observability
2661 start_time = time.monotonic()
2663 while ttl > 0:
2664 ttl -= 1
2665 # The previous attempt's connection was released by its finally and
2666 # may already belong to another caller. Forget it, so a failed
2667 # checkout below does not disconnect or release it a second time.
2668 connection = None
2669 try:
2670 if asking:
2671 target_node = self.get_node(*redirect_addr)
2672 elif moved:
2673 # MOVED occurred and the slots cache was updated,
2674 # refresh the target node
2675 slot = self.determine_slot(*args)
2676 replica_safe = (
2677 self.read_from_replicas
2678 or self.load_balancing_strategy is not None
2679 ) and self._is_replica_safe(command)
2680 target_node = self.nodes_manager.get_node_from_slot(
2681 slot,
2682 replica_safe,
2683 self.load_balancing_strategy if replica_safe else None,
2684 )
2685 moved = False
2687 redis_node = self.get_redis_connection(target_node)
2688 connection = get_connection(redis_node)
2689 himport_set = parse_himport_set_args(args)
2690 if asking and himport_set is None:
2691 connection.send_command("ASKING")
2692 redis_node.parse_response(connection, "ASKING", **kwargs)
2693 asking = False
2694 if himport_set is not None:
2695 # args == (HIMPORT_SET, key, fieldset_name, *values). A raw
2696 # ``execute_command`` with too few args falls through to the
2697 # normal send path below so the server returns its arity error
2698 # instead of a client-side IndexError.
2699 # The cluster
2700 # executor lazily PREPAREs the fieldset on this connection and
2701 # reconciles deferred DISCARDs, then SETs; it already applies the
2702 # HIMPORT SET response callback, so it bypasses the cluster callback
2703 # block below.
2704 # This per-command branch in the hot dispatch path is deliberate
2705 # and has no cleaner alternative: this is the only seam where the
2706 # concrete routed connection is known, and connection-scoped
2707 # session setup can only happen once that connection is chosen.
2708 # On an ASK redirect ``asking`` is folded into the SET's own packed
2709 # write (see the guard above that suppresses the standalone ASKING
2710 # for HIMPORT SET) so the allowance sits immediately before the SET.
2711 # Clear ``asking`` first and carry the allowance in a dedicated
2712 # local: ``_himport_execute_set`` can raise a retriable MOVED/TRYAGAIN
2713 # mid-exchange, and a stale ``asking`` would shadow the moved-retry
2714 # branch on the next loop iteration (mirrors the async client).
2715 key, fieldset_name, values = himport_set
2716 ask_himport = asking
2717 asking = False
2718 response = self._himport_execute_set(
2719 redis_node,
2720 connection,
2721 key,
2722 fieldset_name,
2723 values,
2724 asking=ask_himport,
2725 )
2726 kwargs.pop("keys", None)
2727 else:
2728 connection.send_command(*args, **kwargs)
2729 response = redis_node.parse_response(connection, command, **kwargs)
2731 # Remove keys entry, it needs only for cache.
2732 kwargs.pop("keys", None)
2734 if command in self.cluster_response_callbacks:
2735 response = self.cluster_response_callbacks[command](
2736 response, **kwargs
2737 )
2739 self._record_command_metric(
2740 command_name=command,
2741 duration_seconds=time.monotonic() - start_time,
2742 connection=connection,
2743 )
2744 return response
2745 except AuthenticationError as e:
2746 e.connection = connection if connection is not None else target_node
2747 self._record_command_metric(
2748 command_name=command,
2749 duration_seconds=time.monotonic() - start_time,
2750 connection=e.connection,
2751 error=e,
2752 )
2753 raise
2754 except MaxConnectionsError as e:
2755 # MaxConnectionsError indicates client-side resource exhaustion
2756 # (too many connections in the pool), not a node failure.
2757 # Don't treat this as a node failure - just re-raise the error
2758 # without reinitializing the cluster.
2759 # The connection in the error is used to report the metrics based on host and port info
2760 # so we use the target node object which contains the host and port info
2761 # because we did not get the connection yet
2762 e.connection = target_node
2763 self._record_command_metric(
2764 command_name=command,
2765 duration_seconds=time.monotonic() - start_time,
2766 connection=e.connection,
2767 error=e,
2768 )
2769 raise
2770 except MaxClientsReachedError as e:
2771 # The server refused a new connection because it is at its
2772 # maxclients limit: server-side capacity, not a node failure.
2773 # Recycling the node's working connections or refreshing the
2774 # topology would only open more connections the server refuses,
2775 # so re-raise without either. The connection that read the error
2776 # has already disconnected itself: read_response drops the
2777 # connection on any error it raises.
2778 e.connection = connection if connection is not None else target_node
2779 self._record_command_metric(
2780 command_name=command,
2781 duration_seconds=time.monotonic() - start_time,
2782 connection=e.connection,
2783 error=e,
2784 )
2785 raise
2786 except (ConnectionError, TimeoutError) as e:
2787 if is_debug_log_enabled():
2788 connection_details = (
2789 connection.extract_connection_details()
2790 if connection
2791 else "no connection"
2792 )
2793 # Log only the command name - argument values can carry
2794 # secrets or user data.
2795 args_log_str = safe_str(args[0])
2796 logger.debug(
2797 f"{type(e).__name__} received for command {args_log_str}, on node {target_node.name}, "
2798 f"and connection: {connection}, {connection_details}, error: {e}"
2799 )
2800 # this is used to report the metrics based on host and port info
2801 e.connection = connection if connection else target_node
2803 # ConnectionError can also be raised if we couldn't get a
2804 # connection from the pool before timing out, so check that
2805 # this is an actual connection before attempting to disconnect.
2806 if connection is not None:
2807 connection.disconnect()
2808 # The node's other connections are kept: a timeout or a dropped
2809 # connection does not mean they are broken, and closing them all
2810 # would reconnect every caller of a node that may be healthy.
2811 # One the server closed is reconnected when it is checked out
2812 # (ConnectionPool.ensure_connection).
2814 # Move the failed node to the end of the cached nodes. This does
2815 # not set the order the refresh queries nodes in (it shuffles the
2816 # startup nodes and tries the failed one last through
2817 # last_failed_node_name below), and the refresh replaces the
2818 # nodes cache, so the new order only lasts until then.
2819 self.nodes_manager.move_node_to_end_of_cached_nodes(target_node.name)
2821 # DON'T set redis_connection = None - keep the pool for reuse
2822 # Ask for a topology refresh, run by the next attempt, of any
2823 # command, once due; provide the name of the failed node so we can
2824 # try it last
2825 self.nodes_manager._request_refresh(
2826 last_failed_node_name=target_node.name
2827 )
2828 self._record_command_metric(
2829 command_name=command,
2830 duration_seconds=time.monotonic() - start_time,
2831 connection=e.connection,
2832 error=e,
2833 )
2834 raise e
2835 except MovedError as e:
2836 if is_debug_log_enabled():
2837 connection_details = (
2838 connection.extract_connection_details()
2839 if connection
2840 else "no connection"
2841 )
2842 # Log only the command name - argument values can carry
2843 # secrets or user data.
2844 args_log_str = safe_str(args[0])
2845 logger.debug(
2846 f"MOVED error received for command {args_log_str}, on node {target_node.name}, "
2847 f"and connection: {connection}, {connection_details}, error: {e}"
2848 )
2849 _fill_missing_redirect_host(e, target_node.host)
2850 # Patch the slots/nodes cache with the redirected node and try
2851 # again. Every 'reinitialize_steps' MOVED errors, also ask for a
2852 # refresh of the whole topology, run by the next attempt of any
2853 # command once due: the redirect needs only this slot, which the
2854 # patch already points to the node that owns it.
2855 # 'reinitialize_steps' counter will increase faster when
2856 # the same client object is shared between multiple threads. To
2857 # reduce the frequency you can set this variable in the
2858 # RedisCluster constructor.
2859 self.reinitialize_counter += 1
2860 self.nodes_manager.move_slot(e)
2861 if _should_request_refresh(
2862 self.reinitialize_steps, self.reinitialize_counter
2863 ):
2864 # The refresh also queries the node the error pointed to
2865 self.nodes_manager._request_refresh(
2866 additional_startup_nodes_info=[
2867 self.nodes_manager.remap_host_port(e.host, e.port)
2868 ]
2869 )
2870 # Reset the counter
2871 self.reinitialize_counter = 0
2872 moved = True
2873 self._record_command_metric(
2874 command_name=command,
2875 duration_seconds=time.monotonic() - start_time,
2876 connection=connection,
2877 error=e,
2878 )
2879 self._record_error_metric(
2880 error=e,
2881 connection=connection,
2882 )
2883 except TryAgainError as e:
2884 if is_debug_log_enabled():
2885 connection_details = (
2886 connection.extract_connection_details()
2887 if connection
2888 else "no connection"
2889 )
2890 # Log only the command name - argument values can carry
2891 # secrets or user data.
2892 args_log_str = safe_str(args[0])
2893 logger.debug(
2894 f"TRYAGAIN error received for command {args_log_str}, on node {target_node.name}, "
2895 f"and connection: {connection}, {connection_details}"
2896 )
2897 if ttl < self.RedisClusterRequestTTL / 2:
2898 time.sleep(0.05)
2900 self._record_command_metric(
2901 command_name=command,
2902 duration_seconds=time.monotonic() - start_time,
2903 connection=connection,
2904 error=e,
2905 )
2906 self._record_error_metric(
2907 error=e,
2908 connection=connection,
2909 )
2910 except AskError as e:
2911 if is_debug_log_enabled():
2912 connection_details = (
2913 connection.extract_connection_details()
2914 if connection
2915 else "no connection"
2916 )
2917 # Log only the command name - argument values can carry
2918 # secrets or user data.
2919 args_log_str = safe_str(args[0])
2920 logger.debug(
2921 f"ASK error received for command {args_log_str}, on node {target_node.name}, "
2922 f"and connection: {connection}, {connection_details}, error: {e}"
2923 )
2924 _fill_missing_redirect_host(e, target_node.host)
2925 redirect_addr = self.nodes_manager.remap_host_port(e.host, e.port)
2926 asking = True
2928 self._record_command_metric(
2929 command_name=command,
2930 duration_seconds=time.monotonic() - start_time,
2931 connection=connection,
2932 error=e,
2933 )
2934 self._record_error_metric(
2935 error=e,
2936 connection=connection,
2937 )
2938 except (ClusterDownError, SlotNotCoveredError) as e:
2939 # ClusterDownError can occur during a failover and to get
2940 # self-healed, we will try to reinitialize the cluster layout
2941 # and retry executing the command
2943 # SlotNotCoveredError can occur when the cluster is not fully
2944 # initialized or can be temporary issue.
2945 # We will try to reinitialize the cluster topology
2946 # and retry executing the command
2948 time.sleep(0.25)
2949 # Refreshed here, not paced or asked for: this command raises the
2950 # refresh error if it fails
2951 self.nodes_manager.initialize()
2953 # if we have a connection, use it, otherwise use the target node
2954 # object which contains the host and port info
2955 # this is used to report the metrics based on host and port info
2956 e.connection = connection if connection else target_node
2957 self._record_command_metric(
2958 command_name=command,
2959 duration_seconds=time.monotonic() - start_time,
2960 connection=e.connection,
2961 error=e,
2962 )
2963 raise
2964 except ResponseError as e:
2965 if _is_demoted_primary(e, target_node):
2966 e.demoted_primary = True
2967 # Ask for a topology refresh, run by the next attempt, of
2968 # any command, once due; the caller retries this one
2969 self.nodes_manager._request_refresh()
2970 # this is used to report the metrics based on host and port info
2971 # ResponseError typically happens after get_connection() succeeds,
2972 # so connection should be available
2973 e.connection = connection if connection else target_node
2974 self._record_command_metric(
2975 command_name=command,
2976 duration_seconds=time.monotonic() - start_time,
2977 connection=e.connection,
2978 error=e,
2979 )
2980 raise
2981 except Exception as e:
2982 if connection:
2983 connection.disconnect()
2985 # if we have a connection, use it, otherwise use the target node
2986 # object which contains the host and port info
2987 # this is used to report the metrics based on host and port info
2988 e.connection = connection if connection else target_node
2989 self._record_command_metric(
2990 command_name=command,
2991 duration_seconds=time.monotonic() - start_time,
2992 connection=e.connection,
2993 error=e,
2994 )
2995 raise e
2996 finally:
2997 if connection is not None:
2998 redis_node.connection_pool.release(connection)
3000 e = ClusterError("TTL exhausted.")
3001 # In this case we should have an active connection.
3002 # If we are here, we have received many MOVED or ASK errors and finally exhausted the TTL.
3003 # This means that we used an active connection to read from the socket.
3004 # This is used to report metrics based on the host and port information.
3005 e.connection = connection
3006 self._record_command_metric(
3007 command_name=command,
3008 duration_seconds=time.monotonic() - start_time,
3009 connection=connection,
3010 error=e,
3011 )
3012 raise e
3014 def _record_command_metric(
3015 self,
3016 command_name: str,
3017 duration_seconds: float,
3018 connection: Connection,
3019 error=None,
3020 ):
3021 """
3022 Records operation duration metric directly.
3023 """
3024 host = connection.host if connection else "unknown"
3025 port = connection.port if connection else 0
3026 db = str(connection.db) if connection and hasattr(connection, "db") else "0"
3028 record_operation_duration(
3029 command_name=command_name,
3030 duration_seconds=duration_seconds,
3031 server_address=host,
3032 server_port=port,
3033 db_namespace=db,
3034 error=error,
3035 )
3037 def _record_error_metric(
3038 self,
3039 error: Exception,
3040 connection: Union[Connection, "ClusterNode"],
3041 is_internal: bool = True,
3042 retry_attempts: Optional[int] = None,
3043 ):
3044 """
3045 Records error count metric directly.
3046 Accepts either a Connection or ClusterNode object.
3047 """
3048 record_error_count(
3049 server_address=connection.host,
3050 server_port=connection.port,
3051 network_peer_address=connection.host,
3052 network_peer_port=connection.port,
3053 error_type=error,
3054 retry_attempts=retry_attempts if retry_attempts is not None else 0,
3055 is_internal=is_internal,
3056 )
3058 def close(self) -> None:
3059 try:
3060 with self._lock:
3061 if self.nodes_manager:
3062 self.nodes_manager.close()
3063 except AttributeError:
3064 # RedisCluster's __init__ can fail before nodes_manager is set
3065 pass
3067 def _process_result(self, command, res, response_policy: ResponsePolicy, **kwargs):
3068 """
3069 Process the result of the executed command.
3070 The function would return a dict or a single value.
3072 :type command: str
3073 :type res: dict
3075 `res` should be in the following format:
3076 Dict<node_name, command_result>
3078 A command's own result callback merges the replies when it has one. Otherwise a
3079 single reply is returned as it is, and the replies of several nodes are folded by
3080 the command's response policy.
3081 """
3082 if command in self.result_callbacks:
3083 return self.result_callbacks[command](command, res, **kwargs)
3084 elif len(res) == 1:
3085 # When we execute the command on a single node, we can
3086 # remove the dictionary and return a single response
3087 return list(res.values())[0]
3088 elif response_policy == ResponsePolicy.SPECIAL:
3089 special = _SPECIAL_RESPONSE_CALLBACKS.get(command)
3090 if special is not None:
3091 return special(res)
3093 return _RESPONSE_POLICY_CALLBACKS[response_policy](res)
3095 def load_external_module(self, funcname, func):
3096 """
3097 This function can be used to add externally defined redis modules,
3098 and their namespaces to the redis client.
3100 ``funcname`` - A string containing the name of the function to create
3101 ``func`` - The function, being added to this class.
3102 """
3103 setattr(self, funcname, func)
3105 def transaction(self, func, *watches, **kwargs):
3106 """
3107 Convenience method for executing the callable `func` as a transaction
3108 while watching all keys specified in `watches`. The 'func' callable
3109 should expect a single argument which is a Pipeline object.
3110 """
3111 shard_hint = kwargs.pop("shard_hint", None)
3112 value_from_callable = kwargs.pop("value_from_callable", False)
3113 watch_delay = kwargs.pop("watch_delay", None)
3114 with self.pipeline(True, shard_hint) as pipe:
3115 while True:
3116 try:
3117 if watches:
3118 pipe.watch(*watches)
3119 func_value = func(pipe)
3120 exec_value = pipe.execute()
3121 return func_value if value_from_callable else exec_value
3122 except WatchError:
3123 if watch_delay is not None and watch_delay > 0:
3124 time.sleep(watch_delay)
3125 continue
3128class ClusterNode:
3129 def __init__(self, host, port, server_type=None, redis_connection=None):
3130 if host == "localhost":
3131 host = _resolve_localhost()
3133 self.host = host
3134 self.port = port
3135 self.name = get_node_name(host, port)
3136 self.server_type = server_type
3137 self.redis_connection = redis_connection
3139 def __repr__(self):
3140 return (
3141 f"[host={self.host},"
3142 f"port={self.port},"
3143 f"name={self.name},"
3144 f"server_type={self.server_type},"
3145 f"redis_connection={self.redis_connection}]"
3146 )
3148 def __eq__(self, obj):
3149 return isinstance(obj, ClusterNode) and obj.name == self.name
3151 def __hash__(self):
3152 return hash(self.name)
3155class LoadBalancingStrategy(Enum):
3156 ROUND_ROBIN = "round_robin"
3157 ROUND_ROBIN_REPLICAS = "round_robin_replicas"
3158 RANDOM = "random"
3159 RANDOM_REPLICA = "random_replica"
3162# The strategies that exclude the primary. ``LoadBalancer`` derives the same thing per
3163# strategy as the ``replicas_only`` bit it passes to its index helpers below, but it can
3164# only express it as an index into one shard's node list. Named here so the keyless
3165# routing path - which has no shard, and so no list to index - can ask the same question.
3166# A strategy added to the enum has to be classified here too.
3167_REPLICAS_ONLY_STRATEGIES = frozenset(
3168 {
3169 LoadBalancingStrategy.ROUND_ROBIN_REPLICAS,
3170 LoadBalancingStrategy.RANDOM_REPLICA,
3171 }
3172)
3175class LoadBalancer:
3176 """
3177 Round-Robin Load Balancing
3178 """
3180 def __init__(self, start_index: int = 0) -> None:
3181 self.primary_to_idx: dict[str, int] = {}
3182 self.start_index: int = start_index
3183 self._lock: threading.Lock = threading.Lock()
3185 def get_server_index(
3186 self,
3187 primary: str,
3188 list_size: int,
3189 load_balancing_strategy: LoadBalancingStrategy = LoadBalancingStrategy.ROUND_ROBIN,
3190 ) -> int:
3191 if load_balancing_strategy == LoadBalancingStrategy.RANDOM_REPLICA:
3192 return self._get_random_server_index(
3193 list_size,
3194 replicas_only=True,
3195 )
3196 elif load_balancing_strategy == LoadBalancingStrategy.RANDOM:
3197 return self._get_random_server_index(
3198 list_size,
3199 replicas_only=False,
3200 )
3201 else:
3202 return self._get_round_robin_index(
3203 primary,
3204 list_size,
3205 load_balancing_strategy == LoadBalancingStrategy.ROUND_ROBIN_REPLICAS,
3206 )
3208 def reset(self) -> None:
3209 with self._lock:
3210 self.primary_to_idx.clear()
3212 def _get_random_server_index(self, list_size: int, replicas_only: bool) -> int:
3213 return random.randint(1 if replicas_only else 0, list_size - 1)
3215 def _get_round_robin_index(
3216 self, primary: str, list_size: int, replicas_only: bool
3217 ) -> int:
3218 with self._lock:
3219 server_index = self.primary_to_idx.setdefault(primary, self.start_index)
3220 if replicas_only and server_index == 0:
3221 # skip the primary node index
3222 server_index = 1
3223 # Update the index for the next round
3224 self.primary_to_idx[primary] = (server_index + 1) % list_size
3225 return server_index
3228class NodesManager:
3229 def __init__(
3230 self,
3231 startup_nodes: list[ClusterNode],
3232 from_url=False,
3233 require_full_coverage=False,
3234 lock: "threading.RLock | None" = None,
3235 dynamic_startup_nodes=True,
3236 connection_pool_class=ConnectionPool,
3237 address_remap: Callable[[Tuple[str, int]], Tuple[str, int]] | None = None,
3238 cache: CacheInterface | None = None,
3239 cache_config: CacheConfig | None = None,
3240 cache_factory: CacheFactoryInterface | None = None,
3241 event_dispatcher: EventDispatcher | None = None,
3242 maint_notifications_config: MaintNotificationsConfig | None = None,
3243 himport_registry: HImportRegistry | None = None,
3244 metadata_resolver: MetadataResolver | None = None,
3245 topology_refresh_min_interval: float | None = None,
3246 **kwargs,
3247 ):
3248 # Shared, cluster-wide HIMPORT registry object, injected onto every node's pool
3249 # in create_redis_node (not forwarded through connection_kwargs, so all nodes
3250 # reuse the one object rather than rebuilding it per node).
3251 self.himport_registry = himport_registry
3252 self.nodes_cache: dict[str, ClusterNode] = {}
3253 self.slots_cache: dict[int, list[ClusterNode]] = {}
3254 self.startup_nodes: dict[str, ClusterNode] = {n.name: n for n in startup_nodes}
3255 self.default_node: Optional[ClusterNode] = None
3256 self._epoch: int = 0
3257 self.from_url = from_url
3258 self._require_full_coverage = require_full_coverage
3259 self._dynamic_startup_nodes = dynamic_startup_nodes
3260 self.connection_pool_class = connection_pool_class
3261 self.address_remap = address_remap
3262 # Shared, cluster-wide metadata resolver, injected onto every node's client in
3263 # create_redis_node for the same reason the cache and the HIMPORT registry are:
3264 # every node must resolve command metadata - and therefore cache eligibility -
3265 # through the one object the cluster client was configured with.
3266 self._metadata_resolver = metadata_resolver
3267 # The minimum interval between error-triggered refreshes, or None for
3268 # _TOPOLOGY_REFRESH_MIN_INTERVAL_SECONDS. See _refresh_due.
3269 self._topology_refresh_min_interval = topology_refresh_min_interval
3271 self._cache: Optional[CacheInterface] = None
3272 if cache:
3273 self._cache = cache
3274 elif cache_factory is not None:
3275 self._cache = cache_factory.get_cache()
3276 elif cache_config is not None:
3277 # Injected here, on a copy, rather than left to the node pools: the cluster hands
3278 # every node the one cache built below, so each pool sees a ``cache=`` and would
3279 # set the resolver on the configuration inside it - which is the caller's object,
3280 # since ``CacheFactory`` holds it by reference. Copying keeps a ``CacheConfig``
3281 # reused across clients from picking up whichever resolver was injected last,
3282 # exactly as ``ConnectionPool.__init__`` does for the standalone client.
3283 #
3284 # Only this branch needs it. ``cache=`` and ``cache_factory=`` hand over a whole
3285 # cache whose configuration the caller owns, and the node pools set the resolver
3286 # on it in place - the same thing they do for a standalone client given one.
3287 if metadata_resolver is not None and isinstance(cache_config, CacheConfig):
3288 cache_config = copy(cache_config)
3289 cache_config.set_metadata_resolver(metadata_resolver)
3291 self._cache = CacheFactory(cache_config).get_cache()
3292 self.connection_kwargs = kwargs
3293 self.read_load_balancer = LoadBalancer()
3295 # nodes_cache / slots_cache / startup_nodes / default_node are protected by _lock
3296 if lock is None:
3297 self._lock = threading.RLock()
3298 else:
3299 self._lock = lock
3301 # initialize holds _initialization_lock to dedup multiple calls to reinitialize;
3302 # note that if we hold both _lock and _initialization_lock, we _must_ acquire
3303 # _initialization_lock first (ie: to have a consistent order) to avoid deadlock.
3304 #
3305 # The same ordering rule extends to OSSMaintNotificationsHandler._lock, which
3306 # is a third lock in this graph: initialize runs a CLUSTER SLOTS round trip
3307 # while holding _initialization_lock, and the response can carry an SMIGRATED
3308 # push that is handled inline on that thread and needs the handler's _lock. The
3309 # full order is therefore
3310 # _initialization_lock -> OSSMaintNotificationsHandler._lock
3311 # -> NodesManager._lock / connection pool locks
3312 # ie: a thread holding the handler's _lock must never wait for
3313 # _initialization_lock.
3314 self._initialization_lock: threading.RLock = threading.RLock()
3315 # Ident of the thread currently running initialize, or None. Written only
3316 # under _initialization_lock; see the re-entrancy guard in initialize.
3317 self._initializing_thread_id: Optional[int] = None
3318 # When the last refresh ended, how many failed in a row, and when the
3319 # next error-triggered refresh is due. Every refresh that ends clears
3320 # the due time and the next check computes it, once, from the backoff
3321 # of the caller's retry (a jittered backoff returns a new value on
3322 # every call). See _refresh_due.
3323 self._last_refresh_at: Optional[float] = None
3324 self._failed_refreshes = 0
3325 self._refresh_due_at: Optional[float] = None
3326 # The message (args) of the error of the last refresh if it reached no
3327 # node, cleared by a refresh that ends otherwise; only the message, so
3328 # the error does not keep the frames of that refresh alive. See
3329 # _error_to_raise.
3330 self._last_refresh_unreachable_args: Optional[Tuple[Any, ...]] = None
3331 # A refresh requested by an error path and not run yet; the next
3332 # command runs it once it is due. All written under _lock.
3333 self._refresh_requested = False
3334 self._refresh_requested_at_epoch = 0
3335 self._requested_additional_startup_nodes: List[Tuple[str, int]] = []
3336 self._requested_last_failed_node_name: Optional[str] = None
3337 self._requested_disconnect_startup_nodes_pools = True
3339 if event_dispatcher is None:
3340 self._event_dispatcher = EventDispatcher()
3341 else:
3342 self._event_dispatcher = event_dispatcher
3343 self._credential_provider = self.connection_kwargs.get(
3344 "credential_provider", None
3345 )
3346 self.maint_notifications_config = maint_notifications_config
3348 self.initialize()
3350 def get_node(
3351 self,
3352 host: Optional[str] = None,
3353 port: Optional[int] = None,
3354 node_name: Optional[str] = None,
3355 ) -> Optional[ClusterNode]:
3356 """
3357 Get the requested node from the cluster's nodes.
3358 nodes.
3359 :return: ClusterNode if the node exists, else None
3360 """
3361 if host and port:
3362 # the user passed host and port
3363 if host == "localhost":
3364 host = _resolve_localhost()
3365 with self._lock:
3366 return self.nodes_cache.get(get_node_name(host=host, port=port))
3367 elif node_name:
3368 with self._lock:
3369 return self.nodes_cache.get(node_name)
3370 else:
3371 return None
3373 def move_slot(self, e: Union[AskError, MovedError]):
3374 """
3375 Update the slot's node with the redirected one
3376 """
3377 node_changed = False
3378 # The redirect carries the address the node advertises, like
3379 # CLUSTER SLOTS does, so it needs the same remapping to be reachable
3380 host, port = self.remap_host_port(e.host, e.port)
3381 with self._lock:
3382 redirected_node = self.get_node(host=host, port=port)
3383 if redirected_node is not None:
3384 # The node already exists
3385 if redirected_node.server_type is not PRIMARY:
3386 # Update the node's server type
3387 redirected_node.server_type = PRIMARY
3388 else:
3389 # This is a new node, we will add it to the nodes cache
3390 redirected_node = ClusterNode(host, port, PRIMARY)
3391 self.nodes_cache[redirected_node.name] = redirected_node
3393 slot_nodes = self.slots_cache[e.slot_id]
3394 if redirected_node not in slot_nodes:
3395 # The new slot owner is a new server, or a server from a different
3396 # shard. We need to remove all current nodes from the slot's list
3397 # (including replications) and add just the new node.
3398 self.slots_cache[e.slot_id] = [redirected_node]
3399 node_changed = True
3400 elif redirected_node is not slot_nodes[0]:
3401 # The MOVED error resulted from a failover, and the new slot owner
3402 # had previously been a replica.
3403 old_primary = slot_nodes[0]
3404 # Update the old primary to be a replica and add it to the end of
3405 # the slot's node list
3406 old_primary.server_type = REPLICA
3407 slot_nodes.append(old_primary)
3408 # Remove the old replica, which is now a primary, from the slot's
3409 # node list
3410 slot_nodes.remove(redirected_node)
3411 # Override the old primary with the new one
3412 slot_nodes[0] = redirected_node
3413 if self.default_node == old_primary:
3414 # Update the default node with the new primary
3415 self.default_node = redirected_node
3416 node_changed = True
3417 # else: circular MOVED to current primary -> no-op
3418 # Dispatch outside the lock so listeners can acquire their own locks
3419 # without risk of deadlock. Skipped on the no-op branch to avoid
3420 # needless reconciliation walks under MOVED storms. A listener must
3421 # not break slots-cache refresh; log and continue so a single buggy
3422 # listener cannot starve the rest.
3423 if node_changed:
3424 try:
3425 self._event_dispatcher.dispatch(AfterSlotsCacheRefreshEvent())
3426 except Exception as exc:
3427 # Don't shadow the method parameter ``e``: ``except as`` binds
3428 # the listener exception in the function scope and ``del``s
3429 # the name on block exit (PEP 3134), which would also wipe
3430 # out the original AskError/MovedError parameter.
3431 logger.exception(
3432 "listener raised during slots-cache refresh: %s: %s",
3433 type(exc).__name__,
3434 exc,
3435 )
3437 @deprecated_args(
3438 args_to_warn=["server_type"],
3439 reason=(
3440 "In case you need select some load balancing strategy "
3441 "that will use replicas, please set it through 'load_balancing_strategy'"
3442 ),
3443 version="5.3.0",
3444 )
3445 def get_node_from_slot(
3446 self,
3447 slot: int,
3448 read_from_replicas: bool = False,
3449 load_balancing_strategy: Optional[LoadBalancingStrategy] = None,
3450 server_type: Optional[Literal["primary", "replica"]] = None,
3451 ) -> ClusterNode:
3452 """
3453 Gets a node that servers this hash slot
3454 """
3456 if read_from_replicas is True and load_balancing_strategy is None:
3457 load_balancing_strategy = LoadBalancingStrategy.ROUND_ROBIN
3459 with self._lock:
3460 if self.slots_cache.get(slot) is None or len(self.slots_cache[slot]) == 0:
3461 raise SlotNotCoveredError(
3462 f'Slot "{slot}" not covered by the cluster. '
3463 + f'"require_full_coverage={self._require_full_coverage}"'
3464 )
3466 if len(self.slots_cache[slot]) > 1 and load_balancing_strategy:
3467 # get the server index using the strategy defined in load_balancing_strategy
3468 primary_name = self.slots_cache[slot][0].name
3469 node_idx = self.read_load_balancer.get_server_index(
3470 primary_name, len(self.slots_cache[slot]), load_balancing_strategy
3471 )
3472 elif (
3473 server_type is None
3474 or server_type == PRIMARY
3475 or len(self.slots_cache[slot]) == 1
3476 ):
3477 # return a primary
3478 node_idx = 0
3479 else:
3480 # return a replica
3481 # randomly choose one of the replicas
3482 node_idx = random.randint(1, len(self.slots_cache[slot]) - 1)
3484 return self.slots_cache[slot][node_idx]
3486 def get_nodes_by_server_type(self, server_type: Literal["primary", "replica"]):
3487 """
3488 Get all nodes with the specified server type
3489 :param server_type: 'primary' or 'replica'
3490 :return: list of ClusterNode
3491 """
3492 with self._lock:
3493 return [
3494 node
3495 for node in self.nodes_cache.values()
3496 if node.server_type == server_type
3497 ]
3499 @deprecated_function(
3500 reason="This method is not used anymore internally. The startup nodes are populated automatically.",
3501 version="7.0.2",
3502 )
3503 def populate_startup_nodes(self, nodes):
3504 """
3505 Populate all startup nodes and filters out any duplicates
3506 """
3507 with self._lock:
3508 for n in nodes:
3509 self.startup_nodes[n.name] = n
3511 def move_node_to_end_of_cached_nodes(self, node_name: str) -> None:
3512 """
3513 Move a failing node to the end of startup_nodes and nodes_cache so it's
3514 tried last during reinitialization and when selecting the default node.
3515 If the node is not in the respective list, nothing is done.
3517 Runs under the lock: the error paths of many threads call it at once
3518 when a node fails, and with dynamic startup nodes both names point to
3519 the same dict.
3520 """
3521 with self._lock:
3522 # Move in startup_nodes
3523 if node_name in self.startup_nodes and len(self.startup_nodes) > 1:
3524 node = self.startup_nodes.pop(node_name)
3525 self.startup_nodes[node_name] = node # Re-insert at end
3527 # Move in nodes_cache - this affects get_nodes_by_server_type
3528 # ordering which is used to select the default_node during
3529 # initialize()
3530 if node_name in self.nodes_cache and len(self.nodes_cache) > 1:
3531 node = self.nodes_cache.pop(node_name)
3532 self.nodes_cache[node_name] = node # Re-insert at end
3534 def check_slots_coverage(self, slots_cache):
3535 # Validate if all slots are covered or if we should try next
3536 # startup node
3537 for i in range(0, REDIS_CLUSTER_HASH_SLOTS):
3538 if i not in slots_cache:
3539 return False
3540 return True
3542 def create_redis_connections(self, nodes):
3543 """
3544 This function will create a redis connection to all nodes in :nodes:
3545 """
3546 nodes = list(nodes)
3547 self._create_redis_connections(nodes)
3548 with self._lock:
3549 current_nodes = list(self.nodes_cache.values())
3550 self._dispatch_pools_instantiated(chain(current_nodes, nodes))
3552 def _create_redis_connections(self, nodes) -> None:
3553 """
3554 Create a redis connection for every node in :nodes: that has none,
3555 without registering them for re-authentication.
3556 """
3557 for node in nodes:
3558 if node.redis_connection is None:
3559 node.redis_connection = self.create_redis_node(
3560 host=node.host,
3561 port=node.port,
3562 maint_notifications_config=self.maint_notifications_config,
3563 **self.connection_kwargs,
3564 )
3566 def _dispatch_pools_instantiated(self, nodes) -> None:
3567 """
3568 Register the connection pools of :nodes: for re-authentication.
3570 A streaming credential provider keeps only the last callback registered,
3571 so the event must list the pool of every node that is still serving the
3572 cluster, not just the pools created last.
3573 """
3574 connection_pools = []
3575 seen = set()
3576 for node in nodes:
3577 if node.redis_connection is None:
3578 continue
3579 pool = node.redis_connection.connection_pool
3580 if id(pool) not in seen:
3581 seen.add(id(pool))
3582 connection_pools.append(pool)
3584 self._event_dispatcher.dispatch(
3585 AfterPooledConnectionsInstantiationEvent(
3586 connection_pools, ClientType.SYNC, self._credential_provider
3587 )
3588 )
3590 @staticmethod
3591 def _free_pool_connections(pool) -> None:
3592 """
3593 Mark the in-use connections of :pool: for reconnect, so they are
3594 closed once their current command completes, and disconnect its free
3595 connections.
3596 """
3597 with pool._lock:
3598 pool.update_active_connections_for_reconnect()
3599 pool.disconnect_free_connections()
3601 def _release_removed_nodes(self, old_nodes_cache, new_node_names) -> None:
3602 """
3603 Release the connections of the nodes that left the topology.
3605 Nodes that stay keep their connections whatever their role: the server
3606 keeps the session state of a connection across a role change, READONLY
3607 is sent on every connection when reads from replicas are enabled, and a
3608 command that reaches a node that no longer serves its slot gets MOVED.
3610 :new_node_names: are the names of the new topology taken when it was
3611 published, under the lock: the published cache itself can be halfway
3612 through a move_node_to_end_of_cached_nodes on another thread.
3613 """
3614 for name, node in old_nodes_cache.items():
3615 if name not in new_node_names and node.redis_connection is not None:
3616 if is_debug_log_enabled():
3617 logger.debug(
3618 f"Topology refresh: releasing connections of removed node {name}"
3619 )
3620 self._free_pool_connections(node.redis_connection.connection_pool)
3622 def create_redis_node(
3623 self,
3624 host,
3625 port,
3626 **kwargs,
3627 ):
3628 # We are configuring the connection pool not to retry
3629 # connections on lower level clients to avoid retrying
3630 # connections to nodes that are not reachable
3631 # and to avoid blocking the connection pool.
3632 # The only error that will have some handling in the lower
3633 # level clients is ConnectionError which will trigger disconnection
3634 # of the socket.
3635 # The retries will be handled on cluster client level
3636 # where we will have proper handling of the cluster topology
3637 node_retry_config = Retry(
3638 backoff=NoBackoff(), retries=0, supported_errors=(ConnectionError,)
3639 )
3641 connection_pool = kwargs.pop("connection_pool", None)
3642 if connection_pool is not None:
3643 r = Redis(connection_pool=connection_pool)
3644 else:
3645 # parse_url already turns rediss:// into SSLConnection, do the same
3646 # for ssl=True
3647 if not self.from_url and kwargs.pop("ssl", False):
3648 kwargs.setdefault("connection_class", SSLConnection)
3649 # Create a redis node with a custom connection pool
3650 kwargs.update({"host": host})
3651 kwargs.update({"port": port})
3652 kwargs.update({"cache": self._cache})
3653 kwargs.update({"metadata_resolver": self._metadata_resolver})
3654 kwargs.update({"retry": node_retry_config})
3655 pool = self.connection_pool_class(**kwargs)
3656 if not self.from_url and not issubclass(
3657 pool.connection_class, SSLConnection
3658 ):
3659 # a plain connection rejects the TLS options Redis() used to ignore
3660 for key in [k for k in pool.connection_kwargs if k.startswith("ssl_")]:
3661 del pool.connection_kwargs[key]
3662 r = Redis.from_pool(pool)
3663 # Share the one cluster-wide HIMPORT registry with this node's pool. Injected
3664 # here (rather than forwarded via connection_kwargs) so every node reuses the
3665 # same object; the node has no connections yet, so this is safe.
3666 if self.himport_registry is not None:
3667 r.connection_pool.himport_registry = self.himport_registry
3668 r.connection_pool.connection_kwargs["himport_registry"] = (
3669 self.himport_registry
3670 )
3671 return r
3673 def _get_or_create_cluster_node(self, host, port, role, tmp_nodes_cache):
3674 node_name = get_node_name(host, port)
3675 # check if we already have this node in the tmp_nodes_cache
3676 target_node = tmp_nodes_cache.get(node_name)
3677 if target_node is None:
3678 # before creating a new cluster node, check if the cluster node already
3679 # exists in the current nodes cache and has a valid connection so we can
3680 # reuse it
3681 redis_connection: Optional[Redis] = None
3682 with self._lock:
3683 previous_node = self.nodes_cache.get(node_name)
3684 if previous_node:
3685 redis_connection = previous_node.redis_connection
3686 # don't update the old ClusterNode, so we don't update its role
3687 # outside of the lock
3688 target_node = ClusterNode(host, port, role, redis_connection)
3689 # add this node to the nodes cache
3690 tmp_nodes_cache[target_node.name] = target_node
3692 return target_node
3694 def _get_epoch(self) -> int:
3695 """
3696 Get the current epoch value. This method exists primarily to allow
3697 tests to mock the epoch fetch and control race condition timing.
3698 """
3699 with self._lock:
3700 return self._epoch
3702 @contextmanager
3703 def _initializing_on_this_thread(self):
3704 """
3705 Mark the calling thread as the one currently running ``initialize``.
3707 Must be entered while holding ``_initialization_lock`` - that is what
3708 makes the calling thread the only writer of ``_initializing_thread_id``.
3709 """
3710 self._initializing_thread_id = threading.get_ident()
3711 try:
3712 yield
3713 finally:
3714 self._initializing_thread_id = None
3716 @contextmanager
3717 def _counting_failed_refresh(self):
3718 """
3719 Record a refresh that raised, so error-triggered refreshes back off,
3720 and register the pools of the current nodes for re-authentication
3721 again: every client built during the refresh registered its own pool
3722 with the credential provider, which keeps only the last callback.
3724 A refresh interrupted before it ended (``BaseException``, such as a
3725 gevent timeout) is not counted as failed, but the next one still waits
3726 the delay, so callers that keep timing out do not run one refresh
3727 after another. Its outcome is unknown, so it clears the record of a
3728 refresh that reached no node.
3729 """
3730 try:
3731 yield
3732 except BaseException as e:
3733 with self._lock:
3734 if isinstance(e, Exception):
3735 self._failed_refreshes += 1
3736 self._last_refresh_unreachable_args = (
3737 e.args if isinstance(e, RedisClusterUnreachableError) else None
3738 )
3739 self._last_refresh_at = time.monotonic()
3740 self._refresh_due_at = None
3741 current_nodes = list(self.nodes_cache.values())
3742 if current_nodes:
3743 self._dispatch_pools_instantiated(current_nodes)
3744 raise
3746 @contextmanager
3747 def _releasing_queried_clients(self, disconnect_startup_nodes_pools: bool):
3748 """
3749 Collect the clients queried for CLUSTER SLOTS during a refresh, whether
3750 they answered or not, and release the ones that serve no node of the
3751 topology once the refresh ends, whether it succeeded or raised.
3753 Yields the two lists to fill: (node name, client) of the startup nodes,
3754 and the clients built for the additional startup nodes, which exist
3755 only for this refresh.
3756 """
3757 queried_startup_nodes: List[Tuple[str, Redis]] = []
3758 queried_additional_clients: List[Redis] = []
3759 try:
3760 yield queried_startup_nodes, queried_additional_clients
3761 finally:
3762 if disconnect_startup_nodes_pools and queried_startup_nodes:
3763 with self._lock:
3764 # A copy: another thread can be halfway through
3765 # move_node_to_end_of_cached_nodes on the published cache
3766 nodes_cache = dict(self.nodes_cache)
3767 for name, r in queried_startup_nodes:
3768 node = nodes_cache.get(name)
3769 if node is None or node.redis_connection is not r:
3770 # This client serves no node of the topology (e.g. a
3771 # load balancer or DNS seed, or a startup node whose
3772 # node got its own client), so don't keep its
3773 # connections open
3774 self._free_pool_connections(r.connection_pool)
3775 for r in queried_additional_clients:
3776 # Never a client of the topology, whatever the flag says
3777 self._free_pool_connections(r.connection_pool)
3779 def _refresh_due(self, retry: AbstractRetry | None = None) -> bool:
3780 """
3781 Whether a topology refresh triggered by an error may run now: not
3782 before the delay of _topology_refresh_delay has passed since the
3783 previous refresh ended. The due time is read without the lock; a stale
3784 read only moves one refresh by a call. The first check after a refresh
3785 ended computes it under the lock, so a due time computed for an older
3786 refresh never replaces a newer one.
3787 """
3788 due_at = self._refresh_due_at
3789 if due_at is None:
3790 # The first check since a refresh ended
3791 with self._lock:
3792 due_at = self._refresh_due_at
3793 if due_at is None:
3794 last_refresh_at = self._last_refresh_at
3795 if last_refresh_at is None:
3796 return True
3797 due_at = last_refresh_at + _topology_refresh_delay(
3798 retry,
3799 self._failed_refreshes,
3800 self._topology_refresh_min_interval,
3801 )
3802 self._refresh_due_at = due_at
3803 return time.monotonic() >= due_at
3805 def _error_instead_of_retry(
3806 self, error: Exception, last_refresh_at: Optional[float]
3807 ) -> Optional[Exception]:
3808 """
3809 The error to raise instead of retrying :error:, the connection or
3810 timeout error of the previous attempt, or None to retry. A refresh that
3811 ended since that attempt failed (``_last_refresh_at`` moved from
3812 :last_refresh_at:, read when the error was raised) and reached no node
3813 leaves the retry the slot map that attempt failed on, so the caller
3814 gives up now with the :class:`~.RedisClusterUnreachableError` that
3815 _error_to_raise builds. The two values are read together under the
3816 lock: a refresh ending between two reads could pair the outcome of one
3817 refresh with the end time of the next.
3818 """
3819 with self._lock:
3820 unreachable_args = self._last_refresh_unreachable_args
3821 refresh_at = self._last_refresh_at
3822 if unreachable_args is None or refresh_at == last_refresh_at:
3823 return None
3824 outage_error = _error_to_raise(unreachable_args, error)
3825 return None if outage_error is error else outage_error
3827 def _request_refresh(
3828 self,
3829 additional_startup_nodes_info: Optional[List[Tuple[str, int]]] = None,
3830 last_failed_node_name: Optional[str] = None,
3831 disconnect_startup_nodes_pools: bool = True,
3832 ) -> None:
3833 """
3834 Ask for a topology refresh after an error. Requests are merged until
3835 _run_requested_refresh runs them, once due.
3836 """
3837 with self._lock:
3838 if not self._refresh_requested:
3839 self._refresh_requested = True
3840 self._requested_additional_startup_nodes = []
3841 self._requested_last_failed_node_name = None
3842 self._requested_disconnect_startup_nodes_pools = True
3843 # The epoch of the newest request. A refresh that completes after
3844 # it counts as answering every merged request, even one that
3845 # started before the error and read a slot map from before it: an
3846 # error that outlives it asks again
3847 self._refresh_requested_at_epoch = self._epoch
3848 for node_info in additional_startup_nodes_info or ():
3849 if node_info not in self._requested_additional_startup_nodes:
3850 self._requested_additional_startup_nodes.append(node_info)
3851 if last_failed_node_name is not None:
3852 self._requested_last_failed_node_name = last_failed_node_name
3853 if not disconnect_startup_nodes_pools:
3854 self._requested_disconnect_startup_nodes_pools = False
3856 def _run_requested_refresh(self, retry: Optional[AbstractRetry] = None) -> None:
3857 """
3858 Run the requested topology refresh, if there is one and it is due.
3859 The command and pipeline loops check ``_refresh_requested`` themselves
3860 before calling this, to keep the attempts that have nothing to run free
3861 of a call.
3863 A refresh that fails is logged and asked for again; the current
3864 topology keeps serving. Any other error is raised, and the refresh is
3865 still asked for again.
3866 """
3867 if not self._refresh_requested or not self._refresh_due(retry):
3868 return
3869 with self._lock:
3870 if not self._refresh_requested:
3871 # Another caller took it
3872 return
3873 self._refresh_requested = False
3874 if self._refresh_requested_at_epoch != self._epoch:
3875 # A refresh already completed after the last request
3876 return
3877 additional_startup_nodes_info = self._requested_additional_startup_nodes
3878 last_failed_node_name = self._requested_last_failed_node_name
3879 disconnect_startup_nodes_pools = (
3880 self._requested_disconnect_startup_nodes_pools
3881 )
3882 try:
3883 self.initialize(
3884 additional_startup_nodes_info=additional_startup_nodes_info,
3885 disconnect_startup_nodes_pools=disconnect_startup_nodes_pools,
3886 last_failed_node_name=last_failed_node_name,
3887 )
3888 except RedisClusterException as e:
3889 # The failure is counted, so the request made again here runs once
3890 # the backoff allows, still trying the failed node last
3891 self._request_refresh(
3892 additional_startup_nodes_info=additional_startup_nodes_info,
3893 last_failed_node_name=last_failed_node_name,
3894 disconnect_startup_nodes_pools=disconnect_startup_nodes_pools,
3895 )
3896 # No node answered, or nodes answered with a topology that cannot
3897 # replace the current one (slots not covered, or nodes that
3898 # disagree on them). The current topology keeps serving until a
3899 # refresh succeeds: this may be a command for a healthy shard, which
3900 # must not fail for a refresh another error asked for.
3901 logger.error(f"Topology refresh failed, keeping the current one: {e}")
3902 except BaseException:
3903 # Any other error is raised, but the request is kept: the flag was
3904 # cleared above, and no later attempt would run it otherwise
3905 self._request_refresh(
3906 additional_startup_nodes_info=additional_startup_nodes_info,
3907 last_failed_node_name=last_failed_node_name,
3908 disconnect_startup_nodes_pools=disconnect_startup_nodes_pools,
3909 )
3910 raise
3912 def _current_topology_nodes(
3913 self,
3914 queried_nodes: Iterable["ClusterNode"],
3915 last_failed_node_name: str | None,
3916 ) -> Iterator["ClusterNode"]:
3917 """
3918 The nodes of the current topology that are not in :queried_nodes:, for
3919 a refresh that got no slot map covering all slots from them. With
3920 dynamic_startup_nodes=False the startup nodes are only the seeds, which
3921 may fail while the nodes of the current topology still answer. The
3922 order is random, so clients don't all ask the same node, with the
3923 nodes that have a connection open first, as they served commands
3924 lately and no error closed it, and :last_failed_node_name: last. A
3925 node with no client is skipped: only a node that move_slot added
3926 before its command built one has none, and any other node answers
3927 with the same slot map. So the refresh queries every node through the
3928 client the node keeps, and never installs one on a node that command
3929 threads can reach. A generator: nothing is computed unless the
3930 refresh reaches it.
3931 """
3932 queried_names = {node.name for node in queried_nodes}
3933 with self._lock:
3934 nodes = [
3935 node
3936 for name, node in self.nodes_cache.items()
3937 if name not in queried_names
3938 ]
3939 random.shuffle(nodes)
3940 connected_nodes = []
3941 other_nodes = []
3942 last_failed_node = None
3943 for node in nodes:
3944 r = node.redis_connection
3945 if r is None:
3946 continue
3947 if node.name == last_failed_node_name:
3948 last_failed_node = node
3949 elif any(
3950 connection.is_connected
3951 for connection in r.connection_pool._get_free_connections()
3952 ) or any(
3953 connection.is_connected
3954 for connection in r.connection_pool._get_in_use_connections()
3955 ):
3956 connected_nodes.append(node)
3957 else:
3958 other_nodes.append(node)
3959 yield from connected_nodes
3960 yield from other_nodes
3961 if last_failed_node is not None:
3962 yield last_failed_node
3964 def initialize(
3965 self,
3966 additional_startup_nodes_info: Optional[List[Tuple[str, int]]] = None,
3967 disconnect_startup_nodes_pools: bool = True,
3968 last_failed_node_name: Optional[str] = None,
3969 ):
3970 """
3971 Initializes the nodes cache, slots cache and redis connections.
3972 CLUSTER SLOTS is asked of the startup nodes, the additional startup
3973 nodes and the last failed node, then, while no slot map covers all
3974 slots, of the other nodes of the current topology.
3975 :startup_nodes:
3976 Responsible for discovering other nodes in the cluster
3977 :disconnect_startup_nodes_pools:
3978 Whether to disconnect the connection pool of the startup nodes
3979 after the initialization is complete. This is useful when the
3980 startup nodes are not part of the cluster and we want to avoid
3981 keeping the connection open. Only the pools that serve no node
3982 of the new topology are disconnected; the nodes of the topology
3983 keep their connections.
3984 :additional_startup_nodes_info:
3985 Additional nodes to add temporarily to the startup nodes.
3986 The additional nodes will be used just in the process of extraction of the slots
3987 and nodes information from the cluster.
3988 This is useful when we want to add new nodes to the cluster
3989 and initialize the client
3990 with them.
3991 The format of the list is a list of tuples, where each tuple contains
3992 the host and port of the node. The connections they open are
3993 released once the refresh is done.
3994 :last_failed_node_name:
3995 Name of the node that just failed and should be tried only after
3996 other startup and additional startup nodes during this refresh.
3997 """
3998 if self._initializing_thread_id == threading.get_ident():
3999 # Re-entrant call on the thread that is already refreshing the
4000 # topology: a push notification (SMIGRATED) arrived on the CLUSTER
4001 # SLOTS response below and was handled inline on this thread. The
4002 # outer call is mid-refresh and will publish its own result, so
4003 # running a nested refresh here would reset() and swap the caches
4004 # underneath it, only for the outer call to overwrite them again
4005 # with its older snapshot. Skip instead; the outer refresh reads the
4006 # authoritative slot map anyway, and anything it still misses is
4007 # recovered through MOVED redirection.
4008 #
4009 # Reading the attribute without the lock is safe: while this thread
4010 # holds _initialization_lock it is the only writer, so a match can
4011 # only ever mean "this thread set it". A stale ident belonging to
4012 # another thread simply fails the comparison and falls through to
4013 # the normal blocking acquire below.
4014 if is_debug_log_enabled():
4015 logger.debug(
4016 "Topology refresh: skipping re-entrant initialize on thread "
4017 f"{threading.get_ident()}"
4018 )
4019 return
4020 self.reset()
4021 tmp_nodes_cache = {}
4022 tmp_slots = {}
4023 disagreements = []
4024 startup_nodes_reachable = False
4025 fully_covered = False
4026 kwargs = self.connection_kwargs
4027 exception = None
4028 epoch = self._get_epoch()
4029 if additional_startup_nodes_info is None:
4030 additional_startup_nodes_info = []
4032 with (
4033 self._initialization_lock,
4034 self._initializing_on_this_thread(),
4035 self._counting_failed_refresh(),
4036 self._releasing_queried_clients(disconnect_startup_nodes_pools) as (
4037 queried_startup_nodes,
4038 queried_additional_clients,
4039 ),
4040 ):
4041 with self._lock:
4042 if epoch != self._epoch:
4043 # another thread has already re-initialized the nodes; don't
4044 # bother running again
4045 return
4047 with self._lock:
4048 startup_nodes = list(self.startup_nodes.values())
4049 startup_node_names = {node.name for node in startup_nodes}
4050 deferred_failed_nodes = []
4051 if last_failed_node_name is not None:
4052 for index, node in enumerate(startup_nodes):
4053 if node.name == last_failed_node_name:
4054 deferred_failed_nodes.append(startup_nodes.pop(index))
4055 break
4056 if len(startup_nodes) > 1:
4057 # Vary which startup node is queried first so clients do not
4058 # all reinitialize through the same node.
4059 random.shuffle(startup_nodes)
4061 # An address that is already a startup node is queried through that
4062 # node's client, so a second client never replaces a live node's one.
4063 # One that is a node of the current topology with a client (e.g. the
4064 # target of the MOVED that asked for this refresh) is queried through
4065 # that node, over the connections it already has, and keeps them.
4066 # Startup nodes are named after the resolved localhost, like
4067 # ClusterNode names them.
4068 additional_startup_nodes = []
4069 for host, port in additional_startup_nodes_info:
4070 name = get_node_name(
4071 _resolve_localhost() if host == "localhost" else host, port
4072 )
4073 if name in startup_node_names:
4074 continue
4075 with self._lock:
4076 node = self.nodes_cache.get(name)
4077 if node is None or node.redis_connection is None:
4078 node = ClusterNode(host, port)
4079 additional_startup_nodes.append(node)
4080 if last_failed_node_name is not None:
4081 for index, node in enumerate(additional_startup_nodes):
4082 if node.name == last_failed_node_name:
4083 if not deferred_failed_nodes:
4084 deferred_failed_nodes.append(node)
4085 additional_startup_nodes.pop(index)
4086 break
4087 if is_debug_log_enabled():
4088 logger.debug(
4089 f"Topology refresh: using additional nodes: {[node.name for node in additional_startup_nodes]}; "
4090 f"and startup nodes: {[node.name for node in startup_nodes]}"
4091 )
4093 for startup_node in chain(
4094 startup_nodes,
4095 additional_startup_nodes,
4096 deferred_failed_nodes,
4097 # Only reached while no node gave a slot map covering all slots
4098 self._current_topology_nodes(
4099 chain(
4100 startup_nodes, additional_startup_nodes, deferred_failed_nodes
4101 ),
4102 last_failed_node_name,
4103 ),
4104 ):
4105 try:
4106 created_client = False
4107 if startup_node.redis_connection:
4108 r = startup_node.redis_connection
4110 else:
4111 created_client = True
4112 # Create a new Redis connection
4113 if is_debug_log_enabled():
4114 socket_timeout = kwargs.get("socket_timeout", "not set")
4115 socket_connect_timeout = kwargs.get(
4116 "socket_connect_timeout", "not set"
4117 )
4118 maint_enabled = (
4119 self.maint_notifications_config.enabled
4120 if self.maint_notifications_config
4121 else False
4122 )
4123 logger.debug(
4124 "Topology refresh: Creating new Redis connection to "
4125 f"{startup_node.host}:{startup_node.port}; "
4126 f"with socket_timeout: {socket_timeout}, and "
4127 f"socket_connect_timeout: {socket_connect_timeout}, "
4128 "and maint_notifications enabled: "
4129 f"{maint_enabled}"
4130 )
4131 r = self.create_redis_node(
4132 startup_node.host,
4133 startup_node.port,
4134 maint_notifications_config=self.maint_notifications_config,
4135 **kwargs,
4136 )
4137 if startup_node.name in self.startup_nodes:
4138 self.startup_nodes[startup_node.name].redis_connection = r
4139 else:
4140 startup_node.redis_connection = r
4141 # Collected before the query, so a client is released also
4142 # when its CLUSTER SLOTS raises. A node of the current
4143 # topology is queried through its own client, which stays
4144 # with the node: _release_removed_nodes releases it if the
4145 # node leaves the topology.
4146 if startup_node.name in self.startup_nodes:
4147 queried_startup_nodes.append((startup_node.name, r))
4148 elif created_client:
4149 queried_additional_clients.append(r)
4150 try:
4151 if is_debug_log_enabled():
4152 logger.debug(
4153 "Topology refresh: querying CLUSTER SLOTS on "
4154 f"{startup_node.name}"
4155 )
4156 # Make sure cluster mode is enabled on this node
4157 cluster_slots = str_if_bytes(r.execute_command("CLUSTER SLOTS"))
4158 except ResponseError:
4159 raise RedisClusterException(
4160 "Cluster mode is not enabled on this node"
4161 )
4162 startup_nodes_reachable = True
4163 # An error from an earlier startup node is only raised when
4164 # no node answers, so drop it. Its traceback refers to this
4165 # frame: keeping it forms a reference cycle that holds
4166 # tmp_slots and tmp_nodes_cache until the GC runs.
4167 exception = None
4168 except Exception as e:
4169 # Try the next startup node.
4170 # The last error is kept while no node has answered, and is
4171 # raised only if none does.
4172 if is_debug_log_enabled():
4173 logger.debug(
4174 "Topology refresh: CLUSTER SLOTS failed on "
4175 f"{startup_node.name}: {type(e).__name__}: {e}"
4176 )
4177 # Once a node has answered, later errors are not stored: they
4178 # would bring the cycle back.
4179 if not startup_nodes_reachable:
4180 exception = e
4181 continue
4183 # CLUSTER SLOTS command results in the following output:
4184 # [[slot_section[from_slot,to_slot,master,replica1,...,replicaN]]]
4185 # where each node contains the following list: [IP, port, node_id]
4186 # Therefore, cluster_slots[0][2][0] will be the IP address of the
4187 # primary node of the first slot section.
4188 # If there's only one server in the cluster, its ``host`` is ''
4189 # Fix it to the host in startup_nodes
4190 if (
4191 len(cluster_slots) == 1
4192 and not cluster_slots[0][2][0]
4193 and len(self.startup_nodes) == 1
4194 ):
4195 cluster_slots[0][2][0] = startup_node.host
4197 for slot in cluster_slots:
4198 primary_node = slot[2]
4199 host = str_if_bytes(primary_node[0])
4200 # A node that does not know its own address sends an empty
4201 # host, and one whose endpoint is unknown
4202 # (cluster-preferred-endpoint-type unknown-endpoint) a null
4203 # one: both are reached on the host that answered
4204 if not host:
4205 host = startup_node.host
4206 port = int(primary_node[1])
4207 host, port = self.remap_host_port(host, port)
4209 nodes_for_slot = []
4211 target_node = self._get_or_create_cluster_node(
4212 host, port, PRIMARY, tmp_nodes_cache
4213 )
4214 nodes_for_slot.append(target_node)
4216 replica_nodes = slot[3:]
4217 for replica_node in replica_nodes:
4218 host = str_if_bytes(replica_node[0])
4219 if not host:
4220 host = startup_node.host
4221 port = int(replica_node[1])
4222 host, port = self.remap_host_port(host, port)
4223 target_replica_node = self._get_or_create_cluster_node(
4224 host, port, REPLICA, tmp_nodes_cache
4225 )
4226 nodes_for_slot.append(target_replica_node)
4228 for i in range(int(slot[0]), int(slot[1]) + 1):
4229 if i not in tmp_slots:
4230 tmp_slots[i] = nodes_for_slot
4231 else:
4232 # Validate that 2 nodes want to use the same slot cache
4233 # setup
4234 tmp_slot = tmp_slots[i][0]
4235 if tmp_slot.name != target_node.name:
4236 disagreements.append(
4237 f"{tmp_slot.name} vs {target_node.name} on slot: {i}"
4238 )
4240 if len(disagreements) > 5:
4241 raise RedisClusterException(
4242 f"startup_nodes could not agree on a valid "
4243 f"slots cache: {', '.join(disagreements)}"
4244 )
4246 fully_covered = self.check_slots_coverage(tmp_slots)
4247 if is_debug_log_enabled():
4248 logger.debug(
4249 f"Topology refresh: CLUSTER SLOTS from {startup_node.name} "
4250 f"reported nodes {sorted(tmp_nodes_cache)}; "
4251 f"slots fully covered: {fully_covered}"
4252 )
4253 if fully_covered:
4254 # Don't need to continue to the next startup node if all
4255 # slots are covered
4256 break
4258 if not startup_nodes_reachable:
4259 # The unreachable subtype is reserved for connectivity failures:
4260 # MultiDB registers it as retryable, so a deterministic
4261 # server/configuration error (e.g. cluster mode disabled or
4262 # invalid credentials - AuthenticationError and
4263 # AuthorizationError subclass ConnectionError but cannot be
4264 # repaired by a failover) must keep surfacing as a plain
4265 # RedisClusterException.
4266 try:
4267 if isinstance(
4268 exception, (ConnectionError, TimeoutError, OSError)
4269 ) and not isinstance(
4270 exception, (AuthenticationError, AuthorizationError)
4271 ):
4272 raise RedisClusterUnreachableError(
4273 f"Redis Cluster cannot be connected. Please provide at least "
4274 f"one reachable node: {str(exception)}"
4275 ) from exception
4276 raise RedisClusterException(
4277 f"Redis Cluster cannot be connected. Please provide at least "
4278 f"one reachable node: {str(exception)}"
4279 ) from exception
4280 finally:
4281 # Ensure we clear local references to caught exceptions
4282 exception = None
4284 # Check if the slots are not fully covered
4285 if not fully_covered and self._require_full_coverage:
4286 # Despite the requirement that the slots be covered, there
4287 # isn't a full coverage
4288 raise RedisClusterException(
4289 f"All slots are not covered after query all startup_nodes. "
4290 f"{len(tmp_slots)} of {REDIS_CLUSTER_HASH_SLOTS} "
4291 f"covered..."
4292 )
4294 # Create Redis connections to all new nodes. They are registered for
4295 # re-authentication once they replace the current nodes below.
4296 self._create_redis_connections(tmp_nodes_cache.values())
4298 # Set the tmp variables to the real variables
4299 with self._lock:
4300 old_nodes_cache = self.nodes_cache
4301 self.nodes_cache = tmp_nodes_cache
4302 self.slots_cache = tmp_slots
4303 # Set the default node
4304 self.default_node = self.get_nodes_by_server_type(PRIMARY)[0]
4305 if self._dynamic_startup_nodes:
4306 # Populate the startup nodes with all discovered nodes
4307 self.startup_nodes = tmp_nodes_cache
4308 self._last_refresh_at = time.monotonic()
4309 self._failed_refreshes = 0
4310 self._refresh_due_at = None
4311 self._last_refresh_unreachable_args = None
4312 # Increment the epoch to signal that initialization has completed
4313 self._epoch += 1
4314 # The published cache can change under other threads from now
4315 # on (move_slot, move_node_to_end_of_cached_nodes)
4316 new_nodes = tuple(tmp_nodes_cache.values())
4317 new_node_names = frozenset(tmp_nodes_cache)
4319 # Register the new pools for re-authentication before releasing the
4320 # removed ones, so a token refresh never targets a released pool.
4321 # Connection pool locks are taken outside self._lock.
4322 self._dispatch_pools_instantiated(new_nodes)
4323 self._release_removed_nodes(old_nodes_cache, new_node_names)
4324 # Dispatch so listeners (e.g. ClusterPubSub) can reconcile per-node
4325 # state after slot ownership may have changed. A listener must not
4326 # break slots-cache refresh; log and continue so a single buggy
4327 # listener cannot starve the rest.
4328 try:
4329 self._event_dispatcher.dispatch(AfterSlotsCacheRefreshEvent())
4330 except Exception as e:
4331 logger.exception(
4332 "listener raised during slots-cache refresh: %s: %s",
4333 type(e).__name__,
4334 e,
4335 )
4337 def close(self) -> None:
4338 with self._lock:
4339 self.default_node = None
4340 nodes = tuple(self.nodes_cache.values())
4341 for node in nodes:
4342 if node.redis_connection:
4343 node.redis_connection.close()
4345 def reset(self):
4346 try:
4347 self.read_load_balancer.reset()
4348 except TypeError:
4349 # The read_load_balancer is None, do nothing
4350 pass
4352 def remap_host_port(self, host: str, port: int) -> Tuple[str, int]:
4353 """
4354 Remap the host and port returned from the cluster to a different
4355 internal value. Useful if the client is not connecting directly
4356 to the cluster.
4357 """
4358 if self.address_remap:
4359 return self.address_remap((host, port))
4360 return host, port
4362 def find_connection_owner(self, connection: Connection) -> Optional[ClusterNode]:
4363 node_name = get_node_name(connection.host, connection.port)
4364 with self._lock:
4365 for node in tuple(self.nodes_cache.values()):
4366 if node.redis_connection:
4367 conn_args = node.redis_connection.connection_pool.connection_kwargs
4368 if node_name == get_node_name(
4369 conn_args.get("host"), conn_args.get("port")
4370 ):
4371 return node
4372 return None
4375def _unregister_slots_cache_listener(
4376 dispatcher_ref: "weakref.ref[EventDispatcher]",
4377 listener: EventListenerInterface,
4378 event_type: Type[object],
4379) -> None:
4380 # Module-level finalizer callback. Kept free of strong references to the
4381 # owning ClusterPubSub so attaching it via weakref.finalize does not
4382 # extend the pubsub's lifetime.
4383 dispatcher = dispatcher_ref()
4384 if dispatcher is not None:
4385 dispatcher.unregister_listeners({event_type: [listener]})
4388class ClusterPubSubSlotsCacheListener(EventListenerInterface):
4389 """
4390 Listener that forwards AfterSlotsCacheRefreshEvent to a ClusterPubSub.
4392 Holds a weak reference to the pubsub so it does not keep the instance
4393 alive. Deterministic cleanup of the dispatcher's strong reference to this
4394 listener is performed by a ``weakref.finalize`` attached to the owning
4395 ClusterPubSub in ``ClusterPubSub.__init__``.
4396 """
4398 def __init__(self, pubsub: "ClusterPubSub") -> None:
4399 self._pubsub_ref: "weakref.ref[ClusterPubSub]" = weakref.ref(pubsub)
4401 def listen(self, event: object) -> None:
4402 pubsub = self._pubsub_ref()
4403 if pubsub is None:
4404 # Race window between pubsub GC and the finalizer running; safe
4405 # no-op, finalizer will remove this listener shortly.
4406 return
4407 try:
4408 pubsub.on_slots_changed()
4409 except Exception as e:
4410 # Listeners must not break slots-cache refresh; log and continue so
4411 # a single buggy pubsub cannot starve the rest.
4412 logger.exception(
4413 "pubsub %r raised during slots-cache change: %s: %s",
4414 pubsub,
4415 type(e).__name__,
4416 e,
4417 )
4420# How long a per-node sharded-pubsub connection is skipped by the round robin
4421# after a failed poll. PubSub._execute reconnects and retries through the
4422# connection's own Retry, so one poll on an unreachable node can cost its whole
4423# retry budget rather than the timeout the caller asked for; a cool-off keeps
4424# the single reader from spending every pass on that node while its healthy
4425# siblings hold undelivered messages.
4426SHARD_POLL_COOL_OFF_SECONDS = 1.0
4428# Returned by _poll_node_pubsub when a handler consumed the message it read.
4429_DISPATCHED = object()
4431# How long an unbounded sharded-pubsub poll waits for a not-yet-subscribed
4432# per-node pubsub before re-checking that the pubsub is still in
4433# node_pubsub_mapping. A retired one is never resubscribed and its
4434# subscribed_event is never set again, so an uninterrupted wait would park the
4435# single reader for good and stop delivery from every healthy sibling too.
4436# Only a poll that would otherwise block indefinitely ticks at all.
4437SHARD_SUBSCRIBE_WAIT_TICK_SECONDS = 1.0
4439# How often a failed sharded-pubsub poll may trigger a slots-cache refresh.
4440# Reconciliation is otherwise purely event-driven, and a node that has left the
4441# deployment answers ECONNREFUSED rather than MOVED - so without this the reader
4442# would cool off against the departed node forever and the shard channels pinned
4443# to it would never move to their new owner. Throttled because the refresh costs
4444# a CLUSTER SLOTS round trip and a failing node fails every poll.
4445SHARD_TOPOLOGY_REPAIR_INTERVAL_SECONDS = 5.0
4448class ClusterPubSub(PubSub):
4449 """
4450 Wrapper for PubSub class.
4452 IMPORTANT: before using ClusterPubSub, read about the known limitations
4453 with pubsub in Cluster mode and learn how to workaround them:
4454 https://redis.readthedocs.io/en/stable/clustering.html#known-pubsub-limitations
4455 """
4457 def __init__(
4458 self,
4459 redis_cluster,
4460 node=None,
4461 host=None,
4462 port=None,
4463 push_handler_func=None,
4464 event_dispatcher: Optional["EventDispatcher"] = None,
4465 **kwargs,
4466 ):
4467 """
4468 When a pubsub instance is created without specifying a node, a single
4469 node will be transparently chosen for the pubsub connection on the
4470 first command execution. The node will be determined by:
4471 1. Hashing the channel name in the request to find its keyslot
4472 2. Selecting a node that handles the keyslot: If read_from_replicas is
4473 set to true or load_balancing_strategy is set, a replica can be selected.
4475 :type redis_cluster: RedisCluster
4476 :type node: ClusterNode
4477 :type host: str
4478 :type port: int
4479 """
4480 self.node = None
4481 self.set_pubsub_node(redis_cluster, node, host, port)
4482 connection_pool = (
4483 None
4484 if self.node is None
4485 else redis_cluster.get_redis_connection(self.node).connection_pool
4486 )
4487 self.cluster = redis_cluster
4488 self.node_pubsub_mapping = {}
4489 # Reverse index: shard channel (normalized) -> owning node.name. Used to
4490 # route sunsubscribe calls and reconcile subscriptions after slot
4491 # migration / failover.
4492 self._shard_channel_to_node: dict = {}
4493 # Per-node poll cool-off deadlines (monotonic). Weak-keyed so a
4494 # per-node pubsub dropped from node_pubsub_mapping takes its entry with
4495 # it instead of leaking one per migration.
4496 self._poll_cool_off: "weakref.WeakKeyDictionary[PubSub, float]" = (
4497 weakref.WeakKeyDictionary()
4498 )
4499 # Node names whose last poll failed to connect. Read by
4500 # _migrate_shard_channel to skip a wire SUNSUBSCRIBE that cannot
4501 # succeed, and cleared as soon as a poll on that node works again.
4502 self._unreachable_nodes: Set[str] = set()
4503 # Monotonic deadline before which a failed poll must not trigger
4504 # another slots-cache refresh. 0.0 means "never refreshed".
4505 self._next_topology_repair: float = 0.0
4506 # Dedicated lock for shard-subscription bookkeeping. Distinct from
4507 # PubSub.self._lock (which serializes wire I/O on the cluster-level
4508 # connection used by aclose / send_command / regular subscribe) so
4509 # that reconciliation cannot starve those unrelated paths during
4510 # long per-channel migrations.
4511 self._shard_state_lock: threading.RLock = threading.RLock()
4512 # Worker executor for off-loading slot-migration reconciliation from
4513 # the dispatch call site (mirrors async's asyncio.create_task model so
4514 # the thread that triggered MovedError / topology refresh is not
4515 # blocked on per-channel sunsubscribe / ssubscribe network I/O).
4516 #
4517 # Installed by reset(), which PubSub.__init__ calls below, and replaced
4518 # by every later reset() - so it is never None once construction has
4519 # finished and the scheduling sites need no lock to create it. That
4520 # matters: on_slots_changed runs inline on whichever thread refreshed
4521 # the topology, which can be a thread that handled an SMIGRATED push and
4522 # still holds OSSMaintNotificationsHandler._lock while a third thread
4523 # waits for that handler lock holding a per-node pubsub I/O lock the
4524 # reconciliation worker needs - so blocking there on _shard_state_lock
4525 # closes a three-thread deadlock cycle.
4526 #
4527 # Constructing an executor starts no thread; ThreadPoolExecutor spawns
4528 # its worker on the first submit(), so pubsubs that never see a slot
4529 # migration never pay for one. Declared before super().__init__()
4530 # because reset() reads it.
4531 self._reconcile_executor: Optional[ThreadPoolExecutor] = None
4532 self._pubsubs_generator = self._pubsubs_generator()
4533 if event_dispatcher is None:
4534 self._event_dispatcher = EventDispatcher()
4535 else:
4536 self._event_dispatcher = event_dispatcher
4537 super().__init__(
4538 connection_pool=connection_pool,
4539 encoder=redis_cluster.encoder,
4540 push_handler_func=push_handler_func,
4541 event_dispatcher=self._event_dispatcher,
4542 **kwargs,
4543 )
4544 # Subscribe to slots-cache change notifications so shard subscriptions
4545 # can be reconciled automatically after topology refreshes.
4546 nm_dispatcher = redis_cluster.nodes_manager._event_dispatcher
4547 self._slots_cache_listener = ClusterPubSubSlotsCacheListener(self)
4548 nm_dispatcher.register_listeners(
4549 {AfterSlotsCacheRefreshEvent: [self._slots_cache_listener]}
4550 )
4551 # Deterministic GC-time cleanup so short-lived pubsubs do not leak
4552 # listeners in the dispatcher when no slots-refresh event ever fires.
4553 weakref.finalize(
4554 self,
4555 _unregister_slots_cache_listener,
4556 weakref.ref(nm_dispatcher),
4557 self._slots_cache_listener,
4558 AfterSlotsCacheRefreshEvent,
4559 )
4561 def set_pubsub_node(self, cluster, node=None, host=None, port=None):
4562 """
4563 The pubsub node will be set according to the passed node, host and port
4564 When none of the node, host, or port are specified - the node is set
4565 to None and will be determined by the keyslot of the channel in the
4566 first command to be executed.
4567 RedisClusterException will be thrown if the passed node does not exist
4568 in the cluster.
4569 If host is passed without port, or vice versa, a DataError will be
4570 thrown.
4571 :type cluster: RedisCluster
4572 :type node: ClusterNode
4573 :type host: str
4574 :type port: int
4575 """
4576 if node is not None:
4577 # node is passed by the user
4578 self._raise_on_invalid_node(cluster, node, node.host, node.port)
4579 pubsub_node = node
4580 elif host is not None and port is not None:
4581 # host and port passed by the user
4582 node = cluster.get_node(host=host, port=port)
4583 self._raise_on_invalid_node(cluster, node, host, port)
4584 pubsub_node = node
4585 elif any([host, port]) is True:
4586 # only 'host' or 'port' passed
4587 raise DataError("Passing a host requires passing a port, and vice versa")
4588 else:
4589 # nothing passed by the user. set node to None
4590 pubsub_node = None
4592 self.node = pubsub_node
4594 def get_pubsub_node(self):
4595 """
4596 Get the node that is being used as the pubsub connection
4597 """
4598 return self.node
4600 def _raise_on_invalid_node(self, redis_cluster, node, host, port):
4601 """
4602 Raise a RedisClusterException if the node is None or doesn't exist in
4603 the cluster.
4604 """
4605 if node is None or redis_cluster.get_node(node_name=node.name) is None:
4606 raise RedisClusterException(
4607 f"Node {host}:{port} doesn't exist in the cluster"
4608 )
4610 def execute_command(self, *args):
4611 """
4612 Execute a subscribe/unsubscribe command.
4614 Taken code from redis-py and tweak to make it work within a cluster.
4615 """
4616 # NOTE: don't parse the response in this function -- it could pull a
4617 # legitimate message off the stack if the connection is already
4618 # subscribed to one or more channels
4620 # For shard commands, route to appropriate node
4621 command = args[0].upper() if args else ""
4622 if command in ("SSUBSCRIBE", "SUNSUBSCRIBE", "SPUBLISH"):
4623 if len(args) > 1:
4624 # ssubscribe / sunsubscribe own both the per-node I/O lock and
4625 # the shard_channels / _shard_channel_to_node bookkeeping, so
4626 # delegate to them instead of dispatching raw. A raw dispatch
4627 # writes the socket unguarded against a concurrent poll and
4628 # records nothing, leaving the channel invisible to the reader
4629 # loop and to on_connect's replay.
4630 if command == "SSUBSCRIBE":
4631 return self.ssubscribe(*args[1:])
4632 if command == "SUNSUBSCRIBE":
4633 return self.sunsubscribe(*args[1:])
4634 channel = args[1]
4635 node = self.cluster.get_node_from_key(channel)
4636 if node:
4637 pubsub = self._get_node_pubsub(node)
4638 with self._pubsub_io_lock(pubsub):
4639 return pubsub.execute_command(*args)
4641 # For other commands, use the set node or lazily discover one
4642 if self.connection is None:
4643 if self.connection_pool is None:
4644 if len(args) > 1:
4645 # Hash the first channel and get one of the nodes holding
4646 # this slot
4647 channel = args[1]
4648 slot = self.cluster.keyslot(channel)
4649 node = self.cluster.nodes_manager.get_node_from_slot(
4650 slot,
4651 self.cluster.read_from_replicas,
4652 self.cluster.load_balancing_strategy,
4653 )
4654 else:
4655 # Get a random node
4656 node = self.cluster.get_random_node()
4657 self.node = node
4658 redis_connection = self.cluster.get_redis_connection(node)
4659 self.connection_pool = redis_connection.connection_pool
4660 self.connection = self.connection_pool.get_connection()
4661 # register a callback that re-subscribes to any channels we
4662 # were listening to when we were disconnected
4663 self.connection.register_connect_callback(self.on_connect)
4664 if self.push_handler_func is not None:
4665 self.connection._parser.set_pubsub_push_handler(self.push_handler_func)
4666 self._event_dispatcher.dispatch(
4667 AfterPubSubConnectionInstantiationEvent(
4668 self.connection, self.connection_pool, ClientType.SYNC, self._lock
4669 )
4670 )
4671 connection = self.connection
4672 self._execute(connection, connection.send_command, *args)
4674 def _resubscribe_shard_channels(self) -> None:
4675 # A single node can own multiple slot ranges, so a batched
4676 # ``SSUBSCRIBE`` covering every tracked channel would be rejected by
4677 # Redis with a ``CROSSSLOT`` error. Group by hash slot and emit one
4678 # ``SSUBSCRIBE`` per slot.
4679 by_slot: defaultdict[int, dict] = defaultdict(dict)
4680 for k, v in self.shard_channels.items():
4681 by_slot[key_slot(self.encoder.encode(k))][k] = v
4682 for subscriptions in by_slot.values():
4683 self._resubscribe(subscriptions, self.ssubscribe)
4685 def _get_node_pubsub(self, node):
4686 try:
4687 return self.node_pubsub_mapping[node.name]
4688 except KeyError:
4689 redis_connection = self.cluster.get_redis_connection(node)
4690 pubsub = redis_connection.pubsub(
4691 push_handler_func=self.push_handler_func,
4692 )
4693 # Replay shard subscriptions on reconnect with slot-aware grouping
4694 # so that channels spanning multiple slots owned by this node do
4695 # not trigger a CROSSSLOT error.
4696 pubsub._resubscribe_shard_channels = MethodType(
4697 ClusterPubSub._resubscribe_shard_channels, pubsub
4698 )
4699 self._pubsub_io_lock(pubsub)
4700 self.node_pubsub_mapping[node.name] = pubsub
4701 return pubsub
4703 def _find_node_name_for_pubsub(self, pubsub):
4704 # Snapshot the items: every caller but one runs without
4705 # _shard_state_lock, so iterating the mapping directly would raise
4706 # "dictionary changed size during iteration" whenever a concurrent
4707 # migration adds or retires a per-node pubsub - which is exactly when
4708 # these lookups happen. list() of a dict view is atomic under the GIL.
4709 for node_name, node_pubsub in list(self.node_pubsub_mapping.items()):
4710 if node_pubsub is pubsub:
4711 return node_name
4712 return None
4714 @staticmethod
4715 def _pubsub_io_lock(pubsub) -> threading.RLock:
4716 """Return the per-node pubsub's wire I/O lock, creating it on first use.
4718 A per-node ``PubSub`` is read by whichever thread polls
4719 ``get_sharded_message`` and written by the reconciliation worker
4720 (``_migrate_shard_channel``) and by any caller of ``ssubscribe`` /
4721 ``sunsubscribe``. ``PubSub`` guards writes with its own ``_lock``
4722 (``PubSub.execute_command``) but reads take no lock at all, so without
4723 this the reader can be inside ``read_response`` while another thread's
4724 ``_execute`` disconnects and reconnects the same socket underneath it -
4725 which loses the reply to the handshake and surfaces as a read timeout
4726 followed by ``EBADF``.
4728 Kept on the pubsub rather than in a dict keyed by node name so it
4729 travels with the object through ``node_pubsub_mapping`` and cannot go
4730 stale when a per-node pubsub is dropped and recreated.
4731 """
4732 lock = getattr(pubsub, "_shard_io_lock", None)
4733 if lock is None:
4734 lock = threading.RLock()
4735 pubsub._shard_io_lock = lock
4736 return lock
4738 @staticmethod
4739 def _detach_shard_channel(pubsub, channel) -> None:
4740 """Forget a shard channel on a per-node pubsub without a wire round trip.
4742 ``PubSub.sunsubscribe`` only records the intent in
4743 ``pending_unsubscribe_shard_channels``; the channel leaves
4744 ``shard_channels`` when the server confirmation is read. So if the
4745 ``SUNSUBSCRIBE`` never reaches the server, ``on_connect`` clears the
4746 pending set and replays ``SSUBSCRIBE`` for the channel - on the node it
4747 is being migrated away from, on every reconnect. Once the caller has
4748 decided the channel belongs to a different node, the local intent is
4749 the only truth left, so drop it here.
4751 Deliberately without the per-node I/O lock, unlike every other writer
4752 on a per-node pubsub. ``_forget_shard_channel_on_old_node`` calls this
4753 for a node the reader has just failed to reach, and a bounded poll holds
4754 that lock across ``PubSub._execute``'s reconnect and its whole retry
4755 budget - far longer than the timeout the poll was given. Waiting for it
4756 here, while this pass holds ``_shard_state_lock``, is the migration
4757 slow enough to look like a permanent delivery stall that the
4758 ``_unreachable_nodes`` fast path exists to avoid.
4760 Nothing needs the lock: each mutation below is individually atomic, and
4761 every interleaving with ``handle_message``'s unsubscribe bookkeeping (the
4762 only concurrent writer of the same state, and one that runs under that
4763 lock) converges on the same end state - the channel gone from both the
4764 subscription dict and the pending set. That bookkeeping discards rather
4765 than removes precisely so this detach cannot make it raise ``KeyError``
4766 into a poll no caller catches.
4767 """
4768 pubsub.shard_channels.pop(channel, None)
4769 pubsub.pending_unsubscribe_shard_channels.discard(channel)
4770 if not pubsub.channels and not pubsub.patterns and not pubsub.shard_channels:
4771 pubsub.subscribed_event.clear()
4773 def _drop_node_pubsub(self, name: str, pubsub) -> None:
4774 """Retire a per-node pubsub and drop it from ``node_pubsub_mapping``.
4776 Callers hold ``_shard_state_lock``, the lock that every mutation of
4777 that mapping observes. ``reset()`` runs under the per-node I/O lock so
4778 the socket is not torn down beneath a concurrent bounded poll parked in
4779 ``parse_response``, and its errors are swallowed: retiring one node's
4780 pubsub must not abort the caller's pass, and this also runs from the
4781 ``__del__`` fallback path through ``reset()``.
4783 Every caller must leave nothing subscribed on ``pubsub`` (or have lost
4784 the node itself). An empty per-node pubsub left in the mapping is what
4785 ``_poll_node_pubsub`` stalls on: its ``subscribed_event`` is cleared, so
4786 the prelude waits out the whole timeout of every pass - indefinitely when
4787 the caller passed ``timeout=None``, since the ``reset()`` below only
4788 clears that event again and no message can arrive on a subscription that
4789 is gone.
4791 Popping it from the mapping is also what makes the retirement
4792 *observable*: that prelude gives up on an unbounded wait once the pubsub
4793 it was handed is no longer mapped, which is the only thing standing
4794 between a reader that held the object across this call and a permanent
4795 park. The rebind below keeps it from being handed out to begin with.
4796 """
4797 try:
4798 with self._pubsub_io_lock(pubsub):
4799 pubsub.reset()
4800 except Exception:
4801 pass
4802 self.node_pubsub_mapping.pop(name, None)
4803 self._unreachable_nodes.discard(name)
4804 # Same snapshot reason ``reset()`` recreates this: ``_pubsubs_generator``
4805 # captures node_pubsub_mapping.values() into a local list inside
4806 # ``yield from``, which the pop above does not reach - so a generator
4807 # suspended mid-yield-from would still hand the object we just retired
4808 # to the next poll. ``type(self)`` bypasses the instance-level
4809 # self-shadow established at __init__. Costs nothing: constructing a
4810 # generator runs no frame, so the per-node collection loop in
4811 # reinitialize_shard_subscriptions can rebind once per dropped node.
4812 self._pubsubs_generator = type(self)._pubsubs_generator(self)
4814 def _sharded_message_generator(self, timeout=0.0):
4815 if timeout and len(self.node_pubsub_mapping) > 1:
4816 # Block only when no node has data, so a busy shard does not wait
4817 # out the slices of its idle siblings.
4818 deadline = time.monotonic() + timeout
4819 pubsub, message = self._sharded_pass(0.0)
4820 while message is None:
4821 # A node that returns early leaves time the nodes before it
4822 # did not get; pass again until the deadline.
4823 start = time.monotonic()
4824 if start >= deadline:
4825 break
4826 pubsub, message = self._sharded_pass(deadline - start)
4827 if not self.node_pubsub_mapping:
4828 # A pass over an emptied mapping has only waited, so
4829 # passing again before the deadline would read nothing.
4830 break
4831 if message is None:
4832 # A message can reach a node after its slice ran out.
4833 pubsub, message = self._sharded_pass(0.0)
4834 else:
4835 pubsub, message = self._sharded_pass(timeout)
4836 if message is _DISPATCHED:
4837 return None, None
4838 return pubsub, message
4840 def _sharded_pass(self, timeout):
4841 """Poll each node once; ``message`` may be ``_DISPATCHED``."""
4842 first_error: Optional[BaseException] = None
4843 polled = 0
4844 failed = 0
4845 next_ready: Optional[float] = None
4846 nodes = len(self.node_pubsub_mapping)
4847 # Split the wait across the pass, otherwise every idle node ahead of the
4848 # one with a message adds a full timeout. Each poll gets an equal share
4849 # of what is left, so a skipped or fast-failing node passes its share on.
4850 split = bool(timeout) and nodes > 1
4851 node_timeout = timeout
4852 if split:
4853 pass_deadline = time.monotonic() + timeout
4854 now = time.monotonic()
4855 left = sum(
4856 1
4857 for ps in list(self.node_pubsub_mapping.values())
4858 if self._poll_cool_off.get(ps, 0.0) <= now
4859 )
4860 for _ in range(nodes):
4861 pubsub = next(self._pubsubs_generator)
4862 if pubsub is None:
4863 # node_pubsub_mapping was emptied between the len() above and
4864 # here; nothing left to poll in this pass.
4865 break
4866 if self._poll_cool_off:
4867 deadline = self._poll_cool_off.get(pubsub, 0.0)
4868 if time.monotonic() < deadline:
4869 # In cool-off after a failed poll: skip it so the reader
4870 # spends this pass on the nodes that can still deliver.
4871 if next_ready is None or deadline < next_ready:
4872 next_ready = deadline
4873 continue
4874 polled += 1
4875 if split:
4876 node_timeout = max(pass_deadline - time.monotonic(), 0.0) / max(left, 1)
4877 left -= 1
4878 try:
4879 message = self._poll_node_pubsub(pubsub, node_timeout)
4880 except MovedError as e:
4881 # Handled, not failed: _handle_moved_on_read re-routes the
4882 # offending channels and schedules reconciliation, so the next
4883 # pass recovers. Re-raising a MovedError out of a pubsub read
4884 # would only hand the caller an error it cannot act on. Still
4885 # cool off: if the slots cache cannot be corrected the repair
4886 # would otherwise re-run on every poll.
4887 self._poll_cool_off[pubsub] = (
4888 time.monotonic() + SHARD_POLL_COOL_OFF_SECONDS
4889 )
4890 self._handle_moved_on_read(pubsub, e)
4891 continue
4892 except (ConnectionError, TimeoutError, OSError) as e:
4893 # One unhealthy node must not starve its healthy siblings. A
4894 # single reader serves every per-node pubsub, so aborting the
4895 # pass here stops delivery cluster-wide for as long as this one
4896 # node stays unreachable - even though the slots it no longer
4897 # serves are the only ones affected. Keep polling the rest and
4898 # surface an error only if nothing in the pass worked, the same
4899 # made-progress rule reinitialize_shard_subscriptions applies.
4900 failed += 1
4901 if first_error is None:
4902 first_error = e
4903 # Cool off before polling this one again. PubSub._execute
4904 # reconnects and then retries through the connection's own
4905 # Retry, so a single "bounded" poll on an unreachable node can
4906 # cost its whole retry budget - far longer than the timeout the
4907 # caller asked for. Without a cool-off the reader goes straight
4908 # back to that node on the next pass and pays it again, which
4909 # is what turns one sick node into a cluster-wide delivery
4910 # stall.
4911 self._poll_cool_off[pubsub] = (
4912 time.monotonic() + SHARD_POLL_COOL_OFF_SECONDS
4913 )
4914 # Deliberately outside _shard_state_lock: this is an advisory
4915 # hint for _migrate_shard_channel's fast path, mutated with
4916 # single atomic set operations, and both misread directions are
4917 # handled there and self-heal - a stale entry only skips a
4918 # SUNSUBSCRIBE to a dead node, a missing one only pays a
4919 # reconnect before the same local forget.
4920 node_name = self._find_node_name_for_pubsub(pubsub)
4921 if node_name is not None:
4922 self._unreachable_nodes.add(node_name)
4923 if is_debug_log_enabled():
4924 logger.debug(
4925 "sharded pubsub poll failed on %s: %s: %s",
4926 node_name,
4927 type(e).__name__,
4928 e,
4929 )
4930 # A node that has left the deployment never answers MOVED, so
4931 # this branch is the only signal that its shard channels may
4932 # need a new owner. Ask for a slots-cache refresh; its dispatch
4933 # reaches on_slots_changed and reconciles.
4934 self._schedule_topology_repair()
4935 continue
4936 # Emptiness check first: this is the per-message hot path, and the
4937 # weakref lookup a WeakKeyDictionary pop needs is pure overhead
4938 # while no node is in cool-off, which is the normal case.
4939 if self._poll_cool_off:
4940 self._poll_cool_off.pop(pubsub, None)
4941 if self._unreachable_nodes:
4942 node_name = self._find_node_name_for_pubsub(pubsub)
4943 if node_name is not None:
4944 self._unreachable_nodes.discard(node_name)
4945 if message is not None:
4946 return pubsub, message
4947 if first_error is not None and failed == polled:
4948 raise first_error
4949 if polled == 0:
4950 if next_ready is None:
4951 # No node to read and none cooling off: node_pubsub_mapping is
4952 # empty. A reconciliation pass whose every attach failed leaves
4953 # it that way - the GC drops the per-node pubsubs that hold
4954 # nothing - and its shard channels only retry on the next
4955 # slots-cache change, which a settled topology never sends. Ask
4956 # for one, and wait as for a cool-off: returning at once would
4957 # spin a reader loop on get_sharded_message.
4958 self._schedule_topology_repair()
4959 next_ready = time.monotonic() + SHARD_POLL_COOL_OFF_SECONDS
4960 self._wait_out_cool_off(next_ready, timeout)
4961 return None, None
4963 @staticmethod
4964 def _wait_out_cool_off(next_ready: float, timeout) -> None:
4965 """Wait out a pass in which every node was skipped for cool-off.
4967 Such a pass does no wire read at all, so returning straight away
4968 ignores the timeout the caller asked to block for - and a reader loop
4969 (``PubSubWorkerThread.run`` with ``sharded_pubsub=True``, or a user
4970 loop on ``get_sharded_message``) polls back immediately, spinning
4971 until the cool-off expires instead of blocking. Sleep instead: until
4972 the earliest cool-off is over, never longer than the caller's timeout,
4973 and not at all for a non-blocking poll.
4974 """
4975 if timeout is not None and timeout <= 0:
4976 return
4977 delay = next_ready - time.monotonic()
4978 if delay <= 0:
4979 return
4980 if timeout is not None:
4981 delay = min(delay, timeout)
4982 time.sleep(delay)
4984 def _poll_io_lock(self, pubsub, timeout):
4985 """Guard a per-node poll against concurrent writers on the same socket.
4987 ``timeout=None`` makes ``_poll_node_pubsub``'s read block indefinitely,
4988 so holding the lock across it would block reconciliation for as long as
4989 no message arrives. Such a caller drives the pubsub itself and gets the
4990 pre-existing unguarded behavior; every bounded poll - which is what
4991 ``PubSubWorkerThread`` and ``ClusterPubSub``'s own callers use - is
4992 serialized.
4993 """
4994 if timeout is None:
4995 return nullcontext()
4996 return self._pubsub_io_lock(pubsub)
4998 def _poll_node_pubsub(self, pubsub, timeout):
4999 """Read one message from a per-node pubsub, dispatching outside the lock.
5001 Splits ``PubSub.get_message`` so the per-node I/O lock covers the wire
5002 read only. ``handle_message`` invokes a subscribed channel's user
5003 handler inline, and a handler is free to call ``ssubscribe`` /
5004 ``sunsubscribe`` on this ``ClusterPubSub`` - which takes
5005 ``_shard_state_lock`` and then the same I/O lock. Holding the I/O lock
5006 across the handler therefore deadlocks against the reconciliation
5007 worker, which holds ``_shard_state_lock`` and waits for that I/O lock:
5008 an ABBA cycle between two threads that the ``RLock``'s self-reentrancy
5009 cannot break. The async counterpart's non-reentrant ``asyncio.Lock``
5010 hangs on the re-acquire alone, before any reconciliation is involved.
5012 The two halves of ``handle_message`` are mutually exclusive:
5013 ``UNSUBSCRIBE_MESSAGE_TYPES`` does subscription bookkeeping and never
5014 reaches a handler, ``PUBLISH_MESSAGE_TYPES`` only dispatches. So
5015 bookkeeping stays inside the lock - it mutates the very
5016 ``shard_channels`` / ``pending_unsubscribe_shard_channels`` that
5017 ``ssubscribe`` / ``sunsubscribe`` mutate under this lock - and only the
5018 dispatch moves out. The cost is a narrow race: a reconciliation pass
5019 that detaches the channel between the read and the dispatch makes the
5020 handler lookup miss, so the message is returned to the caller instead
5021 of dispatched. That is the same in-flight-during-unsubscribe race
5022 ``PubSub`` itself has, and closing it would mean duplicating
5023 ``handle_message``'s dispatch here.
5024 """
5025 # ``PubSub.get_message``'s prelude, which bypassing it would drop: a
5026 # per-node pubsub enters node_pubsub_mapping before its first
5027 # SSUBSCRIBE (_get_node_pubsub) and is left connectionless by reset()
5028 # (the GC in reinitialize_shard_subscriptions), while parse_response
5029 # raises RuntimeError on a None connection - which neither poll site
5030 # catches. Deliberately kept outside the I/O lock, unlike the
5031 # get_message call it replaces: waiting here is not wire I/O, and the
5032 # ssubscribe that sets this event needs the I/O lock itself, so waiting
5033 # under it stalls the very subscribe being waited for.
5034 if not pubsub.subscribed:
5035 start_time = time.monotonic()
5036 # An unbounded caller must not wait on this event uninterrupted.
5037 # _drop_node_pubsub retires a per-node pubsub whose event is cleared
5038 # and will never be set again - it is never resubscribed - and the
5039 # reader can be holding that object across the drop: the round robin
5040 # yields from a _pubsubs_generator snapshot the drop's pop does not
5041 # reach, and get_sharded_message's target_node lookup takes no lock.
5042 # So wake up periodically and re-check the mapping rather than park
5043 # the single reader for good, which would withhold the messages of
5044 # every healthy sibling in the pass too.
5045 if timeout is None:
5046 wait_for = SHARD_SUBSCRIBE_WAIT_TICK_SECONDS
5047 else:
5048 wait_for = timeout
5049 while not pubsub.subscribed_event.wait(wait_for):
5050 if timeout is not None:
5051 # The connection isn't subscribed to any channels or
5052 # patterns, so no messages are available
5053 return None
5054 if self._find_node_name_for_pubsub(pubsub) is None:
5055 # Retired by a concurrent drop while we held it. Nothing can
5056 # arrive on a subscription that is gone; let the pass move on
5057 # to the nodes that can still deliver.
5058 return None
5059 # The connection was subscribed during the timeout time frame.
5060 # The timeout should be adjusted based on the time spent
5061 # waiting for the subscription. Only the bounded case needs it: an
5062 # unbounded wait leaves ``timeout`` at None for the read below.
5063 if timeout is not None:
5064 timeout = max(0.0, timeout - (time.monotonic() - start_time))
5065 with self._poll_io_lock(pubsub, timeout):
5066 # Re-check now that no writer can be mid-flight: the prelude above
5067 # can pass and the GC then close this pubsub while holding this very
5068 # lock, which would leave parse_response with the None connection it
5069 # raises RuntimeError on. Only the connection is re-checked, not
5070 # ``subscribed``: a pubsub whose last channel was detached locally
5071 # may still have an in-flight SUNSUBSCRIBE confirmation to read.
5072 if pubsub.connection is None:
5073 return None
5074 response = pubsub.parse_response(block=(timeout is None), timeout=timeout)
5075 # get_message's truthiness test, not "is None": a health check
5076 # reply filtered out by parse_response, or an empty bulk, is "no
5077 # message" rather than a message to parse.
5078 if not response:
5079 return None
5080 if not self._is_publish_response(response):
5081 # Don't pass ignore_subscribe_messages here - let
5082 # get_sharded_message handle the filtering after processing
5083 # subscription state changes
5084 return pubsub.handle_message(response, ignore_subscribe_messages=False)
5085 message = pubsub.handle_message(response, ignore_subscribe_messages=False)
5086 # None here means a handler took it, which is not an empty poll.
5087 return _DISPATCHED if message is None else message
5089 @staticmethod
5090 def _is_publish_response(response) -> bool:
5091 """Whether a raw pubsub reply can make ``handle_message`` dispatch.
5093 ``handle_message`` invokes a user handler only for
5094 ``PUBLISH_MESSAGE_TYPES``; every other reply either does subscription
5095 bookkeeping (``UNSUBSCRIBE_MESSAGE_TYPES``) or is a pong, and the two
5096 branches are mutually exclusive. A non-sequence reply is the bare-PING
5097 shape ``handle_message`` rewrites into a pong, so it cannot dispatch
5098 either.
5099 """
5100 if not isinstance(response, (list, tuple)):
5101 return False
5102 return str_if_bytes(response[0]) in PubSub.PUBLISH_MESSAGE_TYPES
5104 def _schedule_topology_repair(self) -> None:
5105 """Ask for a slots-cache refresh after a poll could not reach a node.
5107 ``reinitialize_shard_subscriptions`` only ever runs from a slots-cache
5108 change notification, and a node that has been rebooted or taken out of
5109 the deployment answers ``ECONNREFUSED`` rather than ``MOVED`` - so the
5110 read path itself has to ask, or the shard channels pinned to that node
5111 stay there for the lifetime of the pubsub.
5113 The repair asks the nodes manager for a refresh and runs it on the
5114 reconciliation worker, once due, so a bounded poll does not pay for a
5115 ``CLUSTER SLOTS`` round trip; it is throttled because a node that is
5116 down fails every poll. The refresh drops nodes that have left the
5117 topology and dispatches ``AfterSlotsCacheRefreshEvent``, which reaches
5118 ``on_slots_changed``.
5120 ``disconnect_startup_nodes_pools=False``, unlike every other caller: a
5121 fresh slot map is all this repair asks for, so it also keeps the idle
5122 connections of a startup node pool that serves no node of the topology.
5123 Pools of the nodes that stay in the topology, which per-node pubsubs
5124 draw their connections from, are not recycled by a refresh either way.
5125 The async counterpart has no such parameter, so this is also the shape
5126 parity asks for.
5127 """
5128 if not self.shard_channels:
5129 return
5130 now = time.monotonic()
5131 if now < self._next_topology_repair:
5132 return
5133 # Unsynchronized on purpose: the read path must not queue behind a
5134 # reconciliation pass doing per-channel network I/O, because the
5135 # cluster-wide delivery stall that would cause is the very thing this
5136 # repair exists to end. Two readers racing the throttle window can both
5137 # submit, but their requests merge into one: the single-worker executor
5138 # runs them sequentially, the first run claims the request, and the
5139 # second finds nothing left to run (or a refresh that already completed
5140 # after its request) and returns without a CLUSTER SLOTS round trip.
5141 self._next_topology_repair = now + SHARD_TOPOLOGY_REPAIR_INTERVAL_SECONDS
5142 # The refresh is subject to the topology refresh minimum interval like
5143 # every other error-triggered one: if it is not due yet, the request
5144 # stays and the next command, or the next repair, runs it.
5145 nodes_manager = self.cluster.nodes_manager
5146 nodes_manager._request_refresh(disconnect_startup_nodes_pools=False)
5147 self._submit_reconcile_work(
5148 partial(nodes_manager._run_requested_refresh, self.cluster.retry)
5149 )
5151 def _handle_moved_on_read(self, pubsub, error: MovedError) -> None:
5152 """Re-route shard channels pinned to a node that lost their slot.
5154 ``PubSub.on_connect`` replays ``SSUBSCRIBE`` to the node its connection
5155 is bound to, so after a slot migration that node answers ``MOVED``.
5156 ``MovedError`` is not in ``Retry.supported_errors`` and no other code on
5157 the read path refreshes the slots cache, so a shard channel left on a
5158 former owner could never recover. Drop the offending channels from this
5159 pubsub so the replay stops, forget their recorded owner so
5160 ``reinitialize_shard_subscriptions`` does not short-circuit on an
5161 already-advanced reverse index, then apply the redirect and reconcile.
5162 """
5163 node_name = self._find_node_name_for_pubsub(pubsub)
5164 logger.debug(
5165 "sharded pubsub: %s no longer owns slot %s; re-routing its shard channels",
5166 node_name,
5167 error.slot_id,
5168 )
5169 with self._shard_state_lock:
5170 for channel in list(pubsub.shard_channels):
5171 if key_slot(self.encoder.encode(channel)) != error.slot_id:
5172 continue
5173 self._detach_shard_channel(pubsub, channel)
5174 if self._shard_channel_to_node.get(channel) == node_name:
5175 del self._shard_channel_to_node[channel]
5176 # The detach above can leave this pubsub with nothing subscribed -
5177 # a node that lost its only slot answers MOVED for every channel it
5178 # held. Retire it here rather than leave it in the mapping for a
5179 # collector elsewhere: no SUNSUBSCRIBE confirmation will arrive for
5180 # a channel forgotten locally, so get_sharded_message's collector
5181 # cannot reach it, and the reconciliation pass scheduled below only
5182 # GCs it once the worker gets to run - a whole poll cool-off later,
5183 # at best, while an unbounded poll that reaches the empty pubsub
5184 # first parks on it for good (see _drop_node_pubsub).
5185 if node_name is not None and not pubsub.subscribed:
5186 self._drop_node_pubsub(node_name, pubsub)
5187 # move_slot applies the redirect to the slots cache and dispatches
5188 # AfterSlotsCacheRefreshEvent, which reaches on_slots_changed. Call
5189 # on_slots_changed unconditionally too: move_slot skips the dispatch on
5190 # a circular MOVED, and a duplicate reconciliation pass is a no-op.
5191 # move_slot indexes slots_cache by the redirected slot, so an
5192 # as-yet-uncovered slot raises: log and still reconcile rather than let
5193 # a repair attempt break a pubsub read.
5194 if node_name is not None:
5195 # A redirect without a host is relative to the node that sent it,
5196 # and a node's name is its host and port
5197 _fill_missing_redirect_host(error, node_name.rsplit(":", 1)[0])
5198 try:
5199 self.cluster.nodes_manager.move_slot(error)
5200 except Exception as exc:
5201 logger.debug(
5202 "sharded pubsub: could not apply the redirect for slot %s: %s: %s",
5203 error.slot_id,
5204 type(exc).__name__,
5205 exc,
5206 )
5207 self.on_slots_changed()
5209 def _pubsubs_generator(self):
5210 # Never return: a generator that returns is exhausted for good and only
5211 # reset() recreates this one, so a momentarily empty
5212 # node_pubsub_mapping - reconciliation drops a per-node pubsub before
5213 # creating its replacement - would stop the round robin permanently.
5214 # Yield None for an empty mapping instead, which lets the caller skip
5215 # the slot without this loop spinning on an empty list.
5216 while True:
5217 current_nodes = list(self.node_pubsub_mapping.values())
5218 if not current_nodes:
5219 yield None
5220 else:
5221 yield from current_nodes
5223 def get_sharded_message(
5224 self, ignore_subscribe_messages=False, timeout=0.0, target_node=None
5225 ):
5226 """
5227 Get the next sharded pubsub message, or ``None`` if none is available.
5229 Polls the per-node connections in round robin unless ``target_node`` is
5230 given, and keeps shard channels attached to the node that currently
5231 owns their slot: a failed poll cools that node off and asks for a
5232 slots-cache refresh, and a ``MOVED`` reply re-routes the affected
5233 channels to their new owner. Neither reaches the caller. A connection
5234 failure is surfaced only when every node polled in the pass failed, so
5235 one unreachable node does not stop delivery from its healthy siblings.
5237 ``target_node`` opts out of that shielding: a caller that names a
5238 single node has no sibling to protect, so connection errors propagate.
5239 A ``MOVED`` reply is still handled rather than raised.
5241 :param ignore_subscribe_messages: Whether to ignore subscribe messages
5242 :param timeout: Timeout for message retrieval
5243 :param target_node: Specific node to get message from
5244 :return: Message dictionary or None
5245 """
5246 if target_node:
5247 # Use .get(): migration-driven cleanup in the sunsubscribe branch
5248 # below and reset() both remove entries from node_pubsub_mapping,
5249 # so a caller polling with target_node may race the cleanup. Match
5250 # the async counterpart's None-handling rather than raising
5251 # KeyError. None pubsub falls through to "no message available".
5252 pubsub = self.node_pubsub_mapping.get(target_node.name)
5253 if pubsub is not None:
5254 try:
5255 message = self._poll_node_pubsub(pubsub, timeout)
5256 if message is _DISPATCHED:
5257 message = None
5258 except MovedError as e:
5259 # Same handling as the round-robin path: the caller cannot
5260 # act on a MovedError raised out of a pubsub read, and the
5261 # channels this node no longer owns have to be re-routed or
5262 # they never recover. Cool off too, so a slots cache that
5263 # cannot be corrected does not re-run the repair on every
5264 # poll. Unlike that path, connectivity errors still
5265 # propagate: they are swallowed there only to keep one sick
5266 # node from starving its healthy siblings, and a caller that
5267 # named a single node has no sibling to protect.
5268 self._poll_cool_off[pubsub] = (
5269 time.monotonic() + SHARD_POLL_COOL_OFF_SECONDS
5270 )
5271 self._handle_moved_on_read(pubsub, e)
5272 message = None
5273 else:
5274 message = None
5275 else:
5276 pubsub, message = self._sharded_message_generator(timeout=timeout)
5277 if message is None:
5278 return None
5279 # Only sunsubscribe mutates cluster-level shard state; bypassing the
5280 # lock on the data-message hot path keeps smessage delivery from
5281 # competing with the reconciliation worker for _shard_state_lock.
5282 if str_if_bytes(message["type"]) == "sunsubscribe":
5283 # Serialize state mutation against reinitialize_shard_subscriptions
5284 # (worker thread). The blocking _poll_node_pubsub above
5285 # intentionally runs outside the lock so reconciliation is not
5286 # stalled by long polls.
5287 with self._shard_state_lock:
5288 if (
5289 message["channel"] in self.pending_unsubscribe_shard_channels
5290 and message["channel"] not in pubsub.shard_channels
5291 ):
5292 # User-initiated sunsubscribe: drop from cluster-level tracking.
5293 self.pending_unsubscribe_shard_channels.remove(message["channel"])
5294 self.shard_channels.pop(message["channel"], None)
5295 self._shard_channel_to_node.pop(message["channel"], None)
5296 # Drop the per-node pubsub that delivered the confirmation once
5297 # it no longer holds any shard subscriptions, regardless of
5298 # whether the sunsubscribe was user-initiated or driven by
5299 # slot-migration reconciliation (_migrate_shard_channel, which
5300 # intentionally does not add the channel to
5301 # pending_unsubscribe_shard_channels). This releases the
5302 # dedicated connection that would otherwise linger.
5303 # Identifying the receiving pubsub directly (rather than via
5304 # the cluster's current slot map) is required after slot
5305 # migration, where the channel's owner is no longer the node
5306 # that received our original SSUBSCRIBE.
5307 if pubsub is not None and not pubsub.subscribed:
5308 name = self._find_node_name_for_pubsub(pubsub)
5309 if name is not None:
5310 self._drop_node_pubsub(name, pubsub)
5311 # Mirror PubSub.handle_message: the empty-check belongs in the
5312 # unsubscribe branch since that is the only path that can
5313 # reduce shard_channels here.
5314 if not self.channels and not self.patterns and not self.shard_channels:
5315 self.subscribed_event.clear()
5316 # Only suppress subscribe/unsubscribe messages, not data messages (smessage)
5317 if str_if_bytes(message["type"]) in ("ssubscribe", "sunsubscribe"):
5318 if self.ignore_subscribe_messages or ignore_subscribe_messages:
5319 return None
5320 return message
5322 def ssubscribe(
5323 self, *args: ChannelT | Subscription, **kwargs: PubSubHandler
5324 ) -> None:
5325 """
5326 Subscribe to shard channels.
5328 Channels supplied as keyword arguments expect a channel name as the key
5329 and a callable as the value. ``Subscription`` objects can also be
5330 supplied positionally with an optional handler.
5331 """
5332 s_channels = parse_pubsub_subscriptions(args, kwargs)
5333 # Serialize against reinitialize_shard_subscriptions (worker thread)
5334 # so the reverse index, shard_channels, and node_pubsub_mapping are
5335 # not mutated concurrently.
5336 with self._shard_state_lock:
5337 for s_channel, handler in s_channels.items():
5338 node = self.cluster.get_node_from_key(s_channel)
5339 if not node:
5340 continue
5341 # Lazy re-route: if this channel is already tracked against a
5342 # different node (e.g. after a slot migration), migrate it now
5343 # so the caller's intent is applied on the current owner.
5344 normalized_key = next(iter(self._normalize_keys({s_channel: None})))
5345 old_name = self._shard_channel_to_node.get(normalized_key)
5346 if old_name and old_name != node.name:
5347 # Match PubSub.ssubscribe() dict.update() semantics: the
5348 # caller's newly supplied handler (including None) always
5349 # overrides any previously registered handler.
5350 self._migrate_shard_channel(
5351 normalized_key,
5352 handler,
5353 old_name,
5354 node,
5355 )
5356 continue
5357 pubsub = self._get_node_pubsub(node)
5358 with self._pubsub_io_lock(pubsub):
5359 if handler:
5360 pubsub.ssubscribe(Subscription(s_channel, handler))
5361 else:
5362 pubsub.ssubscribe(s_channel)
5363 self.shard_channels.update(pubsub.shard_channels)
5364 self._shard_channel_to_node[normalized_key] = node.name
5365 self.pending_unsubscribe_shard_channels.difference_update(
5366 self._normalize_keys({s_channel: None})
5367 )
5368 if pubsub.subscribed and not self.subscribed:
5369 self.subscribed_event.set()
5370 self.health_check_response_counter = 0
5372 def sunsubscribe(self, *args):
5373 if args:
5374 args = list_or_args(args[0], args[1:])
5375 else:
5376 args = list(self.shard_channels)
5378 # Serialize against reinitialize_shard_subscriptions: the reverse
5379 # index and node_pubsub_mapping must not change between the lookup
5380 # and the per-node sunsubscribe call below.
5381 with self._shard_state_lock:
5382 for s_channel in args:
5383 normalized_key = next(iter(self._normalize_keys({s_channel: None})))
5384 # Route via the reverse index so we unsubscribe on the node
5385 # that actually holds the subscription. After a slot migration
5386 # the cluster's current owner may no longer be that node.
5387 name = self._shard_channel_to_node.get(normalized_key)
5388 if name and name in self.node_pubsub_mapping:
5389 p = self.node_pubsub_mapping[name]
5390 else:
5391 node = self.cluster.get_node_from_key(s_channel)
5392 if not node or node.name not in self.node_pubsub_mapping:
5393 continue
5394 p = self.node_pubsub_mapping[node.name]
5395 with self._pubsub_io_lock(p):
5396 p.sunsubscribe(s_channel)
5397 self.pending_unsubscribe_shard_channels.update(
5398 p.pending_unsubscribe_shard_channels
5399 )
5401 def reinitialize_shard_subscriptions(self):
5402 """
5403 Reconcile per-node shard subscriptions against the cluster's current
5404 slot ownership map. For each tracked shard channel whose owning node
5405 has changed (e.g. after CLUSTER SETSLOT / failover), sunsubscribe on
5406 the old node's pubsub and ssubscribe on the new owner's pubsub,
5407 preserving any registered handler.
5408 """
5409 uncovered: list = []
5410 made_progress = False
5411 first_migrate_error: Optional[BaseException] = None
5412 with self._shard_state_lock:
5413 for channel, handler in list(self.shard_channels.items()):
5414 old_name = self._shard_channel_to_node.get(channel)
5415 if channel in self.pending_unsubscribe_shard_channels:
5416 # A reconnect clears the per-node pending set and replays
5417 # SSUBSCRIBE, so a channel the node still holds without a
5418 # pending unsubscribe is subscribed again, not leaving, and
5419 # its cluster-level entry is stale. Check the pending set
5420 # first: handle_message drops the channel before its
5421 # pending entry.
5422 old_pubsub = self.node_pubsub_mapping.get(old_name)
5423 if (
5424 old_pubsub is None
5425 or channel in old_pubsub.pending_unsubscribe_shard_channels
5426 or channel not in old_pubsub.shard_channels
5427 ):
5428 continue
5429 self.pending_unsubscribe_shard_channels.discard(channel)
5430 try:
5431 new_node = self.cluster.get_node_from_key(channel)
5432 except SlotNotCoveredError:
5433 # Slot is transiently uncovered (mid-migration / partial
5434 # topology refresh). Defer this channel so coverable
5435 # siblings still reconcile this pass; we surface the
5436 # error below so the caller (and logs) know not every
5437 # channel was reconciled. Retry happens on the next
5438 # slots-cache change notification.
5439 uncovered.append(channel)
5440 continue
5441 if old_name == new_node.name:
5442 owner = self.node_pubsub_mapping.get(new_node.name)
5443 if owner is not None and channel in owner.shard_channels:
5444 continue
5445 # The reverse index names this node but the subscription is
5446 # not there. _migrate_shard_channel detaches from the old
5447 # owner before it advances the index, so a pass that failed
5448 # to attach leaves the channel subscribed nowhere - and once
5449 # ownership moves back, this short-circuit would skip it for
5450 # the lifetime of the pubsub. Re-attach instead of trusting
5451 # the index; there is nothing to sunsubscribe from.
5452 old_name = None
5453 try:
5454 self._migrate_shard_channel(channel, handler, old_name, new_node)
5455 made_progress = True
5456 except (ConnectionError, TimeoutError, OSError) as e:
5457 # Transient connectivity error while subscribing on the
5458 # new owner (or unsubscribing on the old owner if its
5459 # handler chose to re-raise). Do not abort reconciliation
5460 # for sibling channels: _shard_channel_to_node was not
5461 # advanced for this channel, so the next slots-cache
5462 # change notification will retry it.
5463 logger.warning(
5464 "shard channel %r migration deferred: %s: %s",
5465 channel,
5466 type(e).__name__,
5467 e,
5468 )
5469 if first_migrate_error is None:
5470 first_migrate_error = e
5471 continue
5472 # Garbage-collect per-node pubsubs that no longer hold any
5473 # subscription so their connections are released.
5474 for name, pubsub in list(self.node_pubsub_mapping.items()):
5475 if not pubsub.subscribed:
5476 self._drop_node_pubsub(name, pubsub)
5477 if uncovered:
5478 # Surface the uncovered channels so the caller (and observer
5479 # notification path) knows reconciliation was incomplete. All
5480 # coverable siblings have already been migrated above.
5481 raise SlotNotCoveredError(
5482 f"{len(uncovered)} shard channel(s) left unreconciled; "
5483 f"slot(s) not covered by the cluster: {uncovered!r}"
5484 )
5485 if first_migrate_error is not None and not made_progress:
5486 # Every migration attempted in this pass failed transiently and
5487 # nothing else made progress. Re-raise the first caught error
5488 # (typically the root cause; later failures are often downstream
5489 # symptoms of the same unreachable node) so the worker's done-
5490 # callback surfaces a single representative failure through the
5491 # same logger channel used for SlotNotCoveredError. Per-channel
5492 # WARNINGs above preserve the full forensic detail.
5493 raise first_migrate_error
5495 def _forget_shard_channel_on_old_node(self, old_pubsub, channel, old_name):
5496 """Drop a migrating shard channel from a node we could not tell about it.
5498 Forget the channel locally: the caller advances the reverse index to the
5499 new owner, so reconciliation will never revisit this channel, while
5500 ``on_connect`` would keep replaying ``SSUBSCRIBE`` for it to this very
5501 node on every reconnect - the server would answer ``MOVED`` and the
5502 subscription would never work again.
5503 """
5504 self._detach_shard_channel(old_pubsub, channel)
5505 # Drop the per-node pubsub when either the old node has left the cluster
5506 # topology - no reconnect target, so the round-robin generator must stop
5507 # yielding a dead one, and any sibling subscription it still holds
5508 # recovers through ``PubSub._execute``'s reconnect and ``on_connect``
5509 # replay - or the detach above left it with nothing subscribed.
5510 #
5511 # The empty case cannot be deferred to a collector elsewhere, because
5512 # neither of the other two can reach it. ``get_sharded_message``'s
5513 # unsubscribe branch needs a ``SUNSUBSCRIBE`` confirmation, and none will
5514 # arrive for a channel this method forgot locally - that is the whole
5515 # reason it is forgotten. ``reinitialize_shard_subscriptions``'s
5516 # end-of-pass GC only runs for the reconciliation caller, while
5517 # ``ssubscribe``'s lazy re-route reaches here without it. An empty pubsub
5518 # left in the mapping has had its ``subscribed_event`` cleared by the
5519 # detach, so ``_poll_node_pubsub`` waits on an event nothing will ever
5520 # set: forever when the caller passed ``timeout=None``, and for the whole
5521 # timeout of every pass otherwise, before a single healthy node is read.
5522 if (
5523 self.cluster.get_node(node_name=old_name) is None
5524 or not old_pubsub.subscribed
5525 ):
5526 self._drop_node_pubsub(old_name, old_pubsub)
5528 def _migrate_shard_channel(self, channel, handler, old_name, new_node):
5529 # Detach from the old per-node pubsub, best-effort: the old node may
5530 # already be unreachable during migration / failover.
5531 if old_name and old_name in self.node_pubsub_mapping:
5532 old_pubsub = self.node_pubsub_mapping[old_name]
5533 if old_name in self._unreachable_nodes:
5534 # The reader has just failed to reach this node, so a
5535 # ``SUNSUBSCRIBE`` cannot arrive. Skip it: the attempt would pay
5536 # a full reconnect (and the client's whole retry budget) behind
5537 # the reader on the same per-node io lock, all while this pass
5538 # holds ``_shard_state_lock`` - which is what turns one departed
5539 # node into a migration slow enough to look like a permanent
5540 # delivery stall.
5541 self._forget_shard_channel_on_old_node(old_pubsub, channel, old_name)
5542 else:
5543 try:
5544 with self._pubsub_io_lock(old_pubsub):
5545 old_pubsub.sunsubscribe(channel)
5546 except (ConnectionError, TimeoutError, OSError):
5547 # redis-py's Connection has already called ``disconnect()``
5548 # before raising (see Connection.read_response /
5549 # send_packed_command with ``disconnect_on_error=True``), so
5550 # ``old_pubsub``'s dedicated socket is gone and the
5551 # ``SUNSUBSCRIBE`` never reached the server.
5552 self._forget_shard_channel_on_old_node(
5553 old_pubsub, channel, old_name
5554 )
5555 # Attach to the new per-node pubsub, preserving the handler. Decode to
5556 # a text key only when we must pass it as a kwarg (handler present).
5557 new_pubsub = self._get_node_pubsub(new_node)
5558 with self._pubsub_io_lock(new_pubsub):
5559 if handler:
5560 new_pubsub.ssubscribe(Subscription(channel, handler))
5561 else:
5562 new_pubsub.ssubscribe(channel)
5563 self.shard_channels.update(new_pubsub.shard_channels)
5564 normalized_key = next(iter(self._normalize_keys({channel: None})))
5565 self._shard_channel_to_node[normalized_key] = new_node.name
5566 self.pending_unsubscribe_shard_channels.difference_update(
5567 self._normalize_keys({channel: None})
5568 )
5569 if new_pubsub.subscribed and not self.subscribed:
5570 self.subscribed_event.set()
5571 self.health_check_response_counter = 0
5573 def on_slots_changed(self):
5574 # Observer hook invoked by NodesManager after a slots-cache refresh.
5575 # Schedule reconciliation on a dedicated worker thread so the caller
5576 # (typically MovedError handling in _execute_command or the topology
5577 # refresh thread in initialize()) is not blocked on the network I/O
5578 # performed by reinitialize_shard_subscriptions. Mirrors the async
5579 # path's asyncio.create_task model. No-op when there are no shard
5580 # subscriptions to reconcile.
5581 if not self.shard_channels:
5582 return
5583 # Takes no lock. This hook runs inline on whichever thread refreshed the
5584 # topology - including a command or pubsub thread that handled an
5585 # SMIGRATED push and still holds OSSMaintNotificationsHandler._lock.
5586 # Waiting here for a reconciliation pass that is itself waiting for a
5587 # per-node pubsub I/O lock held by a third thread blocked on that
5588 # handler lock is a deadlock cycle. The async counterpart takes no lock
5589 # here either (the event loop serializes it), so this is also the
5590 # shape sync/async parity asks for.
5591 self._submit_reconcile_work(self.reinitialize_shard_subscriptions)
5593 def _submit_reconcile_work(self, work: Callable[[], Any]) -> Optional["Future"]:
5594 """Run ``work`` on the reconciliation worker, without taking a lock.
5596 The executor is installed by ``reset()`` and never None afterwards, so
5597 there is nothing to create here and no creation race to serialize - see
5598 the ``_reconcile_executor`` comment in ``__init__`` for why the callers
5599 must not block. Only ``reset()`` swaps it, and a submit that loses that
5600 race raises ``RuntimeError``: read the attribute once so the swap cannot
5601 be observed half-done, and treat the rejection as "nothing to do", which
5602 it is - ``reset()`` has already dropped the shard channels this pass
5603 would have reconciled.
5604 """
5605 executor = self._reconcile_executor
5606 if executor is None:
5607 # Defensive: reset() runs from PubSub.__init__, so by the time any
5608 # caller can get here an executor is installed.
5609 return None
5610 try:
5611 future = executor.submit(work)
5612 except RuntimeError:
5613 return None
5614 # Consume the future's exception (if any) so it is not silently lost.
5615 # reinitialize_shard_subscriptions surfaces SlotNotCoveredError when a
5616 # slot is still transiently uncovered; route it through the same logger
5617 # channel as the async path for consistent observability.
5618 future.add_done_callback(self._log_reconcile_future_exception)
5619 return future
5621 @staticmethod
5622 def _log_reconcile_future_exception(future: "Future") -> None:
5623 if future.cancelled():
5624 return
5625 exc = future.exception()
5626 if exc is not None:
5627 logger.error(
5628 "shard subscription reconciliation failed: %r", exc, exc_info=exc
5629 )
5631 def reset(self) -> None:
5632 # Hold _shard_state_lock across the entire teardown so it observes
5633 # the same mutual-exclusion discipline as ssubscribe / sunsubscribe /
5634 # get_sharded_message / reinitialize_shard_subscriptions, which all
5635 # mutate shard_channels, _shard_channel_to_node, and
5636 # node_pubsub_mapping under this lock. Without it, super().reset()
5637 # rebinds shard_channels and pending_unsubscribe_shard_channels in
5638 # parallel with a concurrent user-thread mutation, silently dropping
5639 # subscription intent. The reconciliation executor is swapped out at the
5640 # end of that critical section; see the comment there for why it goes
5641 # last.
5642 with self._shard_state_lock:
5643 # Tear down per-node pubsubs (parity with async aclose) so they
5644 # don't leak their dedicated connections and don't replay stale
5645 # shard_channels via PubSub.on_connect on a subsequent reconnect.
5646 # Errors are swallowed because reset() is also a fallback path
5647 # from __del__; we cannot let one buggy per-node pubsub mask the
5648 # rest of the teardown.
5649 # The per-node I/O lock keeps the socket from being torn down
5650 # beneath a concurrent bounded poll parked in parse_response. It is
5651 # an RLock, so re-entry from this thread is fine; contention is with
5652 # another thread's bounded poll and is bounded by that poll's
5653 # timeout (an unbounded poll holds nullcontext() - see
5654 # _poll_io_lock). reset() is also the __del__ fallback path, where
5655 # the try below does not cover a blocking acquire - that boundedness
5656 # is what makes taking the lock here safe.
5657 for pubsub in self.node_pubsub_mapping.values():
5658 try:
5659 with self._pubsub_io_lock(pubsub):
5660 pubsub.reset()
5661 except Exception:
5662 pass
5663 # Drop the now-dead per-node pubsubs from the mapping so the
5664 # round-robin in _pubsubs_generator / _sharded_message_generator
5665 # cannot yield them between teardown and re-subscription.
5666 self.node_pubsub_mapping.clear()
5667 self._unreachable_nodes.clear()
5668 # Drop the throttle window too: a reused pubsub that keeps a
5669 # deadline armed before the teardown would skip the first repair
5670 # after resubscribing, delaying the move of its shard channels
5671 # off a node that is already gone.
5672 self._next_topology_repair = 0.0
5673 # _pubsubs_generator captures node_pubsub_mapping.values() into
5674 # a local list inside ``yield from``; clearing the mapping does
5675 # not reach references already held by that captured snapshot,
5676 # so a generator suspended mid-yield-from would still surface
5677 # the now-reset() per-node pubsubs after re-subscription.
5678 # Recreate it to drop the captured list. type(self) bypasses
5679 # the instance-level self-shadow established at __init__
5680 # (self._pubsubs_generator = self._pubsubs_generator()).
5681 self._pubsubs_generator = type(self)._pubsubs_generator(self)
5682 super().reset()
5683 self._shard_channel_to_node = {}
5684 # Swap in a fresh reconciliation executor and retire the old one.
5685 # Installing the replacement is what lets the scheduling sites stay
5686 # lock-free (see __init__); it costs nothing until something is
5687 # submitted, because a ThreadPoolExecutor spawns its worker on the
5688 # first submit(). Done last, after super().reset() has emptied
5689 # shard_channels, so a concurrent on_slots_changed either loses the
5690 # swap and is rejected or finds nothing left to reconcile.
5691 # cancel_futures drops queued reconciliation work; a pass already
5692 # running is serialized against us by _shard_state_lock, and
5693 # shutdown(wait=False) avoids waiting on the worker thread's join.
5694 retired = self._reconcile_executor
5695 self._reconcile_executor = ThreadPoolExecutor(
5696 max_workers=1,
5697 thread_name_prefix="redis-cluster-pubsub-reconcile",
5698 )
5699 if retired is not None:
5700 retired.shutdown(wait=False, cancel_futures=True)
5702 def get_redis_connection(self):
5703 """
5704 Get the Redis connection of the pubsub connected node.
5705 """
5706 if self.node is not None:
5707 return self.node.redis_connection
5709 def disconnect(self):
5710 """
5711 Disconnect the pubsub connection.
5712 """
5713 if self.connection:
5714 self.connection.disconnect()
5715 for pubsub in self.node_pubsub_mapping.values():
5716 if pubsub.connection:
5717 pubsub.connection.disconnect()
5720class ClusterPipeline(RedisCluster):
5721 """
5722 Support for Redis pipeline
5723 in cluster mode
5724 """
5726 ERRORS_ALLOW_RETRY = (
5727 ConnectionError,
5728 TimeoutError,
5729 MovedError,
5730 AskError,
5731 TryAgainError,
5732 )
5734 NO_SLOTS_COMMANDS = {"UNWATCH"}
5735 IMMEDIATE_EXECUTE_COMMANDS = {"WATCH", "UNWATCH"}
5736 UNWATCH_COMMANDS = {"DISCARD", "EXEC", "UNWATCH"}
5738 @deprecated_args(
5739 args_to_warn=[
5740 "cluster_error_retry_attempts",
5741 ],
5742 reason="Please configure the 'retry' object instead",
5743 version="6.0.0",
5744 )
5745 def __init__(
5746 self,
5747 nodes_manager: "NodesManager",
5748 commands_parser: "CommandsParser",
5749 result_callbacks: Optional[Dict[str, Callable]] = None,
5750 cluster_response_callbacks: Optional[Dict[str, Callable]] = None,
5751 startup_nodes: Optional[List["ClusterNode"]] = None,
5752 read_from_replicas: bool = False,
5753 load_balancing_strategy: Optional[LoadBalancingStrategy] = None,
5754 cluster_error_retry_attempts: int = DEFAULT_RETRY_COUNT,
5755 reinitialize_steps: int = 5,
5756 retry: Optional[Retry] = None,
5757 lock=None,
5758 transaction=False,
5759 policy_resolver: Optional[PolicyResolver] = None,
5760 event_dispatcher: Optional["EventDispatcher"] = None,
5761 metadata_resolver: Optional[MetadataResolver] = None,
5762 **kwargs,
5763 ):
5764 """ """
5765 self.command_stack = []
5766 self.nodes_manager = nodes_manager
5767 # Share the parent cluster's HIMPORT registry (held on the NodesManager and
5768 # referenced by every node pool). The inherited himport_prepare/discard/
5769 # discard_all mutate this one object, so a fieldset declared on the pipeline is
5770 # visible to the batched himport_set pre-flight exactly as on the parent client.
5771 self._himport_registry = nodes_manager.himport_registry
5772 self.commands_parser = commands_parser
5773 self.refresh_table_asap = False
5774 self.result_callbacks = (
5775 result_callbacks or self.__class__.RESULT_CALLBACKS.copy()
5776 )
5777 self.startup_nodes = startup_nodes if startup_nodes else []
5778 self.read_from_replicas = read_from_replicas
5779 self.load_balancing_strategy = load_balancing_strategy
5780 self.command_flags = self.__class__.COMMAND_FLAGS.copy()
5781 self.node_flags = self.__class__.NODE_FLAGS.copy()
5782 self.cluster_response_callbacks = cluster_response_callbacks
5783 self.reinitialize_counter = 0
5784 self.reinitialize_steps = reinitialize_steps
5785 if retry is not None:
5786 self.retry = retry
5787 else:
5788 self.retry = Retry(
5789 backoff=ExponentialWithJitterBackoff(
5790 base=DEFAULT_RETRY_BASE, cap=DEFAULT_RETRY_CAP
5791 ),
5792 retries=cluster_error_retry_attempts,
5793 )
5795 self.encoder = Encoder(
5796 kwargs.get("encoding", "utf-8"),
5797 kwargs.get("encoding_errors", "strict"),
5798 kwargs.get("decode_responses", False),
5799 )
5800 if lock is None:
5801 lock = threading.RLock()
5802 self._lock = lock
5803 self.parent_execute_command = super().execute_command
5804 self._execution_strategy: ExecutionStrategy = (
5805 PipelineStrategy(self) if not transaction else TransactionStrategy(self)
5806 )
5808 # For backward compatibility, mapping from existing policies to new one
5809 self._command_flags_mapping: dict[str, Union[RequestPolicy, ResponsePolicy]] = {
5810 self.__class__.RANDOM: RequestPolicy.DEFAULT_KEYLESS,
5811 self.__class__.PRIMARIES: RequestPolicy.ALL_SHARDS,
5812 self.__class__.ALL_NODES: RequestPolicy.ALL_NODES,
5813 self.__class__.REPLICAS: RequestPolicy.ALL_REPLICAS,
5814 self.__class__.DEFAULT_NODE: RequestPolicy.DEFAULT_NODE,
5815 SLOT_ID: RequestPolicy.DEFAULT_KEYED,
5816 }
5818 # ``RedisCluster.pipeline`` passes the client's own resolvers, so a pipeline routes by
5819 # whatever the client routes by. Only a pipeline built directly, without either, falls
5820 # back to the static default. Precedence between the two mirrors ``RedisCluster`` -
5821 # see the note there.
5822 if metadata_resolver is None:
5823 self._metadata_resolver: MetadataResolver = StaticMetadataResolver()
5824 else:
5825 self._metadata_resolver = metadata_resolver
5827 if policy_resolver is None:
5828 self._policy_resolver: PolicyResolver = StaticPolicyResolver(
5829 metadata_resolver=self._metadata_resolver
5830 )
5831 else:
5832 self._policy_resolver = policy_resolver
5834 if event_dispatcher is None:
5835 self._event_dispatcher = EventDispatcher()
5836 else:
5837 self._event_dispatcher = event_dispatcher
5839 def __repr__(self):
5840 """ """
5841 return f"{type(self).__name__}"
5843 def __enter__(self):
5844 """ """
5845 return self
5847 def __exit__(self, exc_type, exc_value, traceback):
5848 """ """
5849 self.reset()
5851 def __del__(self):
5852 try:
5853 self.reset()
5854 except Exception:
5855 pass
5857 def __len__(self):
5858 """ """
5859 return len(self._execution_strategy.command_queue)
5861 def __bool__(self):
5862 "Pipeline instances should always evaluate to True on Python 3+"
5863 return True
5865 def execute_command(self, *args, **kwargs):
5866 """
5867 Wrapper function for pipeline_execute_command
5868 """
5869 return self._execution_strategy.execute_command(*args, **kwargs)
5871 def pipeline_execute_command(self, *args, **options):
5872 """
5873 Stage a command to be executed when execute() is next called
5875 Returns the current Pipeline object back so commands can be
5876 chained together, such as:
5878 pipe = pipe.set('foo', 'bar').incr('baz').decr('bang')
5880 At some other point, you can then run: pipe.execute(),
5881 which will execute all commands queued in the pipe.
5882 """
5883 return self._execution_strategy.execute_command(*args, **options)
5885 def annotate_exception(self, exception, number, command):
5886 """
5887 Provides extra context to the exception prior to it being handled
5888 """
5889 self._execution_strategy.annotate_exception(exception, number, command)
5891 def execute(self, raise_on_error: bool = True) -> List[Any]:
5892 """
5893 Execute all the commands in the current pipeline
5894 """
5896 try:
5897 return self._execution_strategy.execute(raise_on_error)
5898 finally:
5899 self.reset()
5901 def reset(self):
5902 """
5903 Reset back to empty pipeline.
5904 """
5905 self._execution_strategy.reset()
5907 def send_cluster_commands(
5908 self, stack, raise_on_error=True, allow_redirections=True
5909 ):
5910 return self._execution_strategy.send_cluster_commands(
5911 stack, raise_on_error=raise_on_error, allow_redirections=allow_redirections
5912 )
5914 def exists(self, *keys):
5915 return self._execution_strategy.exists(*keys)
5917 def touch(self, *keys):
5918 return self._execution_strategy.touch(*keys)
5920 def eval(self):
5921 """ """
5922 return self._execution_strategy.eval()
5924 def multi(self):
5925 """
5926 Start a transactional block of the pipeline after WATCH commands
5927 are issued. End the transactional block with `execute`.
5928 """
5929 self._execution_strategy.multi()
5931 def load_scripts(self):
5932 """ """
5933 self._execution_strategy.load_scripts()
5935 def discard(self):
5936 """Discards the transactional block."""
5937 self._execution_strategy.discard()
5939 def watch(self, *names):
5940 """Watches the values at keys ``names``"""
5941 self._execution_strategy.watch(*names)
5943 def unwatch(self):
5944 """Unwatches all previously specified keys"""
5945 self._execution_strategy.unwatch()
5947 def script_load_for_pipeline(self, *args, **kwargs):
5948 self._execution_strategy.script_load_for_pipeline(*args, **kwargs)
5950 def delete(self, *names):
5951 self._execution_strategy.delete(*names)
5953 def unlink(self, *names):
5954 """
5955 Stages an `UNLINK` for keys ``names``. Like `delete`, it returns ``None``
5956 rather than the pipeline, so it does not chain.
5958 Outside a transactional block only one key is accepted, as with `delete`; more
5959 raises :class:`~.RedisClusterException`. Between :meth:`watch` and
5960 :meth:`multi` it is not staged: it is sent at once, outside the eventual
5961 transaction, and the response is discarded.
5962 """
5963 self._execution_strategy.unlink(*names)
5966def block_pipeline_command(name: str) -> Callable[..., Any]:
5967 """
5968 Prints error because some pipelined commands should
5969 be blocked when running in cluster-mode
5970 """
5972 def inner(*args, **kwargs):
5973 raise RedisClusterException(
5974 f"ERROR: Calling pipelined function {name} is blocked "
5975 f"when running redis in cluster mode..."
5976 )
5978 return inner
5981# The script runners whose keys follow a ``numkeys`` count right after the script, so they are
5982# found without asking the server for them.
5983_EVAL_COMMANDS = ("EVAL", "EVALSHA", "EVAL_RO", "EVALSHA_RO")
5986def is_zero_key_eval_command(*args) -> bool:
5987 """
5988 True for EVAL/EVALSHA, or their read-only variants, with numkeys=0 (any primary).
5989 """
5990 if len(args) < 3:
5991 return False
5992 if str(args[0]).upper() not in _EVAL_COMMANDS:
5993 return False
5994 try:
5995 return int(args[2]) == 0
5996 except (TypeError, ValueError):
5997 return False
6000# Blocked pipeline commands
6001PIPELINE_BLOCKED_COMMANDS = (
6002 "BGREWRITEAOF",
6003 "BGSAVE",
6004 "BITOP",
6005 "BLESS SCAN",
6006 "BRPOPLPUSH",
6007 "CLIENT GETNAME",
6008 "CLIENT KILL",
6009 "CLIENT LIST",
6010 "CLIENT SETNAME",
6011 "CLIENT",
6012 "CONFIG GET",
6013 "CONFIG RESETSTAT",
6014 "CONFIG REWRITE",
6015 "CONFIG SET",
6016 "CONFIG",
6017 "DBSIZE",
6018 "ECHO",
6019 "FLUSHALL",
6020 "FLUSHDB",
6021 "INFO",
6022 "KEYS",
6023 "LASTSAVE",
6024 "MGET",
6025 "MGET NONATOMIC",
6026 "MOVE",
6027 "MSET",
6028 "MSETEX",
6029 "MSET NONATOMIC",
6030 "MSETNX",
6031 "PFCOUNT",
6032 "PFMERGE",
6033 "PING",
6034 "PUBLISH",
6035 "RANDOMKEY",
6036 "READONLY",
6037 "READWRITE",
6038 "RENAME",
6039 "RENAMENX",
6040 "RPOPLPUSH",
6041 "SAVE",
6042 "SCAN",
6043 "SCRIPT EXISTS",
6044 "SCRIPT FLUSH",
6045 "SCRIPT KILL",
6046 "SCRIPT LOAD",
6047 "SCRIPT",
6048 "SDIFF",
6049 "SDIFFSTORE",
6050 "SENTINEL GET MASTER ADDR BY NAME",
6051 "SENTINEL MASTER",
6052 "SENTINEL MASTERS",
6053 "SENTINEL MONITOR",
6054 "SENTINEL REMOVE",
6055 "SENTINEL SENTINELS",
6056 "SENTINEL SET",
6057 "SENTINEL SLAVES",
6058 "SENTINEL",
6059 "SHUTDOWN",
6060 "SINTER",
6061 "SINTERSTORE",
6062 "SLAVEOF",
6063 "SLOWLOG GET",
6064 "SLOWLOG LEN",
6065 "SLOWLOG RESET",
6066 "SLOWLOG",
6067 "SMOVE",
6068 "SORT",
6069 "SUNION",
6070 "SUNIONSTORE",
6071 "TIME",
6072)
6073for command in PIPELINE_BLOCKED_COMMANDS:
6074 command = command.replace(" ", "_").lower()
6076 setattr(ClusterPipeline, command, block_pipeline_command(command))
6078# client_list_iter has no wire command of its own to add to
6079# PIPELINE_BLOCKED_COMMANDS - it sends CLIENT LIST, blocked above under its
6080# own name - so block it explicitly here too, or it would fall through to
6081# the inherited implementation and queue CLIENT LIST like a real pipelined
6082# command instead of raising.
6083setattr(ClusterPipeline, "client_list_iter", block_pipeline_command("client_list_iter"))
6086# The result of a pipeline command no node has answered yet. A reply can be None, so None
6087# cannot tell an unanswered command from one a node answered.
6088_UNANSWERED = object()
6091class PipelineCommand:
6092 """ """
6094 def __init__(self, args, options=None, position=None):
6095 self.args = args
6096 if options is None:
6097 options = {}
6098 self.options = options
6099 self.position = position
6100 self.result = _UNANSWERED
6101 self.node = None
6102 self.asking = False
6103 # Either record type: a policy resolver serves ``CommandPolicies``, while the
6104 # fallbacks below reuse the shared ``CommandMetadata`` defaults. Only the two routing
6105 # policies, which both carry, are ever read.
6106 self.command_policies: Optional[Union[CommandPolicies, CommandMetadata]] = None
6107 # The replies the command already got, kept across the attempts so a retry sends
6108 # it only where it has not been answered - keyed by slot for a split MULTI_SHARD
6109 # command, by node name for a command sent to several nodes
6110 self.replies: Optional[Dict[Any, Any]] = None
6111 # The ``target_nodes`` a retry must route by again - see
6112 # ``PipelineStrategy._send_cluster_commands``
6113 self.target_nodes: Any = None
6116class NodeCommands:
6117 """ """
6119 def __init__(
6120 self, parse_response, connection_pool: ConnectionPool, connection: Connection
6121 ):
6122 """ """
6123 self.parse_response = parse_response
6124 self.connection_pool = connection_pool
6125 self.connection = connection
6126 self.commands = []
6128 def append(self, c):
6129 """ """
6130 self.commands.append(c)
6132 def write(self):
6133 """
6134 Code borrowed from Redis so it can be fixed
6135 """
6136 connection = self.connection
6137 commands = self.commands
6139 # We are going to clobber the commands with the write, so go ahead
6140 # and ensure that nothing is sitting there from a previous run.
6141 for c in commands:
6142 c.result = _UNANSWERED
6144 # build up all commands into a single request to increase network perf
6145 # send all the commands and catch connection and timeout errors.
6146 try:
6147 connection.send_packed_command(
6148 connection.pack_commands([c.args for c in commands])
6149 )
6150 except (ConnectionError, TimeoutError) as e:
6151 for c in commands:
6152 c.result = e
6154 def read(self):
6155 """ """
6156 connection = self.connection
6157 for c in self.commands:
6158 # if there is a result on this command,
6159 # it means we ran into an exception
6160 # like a connection error. Trying to parse
6161 # a response on a connection that
6162 # is no longer open will result in a
6163 # connection error raised by redis-py.
6164 # but redis-py doesn't check in parse_response
6165 # that the sock object is
6166 # still set and if you try to
6167 # read from a closed connection, it will
6168 # result in an AttributeError because
6169 # it will do a readline() call on None.
6170 # This can have all kinds of nasty side-effects.
6171 # Treating this case as a connection error
6172 # is fine because it will dump
6173 # the connection object back into the
6174 # pool and on the next write, it will
6175 # explicitly open the connection and all will be well.
6176 if c.result is _UNANSWERED:
6177 try:
6178 c.result = self.parse_response(connection, c.args[0], **c.options)
6179 except (ConnectionError, TimeoutError) as e:
6180 for c in self.commands:
6181 c.result = e
6182 return
6183 except RedisError:
6184 c.result = sys.exc_info()[1]
6187class ExecutionStrategy(ABC):
6188 @property
6189 @abstractmethod
6190 def command_queue(self):
6191 pass
6193 @abstractmethod
6194 def execute_command(self, *args, **kwargs):
6195 """
6196 Execution flow for current execution strategy.
6198 See: ClusterPipeline.execute_command()
6199 """
6200 pass
6202 @abstractmethod
6203 def annotate_exception(self, exception, number, command):
6204 """
6205 Annotate exception according to current execution strategy.
6207 See: ClusterPipeline.annotate_exception()
6208 """
6209 pass
6211 @abstractmethod
6212 def pipeline_execute_command(self, *args, **options):
6213 """
6214 Pipeline execution flow for current execution strategy.
6216 See: ClusterPipeline.pipeline_execute_command()
6217 """
6218 pass
6220 @abstractmethod
6221 def execute(self, raise_on_error: bool = True) -> List[Any]:
6222 """
6223 Executes current execution strategy.
6225 See: ClusterPipeline.execute()
6226 """
6227 pass
6229 @abstractmethod
6230 def send_cluster_commands(
6231 self, stack, raise_on_error=True, allow_redirections=True
6232 ):
6233 """
6234 Sends commands according to current execution strategy.
6236 See: ClusterPipeline.send_cluster_commands()
6237 """
6238 pass
6240 @abstractmethod
6241 def reset(self):
6242 """
6243 Resets current execution strategy.
6245 See: ClusterPipeline.reset()
6246 """
6247 pass
6249 @abstractmethod
6250 def exists(self, *keys):
6251 pass
6253 def touch(self, *keys):
6254 return self.execute_command("TOUCH", *keys)
6256 @abstractmethod
6257 def eval(self):
6258 pass
6260 @abstractmethod
6261 def multi(self):
6262 """
6263 Starts transactional context.
6265 See: ClusterPipeline.multi()
6266 """
6267 pass
6269 @abstractmethod
6270 def load_scripts(self):
6271 pass
6273 @abstractmethod
6274 def watch(self, *names):
6275 pass
6277 @abstractmethod
6278 def unwatch(self):
6279 """
6280 Unwatches all previously specified keys
6282 See: ClusterPipeline.unwatch()
6283 """
6284 pass
6286 @abstractmethod
6287 def script_load_for_pipeline(self, *args, **kwargs):
6288 pass
6290 @abstractmethod
6291 def delete(self, *names):
6292 """
6293 "Delete a key specified by ``names``"
6295 See: ClusterPipeline.delete()
6296 """
6297 pass
6299 @abstractmethod
6300 def unlink(self, *names):
6301 """
6302 "Unlink a key specified by ``names``"
6304 See: ClusterPipeline.unlink()
6305 """
6306 pass
6308 @abstractmethod
6309 def discard(self):
6310 pass
6313class AbstractStrategy(ExecutionStrategy):
6314 def __init__(
6315 self,
6316 pipe: ClusterPipeline,
6317 ):
6318 self._command_queue: List[PipelineCommand] = []
6319 self._pipe = pipe
6320 self._nodes_manager = self._pipe.nodes_manager
6322 @property
6323 def command_queue(self):
6324 return self._command_queue
6326 @command_queue.setter
6327 def command_queue(self, queue: List[PipelineCommand]):
6328 self._command_queue = queue
6330 @abstractmethod
6331 def execute_command(self, *args, **kwargs):
6332 pass
6334 def pipeline_execute_command(self, *args, **options):
6335 self._command_queue.append(
6336 PipelineCommand(args, options, len(self._command_queue))
6337 )
6338 return self._pipe
6340 def _himport_prepare_pipeline(self, redis_node, conn, commands):
6341 """Delegate to the shared sync HIMPORT executor."""
6342 _himport_exec.prepare_pipeline(redis_node, conn, [args for args, _ in commands])
6344 @abstractmethod
6345 def execute(self, raise_on_error: bool = True) -> List[Any]:
6346 pass
6348 @abstractmethod
6349 def send_cluster_commands(
6350 self, stack, raise_on_error=True, allow_redirections=True
6351 ):
6352 pass
6354 @abstractmethod
6355 def reset(self):
6356 pass
6358 def exists(self, *keys):
6359 return self.execute_command("EXISTS", *keys)
6361 def eval(self):
6362 """ """
6363 raise RedisClusterException("method eval() is not implemented")
6365 def load_scripts(self):
6366 """ """
6367 raise RedisClusterException("method load_scripts() is not implemented")
6369 def script_load_for_pipeline(self, *args, **kwargs):
6370 """ """
6371 raise RedisClusterException(
6372 "method script_load_for_pipeline() is not implemented"
6373 )
6375 def annotate_exception(self, exception, number, command):
6376 """
6377 Provides extra context to the exception prior to it being handled
6378 """
6379 cmd = command_text(command)
6380 msg = (
6381 f"Command # {number} ({truncate_text(cmd)}) of pipeline "
6382 f"caused error: {exception.args[0]}"
6383 )
6384 exception.args = (msg,) + exception.args[1:]
6387class PipelineStrategy(AbstractStrategy):
6388 def __init__(self, pipe: ClusterPipeline):
6389 super().__init__(pipe)
6390 self.command_flags = pipe.command_flags
6392 def execute_command(self, *args, **kwargs):
6393 return self.pipeline_execute_command(*args, **kwargs)
6395 def _raise_first_error(self, stack, start_time):
6396 """
6397 Raise the first exception on the stack
6398 """
6399 for c in stack:
6400 r = c.result
6401 if isinstance(r, Exception):
6402 self.annotate_exception(r, c.position + 1, c.args)
6404 record_operation_duration(
6405 command_name="PIPELINE",
6406 duration_seconds=time.monotonic() - start_time,
6407 error=r,
6408 )
6410 raise r
6412 def execute(self, raise_on_error: bool = True) -> List[Any]:
6413 stack = self._command_queue
6414 if not stack:
6415 return []
6417 try:
6418 return self.send_cluster_commands(stack, raise_on_error)
6419 finally:
6420 self.reset()
6422 def reset(self):
6423 """
6424 Reset back to empty pipeline.
6425 """
6426 self._command_queue = []
6428 def send_cluster_commands(
6429 self, stack, raise_on_error=True, allow_redirections=True
6430 ):
6431 """
6432 Send the commands, retrying on RedisCluster.ERRORS_ALLOW_RETRY, and on
6433 a READONLY reply of a node cached as a primary, as many
6434 times as ``retry`` allows, with the backoff delay before each attempt
6435 and a fixed 0.25 seconds first after CLUSTERDOWN or an uncovered slot.
6436 Every retried error asks for a topology refresh, which the next attempt
6437 runs once due. NOT_NODE_FAILURE_ERRORS are raised at once. Out of
6438 retries, the last error is raised, as RedisClusterUnreachableError when
6439 the last refresh reached no node; a refresh that reached no node since
6440 an attempt failed ends the retries the same way.
6441 """
6442 if not stack:
6443 return []
6444 retry_attempts = self._pipe.retry.get_retries()
6445 failure_count = 0
6446 # The error the previous attempt failed with, and when the last refresh
6447 # had ended by then: a refresh since that reached no node ends the
6448 # retries (see NodesManager._error_instead_of_retry)
6449 last_error: Optional[Exception] = None
6450 last_refresh_at: Optional[float] = None
6451 while True:
6452 # Run a topology refresh an earlier error asked for, once due
6453 if self._nodes_manager._refresh_requested:
6454 self._nodes_manager._run_requested_refresh(self._pipe.retry)
6455 if last_error is not None:
6456 outage_error = self._nodes_manager._error_instead_of_retry(
6457 last_error, last_refresh_at
6458 )
6459 if outage_error is not None:
6460 raise outage_error
6461 try:
6462 return self._send_cluster_commands(
6463 stack,
6464 raise_on_error=raise_on_error,
6465 allow_redirections=allow_redirections,
6466 )
6467 except RedisCluster.NOT_NODE_FAILURE_ERRORS:
6468 raise
6469 except (*RedisCluster.ERRORS_ALLOW_RETRY, ReadOnlyError) as e:
6470 if isinstance(e, ReadOnlyError) and not getattr(
6471 e, "demoted_primary", False
6472 ):
6473 raise
6474 if retry_attempts > 0:
6475 # Try again with the new cluster setup. All other errors
6476 # should be raised.
6477 retry_attempts -= 1
6478 failure_count += 1
6479 last_error = e
6480 last_refresh_at = self._nodes_manager._last_refresh_at
6481 # Ask for a refresh of the topology, run by the next attempt
6482 # once due; a request a connection error already made,
6483 # naming its node, is kept
6484 self._nodes_manager._request_refresh()
6485 if type(e) in (ClusterDownError, SlotNotCoveredError):
6486 # Give the cluster time to recover first, as a command
6487 # that failed so does
6488 time.sleep(0.25)
6489 # Space the attempts out as the retry backoff says
6490 delay = self._pipe._retry_backoff_delay(
6491 self._pipe.retry, failure_count
6492 )
6493 if delay > 0:
6494 time.sleep(delay)
6495 else:
6496 raise _error_to_raise(
6497 self._nodes_manager._last_refresh_unreachable_args, e
6498 )
6500 def _send_cluster_commands(
6501 self, stack, raise_on_error=True, allow_redirections=True
6502 ):
6503 """
6504 Send a bunch of cluster commands to the redis cluster.
6506 `allow_redirections` If the pipeline should follow
6507 `ASK` & `MOVED` responses automatically. If set
6508 to false it will raise RedisClusterException.
6509 """
6510 # the first time sending the commands we send all of
6511 # the commands that were queued up.
6512 # if we have to run through it again, we only retry
6513 # the commands that failed, or that no node answered:
6514 # resending one that succeeded would run a write twice.
6515 attempt = sorted(
6516 (
6517 c
6518 for c in stack
6519 if c.result is _UNANSWERED or isinstance(c.result, Exception)
6520 ),
6521 key=lambda x: x.position,
6522 )
6523 # The commands whose reply is read raw below, so their cluster response callback
6524 # is applied once at the end. A command answered on an earlier attempt was
6525 # parsed then, and one resent on its own is parsed by ``_execute_command``.
6526 parsed_here = {c.position for c in attempt}
6527 is_default_node = False
6528 # build a list of node objects based on node names we need to
6529 nodes: dict[str, NodeCommands] = {}
6530 # node objects keyed by name, so each node's connection can be pre-flighted
6531 # for HIMPORT SET (PREPARE) before the batched write.
6532 node_objs: dict = {}
6533 # the commands sent to several nodes, each with its copies - keyed by node name, or
6534 # by slot for a split MULTI_SHARD command - and the split, if it was one.
6535 fanned_out: List[
6536 Tuple[
6537 PipelineCommand,
6538 Dict[Any, PipelineCommand],
6539 Optional[List[_MultiShardSplit]],
6540 ]
6541 ] = []
6542 # The nodes the caller named for a command, by its position
6543 named_targets: Dict[int, Any] = {}
6544 nodes_written = 0
6545 nodes_read = 0
6547 try:
6548 # as we move through each command that still needs to be processed,
6549 # we figure out the slot number that command maps to, then from
6550 # the slot determine the node.
6551 for c in attempt:
6552 # refer to our internal node -> slot table that
6553 # tells us where a given command should route to.
6554 # (it might be possible we have a cached node that no longer
6555 # exists in the cluster, which is why we do this in a loop)
6556 passed_targets = c.options.pop("target_nodes", c.target_nodes)
6557 splits = None
6558 # The slot of the keys, when resolving the policies took finding them
6559 slot = None
6560 if passed_targets and not self._is_nodes_flag(passed_targets):
6561 target_nodes = self._parse_target_nodes(passed_targets)
6562 named_targets[c.position] = passed_targets
6564 # The caller named its targets, so the command's own aggregation must
6565 # not apply to their replies - see
6566 # ``RedisCluster._resolve_command_policies``.
6567 command_policies = _DEFAULT_KEYLESS_METADATA
6568 else:
6569 if self._is_nodes_flag(passed_targets):
6570 # A nodes flag picks the targets too, in ``_determine_nodes``
6571 # below, and the command's own aggregation must not apply either
6572 command_policies = _DEFAULT_KEYLESS_METADATA
6573 else:
6574 command_policies = self._pipe._policy_resolver.resolve(
6575 c.args[0].lower()
6576 )
6577 if not command_policies:
6578 command = c.args[0].upper()
6579 if (
6580 len(c.args) >= 2
6581 and f"{c.args[0]} {c.args[1]}".upper()
6582 in self._pipe.command_flags
6583 ):
6584 command = f"{c.args[0]} {c.args[1]}".upper()
6586 # We only could resolve key properties if command is not
6587 # in a list of pre-defined request policies
6588 command_flag = self.command_flags.get(command)
6589 if not command_flag:
6590 # Fallback to default policy.
6591 # EVAL/EVALSHA must not use _get_command_keys(): Redis
6592 # <7 breaks on COMMAND GETKEYS when numkeys is 0.
6593 # Other unflagged commands keep the keyless fallback.
6594 if command in ("EVAL", "EVALSHA"):
6595 command_policies = _DEFAULT_KEYED_METADATA
6596 else:
6597 if not self._pipe.get_default_node():
6598 keys = None
6599 else:
6600 keys = self._pipe._get_command_keys(*c.args)
6601 if not keys or len(keys) == 0:
6602 command_policies = _DEFAULT_KEYLESS_METADATA
6603 else:
6604 command_policies = _DEFAULT_KEYED_METADATA
6605 # Routed by these keys, so they are not found
6606 # again to pick the node
6607 slot = self._pipe._slot_of_keys(c.args[0], keys)
6608 else:
6609 if command_flag in self._pipe._command_flags_mapping:
6610 command_policies = _METADATA_BY_REQUEST_POLICY[
6611 self._pipe._command_flags_mapping[command_flag]
6612 ]
6613 else:
6614 command_policies = _DEFAULT_KEYLESS_METADATA
6616 request_policy = command_policies.request_policy
6617 if request_policy == RequestPolicy.MULTI_SHARD:
6618 splits = self._pipe._split_multi_shard_command(*c.args)
6620 if splits is not None and len(splits) < 2:
6621 # One slot: sent as it is, to the node of the slot the split
6622 # already computed
6623 target_nodes = [
6624 self._pipe._get_node_from_slot(c.args[0], splits[0][0])
6625 ]
6626 splits = None
6627 elif splits is None:
6628 target_nodes = self._determine_nodes(
6629 *c.args,
6630 request_policy=request_policy,
6631 nodes_flag=passed_targets,
6632 slot=slot,
6633 )
6634 if not target_nodes:
6635 raise RedisClusterException(
6636 "No targets were found to execute "
6637 f"{truncate_text(command_text(c.args))} command on"
6638 )
6639 c.command_policies = command_policies
6640 # Kept for a retry, which would otherwise route the command by its own
6641 # policy: a nodes flag is resolved again, and a command sent to several
6642 # named nodes is sent to them again. A single named node is not kept, so a
6643 # retry routes a keyed command by its keys - which the per-slot commands of
6644 # ``mget_nonatomic``, ``delete`` and the other multi-key helpers rely on
6645 # after a failover.
6646 if passed_targets and (
6647 self._is_nodes_flag(passed_targets) or len(target_nodes) > 1
6648 ):
6649 c.target_nodes = passed_targets
6651 # A command sent to several nodes - or split into one command per slot of
6652 # its keys - is queued as copies that each carry one reply, and the replies
6653 # are folded back into ``c`` once they are read, so the pipeline still
6654 # answers with one result per queued command.
6655 if splits is not None:
6656 # A slot that succeeded on an earlier attempt is not sent again.
6657 if c.replies is None:
6658 c.replies = {}
6659 copies: Dict[Any, PipelineCommand] = {}
6660 fanned_out.append((c, copies, splits))
6661 queued = []
6662 replica_safe = (
6663 self._pipe.read_from_replicas
6664 or self._pipe.load_balancing_strategy is not None
6665 ) and self._pipe._is_replica_safe(c.args[0])
6666 load_balancing_strategy = (
6667 self._pipe.load_balancing_strategy if replica_safe else None
6668 )
6669 for slot, slot_args, _, keys in splits:
6670 if slot in c.replies:
6671 continue
6672 copies[slot] = PipelineCommand(
6673 slot_args, _with_keys(c.options, keys), c.position
6674 )
6675 queued.append(
6676 (
6677 self._nodes_manager.get_node_from_slot(
6678 slot, replica_safe, load_balancing_strategy
6679 ),
6680 copies[slot],
6681 )
6682 )
6683 elif len(target_nodes) > 1:
6684 # A node that answered on an earlier attempt is not asked again. One
6685 # the topology refresh dropped from the targets is dropped from the
6686 # replies too, as on the main path.
6687 if c.replies is None:
6688 c.replies = {}
6689 else:
6690 _keep_target_replies(c.replies, target_nodes)
6691 copies = {}
6692 fanned_out.append((c, copies, None))
6693 queued = []
6694 for node in target_nodes:
6695 if node.name in c.replies:
6696 continue
6697 copies[node.name] = PipelineCommand(
6698 c.args, c.options, c.position
6699 )
6700 queued.append((node, copies[node.name]))
6701 else:
6702 queued = [(target_nodes[0], c)]
6704 for node, queued_command in queued:
6705 if node == self._pipe.get_default_node():
6706 is_default_node = True
6708 # now that we know the name of the node
6709 # ( it's just a string in the form of host:port )
6710 # we can build a list of commands for each node.
6711 node_name = node.name
6712 if node_name not in nodes:
6713 redis_node = self._pipe.get_redis_connection(node)
6714 try:
6715 connection = get_connection(redis_node)
6716 except (ConnectionError, TimeoutError) as e:
6717 # Release any connections we've already acquired before clearing nodes
6718 for n in nodes.values():
6719 n.connection_pool.release(n.connection)
6720 if not isinstance(e, RedisCluster.NOT_NODE_FAILURE_ERRORS):
6721 # Connection retries are being handled in the node's
6722 # Retry object. Ask for a refresh of the node -> slot
6723 # table, run by the next attempt, of any command,
6724 # once due. The failed node moves to the end of the
6725 # cached nodes, so the refresh does not pick it as
6726 # the default node while it is still a primary.
6727 self._nodes_manager.move_node_to_end_of_cached_nodes(
6728 node.name
6729 )
6730 self._nodes_manager._request_refresh(
6731 last_failed_node_name=node.name
6732 )
6733 if is_default_node:
6734 self._pipe.replace_default_node()
6735 nodes = {}
6736 raise
6737 nodes[node_name] = NodeCommands(
6738 redis_node.parse_response,
6739 redis_node.connection_pool,
6740 connection,
6741 )
6742 node_objs[node_name] = node
6743 nodes[node_name].append(queued_command)
6745 # send the commands in sequence.
6746 # we write to all the open sockets for each node first,
6747 # before reading anything
6748 # this allows us to flush all the requests out across the
6749 # network
6750 # so that we can read them from different sockets as they come back.
6751 # we don't multiplex on the sockets as they come available,
6752 # but that shouldn't make too much difference.
6754 # HIMPORT SETs in the batch need their fieldsets prepared on each
6755 # node's connection first; the packed write bypasses the per-command
6756 # lazy prepare, so pre-flight the PREPARE (once per node) here.
6757 for node_name, n in nodes.items():
6758 redis_node = self._pipe.get_redis_connection(node_objs[node_name])
6759 self._himport_prepare_pipeline(
6760 redis_node, n.connection, [(c.args, c.options) for c in n.commands]
6761 )
6763 # Start timing for observability
6764 start_time = time.monotonic()
6766 node_commands = nodes.values()
6767 for n in node_commands:
6768 nodes_written += 1
6769 n.write()
6771 demoted = False
6772 for node_name, n in nodes.items():
6773 n.read()
6775 # Find the first error in this node's commands, if any
6776 node_error = None
6777 for cmd in n.commands:
6778 if isinstance(cmd.result, Exception):
6779 node_error = cmd.result
6780 break
6782 if node_error is not None:
6783 # A primary that answered READONLY was demoted
6784 node_demoted = False
6785 for cmd in n.commands:
6786 if _is_demoted_primary(cmd.result, node_objs[node_name]):
6787 node_demoted = True
6788 named = named_targets.get(cmd.position)
6789 if named is None:
6790 cmd.result.demoted_primary = True
6791 else:
6792 # Not retried, as RedisCluster does not retry a
6793 # command with target nodes, and resent to them
6794 # if the attempt is retried for another command
6795 cmd.target_nodes = named
6796 if node_demoted:
6797 demoted = True
6798 if node_objs[node_name] == self._pipe.get_default_node():
6799 # Replace it now, as a command does: the refresh
6800 # runs only once due
6801 self._pipe.replace_default_node()
6803 record_operation_duration(
6804 command_name="PIPELINE",
6805 duration_seconds=time.monotonic() - start_time,
6806 server_address=n.connection.host,
6807 server_port=n.connection.port,
6808 db_namespace=str(n.connection.db),
6809 error=node_error,
6810 )
6811 nodes_read += 1
6813 if demoted:
6814 # Ask for a topology refresh, run by the next attempt once due
6815 self._nodes_manager._request_refresh()
6816 finally:
6817 # release all the redis connections we allocated earlier
6818 # back into the connection pool.
6819 # if the connection is dirty (that is: we've written
6820 # commands to it, but haven't read the responses), we need
6821 # to close the connection before returning it to the pool.
6822 # otherwise, the next caller to use this connection will
6823 # read the response from _this_ request, not its own request.
6824 # disconnecting discards the dirty state & forces the next
6825 # caller to reconnect.
6826 # NOTE: dicts have a consistent ordering; we're iterating
6827 # through nodes.values() in the same order as we are when
6828 # reading / writing to the connections above, which is critical
6829 # for how we're using the nodes_written/nodes_read offsets.
6830 for i, n in enumerate(nodes.values()):
6831 if i < nodes_written and i >= nodes_read:
6832 n.connection.disconnect()
6833 n.connection_pool.release(n.connection)
6835 # The copies whose connection error a ONE_SUCCEEDED success dropped. No command
6836 # is resent for them, so no retry finds their node down: a node that held
6837 # nothing else is tried last here instead.
6838 dropped = None
6839 for c, copies, splits in fanned_out:
6840 c.result = self._merge_node_results(c, copies, splits)
6841 # Only a ONE_SUCCEEDED command succeeds while a node failed
6842 if (
6843 c.command_policies.response_policy is ResponsePolicy.ONE_SUCCEEDED
6844 and not isinstance(c.result, Exception)
6845 ):
6846 for node_command in copies.values():
6847 if isinstance(
6848 node_command.result, (ConnectionError, TimeoutError)
6849 ) and not isinstance(
6850 node_command.result, RedisCluster.NOT_NODE_FAILURE_ERRORS
6851 ):
6852 if dropped is None:
6853 dropped = set()
6854 dropped.add(node_command)
6855 if dropped is not None:
6856 for node_name, n in nodes.items():
6857 if all(cmd in dropped for cmd in n.commands):
6858 # As for a connection error on any other command: move the
6859 # failed node to the end of the cached nodes, so the refresh
6860 # does not pick it as the default node while it is still a
6861 # primary, and ask for a refresh that tries it last
6862 self._nodes_manager.move_node_to_end_of_cached_nodes(node_name)
6863 self._nodes_manager._request_refresh(
6864 last_failed_node_name=node_name
6865 )
6866 if node_objs[node_name] == self._pipe.get_default_node():
6867 self._pipe.replace_default_node()
6869 # if the response isn't an exception it is a
6870 # valid response from the node
6871 # we're all done with that command, YAY!
6872 # if we have more commands to attempt, we've run into problems.
6873 # collect all the commands we are allowed to retry.
6874 # (MOVED, ASK, or connection errors or timeout errors)
6875 attempt = sorted(
6876 (
6877 c
6878 for c in attempt
6879 if isinstance(c.result, ClusterPipeline.ERRORS_ALLOW_RETRY)
6880 and not isinstance(c.result, ClusterPipeline.NOT_NODE_FAILURE_ERRORS)
6881 ),
6882 key=lambda x: x.position,
6883 )
6884 parsed_here.difference_update(c.position for c in attempt)
6885 if attempt and allow_redirections:
6886 # RETRY MAGIC HAPPENS HERE!
6887 # send these remaining commands one at a time using `execute_command`
6888 # in the main client. This keeps our retry logic
6889 # in one place mostly,
6890 # and allows us to be more confident in correctness of behavior.
6891 # at this point any speed gains from pipelining have been lost
6892 # anyway, so we might as well make the best
6893 # attempt to get the correct behavior.
6894 #
6895 # The client command will handle retries for each
6896 # individual command sequentially as we pass each
6897 # one into `execute_command`. Any exceptions
6898 # that bubble out should only appear once all
6899 # retries have been exhausted.
6900 #
6901 # If a lot of commands have failed, we'll be setting the
6902 # flag to rebuild the slots table from scratch.
6903 # So MOVED errors should correct themselves fairly quickly.
6904 self._pipe.reinitialize_counter += 1
6905 if _should_request_refresh(
6906 self._pipe.reinitialize_steps, self._pipe.reinitialize_counter
6907 ):
6908 # Ask for a refresh of the topology and run it before the
6909 # commands are sent again, once due. When it is not due it
6910 # stays asked for, and a later command runs it.
6911 self._nodes_manager._request_refresh()
6912 self._nodes_manager._run_requested_refresh(self._pipe.retry)
6913 if is_default_node:
6914 self._pipe.replace_default_node()
6915 # A split MULTI_SHARD command resends only the slots that failed, and a
6916 # command sent to several nodes asks only the nodes that have not answered
6917 fanned_out_by_position = {
6918 c.position: (copies, splits) for c, copies, splits in fanned_out
6919 }
6920 for c in attempt:
6921 fan_out = fanned_out_by_position.get(c.position)
6922 if fan_out is not None:
6923 copies, splits = fan_out
6924 if splits is not None:
6925 c.result = self._retry_failed_slots(c, copies, splits)
6926 else:
6927 c.result = self._retry_failed_nodes(c)
6928 continue
6929 try:
6930 # send each command individually like we
6931 # do in the main client.
6932 if c.target_nodes is None:
6933 c.result = self._pipe.parent_execute_command(
6934 *c.args, **c.options
6935 )
6936 else:
6937 c.result = self._pipe.parent_execute_command(
6938 *c.args, target_nodes=c.target_nodes, **c.options
6939 )
6940 except RedisError as e:
6941 c.result = e
6943 # turn the response back into a simple flat array that corresponds
6944 # to the sequence of commands issued in the stack in pipeline.execute()
6945 # A fanned-out command had its per-node replies parsed when they were merged.
6946 parsed_here.difference_update(c.position for c, _, _ in fanned_out)
6947 response = []
6948 for c in sorted(stack, key=lambda x: x.position):
6949 if (
6950 c.position in parsed_here
6951 and not isinstance(c.result, Exception)
6952 and c.args[0] in self._pipe.cluster_response_callbacks
6953 ):
6954 # Remove keys entry, it needs only for cache.
6955 c.options.pop("keys", None)
6956 c.result = self._pipe.cluster_response_callbacks[c.args[0]](
6957 c.result, **c.options
6958 )
6959 response.append(c.result)
6961 if raise_on_error:
6962 self._raise_first_error(stack, start_time)
6964 return response
6966 def _merge_node_results(
6967 self,
6968 command: PipelineCommand,
6969 copies: Dict[Any, PipelineCommand],
6970 splits: Optional[List[_MultiShardSplit]] = None,
6971 ) -> Any:
6972 """
6973 Fold the per-node replies of a command the pipeline sent to several nodes into the
6974 one result the command answers with, the way the main client does: each reply is
6975 parsed by the command's cluster response callback, an error fails the command
6976 unless its response policy expects one, and the replies are then merged by the
6977 command's result callback or folded by its response policy. The replies of a split
6978 MULTI_SHARD command are merged per slot instead - see
6979 ``_merge_multi_shard_replies`` - once every slot has succeeded, and the slots that
6980 did are kept on ``command`` so a retry resends only the ones that failed.
6981 """
6982 name = command.args[0]
6983 # Remove keys entry, it needs only for cache.
6984 options = {
6985 key: value for key, value in command.options.items() if key != "keys"
6986 }
6987 parse = self._pipe.cluster_response_callbacks.get(name)
6988 res = {
6989 node_name: (
6990 parse(c.result, **options)
6991 if parse is not None and not isinstance(c.result, Exception)
6992 else c.result
6993 )
6994 for node_name, c in copies.items()
6995 }
6997 response_policy = command.command_policies.response_policy
6998 if splits is not None:
6999 error = _record_replies(command.replies, res.items())
7000 if error is not None:
7001 return error
7002 return _merge_multi_shard_replies(command.replies, splits, response_policy)
7004 # The nodes that answered on an earlier attempt are merged with this one's
7005 _record_replies(command.replies, res.items())
7006 res, error = _split_successes_and_failure(
7007 {**command.replies, **res}, response_policy
7008 )
7009 if error is not None:
7010 return error
7012 return self._pipe._process_result(
7013 self._routed_name(command), res, response_policy=response_policy, **options
7014 )
7016 def _routed_name(self, command: PipelineCommand) -> str:
7017 """
7018 The name a command's result callback is keyed by: the routed name, which joins a
7019 container command's two words - see ``RedisCluster._resolve_command_policies``.
7020 """
7021 name = command.args[0]
7022 if (
7023 len(command.args) >= 2
7024 and f"{name} {command.args[1]}".upper() in self._pipe.command_flags
7025 ):
7026 return f"{name} {command.args[1]}".upper()
7027 return name.upper()
7029 def _retry_failed_nodes(self, command: PipelineCommand) -> Any:
7030 """
7031 Ask each node of a command sent to several nodes that has not answered, one node
7032 at a time, like the main client does, and merge the replies once every node has
7033 answered. A node that already answered is not asked again - see
7034 ``_record_replies``.
7036 The targets are resolved again, the way the first attempt resolved them, so a
7037 node the topology refresh replaced is asked in its place.
7038 """
7039 if command.target_nodes is not None and not self._is_nodes_flag(
7040 command.target_nodes
7041 ):
7042 target_nodes = self._parse_target_nodes(command.target_nodes)
7043 else:
7044 target_nodes = self._determine_nodes(
7045 *command.args,
7046 request_policy=command.command_policies.request_policy,
7047 nodes_flag=command.target_nodes,
7048 )
7050 _keep_target_replies(command.replies, target_nodes)
7051 res = dict(command.replies)
7052 for node in target_nodes:
7053 if node.name in command.replies:
7054 continue
7055 try:
7056 reply = self._pipe.parent_execute_command(
7057 *command.args, target_nodes=[node], **command.options
7058 )
7059 except RedisError as e:
7060 res[node.name] = e
7061 continue
7062 command.replies[node.name] = reply
7063 res[node.name] = reply
7065 response_policy = command.command_policies.response_policy
7066 res, error = _split_successes_and_failure(res, response_policy)
7067 if error is not None:
7068 return error
7069 # Remove keys entry, it needs only for cache.
7070 options = {
7071 key: value for key, value in command.options.items() if key != "keys"
7072 }
7073 return self._pipe._process_result(
7074 self._routed_name(command), res, response_policy=response_policy, **options
7075 )
7077 def _retry_failed_slots(
7078 self,
7079 command: PipelineCommand,
7080 copies: Dict[Any, PipelineCommand],
7081 splits: List[_MultiShardSplit],
7082 ) -> Any:
7083 """
7084 Send each slot of a split MULTI_SHARD command that failed individually, like the
7085 main client does, and merge the replies once every slot has succeeded. A slot that
7086 already succeeded is not sent again - see ``_record_replies``.
7087 """
7088 for slot, slot_command in copies.items():
7089 if slot in command.replies:
7090 continue
7091 try:
7092 command.replies[slot] = self._pipe.parent_execute_command(
7093 *slot_command.args, **slot_command.options
7094 )
7095 except RedisError as e:
7096 return e
7098 return _merge_multi_shard_replies(
7099 command.replies, splits, command.command_policies.response_policy
7100 )
7102 def _is_nodes_flag(self, target_nodes):
7103 return isinstance(target_nodes, str) and target_nodes in self._pipe.node_flags
7105 def _parse_target_nodes(self, target_nodes):
7106 if isinstance(target_nodes, list):
7107 nodes = target_nodes
7108 elif isinstance(target_nodes, ClusterNode):
7109 # Supports passing a single ClusterNode as a variable
7110 nodes = [target_nodes]
7111 elif isinstance(target_nodes, dict):
7112 # Supports dictionaries of the format {node_name: node}.
7113 # It enables to execute commands with multi nodes as follows:
7114 # rc.cluster_save_config(rc.get_primaries())
7115 nodes = target_nodes.values()
7116 else:
7117 raise TypeError(
7118 "target_nodes type can be one of the following: "
7119 "node_flag (PRIMARIES, REPLICAS, RANDOM, ALL_NODES),"
7120 "ClusterNode, list<ClusterNode>, or dict<any, ClusterNode>. "
7121 f"The passed type is {type(target_nodes)}"
7122 )
7123 return nodes
7125 def _determine_nodes(
7126 self,
7127 *args,
7128 request_policy: RequestPolicy | None = None,
7129 slot: int | None = None,
7130 **kwargs,
7131 ) -> List["ClusterNode"]:
7132 # Determine which nodes should be executed the command on.
7133 # Returns a list of target nodes.
7134 command = args[0].upper()
7135 if (
7136 len(args) >= 2
7137 and f"{args[0]} {args[1]}".upper() in self._pipe.command_flags
7138 ):
7139 command = f"{args[0]} {args[1]}".upper()
7141 # The caller resolves the command's own policy - see
7142 # ``RedisCluster._resolve_command_policies`` - so the only decision left here is
7143 # an explicit nodes flag, which overrides it. ``slot`` is the slot of the keys
7144 # that resolution already found, if it did, so they are not found twice.
7145 nodes_flag = kwargs.pop("nodes_flag", None)
7146 if nodes_flag and self._is_nodes_flag(nodes_flag):
7147 # nodes flag passed by the user
7148 if nodes_flag in self._pipe._command_flags_mapping:
7149 request_policy = self._pipe._command_flags_mapping[nodes_flag]
7151 if request_policy is None:
7152 raise RedisClusterException(
7153 "No targets were found to execute "
7154 f"{truncate_text(command_text(args))} command on"
7155 )
7157 if slot is not None:
7158 # Only the keyed fallback of the policy resolution computes a slot
7159 nodes = [self._pipe._get_node_from_slot(command, slot)]
7160 else:
7161 nodes = _REQUEST_POLICY_CALLBACKS[request_policy](
7162 self._pipe, command, *args
7163 )
7165 if args[0].lower() == "ft.aggregate":
7166 self._aggregate_nodes = nodes
7168 return nodes
7170 def multi(self):
7171 raise RedisClusterException(
7172 "method multi() is not supported outside of transactional context"
7173 )
7175 def discard(self):
7176 raise RedisClusterException(
7177 "method discard() is not supported outside of transactional context"
7178 )
7180 def watch(self, *names):
7181 raise RedisClusterException(
7182 "method watch() is not supported outside of transactional context"
7183 )
7185 def unwatch(self, *names):
7186 raise RedisClusterException(
7187 "method unwatch() is not supported outside of transactional context"
7188 )
7190 def delete(self, *names):
7191 if len(names) != 1:
7192 raise RedisClusterException(
7193 "deleting multiple keys is not implemented in pipeline command"
7194 )
7196 return self.execute_command("DEL", names[0])
7198 def unlink(self, *names):
7199 if len(names) != 1:
7200 raise RedisClusterException(
7201 "unlinking multiple keys is not implemented in pipeline command"
7202 )
7204 return self.execute_command("UNLINK", names[0])
7207class TransactionStrategy(AbstractStrategy):
7208 NO_SLOTS_COMMANDS = {"UNWATCH"}
7209 IMMEDIATE_EXECUTE_COMMANDS = {"WATCH", "UNWATCH"}
7210 UNWATCH_COMMANDS = {"DISCARD", "EXEC", "UNWATCH"}
7211 SLOT_REDIRECT_ERRORS = (AskError, MovedError)
7212 CONNECTION_ERRORS = (
7213 ConnectionError,
7214 TimeoutError,
7215 OSError,
7216 ClusterDownError,
7217 SlotNotCoveredError,
7218 )
7220 def __init__(self, pipe: ClusterPipeline):
7221 super().__init__(pipe)
7222 self._explicit_transaction = False
7223 self._watching = False
7224 self._watch_acknowledged = False
7225 self._pipeline_slots: Set[int] = set()
7226 # True once a keyed (non-slot-agnostic) command has fixed the slot
7227 self._transaction_has_keyed_slot = False
7228 self._transaction_connection: Optional[Connection] = None
7229 self._transaction_node: Optional[ClusterNode] = None
7230 self._executing = False
7231 # The error the running retry is retrying, and when the last refresh
7232 # had ended by then: a refresh since that reached no node ends the
7233 # retries (see NodesManager._error_instead_of_retry)
7234 self._retrying: Optional[Tuple[Exception, Optional[float]]] = None
7235 self._retry = copy(self._pipe.retry)
7236 self._retry.update_supported_errors(
7237 RedisCluster.ERRORS_ALLOW_RETRY + self.SLOT_REDIRECT_ERRORS
7238 )
7240 def _resolve_transaction_slot(self, *args) -> Optional[int]:
7241 """
7242 Pick a slot for a transactional pipeline command.
7244 Zero-key EVAL/EVALSHA can run on any primary. Reuse an existing
7245 transaction slot when present so multiple zero-key scripts (or a
7246 mix with keyed commands) stay single-slot.
7247 """
7248 if args[0] in ClusterPipeline.NO_SLOTS_COMMANDS:
7249 return None
7251 if is_zero_key_eval_command(*args):
7252 if self._pipeline_slots:
7253 return next(iter(self._pipeline_slots))
7254 return self._pipe.determine_slot(*args)
7256 slot_number = self._pipe.determine_slot(*args)
7257 if (
7258 slot_number is not None
7259 and self._pipeline_slots
7260 and slot_number not in self._pipeline_slots
7261 and not self._transaction_has_keyed_slot
7262 ):
7263 # Prior slots came only from zero-key scripts; retarget.
7264 self._pipeline_slots.clear()
7265 if slot_number is not None:
7266 self._transaction_has_keyed_slot = True
7267 return slot_number
7269 def _get_client_and_connection_for_transaction(self) -> Tuple[Redis, Connection]:
7270 """
7271 Find a connection for a pipeline transaction.
7273 For running an atomic transaction, watch keys ensure that contents have not been
7274 altered as long as the watch commands for those keys were sent over the same
7275 connection. So once we start watching a key, we fetch a connection to the
7276 node that owns that slot and reuse it.
7277 """
7278 if not self._pipeline_slots:
7279 raise RedisClusterException(
7280 "At least a command with a key is needed to identify a node"
7281 )
7283 if self._transaction_connection:
7284 # Keep the node the held connection belongs to, even if a refresh
7285 # moved the slot: the server reports the move (MOVED), and the error
7286 # path releases the connection to its own node before retargeting
7287 return (
7288 self._pipe.get_redis_connection(self._transaction_node),
7289 self._transaction_connection,
7290 )
7292 node: ClusterNode = self._nodes_manager.get_node_from_slot(
7293 list(self._pipeline_slots)[0], False
7294 )
7295 redis_node: Redis = self._pipe.get_redis_connection(node)
7296 self._transaction_connection = get_connection(redis_node)
7297 self._transaction_node = node
7299 return redis_node, self._transaction_connection
7301 def execute_command(self, *args, **kwargs):
7302 slot_number: Optional[int] = None
7303 if args[0] not in ClusterPipeline.NO_SLOTS_COMMANDS:
7304 slot_number = self._resolve_transaction_slot(*args)
7306 if (
7307 self._watching or args[0] in self.IMMEDIATE_EXECUTE_COMMANDS
7308 ) and not self._explicit_transaction:
7309 if args[0] == "WATCH":
7310 self._validate_watch()
7312 if slot_number is not None:
7313 if self._pipeline_slots and slot_number not in self._pipeline_slots:
7314 raise CrossSlotTransactionError(
7315 "Cannot watch or send commands on different slots"
7316 )
7318 self._pipeline_slots.add(slot_number)
7319 elif args[0] not in self.NO_SLOTS_COMMANDS:
7320 raise RedisClusterException(
7321 f"Cannot identify slot number for command: {args[0]},"
7322 "it cannot be triggered in a transaction"
7323 )
7325 return self._immediate_execute_command(*args, **kwargs)
7326 else:
7327 if slot_number is not None:
7328 self._pipeline_slots.add(slot_number)
7330 return self.pipeline_execute_command(*args, **kwargs)
7332 def _validate_watch(self):
7333 if self._explicit_transaction:
7334 raise RedisError("Cannot issue a WATCH after a MULTI")
7336 self._watching = True
7338 def _immediate_execute_command(self, *args, **options):
7339 try:
7340 return self._retry.call_with_retry(
7341 lambda: self._get_connection_and_send_command(*args, **options),
7342 self._reinitialize_on_error,
7343 is_retryable=RedisCluster._is_retryable_cluster_error,
7344 with_failure_count=True,
7345 )
7346 except (ConnectionError, TimeoutError) as e:
7347 raise _error_to_raise(self._nodes_manager._last_refresh_unreachable_args, e)
7348 finally:
7349 # The error of a retried attempt serves the run's next attempt only
7350 self._retrying = None
7352 def _raise_instead_of_retry(self) -> None:
7353 """
7354 Give up the running retry when a refresh that ended since its error
7355 reached no node (see NodesManager._error_instead_of_retry).
7356 """
7357 if self._retrying is not None:
7358 outage_error = self._nodes_manager._error_instead_of_retry(*self._retrying)
7359 if outage_error is not None:
7360 raise outage_error
7362 def _get_connection_and_send_command(self, *args, **options):
7363 # Run a topology refresh an earlier error asked for, once due. The flag
7364 # is read inline: this runs before every attempt.
7365 if self._nodes_manager._refresh_requested:
7366 self._nodes_manager._run_requested_refresh(self._pipe.retry)
7367 self._raise_instead_of_retry()
7368 redis_node, connection = self._get_client_and_connection_for_transaction()
7370 # Start timing for observability
7371 start_time = time.monotonic()
7373 try:
7374 response = self._send_command_parse_response(
7375 connection, redis_node, args[0], *args, **options
7376 )
7378 record_operation_duration(
7379 command_name=args[0],
7380 duration_seconds=time.monotonic() - start_time,
7381 server_address=connection.host,
7382 server_port=connection.port,
7383 db_namespace=str(connection.db),
7384 )
7386 return response
7387 except Exception as e:
7388 if connection:
7389 # this is used to report the metrics based on host and port info
7390 e.connection = connection
7391 record_operation_duration(
7392 command_name=args[0],
7393 duration_seconds=time.monotonic() - start_time,
7394 server_address=connection.host,
7395 server_port=connection.port,
7396 db_namespace=str(connection.db),
7397 error=e,
7398 )
7399 raise
7401 def _send_command_parse_response(
7402 self, conn, redis_node: Redis, command_name, *args, **options
7403 ):
7404 """
7405 Send a command and parse the response
7406 """
7408 # HIMPORT SET's wire form depends on per-connection state: the fieldset
7409 # must be PREPAREd on this connection first, and any fieldset discarded
7410 # since this connection last reconciled must be dropped. The
7411 # immediate/watched path (commands issued after WATCH, before MULTI)
7412 # would otherwise send a bare HIMPORT SET and fail with "no such
7413 # fieldset". Route it through the node's HIMPORT executor, the same way
7414 # the normal cluster path, the batched MULTI/EXEC path, and standalone
7415 # watched pipelines all do.
7416 himport_set = parse_himport_set_args(args)
7417 if himport_set is not None:
7418 # HIMPORT SET in the joined or split raw form; operands at the right
7419 # offsets. Too few operands returns None and falls through to the bare
7420 # send so the server returns its arity error.
7421 key, fieldset_name, values = himport_set
7422 output = redis_node._himport_execute_set(conn, key, fieldset_name, values)
7423 else:
7424 conn.send_command(*args)
7425 output = redis_node.parse_response(conn, command_name, **options)
7427 if command_name == "WATCH":
7428 self._watch_acknowledged = True
7429 elif command_name in self.UNWATCH_COMMANDS:
7430 self._watching = False
7431 self._watch_acknowledged = False
7432 return output
7434 def _reinitialize_on_error(self, error, failure_count):
7435 self._retrying = (error, self._nodes_manager._last_refresh_at)
7436 if hasattr(error, "connection"):
7437 record_error_count(
7438 server_address=error.connection.host,
7439 server_port=error.connection.port,
7440 network_peer_address=error.connection.host,
7441 network_peer_port=error.connection.port,
7442 error_type=error,
7443 retry_attempts=failure_count,
7444 is_internal=True,
7445 )
7447 # WATCH is requested before the first attempt, but only a reply
7448 # establishes the protection that a retry must not silently discard.
7449 if self._watch_acknowledged or isinstance(
7450 error, self.SLOT_REDIRECT_ERRORS + self.CONNECTION_ERRORS
7451 ):
7452 node = None
7453 if self._transaction_connection:
7454 if is_debug_log_enabled():
7455 logger.debug(
7456 f"Operation failed, "
7457 f"with connection: {self._transaction_connection}, "
7458 f"details: {self._transaction_connection.extract_connection_details()}",
7459 )
7460 # Disconnect and release back to pool
7461 self._transaction_connection.disconnect()
7462 node = self._transaction_node
7463 self._release_transaction_connection()
7465 self._pipe.reinitialize_counter += 1
7466 should_request_refresh = _should_request_refresh(
7467 self._pipe.reinitialize_steps, self._pipe.reinitialize_counter
7468 )
7469 if isinstance(error, AskError):
7470 # MovedError is an AskError, so a MOVED slot is patched too, and
7471 # the retry goes to the node that owns it now. The refresh is
7472 # only asked for, run by the next command once due.
7473 if self._transaction_node is not None:
7474 _fill_missing_redirect_host(error, self._transaction_node.host)
7475 self._nodes_manager.move_slot(error)
7476 if should_request_refresh:
7477 self._nodes_manager._request_refresh()
7478 self._pipe.reinitialize_counter = 0
7479 elif should_request_refresh:
7480 # A connection error: ask for a refresh that tries the failed
7481 # node last. The next attempt runs it once due, through
7482 # _run_requested_refresh, which keeps the current topology if
7483 # the refresh fails.
7484 if node is None and self._pipeline_slots:
7485 # Connecting failed, so no connection names the node: it is
7486 # the one that owns the slot the attempt targeted
7487 slot_nodes = self._nodes_manager.slots_cache.get(
7488 list(self._pipeline_slots)[0]
7489 )
7490 if slot_nodes:
7491 node = slot_nodes[0]
7492 failed_node_name = node.name if node is not None else None
7493 if failed_node_name is not None:
7494 self._nodes_manager.move_node_to_end_of_cached_nodes(
7495 failed_node_name
7496 )
7497 self._nodes_manager._request_refresh(
7498 last_failed_node_name=failed_node_name
7499 )
7500 self._pipe.reinitialize_counter = 0
7502 self._executing = False
7503 if self._watch_acknowledged:
7504 self.reset()
7505 if isinstance(error, self.SLOT_REDIRECT_ERRORS):
7506 raise WatchError(
7507 "Slot rebalancing occurred while watching keys"
7508 ) from error
7509 raise WatchError("An error occurred while watching keys") from error
7511 def _raise_first_error(self, responses, stack, start_time):
7512 """
7513 Raise the first exception on the stack
7514 """
7515 for r, cmd in zip(responses, stack):
7516 if isinstance(r, Exception):
7517 self.annotate_exception(r, cmd.position + 1, cmd.args)
7519 record_operation_duration(
7520 command_name="TRANSACTION",
7521 duration_seconds=time.monotonic() - start_time,
7522 server_address=self._transaction_connection.host,
7523 server_port=self._transaction_connection.port,
7524 db_namespace=str(self._transaction_connection.db),
7525 )
7527 raise r
7529 def execute(self, raise_on_error: bool = True) -> List[Any]:
7530 stack = self._command_queue
7531 if not stack and (not self._watching or not self._pipeline_slots):
7532 return []
7534 return self._execute_transaction_with_retries(stack, raise_on_error)
7536 def _execute_transaction_with_retries(
7537 self, stack: List["PipelineCommand"], raise_on_error: bool
7538 ):
7539 try:
7540 return self._retry.call_with_retry(
7541 lambda: self._execute_transaction(stack, raise_on_error),
7542 lambda error, failure_count: self._reinitialize_on_error(
7543 error, failure_count
7544 ),
7545 is_retryable=RedisCluster._is_retryable_cluster_error,
7546 with_failure_count=True,
7547 )
7548 except (ConnectionError, TimeoutError) as e:
7549 raise _error_to_raise(self._nodes_manager._last_refresh_unreachable_args, e)
7550 finally:
7551 # The error of a retried attempt serves the run's next attempt only
7552 self._retrying = None
7554 def _execute_transaction(
7555 self, stack: List["PipelineCommand"], raise_on_error: bool
7556 ):
7557 if len(self._pipeline_slots) > 1:
7558 raise CrossSlotTransactionError(
7559 "All keys involved in a cluster transaction must map to the same slot"
7560 )
7562 # Run a topology refresh an earlier error asked for, once due. The flag
7563 # is read inline: this runs before every attempt.
7564 if self._nodes_manager._refresh_requested:
7565 self._nodes_manager._run_requested_refresh(self._pipe.retry)
7566 self._raise_instead_of_retry()
7568 self._executing = True
7570 redis_node, connection = self._get_client_and_connection_for_transaction()
7572 # Ensure fieldsets referenced by buffered HIMPORT SETs are prepared on this
7573 # node's connection before the MULTI/EXEC block (session state, not
7574 # transactional). All keys share one slot here, so it is a single node.
7575 self._himport_prepare_pipeline(
7576 redis_node, connection, [(c.args, c.options) for c in stack]
7577 )
7579 stack = chain(
7580 [PipelineCommand(("MULTI",))],
7581 stack,
7582 [PipelineCommand(("EXEC",))],
7583 )
7584 commands = [c.args for c in stack if EMPTY_RESPONSE not in c.options]
7585 packed_commands = connection.pack_commands(commands)
7587 # Start timing for observability
7588 start_time = time.monotonic()
7590 connection.send_packed_command(packed_commands)
7591 errors = []
7593 # parse off the response for MULTI
7594 # NOTE: we need to handle ResponseErrors here and continue
7595 # so that we read all the additional command messages from
7596 # the socket
7597 try:
7598 redis_node.parse_response(connection, "MULTI")
7599 except ResponseError as e:
7600 self.annotate_exception(e, 0, "MULTI")
7601 errors.append(e)
7602 except self.CONNECTION_ERRORS as cluster_error:
7603 self.annotate_exception(cluster_error, 0, "MULTI")
7604 raise
7606 # and all the other commands
7607 for i, command in enumerate(self._command_queue):
7608 if EMPTY_RESPONSE in command.options:
7609 errors.append((i, command.options[EMPTY_RESPONSE]))
7610 else:
7611 try:
7612 _ = redis_node.parse_response(connection, "_")
7613 except self.SLOT_REDIRECT_ERRORS as slot_error:
7614 self.annotate_exception(slot_error, i + 1, command.args)
7615 errors.append(slot_error)
7616 except self.CONNECTION_ERRORS as cluster_error:
7617 self.annotate_exception(cluster_error, i + 1, command.args)
7618 raise
7619 except ResponseError as e:
7620 self.annotate_exception(e, i + 1, command.args)
7621 errors.append(e)
7623 response = None
7624 # parse the EXEC.
7625 try:
7626 response = redis_node.parse_response(connection, "EXEC")
7627 except ExecAbortError:
7628 if errors:
7629 raise errors[0]
7630 raise
7632 self._executing = False
7634 record_operation_duration(
7635 command_name="TRANSACTION",
7636 duration_seconds=time.monotonic() - start_time,
7637 server_address=connection.host,
7638 server_port=connection.port,
7639 db_namespace=str(connection.db),
7640 )
7642 # EXEC clears any watched keys
7643 self._watching = False
7644 self._watch_acknowledged = False
7646 if response is None:
7647 raise WatchError("Watched variable changed.")
7649 # put any parse errors into the response
7650 for i, e in errors:
7651 response.insert(i, e)
7653 if len(response) != len(self._command_queue):
7654 raise InvalidPipelineStack(
7655 "Unexpected response length for cluster pipeline EXEC."
7656 " Command stack was {} but response had length {}".format(
7657 [c.args[0] for c in self._command_queue], len(response)
7658 )
7659 )
7661 # find any errors in the response and raise if necessary
7662 if raise_on_error or len(errors) > 0:
7663 self._raise_first_error(
7664 response,
7665 self._command_queue,
7666 start_time,
7667 )
7669 # We have to run response callbacks manually
7670 data = []
7671 for r, cmd in zip(response, self._command_queue):
7672 if not isinstance(r, Exception):
7673 command_name = cmd.args[0]
7674 if command_name in self._pipe.cluster_response_callbacks:
7675 r = self._pipe.cluster_response_callbacks[command_name](
7676 r, **cmd.options
7677 )
7678 data.append(r)
7679 return data
7681 def _release_transaction_connection(self) -> None:
7682 """
7683 Return the held connection to the pool of the node it was taken from.
7685 That node, not the one ``nodes_cache`` holds under its name now: a
7686 refresh may have removed the node, or replaced it with a new instance,
7687 and the connection belongs to the old node's pool either way.
7688 """
7689 connection, self._transaction_connection = self._transaction_connection, None
7690 node = self._transaction_node
7691 if connection and node and node.redis_connection:
7692 node.redis_connection.connection_pool.release(connection)
7694 def reset(self):
7695 self._command_queue = []
7697 # make sure to reset the connection state in the event that we were
7698 # watching something
7699 if self._transaction_connection:
7700 try:
7701 # A dropped connection has already lost its WATCHes, so skip
7702 # the UNWATCH instead of reconnecting to send it.
7703 if self._watching and self._transaction_connection.is_connected:
7704 # call this manually since our unwatch or
7705 # immediate_execute_command methods can call reset()
7706 self._transaction_connection.send_command("UNWATCH")
7707 self._transaction_connection.read_response()
7708 # we can safely return the connection to the pool here since we're
7709 # sure we're no longer WATCHing anything
7710 self._release_transaction_connection()
7711 except self.CONNECTION_ERRORS:
7712 # disconnect will also remove any previous WATCHes
7713 if self._transaction_connection:
7714 self._transaction_connection.disconnect()
7715 self._release_transaction_connection()
7717 # clean up the other instance attributes
7718 self._transaction_node = None
7719 self._watching = False
7720 self._watch_acknowledged = False
7721 self._explicit_transaction = False
7722 self._pipeline_slots = set()
7723 self._transaction_has_keyed_slot = False
7724 self._executing = False
7725 self._retrying = None
7727 def send_cluster_commands(
7728 self, stack, raise_on_error=True, allow_redirections=True
7729 ):
7730 raise NotImplementedError(
7731 "send_cluster_commands cannot be executed in transactional context."
7732 )
7734 def multi(self):
7735 if self._explicit_transaction:
7736 raise RedisError("Cannot issue nested calls to MULTI")
7737 if self._command_queue:
7738 raise RedisError(
7739 "Commands without an initial WATCH have already been issued"
7740 )
7741 self._explicit_transaction = True
7743 def watch(self, *names):
7744 if self._explicit_transaction:
7745 raise RedisError("Cannot issue a WATCH after a MULTI")
7747 return self.execute_command("WATCH", *names)
7749 def unwatch(self):
7750 if self._watching:
7751 return self.execute_command("UNWATCH")
7753 return True
7755 def discard(self):
7756 self.reset()
7758 def delete(self, *names):
7759 return self.execute_command("DEL", *names)
7761 def unlink(self, *names):
7762 return self.execute_command("UNLINK", *names)