result.py 24 KB

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