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