trace.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. # -*- coding: utf-8 -*-
  2. """
  3. celery.app.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 logging
  15. import os
  16. import socket
  17. import sys
  18. from collections import namedtuple
  19. from warnings import warn
  20. from billiard.einfo import ExceptionInfo
  21. from kombu.exceptions import EncodeError
  22. from kombu.serialization import loads as loads_message, prepare_accept_content
  23. from kombu.utils.encoding import safe_repr, safe_str
  24. from celery import current_app, group
  25. from celery import states, signals
  26. from celery._state import _task_stack
  27. from celery.app import set_default_app
  28. from celery.app.task import Task as BaseTask, Context
  29. from celery.exceptions import Ignore, Reject, Retry, InvalidTaskError
  30. from celery.five import monotonic
  31. from celery.utils.log import get_logger
  32. from celery.utils.objects import mro_lookup
  33. from celery.utils.serialization import (
  34. get_pickleable_exception, get_pickled_exception, get_pickleable_etype,
  35. )
  36. from celery.utils.text import truncate
  37. __all__ = ['TraceInfo', 'build_tracer', 'trace_task',
  38. 'setup_worker_optimizations', 'reset_worker_optimizations']
  39. logger = get_logger(__name__)
  40. info = logger.info
  41. #: Format string used to log task success.
  42. LOG_SUCCESS = """\
  43. Task %(name)s[%(id)s] succeeded in %(runtime)ss: %(return_value)s\
  44. """
  45. #: Format string used to log task failure.
  46. LOG_FAILURE = """\
  47. Task %(name)s[%(id)s] %(description)s: %(exc)s\
  48. """
  49. #: Format string used to log task internal error.
  50. LOG_INTERNAL_ERROR = """\
  51. Task %(name)s[%(id)s] %(description)s: %(exc)s\
  52. """
  53. #: Format string used to log task ignored.
  54. LOG_IGNORED = """\
  55. Task %(name)s[%(id)s] %(description)s\
  56. """
  57. #: Format string used to log task rejected.
  58. LOG_REJECTED = """\
  59. Task %(name)s[%(id)s] %(exc)s\
  60. """
  61. #: Format string used to log task retry.
  62. LOG_RETRY = """\
  63. Task %(name)s[%(id)s] retry: %(exc)s\
  64. """
  65. log_policy_t = namedtuple(
  66. 'log_policy_t', ('format', 'description', 'severity', 'traceback', 'mail'),
  67. )
  68. log_policy_reject = log_policy_t(LOG_REJECTED, 'rejected', logging.WARN, 1, 1)
  69. log_policy_ignore = log_policy_t(LOG_IGNORED, 'ignored', logging.INFO, 0, 0)
  70. log_policy_internal = log_policy_t(
  71. LOG_INTERNAL_ERROR, 'INTERNAL ERROR', logging.CRITICAL, 1, 1,
  72. )
  73. log_policy_expected = log_policy_t(
  74. LOG_FAILURE, 'raised expected', logging.INFO, 0, 0,
  75. )
  76. log_policy_unexpected = log_policy_t(
  77. LOG_FAILURE, 'raised unexpected', logging.ERROR, 1, 1,
  78. )
  79. send_prerun = signals.task_prerun.send
  80. send_postrun = signals.task_postrun.send
  81. send_success = signals.task_success.send
  82. STARTED = states.STARTED
  83. SUCCESS = states.SUCCESS
  84. IGNORED = states.IGNORED
  85. REJECTED = states.REJECTED
  86. RETRY = states.RETRY
  87. FAILURE = states.FAILURE
  88. EXCEPTION_STATES = states.EXCEPTION_STATES
  89. IGNORE_STATES = frozenset([IGNORED, RETRY, REJECTED])
  90. #: set by :func:`setup_worker_optimizations`
  91. _localized = []
  92. _patched = {}
  93. trace_ok_t = namedtuple('trace_ok_t', ('retval', 'info', 'runtime', 'retstr'))
  94. def task_has_custom(task, attr):
  95. """Return true if the task or one of its bases
  96. defines ``attr`` (excluding the one in BaseTask)."""
  97. return mro_lookup(task.__class__, attr, stop=(BaseTask, object),
  98. monkey_patched=['celery.app.task'])
  99. def get_log_policy(task, einfo, exc):
  100. if isinstance(exc, Reject):
  101. return log_policy_reject
  102. elif isinstance(exc, Ignore):
  103. return log_policy_ignore
  104. elif einfo.internal:
  105. return log_policy_internal
  106. else:
  107. if task.throws and isinstance(exc, task.throws):
  108. return log_policy_expected
  109. return log_policy_unexpected
  110. class TraceInfo(object):
  111. __slots__ = ('state', 'retval')
  112. def __init__(self, state, retval=None):
  113. self.state = state
  114. self.retval = retval
  115. def handle_error_state(self, task, eager=False):
  116. store_errors = not eager
  117. if task.ignore_result:
  118. store_errors = task.store_errors_even_if_ignored
  119. return {
  120. RETRY: self.handle_retry,
  121. FAILURE: self.handle_failure,
  122. }[self.state](task, store_errors=store_errors)
  123. def handle_reject(self, task, **kwargs):
  124. self._log_error(task, ExceptionInfo())
  125. def handle_ignore(self, task, **kwargs):
  126. self._log_error(task, ExceptionInfo())
  127. def handle_retry(self, task, store_errors=True):
  128. """Handle retry exception."""
  129. # the exception raised is the Retry semi-predicate,
  130. # and it's exc' attribute is the original exception raised (if any).
  131. req = task.request
  132. type_, _, tb = sys.exc_info()
  133. try:
  134. reason = self.retval
  135. einfo = ExceptionInfo((type_, reason, tb))
  136. if store_errors:
  137. task.backend.mark_as_retry(
  138. req.id, reason.exc, einfo.traceback, request=req,
  139. )
  140. task.on_retry(reason.exc, req.id, req.args, req.kwargs, einfo)
  141. signals.task_retry.send(sender=task, request=req,
  142. reason=reason, einfo=einfo)
  143. info(LOG_RETRY, {
  144. 'id': req.id, 'name': task.name,
  145. 'exc': safe_repr(reason.exc),
  146. })
  147. return einfo
  148. finally:
  149. del(tb)
  150. def handle_failure(self, task, store_errors=True):
  151. """Handle exception."""
  152. req = task.request
  153. type_, _, tb = sys.exc_info()
  154. try:
  155. exc = self.retval
  156. einfo = ExceptionInfo()
  157. einfo.exception = get_pickleable_exception(einfo.exception)
  158. einfo.type = get_pickleable_etype(einfo.type)
  159. if store_errors:
  160. task.backend.mark_as_failure(
  161. req.id, exc, einfo.traceback, request=req,
  162. )
  163. task.on_failure(exc, req.id, req.args, req.kwargs, einfo)
  164. signals.task_failure.send(sender=task, task_id=req.id,
  165. exception=exc, args=req.args,
  166. kwargs=req.kwargs,
  167. traceback=tb,
  168. einfo=einfo)
  169. self._log_error(task, einfo)
  170. return einfo
  171. finally:
  172. del(tb)
  173. def _log_error(self, task, einfo):
  174. req = task.request
  175. eobj = einfo.exception = get_pickled_exception(einfo.exception)
  176. exception, traceback, exc_info, sargs, skwargs = (
  177. safe_repr(eobj),
  178. safe_str(einfo.traceback),
  179. einfo.exc_info,
  180. safe_repr(req.args),
  181. safe_repr(req.kwargs),
  182. )
  183. policy = get_log_policy(task, einfo, eobj)
  184. context = {
  185. 'hostname': req.hostname,
  186. 'id': req.id,
  187. 'name': task.name,
  188. 'exc': exception,
  189. 'traceback': traceback,
  190. 'args': sargs,
  191. 'kwargs': skwargs,
  192. 'description': policy.description,
  193. 'internal': einfo.internal,
  194. }
  195. logger.log(policy.severity, policy.format.strip(), context,
  196. exc_info=exc_info if policy.traceback else None,
  197. extra={'data': context})
  198. if policy.mail:
  199. task.send_error_email(context, einfo.exception)
  200. def build_tracer(name, task, loader=None, hostname=None, store_errors=True,
  201. Info=TraceInfo, eager=False, propagate=False, app=None,
  202. monotonic=monotonic, truncate=truncate,
  203. trace_ok_t=trace_ok_t, IGNORE_STATES=IGNORE_STATES):
  204. """Return a function that traces task execution; catches all
  205. exceptions and updates result backend with the state and result
  206. If the call was successful, it saves the result to the task result
  207. backend, and sets the task status to `"SUCCESS"`.
  208. If the call raises :exc:`~@Retry`, it extracts
  209. the original exception, uses that as the result and sets the task state
  210. to `"RETRY"`.
  211. If the call results in an exception, it saves the exception as the task
  212. result, and sets the task state to `"FAILURE"`.
  213. Return a function that takes the following arguments:
  214. :param uuid: The id of the task.
  215. :param args: List of positional args to pass on to the function.
  216. :param kwargs: Keyword arguments mapping to pass on to the function.
  217. :keyword request: Request dict.
  218. """
  219. # If the task doesn't define a custom __call__ method
  220. # we optimize it away by simply calling the run method directly,
  221. # saving the extra method call and a line less in the stack trace.
  222. fun = task if task_has_custom(task, '__call__') else task.run
  223. loader = loader or app.loader
  224. backend = task.backend
  225. ignore_result = task.ignore_result
  226. track_started = task.track_started
  227. track_started = not eager and (task.track_started and not ignore_result)
  228. publish_result = not eager and not ignore_result
  229. hostname = hostname or socket.gethostname()
  230. loader_task_init = loader.on_task_init
  231. loader_cleanup = loader.on_process_cleanup
  232. task_on_success = None
  233. task_after_return = None
  234. if task_has_custom(task, 'on_success'):
  235. task_on_success = task.on_success
  236. if task_has_custom(task, 'after_return'):
  237. task_after_return = task.after_return
  238. store_result = backend.store_result
  239. backend_cleanup = backend.process_cleanup
  240. pid = os.getpid()
  241. request_stack = task.request_stack
  242. push_request = request_stack.push
  243. pop_request = request_stack.pop
  244. push_task = _task_stack.push
  245. pop_task = _task_stack.pop
  246. on_chord_part_return = backend.on_chord_part_return
  247. _does_info = logger.isEnabledFor(logging.INFO)
  248. prerun_receivers = signals.task_prerun.receivers
  249. postrun_receivers = signals.task_postrun.receivers
  250. success_receivers = signals.task_success.receivers
  251. from celery import canvas
  252. signature = canvas.maybe_signature # maybe_ does not clone if already
  253. def on_error(request, exc, uuid, state=FAILURE, call_errbacks=True):
  254. if propagate:
  255. raise
  256. I = Info(state, exc)
  257. R = I.handle_error_state(task, eager=eager)
  258. if call_errbacks:
  259. group(
  260. [signature(errback, app=app)
  261. for errback in request.errbacks or []], app=app,
  262. ).apply_async((uuid, ))
  263. return I, R, I.state, I.retval
  264. def trace_task(uuid, args, kwargs, request=None):
  265. # R - is the possibly prepared return value.
  266. # I - is the Info object.
  267. # T - runtime
  268. # Rstr - textual representation of return value
  269. # retval - is the always unmodified return value.
  270. # state - is the resulting task state.
  271. # This function is very long because we have unrolled all the calls
  272. # for performance reasons, and because the function is so long
  273. # we want the main variables (I, and R) to stand out visually from the
  274. # the rest of the variables, so breaking PEP8 is worth it ;)
  275. R = I = T = Rstr = retval = state = None
  276. time_start = monotonic()
  277. try:
  278. try:
  279. kwargs.items
  280. except AttributeError:
  281. raise InvalidTaskError(
  282. 'Task keyword arguments is not a mapping')
  283. push_task(task)
  284. task_request = Context(request or {}, args=args,
  285. called_directly=False, kwargs=kwargs)
  286. push_request(task_request)
  287. try:
  288. # -*- PRE -*-
  289. if prerun_receivers:
  290. send_prerun(sender=task, task_id=uuid, task=task,
  291. args=args, kwargs=kwargs)
  292. loader_task_init(uuid, task)
  293. if track_started:
  294. store_result(
  295. uuid, {'pid': pid, 'hostname': hostname}, STARTED,
  296. request=task_request,
  297. )
  298. # -*- TRACE -*-
  299. try:
  300. R = retval = fun(*args, **kwargs)
  301. state = SUCCESS
  302. except Reject as exc:
  303. I, R = Info(REJECTED, exc), ExceptionInfo(internal=True)
  304. state, retval = I.state, I.retval
  305. I.handle_reject(task)
  306. except Ignore as exc:
  307. I, R = Info(IGNORED, exc), ExceptionInfo(internal=True)
  308. state, retval = I.state, I.retval
  309. I.handle_ignore(task)
  310. except Retry as exc:
  311. I, R, state, retval = on_error(
  312. task_request, exc, uuid, RETRY, call_errbacks=False,
  313. )
  314. except Exception as exc:
  315. I, R, state, retval = on_error(task_request, exc, uuid)
  316. except BaseException as exc:
  317. raise
  318. else:
  319. try:
  320. # callback tasks must be applied before the result is
  321. # stored, so that result.children is populated.
  322. # groups are called inline and will store trail
  323. # separately, so need to call them separately
  324. # so that the trail's not added multiple times :(
  325. # (Issue #1936)
  326. callbacks = task.request.callbacks
  327. if callbacks:
  328. if len(task.request.callbacks) > 1:
  329. sigs, groups = [], []
  330. for sig in callbacks:
  331. sig = signature(sig, app=app)
  332. if isinstance(sig, group):
  333. groups.append(sig)
  334. else:
  335. sigs.append(sig)
  336. for group_ in groups:
  337. group.apply_async((retval, ))
  338. if sigs:
  339. group(sigs).apply_async(retval, )
  340. else:
  341. signature(callbacks[0], app=app).delay(retval)
  342. if publish_result:
  343. store_result(
  344. uuid, retval, SUCCESS, request=task_request,
  345. )
  346. except EncodeError as exc:
  347. I, R, state, retval = on_error(task_request, exc, uuid)
  348. else:
  349. if task_on_success:
  350. task_on_success(retval, uuid, args, kwargs)
  351. if success_receivers:
  352. send_success(sender=task, result=retval)
  353. if _does_info:
  354. T = monotonic() - time_start
  355. Rstr = truncate(safe_repr(R), 256)
  356. info(LOG_SUCCESS, {
  357. 'id': uuid, 'name': name,
  358. 'return_value': Rstr, 'runtime': T,
  359. })
  360. # -* POST *-
  361. if state not in IGNORE_STATES:
  362. if task_request.chord:
  363. on_chord_part_return(task, state, R)
  364. if task_after_return:
  365. task_after_return(
  366. state, retval, uuid, args, kwargs, None,
  367. )
  368. finally:
  369. try:
  370. if postrun_receivers:
  371. send_postrun(sender=task, task_id=uuid, task=task,
  372. args=args, kwargs=kwargs,
  373. retval=retval, state=state)
  374. finally:
  375. pop_task()
  376. pop_request()
  377. if not eager:
  378. try:
  379. backend_cleanup()
  380. loader_cleanup()
  381. except (KeyboardInterrupt, SystemExit, MemoryError):
  382. raise
  383. except Exception as exc:
  384. logger.error('Process cleanup failed: %r', exc,
  385. exc_info=True)
  386. except MemoryError:
  387. raise
  388. except Exception as exc:
  389. if eager:
  390. raise
  391. R = report_internal_error(task, exc)
  392. return trace_ok_t(R, I, T, Rstr)
  393. return trace_task
  394. def trace_task(task, uuid, args, kwargs, request={}, **opts):
  395. try:
  396. if task.__trace__ is None:
  397. task.__trace__ = build_tracer(task.name, task, **opts)
  398. return task.__trace__(uuid, args, kwargs, request)
  399. except Exception as exc:
  400. return report_internal_error(task, exc)
  401. def _trace_task_ret(name, uuid, request, body, content_type,
  402. content_encoding, loads=loads_message, app=None,
  403. **extra_request):
  404. app = app or current_app._get_current_object()
  405. accept = prepare_accept_content(app.conf.CELERY_ACCEPT_CONTENT)
  406. args, kwargs = loads(body, content_type, content_encoding, accept=accept)
  407. request.update(args=args, kwargs=kwargs, **extra_request)
  408. R, I, T, Rstr = trace_task(app.tasks[name],
  409. uuid, args, kwargs, request, app=app)
  410. return (1, R, T) if I else (0, Rstr, T)
  411. trace_task_ret = _trace_task_ret
  412. def _fast_trace_task_v1(task, uuid, args, kwargs, request={}, _loc=_localized):
  413. # setup_worker_optimizations will point trace_task_ret to here,
  414. # so this is the function used in the worker.
  415. tasks, _ = _loc
  416. R, I, T, Rstr = tasks[task].__trace__(uuid, args, kwargs, request)[0]
  417. # exception instance if error, else result text
  418. return (1, R, T) if I else (0, Rstr, T)
  419. def _fast_trace_task(task, uuid, request, body, content_type,
  420. content_encoding, loads=loads_message, _loc=_localized,
  421. hostname=None, **_):
  422. tasks, accept = _loc
  423. if content_type:
  424. args, kwargs = loads(body, content_type, content_encoding,
  425. accept=accept)
  426. else:
  427. args, kwargs = body
  428. request.update({
  429. 'args': args, 'kwargs': kwargs, 'hostname': hostname,
  430. })
  431. R, I, T, Rstr = tasks[task].__trace__(
  432. uuid, args, kwargs, request,
  433. )
  434. return (1, R, T) if I else (0, Rstr, T)
  435. def report_internal_error(task, exc):
  436. _type, _value, _tb = sys.exc_info()
  437. try:
  438. _value = task.backend.prepare_exception(exc, 'pickle')
  439. exc_info = ExceptionInfo((_type, _value, _tb), internal=True)
  440. warn(RuntimeWarning(
  441. 'Exception raised outside body: {0!r}:\n{1}'.format(
  442. exc, exc_info.traceback)))
  443. return exc_info
  444. finally:
  445. del(_tb)
  446. def setup_worker_optimizations(app):
  447. global trace_task_ret
  448. # make sure custom Task.__call__ methods that calls super
  449. # will not mess up the request/task stack.
  450. _install_stack_protection()
  451. # all new threads start without a current app, so if an app is not
  452. # passed on to the thread it will fall back to the "default app",
  453. # which then could be the wrong app. So for the worker
  454. # we set this to always return our app. This is a hack,
  455. # and means that only a single app can be used for workers
  456. # running in the same process.
  457. app.set_current()
  458. set_default_app(app)
  459. # evaluate all task classes by finalizing the app.
  460. app.finalize()
  461. # set fast shortcut to task registry
  462. _localized[:] = [
  463. app._tasks,
  464. prepare_accept_content(app.conf.CELERY_ACCEPT_CONTENT),
  465. ]
  466. trace_task_ret = _fast_trace_task
  467. from celery.worker import request as request_module
  468. request_module.trace_task_ret = _fast_trace_task
  469. request_module.__optimize__()
  470. def reset_worker_optimizations():
  471. global trace_task_ret
  472. trace_task_ret = _trace_task_ret
  473. try:
  474. delattr(BaseTask, '_stackprotected')
  475. except AttributeError:
  476. pass
  477. try:
  478. BaseTask.__call__ = _patched.pop('BaseTask.__call__')
  479. except KeyError:
  480. pass
  481. from celery.worker import request as request_module
  482. request_module.trace_task_ret = _trace_task_ret
  483. def _install_stack_protection():
  484. # Patches BaseTask.__call__ in the worker to handle the edge case
  485. # where people override it and also call super.
  486. #
  487. # - The worker optimizes away BaseTask.__call__ and instead
  488. # calls task.run directly.
  489. # - so with the addition of current_task and the request stack
  490. # BaseTask.__call__ now pushes to those stacks so that
  491. # they work when tasks are called directly.
  492. #
  493. # The worker only optimizes away __call__ in the case
  494. # where it has not been overridden, so the request/task stack
  495. # will blow if a custom task class defines __call__ and also
  496. # calls super().
  497. if not getattr(BaseTask, '_stackprotected', False):
  498. _patched['BaseTask.__call__'] = orig = BaseTask.__call__
  499. def __protected_call__(self, *args, **kwargs):
  500. stack = self.request_stack
  501. req = stack.top
  502. if req and not req._protected and \
  503. len(stack) == 1 and not req.called_directly:
  504. req._protected = 1
  505. return self.run(*args, **kwargs)
  506. return orig(self, *args, **kwargs)
  507. BaseTask.__call__ = __protected_call__
  508. BaseTask._stackprotected = True