sentinel.py 14 KB

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