consumer.py 23 KB

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