consumer.py 26 KB

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