Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/redis/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

228 statements  

1import random 

2import weakref 

3from typing import Any, Iterable, Mapping, Optional, Sequence, Tuple, Type, Union 

4 

5from redis.backoff import NoBackoff 

6from redis.client import Redis 

7from redis.commands import SentinelCommands 

8from redis.connection import Connection, ConnectionPool, SSLConnection 

9from redis.exceptions import ( 

10 ConnectionError, 

11 ReadOnlyError, 

12 ResponseError, 

13 TimeoutError, 

14) 

15from redis.retry import Retry 

16from redis.typing import EncodableT 

17from redis.utils import SENTINEL 

18 

19DEMOTED_MASTER_UNBLOCKED_ERROR = ( 

20 "UNBLOCKED force unblock from blocking operation, instance state changed" 

21) 

22 

23 

24class MasterNotFoundError(ConnectionError): 

25 pass 

26 

27 

28class SlaveNotFoundError(ConnectionError): 

29 pass 

30 

31 

32ReplicaNotFoundError = SlaveNotFoundError 

33 

34 

35class SentinelManagedConnection(Connection): 

36 def __init__(self, **kwargs): 

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

38 super().__init__(**kwargs) 

39 

40 def __repr__(self): 

41 pool = self.connection_pool 

42 s = ( 

43 f"<{type(self).__module__}.{type(self).__name__}" 

44 f"(service={pool.service_name}%s)>" 

45 ) 

46 if self.host: 

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

48 s = s % host_info 

49 return s 

50 

51 def connect_to(self, address): 

52 self.host, self.port = address 

53 

54 self.connect_check_health( 

55 check_health=self.connection_pool.check_connection, 

56 retry_socket_connect=False, 

57 ) 

58 

59 def _connect_retry(self): 

60 if self._sock: 

61 return # already connected 

62 if self.connection_pool.is_master: 

63 self.connect_to(self.connection_pool.get_master_address()) 

64 else: 

65 for slave in self.connection_pool.rotate_slaves(): 

66 try: 

67 return self.connect_to(slave) 

68 except ConnectionError: 

69 continue 

70 raise SlaveNotFoundError # Never be here 

71 

72 def connect(self): 

73 return self.retry.call_with_retry(self._connect_retry, lambda error: None) 

74 

75 def read_response( 

76 self, 

77 disable_decoding=False, 

78 *, 

79 timeout: Union[float, object] = SENTINEL, 

80 disconnect_on_error: Optional[bool] = True, 

81 push_request: Optional[bool] = False, 

82 ): 

83 try: 

84 return super().read_response( 

85 disable_decoding=disable_decoding, 

86 timeout=timeout, 

87 disconnect_on_error=disconnect_on_error, 

88 push_request=push_request, 

89 ) 

90 except ReadOnlyError: 

91 if self.connection_pool.is_master: 

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

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

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

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

96 # sentinel during the next connect() attempt. 

97 self.disconnect() 

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

99 raise 

100 except ResponseError as e: 

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

102 DEMOTED_MASTER_UNBLOCKED_ERROR 

103 ): 

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

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

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

107 # a coordinated failover. Same meaning as the ReadOnlyError 

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

109 self.disconnect() 

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

111 raise 

112 

113 

114class SentinelManagedSSLConnection(SentinelManagedConnection, SSLConnection): 

115 pass 

116 

117 

118class SentinelConnectionPoolProxy: 

119 def __init__( 

120 self, 

121 connection_pool, 

122 is_master, 

123 check_connection, 

124 service_name, 

125 sentinel_manager, 

126 ): 

127 self.connection_pool_ref = weakref.ref(connection_pool) 

128 self.is_master = is_master 

129 self.check_connection = check_connection 

130 self.service_name = service_name 

131 self.sentinel_manager = sentinel_manager 

132 self.reset() 

133 

134 def reset(self): 

135 self.master_address = None 

136 self.slave_rr_counter = None 

137 

138 def get_master_address(self): 

139 master_address = self.sentinel_manager.discover_master(self.service_name) 

140 if self.is_master and self.master_address != master_address: 

141 self.master_address = master_address 

142 # disconnect any idle connections so that they reconnect 

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

144 connection_pool = self.connection_pool_ref() 

145 if connection_pool is not None: 

146 connection_pool.disconnect(inuse_connections=False) 

147 return master_address 

148 

149 def rotate_slaves(self): 

150 slaves = self.sentinel_manager.discover_slaves(self.service_name) 

151 if slaves: 

152 if self.slave_rr_counter is None: 

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

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

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

156 slave = slaves[self.slave_rr_counter] 

157 yield slave 

158 # Fallback to the master connection 

159 try: 

160 yield self.get_master_address() 

161 except MasterNotFoundError: 

162 pass 

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

164 

165 def rotate_replicas(self): 

166 """Round-robin replica balancer. 

167 

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

169 using the preferred Redis 5.0+ terminology. 

170 """ 

171 return self.rotate_slaves() 

172 

173 

174class SentinelConnectionPool(ConnectionPool): 

175 """ 

176 Sentinel backed connection pool. 

177 

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

179 sends a PING command right after establishing the connection. 

180 """ 

181 

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

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

184 "connection_class", 

185 ( 

186 SentinelManagedSSLConnection 

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

188 else SentinelManagedConnection 

189 ), 

190 ) 

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

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

193 self.proxy = SentinelConnectionPoolProxy( 

194 connection_pool=self, 

195 is_master=self.is_master, 

196 check_connection=self.check_connection, 

197 service_name=service_name, 

198 sentinel_manager=sentinel_manager, 

199 ) 

200 super().__init__(**kwargs) 

201 self.connection_kwargs["connection_pool"] = self.proxy 

202 self.service_name = service_name 

203 self.sentinel_manager = sentinel_manager 

204 

205 def __repr__(self): 

206 role = "master" if self.is_master else "slave" 

207 return ( 

208 f"<{type(self).__module__}.{type(self).__name__}" 

209 f"(service={self.service_name}({role}))>" 

210 ) 

211 

212 def reset(self): 

213 super().reset() 

214 self.proxy.reset() 

215 

216 @property 

217 def master_address(self): 

218 return self.proxy.master_address 

219 

220 def owns_connection(self, connection): 

221 check = not self.is_master or ( 

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

223 ) 

224 parent = super() 

225 return check and parent.owns_connection(connection) 

226 

227 def get_master_address(self): 

228 return self.proxy.get_master_address() 

229 

230 def rotate_slaves(self): 

231 "Round-robin slave balancer" 

232 return self.proxy.rotate_slaves() 

233 

234 def rotate_replicas(self): 

235 """Round-robin replica balancer. 

236 

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

238 using the preferred Redis 5.0+ terminology. 

239 """ 

240 return self.rotate_slaves() 

241 

242 

243class Sentinel(SentinelCommands): 

244 """ 

245 Redis Sentinel cluster client 

246 

247 >>> from redis.sentinel import Sentinel 

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

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

250 >>> master.set('foo', 'bar') 

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

252 >>> slave.get('foo') 

253 b'bar' 

254 

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

256 a pair (hostname, port). 

257 

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

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

260 from that sentinel won't be considered valid. 

261 

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

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

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

265 not specified, any socket_timeout and socket_keepalive options specified 

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

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

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

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

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

271 

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

273 establishing a connection to a Redis server. 

274 """ 

275 

276 def __init__( 

277 self, 

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

279 min_other_sentinels: int = 0, 

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

281 force_master_ip: str | None = None, 

282 **connection_kwargs: Any, 

283 ) -> None: 

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

285 # connection_kwargs 

286 if sentinel_kwargs is None: 

287 sentinel_kwargs = { 

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

289 } 

290 else: 

291 sentinel_kwargs = dict(sentinel_kwargs) 

292 if "retry" not in sentinel_kwargs: 

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

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

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

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

297 # retry_on_timeout or retry_on_error is set. 

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

299 "retry_on_error" 

300 ) 

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

302 self.sentinel_kwargs = sentinel_kwargs 

303 

304 self.sentinels = [ 

305 Redis(hostname, port, **self.sentinel_kwargs) 

306 for hostname, port in sentinels 

307 ] 

308 self.min_other_sentinels = min_other_sentinels 

309 self.connection_kwargs = connection_kwargs 

310 self._force_master_ip = force_master_ip 

311 

312 def execute_command(self, *args, **kwargs): 

313 """ 

314 Execute Sentinel command in sentinel nodes. 

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

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

317 """ 

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

319 

320 # Check if command is supposed to return the original 

321 # responses instead of boolean value. 

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

323 

324 if once: 

325 response = random.choice(self.sentinels).execute_command(*args, **kwargs) 

326 if return_responses: 

327 return [response] 

328 else: 

329 return True if response else False 

330 

331 responses = [] 

332 for sentinel in self.sentinels: 

333 responses.append(sentinel.execute_command(*args, **kwargs)) 

334 

335 if return_responses: 

336 return responses 

337 

338 return all(responses) 

339 

340 def __repr__(self): 

341 sentinel_addresses = [] 

342 for sentinel in self.sentinels: 

343 sentinel_addresses.append( 

344 "{host}:{port}".format_map(sentinel.connection_pool.connection_kwargs) 

345 ) 

346 return ( 

347 f"<{type(self).__module__}.{type(self).__name__}" 

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

349 ) 

350 

351 def close(self) -> None: 

352 """ 

353 Close all sentinel clients created by this Sentinel and their 

354 connection pools. 

355 

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

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

358 

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

360 caller and are not closed here. 

361 """ 

362 exc = None 

363 for sentinel in self.sentinels: 

364 try: 

365 sentinel.close() 

366 except Exception as e: 

367 if exc is None: 

368 exc = e 

369 if exc: 

370 raise exc 

371 

372 def __enter__(self): 

373 return self 

374 

375 def __exit__(self, exc_type, exc_value, traceback): 

376 self.close() 

377 

378 def check_master_state(self, state, service_name): 

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

380 return False 

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

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

383 return False 

384 return True 

385 

386 def discover_master(self, service_name: str): 

387 """ 

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

389 to the service labeled ``service_name``. 

390 

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

392 master is found. 

393 """ 

394 collected_errors = list() 

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

396 try: 

397 masters = sentinel.sentinel_masters() 

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

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

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

401 if str(e): 

402 error += f": {e}" 

403 collected_errors.append(error) 

404 continue 

405 state = masters.get(service_name) 

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

407 # Put this sentinel at the top of the list 

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

409 sentinel, 

410 self.sentinels[0], 

411 ) 

412 

413 ip = ( 

414 self._force_master_ip 

415 if self._force_master_ip is not None 

416 else state["ip"] 

417 ) 

418 return ip, state["port"] 

419 

420 error_info = "" 

421 if len(collected_errors) > 0: 

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

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

424 

425 def filter_slaves(self, slaves): 

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

427 slaves_alive = [] 

428 for slave in slaves: 

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

430 continue 

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

432 return slaves_alive 

433 

434 def filter_replicas(self, replicas): 

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

436 

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

438 using the preferred Redis 5.0+ terminology. 

439 """ 

440 return self.filter_slaves(replicas) 

441 

442 def discover_slaves( 

443 self, service_name: str 

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

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

446 for sentinel in self.sentinels: 

447 try: 

448 slaves = sentinel.sentinel_slaves(service_name) 

449 except (ConnectionError, ResponseError, TimeoutError): 

450 continue 

451 slaves = self.filter_slaves(slaves) 

452 if slaves: 

453 return slaves 

454 return [] 

455 

456 def discover_replicas( 

457 self, service_name: str 

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

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

460 

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

462 using the preferred Redis 5.0+ terminology. 

463 """ 

464 return self.discover_slaves(service_name) 

465 

466 def master_for( 

467 self, 

468 service_name: str, 

469 redis_class: Type[Redis] = Redis, 

470 connection_pool_class: Type[SentinelConnectionPool] = SentinelConnectionPool, 

471 **kwargs, 

472 ): 

473 """ 

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

475 Sentinel client will detect failover and reconnect Redis clients 

476 automatically. 

477 

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

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

480 connection. 

481 

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

483 the old master are closed. 

484 

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

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

487 desire something different. 

488 

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

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

491 will be used by default. 

492 

493 All other keyword arguments are merged with any connection_kwargs 

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

495 arguments to be used to initialize Redis connections. 

496 

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

498 (``himport_prepare``, ``himport_set``, ``himport_discard``, 

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

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

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

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

503 ``himport_set``. Each call to the current method returns a *new* client with 

504 its *own* empty registry, so call ``himport_prepare`` on the long-lived client 

505 you reuse rather than creating a fresh one per operation; otherwise ``himport_set`` 

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

507 the master.) 

508 """ 

509 kwargs["is_master"] = True 

510 connection_kwargs = dict(self.connection_kwargs) 

511 connection_kwargs.update(kwargs) 

512 return redis_class.from_pool( 

513 connection_pool_class(service_name, self, **connection_kwargs) 

514 ) 

515 

516 def slave_for( 

517 self, 

518 service_name: str, 

519 redis_class: Type[Redis] = Redis, 

520 connection_pool_class: Type[SentinelConnectionPool] = SentinelConnectionPool, 

521 **kwargs, 

522 ): 

523 """ 

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

525 

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

527 address before establishing a new connection. 

528 

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

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

531 desire something different. 

532 

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

534 The SentinelConnectionPool will be used by default. 

535 

536 All other keyword arguments are merged with any connection_kwargs 

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

538 arguments to be used to initialize Redis connections. 

539 

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

541 (``himport_prepare``, ``himport_set``, ``himport_discard``, 

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

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

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

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

546 ``himport_set``. Each call to the current method returns a *new* client with 

547 its *own* empty registry, so call ``himport_prepare`` on the long-lived client 

548 you reuse rather than creating a fresh one per operation; otherwise ``himport_set`` 

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

550 the master.) 

551 """ 

552 kwargs["is_master"] = False 

553 connection_kwargs = dict(self.connection_kwargs) 

554 connection_kwargs.update(kwargs) 

555 return redis_class.from_pool( 

556 connection_pool_class(service_name, self, **connection_kwargs) 

557 ) 

558 

559 def replica_for( 

560 self, 

561 service_name: str, 

562 redis_class: Type[Redis] = Redis, 

563 connection_pool_class: Type[SentinelConnectionPool] = SentinelConnectionPool, 

564 **kwargs, 

565 ): 

566 """ 

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

568 

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

570 using the preferred Redis 5.0+ terminology. 

571 """ 

572 return self.slave_for( 

573 service_name, 

574 redis_class=redis_class, 

575 connection_pool_class=connection_pool_class, 

576 **kwargs, 

577 )