result.py 28 KB

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