result.py 22 KB

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