trace.py 14 KB

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