consumer.py 27 KB

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