redis.py 9.8 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. 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. with self.client.pipeline() as pipe:
  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. with client.pipeline() as pipe:
  171. _, readycount, _ = pipe \
  172. .rpush(jkey, self.encode([1, tid, state, result])) \
  173. .llen(jkey) \
  174. .expire(jkey, 86400) \
  175. .execute()
  176. try:
  177. callback = maybe_signature(request.chord, app=app)
  178. total = callback['chord_size']
  179. if readycount == total:
  180. decode, unpack = self.decode, self._unpack_chord_result
  181. with client.pipeline() as pipe:
  182. resl, _, = pipe \
  183. .lrange(jkey, 0, total) \
  184. .delete(jkey) \
  185. .execute()
  186. try:
  187. callback.delay([unpack(tup, decode) for tup in resl])
  188. except Exception as exc:
  189. error('Chord callback for %r raised: %r',
  190. request.group, exc, exc_info=1)
  191. app._tasks[callback.task].backend.fail_from_current_stack(
  192. callback.id,
  193. exc=ChordError('Callback error: {0!r}'.format(exc)),
  194. )
  195. except ChordError as exc:
  196. error('Chord %r raised: %r', request.group, exc, exc_info=1)
  197. app._tasks[callback.task].backend.fail_from_current_stack(
  198. callback.id, exc=exc,
  199. )
  200. except Exception as exc:
  201. error('Chord %r raised: %r', request.group, exc, exc_info=1)
  202. app._tasks[callback.task].backend.fail_from_current_stack(
  203. callback.id, exc=ChordError('Join error: {0!r}'.format(exc)),
  204. )
  205. def _create_client(self, socket_timeout=None, socket_connect_timeout=None,
  206. **params):
  207. return self.redis.Redis(
  208. connection_pool=self.ConnectionPool(
  209. socket_timeout=socket_timeout and float(socket_timeout),
  210. socket_connect_timeout=socket_connect_timeout and float(
  211. socket_connect_timeout),
  212. **params),
  213. )
  214. @property
  215. def ConnectionPool(self):
  216. if self._ConnectionPool is None:
  217. self._ConnectionPool = self.redis.ConnectionPool
  218. return self._ConnectionPool
  219. @cached_property
  220. def client(self):
  221. return self._create_client(**self.connparams)
  222. def __reduce__(self, args=(), kwargs={}):
  223. return super(RedisBackend, self).__reduce__(
  224. (self.url, ), {'expires': self.expires},
  225. )
  226. @deprecated_property(3.2, 3.3)
  227. def host(self):
  228. return self.connparams['host']
  229. @deprecated_property(3.2, 3.3)
  230. def port(self):
  231. return self.connparams['port']
  232. @deprecated_property(3.2, 3.3)
  233. def db(self):
  234. return self.connparams['db']
  235. @deprecated_property(3.2, 3.3)
  236. def password(self):
  237. return self.connparams['password']