job.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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 django.core.mail import mail_admins
  8. from celery.monitoring import TaskTimerStats
  9. import multiprocessing
  10. import traceback
  11. import socket
  12. import sys
  13. # pep8.py borks on a inline signature separator and
  14. # says "trailing whitespace" ;)
  15. EMAIL_SIGNATURE_SEP = "-- "
  16. TASK_FAIL_EMAIL_BODY = """
  17. Task %%(name)s with id %%(id)s raised exception: %%(exc)s
  18. Task was called with args:%%(args)s kwargs:%%(kwargs)s.
  19. The contents of the full traceback was:
  20. %%(traceback)s
  21. %(EMAIL_SIGNATURE_SEP)s
  22. Just thought I'd let you know!
  23. celeryd at %%(hostname)s.
  24. """ % {"EMAIL_SIGNATURE_SEP": EMAIL_SIGNATURE_SEP}
  25. def jail(task_id, task_name, func, args, kwargs):
  26. """Wraps the task in a jail, which catches all exceptions, and
  27. saves the status and result of the task execution to the task
  28. meta backend.
  29. If the call was successful, it saves the result to the task result
  30. backend, and sets the task status to ``"DONE"``.
  31. If the call results in an exception, it saves the exception as the task
  32. result, and sets the task status to ``"FAILURE"``.
  33. :param task_id: The id of the task.
  34. :param task_name: The name of the task.
  35. :param func: Callable object to execute.
  36. :param args: List of positional args to pass on to the function.
  37. :param kwargs: Keyword arguments mapping to pass on to the function.
  38. :returns: the function return value on success, or
  39. the exception instance on failure.
  40. """
  41. ignore_result = getattr(func, "ignore_result", False)
  42. timer_stat = TaskTimerStats.start(task_id, task_name, args, kwargs)
  43. # See: http://groups.google.com/group/django-users/browse_thread/
  44. # thread/78200863d0c07c6d/38402e76cf3233e8?hl=en&lnk=gst&
  45. # q=multiprocessing#38402e76cf3233e8
  46. from django.db import connection
  47. connection.close()
  48. # Reset cache connection only if using memcached/libmemcached
  49. from django.core import cache
  50. # XXX At Opera we use a custom memcached backend that uses libmemcached
  51. # instead of libmemcache (cmemcache). Should find a better solution for
  52. # this, but for now "memcached" should probably be unique enough of a
  53. # string to not make problems.
  54. cache_backend = cache.settings.CACHE_BACKEND
  55. if hasattr(cache, "parse_backend_uri"):
  56. cache_scheme = cache.parse_backend_uri(cache_backend)[0]
  57. else:
  58. # Django <= 1.0.2
  59. cache_scheme = cache_backend.split(":", 1)[0]
  60. if "memcached" in cache_scheme:
  61. cache.cache.close()
  62. # Backend process cleanup
  63. default_backend.process_cleanup()
  64. try:
  65. result = func(*args, **kwargs)
  66. except (SystemExit, KeyboardInterrupt):
  67. raise
  68. except Exception, exc:
  69. stored_exc = default_backend.mark_as_failure(task_id, exc)
  70. type_, _, tb = sys.exc_info()
  71. retval = ExceptionInfo((type_, stored_exc, tb))
  72. else:
  73. if not ignore_result:
  74. default_backend.mark_as_done(task_id, result)
  75. retval = result
  76. finally:
  77. timer_stat.stop()
  78. return retval
  79. class TaskWrapper(object):
  80. """Class wrapping a task to be run.
  81. :param task_name: see :attr:`task_name`.
  82. :param task_id: see :attr:`task_id`.
  83. :param task_func: see :attr:`task_func`
  84. :param args: see :attr:`args`
  85. :param kwargs: see :attr:`kwargs`.
  86. .. attribute:: task_name
  87. Kind of task. Must be a name registered in the task registry.
  88. .. attribute:: task_id
  89. UUID of the task.
  90. .. attribute:: task_func
  91. The tasks callable object.
  92. .. attribute:: args
  93. List of positional arguments to apply to the task.
  94. .. attribute:: kwargs
  95. Mapping of keyword arguments to apply to the task.
  96. .. attribute:: message
  97. The original message sent. Used for acknowledging the message.
  98. """
  99. success_msg = "Task %(name)s[%(id)s] processed: %(return_value)s"
  100. fail_msg = """
  101. Task %(name)s[%(id)s] raised exception: %(exc)s\n%(traceback)s
  102. """
  103. fail_email_subject = """
  104. [celery@%(hostname)s] Error: Task %(name)s (%(id)s): %(exc)s
  105. """
  106. fail_email_body = TASK_FAIL_EMAIL_BODY
  107. def __init__(self, task_name, task_id, task_func, args, kwargs,
  108. on_ack=None, **opts):
  109. self.task_name = task_name
  110. self.task_id = task_id
  111. self.task_func = task_func
  112. self.args = args
  113. self.kwargs = kwargs
  114. self.logger = kwargs.get("logger")
  115. self.on_ack = on_ack
  116. for opt in ("success_msg", "fail_msg", "fail_email_subject",
  117. "fail_email_body"):
  118. setattr(self, opt, opts.get(opt, getattr(self, opt, None)))
  119. if not self.logger:
  120. self.logger = multiprocessing.get_logger()
  121. def __repr__(self):
  122. return '<%s: {name:"%s", id:"%s", args:"%s", kwargs:"%s"}>' % (
  123. self.__class__.__name__,
  124. self.task_name, self.task_id,
  125. self.args, self.kwargs)
  126. @classmethod
  127. def from_message(cls, message, message_data, logger=None):
  128. """Create a :class:`TaskWrapper` from a task message sent by
  129. :class:`celery.messaging.TaskPublisher`.
  130. :raises UnknownTaskError: if the message does not describe a task,
  131. the message is also rejected.
  132. :returns: :class:`TaskWrapper` instance.
  133. """
  134. task_name = message_data["task"]
  135. task_id = message_data["id"]
  136. args = message_data["args"]
  137. kwargs = message_data["kwargs"]
  138. # Convert any unicode keys in the keyword arguments to ascii.
  139. kwargs = dict((key.encode("utf-8"), value)
  140. for key, value in kwargs.items())
  141. if task_name not in tasks:
  142. raise NotRegistered(task_name)
  143. task_func = tasks[task_name]
  144. return cls(task_name, task_id, task_func, args, kwargs,
  145. on_ack=message.ack, logger=logger)
  146. def extend_with_default_kwargs(self, loglevel, logfile):
  147. """Extend the tasks keyword arguments with standard task arguments.
  148. These are ``logfile``, ``loglevel``, ``task_id`` and ``task_name``.
  149. """
  150. task_func_kwargs = {"logfile": logfile,
  151. "loglevel": loglevel,
  152. "task_id": self.task_id,
  153. "task_name": self.task_name}
  154. task_func_kwargs.update(self.kwargs)
  155. return task_func_kwargs
  156. def execute(self, loglevel=None, logfile=None):
  157. """Execute the task in a :func:`jail` and store return value
  158. and status in the task meta backend.
  159. :keyword loglevel: The loglevel used by the task.
  160. :keyword logfile: The logfile used by the task.
  161. """
  162. task_func_kwargs = self.extend_with_default_kwargs(loglevel, logfile)
  163. # acknowledge task as being processed.
  164. if self.on_ack:
  165. self.on_ack()
  166. return jail(self.task_id, self.task_name, self.task_func,
  167. self.args, task_func_kwargs)
  168. def on_success(self, ret_value, meta):
  169. """The handler used if the task was successfully processed (
  170. without raising an exception)."""
  171. task_id = meta.get("task_id")
  172. task_name = meta.get("task_name")
  173. msg = self.success_msg.strip() % {
  174. "id": task_id,
  175. "name": task_name,
  176. "return_value": ret_value}
  177. self.logger.info(msg)
  178. def on_failure(self, exc_info, meta):
  179. """The handler used if the task raised an exception."""
  180. from celery.conf import SEND_CELERY_TASK_ERROR_EMAILS
  181. task_id = meta.get("task_id")
  182. task_name = meta.get("task_name")
  183. context = {
  184. "hostname": socket.gethostname(),
  185. "id": task_id,
  186. "name": task_name,
  187. "exc": exc_info.exception,
  188. "traceback": exc_info.traceback,
  189. "args": self.args,
  190. "kwargs": self.kwargs,
  191. }
  192. self.logger.error(self.fail_msg.strip() % context)
  193. task_obj = tasks.get(task_name, object)
  194. send_error_email = SEND_CELERY_TASK_ERROR_EMAILS and not \
  195. getattr(task_obj, "disable_error_emails", False)
  196. if send_error_email:
  197. subject = self.fail_email_subject.strip() % context
  198. body = self.fail_email_body.strip() % context
  199. mail_admins(subject, body, fail_silently=True)
  200. def execute_using_pool(self, pool, loglevel=None, logfile=None):
  201. """Like :meth:`execute`, but using the :mod:`multiprocessing` pool.
  202. :param pool: A :class:`multiprocessing.Pool` instance.
  203. :keyword loglevel: The loglevel used by the task.
  204. :keyword logfile: The logfile used by the task.
  205. :returns :class:`multiprocessing.AsyncResult` instance.
  206. """
  207. task_func_kwargs = self.extend_with_default_kwargs(loglevel, logfile)
  208. jail_args = [self.task_id, self.task_name, self.task_func,
  209. self.args, task_func_kwargs]
  210. return pool.apply_async(jail, args=jail_args,
  211. callbacks=[self.on_success], errbacks=[self.on_failure],
  212. on_ack=self.on_ack,
  213. meta={"task_id": self.task_id, "task_name": self.task_name})