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.

1342 lines
62 KiB

6 months ago
  1. from __future__ import absolute_import
  2. from collections import defaultdict
  3. import copy
  4. import logging
  5. import socket
  6. from . import ConfigResourceType
  7. from kafka.vendor import six
  8. from kafka.admin.acl_resource import ACLOperation, ACLPermissionType, ACLFilter, ACL, ResourcePattern, ResourceType, \
  9. ACLResourcePatternType
  10. from kafka.client_async import KafkaClient, selectors
  11. from kafka.coordinator.protocol import ConsumerProtocolMemberMetadata, ConsumerProtocolMemberAssignment, ConsumerProtocol
  12. import kafka.errors as Errors
  13. from kafka.errors import (
  14. IncompatibleBrokerVersion, KafkaConfigurationError, NotControllerError,
  15. UnrecognizedBrokerVersion, IllegalArgumentError)
  16. from kafka.metrics import MetricConfig, Metrics
  17. from kafka.protocol.admin import (
  18. CreateTopicsRequest, DeleteTopicsRequest, DescribeConfigsRequest, AlterConfigsRequest, CreatePartitionsRequest,
  19. ListGroupsRequest, DescribeGroupsRequest, DescribeAclsRequest, CreateAclsRequest, DeleteAclsRequest,
  20. DeleteGroupsRequest
  21. )
  22. from kafka.protocol.commit import GroupCoordinatorRequest, OffsetFetchRequest
  23. from kafka.protocol.metadata import MetadataRequest
  24. from kafka.protocol.types import Array
  25. from kafka.structs import TopicPartition, OffsetAndMetadata, MemberInformation, GroupInformation
  26. from kafka.version import __version__
  27. log = logging.getLogger(__name__)
  28. class KafkaAdminClient(object):
  29. """A class for administering the Kafka cluster.
  30. Warning:
  31. This is an unstable interface that was recently added and is subject to
  32. change without warning. In particular, many methods currently return
  33. raw protocol tuples. In future releases, we plan to make these into
  34. nicer, more pythonic objects. Unfortunately, this will likely break
  35. those interfaces.
  36. The KafkaAdminClient class will negotiate for the latest version of each message
  37. protocol format supported by both the kafka-python client library and the
  38. Kafka broker. Usage of optional fields from protocol versions that are not
  39. supported by the broker will result in IncompatibleBrokerVersion exceptions.
  40. Use of this class requires a minimum broker version >= 0.10.0.0.
  41. Keyword Arguments:
  42. bootstrap_servers: 'host[:port]' string (or list of 'host[:port]'
  43. strings) that the consumer should contact to bootstrap initial
  44. cluster metadata. This does not have to be the full node list.
  45. It just needs to have at least one broker that will respond to a
  46. Metadata API Request. Default port is 9092. If no servers are
  47. specified, will default to localhost:9092.
  48. client_id (str): a name for this client. This string is passed in
  49. each request to servers and can be used to identify specific
  50. server-side log entries that correspond to this client. Also
  51. submitted to GroupCoordinator for logging with respect to
  52. consumer group administration. Default: 'kafka-python-{version}'
  53. reconnect_backoff_ms (int): The amount of time in milliseconds to
  54. wait before attempting to reconnect to a given host.
  55. Default: 50.
  56. reconnect_backoff_max_ms (int): The maximum amount of time in
  57. milliseconds to backoff/wait when reconnecting to a broker that has
  58. repeatedly failed to connect. If provided, the backoff per host
  59. will increase exponentially for each consecutive connection
  60. failure, up to this maximum. Once the maximum is reached,
  61. reconnection attempts will continue periodically with this fixed
  62. rate. To avoid connection storms, a randomization factor of 0.2
  63. will be applied to the backoff resulting in a random range between
  64. 20% below and 20% above the computed value. Default: 1000.
  65. request_timeout_ms (int): Client request timeout in milliseconds.
  66. Default: 30000.
  67. connections_max_idle_ms: Close idle connections after the number of
  68. milliseconds specified by this config. The broker closes idle
  69. connections after connections.max.idle.ms, so this avoids hitting
  70. unexpected socket disconnected errors on the client.
  71. Default: 540000
  72. retry_backoff_ms (int): Milliseconds to backoff when retrying on
  73. errors. Default: 100.
  74. max_in_flight_requests_per_connection (int): Requests are pipelined
  75. to kafka brokers up to this number of maximum requests per
  76. broker connection. Default: 5.
  77. receive_buffer_bytes (int): The size of the TCP receive buffer
  78. (SO_RCVBUF) to use when reading data. Default: None (relies on
  79. system defaults). Java client defaults to 32768.
  80. send_buffer_bytes (int): The size of the TCP send buffer
  81. (SO_SNDBUF) to use when sending data. Default: None (relies on
  82. system defaults). Java client defaults to 131072.
  83. socket_options (list): List of tuple-arguments to socket.setsockopt
  84. to apply to broker connection sockets. Default:
  85. [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]
  86. metadata_max_age_ms (int): The period of time in milliseconds after
  87. which we force a refresh of metadata even if we haven't seen any
  88. partition leadership changes to proactively discover any new
  89. brokers or partitions. Default: 300000
  90. security_protocol (str): Protocol used to communicate with brokers.
  91. Valid values are: PLAINTEXT, SSL, SASL_PLAINTEXT, SASL_SSL.
  92. Default: PLAINTEXT.
  93. ssl_context (ssl.SSLContext): Pre-configured SSLContext for wrapping
  94. socket connections. If provided, all other ssl_* configurations
  95. will be ignored. Default: None.
  96. ssl_check_hostname (bool): Flag to configure whether SSL handshake
  97. should verify that the certificate matches the broker's hostname.
  98. Default: True.
  99. ssl_cafile (str): Optional filename of CA file to use in certificate
  100. verification. Default: None.
  101. ssl_certfile (str): Optional filename of file in PEM format containing
  102. the client certificate, as well as any CA certificates needed to
  103. establish the certificate's authenticity. Default: None.
  104. ssl_keyfile (str): Optional filename containing the client private key.
  105. Default: None.
  106. ssl_password (str): Optional password to be used when loading the
  107. certificate chain. Default: None.
  108. ssl_crlfile (str): Optional filename containing the CRL to check for
  109. certificate expiration. By default, no CRL check is done. When
  110. providing a file, only the leaf certificate will be checked against
  111. this CRL. The CRL can only be checked with Python 3.4+ or 2.7.9+.
  112. Default: None.
  113. api_version (tuple): Specify which Kafka API version to use. If set
  114. to None, KafkaClient will attempt to infer the broker version by
  115. probing various APIs. Example: (0, 10, 2). Default: None
  116. api_version_auto_timeout_ms (int): number of milliseconds to throw a
  117. timeout exception from the constructor when checking the broker
  118. api version. Only applies if api_version is None
  119. selector (selectors.BaseSelector): Provide a specific selector
  120. implementation to use for I/O multiplexing.
  121. Default: selectors.DefaultSelector
  122. metrics (kafka.metrics.Metrics): Optionally provide a metrics
  123. instance for capturing network IO stats. Default: None.
  124. metric_group_prefix (str): Prefix for metric names. Default: ''
  125. sasl_mechanism (str): Authentication mechanism when security_protocol
  126. is configured for SASL_PLAINTEXT or SASL_SSL. Valid values are:
  127. PLAIN, GSSAPI, OAUTHBEARER, SCRAM-SHA-256, SCRAM-SHA-512.
  128. sasl_plain_username (str): username for sasl PLAIN and SCRAM authentication.
  129. Required if sasl_mechanism is PLAIN or one of the SCRAM mechanisms.
  130. sasl_plain_password (str): password for sasl PLAIN and SCRAM authentication.
  131. Required if sasl_mechanism is PLAIN or one of the SCRAM mechanisms.
  132. sasl_kerberos_service_name (str): Service name to include in GSSAPI
  133. sasl mechanism handshake. Default: 'kafka'
  134. sasl_kerberos_domain_name (str): kerberos domain name to use in GSSAPI
  135. sasl mechanism handshake. Default: one of bootstrap servers
  136. sasl_oauth_token_provider (AbstractTokenProvider): OAuthBearer token provider
  137. instance. (See kafka.oauth.abstract). Default: None
  138. """
  139. DEFAULT_CONFIG = {
  140. # client configs
  141. 'bootstrap_servers': 'localhost',
  142. 'client_id': 'kafka-python-' + __version__,
  143. 'request_timeout_ms': 30000,
  144. 'connections_max_idle_ms': 9 * 60 * 1000,
  145. 'reconnect_backoff_ms': 50,
  146. 'reconnect_backoff_max_ms': 1000,
  147. 'max_in_flight_requests_per_connection': 5,
  148. 'receive_buffer_bytes': None,
  149. 'send_buffer_bytes': None,
  150. 'socket_options': [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)],
  151. 'sock_chunk_bytes': 4096, # undocumented experimental option
  152. 'sock_chunk_buffer_count': 1000, # undocumented experimental option
  153. 'retry_backoff_ms': 100,
  154. 'metadata_max_age_ms': 300000,
  155. 'security_protocol': 'PLAINTEXT',
  156. 'ssl_context': None,
  157. 'ssl_check_hostname': True,
  158. 'ssl_cafile': None,
  159. 'ssl_certfile': None,
  160. 'ssl_keyfile': None,
  161. 'ssl_password': None,
  162. 'ssl_crlfile': None,
  163. 'api_version': None,
  164. 'api_version_auto_timeout_ms': 2000,
  165. 'selector': selectors.DefaultSelector,
  166. 'sasl_mechanism': None,
  167. 'sasl_plain_username': None,
  168. 'sasl_plain_password': None,
  169. 'sasl_kerberos_service_name': 'kafka',
  170. 'sasl_kerberos_domain_name': None,
  171. 'sasl_oauth_token_provider': None,
  172. # metrics configs
  173. 'metric_reporters': [],
  174. 'metrics_num_samples': 2,
  175. 'metrics_sample_window_ms': 30000,
  176. }
  177. def __init__(self, **configs):
  178. log.debug("Starting KafkaAdminClient with configuration: %s", configs)
  179. extra_configs = set(configs).difference(self.DEFAULT_CONFIG)
  180. if extra_configs:
  181. raise KafkaConfigurationError("Unrecognized configs: {}".format(extra_configs))
  182. self.config = copy.copy(self.DEFAULT_CONFIG)
  183. self.config.update(configs)
  184. # Configure metrics
  185. metrics_tags = {'client-id': self.config['client_id']}
  186. metric_config = MetricConfig(samples=self.config['metrics_num_samples'],
  187. time_window_ms=self.config['metrics_sample_window_ms'],
  188. tags=metrics_tags)
  189. reporters = [reporter() for reporter in self.config['metric_reporters']]
  190. self._metrics = Metrics(metric_config, reporters)
  191. self._client = KafkaClient(metrics=self._metrics,
  192. metric_group_prefix='admin',
  193. **self.config)
  194. self._client.check_version(timeout=(self.config['api_version_auto_timeout_ms'] / 1000))
  195. # Get auto-discovered version from client if necessary
  196. if self.config['api_version'] is None:
  197. self.config['api_version'] = self._client.config['api_version']
  198. self._closed = False
  199. self._refresh_controller_id()
  200. log.debug("KafkaAdminClient started.")
  201. def close(self):
  202. """Close the KafkaAdminClient connection to the Kafka broker."""
  203. if not hasattr(self, '_closed') or self._closed:
  204. log.info("KafkaAdminClient already closed.")
  205. return
  206. self._metrics.close()
  207. self._client.close()
  208. self._closed = True
  209. log.debug("KafkaAdminClient is now closed.")
  210. def _matching_api_version(self, operation):
  211. """Find the latest version of the protocol operation supported by both
  212. this library and the broker.
  213. This resolves to the lesser of either the latest api version this
  214. library supports, or the max version supported by the broker.
  215. :param operation: A list of protocol operation versions from kafka.protocol.
  216. :return: The max matching version number between client and broker.
  217. """
  218. broker_api_versions = self._client.get_api_versions()
  219. api_key = operation[0].API_KEY
  220. if broker_api_versions is None or api_key not in broker_api_versions:
  221. raise IncompatibleBrokerVersion(
  222. "Kafka broker does not support the '{}' Kafka protocol."
  223. .format(operation[0].__name__))
  224. min_version, max_version = broker_api_versions[api_key]
  225. version = min(len(operation) - 1, max_version)
  226. if version < min_version:
  227. # max library version is less than min broker version. Currently,
  228. # no Kafka versions specify a min msg version. Maybe in the future?
  229. raise IncompatibleBrokerVersion(
  230. "No version of the '{}' Kafka protocol is supported by both the client and broker."
  231. .format(operation[0].__name__))
  232. return version
  233. def _validate_timeout(self, timeout_ms):
  234. """Validate the timeout is set or use the configuration default.
  235. :param timeout_ms: The timeout provided by api call, in milliseconds.
  236. :return: The timeout to use for the operation.
  237. """
  238. return timeout_ms or self.config['request_timeout_ms']
  239. def _refresh_controller_id(self):
  240. """Determine the Kafka cluster controller."""
  241. version = self._matching_api_version(MetadataRequest)
  242. if 1 <= version <= 6:
  243. request = MetadataRequest[version]()
  244. future = self._send_request_to_node(self._client.least_loaded_node(), request)
  245. self._wait_for_futures([future])
  246. response = future.value
  247. controller_id = response.controller_id
  248. # verify the controller is new enough to support our requests
  249. controller_version = self._client.check_version(controller_id, timeout=(self.config['api_version_auto_timeout_ms'] / 1000))
  250. if controller_version < (0, 10, 0):
  251. raise IncompatibleBrokerVersion(
  252. "The controller appears to be running Kafka {}. KafkaAdminClient requires brokers >= 0.10.0.0."
  253. .format(controller_version))
  254. self._controller_id = controller_id
  255. else:
  256. raise UnrecognizedBrokerVersion(
  257. "Kafka Admin interface cannot determine the controller using MetadataRequest_v{}."
  258. .format(version))
  259. def _find_coordinator_id_send_request(self, group_id):
  260. """Send a FindCoordinatorRequest to a broker.
  261. :param group_id: The consumer group ID. This is typically the group
  262. name as a string.
  263. :return: A message future
  264. """
  265. # TODO add support for dynamically picking version of
  266. # GroupCoordinatorRequest which was renamed to FindCoordinatorRequest.
  267. # When I experimented with this, the coordinator value returned in
  268. # GroupCoordinatorResponse_v1 didn't match the value returned by
  269. # GroupCoordinatorResponse_v0 and I couldn't figure out why.
  270. version = 0
  271. # version = self._matching_api_version(GroupCoordinatorRequest)
  272. if version <= 0:
  273. request = GroupCoordinatorRequest[version](group_id)
  274. else:
  275. raise NotImplementedError(
  276. "Support for GroupCoordinatorRequest_v{} has not yet been added to KafkaAdminClient."
  277. .format(version))
  278. return self._send_request_to_node(self._client.least_loaded_node(), request)
  279. def _find_coordinator_id_process_response(self, response):
  280. """Process a FindCoordinatorResponse.
  281. :param response: a FindCoordinatorResponse.
  282. :return: The node_id of the broker that is the coordinator.
  283. """
  284. if response.API_VERSION <= 0:
  285. error_type = Errors.for_code(response.error_code)
  286. if error_type is not Errors.NoError:
  287. # Note: When error_type.retriable, Java will retry... see
  288. # KafkaAdminClient's handleFindCoordinatorError method
  289. raise error_type(
  290. "FindCoordinatorRequest failed with response '{}'."
  291. .format(response))
  292. else:
  293. raise NotImplementedError(
  294. "Support for FindCoordinatorRequest_v{} has not yet been added to KafkaAdminClient."
  295. .format(response.API_VERSION))
  296. return response.coordinator_id
  297. def _find_coordinator_ids(self, group_ids):
  298. """Find the broker node_ids of the coordinators of the given groups.
  299. Sends a FindCoordinatorRequest message to the cluster for each group_id.
  300. Will block until the FindCoordinatorResponse is received for all groups.
  301. Any errors are immediately raised.
  302. :param group_ids: A list of consumer group IDs. This is typically the group
  303. name as a string.
  304. :return: A dict of {group_id: node_id} where node_id is the id of the
  305. broker that is the coordinator for the corresponding group.
  306. """
  307. groups_futures = {
  308. group_id: self._find_coordinator_id_send_request(group_id)
  309. for group_id in group_ids
  310. }
  311. self._wait_for_futures(groups_futures.values())
  312. groups_coordinators = {
  313. group_id: self._find_coordinator_id_process_response(future.value)
  314. for group_id, future in groups_futures.items()
  315. }
  316. return groups_coordinators
  317. def _send_request_to_node(self, node_id, request):
  318. """Send a Kafka protocol message to a specific broker.
  319. Returns a future that may be polled for status and results.
  320. :param node_id: The broker id to which to send the message.
  321. :param request: The message to send.
  322. :return: A future object that may be polled for status and results.
  323. :exception: The exception if the message could not be sent.
  324. """
  325. while not self._client.ready(node_id):
  326. # poll until the connection to broker is ready, otherwise send()
  327. # will fail with NodeNotReadyError
  328. self._client.poll()
  329. return self._client.send(node_id, request)
  330. def _send_request_to_controller(self, request):
  331. """Send a Kafka protocol message to the cluster controller.
  332. Will block until the message result is received.
  333. :param request: The message to send.
  334. :return: The Kafka protocol response for the message.
  335. """
  336. tries = 2 # in case our cached self._controller_id is outdated
  337. while tries:
  338. tries -= 1
  339. future = self._send_request_to_node(self._controller_id, request)
  340. self._wait_for_futures([future])
  341. response = future.value
  342. # In Java, the error field name is inconsistent:
  343. # - CreateTopicsResponse / CreatePartitionsResponse uses topic_errors
  344. # - DeleteTopicsResponse uses topic_error_codes
  345. # So this is a little brittle in that it assumes all responses have
  346. # one of these attributes and that they always unpack into
  347. # (topic, error_code) tuples.
  348. topic_error_tuples = (response.topic_errors if hasattr(response, 'topic_errors')
  349. else response.topic_error_codes)
  350. # Also small py2/py3 compatibility -- py3 can ignore extra values
  351. # during unpack via: for x, y, *rest in list_of_values. py2 cannot.
  352. # So for now we have to map across the list and explicitly drop any
  353. # extra values (usually the error_message)
  354. for topic, error_code in map(lambda e: e[:2], topic_error_tuples):
  355. error_type = Errors.for_code(error_code)
  356. if tries and error_type is NotControllerError:
  357. # No need to inspect the rest of the errors for
  358. # non-retriable errors because NotControllerError should
  359. # either be thrown for all errors or no errors.
  360. self._refresh_controller_id()
  361. break
  362. elif error_type is not Errors.NoError:
  363. raise error_type(
  364. "Request '{}' failed with response '{}'."
  365. .format(request, response))
  366. else:
  367. return response
  368. raise RuntimeError("This should never happen, please file a bug with full stacktrace if encountered")
  369. @staticmethod
  370. def _convert_new_topic_request(new_topic):
  371. return (
  372. new_topic.name,
  373. new_topic.num_partitions,
  374. new_topic.replication_factor,
  375. [
  376. (partition_id, replicas) for partition_id, replicas in new_topic.replica_assignments.items()
  377. ],
  378. [
  379. (config_key, config_value) for config_key, config_value in new_topic.topic_configs.items()
  380. ]
  381. )
  382. def create_topics(self, new_topics, timeout_ms=None, validate_only=False):
  383. """Create new topics in the cluster.
  384. :param new_topics: A list of NewTopic objects.
  385. :param timeout_ms: Milliseconds to wait for new topics to be created
  386. before the broker returns.
  387. :param validate_only: If True, don't actually create new topics.
  388. Not supported by all versions. Default: False
  389. :return: Appropriate version of CreateTopicResponse class.
  390. """
  391. version = self._matching_api_version(CreateTopicsRequest)
  392. timeout_ms = self._validate_timeout(timeout_ms)
  393. if version == 0:
  394. if validate_only:
  395. raise IncompatibleBrokerVersion(
  396. "validate_only requires CreateTopicsRequest >= v1, which is not supported by Kafka {}."
  397. .format(self.config['api_version']))
  398. request = CreateTopicsRequest[version](
  399. create_topic_requests=[self._convert_new_topic_request(new_topic) for new_topic in new_topics],
  400. timeout=timeout_ms
  401. )
  402. elif version <= 3:
  403. request = CreateTopicsRequest[version](
  404. create_topic_requests=[self._convert_new_topic_request(new_topic) for new_topic in new_topics],
  405. timeout=timeout_ms,
  406. validate_only=validate_only
  407. )
  408. else:
  409. raise NotImplementedError(
  410. "Support for CreateTopics v{} has not yet been added to KafkaAdminClient."
  411. .format(version))
  412. # TODO convert structs to a more pythonic interface
  413. # TODO raise exceptions if errors
  414. return self._send_request_to_controller(request)
  415. def delete_topics(self, topics, timeout_ms=None):
  416. """Delete topics from the cluster.
  417. :param topics: A list of topic name strings.
  418. :param timeout_ms: Milliseconds to wait for topics to be deleted
  419. before the broker returns.
  420. :return: Appropriate version of DeleteTopicsResponse class.
  421. """
  422. version = self._matching_api_version(DeleteTopicsRequest)
  423. timeout_ms = self._validate_timeout(timeout_ms)
  424. if version <= 3:
  425. request = DeleteTopicsRequest[version](
  426. topics=topics,
  427. timeout=timeout_ms
  428. )
  429. response = self._send_request_to_controller(request)
  430. else:
  431. raise NotImplementedError(
  432. "Support for DeleteTopics v{} has not yet been added to KafkaAdminClient."
  433. .format(version))
  434. return response
  435. def _get_cluster_metadata(self, topics=None, auto_topic_creation=False):
  436. """
  437. topics == None means "get all topics"
  438. """
  439. version = self._matching_api_version(MetadataRequest)
  440. if version <= 3:
  441. if auto_topic_creation:
  442. raise IncompatibleBrokerVersion(
  443. "auto_topic_creation requires MetadataRequest >= v4, which"
  444. " is not supported by Kafka {}"
  445. .format(self.config['api_version']))
  446. request = MetadataRequest[version](topics=topics)
  447. elif version <= 5:
  448. request = MetadataRequest[version](
  449. topics=topics,
  450. allow_auto_topic_creation=auto_topic_creation
  451. )
  452. future = self._send_request_to_node(
  453. self._client.least_loaded_node(),
  454. request
  455. )
  456. self._wait_for_futures([future])
  457. return future.value
  458. def list_topics(self):
  459. metadata = self._get_cluster_metadata(topics=None)
  460. obj = metadata.to_object()
  461. return [t['topic'] for t in obj['topics']]
  462. def describe_topics(self, topics=None):
  463. metadata = self._get_cluster_metadata(topics=topics)
  464. obj = metadata.to_object()
  465. return obj['topics']
  466. def describe_cluster(self):
  467. metadata = self._get_cluster_metadata()
  468. obj = metadata.to_object()
  469. obj.pop('topics') # We have 'describe_topics' for this
  470. return obj
  471. @staticmethod
  472. def _convert_describe_acls_response_to_acls(describe_response):
  473. version = describe_response.API_VERSION
  474. error = Errors.for_code(describe_response.error_code)
  475. acl_list = []
  476. for resources in describe_response.resources:
  477. if version == 0:
  478. resource_type, resource_name, acls = resources
  479. resource_pattern_type = ACLResourcePatternType.LITERAL.value
  480. elif version <= 1:
  481. resource_type, resource_name, resource_pattern_type, acls = resources
  482. else:
  483. raise NotImplementedError(
  484. "Support for DescribeAcls Response v{} has not yet been added to KafkaAdmin."
  485. .format(version)
  486. )
  487. for acl in acls:
  488. principal, host, operation, permission_type = acl
  489. conv_acl = ACL(
  490. principal=principal,
  491. host=host,
  492. operation=ACLOperation(operation),
  493. permission_type=ACLPermissionType(permission_type),
  494. resource_pattern=ResourcePattern(
  495. ResourceType(resource_type),
  496. resource_name,
  497. ACLResourcePatternType(resource_pattern_type)
  498. )
  499. )
  500. acl_list.append(conv_acl)
  501. return (acl_list, error,)
  502. def describe_acls(self, acl_filter):
  503. """Describe a set of ACLs
  504. Used to return a set of ACLs matching the supplied ACLFilter.
  505. The cluster must be configured with an authorizer for this to work, or
  506. you will get a SecurityDisabledError
  507. :param acl_filter: an ACLFilter object
  508. :return: tuple of a list of matching ACL objects and a KafkaError (NoError if successful)
  509. """
  510. version = self._matching_api_version(DescribeAclsRequest)
  511. if version == 0:
  512. request = DescribeAclsRequest[version](
  513. resource_type=acl_filter.resource_pattern.resource_type,
  514. resource_name=acl_filter.resource_pattern.resource_name,
  515. principal=acl_filter.principal,
  516. host=acl_filter.host,
  517. operation=acl_filter.operation,
  518. permission_type=acl_filter.permission_type
  519. )
  520. elif version <= 1:
  521. request = DescribeAclsRequest[version](
  522. resource_type=acl_filter.resource_pattern.resource_type,
  523. resource_name=acl_filter.resource_pattern.resource_name,
  524. resource_pattern_type_filter=acl_filter.resource_pattern.pattern_type,
  525. principal=acl_filter.principal,
  526. host=acl_filter.host,
  527. operation=acl_filter.operation,
  528. permission_type=acl_filter.permission_type
  529. )
  530. else:
  531. raise NotImplementedError(
  532. "Support for DescribeAcls v{} has not yet been added to KafkaAdmin."
  533. .format(version)
  534. )
  535. future = self._send_request_to_node(self._client.least_loaded_node(), request)
  536. self._wait_for_futures([future])
  537. response = future.value
  538. error_type = Errors.for_code(response.error_code)
  539. if error_type is not Errors.NoError:
  540. # optionally we could retry if error_type.retriable
  541. raise error_type(
  542. "Request '{}' failed with response '{}'."
  543. .format(request, response))
  544. return self._convert_describe_acls_response_to_acls(response)
  545. @staticmethod
  546. def _convert_create_acls_resource_request_v0(acl):
  547. return (
  548. acl.resource_pattern.resource_type,
  549. acl.resource_pattern.resource_name,
  550. acl.principal,
  551. acl.host,
  552. acl.operation,
  553. acl.permission_type
  554. )
  555. @staticmethod
  556. def _convert_create_acls_resource_request_v1(acl):
  557. return (
  558. acl.resource_pattern.resource_type,
  559. acl.resource_pattern.resource_name,
  560. acl.resource_pattern.pattern_type,
  561. acl.principal,
  562. acl.host,
  563. acl.operation,
  564. acl.permission_type
  565. )
  566. @staticmethod
  567. def _convert_create_acls_response_to_acls(acls, create_response):
  568. version = create_response.API_VERSION
  569. creations_error = []
  570. creations_success = []
  571. for i, creations in enumerate(create_response.creation_responses):
  572. if version <= 1:
  573. error_code, error_message = creations
  574. acl = acls[i]
  575. error = Errors.for_code(error_code)
  576. else:
  577. raise NotImplementedError(
  578. "Support for DescribeAcls Response v{} has not yet been added to KafkaAdmin."
  579. .format(version)
  580. )
  581. if error is Errors.NoError:
  582. creations_success.append(acl)
  583. else:
  584. creations_error.append((acl, error,))
  585. return {"succeeded": creations_success, "failed": creations_error}
  586. def create_acls(self, acls):
  587. """Create a list of ACLs
  588. This endpoint only accepts a list of concrete ACL objects, no ACLFilters.
  589. Throws TopicAlreadyExistsError if topic is already present.
  590. :param acls: a list of ACL objects
  591. :return: dict of successes and failures
  592. """
  593. for acl in acls:
  594. if not isinstance(acl, ACL):
  595. raise IllegalArgumentError("acls must contain ACL objects")
  596. version = self._matching_api_version(CreateAclsRequest)
  597. if version == 0:
  598. request = CreateAclsRequest[version](
  599. creations=[self._convert_create_acls_resource_request_v0(acl) for acl in acls]
  600. )
  601. elif version <= 1:
  602. request = CreateAclsRequest[version](
  603. creations=[self._convert_create_acls_resource_request_v1(acl) for acl in acls]
  604. )
  605. else:
  606. raise NotImplementedError(
  607. "Support for CreateAcls v{} has not yet been added to KafkaAdmin."
  608. .format(version)
  609. )
  610. future = self._send_request_to_node(self._client.least_loaded_node(), request)
  611. self._wait_for_futures([future])
  612. response = future.value
  613. return self._convert_create_acls_response_to_acls(acls, response)
  614. @staticmethod
  615. def _convert_delete_acls_resource_request_v0(acl):
  616. return (
  617. acl.resource_pattern.resource_type,
  618. acl.resource_pattern.resource_name,
  619. acl.principal,
  620. acl.host,
  621. acl.operation,
  622. acl.permission_type
  623. )
  624. @staticmethod
  625. def _convert_delete_acls_resource_request_v1(acl):
  626. return (
  627. acl.resource_pattern.resource_type,
  628. acl.resource_pattern.resource_name,
  629. acl.resource_pattern.pattern_type,
  630. acl.principal,
  631. acl.host,
  632. acl.operation,
  633. acl.permission_type
  634. )
  635. @staticmethod
  636. def _convert_delete_acls_response_to_matching_acls(acl_filters, delete_response):
  637. version = delete_response.API_VERSION
  638. filter_result_list = []
  639. for i, filter_responses in enumerate(delete_response.filter_responses):
  640. filter_error_code, filter_error_message, matching_acls = filter_responses
  641. filter_error = Errors.for_code(filter_error_code)
  642. acl_result_list = []
  643. for acl in matching_acls:
  644. if version == 0:
  645. error_code, error_message, resource_type, resource_name, principal, host, operation, permission_type = acl
  646. resource_pattern_type = ACLResourcePatternType.LITERAL.value
  647. elif version == 1:
  648. error_code, error_message, resource_type, resource_name, resource_pattern_type, principal, host, operation, permission_type = acl
  649. else:
  650. raise NotImplementedError(
  651. "Support for DescribeAcls Response v{} has not yet been added to KafkaAdmin."
  652. .format(version)
  653. )
  654. acl_error = Errors.for_code(error_code)
  655. conv_acl = ACL(
  656. principal=principal,
  657. host=host,
  658. operation=ACLOperation(operation),
  659. permission_type=ACLPermissionType(permission_type),
  660. resource_pattern=ResourcePattern(
  661. ResourceType(resource_type),
  662. resource_name,
  663. ACLResourcePatternType(resource_pattern_type)
  664. )
  665. )
  666. acl_result_list.append((conv_acl, acl_error,))
  667. filter_result_list.append((acl_filters[i], acl_result_list, filter_error,))
  668. return filter_result_list
  669. def delete_acls(self, acl_filters):
  670. """Delete a set of ACLs
  671. Deletes all ACLs matching the list of input ACLFilter
  672. :param acl_filters: a list of ACLFilter
  673. :return: a list of 3-tuples corresponding to the list of input filters.
  674. The tuples hold (the input ACLFilter, list of affected ACLs, KafkaError instance)
  675. """
  676. for acl in acl_filters:
  677. if not isinstance(acl, ACLFilter):
  678. raise IllegalArgumentError("acl_filters must contain ACLFilter type objects")
  679. version = self._matching_api_version(DeleteAclsRequest)
  680. if version == 0:
  681. request = DeleteAclsRequest[version](
  682. filters=[self._convert_delete_acls_resource_request_v0(acl) for acl in acl_filters]
  683. )
  684. elif version <= 1:
  685. request = DeleteAclsRequest[version](
  686. filters=[self._convert_delete_acls_resource_request_v1(acl) for acl in acl_filters]
  687. )
  688. else:
  689. raise NotImplementedError(
  690. "Support for DeleteAcls v{} has not yet been added to KafkaAdmin."
  691. .format(version)
  692. )
  693. future = self._send_request_to_node(self._client.least_loaded_node(), request)
  694. self._wait_for_futures([future])
  695. response = future.value
  696. return self._convert_delete_acls_response_to_matching_acls(acl_filters, response)
  697. @staticmethod
  698. def _convert_describe_config_resource_request(config_resource):
  699. return (
  700. config_resource.resource_type,
  701. config_resource.name,
  702. [
  703. config_key for config_key, config_value in config_resource.configs.items()
  704. ] if config_resource.configs else None
  705. )
  706. def describe_configs(self, config_resources, include_synonyms=False):
  707. """Fetch configuration parameters for one or more Kafka resources.
  708. :param config_resources: An list of ConfigResource objects.
  709. Any keys in ConfigResource.configs dict will be used to filter the
  710. result. Setting the configs dict to None will get all values. An
  711. empty dict will get zero values (as per Kafka protocol).
  712. :param include_synonyms: If True, return synonyms in response. Not
  713. supported by all versions. Default: False.
  714. :return: Appropriate version of DescribeConfigsResponse class.
  715. """
  716. # Break up requests by type - a broker config request must be sent to the specific broker.
  717. # All other (currently just topic resources) can be sent to any broker.
  718. broker_resources = []
  719. topic_resources = []
  720. for config_resource in config_resources:
  721. if config_resource.resource_type == ConfigResourceType.BROKER:
  722. broker_resources.append(self._convert_describe_config_resource_request(config_resource))
  723. else:
  724. topic_resources.append(self._convert_describe_config_resource_request(config_resource))
  725. futures = []
  726. version = self._matching_api_version(DescribeConfigsRequest)
  727. if version == 0:
  728. if include_synonyms:
  729. raise IncompatibleBrokerVersion(
  730. "include_synonyms requires DescribeConfigsRequest >= v1, which is not supported by Kafka {}."
  731. .format(self.config['api_version']))
  732. if len(broker_resources) > 0:
  733. for broker_resource in broker_resources:
  734. try:
  735. broker_id = int(broker_resource[1])
  736. except ValueError:
  737. raise ValueError("Broker resource names must be an integer or a string represented integer")
  738. futures.append(self._send_request_to_node(
  739. broker_id,
  740. DescribeConfigsRequest[version](resources=[broker_resource])
  741. ))
  742. if len(topic_resources) > 0:
  743. futures.append(self._send_request_to_node(
  744. self._client.least_loaded_node(),
  745. DescribeConfigsRequest[version](resources=topic_resources)
  746. ))
  747. elif version <= 2:
  748. if len(broker_resources) > 0:
  749. for broker_resource in broker_resources:
  750. try:
  751. broker_id = int(broker_resource[1])
  752. except ValueError:
  753. raise ValueError("Broker resource names must be an integer or a string represented integer")
  754. futures.append(self._send_request_to_node(
  755. broker_id,
  756. DescribeConfigsRequest[version](
  757. resources=[broker_resource],
  758. include_synonyms=include_synonyms)
  759. ))
  760. if len(topic_resources) > 0:
  761. futures.append(self._send_request_to_node(
  762. self._client.least_loaded_node(),
  763. DescribeConfigsRequest[version](resources=topic_resources, include_synonyms=include_synonyms)
  764. ))
  765. else:
  766. raise NotImplementedError(
  767. "Support for DescribeConfigs v{} has not yet been added to KafkaAdminClient.".format(version))
  768. self._wait_for_futures(futures)
  769. return [f.value for f in futures]
  770. @staticmethod
  771. def _convert_alter_config_resource_request(config_resource):
  772. return (
  773. config_resource.resource_type,
  774. config_resource.name,
  775. [
  776. (config_key, config_value) for config_key, config_value in config_resource.configs.items()
  777. ]
  778. )
  779. def alter_configs(self, config_resources):
  780. """Alter configuration parameters of one or more Kafka resources.
  781. Warning:
  782. This is currently broken for BROKER resources because those must be
  783. sent to that specific broker, versus this always picks the
  784. least-loaded node. See the comment in the source code for details.
  785. We would happily accept a PR fixing this.
  786. :param config_resources: A list of ConfigResource objects.
  787. :return: Appropriate version of AlterConfigsResponse class.
  788. """
  789. version = self._matching_api_version(AlterConfigsRequest)
  790. if version <= 1:
  791. request = AlterConfigsRequest[version](
  792. resources=[self._convert_alter_config_resource_request(config_resource) for config_resource in config_resources]
  793. )
  794. else:
  795. raise NotImplementedError(
  796. "Support for AlterConfigs v{} has not yet been added to KafkaAdminClient."
  797. .format(version))
  798. # TODO the Java client has the note:
  799. # // We must make a separate AlterConfigs request for every BROKER resource we want to alter
  800. # // and send the request to that specific broker. Other resources are grouped together into
  801. # // a single request that may be sent to any broker.
  802. #
  803. # So this is currently broken as it always sends to the least_loaded_node()
  804. future = self._send_request_to_node(self._client.least_loaded_node(), request)
  805. self._wait_for_futures([future])
  806. response = future.value
  807. return response
  808. # alter replica logs dir protocol not yet implemented
  809. # Note: have to lookup the broker with the replica assignment and send the request to that broker
  810. # describe log dirs protocol not yet implemented
  811. # Note: have to lookup the broker with the replica assignment and send the request to that broker
  812. @staticmethod
  813. def _convert_create_partitions_request(topic_name, new_partitions):
  814. return (
  815. topic_name,
  816. (
  817. new_partitions.total_count,
  818. new_partitions.new_assignments
  819. )
  820. )
  821. def create_partitions(self, topic_partitions, timeout_ms=None, validate_only=False):
  822. """Create additional partitions for an existing topic.
  823. :param topic_partitions: A map of topic name strings to NewPartition objects.
  824. :param timeout_ms: Milliseconds to wait for new partitions to be
  825. created before the broker returns.
  826. :param validate_only: If True, don't actually create new partitions.
  827. Default: False
  828. :return: Appropriate version of CreatePartitionsResponse class.
  829. """
  830. version = self._matching_api_version(CreatePartitionsRequest)
  831. timeout_ms = self._validate_timeout(timeout_ms)
  832. if version <= 1:
  833. request = CreatePartitionsRequest[version](
  834. topic_partitions=[self._convert_create_partitions_request(topic_name, new_partitions) for topic_name, new_partitions in topic_partitions.items()],
  835. timeout=timeout_ms,
  836. validate_only=validate_only
  837. )
  838. else:
  839. raise NotImplementedError(
  840. "Support for CreatePartitions v{} has not yet been added to KafkaAdminClient."
  841. .format(version))
  842. return self._send_request_to_controller(request)
  843. # delete records protocol not yet implemented
  844. # Note: send the request to the partition leaders
  845. # create delegation token protocol not yet implemented
  846. # Note: send the request to the least_loaded_node()
  847. # renew delegation token protocol not yet implemented
  848. # Note: send the request to the least_loaded_node()
  849. # expire delegation_token protocol not yet implemented
  850. # Note: send the request to the least_loaded_node()
  851. # describe delegation_token protocol not yet implemented
  852. # Note: send the request to the least_loaded_node()
  853. def _describe_consumer_groups_send_request(self, group_id, group_coordinator_id, include_authorized_operations=False):
  854. """Send a DescribeGroupsRequest to the group's coordinator.
  855. :param group_id: The group name as a string
  856. :param group_coordinator_id: The node_id of the groups' coordinator
  857. broker.
  858. :return: A message future.
  859. """
  860. version = self._matching_api_version(DescribeGroupsRequest)
  861. if version <= 2:
  862. if include_authorized_operations:
  863. raise IncompatibleBrokerVersion(
  864. "include_authorized_operations requests "
  865. "DescribeGroupsRequest >= v3, which is not "
  866. "supported by Kafka {}".format(version)
  867. )
  868. # Note: KAFKA-6788 A potential optimization is to group the
  869. # request per coordinator and send one request with a list of
  870. # all consumer groups. Java still hasn't implemented this
  871. # because the error checking is hard to get right when some
  872. # groups error and others don't.
  873. request = DescribeGroupsRequest[version](groups=(group_id,))
  874. elif version <= 3:
  875. request = DescribeGroupsRequest[version](
  876. groups=(group_id,),
  877. include_authorized_operations=include_authorized_operations
  878. )
  879. else:
  880. raise NotImplementedError(
  881. "Support for DescribeGroupsRequest_v{} has not yet been added to KafkaAdminClient."
  882. .format(version))
  883. return self._send_request_to_node(group_coordinator_id, request)
  884. def _describe_consumer_groups_process_response(self, response):
  885. """Process a DescribeGroupsResponse into a group description."""
  886. if response.API_VERSION <= 3:
  887. assert len(response.groups) == 1
  888. for response_field, response_name in zip(response.SCHEMA.fields, response.SCHEMA.names):
  889. if isinstance(response_field, Array):
  890. described_groups_field_schema = response_field.array_of
  891. described_group = response.__dict__[response_name][0]
  892. described_group_information_list = []
  893. protocol_type_is_consumer = False
  894. for (described_group_information, group_information_name, group_information_field) in zip(described_group, described_groups_field_schema.names, described_groups_field_schema.fields):
  895. if group_information_name == 'protocol_type':
  896. protocol_type = described_group_information
  897. protocol_type_is_consumer = (protocol_type == ConsumerProtocol.PROTOCOL_TYPE or not protocol_type)
  898. if isinstance(group_information_field, Array):
  899. member_information_list = []
  900. member_schema = group_information_field.array_of
  901. for members in described_group_information:
  902. member_information = []
  903. for (member, member_field, member_name) in zip(members, member_schema.fields, member_schema.names):
  904. if protocol_type_is_consumer:
  905. if member_name == 'member_metadata' and member:
  906. member_information.append(ConsumerProtocolMemberMetadata.decode(member))
  907. elif member_name == 'member_assignment' and member:
  908. member_information.append(ConsumerProtocolMemberAssignment.decode(member))
  909. else:
  910. member_information.append(member)
  911. member_info_tuple = MemberInformation._make(member_information)
  912. member_information_list.append(member_info_tuple)
  913. described_group_information_list.append(member_information_list)
  914. else:
  915. described_group_information_list.append(described_group_information)
  916. # Version 3 of the DescribeGroups API introduced the "authorized_operations" field.
  917. # This will cause the namedtuple to fail.
  918. # Therefore, appending a placeholder of None in it.
  919. if response.API_VERSION <=2:
  920. described_group_information_list.append(None)
  921. group_description = GroupInformation._make(described_group_information_list)
  922. error_code = group_description.error_code
  923. error_type = Errors.for_code(error_code)
  924. # Java has the note: KAFKA-6789, we can retry based on the error code
  925. if error_type is not Errors.NoError:
  926. raise error_type(
  927. "DescribeGroupsResponse failed with response '{}'."
  928. .format(response))
  929. else:
  930. raise NotImplementedError(
  931. "Support for DescribeGroupsResponse_v{} has not yet been added to KafkaAdminClient."
  932. .format(response.API_VERSION))
  933. return group_description
  934. def describe_consumer_groups(self, group_ids, group_coordinator_id=None, include_authorized_operations=False):
  935. """Describe a set of consumer groups.
  936. Any errors are immediately raised.
  937. :param group_ids: A list of consumer group IDs. These are typically the
  938. group names as strings.
  939. :param group_coordinator_id: The node_id of the groups' coordinator
  940. broker. If set to None, it will query the cluster for each group to
  941. find that group's coordinator. Explicitly specifying this can be
  942. useful for avoiding extra network round trips if you already know
  943. the group coordinator. This is only useful when all the group_ids
  944. have the same coordinator, otherwise it will error. Default: None.
  945. :param include_authorized_operations: Whether or not to include
  946. information about the operations a group is allowed to perform.
  947. Only supported on API version >= v3. Default: False.
  948. :return: A list of group descriptions. For now the group descriptions
  949. are the raw results from the DescribeGroupsResponse. Long-term, we
  950. plan to change this to return namedtuples as well as decoding the
  951. partition assignments.
  952. """
  953. group_descriptions = []
  954. if group_coordinator_id is not None:
  955. groups_coordinators = {group_id: group_coordinator_id for group_id in group_ids}
  956. else:
  957. groups_coordinators = self._find_coordinator_ids(group_ids)
  958. futures = [
  959. self._describe_consumer_groups_send_request(
  960. group_id,
  961. coordinator_id,
  962. include_authorized_operations)
  963. for group_id, coordinator_id in groups_coordinators.items()
  964. ]
  965. self._wait_for_futures(futures)
  966. for future in futures:
  967. response = future.value
  968. group_description = self._describe_consumer_groups_process_response(response)
  969. group_descriptions.append(group_description)
  970. return group_descriptions
  971. def _list_consumer_groups_send_request(self, broker_id):
  972. """Send a ListGroupsRequest to a broker.
  973. :param broker_id: The broker's node_id.
  974. :return: A message future
  975. """
  976. version = self._matching_api_version(ListGroupsRequest)
  977. if version <= 2:
  978. request = ListGroupsRequest[version]()
  979. else:
  980. raise NotImplementedError(
  981. "Support for ListGroupsRequest_v{} has not yet been added to KafkaAdminClient."
  982. .format(version))
  983. return self._send_request_to_node(broker_id, request)
  984. def _list_consumer_groups_process_response(self, response):
  985. """Process a ListGroupsResponse into a list of groups."""
  986. if response.API_VERSION <= 2:
  987. error_type = Errors.for_code(response.error_code)
  988. if error_type is not Errors.NoError:
  989. raise error_type(
  990. "ListGroupsRequest failed with response '{}'."
  991. .format(response))
  992. else:
  993. raise NotImplementedError(
  994. "Support for ListGroupsResponse_v{} has not yet been added to KafkaAdminClient."
  995. .format(response.API_VERSION))
  996. return response.groups
  997. def list_consumer_groups(self, broker_ids=None):
  998. """List all consumer groups known to the cluster.
  999. This returns a list of Consumer Group tuples. The tuples are
  1000. composed of the consumer group name and the consumer group protocol
  1001. type.
  1002. Only consumer groups that store their offsets in Kafka are returned.
  1003. The protocol type will be an empty string for groups created using
  1004. Kafka < 0.9 APIs because, although they store their offsets in Kafka,
  1005. they don't use Kafka for group coordination. For groups created using
  1006. Kafka >= 0.9, the protocol type will typically be "consumer".
  1007. As soon as any error is encountered, it is immediately raised.
  1008. :param broker_ids: A list of broker node_ids to query for consumer
  1009. groups. If set to None, will query all brokers in the cluster.
  1010. Explicitly specifying broker(s) can be useful for determining which
  1011. consumer groups are coordinated by those broker(s). Default: None
  1012. :return list: List of tuples of Consumer Groups.
  1013. :exception GroupCoordinatorNotAvailableError: The coordinator is not
  1014. available, so cannot process requests.
  1015. :exception GroupLoadInProgressError: The coordinator is loading and
  1016. hence can't process requests.
  1017. """
  1018. # While we return a list, internally use a set to prevent duplicates
  1019. # because if a group coordinator fails after being queried, and its
  1020. # consumer groups move to new brokers that haven't yet been queried,
  1021. # then the same group could be returned by multiple brokers.
  1022. consumer_groups = set()
  1023. if broker_ids is None:
  1024. broker_ids = [broker.nodeId for broker in self._client.cluster.brokers()]
  1025. futures = [self._list_consumer_groups_send_request(b) for b in broker_ids]
  1026. self._wait_for_futures(futures)
  1027. for f in futures:
  1028. response = f.value
  1029. consumer_groups.update(self._list_consumer_groups_process_response(response))
  1030. return list(consumer_groups)
  1031. def _list_consumer_group_offsets_send_request(self, group_id,
  1032. group_coordinator_id, partitions=None):
  1033. """Send an OffsetFetchRequest to a broker.
  1034. :param group_id: The consumer group id name for which to fetch offsets.
  1035. :param group_coordinator_id: The node_id of the group's coordinator
  1036. broker.
  1037. :return: A message future
  1038. """
  1039. version = self._matching_api_version(OffsetFetchRequest)
  1040. if version <= 3:
  1041. if partitions is None:
  1042. if version <= 1:
  1043. raise ValueError(
  1044. """OffsetFetchRequest_v{} requires specifying the
  1045. partitions for which to fetch offsets. Omitting the
  1046. partitions is only supported on brokers >= 0.10.2.
  1047. For details, see KIP-88.""".format(version))
  1048. topics_partitions = None
  1049. else:
  1050. # transform from [TopicPartition("t1", 1), TopicPartition("t1", 2)] to [("t1", [1, 2])]
  1051. topics_partitions_dict = defaultdict(set)
  1052. for topic, partition in partitions:
  1053. topics_partitions_dict[topic].add(partition)
  1054. topics_partitions = list(six.iteritems(topics_partitions_dict))
  1055. request = OffsetFetchRequest[version](group_id, topics_partitions)
  1056. else:
  1057. raise NotImplementedError(
  1058. "Support for OffsetFetchRequest_v{} has not yet been added to KafkaAdminClient."
  1059. .format(version))
  1060. return self._send_request_to_node(group_coordinator_id, request)
  1061. def _list_consumer_group_offsets_process_response(self, response):
  1062. """Process an OffsetFetchResponse.
  1063. :param response: an OffsetFetchResponse.
  1064. :return: A dictionary composed of TopicPartition keys and
  1065. OffsetAndMetada values.
  1066. """
  1067. if response.API_VERSION <= 3:
  1068. # OffsetFetchResponse_v1 lacks a top-level error_code
  1069. if response.API_VERSION > 1:
  1070. error_type = Errors.for_code(response.error_code)
  1071. if error_type is not Errors.NoError:
  1072. # optionally we could retry if error_type.retriable
  1073. raise error_type(
  1074. "OffsetFetchResponse failed with response '{}'."
  1075. .format(response))
  1076. # transform response into a dictionary with TopicPartition keys and
  1077. # OffsetAndMetada values--this is what the Java AdminClient returns
  1078. offsets = {}
  1079. for topic, partitions in response.topics:
  1080. for partition, offset, metadata, error_code in partitions:
  1081. error_type = Errors.for_code(error_code)
  1082. if error_type is not Errors.NoError:
  1083. raise error_type(
  1084. "Unable to fetch consumer group offsets for topic {}, partition {}"
  1085. .format(topic, partition))
  1086. offsets[TopicPartition(topic, partition)] = OffsetAndMetadata(offset, metadata)
  1087. else:
  1088. raise NotImplementedError(
  1089. "Support for OffsetFetchResponse_v{} has not yet been added to KafkaAdminClient."
  1090. .format(response.API_VERSION))
  1091. return offsets
  1092. def list_consumer_group_offsets(self, group_id, group_coordinator_id=None,
  1093. partitions=None):
  1094. """Fetch Consumer Offsets for a single consumer group.
  1095. Note:
  1096. This does not verify that the group_id or partitions actually exist
  1097. in the cluster.
  1098. As soon as any error is encountered, it is immediately raised.
  1099. :param group_id: The consumer group id name for which to fetch offsets.
  1100. :param group_coordinator_id: The node_id of the group's coordinator
  1101. broker. If set to None, will query the cluster to find the group
  1102. coordinator. Explicitly specifying this can be useful to prevent
  1103. that extra network round trip if you already know the group
  1104. coordinator. Default: None.
  1105. :param partitions: A list of TopicPartitions for which to fetch
  1106. offsets. On brokers >= 0.10.2, this can be set to None to fetch all
  1107. known offsets for the consumer group. Default: None.
  1108. :return dictionary: A dictionary with TopicPartition keys and
  1109. OffsetAndMetada values. Partitions that are not specified and for
  1110. which the group_id does not have a recorded offset are omitted. An
  1111. offset value of `-1` indicates the group_id has no offset for that
  1112. TopicPartition. A `-1` can only happen for partitions that are
  1113. explicitly specified.
  1114. """
  1115. if group_coordinator_id is None:
  1116. group_coordinator_id = self._find_coordinator_ids([group_id])[group_id]
  1117. future = self._list_consumer_group_offsets_send_request(
  1118. group_id, group_coordinator_id, partitions)
  1119. self._wait_for_futures([future])
  1120. response = future.value
  1121. return self._list_consumer_group_offsets_process_response(response)
  1122. def delete_consumer_groups(self, group_ids, group_coordinator_id=None):
  1123. """Delete Consumer Group Offsets for given consumer groups.
  1124. Note:
  1125. This does not verify that the group ids actually exist and
  1126. group_coordinator_id is the correct coordinator for all these groups.
  1127. The result needs checking for potential errors.
  1128. :param group_ids: The consumer group ids of the groups which are to be deleted.
  1129. :param group_coordinator_id: The node_id of the broker which is the coordinator for
  1130. all the groups. Use only if all groups are coordinated by the same broker.
  1131. If set to None, will query the cluster to find the coordinator for every single group.
  1132. Explicitly specifying this can be useful to prevent
  1133. that extra network round trips if you already know the group
  1134. coordinator. Default: None.
  1135. :return: A list of tuples (group_id, KafkaError)
  1136. """
  1137. if group_coordinator_id is not None:
  1138. futures = [self._delete_consumer_groups_send_request(group_ids, group_coordinator_id)]
  1139. else:
  1140. coordinators_groups = defaultdict(list)
  1141. for group_id, coordinator_id in self._find_coordinator_ids(group_ids).items():
  1142. coordinators_groups[coordinator_id].append(group_id)
  1143. futures = [
  1144. self._delete_consumer_groups_send_request(group_ids, coordinator_id)
  1145. for coordinator_id, group_ids in coordinators_groups.items()
  1146. ]
  1147. self._wait_for_futures(futures)
  1148. results = []
  1149. for f in futures:
  1150. results.extend(self._convert_delete_groups_response(f.value))
  1151. return results
  1152. def _convert_delete_groups_response(self, response):
  1153. if response.API_VERSION <= 1:
  1154. results = []
  1155. for group_id, error_code in response.results:
  1156. results.append((group_id, Errors.for_code(error_code)))
  1157. return results
  1158. else:
  1159. raise NotImplementedError(
  1160. "Support for DeleteGroupsResponse_v{} has not yet been added to KafkaAdminClient."
  1161. .format(response.API_VERSION))
  1162. def _delete_consumer_groups_send_request(self, group_ids, group_coordinator_id):
  1163. """Send a DeleteGroups request to a broker.
  1164. :param group_ids: The consumer group ids of the groups which are to be deleted.
  1165. :param group_coordinator_id: The node_id of the broker which is the coordinator for
  1166. all the groups.
  1167. :return: A message future
  1168. """
  1169. version = self._matching_api_version(DeleteGroupsRequest)
  1170. if version <= 1:
  1171. request = DeleteGroupsRequest[version](group_ids)
  1172. else:
  1173. raise NotImplementedError(
  1174. "Support for DeleteGroupsRequest_v{} has not yet been added to KafkaAdminClient."
  1175. .format(version))
  1176. return self._send_request_to_node(group_coordinator_id, request)
  1177. def _wait_for_futures(self, futures):
  1178. while not all(future.succeeded() for future in futures):
  1179. for future in futures:
  1180. self._client.poll(future=future)
  1181. if future.failed():
  1182. raise future.exception # pylint: disable-msg=raising-bad-type