prefork.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. # -*- coding: utf-8 -*-
  2. """
  3. celery.concurrency.prefork
  4. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  5. Pool implementation using :mod:`multiprocessing`.
  6. """
  7. from __future__ import absolute_import
  8. import os
  9. from billiard import forking_enable
  10. from billiard.pool import RUN, CLOSE, Pool as BlockingPool
  11. from celery import platforms
  12. from celery import signals
  13. from celery._state import set_default_app, _set_task_join_will_block
  14. from celery.app import trace
  15. from celery.concurrency.base import BasePool
  16. from celery.five import items
  17. from celery.utils.functional import noop
  18. from celery.utils.log import get_logger
  19. from .asynpool import AsynPool
  20. __all__ = ['TaskPool', 'process_initializer', 'process_destructor']
  21. #: List of signals to reset when a child process starts.
  22. WORKER_SIGRESET = frozenset(['SIGTERM',
  23. 'SIGHUP',
  24. 'SIGTTIN',
  25. 'SIGTTOU',
  26. 'SIGUSR1'])
  27. #: List of signals to ignore when a child process starts.
  28. WORKER_SIGIGNORE = frozenset(['SIGINT'])
  29. logger = get_logger(__name__)
  30. warning, debug = logger.warning, logger.debug
  31. def process_initializer(app, hostname):
  32. """Pool child process initializer.
  33. This will initialize a child pool process to ensure the correct
  34. app instance is used and things like
  35. logging works.
  36. """
  37. _set_task_join_will_block(True)
  38. platforms.signals.reset(*WORKER_SIGRESET)
  39. platforms.signals.ignore(*WORKER_SIGIGNORE)
  40. platforms.set_mp_process_title('celeryd', hostname=hostname)
  41. # This is for Windows and other platforms not supporting
  42. # fork(). Note that init_worker makes sure it's only
  43. # run once per process.
  44. app.loader.init_worker()
  45. app.loader.init_worker_process()
  46. logfile = os.environ.get('CELERY_LOG_FILE') or None
  47. if logfile and '%i' in logfile.lower():
  48. # logfile path will differ so need to set up logging again.
  49. app.log.already_setup = False
  50. app.log.setup(int(os.environ.get('CELERY_LOG_LEVEL', 0) or 0),
  51. logfile,
  52. bool(os.environ.get('CELERY_LOG_REDIRECT', False)),
  53. str(os.environ.get('CELERY_LOG_REDIRECT_LEVEL')),
  54. hostname=hostname)
  55. if os.environ.get('FORKED_BY_MULTIPROCESSING'):
  56. # pool did execv after fork
  57. trace.setup_worker_optimizations(app)
  58. else:
  59. app.set_current()
  60. set_default_app(app)
  61. app.finalize()
  62. trace._tasks = app._tasks # enables fast_trace_task optimization.
  63. # rebuild execution handler for all tasks.
  64. from celery.app.trace import build_tracer
  65. for name, task in items(app.tasks):
  66. task.__trace__ = build_tracer(name, task, app.loader, hostname,
  67. app=app)
  68. signals.worker_process_init.send(sender=None)
  69. def process_destructor(pid, exitcode):
  70. """Pool child process destructor
  71. Dispatch the :signal:`worker_process_shutdown` signal.
  72. """
  73. signals.worker_process_shutdown.send(
  74. sender=None, pid=pid, exitcode=exitcode,
  75. )
  76. class TaskPool(BasePool):
  77. """Multiprocessing Pool implementation."""
  78. Pool = AsynPool
  79. BlockingPool = BlockingPool
  80. uses_semaphore = True
  81. write_stats = None
  82. def on_start(self):
  83. """Run the task pool.
  84. Will pre-fork all workers so they're ready to accept tasks.
  85. """
  86. forking_enable(self.forking_enable)
  87. Pool = (self.BlockingPool if self.options.get('threads', True)
  88. else self.Pool)
  89. P = self._pool = Pool(processes=self.limit,
  90. initializer=process_initializer,
  91. on_process_exit=process_destructor,
  92. synack=False,
  93. **self.options)
  94. # Create proxy methods
  95. self.on_apply = P.apply_async
  96. self.maintain_pool = P.maintain_pool
  97. self.terminate_job = P.terminate_job
  98. self.grow = P.grow
  99. self.shrink = P.shrink
  100. self.flush = getattr(P, 'flush', None) # FIXME add to billiard
  101. def restart(self):
  102. self._pool.restart()
  103. self._pool.apply_async(noop)
  104. def did_start_ok(self):
  105. return self._pool.did_start_ok()
  106. def register_with_event_loop(self, loop):
  107. try:
  108. reg = self._pool.register_with_event_loop
  109. except AttributeError:
  110. return
  111. return reg(loop)
  112. def on_stop(self):
  113. """Gracefully stop the pool."""
  114. if self._pool is not None and self._pool._state in (RUN, CLOSE):
  115. self._pool.close()
  116. self._pool.join()
  117. self._pool = None
  118. def on_terminate(self):
  119. """Force terminate the pool."""
  120. if self._pool is not None:
  121. self._pool.terminate()
  122. self._pool = None
  123. def on_close(self):
  124. if self._pool is not None and self._pool._state == RUN:
  125. self._pool.close()
  126. def _get_info(self):
  127. try:
  128. write_stats = self._pool.human_write_stats
  129. except AttributeError:
  130. write_stats = lambda: 'N/A' # only supported by asynpool
  131. return {
  132. 'max-concurrency': self.limit,
  133. 'processes': [p.pid for p in self._pool._pool],
  134. 'max-tasks-per-child': self._pool._maxtasksperchild or 'N/A',
  135. 'put-guarded-by-semaphore': self.putlocks,
  136. 'timeouts': (self._pool.soft_timeout or 0,
  137. self._pool.timeout or 0),
  138. 'writes': write_stats()
  139. }
  140. @property
  141. def num_processes(self):
  142. return self._pool._processes