result.py 17 KB

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