Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

redis.py 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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. self._client_capabilities = self._detect_client_capabilities()
  51. # For compatibility with the old REDIS_* configuration keys.
  52. def _get(key):
  53. for prefix in 'CELERY_REDIS_{0}', 'REDIS_{0}':
  54. try:
  55. return conf[prefix.format(key)]
  56. except KeyError:
  57. pass
  58. if host and '://' in host:
  59. url = host
  60. host = None
  61. self.max_connections = (
  62. max_connections or _get('MAX_CONNECTIONS') or self.max_connections
  63. )
  64. self._ConnectionPool = connection_pool
  65. self.connparams = {
  66. 'host': _get('HOST') or 'localhost',
  67. 'port': _get('PORT') or 6379,
  68. 'db': _get('DB') or 0,
  69. 'password': _get('PASSWORD'),
  70. 'max_connections': self.max_connections,
  71. }
  72. if url:
  73. self.connparams = self._params_from_url(url, self.connparams)
  74. self.url = url
  75. self.expires = self.prepare_expires(expires, type=int)
  76. try:
  77. new_join = strtobool(self.connparams.pop('new_join'))
  78. except KeyError:
  79. pass
  80. if new_join:
  81. self.apply_chord = self._new_chord_apply
  82. self.on_chord_part_return = self._new_chord_return
  83. self.connection_errors, self.channel_errors = (
  84. get_redis_error_classes() if get_redis_error_classes
  85. else ((), ()))
  86. def _params_from_url(self, url, defaults):
  87. scheme, host, port, user, password, path, query = _parse_url(url)
  88. connparams = dict(
  89. defaults, **dictfilter({
  90. 'host': host, 'port': port, 'password': password,
  91. 'db': query.pop('virtual_host', None)})
  92. )
  93. if scheme == 'socket':
  94. # use 'path' as path to the socket… in this case
  95. # the database number should be given in 'query'
  96. connparams.update({
  97. 'connection_class': self.redis.UnixDomainSocketConnection,
  98. 'path': '/' + path,
  99. })
  100. # host+port are invalid options when using this connection type.
  101. connparams.pop('host', None)
  102. connparams.pop('port', None)
  103. else:
  104. connparams['db'] = path
  105. # db may be string and start with / like in kombu.
  106. db = connparams.get('db') or 0
  107. db = db.strip('/') if isinstance(db, string_t) else db
  108. connparams['db'] = int(db)
  109. # Query parameters override other parameters
  110. connparams.update(query)
  111. return connparams
  112. def get(self, key):
  113. return self.client.get(key)
  114. def mget(self, keys):
  115. return self.client.mget(keys)
  116. def ensure(self, fun, args, **policy):
  117. retry_policy = dict(self.retry_policy, **policy)
  118. max_retries = retry_policy.get('max_retries')
  119. return retry_over_time(
  120. fun, self.connection_errors, args, {},
  121. partial(self.on_connection_error, max_retries),
  122. **retry_policy
  123. )
  124. def on_connection_error(self, max_retries, exc, intervals, retries):
  125. tts = next(intervals)
  126. error('Connection to Redis lost: Retry (%s/%s) %s.',
  127. retries, max_retries or 'Inf',
  128. humanize_seconds(tts, 'in '))
  129. return tts
  130. def set(self, key, value, **retry_policy):
  131. return self.ensure(self._set, (key, value), **retry_policy)
  132. def _set(self, key, value):
  133. with self.client.pipeline() as pipe:
  134. if self.expires:
  135. pipe.setex(key, value, self.expires)
  136. else:
  137. pipe.set(key, value)
  138. pipe.publish(key, value)
  139. pipe.execute()
  140. def delete(self, key):
  141. self.client.delete(key)
  142. def incr(self, key):
  143. return self.client.incr(key)
  144. def expire(self, key, value):
  145. return self.client.expire(key, value)
  146. def _unpack_chord_result(self, tup, decode,
  147. EXCEPTION_STATES=states.EXCEPTION_STATES,
  148. PROPAGATE_STATES=states.PROPAGATE_STATES):
  149. _, tid, state, retval = decode(tup)
  150. if state in EXCEPTION_STATES:
  151. retval = self.exception_to_python(retval)
  152. if state in PROPAGATE_STATES:
  153. raise ChordError('Dependency {0} raised {1!r}'.format(tid, retval))
  154. return retval
  155. def _new_chord_apply(self, header, partial_args, group_id, body,
  156. result=None, **options):
  157. # avoids saving the group in the redis db.
  158. return header(*partial_args, task_id=group_id)
  159. def _new_chord_return(self, task, state, result, propagate=None,
  160. PROPAGATE_STATES=states.PROPAGATE_STATES):
  161. app = self.app
  162. if propagate is None:
  163. propagate = self.app.conf.CELERY_CHORD_PROPAGATES
  164. request = task.request
  165. tid, gid = request.id, request.group
  166. if not gid or not tid:
  167. return
  168. client = self.client
  169. jkey = self.get_key_for_group(gid, '.j')
  170. result = self.encode_result(result, state)
  171. with client.pipeline() as pipe:
  172. _, readycount, _ = pipe \
  173. .rpush(jkey, self.encode([1, tid, state, result])) \
  174. .llen(jkey) \
  175. .expire(jkey, 86400) \
  176. .execute()
  177. try:
  178. callback = maybe_signature(request.chord, app=app)
  179. total = callback['chord_size']
  180. if readycount == total:
  181. decode, unpack = self.decode, self._unpack_chord_result
  182. with client.pipeline() as pipe:
  183. resl, _, = pipe \
  184. .lrange(jkey, 0, total) \
  185. .delete(jkey) \
  186. .execute()
  187. try:
  188. callback.delay([unpack(tup, decode) for tup in resl])
  189. except Exception as exc:
  190. error('Chord callback for %r raised: %r',
  191. request.group, exc, exc_info=1)
  192. return self.chord_error_from_stack(
  193. callback,
  194. ChordError('Callback error: {0!r}'.format(exc)),
  195. )
  196. except ChordError as exc:
  197. error('Chord %r raised: %r', request.group, exc, exc_info=1)
  198. return self.chord_error_from_stack(callback, exc)
  199. except Exception as exc:
  200. error('Chord %r raised: %r', request.group, exc, exc_info=1)
  201. return self.chord_error_from_stack(
  202. callback, ChordError('Join error: {0!r}'.format(exc)),
  203. )
  204. def _detect_client_capabilities(self, socket_connect_timeout=False):
  205. if self.redis.VERSION < (2, 4, 4):
  206. raise ImproperlyConfigured(
  207. 'Redis backend requires redis-py versions 2.4.4 or later. '
  208. 'You have {0.__version__}'.format(redis))
  209. if self.redis.VERSION >= (2, 10):
  210. socket_connect_timeout = True
  211. return {'socket_connect_timeout': socket_connect_timeout}
  212. def _create_client(self, socket_timeout=None, socket_connect_timeout=None,
  213. **params):
  214. return self._new_redis_client(
  215. socket_timeout=socket_timeout and float(socket_timeout),
  216. socket_connect_timeout=socket_connect_timeout and float(
  217. socket_connect_timeout), **params
  218. )
  219. def _new_redis_client(self, **params):
  220. if not self._client_capabilities['socket_connect_timeout']:
  221. params.pop('socket_connect_timeout', None)
  222. return self.redis.Redis(connection_pool=self.ConnectionPool(**params))
  223. @property
  224. def ConnectionPool(self):
  225. if self._ConnectionPool is None:
  226. self._ConnectionPool = self.redis.ConnectionPool
  227. return self._ConnectionPool
  228. @cached_property
  229. def client(self):
  230. return self._create_client(**self.connparams)
  231. def __reduce__(self, args=(), kwargs={}):
  232. return super(RedisBackend, self).__reduce__(
  233. (self.url, ), {'expires': self.expires},
  234. )
  235. @deprecated_property(3.2, 3.3)
  236. def host(self):
  237. return self.connparams['host']
  238. @deprecated_property(3.2, 3.3)
  239. def port(self):
  240. return self.connparams['port']
  241. @deprecated_property(3.2, 3.3)
  242. def db(self):
  243. return self.connparams['db']
  244. @deprecated_property(3.2, 3.3)
  245. def password(self):
  246. return self.connparams['password']