result.py 21 KB

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