Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/redis/maint_notifications.py: 26%

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

457 statements  

1import enum 

2import ipaddress 

3import logging 

4import re 

5import threading 

6import time 

7from abc import ABC, abstractmethod 

8from typing import ( 

9 TYPE_CHECKING, 

10 Any, 

11 Callable, 

12 Dict, 

13 List, 

14 Literal, 

15 Mapping, 

16 Optional, 

17 Type, 

18 Union, 

19) 

20 

21from redis.event import ( 

22 EventDispatcherInterface, 

23 MaintenanceCompletedEvent, 

24 MaintenanceEvent, 

25 MaintenanceStartedEvent, 

26) 

27from redis.observability.attributes import get_pool_name 

28from redis.observability.recorder import ( 

29 record_connection_handoff, 

30 record_connection_relaxed_timeout, 

31 record_maint_notification_count, 

32) 

33from redis.typing import Number 

34 

35if TYPE_CHECKING: 

36 from redis.cluster import MaintNotificationsAbstractRedisCluster 

37 

38logger = logging.getLogger(__name__) 

39 

40 

41class MaintenanceState(enum.Enum): 

42 NONE = "none" 

43 MOVING = "moving" 

44 MAINTENANCE = "maintenance" 

45 

46 

47class EndpointType(enum.Enum): 

48 """Valid endpoint types used in CLIENT MAINT_NOTIFICATIONS command.""" 

49 

50 INTERNAL_IP = "internal-ip" 

51 INTERNAL_FQDN = "internal-fqdn" 

52 EXTERNAL_IP = "external-ip" 

53 EXTERNAL_FQDN = "external-fqdn" 

54 NONE = "none" 

55 

56 def __str__(self): 

57 """Return the string value of the enum.""" 

58 return self.value 

59 

60 

61if TYPE_CHECKING: 

62 from redis.asyncio.connection import AsyncMaintNotificationsAbstractConnection 

63 from redis.connection import ( 

64 MaintNotificationsAbstractConnection, 

65 MaintNotificationsAbstractConnectionPool, 

66 ) 

67 

68 

69class MaintenanceNotification(ABC): 

70 """ 

71 Base class for maintenance notifications sent through push messages by Redis server. 

72 

73 This class provides common functionality for all maintenance notifications including 

74 unique identification and TTL (Time-To-Live) functionality. 

75 

76 Attributes: 

77 id (int): Unique identifier for this notification 

78 ttl (int): Time-to-live in seconds for this notification 

79 creation_time (float): Timestamp when the notification was created/read 

80 """ 

81 

82 def __init__(self, id: int, ttl: int): 

83 """ 

84 Initialize a new MaintenanceNotification with unique ID and TTL functionality. 

85 

86 Args: 

87 id (int): Unique identifier for this notification 

88 ttl (int): Time-to-live in seconds for this notification 

89 """ 

90 self.id = id 

91 self.ttl = ttl 

92 self.creation_time = time.monotonic() 

93 self.expire_at = self.creation_time + self.ttl 

94 

95 def is_expired(self) -> bool: 

96 """ 

97 Check if this notification has expired based on its TTL 

98 and creation time. 

99 

100 Returns: 

101 bool: True if the notification has expired, False otherwise 

102 """ 

103 return time.monotonic() > (self.creation_time + self.ttl) 

104 

105 @abstractmethod 

106 def __repr__(self) -> str: 

107 """ 

108 Return a string representation of the maintenance notification. 

109 

110 This method must be implemented by all concrete subclasses. 

111 

112 Returns: 

113 str: String representation of the notification 

114 """ 

115 pass 

116 

117 @abstractmethod 

118 def __eq__(self, other) -> bool: 

119 """ 

120 Compare two maintenance notifications for equality. 

121 

122 This method must be implemented by all concrete subclasses. 

123 Notifications are typically considered equal if they have the same id 

124 and are of the same type. 

125 

126 Args: 

127 other: The other object to compare with 

128 

129 Returns: 

130 bool: True if the notifications are equal, False otherwise 

131 """ 

132 pass 

133 

134 @abstractmethod 

135 def __hash__(self) -> int: 

136 """ 

137 Return a hash value for the maintenance notification. 

138 

139 This method must be implemented by all concrete subclasses to allow 

140 instances to be used in sets and as dictionary keys. 

141 

142 Returns: 

143 int: Hash value for the notification 

144 """ 

145 pass 

146 

147 

148class NodeMovingNotification(MaintenanceNotification): 

149 """ 

150 This notification is received when a node is replaced with a new node 

151 during cluster rebalancing or maintenance operations. 

152 """ 

153 

154 def __init__( 

155 self, 

156 id: int, 

157 new_node_host: Optional[str], 

158 new_node_port: Optional[int], 

159 ttl: int, 

160 ): 

161 """ 

162 Initialize a new NodeMovingNotification. 

163 

164 Args: 

165 id (int): Unique identifier for this notification 

166 new_node_host (str): Hostname or IP address of the new replacement node 

167 new_node_port (int): Port number of the new replacement node 

168 ttl (int): Time-to-live in seconds for this notification 

169 """ 

170 super().__init__(id, ttl) 

171 self.new_node_host = new_node_host 

172 self.new_node_port = new_node_port 

173 

174 def __repr__(self) -> str: 

175 expiry_time = self.expire_at 

176 remaining = max(0, expiry_time - time.monotonic()) 

177 

178 return ( 

179 f"{self.__class__.__name__}(" 

180 f"id={self.id}, " 

181 f"new_node_host='{self.new_node_host}', " 

182 f"new_node_port={self.new_node_port}, " 

183 f"ttl={self.ttl}, " 

184 f"creation_time={self.creation_time}, " 

185 f"expires_at={expiry_time}, " 

186 f"remaining={remaining:.1f}s, " 

187 f"expired={self.is_expired()}" 

188 f")" 

189 ) 

190 

191 def __eq__(self, other) -> bool: 

192 """ 

193 Two NodeMovingNotification notifications are considered equal if they have the same 

194 id, new_node_host, and new_node_port. 

195 """ 

196 if not isinstance(other, NodeMovingNotification): 

197 return False 

198 return ( 

199 self.id == other.id 

200 and self.new_node_host == other.new_node_host 

201 and self.new_node_port == other.new_node_port 

202 ) 

203 

204 def __hash__(self) -> int: 

205 """ 

206 Return a hash value for the notification to allow 

207 instances to be used in sets and as dictionary keys. 

208 

209 Returns: 

210 int: Hash value based on notification type class name, id, 

211 new_node_host and new_node_port 

212 """ 

213 try: 

214 node_port = int(self.new_node_port) if self.new_node_port else None 

215 except ValueError: 

216 node_port = 0 

217 

218 return hash( 

219 ( 

220 self.__class__.__name__, 

221 int(self.id), 

222 str(self.new_node_host), 

223 node_port, 

224 ) 

225 ) 

226 

227 

228class NodeMigratingNotification(MaintenanceNotification): 

229 """ 

230 Notification for when a Redis cluster node is in the process of migrating slots. 

231 

232 This notification is received when a node starts migrating its slots to another node 

233 during cluster rebalancing or maintenance operations. 

234 

235 Args: 

236 id (int): Unique identifier for this notification 

237 ttl (int): Time-to-live in seconds for this notification 

238 """ 

239 

240 def __init__(self, id: int, ttl: int): 

241 super().__init__(id, ttl) 

242 

243 def __repr__(self) -> str: 

244 expiry_time = self.creation_time + self.ttl 

245 remaining = max(0, expiry_time - time.monotonic()) 

246 return ( 

247 f"{self.__class__.__name__}(" 

248 f"id={self.id}, " 

249 f"ttl={self.ttl}, " 

250 f"creation_time={self.creation_time}, " 

251 f"expires_at={expiry_time}, " 

252 f"remaining={remaining:.1f}s, " 

253 f"expired={self.is_expired()}" 

254 f")" 

255 ) 

256 

257 def __eq__(self, other) -> bool: 

258 """ 

259 Two NodeMigratingNotification notifications are considered equal if they have the same 

260 id and are of the same type. 

261 """ 

262 if not isinstance(other, NodeMigratingNotification): 

263 return False 

264 return self.id == other.id and type(self) is type(other) 

265 

266 def __hash__(self) -> int: 

267 """ 

268 Return a hash value for the notification to allow 

269 instances to be used in sets and as dictionary keys. 

270 

271 Returns: 

272 int: Hash value based on notification type and id 

273 """ 

274 return hash((self.__class__.__name__, int(self.id))) 

275 

276 

277class NodeMigratedNotification(MaintenanceNotification): 

278 """ 

279 Notification for when a Redis cluster node has completed migrating slots. 

280 

281 This notification is received when a node has finished migrating all its slots 

282 to other nodes during cluster rebalancing or maintenance operations. 

283 

284 Args: 

285 id (int): Unique identifier for this notification 

286 """ 

287 

288 DEFAULT_TTL = 5 

289 

290 def __init__(self, id: int): 

291 super().__init__(id, NodeMigratedNotification.DEFAULT_TTL) 

292 

293 def __repr__(self) -> str: 

294 expiry_time = self.creation_time + self.ttl 

295 remaining = max(0, expiry_time - time.monotonic()) 

296 return ( 

297 f"{self.__class__.__name__}(" 

298 f"id={self.id}, " 

299 f"ttl={self.ttl}, " 

300 f"creation_time={self.creation_time}, " 

301 f"expires_at={expiry_time}, " 

302 f"remaining={remaining:.1f}s, " 

303 f"expired={self.is_expired()}" 

304 f")" 

305 ) 

306 

307 def __eq__(self, other) -> bool: 

308 """ 

309 Two NodeMigratedNotification notifications are considered equal if they have the same 

310 id and are of the same type. 

311 """ 

312 if not isinstance(other, NodeMigratedNotification): 

313 return False 

314 return self.id == other.id and type(self) is type(other) 

315 

316 def __hash__(self) -> int: 

317 """ 

318 Return a hash value for the notification to allow 

319 instances to be used in sets and as dictionary keys. 

320 

321 Returns: 

322 int: Hash value based on notification type and id 

323 """ 

324 return hash((self.__class__.__name__, int(self.id))) 

325 

326 

327class NodeFailingOverNotification(MaintenanceNotification): 

328 """ 

329 Notification for when a Redis cluster node is in the process of failing over. 

330 

331 This notification is received when a node starts a failover process during 

332 cluster maintenance operations or when handling node failures. 

333 

334 Args: 

335 id (int): Unique identifier for this notification 

336 ttl (int): Time-to-live in seconds for this notification 

337 """ 

338 

339 def __init__(self, id: int, ttl: int): 

340 super().__init__(id, ttl) 

341 

342 def __repr__(self) -> str: 

343 expiry_time = self.creation_time + self.ttl 

344 remaining = max(0, expiry_time - time.monotonic()) 

345 return ( 

346 f"{self.__class__.__name__}(" 

347 f"id={self.id}, " 

348 f"ttl={self.ttl}, " 

349 f"creation_time={self.creation_time}, " 

350 f"expires_at={expiry_time}, " 

351 f"remaining={remaining:.1f}s, " 

352 f"expired={self.is_expired()}" 

353 f")" 

354 ) 

355 

356 def __eq__(self, other) -> bool: 

357 """ 

358 Two NodeFailingOverNotification notifications are considered equal if they have the same 

359 id and are of the same type. 

360 """ 

361 if not isinstance(other, NodeFailingOverNotification): 

362 return False 

363 return self.id == other.id and type(self) is type(other) 

364 

365 def __hash__(self) -> int: 

366 """ 

367 Return a hash value for the notification to allow 

368 instances to be used in sets and as dictionary keys. 

369 

370 Returns: 

371 int: Hash value based on notification type and id 

372 """ 

373 return hash((self.__class__.__name__, int(self.id))) 

374 

375 

376class NodeFailedOverNotification(MaintenanceNotification): 

377 """ 

378 Notification for when a Redis cluster node has completed a failover. 

379 

380 This notification is received when a node has finished the failover process 

381 during cluster maintenance operations or after handling node failures. 

382 

383 Args: 

384 id (int): Unique identifier for this notification 

385 """ 

386 

387 DEFAULT_TTL = 5 

388 

389 def __init__(self, id: int): 

390 super().__init__(id, NodeFailedOverNotification.DEFAULT_TTL) 

391 

392 def __repr__(self) -> str: 

393 expiry_time = self.creation_time + self.ttl 

394 remaining = max(0, expiry_time - time.monotonic()) 

395 return ( 

396 f"{self.__class__.__name__}(" 

397 f"id={self.id}, " 

398 f"ttl={self.ttl}, " 

399 f"creation_time={self.creation_time}, " 

400 f"expires_at={expiry_time}, " 

401 f"remaining={remaining:.1f}s, " 

402 f"expired={self.is_expired()}" 

403 f")" 

404 ) 

405 

406 def __eq__(self, other) -> bool: 

407 """ 

408 Two NodeFailedOverNotification notifications are considered equal if they have the same 

409 id and are of the same type. 

410 """ 

411 if not isinstance(other, NodeFailedOverNotification): 

412 return False 

413 return self.id == other.id and type(self) is type(other) 

414 

415 def __hash__(self) -> int: 

416 """ 

417 Return a hash value for the notification to allow 

418 instances to be used in sets and as dictionary keys. 

419 

420 Returns: 

421 int: Hash value based on notification type and id 

422 """ 

423 return hash((self.__class__.__name__, int(self.id))) 

424 

425 

426class OSSNodeMigratingNotification(MaintenanceNotification): 

427 """ 

428 Notification for when a Redis OSS API client is used and a node is in the process of migrating slots. 

429 

430 This notification is received when a node starts migrating its slots to another node 

431 during cluster rebalancing or maintenance operations. 

432 

433 Args: 

434 id (int): Unique identifier for this notification 

435 slots (Optional[List[int]]): List of slots being migrated 

436 """ 

437 

438 DEFAULT_TTL = 30 

439 

440 def __init__( 

441 self, 

442 id: int, 

443 slots: Optional[str] = None, 

444 ): 

445 super().__init__(id, OSSNodeMigratingNotification.DEFAULT_TTL) 

446 self.slots = slots 

447 

448 def __repr__(self) -> str: 

449 expiry_time = self.creation_time + self.ttl 

450 remaining = max(0, expiry_time - time.monotonic()) 

451 return ( 

452 f"{self.__class__.__name__}(" 

453 f"id={self.id}, " 

454 f"slots={self.slots}, " 

455 f"ttl={self.ttl}, " 

456 f"creation_time={self.creation_time}, " 

457 f"expires_at={expiry_time}, " 

458 f"remaining={remaining:.1f}s, " 

459 f"expired={self.is_expired()}" 

460 f")" 

461 ) 

462 

463 def __eq__(self, other) -> bool: 

464 """ 

465 Two OSSNodeMigratingNotification notifications are considered equal if they have the same 

466 id and are of the same type. 

467 """ 

468 if not isinstance(other, OSSNodeMigratingNotification): 

469 return False 

470 return self.id == other.id and type(self) is type(other) 

471 

472 def __hash__(self) -> int: 

473 """ 

474 Return a hash value for the notification to allow 

475 instances to be used in sets and as dictionary keys. 

476 

477 Returns: 

478 int: Hash value based on notification type and id 

479 """ 

480 return hash((self.__class__.__name__, int(self.id))) 

481 

482 

483class OSSNodeMigratedNotification(MaintenanceNotification): 

484 """ 

485 Notification for when a Redis OSS API client is used and a node has completed migrating slots. 

486 

487 This notification is received when a node has finished migrating all its slots 

488 to other nodes during cluster rebalancing or maintenance operations. 

489 

490 Args: 

491 id (int): Unique identifier for this notification 

492 nodes_to_slots_mapping (Dict[str, List[Dict[str, str]]]): Map of source node address 

493 to list of destination mappings. Each destination mapping is a dict with 

494 the destination node address as key and the slot range as value. 

495 

496 Structure example: 

497 { 

498 "127.0.0.1:6379": [ 

499 {"127.0.0.1:6380": "1-100"}, 

500 {"127.0.0.1:6381": "101-200"} 

501 ], 

502 "127.0.0.1:6382": [ 

503 {"127.0.0.1:6383": "201-300"} 

504 ] 

505 } 

506 

507 Where: 

508 - Key (str): Source node address in "host:port" format 

509 - Value (List[Dict[str, str]]): List of destination mappings where each dict 

510 contains destination node address as key and slot range as value 

511 """ 

512 

513 DEFAULT_TTL = 120 

514 

515 def __init__( 

516 self, 

517 id: int, 

518 nodes_to_slots_mapping: Dict[str, List[Dict[str, str]]], 

519 ): 

520 super().__init__(id, OSSNodeMigratedNotification.DEFAULT_TTL) 

521 self.nodes_to_slots_mapping = nodes_to_slots_mapping 

522 

523 def __repr__(self) -> str: 

524 expiry_time = self.creation_time + self.ttl 

525 remaining = max(0, expiry_time - time.monotonic()) 

526 return ( 

527 f"{self.__class__.__name__}(" 

528 f"id={self.id}, " 

529 f"nodes_to_slots_mapping={self.nodes_to_slots_mapping}, " 

530 f"ttl={self.ttl}, " 

531 f"creation_time={self.creation_time}, " 

532 f"expires_at={expiry_time}, " 

533 f"remaining={remaining:.1f}s, " 

534 f"expired={self.is_expired()}" 

535 f")" 

536 ) 

537 

538 def __eq__(self, other) -> bool: 

539 """ 

540 Two OSSNodeMigratedNotification notifications are considered equal if they have the same 

541 id and are of the same type. 

542 """ 

543 if not isinstance(other, OSSNodeMigratedNotification): 

544 return False 

545 return self.id == other.id and type(self) is type(other) 

546 

547 def __hash__(self) -> int: 

548 """ 

549 Return a hash value for the notification to allow 

550 instances to be used in sets and as dictionary keys. 

551 

552 Returns: 

553 int: Hash value based on notification type and id 

554 """ 

555 return hash((self.__class__.__name__, int(self.id))) 

556 

557 

558def _is_private_fqdn(host: str) -> bool: 

559 """ 

560 Determine if an FQDN is likely to be internal/private. 

561 

562 This uses heuristics based on RFC 952 and RFC 1123 standards: 

563 - .local domains (RFC 6762 - Multicast DNS) 

564 - .internal domains (common internal convention) 

565 - Single-label hostnames (no dots) 

566 - Common internal TLDs 

567 

568 Args: 

569 host (str): The FQDN to check 

570 

571 Returns: 

572 bool: True if the FQDN appears to be internal/private 

573 """ 

574 host_lower = host.lower().rstrip(".") 

575 

576 # Single-label hostnames (no dots) are typically internal 

577 if "." not in host_lower: 

578 return True 

579 

580 # Common internal/private domain patterns 

581 internal_patterns = [ 

582 r"\.local$", # mDNS/Bonjour domains 

583 r"\.internal$", # Common internal convention 

584 r"\.corp$", # Corporate domains 

585 r"\.lan$", # Local area network 

586 r"\.intranet$", # Intranet domains 

587 r"\.private$", # Private domains 

588 ] 

589 

590 for pattern in internal_patterns: 

591 if re.search(pattern, host_lower): 

592 return True 

593 

594 # If none of the internal patterns match, assume it's external 

595 return False 

596 

597 

598notification_types_mapping: dict[type[MaintenanceNotification], str] = { 

599 NodeMovingNotification: "MOVING", 

600 NodeMigratingNotification: "MIGRATING", 

601 NodeMigratedNotification: "MIGRATED", 

602 NodeFailingOverNotification: "FAILING_OVER", 

603 NodeFailedOverNotification: "FAILED_OVER", 

604 OSSNodeMigratingNotification: "SMIGRATING", 

605 OSSNodeMigratedNotification: "SMIGRATED", 

606} 

607 

608 

609def add_debug_log_for_notification( 

610 connection: "MaintNotificationsAbstractConnection", 

611 notification: Union[str, MaintenanceNotification], 

612): 

613 if logger.isEnabledFor(logging.DEBUG): 

614 logger.debug( 

615 f"Handling maintenance notification: {notification}, " 

616 f"with connection: {connection}, " 

617 f"{connection.extract_connection_details() if connection else 'no connection'}", 

618 ) 

619 

620 

621class MaintNotificationsConfig: 

622 """ 

623 Configuration class for maintenance notifications handling behaviour. Notifications are received through 

624 push notifications. 

625 

626 This class defines how the Redis client should react to different push notifications 

627 such as node moving, migrations, etc. in a Redis cluster. 

628 

629 """ 

630 

631 def __init__( 

632 self, 

633 enabled: Union[bool, Literal["auto"]] = "auto", 

634 proactive_reconnect: bool = True, 

635 relaxed_timeout: Optional[Number] = 10, 

636 endpoint_type: Optional[EndpointType] = None, 

637 event_dispatcher: Optional[EventDispatcherInterface] = None, 

638 ): 

639 """ 

640 Initialize a new MaintNotificationsConfig. 

641 

642 Args: 

643 enabled (bool | "auto"): Controls maintenance notifications handling behavior. 

644 - True: The CLIENT MAINT_NOTIFICATIONS command must succeed during connection setup, 

645 otherwise a ResponseError is raised. 

646 - "auto": The CLIENT MAINT_NOTIFICATIONS command is attempted but failures are 

647 gracefully handled - a warning is logged and normal operation continues. 

648 - False: Maintenance notifications are completely disabled. 

649 Defaults to "auto". 

650 proactive_reconnect (bool): Whether to proactively reconnect when a node is replaced. 

651 Defaults to True. 

652 relaxed_timeout (Number): The relaxed timeout to use for the connection during maintenance. 

653 If -1 is provided - the relaxed timeout is disabled. If None is provided - the 

654 affected operations become blocking. Defaults to 10. 

655 endpoint_type (Optional[EndpointType]): Override for the endpoint type to use in CLIENT MAINT_NOTIFICATIONS. 

656 If None, the endpoint type will be automatically determined based on the host and TLS configuration. 

657 Defaults to None. 

658 event_dispatcher (Optional[EventDispatcherInterface]): Dispatcher that receives a 

659 ``MaintenanceStartedEvent`` when a notification starts relaxing timeouts and a 

660 ``MaintenanceCompletedEvent`` when the relaxation is reverted. Dispatched 

661 synchronously from the handlers, so listeners must not block. If None, 

662 no events are dispatched. Defaults to None. 

663 

664 Raises: 

665 ValueError: If endpoint_type is provided but is not a valid endpoint type. 

666 """ 

667 self.enabled = enabled 

668 self.relaxed_timeout = relaxed_timeout 

669 self.proactive_reconnect = proactive_reconnect 

670 self.endpoint_type = endpoint_type 

671 self.event_dispatcher = event_dispatcher 

672 

673 def __repr__(self) -> str: 

674 return ( 

675 f"{self.__class__.__name__}(" 

676 f"enabled={self.enabled}, " 

677 f"proactive_reconnect={self.proactive_reconnect}, " 

678 f"relaxed_timeout={self.relaxed_timeout}, " 

679 f"endpoint_type={self.endpoint_type!r}, " 

680 f"event_dispatcher={self.event_dispatcher!r}" 

681 f")" 

682 ) 

683 

684 def is_relaxed_timeouts_enabled(self) -> bool: 

685 """ 

686 Check if the relaxed_timeout is enabled. The '-1' value is used to disable the relaxed_timeout. 

687 If relaxed_timeout is set to None, it will make the operation blocking 

688 and waiting until any response is received. 

689 

690 Returns: 

691 True if the relaxed_timeout is enabled, False otherwise. 

692 """ 

693 return self.relaxed_timeout != -1 

694 

695 def get_endpoint_type( 

696 self, 

697 host: str, 

698 connection: "MaintNotificationsAbstractConnection | AsyncMaintNotificationsAbstractConnection", 

699 ) -> EndpointType: 

700 """ 

701 Determine the appropriate endpoint type for CLIENT MAINT_NOTIFICATIONS command. 

702 

703 Logic: 

704 1. If endpoint_type is explicitly set, use it 

705 2. Otherwise, check the original host from connection.host: 

706 - If host is an IP address, use it directly to determine internal-ip vs external-ip 

707 - If host is an FQDN, get the resolved IP to determine internal-fqdn vs external-fqdn 

708 

709 Args: 

710 host: User provided hostname to analyze 

711 connection: The connection object to analyze for endpoint type determination 

712 

713 Returns: 

714 """ 

715 

716 # If endpoint_type is explicitly set, use it 

717 if self.endpoint_type is not None: 

718 return self.endpoint_type 

719 

720 # Check if the host is an IP address 

721 try: 

722 ip_addr = ipaddress.ip_address(host) 

723 # Host is an IP address - use it directly 

724 is_private = ip_addr.is_private 

725 return EndpointType.INTERNAL_IP if is_private else EndpointType.EXTERNAL_IP 

726 except ValueError: 

727 # Host is an FQDN - need to check resolved IP to determine internal vs external 

728 pass 

729 

730 # Host is an FQDN, get the resolved IP to determine if it's internal or external 

731 resolved_ip = connection.get_resolved_ip() 

732 

733 if resolved_ip: 

734 try: 

735 ip_addr = ipaddress.ip_address(resolved_ip) 

736 is_private = ip_addr.is_private 

737 # Use FQDN types since the original host was an FQDN 

738 return ( 

739 EndpointType.INTERNAL_FQDN 

740 if is_private 

741 else EndpointType.EXTERNAL_FQDN 

742 ) 

743 except ValueError: 

744 # This shouldn't happen since we got the IP from the socket, but fallback 

745 pass 

746 

747 # Final fallback: use heuristics on the FQDN itself 

748 is_private = _is_private_fqdn(host) 

749 return EndpointType.INTERNAL_FQDN if is_private else EndpointType.EXTERNAL_FQDN 

750 

751 

752_MAINTENANCE_START_NOTIFICATION_TYPES = ( 

753 NodeMigratingNotification, 

754 NodeFailingOverNotification, 

755 OSSNodeMigratingNotification, 

756) 

757_MAINTENANCE_COMPLETED_NOTIFICATION_TYPES = ( 

758 NodeMigratedNotification, 

759 NodeFailedOverNotification, 

760 OSSNodeMigratedNotification, 

761) 

762 

763 

764def _get_maintenance_notification_type( 

765 notification: MaintenanceNotification, 

766) -> Optional[int]: 

767 if notification.__class__ in _MAINTENANCE_START_NOTIFICATION_TYPES: 

768 return 1 

769 if notification.__class__ in _MAINTENANCE_COMPLETED_NOTIFICATION_TYPES: 

770 return 0 

771 return None 

772 

773 

774def _get_maintenance_notification_name( 

775 notification: MaintenanceNotification, 

776) -> str: 

777 return notification_types_mapping.get(notification.__class__, "") 

778 

779 

780def _should_skip_connection_timeout_update( 

781 maintenance_state: MaintenanceState, 

782 config: MaintNotificationsConfig, 

783) -> bool: 

784 return ( 

785 maintenance_state == MaintenanceState.MOVING 

786 or not config.is_relaxed_timeouts_enabled() 

787 ) 

788 

789 

790# How long a pooled connection's pending push notifications are read for, in 

791# total, when it is handed out. The notifications are already buffered, so a 

792# complete frame costs no wait at all; the bound is for a frame only partly 

793# received, which would otherwise block the checkout for the connection's socket 

794# timeout - or, with a blocking socket, indefinitely. 

795PENDING_PUSH_NOTIFICATIONS_READ_TIMEOUT = 1.0 

796 

797 

798def _dispatch_maintenance_event( 

799 config: MaintNotificationsConfig, 

800 event: MaintenanceEvent, 

801) -> None: 

802 """ 

803 Dispatch a maintenance event to the dispatcher configured on ``config``, 

804 if any. A failing listener is logged and never interrupts the notification 

805 handling that emitted the event: the push parser swallows exceptions 

806 silently, so letting one out would abort the remaining handling instead. 

807 """ 

808 dispatcher = config.event_dispatcher 

809 if dispatcher is None: 

810 return 

811 try: 

812 dispatcher.dispatch(event) 

813 except Exception: 

814 logger.exception(f"Error dispatching maintenance event: {event}") 

815 

816 

817def _build_moving_connection_kwargs( 

818 notification: NodeMovingNotification, 

819 config: MaintNotificationsConfig, 

820) -> dict[str, Any]: 

821 kwargs: dict[str, Any] = { 

822 "maintenance_state": MaintenanceState.MOVING, 

823 "maintenance_notification_hash": hash(notification), 

824 } 

825 if notification.new_node_host is not None: 

826 # the host is not updated if the new node host is None 

827 # this happens when the MOVING push notification does not contain 

828 # the new node host - in this case we only update the timeouts 

829 kwargs["host"] = notification.new_node_host 

830 if config.is_relaxed_timeouts_enabled(): 

831 kwargs.update( 

832 { 

833 "socket_timeout": config.relaxed_timeout, 

834 "socket_connect_timeout": config.relaxed_timeout, 

835 } 

836 ) 

837 return kwargs 

838 

839 

840def _build_moving_cleanup_connection_kwargs( 

841 connection_kwargs: Mapping[str, Any], 

842 notification_hash: int, 

843) -> Optional[dict[str, Any]]: 

844 # if the current maintenance_notification_hash in kwargs is not matching the notification 

845 # it means there has been a new moving notification after this one 

846 # and we don't need to revert the kwargs yet 

847 if connection_kwargs.get("maintenance_notification_hash") != notification_hash: 

848 return None 

849 

850 return { 

851 "maintenance_state": MaintenanceState.NONE, 

852 "maintenance_notification_hash": None, 

853 "host": connection_kwargs.get("orig_host_address"), 

854 "socket_timeout": connection_kwargs.get("orig_socket_timeout"), 

855 "socket_connect_timeout": connection_kwargs.get("orig_socket_connect_timeout"), 

856 } 

857 

858 

859class MaintNotificationsPoolHandler: 

860 def __init__( 

861 self, 

862 pool: "MaintNotificationsAbstractConnectionPool", 

863 config: MaintNotificationsConfig, 

864 ) -> None: 

865 self.pool = pool 

866 self.config = config 

867 self._processed_notifications = set() 

868 self._scheduled_timers: set[threading.Timer] = set() 

869 # The handoffs whose scheduled cleanup has not run yet 

870 self._pending_handoffs: set[NodeMovingNotification] = set() 

871 self._lock = threading.RLock() 

872 self.connection = None 

873 

874 def set_connection(self, connection: "MaintNotificationsAbstractConnection"): 

875 self.connection = connection 

876 

877 def reset_after_fork(self) -> None: 

878 """ 

879 Drop the state inherited from the parent process. 

880 

881 The lock may have been held by a parent thread at fork time, so it is 

882 replaced. The timers belong to threads that do not exist in the child: 

883 they are cancelled and the pending handoffs are cleaned up as 

884 ``close()`` does, so the child starts without the temporary host and 

885 relaxed timeouts of an active MOVING. 

886 """ 

887 self._lock = threading.RLock() 

888 self.cancel_scheduled_tasks() 

889 # A fork between update_connection_kwargs() and the handoff 

890 # registration leaves the MOVING kwargs with no handoff to clean up 

891 connection_kwargs = self.pool.connection_kwargs 

892 if connection_kwargs.get("maintenance_state") == MaintenanceState.MOVING: 

893 self.pool.update_connection_kwargs( 

894 **_build_moving_cleanup_connection_kwargs( 

895 connection_kwargs, 

896 connection_kwargs.get("maintenance_notification_hash"), 

897 ) 

898 ) 

899 self._processed_notifications.clear() 

900 

901 def get_handler_for_connection(self): 

902 # Copy all data that should be shared between connections 

903 # but each connection should have its own pool handler 

904 # since each connection can be in a different state 

905 copy = MaintNotificationsPoolHandler(self.pool, self.config) 

906 copy._processed_notifications = self._processed_notifications 

907 copy._scheduled_timers = self._scheduled_timers 

908 copy._pending_handoffs = self._pending_handoffs 

909 copy._lock = self._lock 

910 copy.connection = None 

911 return copy 

912 

913 def remove_expired_notifications(self): 

914 with self._lock: 

915 for notification in tuple(self._processed_notifications): 

916 if notification.is_expired(): 

917 self._processed_notifications.remove(notification) 

918 

919 def handle_notification(self, notification: MaintenanceNotification): 

920 self.remove_expired_notifications() 

921 

922 if isinstance(notification, NodeMovingNotification): 

923 return self.handle_node_moving_notification(notification) 

924 else: 

925 logger.error(f"Unhandled notification type: {notification}") 

926 

927 def handle_node_moving_notification(self, notification: NodeMovingNotification): 

928 if ( 

929 not self.config.proactive_reconnect 

930 and not self.config.is_relaxed_timeouts_enabled() 

931 ): 

932 return 

933 

934 with self._lock: 

935 if notification in self._processed_notifications: 

936 # nothing to do in the connection pool handling 

937 # the notification has already been handled or is expired 

938 # just return 

939 return 

940 

941 if logger.isEnabledFor(logging.DEBUG): 

942 logger.debug( 

943 f"Handling node MOVING notification: {notification}, " 

944 f"with connection: {self.connection}, connected to ip " 

945 f"{self.connection.get_resolved_ip() if self.connection else None}" 

946 ) 

947 # Get the current connected address - if any 

948 # This is the address that is being moved 

949 # and we need to handle only connections 

950 # connected to the same address 

951 moving_address_src = ( 

952 self.connection.getpeername() if self.connection else None 

953 ) 

954 

955 # Reported before the pool is relaxed: taking over a connection 

956 # under maintenance completes that connection's pair, and a 

957 # listener must see the handoff's pair open by then rather than 

958 # no relaxation at all. 

959 self._dispatch_handoff_event(MaintenanceStartedEvent, notification) 

960 

961 try: 

962 with self.pool._lock: 

963 if getattr(self.pool, "set_in_maintenance", False): 

964 # Set pool in maintenance mode - executed only if 

965 # BlockingConnectionPool is used 

966 self.pool.set_in_maintenance(True) 

967 

968 # Update maintenance state, timeout and optionally host 

969 # address connection settings for matching connections 

970 self.pool.update_connections_settings( 

971 state=MaintenanceState.MOVING, 

972 maintenance_notification_hash=hash(notification), 

973 relaxed_timeout=self.config.relaxed_timeout, 

974 host_address=notification.new_node_host, 

975 matching_address=moving_address_src, 

976 matching_pattern="connected_address", 

977 update_notification_hash=True, 

978 include_free_connections=True, 

979 ) 

980 

981 if self.config.proactive_reconnect: 

982 if notification.new_node_host is not None: 

983 self.run_proactive_reconnect(moving_address_src) 

984 else: 

985 self._schedule( 

986 notification.ttl / 2, 

987 self.run_proactive_reconnect, 

988 moving_address_src, 

989 ) 

990 

991 # Update config for new connections: 

992 # Set state to MOVING 

993 # update host 

994 # if relax timeouts are enabled - update timeouts 

995 self.pool.update_connection_kwargs( 

996 **_build_moving_connection_kwargs(notification, self.config) 

997 ) 

998 

999 if getattr(self.pool, "set_in_maintenance", False): 

1000 self.pool.set_in_maintenance(False) 

1001 

1002 self._schedule( 

1003 notification.ttl, 

1004 self.handle_node_moved_notification, 

1005 notification, 

1006 ) 

1007 self._pending_handoffs.add(notification) 

1008 except BaseException: 

1009 # The relaxation reported above was not applied, or has no 

1010 # cleanup to end it: close its pair 

1011 self._dispatch_handoff_event(MaintenanceCompletedEvent, notification) 

1012 raise 

1013 

1014 record_connection_handoff( 

1015 pool_name=get_pool_name(self.pool), 

1016 ) 

1017 

1018 self._processed_notifications.add(notification) 

1019 

1020 def _dispatch_handoff_event( 

1021 self, 

1022 event_type: Type[MaintenanceEvent], 

1023 notification: NodeMovingNotification, 

1024 ) -> None: 

1025 """ 

1026 Report a handoff's relaxation. The events report relaxed timeouts; a 

1027 handoff handled only for the proactive reconnect relaxes nothing. 

1028 """ 

1029 if self.config.is_relaxed_timeouts_enabled(): 

1030 _dispatch_maintenance_event( 

1031 self.config, 

1032 event_type( 

1033 connection_pool=self.pool, 

1034 connection=self.connection, 

1035 state=MaintenanceState.MOVING, 

1036 notification=notification, 

1037 config=self.config, 

1038 ), 

1039 ) 

1040 

1041 def _schedule(self, delay: float, callback: Callable[..., Any], *args: Any) -> None: 

1042 def run() -> None: 

1043 # Holding the lock through the callback serializes it with 

1044 # cancel_scheduled_tasks(): a timer cancelled before it gets the 

1045 # lock does nothing, and one already running finishes before 

1046 # cancellation proceeds. 

1047 with self._lock: 

1048 if timer not in self._scheduled_timers: 

1049 return 

1050 try: 

1051 callback(*args) 

1052 finally: 

1053 self._scheduled_timers.discard(timer) 

1054 

1055 timer = threading.Timer(delay, run) 

1056 with self._lock: 

1057 self._scheduled_timers.add(timer) 

1058 timer.start() 

1059 

1060 def cancel_scheduled_tasks(self) -> None: 

1061 with self._lock: 

1062 if not self._scheduled_timers and not self._pending_handoffs: 

1063 return 

1064 timers = tuple(self._scheduled_timers) 

1065 self._scheduled_timers.clear() 

1066 pending_handoffs = tuple(self._pending_handoffs) 

1067 for timer in timers: 

1068 timer.cancel() 

1069 # The pool can be reused after close(): run the cancelled MOVING 

1070 # cleanups now so the temporary host and relaxed timeouts do not 

1071 # stay in its connection kwargs, and forget the handoffs so the 

1072 # server can redeliver a still-active MOVING to the reused pool. 

1073 for notification in pending_handoffs: 

1074 # A completion listener that closes the pool re-enters this 

1075 # method and settles the remaining handoffs: skip those 

1076 if notification not in self._pending_handoffs: 

1077 continue 

1078 if not self.handle_node_moved_notification(notification): 

1079 # Closing ends the relaxation of a superseded handoff too 

1080 self._dispatch_handoff_event( 

1081 MaintenanceCompletedEvent, notification 

1082 ) 

1083 self._processed_notifications.discard(notification) 

1084 

1085 def run_proactive_reconnect(self, moving_address_src: Optional[str] = None): 

1086 """ 

1087 Run proactive reconnect for the pool. 

1088 Active connections are marked for reconnect after they complete the current command. 

1089 Inactive connections are disconnected and will be connected on next use. 

1090 """ 

1091 with self._lock: 

1092 with self.pool._lock: 

1093 # take care for the active connections in the pool 

1094 # mark them for reconnect after they complete the current command 

1095 self.pool.update_active_connections_for_reconnect( 

1096 moving_address_src=moving_address_src, 

1097 ) 

1098 # take care for the inactive connections in the pool 

1099 # delete them and create new ones 

1100 self.pool.disconnect_free_connections( 

1101 moving_address_src=moving_address_src, 

1102 ) 

1103 

1104 def handle_node_moved_notification( 

1105 self, notification: NodeMovingNotification 

1106 ) -> bool: 

1107 """ 

1108 Handle the cleanup after a node moving notification expires. 

1109 

1110 Returns whether the cleanup reverted the connection kwargs; it does not 

1111 when a newer MOVING notification has superseded this one. 

1112 """ 

1113 notification_hash = hash(notification) 

1114 

1115 with self._lock: 

1116 if logger.isEnabledFor(logging.DEBUG): 

1117 logger.debug( 

1118 f"Reverting temporary changes related to notification: {notification}, " 

1119 f"with connection: {self.connection}, connected to ip " 

1120 f"{self.connection.get_resolved_ip() if self.connection else None}" 

1121 ) 

1122 kwargs = _build_moving_cleanup_connection_kwargs( 

1123 self.pool.connection_kwargs, notification_hash 

1124 ) 

1125 if kwargs is not None: 

1126 self.pool.update_connection_kwargs(**kwargs) 

1127 

1128 with self.pool._lock: 

1129 reset_relaxed_timeout = self.config.is_relaxed_timeouts_enabled() 

1130 reset_host_address = self.config.proactive_reconnect 

1131 

1132 self.pool.update_connections_settings( 

1133 relaxed_timeout=-1, 

1134 state=MaintenanceState.NONE, 

1135 maintenance_notification_hash=None, 

1136 matching_notification_hash=notification_hash, 

1137 matching_pattern="notification_hash", 

1138 update_notification_hash=True, 

1139 reset_relaxed_timeout=reset_relaxed_timeout, 

1140 reset_host_address=reset_host_address, 

1141 include_free_connections=True, 

1142 ) 

1143 

1144 # Discarded once the state reset is done, so one that failed halfway 

1145 # is run again by a retried close(), and before the listeners run, 

1146 # so a listener closing the pool does not run it a second time 

1147 self._pending_handoffs.discard(notification) 

1148 # A newer MOVING notification has superseded this one when the 

1149 # kwargs were not reverted: the pool stays relaxed until it expires. 

1150 if kwargs is not None: 

1151 self._dispatch_handoff_event(MaintenanceCompletedEvent, notification) 

1152 return kwargs is not None 

1153 

1154 

1155class MaintNotificationsConnectionHandler: 

1156 # 1 = "starting maintenance" notifications, 0 = "completed maintenance" notifications 

1157 _NOTIFICATION_TYPES: dict[type["MaintenanceNotification"], int] = { 

1158 NodeMigratingNotification: 1, 

1159 NodeFailingOverNotification: 1, 

1160 OSSNodeMigratingNotification: 1, 

1161 NodeMigratedNotification: 0, 

1162 NodeFailedOverNotification: 0, 

1163 OSSNodeMigratedNotification: 0, 

1164 } 

1165 

1166 def __init__( 

1167 self, 

1168 connection: "MaintNotificationsAbstractConnection", 

1169 config: MaintNotificationsConfig, 

1170 ) -> None: 

1171 self.connection = connection 

1172 self.config = config 

1173 

1174 def _get_pool(self) -> Optional["MaintNotificationsAbstractConnectionPool"]: 

1175 """ 

1176 Get the pool from the connection's pool handler, or None for 

1177 standalone connections without a pool. 

1178 """ 

1179 pool_handler = getattr( 

1180 self.connection, "_maint_notifications_pool_handler", None 

1181 ) 

1182 if pool_handler: 

1183 return getattr(pool_handler, "pool", None) 

1184 return None 

1185 

1186 def _get_pool_name(self) -> str: 

1187 """ 

1188 Get the pool name from the connection's pool handler. 

1189 Falls back to connection representation if pool is not available. 

1190 """ 

1191 pool = self._get_pool() 

1192 if pool: 

1193 return get_pool_name(pool) 

1194 # Fallback for standalone connections without a pool 

1195 return repr(self.connection) 

1196 

1197 def handle_notification(self, notification: MaintenanceNotification): 

1198 # get the notification type by checking its class 

1199 # 1 for start, 0 for end notification type, None for unknown 

1200 notification_type = _get_maintenance_notification_type(notification) 

1201 maint_notification = _get_maintenance_notification_name(notification) 

1202 

1203 record_maint_notification_count( 

1204 server_address=self.connection.host, 

1205 server_port=self.connection.port, 

1206 network_peer_address=self.connection.host, 

1207 network_peer_port=self.connection.port, 

1208 maint_notification=maint_notification, 

1209 ) 

1210 

1211 if notification_type is None: 

1212 logger.error(f"Unhandled notification type: {notification}") 

1213 return 

1214 

1215 if notification_type: 

1216 self.handle_maintenance_start_notification( 

1217 MaintenanceState.MAINTENANCE, notification 

1218 ) 

1219 else: 

1220 self.handle_maintenance_completed_notification(notification=notification) 

1221 

1222 def handle_maintenance_start_notification( 

1223 self, maintenance_state: MaintenanceState, notification: MaintenanceNotification 

1224 ): 

1225 add_debug_log_for_notification(self.connection, notification) 

1226 

1227 if _should_skip_connection_timeout_update( 

1228 self.connection.maintenance_state, self.config 

1229 ): 

1230 return 

1231 

1232 self.connection.maintenance_state = maintenance_state 

1233 self.connection.set_tmp_settings( 

1234 tmp_relaxed_timeout=self.config.relaxed_timeout 

1235 ) 

1236 # extend the timeout for all created connections 

1237 self.connection.update_current_socket_timeout(self.config.relaxed_timeout) 

1238 if isinstance(notification, OSSNodeMigratingNotification): 

1239 # add the notification id to the set of processed start maint notifications 

1240 # this is used to skip the unrelaxing of the timeouts if we have received more than 

1241 # one start notification before the final end notification 

1242 self.connection.add_maint_start_notification(notification.id) 

1243 

1244 maint_notification = _get_maintenance_notification_name(notification) 

1245 record_connection_relaxed_timeout( 

1246 connection_name=self._get_pool_name(), 

1247 maint_notification=maint_notification, 

1248 relaxed=True, 

1249 ) 

1250 

1251 _dispatch_maintenance_event( 

1252 self.config, 

1253 MaintenanceStartedEvent( 

1254 connection_pool=self._get_pool(), 

1255 connection=self.connection, 

1256 state=maintenance_state, 

1257 notification=notification, 

1258 config=self.config, 

1259 ), 

1260 ) 

1261 

1262 def handle_maintenance_completed_notification(self, **kwargs: Any) -> None: 

1263 # Only reset timeouts if state is not MOVING and relaxed timeouts are enabled 

1264 if _should_skip_connection_timeout_update( 

1265 self.connection.maintenance_state, self.config 

1266 ): 

1267 return 

1268 

1269 # A completion can reach a connection whose start went to another one, 

1270 # or none at all; only a connection that was relaxed has a start event 

1271 # to pair the completion with 

1272 was_relaxed = self.connection.maintenance_state == MaintenanceState.MAINTENANCE 

1273 

1274 notification = None 

1275 if kwargs.get("notification"): 

1276 notification = kwargs["notification"] 

1277 add_debug_log_for_notification( 

1278 self.connection, notification if notification else "MAINTENANCE_COMPLETED" 

1279 ) 

1280 self.connection.reset_tmp_settings(reset_relaxed_timeout=True) 

1281 # Maintenance completed - reset the connection 

1282 # timeouts by providing -1 as the relaxed timeout 

1283 self.connection.update_current_socket_timeout(-1) 

1284 self.connection.maintenance_state = MaintenanceState.NONE 

1285 # reset the sets that keep track of received start maint 

1286 # notifications and skipped end maint notifications 

1287 self.connection.reset_received_notifications() 

1288 

1289 if notification: 

1290 maint_notification = _get_maintenance_notification_name(notification) 

1291 record_connection_relaxed_timeout( 

1292 connection_name=self._get_pool_name(), 

1293 maint_notification=maint_notification, 

1294 relaxed=False, 

1295 ) 

1296 

1297 if was_relaxed: 

1298 _dispatch_maintenance_event( 

1299 self.config, 

1300 MaintenanceCompletedEvent( 

1301 connection_pool=self._get_pool(), 

1302 connection=self.connection, 

1303 state=MaintenanceState.MAINTENANCE, 

1304 notification=notification, 

1305 config=self.config, 

1306 ), 

1307 ) 

1308 

1309 

1310class OSSMaintNotificationsHandler: 

1311 def __init__( 

1312 self, 

1313 cluster_client: "MaintNotificationsAbstractRedisCluster", 

1314 config: MaintNotificationsConfig, 

1315 ) -> None: 

1316 self.cluster_client = cluster_client 

1317 self.config = config 

1318 self._processed_notifications = set() 

1319 self._in_progress = set() 

1320 self._lock = threading.RLock() 

1321 

1322 def remove_expired_notifications(self): 

1323 with self._lock: 

1324 for notification in tuple(self._processed_notifications): 

1325 if notification.is_expired(): 

1326 self._processed_notifications.remove(notification) 

1327 

1328 def handle_notification(self, notification: MaintenanceNotification): 

1329 if isinstance(notification, OSSNodeMigratedNotification): 

1330 self.handle_oss_maintenance_completed_notification(notification) 

1331 else: 

1332 logger.error(f"Unhandled notification type: {notification}") 

1333 

1334 def handle_oss_maintenance_completed_notification( 

1335 self, notification: OSSNodeMigratedNotification 

1336 ): 

1337 self.remove_expired_notifications() 

1338 

1339 with self._lock: 

1340 if ( 

1341 notification in self._in_progress 

1342 or notification in self._processed_notifications 

1343 ): 

1344 # we are already handling this notification or it has already been processed 

1345 # we should skip in_progress notification since when we reinitialize the cluster 

1346 # we execute a CLUSTER SLOTS command that can use a different connection 

1347 # that has also has the notification and we don't want to 

1348 # process the same notification twice 

1349 # 

1350 # This cheap pre-check runs under _lock alone, before the 

1351 # topology refresh lock below. The server delivers the same 

1352 # SMIGRATED on every connection, so the vast majority of 

1353 # arrivals land here; making them wait for an in-flight CLUSTER 

1354 # SLOTS round trip just to discard a notification would stall 

1355 # arbitrary command threads inside read_response. 

1356 return 

1357 

1358 # Lock order: _initialization_lock BEFORE _lock. initialize() below runs a 

1359 # CLUSTER SLOTS round trip while holding _initialization_lock, and the 

1360 # response can carry another SMIGRATED push that is handled inline on that 

1361 # thread and needs _lock - so a thread holding _lock must never wait for 

1362 # _initialization_lock. See the _initialization_lock comment in 

1363 # NodesManager.__init__ for the full ordering rule. 

1364 with self.cluster_client.nodes_manager._initialization_lock, self._lock: 

1365 if ( 

1366 notification in self._in_progress 

1367 or notification in self._processed_notifications 

1368 ): 

1369 # Re-check now that both locks are held: another thread may have 

1370 # handled the notification while we waited for the refresh lock. 

1371 return 

1372 

1373 if logger.isEnabledFor(logging.DEBUG): 

1374 logger.debug(f"Handling SMIGRATED notification: {notification}") 

1375 self._in_progress.add(notification) 

1376 

1377 try: 

1378 # Extract the information about the src and destination nodes that are affected 

1379 # by the maintenance. nodes_to_slots_mapping structure: 

1380 # { 

1381 # "src_host:port": [ 

1382 # {"dest_host:port": "slot_range"}, 

1383 # ... 

1384 # ], 

1385 # ... 

1386 # } 

1387 additional_startup_nodes_info = [] 

1388 affected_nodes = set() 

1389 for ( 

1390 src_address, 

1391 dest_mappings, 

1392 ) in notification.nodes_to_slots_mapping.items(): 

1393 src_host, src_port = src_address.rsplit(":", 1) 

1394 src_node = self.cluster_client.nodes_manager.get_node( 

1395 host=src_host, port=int(src_port) 

1396 ) 

1397 if src_node is not None: 

1398 affected_nodes.add(src_node) 

1399 

1400 for dest_mapping in dest_mappings: 

1401 for dest_address in dest_mapping.keys(): 

1402 dest_host, dest_port = dest_address.rsplit(":", 1) 

1403 additional_startup_nodes_info.append( 

1404 (dest_host, int(dest_port)) 

1405 ) 

1406 

1407 # Updates the cluster slots cache with the new slots mapping 

1408 # This will also update the nodes cache with the new nodes mapping 

1409 self.cluster_client.nodes_manager.initialize( 

1410 disconnect_startup_nodes_pools=False, 

1411 additional_startup_nodes_info=additional_startup_nodes_info, 

1412 ) 

1413 

1414 all_nodes = set(affected_nodes) 

1415 all_nodes = all_nodes.union( 

1416 self.cluster_client.nodes_manager.nodes_cache.values() 

1417 ) 

1418 

1419 for current_node in all_nodes: 

1420 if current_node.redis_connection is None: 

1421 continue 

1422 with current_node.redis_connection.connection_pool._lock: 

1423 handoff_recorded = False 

1424 if current_node in affected_nodes: 

1425 # mark for reconnect all in use connections to the node - this will force them to 

1426 # disconnect after they complete their current commands 

1427 # Some of them might be used by sub sub and we don't know which ones - so we disconnect 

1428 # all in flight connections after they are done with current command execution 

1429 for conn in current_node.redis_connection.connection_pool._get_in_use_connections(): 

1430 add_debug_log_for_notification( 

1431 conn, "SMIGRATED - mark for reconnect" 

1432 ) 

1433 conn.mark_for_reconnect() 

1434 

1435 record_connection_handoff( 

1436 pool_name=get_pool_name( 

1437 current_node.redis_connection.connection_pool 

1438 ) 

1439 ) 

1440 handoff_recorded = True 

1441 else: 

1442 if logger.isEnabledFor(logging.DEBUG): 

1443 logger.debug( 

1444 f"SMIGRATED: Node {current_node.name} not affected by maintenance, " 

1445 f"skipping mark for reconnect" 

1446 ) 

1447 

1448 if ( 

1449 current_node 

1450 not in self.cluster_client.nodes_manager.nodes_cache.values() 

1451 ): 

1452 # disconnect all free connections to the node - this node will be dropped 

1453 # from the cluster, so we don't need to revert the timeouts 

1454 for conn in current_node.redis_connection.connection_pool._get_free_connections(): 

1455 conn.disconnect() 

1456 

1457 # Only record handoff if not already recorded for this node 

1458 if not handoff_recorded: 

1459 record_connection_handoff( 

1460 pool_name=get_pool_name( 

1461 current_node.redis_connection.connection_pool 

1462 ) 

1463 ) 

1464 

1465 # mark the notification as processed 

1466 self._processed_notifications.add(notification) 

1467 finally: 

1468 # Release the in-progress reservation. On success the notification 

1469 # is also in _processed_notifications (so it won't be re-handled); 

1470 # on failure it is not, allowing a later redelivery to retry. 

1471 self._in_progress.discard(notification)