redis.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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. max_connections=None, url=None,
  45. connection_pool=None, new_join=False, **kwargs):
  46. super(RedisBackend, self).__init__(expires_type=int, **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. try:
  75. new_join = strtobool(self.connparams.pop('new_join'))
  76. except KeyError:
  77. pass
  78. if new_join:
  79. self.apply_chord = self._new_chord_apply
  80. self.on_chord_part_return = self._new_chord_return
  81. self.connection_errors, self.channel_errors = (
  82. get_redis_error_classes() if get_redis_error_classes
  83. else ((), ()))
  84. def _params_from_url(self, url, defaults):
  85. scheme, host, port, user, password, path, query = _parse_url(url)
  86. connparams = dict(
  87. defaults, **dictfilter({
  88. 'host': host, 'port': port, 'password': password,
  89. 'db': query.pop('virtual_host', None)})
  90. )
  91. if scheme == 'socket':
  92. # use 'path' as path to the socket… in this case
  93. # the database number should be given in 'query'
  94. connparams.update({
  95. 'connection_class': self.redis.UnixDomainSocketConnection,
  96. 'path': '/' + path,
  97. })
  98. # host+port are invalid options when using this connection type.
  99. connparams.pop('host', None)
  100. connparams.pop('port', None)
  101. else:
  102. connparams['db'] = path
  103. # db may be string and start with / like in kombu.
  104. db = connparams.get('db') or 0
  105. db = db.strip('/') if isinstance(db, string_t) else db
  106. connparams['db'] = int(db)
  107. # Query parameters override other parameters
  108. connparams.update(query)
  109. connparams.update(socket_timeout=5)
  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 add_to_chord(self, group_id, result):
  146. self.client.incr(self.get_key_for_group(group_id, '.t'), 1)
  147. def _unpack_chord_result(self, tup, decode,
  148. EXCEPTION_STATES=states.EXCEPTION_STATES,
  149. PROPAGATE_STATES=states.PROPAGATE_STATES):
  150. _, tid, state, retval = decode(tup)
  151. if state in EXCEPTION_STATES:
  152. retval = self.exception_to_python(retval)
  153. if state in PROPAGATE_STATES:
  154. raise ChordError('Dependency {0} raised {1!r}'.format(tid, retval))
  155. return retval
  156. def _new_chord_apply(self, header, partial_args, group_id, body,
  157. result=None, options={}, **kwargs):
  158. # avoids saving the group in the redis db.
  159. options['task_id'] = group_id
  160. return header(*partial_args, **options or {})
  161. def _new_chord_return(self, task, state, result, propagate=None,
  162. PROPAGATE_STATES=states.PROPAGATE_STATES):
  163. app = self.app
  164. if propagate is None:
  165. propagate = self.app.conf.CELERY_CHORD_PROPAGATES
  166. request = task.request
  167. tid, gid = request.id, request.group
  168. if not gid or not tid:
  169. return
  170. client = self.client
  171. jkey = self.get_key_for_group(gid, '.j')
  172. tkey = self.get_key_for_group(gid, '.t')
  173. result = self.encode_result(result, state)
  174. _, readycount, totaldiff, _, _ = client.pipeline() \
  175. .rpush(jkey, self.encode([1, tid, state, result])) \
  176. .llen(jkey) \
  177. .get(tkey) \
  178. .expire(jkey, 86400) \
  179. .expire(tkey, 86400) \
  180. .execute()
  181. totaldiff = int(totaldiff or 0)
  182. try:
  183. callback = maybe_signature(request.chord, app=app)
  184. total = callback['chord_size'] + totaldiff
  185. if readycount == total:
  186. decode, unpack = self.decode, self._unpack_chord_result
  187. resl, _, _ = client.pipeline() \
  188. .lrange(jkey, 0, total) \
  189. .delete(jkey) \
  190. .delete(tkey) \
  191. .execute()
  192. try:
  193. callback.delay([unpack(tup, decode) for tup in resl])
  194. except Exception as exc:
  195. error('Chord callback for %r raised: %r',
  196. request.group, exc, exc_info=1)
  197. app._tasks[callback.task].backend.fail_from_current_stack(
  198. callback.id,
  199. exc=ChordError('Callback error: {0!r}'.format(exc)),
  200. )
  201. except ChordError as exc:
  202. error('Chord %r raised: %r', request.group, exc, exc_info=1)
  203. app._tasks[callback.task].backend.fail_from_current_stack(
  204. callback.id, exc=exc,
  205. )
  206. except Exception as exc:
  207. error('Chord %r raised: %r', request.group, exc, exc_info=1)
  208. app._tasks[callback.task].backend.fail_from_current_stack(
  209. callback.id, exc=ChordError('Join error: {0!r}'.format(exc)),
  210. )
  211. @property
  212. def ConnectionPool(self):
  213. if self._ConnectionPool is None:
  214. self._ConnectionPool = self.redis.ConnectionPool
  215. return self._ConnectionPool
  216. @cached_property
  217. def client(self):
  218. return self.redis.Redis(
  219. connection_pool=self.ConnectionPool(**self.connparams),
  220. )
  221. def __reduce__(self, args=(), kwargs={}):
  222. return super(RedisBackend, self).__reduce__(
  223. (self.url, ), {'expires': self.expires},
  224. )
  225. @deprecated_property(3.2, 3.3)
  226. def host(self):
  227. return self.connparams['host']
  228. @deprecated_property(3.2, 3.3)
  229. def port(self):
  230. return self.connparams['port']
  231. @deprecated_property(3.2, 3.3)
  232. def db(self):
  233. return self.connparams['db']
  234. @deprecated_property(3.2, 3.3)
  235. def password(self):
  236. return self.connparams['password']