consumer.py 24 KB

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