Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

worker.py 12KB

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