result.py 19 KB

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