consumer.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  1. # -*- coding: utf-8 -*-
  2. """
  3. celery.worker.consumer
  4. ~~~~~~~~~~~~~~~~~~~~~~
  5. This module contains the component responsible for consuming messages
  6. from the broker, processing the messages and keeping the broker connections
  7. up and running.
  8. :copyright: (c) 2009 - 2012 by Ask Solem.
  9. :license: BSD, see LICENSE for more details.
  10. * :meth:`~Consumer.start` is an infinite loop, which only iterates
  11. again if the connection is lost. For each iteration (at start, or if the
  12. connection is lost) it calls :meth:`~Consumer.reset_connection`,
  13. and starts the consumer by calling :meth:`~Consumer.consume_messages`.
  14. * :meth:`~Consumer.reset_connection`, clears the internal queues,
  15. establishes a new connection to the broker, sets up the task
  16. consumer (+ QoS), and the broadcast remote control command consumer.
  17. Also if events are enabled it configures the event dispatcher and starts
  18. up the heartbeat thread.
  19. * Finally it can consume messages. :meth:`~Consumer.consume_messages`
  20. is simply an infinite loop waiting for events on the AMQP channels.
  21. Both the task consumer and the broadcast consumer uses the same
  22. callback: :meth:`~Consumer.receive_message`.
  23. * So for each message received the :meth:`~Consumer.receive_message`
  24. method is called, this checks the payload of the message for either
  25. a `task` key or a `control` key.
  26. If the message is a task, it verifies the validity of the message
  27. converts it to a :class:`celery.worker.job.Request`, and sends
  28. it to :meth:`~Consumer.on_task`.
  29. If the message is a control command the message is passed to
  30. :meth:`~Consumer.on_control`, which in turn dispatches
  31. the control command using the control dispatcher.
  32. It also tries to handle malformed or invalid messages properly,
  33. so the worker doesn't choke on them and die. Any invalid messages
  34. are acknowledged immediately and logged, so the message is not resent
  35. again, and again.
  36. * If the task has an ETA/countdown, the task is moved to the `eta_schedule`
  37. so the :class:`timer2.Timer` can schedule it at its
  38. deadline. Tasks without an eta are moved immediately to the `ready_queue`,
  39. so they can be picked up by the :class:`~celery.worker.mediator.Mediator`
  40. to be sent to the pool.
  41. * When a task with an ETA is received the QoS prefetch count is also
  42. incremented, so another message can be reserved. When the ETA is met
  43. the prefetch count is decremented again, though this cannot happen
  44. immediately because amqplib doesn't support doing broker requests
  45. across threads. Instead the current prefetch count is kept as a
  46. shared counter, so as soon as :meth:`~Consumer.consume_messages`
  47. detects that the value has changed it will send out the actual
  48. QoS event to the broker.
  49. * Notice that when the connection is lost all internal queues are cleared
  50. because we can no longer ack the messages reserved in memory.
  51. However, this is not dangerous as the broker will resend them
  52. to another worker when the channel is closed.
  53. * **WARNING**: :meth:`~Consumer.stop` does not close the connection!
  54. This is because some pre-acked messages may be in processing,
  55. and they need to be finished before the channel is closed.
  56. For celeryd this means the pool must finish the tasks it has acked
  57. early, *then* close the connection.
  58. """
  59. from __future__ import absolute_import
  60. from __future__ import with_statement
  61. import logging
  62. import socket
  63. import threading
  64. import warnings
  65. from ..abstract import StartStopComponent
  66. from ..app import app_or_default
  67. from ..datastructures import AttributeDict
  68. from ..exceptions import InvalidTaskError
  69. from ..utils import noop
  70. from ..utils import timer2
  71. from ..utils.encoding import safe_repr
  72. from . import state
  73. from .control import Panel
  74. from .heartbeat import Heart
  75. RUN = 0x1
  76. CLOSE = 0x2
  77. #: Prefetch count can't exceed short.
  78. PREFETCH_COUNT_MAX = 0xFFFF
  79. #: Error message for when an unregistered task is received.
  80. UNKNOWN_TASK_ERROR = """\
  81. Received unregistered task of type %s.
  82. The message has been ignored and discarded.
  83. Did you remember to import the module containing this task?
  84. Or maybe you are using relative imports?
  85. Please see http://bit.ly/gLye1c for more information.
  86. The full contents of the message body was:
  87. %s
  88. """
  89. #: Error message for when an invalid task message is received.
  90. INVALID_TASK_ERROR = """\
  91. Received invalid task message: %s
  92. The message has been ignored and discarded.
  93. Please ensure your message conforms to the task
  94. message protocol as described here: http://bit.ly/hYj41y
  95. The full contents of the message body was:
  96. %s
  97. """
  98. MESSAGE_REPORT_FMT = """\
  99. body: %s {content_type:%s content_encoding:%s delivery_info:%s}\
  100. """
  101. class Component(StartStopComponent):
  102. name = "worker.consumer"
  103. last = True
  104. def create(self, w):
  105. prefetch_count = w.concurrency * w.prefetch_multiplier
  106. c = w.consumer = self.instantiate(
  107. w.consumer_cls, w.ready_queue, w.scheduler,
  108. logger=w.logger, hostname=w.hostname,
  109. send_events=w.send_events,
  110. init_callback=w.ready_callback,
  111. initial_prefetch_count=prefetch_count,
  112. pool=w.pool,
  113. priority_timer=w.priority_timer,
  114. app=w.app,
  115. controller=w)
  116. return c
  117. class QoS(object):
  118. """Quality of Service for Channel.
  119. For thread-safe increment/decrement of a channels prefetch count value.
  120. :param consumer: A :class:`kombu.messaging.Consumer` instance.
  121. :param initial_value: Initial prefetch count value.
  122. :param logger: Logger used to log debug messages.
  123. """
  124. prev = None
  125. def __init__(self, consumer, initial_value, logger):
  126. self.consumer = consumer
  127. self.logger = logger
  128. self._mutex = threading.RLock()
  129. self.value = initial_value
  130. def increment(self, n=1):
  131. """Increment the current prefetch count value by n."""
  132. with self._mutex:
  133. if self.value:
  134. new_value = self.value + max(n, 0)
  135. self.value = self.set(new_value)
  136. return self.value
  137. def _sub(self, n=1):
  138. assert self.value - n > 1
  139. self.value -= n
  140. def decrement(self, n=1):
  141. """Decrement the current prefetch count value by n."""
  142. with self._mutex:
  143. if self.value:
  144. self._sub(n)
  145. self.set(self.value)
  146. return self.value
  147. def decrement_eventually(self, n=1):
  148. """Decrement the value, but do not update the qos.
  149. The MainThread will be responsible for calling :meth:`update`
  150. when necessary.
  151. """
  152. with self._mutex:
  153. if self.value:
  154. self._sub(n)
  155. def set(self, pcount):
  156. """Set channel prefetch_count setting."""
  157. if pcount != self.prev:
  158. new_value = pcount
  159. if pcount > PREFETCH_COUNT_MAX:
  160. self.logger.warning("QoS: Disabled: prefetch_count exceeds %r",
  161. PREFETCH_COUNT_MAX)
  162. new_value = 0
  163. self.logger.debug("basic.qos: prefetch_count->%s", new_value)
  164. self.consumer.qos(prefetch_count=new_value)
  165. self.prev = pcount
  166. return pcount
  167. def update(self):
  168. """Update prefetch count with current value."""
  169. with self._mutex:
  170. return self.set(self.value)
  171. class Consumer(object):
  172. """Listen for messages received from the broker and
  173. move them to the ready queue for task processing.
  174. :param ready_queue: See :attr:`ready_queue`.
  175. :param eta_schedule: See :attr:`eta_schedule`.
  176. """
  177. #: The queue that holds tasks ready for immediate processing.
  178. ready_queue = None
  179. #: Timer for tasks with an ETA/countdown.
  180. eta_schedule = None
  181. #: Enable/disable events.
  182. send_events = False
  183. #: Optional callback to be called when the connection is established.
  184. #: Will only be called once, even if the connection is lost and
  185. #: re-established.
  186. init_callback = None
  187. #: The current hostname. Defaults to the system hostname.
  188. hostname = None
  189. #: Initial QoS prefetch count for the task channel.
  190. initial_prefetch_count = 0
  191. #: A :class:`celery.events.EventDispatcher` for sending events.
  192. event_dispatcher = None
  193. #: The thread that sends event heartbeats at regular intervals.
  194. #: The heartbeats are used by monitors to detect that a worker
  195. #: went offline/disappeared.
  196. heart = None
  197. #: The logger instance to use. Defaults to the default Celery logger.
  198. logger = None
  199. #: The broker connection.
  200. connection = None
  201. #: The consumer used to consume task messages.
  202. task_consumer = None
  203. #: The consumer used to consume broadcast commands.
  204. broadcast_consumer = None
  205. #: The process mailbox (kombu pidbox node).
  206. pidbox_node = None
  207. _pidbox_node_shutdown = None # used for greenlets
  208. _pidbox_node_stopped = None # used for greenlets
  209. #: The current worker pool instance.
  210. pool = None
  211. #: A timer used for high-priority internal tasks, such
  212. #: as sending heartbeats.
  213. priority_timer = None
  214. # Consumer state, can be RUN or CLOSE.
  215. _state = None
  216. def __init__(self, ready_queue, eta_schedule, logger,
  217. init_callback=noop, send_events=False, hostname=None,
  218. initial_prefetch_count=2, pool=None, app=None,
  219. priority_timer=None, controller=None):
  220. self.app = app_or_default(app)
  221. self.connection = None
  222. self.task_consumer = None
  223. self.controller = controller
  224. self.broadcast_consumer = None
  225. self.ready_queue = ready_queue
  226. self.eta_schedule = eta_schedule
  227. self.send_events = send_events
  228. self.init_callback = init_callback
  229. self.logger = logger
  230. self.hostname = hostname or socket.gethostname()
  231. self.initial_prefetch_count = initial_prefetch_count
  232. self.event_dispatcher = None
  233. self.heart = None
  234. self.pool = pool
  235. self.priority_timer = priority_timer or timer2.default_timer
  236. pidbox_state = AttributeDict(app=self.app,
  237. logger=logger,
  238. hostname=self.hostname,
  239. listener=self, # pre 2.2
  240. consumer=self)
  241. self.pidbox_node = self.app.control.mailbox.Node(self.hostname,
  242. state=pidbox_state,
  243. handlers=Panel.data)
  244. conninfo = self.app.broker_connection()
  245. self.connection_errors = conninfo.connection_errors
  246. self.channel_errors = conninfo.channel_errors
  247. self._does_info = self.logger.isEnabledFor(logging.INFO)
  248. self.strategies = {}
  249. def update_strategies(self):
  250. S = self.strategies
  251. for task in self.app.tasks.itervalues():
  252. S[task.name] = task.start_strategy(self.app, self)
  253. def start(self):
  254. """Start the consumer.
  255. Automatically survives intermittent connection failure,
  256. and will retry establishing the connection and restart
  257. consuming messages.
  258. """
  259. self.init_callback(self)
  260. while self._state != CLOSE:
  261. try:
  262. self.reset_connection()
  263. self.consume_messages()
  264. except self.connection_errors + self.channel_errors:
  265. self.logger.error("Consumer: Connection to broker lost."
  266. + " Trying to re-establish the connection...",
  267. exc_info=True)
  268. def consume_messages(self):
  269. """Consume messages forever (or until an exception is raised)."""
  270. self._debug("Starting message consumer...")
  271. self.task_consumer.consume()
  272. self._debug("Ready to accept tasks!")
  273. while self._state != CLOSE and self.connection:
  274. if self.qos.prev != self.qos.value:
  275. self.qos.update()
  276. try:
  277. self.connection.drain_events(timeout=1)
  278. except socket.timeout:
  279. pass
  280. except socket.error:
  281. if self._state != CLOSE:
  282. raise
  283. def on_task(self, task):
  284. """Handle received task.
  285. If the task has an `eta` we enter it into the ETA schedule,
  286. otherwise we move it the ready queue for immediate processing.
  287. """
  288. if task.revoked():
  289. return
  290. if self._does_info:
  291. self.logger.info("Got task from broker: %s", task.shortinfo())
  292. if self.event_dispatcher.enabled:
  293. self.event_dispatcher.send("task-received", uuid=task.task_id,
  294. name=task.task_name, args=safe_repr(task.args),
  295. kwargs=safe_repr(task.kwargs),
  296. retries=task.request_dict.get("retries", 0),
  297. eta=task.eta and task.eta.isoformat(),
  298. expires=task.expires and task.expires.isoformat())
  299. if task.eta:
  300. try:
  301. eta = timer2.to_timestamp(task.eta)
  302. except OverflowError, exc:
  303. self.logger.error(
  304. "Couldn't convert eta %s to timestamp: %r. Task: %r",
  305. task.eta, exc, task.info(safe=True),
  306. exc_info=True)
  307. task.acknowledge()
  308. else:
  309. self.qos.increment()
  310. self.eta_schedule.apply_at(eta,
  311. self.apply_eta_task, (task, ))
  312. else:
  313. state.task_reserved(task)
  314. self.ready_queue.put(task)
  315. def on_control(self, body, message):
  316. """Process remote control command message."""
  317. try:
  318. self.pidbox_node.handle_message(body, message)
  319. except KeyError, exc:
  320. self.logger.error("No such control command: %s", exc)
  321. except Exception, exc:
  322. self.logger.error(
  323. "Error occurred while handling control command: %r",
  324. exc, exc_info=True)
  325. self.reset_pidbox_node()
  326. def apply_eta_task(self, task):
  327. """Method called by the timer to apply a task with an
  328. ETA/countdown."""
  329. state.task_reserved(task)
  330. self.ready_queue.put(task)
  331. self.qos.decrement_eventually()
  332. def _message_report(self, body, message):
  333. return MESSAGE_REPORT_FMT % (safe_repr(body),
  334. safe_repr(message.content_type),
  335. safe_repr(message.content_encoding),
  336. safe_repr(message.delivery_info))
  337. def receive_message(self, body, message):
  338. """Handles incoming messages.
  339. :param body: The message body.
  340. :param message: The kombu message object.
  341. """
  342. try:
  343. name = body["task"]
  344. except (KeyError, TypeError):
  345. warnings.warn(RuntimeWarning(
  346. "Received and deleted unknown message. Wrong destination?!? \
  347. the full contents of the message body was: %s" % (
  348. self._message_report(body, message), )))
  349. message.reject_log_error(self.logger, self.connection_errors)
  350. return
  351. try:
  352. self.strategies[name](message, body, message.ack_log_error)
  353. except KeyError, exc:
  354. self.logger.error(UNKNOWN_TASK_ERROR, exc, safe_repr(body),
  355. exc_info=True)
  356. message.reject_log_error(self.logger, self.connection_errors)
  357. except InvalidTaskError, exc:
  358. self.logger.error(INVALID_TASK_ERROR, str(exc), safe_repr(body),
  359. exc_info=True)
  360. message.reject_log_error(self.logger, self.connection_errors)
  361. def maybe_conn_error(self, fun):
  362. """Applies function but ignores any connection or channel
  363. errors raised."""
  364. try:
  365. fun()
  366. except (AttributeError, ) + \
  367. self.connection_errors + \
  368. self.channel_errors:
  369. pass
  370. def close_connection(self):
  371. """Closes the current broker connection and all open channels."""
  372. # We must set self.connection to None here, so
  373. # that the green pidbox thread exits.
  374. connection, self.connection = self.connection, None
  375. if self.task_consumer:
  376. self._debug("Closing consumer channel...")
  377. self.task_consumer = \
  378. self.maybe_conn_error(self.task_consumer.close)
  379. self.stop_pidbox_node()
  380. if connection:
  381. self._debug("Closing broker connection...")
  382. self.maybe_conn_error(connection.close)
  383. def stop_consumers(self, close_connection=True):
  384. """Stop consuming tasks and broadcast commands, also stops
  385. the heartbeat thread and event dispatcher.
  386. :keyword close_connection: Set to False to skip closing the broker
  387. connection.
  388. """
  389. if not self._state == RUN:
  390. return
  391. if self.heart:
  392. # Stop the heartbeat thread if it's running.
  393. self.logger.debug("Heart: Going into cardiac arrest...")
  394. self.heart = self.heart.stop()
  395. self._debug("Cancelling task consumer...")
  396. if self.task_consumer:
  397. self.maybe_conn_error(self.task_consumer.cancel)
  398. if self.event_dispatcher:
  399. self._debug("Shutting down event dispatcher...")
  400. self.event_dispatcher = \
  401. self.maybe_conn_error(self.event_dispatcher.close)
  402. self._debug("Cancelling broadcast consumer...")
  403. if self.broadcast_consumer:
  404. self.maybe_conn_error(self.broadcast_consumer.cancel)
  405. if close_connection:
  406. self.close_connection()
  407. def on_decode_error(self, message, exc):
  408. """Callback called if an error occurs while decoding
  409. a message received.
  410. Simply logs the error and acknowledges the message so it
  411. doesn't enter a loop.
  412. :param message: The message with errors.
  413. :param exc: The original exception instance.
  414. """
  415. self.logger.critical(
  416. "Can't decode message body: %r (type:%r encoding:%r raw:%r')",
  417. exc, message.content_type, message.content_encoding,
  418. safe_repr(message.body))
  419. message.ack()
  420. def reset_pidbox_node(self):
  421. """Sets up the process mailbox."""
  422. self.stop_pidbox_node()
  423. # close previously opened channel if any.
  424. if self.pidbox_node.channel:
  425. try:
  426. self.pidbox_node.channel.close()
  427. except self.connection_errors + self.channel_errors:
  428. pass
  429. if self.pool is not None and self.pool.is_green:
  430. return self.pool.spawn_n(self._green_pidbox_node)
  431. self.pidbox_node.channel = self.connection.channel()
  432. self.broadcast_consumer = self.pidbox_node.listen(
  433. callback=self.on_control)
  434. self.broadcast_consumer.consume()
  435. def stop_pidbox_node(self):
  436. if self._pidbox_node_stopped:
  437. self._pidbox_node_shutdown.set()
  438. self._debug("Waiting for broadcast thread to shutdown...")
  439. self._pidbox_node_stopped.wait()
  440. self._pidbox_node_stopped = self._pidbox_node_shutdown = None
  441. elif self.broadcast_consumer:
  442. self._debug("Closing broadcast channel...")
  443. self.broadcast_consumer = \
  444. self.maybe_conn_error(self.broadcast_consumer.channel.close)
  445. def _green_pidbox_node(self):
  446. """Sets up the process mailbox when running in a greenlet
  447. environment."""
  448. # THIS CODE IS TERRIBLE
  449. # Luckily work has already started rewriting the Consumer for 3.0.
  450. self._pidbox_node_shutdown = threading.Event()
  451. self._pidbox_node_stopped = threading.Event()
  452. try:
  453. with self._open_connection() as conn:
  454. self.pidbox_node.channel = conn.default_channel
  455. self.broadcast_consumer = self.pidbox_node.listen(
  456. callback=self.on_control)
  457. with self.broadcast_consumer:
  458. while not self._pidbox_node_shutdown.isSet():
  459. try:
  460. conn.drain_events(timeout=1.0)
  461. except socket.timeout:
  462. pass
  463. finally:
  464. self._pidbox_node_stopped.set()
  465. def reset_connection(self):
  466. """Re-establish the broker connection and set up consumers,
  467. heartbeat and the event dispatcher."""
  468. self._debug("Re-establishing connection to the broker...")
  469. self.stop_consumers()
  470. # Clear internal queues to get rid of old messages.
  471. # They can't be acked anyway, as a delivery tag is specific
  472. # to the current channel.
  473. self.ready_queue.clear()
  474. self.eta_schedule.clear()
  475. # Re-establish the broker connection and setup the task consumer.
  476. self.connection = self._open_connection()
  477. self._debug("Connection established.")
  478. self.task_consumer = self.app.amqp.get_task_consumer(self.connection,
  479. on_decode_error=self.on_decode_error)
  480. # QoS: Reset prefetch window.
  481. self.qos = QoS(self.task_consumer,
  482. self.initial_prefetch_count, self.logger)
  483. self.qos.update()
  484. # receive_message handles incoming messages.
  485. self.task_consumer.register_callback(self.receive_message)
  486. # Setup the process mailbox.
  487. self.reset_pidbox_node()
  488. # Flush events sent while connection was down.
  489. prev_event_dispatcher = self.event_dispatcher
  490. self.event_dispatcher = self.app.events.Dispatcher(self.connection,
  491. hostname=self.hostname,
  492. enabled=self.send_events)
  493. if prev_event_dispatcher:
  494. self.event_dispatcher.copy_buffer(prev_event_dispatcher)
  495. self.event_dispatcher.flush()
  496. # Restart heartbeat thread.
  497. self.restart_heartbeat()
  498. # reload all task's execution strategies.
  499. self.update_strategies()
  500. # We're back!
  501. self._state = RUN
  502. def restart_heartbeat(self):
  503. """Restart the heartbeat thread.
  504. This thread sends heartbeat events at intervals so monitors
  505. can tell if the worker is off-line/missing.
  506. """
  507. self.heart = Heart(self.priority_timer, self.event_dispatcher)
  508. self.heart.start()
  509. def _open_connection(self):
  510. """Establish the broker connection.
  511. Will retry establishing the connection if the
  512. :setting:`BROKER_CONNECTION_RETRY` setting is enabled
  513. """
  514. # Callback called for each retry while the connection
  515. # can't be established.
  516. def _error_handler(exc, interval):
  517. self.logger.error("Consumer: Connection Error: %s. "
  518. "Trying again in %d seconds...", exc, interval)
  519. # remember that the connection is lazy, it won't establish
  520. # until it's needed.
  521. conn = self.app.broker_connection()
  522. if not self.app.conf.BROKER_CONNECTION_RETRY:
  523. # retry disabled, just call connect directly.
  524. conn.connect()
  525. return conn
  526. return conn.ensure_connection(_error_handler,
  527. self.app.conf.BROKER_CONNECTION_MAX_RETRIES)
  528. def stop(self):
  529. """Stop consuming.
  530. Does not close the broker connection, so be sure to call
  531. :meth:`close_connection` when you are finished with it.
  532. """
  533. # Notifies other threads that this instance can't be used
  534. # anymore.
  535. self._state = CLOSE
  536. self._debug("Stopping consumers...")
  537. self.stop_consumers(close_connection=False)
  538. @property
  539. def info(self):
  540. """Returns information about this consumer instance
  541. as a dict.
  542. This is also the consumer related info returned by
  543. ``celeryctl stats``.
  544. """
  545. conninfo = {}
  546. if self.connection:
  547. conninfo = self.connection.info()
  548. conninfo.pop("password", None) # don't send password.
  549. return {"broker": conninfo, "prefetch_count": self.qos.value}
  550. def _debug(self, msg, **kwargs):
  551. self.logger.debug("Consumer: %s", msg, **kwargs)