result.py 20 KB

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