client.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  1. from __future__ import absolute_import
  2. import collections
  3. import copy
  4. import functools
  5. import logging
  6. import random
  7. import time
  8. import select
  9. from kafka.vendor import six
  10. import kafka.errors
  11. from kafka.errors import (UnknownError, ConnectionError, FailedPayloadsError,
  12. KafkaTimeoutError, KafkaUnavailableError,
  13. LeaderNotAvailableError, UnknownTopicOrPartitionError,
  14. NotLeaderForPartitionError, ReplicaNotAvailableError)
  15. from kafka.structs import TopicPartition, BrokerMetadata
  16. from kafka.conn import (
  17. collect_hosts, BrokerConnection,
  18. ConnectionStates, get_ip_port_afi)
  19. from kafka.protocol import KafkaProtocol
  20. # New KafkaClient
  21. # this is not exposed in top-level imports yet,
  22. # due to conflicts with legacy SimpleConsumer / SimpleProducer usage
  23. from kafka.client_async import KafkaClient
  24. log = logging.getLogger(__name__)
  25. # Legacy KafkaClient interface -- will be deprecated soon
  26. class SimpleClient(object):
  27. CLIENT_ID = b'kafka-python'
  28. DEFAULT_SOCKET_TIMEOUT_SECONDS = 120
  29. # NOTE: The timeout given to the client should always be greater than the
  30. # one passed to SimpleConsumer.get_message(), otherwise you can get a
  31. # socket timeout.
  32. def __init__(self, hosts, client_id=CLIENT_ID,
  33. timeout=DEFAULT_SOCKET_TIMEOUT_SECONDS,
  34. correlation_id=0):
  35. # We need one connection to bootstrap
  36. self.client_id = client_id
  37. self.timeout = timeout
  38. self.hosts = collect_hosts(hosts)
  39. self.correlation_id = correlation_id
  40. self._conns = {}
  41. self.brokers = {} # broker_id -> BrokerMetadata
  42. self.topics_to_brokers = {} # TopicPartition -> BrokerMetadata
  43. self.topic_partitions = {} # topic -> partition -> leader
  44. self.load_metadata_for_topics() # bootstrap with all metadata
  45. ##################
  46. # Private API #
  47. ##################
  48. def _get_conn(self, host, port, afi):
  49. """Get or create a connection to a broker using host and port"""
  50. host_key = (host, port)
  51. if host_key not in self._conns:
  52. self._conns[host_key] = BrokerConnection(
  53. host, port, afi,
  54. request_timeout_ms=self.timeout * 1000,
  55. client_id=self.client_id
  56. )
  57. conn = self._conns[host_key]
  58. conn.connect()
  59. if conn.connected():
  60. return conn
  61. timeout = time.time() + self.timeout
  62. while time.time() < timeout and conn.connecting():
  63. if conn.connect() is ConnectionStates.CONNECTED:
  64. break
  65. else:
  66. time.sleep(0.05)
  67. else:
  68. conn.close()
  69. raise ConnectionError("%s:%s (%s)" % (host, port, afi))
  70. return conn
  71. def _get_leader_for_partition(self, topic, partition):
  72. """
  73. Returns the leader for a partition or None if the partition exists
  74. but has no leader.
  75. Raises:
  76. UnknownTopicOrPartitionError: If the topic or partition is not part
  77. of the metadata.
  78. LeaderNotAvailableError: If the server has metadata, but there is no
  79. current leader.
  80. """
  81. key = TopicPartition(topic, partition)
  82. # Use cached metadata if it is there
  83. if self.topics_to_brokers.get(key) is not None:
  84. return self.topics_to_brokers[key]
  85. # Otherwise refresh metadata
  86. # If topic does not already exist, this will raise
  87. # UnknownTopicOrPartitionError if not auto-creating
  88. # LeaderNotAvailableError otherwise until partitions are created
  89. self.load_metadata_for_topics(topic)
  90. # If the partition doesn't actually exist, raise
  91. if partition not in self.topic_partitions.get(topic, []):
  92. raise UnknownTopicOrPartitionError(key)
  93. # If there's no leader for the partition, raise
  94. leader = self.topic_partitions[topic][partition]
  95. if leader == -1:
  96. raise LeaderNotAvailableError((topic, partition))
  97. # Otherwise return the BrokerMetadata
  98. return self.brokers[leader]
  99. def _get_coordinator_for_group(self, group):
  100. """
  101. Returns the coordinator broker for a consumer group.
  102. GroupCoordinatorNotAvailableError will be raised if the coordinator
  103. does not currently exist for the group.
  104. GroupLoadInProgressError is raised if the coordinator is available
  105. but is still loading offsets from the internal topic
  106. """
  107. resp = self.send_consumer_metadata_request(group)
  108. # If there's a problem with finding the coordinator, raise the
  109. # provided error
  110. kafka.errors.check_error(resp)
  111. # Otherwise return the BrokerMetadata
  112. return BrokerMetadata(resp.nodeId, resp.host, resp.port, None)
  113. def _next_id(self):
  114. """Generate a new correlation id"""
  115. # modulo to keep w/i int32
  116. self.correlation_id = (self.correlation_id + 1) % 2**31
  117. return self.correlation_id
  118. def _send_broker_unaware_request(self, payloads, encoder_fn, decoder_fn):
  119. """
  120. Attempt to send a broker-agnostic request to one of the available
  121. brokers. Keep trying until you succeed.
  122. """
  123. hosts = set()
  124. for broker in self.brokers.values():
  125. host, port, afi = get_ip_port_afi(broker.host)
  126. hosts.add((host, broker.port, afi))
  127. hosts.update(self.hosts)
  128. hosts = list(hosts)
  129. random.shuffle(hosts)
  130. for (host, port, afi) in hosts:
  131. try:
  132. conn = self._get_conn(host, port, afi)
  133. except ConnectionError:
  134. log.warning("Skipping unconnected connection: %s:%s (AFI %s)",
  135. host, port, afi)
  136. continue
  137. request = encoder_fn(payloads=payloads)
  138. future = conn.send(request)
  139. # Block
  140. while not future.is_done:
  141. conn.recv()
  142. if future.failed():
  143. log.error("Request failed: %s", future.exception)
  144. continue
  145. return decoder_fn(future.value)
  146. raise KafkaUnavailableError('All servers failed to process request: %s' % hosts)
  147. def _payloads_by_broker(self, payloads):
  148. payloads_by_broker = collections.defaultdict(list)
  149. for payload in payloads:
  150. try:
  151. leader = self._get_leader_for_partition(payload.topic, payload.partition)
  152. except (KafkaUnavailableError, LeaderNotAvailableError,
  153. UnknownTopicOrPartitionError):
  154. leader = None
  155. payloads_by_broker[leader].append(payload)
  156. return dict(payloads_by_broker)
  157. def _send_broker_aware_request(self, payloads, encoder_fn, decoder_fn):
  158. """
  159. Group a list of request payloads by topic+partition and send them to
  160. the leader broker for that partition using the supplied encode/decode
  161. functions
  162. Arguments:
  163. payloads: list of object-like entities with a topic (str) and
  164. partition (int) attribute; payloads with duplicate topic-partitions
  165. are not supported.
  166. encode_fn: a method to encode the list of payloads to a request body,
  167. must accept client_id, correlation_id, and payloads as
  168. keyword arguments
  169. decode_fn: a method to decode a response body into response objects.
  170. The response objects must be object-like and have topic
  171. and partition attributes
  172. Returns:
  173. List of response objects in the same order as the supplied payloads
  174. """
  175. # encoders / decoders do not maintain ordering currently
  176. # so we need to keep this so we can rebuild order before returning
  177. original_ordering = [(p.topic, p.partition) for p in payloads]
  178. # Connection errors generally mean stale metadata
  179. # although sometimes it means incorrect api request
  180. # Unfortunately there is no good way to tell the difference
  181. # so we'll just reset metadata on all errors to be safe
  182. refresh_metadata = False
  183. # For each broker, send the list of request payloads
  184. # and collect the responses and errors
  185. payloads_by_broker = self._payloads_by_broker(payloads)
  186. responses = {}
  187. def failed_payloads(payloads):
  188. for payload in payloads:
  189. topic_partition = (str(payload.topic), payload.partition)
  190. responses[(topic_partition)] = FailedPayloadsError(payload)
  191. # For each BrokerConnection keep the real socket so that we can use
  192. # a select to perform unblocking I/O
  193. connections_by_future = {}
  194. for broker, broker_payloads in six.iteritems(payloads_by_broker):
  195. if broker is None:
  196. failed_payloads(broker_payloads)
  197. continue
  198. host, port, afi = get_ip_port_afi(broker.host)
  199. try:
  200. conn = self._get_conn(host, broker.port, afi)
  201. except ConnectionError:
  202. refresh_metadata = True
  203. failed_payloads(broker_payloads)
  204. continue
  205. request = encoder_fn(payloads=broker_payloads)
  206. future = conn.send(request)
  207. if future.failed():
  208. refresh_metadata = True
  209. failed_payloads(broker_payloads)
  210. continue
  211. if not request.expect_response():
  212. for payload in broker_payloads:
  213. topic_partition = (str(payload.topic), payload.partition)
  214. responses[topic_partition] = None
  215. continue
  216. connections_by_future[future] = (conn, broker)
  217. conn = None
  218. while connections_by_future:
  219. futures = list(connections_by_future.keys())
  220. # block until a socket is ready to be read
  221. sockets = [
  222. conn._sock
  223. for future, (conn, _) in six.iteritems(connections_by_future)
  224. if not future.is_done and conn._sock is not None]
  225. if sockets:
  226. read_socks, _, _ = select.select(sockets, [], [])
  227. for future in futures:
  228. if not future.is_done:
  229. conn, _ = connections_by_future[future]
  230. conn.recv()
  231. continue
  232. _, broker = connections_by_future.pop(future)
  233. if future.failed():
  234. refresh_metadata = True
  235. failed_payloads(payloads_by_broker[broker])
  236. else:
  237. for payload_response in decoder_fn(future.value):
  238. topic_partition = (str(payload_response.topic),
  239. payload_response.partition)
  240. responses[topic_partition] = payload_response
  241. if refresh_metadata:
  242. self.reset_all_metadata()
  243. # Return responses in the same order as provided
  244. return [responses[tp] for tp in original_ordering]
  245. def _send_consumer_aware_request(self, group, payloads, encoder_fn, decoder_fn):
  246. """
  247. Send a list of requests to the consumer coordinator for the group
  248. specified using the supplied encode/decode functions. As the payloads
  249. that use consumer-aware requests do not contain the group (e.g.
  250. OffsetFetchRequest), all payloads must be for a single group.
  251. Arguments:
  252. group: the name of the consumer group (str) the payloads are for
  253. payloads: list of object-like entities with topic (str) and
  254. partition (int) attributes; payloads with duplicate
  255. topic+partition are not supported.
  256. encode_fn: a method to encode the list of payloads to a request body,
  257. must accept client_id, correlation_id, and payloads as
  258. keyword arguments
  259. decode_fn: a method to decode a response body into response objects.
  260. The response objects must be object-like and have topic
  261. and partition attributes
  262. Returns:
  263. List of response objects in the same order as the supplied payloads
  264. """
  265. # encoders / decoders do not maintain ordering currently
  266. # so we need to keep this so we can rebuild order before returning
  267. original_ordering = [(p.topic, p.partition) for p in payloads]
  268. broker = self._get_coordinator_for_group(group)
  269. # Send the list of request payloads and collect the responses and
  270. # errors
  271. responses = {}
  272. request_id = self._next_id()
  273. log.debug('Request %s to %s: %s', request_id, broker, payloads)
  274. request = encoder_fn(client_id=self.client_id,
  275. correlation_id=request_id, payloads=payloads)
  276. # Send the request, recv the response
  277. try:
  278. host, port, afi = get_ip_port_afi(broker.host)
  279. conn = self._get_conn(host, broker.port, afi)
  280. conn.send(request_id, request)
  281. except ConnectionError as e:
  282. log.warning('ConnectionError attempting to send request %s '
  283. 'to server %s: %s', request_id, broker, e)
  284. for payload in payloads:
  285. topic_partition = (payload.topic, payload.partition)
  286. responses[topic_partition] = FailedPayloadsError(payload)
  287. # No exception, try to get response
  288. else:
  289. # decoder_fn=None signal that the server is expected to not
  290. # send a response. This probably only applies to
  291. # ProduceRequest w/ acks = 0
  292. if decoder_fn is None:
  293. log.debug('Request %s does not expect a response '
  294. '(skipping conn.recv)', request_id)
  295. for payload in payloads:
  296. topic_partition = (payload.topic, payload.partition)
  297. responses[topic_partition] = None
  298. return []
  299. try:
  300. response = conn.recv(request_id)
  301. except ConnectionError as e:
  302. log.warning('ConnectionError attempting to receive a '
  303. 'response to request %s from server %s: %s',
  304. request_id, broker, e)
  305. for payload in payloads:
  306. topic_partition = (payload.topic, payload.partition)
  307. responses[topic_partition] = FailedPayloadsError(payload)
  308. else:
  309. _resps = []
  310. for payload_response in decoder_fn(response):
  311. topic_partition = (payload_response.topic,
  312. payload_response.partition)
  313. responses[topic_partition] = payload_response
  314. _resps.append(payload_response)
  315. log.debug('Response %s: %s', request_id, _resps)
  316. # Return responses in the same order as provided
  317. return [responses[tp] for tp in original_ordering]
  318. def __repr__(self):
  319. return '<KafkaClient client_id=%s>' % (self.client_id)
  320. def _raise_on_response_error(self, resp):
  321. # Response can be an unraised exception object (FailedPayloadsError)
  322. if isinstance(resp, Exception):
  323. raise resp
  324. # Or a server api error response
  325. try:
  326. kafka.errors.check_error(resp)
  327. except (UnknownTopicOrPartitionError, NotLeaderForPartitionError):
  328. self.reset_topic_metadata(resp.topic)
  329. raise
  330. # Return False if no error to enable list comprehensions
  331. return False
  332. #################
  333. # Public API #
  334. #################
  335. def close(self):
  336. for conn in self._conns.values():
  337. conn.close()
  338. def copy(self):
  339. """
  340. Create an inactive copy of the client object, suitable for passing
  341. to a separate thread.
  342. Note that the copied connections are not initialized, so :meth:`.reinit`
  343. must be called on the returned copy.
  344. """
  345. _conns = self._conns
  346. self._conns = {}
  347. c = copy.deepcopy(self)
  348. self._conns = _conns
  349. return c
  350. def reinit(self):
  351. timeout = time.time() + self.timeout
  352. conns = set(self._conns.values())
  353. for conn in conns:
  354. conn.close()
  355. conn.connect()
  356. while time.time() < timeout:
  357. for conn in list(conns):
  358. conn.connect()
  359. if conn.connected():
  360. conns.remove(conn)
  361. if not conns:
  362. break
  363. def reset_topic_metadata(self, *topics):
  364. for topic in topics:
  365. for topic_partition in list(self.topics_to_brokers.keys()):
  366. if topic_partition.topic == topic:
  367. del self.topics_to_brokers[topic_partition]
  368. if topic in self.topic_partitions:
  369. del self.topic_partitions[topic]
  370. def reset_all_metadata(self):
  371. self.topics_to_brokers.clear()
  372. self.topic_partitions.clear()
  373. def has_metadata_for_topic(self, topic):
  374. return (
  375. topic in self.topic_partitions
  376. and len(self.topic_partitions[topic]) > 0
  377. )
  378. def get_partition_ids_for_topic(self, topic):
  379. if topic not in self.topic_partitions:
  380. return []
  381. return sorted(list(self.topic_partitions[topic]))
  382. @property
  383. def topics(self):
  384. return list(self.topic_partitions.keys())
  385. def ensure_topic_exists(self, topic, timeout=30):
  386. start_time = time.time()
  387. while not self.has_metadata_for_topic(topic):
  388. if time.time() > start_time + timeout:
  389. raise KafkaTimeoutError('Unable to create topic {0}'.format(topic))
  390. self.load_metadata_for_topics(topic, ignore_leadernotavailable=True)
  391. time.sleep(.5)
  392. def load_metadata_for_topics(self, *topics, **kwargs):
  393. """Fetch broker and topic-partition metadata from the server.
  394. Updates internal data: broker list, topic/partition list, and
  395. topic/partition -> broker map. This method should be called after
  396. receiving any error.
  397. Note: Exceptions *will not* be raised in a full refresh (i.e. no topic
  398. list). In this case, error codes will be logged as errors.
  399. Partition-level errors will also not be raised here (a single partition
  400. w/o a leader, for example).
  401. Arguments:
  402. *topics (optional): If a list of topics is provided,
  403. the metadata refresh will be limited to the specified topics
  404. only.
  405. ignore_leadernotavailable (bool): suppress LeaderNotAvailableError
  406. so that metadata is loaded correctly during auto-create.
  407. Default: False.
  408. Raises:
  409. UnknownTopicOrPartitionError: Raised for topics that do not exist,
  410. unless the broker is configured to auto-create topics.
  411. LeaderNotAvailableError: Raised for topics that do not exist yet,
  412. when the broker is configured to auto-create topics. Retry
  413. after a short backoff (topics/partitions are initializing).
  414. """
  415. if 'ignore_leadernotavailable' in kwargs:
  416. ignore_leadernotavailable = kwargs['ignore_leadernotavailable']
  417. else:
  418. ignore_leadernotavailable = False
  419. if topics:
  420. self.reset_topic_metadata(*topics)
  421. else:
  422. self.reset_all_metadata()
  423. resp = self.send_metadata_request(topics)
  424. log.debug('Updating broker metadata: %s', resp.brokers)
  425. log.debug('Updating topic metadata: %s', [topic for _, topic, _ in resp.topics])
  426. self.brokers = dict([(nodeId, BrokerMetadata(nodeId, host, port, None))
  427. for nodeId, host, port in resp.brokers])
  428. for error, topic, partitions in resp.topics:
  429. # Errors expected for new topics
  430. if error:
  431. error_type = kafka.errors.kafka_errors.get(error, UnknownError)
  432. if error_type in (UnknownTopicOrPartitionError, LeaderNotAvailableError):
  433. log.error('Error loading topic metadata for %s: %s (%s)',
  434. topic, error_type, error)
  435. if topic not in topics:
  436. continue
  437. elif (error_type is LeaderNotAvailableError and
  438. ignore_leadernotavailable):
  439. continue
  440. raise error_type(topic)
  441. self.topic_partitions[topic] = {}
  442. for error, partition, leader, _, _ in partitions:
  443. self.topic_partitions[topic][partition] = leader
  444. # Populate topics_to_brokers dict
  445. topic_part = TopicPartition(topic, partition)
  446. # Check for partition errors
  447. if error:
  448. error_type = kafka.errors.kafka_errors.get(error, UnknownError)
  449. # If No Leader, topics_to_brokers topic_partition -> None
  450. if error_type is LeaderNotAvailableError:
  451. log.error('No leader for topic %s partition %d', topic, partition)
  452. self.topics_to_brokers[topic_part] = None
  453. continue
  454. # If one of the replicas is unavailable -- ignore
  455. # this error code is provided for admin purposes only
  456. # we never talk to replicas, only the leader
  457. elif error_type is ReplicaNotAvailableError:
  458. log.debug('Some (non-leader) replicas not available for topic %s partition %d', topic, partition)
  459. else:
  460. raise error_type(topic_part)
  461. # If Known Broker, topic_partition -> BrokerMetadata
  462. if leader in self.brokers:
  463. self.topics_to_brokers[topic_part] = self.brokers[leader]
  464. # If Unknown Broker, fake BrokerMetadata so we don't lose the id
  465. # (not sure how this could happen. server could be in bad state)
  466. else:
  467. self.topics_to_brokers[topic_part] = BrokerMetadata(
  468. leader, None, None, None
  469. )
  470. def send_metadata_request(self, payloads=(), fail_on_error=True,
  471. callback=None):
  472. encoder = KafkaProtocol.encode_metadata_request
  473. decoder = KafkaProtocol.decode_metadata_response
  474. return self._send_broker_unaware_request(payloads, encoder, decoder)
  475. def send_consumer_metadata_request(self, payloads=(), fail_on_error=True,
  476. callback=None):
  477. encoder = KafkaProtocol.encode_consumer_metadata_request
  478. decoder = KafkaProtocol.decode_consumer_metadata_response
  479. return self._send_broker_unaware_request(payloads, encoder, decoder)
  480. def send_produce_request(self, payloads=(), acks=1, timeout=1000,
  481. fail_on_error=True, callback=None):
  482. """
  483. Encode and send some ProduceRequests
  484. ProduceRequests will be grouped by (topic, partition) and then
  485. sent to a specific broker. Output is a list of responses in the
  486. same order as the list of payloads specified
  487. Arguments:
  488. payloads (list of ProduceRequest): produce requests to send to kafka
  489. ProduceRequest payloads must not contain duplicates for any
  490. topic-partition.
  491. acks (int, optional): how many acks the servers should receive from replica
  492. brokers before responding to the request. If it is 0, the server
  493. will not send any response. If it is 1, the server will wait
  494. until the data is written to the local log before sending a
  495. response. If it is -1, the server will wait until the message
  496. is committed by all in-sync replicas before sending a response.
  497. For any value > 1, the server will wait for this number of acks to
  498. occur (but the server will never wait for more acknowledgements than
  499. there are in-sync replicas). defaults to 1.
  500. timeout (int, optional): maximum time in milliseconds the server can
  501. await the receipt of the number of acks, defaults to 1000.
  502. fail_on_error (bool, optional): raise exceptions on connection and
  503. server response errors, defaults to True.
  504. callback (function, optional): instead of returning the ProduceResponse,
  505. first pass it through this function, defaults to None.
  506. Returns:
  507. list of ProduceResponses, or callback results if supplied, in the
  508. order of input payloads
  509. """
  510. encoder = functools.partial(
  511. KafkaProtocol.encode_produce_request,
  512. acks=acks,
  513. timeout=timeout)
  514. if acks == 0:
  515. decoder = None
  516. else:
  517. decoder = KafkaProtocol.decode_produce_response
  518. resps = self._send_broker_aware_request(payloads, encoder, decoder)
  519. return [resp if not callback else callback(resp) for resp in resps
  520. if resp is not None and
  521. (not fail_on_error or not self._raise_on_response_error(resp))]
  522. def send_fetch_request(self, payloads=(), fail_on_error=True,
  523. callback=None, max_wait_time=100, min_bytes=4096):
  524. """
  525. Encode and send a FetchRequest
  526. Payloads are grouped by topic and partition so they can be pipelined
  527. to the same brokers.
  528. """
  529. encoder = functools.partial(KafkaProtocol.encode_fetch_request,
  530. max_wait_time=max_wait_time,
  531. min_bytes=min_bytes)
  532. resps = self._send_broker_aware_request(
  533. payloads, encoder,
  534. KafkaProtocol.decode_fetch_response)
  535. return [resp if not callback else callback(resp) for resp in resps
  536. if not fail_on_error or not self._raise_on_response_error(resp)]
  537. def send_offset_request(self, payloads=(), fail_on_error=True,
  538. callback=None):
  539. resps = self._send_broker_aware_request(
  540. payloads,
  541. KafkaProtocol.encode_offset_request,
  542. KafkaProtocol.decode_offset_response)
  543. return [resp if not callback else callback(resp) for resp in resps
  544. if not fail_on_error or not self._raise_on_response_error(resp)]
  545. def send_list_offset_request(self, payloads=(), fail_on_error=True,
  546. callback=None):
  547. resps = self._send_broker_aware_request(
  548. payloads,
  549. KafkaProtocol.encode_list_offset_request,
  550. KafkaProtocol.decode_list_offset_response)
  551. return [resp if not callback else callback(resp) for resp in resps
  552. if not fail_on_error or not self._raise_on_response_error(resp)]
  553. def send_offset_commit_request(self, group, payloads=(),
  554. fail_on_error=True, callback=None):
  555. encoder = functools.partial(KafkaProtocol.encode_offset_commit_request,
  556. group=group)
  557. decoder = KafkaProtocol.decode_offset_commit_response
  558. resps = self._send_broker_aware_request(payloads, encoder, decoder)
  559. return [resp if not callback else callback(resp) for resp in resps
  560. if not fail_on_error or not self._raise_on_response_error(resp)]
  561. def send_offset_fetch_request(self, group, payloads=(),
  562. fail_on_error=True, callback=None):
  563. encoder = functools.partial(KafkaProtocol.encode_offset_fetch_request,
  564. group=group)
  565. decoder = KafkaProtocol.decode_offset_fetch_response
  566. resps = self._send_broker_aware_request(payloads, encoder, decoder)
  567. return [resp if not callback else callback(resp) for resp in resps
  568. if not fail_on_error or not self._raise_on_response_error(resp)]
  569. def send_offset_fetch_request_kafka(self, group, payloads=(),
  570. fail_on_error=True, callback=None):
  571. encoder = functools.partial(KafkaProtocol.encode_offset_fetch_request,
  572. group=group, from_kafka=True)
  573. decoder = KafkaProtocol.decode_offset_fetch_response
  574. resps = self._send_consumer_aware_request(group, payloads, encoder, decoder)
  575. return [resp if not callback else callback(resp) for resp in resps
  576. if not fail_on_error or not self._raise_on_response_error(resp)]