result.py 28 KB

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