result.py 28 KB

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