worker.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. # -*- coding: utf-8 -*-
  2. """
  3. celery.apps.worker
  4. ~~~~~~~~~~~~~~~~~~
  5. This module is the 'program-version' of :mod:`celery.worker`.
  6. It does everything necessary to run that module
  7. as an actual application, like installing signal handlers,
  8. platform tweaks, and so on.
  9. """
  10. from __future__ import absolute_import, print_function
  11. import logging
  12. import os
  13. import platform as _platform
  14. import sys
  15. import warnings
  16. from functools import partial
  17. from billiard import current_process
  18. from kombu.utils.encoding import safe_str
  19. from celery import VERSION_BANNER, platforms, signals
  20. from celery.app.abstract import from_config
  21. from celery.exceptions import SystemTerminate
  22. from celery.five import string, string_t
  23. from celery.loaders.app import AppLoader
  24. from celery.task import trace
  25. from celery.utils import cry, isatty
  26. from celery.utils.imports import qualname
  27. from celery.utils.log import get_logger, in_sighandler, set_in_sighandler
  28. from celery.utils.text import pluralize
  29. from celery.worker import WorkController
  30. logger = get_logger(__name__)
  31. is_jython = sys.platform.startswith('java')
  32. is_pypy = hasattr(sys, 'pypy_version_info')
  33. def active_thread_count():
  34. from threading import enumerate
  35. return sum(1 for t in enumerate()
  36. if not t.name.startswith('Dummy-'))
  37. def safe_say(msg):
  38. print('\n{0}'.format(msg), file=sys.__stderr__)
  39. ARTLINES = [
  40. ' --------------',
  41. '---- **** -----',
  42. '--- * *** * --',
  43. '-- * - **** ---',
  44. '- ** ----------',
  45. '- ** ----------',
  46. '- ** ----------',
  47. '- ** ----------',
  48. '- *** --- * ---',
  49. '-- ******* ----',
  50. '--- ***** -----',
  51. ' --------------',
  52. ]
  53. BANNER = """\
  54. {hostname} v{version}
  55. <<<<<<< HEAD
  56. [Configuration]
  57. . broker: {conninfo}
  58. . app: {app}
  59. . concurrency: {concurrency}
  60. . events: {events}
  61. [Queues]
  62. {queues}
  63. =======
  64. %(platform)s
  65. [config]
  66. .> broker: %(conninfo)s
  67. .> app: %(app)s
  68. .> concurrency: %(concurrency)s
  69. .> events: %(events)s
  70. [queues]
  71. %(queues)s
  72. >>>>>>> 3.0
  73. """
  74. EXTRA_INFO_FMT = """
  75. [Tasks]
  76. {tasks}
  77. """
  78. class Worker(WorkController):
  79. redirect_stdouts = from_config()
  80. redirect_stdouts_level = from_config()
  81. def on_before_init(self, purge=False, no_color=None, **kwargs):
  82. # apply task execution optimizations
  83. trace.setup_worker_optimizations(self.app)
  84. # this signal can be used to set up configuration for
  85. # workers by name.
  86. conf = self.app.conf
  87. signals.celeryd_init.send(
  88. sender=self.hostname, instance=self, conf=conf,
  89. )
  90. self.purge = purge
  91. self.no_color = no_color
  92. self._isatty = isatty(sys.stdout)
  93. self.colored = self.app.log.colored(
  94. self.logfile,
  95. enabled=not no_color if no_color is not None else no_color
  96. )
  97. def on_init_namespace(self):
  98. self._custom_logging = self.setup_logging()
  99. # apply task execution optimizations
  100. trace.setup_worker_optimizations(self.app)
  101. def on_start(self):
  102. if not self._custom_logging and self.redirect_stdouts:
  103. self.app.log.redirect_stdouts(self.redirect_stdouts_level)
  104. WorkController.on_start(self)
  105. # this signal can be used to e.g. change queues after
  106. # the -Q option has been applied.
  107. signals.celeryd_after_setup.send(
  108. sender=self.hostname, instance=self, conf=self.app.conf,
  109. )
  110. if getattr(os, 'getuid', None) and os.getuid() == 0:
  111. warnings.warn(RuntimeWarning(
  112. 'Running the worker with superuser privileges is discouraged!',
  113. ))
  114. if self.purge:
  115. self.purge_messages()
  116. # Dump configuration to screen so we have some basic information
  117. # for when users sends bug reports.
  118. sys.__stdout__.write(
  119. str(self.colored.cyan(' \n', self.startup_info())) +
  120. str(self.colored.reset(self.extra_info() or '')) + '\n'
  121. )
  122. self.set_process_status('-active-')
  123. self.install_platform_tweaks(self)
  124. def on_consumer_ready(self, consumer):
  125. signals.worker_ready.send(sender=consumer)
  126. print('{0} ready.'.format(safe_str(self.hostname), ))
  127. def setup_logging(self, colorize=None):
  128. if colorize is None and self.no_color is not None:
  129. colorize = not self.no_color
  130. return self.app.log.setup(
  131. self.loglevel, self.logfile,
  132. redirect_stdouts=False, colorize=colorize,
  133. )
  134. def purge_messages(self):
  135. count = self.app.control.purge()
  136. print('purge: Erased {0} {1} from the queue.\n'.format(
  137. count, pluralize(count, 'message')))
  138. def tasklist(self, include_builtins=True, sep='\n', int_='celery.'):
  139. return sep.join(
  140. ' . {0}'.format(task) for task in sorted(self.app.tasks)
  141. if (not task.startswith(int_) if not include_builtins else task)
  142. )
  143. def extra_info(self):
  144. if self.loglevel <= logging.INFO:
  145. include_builtins = self.loglevel <= logging.DEBUG
  146. tasklist = self.tasklist(include_builtins=include_builtins)
  147. return EXTRA_INFO_FMT.format(tasks=tasklist)
  148. def startup_info(self):
  149. app = self.app
  150. concurrency = string(self.concurrency)
  151. appr = '{0}:0x{1:x}'.format(app.main or '__main__', id(app))
  152. if not isinstance(app.loader, AppLoader):
  153. loader = qualname(app.loader)
  154. if loader.startswith('celery.loaders'):
  155. loader = loader[14:]
  156. appr += ' ({0})'.format(loader)
  157. if self.autoscale:
  158. max, min = self.autoscale
  159. concurrency = '{{min={0}, max={1}}}'.format(min, max)
  160. pool = self.pool_cls
  161. if not isinstance(pool, string_t):
  162. pool = pool.__module__
  163. concurrency += ' ({0})'.format(pool.split('.')[-1])
  164. events = 'ON'
  165. if not self.send_events:
  166. events = 'OFF (enable -E to monitor this worker)'
  167. banner = BANNER.format(
  168. app=appr,
  169. hostname=self.hostname,
  170. version=VERSION_BANNER,
  171. conninfo=self.app.connection().as_uri(),
  172. concurrency=concurrency,
  173. platform=_platform.platform(),
  174. events=events,
  175. queues=app.amqp.queues.format(indent=0, indent_first=False),
  176. ).splitlines()
  177. # integrate the ASCII art.
  178. for i, x in enumerate(banner):
  179. try:
  180. banner[i] = ' '.join([ARTLINES[i], banner[i]])
  181. except IndexError:
  182. banner[i] = ' ' * 16 + banner[i]
  183. return '\n'.join(banner) + '\n'
  184. def install_platform_tweaks(self, worker):
  185. """Install platform specific tweaks and workarounds."""
  186. if self.app.IS_OSX:
  187. self.osx_proxy_detection_workaround()
  188. # Install signal handler so SIGHUP restarts the worker.
  189. if not self._isatty:
  190. # only install HUP handler if detached from terminal,
  191. # so closing the terminal window doesn't restart the worker
  192. # into the background.
  193. if self.app.IS_OSX:
  194. # OS X can't exec from a process using threads.
  195. # See http://github.com/celery/celery/issues#issue/152
  196. install_HUP_not_supported_handler(worker)
  197. else:
  198. install_worker_restart_handler(worker)
  199. install_worker_term_handler(worker)
  200. install_worker_term_hard_handler(worker)
  201. install_worker_int_handler(worker)
  202. install_cry_handler()
  203. install_rdb_handler()
  204. def osx_proxy_detection_workaround(self):
  205. """See http://github.com/celery/celery/issues#issue/161"""
  206. os.environ.setdefault('celery_dummy_proxy', 'set_by_celeryd')
  207. def set_process_status(self, info):
  208. return platforms.set_mp_process_title(
  209. 'celeryd',
  210. info='{0} ({1})'.format(info, platforms.strargv(sys.argv)),
  211. hostname=self.hostname,
  212. )
  213. def _shutdown_handler(worker, sig='TERM', how='Warm',
  214. exc=SystemExit, callback=None):
  215. def _handle_request(signum, frame):
  216. with in_sighandler():
  217. from celery.worker import state
  218. if current_process()._name == 'MainProcess':
  219. if callback:
  220. callback(worker)
  221. safe_say('worker: {0} shutdown (MainProcess)'.format(how))
  222. if active_thread_count() > 1:
  223. setattr(state, {'Warm': 'should_stop',
  224. 'Cold': 'should_terminate'}[how], True)
  225. else:
  226. raise exc()
  227. _handle_request.__name__ = 'worker_' + how
  228. platforms.signals[sig] = _handle_request
  229. install_worker_term_handler = partial(
  230. _shutdown_handler, sig='SIGTERM', how='Warm', exc=SystemExit,
  231. )
  232. if not is_jython:
  233. install_worker_term_hard_handler = partial(
  234. _shutdown_handler, sig='SIGQUIT', how='Cold', exc=SystemTerminate,
  235. )
  236. else:
  237. install_worker_term_handler = \
  238. install_worker_term_hard_handler = lambda *a, **kw: None
  239. def on_SIGINT(worker):
  240. safe_say('worker: Hitting Ctrl+C again will terminate all running tasks!')
  241. install_worker_term_hard_handler(worker, sig='SIGINT')
  242. if not is_jython:
  243. install_worker_int_handler = partial(
  244. _shutdown_handler, sig='SIGINT', callback=on_SIGINT
  245. )
  246. else:
  247. install_worker_int_handler = lambda *a, **kw: None
  248. def _clone_current_worker():
  249. if os.fork() == 0:
  250. platforms.close_open_fds([
  251. sys.__stdin__, sys.__stdout__, sys.__stderr__,
  252. ])
  253. os.execv(sys.executable, [sys.executable] + sys.argv)
  254. def install_worker_restart_handler(worker, sig='SIGHUP'):
  255. def restart_worker_sig_handler(*args):
  256. """Signal handler restarting the current python program."""
  257. set_in_sighandler(True)
  258. safe_say('Restarting celery worker ({0})'.format(' '.join(sys.argv)))
  259. import atexit
  260. atexit.register(_clone_current_worker)
  261. from celery.worker import state
  262. state.should_stop = True
  263. platforms.signals[sig] = restart_worker_sig_handler
  264. def install_cry_handler(sig='SIGUSR1'):
  265. # Jython/PyPy does not have sys._current_frames
  266. if is_jython or is_pypy: # pragma: no cover
  267. return
  268. def cry_handler(*args):
  269. """Signal handler logging the stacktrace of all active threads."""
  270. with in_sighandler():
  271. safe_say(cry())
  272. platforms.signals[sig] = cry_handler
  273. def install_rdb_handler(envvar='CELERY_RDBSIG',
  274. sig='SIGUSR2'): # pragma: no cover
  275. def rdb_handler(*args):
  276. """Signal handler setting a rdb breakpoint at the current frame."""
  277. with in_sighandler():
  278. _, frame = args
  279. from celery.contrib import rdb
  280. rdb.set_trace(frame)
  281. if os.environ.get(envvar):
  282. platforms.signals[sig] = rdb_handler
  283. def install_HUP_not_supported_handler(worker, sig='SIGHUP'):
  284. def warn_on_HUP_handler(signum, frame):
  285. with in_sighandler():
  286. safe_say('{sig} not supported: Restarting with {sig} is '
  287. 'unstable on this platform!'.format(sig=sig))
  288. platforms.signals[sig] = warn_on_HUP_handler