consumer.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835
  1. # -*- coding: utf-8 -*-
  2. """
  3. celery.worker.consumer
  4. ~~~~~~~~~~~~~~~~~~~~~~
  5. This module contains the components responsible for consuming messages
  6. from the broker, processing the messages and keeping the broker connections
  7. up and running.
  8. """
  9. from __future__ import absolute_import
  10. import errno
  11. import kombu
  12. import logging
  13. import os
  14. import socket
  15. from collections import defaultdict
  16. from functools import partial
  17. from heapq import heappush
  18. from operator import itemgetter
  19. from time import sleep
  20. from billiard.common import restart_state
  21. from billiard.exceptions import RestartFreqExceeded
  22. from kombu.async.semaphore import DummyLock
  23. from kombu.common import QoS, ignore_errors
  24. from kombu.syn import _detect_environment
  25. from kombu.utils.compat import get_errno
  26. from kombu.utils.encoding import safe_repr, bytes_t
  27. from kombu.utils.limits import TokenBucket
  28. from celery import bootsteps
  29. from celery.app.trace import build_tracer
  30. from celery.canvas import signature
  31. from celery.exceptions import InvalidTaskError
  32. from celery.five import items, values
  33. from celery.utils.functional import noop
  34. from celery.utils.log import get_logger
  35. from celery.utils.text import truncate
  36. from celery.utils.timeutils import humanize_seconds, rate
  37. from . import heartbeat, loops, pidbox
  38. from .state import task_reserved, maybe_shutdown, revoked, reserved_requests
  39. try:
  40. buffer_t = buffer
  41. except NameError: # pragma: no cover
  42. # Py3 does not have buffer, but we only need isinstance.
  43. class buffer_t(object): # noqa
  44. pass
  45. __all__ = [
  46. 'Consumer', 'Connection', 'Events', 'Heart', 'Control',
  47. 'Tasks', 'Evloop', 'Agent', 'Mingle', 'Gossip', 'dump_body',
  48. ]
  49. CLOSE = bootsteps.CLOSE
  50. logger = get_logger(__name__)
  51. debug, info, warn, error, crit = (logger.debug, logger.info, logger.warning,
  52. logger.error, logger.critical)
  53. CONNECTION_RETRY = """\
  54. consumer: Connection to broker lost. \
  55. Trying to re-establish the connection...\
  56. """
  57. CONNECTION_RETRY_STEP = """\
  58. Trying again {when}...\
  59. """
  60. CONNECTION_ERROR = """\
  61. consumer: Cannot connect to %s: %s.
  62. %s
  63. """
  64. CONNECTION_FAILOVER = """\
  65. Will retry using next failover.\
  66. """
  67. UNKNOWN_FORMAT = """\
  68. Received and deleted unknown message. Wrong destination?!?
  69. The full contents of the message body was: %s
  70. """
  71. #: Error message for when an unregistered task is received.
  72. UNKNOWN_TASK_ERROR = """\
  73. Received unregistered task of type %s.
  74. The message has been ignored and discarded.
  75. Did you remember to import the module containing this task?
  76. Or maybe you are using relative imports?
  77. Please see http://bit.ly/gLye1c for more information.
  78. The full contents of the message body was:
  79. %s
  80. """
  81. #: Error message for when an invalid task message is received.
  82. INVALID_TASK_ERROR = """\
  83. Received invalid task message: %s
  84. The message has been ignored and discarded.
  85. Please ensure your message conforms to the task
  86. message protocol as described here: http://bit.ly/hYj41y
  87. The full contents of the message body was:
  88. %s
  89. """
  90. MESSAGE_DECODE_ERROR = """\
  91. Can't decode message body: %r [type:%r encoding:%r headers:%s]
  92. body: %s
  93. """
  94. MESSAGE_REPORT = """\
  95. body: {0}
  96. {{content_type:{1} content_encoding:{2}
  97. delivery_info:{3} headers={4}}}
  98. """
  99. MINGLE_GET_FIELDS = itemgetter('clock', 'revoked')
  100. def dump_body(m, body):
  101. # v2 protocol does not deserialize body
  102. body = m.body if body is None else body
  103. if isinstance(body, buffer_t):
  104. body = bytes_t(body)
  105. return '{0} ({1}b)'.format(truncate(safe_repr(body), 1024),
  106. len(m.body))
  107. class Consumer(object):
  108. Strategies = dict
  109. #: set when consumer is shutting down.
  110. in_shutdown = False
  111. #: Optional callback called the first time the worker
  112. #: is ready to receive tasks.
  113. init_callback = None
  114. #: The current worker pool instance.
  115. pool = None
  116. #: A timer used for high-priority internal tasks, such
  117. #: as sending heartbeats.
  118. timer = None
  119. restart_count = -1 # first start is the same as a restart
  120. class Blueprint(bootsteps.Blueprint):
  121. name = 'Consumer'
  122. default_steps = [
  123. 'celery.worker.consumer:Connection',
  124. 'celery.worker.consumer:Mingle',
  125. 'celery.worker.consumer:Events',
  126. 'celery.worker.consumer:Gossip',
  127. 'celery.worker.consumer:Heart',
  128. 'celery.worker.consumer:Control',
  129. 'celery.worker.consumer:Tasks',
  130. 'celery.worker.consumer:Evloop',
  131. 'celery.worker.consumer:Agent',
  132. ]
  133. def shutdown(self, parent):
  134. self.send_all(parent, 'shutdown')
  135. def __init__(self, on_task_request,
  136. init_callback=noop, hostname=None,
  137. pool=None, app=None,
  138. timer=None, controller=None, hub=None, amqheartbeat=None,
  139. worker_options=None, disable_rate_limits=False,
  140. initial_prefetch_count=2, prefetch_multiplier=1, **kwargs):
  141. self.app = app
  142. self.controller = controller
  143. self.init_callback = init_callback
  144. self.hostname = hostname or socket.gethostname()
  145. self.pid = os.getpid()
  146. self.pool = pool
  147. self.timer = timer
  148. self.strategies = self.Strategies()
  149. conninfo = self.app.connection()
  150. self.connection_errors = conninfo.connection_errors
  151. self.channel_errors = conninfo.channel_errors
  152. self._restart_state = restart_state(maxR=5, maxT=1)
  153. self._does_info = logger.isEnabledFor(logging.INFO)
  154. self.on_task_request = on_task_request
  155. self.on_task_message = set()
  156. self.amqheartbeat_rate = self.app.conf.BROKER_HEARTBEAT_CHECKRATE
  157. self.disable_rate_limits = disable_rate_limits
  158. self.initial_prefetch_count = initial_prefetch_count
  159. self.prefetch_multiplier = prefetch_multiplier
  160. # this contains a tokenbucket for each task type by name, used for
  161. # rate limits, or None if rate limits are disabled for that task.
  162. self.task_buckets = defaultdict(lambda: None)
  163. self.reset_rate_limits()
  164. self.hub = hub
  165. if self.hub:
  166. self.amqheartbeat = amqheartbeat
  167. if self.amqheartbeat is None:
  168. self.amqheartbeat = self.app.conf.BROKER_HEARTBEAT
  169. else:
  170. self.amqheartbeat = 0
  171. if not hasattr(self, 'loop'):
  172. self.loop = loops.asynloop if hub else loops.synloop
  173. if _detect_environment() == 'gevent':
  174. # there's a gevent bug that causes timeouts to not be reset,
  175. # so if the connection timeout is exceeded once, it can NEVER
  176. # connect again.
  177. self.app.conf.BROKER_CONNECTION_TIMEOUT = None
  178. self.steps = []
  179. self.blueprint = self.Blueprint(
  180. app=self.app, on_close=self.on_close,
  181. )
  182. self.blueprint.apply(self, **dict(worker_options or {}, **kwargs))
  183. def bucket_for_task(self, type):
  184. limit = rate(getattr(type, 'rate_limit', None))
  185. return TokenBucket(limit, capacity=1) if limit else None
  186. def reset_rate_limits(self):
  187. self.task_buckets.update(
  188. (n, self.bucket_for_task(t)) for n, t in items(self.app.tasks)
  189. )
  190. def _update_prefetch_count(self, index=0):
  191. """Update prefetch count after pool/shrink grow operations.
  192. Index must be the change in number of processes as a positive
  193. (increasing) or negative (decreasing) number.
  194. .. note::
  195. Currently pool grow operations will end up with an offset
  196. of +1 if the initial size of the pool was 0 (e.g.
  197. ``--autoscale=1,0``).
  198. """
  199. num_processes = self.pool.num_processes
  200. if not self.initial_prefetch_count or not num_processes:
  201. return # prefetch disabled
  202. self.initial_prefetch_count = (
  203. self.pool.num_processes * self.prefetch_multiplier
  204. )
  205. return self._update_qos_eventually(index)
  206. def _update_qos_eventually(self, index):
  207. return (self.qos.decrement_eventually if index < 0
  208. else self.qos.increment_eventually)(
  209. abs(index) * self.prefetch_multiplier)
  210. def _limit_task(self, request, bucket, tokens):
  211. if not bucket.can_consume(tokens):
  212. hold = bucket.expected_time(tokens)
  213. self.timer.call_after(
  214. hold, self._limit_task, (request, bucket, tokens),
  215. )
  216. else:
  217. task_reserved(request)
  218. self.on_task_request(request)
  219. def start(self):
  220. blueprint, loop = self.blueprint, self.loop
  221. while blueprint.state != CLOSE:
  222. self.restart_count += 1
  223. maybe_shutdown()
  224. try:
  225. blueprint.start(self)
  226. except self.connection_errors as exc:
  227. if isinstance(exc, OSError) and get_errno(exc) == errno.EMFILE:
  228. raise # Too many open files
  229. maybe_shutdown()
  230. try:
  231. self._restart_state.step()
  232. except RestartFreqExceeded as exc:
  233. crit('Frequent restarts detected: %r', exc, exc_info=1)
  234. sleep(1)
  235. if blueprint.state != CLOSE and self.connection:
  236. warn(CONNECTION_RETRY, exc_info=True)
  237. try:
  238. self.connection.collect()
  239. except Exception:
  240. pass
  241. self.on_close()
  242. blueprint.restart(self)
  243. def register_with_event_loop(self, hub):
  244. self.blueprint.send_all(
  245. self, 'register_with_event_loop', args=(hub, ),
  246. description='Hub.register',
  247. )
  248. def shutdown(self):
  249. self.in_shutdown = True
  250. self.blueprint.shutdown(self)
  251. def stop(self):
  252. self.blueprint.stop(self)
  253. def on_ready(self):
  254. callback, self.init_callback = self.init_callback, None
  255. if callback:
  256. callback(self)
  257. def loop_args(self):
  258. return (self, self.connection, self.task_consumer,
  259. self.blueprint, self.hub, self.qos, self.amqheartbeat,
  260. self.app.clock, self.amqheartbeat_rate)
  261. def on_decode_error(self, message, exc):
  262. """Callback called if an error occurs while decoding
  263. a message received.
  264. Simply logs the error and acknowledges the message so it
  265. doesn't enter a loop.
  266. :param message: The message with errors.
  267. :param exc: The original exception instance.
  268. """
  269. crit(MESSAGE_DECODE_ERROR,
  270. exc, message.content_type, message.content_encoding,
  271. safe_repr(message.headers), dump_body(message, message.body),
  272. exc_info=1)
  273. message.ack()
  274. def on_close(self):
  275. # Clear internal queues to get rid of old messages.
  276. # They can't be acked anyway, as a delivery tag is specific
  277. # to the current channel.
  278. if self.controller and self.controller.semaphore:
  279. self.controller.semaphore.clear()
  280. if self.timer:
  281. self.timer.clear()
  282. reserved_requests.clear()
  283. if self.pool and self.pool.flush:
  284. self.pool.flush()
  285. def connect(self):
  286. """Establish the broker connection.
  287. Will retry establishing the connection if the
  288. :setting:`BROKER_CONNECTION_RETRY` setting is enabled
  289. """
  290. conn = self.app.connection(heartbeat=self.amqheartbeat)
  291. # Callback called for each retry while the connection
  292. # can't be established.
  293. def _error_handler(exc, interval, next_step=CONNECTION_RETRY_STEP):
  294. if getattr(conn, 'alt', None) and interval == 0:
  295. next_step = CONNECTION_FAILOVER
  296. error(CONNECTION_ERROR, conn.as_uri(), exc,
  297. next_step.format(when=humanize_seconds(interval, 'in', ' ')))
  298. # remember that the connection is lazy, it won't establish
  299. # until needed.
  300. if not self.app.conf.BROKER_CONNECTION_RETRY:
  301. # retry disabled, just call connect directly.
  302. conn.connect()
  303. return conn
  304. conn = conn.ensure_connection(
  305. _error_handler, self.app.conf.BROKER_CONNECTION_MAX_RETRIES,
  306. callback=maybe_shutdown,
  307. )
  308. if self.hub:
  309. conn.transport.register_with_event_loop(conn.connection, self.hub)
  310. return conn
  311. def add_task_queue(self, queue, exchange=None, exchange_type=None,
  312. routing_key=None, **options):
  313. cset = self.task_consumer
  314. queues = self.app.amqp.queues
  315. # Must use in' here, as __missing__ will automatically
  316. # create queues when CELERY_CREATE_MISSING_QUEUES is enabled.
  317. # (Issue #1079)
  318. if queue in queues:
  319. q = queues[queue]
  320. else:
  321. exchange = queue if exchange is None else exchange
  322. exchange_type = ('direct' if exchange_type is None
  323. else exchange_type)
  324. q = queues.select_add(queue,
  325. exchange=exchange,
  326. exchange_type=exchange_type,
  327. routing_key=routing_key, **options)
  328. if not cset.consuming_from(queue):
  329. cset.add_queue(q)
  330. cset.consume()
  331. info('Started consuming from %s', queue)
  332. def cancel_task_queue(self, queue):
  333. info('Cancelling queue %s', queue)
  334. self.app.amqp.queues.deselect(queue)
  335. self.task_consumer.cancel_by_queue(queue)
  336. def apply_eta_task(self, task):
  337. """Method called by the timer to apply a task with an
  338. ETA/countdown."""
  339. task_reserved(task)
  340. self.on_task_request(task)
  341. self.qos.decrement_eventually()
  342. def _message_report(self, body, message):
  343. return MESSAGE_REPORT.format(dump_body(message, body),
  344. safe_repr(message.content_type),
  345. safe_repr(message.content_encoding),
  346. safe_repr(message.delivery_info),
  347. safe_repr(message.headers))
  348. def on_unknown_message(self, body, message):
  349. warn(UNKNOWN_FORMAT, self._message_report(body, message))
  350. message.reject_log_error(logger, self.connection_errors)
  351. def on_unknown_task(self, body, message, exc):
  352. error(UNKNOWN_TASK_ERROR, exc, dump_body(message, body), exc_info=True)
  353. message.reject_log_error(logger, self.connection_errors)
  354. def on_invalid_task(self, body, message, exc):
  355. error(INVALID_TASK_ERROR, exc, dump_body(message, body), exc_info=True)
  356. message.reject_log_error(logger, self.connection_errors)
  357. def update_strategies(self):
  358. loader = self.app.loader
  359. for name, task in items(self.app.tasks):
  360. self.strategies[name] = task.start_strategy(self.app, self)
  361. task.__trace__ = build_tracer(name, task, loader, self.hostname,
  362. app=self.app)
  363. def create_task_handler(self):
  364. strategies = self.strategies
  365. on_unknown_message = self.on_unknown_message
  366. on_unknown_task = self.on_unknown_task
  367. on_invalid_task = self.on_invalid_task
  368. callbacks = self.on_task_message
  369. def on_task_received(message):
  370. # payload will only be set for v1 protocol, since v2
  371. # will defer deserializing the message body to the pool.
  372. payload = None
  373. try:
  374. type_ = message.headers['c_type'] # protocol v2
  375. except TypeError:
  376. return on_unknown_message(None, message)
  377. except KeyError:
  378. payload = message.payload
  379. try:
  380. type_ = payload['task'] # protocol v1
  381. except (TypeError, KeyError):
  382. return on_unknown_message(payload, message)
  383. try:
  384. strategies[type_](
  385. message, None,
  386. message.ack_log_error, message.reject_log_error, callbacks,
  387. )
  388. except KeyError as exc:
  389. on_unknown_task(payload, message, exc)
  390. except InvalidTaskError as exc:
  391. on_invalid_task(payload, message, exc)
  392. return on_task_received
  393. def __repr__(self):
  394. return '<Consumer: {self.hostname} ({state})>'.format(
  395. self=self, state=self.blueprint.human_state(),
  396. )
  397. class Connection(bootsteps.StartStopStep):
  398. def __init__(self, c, **kwargs):
  399. c.connection = None
  400. def start(self, c):
  401. c.connection = c.connect()
  402. info('Connected to %s', c.connection.as_uri())
  403. def shutdown(self, c):
  404. # We must set self.connection to None here, so
  405. # that the green pidbox thread exits.
  406. connection, c.connection = c.connection, None
  407. if connection:
  408. ignore_errors(connection, connection.close)
  409. def info(self, c, params='N/A'):
  410. if c.connection:
  411. params = c.connection.info()
  412. params.pop('password', None) # don't send password.
  413. return {'broker': params}
  414. class Events(bootsteps.StartStopStep):
  415. requires = (Connection, )
  416. def __init__(self, c, send_events=None, **kwargs):
  417. self.send_events = True
  418. self.groups = None if send_events else ['worker']
  419. c.event_dispatcher = None
  420. def start(self, c):
  421. # flush events sent while connection was down.
  422. prev = self._close(c)
  423. dis = c.event_dispatcher = c.app.events.Dispatcher(
  424. c.connect(), hostname=c.hostname,
  425. enabled=self.send_events, groups=self.groups,
  426. )
  427. if prev:
  428. dis.extend_buffer(prev)
  429. dis.flush()
  430. def stop(self, c):
  431. pass
  432. def _close(self, c):
  433. if c.event_dispatcher:
  434. dispatcher = c.event_dispatcher
  435. # remember changes from remote control commands:
  436. self.groups = dispatcher.groups
  437. # close custom connection
  438. if dispatcher.connection:
  439. ignore_errors(c, dispatcher.connection.close)
  440. ignore_errors(c, dispatcher.close)
  441. c.event_dispatcher = None
  442. return dispatcher
  443. def shutdown(self, c):
  444. self._close(c)
  445. class Heart(bootsteps.StartStopStep):
  446. requires = (Events, )
  447. def __init__(self, c, without_heartbeat=False, heartbeat_interval=None,
  448. **kwargs):
  449. self.enabled = not without_heartbeat
  450. self.heartbeat_interval = heartbeat_interval
  451. c.heart = None
  452. def start(self, c):
  453. c.heart = heartbeat.Heart(
  454. c.timer, c.event_dispatcher, self.heartbeat_interval,
  455. )
  456. c.heart.start()
  457. def stop(self, c):
  458. c.heart = c.heart and c.heart.stop()
  459. shutdown = stop
  460. class Mingle(bootsteps.StartStopStep):
  461. label = 'Mingle'
  462. requires = (Events, )
  463. compatible_transports = {'amqp', 'redis'}
  464. def __init__(self, c, without_mingle=False, **kwargs):
  465. self.enabled = not without_mingle and self.compatible_transport(c.app)
  466. def compatible_transport(self, app):
  467. with app.connection() as conn:
  468. return conn.transport.driver_type in self.compatible_transports
  469. def start(self, c):
  470. info('mingle: searching for neighbors')
  471. I = c.app.control.inspect(timeout=1.0, connection=c.connection)
  472. replies = I.hello(c.hostname, revoked._data) or {}
  473. replies.pop(c.hostname, None)
  474. if replies:
  475. info('mingle: sync with %s nodes',
  476. len([reply for reply, value in items(replies) if value]))
  477. for reply in values(replies):
  478. if reply:
  479. try:
  480. other_clock, other_revoked = MINGLE_GET_FIELDS(reply)
  481. except KeyError: # reply from pre-3.1 worker
  482. pass
  483. else:
  484. c.app.clock.adjust(other_clock)
  485. revoked.update(other_revoked)
  486. info('mingle: sync complete')
  487. else:
  488. info('mingle: all alone')
  489. class Tasks(bootsteps.StartStopStep):
  490. requires = (Mingle, )
  491. def __init__(self, c, **kwargs):
  492. c.task_consumer = c.qos = None
  493. def start(self, c):
  494. c.update_strategies()
  495. # - RabbitMQ 3.3 completely redefines how basic_qos works..
  496. # This will detect if the new qos smenatics is in effect,
  497. # and if so make sure the 'apply_global' flag is set on qos updates.
  498. qos_global = not c.connection.qos_semantics_matches_spec
  499. # set initial prefetch count
  500. c.connection.default_channel.basic_qos(
  501. 0, c.initial_prefetch_count, qos_global,
  502. )
  503. c.task_consumer = c.app.amqp.TaskConsumer(
  504. c.connection, on_decode_error=c.on_decode_error,
  505. )
  506. def set_prefetch_count(prefetch_count):
  507. return c.task_consumer.qos(
  508. prefetch_count=prefetch_count,
  509. apply_global=qos_global,
  510. )
  511. c.qos = QoS(set_prefetch_count, c.initial_prefetch_count)
  512. def stop(self, c):
  513. if c.task_consumer:
  514. debug('Cancelling task consumer...')
  515. ignore_errors(c, c.task_consumer.cancel)
  516. def shutdown(self, c):
  517. if c.task_consumer:
  518. self.stop(c)
  519. debug('Closing consumer channel...')
  520. ignore_errors(c, c.task_consumer.close)
  521. c.task_consumer = None
  522. def info(self, c):
  523. return {'prefetch_count': c.qos.value if c.qos else 'N/A'}
  524. class Agent(bootsteps.StartStopStep):
  525. conditional = True
  526. requires = (Connection, )
  527. def __init__(self, c, **kwargs):
  528. self.agent_cls = self.enabled = c.app.conf.CELERYD_AGENT
  529. def create(self, c):
  530. agent = c.agent = self.instantiate(self.agent_cls, c.connection)
  531. return agent
  532. class Control(bootsteps.StartStopStep):
  533. requires = (Tasks, )
  534. def __init__(self, c, **kwargs):
  535. self.is_green = c.pool is not None and c.pool.is_green
  536. self.box = (pidbox.gPidbox if self.is_green else pidbox.Pidbox)(c)
  537. self.start = self.box.start
  538. self.stop = self.box.stop
  539. self.shutdown = self.box.shutdown
  540. def include_if(self, c):
  541. return c.app.conf.CELERY_ENABLE_REMOTE_CONTROL
  542. class Gossip(bootsteps.ConsumerStep):
  543. label = 'Gossip'
  544. requires = (Mingle, )
  545. _cons_stamp_fields = itemgetter(
  546. 'id', 'clock', 'hostname', 'pid', 'topic', 'action', 'cver',
  547. )
  548. compatible_transports = {'amqp', 'redis'}
  549. def __init__(self, c, without_gossip=False, interval=5.0, **kwargs):
  550. self.enabled = not without_gossip and self.compatible_transport(c.app)
  551. self.app = c.app
  552. c.gossip = self
  553. self.Receiver = c.app.events.Receiver
  554. self.hostname = c.hostname
  555. self.full_hostname = '.'.join([self.hostname, str(c.pid)])
  556. self.timer = c.timer
  557. if self.enabled:
  558. self.state = c.app.events.State(
  559. on_node_join=self.on_node_join,
  560. on_node_leave=self.on_node_leave,
  561. max_tasks_in_memory=1,
  562. )
  563. if c.hub:
  564. c._mutex = DummyLock()
  565. self.update_state = self.state.event
  566. self.interval = interval
  567. self._tref = None
  568. self.consensus_requests = defaultdict(list)
  569. self.consensus_replies = {}
  570. self.event_handlers = {
  571. 'worker.elect': self.on_elect,
  572. 'worker.elect.ack': self.on_elect_ack,
  573. }
  574. self.clock = c.app.clock
  575. self.election_handlers = {
  576. 'task': self.call_task
  577. }
  578. def compatible_transport(self, app):
  579. with app.connection() as conn:
  580. return conn.transport.driver_type in self.compatible_transports
  581. def election(self, id, topic, action=None):
  582. self.consensus_replies[id] = []
  583. self.dispatcher.send(
  584. 'worker-elect',
  585. id=id, topic=topic, action=action, cver=1,
  586. )
  587. def call_task(self, task):
  588. try:
  589. signature(task, app=self.app).apply_async()
  590. except Exception as exc:
  591. error('Could not call task: %r', exc, exc_info=1)
  592. def on_elect(self, event):
  593. try:
  594. (id_, clock, hostname, pid,
  595. topic, action, _) = self._cons_stamp_fields(event)
  596. except KeyError as exc:
  597. return error('election request missing field %s', exc, exc_info=1)
  598. heappush(
  599. self.consensus_requests[id_],
  600. (clock, '%s.%s' % (hostname, pid), topic, action),
  601. )
  602. self.dispatcher.send('worker-elect-ack', id=id_)
  603. def start(self, c):
  604. super(Gossip, self).start(c)
  605. self.dispatcher = c.event_dispatcher
  606. def on_elect_ack(self, event):
  607. id = event['id']
  608. try:
  609. replies = self.consensus_replies[id]
  610. except KeyError:
  611. return # not for us
  612. alive_workers = self.state.alive_workers()
  613. replies.append(event['hostname'])
  614. if len(replies) >= len(alive_workers):
  615. _, leader, topic, action = self.clock.sort_heap(
  616. self.consensus_requests[id],
  617. )
  618. if leader == self.full_hostname:
  619. info('I won the election %r', id)
  620. try:
  621. handler = self.election_handlers[topic]
  622. except KeyError:
  623. error('Unknown election topic %r', topic, exc_info=1)
  624. else:
  625. handler(action)
  626. else:
  627. info('node %s elected for %r', leader, id)
  628. self.consensus_requests.pop(id, None)
  629. self.consensus_replies.pop(id, None)
  630. def on_node_join(self, worker):
  631. debug('%s joined the party', worker.hostname)
  632. def on_node_leave(self, worker):
  633. debug('%s left', worker.hostname)
  634. def on_node_lost(self, worker):
  635. info('missed heartbeat from %s', worker.hostname)
  636. def register_timer(self):
  637. if self._tref is not None:
  638. self._tref.cancel()
  639. self._tref = self.timer.call_repeatedly(self.interval, self.periodic)
  640. def periodic(self):
  641. workers = self.state.workers
  642. dirty = set()
  643. for worker in values(workers):
  644. if not worker.alive:
  645. dirty.add(worker)
  646. self.on_node_lost(worker)
  647. for worker in dirty:
  648. workers.pop(worker.hostname, None)
  649. def get_consumers(self, channel):
  650. self.register_timer()
  651. ev = self.Receiver(channel, routing_key='worker.#')
  652. return [kombu.Consumer(
  653. channel,
  654. queues=[ev.queue],
  655. on_message=partial(self.on_message, ev.event_from_message),
  656. no_ack=True
  657. )]
  658. def on_message(self, prepare, message):
  659. _type = message.delivery_info['routing_key']
  660. # For redis when `fanout_patterns=False` (See Issue #1882)
  661. if _type.split('.', 1)[0] == 'task':
  662. return
  663. try:
  664. handler = self.event_handlers[_type]
  665. except KeyError:
  666. pass
  667. else:
  668. return handler(message.payload)
  669. hostname = (message.headers.get('hostname') or
  670. message.payload['hostname'])
  671. if hostname != self.hostname:
  672. type, event = prepare(message.payload)
  673. obj, subject = self.update_state(event)
  674. else:
  675. self.clock.forward()
  676. class Evloop(bootsteps.StartStopStep):
  677. label = 'event loop'
  678. last = True
  679. def start(self, c):
  680. self.patch_all(c)
  681. c.loop(*c.loop_args())
  682. def patch_all(self, c):
  683. c.qos._mutex = DummyLock()