worker.py 14 KB

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