result.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  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, map, 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, 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) 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 any 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 any of the tasks is 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 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(map(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):
  293. """Revoke all tasks in the set."""
  294. with self.app.connection_or_acquire(connection) as conn:
  295. for result in self.results:
  296. result.revoke(connection=conn)
  297. def __iter__(self):
  298. return self.iterate()
  299. def __getitem__(self, index):
  300. """`res[i] -> res.results[i]`"""
  301. return self.results[index]
  302. def iterate(self, timeout=None, propagate=True, interval=0.5):
  303. """Iterate over the return values of the tasks as they finish
  304. one by one.
  305. :raises: The exception if any of the tasks raised an exception.
  306. """
  307. elapsed = 0.0
  308. results = OrderedDict((result.id, copy(result))
  309. for result in self.results)
  310. while results:
  311. removed = set()
  312. for task_id, result in items(results):
  313. if result.ready():
  314. yield result.get(timeout=timeout and timeout - elapsed,
  315. propagate=propagate)
  316. removed.add(task_id)
  317. else:
  318. if result.backend.subpolling_interval:
  319. time.sleep(result.backend.subpolling_interval)
  320. for task_id in removed:
  321. results.pop(task_id, None)
  322. time.sleep(interval)
  323. elapsed += interval
  324. if timeout and elapsed >= timeout:
  325. raise TimeoutError('The operation timed out')
  326. def get(self, timeout=None, propagate=True, interval=0.5):
  327. """See :meth:`join`
  328. This is here for API compatibility with :class:`AsyncResult`,
  329. in addition it uses :meth:`join_native` if available for the
  330. current result backend.
  331. """
  332. return (self.join_native if self.supports_native_join else self.join)(
  333. timeout=timeout, propagate=propagate, interval=interval)
  334. def join(self, timeout=None, propagate=True, interval=0.5):
  335. """Gathers the results of all tasks as a list in order.
  336. .. note::
  337. This can be an expensive operation for result store
  338. backends that must resort to polling (e.g. database).
  339. You should consider using :meth:`join_native` if your backend
  340. supports it.
  341. .. warning::
  342. Waiting for tasks within a task may lead to deadlocks.
  343. Please see :ref:`task-synchronous-subtasks`.
  344. :keyword timeout: The number of seconds to wait for results before
  345. the operation times out.
  346. :keyword propagate: If any of the tasks raises an exception, the
  347. exception will be re-raised.
  348. :keyword interval: Time to wait (in seconds) before retrying to
  349. retrieve a result from the set. Note that this
  350. does not have any effect when using the amqp
  351. result store backend, as it does not use polling.
  352. :raises celery.exceptions.TimeoutError: if `timeout` is not
  353. :const:`None` and the operation takes longer than `timeout`
  354. seconds.
  355. """
  356. time_start = time.time()
  357. remaining = None
  358. results = []
  359. for result in self.results:
  360. remaining = None
  361. if timeout:
  362. remaining = timeout - (time.time() - time_start)
  363. if remaining <= 0.0:
  364. raise TimeoutError('join operation timed out')
  365. results.append(result.get(timeout=remaining,
  366. propagate=propagate,
  367. interval=interval))
  368. return results
  369. def iter_native(self, timeout=None, interval=None):
  370. """Backend optimized version of :meth:`iterate`.
  371. .. versionadded:: 2.2
  372. Note that this does not support collecting the results
  373. for different task types using different backends.
  374. This is currently only supported by the amqp, Redis and cache
  375. result backends.
  376. """
  377. if not self.results:
  378. return iter([])
  379. backend = self.results[0].backend
  380. ids = [result.id for result in self.results]
  381. return backend.get_many(ids, timeout=timeout, interval=interval)
  382. def join_native(self, timeout=None, propagate=True, interval=0.5):
  383. """Backend optimized version of :meth:`join`.
  384. .. versionadded:: 2.2
  385. Note that this does not support collecting the results
  386. for different task types using different backends.
  387. This is currently only supported by the amqp, Redis and cache
  388. result backends.
  389. """
  390. results = self.results
  391. acc = [None for _ in range(len(self))]
  392. for task_id, meta in self.iter_native(timeout=timeout,
  393. interval=interval):
  394. if propagate and meta['status'] in states.PROPAGATE_STATES:
  395. raise meta['result']
  396. acc[results.index(task_id)] = meta['result']
  397. return acc
  398. def _failed_join_report(self):
  399. return (res for res in self.results
  400. if res.backend.is_cached(res.id) and
  401. res.state in states.PROPAGATE_STATES)
  402. def __len__(self):
  403. return len(self.results)
  404. def __eq__(self, other):
  405. if isinstance(other, ResultSet):
  406. return other.results == self.results
  407. return NotImplemented
  408. def __repr__(self):
  409. return '<{0}: [{1}]>'.format(type(self).__name__,
  410. ', '.join(r.id for r in self.results))
  411. @property
  412. def subtasks(self):
  413. """Deprecated alias to :attr:`results`."""
  414. return self.results
  415. @property
  416. def supports_native_join(self):
  417. return self.results[0].supports_native_join
  418. class GroupResult(ResultSet):
  419. """Like :class:`ResultSet`, but with an associated id.
  420. This type is returned by :class:`~celery.group`, and the
  421. deprecated TaskSet, meth:`~celery.task.TaskSet.apply_async` method.
  422. It enables inspection of the tasks state and return values as
  423. a single entity.
  424. :param id: The id of the group.
  425. :param results: List of result instances.
  426. """
  427. #: The UUID of the group.
  428. id = None
  429. #: List/iterator of results in the group
  430. results = None
  431. def __init__(self, id=None, results=None, **kwargs):
  432. self.id = id
  433. ResultSet.__init__(self, results, **kwargs)
  434. def save(self, backend=None):
  435. """Save group-result for later retrieval using :meth:`restore`.
  436. Example::
  437. >>> result.save()
  438. >>> result = GroupResult.restore(group_id)
  439. """
  440. return (backend or self.app.backend).save_group(self.id, self)
  441. def delete(self, backend=None):
  442. """Remove this result if it was previously saved."""
  443. (backend or self.app.backend).delete_group(self.id)
  444. def __reduce__(self):
  445. return self.__class__, self.__reduce_args__()
  446. def __reduce_args__(self):
  447. return self.id, self.results
  448. def __eq__(self, other):
  449. if isinstance(other, GroupResult):
  450. return other.id == self.id and other.results == self.results
  451. return NotImplemented
  452. def __repr__(self):
  453. return '<{0}: {1} [{2}]>'.format(type(self).__name__, self.id,
  454. ', '.join(r.id for r in self.results))
  455. def serializable(self):
  456. return self.id, [r.serializable() for r in self.results]
  457. @property
  458. def children(self):
  459. return self.results
  460. @classmethod
  461. def restore(self, id, backend=None):
  462. """Restore previously saved group result."""
  463. return (backend or current_app.backend).restore_group(id)
  464. class TaskSetResult(GroupResult):
  465. """Deprecated version of :class:`GroupResult`"""
  466. def __init__(self, taskset_id, results=None, **kwargs):
  467. # XXX supports the taskset_id kwarg.
  468. # XXX previously the "results" arg was named "subtasks".
  469. if 'subtasks' in kwargs:
  470. results = kwargs['subtasks']
  471. GroupResult.__init__(self, taskset_id, results, **kwargs)
  472. def itersubtasks(self):
  473. """Deprecated. Use ``iter(self.results)`` instead."""
  474. return iter(self.results)
  475. @property
  476. def total(self):
  477. """Deprecated: Use ``len(r)``."""
  478. return len(self)
  479. @property
  480. def taskset_id(self):
  481. """compat alias to :attr:`self.id`"""
  482. return self.id
  483. @taskset_id.setter # noqa
  484. def taskset_id(self, id):
  485. self.id = id
  486. class EagerResult(AsyncResult):
  487. """Result that we know has already been executed."""
  488. task_name = None
  489. def __init__(self, id, ret_value, state, traceback=None):
  490. self.id = id
  491. self._result = ret_value
  492. self._state = state
  493. self._traceback = traceback
  494. def __reduce__(self):
  495. return self.__class__, self.__reduce_args__()
  496. def __reduce_args__(self):
  497. return (self.id, self._result, self._state, self._traceback)
  498. def __copy__(self):
  499. cls, args = self.__reduce__()
  500. return cls(*args)
  501. def ready(self):
  502. return True
  503. def get(self, timeout=None, propagate=True, **kwargs):
  504. if self.successful():
  505. return self.result
  506. elif self.state in states.PROPAGATE_STATES:
  507. if propagate:
  508. raise self.result
  509. return self.result
  510. wait = get
  511. def forget(self):
  512. pass
  513. def revoke(self):
  514. self._state = states.REVOKED
  515. def __repr__(self):
  516. return '<EagerResult: {0.id}>'.format(self)
  517. @property
  518. def result(self):
  519. """The tasks return value"""
  520. return self._result
  521. @property
  522. def state(self):
  523. """The tasks state."""
  524. return self._state
  525. status = state
  526. @property
  527. def traceback(self):
  528. """The traceback if the task failed."""
  529. return self._traceback
  530. @property
  531. def supports_native_join(self):
  532. return False
  533. def from_serializable(r, Result=AsyncResult):
  534. # earlier backends may just pickle, so check if
  535. # result is already prepared.
  536. if not isinstance(r, ResultBase):
  537. id = parent = None
  538. res, nodes = r
  539. if nodes:
  540. return GroupResult(
  541. res, [from_serializable(child, Result) for child in nodes],
  542. )
  543. if isinstance(res, (list, tuple)):
  544. id, parent = res[0], res[1]
  545. return Result(id, parent=parent)
  546. return r