redis.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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
  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._pending_messages,
  118. )
  119. def _params_from_url(self, url, defaults):
  120. scheme, host, port, user, password, path, query = _parse_url(url)
  121. connparams = dict(
  122. defaults, **dictfilter({
  123. 'host': host, 'port': port, 'password': password,
  124. 'db': query.pop('virtual_host', None)})
  125. )
  126. if scheme == 'socket':
  127. # use 'path' as path to the socket… in this case
  128. # the database number should be given in 'query'
  129. connparams.update({
  130. 'connection_class': self.redis.UnixDomainSocketConnection,
  131. 'path': '/' + path,
  132. })
  133. # host+port are invalid options when using this connection type.
  134. connparams.pop('host', None)
  135. connparams.pop('port', None)
  136. else:
  137. connparams['db'] = path
  138. # db may be string and start with / like in kombu.
  139. db = connparams.get('db') or 0
  140. db = db.strip('/') if isinstance(db, string_t) else db
  141. connparams['db'] = int(db)
  142. # Query parameters override other parameters
  143. connparams.update(query)
  144. return connparams
  145. def on_task_call(self, producer, task_id):
  146. if not task_join_will_block():
  147. self.result_consumer.consume_from(task_id)
  148. def get(self, key):
  149. return self.client.get(key)
  150. def mget(self, keys):
  151. return self.client.mget(keys)
  152. def ensure(self, fun, args, **policy):
  153. retry_policy = dict(self.retry_policy, **policy)
  154. max_retries = retry_policy.get('max_retries')
  155. return retry_over_time(
  156. fun, self.connection_errors, args, {},
  157. partial(self.on_connection_error, max_retries),
  158. **retry_policy
  159. )
  160. def on_connection_error(self, max_retries, exc, intervals, retries):
  161. tts = next(intervals)
  162. error(E_LOST, retries, max_retries or 'Inf',
  163. humanize_seconds(tts, 'in '))
  164. return tts
  165. def set(self, key, value, **retry_policy):
  166. return self.ensure(self._set, (key, value), **retry_policy)
  167. def _set(self, key, value):
  168. with self.client.pipeline() as pipe:
  169. if self.expires:
  170. pipe.setex(key, self.expires, value)
  171. else:
  172. pipe.set(key, value)
  173. pipe.publish(key, value)
  174. pipe.execute()
  175. def delete(self, key):
  176. self.client.delete(key)
  177. def incr(self, key):
  178. return self.client.incr(key)
  179. def expire(self, key, value):
  180. return self.client.expire(key, value)
  181. def add_to_chord(self, group_id, result):
  182. self.client.incr(self.get_key_for_group(group_id, '.t'), 1)
  183. def _unpack_chord_result(self, tup, decode,
  184. EXCEPTION_STATES=states.EXCEPTION_STATES,
  185. PROPAGATE_STATES=states.PROPAGATE_STATES):
  186. _, tid, state, retval = decode(tup)
  187. if state in EXCEPTION_STATES:
  188. retval = self.exception_to_python(retval)
  189. if state in PROPAGATE_STATES:
  190. raise ChordError('Dependency {0} raised {1!r}'.format(tid, retval))
  191. return retval
  192. def apply_chord(self, header, partial_args, group_id, body,
  193. result=None, options={}, **kwargs):
  194. # avoids saving the group in the redis db.
  195. options['task_id'] = group_id
  196. return header(*partial_args, **options or {})
  197. def on_chord_part_return(self, request, state, result, propagate=None):
  198. app = self.app
  199. tid, gid = request.id, request.group
  200. if not gid or not tid:
  201. return
  202. client = self.client
  203. jkey = self.get_key_for_group(gid, '.j')
  204. tkey = self.get_key_for_group(gid, '.t')
  205. result = self.encode_result(result, state)
  206. with client.pipeline() as pipe:
  207. _, readycount, totaldiff, _, _ = pipe \
  208. .rpush(jkey, self.encode([1, tid, state, result])) \
  209. .llen(jkey) \
  210. .get(tkey) \
  211. .expire(jkey, 86400) \
  212. .expire(tkey, 86400) \
  213. .execute()
  214. totaldiff = int(totaldiff or 0)
  215. try:
  216. callback = maybe_signature(request.chord, app=app)
  217. total = callback['chord_size'] + totaldiff
  218. if readycount == total:
  219. decode, unpack = self.decode, self._unpack_chord_result
  220. with client.pipeline() as pipe:
  221. resl, _, _ = pipe \
  222. .lrange(jkey, 0, total) \
  223. .delete(jkey) \
  224. .delete(tkey) \
  225. .execute()
  226. try:
  227. callback.delay([unpack(tup, decode) for tup in resl])
  228. except Exception as exc:
  229. error('Chord callback for %r raised: %r',
  230. request.group, exc, exc_info=1)
  231. return self.chord_error_from_stack(
  232. callback,
  233. ChordError('Callback error: {0!r}'.format(exc)),
  234. )
  235. except ChordError as exc:
  236. error('Chord %r raised: %r', request.group, exc, exc_info=1)
  237. return self.chord_error_from_stack(callback, exc)
  238. except Exception as exc:
  239. error('Chord %r raised: %r', request.group, exc, exc_info=1)
  240. return self.chord_error_from_stack(
  241. callback,
  242. ChordError('Join error: {0!r}'.format(exc)),
  243. )
  244. def _create_client(self, socket_timeout=None, socket_connect_timeout=None,
  245. **params):
  246. return self.redis.StrictRedis(
  247. connection_pool=self.ConnectionPool(
  248. socket_timeout=socket_timeout and float(socket_timeout),
  249. socket_connect_timeout=socket_connect_timeout and float(
  250. socket_connect_timeout),
  251. **params),
  252. )
  253. @property
  254. def ConnectionPool(self):
  255. if self._ConnectionPool is None:
  256. self._ConnectionPool = self.redis.ConnectionPool
  257. return self._ConnectionPool
  258. @cached_property
  259. def client(self):
  260. return self._create_client(**self.connparams)
  261. def __reduce__(self, args=(), kwargs={}):
  262. return super(RedisBackend, self).__reduce__(
  263. (self.url,), {'expires': self.expires},
  264. )
  265. @deprecated.Property(4.0, 5.0)
  266. def host(self):
  267. return self.connparams['host']
  268. @deprecated.Property(4.0, 5.0)
  269. def port(self):
  270. return self.connparams['port']
  271. @deprecated.Property(4.0, 5.0)
  272. def db(self):
  273. return self.connparams['db']
  274. @deprecated.Property(4.0, 5.0)
  275. def password(self):
  276. return self.connparams['password']