__init__.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. """
  2. The Multiprocessing Worker Server
  3. """
  4. import socket
  5. import logging
  6. import traceback
  7. from Queue import Queue
  8. from celery import conf
  9. from celery import registry
  10. from celery import platform
  11. from celery import signals
  12. from celery.log import setup_logger, _hijack_multiprocessing_logger
  13. from celery.beat import ClockServiceThread
  14. from celery.worker.pool import TaskPool
  15. from celery.worker.buckets import TaskBucket
  16. from celery.worker.listener import CarrotListener
  17. from celery.worker.scheduler import Scheduler
  18. from celery.worker.controllers import Mediator, ScheduleController
  19. def process_initializer():
  20. # There seems to a bug in multiprocessing (backport?)
  21. # when detached, where the worker gets EOFErrors from time to time
  22. # and the logger is left from the parent process causing a crash.
  23. _hijack_multiprocessing_logger()
  24. platform.set_mp_process_title("celeryd")
  25. class WorkController(object):
  26. """Executes tasks waiting in the task queue.
  27. :param concurrency: see :attr:`concurrency`.
  28. :param logfile: see :attr:`logfile`.
  29. :param loglevel: see :attr:`loglevel`.
  30. :param embed_clockservice: see :attr:`run_clockservice`.
  31. :param send_events: see :attr:`send_events`.
  32. .. attribute:: concurrency
  33. The number of simultaneous processes doing work (default:
  34. :const:`celery.conf.CELERYD_CONCURRENCY`)
  35. .. attribute:: loglevel
  36. The loglevel used (default: :const:`logging.INFO`)
  37. .. attribute:: logfile
  38. The logfile used, if no logfile is specified it uses ``stderr``
  39. (default: :const:`celery.conf.CELERYD_LOG_FILE`).
  40. .. attribute:: embed_clockservice
  41. If ``True``, celerybeat is embedded, running in the main worker
  42. process as a thread.
  43. .. attribute:: send_events
  44. Enable the sending of monitoring events, these events can be captured
  45. by monitors (celerymon).
  46. .. attribute:: logger
  47. The :class:`logging.Logger` instance used for logging.
  48. .. attribute:: pool
  49. The :class:`multiprocessing.Pool` instance used.
  50. .. attribute:: ready_queue
  51. The :class:`Queue.Queue` that holds tasks ready for immediate
  52. processing.
  53. .. attribute:: hold_queue
  54. The :class:`Queue.Queue` that holds paused tasks. Reasons for holding
  55. back the task include waiting for ``eta`` to pass or the task is being
  56. retried.
  57. .. attribute:: schedule_controller
  58. Instance of :class:`celery.worker.controllers.ScheduleController`.
  59. .. attribute:: mediator
  60. Instance of :class:`celery.worker.controllers.Mediator`.
  61. .. attribute:: listener
  62. Instance of :class:`CarrotListener`.
  63. """
  64. loglevel = logging.ERROR
  65. concurrency = conf.CELERYD_CONCURRENCY
  66. logfile = conf.CELERYD_LOG_FILE
  67. _state = None
  68. def __init__(self, concurrency=None, logfile=None, loglevel=None,
  69. send_events=conf.SEND_EVENTS, hostname=None,
  70. embed_clockservice=False):
  71. # Options
  72. self.loglevel = loglevel or self.loglevel
  73. self.concurrency = concurrency or self.concurrency
  74. self.logfile = logfile or self.logfile
  75. self.logger = setup_logger(loglevel, logfile)
  76. self.hostname = hostname or socket.gethostname()
  77. self.embed_clockservice = embed_clockservice
  78. self.send_events = send_events
  79. # Queues
  80. if conf.DISABLE_RATE_LIMITS:
  81. self.ready_queue = Queue()
  82. else:
  83. self.ready_queue = TaskBucket(task_registry=registry.tasks)
  84. self.eta_schedule = Scheduler(self.ready_queue)
  85. self.logger.debug("Instantiating thread components...")
  86. # Threads + Pool + Consumer
  87. self.pool = TaskPool(self.concurrency,
  88. logger=self.logger,
  89. initializer=process_initializer)
  90. self.mediator = Mediator(self.ready_queue,
  91. callback=self.process_task,
  92. logger=self.logger)
  93. self.scheduler = ScheduleController(self.eta_schedule,
  94. logger=self.logger)
  95. # Need a tight loop interval when embedded so the program
  96. # can be stopped in a sensible short time.
  97. self.clockservice = self.embed_clockservice and ClockServiceThread(
  98. logger=self.logger,
  99. max_interval=1) or None
  100. prefetch_count = concurrency * conf.CELERYD_PREFETCH_MULTIPLIER
  101. self.listener = CarrotListener(self.ready_queue,
  102. self.eta_schedule,
  103. logger=self.logger,
  104. hostname=self.hostname,
  105. send_events=send_events,
  106. initial_prefetch_count=prefetch_count)
  107. # The order is important here;
  108. # the first in the list is the first to start,
  109. # and they must be stopped in reverse order.
  110. self.components = filter(None, (self.pool,
  111. self.mediator,
  112. self.scheduler,
  113. self.clockservice,
  114. self.listener))
  115. def start(self):
  116. """Starts the workers main loop."""
  117. self._state = "RUN"
  118. try:
  119. for component in self.components:
  120. self.logger.debug("Starting thread %s..." % \
  121. component.__class__.__name__)
  122. component.start()
  123. finally:
  124. self.stop()
  125. def process_task(self, wrapper):
  126. """Process task by sending it to the pool of workers."""
  127. try:
  128. try:
  129. wrapper.task.execute(wrapper, self.pool,
  130. self.loglevel, self.logfile)
  131. except Exception, exc:
  132. self.logger.critical("Internal error %s: %s\n%s" % (
  133. exc.__class__, exc, traceback.format_exc()))
  134. except (SystemExit, KeyboardInterrupt):
  135. self.stop()
  136. def stop(self):
  137. """Gracefully shutdown the worker server."""
  138. if self._state != "RUN":
  139. return
  140. signals.worker_shutdown.send(sender=self)
  141. [component.stop() for component in reversed(self.components)]
  142. self._state = "STOP"