consumer.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824
  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. * :meth:`~Consumer.start` is an infinite loop, which only iterates
  9. again if the connection is lost. For each iteration (at start, or if the
  10. connection is lost) it calls :meth:`~Consumer.reset_connection`,
  11. and starts the consumer by calling :meth:`~Consumer.consume_messages`.
  12. * :meth:`~Consumer.reset_connection`, clears the internal queues,
  13. establishes a new connection to the broker, sets up the task
  14. consumer (+ QoS), and the broadcast remote control command consumer.
  15. Also if events are enabled it configures the event dispatcher and starts
  16. up the heartbeat thread.
  17. * Finally it can consume messages. :meth:`~Consumer.consume_messages`
  18. is simply an infinite loop waiting for events on the AMQP channels.
  19. Both the task consumer and the broadcast consumer uses the same
  20. callback: :meth:`~Consumer.receive_message`.
  21. * So for each message received the :meth:`~Consumer.receive_message`
  22. method is called, this checks the payload of the message for either
  23. a `task` key or a `control` key.
  24. If the message is a task, it verifies the validity of the message
  25. converts it to a :class:`celery.worker.job.Request`, and sends
  26. it to :meth:`~Consumer.on_task`.
  27. If the message is a control command the message is passed to
  28. :meth:`~Consumer.on_control`, which in turn dispatches
  29. the control command using the control dispatcher.
  30. It also tries to handle malformed or invalid messages properly,
  31. so the worker doesn't choke on them and die. Any invalid messages
  32. are acknowledged immediately and logged, so the message is not resent
  33. again, and again.
  34. * If the task has an ETA/countdown, the task is moved to the `timer`
  35. so the :class:`timer2.Timer` can schedule it at its
  36. deadline. Tasks without an eta are moved immediately to the `ready_queue`,
  37. so they can be picked up by the :class:`~celery.worker.mediator.Mediator`
  38. to be sent to the pool.
  39. * When a task with an ETA is received the QoS prefetch count is also
  40. incremented, so another message can be reserved. When the ETA is met
  41. the prefetch count is decremented again, though this cannot happen
  42. immediately because amqplib doesn't support doing broker requests
  43. across threads. Instead the current prefetch count is kept as a
  44. shared counter, so as soon as :meth:`~Consumer.consume_messages`
  45. detects that the value has changed it will send out the actual
  46. QoS event to the broker.
  47. * Notice that when the connection is lost all internal queues are cleared
  48. because we can no longer ack the messages reserved in memory.
  49. However, this is not dangerous as the broker will resend them
  50. to another worker when the channel is closed.
  51. * **WARNING**: :meth:`~Consumer.stop` does not close the connection!
  52. This is because some pre-acked messages may be in processing,
  53. and they need to be finished before the channel is closed.
  54. For celeryd this means the pool must finish the tasks it has acked
  55. early, *then* close the connection.
  56. """
  57. from __future__ import absolute_import
  58. import logging
  59. import socket
  60. import threading
  61. from time import sleep
  62. from Queue import Empty
  63. from kombu.utils.encoding import safe_repr
  64. from kombu.utils.eventio import READ, WRITE, ERR
  65. from celery.app import app_or_default
  66. from celery.datastructures import AttributeDict
  67. from celery.exceptions import InvalidTaskError, SystemTerminate
  68. from celery.task.trace import build_tracer
  69. from celery.utils import timer2
  70. from celery.utils.functional import noop
  71. from celery.utils.log import get_logger
  72. from celery.utils import text
  73. from . import state
  74. from .bootsteps import StartStopComponent
  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. UNKNOWN_FORMAT = """\
  82. Received and deleted unknown message. Wrong destination?!?
  83. The full contents of the message body was: %s
  84. """
  85. #: Error message for when an unregistered task is received.
  86. UNKNOWN_TASK_ERROR = """\
  87. Received unregistered task of type %s.
  88. The message has been ignored and discarded.
  89. Did you remember to import the module containing this task?
  90. Or maybe you are using relative imports?
  91. Please see http://bit.ly/gLye1c for more information.
  92. The full contents of the message body was:
  93. %s
  94. """
  95. #: Error message for when an invalid task message is received.
  96. INVALID_TASK_ERROR = """\
  97. Received invalid task message: %s
  98. The message has been ignored and discarded.
  99. Please ensure your message conforms to the task
  100. message protocol as described here: http://bit.ly/hYj41y
  101. The full contents of the message body was:
  102. %s
  103. """
  104. MESSAGE_REPORT_FMT = """\
  105. body: {0} {{content_type:{1} content_encoding:{2} delivery_info:{3}}}\
  106. """
  107. RETRY_CONNECTION = """\
  108. Consumer: Connection to broker lost. \
  109. Trying to re-establish the connection...\
  110. """
  111. task_reserved = state.task_reserved
  112. logger = get_logger(__name__)
  113. info, warn, error, crit = (logger.info, logger.warn,
  114. logger.error, logger.critical)
  115. def debug(msg, *args, **kwargs):
  116. logger.debug('Consumer: {0}'.format(msg), *args, **kwargs)
  117. def dump_body(m, body):
  118. return "{0} ({1}b)".format(text.truncate(safe_repr(body), 1024),
  119. len(m.body))
  120. class Component(StartStopComponent):
  121. name = 'worker.consumer'
  122. last = True
  123. def Consumer(self, w):
  124. return (w.consumer_cls or
  125. Consumer if w.hub else BlockingConsumer)
  126. def create(self, w):
  127. prefetch_count = w.concurrency * w.prefetch_multiplier
  128. c = w.consumer = self.instantiate(self.Consumer(w),
  129. w.ready_queue,
  130. hostname=w.hostname,
  131. send_events=w.send_events,
  132. init_callback=w.ready_callback,
  133. initial_prefetch_count=prefetch_count,
  134. pool=w.pool,
  135. timer=w.timer,
  136. app=w.app,
  137. controller=w,
  138. hub=w.hub)
  139. return c
  140. class QoS(object):
  141. """Thread safe increment/decrement of a channels prefetch_count.
  142. :param consumer: A :class:`kombu.messaging.Consumer` instance.
  143. :param initial_value: Initial prefetch count value.
  144. """
  145. prev = None
  146. def __init__(self, consumer, initial_value):
  147. self.consumer = consumer
  148. self._mutex = threading.RLock()
  149. self.value = initial_value or 0
  150. def increment_eventually(self, n=1):
  151. """Increment the value, but do not update the channels 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.value = self.value + max(n, 0)
  158. return self.value
  159. def decrement_eventually(self, n=1):
  160. """Decrement the value, but do not update the channels QoS.
  161. The MainThread will be responsible for calling :meth:`update`
  162. when necessary.
  163. """
  164. with self._mutex:
  165. if self.value:
  166. self.value -= n
  167. return self.value
  168. def set(self, pcount):
  169. """Set channel prefetch_count setting."""
  170. if pcount != self.prev:
  171. new_value = pcount
  172. if pcount > PREFETCH_COUNT_MAX:
  173. warn('QoS: Disabled: prefetch_count exceeds %r',
  174. PREFETCH_COUNT_MAX)
  175. new_value = 0
  176. debug('basic.qos: prefetch_count->%s', new_value)
  177. self.consumer.qos(prefetch_count=new_value)
  178. self.prev = pcount
  179. return pcount
  180. def update(self):
  181. """Update prefetch count with current value."""
  182. with self._mutex:
  183. return self.set(self.value)
  184. class Consumer(object):
  185. """Listen for messages received from the broker and
  186. move them to the ready queue for task processing.
  187. :param ready_queue: See :attr:`ready_queue`.
  188. :param timer: See :attr:`timer`.
  189. """
  190. #: The queue that holds tasks ready for immediate processing.
  191. ready_queue = None
  192. #: Enable/disable events.
  193. send_events = False
  194. #: Optional callback to be called when the connection is established.
  195. #: Will only be called once, even if the connection is lost and
  196. #: re-established.
  197. init_callback = None
  198. #: The current hostname. Defaults to the system hostname.
  199. hostname = None
  200. #: Initial QoS prefetch count for the task channel.
  201. initial_prefetch_count = 0
  202. #: A :class:`celery.events.EventDispatcher` for sending events.
  203. event_dispatcher = None
  204. #: The thread that sends event heartbeats at regular intervals.
  205. #: The heartbeats are used by monitors to detect that a worker
  206. #: went offline/disappeared.
  207. heart = None
  208. #: The broker connection.
  209. connection = None
  210. #: The consumer used to consume task messages.
  211. task_consumer = None
  212. #: The consumer used to consume broadcast commands.
  213. broadcast_consumer = None
  214. #: The process mailbox (kombu pidbox node).
  215. pidbox_node = None
  216. _pidbox_node_shutdown = None # used for greenlets
  217. _pidbox_node_stopped = None # used for greenlets
  218. #: The current worker pool instance.
  219. pool = None
  220. #: A timer used for high-priority internal tasks, such
  221. #: as sending heartbeats.
  222. timer = None
  223. # Consumer state, can be RUN or CLOSE.
  224. _state = None
  225. def __init__(self, ready_queue,
  226. init_callback=noop, send_events=False, hostname=None,
  227. initial_prefetch_count=2, pool=None, app=None,
  228. timer=None, controller=None, hub=None, **kwargs):
  229. self.app = app_or_default(app)
  230. self.connection = None
  231. self.task_consumer = None
  232. self.controller = controller
  233. self.broadcast_consumer = None
  234. self.ready_queue = ready_queue
  235. self.send_events = send_events
  236. self.init_callback = init_callback
  237. self.hostname = hostname or socket.gethostname()
  238. self.initial_prefetch_count = initial_prefetch_count
  239. self.event_dispatcher = None
  240. self.heart = None
  241. self.pool = pool
  242. self.timer = timer or timer2.default_timer
  243. pidbox_state = AttributeDict(app=self.app,
  244. hostname=self.hostname,
  245. listener=self, # pre 2.2
  246. consumer=self)
  247. self.pidbox_node = self.app.control.mailbox.Node(self.hostname,
  248. state=pidbox_state,
  249. handlers=Panel.data)
  250. conninfo = self.app.connection()
  251. self.connection_errors = conninfo.connection_errors
  252. self.channel_errors = conninfo.channel_errors
  253. self._does_info = logger.isEnabledFor(logging.INFO)
  254. self.strategies = {}
  255. if hub:
  256. hub.on_init.append(self.on_poll_init)
  257. self.hub = hub
  258. self._quick_put = self.ready_queue.put
  259. def update_strategies(self):
  260. S = self.strategies
  261. app = self.app
  262. loader = app.loader
  263. hostname = self.hostname
  264. for name, task in self.app.tasks.iteritems():
  265. S[name] = task.start_strategy(app, self)
  266. task.__trace__ = build_tracer(name, task, loader, hostname)
  267. def start(self):
  268. """Start the consumer.
  269. Automatically survives intermittent connection failure,
  270. and will retry establishing the connection and restart
  271. consuming messages.
  272. """
  273. self.init_callback(self)
  274. while self._state != CLOSE:
  275. self.maybe_shutdown()
  276. try:
  277. self.reset_connection()
  278. self.consume_messages()
  279. except self.connection_errors + self.channel_errors:
  280. error(RETRY_CONNECTION, exc_info=True)
  281. def on_poll_init(self, hub):
  282. hub.update_readers(self.connection.eventmap)
  283. self.connection.transport.on_poll_init(hub.poller)
  284. def consume_messages(self, sleep=sleep, min=min, Empty=Empty):
  285. """Consume messages forever (or until an exception is raised)."""
  286. with self.hub as hub:
  287. qos = self.qos
  288. update_qos = qos.update
  289. update_readers = hub.update_readers
  290. readers, writers = hub.readers, hub.writers
  291. poll = hub.poller.poll
  292. fire_timers = hub.fire_timers
  293. scheduled = hub.timer._queue
  294. connection = self.connection
  295. on_poll_start = connection.transport.on_poll_start
  296. strategies = self.strategies
  297. drain_nowait = connection.drain_nowait
  298. on_task_callbacks = hub.on_task
  299. keep_draining = connection.transport.nb_keep_draining
  300. def on_task_received(body, message):
  301. if on_task_callbacks:
  302. [callback() for callback in on_task_callbacks]
  303. try:
  304. name = body['task']
  305. except (KeyError, TypeError):
  306. return self.handle_unknown_message(body, message)
  307. try:
  308. strategies[name](message, body, message.ack_log_error)
  309. except KeyError as exc:
  310. self.handle_unknown_task(body, message, exc)
  311. except InvalidTaskError as exc:
  312. self.handle_invalid_task(body, message, exc)
  313. #fire_timers()
  314. self.task_consumer.callbacks = [on_task_received]
  315. self.task_consumer.consume()
  316. debug('Ready to accept tasks!')
  317. while self._state != CLOSE and self.connection:
  318. # shutdown if signal handlers told us to.
  319. if state.should_stop:
  320. raise SystemExit()
  321. elif state.should_terminate:
  322. raise SystemTerminate()
  323. # fire any ready timers, this also returns
  324. # the number of seconds until we need to fire timers again.
  325. poll_timeout = fire_timers() if scheduled else 1
  326. # We only update QoS when there is no more messages to read.
  327. # This groups together qos calls, and makes sure that remote
  328. # control commands will be prioritized over task messages.
  329. if qos.prev != qos.value:
  330. update_qos()
  331. update_readers(on_poll_start())
  332. if readers or writers:
  333. connection.more_to_read = True
  334. while connection.more_to_read:
  335. for fileno, event in poll(poll_timeout) or ():
  336. try:
  337. if event & READ:
  338. readers[fileno](fileno, event)
  339. if event & WRITE:
  340. writers[fileno](fileno, event)
  341. if event & ERR:
  342. for handlermap in readers, writers:
  343. try:
  344. handlermap[fileno](fileno, event)
  345. except KeyError:
  346. pass
  347. except Empty:
  348. continue
  349. except socket.error:
  350. if self._state != CLOSE: # pragma: no cover
  351. raise
  352. if keep_draining:
  353. drain_nowait()
  354. poll_timeout = 0
  355. else:
  356. connection.more_to_read = False
  357. else:
  358. # no sockets yet, startup is probably not done.
  359. sleep(min(poll_timeout, 0.1))
  360. def on_task(self, task, task_reserved=task_reserved):
  361. """Handle received task.
  362. If the task has an `eta` we enter it into the ETA schedule,
  363. otherwise we move it the ready queue for immediate processing.
  364. """
  365. if task.revoked():
  366. return
  367. if self._does_info:
  368. info('Got task from broker: %s', task)
  369. if self.event_dispatcher.enabled:
  370. self.event_dispatcher.send('task-received', uuid=task.id,
  371. name=task.name, args=safe_repr(task.args),
  372. kwargs=safe_repr(task.kwargs),
  373. retries=task.request_dict.get('retries', 0),
  374. eta=task.eta and task.eta.isoformat(),
  375. expires=task.expires and task.expires.isoformat())
  376. if task.eta:
  377. try:
  378. eta = timer2.to_timestamp(task.eta)
  379. except OverflowError as exc:
  380. error("Couldn't convert eta %s to timestamp: %r. Task: %r",
  381. task.eta, exc, task.info(safe=True), exc_info=True)
  382. task.acknowledge()
  383. else:
  384. self.qos.increment_eventually()
  385. self.timer.apply_at(eta, self.apply_eta_task, (task, ),
  386. priority=6)
  387. else:
  388. task_reserved(task)
  389. self._quick_put(task)
  390. def on_control(self, body, message):
  391. """Process remote control command message."""
  392. try:
  393. self.pidbox_node.handle_message(body, message)
  394. except KeyError as exc:
  395. error('No such control command: %s', exc)
  396. except Exception as exc:
  397. error('Control command error: %r', exc, exc_info=True)
  398. self.reset_pidbox_node()
  399. def apply_eta_task(self, task):
  400. """Method called by the timer to apply a task with an
  401. ETA/countdown."""
  402. task_reserved(task)
  403. self._quick_put(task)
  404. self.qos.decrement_eventually()
  405. def _message_report(self, body, message):
  406. return MESSAGE_REPORT_FMT.format(dump_body(message, body),
  407. safe_repr(message.content_type),
  408. safe_repr(message.content_encoding),
  409. safe_repr(message.delivery_info))
  410. def handle_unknown_message(self, body, message):
  411. warn(UNKNOWN_FORMAT, self._message_report(body, message))
  412. message.reject_log_error(logger, self.connection_errors)
  413. def handle_unknown_task(self, body, message, exc):
  414. error(UNKNOWN_TASK_ERROR, exc, dump_body(message, body), exc_info=True)
  415. message.reject_log_error(logger, self.connection_errors)
  416. def handle_invalid_task(self, body, message, exc):
  417. error(INVALID_TASK_ERROR, exc, dump_body(message, body), exc_info=True)
  418. message.reject_log_error(logger, self.connection_errors)
  419. def receive_message(self, body, message):
  420. """Handles incoming messages.
  421. :param body: The message body.
  422. :param message: The kombu message object.
  423. """
  424. try:
  425. name = body['task']
  426. except (KeyError, TypeError):
  427. return self.handle_unknown_message(body, message)
  428. try:
  429. self.strategies[name](message, body, message.ack_log_error)
  430. except KeyError as exc:
  431. self.handle_unknown_task(body, message, exc)
  432. except InvalidTaskError as exc:
  433. self.handle_invalid_task(body, message, exc)
  434. def maybe_conn_error(self, fun):
  435. """Applies function but ignores any connection or channel
  436. errors raised."""
  437. try:
  438. fun()
  439. except (AttributeError, ) + \
  440. self.connection_errors + \
  441. self.channel_errors:
  442. pass
  443. def close_connection(self):
  444. """Closes the current broker connection and all open channels."""
  445. # We must set self.connection to None here, so
  446. # that the green pidbox thread exits.
  447. connection, self.connection = self.connection, None
  448. if self.task_consumer:
  449. debug('Closing consumer channel...')
  450. self.task_consumer = \
  451. self.maybe_conn_error(self.task_consumer.close)
  452. self.stop_pidbox_node()
  453. if connection:
  454. debug('Closing broker connection...')
  455. self.maybe_conn_error(connection.close)
  456. def stop_consumers(self, close_connection=True):
  457. """Stop consuming tasks and broadcast commands, also stops
  458. the heartbeat thread and event dispatcher.
  459. :keyword close_connection: Set to False to skip closing the broker
  460. connection.
  461. """
  462. if not self._state == RUN:
  463. return
  464. if self.heart:
  465. # Stop the heartbeat thread if it's running.
  466. debug('Heart: Going into cardiac arrest...')
  467. self.heart = self.heart.stop()
  468. debug('Cancelling task consumer...')
  469. if self.task_consumer:
  470. self.maybe_conn_error(self.task_consumer.cancel)
  471. if self.event_dispatcher:
  472. debug('Shutting down event dispatcher...')
  473. self.event_dispatcher = \
  474. self.maybe_conn_error(self.event_dispatcher.close)
  475. debug('Cancelling broadcast consumer...')
  476. if self.broadcast_consumer:
  477. self.maybe_conn_error(self.broadcast_consumer.cancel)
  478. if close_connection:
  479. self.close_connection()
  480. def on_decode_error(self, message, exc):
  481. """Callback called if an error occurs while decoding
  482. a message received.
  483. Simply logs the error and acknowledges the message so it
  484. doesn't enter a loop.
  485. :param message: The message with errors.
  486. :param exc: The original exception instance.
  487. """
  488. crit("Can't decode message body: %r (type:%r encoding:%r raw:%r')",
  489. exc, message.content_type, message.content_encoding,
  490. dump_body(message, message.body))
  491. message.ack()
  492. def reset_pidbox_node(self):
  493. """Sets up the process mailbox."""
  494. self.stop_pidbox_node()
  495. # close previously opened channel if any.
  496. if self.pidbox_node.channel:
  497. try:
  498. self.pidbox_node.channel.close()
  499. except self.connection_errors + self.channel_errors:
  500. pass
  501. if self.pool is not None and self.pool.is_green:
  502. return self.pool.spawn_n(self._green_pidbox_node)
  503. self.pidbox_node.channel = self.connection.channel()
  504. self.broadcast_consumer = self.pidbox_node.listen(
  505. callback=self.on_control)
  506. def stop_pidbox_node(self):
  507. if self._pidbox_node_stopped:
  508. self._pidbox_node_shutdown.set()
  509. debug('Waiting for broadcast thread to shutdown...')
  510. self._pidbox_node_stopped.wait()
  511. self._pidbox_node_stopped = self._pidbox_node_shutdown = None
  512. elif self.broadcast_consumer:
  513. debug('Closing broadcast channel...')
  514. self.broadcast_consumer = \
  515. self.maybe_conn_error(self.broadcast_consumer.channel.close)
  516. def _green_pidbox_node(self):
  517. """Sets up the process mailbox when running in a greenlet
  518. environment."""
  519. # THIS CODE IS TERRIBLE
  520. # Luckily work has already started rewriting the Consumer for 4.0.
  521. self._pidbox_node_shutdown = threading.Event()
  522. self._pidbox_node_stopped = threading.Event()
  523. try:
  524. with self._open_connection() as conn:
  525. self.pidbox_node.channel = conn.default_channel
  526. self.broadcast_consumer = self.pidbox_node.listen(
  527. callback=self.on_control)
  528. with self.broadcast_consumer:
  529. while not self._pidbox_node_shutdown.isSet():
  530. try:
  531. conn.drain_events(timeout=1.0)
  532. except socket.timeout:
  533. pass
  534. finally:
  535. self._pidbox_node_stopped.set()
  536. def reset_connection(self):
  537. """Re-establish the broker connection and set up consumers,
  538. heartbeat and the event dispatcher."""
  539. debug('Re-establishing connection to the broker...')
  540. self.stop_consumers()
  541. # Clear internal queues to get rid of old messages.
  542. # They can't be acked anyway, as a delivery tag is specific
  543. # to the current channel.
  544. self.ready_queue.clear()
  545. self.timer.clear()
  546. # Re-establish the broker connection and setup the task consumer.
  547. self.connection = self._open_connection()
  548. debug('Connection established.')
  549. self.task_consumer = self.app.amqp.TaskConsumer(self.connection,
  550. on_decode_error=self.on_decode_error)
  551. # QoS: Reset prefetch window.
  552. self.qos = QoS(self.task_consumer, self.initial_prefetch_count)
  553. self.qos.update()
  554. # Setup the process mailbox.
  555. self.reset_pidbox_node()
  556. # Flush events sent while connection was down.
  557. prev_event_dispatcher = self.event_dispatcher
  558. self.event_dispatcher = self.app.events.Dispatcher(self.connection,
  559. hostname=self.hostname,
  560. enabled=self.send_events)
  561. if prev_event_dispatcher:
  562. self.event_dispatcher.copy_buffer(prev_event_dispatcher)
  563. self.event_dispatcher.flush()
  564. # Restart heartbeat thread.
  565. self.restart_heartbeat()
  566. # reload all task's execution strategies.
  567. self.update_strategies()
  568. # We're back!
  569. self._state = RUN
  570. def restart_heartbeat(self):
  571. """Restart the heartbeat thread.
  572. This thread sends heartbeat events at intervals so monitors
  573. can tell if the worker is off-line/missing.
  574. """
  575. self.heart = Heart(self.timer, self.event_dispatcher)
  576. self.heart.start()
  577. def _open_connection(self):
  578. """Establish the broker connection.
  579. Will retry establishing the connection if the
  580. :setting:`BROKER_CONNECTION_RETRY` setting is enabled
  581. """
  582. # Callback called for each retry while the connection
  583. # can't be established.
  584. def _error_handler(exc, interval):
  585. error('Consumer: Connection Error: %s. '
  586. 'Trying again in %d seconds...', exc, interval)
  587. # remember that the connection is lazy, it won't establish
  588. # until it's needed.
  589. conn = self.app.connection()
  590. if not self.app.conf.BROKER_CONNECTION_RETRY:
  591. # retry disabled, just call connect directly.
  592. conn.connect()
  593. return conn
  594. return conn.ensure_connection(_error_handler,
  595. self.app.conf.BROKER_CONNECTION_MAX_RETRIES,
  596. callback=self.maybe_shutdown)
  597. def stop(self):
  598. """Stop consuming.
  599. Does not close the broker connection, so be sure to call
  600. :meth:`close_connection` when you are finished with it.
  601. """
  602. # Notifies other threads that this instance can't be used
  603. # anymore.
  604. self.close()
  605. debug('Stopping consumers...')
  606. self.stop_consumers(close_connection=False)
  607. def close(self):
  608. self._state = CLOSE
  609. def maybe_shutdown(self):
  610. if state.should_stop:
  611. raise SystemExit()
  612. elif state.should_terminate:
  613. raise SystemTerminate()
  614. def add_task_queue(self, queue, exchange=None, exchange_type=None,
  615. routing_key=None, **options):
  616. cset = self.task_consumer
  617. try:
  618. q = self.app.amqp.queues[queue]
  619. except KeyError:
  620. exchange = queue if exchange is None else exchange
  621. exchange_type = 'direct' if exchange_type is None \
  622. else exchange_type
  623. q = self.app.amqp.queues.select_add(queue,
  624. exchange=exchange,
  625. exchange_type=exchange_type,
  626. routing_key=routing_key, **options)
  627. if not cset.consuming_from(queue):
  628. cset.add_queue(q)
  629. cset.consume()
  630. logger.info('Started consuming from %r', queue)
  631. def cancel_task_queue(self, queue):
  632. self.app.amqp.queues.select_remove(queue)
  633. self.task_consumer.cancel_by_queue(queue)
  634. @property
  635. def info(self):
  636. """Returns information about this consumer instance
  637. as a dict.
  638. This is also the consumer related info returned by
  639. ``celeryctl stats``.
  640. """
  641. conninfo = {}
  642. if self.connection:
  643. conninfo = self.connection.info()
  644. conninfo.pop('password', None) # don't send password.
  645. return {'broker': conninfo, 'prefetch_count': self.qos.value}
  646. class BlockingConsumer(Consumer):
  647. def consume_messages(self):
  648. # receive_message handles incoming messages.
  649. self.task_consumer.register_callback(self.receive_message)
  650. self.task_consumer.consume()
  651. debug('Ready to accept tasks!')
  652. while self._state != CLOSE and self.connection:
  653. self.maybe_shutdown()
  654. if self.qos.prev != self.qos.value: # pragma: no cover
  655. self.qos.update()
  656. try:
  657. self.connection.drain_events(timeout=10.0)
  658. except socket.timeout:
  659. pass
  660. except socket.error:
  661. if self._state != CLOSE: # pragma: no cover
  662. raise