result.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977
  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 .exceptions import ImproperlyConfigured, IncompleteStream, TimeoutError
  19. from .five import (
  20. items, python_2_unicode_compatible, range, string_t, monotonic,
  21. )
  22. from .utils import deprecated
  23. from .utils.graph import DependencyGraph, GraphFormatter
  24. try:
  25. import tblib
  26. except ImportError:
  27. tblib = None
  28. __all__ = [
  29. 'ResultBase', 'AsyncResult', 'ResultSet',
  30. 'GroupResult', 'EagerResult', 'result_from_tuple',
  31. ]
  32. E_WOULDBLOCK = """\
  33. Never call result.get() within a task!
  34. See http://docs.celeryq.org/en/latest/userguide/tasks.html\
  35. #task-synchronous-subtasks
  36. """
  37. def assert_will_not_block():
  38. if task_join_will_block():
  39. raise RuntimeError(E_WOULDBLOCK)
  40. @contextmanager
  41. def allow_join_result():
  42. reset_value = task_join_will_block()
  43. _set_task_join_will_block(False)
  44. try:
  45. yield
  46. finally:
  47. _set_task_join_will_block(reset_value)
  48. class ResultBase(object):
  49. """Base class for all results"""
  50. #: Parent result (if part of a chain)
  51. parent = None
  52. @Thenable.register
  53. @python_2_unicode_compatible
  54. class AsyncResult(ResultBase):
  55. """Query task state.
  56. :param id: see :attr:`id`.
  57. :keyword backend: see :attr:`backend`.
  58. """
  59. app = None
  60. #: Error raised for timeouts.
  61. TimeoutError = TimeoutError
  62. #: The task's UUID.
  63. id = None
  64. #: The task result backend to use.
  65. backend = None
  66. def __init__(self, id, backend=None,
  67. task_name=None, # deprecated
  68. app=None, parent=None):
  69. if id is None:
  70. raise ValueError(
  71. 'AsyncResult requires valid id, not {0}'.format(type(id)))
  72. self.app = app_or_default(app or self.app)
  73. self.id = id
  74. self.backend = backend or self.app.backend
  75. self.parent = parent
  76. self.on_ready = promise(self._on_fulfilled)
  77. self._cache = None
  78. def then(self, callback, on_error=None, weak=False):
  79. self.backend.add_pending_result(self, weak=weak)
  80. return self.on_ready.then(callback, on_error)
  81. def _on_fulfilled(self, result):
  82. self.backend.remove_pending_result(self)
  83. return result
  84. def as_tuple(self):
  85. parent = self.parent
  86. return (self.id, parent and parent.as_tuple()), None
  87. def forget(self):
  88. """Forget about (and possibly remove the result of) this task."""
  89. self._cache = None
  90. self.backend.forget(self.id)
  91. def revoke(self, connection=None, terminate=False, signal=None,
  92. wait=False, timeout=None):
  93. """Send revoke signal to all workers.
  94. Any worker receiving the task, or having reserved the
  95. task, *must* ignore it.
  96. :keyword terminate: Also terminate the process currently working
  97. on the task (if any).
  98. :keyword signal: Name of signal to send to process if terminate.
  99. Default is TERM.
  100. :keyword wait: Wait for replies from workers. Will wait for 1 second
  101. by default or you can specify a custom ``timeout``.
  102. :keyword timeout: Time in seconds to wait for replies if ``wait``
  103. enabled.
  104. """
  105. self.app.control.revoke(self.id, connection=connection,
  106. terminate=terminate, signal=signal,
  107. reply=wait, timeout=timeout)
  108. def get(self, timeout=None, propagate=True, interval=0.5,
  109. no_ack=True, follow_parents=True, callback=None, on_interval=None,
  110. EXCEPTION_STATES=states.EXCEPTION_STATES,
  111. PROPAGATE_STATES=states.PROPAGATE_STATES):
  112. """Wait until task is ready, and return its result.
  113. .. warning::
  114. Waiting for tasks within a task may lead to deadlocks.
  115. Please read :ref:`task-synchronous-subtasks`.
  116. :keyword timeout: How long to wait, in seconds, before the
  117. operation times out.
  118. :keyword propagate: Re-raise exception if the task failed.
  119. :keyword interval: Time to wait (in seconds) before retrying to
  120. retrieve the result. Note that this does not have any effect
  121. when using the RPC/redis result store backends, as they do not
  122. use polling.
  123. :keyword no_ack: Enable amqp no ack (automatically acknowledge
  124. message). If this is :const:`False` then the message will
  125. **not be acked**.
  126. :keyword follow_parents: Re-raise any exception raised by parent task.
  127. :raises celery.exceptions.TimeoutError: if `timeout` is not
  128. :const:`None` and the result does not arrive within `timeout`
  129. seconds.
  130. If the remote call raised an exception then that exception will
  131. be re-raised.
  132. """
  133. assert_will_not_block()
  134. _on_interval = promise()
  135. if follow_parents and propagate and self.parent:
  136. on_interval = promise(self._maybe_reraise_parent_error)
  137. self._maybe_reraise_parent_error()
  138. if on_interval:
  139. _on_interval.then(on_interval)
  140. if self._cache:
  141. if propagate:
  142. self.maybe_throw(callback=callback)
  143. return self.result
  144. self.backend.add_pending_result(self)
  145. return self.backend.wait_for_pending(
  146. self, timeout=timeout,
  147. interval=interval,
  148. on_interval=_on_interval,
  149. no_ack=no_ack,
  150. propagate=propagate,
  151. callback=callback,
  152. )
  153. wait = get # deprecated alias to :meth:`get`.
  154. def _maybe_reraise_parent_error(self):
  155. for node in reversed(list(self._parents())):
  156. node.maybe_throw()
  157. def _parents(self):
  158. node = self.parent
  159. while node:
  160. yield node
  161. node = node.parent
  162. def collect(self, intermediate=False, **kwargs):
  163. """Iterator, like :meth:`get` will wait for the task to complete,
  164. but will also follow :class:`AsyncResult` and :class:`ResultSet`
  165. returned by the task, yielding ``(result, value)`` tuples for each
  166. result in the tree.
  167. An example would be having the following tasks:
  168. .. code-block:: python
  169. from celery import group
  170. from proj.celery import app
  171. @app.task(trail=True)
  172. def A(how_many):
  173. return group(B.s(i) for i in range(how_many))()
  174. @app.task(trail=True)
  175. def B(i):
  176. return pow2.delay(i)
  177. @app.task(trail=True)
  178. def pow2(i):
  179. return i ** 2
  180. Note that the ``trail`` option must be enabled
  181. so that the list of children is stored in ``result.children``.
  182. This is the default but enabled explicitly for illustration.
  183. Calling :meth:`collect` would return:
  184. .. code-block:: pycon
  185. >>> from celery.result import ResultBase
  186. >>> from proj.tasks import A
  187. >>> result = A.delay(10)
  188. >>> [v for v in result.collect()
  189. ... if not isinstance(v, (ResultBase, tuple))]
  190. [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
  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, string_t):
  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. status = state # XXX compat
  331. @property
  332. def task_id(self):
  333. """compat alias to :attr:`id`"""
  334. return self.id
  335. @task_id.setter # noqa
  336. def task_id(self, id):
  337. self.id = id
  338. @Thenable.register
  339. @python_2_unicode_compatible
  340. class ResultSet(ResultBase):
  341. """Working with more than one result.
  342. :param results: List of result instances.
  343. """
  344. _app = None
  345. #: List of results in in the set.
  346. results = None
  347. def __init__(self, results, app=None, ready_barrier=None, **kwargs):
  348. self._app = app
  349. self._cache = None
  350. self.results = results
  351. self.on_ready = promise(args=(self,))
  352. self._on_full = ready_barrier or barrier(results)
  353. if self._on_full:
  354. self._on_full.then(promise(self.on_ready))
  355. def add(self, result):
  356. """Add :class:`AsyncResult` as a new member of the set.
  357. Does nothing if the result is already a member.
  358. """
  359. if result not in self.results:
  360. self.results.append(result)
  361. if self._on_full:
  362. self._on_full.add(result)
  363. def _on_ready(self):
  364. self.backend.remove_pending_result(self)
  365. if self.backend.is_async:
  366. self._cache = [r.get() for r in self.results]
  367. self.on_ready()
  368. def remove(self, result):
  369. """Remove result from the set; it must be a member.
  370. :raises KeyError: if the result is not a member.
  371. """
  372. if isinstance(result, string_t):
  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. If it is not a member, do nothing.
  381. """
  382. try:
  383. self.remove(result)
  384. except KeyError:
  385. pass
  386. def update(self, results):
  387. """Update set with the union of itself and an iterable with
  388. results."""
  389. self.results.extend(r for r in results if r not in self.results)
  390. def clear(self):
  391. """Remove all results from this set."""
  392. self.results[:] = [] # don't create new list.
  393. def successful(self):
  394. """Was all of the tasks successful?
  395. :returns: :const:`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: :const:`True` if one of the tasks failed.
  402. (i.e., raised an exception)
  403. """
  404. return any(result.failed() for result in self.results)
  405. def maybe_throw(self, callback=None, propagate=True):
  406. for result in self.results:
  407. result.maybe_throw(callback=callback, propagate=propagate)
  408. def waiting(self):
  409. """Are any of the tasks incomplete?
  410. :returns: :const:`True` if one of the tasks are still
  411. waiting for execution.
  412. """
  413. return any(not result.ready() for result in self.results)
  414. def ready(self):
  415. """Did all of the tasks complete? (either by success of failure).
  416. :returns: :const:`True` if all of the tasks has been
  417. executed.
  418. """
  419. return all(result.ready() for result in self.results)
  420. def completed_count(self):
  421. """Task completion count.
  422. :returns: the number of tasks completed.
  423. """
  424. return sum(int(result.successful()) for result in self.results)
  425. def forget(self):
  426. """Forget about (and possible remove the result of) all the tasks."""
  427. for result in self.results:
  428. result.forget()
  429. def revoke(self, connection=None, terminate=False, signal=None,
  430. wait=False, timeout=None):
  431. """Send revoke signal to all workers for all tasks in the set.
  432. :keyword terminate: Also terminate the process currently working
  433. on the task (if any).
  434. :keyword signal: Name of signal to send to process if terminate.
  435. Default is TERM.
  436. :keyword wait: Wait for replies from worker. Will wait for 1 second
  437. by default or you can specify a custom ``timeout``.
  438. :keyword timeout: Time in seconds to wait for replies if ``wait``
  439. enabled.
  440. """
  441. self.app.control.revoke([r.id for r in self.results],
  442. connection=connection, timeout=timeout,
  443. terminate=terminate, signal=signal, reply=wait)
  444. def __iter__(self):
  445. return iter(self.results)
  446. def __getitem__(self, index):
  447. """`res[i] -> res.results[i]`"""
  448. return self.results[index]
  449. @deprecated.Callable('4.0', '5.0')
  450. def iterate(self, timeout=None, propagate=True, interval=0.5):
  451. """Deprecated method, use :meth:`get` with a callback argument."""
  452. elapsed = 0.0
  453. results = OrderedDict((result.id, copy(result))
  454. for result in self.results)
  455. while results:
  456. removed = set()
  457. for task_id, result in items(results):
  458. if result.ready():
  459. yield result.get(timeout=timeout and timeout - elapsed,
  460. propagate=propagate)
  461. removed.add(task_id)
  462. else:
  463. if result.backend.subpolling_interval:
  464. time.sleep(result.backend.subpolling_interval)
  465. for task_id in removed:
  466. results.pop(task_id, None)
  467. time.sleep(interval)
  468. elapsed += interval
  469. if timeout and elapsed >= timeout:
  470. raise TimeoutError('The operation timed out')
  471. def get(self, timeout=None, propagate=True, interval=0.5,
  472. callback=None, no_ack=True, on_message=None):
  473. """See :meth:`join`
  474. This is here for API compatibility with :class:`AsyncResult`,
  475. in addition it uses :meth:`join_native` if available for the
  476. current result backend.
  477. """
  478. if self._cache is not None:
  479. return self._cache
  480. return (self.join_native if self.supports_native_join else self.join)(
  481. timeout=timeout, propagate=propagate,
  482. interval=interval, callback=callback, no_ack=no_ack,
  483. on_message=on_message,
  484. )
  485. def join(self, timeout=None, propagate=True, interval=0.5,
  486. callback=None, no_ack=True, on_message=None, on_interval=None):
  487. """Gathers the results of all tasks as a list in order.
  488. .. note::
  489. This can be an expensive operation for result store
  490. backends that must resort to polling (e.g. database).
  491. You should consider using :meth:`join_native` if your backend
  492. supports it.
  493. .. warning::
  494. Waiting for tasks within a task may lead to deadlocks.
  495. Please see :ref:`task-synchronous-subtasks`.
  496. :keyword timeout: The number of seconds to wait for results before
  497. the operation times out.
  498. :keyword propagate: If any of the tasks raises an exception, the
  499. exception will be re-raised.
  500. :keyword interval: Time to wait (in seconds) before retrying to
  501. retrieve a result from the set. Note that this
  502. does not have any effect when using the amqp
  503. result store backend, as it does not use polling.
  504. :keyword callback: Optional callback to be called for every result
  505. received. Must have signature ``(task_id, value)``
  506. No results will be returned by this function if
  507. a callback is specified. The order of results
  508. is also arbitrary when a callback is used.
  509. To get access to the result object for a particular
  510. id you will have to generate an index first:
  511. ``index = {r.id: r for r in gres.results.values()}``
  512. Or you can create new result objects on the fly:
  513. ``result = app.AsyncResult(task_id)`` (both will
  514. take advantage of the backend cache anyway).
  515. :keyword no_ack: Automatic message acknowledgment (Note that if this
  516. is set to :const:`False` then the messages *will not be
  517. acknowledged*).
  518. :raises celery.exceptions.TimeoutError: if ``timeout`` is not
  519. :const:`None` and the operation takes longer than ``timeout``
  520. seconds.
  521. """
  522. assert_will_not_block()
  523. time_start = monotonic()
  524. remaining = None
  525. if on_message is not None:
  526. raise ImproperlyConfigured(
  527. 'Backend does not support on_message callback')
  528. results = []
  529. for result in self.results:
  530. remaining = None
  531. if timeout:
  532. remaining = timeout - (monotonic() - time_start)
  533. if remaining <= 0.0:
  534. raise TimeoutError('join operation timed out')
  535. value = result.get(
  536. timeout=remaining, propagate=propagate,
  537. interval=interval, no_ack=no_ack, on_interval=on_interval,
  538. )
  539. if callback:
  540. callback(result.id, value)
  541. else:
  542. results.append(value)
  543. return results
  544. def then(self, callback, on_error=None):
  545. return self.on_ready.then(callback, on_error)
  546. def iter_native(self, timeout=None, interval=0.5, no_ack=True,
  547. on_message=None, on_interval=None):
  548. """Backend optimized version of :meth:`iterate`.
  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. return self.backend.iter_native(
  556. self,
  557. timeout=timeout, interval=interval, no_ack=no_ack,
  558. on_message=on_message, on_interval=on_interval,
  559. )
  560. def join_native(self, timeout=None, propagate=True,
  561. interval=0.5, callback=None, no_ack=True,
  562. on_message=None, on_interval=None):
  563. """Backend optimized version of :meth:`join`.
  564. .. versionadded:: 2.2
  565. Note that this does not support collecting the results
  566. for different task types using different backends.
  567. This is currently only supported by the amqp, Redis and cache
  568. result backends.
  569. """
  570. assert_will_not_block()
  571. order_index = None if callback else {
  572. result.id: i for i, result in enumerate(self.results)
  573. }
  574. acc = None if callback else [None for _ in range(len(self))]
  575. for task_id, meta in self.iter_native(timeout, interval, no_ack,
  576. on_message, on_interval):
  577. value = meta['result']
  578. if propagate and meta['status'] in states.PROPAGATE_STATES:
  579. raise value
  580. if callback:
  581. callback(task_id, value)
  582. else:
  583. acc[order_index[task_id]] = value
  584. return acc
  585. def _iter_meta(self):
  586. return (meta for _, meta in self.backend.get_many(
  587. {r.id for r in self.results}, max_iterations=1,
  588. ))
  589. def _failed_join_report(self):
  590. return (res for res in self.results
  591. if res.backend.is_cached(res.id) and
  592. res.state in states.PROPAGATE_STATES)
  593. def __len__(self):
  594. return len(self.results)
  595. def __eq__(self, other):
  596. if isinstance(other, ResultSet):
  597. return other.results == self.results
  598. return NotImplemented
  599. def __ne__(self, other):
  600. res = self.__eq__(other)
  601. return True if res is NotImplemented else not res
  602. def __repr__(self):
  603. return '<{0}: [{1}]>'.format(type(self).__name__,
  604. ', '.join(r.id for r in self.results))
  605. @property
  606. def supports_native_join(self):
  607. try:
  608. return self.results[0].supports_native_join
  609. except IndexError:
  610. pass
  611. @property
  612. def app(self):
  613. if self._app is None:
  614. self._app = (self.results[0].app if self.results else
  615. current_app._get_current_object())
  616. return self._app
  617. @app.setter
  618. def app(self, app): # noqa
  619. self._app = app
  620. @property
  621. def backend(self):
  622. return self.app.backend if self.app else self.results[0].backend
  623. @Thenable.register
  624. @python_2_unicode_compatible
  625. class GroupResult(ResultSet):
  626. """Like :class:`ResultSet`, but with an associated id.
  627. This type is returned by :class:`~celery.group`.
  628. It enables inspection of the tasks state and return values as
  629. a single entity.
  630. :param id: The id of the group.
  631. :param results: List of result instances.
  632. """
  633. #: The UUID of the group.
  634. id = None
  635. #: List/iterator of results in the group
  636. results = None
  637. def __init__(self, id=None, results=None, **kwargs):
  638. self.id = id
  639. ResultSet.__init__(self, results, **kwargs)
  640. def save(self, backend=None):
  641. """Save group-result for later retrieval using :meth:`restore`.
  642. Example::
  643. >>> def save_and_restore(result):
  644. ... result.save()
  645. ... result = GroupResult.restore(result.id)
  646. """
  647. return (backend or self.app.backend).save_group(self.id, self)
  648. def delete(self, backend=None):
  649. """Remove this result if it was previously saved."""
  650. (backend or self.app.backend).delete_group(self.id)
  651. def __reduce__(self):
  652. return self.__class__, self.__reduce_args__()
  653. def __reduce_args__(self):
  654. return self.id, self.results
  655. def __bool__(self):
  656. return bool(self.id or self.results)
  657. __nonzero__ = __bool__ # Included for Py2 backwards compatibility
  658. def __eq__(self, other):
  659. if isinstance(other, GroupResult):
  660. return other.id == self.id and other.results == self.results
  661. return NotImplemented
  662. def __ne__(self, other):
  663. res = self.__eq__(other)
  664. return True if res is NotImplemented else not res
  665. def __repr__(self):
  666. return '<{0}: {1} [{2}]>'.format(type(self).__name__, self.id,
  667. ', '.join(r.id for r in self.results))
  668. def as_tuple(self):
  669. return self.id, [r.as_tuple() for r in self.results]
  670. @property
  671. def children(self):
  672. return self.results
  673. @classmethod
  674. def restore(self, id, backend=None):
  675. """Restore previously saved group result."""
  676. return (
  677. backend or (self.app.backend if self.app else current_app.backend)
  678. ).restore_group(id)
  679. @Thenable.register
  680. @python_2_unicode_compatible
  681. class EagerResult(AsyncResult):
  682. """Result that we know has already been executed."""
  683. def __init__(self, id, ret_value, state, traceback=None):
  684. self.id = id
  685. self._result = ret_value
  686. self._state = state
  687. self._traceback = traceback
  688. self.on_ready = promise(args=(self,))
  689. self.on_ready()
  690. def then(self, callback, on_error=None):
  691. return self.on_ready.then(callback, on_error)
  692. def _get_task_meta(self):
  693. return self._cache
  694. def __reduce__(self):
  695. return self.__class__, self.__reduce_args__()
  696. def __reduce_args__(self):
  697. return (self.id, self._result, self._state, self._traceback)
  698. def __copy__(self):
  699. cls, args = self.__reduce__()
  700. return cls(*args)
  701. def ready(self):
  702. return True
  703. def get(self, timeout=None, propagate=True, **kwargs):
  704. if self.successful():
  705. return self.result
  706. elif self.state in states.PROPAGATE_STATES:
  707. if propagate:
  708. raise self.result
  709. return self.result
  710. wait = get # XXX Compat (remove 5.0)
  711. def forget(self):
  712. pass
  713. def revoke(self, *args, **kwargs):
  714. self._state = states.REVOKED
  715. def __repr__(self):
  716. return '<EagerResult: {0.id}>'.format(self)
  717. @property
  718. def _cache(self):
  719. return {'task_id': self.id, 'result': self._result, 'status':
  720. self._state, 'traceback': self._traceback}
  721. @property
  722. def result(self):
  723. """The tasks return value"""
  724. return self._result
  725. @property
  726. def state(self):
  727. """The tasks state."""
  728. return self._state
  729. status = state
  730. @property
  731. def traceback(self):
  732. """The traceback if the task failed."""
  733. return self._traceback
  734. @property
  735. def supports_native_join(self):
  736. return False
  737. def result_from_tuple(r, app=None):
  738. # earlier backends may just pickle, so check if
  739. # result is already prepared.
  740. app = app_or_default(app)
  741. Result = app.AsyncResult
  742. if not isinstance(r, ResultBase):
  743. res, nodes = r
  744. if nodes:
  745. return app.GroupResult(
  746. res, [result_from_tuple(child, app) for child in nodes],
  747. )
  748. # previously did not include parent
  749. id, parent = res if isinstance(res, (list, tuple)) else (res, None)
  750. if parent:
  751. parent = result_from_tuple(parent, app)
  752. return Result(id, parent=parent)
  753. return r