sentinel.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. import asyncio
  2. import random
  3. import weakref
  4. from typing import AsyncIterator, Iterable, Mapping, Optional, Sequence, Tuple, Type
  5. from redis.asyncio.client import Redis
  6. from redis.asyncio.connection import (
  7. Connection,
  8. ConnectionPool,
  9. EncodableT,
  10. SSLConnection,
  11. )
  12. from redis.commands import AsyncSentinelCommands
  13. from redis.exceptions import ConnectionError, ReadOnlyError, ResponseError, TimeoutError
  14. from redis.utils import str_if_bytes
  15. class MasterNotFoundError(ConnectionError):
  16. pass
  17. class SlaveNotFoundError(ConnectionError):
  18. pass
  19. class SentinelManagedConnection(Connection):
  20. def __init__(self, **kwargs):
  21. self.connection_pool = kwargs.pop("connection_pool")
  22. super().__init__(**kwargs)
  23. def __repr__(self):
  24. s = f"<{self.__class__.__module__}.{self.__class__.__name__}"
  25. if self.host:
  26. host_info = f",host={self.host},port={self.port}"
  27. s += host_info
  28. return s + ")>"
  29. async def connect_to(self, address):
  30. self.host, self.port = address
  31. await super().connect()
  32. if self.connection_pool.check_connection:
  33. await self.send_command("PING")
  34. if str_if_bytes(await self.read_response()) != "PONG":
  35. raise ConnectionError("PING failed")
  36. async def _connect_retry(self):
  37. if self._reader:
  38. return # already connected
  39. if self.connection_pool.is_master:
  40. await self.connect_to(await self.connection_pool.get_master_address())
  41. else:
  42. async for slave in self.connection_pool.rotate_slaves():
  43. try:
  44. return await self.connect_to(slave)
  45. except ConnectionError:
  46. continue
  47. raise SlaveNotFoundError # Never be here
  48. async def connect(self):
  49. return await self.retry.call_with_retry(
  50. self._connect_retry,
  51. lambda error: asyncio.sleep(0),
  52. )
  53. async def read_response(
  54. self,
  55. disable_decoding: bool = False,
  56. timeout: Optional[float] = None,
  57. *,
  58. disconnect_on_error: Optional[float] = True,
  59. push_request: Optional[bool] = False,
  60. ):
  61. try:
  62. return await super().read_response(
  63. disable_decoding=disable_decoding,
  64. timeout=timeout,
  65. disconnect_on_error=disconnect_on_error,
  66. push_request=push_request,
  67. )
  68. except ReadOnlyError:
  69. if self.connection_pool.is_master:
  70. # When talking to a master, a ReadOnlyError when likely
  71. # indicates that the previous master that we're still connected
  72. # to has been demoted to a slave and there's a new master.
  73. # calling disconnect will force the connection to re-query
  74. # sentinel during the next connect() attempt.
  75. await self.disconnect()
  76. raise ConnectionError("The previous master is now a slave")
  77. raise
  78. class SentinelManagedSSLConnection(SentinelManagedConnection, SSLConnection):
  79. pass
  80. class SentinelConnectionPool(ConnectionPool):
  81. """
  82. Sentinel backed connection pool.
  83. If ``check_connection`` flag is set to True, SentinelManagedConnection
  84. sends a PING command right after establishing the connection.
  85. """
  86. def __init__(self, service_name, sentinel_manager, **kwargs):
  87. kwargs["connection_class"] = kwargs.get(
  88. "connection_class",
  89. (
  90. SentinelManagedSSLConnection
  91. if kwargs.pop("ssl", False)
  92. else SentinelManagedConnection
  93. ),
  94. )
  95. self.is_master = kwargs.pop("is_master", True)
  96. self.check_connection = kwargs.pop("check_connection", False)
  97. super().__init__(**kwargs)
  98. self.connection_kwargs["connection_pool"] = weakref.proxy(self)
  99. self.service_name = service_name
  100. self.sentinel_manager = sentinel_manager
  101. self.master_address = None
  102. self.slave_rr_counter = None
  103. def __repr__(self):
  104. return (
  105. f"<{self.__class__.__module__}.{self.__class__.__name__}"
  106. f"(service={self.service_name}({self.is_master and 'master' or 'slave'}))>"
  107. )
  108. def reset(self):
  109. super().reset()
  110. self.master_address = None
  111. self.slave_rr_counter = None
  112. def owns_connection(self, connection: Connection):
  113. check = not self.is_master or (
  114. self.is_master and self.master_address == (connection.host, connection.port)
  115. )
  116. return check and super().owns_connection(connection)
  117. async def get_master_address(self):
  118. master_address = await self.sentinel_manager.discover_master(self.service_name)
  119. if self.is_master:
  120. if self.master_address != master_address:
  121. self.master_address = master_address
  122. # disconnect any idle connections so that they reconnect
  123. # to the new master the next time that they are used.
  124. await self.disconnect(inuse_connections=False)
  125. return master_address
  126. async def rotate_slaves(self) -> AsyncIterator:
  127. """Round-robin slave balancer"""
  128. slaves = await self.sentinel_manager.discover_slaves(self.service_name)
  129. if slaves:
  130. if self.slave_rr_counter is None:
  131. self.slave_rr_counter = random.randint(0, len(slaves) - 1)
  132. for _ in range(len(slaves)):
  133. self.slave_rr_counter = (self.slave_rr_counter + 1) % len(slaves)
  134. slave = slaves[self.slave_rr_counter]
  135. yield slave
  136. # Fallback to the master connection
  137. try:
  138. yield await self.get_master_address()
  139. except MasterNotFoundError:
  140. pass
  141. raise SlaveNotFoundError(f"No slave found for {self.service_name!r}")
  142. class Sentinel(AsyncSentinelCommands):
  143. """
  144. Redis Sentinel cluster client
  145. >>> from redis.sentinel import Sentinel
  146. >>> sentinel = Sentinel([('localhost', 26379)], socket_timeout=0.1)
  147. >>> master = sentinel.master_for('mymaster', socket_timeout=0.1)
  148. >>> await master.set('foo', 'bar')
  149. >>> slave = sentinel.slave_for('mymaster', socket_timeout=0.1)
  150. >>> await slave.get('foo')
  151. b'bar'
  152. ``sentinels`` is a list of sentinel nodes. Each node is represented by
  153. a pair (hostname, port).
  154. ``min_other_sentinels`` defined a minimum number of peers for a sentinel.
  155. When querying a sentinel, if it doesn't meet this threshold, responses
  156. from that sentinel won't be considered valid.
  157. ``sentinel_kwargs`` is a dictionary of connection arguments used when
  158. connecting to sentinel instances. Any argument that can be passed to
  159. a normal Redis connection can be specified here. If ``sentinel_kwargs`` is
  160. not specified, any socket_timeout and socket_keepalive options specified
  161. in ``connection_kwargs`` will be used.
  162. ``connection_kwargs`` are keyword arguments that will be used when
  163. establishing a connection to a Redis server.
  164. """
  165. def __init__(
  166. self,
  167. sentinels,
  168. min_other_sentinels=0,
  169. sentinel_kwargs=None,
  170. force_master_ip=None,
  171. **connection_kwargs,
  172. ):
  173. # if sentinel_kwargs isn't defined, use the socket_* options from
  174. # connection_kwargs
  175. if sentinel_kwargs is None:
  176. sentinel_kwargs = {
  177. k: v for k, v in connection_kwargs.items() if k.startswith("socket_")
  178. }
  179. self.sentinel_kwargs = sentinel_kwargs
  180. self.sentinels = [
  181. Redis(host=hostname, port=port, **self.sentinel_kwargs)
  182. for hostname, port in sentinels
  183. ]
  184. self.min_other_sentinels = min_other_sentinels
  185. self.connection_kwargs = connection_kwargs
  186. self._force_master_ip = force_master_ip
  187. async def execute_command(self, *args, **kwargs):
  188. """
  189. Execute Sentinel command in sentinel nodes.
  190. once - If set to True, then execute the resulting command on a single
  191. node at random, rather than across the entire sentinel cluster.
  192. """
  193. once = bool(kwargs.get("once", False))
  194. if "once" in kwargs.keys():
  195. kwargs.pop("once")
  196. if once:
  197. await random.choice(self.sentinels).execute_command(*args, **kwargs)
  198. else:
  199. tasks = [
  200. asyncio.Task(sentinel.execute_command(*args, **kwargs))
  201. for sentinel in self.sentinels
  202. ]
  203. await asyncio.gather(*tasks)
  204. return True
  205. def __repr__(self):
  206. sentinel_addresses = []
  207. for sentinel in self.sentinels:
  208. sentinel_addresses.append(
  209. f"{sentinel.connection_pool.connection_kwargs['host']}:"
  210. f"{sentinel.connection_pool.connection_kwargs['port']}"
  211. )
  212. return (
  213. f"<{self.__class__}.{self.__class__.__name__}"
  214. f"(sentinels=[{','.join(sentinel_addresses)}])>"
  215. )
  216. def check_master_state(self, state: dict, service_name: str) -> bool:
  217. if not state["is_master"] or state["is_sdown"] or state["is_odown"]:
  218. return False
  219. # Check if our sentinel doesn't see other nodes
  220. if state["num-other-sentinels"] < self.min_other_sentinels:
  221. return False
  222. return True
  223. async def discover_master(self, service_name: str):
  224. """
  225. Asks sentinel servers for the Redis master's address corresponding
  226. to the service labeled ``service_name``.
  227. Returns a pair (address, port) or raises MasterNotFoundError if no
  228. master is found.
  229. """
  230. collected_errors = list()
  231. for sentinel_no, sentinel in enumerate(self.sentinels):
  232. try:
  233. masters = await sentinel.sentinel_masters()
  234. except (ConnectionError, TimeoutError) as e:
  235. collected_errors.append(f"{sentinel} - {e!r}")
  236. continue
  237. state = masters.get(service_name)
  238. if state and self.check_master_state(state, service_name):
  239. # Put this sentinel at the top of the list
  240. self.sentinels[0], self.sentinels[sentinel_no] = (
  241. sentinel,
  242. self.sentinels[0],
  243. )
  244. ip = (
  245. self._force_master_ip
  246. if self._force_master_ip is not None
  247. else state["ip"]
  248. )
  249. return ip, state["port"]
  250. error_info = ""
  251. if len(collected_errors) > 0:
  252. error_info = f" : {', '.join(collected_errors)}"
  253. raise MasterNotFoundError(f"No master found for {service_name!r}{error_info}")
  254. def filter_slaves(
  255. self, slaves: Iterable[Mapping]
  256. ) -> Sequence[Tuple[EncodableT, EncodableT]]:
  257. """Remove slaves that are in an ODOWN or SDOWN state"""
  258. slaves_alive = []
  259. for slave in slaves:
  260. if slave["is_odown"] or slave["is_sdown"]:
  261. continue
  262. slaves_alive.append((slave["ip"], slave["port"]))
  263. return slaves_alive
  264. async def discover_slaves(
  265. self, service_name: str
  266. ) -> Sequence[Tuple[EncodableT, EncodableT]]:
  267. """Returns a list of alive slaves for service ``service_name``"""
  268. for sentinel in self.sentinels:
  269. try:
  270. slaves = await sentinel.sentinel_slaves(service_name)
  271. except (ConnectionError, ResponseError, TimeoutError):
  272. continue
  273. slaves = self.filter_slaves(slaves)
  274. if slaves:
  275. return slaves
  276. return []
  277. def master_for(
  278. self,
  279. service_name: str,
  280. redis_class: Type[Redis] = Redis,
  281. connection_pool_class: Type[SentinelConnectionPool] = SentinelConnectionPool,
  282. **kwargs,
  283. ):
  284. """
  285. Returns a redis client instance for the ``service_name`` master.
  286. Sentinel client will detect failover and reconnect Redis clients
  287. automatically.
  288. A :py:class:`~redis.sentinel.SentinelConnectionPool` class is
  289. used to retrieve the master's address before establishing a new
  290. connection.
  291. NOTE: If the master's address has changed, any cached connections to
  292. the old master are closed.
  293. By default clients will be a :py:class:`~redis.Redis` instance.
  294. Specify a different class to the ``redis_class`` argument if you
  295. desire something different.
  296. The ``connection_pool_class`` specifies the connection pool to
  297. use. The :py:class:`~redis.sentinel.SentinelConnectionPool`
  298. will be used by default.
  299. All other keyword arguments are merged with any connection_kwargs
  300. passed to this class and passed to the connection pool as keyword
  301. arguments to be used to initialize Redis connections.
  302. """
  303. kwargs["is_master"] = True
  304. connection_kwargs = dict(self.connection_kwargs)
  305. connection_kwargs.update(kwargs)
  306. connection_pool = connection_pool_class(service_name, self, **connection_kwargs)
  307. # The Redis object "owns" the pool
  308. return redis_class.from_pool(connection_pool)
  309. def slave_for(
  310. self,
  311. service_name: str,
  312. redis_class: Type[Redis] = Redis,
  313. connection_pool_class: Type[SentinelConnectionPool] = SentinelConnectionPool,
  314. **kwargs,
  315. ):
  316. """
  317. Returns redis client instance for the ``service_name`` slave(s).
  318. A SentinelConnectionPool class is used to retrieve the slave's
  319. address before establishing a new connection.
  320. By default clients will be a :py:class:`~redis.Redis` instance.
  321. Specify a different class to the ``redis_class`` argument if you
  322. desire something different.
  323. The ``connection_pool_class`` specifies the connection pool to use.
  324. The SentinelConnectionPool will be used by default.
  325. All other keyword arguments are merged with any connection_kwargs
  326. passed to this class and passed to the connection pool as keyword
  327. arguments to be used to initialize Redis connections.
  328. """
  329. kwargs["is_master"] = False
  330. connection_kwargs = dict(self.connection_kwargs)
  331. connection_kwargs.update(kwargs)
  332. connection_pool = connection_pool_class(service_name, self, **connection_kwargs)
  333. # The Redis object "owns" the pool
  334. return redis_class.from_pool(connection_pool)