result.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961
  1. # -*- coding: utf-8 -*-
  2. """
  3. celery.result
  4. ~~~~~~~~~~~~~
  5. Task results/state and groups of results.
  6. """
  7. from __future__ import absolute_import, unicode_literals
  8. import time
  9. from collections import OrderedDict, deque
  10. from contextlib import contextmanager
  11. from copy import copy
  12. from kombu.utils import cached_property
  13. from vine import Thenable, barrier, promise
  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 _iter_meta(self):
  279. return iter([self._get_task_meta()])
  280. def _set_cache(self, d):
  281. children = d.get('children')
  282. if children:
  283. d['children'] = [
  284. result_from_tuple(child, self.app) for child in children
  285. ]
  286. self._cache = d
  287. return d
  288. @property
  289. def result(self):
  290. """When the task has been executed, this contains the return value.
  291. If the task raised an exception, this will be the exception
  292. instance."""
  293. return self._get_task_meta()['result']
  294. info = result
  295. @property
  296. def traceback(self):
  297. """Get the traceback of a failed task."""
  298. return self._get_task_meta().get('traceback')
  299. @property
  300. def state(self):
  301. """The tasks current state.
  302. Possible values includes:
  303. *PENDING*
  304. The task is waiting for execution.
  305. *STARTED*
  306. The task has been started.
  307. *RETRY*
  308. The task is to be retried, possibly because of failure.
  309. *FAILURE*
  310. The task raised an exception, or has exceeded the retry limit.
  311. The :attr:`result` attribute then contains the
  312. exception raised by the task.
  313. *SUCCESS*
  314. The task executed successfully. The :attr:`result` attribute
  315. then contains the tasks return value.
  316. """
  317. return self._get_task_meta()['status']
  318. status = state # XXX compat
  319. @property
  320. def task_id(self):
  321. """compat alias to :attr:`id`"""
  322. return self.id
  323. @task_id.setter # noqa
  324. def task_id(self, id):
  325. self.id = id
  326. Thenable.register(AsyncResult)
  327. class ResultSet(ResultBase):
  328. """Working with more than one result.
  329. :param results: List of result instances.
  330. """
  331. _app = None
  332. #: List of results in in the set.
  333. results = None
  334. def __init__(self, results, app=None, ready_barrier=None, **kwargs):
  335. self._app = app
  336. self._cache = None
  337. self.results = results
  338. self.on_ready = promise(args=(self,))
  339. self._on_full = ready_barrier or barrier(results)
  340. if self._on_full:
  341. self._on_full.then(promise(self.on_ready))
  342. def add(self, result):
  343. """Add :class:`AsyncResult` as a new member of the set.
  344. Does nothing if the result is already a member.
  345. """
  346. if result not in self.results:
  347. self.results.append(result)
  348. if self._on_full:
  349. self._on_full.add(result)
  350. def _on_ready(self):
  351. self.backend.remove_pending_result(self)
  352. if self.backend.is_async:
  353. self._cache = [r.get() for r in self.results]
  354. self.on_ready()
  355. def remove(self, result):
  356. """Remove result from the set; it must be a member.
  357. :raises KeyError: if the result is not a member.
  358. """
  359. if isinstance(result, string_t):
  360. result = self.app.AsyncResult(result)
  361. try:
  362. self.results.remove(result)
  363. except ValueError:
  364. raise KeyError(result)
  365. def discard(self, result):
  366. """Remove result from the set if it is a member.
  367. If it is not a member, do nothing.
  368. """
  369. try:
  370. self.remove(result)
  371. except KeyError:
  372. pass
  373. def update(self, results):
  374. """Update set with the union of itself and an iterable with
  375. results."""
  376. self.results.extend(r for r in results if r not in self.results)
  377. def clear(self):
  378. """Remove all results from this set."""
  379. self.results[:] = [] # don't create new list.
  380. def successful(self):
  381. """Was all of the tasks successful?
  382. :returns: :const:`True` if all of the tasks finished
  383. successfully (i.e. did not raise an exception).
  384. """
  385. return all(result.successful() for result in self.results)
  386. def failed(self):
  387. """Did any of the tasks fail?
  388. :returns: :const:`True` if one of the tasks failed.
  389. (i.e., raised an exception)
  390. """
  391. return any(result.failed() for result in self.results)
  392. def maybe_throw(self, callback=None, propagate=True):
  393. for result in self.results:
  394. result.maybe_throw(callback=callback, propagate=propagate)
  395. def waiting(self):
  396. """Are any of the tasks incomplete?
  397. :returns: :const:`True` if one of the tasks are still
  398. waiting for execution.
  399. """
  400. return any(not result.ready() for result in self.results)
  401. def ready(self):
  402. """Did all of the tasks complete? (either by success of failure).
  403. :returns: :const:`True` if all of the tasks has been
  404. executed.
  405. """
  406. return all(result.ready() for result in self.results)
  407. def completed_count(self):
  408. """Task completion count.
  409. :returns: the number of tasks completed.
  410. """
  411. return sum(int(result.successful()) for result in self.results)
  412. def forget(self):
  413. """Forget about (and possible remove the result of) all the tasks."""
  414. for result in self.results:
  415. result.forget()
  416. def revoke(self, connection=None, terminate=False, signal=None,
  417. wait=False, timeout=None):
  418. """Send revoke signal to all workers for all tasks in the set.
  419. :keyword terminate: Also terminate the process currently working
  420. on the task (if any).
  421. :keyword signal: Name of signal to send to process if terminate.
  422. Default is TERM.
  423. :keyword wait: Wait for replies from worker. Will wait for 1 second
  424. by default or you can specify a custom ``timeout``.
  425. :keyword timeout: Time in seconds to wait for replies if ``wait``
  426. enabled.
  427. """
  428. self.app.control.revoke([r.id for r in self.results],
  429. connection=connection, timeout=timeout,
  430. terminate=terminate, signal=signal, reply=wait)
  431. def __iter__(self):
  432. return iter(self.results)
  433. def __getitem__(self, index):
  434. """`res[i] -> res.results[i]`"""
  435. return self.results[index]
  436. @deprecated('4.0', '5.0')
  437. def iterate(self, timeout=None, propagate=True, interval=0.5):
  438. """Deprecated method, use :meth:`get` with a callback argument."""
  439. elapsed = 0.0
  440. results = OrderedDict((result.id, copy(result))
  441. for result in self.results)
  442. while results:
  443. removed = set()
  444. for task_id, result in items(results):
  445. if result.ready():
  446. yield result.get(timeout=timeout and timeout - elapsed,
  447. propagate=propagate)
  448. removed.add(task_id)
  449. else:
  450. if result.backend.subpolling_interval:
  451. time.sleep(result.backend.subpolling_interval)
  452. for task_id in removed:
  453. results.pop(task_id, None)
  454. time.sleep(interval)
  455. elapsed += interval
  456. if timeout and elapsed >= timeout:
  457. raise TimeoutError('The operation timed out')
  458. def get(self, timeout=None, propagate=True, interval=0.5,
  459. callback=None, no_ack=True, on_message=None):
  460. """See :meth:`join`
  461. This is here for API compatibility with :class:`AsyncResult`,
  462. in addition it uses :meth:`join_native` if available for the
  463. current result backend.
  464. """
  465. if self._cache is not None:
  466. return self._cache
  467. return (self.join_native if self.supports_native_join else self.join)(
  468. timeout=timeout, propagate=propagate,
  469. interval=interval, callback=callback, no_ack=no_ack,
  470. on_message=on_message,
  471. )
  472. def join(self, timeout=None, propagate=True, interval=0.5,
  473. callback=None, no_ack=True, on_message=None, on_interval=None):
  474. """Gathers the results of all tasks as a list in order.
  475. .. note::
  476. This can be an expensive operation for result store
  477. backends that must resort to polling (e.g. database).
  478. You should consider using :meth:`join_native` if your backend
  479. supports it.
  480. .. warning::
  481. Waiting for tasks within a task may lead to deadlocks.
  482. Please see :ref:`task-synchronous-subtasks`.
  483. :keyword timeout: The number of seconds to wait for results before
  484. the operation times out.
  485. :keyword propagate: If any of the tasks raises an exception, the
  486. exception will be re-raised.
  487. :keyword interval: Time to wait (in seconds) before retrying to
  488. retrieve a result from the set. Note that this
  489. does not have any effect when using the amqp
  490. result store backend, as it does not use polling.
  491. :keyword callback: Optional callback to be called for every result
  492. received. Must have signature ``(task_id, value)``
  493. No results will be returned by this function if
  494. a callback is specified. The order of results
  495. is also arbitrary when a callback is used.
  496. To get access to the result object for a particular
  497. id you will have to generate an index first:
  498. ``index = {r.id: r for r in gres.results.values()}``
  499. Or you can create new result objects on the fly:
  500. ``result = app.AsyncResult(task_id)`` (both will
  501. take advantage of the backend cache anyway).
  502. :keyword no_ack: Automatic message acknowledgement (Note that if this
  503. is set to :const:`False` then the messages *will not be
  504. acknowledged*).
  505. :raises celery.exceptions.TimeoutError: if ``timeout`` is not
  506. :const:`None` and the operation takes longer than ``timeout``
  507. seconds.
  508. """
  509. assert_will_not_block()
  510. time_start = monotonic()
  511. remaining = None
  512. if on_message is not None:
  513. raise ImproperlyConfigured(
  514. 'Backend does not support on_message callback')
  515. results = []
  516. for result in self.results:
  517. remaining = None
  518. if timeout:
  519. remaining = timeout - (monotonic() - time_start)
  520. if remaining <= 0.0:
  521. raise TimeoutError('join operation timed out')
  522. value = result.get(
  523. timeout=remaining, propagate=propagate,
  524. interval=interval, no_ack=no_ack, on_interval=on_interval,
  525. )
  526. if callback:
  527. callback(result.id, value)
  528. else:
  529. results.append(value)
  530. return results
  531. def then(self, callback, on_error=None):
  532. return self.on_ready.then(callback, on_error)
  533. def iter_native(self, timeout=None, interval=0.5, no_ack=True,
  534. on_message=None, on_interval=None):
  535. """Backend optimized version of :meth:`iterate`.
  536. .. versionadded:: 2.2
  537. Note that this does not support collecting the results
  538. for different task types using different backends.
  539. This is currently only supported by the amqp, Redis and cache
  540. result backends.
  541. """
  542. return self.backend.iter_native(
  543. self,
  544. timeout=timeout, interval=interval, no_ack=no_ack,
  545. on_message=on_message, on_interval=on_interval,
  546. )
  547. def join_native(self, timeout=None, propagate=True,
  548. interval=0.5, callback=None, no_ack=True,
  549. on_message=None, on_interval=None):
  550. """Backend optimized version of :meth:`join`.
  551. .. versionadded:: 2.2
  552. Note that this does not support collecting the results
  553. for different task types using different backends.
  554. This is currently only supported by the amqp, Redis and cache
  555. result backends.
  556. """
  557. assert_will_not_block()
  558. order_index = None if callback else {
  559. result.id: i for i, result in enumerate(self.results)
  560. }
  561. acc = None if callback else [None for _ in range(len(self))]
  562. for task_id, meta in self.iter_native(timeout, interval, no_ack,
  563. on_message, on_interval):
  564. value = meta['result']
  565. if propagate and meta['status'] in states.PROPAGATE_STATES:
  566. raise value
  567. if callback:
  568. callback(task_id, value)
  569. else:
  570. acc[order_index[task_id]] = value
  571. return acc
  572. def _iter_meta(self):
  573. return (meta for _, meta in self.backend.get_many(
  574. {r.id for r in self.results}, max_iterations=1,
  575. ))
  576. def _failed_join_report(self):
  577. return (res for res in self.results
  578. if res.backend.is_cached(res.id) and
  579. res.state in states.PROPAGATE_STATES)
  580. def __len__(self):
  581. return len(self.results)
  582. def __eq__(self, other):
  583. if isinstance(other, ResultSet):
  584. return other.results == self.results
  585. return NotImplemented
  586. def __ne__(self, other):
  587. res = self.__eq__(other)
  588. return True if res is NotImplemented else not res
  589. def __repr__(self):
  590. return '<{0}: [{1}]>'.format(type(self).__name__,
  591. ', '.join(r.id for r in self.results))
  592. @property
  593. def supports_native_join(self):
  594. try:
  595. return self.results[0].supports_native_join
  596. except IndexError:
  597. pass
  598. @property
  599. def app(self):
  600. if self._app is None:
  601. self._app = (self.results[0].app if self.results else
  602. current_app._get_current_object())
  603. return self._app
  604. @app.setter
  605. def app(self, app): # noqa
  606. self._app = app
  607. @property
  608. def backend(self):
  609. return self.app.backend if self.app else self.results[0].backend
  610. Thenable.register(ResultSet)
  611. class GroupResult(ResultSet):
  612. """Like :class:`ResultSet`, but with an associated id.
  613. This type is returned by :class:`~celery.group`.
  614. It enables inspection of the tasks state and return values as
  615. a single entity.
  616. :param id: The id of the group.
  617. :param results: List of result instances.
  618. """
  619. #: The UUID of the group.
  620. id = None
  621. #: List/iterator of results in the group
  622. results = None
  623. def __init__(self, id=None, results=None, **kwargs):
  624. self.id = id
  625. ResultSet.__init__(self, results, **kwargs)
  626. def save(self, backend=None):
  627. """Save group-result for later retrieval using :meth:`restore`.
  628. Example::
  629. >>> def save_and_restore(result):
  630. ... result.save()
  631. ... result = GroupResult.restore(result.id)
  632. """
  633. return (backend or self.app.backend).save_group(self.id, self)
  634. def delete(self, backend=None):
  635. """Remove this result if it was previously saved."""
  636. (backend or self.app.backend).delete_group(self.id)
  637. def __reduce__(self):
  638. return self.__class__, self.__reduce_args__()
  639. def __reduce_args__(self):
  640. return self.id, self.results
  641. def __eq__(self, other):
  642. if isinstance(other, GroupResult):
  643. return other.id == self.id and other.results == self.results
  644. return NotImplemented
  645. def __ne__(self, other):
  646. res = self.__eq__(other)
  647. return True if res is NotImplemented else not res
  648. def __repr__(self):
  649. return '<{0}: {1} [{2}]>'.format(type(self).__name__, self.id,
  650. ', '.join(r.id for r in self.results))
  651. def as_tuple(self):
  652. return self.id, [r.as_tuple() for r in self.results]
  653. @property
  654. def children(self):
  655. return self.results
  656. @classmethod
  657. def restore(self, id, backend=None):
  658. """Restore previously saved group result."""
  659. return (
  660. backend or (self.app.backend if self.app else current_app.backend)
  661. ).restore_group(id)
  662. Thenable.register(ResultSet)
  663. class EagerResult(AsyncResult):
  664. """Result that we know has already been executed."""
  665. def __init__(self, id, ret_value, state, traceback=None):
  666. self.id = id
  667. self._result = ret_value
  668. self._state = state
  669. self._traceback = traceback
  670. self.on_ready = promise(args=(self,))
  671. self.on_ready()
  672. def then(self, callback, on_error=None):
  673. return self.on_ready.then(callback, on_error)
  674. def _get_task_meta(self):
  675. return self._cache
  676. def __del__(self):
  677. pass
  678. def __reduce__(self):
  679. return self.__class__, self.__reduce_args__()
  680. def __reduce_args__(self):
  681. return (self.id, self._result, self._state, self._traceback)
  682. def __copy__(self):
  683. cls, args = self.__reduce__()
  684. return cls(*args)
  685. def ready(self):
  686. return True
  687. def get(self, timeout=None, propagate=True, **kwargs):
  688. if self.successful():
  689. return self.result
  690. elif self.state in states.PROPAGATE_STATES:
  691. if propagate:
  692. raise self.result
  693. return self.result
  694. wait = get # XXX Compat (remove 5.0)
  695. def forget(self):
  696. pass
  697. def revoke(self, *args, **kwargs):
  698. self._state = states.REVOKED
  699. def __repr__(self):
  700. return '<EagerResult: {0.id}>'.format(self)
  701. @property
  702. def _cache(self):
  703. return {'task_id': self.id, 'result': self._result, 'status':
  704. self._state, 'traceback': self._traceback}
  705. @property
  706. def result(self):
  707. """The tasks return value"""
  708. return self._result
  709. @property
  710. def state(self):
  711. """The tasks state."""
  712. return self._state
  713. status = state
  714. @property
  715. def traceback(self):
  716. """The traceback if the task failed."""
  717. return self._traceback
  718. @property
  719. def supports_native_join(self):
  720. return False
  721. Thenable.register(EagerResult)
  722. def result_from_tuple(r, app=None):
  723. # earlier backends may just pickle, so check if
  724. # result is already prepared.
  725. app = app_or_default(app)
  726. Result = app.AsyncResult
  727. if not isinstance(r, ResultBase):
  728. res, nodes = r
  729. if nodes:
  730. return app.GroupResult(
  731. res, [result_from_tuple(child, app) for child in nodes],
  732. )
  733. # previously did not include parent
  734. id, parent = res if isinstance(res, (list, tuple)) else (res, None)
  735. if parent:
  736. parent = result_from_tuple(parent, app)
  737. return Result(id, parent=parent)
  738. return r