redis.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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. for key in ['socket_timeout', 'socket_connect_timeout']:
  109. if key in query:
  110. query[key] = float(query[key])
  111. # Query parameters override other parameters
  112. connparams.update(query)
  113. return connparams
  114. def get(self, key):
  115. return self.client.get(key)
  116. def mget(self, keys):
  117. return self.client.mget(keys)
  118. def ensure(self, fun, args, **policy):
  119. retry_policy = dict(self.retry_policy, **policy)
  120. max_retries = retry_policy.get('max_retries')
  121. return retry_over_time(
  122. fun, self.connection_errors, args, {},
  123. partial(self.on_connection_error, max_retries),
  124. **retry_policy
  125. )
  126. def on_connection_error(self, max_retries, exc, intervals, retries):
  127. tts = next(intervals)
  128. error('Connection to Redis lost: Retry (%s/%s) %s.',
  129. retries, max_retries or 'Inf',
  130. humanize_seconds(tts, 'in '))
  131. return tts
  132. def set(self, key, value, **retry_policy):
  133. return self.ensure(self._set, (key, value), **retry_policy)
  134. def _set(self, key, value):
  135. with self.client.pipeline() as pipe:
  136. if self.expires:
  137. pipe.setex(key, value, self.expires)
  138. else:
  139. pipe.set(key, value)
  140. pipe.publish(key, value)
  141. pipe.execute()
  142. def delete(self, key):
  143. self.client.delete(key)
  144. def incr(self, key):
  145. return self.client.incr(key)
  146. def expire(self, key, value):
  147. return self.client.expire(key, value)
  148. def _unpack_chord_result(self, tup, decode,
  149. EXCEPTION_STATES=states.EXCEPTION_STATES,
  150. PROPAGATE_STATES=states.PROPAGATE_STATES):
  151. _, tid, state, retval = decode(tup)
  152. if state in EXCEPTION_STATES:
  153. retval = self.exception_to_python(retval)
  154. if state in PROPAGATE_STATES:
  155. raise ChordError('Dependency {0} raised {1!r}'.format(tid, retval))
  156. return retval
  157. def _new_chord_apply(self, header, partial_args, group_id, body,
  158. result=None, **options):
  159. # avoids saving the group in the redis db.
  160. return header(*partial_args, task_id=group_id)
  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. result = self.encode_result(result, state)
  173. with client.pipeline() as pipe:
  174. _, readycount, _ = pipe \
  175. .rpush(jkey, self.encode([1, tid, state, result])) \
  176. .llen(jkey) \
  177. .expire(jkey, 86400) \
  178. .execute()
  179. try:
  180. callback = maybe_signature(request.chord, app=app)
  181. total = callback['chord_size']
  182. if readycount == total:
  183. decode, unpack = self.decode, self._unpack_chord_result
  184. with client.pipeline() as pipe:
  185. resl, _, = pipe \
  186. .lrange(jkey, 0, total) \
  187. .delete(jkey) \
  188. .execute()
  189. try:
  190. callback.delay([unpack(tup, decode) for tup in resl])
  191. except Exception as exc:
  192. error('Chord callback for %r raised: %r',
  193. request.group, exc, exc_info=1)
  194. app._tasks[callback.task].backend.fail_from_current_stack(
  195. callback.id,
  196. exc=ChordError('Callback error: {0!r}'.format(exc)),
  197. )
  198. except ChordError 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=exc,
  202. )
  203. except Exception as exc:
  204. error('Chord %r raised: %r', request.group, exc, exc_info=1)
  205. app._tasks[callback.task].backend.fail_from_current_stack(
  206. callback.id, exc=ChordError('Join error: {0!r}'.format(exc)),
  207. )
  208. @property
  209. def ConnectionPool(self):
  210. if self._ConnectionPool is None:
  211. self._ConnectionPool = self.redis.ConnectionPool
  212. return self._ConnectionPool
  213. @cached_property
  214. def client(self):
  215. return self.redis.Redis(
  216. connection_pool=self.ConnectionPool(**self.connparams),
  217. )
  218. def __reduce__(self, args=(), kwargs={}):
  219. return super(RedisBackend, self).__reduce__(
  220. (self.url, ), {'expires': self.expires},
  221. )
  222. @deprecated_property(3.2, 3.3)
  223. def host(self):
  224. return self.connparams['host']
  225. @deprecated_property(3.2, 3.3)
  226. def port(self):
  227. return self.connparams['port']
  228. @deprecated_property(3.2, 3.3)
  229. def db(self):
  230. return self.connparams['db']
  231. @deprecated_property(3.2, 3.3)
  232. def password(self):
  233. return self.connparams['password']