worker.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. """celery.worker"""
  2. from carrot.connection import DjangoAMQPConnection
  3. from celery.messaging import TaskConsumer
  4. from celery.loaders import current_loader
  5. from celery.conf import DAEMON_CONCURRENCY, DAEMON_LOG_FILE
  6. from celery.conf import SEND_CELERY_TASK_ERROR_EMAILS
  7. from celery.log import setup_logger
  8. from celery.registry import tasks
  9. from celery.pool import TaskPool
  10. from celery.datastructures import ExceptionInfo
  11. from celery.backends import default_backend, default_periodic_status_backend
  12. from celery.timer import EventTimer
  13. from django.core.mail import mail_admins
  14. from celery.monitoring import TaskTimerStats
  15. import multiprocessing
  16. import traceback
  17. import threading
  18. import logging
  19. import signal
  20. import socket
  21. import time
  22. import sys
  23. # pep8.py borks on a inline signature separator and
  24. # says "trailing whitespace" ;)
  25. EMAIL_SIGNATURE_SEP = "-- "
  26. TASK_FAIL_EMAIL_BODY = """
  27. Task %%(name)s with id %%(id)s raised exception: %%(exc)s
  28. The contents of the full traceback was:
  29. %%(traceback)s
  30. %(EMAIL_SIGNATURE_SEP)s
  31. Just thought I'd let you know!
  32. celeryd at %%(hostname)s.
  33. """ % {"EMAIL_SIGNATURE_SEP": EMAIL_SIGNATURE_SEP}
  34. class UnknownTask(Exception):
  35. """Got an unknown task in the queue. The message is requeued and
  36. ignored."""
  37. def jail(task_id, task_name, func, args, kwargs):
  38. """Wraps the task in a jail, which catches all exceptions, and
  39. saves the status and result of the task execution to the task
  40. meta backend.
  41. If the call was successful, it saves the result to the task result
  42. backend, and sets the task status to ``"DONE"``.
  43. If the call results in an exception, it saves the exception as the task
  44. result, and sets the task status to ``"FAILURE"``.
  45. :param task_id: The id of the task.
  46. :param task_name: The name of the task.
  47. :param func: Callable object to execute.
  48. :param args: List of positional args to pass on to the function.
  49. :param kwargs: Keyword arguments mapping to pass on to the function.
  50. :returns: the function return value on success, or
  51. the exception instance on failure.
  52. """
  53. ignore_result = getattr(func, "ignore_result", False)
  54. timer_stat = TaskTimerStats.start(task_id, task_name, args, kwargs)
  55. # Load task pre-init handler
  56. current_loader.on_worker_init()
  57. # Backend process cleanup
  58. default_backend.process_cleanup()
  59. try:
  60. result = func(*args, **kwargs)
  61. except (SystemExit, KeyboardInterrupt):
  62. raise
  63. except Exception, exc:
  64. default_backend.mark_as_failure(task_id, exc)
  65. retval = ExceptionInfo(sys.exc_info())
  66. else:
  67. if not ignore_result:
  68. default_backend.mark_as_done(task_id, result)
  69. retval = result
  70. finally:
  71. timer_stat.stop()
  72. return retval
  73. class TaskWrapper(object):
  74. """Class wrapping a task to be run.
  75. :param task_name: see :attr:`task_name`.
  76. :param task_id: see :attr:`task_id`.
  77. :param task_func: see :attr:`task_func`
  78. :param args: see :attr:`args`
  79. :param kwargs: see :attr:`kwargs`.
  80. .. attribute:: task_name
  81. Kind of task. Must be a name registered in the task registry.
  82. .. attribute:: task_id
  83. UUID of the task.
  84. .. attribute:: task_func
  85. The tasks callable object.
  86. .. attribute:: args
  87. List of positional arguments to apply to the task.
  88. .. attribute:: kwargs
  89. Mapping of keyword arguments to apply to the task.
  90. .. attribute:: message
  91. The original message sent. Used for acknowledging the message.
  92. """
  93. success_msg = "Task %(name)s[%(id)s] processed: %(return_value)s"
  94. fail_msg = """
  95. Task %(name)s[%(id)s] raised exception: %(exc)s\n%(traceback)s
  96. """
  97. fail_email_subject = """
  98. [celery@%(hostname)s] Error: Task %(name)s (%(id)s): %(exc)s
  99. """
  100. fail_email_body = TASK_FAIL_EMAIL_BODY
  101. def __init__(self, task_name, task_id, task_func, args, kwargs,
  102. on_acknowledge=None, **opts):
  103. self.task_name = task_name
  104. self.task_id = task_id
  105. self.task_func = task_func
  106. self.args = args
  107. self.kwargs = kwargs
  108. self.logger = kwargs.get("logger")
  109. self.on_acknowledge = on_acknowledge
  110. for opt in ("success_msg", "fail_msg", "fail_email_subject",
  111. "fail_email_body"):
  112. setattr(self, opt, opts.get(opt, getattr(self, opt, None)))
  113. if not self.logger:
  114. self.logger = multiprocessing.get_logger()
  115. def __repr__(self):
  116. return '<%s: {name:"%s", id:"%s", args:"%s", kwargs:"%s"}>' % (
  117. self.__class__.__name__,
  118. self.task_name, self.task_id,
  119. self.args, self.kwargs)
  120. @classmethod
  121. def from_message(cls, message, message_data, logger):
  122. """Create a :class:`TaskWrapper` from a task message sent by
  123. :class:`celery.messaging.TaskPublisher`.
  124. :raises UnknownTask: if the message does not describe a task,
  125. the message is also rejected.
  126. :returns: :class:`TaskWrapper` instance.
  127. """
  128. task_name = message_data["task"]
  129. task_id = message_data["id"]
  130. args = message_data["args"]
  131. kwargs = message_data["kwargs"]
  132. # Convert any unicode keys in the keyword arguments to ascii.
  133. kwargs = dict([(key.encode("utf-8"), value)
  134. for key, value in kwargs.items()])
  135. if task_name not in tasks:
  136. raise UnknownTask(task_name)
  137. task_func = tasks[task_name]
  138. return cls(task_name, task_id, task_func, args, kwargs,
  139. on_acknowledge=message.ack, logger=logger)
  140. def extend_with_default_kwargs(self, loglevel, logfile):
  141. """Extend the tasks keyword arguments with standard task arguments.
  142. These are ``logfile``, ``loglevel``, ``task_id`` and ``task_name``.
  143. """
  144. task_func_kwargs = {"logfile": logfile,
  145. "loglevel": loglevel,
  146. "task_id": self.task_id,
  147. "task_name": self.task_name}
  148. task_func_kwargs.update(self.kwargs)
  149. return task_func_kwargs
  150. def execute(self, loglevel=None, logfile=None):
  151. """Execute the task in a :func:`jail` and store return value
  152. and status in the task meta backend.
  153. :keyword loglevel: The loglevel used by the task.
  154. :keyword logfile: The logfile used by the task.
  155. """
  156. task_func_kwargs = self.extend_with_default_kwargs(loglevel, logfile)
  157. if self.on_acknowledge:
  158. self.on_acknowledge()
  159. return jail(self.task_id, self.task_name, [
  160. self.task_func, self.args, task_func_kwargs])
  161. def on_success(self, ret_value, meta):
  162. """The handler used if the task was successfully processed (
  163. without raising an exception)."""
  164. task_id = meta.get("task_id")
  165. task_name = meta.get("task_name")
  166. msg = self.success_msg.strip() % {
  167. "id": task_id,
  168. "name": task_name,
  169. "return_value": ret_value}
  170. self.logger.info(msg)
  171. def on_failure(self, exc_info, meta):
  172. """The handler used if the task raised an exception."""
  173. task_id = meta.get("task_id")
  174. task_name = meta.get("task_name")
  175. context = {
  176. "hostname": socket.gethostname(),
  177. "id": task_id,
  178. "name": task_name,
  179. "exc": exc_info.exception,
  180. "traceback": exc_info.traceback,
  181. }
  182. self.logger.error(self.fail_msg.strip() % context)
  183. task_obj = tasks.get(task_name, object)
  184. send_error_email = SEND_CELERY_TASK_ERROR_EMAILS and not \
  185. getattr(task_obj, "disable_error_emails", False)
  186. if send_error_email:
  187. subject = self.fail_email_subject.strip() % context
  188. body = self.fail_email_body.strip() % context
  189. mail_admins(subject, body, fail_silently=True)
  190. def execute_using_pool(self, pool, loglevel=None, logfile=None):
  191. """Like :meth:`execute`, but using the :mod:`multiprocessing` pool.
  192. :param pool: A :class:`multiprocessing.Pool` instance.
  193. :keyword loglevel: The loglevel used by the task.
  194. :keyword logfile: The logfile used by the task.
  195. :returns :class:`multiprocessing.AsyncResult` instance.
  196. """
  197. task_func_kwargs = self.extend_with_default_kwargs(loglevel, logfile)
  198. jail_args = [self.task_id, self.task_name, self.task_func,
  199. self.args, task_func_kwargs]
  200. return pool.apply_async(jail, args=jail_args,
  201. callbacks=[self.on_success], errbacks=[self.on_failure],
  202. on_acknowledge=self.on_acknowledge,
  203. meta={"task_id": self.task_id, "task_name": self.task_name})
  204. class PeriodicWorkController(threading.Thread):
  205. """A thread that continuously checks if there are
  206. :class:`celery.task.PeriodicTask` tasks waiting for execution,
  207. and executes them.
  208. Example:
  209. >>> PeriodicWorkController().start()
  210. """
  211. def __init__(self):
  212. super(PeriodicWorkController, self).__init__()
  213. self._shutdown = threading.Event()
  214. self._stopped = threading.Event()
  215. def run(self):
  216. """Run when you use :meth:`Thread.start`"""
  217. while True:
  218. if self._shutdown.isSet():
  219. break
  220. default_periodic_status_backend.run_periodic_tasks()
  221. time.sleep(1)
  222. self._stopped.set() # indicate that we are stopped
  223. def stop(self):
  224. """Shutdown the thread."""
  225. self._shutdown.set()
  226. self._stopped.wait() # block until this thread is done
  227. class WorkController(object):
  228. """Executes tasks waiting in the task queue.
  229. :param concurrency: see :attr:`concurrency`.
  230. :param logfile: see :attr:`logfile`.
  231. :param loglevel: see :attr:`loglevel`.
  232. .. attribute:: concurrency
  233. The number of simultaneous processes doing work (default:
  234. :const:`celery.conf.DAEMON_CONCURRENCY`)
  235. .. attribute:: loglevel
  236. The loglevel used (default: :const:`logging.INFO`)
  237. .. attribute:: logfile
  238. The logfile used, if no logfile is specified it uses ``stderr``
  239. (default: :const:`celery.conf.DAEMON_LOG_FILE`).
  240. .. attribute:: logger
  241. The :class:`logging.Logger` instance used for logging.
  242. .. attribute:: pool
  243. The :class:`multiprocessing.Pool` instance used.
  244. .. attribute:: task_consumer
  245. The :class:`celery.messaging.TaskConsumer` instance used.
  246. """
  247. loglevel = logging.ERROR
  248. concurrency = DAEMON_CONCURRENCY
  249. logfile = DAEMON_LOG_FILE
  250. _state = None
  251. def __init__(self, concurrency=None, logfile=None, loglevel=None,
  252. is_detached=False):
  253. self.loglevel = loglevel or self.loglevel
  254. self.concurrency = concurrency or self.concurrency
  255. self.logfile = logfile or self.logfile
  256. self.logger = setup_logger(loglevel, logfile)
  257. self.pool = TaskPool(self.concurrency, logger=self.logger)
  258. self.periodicworkcontroller = PeriodicWorkController()
  259. self.is_detached = is_detached
  260. self.amqp_connection = None
  261. self.task_consumer = None
  262. def close_connection(self):
  263. """Close the AMQP connection."""
  264. if self.task_consumer:
  265. self.task_consumer.close()
  266. if self.amqp_connection:
  267. self.amqp_connection.close()
  268. def reset_connection(self):
  269. """Reset the AMQP connection, and reinitialize the
  270. :class:`celery.messaging.TaskConsumer` instance.
  271. Resets the task consumer in :attr:`task_consumer`.
  272. """
  273. self.close_connection()
  274. self.amqp_connection = DjangoAMQPConnection()
  275. self.task_consumer = TaskConsumer(connection=self.amqp_connection)
  276. self.task_consumer.register_callback(self._message_callback)
  277. return self.task_consumer
  278. def connection_diagnostics(self):
  279. """Diagnose the AMQP connection, and reset connection if
  280. necessary."""
  281. connection = self.task_consumer.backend.channel.connection
  282. if not connection:
  283. self.logger.info(
  284. "AMQP Connection has died, restoring connection.")
  285. self.reset_connection()
  286. def _message_callback(self, message_data, message):
  287. """The method called when we receive a message."""
  288. try:
  289. try:
  290. self.process_task(message_data, message)
  291. except ValueError:
  292. # execute_next_task didn't return a r/name/id tuple,
  293. # probably because it got an exception.
  294. pass
  295. except UnknownTask, exc:
  296. self.logger.info("Unknown task ignored: %s" % (exc))
  297. except Exception, exc:
  298. self.logger.critical("Message queue raised %s: %s\n%s" % (
  299. exc.__class__, exc, traceback.format_exc()))
  300. except (SystemExit, KeyboardInterrupt):
  301. self.shutdown()
  302. def process_task(self, message_data, message):
  303. """Process task message by passing it to the pool of workers."""
  304. task = TaskWrapper.from_message(message, message_data,
  305. logger=self.logger)
  306. self.logger.info("Got task from broker: %s[%s]" % (
  307. task.task_name, task.task_id))
  308. self.logger.debug("Got a task: %s. Trying to execute it..." % task)
  309. result = task.execute_using_pool(self.pool, self.loglevel,
  310. self.logfile)
  311. self.logger.debug("Task %s has been executed asynchronously." % task)
  312. return result
  313. def shutdown(self):
  314. """Make sure ``celeryd`` exits cleanly."""
  315. # shut down the periodic work controller thread
  316. if self._state != "RUN":
  317. return
  318. self._state = "TERMINATE"
  319. self.periodicworkcontroller.stop()
  320. self.pool.terminate()
  321. self.close_connection()
  322. def run(self):
  323. """Starts the workers main loop."""
  324. self._state = "RUN"
  325. task_consumer = self.reset_connection()
  326. it = task_consumer.iterconsume(limit=None)
  327. self.pool.run()
  328. self.periodicworkcontroller.start()
  329. # If not running as daemon, and DEBUG logging level is enabled,
  330. # print pool PIDs and sleep for a second before we start.
  331. if self.logger.isEnabledFor(logging.DEBUG):
  332. self.logger.debug("Pool child processes: [%s]" % (
  333. "|".join(map(str, self.pool.get_worker_pids()))))
  334. if not self.is_detached:
  335. time.sleep(1)
  336. try:
  337. while True:
  338. it.next()
  339. except (SystemExit, KeyboardInterrupt):
  340. self.shutdown()