redis.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. # -*- coding: utf-8 -*-
  2. """Redis result store backend."""
  3. from __future__ import absolute_import, unicode_literals
  4. from functools import partial
  5. from kombu.utils.functional import retry_over_time
  6. from kombu.utils.objects import cached_property
  7. from kombu.utils.url import _parse_url
  8. from celery import states
  9. from celery._state import task_join_will_block
  10. from celery.canvas import maybe_signature
  11. from celery.exceptions import ChordError, ImproperlyConfigured
  12. from celery.five import string_t
  13. from celery.utils import deprecated
  14. from celery.utils.functional import dictfilter
  15. from celery.utils.log import get_logger
  16. from celery.utils.time import humanize_seconds
  17. from . import async
  18. from . import base
  19. try:
  20. import redis
  21. from redis.exceptions import ConnectionError
  22. from kombu.transport.redis import get_redis_error_classes
  23. except ImportError: # pragma: no cover
  24. redis = None # noqa
  25. ConnectionError = None # noqa
  26. get_redis_error_classes = None # noqa
  27. __all__ = ['RedisBackend']
  28. REDIS_MISSING = """\
  29. You need to install the redis library in order to use \
  30. the Redis result store backend."""
  31. E_LOST = """\
  32. Connection to Redis lost: Retry (%s/%s) %s.\
  33. """
  34. logger = get_logger(__name__)
  35. error = logger.error
  36. class ResultConsumer(async.BaseResultConsumer):
  37. _pubsub = None
  38. def __init__(self, *args, **kwargs):
  39. super(ResultConsumer, self).__init__(*args, **kwargs)
  40. self._get_key_for_task = self.backend.get_key_for_task
  41. self._decode_result = self.backend.decode_result
  42. self.subscribed_to = set()
  43. def start(self, initial_task_id):
  44. self._pubsub = self.backend.client.pubsub(
  45. ignore_subscribe_messages=True,
  46. )
  47. self._consume_from(initial_task_id)
  48. def on_wait_for_pending(self, result, **kwargs):
  49. for meta in result._iter_meta():
  50. if meta is not None:
  51. self.on_state_change(meta, None)
  52. def stop(self):
  53. if self._pubsub is not None:
  54. self._pubsub.close()
  55. def drain_events(self, timeout=None):
  56. m = self._pubsub.get_message(timeout=timeout)
  57. if m and m['type'] == 'message':
  58. self.on_state_change(self._decode_result(m['data']), m)
  59. def consume_from(self, task_id):
  60. if self._pubsub is None:
  61. return self.start(task_id)
  62. self._consume_from(task_id)
  63. def _consume_from(self, task_id):
  64. key = self._get_key_for_task(task_id)
  65. if key not in self.subscribed_to:
  66. self.subscribed_to.add(key)
  67. self._pubsub.subscribe(key)
  68. def cancel_for(self, task_id):
  69. if self._pubsub:
  70. key = self._get_key_for_task(task_id)
  71. self.subscribed_to.discard(key)
  72. self._pubsub.unsubscribe(key)
  73. class RedisBackend(base.BaseKeyValueStoreBackend, async.AsyncBackendMixin):
  74. """Redis task result store."""
  75. ResultConsumer = ResultConsumer
  76. #: :pypi:`redis` client module.
  77. redis = redis
  78. #: Maximum number of connections in the pool.
  79. max_connections = None
  80. supports_autoexpire = True
  81. supports_native_join = True
  82. def __init__(self, host=None, port=None, db=None, password=None,
  83. max_connections=None, url=None,
  84. connection_pool=None, **kwargs):
  85. super(RedisBackend, self).__init__(expires_type=int, **kwargs)
  86. _get = self.app.conf.get
  87. if self.redis is None:
  88. raise ImproperlyConfigured(REDIS_MISSING)
  89. if host and '://' in host:
  90. url, host = host, None
  91. self.max_connections = (
  92. max_connections or
  93. _get('redis_max_connections') or
  94. self.max_connections)
  95. self._ConnectionPool = connection_pool
  96. self.connparams = {
  97. 'host': _get('redis_host') or 'localhost',
  98. 'port': _get('redis_port') or 6379,
  99. 'db': _get('redis_db') or 0,
  100. 'password': _get('redis_password'),
  101. 'socket_timeout': _get('redis_socket_timeout'),
  102. 'max_connections': self.max_connections,
  103. }
  104. if url:
  105. self.connparams = self._params_from_url(url, self.connparams)
  106. self.url = url
  107. self.connection_errors, self.channel_errors = (
  108. get_redis_error_classes() if get_redis_error_classes
  109. else ((), ()))
  110. self.result_consumer = self.ResultConsumer(
  111. self, self.app, self.accept,
  112. self._pending_results, self._pending_messages,
  113. )
  114. def _params_from_url(self, url, defaults):
  115. scheme, host, port, user, password, path, query = _parse_url(url)
  116. connparams = dict(
  117. defaults, **dictfilter({
  118. 'host': host, 'port': port, 'password': password,
  119. 'db': query.pop('virtual_host', None)})
  120. )
  121. if scheme == 'socket':
  122. # use 'path' as path to the socket… in this case
  123. # the database number should be given in 'query'
  124. connparams.update({
  125. 'connection_class': self.redis.UnixDomainSocketConnection,
  126. 'path': '/' + path,
  127. })
  128. # host+port are invalid options when using this connection type.
  129. connparams.pop('host', None)
  130. connparams.pop('port', None)
  131. else:
  132. connparams['db'] = path
  133. # db may be string and start with / like in kombu.
  134. db = connparams.get('db') or 0
  135. db = db.strip('/') if isinstance(db, string_t) else db
  136. connparams['db'] = int(db)
  137. # Query parameters override other parameters
  138. connparams.update(query)
  139. return connparams
  140. def on_task_call(self, producer, task_id):
  141. if not task_join_will_block():
  142. self.result_consumer.consume_from(task_id)
  143. def get(self, key):
  144. return self.client.get(key)
  145. def mget(self, keys):
  146. return self.client.mget(keys)
  147. def ensure(self, fun, args, **policy):
  148. retry_policy = dict(self.retry_policy, **policy)
  149. max_retries = retry_policy.get('max_retries')
  150. return retry_over_time(
  151. fun, self.connection_errors, args, {},
  152. partial(self.on_connection_error, max_retries),
  153. **retry_policy)
  154. def on_connection_error(self, max_retries, exc, intervals, retries):
  155. tts = next(intervals)
  156. error(E_LOST, retries, max_retries or 'Inf',
  157. humanize_seconds(tts, 'in '))
  158. return tts
  159. def set(self, key, value, **retry_policy):
  160. return self.ensure(self._set, (key, value), **retry_policy)
  161. def _set(self, key, value):
  162. with self.client.pipeline() as pipe:
  163. if self.expires:
  164. pipe.setex(key, self.expires, value)
  165. else:
  166. pipe.set(key, value)
  167. pipe.publish(key, value)
  168. pipe.execute()
  169. def delete(self, key):
  170. self.client.delete(key)
  171. def incr(self, key):
  172. return self.client.incr(key)
  173. def expire(self, key, value):
  174. return self.client.expire(key, value)
  175. def add_to_chord(self, group_id, result):
  176. self.client.incr(self.get_key_for_group(group_id, '.t'), 1)
  177. def _unpack_chord_result(self, tup, decode,
  178. EXCEPTION_STATES=states.EXCEPTION_STATES,
  179. PROPAGATE_STATES=states.PROPAGATE_STATES):
  180. _, tid, state, retval = decode(tup)
  181. if state in EXCEPTION_STATES:
  182. retval = self.exception_to_python(retval)
  183. if state in PROPAGATE_STATES:
  184. raise ChordError('Dependency {0} raised {1!r}'.format(tid, retval))
  185. return retval
  186. def apply_chord(self, header, partial_args, group_id, body,
  187. result=None, options={}, **kwargs):
  188. # avoids saving the group in the redis db.
  189. options['task_id'] = group_id
  190. return header(*partial_args, **options or {})
  191. def on_chord_part_return(self, request, state, result, propagate=None):
  192. app = self.app
  193. tid, gid = request.id, request.group
  194. if not gid or not tid:
  195. return
  196. client = self.client
  197. jkey = self.get_key_for_group(gid, '.j')
  198. tkey = self.get_key_for_group(gid, '.t')
  199. result = self.encode_result(result, state)
  200. with client.pipeline() as pipe:
  201. _, readycount, totaldiff, _, _ = pipe \
  202. .rpush(jkey, self.encode([1, tid, state, result])) \
  203. .llen(jkey) \
  204. .get(tkey) \
  205. .expire(jkey, 86400) \
  206. .expire(tkey, 86400) \
  207. .execute()
  208. totaldiff = int(totaldiff or 0)
  209. try:
  210. callback = maybe_signature(request.chord, app=app)
  211. total = callback['chord_size'] + totaldiff
  212. if readycount == total:
  213. decode, unpack = self.decode, self._unpack_chord_result
  214. with client.pipeline() as pipe:
  215. resl, _, _ = pipe \
  216. .lrange(jkey, 0, total) \
  217. .delete(jkey) \
  218. .delete(tkey) \
  219. .execute()
  220. try:
  221. callback.delay([unpack(tup, decode) for tup in resl])
  222. except Exception as exc:
  223. error('Chord callback for %r raised: %r',
  224. request.group, exc, exc_info=1)
  225. return self.chord_error_from_stack(
  226. callback,
  227. ChordError('Callback error: {0!r}'.format(exc)),
  228. )
  229. except ChordError as exc:
  230. error('Chord %r raised: %r', request.group, exc, exc_info=1)
  231. return self.chord_error_from_stack(callback, exc)
  232. except Exception as exc:
  233. error('Chord %r raised: %r', request.group, exc, exc_info=1)
  234. return self.chord_error_from_stack(
  235. callback,
  236. ChordError('Join error: {0!r}'.format(exc)),
  237. )
  238. def _create_client(self, socket_timeout=None, socket_connect_timeout=None,
  239. **params):
  240. return self.redis.StrictRedis(
  241. connection_pool=self.ConnectionPool(
  242. socket_timeout=socket_timeout and float(socket_timeout),
  243. socket_connect_timeout=socket_connect_timeout and float(
  244. socket_connect_timeout),
  245. **params),
  246. )
  247. @property
  248. def ConnectionPool(self):
  249. if self._ConnectionPool is None:
  250. self._ConnectionPool = self.redis.ConnectionPool
  251. return self._ConnectionPool
  252. @cached_property
  253. def client(self):
  254. return self._create_client(**self.connparams)
  255. def __reduce__(self, args=(), kwargs={}):
  256. return super(RedisBackend, self).__reduce__(
  257. (self.url,), {'expires': self.expires},
  258. )
  259. @deprecated.Property(4.0, 5.0)
  260. def host(self):
  261. return self.connparams['host']
  262. @deprecated.Property(4.0, 5.0)
  263. def port(self):
  264. return self.connparams['port']
  265. @deprecated.Property(4.0, 5.0)
  266. def db(self):
  267. return self.connparams['db']
  268. @deprecated.Property(4.0, 5.0)
  269. def password(self):
  270. return self.connparams['password']