result.py 21 KB

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