result.py 24 KB

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