consumer.py 24 KB

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