sentinel.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. import os
  2. import random
  3. import weakref
  4. from redis.client import StrictRedis
  5. from redis.connection import ConnectionPool, Connection
  6. from redis.exceptions import ConnectionError, ResponseError, ReadOnlyError
  7. from redis._compat import iteritems, nativestr, xrange
  8. class MasterNotFoundError(ConnectionError):
  9. pass
  10. class SlaveNotFoundError(ConnectionError):
  11. pass
  12. class SentinelManagedConnection(Connection):
  13. def __init__(self, **kwargs):
  14. self.connection_pool = kwargs.pop('connection_pool')
  15. super(SentinelManagedConnection, self).__init__(**kwargs)
  16. def __repr__(self):
  17. pool = self.connection_pool
  18. s = '%s<service=%s%%s>' % (type(self).__name__, pool.service_name)
  19. if self.host:
  20. host_info = ',host=%s,port=%s' % (self.host, self.port)
  21. s = s % host_info
  22. return s
  23. def connect_to(self, address):
  24. self.host, self.port = address
  25. super(SentinelManagedConnection, self).connect()
  26. if self.connection_pool.check_connection:
  27. self.send_command('PING')
  28. if nativestr(self.read_response()) != 'PONG':
  29. raise ConnectionError('PING failed')
  30. def connect(self):
  31. if self._sock:
  32. return # already connected
  33. if self.connection_pool.is_master:
  34. self.connect_to(self.connection_pool.get_master_address())
  35. else:
  36. for slave in self.connection_pool.rotate_slaves():
  37. try:
  38. return self.connect_to(slave)
  39. except ConnectionError:
  40. continue
  41. raise SlaveNotFoundError # Never be here
  42. def read_response(self):
  43. try:
  44. return super(SentinelManagedConnection, self).read_response()
  45. except ReadOnlyError:
  46. if self.connection_pool.is_master:
  47. # When talking to a master, a ReadOnlyError when likely
  48. # indicates that the previous master that we're still connected
  49. # to has been demoted to a slave and there's a new master.
  50. # calling disconnect will force the connection to re-query
  51. # sentinel during the next connect() attempt.
  52. self.disconnect()
  53. raise ConnectionError('The previous master is now a slave')
  54. raise
  55. class SentinelConnectionPool(ConnectionPool):
  56. """
  57. Sentinel backed connection pool.
  58. If ``check_connection`` flag is set to True, SentinelManagedConnection
  59. sends a PING command right after establishing the connection.
  60. """
  61. def __init__(self, service_name, sentinel_manager, **kwargs):
  62. kwargs['connection_class'] = kwargs.get(
  63. 'connection_class', SentinelManagedConnection)
  64. self.is_master = kwargs.pop('is_master', True)
  65. self.check_connection = kwargs.pop('check_connection', False)
  66. super(SentinelConnectionPool, self).__init__(**kwargs)
  67. self.connection_kwargs['connection_pool'] = weakref.proxy(self)
  68. self.service_name = service_name
  69. self.sentinel_manager = sentinel_manager
  70. def __repr__(self):
  71. return "%s<service=%s(%s)" % (
  72. type(self).__name__,
  73. self.service_name,
  74. self.is_master and 'master' or 'slave',
  75. )
  76. def reset(self):
  77. super(SentinelConnectionPool, self).reset()
  78. self.master_address = None
  79. self.slave_rr_counter = None
  80. def get_master_address(self):
  81. master_address = self.sentinel_manager.discover_master(
  82. self.service_name)
  83. if self.is_master:
  84. if self.master_address is None:
  85. self.master_address = master_address
  86. elif master_address != self.master_address:
  87. # Master address changed, disconnect all clients in this pool
  88. self.disconnect()
  89. return master_address
  90. def rotate_slaves(self):
  91. "Round-robin slave balancer"
  92. slaves = self.sentinel_manager.discover_slaves(self.service_name)
  93. if slaves:
  94. if self.slave_rr_counter is None:
  95. self.slave_rr_counter = random.randint(0, len(slaves) - 1)
  96. for _ in xrange(len(slaves)):
  97. self.slave_rr_counter = (
  98. self.slave_rr_counter + 1) % len(slaves)
  99. slave = slaves[self.slave_rr_counter]
  100. yield slave
  101. # Fallback to the master connection
  102. try:
  103. yield self.get_master_address()
  104. except MasterNotFoundError:
  105. pass
  106. raise SlaveNotFoundError('No slave found for %r' % (self.service_name))
  107. def _checkpid(self):
  108. if self.pid != os.getpid():
  109. self.disconnect()
  110. self.reset()
  111. self.__init__(self.service_name, self.sentinel_manager,
  112. is_master=self.is_master,
  113. check_connection=self.check_connection,
  114. connection_class=self.connection_class,
  115. max_connections=self.max_connections,
  116. **self.connection_kwargs)
  117. class Sentinel(object):
  118. """
  119. Redis Sentinel cluster client
  120. >>> from redis.sentinel import Sentinel
  121. >>> sentinel = Sentinel([('localhost', 26379)], socket_timeout=0.1)
  122. >>> master = sentinel.master_for('mymaster', socket_timeout=0.1)
  123. >>> master.set('foo', 'bar')
  124. >>> slave = sentinel.slave_for('mymaster', socket_timeout=0.1)
  125. >>> slave.get('foo')
  126. 'bar'
  127. ``sentinels`` is a list of sentinel nodes. Each node is represented by
  128. a pair (hostname, port).
  129. ``min_other_sentinels`` defined a minimum number of peers for a sentinel.
  130. When querying a sentinel, if it doesn't meet this threshold, responses
  131. from that sentinel won't be considered valid.
  132. ``sentinel_kwargs`` is a dictionary of connection arguments used when
  133. connecting to sentinel instances. Any argument that can be passed to
  134. a normal Redis connection can be specified here. If ``sentinel_kwargs`` is
  135. not specified, any socket_timeout and socket_keepalive options specified
  136. in ``connection_kwargs`` will be used.
  137. ``connection_kwargs`` are keyword arguments that will be used when
  138. establishing a connection to a Redis server.
  139. """
  140. def __init__(self, sentinels, min_other_sentinels=0, sentinel_kwargs=None,
  141. **connection_kwargs):
  142. # if sentinel_kwargs isn't defined, use the socket_* options from
  143. # connection_kwargs
  144. if sentinel_kwargs is None:
  145. sentinel_kwargs = dict([(k, v)
  146. for k, v in iteritems(connection_kwargs)
  147. if k.startswith('socket_')
  148. ])
  149. self.sentinel_kwargs = sentinel_kwargs
  150. self.sentinels = [StrictRedis(hostname, port, **self.sentinel_kwargs)
  151. for hostname, port in sentinels]
  152. self.min_other_sentinels = min_other_sentinels
  153. self.connection_kwargs = connection_kwargs
  154. def __repr__(self):
  155. sentinel_addresses = []
  156. for sentinel in self.sentinels:
  157. sentinel_addresses.append('%s:%s' % (
  158. sentinel.connection_pool.connection_kwargs['host'],
  159. sentinel.connection_pool.connection_kwargs['port'],
  160. ))
  161. return '%s<sentinels=[%s]>' % (
  162. type(self).__name__,
  163. ','.join(sentinel_addresses))
  164. def check_master_state(self, state, service_name):
  165. if not state['is_master'] or state['is_sdown'] or state['is_odown']:
  166. return False
  167. # Check if our sentinel doesn't see other nodes
  168. if state['num-other-sentinels'] < self.min_other_sentinels:
  169. return False
  170. return True
  171. def discover_master(self, service_name):
  172. """
  173. Asks sentinel servers for the Redis master's address corresponding
  174. to the service labeled ``service_name``.
  175. Returns a pair (address, port) or raises MasterNotFoundError if no
  176. master is found.
  177. """
  178. for sentinel_no, sentinel in enumerate(self.sentinels):
  179. try:
  180. masters = sentinel.sentinel_masters()
  181. except ConnectionError:
  182. continue
  183. state = masters.get(service_name)
  184. if state and self.check_master_state(state, service_name):
  185. # Put this sentinel at the top of the list
  186. self.sentinels[0], self.sentinels[sentinel_no] = (
  187. sentinel, self.sentinels[0])
  188. return state['ip'], state['port']
  189. raise MasterNotFoundError("No master found for %r" % (service_name,))
  190. def filter_slaves(self, slaves):
  191. "Remove slaves that are in an ODOWN or SDOWN state"
  192. slaves_alive = []
  193. for slave in slaves:
  194. if slave['is_odown'] or slave['is_sdown']:
  195. continue
  196. slaves_alive.append((slave['ip'], slave['port']))
  197. return slaves_alive
  198. def discover_slaves(self, service_name):
  199. "Returns a list of alive slaves for service ``service_name``"
  200. for sentinel in self.sentinels:
  201. try:
  202. slaves = sentinel.sentinel_slaves(service_name)
  203. except (ConnectionError, ResponseError):
  204. continue
  205. slaves = self.filter_slaves(slaves)
  206. if slaves:
  207. return slaves
  208. return []
  209. def master_for(self, service_name, redis_class=StrictRedis,
  210. connection_pool_class=SentinelConnectionPool, **kwargs):
  211. """
  212. Returns a redis client instance for the ``service_name`` master.
  213. A SentinelConnectionPool class is used to retrive the master's
  214. address before establishing a new connection.
  215. NOTE: If the master's address has changed, any cached connections to
  216. the old master are closed.
  217. By default clients will be a redis.StrictRedis instance. Specify a
  218. different class to the ``redis_class`` argument if you desire
  219. something different.
  220. The ``connection_pool_class`` specifies the connection pool to use.
  221. The SentinelConnectionPool will be used by default.
  222. All other keyword arguments are merged with any connection_kwargs
  223. passed to this class and passed to the connection pool as keyword
  224. arguments to be used to initialize Redis connections.
  225. """
  226. kwargs['is_master'] = True
  227. connection_kwargs = dict(self.connection_kwargs)
  228. connection_kwargs.update(kwargs)
  229. return redis_class(connection_pool=connection_pool_class(
  230. service_name, self, **connection_kwargs))
  231. def slave_for(self, service_name, redis_class=StrictRedis,
  232. connection_pool_class=SentinelConnectionPool, **kwargs):
  233. """
  234. Returns redis client instance for the ``service_name`` slave(s).
  235. A SentinelConnectionPool class is used to retrive the slave's
  236. address before establishing a new connection.
  237. By default clients will be a redis.StrictRedis instance. Specify a
  238. different class to the ``redis_class`` argument if you desire
  239. something different.
  240. The ``connection_pool_class`` specifies the connection pool to use.
  241. The SentinelConnectionPool will be used by default.
  242. All other keyword arguments are merged with any connection_kwargs
  243. passed to this class and passed to the connection pool as keyword
  244. arguments to be used to initialize Redis connections.
  245. """
  246. kwargs['is_master'] = False
  247. connection_kwargs = dict(self.connection_kwargs)
  248. connection_kwargs.update(kwargs)
  249. return redis_class(connection_pool=connection_pool_class(
  250. service_name, self, **connection_kwargs))