result.py 29 KB

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