redis.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. # -*- coding: utf-8 -*-
  2. """
  3. ``celery.backends.redis``
  4. ~~~~~~~~~~~~~~~~~~~~~~~~~
  5. Redis result store backend.
  6. """
  7. from __future__ import absolute_import, unicode_literals
  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 on_wait_for_pending(self, result, **kwargs):
  52. for meta in result._iter_meta():
  53. if meta is not None:
  54. self.on_state_change(meta, None)
  55. def stop(self):
  56. if self._pubsub is not None:
  57. self._pubsub.close()
  58. def drain_events(self, timeout=None):
  59. m = self._pubsub.get_message(timeout=timeout)
  60. if m and m['type'] == 'message':
  61. self.on_state_change(self._decode_result(m['data']), m)
  62. def consume_from(self, task_id):
  63. if self._pubsub is None:
  64. return self.start(task_id)
  65. self._consume_from(task_id)
  66. def _consume_from(self, task_id):
  67. key = self._get_key_for_task(task_id)
  68. if key not in self.subscribed_to:
  69. self.subscribed_to.add(key)
  70. self._pubsub.subscribe(key)
  71. def cancel_for(self, task_id):
  72. if self._pubsub:
  73. key = self._get_key_for_task(task_id)
  74. self.subscribed_to.discard(key)
  75. self._pubsub.unsubscribe(key)
  76. class RedisBackend(base.BaseKeyValueStoreBackend, async.AsyncBackendMixin):
  77. """Redis task result store."""
  78. ResultConsumer = ResultConsumer
  79. #: :pypi:`redis` client module.
  80. redis = redis
  81. #: Maximum number of connections in the pool.
  82. max_connections = None
  83. supports_autoexpire = True
  84. supports_native_join = True
  85. def __init__(self, host=None, port=None, db=None, password=None,
  86. max_connections=None, url=None,
  87. connection_pool=None, **kwargs):
  88. super(RedisBackend, self).__init__(expires_type=int, **kwargs)
  89. _get = self.app.conf.get
  90. if self.redis is None:
  91. raise ImproperlyConfigured(REDIS_MISSING)
  92. if host and '://' in host:
  93. url = host
  94. host = None
  95. self.max_connections = (
  96. max_connections or
  97. _get('redis_max_connections') or
  98. self.max_connections
  99. )
  100. self._ConnectionPool = connection_pool
  101. self.connparams = {
  102. 'host': _get('redis_host') or 'localhost',
  103. 'port': _get('redis_port') or 6379,
  104. 'db': _get('redis_db') or 0,
  105. 'password': _get('redis_password'),
  106. 'socket_timeout': _get('redis_socket_timeout'),
  107. 'max_connections': self.max_connections,
  108. }
  109. if url:
  110. self.connparams = self._params_from_url(url, self.connparams)
  111. self.url = url
  112. self.connection_errors, self.channel_errors = (
  113. get_redis_error_classes() if get_redis_error_classes
  114. else ((), ()))
  115. self.result_consumer = self.ResultConsumer(
  116. self, self.app, self.accept,
  117. self._pending_results, self._weak_pending_results)
  118. def _params_from_url(self, url, defaults):
  119. scheme, host, port, user, password, path, query = _parse_url(url)
  120. connparams = dict(
  121. defaults, **dictfilter({
  122. 'host': host, 'port': port, 'password': password,
  123. 'db': query.pop('virtual_host', None)})
  124. )
  125. if scheme == 'socket':
  126. # use 'path' as path to the socket… in this case
  127. # the database number should be given in 'query'
  128. connparams.update({
  129. 'connection_class': self.redis.UnixDomainSocketConnection,
  130. 'path': '/' + path,
  131. })
  132. # host+port are invalid options when using this connection type.
  133. connparams.pop('host', None)
  134. connparams.pop('port', None)
  135. else:
  136. connparams['db'] = path
  137. # db may be string and start with / like in kombu.
  138. db = connparams.get('db') or 0
  139. db = db.strip('/') if isinstance(db, string_t) else db
  140. connparams['db'] = int(db)
  141. # Query parameters override other parameters
  142. connparams.update(query)
  143. return connparams
  144. def on_task_call(self, producer, task_id):
  145. if not task_join_will_block():
  146. self.result_consumer.consume_from(task_id)
  147. def get(self, key):
  148. return self.client.get(key)
  149. def mget(self, keys):
  150. return self.client.mget(keys)
  151. def ensure(self, fun, args, **policy):
  152. retry_policy = dict(self.retry_policy, **policy)
  153. max_retries = retry_policy.get('max_retries')
  154. return retry_over_time(
  155. fun, self.connection_errors, args, {},
  156. partial(self.on_connection_error, max_retries),
  157. **retry_policy
  158. )
  159. def on_connection_error(self, max_retries, exc, intervals, retries):
  160. tts = next(intervals)
  161. error(E_LOST, retries, max_retries or 'Inf',
  162. humanize_seconds(tts, 'in '))
  163. return tts
  164. def set(self, key, value, **retry_policy):
  165. return self.ensure(self._set, (key, value), **retry_policy)
  166. def _set(self, key, value):
  167. with self.client.pipeline() as pipe:
  168. if self.expires:
  169. pipe.setex(key, self.expires, value)
  170. else:
  171. pipe.set(key, value)
  172. pipe.publish(key, value)
  173. pipe.execute()
  174. def delete(self, key):
  175. self.client.delete(key)
  176. def incr(self, key):
  177. return self.client.incr(key)
  178. def expire(self, key, value):
  179. return self.client.expire(key, value)
  180. def add_to_chord(self, group_id, result):
  181. self.client.incr(self.get_key_for_group(group_id, '.t'), 1)
  182. def _unpack_chord_result(self, tup, decode,
  183. EXCEPTION_STATES=states.EXCEPTION_STATES,
  184. PROPAGATE_STATES=states.PROPAGATE_STATES):
  185. _, tid, state, retval = decode(tup)
  186. if state in EXCEPTION_STATES:
  187. retval = self.exception_to_python(retval)
  188. if state in PROPAGATE_STATES:
  189. raise ChordError('Dependency {0} raised {1!r}'.format(tid, retval))
  190. return retval
  191. def apply_chord(self, header, partial_args, group_id, body,
  192. result=None, options={}, **kwargs):
  193. # avoids saving the group in the redis db.
  194. options['task_id'] = group_id
  195. return header(*partial_args, **options or {})
  196. def on_chord_part_return(self, request, state, result, propagate=None):
  197. app = self.app
  198. tid, gid = request.id, request.group
  199. if not gid or not tid:
  200. return
  201. client = self.client
  202. jkey = self.get_key_for_group(gid, '.j')
  203. tkey = self.get_key_for_group(gid, '.t')
  204. result = self.encode_result(result, state)
  205. with client.pipeline() as pipe:
  206. _, readycount, totaldiff, _, _ = pipe \
  207. .rpush(jkey, self.encode([1, tid, state, result])) \
  208. .llen(jkey) \
  209. .get(tkey) \
  210. .expire(jkey, 86400) \
  211. .expire(tkey, 86400) \
  212. .execute()
  213. totaldiff = int(totaldiff or 0)
  214. try:
  215. callback = maybe_signature(request.chord, app=app)
  216. total = callback['chord_size'] + totaldiff
  217. if readycount == total:
  218. decode, unpack = self.decode, self._unpack_chord_result
  219. with client.pipeline() as pipe:
  220. resl, _, _ = pipe \
  221. .lrange(jkey, 0, total) \
  222. .delete(jkey) \
  223. .delete(tkey) \
  224. .execute()
  225. try:
  226. callback.delay([unpack(tup, decode) for tup in resl])
  227. except Exception as exc:
  228. error('Chord callback for %r raised: %r',
  229. request.group, exc, exc_info=1)
  230. return self.chord_error_from_stack(
  231. callback,
  232. ChordError('Callback error: {0!r}'.format(exc)),
  233. )
  234. except ChordError as exc:
  235. error('Chord %r raised: %r', request.group, exc, exc_info=1)
  236. return self.chord_error_from_stack(callback, exc)
  237. except Exception as exc:
  238. error('Chord %r raised: %r', request.group, exc, exc_info=1)
  239. return self.chord_error_from_stack(
  240. callback,
  241. ChordError('Join error: {0!r}'.format(exc)),
  242. )
  243. def _create_client(self, socket_timeout=None, socket_connect_timeout=None,
  244. **params):
  245. return self.redis.StrictRedis(
  246. connection_pool=self.ConnectionPool(
  247. socket_timeout=socket_timeout and float(socket_timeout),
  248. socket_connect_timeout=socket_connect_timeout and float(
  249. socket_connect_timeout),
  250. **params),
  251. )
  252. @property
  253. def ConnectionPool(self):
  254. if self._ConnectionPool is None:
  255. self._ConnectionPool = self.redis.ConnectionPool
  256. return self._ConnectionPool
  257. @cached_property
  258. def client(self):
  259. return self._create_client(**self.connparams)
  260. def __reduce__(self, args=(), kwargs={}):
  261. return super(RedisBackend, self).__reduce__(
  262. (self.url,), {'expires': self.expires},
  263. )
  264. @deprecated_property(4.0, 5.0)
  265. def host(self):
  266. return self.connparams['host']
  267. @deprecated_property(4.0, 5.0)
  268. def port(self):
  269. return self.connparams['port']
  270. @deprecated_property(4.0, 5.0)
  271. def db(self):
  272. return self.connparams['db']
  273. @deprecated_property(4.0, 5.0)
  274. def password(self):
  275. return self.connparams['password']