trace.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  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. task.backend.mark_as_failure(
  158. req.id, exc, einfo.traceback, req, store_errors,
  159. )
  160. task.on_failure(exc, req.id, req.args, req.kwargs, einfo)
  161. signals.task_failure.send(sender=task, task_id=req.id,
  162. exception=exc, args=req.args,
  163. kwargs=req.kwargs,
  164. traceback=tb,
  165. einfo=einfo)
  166. self._log_error(task, req, einfo)
  167. return einfo
  168. finally:
  169. del(tb)
  170. def _log_error(self, task, req, einfo):
  171. eobj = einfo.exception = get_pickled_exception(einfo.exception)
  172. exception, traceback, exc_info, sargs, skwargs = (
  173. safe_repr(eobj),
  174. safe_str(einfo.traceback),
  175. einfo.exc_info,
  176. safe_repr(req.args),
  177. safe_repr(req.kwargs),
  178. )
  179. policy = get_log_policy(task, einfo, eobj)
  180. context = {
  181. 'hostname': req.hostname,
  182. 'id': req.id,
  183. 'name': task.name,
  184. 'exc': exception,
  185. 'traceback': traceback,
  186. 'args': sargs,
  187. 'kwargs': skwargs,
  188. 'description': policy.description,
  189. 'internal': einfo.internal,
  190. }
  191. logger.log(policy.severity, policy.format.strip(), context,
  192. exc_info=exc_info if policy.traceback else None,
  193. extra={'data': context})
  194. if policy.mail:
  195. task.send_error_email(context, einfo.exception)
  196. def build_tracer(name, task, loader=None, hostname=None, store_errors=True,
  197. Info=TraceInfo, eager=False, propagate=False, app=None,
  198. monotonic=monotonic, truncate=truncate,
  199. trace_ok_t=trace_ok_t, IGNORE_STATES=IGNORE_STATES):
  200. """Return a function that traces task execution; catches all
  201. exceptions and updates result backend with the state and result
  202. If the call was successful, it saves the result to the task result
  203. backend, and sets the task status to `"SUCCESS"`.
  204. If the call raises :exc:`~@Retry`, it extracts
  205. the original exception, uses that as the result and sets the task state
  206. to `"RETRY"`.
  207. If the call results in an exception, it saves the exception as the task
  208. result, and sets the task state to `"FAILURE"`.
  209. Return a function that takes the following arguments:
  210. :param uuid: The id of the task.
  211. :param args: List of positional args to pass on to the function.
  212. :param kwargs: Keyword arguments mapping to pass on to the function.
  213. :keyword request: Request dict.
  214. """
  215. # If the task doesn't define a custom __call__ method
  216. # we optimize it away by simply calling the run method directly,
  217. # saving the extra method call and a line less in the stack trace.
  218. fun = task if task_has_custom(task, '__call__') else task.run
  219. loader = loader or app.loader
  220. backend = task.backend
  221. ignore_result = task.ignore_result
  222. track_started = task.track_started
  223. track_started = not eager and (task.track_started and not ignore_result)
  224. publish_result = not eager and not ignore_result
  225. hostname = hostname or socket.gethostname()
  226. loader_task_init = loader.on_task_init
  227. loader_cleanup = loader.on_process_cleanup
  228. task_on_success = None
  229. task_after_return = None
  230. if task_has_custom(task, 'on_success'):
  231. task_on_success = task.on_success
  232. if task_has_custom(task, 'after_return'):
  233. task_after_return = task.after_return
  234. store_result = backend.store_result
  235. mark_as_done = backend.mark_as_done
  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. _does_info = logger.isEnabledFor(logging.INFO)
  244. prerun_receivers = signals.task_prerun.receivers
  245. postrun_receivers = signals.task_postrun.receivers
  246. success_receivers = signals.task_success.receivers
  247. from celery import canvas
  248. signature = canvas.maybe_signature # maybe_ does not clone if already
  249. def on_error(request, exc, uuid, state=FAILURE, call_errbacks=True):
  250. if propagate:
  251. raise
  252. I = Info(state, exc)
  253. R = I.handle_error_state(task, request, eager=eager)
  254. if call_errbacks:
  255. root_id = request.root_id or uuid
  256. group(
  257. [signature(errback, app=app)
  258. for errback in request.errbacks or []], app=app,
  259. ).apply_async((uuid,), parent_id=uuid, root_id=root_id)
  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. root_id = task_request.root_id or uuid
  285. push_request(task_request)
  286. try:
  287. # -*- PRE -*-
  288. if prerun_receivers:
  289. send_prerun(sender=task, task_id=uuid, task=task,
  290. args=args, kwargs=kwargs)
  291. loader_task_init(uuid, task)
  292. if track_started:
  293. store_result(
  294. uuid, {'pid': pid, 'hostname': hostname}, STARTED,
  295. request=task_request,
  296. )
  297. # -*- TRACE -*-
  298. try:
  299. R = retval = fun(*args, **kwargs)
  300. state = SUCCESS
  301. except Reject as exc:
  302. I, R = Info(REJECTED, exc), ExceptionInfo(internal=True)
  303. state, retval = I.state, I.retval
  304. I.handle_reject(task, task_request)
  305. except Ignore as exc:
  306. I, R = Info(IGNORED, exc), ExceptionInfo(internal=True)
  307. state, retval = I.state, I.retval
  308. I.handle_ignore(task, task_request)
  309. except Retry as exc:
  310. I, R, state, retval = on_error(
  311. task_request, exc, uuid, RETRY, call_errbacks=False)
  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(
  336. (retval,),
  337. parent_id=uuid, root_id=root_id,
  338. )
  339. if sigs:
  340. group(sigs).apply_async(
  341. (retval,),
  342. parent_id=uuid, root_id=root_id,
  343. )
  344. else:
  345. signature(callbacks[0], app=app).apply_async(
  346. (retval,), parent_id=uuid, root_id=root_id,
  347. )
  348. # execute first task in chain
  349. chain = task_request.chain
  350. if chain:
  351. signature(chain.pop(), app=app).apply_async(
  352. (retval,), chain=chain,
  353. parent_id=uuid, root_id=root_id,
  354. )
  355. mark_as_done(
  356. uuid, retval, task_request, publish_result,
  357. )
  358. except EncodeError as exc:
  359. I, R, state, retval = on_error(task_request, exc, uuid)
  360. else:
  361. if task_on_success:
  362. task_on_success(retval, uuid, args, kwargs)
  363. if success_receivers:
  364. send_success(sender=task, result=retval)
  365. if _does_info:
  366. T = monotonic() - time_start
  367. Rstr = truncate(safe_repr(R), 256)
  368. info(LOG_SUCCESS, {
  369. 'id': uuid, 'name': name,
  370. 'return_value': Rstr, 'runtime': T,
  371. })
  372. # -* POST *-
  373. if state not in IGNORE_STATES:
  374. if task_after_return:
  375. task_after_return(
  376. state, retval, uuid, args, kwargs, None,
  377. )
  378. finally:
  379. try:
  380. if postrun_receivers:
  381. send_postrun(sender=task, task_id=uuid, task=task,
  382. args=args, kwargs=kwargs,
  383. retval=retval, state=state)
  384. finally:
  385. pop_task()
  386. pop_request()
  387. if not eager:
  388. try:
  389. backend_cleanup()
  390. loader_cleanup()
  391. except (KeyboardInterrupt, SystemExit, MemoryError):
  392. raise
  393. except Exception as exc:
  394. logger.error('Process cleanup failed: %r', exc,
  395. exc_info=True)
  396. except MemoryError:
  397. raise
  398. except Exception as exc:
  399. if eager:
  400. raise
  401. R = report_internal_error(task, exc)
  402. if task_request is not None:
  403. I, _, _, _ = on_error(task_request, exc, uuid)
  404. return trace_ok_t(R, I, T, Rstr)
  405. return trace_task
  406. def trace_task(task, uuid, args, kwargs, request={}, **opts):
  407. try:
  408. if task.__trace__ is None:
  409. task.__trace__ = build_tracer(task.name, task, **opts)
  410. return task.__trace__(uuid, args, kwargs, request)
  411. except Exception as exc:
  412. return trace_ok_t(report_internal_error(task, exc), None, 0.0, None)
  413. def _trace_task_ret(name, uuid, request, body, content_type,
  414. content_encoding, loads=loads_message, app=None,
  415. **extra_request):
  416. app = app or current_app._get_current_object()
  417. embed = None
  418. if content_type:
  419. accept = prepare_accept_content(app.conf.accept_content)
  420. args, kwargs, embed = loads(
  421. body, content_type, content_encoding, accept=accept,
  422. )
  423. else:
  424. args, kwargs = body
  425. hostname = socket.gethostname()
  426. request.update({
  427. 'args': args, 'kwargs': kwargs,
  428. 'hostname': hostname, 'is_eager': False,
  429. }, **embed or {})
  430. R, I, T, Rstr = trace_task(app.tasks[name],
  431. uuid, args, kwargs, request, app=app)
  432. return (1, R, T) if I else (0, Rstr, T)
  433. trace_task_ret = _trace_task_ret
  434. def _fast_trace_task(task, uuid, request, body, content_type,
  435. content_encoding, loads=loads_message, _loc=_localized,
  436. hostname=None, **_):
  437. embed = None
  438. tasks, accept, hostname = _loc
  439. if content_type:
  440. args, kwargs, embed = loads(
  441. body, content_type, content_encoding, accept=accept,
  442. )
  443. else:
  444. args, kwargs = body
  445. request.update({
  446. 'args': args, 'kwargs': kwargs,
  447. 'hostname': hostname, 'is_eager': False,
  448. }, **embed or {})
  449. R, I, T, Rstr = tasks[task].__trace__(
  450. uuid, args, kwargs, request,
  451. )
  452. return (1, R, T) if I else (0, Rstr, T)
  453. def report_internal_error(task, exc):
  454. _type, _value, _tb = sys.exc_info()
  455. try:
  456. _value = task.backend.prepare_exception(exc, 'pickle')
  457. exc_info = ExceptionInfo((_type, _value, _tb), internal=True)
  458. warn(RuntimeWarning(
  459. 'Exception raised outside body: {0!r}:\n{1}'.format(
  460. exc, exc_info.traceback)))
  461. return exc_info
  462. finally:
  463. del(_tb)
  464. def setup_worker_optimizations(app, hostname=None):
  465. global trace_task_ret
  466. hostname = hostname or socket.gethostname()
  467. # make sure custom Task.__call__ methods that calls super
  468. # will not mess up the request/task stack.
  469. _install_stack_protection()
  470. # all new threads start without a current app, so if an app is not
  471. # passed on to the thread it will fall back to the "default app",
  472. # which then could be the wrong app. So for the worker
  473. # we set this to always return our app. This is a hack,
  474. # and means that only a single app can be used for workers
  475. # running in the same process.
  476. app.set_current()
  477. set_default_app(app)
  478. # evaluate all task classes by finalizing the app.
  479. app.finalize()
  480. # set fast shortcut to task registry
  481. _localized[:] = [
  482. app._tasks,
  483. prepare_accept_content(app.conf.accept_content),
  484. hostname,
  485. ]
  486. trace_task_ret = _fast_trace_task
  487. from celery.worker import request as request_module
  488. request_module.trace_task_ret = _fast_trace_task
  489. request_module.__optimize__()
  490. def reset_worker_optimizations():
  491. global trace_task_ret
  492. trace_task_ret = _trace_task_ret
  493. try:
  494. delattr(BaseTask, '_stackprotected')
  495. except AttributeError:
  496. pass
  497. try:
  498. BaseTask.__call__ = _patched.pop('BaseTask.__call__')
  499. except KeyError:
  500. pass
  501. from celery.worker import request as request_module
  502. request_module.trace_task_ret = _trace_task_ret
  503. def _install_stack_protection():
  504. # Patches BaseTask.__call__ in the worker to handle the edge case
  505. # where people override it and also call super.
  506. #
  507. # - The worker optimizes away BaseTask.__call__ and instead
  508. # calls task.run directly.
  509. # - so with the addition of current_task and the request stack
  510. # BaseTask.__call__ now pushes to those stacks so that
  511. # they work when tasks are called directly.
  512. #
  513. # The worker only optimizes away __call__ in the case
  514. # where it has not been overridden, so the request/task stack
  515. # will blow if a custom task class defines __call__ and also
  516. # calls super().
  517. if not getattr(BaseTask, '_stackprotected', False):
  518. _patched['BaseTask.__call__'] = orig = BaseTask.__call__
  519. def __protected_call__(self, *args, **kwargs):
  520. stack = self.request_stack
  521. req = stack.top
  522. if req and not req._protected and \
  523. len(stack) == 1 and not req.called_directly:
  524. req._protected = 1
  525. return self.run(*args, **kwargs)
  526. return orig(self, *args, **kwargs)
  527. BaseTask.__call__ = __protected_call__
  528. BaseTask._stackprotected = True