Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/redis/asyncio/sentinel.py: 25%

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

204 statements  

1import asyncio 

2import random 

3import weakref 

4from typing import ( 

5 Any, 

6 AsyncIterator, 

7 Iterable, 

8 Mapping, 

9 Optional, 

10 Sequence, 

11 Tuple, 

12 Type, 

13) 

14 

15from redis.asyncio.client import Redis 

16from redis.asyncio.connection import ( 

17 Connection, 

18 ConnectionPool, 

19 EncodableT, 

20 SSLConnection, 

21) 

22from redis.asyncio.retry import Retry 

23from redis.backoff import NoBackoff 

24from redis.commands import AsyncSentinelCommands 

25from redis.exceptions import ( 

26 ConnectionError, 

27 ReadOnlyError, 

28 ResponseError, 

29 TimeoutError, 

30) 

31from redis.sentinel import DEMOTED_MASTER_UNBLOCKED_ERROR 

32 

33 

34class MasterNotFoundError(ConnectionError): 

35 pass 

36 

37 

38class SlaveNotFoundError(ConnectionError): 

39 pass 

40 

41 

42ReplicaNotFoundError = SlaveNotFoundError 

43 

44 

45class SentinelManagedConnection(Connection): 

46 def __init__(self, **kwargs): 

47 self.connection_pool = kwargs.pop("connection_pool") 

48 super().__init__(**kwargs) 

49 

50 def __repr__(self): 

51 s = f"<{self.__class__.__module__}.{self.__class__.__name__}" 

52 if self.host: 

53 host_info = f",host={self.host},port={self.port}" 

54 s += host_info 

55 return s + ")>" 

56 

57 async def connect_to(self, address): 

58 self.host, self.port = address 

59 await self.connect_check_health( 

60 check_health=self.connection_pool.check_connection, 

61 retry_socket_connect=False, 

62 ) 

63 

64 async def _connect_retry(self): 

65 if self._reader: 

66 return # already connected 

67 if self.connection_pool.is_master: 

68 await self.connect_to(await self.connection_pool.get_master_address()) 

69 else: 

70 async for slave in self.connection_pool.rotate_slaves(): 

71 try: 

72 return await self.connect_to(slave) 

73 except ConnectionError: 

74 continue 

75 raise SlaveNotFoundError # Never be here 

76 

77 async def connect(self): 

78 return await self.retry.call_with_retry( 

79 self._connect_retry, 

80 lambda error: asyncio.sleep(0), 

81 ) 

82 

83 async def read_response( 

84 self, 

85 disable_decoding: bool = False, 

86 timeout: Optional[float] = None, 

87 *, 

88 disconnect_on_error: Optional[float] = True, 

89 push_request: Optional[bool] = False, 

90 ): 

91 try: 

92 return await super().read_response( 

93 disable_decoding=disable_decoding, 

94 timeout=timeout, 

95 disconnect_on_error=disconnect_on_error, 

96 push_request=push_request, 

97 ) 

98 except ReadOnlyError: 

99 if self.connection_pool.is_master: 

100 # When talking to a master, a ReadOnlyError when likely 

101 # indicates that the previous master that we're still connected 

102 # to has been demoted to a slave and there's a new master. 

103 # calling disconnect will force the connection to re-query 

104 # sentinel during the next connect() attempt. 

105 await self.disconnect() 

106 raise ConnectionError("The previous master is now a slave") 

107 raise 

108 except ResponseError as e: 

109 if self.connection_pool.is_master and str(e).startswith( 

110 DEMOTED_MASTER_UNBLOCKED_ERROR 

111 ): 

112 # A master that turns into a replica unblocks every client 

113 # waiting on a blocking command (BLPOP, BRPOP, XREAD...) with 

114 # this error and closes the connection, as when Sentinel runs 

115 # a coordinated failover. Same meaning as the ReadOnlyError 

116 # above: re-query Sentinel on the next connect() attempt. 

117 await self.disconnect() 

118 raise ConnectionError("The previous master is now a slave") 

119 raise 

120 

121 

122class SentinelManagedSSLConnection(SentinelManagedConnection, SSLConnection): 

123 pass 

124 

125 

126class SentinelConnectionPool(ConnectionPool): 

127 """ 

128 Sentinel backed connection pool. 

129 

130 If ``check_connection`` flag is set to True, SentinelManagedConnection 

131 sends a PING command right after establishing the connection. 

132 """ 

133 

134 def __init__(self, service_name, sentinel_manager, **kwargs): 

135 kwargs["connection_class"] = kwargs.get( 

136 "connection_class", 

137 ( 

138 SentinelManagedSSLConnection 

139 if kwargs.pop("ssl", False) 

140 else SentinelManagedConnection 

141 ), 

142 ) 

143 self.is_master = kwargs.pop("is_master", True) 

144 self.check_connection = kwargs.pop("check_connection", False) 

145 super().__init__(**kwargs) 

146 self.connection_kwargs["connection_pool"] = weakref.proxy(self) 

147 self.service_name = service_name 

148 self.sentinel_manager = sentinel_manager 

149 self.master_address = None 

150 self.slave_rr_counter = None 

151 

152 def __repr__(self): 

153 return ( 

154 f"<{self.__class__.__module__}.{self.__class__.__name__}" 

155 f"(service={self.service_name}({self.is_master and 'master' or 'slave'}))>" 

156 ) 

157 

158 def reset(self): 

159 super().reset() 

160 self.master_address = None 

161 self.slave_rr_counter = None 

162 

163 def owns_connection(self, connection: Connection): 

164 return not self.is_master or ( 

165 self.is_master and self.master_address == (connection.host, connection.port) 

166 ) 

167 

168 async def release(self, connection: Connection): 

169 if not self.owns_connection(connection): 

170 # Still connected to a master that Sentinel no longer reports. It was 

171 # in use when get_master_address() disconnected the idle connections, 

172 # so disconnect it now and let its next use ask Sentinel again. 

173 connection.mark_for_reconnect() 

174 await super().release(connection) 

175 

176 async def get_master_address(self): 

177 master_address = await self.sentinel_manager.discover_master(self.service_name) 

178 if self.is_master: 

179 if self.master_address != master_address: 

180 self.master_address = master_address 

181 # disconnect any idle connections so that they reconnect 

182 # to the new master the next time that they are used. 

183 await self.disconnect(inuse_connections=False) 

184 return master_address 

185 

186 async def rotate_slaves(self) -> AsyncIterator: 

187 """Round-robin slave balancer""" 

188 slaves = await self.sentinel_manager.discover_slaves(self.service_name) 

189 if slaves: 

190 if self.slave_rr_counter is None: 

191 self.slave_rr_counter = random.randint(0, len(slaves) - 1) 

192 for _ in range(len(slaves)): 

193 self.slave_rr_counter = (self.slave_rr_counter + 1) % len(slaves) 

194 slave = slaves[self.slave_rr_counter] 

195 yield slave 

196 # Fallback to the master connection 

197 try: 

198 yield await self.get_master_address() 

199 except MasterNotFoundError: 

200 pass 

201 raise SlaveNotFoundError(f"No slave found for {self.service_name!r}") 

202 

203 def rotate_replicas(self) -> AsyncIterator: 

204 """Round-robin replica balancer. 

205 

206 This is an alias for :py:meth:`rotate_slaves`, 

207 using the preferred Redis 5.0+ terminology. 

208 """ 

209 return self.rotate_slaves() 

210 

211 

212class Sentinel(AsyncSentinelCommands): 

213 """ 

214 Redis Sentinel cluster client 

215 

216 >>> from redis.sentinel import Sentinel 

217 >>> sentinel = Sentinel([('localhost', 26379)], socket_timeout=0.1) 

218 >>> master = sentinel.master_for('mymaster', socket_timeout=0.1) 

219 >>> await master.set('foo', 'bar') 

220 >>> slave = sentinel.slave_for('mymaster', socket_timeout=0.1) 

221 >>> await slave.get('foo') 

222 b'bar' 

223 

224 ``sentinels`` is a list of sentinel nodes. Each node is represented by 

225 a pair (hostname, port). 

226 

227 ``min_other_sentinels`` defined a minimum number of peers for a sentinel. 

228 When querying a sentinel, if it doesn't meet this threshold, responses 

229 from that sentinel won't be considered valid. 

230 

231 ``sentinel_kwargs`` is a dictionary of connection arguments used when 

232 connecting to sentinel instances. Any argument that can be passed to 

233 a normal Redis connection can be specified here. If ``sentinel_kwargs`` is 

234 not specified, any socket_timeout and socket_keepalive options specified 

235 in ``connection_kwargs`` will be used. Unless ``sentinel_kwargs`` contains 

236 ``retry``, the sentinel clients don't retry a failed command (or retry it 

237 once when ``retry_on_timeout`` or ``retry_on_error`` is set), since master 

238 discovery already moves on to the next sentinel; pass a ``Retry`` object 

239 as ``retry`` to use another policy. 

240 

241 ``connection_kwargs`` are keyword arguments that will be used when 

242 establishing a connection to a Redis server. 

243 """ 

244 

245 def __init__( 

246 self, 

247 sentinels: Iterable[Tuple[str, int]], 

248 min_other_sentinels: int = 0, 

249 sentinel_kwargs: Mapping[str, Any] | None = None, 

250 force_master_ip: str | None = None, 

251 **connection_kwargs: Any, 

252 ) -> None: 

253 # if sentinel_kwargs isn't defined, use the socket_* options from 

254 # connection_kwargs 

255 if sentinel_kwargs is None: 

256 sentinel_kwargs = { 

257 k: v for k, v in connection_kwargs.items() if k.startswith("socket_") 

258 } 

259 else: 

260 sentinel_kwargs = dict(sentinel_kwargs) 

261 if "retry" not in sentinel_kwargs: 

262 # Master discovery already moves on to the next sentinel when one 

263 # fails, so the client's default retry policy would only multiply 

264 # the timeout of an unreachable sentinel. Keep the connection-level 

265 # behaviour instead: no retries, or a single one when 

266 # retry_on_timeout or retry_on_error is set. 

267 retry_once = sentinel_kwargs.get("retry_on_timeout") or sentinel_kwargs.get( 

268 "retry_on_error" 

269 ) 

270 sentinel_kwargs["retry"] = Retry(NoBackoff(), 1 if retry_once else 0) 

271 self.sentinel_kwargs = sentinel_kwargs 

272 

273 self.sentinels = [ 

274 Redis(host=hostname, port=port, **self.sentinel_kwargs) 

275 for hostname, port in sentinels 

276 ] 

277 self.min_other_sentinels = min_other_sentinels 

278 self.connection_kwargs = connection_kwargs 

279 self._force_master_ip = force_master_ip 

280 

281 async def execute_command(self, *args, **kwargs): 

282 """ 

283 Execute Sentinel command in sentinel nodes. 

284 once - If set to True, then execute the resulting command on a single 

285 node at random, rather than across the entire sentinel cluster. 

286 """ 

287 once = bool(kwargs.pop("once", False)) 

288 

289 # Check if command is supposed to return the original 

290 # responses instead of boolean value. 

291 return_responses = bool(kwargs.pop("return_responses", False)) 

292 

293 if once: 

294 response = await random.choice(self.sentinels).execute_command( 

295 *args, **kwargs 

296 ) 

297 if return_responses: 

298 return [response] 

299 else: 

300 return True if response else False 

301 

302 tasks = [ 

303 asyncio.Task(sentinel.execute_command(*args, **kwargs)) 

304 for sentinel in self.sentinels 

305 ] 

306 responses = await asyncio.gather(*tasks) 

307 

308 if return_responses: 

309 return responses 

310 

311 return all(responses) 

312 

313 def __repr__(self): 

314 sentinel_addresses = [] 

315 for sentinel in self.sentinels: 

316 sentinel_addresses.append( 

317 f"{sentinel.connection_pool.connection_kwargs['host']}:" 

318 f"{sentinel.connection_pool.connection_kwargs['port']}" 

319 ) 

320 return ( 

321 f"<{self.__class__}.{self.__class__.__name__}" 

322 f"(sentinels=[{','.join(sentinel_addresses)}])>" 

323 ) 

324 

325 async def aclose(self) -> None: 

326 """ 

327 Close all sentinel clients created by this Sentinel and their 

328 connection pools. 

329 

330 Each client is closed independently: if one raises, the remaining 

331 clients are still closed and the first error is re-raised afterwards. 

332 

333 Clients returned by ``master_for``/``slave_for`` are owned by the 

334 caller and are not closed here. 

335 """ 

336 resp = await asyncio.gather( 

337 *(sentinel.aclose() for sentinel in self.sentinels), 

338 return_exceptions=True, 

339 ) 

340 exc = next((r for r in resp if isinstance(r, BaseException)), None) 

341 if exc: 

342 raise exc 

343 

344 async def __aenter__(self) -> "Sentinel": 

345 return self 

346 

347 async def __aexit__(self, exc_type, exc_value, traceback) -> None: 

348 await self.aclose() 

349 

350 def check_master_state(self, state: dict, service_name: str) -> bool: 

351 if not state["is_master"] or state["is_sdown"] or state["is_odown"]: 

352 return False 

353 # Check if our sentinel doesn't see other nodes 

354 if state["num-other-sentinels"] < self.min_other_sentinels: 

355 return False 

356 return True 

357 

358 async def discover_master(self, service_name: str): 

359 """ 

360 Asks sentinel servers for the Redis master's address corresponding 

361 to the service labeled ``service_name``. 

362 

363 Returns a pair (address, port) or raises MasterNotFoundError if no 

364 master is found. 

365 """ 

366 collected_errors = list() 

367 for sentinel_no, sentinel in enumerate(self.sentinels): 

368 try: 

369 masters = await sentinel.sentinel_masters() 

370 except (ConnectionError, ResponseError, TimeoutError) as e: 

371 # repr() names only the class; str() keeps the reply text 

372 error = f"{sentinel} - {e!r}" 

373 if str(e): 

374 error += f": {e}" 

375 collected_errors.append(error) 

376 continue 

377 state = masters.get(service_name) 

378 if state and self.check_master_state(state, service_name): 

379 # Put this sentinel at the top of the list 

380 self.sentinels[0], self.sentinels[sentinel_no] = ( 

381 sentinel, 

382 self.sentinels[0], 

383 ) 

384 

385 ip = ( 

386 self._force_master_ip 

387 if self._force_master_ip is not None 

388 else state["ip"] 

389 ) 

390 return ip, state["port"] 

391 

392 error_info = "" 

393 if len(collected_errors) > 0: 

394 error_info = f" : {', '.join(collected_errors)}" 

395 raise MasterNotFoundError(f"No master found for {service_name!r}{error_info}") 

396 

397 def filter_slaves( 

398 self, slaves: Iterable[Mapping] 

399 ) -> Sequence[Tuple[EncodableT, EncodableT]]: 

400 """Remove slaves that are in an ODOWN or SDOWN state""" 

401 slaves_alive = [] 

402 for slave in slaves: 

403 if slave["is_odown"] or slave["is_sdown"]: 

404 continue 

405 slaves_alive.append((slave["ip"], slave["port"])) 

406 return slaves_alive 

407 

408 def filter_replicas( 

409 self, replicas: Iterable[Mapping] 

410 ) -> Sequence[Tuple[EncodableT, EncodableT]]: 

411 """Remove replicas that are in an ODOWN or SDOWN state. 

412 

413 This is an alias for :py:meth:`filter_slaves`, 

414 using the preferred Redis 5.0+ terminology. 

415 """ 

416 return self.filter_slaves(replicas) 

417 

418 async def discover_slaves( 

419 self, service_name: str 

420 ) -> Sequence[Tuple[EncodableT, EncodableT]]: 

421 """Returns a list of alive slaves for service ``service_name``""" 

422 for sentinel in self.sentinels: 

423 try: 

424 slaves = await sentinel.sentinel_slaves(service_name) 

425 except (ConnectionError, ResponseError, TimeoutError): 

426 continue 

427 slaves = self.filter_slaves(slaves) 

428 if slaves: 

429 return slaves 

430 return [] 

431 

432 async def discover_replicas( 

433 self, service_name: str 

434 ) -> Sequence[Tuple[EncodableT, EncodableT]]: 

435 """Returns a list of alive replicas for service ``service_name``. 

436 

437 This is an alias for :py:meth:`discover_slaves`, 

438 using the preferred Redis 5.0+ terminology. 

439 """ 

440 return await self.discover_slaves(service_name) 

441 

442 def master_for( 

443 self, 

444 service_name: str, 

445 redis_class: Type[Redis] = Redis, 

446 connection_pool_class: Type[SentinelConnectionPool] = SentinelConnectionPool, 

447 **kwargs, 

448 ): 

449 """ 

450 Returns a redis client instance for the ``service_name`` master. 

451 Sentinel client will detect failover and reconnect Redis clients 

452 automatically. 

453 

454 A :py:class:`~redis.sentinel.SentinelConnectionPool` class is 

455 used to retrieve the master's address before establishing a new 

456 connection. 

457 

458 NOTE: If the master's address has changed, any cached connections to 

459 the old master are closed. 

460 

461 By default clients will be a :py:class:`~redis.Redis` instance. 

462 Specify a different class to the ``redis_class`` argument if you 

463 desire something different. 

464 

465 The ``connection_pool_class`` specifies the connection pool to 

466 use. The :py:class:`~redis.sentinel.SentinelConnectionPool` 

467 will be used by default. 

468 

469 All other keyword arguments are merged with any connection_kwargs 

470 passed to this class and passed to the connection pool as keyword 

471 arguments to be used to initialize Redis connections. 

472 

473 HIMPORT note: the returned client exposes the HIMPORT command family 

474 (``himport_prepare``, ``himport_set``, ``himport_discard``, 

475 ``himport_discard_all``). Fieldsets are declared at runtime with 

476 ``himport_prepare`` on the client and live on that client's shared registry, 

477 so they survive Sentinel failover automatically: the pool re-points to the 

478 new master and the fieldset is re-prepared lazily on the next 

479 ``himport_set``. Each call to the current command returns a *new* client with its *own* empty 

480 registry, so call ``himport_prepare`` on the long-lived client you reuse 

481 rather than creating a fresh one per operation; otherwise ``himport_set`` 

482 fails with ``no such fieldset``. (``himport_set`` is a write and is served by 

483 the master.) 

484 """ 

485 kwargs["is_master"] = True 

486 connection_kwargs = dict(self.connection_kwargs) 

487 connection_kwargs.update(kwargs) 

488 

489 connection_pool = connection_pool_class(service_name, self, **connection_kwargs) 

490 # The Redis object "owns" the pool 

491 return redis_class.from_pool(connection_pool) 

492 

493 def slave_for( 

494 self, 

495 service_name: str, 

496 redis_class: Type[Redis] = Redis, 

497 connection_pool_class: Type[SentinelConnectionPool] = SentinelConnectionPool, 

498 **kwargs, 

499 ): 

500 """ 

501 Returns redis client instance for the ``service_name`` slave(s). 

502 

503 A SentinelConnectionPool class is used to retrieve the slave's 

504 address before establishing a new connection. 

505 

506 By default clients will be a :py:class:`~redis.Redis` instance. 

507 Specify a different class to the ``redis_class`` argument if you 

508 desire something different. 

509 

510 The ``connection_pool_class`` specifies the connection pool to use. 

511 The SentinelConnectionPool will be used by default. 

512 

513 All other keyword arguments are merged with any connection_kwargs 

514 passed to this class and passed to the connection pool as keyword 

515 arguments to be used to initialize Redis connections. 

516 

517 HIMPORT note: the returned client exposes the HIMPORT command family 

518 (``himport_prepare``, ``himport_set``, ``himport_discard``, 

519 ``himport_discard_all``). Fieldsets are declared at runtime with 

520 ``himport_prepare`` on the client and live on that client's shared registry, 

521 so they survive Sentinel failover automatically: the pool re-points to the 

522 new master and the fieldset is re-prepared lazily on the next 

523 ``himport_set``. Each call to the current command returns a *new* client with its *own* empty 

524 registry, so call ``himport_prepare`` on the long-lived client you reuse 

525 rather than creating a fresh one per operation; otherwise ``himport_set`` 

526 fails with ``no such fieldset``. (``himport_set`` is a write and is served by 

527 the master.) 

528 """ 

529 kwargs["is_master"] = False 

530 connection_kwargs = dict(self.connection_kwargs) 

531 connection_kwargs.update(kwargs) 

532 

533 connection_pool = connection_pool_class(service_name, self, **connection_kwargs) 

534 # The Redis object "owns" the pool 

535 return redis_class.from_pool(connection_pool) 

536 

537 def replica_for( 

538 self, 

539 service_name: str, 

540 redis_class: Type[Redis] = Redis, 

541 connection_pool_class: Type[SentinelConnectionPool] = SentinelConnectionPool, 

542 **kwargs, 

543 ): 

544 """ 

545 Returns redis client instance for the ``service_name`` replica(s). 

546 

547 This is an alias for :py:meth:`slave_for`, 

548 using the preferred Redis 5.0+ terminology. 

549 """ 

550 return self.slave_for( 

551 service_name, 

552 redis_class=redis_class, 

553 connection_pool_class=connection_pool_class, 

554 **kwargs, 

555 )