result.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831
  1. # -*- coding: utf-8 -*-
  2. """
  3. celery.result
  4. ~~~~~~~~~~~~~
  5. Task results/state and groups of results.
  6. """
  7. from __future__ import absolute_import
  8. import time
  9. import warnings
  10. from collections import deque
  11. from contextlib import contextmanager
  12. from copy import copy
  13. from kombu.utils import cached_property
  14. from kombu.utils.compat import OrderedDict
  15. from . import current_app
  16. from . import states
  17. from ._state import _set_task_join_will_block, task_join_will_block
  18. from .app import app_or_default
  19. from .datastructures import DependencyGraph, GraphFormatter
  20. from .exceptions import IncompleteStream, TimeoutError
  21. from .five import items, range, string_t, monotonic
  22. __all__ = ['ResultBase', 'AsyncResult', 'ResultSet', 'GroupResult',
  23. 'EagerResult', 'result_from_tuple']
  24. E_WOULDBLOCK = """\
  25. Never call result.get() within a task!
  26. See http://docs.celeryq.org/en/latest/userguide/tasks.html\
  27. #task-synchronous-subtasks
  28. In Celery 3.2 this will result in an exception being
  29. raised instead of just being a warning.
  30. """
  31. def assert_will_not_block():
  32. if task_join_will_block():
  33. warnings.warn(RuntimeWarning(E_WOULDBLOCK))
  34. @contextmanager
  35. def allow_join_result():
  36. reset_value = task_join_will_block()
  37. _set_task_join_will_block(False)
  38. try:
  39. yield
  40. finally:
  41. _set_task_join_will_block(reset_value)
  42. class ResultBase(object):
  43. """Base class for all results"""
  44. #: Parent result (if part of a chain)
  45. parent = None
  46. class AsyncResult(ResultBase):
  47. """Query task state.
  48. :param id: see :attr:`id`.
  49. :keyword backend: see :attr:`backend`.
  50. """
  51. app = None
  52. #: Error raised for timeouts.
  53. TimeoutError = TimeoutError
  54. #: The task's UUID.
  55. id = None
  56. #: The task result backend to use.
  57. backend = None
  58. def __init__(self, id, backend=None, task_name=None,
  59. app=None, parent=None):
  60. self.app = app_or_default(app or self.app)
  61. self.id = id
  62. self.backend = backend or self.app.backend
  63. self.task_name = task_name
  64. self.parent = parent
  65. def as_tuple(self):
  66. parent = self.parent
  67. return (self.id, parent and parent.as_tuple()), None
  68. serializable = as_tuple # XXX compat
  69. def forget(self):
  70. """Forget about (and possibly remove the result of) this task."""
  71. self.backend.forget(self.id)
  72. def revoke(self, connection=None, terminate=False, signal=None,
  73. wait=False, timeout=None):
  74. """Send revoke signal to all workers.
  75. Any worker receiving the task, or having reserved the
  76. task, *must* ignore it.
  77. :keyword terminate: Also terminate the process currently working
  78. on the task (if any).
  79. :keyword signal: Name of signal to send to process if terminate.
  80. Default is TERM.
  81. :keyword wait: Wait for replies from workers. Will wait for 1 second
  82. by default or you can specify a custom ``timeout``.
  83. :keyword timeout: Time in seconds to wait for replies if ``wait``
  84. enabled.
  85. """
  86. self.app.control.revoke(self.id, connection=connection,
  87. terminate=terminate, signal=signal,
  88. reply=wait, timeout=timeout)
  89. def get(self, timeout=None, propagate=True, interval=0.5):
  90. """Wait until task is ready, and return its result.
  91. .. warning::
  92. Waiting for tasks within a task may lead to deadlocks.
  93. Please read :ref:`task-synchronous-subtasks`.
  94. :keyword timeout: How long to wait, in seconds, before the
  95. operation times out.
  96. :keyword propagate: Re-raise exception if the task failed.
  97. :keyword interval: Time to wait (in seconds) before retrying to
  98. retrieve the result. Note that this does not have any effect
  99. when using the amqp result store backend, as it does not
  100. use polling.
  101. :raises celery.exceptions.TimeoutError: if `timeout` is not
  102. :const:`None` and the result does not arrive within `timeout`
  103. seconds.
  104. If the remote call raised an exception then that exception will
  105. be re-raised.
  106. """
  107. assert_will_not_block()
  108. if propagate and self.parent:
  109. for node in reversed(list(self._parents())):
  110. node.get(propagate=True, timeout=timeout, interval=interval)
  111. return self.backend.wait_for(self.id, timeout=timeout,
  112. propagate=propagate,
  113. interval=interval)
  114. wait = get # deprecated alias to :meth:`get`.
  115. def _parents(self):
  116. node = self.parent
  117. while node:
  118. yield node
  119. node = node.parent
  120. def collect(self, intermediate=False, **kwargs):
  121. """Iterator, like :meth:`get` will wait for the task to complete,
  122. but will also follow :class:`AsyncResult` and :class:`ResultSet`
  123. returned by the task, yielding for each result in the tree.
  124. An example would be having the following tasks:
  125. .. code-block:: python
  126. @task()
  127. def A(how_many):
  128. return group(B.s(i) for i in range(how_many))
  129. @task()
  130. def B(i):
  131. return pow2.delay(i)
  132. @task()
  133. def pow2(i):
  134. return i ** 2
  135. Calling :meth:`collect` would return:
  136. .. code-block:: python
  137. >>> from proj.tasks import A
  138. >>> result = A.delay(10)
  139. >>> list(result.collect())
  140. [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
  141. """
  142. for _, R in self.iterdeps(intermediate=intermediate):
  143. yield R, R.get(**kwargs)
  144. def get_leaf(self):
  145. value = None
  146. for _, R in self.iterdeps():
  147. value = R.get()
  148. return value
  149. def iterdeps(self, intermediate=False):
  150. stack = deque([(None, self)])
  151. while stack:
  152. parent, node = stack.popleft()
  153. yield parent, node
  154. if node.ready():
  155. stack.extend((node, child) for child in node.children or [])
  156. else:
  157. if not intermediate:
  158. raise IncompleteStream()
  159. def ready(self):
  160. """Returns :const:`True` if the task has been executed.
  161. If the task is still running, pending, or is waiting
  162. for retry then :const:`False` is returned.
  163. """
  164. return self.state in self.backend.READY_STATES
  165. def successful(self):
  166. """Returns :const:`True` if the task executed successfully."""
  167. return self.state == states.SUCCESS
  168. def failed(self):
  169. """Returns :const:`True` if the task failed."""
  170. return self.state == states.FAILURE
  171. def build_graph(self, intermediate=False, formatter=None):
  172. graph = DependencyGraph(
  173. formatter=formatter or GraphFormatter(root=self.id, shape='oval'),
  174. )
  175. for parent, node in self.iterdeps(intermediate=intermediate):
  176. graph.add_arc(node)
  177. if parent:
  178. graph.add_edge(parent, node)
  179. return graph
  180. def __str__(self):
  181. """`str(self) -> self.id`"""
  182. return str(self.id)
  183. def __hash__(self):
  184. """`hash(self) -> hash(self.id)`"""
  185. return hash(self.id)
  186. def __repr__(self):
  187. return '<{0}: {1}>'.format(type(self).__name__, self.id)
  188. def __eq__(self, other):
  189. if isinstance(other, AsyncResult):
  190. return other.id == self.id
  191. elif isinstance(other, string_t):
  192. return other == self.id
  193. return NotImplemented
  194. def __ne__(self, other):
  195. return not self.__eq__(other)
  196. def __copy__(self):
  197. return self.__class__(
  198. self.id, self.backend, self.task_name, self.app, self.parent,
  199. )
  200. def __reduce__(self):
  201. return self.__class__, self.__reduce_args__()
  202. def __reduce_args__(self):
  203. return self.id, self.backend, self.task_name, None, self.parent
  204. @cached_property
  205. def graph(self):
  206. return self.build_graph()
  207. @property
  208. def supports_native_join(self):
  209. return self.backend.supports_native_join
  210. @property
  211. def children(self):
  212. children = self.backend.get_children(self.id)
  213. if children:
  214. return [result_from_tuple(child, self.app) for child in children]
  215. @property
  216. def result(self):
  217. """When the task has been executed, this contains the return value.
  218. If the task raised an exception, this will be the exception
  219. instance."""
  220. return self.backend.get_result(self.id)
  221. info = result
  222. @property
  223. def traceback(self):
  224. """Get the traceback of a failed task."""
  225. return self.backend.get_traceback(self.id)
  226. @property
  227. def state(self):
  228. """The tasks current state.
  229. Possible values includes:
  230. *PENDING*
  231. The task is waiting for execution.
  232. *STARTED*
  233. The task has been started.
  234. *RETRY*
  235. The task is to be retried, possibly because of failure.
  236. *FAILURE*
  237. The task raised an exception, or has exceeded the retry limit.
  238. The :attr:`result` attribute then contains the
  239. exception raised by the task.
  240. *SUCCESS*
  241. The task executed successfully. The :attr:`result` attribute
  242. then contains the tasks return value.
  243. """
  244. return self.backend.get_status(self.id)
  245. status = state
  246. @property
  247. def task_id(self):
  248. """compat alias to :attr:`id`"""
  249. return self.id
  250. @task_id.setter # noqa
  251. def task_id(self, id):
  252. self.id = id
  253. BaseAsyncResult = AsyncResult # for backwards compatibility.
  254. class ResultSet(ResultBase):
  255. """Working with more than one result.
  256. :param results: List of result instances.
  257. """
  258. app = None
  259. #: List of results in in the set.
  260. results = None
  261. def __init__(self, results, app=None, **kwargs):
  262. self.app = app_or_default(app or self.app)
  263. self.results = results
  264. def add(self, result):
  265. """Add :class:`AsyncResult` as a new member of the set.
  266. Does nothing if the result is already a member.
  267. """
  268. if result not in self.results:
  269. self.results.append(result)
  270. def remove(self, result):
  271. """Remove result from the set; it must be a member.
  272. :raises KeyError: if the result is not a member.
  273. """
  274. if isinstance(result, string_t):
  275. result = self.app.AsyncResult(result)
  276. try:
  277. self.results.remove(result)
  278. except ValueError:
  279. raise KeyError(result)
  280. def discard(self, result):
  281. """Remove result from the set if it is a member.
  282. If it is not a member, do nothing.
  283. """
  284. try:
  285. self.remove(result)
  286. except KeyError:
  287. pass
  288. def update(self, results):
  289. """Update set with the union of itself and an iterable with
  290. results."""
  291. self.results.extend(r for r in results if r not in self.results)
  292. def clear(self):
  293. """Remove all results from this set."""
  294. self.results[:] = [] # don't create new list.
  295. def successful(self):
  296. """Was all of the tasks successful?
  297. :returns: :const:`True` if all of the tasks finished
  298. successfully (i.e. did not raise an exception).
  299. """
  300. return all(result.successful() for result in self.results)
  301. def failed(self):
  302. """Did any of the tasks fail?
  303. :returns: :const:`True` if one of the tasks failed.
  304. (i.e., raised an exception)
  305. """
  306. return any(result.failed() for result in self.results)
  307. def waiting(self):
  308. """Are any of the tasks incomplete?
  309. :returns: :const:`True` if one of the tasks are still
  310. waiting for execution.
  311. """
  312. return any(not result.ready() for result in self.results)
  313. def ready(self):
  314. """Did all of the tasks complete? (either by success of failure).
  315. :returns: :const:`True` if all of the tasks has been
  316. executed.
  317. """
  318. return all(result.ready() for result in self.results)
  319. def completed_count(self):
  320. """Task completion count.
  321. :returns: the number of tasks completed.
  322. """
  323. return sum(int(result.successful()) for result in self.results)
  324. def forget(self):
  325. """Forget about (and possible remove the result of) all the tasks."""
  326. for result in self.results:
  327. result.forget()
  328. def revoke(self, connection=None, terminate=False, signal=None,
  329. wait=False, timeout=None):
  330. """Send revoke signal to all workers for all tasks in the set.
  331. :keyword terminate: Also terminate the process currently working
  332. on the task (if any).
  333. :keyword signal: Name of signal to send to process if terminate.
  334. Default is TERM.
  335. :keyword wait: Wait for replies from worker. Will wait for 1 second
  336. by default or you can specify a custom ``timeout``.
  337. :keyword timeout: Time in seconds to wait for replies if ``wait``
  338. enabled.
  339. """
  340. self.app.control.revoke([r.id for r in self.results],
  341. connection=connection, timeout=timeout,
  342. terminate=terminate, signal=signal, reply=wait)
  343. def __iter__(self):
  344. return iter(self.results)
  345. def __getitem__(self, index):
  346. """`res[i] -> res.results[i]`"""
  347. return self.results[index]
  348. def iterate(self, timeout=None, propagate=True, interval=0.5):
  349. """Iterate over the return values of the tasks as they finish
  350. one by one.
  351. :raises: The exception if any of the tasks raised an exception.
  352. """
  353. elapsed = 0.0
  354. results = OrderedDict((result.id, copy(result))
  355. for result in self.results)
  356. while results:
  357. removed = set()
  358. for task_id, result in items(results):
  359. if result.ready():
  360. yield result.get(timeout=timeout and timeout - elapsed,
  361. propagate=propagate)
  362. removed.add(task_id)
  363. else:
  364. if result.backend.subpolling_interval:
  365. time.sleep(result.backend.subpolling_interval)
  366. for task_id in removed:
  367. results.pop(task_id, None)
  368. time.sleep(interval)
  369. elapsed += interval
  370. if timeout and elapsed >= timeout:
  371. raise TimeoutError('The operation timed out')
  372. def get(self, timeout=None, propagate=True, interval=0.5, callback=None):
  373. """See :meth:`join`
  374. This is here for API compatibility with :class:`AsyncResult`,
  375. in addition it uses :meth:`join_native` if available for the
  376. current result backend.
  377. """
  378. return (self.join_native if self.supports_native_join else self.join)(
  379. timeout=timeout, propagate=propagate,
  380. interval=interval, callback=callback)
  381. def join(self, timeout=None, propagate=True, interval=0.5, callback=None):
  382. """Gathers the results of all tasks as a list in order.
  383. .. note::
  384. This can be an expensive operation for result store
  385. backends that must resort to polling (e.g. database).
  386. You should consider using :meth:`join_native` if your backend
  387. supports it.
  388. .. warning::
  389. Waiting for tasks within a task may lead to deadlocks.
  390. Please see :ref:`task-synchronous-subtasks`.
  391. :keyword timeout: The number of seconds to wait for results before
  392. the operation times out.
  393. :keyword propagate: If any of the tasks raises an exception, the
  394. exception will be re-raised.
  395. :keyword interval: Time to wait (in seconds) before retrying to
  396. retrieve a result from the set. Note that this
  397. does not have any effect when using the amqp
  398. result store backend, as it does not use polling.
  399. :keyword callback: Optional callback to be called for every result
  400. received. Must have signature ``(task_id, value)``
  401. No results will be returned by this function if
  402. a callback is specified. The order of results
  403. is also arbitrary when a callback is used.
  404. :raises celery.exceptions.TimeoutError: if `timeout` is not
  405. :const:`None` and the operation takes longer than `timeout`
  406. seconds.
  407. """
  408. assert_will_not_block()
  409. time_start = monotonic()
  410. remaining = None
  411. results = []
  412. for result in self.results:
  413. remaining = None
  414. if timeout:
  415. remaining = timeout - (monotonic() - time_start)
  416. if remaining <= 0.0:
  417. raise TimeoutError('join operation timed out')
  418. value = result.get(timeout=remaining,
  419. propagate=propagate,
  420. interval=interval)
  421. if callback:
  422. callback(result.id, value)
  423. else:
  424. results.append(value)
  425. return results
  426. def iter_native(self, timeout=None, interval=0.5):
  427. """Backend optimized version of :meth:`iterate`.
  428. .. versionadded:: 2.2
  429. Note that this does not support collecting the results
  430. for different task types using different backends.
  431. This is currently only supported by the amqp, Redis and cache
  432. result backends.
  433. """
  434. results = self.results
  435. if not results:
  436. return iter([])
  437. return results[0].backend.get_many(
  438. set(r.id for r in results), timeout=timeout, interval=interval,
  439. )
  440. def join_native(self, timeout=None, propagate=True,
  441. interval=0.5, callback=None):
  442. """Backend optimized version of :meth:`join`.
  443. .. versionadded:: 2.2
  444. Note that this does not support collecting the results
  445. for different task types using different backends.
  446. This is currently only supported by the amqp, Redis and cache
  447. result backends.
  448. """
  449. assert_will_not_block()
  450. order_index = None if callback else dict(
  451. (result.id, i) for i, result in enumerate(self.results)
  452. )
  453. acc = None if callback else [None for _ in range(len(self))]
  454. for task_id, meta in self.iter_native(timeout, interval):
  455. value = meta['result']
  456. if propagate and meta['status'] in states.PROPAGATE_STATES:
  457. raise value
  458. if callback:
  459. callback(task_id, value)
  460. else:
  461. acc[order_index[task_id]] = value
  462. return acc
  463. def _failed_join_report(self):
  464. return (res for res in self.results
  465. if res.backend.is_cached(res.id) and
  466. res.state in states.PROPAGATE_STATES)
  467. def __len__(self):
  468. return len(self.results)
  469. def __eq__(self, other):
  470. if isinstance(other, ResultSet):
  471. return other.results == self.results
  472. return NotImplemented
  473. def __ne__(self, other):
  474. return not self.__eq__(other)
  475. def __repr__(self):
  476. return '<{0}: [{1}]>'.format(type(self).__name__,
  477. ', '.join(r.id for r in self.results))
  478. @property
  479. def subtasks(self):
  480. """Deprecated alias to :attr:`results`."""
  481. return self.results
  482. @property
  483. def supports_native_join(self):
  484. return self.results[0].supports_native_join
  485. class GroupResult(ResultSet):
  486. """Like :class:`ResultSet`, but with an associated id.
  487. This type is returned by :class:`~celery.group`, and the
  488. deprecated TaskSet, meth:`~celery.task.TaskSet.apply_async` method.
  489. It enables inspection of the tasks state and return values as
  490. a single entity.
  491. :param id: The id of the group.
  492. :param results: List of result instances.
  493. """
  494. #: The UUID of the group.
  495. id = None
  496. #: List/iterator of results in the group
  497. results = None
  498. def __init__(self, id=None, results=None, **kwargs):
  499. self.id = id
  500. ResultSet.__init__(self, results, **kwargs)
  501. def save(self, backend=None):
  502. """Save group-result for later retrieval using :meth:`restore`.
  503. Example::
  504. >>> def save_and_restore(result):
  505. ... result.save()
  506. ... result = GroupResult.restore(result.id)
  507. """
  508. return (backend or self.app.backend).save_group(self.id, self)
  509. def delete(self, backend=None):
  510. """Remove this result if it was previously saved."""
  511. (backend or self.app.backend).delete_group(self.id)
  512. def __reduce__(self):
  513. return self.__class__, self.__reduce_args__()
  514. def __reduce_args__(self):
  515. return self.id, self.results
  516. def __eq__(self, other):
  517. if isinstance(other, GroupResult):
  518. return other.id == self.id and other.results == self.results
  519. return NotImplemented
  520. def __ne__(self, other):
  521. return not self.__eq__(other)
  522. def __repr__(self):
  523. return '<{0}: {1} [{2}]>'.format(type(self).__name__, self.id,
  524. ', '.join(r.id for r in self.results))
  525. def as_tuple(self):
  526. return self.id, [r.as_tuple() for r in self.results]
  527. serializable = as_tuple # XXX compat
  528. @property
  529. def children(self):
  530. return self.results
  531. @classmethod
  532. def restore(self, id, backend=None):
  533. """Restore previously saved group result."""
  534. return (
  535. backend or (self.app.backend if self.app else current_app.backend)
  536. ).restore_group(id)
  537. class TaskSetResult(GroupResult):
  538. """Deprecated version of :class:`GroupResult`"""
  539. def __init__(self, taskset_id, results=None, **kwargs):
  540. # XXX supports the taskset_id kwarg.
  541. # XXX previously the "results" arg was named "subtasks".
  542. if 'subtasks' in kwargs:
  543. results = kwargs['subtasks']
  544. GroupResult.__init__(self, taskset_id, results, **kwargs)
  545. def itersubtasks(self):
  546. """Deprecated. Use ``iter(self.results)`` instead."""
  547. return iter(self.results)
  548. @property
  549. def total(self):
  550. """Deprecated: Use ``len(r)``."""
  551. return len(self)
  552. @property
  553. def taskset_id(self):
  554. """compat alias to :attr:`self.id`"""
  555. return self.id
  556. @taskset_id.setter # noqa
  557. def taskset_id(self, id):
  558. self.id = id
  559. class EagerResult(AsyncResult):
  560. """Result that we know has already been executed."""
  561. task_name = None
  562. def __init__(self, id, ret_value, state, traceback=None):
  563. self.id = id
  564. self._result = ret_value
  565. self._state = state
  566. self._traceback = traceback
  567. def __reduce__(self):
  568. return self.__class__, self.__reduce_args__()
  569. def __reduce_args__(self):
  570. return (self.id, self._result, self._state, self._traceback)
  571. def __copy__(self):
  572. cls, args = self.__reduce__()
  573. return cls(*args)
  574. def ready(self):
  575. return True
  576. def get(self, timeout=None, propagate=True, **kwargs):
  577. if self.successful():
  578. return self.result
  579. elif self.state in states.PROPAGATE_STATES:
  580. if propagate:
  581. raise self.result
  582. return self.result
  583. wait = get
  584. def forget(self):
  585. pass
  586. def revoke(self, *args, **kwargs):
  587. self._state = states.REVOKED
  588. def __repr__(self):
  589. return '<EagerResult: {0.id}>'.format(self)
  590. @property
  591. def result(self):
  592. """The tasks return value"""
  593. return self._result
  594. @property
  595. def state(self):
  596. """The tasks state."""
  597. return self._state
  598. status = state
  599. @property
  600. def traceback(self):
  601. """The traceback if the task failed."""
  602. return self._traceback
  603. @property
  604. def supports_native_join(self):
  605. return False
  606. def result_from_tuple(r, app=None):
  607. # earlier backends may just pickle, so check if
  608. # result is already prepared.
  609. app = app_or_default(app)
  610. Result = app.AsyncResult
  611. if not isinstance(r, ResultBase):
  612. res, nodes = r
  613. if nodes:
  614. return app.GroupResult(
  615. res, [result_from_tuple(child, app) for child in nodes],
  616. )
  617. # previously did not include parent
  618. id, parent = res if isinstance(res, (list, tuple)) else (res, None)
  619. if parent:
  620. parent = result_from_tuple(parent, app)
  621. return Result(id, parent=parent)
  622. return r
  623. from_serializable = result_from_tuple # XXX compat