result.py 18 KB

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