worker.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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, unicode_literals
  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 import trace
  21. from celery.exceptions import CDeprecationWarning, SystemTerminate
  22. from celery.five import string, string_t
  23. from celery.loaders.app import AppLoader
  24. from celery.platforms import check_privileges
  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. __all__ = ['Worker']
  31. logger = get_logger(__name__)
  32. is_jython = sys.platform.startswith('java')
  33. is_pypy = hasattr(sys, 'pypy_version_info')
  34. W_PICKLE_DEPRECATED = """
  35. Starting from version 3.2 Celery will refuse to accept pickle by default.
  36. The pickle serializer is a security concern as it may give attackers
  37. the ability to execute any command. It's important to secure
  38. your broker from unauthorized access when using pickle, so we think
  39. that enabling pickle should require a deliberate action and not be
  40. the default choice.
  41. If you depend on pickle then you should set a setting to disable this
  42. warning and to be sure that everything will continue working
  43. when you upgrade to Celery 3.2::
  44. CELERY_ACCEPT_CONTENT = ['pickle', 'json', 'msgpack', 'yaml']
  45. You must only enable the serializers that you will actually use.
  46. """
  47. def active_thread_count():
  48. from threading import enumerate
  49. return sum(1 for t in enumerate()
  50. if not t.name.startswith('Dummy-'))
  51. def safe_say(msg):
  52. print('\n{0}'.format(msg), file=sys.__stderr__)
  53. ARTLINES = [
  54. ' --------------',
  55. '---- **** -----',
  56. '--- * *** * --',
  57. '-- * - **** ---',
  58. '- ** ----------',
  59. '- ** ----------',
  60. '- ** ----------',
  61. '- ** ----------',
  62. '- *** --- * ---',
  63. '-- ******* ----',
  64. '--- ***** -----',
  65. ' --------------',
  66. ]
  67. BANNER = """\
  68. {hostname} v{version}
  69. {platform}
  70. [config]
  71. .> app: {app}
  72. .> transport: {conninfo}
  73. .> results: {results}
  74. .> concurrency: {concurrency}
  75. [queues]
  76. {queues}
  77. """
  78. EXTRA_INFO_FMT = """
  79. [tasks]
  80. {tasks}
  81. """
  82. class Worker(WorkController):
  83. def on_before_init(self, **kwargs):
  84. trace.setup_worker_optimizations(self.app)
  85. # this signal can be used to set up configuration for
  86. # workers by name.
  87. signals.celeryd_init.send(
  88. sender=self.hostname, instance=self,
  89. conf=self.app.conf, options=kwargs,
  90. )
  91. check_privileges(self.app.conf.CELERY_ACCEPT_CONTENT)
  92. def on_after_init(self, purge=False, no_color=None,
  93. redirect_stdouts=None, redirect_stdouts_level=None,
  94. **kwargs):
  95. self.redirect_stdouts = self._getopt(
  96. 'redirect_stdouts', redirect_stdouts,
  97. )
  98. self.redirect_stdouts_level = self._getopt(
  99. 'redirect_stdouts_level', redirect_stdouts_level,
  100. )
  101. super(Worker, self).setup_defaults(**kwargs)
  102. self.purge = purge
  103. self.no_color = no_color
  104. self._isatty = isatty(sys.stdout)
  105. self.colored = self.app.log.colored(
  106. self.logfile,
  107. enabled=not no_color if no_color is not None else no_color
  108. )
  109. def on_init_blueprint(self):
  110. self._custom_logging = self.setup_logging()
  111. # apply task execution optimizations
  112. # -- This will finalize the app!
  113. trace.setup_worker_optimizations(self.app)
  114. def on_start(self):
  115. if not self._custom_logging and self.redirect_stdouts:
  116. self.app.log.redirect_stdouts(self.redirect_stdouts_level)
  117. WorkController.on_start(self)
  118. # this signal can be used to e.g. change queues after
  119. # the -Q option has been applied.
  120. signals.celeryd_after_setup.send(
  121. sender=self.hostname, instance=self, conf=self.app.conf,
  122. )
  123. if not self.app.conf.value_set_for('CELERY_ACCEPT_CONTENT'):
  124. warnings.warn(CDeprecationWarning(W_PICKLE_DEPRECATED))
  125. if self.purge:
  126. self.purge_messages()
  127. # Dump configuration to screen so we have some basic information
  128. # for when users sends bug reports.
  129. print(''.join([
  130. string(self.colored.cyan(' \n', self.startup_info())),
  131. string(self.colored.reset(self.extra_info() or '')),
  132. ]), file=sys.__stdout__)
  133. self.set_process_status('-active-')
  134. self.install_platform_tweaks(self)
  135. def on_consumer_ready(self, consumer):
  136. signals.worker_ready.send(sender=consumer)
  137. print('{0} ready.'.format(safe_str(self.hostname), ))
  138. def setup_logging(self, colorize=None):
  139. if colorize is None and self.no_color is not None:
  140. colorize = not self.no_color
  141. return self.app.log.setup(
  142. self.loglevel, self.logfile,
  143. redirect_stdouts=False, colorize=colorize,
  144. )
  145. def purge_messages(self):
  146. count = self.app.control.purge()
  147. if count:
  148. print('purge: Erased {0} {1} from the queue.\n'.format(
  149. count, pluralize(count, 'message')))
  150. def tasklist(self, include_builtins=True, sep='\n', int_='celery.'):
  151. return sep.join(
  152. ' . {0}'.format(task) for task in sorted(self.app.tasks)
  153. if (not task.startswith(int_) if not include_builtins else task)
  154. )
  155. def extra_info(self):
  156. if self.loglevel <= logging.INFO:
  157. include_builtins = self.loglevel <= logging.DEBUG
  158. tasklist = self.tasklist(include_builtins=include_builtins)
  159. return EXTRA_INFO_FMT.format(tasks=tasklist)
  160. def startup_info(self):
  161. app = self.app
  162. concurrency = string(self.concurrency)
  163. appr = '{0}:0x{1:x}'.format(app.main or '__main__', id(app))
  164. if not isinstance(app.loader, AppLoader):
  165. loader = qualname(app.loader)
  166. if loader.startswith('celery.loaders'):
  167. loader = loader[14:]
  168. appr += ' ({0})'.format(loader)
  169. if self.autoscale:
  170. max, min = self.autoscale
  171. concurrency = '{{min={0}, max={1}}}'.format(min, max)
  172. pool = self.pool_cls
  173. if not isinstance(pool, string_t):
  174. pool = pool.__module__
  175. concurrency += ' ({0})'.format(pool.split('.')[-1])
  176. events = 'ON'
  177. if not self.send_events:
  178. events = 'OFF (enable -E to monitor this worker)'
  179. banner = BANNER.format(
  180. app=appr,
  181. hostname=safe_str(self.hostname),
  182. version=VERSION_BANNER,
  183. conninfo=self.app.connection().as_uri(),
  184. results=self.app.conf.CELERY_RESULT_BACKEND or 'disabled',
  185. concurrency=concurrency,
  186. platform=safe_str(_platform.platform()),
  187. events=events,
  188. queues=app.amqp.queues.format(indent=0, indent_first=False),
  189. ).splitlines()
  190. # integrate the ASCII art.
  191. for i, x in enumerate(banner):
  192. try:
  193. banner[i] = ' '.join([ARTLINES[i], banner[i]])
  194. except IndexError:
  195. banner[i] = ' ' * 16 + banner[i]
  196. return '\n'.join(banner) + '\n'
  197. def install_platform_tweaks(self, worker):
  198. """Install platform specific tweaks and workarounds."""
  199. if self.app.IS_OSX:
  200. self.osx_proxy_detection_workaround()
  201. # Install signal handler so SIGHUP restarts the worker.
  202. if not self._isatty:
  203. # only install HUP handler if detached from terminal,
  204. # so closing the terminal window doesn't restart the worker
  205. # into the background.
  206. if self.app.IS_OSX:
  207. # OS X can't exec from a process using threads.
  208. # See http://github.com/celery/celery/issues#issue/152
  209. install_HUP_not_supported_handler(worker)
  210. else:
  211. install_worker_restart_handler(worker)
  212. install_worker_term_handler(worker)
  213. install_worker_term_hard_handler(worker)
  214. install_worker_int_handler(worker)
  215. install_cry_handler()
  216. install_rdb_handler()
  217. def osx_proxy_detection_workaround(self):
  218. """See http://github.com/celery/celery/issues#issue/161"""
  219. os.environ.setdefault('celery_dummy_proxy', 'set_by_celeryd')
  220. def set_process_status(self, info):
  221. return platforms.set_mp_process_title(
  222. 'celeryd',
  223. info='{0} ({1})'.format(info, platforms.strargv(sys.argv)),
  224. hostname=self.hostname,
  225. )
  226. def _shutdown_handler(worker, sig='TERM', how='Warm',
  227. exc=SystemExit, callback=None):
  228. def _handle_request(*args):
  229. with in_sighandler():
  230. from celery.worker import state
  231. if current_process()._name == 'MainProcess':
  232. if callback:
  233. callback(worker)
  234. safe_say('worker: {0} shutdown (MainProcess)'.format(how))
  235. if active_thread_count() > 1:
  236. setattr(state, {'Warm': 'should_stop',
  237. 'Cold': 'should_terminate'}[how], True)
  238. else:
  239. raise exc()
  240. _handle_request.__name__ = str('worker_{0}'.format(how))
  241. platforms.signals[sig] = _handle_request
  242. install_worker_term_handler = partial(
  243. _shutdown_handler, sig='SIGTERM', how='Warm', exc=SystemExit,
  244. )
  245. if not is_jython: # pragma: no cover
  246. install_worker_term_hard_handler = partial(
  247. _shutdown_handler, sig='SIGQUIT', how='Cold', exc=SystemTerminate,
  248. )
  249. else: # pragma: no cover
  250. install_worker_term_handler = \
  251. install_worker_term_hard_handler = lambda *a, **kw: None
  252. def on_SIGINT(worker):
  253. safe_say('worker: Hitting Ctrl+C again will terminate all running tasks!')
  254. install_worker_term_hard_handler(worker, sig='SIGINT')
  255. if not is_jython: # pragma: no cover
  256. install_worker_int_handler = partial(
  257. _shutdown_handler, sig='SIGINT', callback=on_SIGINT
  258. )
  259. else: # pragma: no cover
  260. install_worker_int_handler = lambda *a, **kw: None
  261. def _reload_current_worker():
  262. platforms.close_open_fds([
  263. sys.__stdin__, sys.__stdout__, sys.__stderr__,
  264. ])
  265. os.execv(sys.executable, [sys.executable] + sys.argv)
  266. def install_worker_restart_handler(worker, sig='SIGHUP'):
  267. def restart_worker_sig_handler(*args):
  268. """Signal handler restarting the current python program."""
  269. set_in_sighandler(True)
  270. safe_say('Restarting celery worker ({0})'.format(' '.join(sys.argv)))
  271. import atexit
  272. atexit.register(_reload_current_worker)
  273. from celery.worker import state
  274. state.should_stop = True
  275. platforms.signals[sig] = restart_worker_sig_handler
  276. def install_cry_handler(sig='SIGUSR1'):
  277. # Jython/PyPy does not have sys._current_frames
  278. if is_jython or is_pypy: # pragma: no cover
  279. return
  280. def cry_handler(*args):
  281. """Signal handler logging the stacktrace of all active threads."""
  282. with in_sighandler():
  283. safe_say(cry())
  284. platforms.signals[sig] = cry_handler
  285. def install_rdb_handler(envvar='CELERY_RDBSIG',
  286. sig='SIGUSR2'): # pragma: no cover
  287. def rdb_handler(*args):
  288. """Signal handler setting a rdb breakpoint at the current frame."""
  289. with in_sighandler():
  290. from celery.contrib.rdb import set_trace, _frame
  291. # gevent does not pass standard signal handler args
  292. frame = args[1] if args else _frame().f_back
  293. set_trace(frame)
  294. if os.environ.get(envvar):
  295. platforms.signals[sig] = rdb_handler
  296. def install_HUP_not_supported_handler(worker, sig='SIGHUP'):
  297. def warn_on_HUP_handler(signum, frame):
  298. with in_sighandler():
  299. safe_say('{sig} not supported: Restarting with {sig} is '
  300. 'unstable on this platform!'.format(sig=sig))
  301. platforms.signals[sig] = warn_on_HUP_handler