result.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  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
  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):
  140. graph = DependencyGraph()
  141. for parent, node in self.iterdeps(intermediate=intermediate):
  142. if parent:
  143. graph.add_arc(parent)
  144. graph.add_edge(parent, node)
  145. return graph
  146. def __str__(self):
  147. """`str(self) -> self.id`"""
  148. return self.id
  149. def __hash__(self):
  150. """`hash(self) -> hash(self.id)`"""
  151. return hash(self.id)
  152. def __repr__(self):
  153. return '<{0}: {1}>'.format(type(self).__name__, self.id)
  154. def __eq__(self, other):
  155. if isinstance(other, AsyncResult):
  156. return other.id == self.id
  157. elif isinstance(other, basestring):
  158. return other == self.id
  159. return NotImplemented
  160. def __copy__(self):
  161. r = self.__reduce__()
  162. return r[0](*r[1])
  163. def __reduce__(self):
  164. return self.__class__, self.__reduce_args__()
  165. def __reduce_args__(self):
  166. return self.id, self.backend, self.task_name, self.parent
  167. @cached_property
  168. def graph(self):
  169. return self.build_graph()
  170. @property
  171. def supports_native_join(self):
  172. return self.backend.supports_native_join
  173. @property
  174. def children(self):
  175. children = self.backend.get_children(self.id)
  176. if children:
  177. return [from_serializable(child) for child in children]
  178. @property
  179. def result(self):
  180. """When the task has been executed, this contains the return value.
  181. If the task raised an exception, this will be the exception
  182. instance."""
  183. return self.backend.get_result(self.id)
  184. info = result
  185. @property
  186. def traceback(self):
  187. """Get the traceback of a failed task."""
  188. return self.backend.get_traceback(self.id)
  189. @property
  190. def state(self):
  191. """The tasks current state.
  192. Possible values includes:
  193. *PENDING*
  194. The task is waiting for execution.
  195. *STARTED*
  196. The task has been started.
  197. *RETRY*
  198. The task is to be retried, possibly because of failure.
  199. *FAILURE*
  200. The task raised an exception, or has exceeded the retry limit.
  201. The :attr:`result` attribute then contains the
  202. exception raised by the task.
  203. *SUCCESS*
  204. The task executed successfully. The :attr:`result` attribute
  205. then contains the tasks return value.
  206. """
  207. return self.backend.get_status(self.id)
  208. status = state
  209. @property
  210. def task_id(self):
  211. """compat alias to :attr:`id`"""
  212. return self.id
  213. @task_id.setter # noqa
  214. def task_id(self, id):
  215. self.id = id
  216. BaseAsyncResult = AsyncResult # for backwards compatibility.
  217. class ResultSet(ResultBase):
  218. """Working with more than one result.
  219. :param results: List of result instances.
  220. """
  221. app = None
  222. #: List of results in in the set.
  223. results = None
  224. def __init__(self, results, app=None, **kwargs):
  225. self.app = app_or_default(app or self.app)
  226. self.results = results
  227. def add(self, result):
  228. """Add :class:`AsyncResult` as a new member of the set.
  229. Does nothing if the result is already a member.
  230. """
  231. if result not in self.results:
  232. self.results.append(result)
  233. def remove(self, result):
  234. """Removes result from the set; it must be a member.
  235. :raises KeyError: if the result is not a member.
  236. """
  237. if isinstance(result, basestring):
  238. result = AsyncResult(result)
  239. try:
  240. self.results.remove(result)
  241. except ValueError:
  242. raise KeyError(result)
  243. def discard(self, result):
  244. """Remove result from the set if it is a member.
  245. If it is not a member, do nothing.
  246. """
  247. try:
  248. self.remove(result)
  249. except KeyError:
  250. pass
  251. def update(self, results):
  252. """Update set with the union of itself and an iterable with
  253. results."""
  254. self.results.extend(r for r in results if r not in self.results)
  255. def clear(self):
  256. """Remove all results from this set."""
  257. self.results[:] = [] # don't create new list.
  258. def successful(self):
  259. """Was all of the tasks successful?
  260. :returns: :const:`True` if all of the tasks finished
  261. successfully (i.e. did not raise an exception).
  262. """
  263. return all(result.successful() for result in self.results)
  264. def failed(self):
  265. """Did any of the tasks fail?
  266. :returns: :const:`True` if any of the tasks failed.
  267. (i.e., raised an exception)
  268. """
  269. return any(result.failed() for result in self.results)
  270. def waiting(self):
  271. """Are any of the tasks incomplete?
  272. :returns: :const:`True` if any of the tasks is still
  273. waiting for execution.
  274. """
  275. return any(not result.ready() for result in self.results)
  276. def ready(self):
  277. """Did all of the tasks complete? (either by success of failure).
  278. :returns: :const:`True` if all of the tasks been
  279. executed.
  280. """
  281. return all(result.ready() for result in self.results)
  282. def completed_count(self):
  283. """Task completion count.
  284. :returns: the number of tasks completed.
  285. """
  286. return sum(imap(int, (result.successful() for result in self.results)))
  287. def forget(self):
  288. """Forget about (and possible remove the result of) all the tasks."""
  289. for result in self.results:
  290. result.forget()
  291. def revoke(self, connection=None):
  292. """Revoke all tasks in the set."""
  293. with self.app.connection_or_acquire(connection) as conn:
  294. for result in self.results:
  295. result.revoke(connection=conn)
  296. def __iter__(self):
  297. return self.iterate()
  298. def __getitem__(self, index):
  299. """`res[i] -> res.results[i]`"""
  300. return self.results[index]
  301. def iterate(self, timeout=None, propagate=True, interval=0.5):
  302. """Iterate over the return values of the tasks as they finish
  303. one by one.
  304. :raises: The exception if any of the tasks raised an exception.
  305. """
  306. elapsed = 0.0
  307. results = OrderedDict((result.id, copy(result))
  308. for result in self.results)
  309. while results:
  310. removed = set()
  311. for task_id, result in results.iteritems():
  312. if result.ready():
  313. yield result.get(timeout=timeout and timeout - elapsed,
  314. propagate=propagate)
  315. removed.add(task_id)
  316. else:
  317. if result.backend.subpolling_interval:
  318. time.sleep(result.backend.subpolling_interval)
  319. for task_id in removed:
  320. results.pop(task_id, None)
  321. time.sleep(interval)
  322. elapsed += interval
  323. if timeout and elapsed >= timeout:
  324. raise TimeoutError('The operation timed out')
  325. def get(self, timeout=None, propagate=True, interval=0.5):
  326. """See :meth:`join`
  327. This is here for API compatibility with :class:`AsyncResult`,
  328. in addition it uses :meth:`join_native` if available for the
  329. current result backend.
  330. """
  331. return (self.join_native if self.supports_native_join else self.join)(
  332. timeout=timeout, propagate=propagate, interval=interval)
  333. def join(self, timeout=None, propagate=True, interval=0.5):
  334. """Gathers the results of all tasks as a list in order.
  335. .. note::
  336. This can be an expensive operation for result store
  337. backends that must resort to polling (e.g. database).
  338. You should consider using :meth:`join_native` if your backend
  339. supports it.
  340. .. warning::
  341. Waiting for tasks within a task may lead to deadlocks.
  342. Please see :ref:`task-synchronous-subtasks`.
  343. :keyword timeout: The number of seconds to wait for results before
  344. the operation times out.
  345. :keyword propagate: If any of the tasks raises an exception, the
  346. exception will be re-raised.
  347. :keyword interval: Time to wait (in seconds) before retrying to
  348. retrieve a result from the set. Note that this
  349. does not have any effect when using the amqp
  350. result store backend, as it does not use polling.
  351. :raises celery.exceptions.TimeoutError: if `timeout` is not
  352. :const:`None` and the operation takes longer than `timeout`
  353. seconds.
  354. """
  355. time_start = time.time()
  356. remaining = None
  357. results = []
  358. for result in self.results:
  359. remaining = None
  360. if timeout:
  361. remaining = timeout - (time.time() - time_start)
  362. if remaining <= 0.0:
  363. raise TimeoutError('join operation timed out')
  364. results.append(result.get(timeout=remaining,
  365. propagate=propagate,
  366. interval=interval))
  367. return results
  368. def iter_native(self, timeout=None, interval=None):
  369. """Backend optimized version of :meth:`iterate`.
  370. .. versionadded:: 2.2
  371. Note that this does not support collecting the results
  372. for different task types using different backends.
  373. This is currently only supported by the amqp, Redis and cache
  374. result backends.
  375. """
  376. backend = self.results[0].backend
  377. ids = [result.id for result in self.results]
  378. return backend.get_many(ids, timeout=timeout, interval=interval)
  379. def join_native(self, timeout=None, propagate=True, interval=0.5):
  380. """Backend optimized version of :meth:`join`.
  381. .. versionadded:: 2.2
  382. Note that this does not support collecting the results
  383. for different task types using different backends.
  384. This is currently only supported by the amqp, Redis and cache
  385. result backends.
  386. """
  387. results = self.results
  388. acc = [None for _ in xrange(len(self))]
  389. for task_id, meta in self.iter_native(timeout=timeout,
  390. interval=interval):
  391. acc[results.index(task_id)] = meta['result']
  392. return acc
  393. def __len__(self):
  394. return len(self.results)
  395. def __eq__(self, other):
  396. if isinstance(other, ResultSet):
  397. return other.results == self.results
  398. return NotImplemented
  399. def __repr__(self):
  400. return '<{0}: [{1}]>'.format(type(self).__name__,
  401. ', '.join(r.id for r in self.results))
  402. @property
  403. def subtasks(self):
  404. """Deprecated alias to :attr:`results`."""
  405. return self.results
  406. @property
  407. def supports_native_join(self):
  408. return self.results[0].supports_native_join
  409. class GroupResult(ResultSet):
  410. """Like :class:`ResultSet`, but with an associated id.
  411. This type is returned by :class:`~celery.group`, and the
  412. deprecated TaskSet, meth:`~celery.task.TaskSet.apply_async` method.
  413. It enables inspection of the tasks state and return values as
  414. a single entity.
  415. :param id: The id of the group.
  416. :param results: List of result instances.
  417. """
  418. #: The UUID of the group.
  419. id = None
  420. #: List/iterator of results in the group
  421. results = None
  422. def __init__(self, id=None, results=None, **kwargs):
  423. self.id = id
  424. ResultSet.__init__(self, results, **kwargs)
  425. def save(self, backend=None):
  426. """Save group-result for later retrieval using :meth:`restore`.
  427. Example::
  428. >>> result.save()
  429. >>> result = GroupResult.restore(group_id)
  430. """
  431. return (backend or self.app.backend).save_group(self.id, self)
  432. def delete(self, backend=None):
  433. """Remove this result if it was previously saved."""
  434. (backend or self.app.backend).delete_group(self.id)
  435. def __reduce__(self):
  436. return self.__class__, self.__reduce_args__()
  437. def __reduce_args__(self):
  438. return self.id, self.results
  439. def __eq__(self, other):
  440. if isinstance(other, GroupResult):
  441. return other.id == self.id and other.results == self.results
  442. return NotImplemented
  443. def __repr__(self):
  444. return '<{0}: {1} [{2}]>'.format(type(self).__name__, self.id,
  445. ', '.join(r.id for r in self.results))
  446. def serializable(self):
  447. return self.id, [r.serializable() for r in self.results]
  448. @property
  449. def children(self):
  450. return self.results
  451. @classmethod
  452. def restore(self, id, backend=None):
  453. """Restore previously saved group result."""
  454. return (backend or current_app.backend).restore_group(id)
  455. class TaskSetResult(GroupResult):
  456. """Deprecated version of :class:`GroupResult`"""
  457. def __init__(self, taskset_id, results=None, **kwargs):
  458. # XXX supports the taskset_id kwarg.
  459. # XXX previously the "results" arg was named "subtasks".
  460. if 'subtasks' in kwargs:
  461. results = kwargs['subtasks']
  462. GroupResult.__init__(self, taskset_id, results, **kwargs)
  463. def itersubtasks(self):
  464. """Deprecated. Use ``iter(self.results)`` instead."""
  465. return iter(self.results)
  466. @property
  467. def total(self):
  468. """Deprecated: Use ``len(r)``."""
  469. return len(self)
  470. @property
  471. def taskset_id(self):
  472. """compat alias to :attr:`self.id`"""
  473. return self.id
  474. @taskset_id.setter # noqa
  475. def taskset_id(self, id):
  476. self.id = id
  477. class EagerResult(AsyncResult):
  478. """Result that we know has already been executed."""
  479. task_name = None
  480. def __init__(self, id, ret_value, state, traceback=None):
  481. self.id = id
  482. self._result = ret_value
  483. self._state = state
  484. self._traceback = traceback
  485. def __reduce__(self):
  486. return self.__class__, self.__reduce_args__()
  487. def __reduce_args__(self):
  488. return (self.id, self._result, self._state, self._traceback)
  489. def __copy__(self):
  490. cls, args = self.__reduce__()
  491. return cls(*args)
  492. def ready(self):
  493. return True
  494. def get(self, timeout=None, propagate=True, **kwargs):
  495. if self.successful():
  496. return self.result
  497. elif self.state in states.PROPAGATE_STATES:
  498. if propagate:
  499. raise self.result
  500. return self.result
  501. wait = get
  502. def forget(self):
  503. pass
  504. def revoke(self):
  505. self._state = states.REVOKED
  506. def __repr__(self):
  507. return '<EagerResult: {0.id}>'.format(self)
  508. @property
  509. def result(self):
  510. """The tasks return value"""
  511. return self._result
  512. @property
  513. def state(self):
  514. """The tasks state."""
  515. return self._state
  516. status = state
  517. @property
  518. def traceback(self):
  519. """The traceback if the task failed."""
  520. return self._traceback
  521. @property
  522. def supports_native_join(self):
  523. return False