trace.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  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, req, 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, req, store_errors=store_errors)
  123. def handle_reject(self, task, req, **kwargs):
  124. self._log_error(task, req, ExceptionInfo())
  125. def handle_ignore(self, task, req, **kwargs):
  126. self._log_error(task, req, ExceptionInfo())
  127. def handle_retry(self, task, req, 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. type_, _, tb = sys.exc_info()
  132. try:
  133. reason = self.retval
  134. einfo = ExceptionInfo((type_, reason, tb))
  135. if store_errors:
  136. task.backend.mark_as_retry(
  137. req.id, reason.exc, einfo.traceback, request=req,
  138. )
  139. task.on_retry(reason.exc, req.id, req.args, req.kwargs, einfo)
  140. signals.task_retry.send(sender=task, request=req,
  141. reason=reason, einfo=einfo)
  142. info(LOG_RETRY, {
  143. 'id': req.id, 'name': task.name,
  144. 'exc': safe_repr(reason.exc),
  145. })
  146. return einfo
  147. finally:
  148. del(tb)
  149. def handle_failure(self, task, req, store_errors=True):
  150. """Handle exception."""
  151. type_, _, tb = sys.exc_info()
  152. try:
  153. exc = self.retval
  154. einfo = ExceptionInfo()
  155. einfo.exception = get_pickleable_exception(einfo.exception)
  156. einfo.type = get_pickleable_etype(einfo.type)
  157. if store_errors:
  158. task.backend.mark_as_failure(
  159. req.id, exc, einfo.traceback, request=req,
  160. )
  161. task.on_failure(exc, req.id, req.args, req.kwargs, einfo)
  162. signals.task_failure.send(sender=task, task_id=req.id,
  163. exception=exc, args=req.args,
  164. kwargs=req.kwargs,
  165. traceback=tb,
  166. einfo=einfo)
  167. self._log_error(task, req, einfo)
  168. return einfo
  169. finally:
  170. del(tb)
  171. def _log_error(self, task, req, einfo):
  172. eobj = einfo.exception = get_pickled_exception(einfo.exception)
  173. exception, traceback, exc_info, sargs, skwargs = (
  174. safe_repr(eobj),
  175. safe_str(einfo.traceback),
  176. einfo.exc_info,
  177. safe_repr(req.args),
  178. safe_repr(req.kwargs),
  179. )
  180. policy = get_log_policy(task, einfo, eobj)
  181. context = {
  182. 'hostname': req.hostname,
  183. 'id': req.id,
  184. 'name': task.name,
  185. 'exc': exception,
  186. 'traceback': traceback,
  187. 'args': sargs,
  188. 'kwargs': skwargs,
  189. 'description': policy.description,
  190. 'internal': einfo.internal,
  191. }
  192. logger.log(policy.severity, policy.format.strip(), context,
  193. exc_info=exc_info if policy.traceback else None,
  194. extra={'data': context})
  195. if policy.mail:
  196. task.send_error_email(context, einfo.exception)
  197. def build_tracer(name, task, loader=None, hostname=None, store_errors=True,
  198. Info=TraceInfo, eager=False, propagate=False, app=None,
  199. monotonic=monotonic, truncate=truncate,
  200. trace_ok_t=trace_ok_t, IGNORE_STATES=IGNORE_STATES):
  201. """Return a function that traces task execution; catches all
  202. exceptions and updates result backend with the state and result
  203. If the call was successful, it saves the result to the task result
  204. backend, and sets the task status to `"SUCCESS"`.
  205. If the call raises :exc:`~@Retry`, it extracts
  206. the original exception, uses that as the result and sets the task state
  207. to `"RETRY"`.
  208. If the call results in an exception, it saves the exception as the task
  209. result, and sets the task state to `"FAILURE"`.
  210. Return a function that takes the following arguments:
  211. :param uuid: The id of the task.
  212. :param args: List of positional args to pass on to the function.
  213. :param kwargs: Keyword arguments mapping to pass on to the function.
  214. :keyword request: Request dict.
  215. """
  216. # If the task doesn't define a custom __call__ method
  217. # we optimize it away by simply calling the run method directly,
  218. # saving the extra method call and a line less in the stack trace.
  219. fun = task if task_has_custom(task, '__call__') else task.run
  220. loader = loader or app.loader
  221. backend = task.backend
  222. ignore_result = task.ignore_result
  223. track_started = task.track_started
  224. track_started = not eager and (task.track_started and not ignore_result)
  225. publish_result = not eager and not ignore_result
  226. hostname = hostname or socket.gethostname()
  227. loader_task_init = loader.on_task_init
  228. loader_cleanup = loader.on_process_cleanup
  229. task_on_success = None
  230. task_after_return = None
  231. if task_has_custom(task, 'on_success'):
  232. task_on_success = task.on_success
  233. if task_has_custom(task, 'after_return'):
  234. task_after_return = task.after_return
  235. store_result = backend.store_result
  236. backend_cleanup = backend.process_cleanup
  237. pid = os.getpid()
  238. request_stack = task.request_stack
  239. push_request = request_stack.push
  240. pop_request = request_stack.pop
  241. push_task = _task_stack.push
  242. pop_task = _task_stack.pop
  243. on_chord_part_return = backend.on_chord_part_return
  244. _does_info = logger.isEnabledFor(logging.INFO)
  245. prerun_receivers = signals.task_prerun.receivers
  246. postrun_receivers = signals.task_postrun.receivers
  247. success_receivers = signals.task_success.receivers
  248. from celery import canvas
  249. signature = canvas.maybe_signature # maybe_ does not clone if already
  250. def on_error(request, exc, uuid, state=FAILURE, call_errbacks=True):
  251. if propagate:
  252. raise
  253. I = Info(state, exc)
  254. R = I.handle_error_state(task, request, eager=eager)
  255. if call_errbacks:
  256. group(
  257. [signature(errback, app=app)
  258. for errback in request.errbacks or []], app=app,
  259. ).apply_async((uuid, ))
  260. return I, R, I.state, I.retval
  261. def trace_task(uuid, args, kwargs, request=None):
  262. # R - is the possibly prepared return value.
  263. # I - is the Info object.
  264. # T - runtime
  265. # Rstr - textual representation of return value
  266. # retval - is the always unmodified return value.
  267. # state - is the resulting task state.
  268. # This function is very long because we have unrolled all the calls
  269. # for performance reasons, and because the function is so long
  270. # we want the main variables (I, and R) to stand out visually from the
  271. # the rest of the variables, so breaking PEP8 is worth it ;)
  272. R = I = T = Rstr = retval = state = None
  273. task_request = None
  274. time_start = monotonic()
  275. try:
  276. try:
  277. kwargs.items
  278. except AttributeError:
  279. raise InvalidTaskError(
  280. 'Task keyword arguments is not a mapping')
  281. push_task(task)
  282. task_request = Context(request or {}, args=args,
  283. called_directly=False, kwargs=kwargs)
  284. push_request(task_request)
  285. try:
  286. # -*- PRE -*-
  287. if prerun_receivers:
  288. send_prerun(sender=task, task_id=uuid, task=task,
  289. args=args, kwargs=kwargs)
  290. loader_task_init(uuid, task)
  291. if track_started:
  292. store_result(
  293. uuid, {'pid': pid, 'hostname': hostname}, STARTED,
  294. request=task_request,
  295. )
  296. # -*- TRACE -*-
  297. try:
  298. R = retval = fun(*args, **kwargs)
  299. state = SUCCESS
  300. except Reject as exc:
  301. I, R = Info(REJECTED, exc), ExceptionInfo(internal=True)
  302. state, retval = I.state, I.retval
  303. I.handle_reject(task, task_request)
  304. except Ignore as exc:
  305. I, R = Info(IGNORED, exc), ExceptionInfo(internal=True)
  306. state, retval = I.state, I.retval
  307. I.handle_ignore(task, task_request)
  308. except Retry as exc:
  309. I, R, state, retval = on_error(
  310. task_request, exc, uuid, RETRY, call_errbacks=False,
  311. )
  312. except Exception as exc:
  313. I, R, state, retval = on_error(task_request, exc, uuid)
  314. except BaseException as exc:
  315. raise
  316. else:
  317. try:
  318. # callback tasks must be applied before the result is
  319. # stored, so that result.children is populated.
  320. # groups are called inline and will store trail
  321. # separately, so need to call them separately
  322. # so that the trail's not added multiple times :(
  323. # (Issue #1936)
  324. callbacks = task.request.callbacks
  325. if callbacks:
  326. if len(task.request.callbacks) > 1:
  327. sigs, groups = [], []
  328. for sig in callbacks:
  329. sig = signature(sig, app=app)
  330. if isinstance(sig, group):
  331. groups.append(sig)
  332. else:
  333. sigs.append(sig)
  334. for group_ in groups:
  335. group.apply_async((retval, ))
  336. if sigs:
  337. group(sigs).apply_async(retval, )
  338. else:
  339. signature(callbacks[0], app=app).delay(retval)
  340. if publish_result:
  341. store_result(
  342. uuid, retval, SUCCESS, request=task_request,
  343. )
  344. except EncodeError as exc:
  345. I, R, state, retval = on_error(task_request, exc, uuid)
  346. else:
  347. if task_on_success:
  348. task_on_success(retval, uuid, args, kwargs)
  349. if success_receivers:
  350. send_success(sender=task, result=retval)
  351. if _does_info:
  352. T = monotonic() - time_start
  353. Rstr = truncate(safe_repr(R), 256)
  354. info(LOG_SUCCESS, {
  355. 'id': uuid, 'name': name,
  356. 'return_value': Rstr, 'runtime': T,
  357. })
  358. # -* POST *-
  359. if state not in IGNORE_STATES:
  360. if task_request.chord:
  361. on_chord_part_return(task, state, R)
  362. if task_after_return:
  363. task_after_return(
  364. state, retval, uuid, args, kwargs, None,
  365. )
  366. finally:
  367. try:
  368. if postrun_receivers:
  369. send_postrun(sender=task, task_id=uuid, task=task,
  370. args=args, kwargs=kwargs,
  371. retval=retval, state=state)
  372. finally:
  373. pop_task()
  374. pop_request()
  375. if not eager:
  376. try:
  377. backend_cleanup()
  378. loader_cleanup()
  379. except (KeyboardInterrupt, SystemExit, MemoryError):
  380. raise
  381. except Exception as exc:
  382. logger.error('Process cleanup failed: %r', exc,
  383. exc_info=True)
  384. except MemoryError:
  385. raise
  386. except Exception as exc:
  387. if eager:
  388. raise
  389. R = report_internal_error(task, exc)
  390. if task_request is not None:
  391. I, _, _, _ = on_error(task_request, exc, uuid)
  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 trace_ok_t(report_internal_error(task, exc), None, 0.0, None)
  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. embed = None
  406. if content_type:
  407. accept = prepare_accept_content(app.conf.CELERY_ACCEPT_CONTENT)
  408. args, kwargs, embed = loads(
  409. body, content_type, content_encoding, accept=accept,
  410. )
  411. else:
  412. args, kwargs = body
  413. hostname = socket.gethostname()
  414. request.update({
  415. 'args': args, 'kwargs': kwargs,
  416. 'hostname': hostname, 'is_eager': False,
  417. }, **embed or {})
  418. R, I, T, Rstr = trace_task(app.tasks[name],
  419. uuid, args, kwargs, request, app=app)
  420. return (1, R, T) if I else (0, Rstr, T)
  421. trace_task_ret = _trace_task_ret
  422. def _fast_trace_task(task, uuid, request, body, content_type,
  423. content_encoding, loads=loads_message, _loc=_localized,
  424. hostname=None, **_):
  425. embed = None
  426. tasks, accept, hostname = _loc
  427. if content_type:
  428. args, kwargs, embed = loads(
  429. body, content_type, content_encoding, accept=accept,
  430. )
  431. else:
  432. args, kwargs = body
  433. request.update({
  434. 'args': args, 'kwargs': kwargs,
  435. 'hostname': hostname, 'is_eager': False,
  436. }, **embed or {})
  437. R, I, T, Rstr = tasks[task].__trace__(
  438. uuid, args, kwargs, request,
  439. )
  440. return (1, R, T) if I else (0, Rstr, T)
  441. def report_internal_error(task, exc):
  442. _type, _value, _tb = sys.exc_info()
  443. try:
  444. _value = task.backend.prepare_exception(exc, 'pickle')
  445. exc_info = ExceptionInfo((_type, _value, _tb), internal=True)
  446. warn(RuntimeWarning(
  447. 'Exception raised outside body: {0!r}:\n{1}'.format(
  448. exc, exc_info.traceback)))
  449. return exc_info
  450. finally:
  451. del(_tb)
  452. def setup_worker_optimizations(app, hostname=None):
  453. global trace_task_ret
  454. hostname = hostname or socket.gethostname()
  455. # make sure custom Task.__call__ methods that calls super
  456. # will not mess up the request/task stack.
  457. _install_stack_protection()
  458. # all new threads start without a current app, so if an app is not
  459. # passed on to the thread it will fall back to the "default app",
  460. # which then could be the wrong app. So for the worker
  461. # we set this to always return our app. This is a hack,
  462. # and means that only a single app can be used for workers
  463. # running in the same process.
  464. app.set_current()
  465. set_default_app(app)
  466. # evaluate all task classes by finalizing the app.
  467. app.finalize()
  468. # set fast shortcut to task registry
  469. _localized[:] = [
  470. app._tasks,
  471. prepare_accept_content(app.conf.CELERY_ACCEPT_CONTENT),
  472. hostname,
  473. ]
  474. trace_task_ret = _fast_trace_task
  475. from celery.worker import request as request_module
  476. request_module.trace_task_ret = _fast_trace_task
  477. request_module.__optimize__()
  478. def reset_worker_optimizations():
  479. global trace_task_ret
  480. trace_task_ret = _trace_task_ret
  481. try:
  482. delattr(BaseTask, '_stackprotected')
  483. except AttributeError:
  484. pass
  485. try:
  486. BaseTask.__call__ = _patched.pop('BaseTask.__call__')
  487. except KeyError:
  488. pass
  489. from celery.worker import request as request_module
  490. request_module.trace_task_ret = _trace_task_ret
  491. def _install_stack_protection():
  492. # Patches BaseTask.__call__ in the worker to handle the edge case
  493. # where people override it and also call super.
  494. #
  495. # - The worker optimizes away BaseTask.__call__ and instead
  496. # calls task.run directly.
  497. # - so with the addition of current_task and the request stack
  498. # BaseTask.__call__ now pushes to those stacks so that
  499. # they work when tasks are called directly.
  500. #
  501. # The worker only optimizes away __call__ in the case
  502. # where it has not been overridden, so the request/task stack
  503. # will blow if a custom task class defines __call__ and also
  504. # calls super().
  505. if not getattr(BaseTask, '_stackprotected', False):
  506. _patched['BaseTask.__call__'] = orig = BaseTask.__call__
  507. def __protected_call__(self, *args, **kwargs):
  508. stack = self.request_stack
  509. req = stack.top
  510. if req and not req._protected and \
  511. len(stack) == 1 and not req.called_directly:
  512. req._protected = 1
  513. return self.run(*args, **kwargs)
  514. return orig(self, *args, **kwargs)
  515. BaseTask.__call__ = __protected_call__
  516. BaseTask._stackprotected = True