consumer.py 27 KB

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