job.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. """
  2. Jobs Executable by the Worker Server.
  3. """
  4. from celery.registry import tasks, NotRegistered
  5. from celery.datastructures import ExceptionInfo
  6. from celery.backends import default_backend
  7. from celery.loaders import current_loader
  8. from django.core.mail import mail_admins
  9. from celery.monitoring import TaskTimerStats
  10. from celery.task.base import RetryTaskError
  11. from celery import signals
  12. import multiprocessing
  13. import traceback
  14. import socket
  15. import sys
  16. # pep8.py borks on a inline signature separator and
  17. # says "trailing whitespace" ;)
  18. EMAIL_SIGNATURE_SEP = "-- "
  19. TASK_FAIL_EMAIL_BODY = """
  20. Task %%(name)s with id %%(id)s raised exception: %%(exc)s
  21. Task was called with args:%%(args)s kwargs:%%(kwargs)s.
  22. The contents of the full traceback was:
  23. %%(traceback)s
  24. %(EMAIL_SIGNATURE_SEP)s
  25. Just thought I'd let you know!
  26. celeryd at %%(hostname)s.
  27. """ % {"EMAIL_SIGNATURE_SEP": EMAIL_SIGNATURE_SEP}
  28. def jail(task_id, task_name, func, args, kwargs):
  29. """Wraps the task in a jail, which catches all exceptions, and
  30. saves the status and result of the task execution to the task
  31. meta backend.
  32. If the call was successful, it saves the result to the task result
  33. backend, and sets the task status to ``"DONE"``.
  34. If the call results in an exception, it saves the exception as the task
  35. result, and sets the task status to ``"FAILURE"``.
  36. :param task_id: The id of the task.
  37. :param task_name: The name of the task.
  38. :param func: Callable object to execute.
  39. :param args: List of positional args to pass on to the function.
  40. :param kwargs: Keyword arguments mapping to pass on to the function.
  41. :returns: the function return value on success, or
  42. the exception instance on failure.
  43. """
  44. ignore_result = getattr(func, "ignore_result", False)
  45. timer_stat = TaskTimerStats.start(task_id, task_name, args, kwargs)
  46. # Run task loader init handler.
  47. current_loader.on_task_init(task_id, func)
  48. signals.task_prerun.send(sender=func, task_id=task_id, task=func,
  49. args=args, kwargs=kwargs)
  50. # Backend process cleanup
  51. default_backend.process_cleanup()
  52. try:
  53. result = func(*args, **kwargs)
  54. except (SystemExit, KeyboardInterrupt):
  55. raise
  56. except RetryTaskError, exc:
  57. ### Task is to be retried.
  58. # RetryTaskError stores both a small message describing the retry
  59. # and the original exception.
  60. message, orig_exc = exc.args
  61. default_backend.mark_as_retry(task_id, orig_exc)
  62. # Create a simpler version of the RetryTaskError that stringifies
  63. # the original exception instead of including the exception instance.
  64. # This is for reporting the retry in logs, e-mail etc, while
  65. # guaranteeing pickleability.
  66. expanded_msg = "%s: %s" % (message, str(orig_exc))
  67. type_, _, tb = sys.exc_info()
  68. retval = ExceptionInfo((type_,
  69. type_(expanded_msg, None),
  70. tb))
  71. except Exception, exc:
  72. ### Task ended in failure.
  73. # mark_as_failure returns an exception that is guaranteed to
  74. # be pickleable.
  75. stored_exc = default_backend.mark_as_failure(task_id, exc)
  76. # wrap exception info + traceback and return it to caller.
  77. type_, _, tb = sys.exc_info()
  78. retval = ExceptionInfo((type_, stored_exc, tb))
  79. else:
  80. ### Task executed successfully.
  81. if not ignore_result:
  82. default_backend.mark_as_done(task_id, result)
  83. retval = result
  84. finally:
  85. timer_stat.stop()
  86. signals.task_postrun.send(sender=func, task_id=task_id, task=func,
  87. args=args, kwargs=kwargs, retval=retval)
  88. return retval
  89. class TaskWrapper(object):
  90. """Class wrapping a task to be run.
  91. :param task_name: see :attr:`task_name`.
  92. :param task_id: see :attr:`task_id`.
  93. :param task_func: see :attr:`task_func`
  94. :param args: see :attr:`args`
  95. :param kwargs: see :attr:`kwargs`.
  96. .. attribute:: task_name
  97. Kind of task. Must be a name registered in the task registry.
  98. .. attribute:: task_id
  99. UUID of the task.
  100. .. attribute:: task_func
  101. The tasks callable object.
  102. .. attribute:: args
  103. List of positional arguments to apply to the task.
  104. .. attribute:: kwargs
  105. Mapping of keyword arguments to apply to the task.
  106. .. attribute:: message
  107. The original message sent. Used for acknowledging the message.
  108. """
  109. success_msg = "Task %(name)s[%(id)s] processed: %(return_value)s"
  110. fail_msg = """
  111. Task %(name)s[%(id)s] raised exception: %(exc)s\n%(traceback)s
  112. """
  113. fail_email_subject = """
  114. [celery@%(hostname)s] Error: Task %(name)s (%(id)s): %(exc)s
  115. """
  116. fail_email_body = TASK_FAIL_EMAIL_BODY
  117. def __init__(self, task_name, task_id, task_func, args, kwargs,
  118. on_ack=None, retries=0, **opts):
  119. self.task_name = task_name
  120. self.task_id = task_id
  121. self.task_func = task_func
  122. self.retries = retries
  123. self.args = args
  124. self.kwargs = kwargs
  125. self.logger = kwargs.get("logger")
  126. self.on_ack = on_ack
  127. for opt in ("success_msg", "fail_msg", "fail_email_subject",
  128. "fail_email_body"):
  129. setattr(self, opt, opts.get(opt, getattr(self, opt, None)))
  130. if not self.logger:
  131. self.logger = multiprocessing.get_logger()
  132. def __repr__(self):
  133. return '<%s: {name:"%s", id:"%s", args:"%s", kwargs:"%s"}>' % (
  134. self.__class__.__name__,
  135. self.task_name, self.task_id,
  136. self.args, self.kwargs)
  137. @classmethod
  138. def from_message(cls, message, message_data, logger=None):
  139. """Create a :class:`TaskWrapper` from a task message sent by
  140. :class:`celery.messaging.TaskPublisher`.
  141. :raises UnknownTaskError: if the message does not describe a task,
  142. the message is also rejected.
  143. :returns: :class:`TaskWrapper` instance.
  144. """
  145. task_name = message_data["task"]
  146. task_id = message_data["id"]
  147. args = message_data["args"]
  148. kwargs = message_data["kwargs"]
  149. retries = message_data.get("retries", 0)
  150. # Convert any unicode keys in the keyword arguments to ascii.
  151. kwargs = dict((key.encode("utf-8"), value)
  152. for key, value in kwargs.items())
  153. if task_name not in tasks:
  154. raise NotRegistered(task_name)
  155. task_func = tasks[task_name]
  156. return cls(task_name, task_id, task_func, args, kwargs,
  157. retries=retries, on_ack=message.ack, logger=logger)
  158. def extend_with_default_kwargs(self, loglevel, logfile):
  159. """Extend the tasks keyword arguments with standard task arguments.
  160. These are ``logfile``, ``loglevel``, ``task_id`` and ``task_name``.
  161. """
  162. kwargs = dict(self.kwargs)
  163. task_func_kwargs = {"logfile": logfile,
  164. "loglevel": loglevel,
  165. "task_id": self.task_id,
  166. "task_name": self.task_name,
  167. "task_retries": self.retries}
  168. kwargs.update(task_func_kwargs)
  169. return kwargs
  170. def execute(self, loglevel=None, logfile=None):
  171. """Execute the task in a :func:`jail` and store return value
  172. and status in the task meta backend.
  173. :keyword loglevel: The loglevel used by the task.
  174. :keyword logfile: The logfile used by the task.
  175. """
  176. task_func_kwargs = self.extend_with_default_kwargs(loglevel, logfile)
  177. # acknowledge task as being processed.
  178. if self.on_ack:
  179. self.on_ack()
  180. return jail(self.task_id, self.task_name, self.task_func,
  181. self.args, task_func_kwargs)
  182. def on_success(self, ret_value, meta):
  183. """The handler used if the task was successfully processed (
  184. without raising an exception)."""
  185. task_id = meta.get("task_id")
  186. task_name = meta.get("task_name")
  187. msg = self.success_msg.strip() % {
  188. "id": task_id,
  189. "name": task_name,
  190. "return_value": ret_value}
  191. self.logger.info(msg)
  192. def on_failure(self, exc_info, meta):
  193. """The handler used if the task raised an exception."""
  194. from celery.conf import SEND_CELERY_TASK_ERROR_EMAILS
  195. task_id = meta.get("task_id")
  196. task_name = meta.get("task_name")
  197. context = {
  198. "hostname": socket.gethostname(),
  199. "id": task_id,
  200. "name": task_name,
  201. "exc": exc_info.exception,
  202. "traceback": exc_info.traceback,
  203. "args": self.args,
  204. "kwargs": self.kwargs,
  205. }
  206. self.logger.error(self.fail_msg.strip() % context)
  207. task_obj = tasks.get(task_name, object)
  208. send_error_email = SEND_CELERY_TASK_ERROR_EMAILS and not \
  209. getattr(task_obj, "disable_error_emails", False)
  210. if send_error_email:
  211. subject = self.fail_email_subject.strip() % context
  212. body = self.fail_email_body.strip() % context
  213. mail_admins(subject, body, fail_silently=True)
  214. def execute_using_pool(self, pool, loglevel=None, logfile=None):
  215. """Like :meth:`execute`, but using the :mod:`multiprocessing` pool.
  216. :param pool: A :class:`multiprocessing.Pool` instance.
  217. :keyword loglevel: The loglevel used by the task.
  218. :keyword logfile: The logfile used by the task.
  219. :returns :class:`multiprocessing.AsyncResult` instance.
  220. """
  221. task_func_kwargs = self.extend_with_default_kwargs(loglevel, logfile)
  222. jail_args = [self.task_id, self.task_name, self.task_func,
  223. self.args, task_func_kwargs]
  224. return pool.apply_async(jail, args=jail_args,
  225. callbacks=[self.on_success], errbacks=[self.on_failure],
  226. on_ack=self.on_ack,
  227. meta={"task_id": self.task_id, "task_name": self.task_name})