base.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. # -*- coding: utf-8 -*-
  2. """
  3. celery.backends.base
  4. ~~~~~~~~~~~~~~~~~~~~
  5. Result backend base classes.
  6. - :class:`BaseBackend` defines the interface.
  7. - :class:`BaseDictBackend` assumes the fields are stored in a dict.
  8. - :class:`KeyValueStoreBackend` is a common base class
  9. using K/V semantics like _get and _put.
  10. """
  11. from __future__ import absolute_import
  12. import time
  13. import sys
  14. from datetime import timedelta
  15. from kombu import serialization
  16. from kombu.utils.encoding import bytes_to_str, ensure_bytes, from_utf8
  17. from celery import states
  18. from celery.app import current_task
  19. from celery.datastructures import LRUCache
  20. from celery.exceptions import TimeoutError, TaskRevokedError
  21. from celery.result import from_serializable, GroupResult
  22. from celery.utils import timeutils
  23. from celery.utils.serialization import (
  24. get_pickled_exception,
  25. get_pickleable_exception,
  26. create_exception_cls,
  27. )
  28. EXCEPTION_ABLE_CODECS = frozenset(['pickle', 'yaml'])
  29. is_py3k = sys.version_info >= (3, 0)
  30. def unpickle_backend(cls, args, kwargs):
  31. """Returns an unpickled backend."""
  32. return cls(*args, **kwargs)
  33. class BaseBackend(object):
  34. """Base backend class."""
  35. READY_STATES = states.READY_STATES
  36. UNREADY_STATES = states.UNREADY_STATES
  37. EXCEPTION_STATES = states.EXCEPTION_STATES
  38. TimeoutError = TimeoutError
  39. #: Time to sleep between polling each individual item
  40. #: in `ResultSet.iterate`. as opposed to the `interval`
  41. #: argument which is for each pass.
  42. subpolling_interval = None
  43. #: If true the backend must implement :meth:`get_many`.
  44. supports_native_join = False
  45. def __init__(self, *args, **kwargs):
  46. from celery.app import app_or_default
  47. self.app = app_or_default(kwargs.get('app'))
  48. self.serializer = kwargs.get('serializer',
  49. self.app.conf.CELERY_RESULT_SERIALIZER)
  50. (self.content_type,
  51. self.content_encoding,
  52. self.encoder) = serialization.registry._encoders[self.serializer]
  53. def encode(self, data):
  54. _, _, payload = serialization.encode(data, serializer=self.serializer)
  55. return payload
  56. def decode(self, payload):
  57. payload = is_py3k and payload or str(payload)
  58. return serialization.decode(payload,
  59. content_type=self.content_type,
  60. content_encoding=self.content_encoding)
  61. def prepare_expires(self, value, type=None):
  62. if value is None:
  63. value = self.app.conf.CELERY_TASK_RESULT_EXPIRES
  64. if isinstance(value, timedelta):
  65. value = timeutils.timedelta_seconds(value)
  66. if value is not None and type:
  67. return type(value)
  68. return value
  69. def encode_result(self, result, status):
  70. if status in self.EXCEPTION_STATES and isinstance(result, Exception):
  71. return self.prepare_exception(result)
  72. else:
  73. return self.prepare_value(result)
  74. def store_result(self, task_id, result, status, traceback=None):
  75. """Store the result and status of a task."""
  76. raise NotImplementedError(
  77. 'store_result is not supported by this backend.')
  78. def mark_as_started(self, task_id, **meta):
  79. """Mark a task as started"""
  80. return self.store_result(task_id, meta, status=states.STARTED)
  81. def mark_as_done(self, task_id, result):
  82. """Mark task as successfully executed."""
  83. return self.store_result(task_id, result, status=states.SUCCESS)
  84. def mark_as_failure(self, task_id, exc, traceback=None):
  85. """Mark task as executed with failure. Stores the execption."""
  86. return self.store_result(task_id, exc, status=states.FAILURE,
  87. traceback=traceback)
  88. def mark_as_retry(self, task_id, exc, traceback=None):
  89. """Mark task as being retries. Stores the current
  90. exception (if any)."""
  91. return self.store_result(task_id, exc, status=states.RETRY,
  92. traceback=traceback)
  93. def mark_as_revoked(self, task_id, reason=''):
  94. return self.store_result(task_id, TaskRevokedError(reason),
  95. status=states.REVOKED, traceback=None)
  96. def prepare_exception(self, exc):
  97. """Prepare exception for serialization."""
  98. if self.serializer in EXCEPTION_ABLE_CODECS:
  99. return get_pickleable_exception(exc)
  100. return {'exc_type': type(exc).__name__, 'exc_message': str(exc)}
  101. def exception_to_python(self, exc):
  102. """Convert serialized exception to Python exception."""
  103. if self.serializer in EXCEPTION_ABLE_CODECS:
  104. return get_pickled_exception(exc)
  105. return create_exception_cls(from_utf8(exc['exc_type']),
  106. sys.modules[__name__])(exc['exc_message'])
  107. def prepare_value(self, result):
  108. """Prepare value for storage."""
  109. if isinstance(result, GroupResult):
  110. return result.serializable()
  111. return result
  112. def forget(self, task_id):
  113. raise NotImplementedError('%s does not implement forget.' % (
  114. self.__class__))
  115. def wait_for(self, task_id, timeout=None, propagate=True, interval=0.5):
  116. """Wait for task and return its result.
  117. If the task raises an exception, this exception
  118. will be re-raised by :func:`wait_for`.
  119. If `timeout` is not :const:`None`, this raises the
  120. :class:`celery.exceptions.TimeoutError` exception if the operation
  121. takes longer than `timeout` seconds.
  122. """
  123. time_elapsed = 0.0
  124. while 1:
  125. status = self.get_status(task_id)
  126. if status == states.SUCCESS:
  127. return self.get_result(task_id)
  128. elif status in states.PROPAGATE_STATES:
  129. result = self.get_result(task_id)
  130. if propagate:
  131. raise result
  132. return result
  133. # avoid hammering the CPU checking status.
  134. time.sleep(interval)
  135. time_elapsed += interval
  136. if timeout and time_elapsed >= timeout:
  137. raise TimeoutError('The operation timed out.')
  138. def cleanup(self):
  139. """Backend cleanup. Is run by
  140. :class:`celery.task.DeleteExpiredTaskMetaTask`."""
  141. pass
  142. def process_cleanup(self):
  143. """Cleanup actions to do at the end of a task worker process."""
  144. pass
  145. def get_status(self, task_id):
  146. """Get the status of a task."""
  147. raise NotImplementedError(
  148. 'get_status is not supported by this backend.')
  149. def get_result(self, task_id):
  150. """Get the result of a task."""
  151. raise NotImplementedError(
  152. 'get_result is not supported by this backend.')
  153. def get_children(self, task_id):
  154. raise NotImplementedError(
  155. 'get_children is not supported by this backend.')
  156. def get_traceback(self, task_id):
  157. """Get the traceback for a failed task."""
  158. raise NotImplementedError(
  159. 'get_traceback is not supported by this backend.')
  160. def save_group(self, group_id, result):
  161. """Store the result and status of a task."""
  162. raise NotImplementedError(
  163. 'save_group is not supported by this backend.')
  164. def restore_group(self, group_id, cache=True):
  165. """Get the result of a group."""
  166. raise NotImplementedError(
  167. 'restore_group is not supported by this backend.')
  168. def delete_group(self, group_id):
  169. raise NotImplementedError(
  170. 'delete_group is not supported by this backend.')
  171. def reload_task_result(self, task_id):
  172. """Reload task result, even if it has been previously fetched."""
  173. raise NotImplementedError(
  174. 'reload_task_result is not supported by this backend.')
  175. def reload_group_result(self, task_id):
  176. """Reload group result, even if it has been previously fetched."""
  177. raise NotImplementedError(
  178. 'reload_group_result is not supported by this backend.')
  179. def on_chord_part_return(self, task, propagate=False):
  180. pass
  181. def fallback_chord_unlock(self, group_id, body, result=None, **kwargs):
  182. kwargs['result'] = [r.id for r in result]
  183. self.app.tasks['celery.chord_unlock'].apply_async((group_id, body, ),
  184. kwargs, countdown=1)
  185. on_chord_apply = fallback_chord_unlock
  186. def current_task_children(self):
  187. current = current_task()
  188. if current:
  189. return [r.serializable() for r in current.request.children]
  190. def __reduce__(self, args=(), kwargs={}):
  191. return (unpickle_backend, (self.__class__, args, kwargs))
  192. class BaseDictBackend(BaseBackend):
  193. def __init__(self, *args, **kwargs):
  194. super(BaseDictBackend, self).__init__(*args, **kwargs)
  195. self._cache = LRUCache(limit=kwargs.get('max_cached_results') or
  196. self.app.conf.CELERY_MAX_CACHED_RESULTS)
  197. def store_result(self, task_id, result, status, traceback=None, **kwargs):
  198. """Store task result and status."""
  199. result = self.encode_result(result, status)
  200. self._store_result(task_id, result, status, traceback, **kwargs)
  201. return result
  202. def forget(self, task_id):
  203. self._cache.pop(task_id, None)
  204. self._forget(task_id)
  205. def _forget(self, task_id):
  206. raise NotImplementedError('%s does not implement forget.' % (
  207. self.__class__))
  208. def get_status(self, task_id):
  209. """Get the status of a task."""
  210. return self.get_task_meta(task_id)['status']
  211. def get_traceback(self, task_id):
  212. """Get the traceback for a failed task."""
  213. return self.get_task_meta(task_id).get('traceback')
  214. def get_result(self, task_id):
  215. """Get the result of a task."""
  216. meta = self.get_task_meta(task_id)
  217. if meta['status'] in self.EXCEPTION_STATES:
  218. return self.exception_to_python(meta['result'])
  219. else:
  220. return meta['result']
  221. def get_children(self, task_id):
  222. """Get the list of subtasks sent by a task."""
  223. try:
  224. return self.get_task_meta(task_id)['children']
  225. except KeyError:
  226. pass
  227. def get_task_meta(self, task_id, cache=True):
  228. if cache:
  229. try:
  230. return self._cache[task_id]
  231. except KeyError:
  232. pass
  233. meta = self._get_task_meta_for(task_id)
  234. if cache and meta.get('status') == states.SUCCESS:
  235. self._cache[task_id] = meta
  236. return meta
  237. def reload_task_result(self, task_id):
  238. self._cache[task_id] = self.get_task_meta(task_id, cache=False)
  239. def reload_group_result(self, group_id):
  240. self._cache[group_id] = self.get_group_meta(group_id,
  241. cache=False)
  242. def get_group_meta(self, group_id, cache=True):
  243. if cache:
  244. try:
  245. return self._cache[group_id]
  246. except KeyError:
  247. pass
  248. meta = self._restore_group(group_id)
  249. if cache and meta is not None:
  250. self._cache[group_id] = meta
  251. return meta
  252. def restore_group(self, group_id, cache=True):
  253. """Get the result for a group."""
  254. meta = self.get_group_meta(group_id, cache=cache)
  255. if meta:
  256. return meta['result']
  257. def save_group(self, group_id, result):
  258. """Store the result of an executed group."""
  259. return self._save_group(group_id, result)
  260. def delete_group(self, group_id):
  261. self._cache.pop(group_id, None)
  262. return self._delete_group(group_id)
  263. class KeyValueStoreBackend(BaseDictBackend):
  264. task_keyprefix = ensure_bytes('celery-task-meta-')
  265. group_keyprefix = ensure_bytes('celery-taskset-meta-')
  266. chord_keyprefix = ensure_bytes('chord-unlock-')
  267. implements_incr = False
  268. def get(self, key):
  269. raise NotImplementedError('Must implement the get method.')
  270. def mget(self, keys):
  271. raise NotImplementedError('Does not support get_many')
  272. def set(self, key, value):
  273. raise NotImplementedError('Must implement the set method.')
  274. def delete(self, key):
  275. raise NotImplementedError('Must implement the delete method')
  276. def incr(self, key):
  277. raise NotImplementedError('Does not implement incr')
  278. def expire(self, key, value):
  279. pass
  280. def get_key_for_task(self, task_id):
  281. """Get the cache key for a task by id."""
  282. return self.task_keyprefix + ensure_bytes(task_id)
  283. def get_key_for_group(self, group_id):
  284. """Get the cache key for a group by id."""
  285. return self.group_keyprefix + ensure_bytes(group_id)
  286. def get_key_for_chord(self, group_id):
  287. """Get the cache key for the chord waiting on group with given id."""
  288. return self.chord_keyprefix + ensure_bytes(group_id)
  289. def _strip_prefix(self, key):
  290. """Takes bytes, emits string."""
  291. key = ensure_bytes(key)
  292. for prefix in self.task_keyprefix, self.group_keyprefix:
  293. if key.startswith(prefix):
  294. return bytes_to_str(key[len(prefix):])
  295. return bytes_to_str(key)
  296. def _mget_to_results(self, values, keys):
  297. if hasattr(values, 'items'):
  298. # client returns dict so mapping preserved.
  299. return dict((self._strip_prefix(k), self.decode(v))
  300. for k, v in values.iteritems()
  301. if v is not None)
  302. else:
  303. # client returns list so need to recreate mapping.
  304. return dict((bytes_to_str(keys[i]), self.decode(value))
  305. for i, value in enumerate(values)
  306. if value is not None)
  307. def get_many(self, task_ids, timeout=None, interval=0.5):
  308. ids = set(task_ids)
  309. cached_ids = set()
  310. for task_id in ids:
  311. try:
  312. cached = self._cache[task_id]
  313. except KeyError:
  314. pass
  315. else:
  316. if cached['status'] in states.READY_STATES:
  317. yield bytes_to_str(task_id), cached
  318. cached_ids.add(task_id)
  319. ids ^= cached_ids
  320. iterations = 0
  321. while ids:
  322. keys = list(ids)
  323. r = self._mget_to_results(self.mget([self.get_key_for_task(k)
  324. for k in keys]), keys)
  325. self._cache.update(r)
  326. ids ^= set(map(bytes_to_str, r))
  327. for key, value in r.iteritems():
  328. yield bytes_to_str(key), value
  329. if timeout and iterations * interval >= timeout:
  330. raise TimeoutError('Operation timed out (%s)' % (timeout, ))
  331. time.sleep(interval) # don't busy loop.
  332. iterations += 0
  333. def _forget(self, task_id):
  334. self.delete(self.get_key_for_task(task_id))
  335. def _store_result(self, task_id, result, status, traceback=None):
  336. meta = {'status': status, 'result': result, 'traceback': traceback,
  337. 'children': self.current_task_children()}
  338. self.set(self.get_key_for_task(task_id), self.encode(meta))
  339. return result
  340. def _save_group(self, group_id, result):
  341. self.set(self.get_key_for_group(group_id),
  342. self.encode({'result': result.serializable()}))
  343. return result
  344. def _delete_group(self, group_id):
  345. self.delete(self.get_key_for_group(group_id))
  346. def _get_task_meta_for(self, task_id):
  347. """Get task metadata for a task by id."""
  348. meta = self.get(self.get_key_for_task(task_id))
  349. if not meta:
  350. return {'status': states.PENDING, 'result': None}
  351. return self.decode(meta)
  352. def _restore_group(self, group_id):
  353. """Get task metadata for a task by id."""
  354. meta = self.get(self.get_key_for_group(group_id))
  355. # previously this was always pickled, but later this
  356. # was extended to support other serializers, so the
  357. # structure is kind of weird.
  358. if meta:
  359. meta = self.decode(meta)
  360. result = meta['result']
  361. if isinstance(result, (list, tuple)):
  362. return {'result': from_serializable(result)}
  363. return meta
  364. def on_chord_apply(self, group_id, body, result=None, **kwargs):
  365. if self.implements_incr:
  366. self.app.GroupResult(group_id, result).save()
  367. else:
  368. self.fallback_chord_unlock(group_id, body, result, **kwargs)
  369. def on_chord_part_return(self, task, propagate=False):
  370. if not self.implements_incr:
  371. return
  372. from celery import subtask
  373. from celery.result import GroupResult
  374. gid = task.request.group
  375. if not gid:
  376. return
  377. key = self.get_key_for_chord(gid)
  378. deps = GroupResult.restore(gid, backend=task.backend)
  379. val = self.incr(key)
  380. if val >= len(deps):
  381. subtask(task.request.chord).delay(deps.join(propagate=propagate))
  382. deps.delete()
  383. self.client.delete(key)
  384. else:
  385. self.expire(key, 86400)
  386. class DisabledBackend(BaseBackend):
  387. _cache = {} # need this attribute to reset cache in tests.
  388. def store_result(self, *args, **kwargs):
  389. pass
  390. def _is_disabled(self, *args, **kwargs):
  391. raise NotImplementedError('No result backend configured. '
  392. 'Please see the documentation for more information.')
  393. wait_for = get_status = get_result = get_traceback = _is_disabled