redis.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. # -*- coding: utf-8 -*-
  2. """
  3. celery.backends.redis
  4. ~~~~~~~~~~~~~~~~~~~~~
  5. Redis result store backend.
  6. """
  7. from __future__ import absolute_import
  8. from functools import partial
  9. from kombu.utils import cached_property, retry_over_time
  10. from kombu.utils.url import _parse_url
  11. from celery import states
  12. from celery._state import task_join_will_block
  13. from celery.canvas import maybe_signature
  14. from celery.exceptions import ChordError, ImproperlyConfigured
  15. from celery.five import string_t
  16. from celery.utils import deprecated_property
  17. from celery.utils.functional import dictfilter
  18. from celery.utils.log import get_logger
  19. from celery.utils.timeutils import humanize_seconds
  20. from . import async
  21. from . import base
  22. try:
  23. import redis
  24. from redis.exceptions import ConnectionError
  25. from kombu.transport.redis import get_redis_error_classes
  26. except ImportError: # pragma: no cover
  27. redis = None # noqa
  28. ConnectionError = None # noqa
  29. get_redis_error_classes = None # noqa
  30. __all__ = ['RedisBackend']
  31. REDIS_MISSING = """\
  32. You need to install the redis library in order to use \
  33. the Redis result store backend."""
  34. E_LOST = """\
  35. Connection to Redis lost: Retry (%s/%s) %s.\
  36. """
  37. logger = get_logger(__name__)
  38. error = logger.error
  39. class ResultConsumer(async.BaseResultConsumer):
  40. _pubsub = None
  41. def __init__(self, *args, **kwargs):
  42. super(ResultConsumer, self).__init__(*args, **kwargs)
  43. self._get_key_for_task = self.backend.get_key_for_task
  44. self._decode_result = self.backend.decode_result
  45. self.subscribed_to = set()
  46. def start(self, initial_task_id):
  47. self._pubsub = self.backend.client.pubsub(
  48. ignore_subscribe_messages=True,
  49. )
  50. self._consume_from(initial_task_id)
  51. def stop(self):
  52. if self._pubsub is not None:
  53. self._pubsub.close()
  54. def drain_events(self, timeout=None):
  55. m = self._pubsub.get_message(timeout=timeout)
  56. if m and m['type'] == 'message':
  57. self.on_state_change(self._decode_result(m['data']), m)
  58. def consume_from(self, task_id):
  59. if self._pubsub is None:
  60. return self.start(task_id)
  61. self._consume_from(task_id)
  62. def _consume_from(self, task_id):
  63. key = self._get_key_for_task(task_id)
  64. if key not in self.subscribed_to:
  65. self.subscribed_to.add(key)
  66. self._pubsub.subscribe(key)
  67. def cancel_for(self, task_id):
  68. if self._pubsub:
  69. key = self._get_key_for_task(task_id)
  70. self.subscribed_to.discard(key)
  71. self._pubsub.unsubscribe(key)
  72. class RedisBackend(base.BaseKeyValueStoreBackend, async.AsyncBackendMixin):
  73. """Redis task result store."""
  74. ResultConsumer = ResultConsumer
  75. #: redis-py client module.
  76. redis = redis
  77. #: Maximium number of connections in the pool.
  78. max_connections = None
  79. supports_autoexpire = True
  80. supports_native_join = True
  81. def __init__(self, host=None, port=None, db=None, password=None,
  82. max_connections=None, url=None,
  83. connection_pool=None, **kwargs):
  84. super(RedisBackend, self).__init__(expires_type=int, **kwargs)
  85. _get = self.app.conf.get
  86. if self.redis is None:
  87. raise ImproperlyConfigured(REDIS_MISSING)
  88. if host and '://' in host:
  89. url = host
  90. host = None
  91. self.max_connections = (
  92. max_connections or
  93. _get('redis_max_connections') or
  94. self.max_connections
  95. )
  96. self._ConnectionPool = connection_pool
  97. self.connparams = {
  98. 'host': _get('redis_host') or 'localhost',
  99. 'port': _get('redis_port') or 6379,
  100. 'db': _get('redis_db') or 0,
  101. 'password': _get('redis_password'),
  102. 'socket_timeout': _get('redis_socket_timeout'),
  103. 'max_connections': self.max_connections,
  104. }
  105. if url:
  106. self.connparams = self._params_from_url(url, self.connparams)
  107. self.url = url
  108. self.connection_errors, self.channel_errors = (
  109. get_redis_error_classes() if get_redis_error_classes
  110. else ((), ()))
  111. self.result_consumer = self.ResultConsumer(
  112. self, self.app, self.accept, self._pending_results)
  113. def _params_from_url(self, url, defaults):
  114. scheme, host, port, user, password, path, query = _parse_url(url)
  115. connparams = dict(
  116. defaults, **dictfilter({
  117. 'host': host, 'port': port, 'password': password,
  118. 'db': query.pop('virtual_host', None)})
  119. )
  120. if scheme == 'socket':
  121. # use 'path' as path to the socket… in this case
  122. # the database number should be given in 'query'
  123. connparams.update({
  124. 'connection_class': self.redis.UnixDomainSocketConnection,
  125. 'path': '/' + path,
  126. })
  127. # host+port are invalid options when using this connection type.
  128. connparams.pop('host', None)
  129. connparams.pop('port', None)
  130. else:
  131. connparams['db'] = path
  132. # db may be string and start with / like in kombu.
  133. db = connparams.get('db') or 0
  134. db = db.strip('/') if isinstance(db, string_t) else db
  135. connparams['db'] = int(db)
  136. # Query parameters override other parameters
  137. connparams.update(query)
  138. return connparams
  139. def on_task_call(self, producer, task_id):
  140. if not task_join_will_block():
  141. self.result_consumer.consume_from(task_id)
  142. def get(self, key):
  143. return self.client.get(key)
  144. def mget(self, keys):
  145. return self.client.mget(keys)
  146. def ensure(self, fun, args, **policy):
  147. retry_policy = dict(self.retry_policy, **policy)
  148. max_retries = retry_policy.get('max_retries')
  149. return retry_over_time(
  150. fun, self.connection_errors, args, {},
  151. partial(self.on_connection_error, max_retries),
  152. **retry_policy
  153. )
  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']