trace.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. # -*- coding: utf-8 -*-
  2. """
  3. celery.task.trace
  4. ~~~~~~~~~~~~~~~~~~~~
  5. This module defines how the task execution is traced:
  6. errors are recorded, handlers are applied and so on.
  7. """
  8. from __future__ import absolute_import
  9. # ## ---
  10. # This is the heart of the worker, the inner loop so to speak.
  11. # It used to be split up into nice little classes and methods,
  12. # but in the end it only resulted in bad performance and horrible tracebacks,
  13. # so instead we now use one closure per task class.
  14. import os
  15. import socket
  16. import sys
  17. from warnings import warn
  18. from kombu.utils import kwdict
  19. from celery import current_app
  20. from celery import states, signals
  21. from celery._state import _task_stack
  22. from celery.app import set_default_app
  23. from celery.app.task import Task as BaseTask, Context
  24. from celery.datastructures import ExceptionInfo
  25. from celery.exceptions import Ignore, RetryTaskError
  26. from celery.utils.serialization import get_pickleable_exception
  27. from celery.utils.log import get_logger
  28. _logger = get_logger(__name__)
  29. send_prerun = signals.task_prerun.send
  30. prerun_receivers = signals.task_prerun.receivers
  31. send_postrun = signals.task_postrun.send
  32. postrun_receivers = signals.task_postrun.receivers
  33. send_success = signals.task_success.send
  34. success_receivers = signals.task_success.receivers
  35. STARTED = states.STARTED
  36. SUCCESS = states.SUCCESS
  37. IGNORED = states.IGNORED
  38. RETRY = states.RETRY
  39. FAILURE = states.FAILURE
  40. EXCEPTION_STATES = states.EXCEPTION_STATES
  41. #: set by :func:`setup_worker_optimizations`
  42. _tasks = None
  43. _patched = {}
  44. def mro_lookup(cls, attr, stop=(), monkey_patched=[]):
  45. """Returns the first node by MRO order that defines an attribute.
  46. :keyword stop: A list of types that if reached will stop the search.
  47. :keyword monkey_patched: Use one of the stop classes if the attr's
  48. module origin is not in this list, this to detect monkey patched
  49. attributes.
  50. :returns None: if the attribute was not found.
  51. """
  52. for node in cls.mro():
  53. if node in stop:
  54. try:
  55. attr = node.__dict__[attr]
  56. module_origin = attr.__module__
  57. except (AttributeError, KeyError):
  58. pass
  59. else:
  60. if module_origin not in monkey_patched:
  61. return node
  62. return
  63. if attr in node.__dict__:
  64. return node
  65. def task_has_custom(task, attr):
  66. """Returns true if the task or one of its bases
  67. defines ``attr`` (excluding the one in BaseTask)."""
  68. return mro_lookup(task.__class__, attr, stop=(BaseTask, object),
  69. monkey_patched=['celery.app.task'])
  70. class TraceInfo(object):
  71. __slots__ = ('state', 'retval')
  72. def __init__(self, state, retval=None):
  73. self.state = state
  74. self.retval = retval
  75. def handle_error_state(self, task, eager=False):
  76. store_errors = not eager
  77. if task.ignore_result:
  78. store_errors = task.store_errors_even_if_ignored
  79. return {
  80. RETRY: self.handle_retry,
  81. FAILURE: self.handle_failure,
  82. }[self.state](task, store_errors=store_errors)
  83. def handle_retry(self, task, store_errors=True):
  84. """Handle retry exception."""
  85. # the exception raised is the RetryTaskError semi-predicate,
  86. # and it's exc' attribute is the original exception raised (if any).
  87. req = task.request
  88. type_, _, tb = sys.exc_info()
  89. try:
  90. pred = self.retval
  91. einfo = ExceptionInfo((type_, pred, tb))
  92. if store_errors:
  93. task.backend.mark_as_retry(req.id, pred.exc, einfo.traceback)
  94. task.on_retry(pred.exc, req.id, req.args, req.kwargs, einfo)
  95. return einfo
  96. finally:
  97. del(tb)
  98. def handle_failure(self, task, store_errors=True):
  99. """Handle exception."""
  100. req = task.request
  101. type_, _, tb = sys.exc_info()
  102. try:
  103. exc = self.retval
  104. einfo = ExceptionInfo((type_, get_pickleable_exception(exc), tb))
  105. if store_errors:
  106. task.backend.mark_as_failure(req.id, exc, einfo.traceback)
  107. task.on_failure(exc, req.id, req.args, req.kwargs, einfo)
  108. signals.task_failure.send(sender=task, task_id=req.id,
  109. exception=exc, args=req.args,
  110. kwargs=req.kwargs,
  111. traceback=einfo.tb,
  112. einfo=einfo)
  113. return einfo
  114. finally:
  115. del(tb)
  116. def build_tracer(name, task, loader=None, hostname=None, store_errors=True,
  117. Info=TraceInfo, eager=False, propagate=False):
  118. """Builts a function that tracing the tasks execution; catches all
  119. exceptions, and saves the state and result of the task execution
  120. to the result backend.
  121. If the call was successful, it saves the result to the task result
  122. backend, and sets the task status to `"SUCCESS"`.
  123. If the call raises :exc:`~celery.exceptions.RetryTaskError`, it extracts
  124. the original exception, uses that as the result and sets the task status
  125. to `"RETRY"`.
  126. If the call results in an exception, it saves the exception as the task
  127. result, and sets the task status to `"FAILURE"`.
  128. Returns a function that takes the following arguments:
  129. :param uuid: The unique id of the task.
  130. :param args: List of positional args to pass on to the function.
  131. :param kwargs: Keyword arguments mapping to pass on to the function.
  132. :keyword request: Request dict.
  133. """
  134. # If the task doesn't define a custom __call__ method
  135. # we optimize it away by simply calling the run method directly,
  136. # saving the extra method call and a line less in the stack trace.
  137. fun = task if task_has_custom(task, '__call__') else task.run
  138. loader = loader or current_app.loader
  139. backend = task.backend
  140. ignore_result = task.ignore_result
  141. track_started = task.track_started
  142. track_started = not eager and (task.track_started and not ignore_result)
  143. publish_result = not eager and not ignore_result
  144. hostname = hostname or socket.gethostname()
  145. loader_task_init = loader.on_task_init
  146. loader_cleanup = loader.on_process_cleanup
  147. task_on_success = None
  148. task_after_return = None
  149. if task_has_custom(task, 'on_success'):
  150. task_on_success = task.on_success
  151. if task_has_custom(task, 'after_return'):
  152. task_after_return = task.after_return
  153. store_result = backend.store_result
  154. backend_cleanup = backend.process_cleanup
  155. pid = os.getpid()
  156. request_stack = task.request_stack
  157. push_request = request_stack.push
  158. pop_request = request_stack.pop
  159. push_task = _task_stack.push
  160. pop_task = _task_stack.pop
  161. on_chord_part_return = backend.on_chord_part_return
  162. from celery import canvas
  163. subtask = canvas.subtask
  164. def trace_task(uuid, args, kwargs, request=None):
  165. R = I = None
  166. kwargs = kwdict(kwargs)
  167. try:
  168. push_task(task)
  169. task_request = Context(request or {}, args=args,
  170. called_directly=False, kwargs=kwargs)
  171. push_request(task_request)
  172. try:
  173. # -*- PRE -*-
  174. if prerun_receivers:
  175. send_prerun(sender=task, task_id=uuid, task=task,
  176. args=args, kwargs=kwargs)
  177. loader_task_init(uuid, task)
  178. if track_started:
  179. store_result(uuid, {'pid': pid,
  180. 'hostname': hostname}, STARTED)
  181. # -*- TRACE -*-
  182. try:
  183. R = retval = fun(*args, **kwargs)
  184. state = SUCCESS
  185. except Ignore as exc:
  186. I, R = Info(IGNORED, exc), ExceptionInfo(internal=True)
  187. except RetryTaskError as exc:
  188. I = Info(RETRY, exc)
  189. state, retval = I.state, I.retval
  190. R = I.handle_error_state(task, eager=eager)
  191. except Exception as exc:
  192. if propagate:
  193. raise
  194. I = Info(FAILURE, exc)
  195. state, retval = I.state, I.retval
  196. R = I.handle_error_state(task, eager=eager)
  197. [subtask(errback).apply_async((uuid, ))
  198. for errback in task_request.errbacks or []]
  199. except BaseException as exc:
  200. raise
  201. else:
  202. # callback tasks must be applied before the result is
  203. # stored, so that result.children is populated.
  204. [subtask(callback).apply_async((retval, ))
  205. for callback in task_request.callbacks or []]
  206. if publish_result:
  207. store_result(uuid, retval, SUCCESS)
  208. if task_on_success:
  209. task_on_success(retval, uuid, args, kwargs)
  210. if success_receivers:
  211. send_success(sender=task, result=retval)
  212. # -* POST *-
  213. if task_request.chord:
  214. on_chord_part_return(task)
  215. if task_after_return:
  216. task_after_return(state, retval, uuid, args, kwargs, None)
  217. if postrun_receivers:
  218. send_postrun(sender=task, task_id=uuid, task=task,
  219. args=args, kwargs=kwargs,
  220. retval=retval, state=state)
  221. finally:
  222. pop_task()
  223. pop_request()
  224. if not eager:
  225. try:
  226. backend_cleanup()
  227. loader_cleanup()
  228. except (KeyboardInterrupt, SystemExit, MemoryError):
  229. raise
  230. except Exception as exc:
  231. _logger.error('Process cleanup failed: %r', exc,
  232. exc_info=True)
  233. except Exception as exc:
  234. if eager:
  235. raise
  236. R = report_internal_error(task, exc)
  237. return R, I
  238. return trace_task
  239. def trace_task(task, uuid, args, kwargs, request={}, **opts):
  240. try:
  241. if task.__trace__ is None:
  242. task.__trace__ = build_tracer(task.name, task, **opts)
  243. return task.__trace__(uuid, args, kwargs, request)[0]
  244. except Exception as exc:
  245. return report_internal_error(task, exc)
  246. def _trace_task_ret(name, uuid, args, kwargs, request={}, **opts):
  247. return trace_task(current_app.tasks[name],
  248. uuid, args, kwargs, request, **opts)
  249. trace_task_ret = _trace_task_ret
  250. def _fast_trace_task(task, uuid, args, kwargs, request={}):
  251. # setup_worker_optimizations will point trace_task_ret to here,
  252. # so this is the function used in the worker.
  253. return _tasks[task].__trace__(uuid, args, kwargs, request)[0]
  254. def eager_trace_task(task, uuid, args, kwargs, request=None, **opts):
  255. opts.setdefault('eager', True)
  256. return build_tracer(task.name, task, **opts)(
  257. uuid, args, kwargs, request)
  258. def report_internal_error(task, exc):
  259. _type, _value, _tb = sys.exc_info()
  260. try:
  261. _value = task.backend.prepare_exception(exc)
  262. exc_info = ExceptionInfo((_type, _value, _tb), internal=True)
  263. warn(RuntimeWarning(
  264. 'Exception raised outside body: {0!r}:\n{1}'.format(
  265. exc, exc_info.traceback)))
  266. return exc_info
  267. finally:
  268. del(_tb)
  269. def setup_worker_optimizations(app):
  270. global _tasks
  271. global trace_task_ret
  272. # make sure custom Task.__call__ methods that calls super
  273. # will not mess up the request/task stack.
  274. _install_stack_protection()
  275. # all new threads start without a current app, so if an app is not
  276. # passed on to the thread it will fall back to the "default app",
  277. # which then could be the wrong app. So for the worker
  278. # we set this to always return our app. This is a hack,
  279. # and means that only a single app can be used for workers
  280. # running in the same process.
  281. set_default_app(app)
  282. # evaluate all task classes by finalizing the app.
  283. app.finalize()
  284. # set fast shortcut to task registry
  285. _tasks = app._tasks
  286. trace_task_ret = _fast_trace_task
  287. try:
  288. sys.modules['celery.worker.job'].trace_task_ret = _fast_trace_task
  289. except KeyError:
  290. pass
  291. def reset_worker_optimizations():
  292. global trace_task_ret
  293. trace_task_ret = _trace_task_ret
  294. try:
  295. delattr(BaseTask, '_stackprotected')
  296. except AttributeError:
  297. pass
  298. try:
  299. BaseTask.__call__ = _patched.pop('BaseTask.__call__')
  300. except KeyError:
  301. pass
  302. try:
  303. sys.modules['celery.worker.job'].trace_task_ret = _trace_task_ret
  304. except KeyError:
  305. pass
  306. def _install_stack_protection():
  307. # Patches BaseTask.__call__ in the worker to handle the edge case
  308. # where people override it and also call super.
  309. #
  310. # - The worker optimizes away BaseTask.__call__ and instead
  311. # calls task.run directly.
  312. # - so with the addition of current_task and the request stack
  313. # BaseTask.__call__ now pushes to those stacks so that
  314. # they work when tasks are called directly.
  315. #
  316. # The worker only optimizes away __call__ in the case
  317. # where it has not been overridden, so the request/task stack
  318. # will blow if a custom task class defines __call__ and also
  319. # calls super().
  320. if not getattr(BaseTask, '_stackprotected', False):
  321. _patched['BaseTask.__call__'] = orig = BaseTask.__call__
  322. def __protected_call__(self, *args, **kwargs):
  323. stack = self.request_stack
  324. req = stack.top
  325. if req and not req._protected and \
  326. len(stack) == 1 and not req.called_directly:
  327. req._protected = 1
  328. return self.run(*args, **kwargs)
  329. return orig(self, *args, **kwargs)
  330. BaseTask.__call__ = __protected_call__
  331. BaseTask._stackprotected = True