result.py 30 KB

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