redis.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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.canvas import maybe_signature
  13. from celery.exceptions import ChordError, ImproperlyConfigured
  14. from celery.five import string_t
  15. from celery.utils import deprecated_property, strtobool
  16. from celery.utils.functional import dictfilter
  17. from celery.utils.log import get_logger
  18. from celery.utils.timeutils import humanize_seconds
  19. from .base import KeyValueStoreBackend
  20. try:
  21. import redis
  22. from redis.exceptions import ConnectionError
  23. from kombu.transport.redis import get_redis_error_classes
  24. except ImportError: # pragma: no cover
  25. redis = None # noqa
  26. ConnectionError = None # noqa
  27. get_redis_error_classes = None # noqa
  28. __all__ = ['RedisBackend']
  29. REDIS_MISSING = """\
  30. You need to install the redis library in order to use \
  31. the Redis result store backend."""
  32. logger = get_logger(__name__)
  33. error = logger.error
  34. class RedisBackend(KeyValueStoreBackend):
  35. """Redis task result store."""
  36. #: redis-py client module.
  37. redis = redis
  38. #: Maximium number of connections in the pool.
  39. max_connections = None
  40. supports_autoexpire = True
  41. supports_native_join = True
  42. implements_incr = True
  43. def __init__(self, host=None, port=None, db=None, password=None,
  44. expires=None, max_connections=None, url=None,
  45. connection_pool=None, new_join=False, **kwargs):
  46. super(RedisBackend, self).__init__(**kwargs)
  47. conf = self.app.conf
  48. if self.redis is None:
  49. raise ImproperlyConfigured(REDIS_MISSING)
  50. # For compatibility with the old REDIS_* configuration keys.
  51. def _get(key):
  52. for prefix in 'CELERY_REDIS_{0}', 'REDIS_{0}':
  53. try:
  54. return conf[prefix.format(key)]
  55. except KeyError:
  56. pass
  57. if host and '://' in host:
  58. url = host
  59. host = None
  60. self.max_connections = (
  61. max_connections or _get('MAX_CONNECTIONS') or self.max_connections
  62. )
  63. self._ConnectionPool = connection_pool
  64. self.connparams = {
  65. 'host': _get('HOST') or 'localhost',
  66. 'port': _get('PORT') or 6379,
  67. 'db': _get('DB') or 0,
  68. 'password': _get('PASSWORD'),
  69. 'max_connections': self.max_connections,
  70. }
  71. if url:
  72. self.connparams = self._params_from_url(url, self.connparams)
  73. self.url = url
  74. self.expires = self.prepare_expires(expires, type=int)
  75. try:
  76. new_join = strtobool(self.connparams.pop('new_join'))
  77. except KeyError:
  78. pass
  79. if new_join:
  80. self.apply_chord = self._new_chord_apply
  81. self.on_chord_part_return = self._new_chord_return
  82. self.connection_errors, self.channel_errors = (
  83. get_redis_error_classes() if get_redis_error_classes
  84. else ((), ()))
  85. def _params_from_url(self, url, defaults):
  86. scheme, host, port, user, password, path, query = _parse_url(url)
  87. connparams = dict(
  88. defaults, **dictfilter({
  89. 'host': host, 'port': port, 'password': password,
  90. 'db': query.pop('virtual_host', None)})
  91. )
  92. if scheme == 'socket':
  93. # use 'path' as path to the socket… in this case
  94. # the database number should be given in 'query'
  95. connparams.update({
  96. 'connection_class': self.redis.UnixDomainSocketConnection,
  97. 'path': '/' + path,
  98. })
  99. # host+port are invalid options when using this connection type.
  100. connparams.pop('host', None)
  101. connparams.pop('port', None)
  102. else:
  103. connparams['db'] = path
  104. # db may be string and start with / like in kombu.
  105. db = connparams.get('db') or 0
  106. db = db.strip('/') if isinstance(db, string_t) else db
  107. connparams['db'] = int(db)
  108. # Query parameters override other parameters
  109. connparams.update(query)
  110. return connparams
  111. def get(self, key):
  112. return self.client.get(key)
  113. def mget(self, keys):
  114. return self.client.mget(keys)
  115. def ensure(self, fun, args, **policy):
  116. retry_policy = dict(self.retry_policy, **policy)
  117. max_retries = retry_policy.get('max_retries')
  118. return retry_over_time(
  119. fun, self.connection_errors, args, {},
  120. partial(self.on_connection_error, max_retries),
  121. **retry_policy
  122. )
  123. def on_connection_error(self, max_retries, exc, intervals, retries):
  124. tts = next(intervals)
  125. error('Connection to Redis lost: Retry (%s/%s) %s.',
  126. retries, max_retries or 'Inf',
  127. humanize_seconds(tts, 'in '))
  128. return tts
  129. def set(self, key, value, **retry_policy):
  130. return self.ensure(self._set, (key, value), **retry_policy)
  131. def _set(self, key, value):
  132. pipe = self.client.pipeline()
  133. if self.expires:
  134. pipe.setex(key, value, self.expires)
  135. else:
  136. pipe.set(key, value)
  137. pipe.publish(key, value)
  138. pipe.execute()
  139. def delete(self, key):
  140. self.client.delete(key)
  141. def incr(self, key):
  142. return self.client.incr(key)
  143. def expire(self, key, value):
  144. return self.client.expire(key, value)
  145. def _unpack_chord_result(self, tup, decode,
  146. EXCEPTION_STATES=states.EXCEPTION_STATES,
  147. PROPAGATE_STATES=states.PROPAGATE_STATES):
  148. _, tid, state, retval = decode(tup)
  149. if state in EXCEPTION_STATES:
  150. retval = self.exception_to_python(retval)
  151. if state in PROPAGATE_STATES:
  152. raise ChordError('Dependency {0} raised {1!r}'.format(tid, retval))
  153. return retval
  154. def _new_chord_apply(self, header, partial_args, group_id, body,
  155. result=None, **options):
  156. # avoids saving the group in the redis db.
  157. return header(*partial_args, task_id=group_id)
  158. def _new_chord_return(self, task, state, result, propagate=None,
  159. PROPAGATE_STATES=states.PROPAGATE_STATES):
  160. app = self.app
  161. if propagate is None:
  162. propagate = self.app.conf.CELERY_CHORD_PROPAGATES
  163. request = task.request
  164. tid, gid = request.id, request.group
  165. if not gid or not tid:
  166. return
  167. client = self.client
  168. jkey = self.get_key_for_group(gid, '.j')
  169. result = self.encode_result(result, state)
  170. _, readycount, _ = client.pipeline() \
  171. .rpush(jkey, self.encode([1, tid, state, result])) \
  172. .llen(jkey) \
  173. .expire(jkey, 86400) \
  174. .execute()
  175. try:
  176. callback = maybe_signature(request.chord, app=app)
  177. total = callback['chord_size']
  178. if readycount == total:
  179. decode, unpack = self.decode, self._unpack_chord_result
  180. resl, _ = client.pipeline() \
  181. .lrange(jkey, 0, total) \
  182. .delete(jkey) \
  183. .execute()
  184. try:
  185. callback.delay([unpack(tup, decode) for tup in resl])
  186. except Exception as exc:
  187. error('Chord callback for %r raised: %r',
  188. request.group, exc, exc_info=1)
  189. app._tasks[callback.task].backend.fail_from_current_stack(
  190. callback.id,
  191. exc=ChordError('Callback error: {0!r}'.format(exc)),
  192. )
  193. except ChordError as exc:
  194. error('Chord %r raised: %r', request.group, exc, exc_info=1)
  195. app._tasks[callback.task].backend.fail_from_current_stack(
  196. callback.id, exc=exc,
  197. )
  198. except Exception as exc:
  199. error('Chord %r raised: %r', request.group, exc, exc_info=1)
  200. app._tasks[callback.task].backend.fail_from_current_stack(
  201. callback.id, exc=ChordError('Join error: {0!r}'.format(exc)),
  202. )
  203. @property
  204. def ConnectionPool(self):
  205. if self._ConnectionPool is None:
  206. self._ConnectionPool = self.redis.ConnectionPool
  207. return self._ConnectionPool
  208. @cached_property
  209. def client(self):
  210. return self.redis.Redis(
  211. connection_pool=self.ConnectionPool(**self.connparams),
  212. )
  213. def __reduce__(self, args=(), kwargs={}):
  214. return super(RedisBackend, self).__reduce__(
  215. (self.url, ), {'expires': self.expires},
  216. )
  217. @deprecated_property(3.2, 3.3)
  218. def host(self):
  219. return self.connparams['host']
  220. @deprecated_property(3.2, 3.3)
  221. def port(self):
  222. return self.connparams['port']
  223. @deprecated_property(3.2, 3.3)
  224. def db(self):
  225. return self.connparams['db']
  226. @deprecated_property(3.2, 3.3)
  227. def password(self):
  228. return self.connparams['password']