result.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961
  1. # -*- coding: utf-8 -*-
  2. """Task results/state and results for groups of tasks."""
  3. from __future__ import absolute_import, unicode_literals
  4. import time
  5. from collections import OrderedDict, deque
  6. from contextlib import contextmanager
  7. from copy import copy
  8. from kombu.utils.objects import cached_property
  9. from vine import Thenable, barrier, promise
  10. from . import current_app
  11. from . import states
  12. from ._state import _set_task_join_will_block, task_join_will_block
  13. from .app import app_or_default
  14. from .exceptions import ImproperlyConfigured, IncompleteStream, TimeoutError
  15. from .five import (
  16. items, python_2_unicode_compatible, range, string_t, monotonic,
  17. )
  18. from .utils import deprecated
  19. from .utils.graph import DependencyGraph, GraphFormatter
  20. try:
  21. import tblib
  22. except ImportError:
  23. tblib = None
  24. __all__ = [
  25. 'ResultBase', 'AsyncResult', 'ResultSet',
  26. 'GroupResult', 'EagerResult', 'result_from_tuple',
  27. ]
  28. E_WOULDBLOCK = """\
  29. Never call result.get() within a task!
  30. See http://docs.celeryq.org/en/latest/userguide/tasks.html\
  31. #task-synchronous-subtasks
  32. """
  33. def assert_will_not_block():
  34. if task_join_will_block():
  35. raise RuntimeError(E_WOULDBLOCK)
  36. @contextmanager
  37. def allow_join_result():
  38. reset_value = task_join_will_block()
  39. _set_task_join_will_block(False)
  40. try:
  41. yield
  42. finally:
  43. _set_task_join_will_block(reset_value)
  44. class ResultBase(object):
  45. """Base class for all results"""
  46. #: Parent result (if part of a chain)
  47. parent = None
  48. @Thenable.register
  49. @python_2_unicode_compatible
  50. class AsyncResult(ResultBase):
  51. """Query task state.
  52. Arguments:
  53. id (str): See :attr:`id`.
  54. backend (Backend): See :attr:`backend`.
  55. """
  56. app = None
  57. #: Error raised for timeouts.
  58. TimeoutError = TimeoutError
  59. #: The task's UUID.
  60. id = None
  61. #: The task result backend to use.
  62. backend = None
  63. def __init__(self, id, backend=None,
  64. task_name=None, # deprecated
  65. app=None, parent=None):
  66. if id is None:
  67. raise ValueError(
  68. 'AsyncResult requires valid id, not {0}'.format(type(id)))
  69. self.app = app_or_default(app or self.app)
  70. self.id = id
  71. self.backend = backend or self.app.backend
  72. self.parent = parent
  73. self.on_ready = promise(self._on_fulfilled)
  74. self._cache = None
  75. def then(self, callback, on_error=None, weak=False):
  76. self.backend.add_pending_result(self, weak=weak)
  77. return self.on_ready.then(callback, on_error)
  78. def _on_fulfilled(self, result):
  79. self.backend.remove_pending_result(self)
  80. return result
  81. def as_tuple(self):
  82. parent = self.parent
  83. return (self.id, parent and parent.as_tuple()), None
  84. def forget(self):
  85. """Forget about (and possibly remove the result of) this task."""
  86. self._cache = None
  87. self.backend.forget(self.id)
  88. def revoke(self, connection=None, terminate=False, signal=None,
  89. wait=False, timeout=None):
  90. """Send revoke signal to all workers.
  91. Any worker receiving the task, or having reserved the
  92. task, *must* ignore it.
  93. Arguments:
  94. terminate (bool): Also terminate the process currently working
  95. on the task (if any).
  96. signal (str): Name of signal to send to process if terminate.
  97. Default is TERM.
  98. wait (bool): Wait for replies from workers.
  99. The ``timeout`` argument specifies the seconds to wait.
  100. Disabled by default.
  101. timeout (float): Time in seconds to wait for replies when
  102. ``wait`` is enabled.
  103. """
  104. self.app.control.revoke(self.id, connection=connection,
  105. terminate=terminate, signal=signal,
  106. reply=wait, timeout=timeout)
  107. def get(self, timeout=None, propagate=True, interval=0.5,
  108. no_ack=True, follow_parents=True, callback=None, on_interval=None,
  109. EXCEPTION_STATES=states.EXCEPTION_STATES,
  110. PROPAGATE_STATES=states.PROPAGATE_STATES):
  111. """Wait until task is ready, and return its result.
  112. Warning:
  113. Waiting for tasks within a task may lead to deadlocks.
  114. Please read :ref:`task-synchronous-subtasks`.
  115. Arguments:
  116. timeout (float): How long to wait, in seconds, before the
  117. operation times out.
  118. propagate (bool): Re-raise exception if the task failed.
  119. interval (float): Time to wait (in seconds) before retrying to
  120. retrieve the result. Note that this does not have any effect
  121. when using the RPC/redis result store backends, as they don't
  122. use polling.
  123. no_ack (bool): Enable amqp no ack (automatically acknowledge
  124. message). If this is :const:`False` then the message will
  125. **not be acked**.
  126. follow_parents (bool): Re-raise any exception raised by
  127. parent tasks.
  128. Raises:
  129. celery.exceptions.TimeoutError: if `timeout` isn't
  130. :const:`None` and the result does not arrive within
  131. `timeout` seconds.
  132. Exception: If the remote call raised an exception then that
  133. exception will be re-raised in the caller process.
  134. """
  135. assert_will_not_block()
  136. _on_interval = promise()
  137. if follow_parents and propagate and self.parent:
  138. on_interval = promise(self._maybe_reraise_parent_error)
  139. self._maybe_reraise_parent_error()
  140. if on_interval:
  141. _on_interval.then(on_interval)
  142. if self._cache:
  143. if propagate:
  144. self.maybe_throw(callback=callback)
  145. return self.result
  146. self.backend.add_pending_result(self)
  147. return self.backend.wait_for_pending(
  148. self, timeout=timeout,
  149. interval=interval,
  150. on_interval=_on_interval,
  151. no_ack=no_ack,
  152. propagate=propagate,
  153. callback=callback,
  154. )
  155. wait = get # deprecated alias to :meth:`get`.
  156. def _maybe_reraise_parent_error(self):
  157. for node in reversed(list(self._parents())):
  158. node.maybe_throw()
  159. def _parents(self):
  160. node = self.parent
  161. while node:
  162. yield node
  163. node = node.parent
  164. def collect(self, intermediate=False, **kwargs):
  165. """Iterator, like :meth:`get` will wait for the task to complete,
  166. but will also follow :class:`AsyncResult` and :class:`ResultSet`
  167. returned by the task, yielding ``(result, value)`` tuples for each
  168. result in the tree.
  169. An example would be having the following tasks:
  170. .. code-block:: python
  171. from celery import group
  172. from proj.celery import app
  173. @app.task(trail=True)
  174. def A(how_many):
  175. return group(B.s(i) for i in range(how_many))()
  176. @app.task(trail=True)
  177. def B(i):
  178. return pow2.delay(i)
  179. @app.task(trail=True)
  180. def pow2(i):
  181. return i ** 2
  182. .. code-block:: pycon
  183. >>> from celery.result import ResultBase
  184. >>> from proj.tasks import A
  185. >>> result = A.delay(10)
  186. >>> [v for v in result.collect()
  187. ... if not isinstance(v, (ResultBase, tuple))]
  188. [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
  189. Note:
  190. The ``Task.trail`` option must be enabled
  191. so that the list of children is stored in ``result.children``.
  192. This is the default but enabled explicitly for illustration.
  193. Yields:
  194. Tuple[AsyncResult, Any]: tuples containing the result instance
  195. of the child task, and the return value of that task.
  196. """
  197. for _, R in self.iterdeps(intermediate=intermediate):
  198. yield R, R.get(**kwargs)
  199. def get_leaf(self):
  200. value = None
  201. for _, R in self.iterdeps():
  202. value = R.get()
  203. return value
  204. def iterdeps(self, intermediate=False):
  205. stack = deque([(None, self)])
  206. while stack:
  207. parent, node = stack.popleft()
  208. yield parent, node
  209. if node.ready():
  210. stack.extend((node, child) for child in node.children or [])
  211. else:
  212. if not intermediate:
  213. raise IncompleteStream()
  214. def ready(self):
  215. """Returns :const:`True` if the task has been executed.
  216. If the task is still running, pending, or is waiting
  217. for retry then :const:`False` is returned.
  218. """
  219. return self.state in self.backend.READY_STATES
  220. def successful(self):
  221. """Returns :const:`True` if the task executed successfully."""
  222. return self.state == states.SUCCESS
  223. def failed(self):
  224. """Returns :const:`True` if the task failed."""
  225. return self.state == states.FAILURE
  226. def throw(self, *args, **kwargs):
  227. self.on_ready.throw(*args, **kwargs)
  228. def maybe_throw(self, propagate=True, callback=None):
  229. cache = self._get_task_meta() if self._cache is None else self._cache
  230. state, value, tb = (
  231. cache['status'], cache['result'], cache.get('traceback'))
  232. if state in states.PROPAGATE_STATES and propagate:
  233. self.throw(value, self._to_remote_traceback(tb))
  234. if callback is not None:
  235. callback(self.id, value)
  236. return value
  237. def _to_remote_traceback(self, tb):
  238. if tb and tblib is not None and self.app.conf.task_remote_tracebacks:
  239. return tblib.Traceback.from_string(tb).as_traceback()
  240. def build_graph(self, intermediate=False, formatter=None):
  241. graph = DependencyGraph(
  242. formatter=formatter or GraphFormatter(root=self.id, shape='oval'),
  243. )
  244. for parent, node in self.iterdeps(intermediate=intermediate):
  245. graph.add_arc(node)
  246. if parent:
  247. graph.add_edge(parent, node)
  248. return graph
  249. def __str__(self):
  250. """`str(self) -> self.id`"""
  251. return str(self.id)
  252. def __hash__(self):
  253. """`hash(self) -> hash(self.id)`"""
  254. return hash(self.id)
  255. def __repr__(self):
  256. return '<{0}: {1}>'.format(type(self).__name__, self.id)
  257. def __eq__(self, other):
  258. if isinstance(other, AsyncResult):
  259. return other.id == self.id
  260. elif isinstance(other, string_t):
  261. return other == self.id
  262. return NotImplemented
  263. def __ne__(self, other):
  264. res = self.__eq__(other)
  265. return True if res is NotImplemented else not res
  266. def __copy__(self):
  267. return self.__class__(
  268. self.id, self.backend, None, self.app, self.parent,
  269. )
  270. def __reduce__(self):
  271. return self.__class__, self.__reduce_args__()
  272. def __reduce_args__(self):
  273. return self.id, self.backend, None, None, self.parent
  274. @cached_property
  275. def graph(self):
  276. return self.build_graph()
  277. @property
  278. def supports_native_join(self):
  279. return self.backend.supports_native_join
  280. @property
  281. def children(self):
  282. return self._get_task_meta().get('children')
  283. def _maybe_set_cache(self, meta):
  284. if meta:
  285. state = meta['status']
  286. if state in states.READY_STATES:
  287. d = self._set_cache(self.backend.meta_from_decoded(meta))
  288. self.on_ready(self)
  289. return d
  290. return meta
  291. def _get_task_meta(self):
  292. if self._cache is None:
  293. return self._maybe_set_cache(self.backend.get_task_meta(self.id))
  294. return self._cache
  295. def _iter_meta(self):
  296. return iter([self._get_task_meta()])
  297. def _set_cache(self, d):
  298. children = d.get('children')
  299. if children:
  300. d['children'] = [
  301. result_from_tuple(child, self.app) for child in children
  302. ]
  303. self._cache = d
  304. return d
  305. @property
  306. def result(self):
  307. """When the task has been executed, this contains the return value.
  308. If the task raised an exception, this will be the exception
  309. instance."""
  310. return self._get_task_meta()['result']
  311. info = result
  312. @property
  313. def traceback(self):
  314. """Get the traceback of a failed task."""
  315. return self._get_task_meta().get('traceback')
  316. @property
  317. def state(self):
  318. """The tasks current state.
  319. Possible values includes:
  320. *PENDING*
  321. The task is waiting for execution.
  322. *STARTED*
  323. The task has been started.
  324. *RETRY*
  325. The task is to be retried, possibly because of failure.
  326. *FAILURE*
  327. The task raised an exception, or has exceeded the retry limit.
  328. The :attr:`result` attribute then contains the
  329. exception raised by the task.
  330. *SUCCESS*
  331. The task executed successfully. The :attr:`result` attribute
  332. then contains the tasks return value.
  333. """
  334. return self._get_task_meta()['status']
  335. status = state # XXX compat
  336. @property
  337. def task_id(self):
  338. """compat alias to :attr:`id`"""
  339. return self.id
  340. @task_id.setter # noqa
  341. def task_id(self, id):
  342. self.id = id
  343. @Thenable.register
  344. @python_2_unicode_compatible
  345. class ResultSet(ResultBase):
  346. """Working with more than one result.
  347. Arguments:
  348. results (Sequence[AsyncResult]): List of result instances.
  349. """
  350. _app = None
  351. #: List of results in in the set.
  352. results = None
  353. def __init__(self, results, app=None, ready_barrier=None, **kwargs):
  354. self._app = app
  355. self._cache = None
  356. self.results = results
  357. self.on_ready = promise(args=(self,))
  358. self._on_full = ready_barrier or barrier(results)
  359. if self._on_full:
  360. self._on_full.then(promise(self.on_ready))
  361. def add(self, result):
  362. """Add :class:`AsyncResult` as a new member of the set.
  363. Does nothing if the result is already a member.
  364. """
  365. if result not in self.results:
  366. self.results.append(result)
  367. if self._on_full:
  368. self._on_full.add(result)
  369. def _on_ready(self):
  370. self.backend.remove_pending_result(self)
  371. if self.backend.is_async:
  372. self._cache = [r.get() for r in self.results]
  373. self.on_ready()
  374. def remove(self, result):
  375. """Remove result from the set; it must be a member.
  376. Raises:
  377. KeyError: if the result isn't a member.
  378. """
  379. if isinstance(result, string_t):
  380. result = self.app.AsyncResult(result)
  381. try:
  382. self.results.remove(result)
  383. except ValueError:
  384. raise KeyError(result)
  385. def discard(self, result):
  386. """Remove result from the set if it is a member,
  387. or do nothing if it's not."""
  388. try:
  389. self.remove(result)
  390. except KeyError:
  391. pass
  392. def update(self, results):
  393. """Update set with the union of itself and an iterable with
  394. results."""
  395. self.results.extend(r for r in results if r not in self.results)
  396. def clear(self):
  397. """Remove all results from this set."""
  398. self.results[:] = [] # don't create new list.
  399. def successful(self):
  400. """Was all of the tasks successful?
  401. Returns:
  402. bool: true if all of the tasks finished
  403. successfully (i.e. didn't raise an exception).
  404. """
  405. return all(result.successful() for result in self.results)
  406. def failed(self):
  407. """Did any of the tasks fail?
  408. Returns:
  409. bool: true if one of the tasks failed.
  410. (i.e., raised an exception)
  411. """
  412. return any(result.failed() for result in self.results)
  413. def maybe_throw(self, callback=None, propagate=True):
  414. for result in self.results:
  415. result.maybe_throw(callback=callback, propagate=propagate)
  416. def waiting(self):
  417. """Are any of the tasks incomplete?
  418. Returns:
  419. bool: true if one of the tasks are still
  420. waiting for execution.
  421. """
  422. return any(not result.ready() for result in self.results)
  423. def ready(self):
  424. """Did all of the tasks complete? (either by success of failure).
  425. Returns:
  426. bool: true if all of the tasks have been executed.
  427. """
  428. return all(result.ready() for result in self.results)
  429. def completed_count(self):
  430. """Task completion count.
  431. Returns:
  432. int: the number of tasks completed.
  433. """
  434. return sum(int(result.successful()) for result in self.results)
  435. def forget(self):
  436. """Forget about (and possible remove the result of) all the tasks."""
  437. for result in self.results:
  438. result.forget()
  439. def revoke(self, connection=None, terminate=False, signal=None,
  440. wait=False, timeout=None):
  441. """Send revoke signal to all workers for all tasks in the set.
  442. Arguments:
  443. terminate (bool): Also terminate the process currently working
  444. on the task (if any).
  445. signal (str): Name of signal to send to process if terminate.
  446. Default is TERM.
  447. wait (bool): Wait for replies from worker.
  448. The ``timeout`` argument specifies the number of seconds
  449. to wait. Disabled by default.
  450. timeout (float): Time in seconds to wait for replies when
  451. the ``wait`` argument is enabled.
  452. """
  453. self.app.control.revoke([r.id for r in self.results],
  454. connection=connection, timeout=timeout,
  455. terminate=terminate, signal=signal, reply=wait)
  456. def __iter__(self):
  457. return iter(self.results)
  458. def __getitem__(self, index):
  459. """`res[i] -> res.results[i]`"""
  460. return self.results[index]
  461. @deprecated.Callable('4.0', '5.0')
  462. def iterate(self, timeout=None, propagate=True, interval=0.5):
  463. """Deprecated method, use :meth:`get` with a callback argument."""
  464. elapsed = 0.0
  465. results = OrderedDict((result.id, copy(result))
  466. for result in self.results)
  467. while results:
  468. removed = set()
  469. for task_id, result in items(results):
  470. if result.ready():
  471. yield result.get(timeout=timeout and timeout - elapsed,
  472. propagate=propagate)
  473. removed.add(task_id)
  474. else:
  475. if result.backend.subpolling_interval:
  476. time.sleep(result.backend.subpolling_interval)
  477. for task_id in removed:
  478. results.pop(task_id, None)
  479. time.sleep(interval)
  480. elapsed += interval
  481. if timeout and elapsed >= timeout:
  482. raise TimeoutError('The operation timed out')
  483. def get(self, timeout=None, propagate=True, interval=0.5,
  484. callback=None, no_ack=True, on_message=None):
  485. """See :meth:`join`
  486. This is here for API compatibility with :class:`AsyncResult`,
  487. in addition it uses :meth:`join_native` if available for the
  488. current result backend.
  489. """
  490. if self._cache is not None:
  491. return self._cache
  492. return (self.join_native if self.supports_native_join else self.join)(
  493. timeout=timeout, propagate=propagate,
  494. interval=interval, callback=callback, no_ack=no_ack,
  495. on_message=on_message,
  496. )
  497. def join(self, timeout=None, propagate=True, interval=0.5,
  498. callback=None, no_ack=True, on_message=None, on_interval=None):
  499. """Gathers the results of all tasks as a list in order.
  500. Note:
  501. This can be an expensive operation for result store
  502. backends that must resort to polling (e.g., database).
  503. You should consider using :meth:`join_native` if your backend
  504. supports it.
  505. Warning:
  506. Waiting for tasks within a task may lead to deadlocks.
  507. Please see :ref:`task-synchronous-subtasks`.
  508. Arguments:
  509. timeout (float): The number of seconds to wait for results
  510. before the operation times out.
  511. propagate (bool): If any of the tasks raises an exception,
  512. the exception will be re-raised when this flag is set.
  513. interval (float): Time to wait (in seconds) before retrying to
  514. retrieve a result from the set. Note that this does not have
  515. any effect when using the amqp result store backend,
  516. as it does not use polling.
  517. callback (Callable): Optional callback to be called for every
  518. result received. Must have signature ``(task_id, value)``
  519. No results will be returned by this function if a callback
  520. is specified. The order of results is also arbitrary when a
  521. callback is used. To get access to the result object for
  522. a particular id you'll have to generate an index first:
  523. ``index = {r.id: r for r in gres.results.values()}``
  524. Or you can create new result objects on the fly:
  525. ``result = app.AsyncResult(task_id)`` (both will
  526. take advantage of the backend cache anyway).
  527. no_ack (bool): Automatic message acknowledgment (Note that if this
  528. is set to :const:`False` then the messages
  529. *will not be acknowledged*).
  530. Raises:
  531. celery.exceptions.TimeoutError: if ``timeout`` isn't
  532. :const:`None` and the operation takes longer than ``timeout``
  533. seconds.
  534. """
  535. assert_will_not_block()
  536. time_start = monotonic()
  537. remaining = None
  538. if on_message is not None:
  539. raise ImproperlyConfigured(
  540. 'Backend does not support on_message callback')
  541. results = []
  542. for result in self.results:
  543. remaining = None
  544. if timeout:
  545. remaining = timeout - (monotonic() - time_start)
  546. if remaining <= 0.0:
  547. raise TimeoutError('join operation timed out')
  548. value = result.get(
  549. timeout=remaining, propagate=propagate,
  550. interval=interval, no_ack=no_ack, on_interval=on_interval,
  551. )
  552. if callback:
  553. callback(result.id, value)
  554. else:
  555. results.append(value)
  556. return results
  557. def then(self, callback, on_error=None):
  558. return self.on_ready.then(callback, on_error)
  559. def iter_native(self, timeout=None, interval=0.5, no_ack=True,
  560. on_message=None, on_interval=None):
  561. """Backend optimized version of :meth:`iterate`.
  562. .. versionadded:: 2.2
  563. Note that this does not support collecting the results
  564. for different task types using different backends.
  565. This is currently only supported by the amqp, Redis and cache
  566. result backends.
  567. """
  568. return self.backend.iter_native(
  569. self,
  570. timeout=timeout, interval=interval, no_ack=no_ack,
  571. on_message=on_message, on_interval=on_interval,
  572. )
  573. def join_native(self, timeout=None, propagate=True,
  574. interval=0.5, callback=None, no_ack=True,
  575. on_message=None, on_interval=None):
  576. """Backend optimized version of :meth:`join`.
  577. .. versionadded:: 2.2
  578. Note that this does not support collecting the results
  579. for different task types using different backends.
  580. This is currently only supported by the amqp, Redis and cache
  581. result backends.
  582. """
  583. assert_will_not_block()
  584. order_index = None if callback else {
  585. result.id: i for i, result in enumerate(self.results)
  586. }
  587. acc = None if callback else [None for _ in range(len(self))]
  588. for task_id, meta in self.iter_native(timeout, interval, no_ack,
  589. on_message, on_interval):
  590. value = meta['result']
  591. if propagate and meta['status'] in states.PROPAGATE_STATES:
  592. raise value
  593. if callback:
  594. callback(task_id, value)
  595. else:
  596. acc[order_index[task_id]] = value
  597. return acc
  598. def _iter_meta(self):
  599. return (meta for _, meta in self.backend.get_many(
  600. {r.id for r in self.results}, max_iterations=1,
  601. ))
  602. def _failed_join_report(self):
  603. return (res for res in self.results
  604. if res.backend.is_cached(res.id) and
  605. res.state in states.PROPAGATE_STATES)
  606. def __len__(self):
  607. return len(self.results)
  608. def __eq__(self, other):
  609. if isinstance(other, ResultSet):
  610. return other.results == self.results
  611. return NotImplemented
  612. def __ne__(self, other):
  613. res = self.__eq__(other)
  614. return True if res is NotImplemented else not res
  615. def __repr__(self):
  616. return '<{0}: [{1}]>'.format(type(self).__name__,
  617. ', '.join(r.id for r in self.results))
  618. @property
  619. def supports_native_join(self):
  620. try:
  621. return self.results[0].supports_native_join
  622. except IndexError:
  623. pass
  624. @property
  625. def app(self):
  626. if self._app is None:
  627. self._app = (self.results[0].app if self.results else
  628. current_app._get_current_object())
  629. return self._app
  630. @app.setter
  631. def app(self, app): # noqa
  632. self._app = app
  633. @property
  634. def backend(self):
  635. return self.app.backend if self.app else self.results[0].backend
  636. @Thenable.register
  637. @python_2_unicode_compatible
  638. class GroupResult(ResultSet):
  639. """Like :class:`ResultSet`, but with an associated id.
  640. This type is returned by :class:`~celery.group`.
  641. It enables inspection of the tasks state and return values as
  642. a single entity.
  643. Arguments:
  644. id (str): The id of the group.
  645. results (Sequence[AsyncResult]): List of result instances.
  646. """
  647. #: The UUID of the group.
  648. id = None
  649. #: List/iterator of results in the group
  650. results = None
  651. def __init__(self, id=None, results=None, **kwargs):
  652. self.id = id
  653. ResultSet.__init__(self, results, **kwargs)
  654. def save(self, backend=None):
  655. """Save group-result for later retrieval using :meth:`restore`.
  656. Example:
  657. >>> def save_and_restore(result):
  658. ... result.save()
  659. ... result = GroupResult.restore(result.id)
  660. """
  661. return (backend or self.app.backend).save_group(self.id, self)
  662. def delete(self, backend=None):
  663. """Remove this result if it was previously saved."""
  664. (backend or self.app.backend).delete_group(self.id)
  665. def __reduce__(self):
  666. return self.__class__, self.__reduce_args__()
  667. def __reduce_args__(self):
  668. return self.id, self.results
  669. def __bool__(self):
  670. return bool(self.id or self.results)
  671. __nonzero__ = __bool__ # Included for Py2 backwards compatibility
  672. def __eq__(self, other):
  673. if isinstance(other, GroupResult):
  674. return other.id == self.id and other.results == self.results
  675. return NotImplemented
  676. def __ne__(self, other):
  677. res = self.__eq__(other)
  678. return True if res is NotImplemented else not res
  679. def __repr__(self):
  680. return '<{0}: {1} [{2}]>'.format(type(self).__name__, self.id,
  681. ', '.join(r.id for r in self.results))
  682. def as_tuple(self):
  683. return self.id, [r.as_tuple() for r in self.results]
  684. @property
  685. def children(self):
  686. return self.results
  687. @classmethod
  688. def restore(self, id, backend=None):
  689. """Restore previously saved group result."""
  690. return (
  691. backend or (self.app.backend if self.app else current_app.backend)
  692. ).restore_group(id)
  693. @Thenable.register
  694. @python_2_unicode_compatible
  695. class EagerResult(AsyncResult):
  696. """Result that we know has already been executed."""
  697. def __init__(self, id, ret_value, state, traceback=None):
  698. self.id = id
  699. self._result = ret_value
  700. self._state = state
  701. self._traceback = traceback
  702. self.on_ready = promise(args=(self,))
  703. self.on_ready()
  704. def then(self, callback, on_error=None):
  705. return self.on_ready.then(callback, on_error)
  706. def _get_task_meta(self):
  707. return self._cache
  708. def __reduce__(self):
  709. return self.__class__, self.__reduce_args__()
  710. def __reduce_args__(self):
  711. return (self.id, self._result, self._state, self._traceback)
  712. def __copy__(self):
  713. cls, args = self.__reduce__()
  714. return cls(*args)
  715. def ready(self):
  716. return True
  717. def get(self, timeout=None, propagate=True, **kwargs):
  718. if self.successful():
  719. return self.result
  720. elif self.state in states.PROPAGATE_STATES:
  721. if propagate:
  722. raise self.result
  723. return self.result
  724. wait = get # XXX Compat (remove 5.0)
  725. def forget(self):
  726. pass
  727. def revoke(self, *args, **kwargs):
  728. self._state = states.REVOKED
  729. def __repr__(self):
  730. return '<EagerResult: {0.id}>'.format(self)
  731. @property
  732. def _cache(self):
  733. return {
  734. 'task_id': self.id,
  735. 'result': self._result,
  736. 'status': self._state,
  737. 'traceback': self._traceback,
  738. }
  739. @property
  740. def result(self):
  741. """The tasks return value"""
  742. return self._result
  743. @property
  744. def state(self):
  745. """The tasks state."""
  746. return self._state
  747. status = state
  748. @property
  749. def traceback(self):
  750. """The traceback if the task failed."""
  751. return self._traceback
  752. @property
  753. def supports_native_join(self):
  754. return False
  755. def result_from_tuple(r, app=None):
  756. # earlier backends may just pickle, so check if
  757. # result is already prepared.
  758. app = app_or_default(app)
  759. Result = app.AsyncResult
  760. if not isinstance(r, ResultBase):
  761. res, nodes = r
  762. if nodes:
  763. return app.GroupResult(
  764. res, [result_from_tuple(child, app) for child in nodes],
  765. )
  766. # previously didn't include parent
  767. id, parent = res if isinstance(res, (list, tuple)) else (res, None)
  768. if parent:
  769. parent = result_from_tuple(parent, app)
  770. return Result(id, parent=parent)
  771. return r