图片解析应用
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

398 lines
14 KiB

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