m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1533 lines
67 KiB

6 months ago
  1. from __future__ import absolute_import, division
  2. import copy
  3. import errno
  4. import io
  5. import logging
  6. from random import shuffle, uniform
  7. # selectors in stdlib as of py3.4
  8. try:
  9. import selectors # pylint: disable=import-error
  10. except ImportError:
  11. # vendored backport module
  12. from kafka.vendor import selectors34 as selectors
  13. import socket
  14. import struct
  15. import threading
  16. import time
  17. from kafka.vendor import six
  18. import kafka.errors as Errors
  19. from kafka.future import Future
  20. from kafka.metrics.stats import Avg, Count, Max, Rate
  21. from kafka.oauth.abstract import AbstractTokenProvider
  22. from kafka.protocol.admin import SaslHandShakeRequest, DescribeAclsRequest_v2
  23. from kafka.protocol.commit import OffsetFetchRequest
  24. from kafka.protocol.offset import OffsetRequest
  25. from kafka.protocol.produce import ProduceRequest
  26. from kafka.protocol.metadata import MetadataRequest
  27. from kafka.protocol.fetch import FetchRequest
  28. from kafka.protocol.parser import KafkaProtocol
  29. from kafka.protocol.types import Int32, Int8
  30. from kafka.scram import ScramClient
  31. from kafka.version import __version__
  32. if six.PY2:
  33. ConnectionError = socket.error
  34. TimeoutError = socket.error
  35. BlockingIOError = Exception
  36. log = logging.getLogger(__name__)
  37. DEFAULT_KAFKA_PORT = 9092
  38. SASL_QOP_AUTH = 1
  39. SASL_QOP_AUTH_INT = 2
  40. SASL_QOP_AUTH_CONF = 4
  41. try:
  42. import ssl
  43. ssl_available = True
  44. try:
  45. SSLEOFError = ssl.SSLEOFError
  46. SSLWantReadError = ssl.SSLWantReadError
  47. SSLWantWriteError = ssl.SSLWantWriteError
  48. SSLZeroReturnError = ssl.SSLZeroReturnError
  49. except AttributeError:
  50. # support older ssl libraries
  51. log.warning('Old SSL module detected.'
  52. ' SSL error handling may not operate cleanly.'
  53. ' Consider upgrading to Python 3.3 or 2.7.9')
  54. SSLEOFError = ssl.SSLError
  55. SSLWantReadError = ssl.SSLError
  56. SSLWantWriteError = ssl.SSLError
  57. SSLZeroReturnError = ssl.SSLError
  58. except ImportError:
  59. # support Python without ssl libraries
  60. ssl_available = False
  61. class SSLWantReadError(Exception):
  62. pass
  63. class SSLWantWriteError(Exception):
  64. pass
  65. # needed for SASL_GSSAPI authentication:
  66. try:
  67. import gssapi
  68. from gssapi.raw.misc import GSSError
  69. except ImportError:
  70. #no gssapi available, will disable gssapi mechanism
  71. gssapi = None
  72. GSSError = None
  73. AFI_NAMES = {
  74. socket.AF_UNSPEC: "unspecified",
  75. socket.AF_INET: "IPv4",
  76. socket.AF_INET6: "IPv6",
  77. }
  78. class ConnectionStates(object):
  79. DISCONNECTING = '<disconnecting>'
  80. DISCONNECTED = '<disconnected>'
  81. CONNECTING = '<connecting>'
  82. HANDSHAKE = '<handshake>'
  83. CONNECTED = '<connected>'
  84. AUTHENTICATING = '<authenticating>'
  85. class BrokerConnection(object):
  86. """Initialize a Kafka broker connection
  87. Keyword Arguments:
  88. client_id (str): a name for this client. This string is passed in
  89. each request to servers and can be used to identify specific
  90. server-side log entries that correspond to this client. Also
  91. submitted to GroupCoordinator for logging with respect to
  92. consumer group administration. Default: 'kafka-python-{version}'
  93. reconnect_backoff_ms (int): The amount of time in milliseconds to
  94. wait before attempting to reconnect to a given host.
  95. Default: 50.
  96. reconnect_backoff_max_ms (int): The maximum amount of time in
  97. milliseconds to backoff/wait when reconnecting to a broker that has
  98. repeatedly failed to connect. If provided, the backoff per host
  99. will increase exponentially for each consecutive connection
  100. failure, up to this maximum. Once the maximum is reached,
  101. reconnection attempts will continue periodically with this fixed
  102. rate. To avoid connection storms, a randomization factor of 0.2
  103. will be applied to the backoff resulting in a random range between
  104. 20% below and 20% above the computed value. Default: 1000.
  105. request_timeout_ms (int): Client request timeout in milliseconds.
  106. Default: 30000.
  107. max_in_flight_requests_per_connection (int): Requests are pipelined
  108. to kafka brokers up to this number of maximum requests per
  109. broker connection. Default: 5.
  110. receive_buffer_bytes (int): The size of the TCP receive buffer
  111. (SO_RCVBUF) to use when reading data. Default: None (relies on
  112. system defaults). Java client defaults to 32768.
  113. send_buffer_bytes (int): The size of the TCP send buffer
  114. (SO_SNDBUF) to use when sending data. Default: None (relies on
  115. system defaults). Java client defaults to 131072.
  116. socket_options (list): List of tuple-arguments to socket.setsockopt
  117. to apply to broker connection sockets. Default:
  118. [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]
  119. security_protocol (str): Protocol used to communicate with brokers.
  120. Valid values are: PLAINTEXT, SSL, SASL_PLAINTEXT, SASL_SSL.
  121. Default: PLAINTEXT.
  122. ssl_context (ssl.SSLContext): pre-configured SSLContext for wrapping
  123. socket connections. If provided, all other ssl_* configurations
  124. will be ignored. Default: None.
  125. ssl_check_hostname (bool): flag to configure whether ssl handshake
  126. should verify that the certificate matches the brokers hostname.
  127. default: True.
  128. ssl_cafile (str): optional filename of ca file to use in certificate
  129. verification. default: None.
  130. ssl_certfile (str): optional filename of file in pem format containing
  131. the client certificate, as well as any ca certificates needed to
  132. establish the certificate's authenticity. default: None.
  133. ssl_keyfile (str): optional filename containing the client private key.
  134. default: None.
  135. ssl_password (callable, str, bytes, bytearray): optional password or
  136. callable function that returns a password, for decrypting the
  137. client private key. Default: None.
  138. ssl_crlfile (str): optional filename containing the CRL to check for
  139. certificate expiration. By default, no CRL check is done. When
  140. providing a file, only the leaf certificate will be checked against
  141. this CRL. The CRL can only be checked with Python 3.4+ or 2.7.9+.
  142. default: None.
  143. ssl_ciphers (str): optionally set the available ciphers for ssl
  144. connections. It should be a string in the OpenSSL cipher list
  145. format. If no cipher can be selected (because compile-time options
  146. or other configuration forbids use of all the specified ciphers),
  147. an ssl.SSLError will be raised. See ssl.SSLContext.set_ciphers
  148. api_version (tuple): Specify which Kafka API version to use.
  149. Accepted values are: (0, 8, 0), (0, 8, 1), (0, 8, 2), (0, 9),
  150. (0, 10). Default: (0, 8, 2)
  151. api_version_auto_timeout_ms (int): number of milliseconds to throw a
  152. timeout exception from the constructor when checking the broker
  153. api version. Only applies if api_version is None
  154. selector (selectors.BaseSelector): Provide a specific selector
  155. implementation to use for I/O multiplexing.
  156. Default: selectors.DefaultSelector
  157. state_change_callback (callable): function to be called when the
  158. connection state changes from CONNECTING to CONNECTED etc.
  159. metrics (kafka.metrics.Metrics): Optionally provide a metrics
  160. instance for capturing network IO stats. Default: None.
  161. metric_group_prefix (str): Prefix for metric names. Default: ''
  162. sasl_mechanism (str): Authentication mechanism when security_protocol
  163. is configured for SASL_PLAINTEXT or SASL_SSL. Valid values are:
  164. PLAIN, GSSAPI, OAUTHBEARER, SCRAM-SHA-256, SCRAM-SHA-512.
  165. sasl_plain_username (str): username for sasl PLAIN and SCRAM authentication.
  166. Required if sasl_mechanism is PLAIN or one of the SCRAM mechanisms.
  167. sasl_plain_password (str): password for sasl PLAIN and SCRAM authentication.
  168. Required if sasl_mechanism is PLAIN or one of the SCRAM mechanisms.
  169. sasl_kerberos_service_name (str): Service name to include in GSSAPI
  170. sasl mechanism handshake. Default: 'kafka'
  171. sasl_kerberos_domain_name (str): kerberos domain name to use in GSSAPI
  172. sasl mechanism handshake. Default: one of bootstrap servers
  173. sasl_oauth_token_provider (AbstractTokenProvider): OAuthBearer token provider
  174. instance. (See kafka.oauth.abstract). Default: None
  175. """
  176. DEFAULT_CONFIG = {
  177. 'client_id': 'kafka-python-' + __version__,
  178. 'node_id': 0,
  179. 'request_timeout_ms': 30000,
  180. 'reconnect_backoff_ms': 50,
  181. 'reconnect_backoff_max_ms': 1000,
  182. 'max_in_flight_requests_per_connection': 5,
  183. 'receive_buffer_bytes': None,
  184. 'send_buffer_bytes': None,
  185. 'socket_options': [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)],
  186. 'sock_chunk_bytes': 4096, # undocumented experimental option
  187. 'sock_chunk_buffer_count': 1000, # undocumented experimental option
  188. 'security_protocol': 'PLAINTEXT',
  189. 'ssl_context': None,
  190. 'ssl_check_hostname': True,
  191. 'ssl_cafile': None,
  192. 'ssl_certfile': None,
  193. 'ssl_keyfile': None,
  194. 'ssl_crlfile': None,
  195. 'ssl_password': None,
  196. 'ssl_ciphers': None,
  197. 'api_version': (0, 8, 2), # default to most restrictive
  198. 'selector': selectors.DefaultSelector,
  199. 'state_change_callback': lambda node_id, sock, conn: True,
  200. 'metrics': None,
  201. 'metric_group_prefix': '',
  202. 'sasl_mechanism': None,
  203. 'sasl_plain_username': None,
  204. 'sasl_plain_password': None,
  205. 'sasl_kerberos_service_name': 'kafka',
  206. 'sasl_kerberos_domain_name': None,
  207. 'sasl_oauth_token_provider': None
  208. }
  209. SECURITY_PROTOCOLS = ('PLAINTEXT', 'SSL', 'SASL_PLAINTEXT', 'SASL_SSL')
  210. SASL_MECHANISMS = ('PLAIN', 'GSSAPI', 'OAUTHBEARER', "SCRAM-SHA-256", "SCRAM-SHA-512")
  211. def __init__(self, host, port, afi, **configs):
  212. self.host = host
  213. self.port = port
  214. self.afi = afi
  215. self._sock_afi = afi
  216. self._sock_addr = None
  217. self._api_versions = None
  218. self.config = copy.copy(self.DEFAULT_CONFIG)
  219. for key in self.config:
  220. if key in configs:
  221. self.config[key] = configs[key]
  222. self.node_id = self.config.pop('node_id')
  223. if self.config['receive_buffer_bytes'] is not None:
  224. self.config['socket_options'].append(
  225. (socket.SOL_SOCKET, socket.SO_RCVBUF,
  226. self.config['receive_buffer_bytes']))
  227. if self.config['send_buffer_bytes'] is not None:
  228. self.config['socket_options'].append(
  229. (socket.SOL_SOCKET, socket.SO_SNDBUF,
  230. self.config['send_buffer_bytes']))
  231. assert self.config['security_protocol'] in self.SECURITY_PROTOCOLS, (
  232. 'security_protocol must be in ' + ', '.join(self.SECURITY_PROTOCOLS))
  233. if self.config['security_protocol'] in ('SSL', 'SASL_SSL'):
  234. assert ssl_available, "Python wasn't built with SSL support"
  235. if self.config['security_protocol'] in ('SASL_PLAINTEXT', 'SASL_SSL'):
  236. assert self.config['sasl_mechanism'] in self.SASL_MECHANISMS, (
  237. 'sasl_mechanism must be in ' + ', '.join(self.SASL_MECHANISMS))
  238. if self.config['sasl_mechanism'] in ('PLAIN', 'SCRAM-SHA-256', 'SCRAM-SHA-512'):
  239. assert self.config['sasl_plain_username'] is not None, (
  240. 'sasl_plain_username required for PLAIN or SCRAM sasl'
  241. )
  242. assert self.config['sasl_plain_password'] is not None, (
  243. 'sasl_plain_password required for PLAIN or SCRAM sasl'
  244. )
  245. if self.config['sasl_mechanism'] == 'GSSAPI':
  246. assert gssapi is not None, 'GSSAPI lib not available'
  247. assert self.config['sasl_kerberos_service_name'] is not None, 'sasl_kerberos_service_name required for GSSAPI sasl'
  248. if self.config['sasl_mechanism'] == 'OAUTHBEARER':
  249. token_provider = self.config['sasl_oauth_token_provider']
  250. assert token_provider is not None, 'sasl_oauth_token_provider required for OAUTHBEARER sasl'
  251. assert callable(getattr(token_provider, "token", None)), 'sasl_oauth_token_provider must implement method #token()'
  252. # This is not a general lock / this class is not generally thread-safe yet
  253. # However, to avoid pushing responsibility for maintaining
  254. # per-connection locks to the upstream client, we will use this lock to
  255. # make sure that access to the protocol buffer is synchronized
  256. # when sends happen on multiple threads
  257. self._lock = threading.Lock()
  258. # the protocol parser instance manages actual tracking of the
  259. # sequence of in-flight requests to responses, which should
  260. # function like a FIFO queue. For additional request data,
  261. # including tracking request futures and timestamps, we
  262. # can use a simple dictionary of correlation_id => request data
  263. self.in_flight_requests = dict()
  264. self._protocol = KafkaProtocol(
  265. client_id=self.config['client_id'],
  266. api_version=self.config['api_version'])
  267. self.state = ConnectionStates.DISCONNECTED
  268. self._reset_reconnect_backoff()
  269. self._sock = None
  270. self._send_buffer = b''
  271. self._ssl_context = None
  272. if self.config['ssl_context'] is not None:
  273. self._ssl_context = self.config['ssl_context']
  274. self._sasl_auth_future = None
  275. self.last_attempt = 0
  276. self._gai = []
  277. self._sensors = None
  278. if self.config['metrics']:
  279. self._sensors = BrokerConnectionMetrics(self.config['metrics'],
  280. self.config['metric_group_prefix'],
  281. self.node_id)
  282. def _dns_lookup(self):
  283. self._gai = dns_lookup(self.host, self.port, self.afi)
  284. if not self._gai:
  285. log.error('DNS lookup failed for %s:%i (%s)',
  286. self.host, self.port, self.afi)
  287. return False
  288. return True
  289. def _next_afi_sockaddr(self):
  290. if not self._gai:
  291. if not self._dns_lookup():
  292. return
  293. afi, _, __, ___, sockaddr = self._gai.pop(0)
  294. return (afi, sockaddr)
  295. def connect_blocking(self, timeout=float('inf')):
  296. if self.connected():
  297. return True
  298. timeout += time.time()
  299. # First attempt to perform dns lookup
  300. # note that the underlying interface, socket.getaddrinfo,
  301. # has no explicit timeout so we may exceed the user-specified timeout
  302. self._dns_lookup()
  303. # Loop once over all returned dns entries
  304. selector = None
  305. while self._gai:
  306. while time.time() < timeout:
  307. self.connect()
  308. if self.connected():
  309. if selector is not None:
  310. selector.close()
  311. return True
  312. elif self.connecting():
  313. if selector is None:
  314. selector = self.config['selector']()
  315. selector.register(self._sock, selectors.EVENT_WRITE)
  316. selector.select(1)
  317. elif self.disconnected():
  318. if selector is not None:
  319. selector.close()
  320. selector = None
  321. break
  322. else:
  323. break
  324. return False
  325. def connect(self):
  326. """Attempt to connect and return ConnectionState"""
  327. if self.state is ConnectionStates.DISCONNECTED and not self.blacked_out():
  328. self.last_attempt = time.time()
  329. next_lookup = self._next_afi_sockaddr()
  330. if not next_lookup:
  331. self.close(Errors.KafkaConnectionError('DNS failure'))
  332. return self.state
  333. else:
  334. log.debug('%s: creating new socket', self)
  335. assert self._sock is None
  336. self._sock_afi, self._sock_addr = next_lookup
  337. self._sock = socket.socket(self._sock_afi, socket.SOCK_STREAM)
  338. for option in self.config['socket_options']:
  339. log.debug('%s: setting socket option %s', self, option)
  340. self._sock.setsockopt(*option)
  341. self._sock.setblocking(False)
  342. self.state = ConnectionStates.CONNECTING
  343. self.config['state_change_callback'](self.node_id, self._sock, self)
  344. log.info('%s: connecting to %s:%d [%s %s]', self, self.host,
  345. self.port, self._sock_addr, AFI_NAMES[self._sock_afi])
  346. if self.state is ConnectionStates.CONNECTING:
  347. # in non-blocking mode, use repeated calls to socket.connect_ex
  348. # to check connection status
  349. ret = None
  350. try:
  351. ret = self._sock.connect_ex(self._sock_addr)
  352. except socket.error as err:
  353. ret = err.errno
  354. # Connection succeeded
  355. if not ret or ret == errno.EISCONN:
  356. log.debug('%s: established TCP connection', self)
  357. if self.config['security_protocol'] in ('SSL', 'SASL_SSL'):
  358. log.debug('%s: initiating SSL handshake', self)
  359. self.state = ConnectionStates.HANDSHAKE
  360. self.config['state_change_callback'](self.node_id, self._sock, self)
  361. # _wrap_ssl can alter the connection state -- disconnects on failure
  362. self._wrap_ssl()
  363. elif self.config['security_protocol'] == 'SASL_PLAINTEXT':
  364. log.debug('%s: initiating SASL authentication', self)
  365. self.state = ConnectionStates.AUTHENTICATING
  366. self.config['state_change_callback'](self.node_id, self._sock, self)
  367. else:
  368. # security_protocol PLAINTEXT
  369. log.info('%s: Connection complete.', self)
  370. self.state = ConnectionStates.CONNECTED
  371. self._reset_reconnect_backoff()
  372. self.config['state_change_callback'](self.node_id, self._sock, self)
  373. # Connection failed
  374. # WSAEINVAL == 10022, but errno.WSAEINVAL is not available on non-win systems
  375. elif ret not in (errno.EINPROGRESS, errno.EALREADY, errno.EWOULDBLOCK, 10022):
  376. log.error('Connect attempt to %s returned error %s.'
  377. ' Disconnecting.', self, ret)
  378. errstr = errno.errorcode.get(ret, 'UNKNOWN')
  379. self.close(Errors.KafkaConnectionError('{} {}'.format(ret, errstr)))
  380. return self.state
  381. # Needs retry
  382. else:
  383. pass
  384. if self.state is ConnectionStates.HANDSHAKE:
  385. if self._try_handshake():
  386. log.debug('%s: completed SSL handshake.', self)
  387. if self.config['security_protocol'] == 'SASL_SSL':
  388. log.debug('%s: initiating SASL authentication', self)
  389. self.state = ConnectionStates.AUTHENTICATING
  390. else:
  391. log.info('%s: Connection complete.', self)
  392. self.state = ConnectionStates.CONNECTED
  393. self._reset_reconnect_backoff()
  394. self.config['state_change_callback'](self.node_id, self._sock, self)
  395. if self.state is ConnectionStates.AUTHENTICATING:
  396. assert self.config['security_protocol'] in ('SASL_PLAINTEXT', 'SASL_SSL')
  397. if self._try_authenticate():
  398. # _try_authenticate has side-effects: possibly disconnected on socket errors
  399. if self.state is ConnectionStates.AUTHENTICATING:
  400. log.info('%s: Connection complete.', self)
  401. self.state = ConnectionStates.CONNECTED
  402. self._reset_reconnect_backoff()
  403. self.config['state_change_callback'](self.node_id, self._sock, self)
  404. if self.state not in (ConnectionStates.CONNECTED,
  405. ConnectionStates.DISCONNECTED):
  406. # Connection timed out
  407. request_timeout = self.config['request_timeout_ms'] / 1000.0
  408. if time.time() > request_timeout + self.last_attempt:
  409. log.error('Connection attempt to %s timed out', self)
  410. self.close(Errors.KafkaConnectionError('timeout'))
  411. return self.state
  412. return self.state
  413. def _wrap_ssl(self):
  414. assert self.config['security_protocol'] in ('SSL', 'SASL_SSL')
  415. if self._ssl_context is None:
  416. log.debug('%s: configuring default SSL Context', self)
  417. self._ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) # pylint: disable=no-member
  418. self._ssl_context.options |= ssl.OP_NO_SSLv2 # pylint: disable=no-member
  419. self._ssl_context.options |= ssl.OP_NO_SSLv3 # pylint: disable=no-member
  420. self._ssl_context.verify_mode = ssl.CERT_OPTIONAL
  421. if self.config['ssl_check_hostname']:
  422. self._ssl_context.check_hostname = True
  423. if self.config['ssl_cafile']:
  424. log.info('%s: Loading SSL CA from %s', self, self.config['ssl_cafile'])
  425. self._ssl_context.load_verify_locations(self.config['ssl_cafile'])
  426. self._ssl_context.verify_mode = ssl.CERT_REQUIRED
  427. else:
  428. log.info('%s: Loading system default SSL CAs from %s', self, ssl.get_default_verify_paths())
  429. self._ssl_context.load_default_certs()
  430. if self.config['ssl_certfile'] and self.config['ssl_keyfile']:
  431. log.info('%s: Loading SSL Cert from %s', self, self.config['ssl_certfile'])
  432. log.info('%s: Loading SSL Key from %s', self, self.config['ssl_keyfile'])
  433. self._ssl_context.load_cert_chain(
  434. certfile=self.config['ssl_certfile'],
  435. keyfile=self.config['ssl_keyfile'],
  436. password=self.config['ssl_password'])
  437. if self.config['ssl_crlfile']:
  438. if not hasattr(ssl, 'VERIFY_CRL_CHECK_LEAF'):
  439. raise RuntimeError('This version of Python does not support ssl_crlfile!')
  440. log.info('%s: Loading SSL CRL from %s', self, self.config['ssl_crlfile'])
  441. self._ssl_context.load_verify_locations(self.config['ssl_crlfile'])
  442. # pylint: disable=no-member
  443. self._ssl_context.verify_flags |= ssl.VERIFY_CRL_CHECK_LEAF
  444. if self.config['ssl_ciphers']:
  445. log.info('%s: Setting SSL Ciphers: %s', self, self.config['ssl_ciphers'])
  446. self._ssl_context.set_ciphers(self.config['ssl_ciphers'])
  447. log.debug('%s: wrapping socket in ssl context', self)
  448. try:
  449. self._sock = self._ssl_context.wrap_socket(
  450. self._sock,
  451. server_hostname=self.host,
  452. do_handshake_on_connect=False)
  453. except ssl.SSLError as e:
  454. log.exception('%s: Failed to wrap socket in SSLContext!', self)
  455. self.close(e)
  456. def _try_handshake(self):
  457. assert self.config['security_protocol'] in ('SSL', 'SASL_SSL')
  458. try:
  459. self._sock.do_handshake()
  460. return True
  461. # old ssl in python2.6 will swallow all SSLErrors here...
  462. except (SSLWantReadError, SSLWantWriteError):
  463. pass
  464. except (SSLZeroReturnError, ConnectionError, TimeoutError, SSLEOFError):
  465. log.warning('SSL connection closed by server during handshake.')
  466. self.close(Errors.KafkaConnectionError('SSL connection closed by server during handshake'))
  467. # Other SSLErrors will be raised to user
  468. return False
  469. def _try_authenticate(self):
  470. assert self.config['api_version'] is None or self.config['api_version'] >= (0, 10)
  471. if self._sasl_auth_future is None:
  472. # Build a SaslHandShakeRequest message
  473. request = SaslHandShakeRequest[0](self.config['sasl_mechanism'])
  474. future = Future()
  475. sasl_response = self._send(request)
  476. sasl_response.add_callback(self._handle_sasl_handshake_response, future)
  477. sasl_response.add_errback(lambda f, e: f.failure(e), future)
  478. self._sasl_auth_future = future
  479. for r, f in self.recv():
  480. f.success(r)
  481. # A connection error could trigger close() which will reset the future
  482. if self._sasl_auth_future is None:
  483. return False
  484. elif self._sasl_auth_future.failed():
  485. ex = self._sasl_auth_future.exception
  486. if not isinstance(ex, Errors.KafkaConnectionError):
  487. raise ex # pylint: disable-msg=raising-bad-type
  488. return self._sasl_auth_future.succeeded()
  489. def _handle_sasl_handshake_response(self, future, response):
  490. error_type = Errors.for_code(response.error_code)
  491. if error_type is not Errors.NoError:
  492. error = error_type(self)
  493. self.close(error=error)
  494. return future.failure(error_type(self))
  495. if self.config['sasl_mechanism'] not in response.enabled_mechanisms:
  496. return future.failure(
  497. Errors.UnsupportedSaslMechanismError(
  498. 'Kafka broker does not support %s sasl mechanism. Enabled mechanisms are: %s'
  499. % (self.config['sasl_mechanism'], response.enabled_mechanisms)))
  500. elif self.config['sasl_mechanism'] == 'PLAIN':
  501. return self._try_authenticate_plain(future)
  502. elif self.config['sasl_mechanism'] == 'GSSAPI':
  503. return self._try_authenticate_gssapi(future)
  504. elif self.config['sasl_mechanism'] == 'OAUTHBEARER':
  505. return self._try_authenticate_oauth(future)
  506. elif self.config['sasl_mechanism'].startswith("SCRAM-SHA-"):
  507. return self._try_authenticate_scram(future)
  508. else:
  509. return future.failure(
  510. Errors.UnsupportedSaslMechanismError(
  511. 'kafka-python does not support SASL mechanism %s' %
  512. self.config['sasl_mechanism']))
  513. def _send_bytes(self, data):
  514. """Send some data via non-blocking IO
  515. Note: this method is not synchronized internally; you should
  516. always hold the _lock before calling
  517. Returns: number of bytes
  518. Raises: socket exception
  519. """
  520. total_sent = 0
  521. while total_sent < len(data):
  522. try:
  523. sent_bytes = self._sock.send(data[total_sent:])
  524. total_sent += sent_bytes
  525. except (SSLWantReadError, SSLWantWriteError):
  526. break
  527. except (ConnectionError, TimeoutError) as e:
  528. if six.PY2 and e.errno == errno.EWOULDBLOCK:
  529. break
  530. raise
  531. except BlockingIOError:
  532. if six.PY3:
  533. break
  534. raise
  535. return total_sent
  536. def _send_bytes_blocking(self, data):
  537. self._sock.settimeout(self.config['request_timeout_ms'] / 1000)
  538. total_sent = 0
  539. try:
  540. while total_sent < len(data):
  541. sent_bytes = self._sock.send(data[total_sent:])
  542. total_sent += sent_bytes
  543. if total_sent != len(data):
  544. raise ConnectionError('Buffer overrun during socket send')
  545. return total_sent
  546. finally:
  547. self._sock.settimeout(0.0)
  548. def _recv_bytes_blocking(self, n):
  549. self._sock.settimeout(self.config['request_timeout_ms'] / 1000)
  550. try:
  551. data = b''
  552. while len(data) < n:
  553. fragment = self._sock.recv(n - len(data))
  554. if not fragment:
  555. raise ConnectionError('Connection reset during recv')
  556. data += fragment
  557. return data
  558. finally:
  559. self._sock.settimeout(0.0)
  560. def _try_authenticate_plain(self, future):
  561. if self.config['security_protocol'] == 'SASL_PLAINTEXT':
  562. log.warning('%s: Sending username and password in the clear', self)
  563. data = b''
  564. # Send PLAIN credentials per RFC-4616
  565. msg = bytes('\0'.join([self.config['sasl_plain_username'],
  566. self.config['sasl_plain_username'],
  567. self.config['sasl_plain_password']]).encode('utf-8'))
  568. size = Int32.encode(len(msg))
  569. err = None
  570. close = False
  571. with self._lock:
  572. if not self._can_send_recv():
  573. err = Errors.NodeNotReadyError(str(self))
  574. close = False
  575. else:
  576. try:
  577. self._send_bytes_blocking(size + msg)
  578. # The server will send a zero sized message (that is Int32(0)) on success.
  579. # The connection is closed on failure
  580. data = self._recv_bytes_blocking(4)
  581. except (ConnectionError, TimeoutError) as e:
  582. log.exception("%s: Error receiving reply from server", self)
  583. err = Errors.KafkaConnectionError("%s: %s" % (self, e))
  584. close = True
  585. if err is not None:
  586. if close:
  587. self.close(error=err)
  588. return future.failure(err)
  589. if data != b'\x00\x00\x00\x00':
  590. error = Errors.AuthenticationFailedError('Unrecognized response during authentication')
  591. return future.failure(error)
  592. log.info('%s: Authenticated as %s via PLAIN', self, self.config['sasl_plain_username'])
  593. return future.success(True)
  594. def _try_authenticate_scram(self, future):
  595. if self.config['security_protocol'] == 'SASL_PLAINTEXT':
  596. log.warning('%s: Exchanging credentials in the clear', self)
  597. scram_client = ScramClient(
  598. self.config['sasl_plain_username'], self.config['sasl_plain_password'], self.config['sasl_mechanism']
  599. )
  600. err = None
  601. close = False
  602. with self._lock:
  603. if not self._can_send_recv():
  604. err = Errors.NodeNotReadyError(str(self))
  605. close = False
  606. else:
  607. try:
  608. client_first = scram_client.first_message().encode('utf-8')
  609. size = Int32.encode(len(client_first))
  610. self._send_bytes_blocking(size + client_first)
  611. (data_len,) = struct.unpack('>i', self._recv_bytes_blocking(4))
  612. server_first = self._recv_bytes_blocking(data_len).decode('utf-8')
  613. scram_client.process_server_first_message(server_first)
  614. client_final = scram_client.final_message().encode('utf-8')
  615. size = Int32.encode(len(client_final))
  616. self._send_bytes_blocking(size + client_final)
  617. (data_len,) = struct.unpack('>i', self._recv_bytes_blocking(4))
  618. server_final = self._recv_bytes_blocking(data_len).decode('utf-8')
  619. scram_client.process_server_final_message(server_final)
  620. except (ConnectionError, TimeoutError) as e:
  621. log.exception("%s: Error receiving reply from server", self)
  622. err = Errors.KafkaConnectionError("%s: %s" % (self, e))
  623. close = True
  624. if err is not None:
  625. if close:
  626. self.close(error=err)
  627. return future.failure(err)
  628. log.info(
  629. '%s: Authenticated as %s via %s', self, self.config['sasl_plain_username'], self.config['sasl_mechanism']
  630. )
  631. return future.success(True)
  632. def _try_authenticate_gssapi(self, future):
  633. kerberos_damin_name = self.config['sasl_kerberos_domain_name'] or self.host
  634. auth_id = self.config['sasl_kerberos_service_name'] + '@' + kerberos_damin_name
  635. gssapi_name = gssapi.Name(
  636. auth_id,
  637. name_type=gssapi.NameType.hostbased_service
  638. ).canonicalize(gssapi.MechType.kerberos)
  639. log.debug('%s: GSSAPI name: %s', self, gssapi_name)
  640. err = None
  641. close = False
  642. with self._lock:
  643. if not self._can_send_recv():
  644. err = Errors.NodeNotReadyError(str(self))
  645. close = False
  646. else:
  647. # Establish security context and negotiate protection level
  648. # For reference RFC 2222, section 7.2.1
  649. try:
  650. # Exchange tokens until authentication either succeeds or fails
  651. client_ctx = gssapi.SecurityContext(name=gssapi_name, usage='initiate')
  652. received_token = None
  653. while not client_ctx.complete:
  654. # calculate an output token from kafka token (or None if first iteration)
  655. output_token = client_ctx.step(received_token)
  656. # pass output token to kafka, or send empty response if the security
  657. # context is complete (output token is None in that case)
  658. if output_token is None:
  659. self._send_bytes_blocking(Int32.encode(0))
  660. else:
  661. msg = output_token
  662. size = Int32.encode(len(msg))
  663. self._send_bytes_blocking(size + msg)
  664. # The server will send a token back. Processing of this token either
  665. # establishes a security context, or it needs further token exchange.
  666. # The gssapi will be able to identify the needed next step.
  667. # The connection is closed on failure.
  668. header = self._recv_bytes_blocking(4)
  669. (token_size,) = struct.unpack('>i', header)
  670. received_token = self._recv_bytes_blocking(token_size)
  671. # Process the security layer negotiation token, sent by the server
  672. # once the security context is established.
  673. # unwraps message containing supported protection levels and msg size
  674. msg = client_ctx.unwrap(received_token).message
  675. # Kafka currently doesn't support integrity or confidentiality security layers, so we
  676. # simply set QoP to 'auth' only (first octet). We reuse the max message size proposed
  677. # by the server
  678. msg = Int8.encode(SASL_QOP_AUTH & Int8.decode(io.BytesIO(msg[0:1]))) + msg[1:]
  679. # add authorization identity to the response, GSS-wrap and send it
  680. msg = client_ctx.wrap(msg + auth_id.encode(), False).message
  681. size = Int32.encode(len(msg))
  682. self._send_bytes_blocking(size + msg)
  683. except (ConnectionError, TimeoutError) as e:
  684. log.exception("%s: Error receiving reply from server", self)
  685. err = Errors.KafkaConnectionError("%s: %s" % (self, e))
  686. close = True
  687. except Exception as e:
  688. err = e
  689. close = True
  690. if err is not None:
  691. if close:
  692. self.close(error=err)
  693. return future.failure(err)
  694. log.info('%s: Authenticated as %s via GSSAPI', self, gssapi_name)
  695. return future.success(True)
  696. def _try_authenticate_oauth(self, future):
  697. data = b''
  698. msg = bytes(self._build_oauth_client_request().encode("utf-8"))
  699. size = Int32.encode(len(msg))
  700. err = None
  701. close = False
  702. with self._lock:
  703. if not self._can_send_recv():
  704. err = Errors.NodeNotReadyError(str(self))
  705. close = False
  706. else:
  707. try:
  708. # Send SASL OAuthBearer request with OAuth token
  709. self._send_bytes_blocking(size + msg)
  710. # The server will send a zero sized message (that is Int32(0)) on success.
  711. # The connection is closed on failure
  712. data = self._recv_bytes_blocking(4)
  713. except (ConnectionError, TimeoutError) as e:
  714. log.exception("%s: Error receiving reply from server", self)
  715. err = Errors.KafkaConnectionError("%s: %s" % (self, e))
  716. close = True
  717. if err is not None:
  718. if close:
  719. self.close(error=err)
  720. return future.failure(err)
  721. if data != b'\x00\x00\x00\x00':
  722. error = Errors.AuthenticationFailedError('Unrecognized response during authentication')
  723. return future.failure(error)
  724. log.info('%s: Authenticated via OAuth', self)
  725. return future.success(True)
  726. def _build_oauth_client_request(self):
  727. token_provider = self.config['sasl_oauth_token_provider']
  728. return "n,,\x01auth=Bearer {}{}\x01\x01".format(token_provider.token(), self._token_extensions())
  729. def _token_extensions(self):
  730. """
  731. Return a string representation of the OPTIONAL key-value pairs that can be sent with an OAUTHBEARER
  732. initial request.
  733. """
  734. token_provider = self.config['sasl_oauth_token_provider']
  735. # Only run if the #extensions() method is implemented by the clients Token Provider class
  736. # Builds up a string separated by \x01 via a dict of key value pairs
  737. if callable(getattr(token_provider, "extensions", None)) and len(token_provider.extensions()) > 0:
  738. msg = "\x01".join(["{}={}".format(k, v) for k, v in token_provider.extensions().items()])
  739. return "\x01" + msg
  740. else:
  741. return ""
  742. def blacked_out(self):
  743. """
  744. Return true if we are disconnected from the given node and can't
  745. re-establish a connection yet
  746. """
  747. if self.state is ConnectionStates.DISCONNECTED:
  748. if time.time() < self.last_attempt + self._reconnect_backoff:
  749. return True
  750. return False
  751. def connection_delay(self):
  752. """
  753. Return the number of milliseconds to wait, based on the connection
  754. state, before attempting to send data. When disconnected, this respects
  755. the reconnect backoff time. When connecting or connected, returns a very
  756. large number to handle slow/stalled connections.
  757. """
  758. time_waited = time.time() - (self.last_attempt or 0)
  759. if self.state is ConnectionStates.DISCONNECTED:
  760. return max(self._reconnect_backoff - time_waited, 0) * 1000
  761. else:
  762. # When connecting or connected, we should be able to delay
  763. # indefinitely since other events (connection or data acked) will
  764. # cause a wakeup once data can be sent.
  765. return float('inf')
  766. def connected(self):
  767. """Return True iff socket is connected."""
  768. return self.state is ConnectionStates.CONNECTED
  769. def connecting(self):
  770. """Returns True if still connecting (this may encompass several
  771. different states, such as SSL handshake, authorization, etc)."""
  772. return self.state in (ConnectionStates.CONNECTING,
  773. ConnectionStates.HANDSHAKE,
  774. ConnectionStates.AUTHENTICATING)
  775. def disconnected(self):
  776. """Return True iff socket is closed"""
  777. return self.state is ConnectionStates.DISCONNECTED
  778. def _reset_reconnect_backoff(self):
  779. self._failures = 0
  780. self._reconnect_backoff = self.config['reconnect_backoff_ms'] / 1000.0
  781. def _update_reconnect_backoff(self):
  782. # Do not mark as failure if there are more dns entries available to try
  783. if len(self._gai) > 0:
  784. return
  785. if self.config['reconnect_backoff_max_ms'] > self.config['reconnect_backoff_ms']:
  786. self._failures += 1
  787. self._reconnect_backoff = self.config['reconnect_backoff_ms'] * 2 ** (self._failures - 1)
  788. self._reconnect_backoff = min(self._reconnect_backoff, self.config['reconnect_backoff_max_ms'])
  789. self._reconnect_backoff *= uniform(0.8, 1.2)
  790. self._reconnect_backoff /= 1000.0
  791. log.debug('%s: reconnect backoff %s after %s failures', self, self._reconnect_backoff, self._failures)
  792. def _close_socket(self):
  793. if hasattr(self, '_sock') and self._sock is not None:
  794. self._sock.close()
  795. self._sock = None
  796. def __del__(self):
  797. self._close_socket()
  798. def close(self, error=None):
  799. """Close socket and fail all in-flight-requests.
  800. Arguments:
  801. error (Exception, optional): pending in-flight-requests
  802. will be failed with this exception.
  803. Default: kafka.errors.KafkaConnectionError.
  804. """
  805. if self.state is ConnectionStates.DISCONNECTED:
  806. return
  807. with self._lock:
  808. if self.state is ConnectionStates.DISCONNECTED:
  809. return
  810. log.info('%s: Closing connection. %s', self, error or '')
  811. self._update_reconnect_backoff()
  812. self._sasl_auth_future = None
  813. self._protocol = KafkaProtocol(
  814. client_id=self.config['client_id'],
  815. api_version=self.config['api_version'])
  816. self._send_buffer = b''
  817. if error is None:
  818. error = Errors.Cancelled(str(self))
  819. ifrs = list(self.in_flight_requests.items())
  820. self.in_flight_requests.clear()
  821. self.state = ConnectionStates.DISCONNECTED
  822. # To avoid race conditions and/or deadlocks
  823. # keep a reference to the socket but leave it
  824. # open until after the state_change_callback
  825. # This should give clients a change to deregister
  826. # the socket fd from selectors cleanly.
  827. sock = self._sock
  828. self._sock = None
  829. # drop lock before state change callback and processing futures
  830. self.config['state_change_callback'](self.node_id, sock, self)
  831. sock.close()
  832. for (_correlation_id, (future, _timestamp)) in ifrs:
  833. future.failure(error)
  834. def _can_send_recv(self):
  835. """Return True iff socket is ready for requests / responses"""
  836. return self.state in (ConnectionStates.AUTHENTICATING,
  837. ConnectionStates.CONNECTED)
  838. def send(self, request, blocking=True):
  839. """Queue request for async network send, return Future()"""
  840. future = Future()
  841. if self.connecting():
  842. return future.failure(Errors.NodeNotReadyError(str(self)))
  843. elif not self.connected():
  844. return future.failure(Errors.KafkaConnectionError(str(self)))
  845. elif not self.can_send_more():
  846. return future.failure(Errors.TooManyInFlightRequests(str(self)))
  847. return self._send(request, blocking=blocking)
  848. def _send(self, request, blocking=True):
  849. future = Future()
  850. with self._lock:
  851. if not self._can_send_recv():
  852. # In this case, since we created the future above,
  853. # we know there are no callbacks/errbacks that could fire w/
  854. # lock. So failing + returning inline should be safe
  855. return future.failure(Errors.NodeNotReadyError(str(self)))
  856. correlation_id = self._protocol.send_request(request)
  857. log.debug('%s Request %d: %s', self, correlation_id, request)
  858. if request.expect_response():
  859. sent_time = time.time()
  860. assert correlation_id not in self.in_flight_requests, 'Correlation ID already in-flight!'
  861. self.in_flight_requests[correlation_id] = (future, sent_time)
  862. else:
  863. future.success(None)
  864. # Attempt to replicate behavior from prior to introduction of
  865. # send_pending_requests() / async sends
  866. if blocking:
  867. self.send_pending_requests()
  868. return future
  869. def send_pending_requests(self):
  870. """Attempts to send pending requests messages via blocking IO
  871. If all requests have been sent, return True
  872. Otherwise, if the socket is blocked and there are more bytes to send,
  873. return False.
  874. """
  875. try:
  876. with self._lock:
  877. if not self._can_send_recv():
  878. return False
  879. data = self._protocol.send_bytes()
  880. total_bytes = self._send_bytes_blocking(data)
  881. if self._sensors:
  882. self._sensors.bytes_sent.record(total_bytes)
  883. return True
  884. except (ConnectionError, TimeoutError) as e:
  885. log.exception("Error sending request data to %s", self)
  886. error = Errors.KafkaConnectionError("%s: %s" % (self, e))
  887. self.close(error=error)
  888. return False
  889. def send_pending_requests_v2(self):
  890. """Attempts to send pending requests messages via non-blocking IO
  891. If all requests have been sent, return True
  892. Otherwise, if the socket is blocked and there are more bytes to send,
  893. return False.
  894. """
  895. try:
  896. with self._lock:
  897. if not self._can_send_recv():
  898. return False
  899. # _protocol.send_bytes returns encoded requests to send
  900. # we send them via _send_bytes()
  901. # and hold leftover bytes in _send_buffer
  902. if not self._send_buffer:
  903. self._send_buffer = self._protocol.send_bytes()
  904. total_bytes = 0
  905. if self._send_buffer:
  906. total_bytes = self._send_bytes(self._send_buffer)
  907. self._send_buffer = self._send_buffer[total_bytes:]
  908. if self._sensors:
  909. self._sensors.bytes_sent.record(total_bytes)
  910. # Return True iff send buffer is empty
  911. return len(self._send_buffer) == 0
  912. except (ConnectionError, TimeoutError, Exception) as e:
  913. log.exception("Error sending request data to %s", self)
  914. error = Errors.KafkaConnectionError("%s: %s" % (self, e))
  915. self.close(error=error)
  916. return False
  917. def can_send_more(self):
  918. """Return True unless there are max_in_flight_requests_per_connection."""
  919. max_ifrs = self.config['max_in_flight_requests_per_connection']
  920. return len(self.in_flight_requests) < max_ifrs
  921. def recv(self):
  922. """Non-blocking network receive.
  923. Return list of (response, future) tuples
  924. """
  925. responses = self._recv()
  926. if not responses and self.requests_timed_out():
  927. log.warning('%s timed out after %s ms. Closing connection.',
  928. self, self.config['request_timeout_ms'])
  929. self.close(error=Errors.RequestTimedOutError(
  930. 'Request timed out after %s ms' %
  931. self.config['request_timeout_ms']))
  932. return ()
  933. # augment responses w/ correlation_id, future, and timestamp
  934. for i, (correlation_id, response) in enumerate(responses):
  935. try:
  936. with self._lock:
  937. (future, timestamp) = self.in_flight_requests.pop(correlation_id)
  938. except KeyError:
  939. self.close(Errors.KafkaConnectionError('Received unrecognized correlation id'))
  940. return ()
  941. latency_ms = (time.time() - timestamp) * 1000
  942. if self._sensors:
  943. self._sensors.request_time.record(latency_ms)
  944. log.debug('%s Response %d (%s ms): %s', self, correlation_id, latency_ms, response)
  945. responses[i] = (response, future)
  946. return responses
  947. def _recv(self):
  948. """Take all available bytes from socket, return list of any responses from parser"""
  949. recvd = []
  950. err = None
  951. with self._lock:
  952. if not self._can_send_recv():
  953. log.warning('%s cannot recv: socket not connected', self)
  954. return ()
  955. while len(recvd) < self.config['sock_chunk_buffer_count']:
  956. try:
  957. data = self._sock.recv(self.config['sock_chunk_bytes'])
  958. # We expect socket.recv to raise an exception if there are no
  959. # bytes available to read from the socket in non-blocking mode.
  960. # but if the socket is disconnected, we will get empty data
  961. # without an exception raised
  962. if not data:
  963. log.error('%s: socket disconnected', self)
  964. err = Errors.KafkaConnectionError('socket disconnected')
  965. break
  966. else:
  967. recvd.append(data)
  968. except (SSLWantReadError, SSLWantWriteError):
  969. break
  970. except (ConnectionError, TimeoutError) as e:
  971. if six.PY2 and e.errno == errno.EWOULDBLOCK:
  972. break
  973. log.exception('%s: Error receiving network data'
  974. ' closing socket', self)
  975. err = Errors.KafkaConnectionError(e)
  976. break
  977. except BlockingIOError:
  978. if six.PY3:
  979. break
  980. # For PY2 this is a catchall and should be re-raised
  981. raise
  982. # Only process bytes if there was no connection exception
  983. if err is None:
  984. recvd_data = b''.join(recvd)
  985. if self._sensors:
  986. self._sensors.bytes_received.record(len(recvd_data))
  987. # We need to keep the lock through protocol receipt
  988. # so that we ensure that the processed byte order is the
  989. # same as the received byte order
  990. try:
  991. return self._protocol.receive_bytes(recvd_data)
  992. except Errors.KafkaProtocolError as e:
  993. err = e
  994. self.close(error=err)
  995. return ()
  996. def requests_timed_out(self):
  997. with self._lock:
  998. if self.in_flight_requests:
  999. get_timestamp = lambda v: v[1]
  1000. oldest_at = min(map(get_timestamp,
  1001. self.in_flight_requests.values()))
  1002. timeout = self.config['request_timeout_ms'] / 1000.0
  1003. if time.time() >= oldest_at + timeout:
  1004. return True
  1005. return False
  1006. def _handle_api_version_response(self, response):
  1007. error_type = Errors.for_code(response.error_code)
  1008. assert error_type is Errors.NoError, "API version check failed"
  1009. self._api_versions = dict([
  1010. (api_key, (min_version, max_version))
  1011. for api_key, min_version, max_version in response.api_versions
  1012. ])
  1013. return self._api_versions
  1014. def get_api_versions(self):
  1015. if self._api_versions is not None:
  1016. return self._api_versions
  1017. version = self.check_version()
  1018. if version < (0, 10, 0):
  1019. raise Errors.UnsupportedVersionError(
  1020. "ApiVersion not supported by cluster version {} < 0.10.0"
  1021. .format(version))
  1022. # _api_versions is set as a side effect of check_versions() on a cluster
  1023. # that supports 0.10.0 or later
  1024. return self._api_versions
  1025. def _infer_broker_version_from_api_versions(self, api_versions):
  1026. # The logic here is to check the list of supported request versions
  1027. # in reverse order. As soon as we find one that works, return it
  1028. test_cases = [
  1029. # format (<broker version>, <needed struct>)
  1030. ((2, 5, 0), DescribeAclsRequest_v2),
  1031. ((2, 4, 0), ProduceRequest[8]),
  1032. ((2, 3, 0), FetchRequest[11]),
  1033. ((2, 2, 0), OffsetRequest[5]),
  1034. ((2, 1, 0), FetchRequest[10]),
  1035. ((2, 0, 0), FetchRequest[8]),
  1036. ((1, 1, 0), FetchRequest[7]),
  1037. ((1, 0, 0), MetadataRequest[5]),
  1038. ((0, 11, 0), MetadataRequest[4]),
  1039. ((0, 10, 2), OffsetFetchRequest[2]),
  1040. ((0, 10, 1), MetadataRequest[2]),
  1041. ]
  1042. # Get the best match of test cases
  1043. for broker_version, struct in sorted(test_cases, reverse=True):
  1044. if struct.API_KEY not in api_versions:
  1045. continue
  1046. min_version, max_version = api_versions[struct.API_KEY]
  1047. if min_version <= struct.API_VERSION <= max_version:
  1048. return broker_version
  1049. # We know that ApiVersionResponse is only supported in 0.10+
  1050. # so if all else fails, choose that
  1051. return (0, 10, 0)
  1052. def check_version(self, timeout=2, strict=False, topics=[]):
  1053. """Attempt to guess the broker version.
  1054. Note: This is a blocking call.
  1055. Returns: version tuple, i.e. (0, 10), (0, 9), (0, 8, 2), ...
  1056. """
  1057. timeout_at = time.time() + timeout
  1058. log.info('Probing node %s broker version', self.node_id)
  1059. # Monkeypatch some connection configurations to avoid timeouts
  1060. override_config = {
  1061. 'request_timeout_ms': timeout * 1000,
  1062. 'max_in_flight_requests_per_connection': 5
  1063. }
  1064. stashed = {}
  1065. for key in override_config:
  1066. stashed[key] = self.config[key]
  1067. self.config[key] = override_config[key]
  1068. def reset_override_configs():
  1069. for key in stashed:
  1070. self.config[key] = stashed[key]
  1071. # kafka kills the connection when it doesn't recognize an API request
  1072. # so we can send a test request and then follow immediately with a
  1073. # vanilla MetadataRequest. If the server did not recognize the first
  1074. # request, both will be failed with a ConnectionError that wraps
  1075. # socket.error (32, 54, or 104)
  1076. from kafka.protocol.admin import ApiVersionRequest, ListGroupsRequest
  1077. from kafka.protocol.commit import OffsetFetchRequest, GroupCoordinatorRequest
  1078. test_cases = [
  1079. # All cases starting from 0.10 will be based on ApiVersionResponse
  1080. ((0, 10), ApiVersionRequest[0]()),
  1081. ((0, 9), ListGroupsRequest[0]()),
  1082. ((0, 8, 2), GroupCoordinatorRequest[0]('kafka-python-default-group')),
  1083. ((0, 8, 1), OffsetFetchRequest[0]('kafka-python-default-group', [])),
  1084. ((0, 8, 0), MetadataRequest[0](topics)),
  1085. ]
  1086. for version, request in test_cases:
  1087. if not self.connect_blocking(timeout_at - time.time()):
  1088. reset_override_configs()
  1089. raise Errors.NodeNotReadyError()
  1090. f = self.send(request)
  1091. # HACK: sleeping to wait for socket to send bytes
  1092. time.sleep(0.1)
  1093. # when broker receives an unrecognized request API
  1094. # it abruptly closes our socket.
  1095. # so we attempt to send a second request immediately
  1096. # that we believe it will definitely recognize (metadata)
  1097. # the attempt to write to a disconnected socket should
  1098. # immediately fail and allow us to infer that the prior
  1099. # request was unrecognized
  1100. mr = self.send(MetadataRequest[0](topics))
  1101. selector = self.config['selector']()
  1102. selector.register(self._sock, selectors.EVENT_READ)
  1103. while not (f.is_done and mr.is_done):
  1104. selector.select(1)
  1105. for response, future in self.recv():
  1106. future.success(response)
  1107. selector.close()
  1108. if f.succeeded():
  1109. if isinstance(request, ApiVersionRequest[0]):
  1110. # Starting from 0.10 kafka broker we determine version
  1111. # by looking at ApiVersionResponse
  1112. api_versions = self._handle_api_version_response(f.value)
  1113. version = self._infer_broker_version_from_api_versions(api_versions)
  1114. log.info('Broker version identified as %s', '.'.join(map(str, version)))
  1115. log.info('Set configuration api_version=%s to skip auto'
  1116. ' check_version requests on startup', version)
  1117. break
  1118. # Only enable strict checking to verify that we understand failure
  1119. # modes. For most users, the fact that the request failed should be
  1120. # enough to rule out a particular broker version.
  1121. if strict:
  1122. # If the socket flush hack did not work (which should force the
  1123. # connection to close and fail all pending requests), then we
  1124. # get a basic Request Timeout. This is not ideal, but we'll deal
  1125. if isinstance(f.exception, Errors.RequestTimedOutError):
  1126. pass
  1127. # 0.9 brokers do not close the socket on unrecognized api
  1128. # requests (bug...). In this case we expect to see a correlation
  1129. # id mismatch
  1130. elif (isinstance(f.exception, Errors.CorrelationIdError) and
  1131. version == (0, 10)):
  1132. pass
  1133. elif six.PY2:
  1134. assert isinstance(f.exception.args[0], socket.error)
  1135. assert f.exception.args[0].errno in (32, 54, 104)
  1136. else:
  1137. assert isinstance(f.exception.args[0], ConnectionError)
  1138. log.info("Broker is not v%s -- it did not recognize %s",
  1139. version, request.__class__.__name__)
  1140. else:
  1141. reset_override_configs()
  1142. raise Errors.UnrecognizedBrokerVersion()
  1143. reset_override_configs()
  1144. return version
  1145. def __str__(self):
  1146. return "<BrokerConnection node_id=%s host=%s:%d %s [%s %s]>" % (
  1147. self.node_id, self.host, self.port, self.state,
  1148. AFI_NAMES[self._sock_afi], self._sock_addr)
  1149. class BrokerConnectionMetrics(object):
  1150. def __init__(self, metrics, metric_group_prefix, node_id):
  1151. self.metrics = metrics
  1152. # Any broker may have registered summary metrics already
  1153. # but if not, we need to create them so we can set as parents below
  1154. all_conns_transferred = metrics.get_sensor('bytes-sent-received')
  1155. if not all_conns_transferred:
  1156. metric_group_name = metric_group_prefix + '-metrics'
  1157. bytes_transferred = metrics.sensor('bytes-sent-received')
  1158. bytes_transferred.add(metrics.metric_name(
  1159. 'network-io-rate', metric_group_name,
  1160. 'The average number of network operations (reads or writes) on all'
  1161. ' connections per second.'), Rate(sampled_stat=Count()))
  1162. bytes_sent = metrics.sensor('bytes-sent',
  1163. parents=[bytes_transferred])
  1164. bytes_sent.add(metrics.metric_name(
  1165. 'outgoing-byte-rate', metric_group_name,
  1166. 'The average number of outgoing bytes sent per second to all'
  1167. ' servers.'), Rate())
  1168. bytes_sent.add(metrics.metric_name(
  1169. 'request-rate', metric_group_name,
  1170. 'The average number of requests sent per second.'),
  1171. Rate(sampled_stat=Count()))
  1172. bytes_sent.add(metrics.metric_name(
  1173. 'request-size-avg', metric_group_name,
  1174. 'The average size of all requests in the window.'), Avg())
  1175. bytes_sent.add(metrics.metric_name(
  1176. 'request-size-max', metric_group_name,
  1177. 'The maximum size of any request sent in the window.'), Max())
  1178. bytes_received = metrics.sensor('bytes-received',
  1179. parents=[bytes_transferred])
  1180. bytes_received.add(metrics.metric_name(
  1181. 'incoming-byte-rate', metric_group_name,
  1182. 'Bytes/second read off all sockets'), Rate())
  1183. bytes_received.add(metrics.metric_name(
  1184. 'response-rate', metric_group_name,
  1185. 'Responses received sent per second.'),
  1186. Rate(sampled_stat=Count()))
  1187. request_latency = metrics.sensor('request-latency')
  1188. request_latency.add(metrics.metric_name(
  1189. 'request-latency-avg', metric_group_name,
  1190. 'The average request latency in ms.'),
  1191. Avg())
  1192. request_latency.add(metrics.metric_name(
  1193. 'request-latency-max', metric_group_name,
  1194. 'The maximum request latency in ms.'),
  1195. Max())
  1196. # if one sensor of the metrics has been registered for the connection,
  1197. # then all other sensors should have been registered; and vice versa
  1198. node_str = 'node-{0}'.format(node_id)
  1199. node_sensor = metrics.get_sensor(node_str + '.bytes-sent')
  1200. if not node_sensor:
  1201. metric_group_name = metric_group_prefix + '-node-metrics.' + node_str
  1202. bytes_sent = metrics.sensor(
  1203. node_str + '.bytes-sent',
  1204. parents=[metrics.get_sensor('bytes-sent')])
  1205. bytes_sent.add(metrics.metric_name(
  1206. 'outgoing-byte-rate', metric_group_name,
  1207. 'The average number of outgoing bytes sent per second.'),
  1208. Rate())
  1209. bytes_sent.add(metrics.metric_name(
  1210. 'request-rate', metric_group_name,
  1211. 'The average number of requests sent per second.'),
  1212. Rate(sampled_stat=Count()))
  1213. bytes_sent.add(metrics.metric_name(
  1214. 'request-size-avg', metric_group_name,
  1215. 'The average size of all requests in the window.'),
  1216. Avg())
  1217. bytes_sent.add(metrics.metric_name(
  1218. 'request-size-max', metric_group_name,
  1219. 'The maximum size of any request sent in the window.'),
  1220. Max())
  1221. bytes_received = metrics.sensor(
  1222. node_str + '.bytes-received',
  1223. parents=[metrics.get_sensor('bytes-received')])
  1224. bytes_received.add(metrics.metric_name(
  1225. 'incoming-byte-rate', metric_group_name,
  1226. 'Bytes/second read off node-connection socket'),
  1227. Rate())
  1228. bytes_received.add(metrics.metric_name(
  1229. 'response-rate', metric_group_name,
  1230. 'The average number of responses received per second.'),
  1231. Rate(sampled_stat=Count()))
  1232. request_time = metrics.sensor(
  1233. node_str + '.latency',
  1234. parents=[metrics.get_sensor('request-latency')])
  1235. request_time.add(metrics.metric_name(
  1236. 'request-latency-avg', metric_group_name,
  1237. 'The average request latency in ms.'),
  1238. Avg())
  1239. request_time.add(metrics.metric_name(
  1240. 'request-latency-max', metric_group_name,
  1241. 'The maximum request latency in ms.'),
  1242. Max())
  1243. self.bytes_sent = metrics.sensor(node_str + '.bytes-sent')
  1244. self.bytes_received = metrics.sensor(node_str + '.bytes-received')
  1245. self.request_time = metrics.sensor(node_str + '.latency')
  1246. def _address_family(address):
  1247. """
  1248. Attempt to determine the family of an address (or hostname)
  1249. :return: either socket.AF_INET or socket.AF_INET6 or socket.AF_UNSPEC if the address family
  1250. could not be determined
  1251. """
  1252. if address.startswith('[') and address.endswith(']'):
  1253. return socket.AF_INET6
  1254. for af in (socket.AF_INET, socket.AF_INET6):
  1255. try:
  1256. socket.inet_pton(af, address)
  1257. return af
  1258. except (ValueError, AttributeError, socket.error):
  1259. continue
  1260. return socket.AF_UNSPEC
  1261. def get_ip_port_afi(host_and_port_str):
  1262. """
  1263. Parse the IP and port from a string in the format of:
  1264. * host_or_ip <- Can be either IPv4 address literal or hostname/fqdn
  1265. * host_or_ipv4:port <- Can be either IPv4 address literal or hostname/fqdn
  1266. * [host_or_ip] <- IPv6 address literal
  1267. * [host_or_ip]:port. <- IPv6 address literal
  1268. .. note:: IPv6 address literals with ports *must* be enclosed in brackets
  1269. .. note:: If the port is not specified, default will be returned.
  1270. :return: tuple (host, port, afi), afi will be socket.AF_INET or socket.AF_INET6 or socket.AF_UNSPEC
  1271. """
  1272. host_and_port_str = host_and_port_str.strip()
  1273. if host_and_port_str.startswith('['):
  1274. af = socket.AF_INET6
  1275. host, rest = host_and_port_str[1:].split(']')
  1276. if rest:
  1277. port = int(rest[1:])
  1278. else:
  1279. port = DEFAULT_KAFKA_PORT
  1280. return host, port, af
  1281. else:
  1282. if ':' not in host_and_port_str:
  1283. af = _address_family(host_and_port_str)
  1284. return host_and_port_str, DEFAULT_KAFKA_PORT, af
  1285. else:
  1286. # now we have something with a colon in it and no square brackets. It could be
  1287. # either an IPv6 address literal (e.g., "::1") or an IP:port pair or a host:port pair
  1288. try:
  1289. # if it decodes as an IPv6 address, use that
  1290. socket.inet_pton(socket.AF_INET6, host_and_port_str)
  1291. return host_and_port_str, DEFAULT_KAFKA_PORT, socket.AF_INET6
  1292. except AttributeError:
  1293. log.warning('socket.inet_pton not available on this platform.'
  1294. ' consider `pip install win_inet_pton`')
  1295. pass
  1296. except (ValueError, socket.error):
  1297. # it's a host:port pair
  1298. pass
  1299. host, port = host_and_port_str.rsplit(':', 1)
  1300. port = int(port)
  1301. af = _address_family(host)
  1302. return host, port, af
  1303. def collect_hosts(hosts, randomize=True):
  1304. """
  1305. Collects a comma-separated set of hosts (host:port) and optionally
  1306. randomize the returned list.
  1307. """
  1308. if isinstance(hosts, six.string_types):
  1309. hosts = hosts.strip().split(',')
  1310. result = []
  1311. afi = socket.AF_INET
  1312. for host_port in hosts:
  1313. host, port, afi = get_ip_port_afi(host_port)
  1314. if port < 0:
  1315. port = DEFAULT_KAFKA_PORT
  1316. result.append((host, port, afi))
  1317. if randomize:
  1318. shuffle(result)
  1319. return result
  1320. def is_inet_4_or_6(gai):
  1321. """Given a getaddrinfo struct, return True iff ipv4 or ipv6"""
  1322. return gai[0] in (socket.AF_INET, socket.AF_INET6)
  1323. def dns_lookup(host, port, afi=socket.AF_UNSPEC):
  1324. """Returns a list of getaddrinfo structs, optionally filtered to an afi (ipv4 / ipv6)"""
  1325. # XXX: all DNS functions in Python are blocking. If we really
  1326. # want to be non-blocking here, we need to use a 3rd-party
  1327. # library like python-adns, or move resolution onto its
  1328. # own thread. This will be subject to the default libc
  1329. # name resolution timeout (5s on most Linux boxes)
  1330. try:
  1331. return list(filter(is_inet_4_or_6,
  1332. socket.getaddrinfo(host, port, afi,
  1333. socket.SOCK_STREAM)))
  1334. except socket.gaierror as ex:
  1335. log.warning('DNS lookup failed for %s:%d,'
  1336. ' exception was %s. Is your'
  1337. ' advertised.listeners (called'
  1338. ' advertised.host.name before Kafka 9)'
  1339. ' correct and resolvable?',
  1340. host, port, ex)
  1341. return []