result.py 20 KB

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