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.

1221 lines
57 KiB

6 months ago
  1. from __future__ import absolute_import, division
  2. import copy
  3. import logging
  4. import socket
  5. import time
  6. from kafka.errors import KafkaConfigurationError, UnsupportedVersionError
  7. from kafka.vendor import six
  8. from kafka.client_async import KafkaClient, selectors
  9. from kafka.consumer.fetcher import Fetcher
  10. from kafka.consumer.subscription_state import SubscriptionState
  11. from kafka.coordinator.consumer import ConsumerCoordinator
  12. from kafka.coordinator.assignors.range import RangePartitionAssignor
  13. from kafka.coordinator.assignors.roundrobin import RoundRobinPartitionAssignor
  14. from kafka.metrics import MetricConfig, Metrics
  15. from kafka.protocol.offset import OffsetResetStrategy
  16. from kafka.structs import TopicPartition
  17. from kafka.version import __version__
  18. log = logging.getLogger(__name__)
  19. class KafkaConsumer(six.Iterator):
  20. """Consume records from a Kafka cluster.
  21. The consumer will transparently handle the failure of servers in the Kafka
  22. cluster, and adapt as topic-partitions are created or migrate between
  23. brokers. It also interacts with the assigned kafka Group Coordinator node
  24. to allow multiple consumers to load balance consumption of topics (requires
  25. kafka >= 0.9.0.0).
  26. The consumer is not thread safe and should not be shared across threads.
  27. Arguments:
  28. *topics (str): optional list of topics to subscribe to. If not set,
  29. call :meth:`~kafka.KafkaConsumer.subscribe` or
  30. :meth:`~kafka.KafkaConsumer.assign` before consuming records.
  31. Keyword Arguments:
  32. bootstrap_servers: 'host[:port]' string (or list of 'host[:port]'
  33. strings) that the consumer should contact to bootstrap initial
  34. cluster metadata. This does not have to be the full node list.
  35. It just needs to have at least one broker that will respond to a
  36. Metadata API Request. Default port is 9092. If no servers are
  37. specified, will default to localhost:9092.
  38. client_id (str): A name for this client. This string is passed in
  39. each request to servers and can be used to identify specific
  40. server-side log entries that correspond to this client. Also
  41. submitted to GroupCoordinator for logging with respect to
  42. consumer group administration. Default: 'kafka-python-{version}'
  43. group_id (str or None): The name of the consumer group to join for dynamic
  44. partition assignment (if enabled), and to use for fetching and
  45. committing offsets. If None, auto-partition assignment (via
  46. group coordinator) and offset commits are disabled.
  47. Default: None
  48. key_deserializer (callable): Any callable that takes a
  49. raw message key and returns a deserialized key.
  50. value_deserializer (callable): Any callable that takes a
  51. raw message value and returns a deserialized value.
  52. fetch_min_bytes (int): Minimum amount of data the server should
  53. return for a fetch request, otherwise wait up to
  54. fetch_max_wait_ms for more data to accumulate. Default: 1.
  55. fetch_max_wait_ms (int): The maximum amount of time in milliseconds
  56. the server will block before answering the fetch request if
  57. there isn't sufficient data to immediately satisfy the
  58. requirement given by fetch_min_bytes. Default: 500.
  59. fetch_max_bytes (int): The maximum amount of data the server should
  60. return for a fetch request. This is not an absolute maximum, if the
  61. first message in the first non-empty partition of the fetch is
  62. larger than this value, the message will still be returned to
  63. ensure that the consumer can make progress. NOTE: consumer performs
  64. fetches to multiple brokers in parallel so memory usage will depend
  65. on the number of brokers containing partitions for the topic.
  66. Supported Kafka version >= 0.10.1.0. Default: 52428800 (50 MB).
  67. max_partition_fetch_bytes (int): The maximum amount of data
  68. per-partition the server will return. The maximum total memory
  69. used for a request = #partitions * max_partition_fetch_bytes.
  70. This size must be at least as large as the maximum message size
  71. the server allows or else it is possible for the producer to
  72. send messages larger than the consumer can fetch. If that
  73. happens, the consumer can get stuck trying to fetch a large
  74. message on a certain partition. Default: 1048576.
  75. request_timeout_ms (int): Client request timeout in milliseconds.
  76. Default: 305000.
  77. retry_backoff_ms (int): Milliseconds to backoff when retrying on
  78. errors. Default: 100.
  79. reconnect_backoff_ms (int): The amount of time in milliseconds to
  80. wait before attempting to reconnect to a given host.
  81. Default: 50.
  82. reconnect_backoff_max_ms (int): The maximum amount of time in
  83. milliseconds to backoff/wait when reconnecting to a broker that has
  84. repeatedly failed to connect. If provided, the backoff per host
  85. will increase exponentially for each consecutive connection
  86. failure, up to this maximum. Once the maximum is reached,
  87. reconnection attempts will continue periodically with this fixed
  88. rate. To avoid connection storms, a randomization factor of 0.2
  89. will be applied to the backoff resulting in a random range between
  90. 20% below and 20% above the computed value. Default: 1000.
  91. max_in_flight_requests_per_connection (int): Requests are pipelined
  92. to kafka brokers up to this number of maximum requests per
  93. broker connection. Default: 5.
  94. auto_offset_reset (str): A policy for resetting offsets on
  95. OffsetOutOfRange errors: 'earliest' will move to the oldest
  96. available message, 'latest' will move to the most recent. Any
  97. other value will raise the exception. Default: 'latest'.
  98. enable_auto_commit (bool): If True , the consumer's offset will be
  99. periodically committed in the background. Default: True.
  100. auto_commit_interval_ms (int): Number of milliseconds between automatic
  101. offset commits, if enable_auto_commit is True. Default: 5000.
  102. default_offset_commit_callback (callable): Called as
  103. callback(offsets, response) response will be either an Exception
  104. or an OffsetCommitResponse struct. This callback can be used to
  105. trigger custom actions when a commit request completes.
  106. check_crcs (bool): Automatically check the CRC32 of the records
  107. consumed. This ensures no on-the-wire or on-disk corruption to
  108. the messages occurred. This check adds some overhead, so it may
  109. be disabled in cases seeking extreme performance. Default: True
  110. metadata_max_age_ms (int): The period of time in milliseconds after
  111. which we force a refresh of metadata, even if we haven't seen any
  112. partition leadership changes to proactively discover any new
  113. brokers or partitions. Default: 300000
  114. partition_assignment_strategy (list): List of objects to use to
  115. distribute partition ownership amongst consumer instances when
  116. group management is used.
  117. Default: [RangePartitionAssignor, RoundRobinPartitionAssignor]
  118. max_poll_records (int): The maximum number of records returned in a
  119. single call to :meth:`~kafka.KafkaConsumer.poll`. Default: 500
  120. max_poll_interval_ms (int): The maximum delay between invocations of
  121. :meth:`~kafka.KafkaConsumer.poll` when using consumer group
  122. management. This places an upper bound on the amount of time that
  123. the consumer can be idle before fetching more records. If
  124. :meth:`~kafka.KafkaConsumer.poll` is not called before expiration
  125. of this timeout, then the consumer is considered failed and the
  126. group will rebalance in order to reassign the partitions to another
  127. member. Default 300000
  128. session_timeout_ms (int): The timeout used to detect failures when
  129. using Kafka's group management facilities. The consumer sends
  130. periodic heartbeats to indicate its liveness to the broker. If
  131. no heartbeats are received by the broker before the expiration of
  132. this session timeout, then the broker will remove this consumer
  133. from the group and initiate a rebalance. Note that the value must
  134. be in the allowable range as configured in the broker configuration
  135. by group.min.session.timeout.ms and group.max.session.timeout.ms.
  136. Default: 10000
  137. heartbeat_interval_ms (int): The expected time in milliseconds
  138. between heartbeats to the consumer coordinator when using
  139. Kafka's group management facilities. Heartbeats are used to ensure
  140. that the consumer's session stays active and to facilitate
  141. rebalancing when new consumers join or leave the group. The
  142. value must be set lower than session_timeout_ms, but typically
  143. should be set no higher than 1/3 of that value. It can be
  144. adjusted even lower to control the expected time for normal
  145. rebalances. Default: 3000
  146. receive_buffer_bytes (int): The size of the TCP receive buffer
  147. (SO_RCVBUF) to use when reading data. Default: None (relies on
  148. system defaults). The java client defaults to 32768.
  149. send_buffer_bytes (int): The size of the TCP send buffer
  150. (SO_SNDBUF) to use when sending data. Default: None (relies on
  151. system defaults). The java client defaults to 131072.
  152. socket_options (list): List of tuple-arguments to socket.setsockopt
  153. to apply to broker connection sockets. Default:
  154. [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]
  155. consumer_timeout_ms (int): number of milliseconds to block during
  156. message iteration before raising StopIteration (i.e., ending the
  157. iterator). Default block forever [float('inf')].
  158. security_protocol (str): Protocol used to communicate with brokers.
  159. Valid values are: PLAINTEXT, SSL, SASL_PLAINTEXT, SASL_SSL.
  160. Default: PLAINTEXT.
  161. ssl_context (ssl.SSLContext): Pre-configured SSLContext for wrapping
  162. socket connections. If provided, all other ssl_* configurations
  163. will be ignored. Default: None.
  164. ssl_check_hostname (bool): Flag to configure whether ssl handshake
  165. should verify that the certificate matches the brokers hostname.
  166. Default: True.
  167. ssl_cafile (str): Optional filename of ca file to use in certificate
  168. verification. Default: None.
  169. ssl_certfile (str): Optional filename of file in pem format containing
  170. the client certificate, as well as any ca certificates needed to
  171. establish the certificate's authenticity. Default: None.
  172. ssl_keyfile (str): Optional filename containing the client private key.
  173. Default: None.
  174. ssl_password (str): Optional password to be used when loading the
  175. certificate chain. Default: None.
  176. ssl_crlfile (str): Optional filename containing the CRL to check for
  177. certificate expiration. By default, no CRL check is done. When
  178. providing a file, only the leaf certificate will be checked against
  179. this CRL. The CRL can only be checked with Python 3.4+ or 2.7.9+.
  180. Default: None.
  181. ssl_ciphers (str): optionally set the available ciphers for ssl
  182. connections. It should be a string in the OpenSSL cipher list
  183. format. If no cipher can be selected (because compile-time options
  184. or other configuration forbids use of all the specified ciphers),
  185. an ssl.SSLError will be raised. See ssl.SSLContext.set_ciphers
  186. api_version (tuple): Specify which Kafka API version to use. If set to
  187. None, the client will attempt to infer the broker version by probing
  188. various APIs. Different versions enable different functionality.
  189. Examples:
  190. (0, 9) enables full group coordination features with automatic
  191. partition assignment and rebalancing,
  192. (0, 8, 2) enables kafka-storage offset commits with manual
  193. partition assignment only,
  194. (0, 8, 1) enables zookeeper-storage offset commits with manual
  195. partition assignment only,
  196. (0, 8, 0) enables basic functionality but requires manual
  197. partition assignment and offset management.
  198. Default: None
  199. api_version_auto_timeout_ms (int): number of milliseconds to throw a
  200. timeout exception from the constructor when checking the broker
  201. api version. Only applies if api_version set to None.
  202. connections_max_idle_ms: Close idle connections after the number of
  203. milliseconds specified by this config. The broker closes idle
  204. connections after connections.max.idle.ms, so this avoids hitting
  205. unexpected socket disconnected errors on the client.
  206. Default: 540000
  207. metric_reporters (list): A list of classes to use as metrics reporters.
  208. Implementing the AbstractMetricsReporter interface allows plugging
  209. in classes that will be notified of new metric creation. Default: []
  210. metrics_num_samples (int): The number of samples maintained to compute
  211. metrics. Default: 2
  212. metrics_sample_window_ms (int): The maximum age in milliseconds of
  213. samples used to compute metrics. Default: 30000
  214. selector (selectors.BaseSelector): Provide a specific selector
  215. implementation to use for I/O multiplexing.
  216. Default: selectors.DefaultSelector
  217. exclude_internal_topics (bool): Whether records from internal topics
  218. (such as offsets) should be exposed to the consumer. If set to True
  219. the only way to receive records from an internal topic is
  220. subscribing to it. Requires 0.10+ Default: True
  221. sasl_mechanism (str): Authentication mechanism when security_protocol
  222. is configured for SASL_PLAINTEXT or SASL_SSL. Valid values are:
  223. PLAIN, GSSAPI, OAUTHBEARER, SCRAM-SHA-256, SCRAM-SHA-512.
  224. sasl_plain_username (str): username for sasl PLAIN and SCRAM authentication.
  225. Required if sasl_mechanism is PLAIN or one of the SCRAM mechanisms.
  226. sasl_plain_password (str): password for sasl PLAIN and SCRAM authentication.
  227. Required if sasl_mechanism is PLAIN or one of the SCRAM mechanisms.
  228. sasl_kerberos_service_name (str): Service name to include in GSSAPI
  229. sasl mechanism handshake. Default: 'kafka'
  230. sasl_kerberos_domain_name (str): kerberos domain name to use in GSSAPI
  231. sasl mechanism handshake. Default: one of bootstrap servers
  232. sasl_oauth_token_provider (AbstractTokenProvider): OAuthBearer token provider
  233. instance. (See kafka.oauth.abstract). Default: None
  234. Note:
  235. Configuration parameters are described in more detail at
  236. https://kafka.apache.org/documentation/#consumerconfigs
  237. """
  238. DEFAULT_CONFIG = {
  239. 'bootstrap_servers': 'localhost',
  240. 'client_id': 'kafka-python-' + __version__,
  241. 'group_id': None,
  242. 'key_deserializer': None,
  243. 'value_deserializer': None,
  244. 'fetch_max_wait_ms': 500,
  245. 'fetch_min_bytes': 1,
  246. 'fetch_max_bytes': 52428800,
  247. 'max_partition_fetch_bytes': 1 * 1024 * 1024,
  248. 'request_timeout_ms': 305000, # chosen to be higher than the default of max_poll_interval_ms
  249. 'retry_backoff_ms': 100,
  250. 'reconnect_backoff_ms': 50,
  251. 'reconnect_backoff_max_ms': 1000,
  252. 'max_in_flight_requests_per_connection': 5,
  253. 'auto_offset_reset': 'latest',
  254. 'enable_auto_commit': True,
  255. 'auto_commit_interval_ms': 5000,
  256. 'default_offset_commit_callback': lambda offsets, response: True,
  257. 'check_crcs': True,
  258. 'metadata_max_age_ms': 5 * 60 * 1000,
  259. 'partition_assignment_strategy': (RangePartitionAssignor, RoundRobinPartitionAssignor),
  260. 'max_poll_records': 500,
  261. 'max_poll_interval_ms': 300000,
  262. 'session_timeout_ms': 10000,
  263. 'heartbeat_interval_ms': 3000,
  264. 'receive_buffer_bytes': None,
  265. 'send_buffer_bytes': None,
  266. 'socket_options': [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)],
  267. 'sock_chunk_bytes': 4096, # undocumented experimental option
  268. 'sock_chunk_buffer_count': 1000, # undocumented experimental option
  269. 'consumer_timeout_ms': float('inf'),
  270. 'security_protocol': 'PLAINTEXT',
  271. 'ssl_context': None,
  272. 'ssl_check_hostname': True,
  273. 'ssl_cafile': None,
  274. 'ssl_certfile': None,
  275. 'ssl_keyfile': None,
  276. 'ssl_crlfile': None,
  277. 'ssl_password': None,
  278. 'ssl_ciphers': None,
  279. 'api_version': None,
  280. 'api_version_auto_timeout_ms': 2000,
  281. 'connections_max_idle_ms': 9 * 60 * 1000,
  282. 'metric_reporters': [],
  283. 'metrics_num_samples': 2,
  284. 'metrics_sample_window_ms': 30000,
  285. 'metric_group_prefix': 'consumer',
  286. 'selector': selectors.DefaultSelector,
  287. 'exclude_internal_topics': True,
  288. 'sasl_mechanism': None,
  289. 'sasl_plain_username': None,
  290. 'sasl_plain_password': None,
  291. 'sasl_kerberos_service_name': 'kafka',
  292. 'sasl_kerberos_domain_name': None,
  293. 'sasl_oauth_token_provider': None,
  294. 'legacy_iterator': False, # enable to revert to < 1.4.7 iterator
  295. }
  296. DEFAULT_SESSION_TIMEOUT_MS_0_9 = 30000
  297. def __init__(self, *topics, **configs):
  298. # Only check for extra config keys in top-level class
  299. extra_configs = set(configs).difference(self.DEFAULT_CONFIG)
  300. if extra_configs:
  301. raise KafkaConfigurationError("Unrecognized configs: %s" % (extra_configs,))
  302. self.config = copy.copy(self.DEFAULT_CONFIG)
  303. self.config.update(configs)
  304. deprecated = {'smallest': 'earliest', 'largest': 'latest'}
  305. if self.config['auto_offset_reset'] in deprecated:
  306. new_config = deprecated[self.config['auto_offset_reset']]
  307. log.warning('use auto_offset_reset=%s (%s is deprecated)',
  308. new_config, self.config['auto_offset_reset'])
  309. self.config['auto_offset_reset'] = new_config
  310. connections_max_idle_ms = self.config['connections_max_idle_ms']
  311. request_timeout_ms = self.config['request_timeout_ms']
  312. fetch_max_wait_ms = self.config['fetch_max_wait_ms']
  313. if not (fetch_max_wait_ms < request_timeout_ms < connections_max_idle_ms):
  314. raise KafkaConfigurationError(
  315. "connections_max_idle_ms ({}) must be larger than "
  316. "request_timeout_ms ({}) which must be larger than "
  317. "fetch_max_wait_ms ({})."
  318. .format(connections_max_idle_ms, request_timeout_ms, fetch_max_wait_ms))
  319. metrics_tags = {'client-id': self.config['client_id']}
  320. metric_config = MetricConfig(samples=self.config['metrics_num_samples'],
  321. time_window_ms=self.config['metrics_sample_window_ms'],
  322. tags=metrics_tags)
  323. reporters = [reporter() for reporter in self.config['metric_reporters']]
  324. self._metrics = Metrics(metric_config, reporters)
  325. # TODO _metrics likely needs to be passed to KafkaClient, etc.
  326. # api_version was previously a str. Accept old format for now
  327. if isinstance(self.config['api_version'], str):
  328. str_version = self.config['api_version']
  329. if str_version == 'auto':
  330. self.config['api_version'] = None
  331. else:
  332. self.config['api_version'] = tuple(map(int, str_version.split('.')))
  333. log.warning('use api_version=%s [tuple] -- "%s" as str is deprecated',
  334. str(self.config['api_version']), str_version)
  335. self._client = KafkaClient(metrics=self._metrics, **self.config)
  336. # Get auto-discovered version from client if necessary
  337. if self.config['api_version'] is None:
  338. self.config['api_version'] = self._client.config['api_version']
  339. # Coordinator configurations are different for older brokers
  340. # max_poll_interval_ms is not supported directly -- it must the be
  341. # the same as session_timeout_ms. If the user provides one of them,
  342. # use it for both. Otherwise use the old default of 30secs
  343. if self.config['api_version'] < (0, 10, 1):
  344. if 'session_timeout_ms' not in configs:
  345. if 'max_poll_interval_ms' in configs:
  346. self.config['session_timeout_ms'] = configs['max_poll_interval_ms']
  347. else:
  348. self.config['session_timeout_ms'] = self.DEFAULT_SESSION_TIMEOUT_MS_0_9
  349. if 'max_poll_interval_ms' not in configs:
  350. self.config['max_poll_interval_ms'] = self.config['session_timeout_ms']
  351. if self.config['group_id'] is not None:
  352. if self.config['request_timeout_ms'] <= self.config['session_timeout_ms']:
  353. raise KafkaConfigurationError(
  354. "Request timeout (%s) must be larger than session timeout (%s)" %
  355. (self.config['request_timeout_ms'], self.config['session_timeout_ms']))
  356. self._subscription = SubscriptionState(self.config['auto_offset_reset'])
  357. self._fetcher = Fetcher(
  358. self._client, self._subscription, self._metrics, **self.config)
  359. self._coordinator = ConsumerCoordinator(
  360. self._client, self._subscription, self._metrics,
  361. assignors=self.config['partition_assignment_strategy'],
  362. **self.config)
  363. self._closed = False
  364. self._iterator = None
  365. self._consumer_timeout = float('inf')
  366. if topics:
  367. self._subscription.subscribe(topics=topics)
  368. self._client.set_topics(topics)
  369. def bootstrap_connected(self):
  370. """Return True if the bootstrap is connected."""
  371. return self._client.bootstrap_connected()
  372. def assign(self, partitions):
  373. """Manually assign a list of TopicPartitions to this consumer.
  374. Arguments:
  375. partitions (list of TopicPartition): Assignment for this instance.
  376. Raises:
  377. IllegalStateError: If consumer has already called
  378. :meth:`~kafka.KafkaConsumer.subscribe`.
  379. Warning:
  380. It is not possible to use both manual partition assignment with
  381. :meth:`~kafka.KafkaConsumer.assign` and group assignment with
  382. :meth:`~kafka.KafkaConsumer.subscribe`.
  383. Note:
  384. This interface does not support incremental assignment and will
  385. replace the previous assignment (if there was one).
  386. Note:
  387. Manual topic assignment through this method does not use the
  388. consumer's group management functionality. As such, there will be
  389. no rebalance operation triggered when group membership or cluster
  390. and topic metadata change.
  391. """
  392. self._subscription.assign_from_user(partitions)
  393. self._client.set_topics([tp.topic for tp in partitions])
  394. def assignment(self):
  395. """Get the TopicPartitions currently assigned to this consumer.
  396. If partitions were directly assigned using
  397. :meth:`~kafka.KafkaConsumer.assign`, then this will simply return the
  398. same partitions that were previously assigned. If topics were
  399. subscribed using :meth:`~kafka.KafkaConsumer.subscribe`, then this will
  400. give the set of topic partitions currently assigned to the consumer
  401. (which may be None if the assignment hasn't happened yet, or if the
  402. partitions are in the process of being reassigned).
  403. Returns:
  404. set: {TopicPartition, ...}
  405. """
  406. return self._subscription.assigned_partitions()
  407. def close(self, autocommit=True):
  408. """Close the consumer, waiting indefinitely for any needed cleanup.
  409. Keyword Arguments:
  410. autocommit (bool): If auto-commit is configured for this consumer,
  411. this optional flag causes the consumer to attempt to commit any
  412. pending consumed offsets prior to close. Default: True
  413. """
  414. if self._closed:
  415. return
  416. log.debug("Closing the KafkaConsumer.")
  417. self._closed = True
  418. self._coordinator.close(autocommit=autocommit)
  419. self._metrics.close()
  420. self._client.close()
  421. try:
  422. self.config['key_deserializer'].close()
  423. except AttributeError:
  424. pass
  425. try:
  426. self.config['value_deserializer'].close()
  427. except AttributeError:
  428. pass
  429. log.debug("The KafkaConsumer has closed.")
  430. def commit_async(self, offsets=None, callback=None):
  431. """Commit offsets to kafka asynchronously, optionally firing callback.
  432. This commits offsets only to Kafka. The offsets committed using this API
  433. will be used on the first fetch after every rebalance and also on
  434. startup. As such, if you need to store offsets in anything other than
  435. Kafka, this API should not be used. To avoid re-processing the last
  436. message read if a consumer is restarted, the committed offset should be
  437. the next message your application should consume, i.e.: last_offset + 1.
  438. This is an asynchronous call and will not block. Any errors encountered
  439. are either passed to the callback (if provided) or discarded.
  440. Arguments:
  441. offsets (dict, optional): {TopicPartition: OffsetAndMetadata} dict
  442. to commit with the configured group_id. Defaults to currently
  443. consumed offsets for all subscribed partitions.
  444. callback (callable, optional): Called as callback(offsets, response)
  445. with response as either an Exception or an OffsetCommitResponse
  446. struct. This callback can be used to trigger custom actions when
  447. a commit request completes.
  448. Returns:
  449. kafka.future.Future
  450. """
  451. assert self.config['api_version'] >= (0, 8, 1), 'Requires >= Kafka 0.8.1'
  452. assert self.config['group_id'] is not None, 'Requires group_id'
  453. if offsets is None:
  454. offsets = self._subscription.all_consumed_offsets()
  455. log.debug("Committing offsets: %s", offsets)
  456. future = self._coordinator.commit_offsets_async(
  457. offsets, callback=callback)
  458. return future
  459. def commit(self, offsets=None):
  460. """Commit offsets to kafka, blocking until success or error.
  461. This commits offsets only to Kafka. The offsets committed using this API
  462. will be used on the first fetch after every rebalance and also on
  463. startup. As such, if you need to store offsets in anything other than
  464. Kafka, this API should not be used. To avoid re-processing the last
  465. message read if a consumer is restarted, the committed offset should be
  466. the next message your application should consume, i.e.: last_offset + 1.
  467. Blocks until either the commit succeeds or an unrecoverable error is
  468. encountered (in which case it is thrown to the caller).
  469. Currently only supports kafka-topic offset storage (not zookeeper).
  470. Arguments:
  471. offsets (dict, optional): {TopicPartition: OffsetAndMetadata} dict
  472. to commit with the configured group_id. Defaults to currently
  473. consumed offsets for all subscribed partitions.
  474. """
  475. assert self.config['api_version'] >= (0, 8, 1), 'Requires >= Kafka 0.8.1'
  476. assert self.config['group_id'] is not None, 'Requires group_id'
  477. if offsets is None:
  478. offsets = self._subscription.all_consumed_offsets()
  479. self._coordinator.commit_offsets_sync(offsets)
  480. def committed(self, partition, metadata=False):
  481. """Get the last committed offset for the given partition.
  482. This offset will be used as the position for the consumer
  483. in the event of a failure.
  484. This call may block to do a remote call if the partition in question
  485. isn't assigned to this consumer or if the consumer hasn't yet
  486. initialized its cache of committed offsets.
  487. Arguments:
  488. partition (TopicPartition): The partition to check.
  489. metadata (bool, optional): If True, return OffsetAndMetadata struct
  490. instead of offset int. Default: False.
  491. Returns:
  492. The last committed offset (int or OffsetAndMetadata), or None if there was no prior commit.
  493. """
  494. assert self.config['api_version'] >= (0, 8, 1), 'Requires >= Kafka 0.8.1'
  495. assert self.config['group_id'] is not None, 'Requires group_id'
  496. if not isinstance(partition, TopicPartition):
  497. raise TypeError('partition must be a TopicPartition namedtuple')
  498. if self._subscription.is_assigned(partition):
  499. committed = self._subscription.assignment[partition].committed
  500. if committed is None:
  501. self._coordinator.refresh_committed_offsets_if_needed()
  502. committed = self._subscription.assignment[partition].committed
  503. else:
  504. commit_map = self._coordinator.fetch_committed_offsets([partition])
  505. if partition in commit_map:
  506. committed = commit_map[partition]
  507. else:
  508. committed = None
  509. if committed is not None:
  510. if metadata:
  511. return committed
  512. else:
  513. return committed.offset
  514. def _fetch_all_topic_metadata(self):
  515. """A blocking call that fetches topic metadata for all topics in the
  516. cluster that the user is authorized to view.
  517. """
  518. cluster = self._client.cluster
  519. if self._client._metadata_refresh_in_progress and self._client._topics:
  520. future = cluster.request_update()
  521. self._client.poll(future=future)
  522. stash = cluster.need_all_topic_metadata
  523. cluster.need_all_topic_metadata = True
  524. future = cluster.request_update()
  525. self._client.poll(future=future)
  526. cluster.need_all_topic_metadata = stash
  527. def topics(self):
  528. """Get all topics the user is authorized to view.
  529. This will always issue a remote call to the cluster to fetch the latest
  530. information.
  531. Returns:
  532. set: topics
  533. """
  534. self._fetch_all_topic_metadata()
  535. return self._client.cluster.topics()
  536. def partitions_for_topic(self, topic):
  537. """This method first checks the local metadata cache for information
  538. about the topic. If the topic is not found (either because the topic
  539. does not exist, the user is not authorized to view the topic, or the
  540. metadata cache is not populated), then it will issue a metadata update
  541. call to the cluster.
  542. Arguments:
  543. topic (str): Topic to check.
  544. Returns:
  545. set: Partition ids
  546. """
  547. cluster = self._client.cluster
  548. partitions = cluster.partitions_for_topic(topic)
  549. if partitions is None:
  550. self._fetch_all_topic_metadata()
  551. partitions = cluster.partitions_for_topic(topic)
  552. return partitions
  553. def poll(self, timeout_ms=0, max_records=None, update_offsets=True):
  554. """Fetch data from assigned topics / partitions.
  555. Records are fetched and returned in batches by topic-partition.
  556. On each poll, consumer will try to use the last consumed offset as the
  557. starting offset and fetch sequentially. The last consumed offset can be
  558. manually set through :meth:`~kafka.KafkaConsumer.seek` or automatically
  559. set as the last committed offset for the subscribed list of partitions.
  560. Incompatible with iterator interface -- use one or the other, not both.
  561. Arguments:
  562. timeout_ms (int, optional): Milliseconds spent waiting in poll if
  563. data is not available in the buffer. If 0, returns immediately
  564. with any records that are available currently in the buffer,
  565. else returns empty. Must not be negative. Default: 0
  566. max_records (int, optional): The maximum number of records returned
  567. in a single call to :meth:`~kafka.KafkaConsumer.poll`.
  568. Default: Inherit value from max_poll_records.
  569. Returns:
  570. dict: Topic to list of records since the last fetch for the
  571. subscribed list of topics and partitions.
  572. """
  573. # Note: update_offsets is an internal-use only argument. It is used to
  574. # support the python iterator interface, and which wraps consumer.poll()
  575. # and requires that the partition offsets tracked by the fetcher are not
  576. # updated until the iterator returns each record to the user. As such,
  577. # the argument is not documented and should not be relied on by library
  578. # users to not break in the future.
  579. assert timeout_ms >= 0, 'Timeout must not be negative'
  580. if max_records is None:
  581. max_records = self.config['max_poll_records']
  582. assert isinstance(max_records, int), 'max_records must be an integer'
  583. assert max_records > 0, 'max_records must be positive'
  584. assert not self._closed, 'KafkaConsumer is closed'
  585. # Poll for new data until the timeout expires
  586. start = time.time()
  587. remaining = timeout_ms
  588. while True:
  589. records = self._poll_once(remaining, max_records, update_offsets=update_offsets)
  590. if records:
  591. return records
  592. elapsed_ms = (time.time() - start) * 1000
  593. remaining = timeout_ms - elapsed_ms
  594. if remaining <= 0:
  595. return {}
  596. def _poll_once(self, timeout_ms, max_records, update_offsets=True):
  597. """Do one round of polling. In addition to checking for new data, this does
  598. any needed heart-beating, auto-commits, and offset updates.
  599. Arguments:
  600. timeout_ms (int): The maximum time in milliseconds to block.
  601. Returns:
  602. dict: Map of topic to list of records (may be empty).
  603. """
  604. self._coordinator.poll()
  605. # Fetch positions if we have partitions we're subscribed to that we
  606. # don't know the offset for
  607. if not self._subscription.has_all_fetch_positions():
  608. self._update_fetch_positions(self._subscription.missing_fetch_positions())
  609. # If data is available already, e.g. from a previous network client
  610. # poll() call to commit, then just return it immediately
  611. records, partial = self._fetcher.fetched_records(max_records, update_offsets=update_offsets)
  612. if records:
  613. # Before returning the fetched records, we can send off the
  614. # next round of fetches and avoid block waiting for their
  615. # responses to enable pipelining while the user is handling the
  616. # fetched records.
  617. if not partial:
  618. futures = self._fetcher.send_fetches()
  619. if len(futures):
  620. self._client.poll(timeout_ms=0)
  621. return records
  622. # Send any new fetches (won't resend pending fetches)
  623. futures = self._fetcher.send_fetches()
  624. if len(futures):
  625. self._client.poll(timeout_ms=0)
  626. timeout_ms = min(timeout_ms, self._coordinator.time_to_next_poll() * 1000)
  627. self._client.poll(timeout_ms=timeout_ms)
  628. # after the long poll, we should check whether the group needs to rebalance
  629. # prior to returning data so that the group can stabilize faster
  630. if self._coordinator.need_rejoin():
  631. return {}
  632. records, _ = self._fetcher.fetched_records(max_records, update_offsets=update_offsets)
  633. return records
  634. def position(self, partition):
  635. """Get the offset of the next record that will be fetched
  636. Arguments:
  637. partition (TopicPartition): Partition to check
  638. Returns:
  639. int: Offset
  640. """
  641. if not isinstance(partition, TopicPartition):
  642. raise TypeError('partition must be a TopicPartition namedtuple')
  643. assert self._subscription.is_assigned(partition), 'Partition is not assigned'
  644. offset = self._subscription.assignment[partition].position
  645. if offset is None:
  646. self._update_fetch_positions([partition])
  647. offset = self._subscription.assignment[partition].position
  648. return offset
  649. def highwater(self, partition):
  650. """Last known highwater offset for a partition.
  651. A highwater offset is the offset that will be assigned to the next
  652. message that is produced. It may be useful for calculating lag, by
  653. comparing with the reported position. Note that both position and
  654. highwater refer to the *next* offset -- i.e., highwater offset is
  655. one greater than the newest available message.
  656. Highwater offsets are returned in FetchResponse messages, so will
  657. not be available if no FetchRequests have been sent for this partition
  658. yet.
  659. Arguments:
  660. partition (TopicPartition): Partition to check
  661. Returns:
  662. int or None: Offset if available
  663. """
  664. if not isinstance(partition, TopicPartition):
  665. raise TypeError('partition must be a TopicPartition namedtuple')
  666. assert self._subscription.is_assigned(partition), 'Partition is not assigned'
  667. return self._subscription.assignment[partition].highwater
  668. def pause(self, *partitions):
  669. """Suspend fetching from the requested partitions.
  670. Future calls to :meth:`~kafka.KafkaConsumer.poll` will not return any
  671. records from these partitions until they have been resumed using
  672. :meth:`~kafka.KafkaConsumer.resume`.
  673. Note: This method does not affect partition subscription. In particular,
  674. it does not cause a group rebalance when automatic assignment is used.
  675. Arguments:
  676. *partitions (TopicPartition): Partitions to pause.
  677. """
  678. if not all([isinstance(p, TopicPartition) for p in partitions]):
  679. raise TypeError('partitions must be TopicPartition namedtuples')
  680. for partition in partitions:
  681. log.debug("Pausing partition %s", partition)
  682. self._subscription.pause(partition)
  683. # Because the iterator checks is_fetchable() on each iteration
  684. # we expect pauses to get handled automatically and therefore
  685. # we do not need to reset the full iterator (forcing a full refetch)
  686. def paused(self):
  687. """Get the partitions that were previously paused using
  688. :meth:`~kafka.KafkaConsumer.pause`.
  689. Returns:
  690. set: {partition (TopicPartition), ...}
  691. """
  692. return self._subscription.paused_partitions()
  693. def resume(self, *partitions):
  694. """Resume fetching from the specified (paused) partitions.
  695. Arguments:
  696. *partitions (TopicPartition): Partitions to resume.
  697. """
  698. if not all([isinstance(p, TopicPartition) for p in partitions]):
  699. raise TypeError('partitions must be TopicPartition namedtuples')
  700. for partition in partitions:
  701. log.debug("Resuming partition %s", partition)
  702. self._subscription.resume(partition)
  703. def seek(self, partition, offset):
  704. """Manually specify the fetch offset for a TopicPartition.
  705. Overrides the fetch offsets that the consumer will use on the next
  706. :meth:`~kafka.KafkaConsumer.poll`. If this API is invoked for the same
  707. partition more than once, the latest offset will be used on the next
  708. :meth:`~kafka.KafkaConsumer.poll`.
  709. Note: You may lose data if this API is arbitrarily used in the middle of
  710. consumption to reset the fetch offsets.
  711. Arguments:
  712. partition (TopicPartition): Partition for seek operation
  713. offset (int): Message offset in partition
  714. Raises:
  715. AssertionError: If offset is not an int >= 0; or if partition is not
  716. currently assigned.
  717. """
  718. if not isinstance(partition, TopicPartition):
  719. raise TypeError('partition must be a TopicPartition namedtuple')
  720. assert isinstance(offset, int) and offset >= 0, 'Offset must be >= 0'
  721. assert partition in self._subscription.assigned_partitions(), 'Unassigned partition'
  722. log.debug("Seeking to offset %s for partition %s", offset, partition)
  723. self._subscription.assignment[partition].seek(offset)
  724. if not self.config['legacy_iterator']:
  725. self._iterator = None
  726. def seek_to_beginning(self, *partitions):
  727. """Seek to the oldest available offset for partitions.
  728. Arguments:
  729. *partitions: Optionally provide specific TopicPartitions, otherwise
  730. default to all assigned partitions.
  731. Raises:
  732. AssertionError: If any partition is not currently assigned, or if
  733. no partitions are assigned.
  734. """
  735. if not all([isinstance(p, TopicPartition) for p in partitions]):
  736. raise TypeError('partitions must be TopicPartition namedtuples')
  737. if not partitions:
  738. partitions = self._subscription.assigned_partitions()
  739. assert partitions, 'No partitions are currently assigned'
  740. else:
  741. for p in partitions:
  742. assert p in self._subscription.assigned_partitions(), 'Unassigned partition'
  743. for tp in partitions:
  744. log.debug("Seeking to beginning of partition %s", tp)
  745. self._subscription.need_offset_reset(tp, OffsetResetStrategy.EARLIEST)
  746. if not self.config['legacy_iterator']:
  747. self._iterator = None
  748. def seek_to_end(self, *partitions):
  749. """Seek to the most recent available offset for partitions.
  750. Arguments:
  751. *partitions: Optionally provide specific TopicPartitions, otherwise
  752. default to all assigned partitions.
  753. Raises:
  754. AssertionError: If any partition is not currently assigned, or if
  755. no partitions are assigned.
  756. """
  757. if not all([isinstance(p, TopicPartition) for p in partitions]):
  758. raise TypeError('partitions must be TopicPartition namedtuples')
  759. if not partitions:
  760. partitions = self._subscription.assigned_partitions()
  761. assert partitions, 'No partitions are currently assigned'
  762. else:
  763. for p in partitions:
  764. assert p in self._subscription.assigned_partitions(), 'Unassigned partition'
  765. for tp in partitions:
  766. log.debug("Seeking to end of partition %s", tp)
  767. self._subscription.need_offset_reset(tp, OffsetResetStrategy.LATEST)
  768. if not self.config['legacy_iterator']:
  769. self._iterator = None
  770. def subscribe(self, topics=(), pattern=None, listener=None):
  771. """Subscribe to a list of topics, or a topic regex pattern.
  772. Partitions will be dynamically assigned via a group coordinator.
  773. Topic subscriptions are not incremental: this list will replace the
  774. current assignment (if there is one).
  775. This method is incompatible with :meth:`~kafka.KafkaConsumer.assign`.
  776. Arguments:
  777. topics (list): List of topics for subscription.
  778. pattern (str): Pattern to match available topics. You must provide
  779. either topics or pattern, but not both.
  780. listener (ConsumerRebalanceListener): Optionally include listener
  781. callback, which will be called before and after each rebalance
  782. operation.
  783. As part of group management, the consumer will keep track of the
  784. list of consumers that belong to a particular group and will
  785. trigger a rebalance operation if one of the following events
  786. trigger:
  787. * Number of partitions change for any of the subscribed topics
  788. * Topic is created or deleted
  789. * An existing member of the consumer group dies
  790. * A new member is added to the consumer group
  791. When any of these events are triggered, the provided listener
  792. will be invoked first to indicate that the consumer's assignment
  793. has been revoked, and then again when the new assignment has
  794. been received. Note that this listener will immediately override
  795. any listener set in a previous call to subscribe. It is
  796. guaranteed, however, that the partitions revoked/assigned
  797. through this interface are from topics subscribed in this call.
  798. Raises:
  799. IllegalStateError: If called after previously calling
  800. :meth:`~kafka.KafkaConsumer.assign`.
  801. AssertionError: If neither topics or pattern is provided.
  802. TypeError: If listener is not a ConsumerRebalanceListener.
  803. """
  804. # SubscriptionState handles error checking
  805. self._subscription.subscribe(topics=topics,
  806. pattern=pattern,
  807. listener=listener)
  808. # Regex will need all topic metadata
  809. if pattern is not None:
  810. self._client.cluster.need_all_topic_metadata = True
  811. self._client.set_topics([])
  812. self._client.cluster.request_update()
  813. log.debug("Subscribed to topic pattern: %s", pattern)
  814. else:
  815. self._client.cluster.need_all_topic_metadata = False
  816. self._client.set_topics(self._subscription.group_subscription())
  817. log.debug("Subscribed to topic(s): %s", topics)
  818. def subscription(self):
  819. """Get the current topic subscription.
  820. Returns:
  821. set: {topic, ...}
  822. """
  823. if self._subscription.subscription is None:
  824. return None
  825. return self._subscription.subscription.copy()
  826. def unsubscribe(self):
  827. """Unsubscribe from all topics and clear all assigned partitions."""
  828. self._subscription.unsubscribe()
  829. self._coordinator.close()
  830. self._client.cluster.need_all_topic_metadata = False
  831. self._client.set_topics([])
  832. log.debug("Unsubscribed all topics or patterns and assigned partitions")
  833. if not self.config['legacy_iterator']:
  834. self._iterator = None
  835. def metrics(self, raw=False):
  836. """Get metrics on consumer performance.
  837. This is ported from the Java Consumer, for details see:
  838. https://kafka.apache.org/documentation/#consumer_monitoring
  839. Warning:
  840. This is an unstable interface. It may change in future
  841. releases without warning.
  842. """
  843. if raw:
  844. return self._metrics.metrics.copy()
  845. metrics = {}
  846. for k, v in six.iteritems(self._metrics.metrics.copy()):
  847. if k.group not in metrics:
  848. metrics[k.group] = {}
  849. if k.name not in metrics[k.group]:
  850. metrics[k.group][k.name] = {}
  851. metrics[k.group][k.name] = v.value()
  852. return metrics
  853. def offsets_for_times(self, timestamps):
  854. """Look up the offsets for the given partitions by timestamp. The
  855. returned offset for each partition is the earliest offset whose
  856. timestamp is greater than or equal to the given timestamp in the
  857. corresponding partition.
  858. This is a blocking call. The consumer does not have to be assigned the
  859. partitions.
  860. If the message format version in a partition is before 0.10.0, i.e.
  861. the messages do not have timestamps, ``None`` will be returned for that
  862. partition. ``None`` will also be returned for the partition if there
  863. are no messages in it.
  864. Note:
  865. This method may block indefinitely if the partition does not exist.
  866. Arguments:
  867. timestamps (dict): ``{TopicPartition: int}`` mapping from partition
  868. to the timestamp to look up. Unit should be milliseconds since
  869. beginning of the epoch (midnight Jan 1, 1970 (UTC))
  870. Returns:
  871. ``{TopicPartition: OffsetAndTimestamp}``: mapping from partition
  872. to the timestamp and offset of the first message with timestamp
  873. greater than or equal to the target timestamp.
  874. Raises:
  875. ValueError: If the target timestamp is negative
  876. UnsupportedVersionError: If the broker does not support looking
  877. up the offsets by timestamp.
  878. KafkaTimeoutError: If fetch failed in request_timeout_ms
  879. """
  880. if self.config['api_version'] <= (0, 10, 0):
  881. raise UnsupportedVersionError(
  882. "offsets_for_times API not supported for cluster version {}"
  883. .format(self.config['api_version']))
  884. for tp, ts in six.iteritems(timestamps):
  885. timestamps[tp] = int(ts)
  886. if ts < 0:
  887. raise ValueError(
  888. "The target time for partition {} is {}. The target time "
  889. "cannot be negative.".format(tp, ts))
  890. return self._fetcher.get_offsets_by_times(
  891. timestamps, self.config['request_timeout_ms'])
  892. def beginning_offsets(self, partitions):
  893. """Get the first offset for the given partitions.
  894. This method does not change the current consumer position of the
  895. partitions.
  896. Note:
  897. This method may block indefinitely if the partition does not exist.
  898. Arguments:
  899. partitions (list): List of TopicPartition instances to fetch
  900. offsets for.
  901. Returns:
  902. ``{TopicPartition: int}``: The earliest available offsets for the
  903. given partitions.
  904. Raises:
  905. UnsupportedVersionError: If the broker does not support looking
  906. up the offsets by timestamp.
  907. KafkaTimeoutError: If fetch failed in request_timeout_ms.
  908. """
  909. offsets = self._fetcher.beginning_offsets(
  910. partitions, self.config['request_timeout_ms'])
  911. return offsets
  912. def end_offsets(self, partitions):
  913. """Get the last offset for the given partitions. The last offset of a
  914. partition is the offset of the upcoming message, i.e. the offset of the
  915. last available message + 1.
  916. This method does not change the current consumer position of the
  917. partitions.
  918. Note:
  919. This method may block indefinitely if the partition does not exist.
  920. Arguments:
  921. partitions (list): List of TopicPartition instances to fetch
  922. offsets for.
  923. Returns:
  924. ``{TopicPartition: int}``: The end offsets for the given partitions.
  925. Raises:
  926. UnsupportedVersionError: If the broker does not support looking
  927. up the offsets by timestamp.
  928. KafkaTimeoutError: If fetch failed in request_timeout_ms
  929. """
  930. offsets = self._fetcher.end_offsets(
  931. partitions, self.config['request_timeout_ms'])
  932. return offsets
  933. def _use_consumer_group(self):
  934. """Return True iff this consumer can/should join a broker-coordinated group."""
  935. if self.config['api_version'] < (0, 9):
  936. return False
  937. elif self.config['group_id'] is None:
  938. return False
  939. elif not self._subscription.partitions_auto_assigned():
  940. return False
  941. return True
  942. def _update_fetch_positions(self, partitions):
  943. """Set the fetch position to the committed position (if there is one)
  944. or reset it using the offset reset policy the user has configured.
  945. Arguments:
  946. partitions (List[TopicPartition]): The partitions that need
  947. updating fetch positions.
  948. Raises:
  949. NoOffsetForPartitionError: If no offset is stored for a given
  950. partition and no offset reset policy is defined.
  951. """
  952. # Lookup any positions for partitions which are awaiting reset (which may be the
  953. # case if the user called :meth:`seek_to_beginning` or :meth:`seek_to_end`. We do
  954. # this check first to avoid an unnecessary lookup of committed offsets (which
  955. # typically occurs when the user is manually assigning partitions and managing
  956. # their own offsets).
  957. self._fetcher.reset_offsets_if_needed(partitions)
  958. if not self._subscription.has_all_fetch_positions():
  959. # if we still don't have offsets for all partitions, then we should either seek
  960. # to the last committed position or reset using the auto reset policy
  961. if (self.config['api_version'] >= (0, 8, 1) and
  962. self.config['group_id'] is not None):
  963. # first refresh commits for all assigned partitions
  964. self._coordinator.refresh_committed_offsets_if_needed()
  965. # Then, do any offset lookups in case some positions are not known
  966. self._fetcher.update_fetch_positions(partitions)
  967. def _message_generator_v2(self):
  968. timeout_ms = 1000 * (self._consumer_timeout - time.time())
  969. record_map = self.poll(timeout_ms=timeout_ms, update_offsets=False)
  970. for tp, records in six.iteritems(record_map):
  971. # Generators are stateful, and it is possible that the tp / records
  972. # here may become stale during iteration -- i.e., we seek to a
  973. # different offset, pause consumption, or lose assignment.
  974. for record in records:
  975. # is_fetchable(tp) should handle assignment changes and offset
  976. # resets; for all other changes (e.g., seeks) we'll rely on the
  977. # outer function destroying the existing iterator/generator
  978. # via self._iterator = None
  979. if not self._subscription.is_fetchable(tp):
  980. log.debug("Not returning fetched records for partition %s"
  981. " since it is no longer fetchable", tp)
  982. break
  983. self._subscription.assignment[tp].position = record.offset + 1
  984. yield record
  985. def _message_generator(self):
  986. assert self.assignment() or self.subscription() is not None, 'No topic subscription or manual partition assignment'
  987. while time.time() < self._consumer_timeout:
  988. self._coordinator.poll()
  989. # Fetch offsets for any subscribed partitions that we arent tracking yet
  990. if not self._subscription.has_all_fetch_positions():
  991. partitions = self._subscription.missing_fetch_positions()
  992. self._update_fetch_positions(partitions)
  993. poll_ms = min((1000 * (self._consumer_timeout - time.time())), self.config['retry_backoff_ms'])
  994. self._client.poll(timeout_ms=poll_ms)
  995. # after the long poll, we should check whether the group needs to rebalance
  996. # prior to returning data so that the group can stabilize faster
  997. if self._coordinator.need_rejoin():
  998. continue
  999. # We need to make sure we at least keep up with scheduled tasks,
  1000. # like heartbeats, auto-commits, and metadata refreshes
  1001. timeout_at = self._next_timeout()
  1002. # Short-circuit the fetch iterator if we are already timed out
  1003. # to avoid any unintentional interaction with fetcher setup
  1004. if time.time() > timeout_at:
  1005. continue
  1006. for msg in self._fetcher:
  1007. yield msg
  1008. if time.time() > timeout_at:
  1009. log.debug("internal iterator timeout - breaking for poll")
  1010. break
  1011. self._client.poll(timeout_ms=0)
  1012. # An else block on a for loop only executes if there was no break
  1013. # so this should only be called on a StopIteration from the fetcher
  1014. # We assume that it is safe to init_fetches when fetcher is done
  1015. # i.e., there are no more records stored internally
  1016. else:
  1017. self._fetcher.send_fetches()
  1018. def _next_timeout(self):
  1019. timeout = min(self._consumer_timeout,
  1020. self._client.cluster.ttl() / 1000.0 + time.time(),
  1021. self._coordinator.time_to_next_poll() + time.time())
  1022. return timeout
  1023. def __iter__(self): # pylint: disable=non-iterator-returned
  1024. return self
  1025. def __next__(self):
  1026. if self._closed:
  1027. raise StopIteration('KafkaConsumer closed')
  1028. # Now that the heartbeat thread runs in the background
  1029. # there should be no reason to maintain a separate iterator
  1030. # but we'll keep it available for a few releases just in case
  1031. if self.config['legacy_iterator']:
  1032. return self.next_v1()
  1033. else:
  1034. return self.next_v2()
  1035. def next_v2(self):
  1036. self._set_consumer_timeout()
  1037. while time.time() < self._consumer_timeout:
  1038. if not self._iterator:
  1039. self._iterator = self._message_generator_v2()
  1040. try:
  1041. return next(self._iterator)
  1042. except StopIteration:
  1043. self._iterator = None
  1044. raise StopIteration()
  1045. def next_v1(self):
  1046. if not self._iterator:
  1047. self._iterator = self._message_generator()
  1048. self._set_consumer_timeout()
  1049. try:
  1050. return next(self._iterator)
  1051. except StopIteration:
  1052. self._iterator = None
  1053. raise
  1054. def _set_consumer_timeout(self):
  1055. # consumer_timeout_ms can be used to stop iteration early
  1056. if self.config['consumer_timeout_ms'] >= 0:
  1057. self._consumer_timeout = time.time() + (
  1058. self.config['consumer_timeout_ms'] / 1000.0)