result.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. # -*- coding: utf-8 -*-
  2. """
  3. celery.result
  4. ~~~~~~~~~~~~~
  5. Task results/state and groups of results.
  6. :copyright: (c) 2009 - 2011 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 BaseAsyncResult(object):
  23. """Base class for pending result, supports custom task result backend.
  24. :param task_id: see :attr:`task_id`.
  25. :param 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, task_name=None, app=None):
  34. self.app = app_or_default(app)
  35. self.task_id = task_id
  36. self.backend = 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. class AsyncResult(BaseAsyncResult):
  142. """Pending task result using the default backend.
  143. :param task_id: The task uuid.
  144. """
  145. #: Task result store backend to use.
  146. backend = None
  147. def __init__(self, task_id, backend=None, task_name=None, app=None):
  148. app = app_or_default(app)
  149. backend = backend or app.backend
  150. super(AsyncResult, self).__init__(task_id, backend,
  151. task_name=task_name, app=app)
  152. class ResultSet(object):
  153. """Working with more than one result.
  154. :param results: List of result instances.
  155. """
  156. #: List of results in in the set.
  157. results = None
  158. def __init__(self, results, app=None, **kwargs):
  159. self.app = app_or_default(app)
  160. self.results = results
  161. def add(self, result):
  162. """Add :class:`AsyncResult` as a new member of the set.
  163. Does nothing if the result is already a member.
  164. """
  165. if result not in self.results:
  166. self.results.append(result)
  167. def remove(self, result):
  168. """Removes result from the set; it must be a member.
  169. :raises KeyError: if the result is not a member.
  170. """
  171. if isinstance(result, basestring):
  172. result = AsyncResult(result)
  173. try:
  174. self.results.remove(result)
  175. except ValueError:
  176. raise KeyError(result)
  177. def discard(self, result):
  178. """Remove result from the set if it is a member.
  179. If it is not a member, do nothing.
  180. """
  181. try:
  182. self.remove(result)
  183. except KeyError:
  184. pass
  185. def update(self, results):
  186. """Update set with the union of itself and an iterable with
  187. results."""
  188. self.results.extend(r for r in results if r not in self.results)
  189. def clear(self):
  190. """Remove all results from this set."""
  191. self.results[:] = [] # don't create new list.
  192. def successful(self):
  193. """Was all of the tasks successful?
  194. :returns: :const:`True` if all of the tasks finished
  195. successfully (i.e. did not raise an exception).
  196. """
  197. return all(result.successful() for result in self.results)
  198. def failed(self):
  199. """Did any of the tasks fail?
  200. :returns: :const:`True` if any of the tasks failed.
  201. (i.e., raised an exception)
  202. """
  203. return any(result.failed() for result in self.results)
  204. def waiting(self):
  205. """Are any of the tasks incomplete?
  206. :returns: :const:`True` if any of the tasks is still
  207. waiting for execution.
  208. """
  209. return any(not result.ready() for result in self.results)
  210. def ready(self):
  211. """Did all of the tasks complete? (either by success of failure).
  212. :returns: :const:`True` if all of the tasks been
  213. executed.
  214. """
  215. return all(result.ready() for result in self.results)
  216. def completed_count(self):
  217. """Task completion count.
  218. :returns: the number of tasks completed.
  219. """
  220. return sum(imap(int, (result.successful() for result in self.results)))
  221. def forget(self):
  222. """Forget about (and possible remove the result of) all the tasks."""
  223. for result in self.results:
  224. result.forget()
  225. def revoke(self, connection=None, connect_timeout=None):
  226. """Revoke all tasks in the set."""
  227. with self.app.default_connection(connection, connect_timeout) as conn:
  228. for result in self.results:
  229. result.revoke(connection=conn)
  230. def __iter__(self):
  231. return self.iterate()
  232. def __getitem__(self, index):
  233. """`res[i] -> res.results[i]`"""
  234. return self.results[index]
  235. def iterate(self, timeout=None, propagate=True, interval=0.5):
  236. """Iterate over the return values of the tasks as they finish
  237. one by one.
  238. :raises: The exception if any of the tasks raised an exception.
  239. """
  240. elapsed = 0.0
  241. results = OrderedDict((result.task_id, copy(result))
  242. for result in self.results)
  243. while results:
  244. removed = set()
  245. for task_id, result in results.iteritems():
  246. if result.ready():
  247. yield result.get(timeout=timeout and timeout - elapsed,
  248. propagate=propagate)
  249. removed.add(task_id)
  250. else:
  251. if result.backend.subpolling_interval:
  252. time.sleep(result.backend.subpolling_interval)
  253. for task_id in removed:
  254. results.pop(task_id, None)
  255. time.sleep(interval)
  256. elapsed += interval
  257. if timeout and elapsed >= timeout:
  258. raise TimeoutError("The operation timed out")
  259. def join(self, timeout=None, propagate=True, interval=0.5):
  260. """Gathers the results of all tasks as a list in order.
  261. .. note::
  262. This can be an expensive operation for result store
  263. backends that must resort to polling (e.g. database).
  264. You should consider using :meth:`join_native` if your backend
  265. supports it.
  266. .. warning::
  267. Waiting for tasks within a task may lead to deadlocks.
  268. Please see :ref:`task-synchronous-subtasks`.
  269. :keyword timeout: The number of seconds to wait for results before
  270. the operation times out.
  271. :keyword propagate: If any of the tasks raises an exception, the
  272. exception will be re-raised.
  273. :keyword interval: Time to wait (in seconds) before retrying to
  274. retrieve a result from the set. Note that this
  275. does not have any effect when using the AMQP
  276. result store backend, as it does not use polling.
  277. :raises celery.exceptions.TimeoutError: if `timeout` is not
  278. :const:`None` and the operation takes longer than `timeout`
  279. seconds.
  280. """
  281. time_start = time.time()
  282. remaining = None
  283. results = []
  284. for result in self.results:
  285. remaining = None
  286. if timeout:
  287. remaining = timeout - (time.time() - time_start)
  288. if remaining <= 0.0:
  289. raise TimeoutError("join operation timed out")
  290. results.append(result.wait(timeout=remaining,
  291. propagate=propagate,
  292. interval=interval))
  293. return results
  294. def iter_native(self, timeout=None, interval=None):
  295. """Backend optimized version of :meth:`iterate`.
  296. .. versionadded:: 2.2
  297. Note that this does not support collecting the results
  298. for different task types using different backends.
  299. This is currently only supported by the AMQP, Redis and cache
  300. result backends.
  301. """
  302. backend = self.results[0].backend
  303. ids = [result.task_id for result in self.results]
  304. return backend.get_many(ids, timeout=timeout, interval=interval)
  305. def join_native(self, timeout=None, propagate=True, interval=0.5):
  306. """Backend optimized version of :meth:`join`.
  307. .. versionadded:: 2.2
  308. Note that this does not support collecting the results
  309. for different task types using different backends.
  310. This is currently only supported by the AMQP, Redis and cache
  311. result backends.
  312. """
  313. results = self.results
  314. acc = [None for _ in xrange(self.total)]
  315. for task_id, meta in self.iter_native(timeout=timeout,
  316. interval=interval):
  317. acc[results.index(task_id)] = meta["result"]
  318. return acc
  319. @property
  320. def total(self):
  321. """Total number of tasks in the set."""
  322. return len(self.results)
  323. @property
  324. def subtasks(self):
  325. """Deprecated alias to :attr:`results`."""
  326. return self.results
  327. class TaskSetResult(ResultSet):
  328. """An instance of this class is returned by
  329. `TaskSet`'s :meth:`~celery.task.TaskSet.apply_async` method.
  330. It enables inspection of the tasks state and return values as
  331. a single entity.
  332. :param taskset_id: The id of the taskset.
  333. :param results: List of result instances.
  334. """
  335. #: The UUID of the taskset.
  336. taskset_id = None
  337. #: List/iterator of results in the taskset
  338. results = None
  339. def __init__(self, taskset_id, results=None, **kwargs):
  340. self.taskset_id = taskset_id
  341. # XXX previously the "results" arg was named "subtasks".
  342. if "subtasks" in kwargs:
  343. results = kwargs["subtasks"]
  344. super(TaskSetResult, self).__init__(results, **kwargs)
  345. def save(self, backend=None):
  346. """Save taskset result for later retrieval using :meth:`restore`.
  347. Example::
  348. >>> result.save()
  349. >>> result = TaskSetResult.restore(taskset_id)
  350. """
  351. return (backend or self.app.backend).save_taskset(self.taskset_id,
  352. self)
  353. def delete(self, backend=None):
  354. """Remove this result if it was previously saved."""
  355. (backend or self.app.backend).delete_taskset(self.taskset_id)
  356. @classmethod
  357. def restore(self, taskset_id, backend=None):
  358. """Restore previously saved taskset result."""
  359. return (backend or current_app.backend).restore_taskset(taskset_id)
  360. def itersubtasks(self):
  361. """Depreacted. Use ``iter(self.results)`` instead."""
  362. return iter(self.results)
  363. def __reduce__(self):
  364. return (self.__class__, (self.taskset_id, self.results))
  365. class EagerResult(BaseAsyncResult):
  366. """Result that we know has already been executed."""
  367. TimeoutError = TimeoutError
  368. def __init__(self, task_id, ret_value, state, traceback=None):
  369. self.task_id = task_id
  370. self._result = ret_value
  371. self._state = state
  372. self._traceback = traceback
  373. def __reduce__(self):
  374. return (self.__class__, (self.task_id, self._result,
  375. self._state, self._traceback))
  376. def __copy__(self):
  377. cls, args = self.__reduce__()
  378. return cls(*args)
  379. def successful(self):
  380. """Returns :const:`True` if the task executed without failure."""
  381. return self.state == states.SUCCESS
  382. def ready(self):
  383. """Returns :const:`True` if the task has been executed."""
  384. return True
  385. def get(self, timeout=None, propagate=True, **kwargs):
  386. """Wait until the task has been executed and return its result."""
  387. if self.state == states.SUCCESS:
  388. return self.result
  389. elif self.state in states.PROPAGATE_STATES:
  390. if propagate:
  391. raise self.result
  392. return self.result
  393. def revoke(self):
  394. self._state = states.REVOKED
  395. def __repr__(self):
  396. return "<EagerResult: %s>" % self.task_id
  397. @property
  398. def result(self):
  399. """The tasks return value"""
  400. return self._result
  401. @property
  402. def state(self):
  403. """The tasks state."""
  404. return self._state
  405. @property
  406. def traceback(self):
  407. """The traceback if the task failed."""
  408. return self._traceback
  409. @property
  410. def status(self):
  411. """The tasks status (alias to :attr:`state`)."""
  412. return self._state