sentinel.py 14 KB

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