kafka-python 3.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (373) hide show
  1. kafka/__init__.py +34 -0
  2. kafka/__main__.py +5 -0
  3. kafka/admin/__init__.py +29 -0
  4. kafka/admin/__main__.py +5 -0
  5. kafka/admin/_acls.py +355 -0
  6. kafka/admin/_cluster.py +359 -0
  7. kafka/admin/_configs.py +479 -0
  8. kafka/admin/_groups.py +754 -0
  9. kafka/admin/_partitions.py +595 -0
  10. kafka/admin/_topics.py +281 -0
  11. kafka/admin/_transactions.py +450 -0
  12. kafka/admin/_users.py +194 -0
  13. kafka/admin/client.py +373 -0
  14. kafka/benchmarks/__init__.py +0 -0
  15. kafka/benchmarks/consumer_performance.py +138 -0
  16. kafka/benchmarks/load_example.py +109 -0
  17. kafka/benchmarks/producer_encode_path.py +201 -0
  18. kafka/benchmarks/producer_performance.py +161 -0
  19. kafka/benchmarks/profile_protocol.py +138 -0
  20. kafka/benchmarks/protocol_old_vs_new.py +447 -0
  21. kafka/benchmarks/record_batch_compose.py +77 -0
  22. kafka/benchmarks/record_batch_read.py +82 -0
  23. kafka/benchmarks/varint_speed.py +426 -0
  24. kafka/cli/__init__.py +36 -0
  25. kafka/cli/admin/__init__.py +117 -0
  26. kafka/cli/admin/acls/__init__.py +9 -0
  27. kafka/cli/admin/acls/common.py +76 -0
  28. kafka/cli/admin/acls/create.py +19 -0
  29. kafka/cli/admin/acls/delete.py +23 -0
  30. kafka/cli/admin/acls/describe.py +16 -0
  31. kafka/cli/admin/cluster/__init__.py +14 -0
  32. kafka/cli/admin/cluster/describe.py +11 -0
  33. kafka/cli/admin/cluster/describe_quorum.py +11 -0
  34. kafka/cli/admin/cluster/features.py +52 -0
  35. kafka/cli/admin/cluster/log_dirs.py +43 -0
  36. kafka/cli/admin/cluster/versions.py +33 -0
  37. kafka/cli/admin/configs/__init__.py +10 -0
  38. kafka/cli/admin/configs/alter.py +43 -0
  39. kafka/cli/admin/configs/common.py +17 -0
  40. kafka/cli/admin/configs/describe.py +30 -0
  41. kafka/cli/admin/configs/list.py +16 -0
  42. kafka/cli/admin/configs/reset.py +20 -0
  43. kafka/cli/admin/groups/__init__.py +16 -0
  44. kafka/cli/admin/groups/alter_offsets.py +30 -0
  45. kafka/cli/admin/groups/delete.py +11 -0
  46. kafka/cli/admin/groups/delete_offsets.py +29 -0
  47. kafka/cli/admin/groups/describe.py +11 -0
  48. kafka/cli/admin/groups/list.py +28 -0
  49. kafka/cli/admin/groups/list_offsets.py +29 -0
  50. kafka/cli/admin/groups/remove_members.py +40 -0
  51. kafka/cli/admin/groups/reset_offsets.py +139 -0
  52. kafka/cli/admin/partitions/__init__.py +21 -0
  53. kafka/cli/admin/partitions/alter_reassignments.py +37 -0
  54. kafka/cli/admin/partitions/create.py +27 -0
  55. kafka/cli/admin/partitions/delete_records.py +31 -0
  56. kafka/cli/admin/partitions/describe.py +36 -0
  57. kafka/cli/admin/partitions/elect_leaders.py +53 -0
  58. kafka/cli/admin/partitions/list_offsets.py +88 -0
  59. kafka/cli/admin/partitions/list_reassignments.py +35 -0
  60. kafka/cli/admin/topics/__init__.py +10 -0
  61. kafka/cli/admin/topics/create.py +13 -0
  62. kafka/cli/admin/topics/delete.py +19 -0
  63. kafka/cli/admin/topics/describe.py +18 -0
  64. kafka/cli/admin/topics/list.py +11 -0
  65. kafka/cli/admin/transactions/__init__.py +17 -0
  66. kafka/cli/admin/transactions/abort.py +38 -0
  67. kafka/cli/admin/transactions/describe.py +24 -0
  68. kafka/cli/admin/transactions/describe_producers.py +29 -0
  69. kafka/cli/admin/transactions/find_hanging.py +26 -0
  70. kafka/cli/admin/transactions/list.py +37 -0
  71. kafka/cli/admin/users/__init__.py +8 -0
  72. kafka/cli/admin/users/alter_user_scram_credentials.py +34 -0
  73. kafka/cli/admin/users/describe_user_scram_credentials.py +15 -0
  74. kafka/cli/common.py +95 -0
  75. kafka/cli/consumer/__init__.py +63 -0
  76. kafka/cli/producer/__init__.py +57 -0
  77. kafka/cluster.py +824 -0
  78. kafka/codec.py +325 -0
  79. kafka/consumer/__init__.py +5 -0
  80. kafka/consumer/__main__.py +5 -0
  81. kafka/consumer/fetcher.py +2012 -0
  82. kafka/consumer/group.py +1347 -0
  83. kafka/consumer/subscription_state.py +897 -0
  84. kafka/coordinator/__init__.py +0 -0
  85. kafka/coordinator/assignors/__init__.py +0 -0
  86. kafka/coordinator/assignors/abstract.py +90 -0
  87. kafka/coordinator/assignors/cooperative_sticky.py +167 -0
  88. kafka/coordinator/assignors/range.py +81 -0
  89. kafka/coordinator/assignors/roundrobin.py +101 -0
  90. kafka/coordinator/assignors/sticky/StickyAssignorUserData.json +37 -0
  91. kafka/coordinator/assignors/sticky/__init__.py +0 -0
  92. kafka/coordinator/assignors/sticky/partition_movements.py +149 -0
  93. kafka/coordinator/assignors/sticky/sorted_set.py +63 -0
  94. kafka/coordinator/assignors/sticky/sticky_assignor.py +665 -0
  95. kafka/coordinator/assignors/sticky/user_data.py +8 -0
  96. kafka/coordinator/base.py +1215 -0
  97. kafka/coordinator/consumer.py +1224 -0
  98. kafka/coordinator/heartbeat.py +82 -0
  99. kafka/coordinator/subscription.py +34 -0
  100. kafka/errors.py +1004 -0
  101. kafka/future.py +166 -0
  102. kafka/metrics/__init__.py +13 -0
  103. kafka/metrics/compound_stat.py +33 -0
  104. kafka/metrics/dict_reporter.py +81 -0
  105. kafka/metrics/kafka_metric.py +36 -0
  106. kafka/metrics/measurable.py +27 -0
  107. kafka/metrics/measurable_stat.py +13 -0
  108. kafka/metrics/metric_config.py +33 -0
  109. kafka/metrics/metric_name.py +105 -0
  110. kafka/metrics/metrics.py +261 -0
  111. kafka/metrics/metrics_reporter.py +53 -0
  112. kafka/metrics/quota.py +41 -0
  113. kafka/metrics/stat.py +19 -0
  114. kafka/metrics/stats/__init__.py +15 -0
  115. kafka/metrics/stats/avg.py +24 -0
  116. kafka/metrics/stats/count.py +17 -0
  117. kafka/metrics/stats/histogram.py +99 -0
  118. kafka/metrics/stats/max_stat.py +17 -0
  119. kafka/metrics/stats/min_stat.py +19 -0
  120. kafka/metrics/stats/percentile.py +14 -0
  121. kafka/metrics/stats/percentiles.py +75 -0
  122. kafka/metrics/stats/rate.py +118 -0
  123. kafka/metrics/stats/sampled_stat.py +99 -0
  124. kafka/metrics/stats/sensor.py +136 -0
  125. kafka/metrics/stats/total.py +15 -0
  126. kafka/net/__init__.py +19 -0
  127. kafka/net/compat.py +165 -0
  128. kafka/net/connection.py +593 -0
  129. kafka/net/http_connect.py +144 -0
  130. kafka/net/inet.py +122 -0
  131. kafka/net/manager.py +451 -0
  132. kafka/net/metrics.py +149 -0
  133. kafka/net/sasl/__init__.py +32 -0
  134. kafka/net/sasl/abc.py +28 -0
  135. kafka/net/sasl/gssapi.py +95 -0
  136. kafka/net/sasl/msk.py +245 -0
  137. kafka/net/sasl/oauth.py +98 -0
  138. kafka/net/sasl/plain.py +42 -0
  139. kafka/net/sasl/scram.py +135 -0
  140. kafka/net/sasl/sspi.py +111 -0
  141. kafka/net/selector.py +644 -0
  142. kafka/net/socks5.py +262 -0
  143. kafka/net/transport.py +415 -0
  144. kafka/net/wakeup_notifier.py +72 -0
  145. kafka/partitioner/__init__.py +8 -0
  146. kafka/partitioner/abc.py +8 -0
  147. kafka/partitioner/default.py +89 -0
  148. kafka/partitioner/sticky.py +109 -0
  149. kafka/producer/__init__.py +5 -0
  150. kafka/producer/__main__.py +5 -0
  151. kafka/producer/future.py +101 -0
  152. kafka/producer/kafka.py +1123 -0
  153. kafka/producer/producer_batch.py +192 -0
  154. kafka/producer/record_accumulator.py +647 -0
  155. kafka/producer/sender.py +884 -0
  156. kafka/producer/transaction_manager.py +1326 -0
  157. kafka/protocol/__init__.py +0 -0
  158. kafka/protocol/admin/__init__.py +29 -0
  159. kafka/protocol/admin/acl.py +83 -0
  160. kafka/protocol/admin/acl.pyi +375 -0
  161. kafka/protocol/admin/client_quotas.py +14 -0
  162. kafka/protocol/admin/client_quotas.pyi +265 -0
  163. kafka/protocol/admin/cluster.py +31 -0
  164. kafka/protocol/admin/cluster.pyi +620 -0
  165. kafka/protocol/admin/configs.py +22 -0
  166. kafka/protocol/admin/configs.pyi +437 -0
  167. kafka/protocol/admin/groups.py +24 -0
  168. kafka/protocol/admin/groups.pyi +261 -0
  169. kafka/protocol/admin/topics.py +53 -0
  170. kafka/protocol/admin/topics.pyi +982 -0
  171. kafka/protocol/admin/transactions.py +18 -0
  172. kafka/protocol/admin/transactions.pyi +311 -0
  173. kafka/protocol/admin/users.py +14 -0
  174. kafka/protocol/admin/users.pyi +223 -0
  175. kafka/protocol/api_data.py +125 -0
  176. kafka/protocol/api_header.py +55 -0
  177. kafka/protocol/api_key.py +97 -0
  178. kafka/protocol/api_message.py +277 -0
  179. kafka/protocol/broker_version_data.py +246 -0
  180. kafka/protocol/consumer/__init__.py +13 -0
  181. kafka/protocol/consumer/fetch.py +16 -0
  182. kafka/protocol/consumer/fetch.pyi +298 -0
  183. kafka/protocol/consumer/group.py +38 -0
  184. kafka/protocol/consumer/group.pyi +824 -0
  185. kafka/protocol/consumer/metadata.py +30 -0
  186. kafka/protocol/consumer/metadata.pyi +89 -0
  187. kafka/protocol/consumer/offsets.py +75 -0
  188. kafka/protocol/consumer/offsets.pyi +288 -0
  189. kafka/protocol/data_container.py +166 -0
  190. kafka/protocol/frame.py +30 -0
  191. kafka/protocol/generate_stubs.py +468 -0
  192. kafka/protocol/metadata/__init__.py +10 -0
  193. kafka/protocol/metadata/api_versions.py +41 -0
  194. kafka/protocol/metadata/api_versions.pyi +128 -0
  195. kafka/protocol/metadata/find_coordinator.py +19 -0
  196. kafka/protocol/metadata/find_coordinator.pyi +105 -0
  197. kafka/protocol/metadata/metadata.py +34 -0
  198. kafka/protocol/metadata/metadata.pyi +160 -0
  199. kafka/protocol/old/__init__.py +0 -0
  200. kafka/protocol/old/abstract.py +17 -0
  201. kafka/protocol/old/add_offsets_to_txn.py +54 -0
  202. kafka/protocol/old/add_partitions_to_txn.py +71 -0
  203. kafka/protocol/old/admin.py +1086 -0
  204. kafka/protocol/old/api.py +205 -0
  205. kafka/protocol/old/api_versions.py +133 -0
  206. kafka/protocol/old/commit.py +355 -0
  207. kafka/protocol/old/consumer_protocol.py +36 -0
  208. kafka/protocol/old/end_txn.py +53 -0
  209. kafka/protocol/old/fetch.py +408 -0
  210. kafka/protocol/old/find_coordinator.py +72 -0
  211. kafka/protocol/old/group.py +451 -0
  212. kafka/protocol/old/init_producer_id.py +42 -0
  213. kafka/protocol/old/list_offsets.py +186 -0
  214. kafka/protocol/old/metadata.py +290 -0
  215. kafka/protocol/old/offset_for_leader_epoch.py +133 -0
  216. kafka/protocol/old/produce.py +247 -0
  217. kafka/protocol/old/sasl_authenticate.py +38 -0
  218. kafka/protocol/old/sasl_handshake.py +39 -0
  219. kafka/protocol/old/struct.py +87 -0
  220. kafka/protocol/old/txn_offset_commit.py +73 -0
  221. kafka/protocol/old/types.py +440 -0
  222. kafka/protocol/parser.py +191 -0
  223. kafka/protocol/producer/__init__.py +7 -0
  224. kafka/protocol/producer/produce.py +17 -0
  225. kafka/protocol/producer/produce.pyi +197 -0
  226. kafka/protocol/producer/transaction.py +30 -0
  227. kafka/protocol/producer/transaction.pyi +663 -0
  228. kafka/protocol/sasl.py +52 -0
  229. kafka/protocol/sasl.pyi +126 -0
  230. kafka/protocol/schemas/__init__.py +7 -0
  231. kafka/protocol/schemas/fields/__init__.py +7 -0
  232. kafka/protocol/schemas/fields/array.py +127 -0
  233. kafka/protocol/schemas/fields/base.py +156 -0
  234. kafka/protocol/schemas/fields/codecs/__init__.py +12 -0
  235. kafka/protocol/schemas/fields/codecs/encode_buffer.py +82 -0
  236. kafka/protocol/schemas/fields/codecs/tagged_fields.py +109 -0
  237. kafka/protocol/schemas/fields/codecs/types.py +505 -0
  238. kafka/protocol/schemas/fields/codegen.py +40 -0
  239. kafka/protocol/schemas/fields/simple.py +127 -0
  240. kafka/protocol/schemas/fields/struct.py +357 -0
  241. kafka/protocol/schemas/fields/struct_array.py +142 -0
  242. kafka/protocol/schemas/load_json.py +42 -0
  243. kafka/protocol/schemas/resources/AddOffsetsToTxnRequest.json +40 -0
  244. kafka/protocol/schemas/resources/AddOffsetsToTxnResponse.json +35 -0
  245. kafka/protocol/schemas/resources/AddPartitionsToTxnRequest.json +65 -0
  246. kafka/protocol/schemas/resources/AddPartitionsToTxnResponse.json +60 -0
  247. kafka/protocol/schemas/resources/AlterClientQuotasRequest.json +47 -0
  248. kafka/protocol/schemas/resources/AlterClientQuotasResponse.json +41 -0
  249. kafka/protocol/schemas/resources/AlterConfigsRequest.json +43 -0
  250. kafka/protocol/schemas/resources/AlterConfigsResponse.json +39 -0
  251. kafka/protocol/schemas/resources/AlterPartitionReassignmentsRequest.json +42 -0
  252. kafka/protocol/schemas/resources/AlterPartitionReassignmentsResponse.json +47 -0
  253. kafka/protocol/schemas/resources/AlterReplicaLogDirsRequest.json +41 -0
  254. kafka/protocol/schemas/resources/AlterReplicaLogDirsResponse.json +41 -0
  255. kafka/protocol/schemas/resources/AlterUserScramCredentialsRequest.json +45 -0
  256. kafka/protocol/schemas/resources/AlterUserScramCredentialsResponse.json +35 -0
  257. kafka/protocol/schemas/resources/ApiVersionsRequest.json +34 -0
  258. kafka/protocol/schemas/resources/ApiVersionsResponse.json +79 -0
  259. kafka/protocol/schemas/resources/ConsumerProtocolAssignment.json +42 -0
  260. kafka/protocol/schemas/resources/ConsumerProtocolSubscription.json +49 -0
  261. kafka/protocol/schemas/resources/CreateAclsRequest.json +46 -0
  262. kafka/protocol/schemas/resources/CreateAclsResponse.json +37 -0
  263. kafka/protocol/schemas/resources/CreatePartitionsRequest.json +47 -0
  264. kafka/protocol/schemas/resources/CreatePartitionsResponse.json +41 -0
  265. kafka/protocol/schemas/resources/CreateTopicsRequest.json +65 -0
  266. kafka/protocol/schemas/resources/CreateTopicsResponse.json +72 -0
  267. kafka/protocol/schemas/resources/DeleteAclsRequest.json +46 -0
  268. kafka/protocol/schemas/resources/DeleteAclsResponse.json +59 -0
  269. kafka/protocol/schemas/resources/DeleteGroupsRequest.json +30 -0
  270. kafka/protocol/schemas/resources/DeleteGroupsResponse.json +36 -0
  271. kafka/protocol/schemas/resources/DeleteRecordsRequest.json +42 -0
  272. kafka/protocol/schemas/resources/DeleteRecordsResponse.json +43 -0
  273. kafka/protocol/schemas/resources/DeleteTopicsRequest.json +43 -0
  274. kafka/protocol/schemas/resources/DeleteTopicsResponse.json +52 -0
  275. kafka/protocol/schemas/resources/DescribeAclsRequest.json +43 -0
  276. kafka/protocol/schemas/resources/DescribeAclsResponse.json +55 -0
  277. kafka/protocol/schemas/resources/DescribeClientQuotasRequest.json +37 -0
  278. kafka/protocol/schemas/resources/DescribeClientQuotasResponse.json +47 -0
  279. kafka/protocol/schemas/resources/DescribeClusterRequest.json +35 -0
  280. kafka/protocol/schemas/resources/DescribeClusterResponse.json +56 -0
  281. kafka/protocol/schemas/resources/DescribeConfigsRequest.json +42 -0
  282. kafka/protocol/schemas/resources/DescribeConfigsResponse.json +69 -0
  283. kafka/protocol/schemas/resources/DescribeGroupsRequest.json +38 -0
  284. kafka/protocol/schemas/resources/DescribeGroupsResponse.json +74 -0
  285. kafka/protocol/schemas/resources/DescribeLogDirsRequest.json +38 -0
  286. kafka/protocol/schemas/resources/DescribeLogDirsResponse.json +65 -0
  287. kafka/protocol/schemas/resources/DescribeProducersRequest.json +32 -0
  288. kafka/protocol/schemas/resources/DescribeProducersResponse.json +55 -0
  289. kafka/protocol/schemas/resources/DescribeQuorumRequest.json +39 -0
  290. kafka/protocol/schemas/resources/DescribeQuorumResponse.json +82 -0
  291. kafka/protocol/schemas/resources/DescribeTopicPartitionsRequest.json +40 -0
  292. kafka/protocol/schemas/resources/DescribeTopicPartitionsResponse.json +66 -0
  293. kafka/protocol/schemas/resources/DescribeTransactionsRequest.json +27 -0
  294. kafka/protocol/schemas/resources/DescribeTransactionsResponse.json +52 -0
  295. kafka/protocol/schemas/resources/DescribeUserScramCredentialsRequest.json +30 -0
  296. kafka/protocol/schemas/resources/DescribeUserScramCredentialsResponse.json +45 -0
  297. kafka/protocol/schemas/resources/ElectLeadersRequest.json +41 -0
  298. kafka/protocol/schemas/resources/ElectLeadersResponse.json +45 -0
  299. kafka/protocol/schemas/resources/EndTxnRequest.json +43 -0
  300. kafka/protocol/schemas/resources/EndTxnResponse.json +41 -0
  301. kafka/protocol/schemas/resources/FetchRequest.json +125 -0
  302. kafka/protocol/schemas/resources/FetchResponse.json +124 -0
  303. kafka/protocol/schemas/resources/FindCoordinatorRequest.json +43 -0
  304. kafka/protocol/schemas/resources/FindCoordinatorResponse.json +58 -0
  305. kafka/protocol/schemas/resources/HeartbeatRequest.json +39 -0
  306. kafka/protocol/schemas/resources/HeartbeatResponse.json +35 -0
  307. kafka/protocol/schemas/resources/IncrementalAlterConfigsRequest.json +44 -0
  308. kafka/protocol/schemas/resources/IncrementalAlterConfigsResponse.json +38 -0
  309. kafka/protocol/schemas/resources/InitProducerIdRequest.json +50 -0
  310. kafka/protocol/schemas/resources/InitProducerIdResponse.json +47 -0
  311. kafka/protocol/schemas/resources/JoinGroupRequest.json +63 -0
  312. kafka/protocol/schemas/resources/JoinGroupResponse.json +69 -0
  313. kafka/protocol/schemas/resources/LeaveGroupRequest.json +47 -0
  314. kafka/protocol/schemas/resources/LeaveGroupResponse.json +47 -0
  315. kafka/protocol/schemas/resources/ListConfigResourcesRequest.json +31 -0
  316. kafka/protocol/schemas/resources/ListConfigResourcesResponse.json +37 -0
  317. kafka/protocol/schemas/resources/ListGroupsRequest.json +36 -0
  318. kafka/protocol/schemas/resources/ListGroupsResponse.json +49 -0
  319. kafka/protocol/schemas/resources/ListOffsetsRequest.json +72 -0
  320. kafka/protocol/schemas/resources/ListOffsetsResponse.json +71 -0
  321. kafka/protocol/schemas/resources/ListPartitionReassignmentsRequest.json +34 -0
  322. kafka/protocol/schemas/resources/ListPartitionReassignmentsResponse.json +46 -0
  323. kafka/protocol/schemas/resources/ListTransactionsRequest.json +40 -0
  324. kafka/protocol/schemas/resources/ListTransactionsResponse.json +42 -0
  325. kafka/protocol/schemas/resources/MetadataRequest.json +56 -0
  326. kafka/protocol/schemas/resources/MetadataResponse.json +101 -0
  327. kafka/protocol/schemas/resources/OffsetCommitRequest.json +76 -0
  328. kafka/protocol/schemas/resources/OffsetCommitResponse.json +71 -0
  329. kafka/protocol/schemas/resources/OffsetDeleteRequest.json +39 -0
  330. kafka/protocol/schemas/resources/OffsetDeleteResponse.json +42 -0
  331. kafka/protocol/schemas/resources/OffsetFetchRequest.json +76 -0
  332. kafka/protocol/schemas/resources/OffsetFetchResponse.json +107 -0
  333. kafka/protocol/schemas/resources/OffsetForLeaderEpochRequest.json +52 -0
  334. kafka/protocol/schemas/resources/OffsetForLeaderEpochResponse.json +51 -0
  335. kafka/protocol/schemas/resources/ProduceRequest.json +73 -0
  336. kafka/protocol/schemas/resources/ProduceResponse.json +96 -0
  337. kafka/protocol/schemas/resources/RequestHeader.json +44 -0
  338. kafka/protocol/schemas/resources/ResponseHeader.json +26 -0
  339. kafka/protocol/schemas/resources/SaslAuthenticateRequest.json +29 -0
  340. kafka/protocol/schemas/resources/SaslAuthenticateResponse.json +34 -0
  341. kafka/protocol/schemas/resources/SaslHandshakeRequest.json +31 -0
  342. kafka/protocol/schemas/resources/SaslHandshakeResponse.json +32 -0
  343. kafka/protocol/schemas/resources/SyncGroupRequest.json +56 -0
  344. kafka/protocol/schemas/resources/SyncGroupResponse.json +46 -0
  345. kafka/protocol/schemas/resources/TxnOffsetCommitRequest.json +68 -0
  346. kafka/protocol/schemas/resources/TxnOffsetCommitResponse.json +47 -0
  347. kafka/protocol/schemas/resources/UpdateFeaturesRequest.json +43 -0
  348. kafka/protocol/schemas/resources/UpdateFeaturesResponse.json +39 -0
  349. kafka/protocol/schemas/resources/WriteTxnMarkersRequest.json +49 -0
  350. kafka/protocol/schemas/resources/WriteTxnMarkersResponse.json +45 -0
  351. kafka/protocol/schemas/resources/__init__.py +0 -0
  352. kafka/record/__init__.py +3 -0
  353. kafka/record/_crc32c.py +161 -0
  354. kafka/record/abc.py +144 -0
  355. kafka/record/default_records.py +782 -0
  356. kafka/record/legacy_records.py +587 -0
  357. kafka/record/memory_records.py +255 -0
  358. kafka/record/util.py +135 -0
  359. kafka/serializer/__init__.py +4 -0
  360. kafka/serializer/abstract.py +20 -0
  361. kafka/serializer/default.py +16 -0
  362. kafka/serializer/json.py +17 -0
  363. kafka/serializer/wrapper.py +21 -0
  364. kafka/structs.py +69 -0
  365. kafka/util.py +159 -0
  366. kafka/vendor/__init__.py +0 -0
  367. kafka/version.py +1 -0
  368. kafka_python-3.0.0.dist-info/METADATA +319 -0
  369. kafka_python-3.0.0.dist-info/RECORD +373 -0
  370. kafka_python-3.0.0.dist-info/WHEEL +5 -0
  371. kafka_python-3.0.0.dist-info/entry_points.txt +2 -0
  372. kafka_python-3.0.0.dist-info/licenses/LICENSE +202 -0
  373. kafka_python-3.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1347 @@
1
+ import copy
2
+ import logging
3
+ import re
4
+ import selectors
5
+ import socket
6
+ import time
7
+
8
+ import kafka.errors as Errors
9
+ from kafka.errors import KafkaConfigurationError, UnsupportedVersionError
10
+
11
+ from kafka.consumer.fetcher import Fetcher
12
+ from kafka.consumer.subscription_state import SubscriptionState
13
+ from kafka.coordinator.consumer import ConsumerCoordinator
14
+ from kafka.coordinator.assignors.range import RangePartitionAssignor
15
+ from kafka.coordinator.assignors.roundrobin import RoundRobinPartitionAssignor
16
+ from kafka.metrics import MetricConfig, Metrics
17
+ from kafka.net.compat import KafkaNetClient
18
+ from kafka.protocol.consumer import OffsetResetStrategy
19
+ from kafka.structs import ConsumerGroupMetadata, OffsetAndMetadata, TopicPartition
20
+ from kafka.util import Timer
21
+ from kafka.version import __version__
22
+
23
+ log = logging.getLogger(__name__)
24
+
25
+
26
+ class KafkaConsumer:
27
+ """Consume records from a Kafka cluster.
28
+
29
+ The consumer will transparently handle the failure of servers in the Kafka
30
+ cluster, and adapt as topic-partitions are created or migrate between
31
+ brokers. It also interacts with the assigned kafka Group Coordinator node
32
+ to allow multiple consumers to load balance consumption of topics (requires
33
+ kafka >= 0.9.0.0).
34
+
35
+ The consumer is not thread safe and should not be shared across threads.
36
+
37
+ Arguments:
38
+ *topics (str): optional list of topics to subscribe to. If not set,
39
+ call :meth:`~kafka.KafkaConsumer.subscribe` or
40
+ :meth:`~kafka.KafkaConsumer.assign` before consuming records.
41
+
42
+ Keyword Arguments:
43
+ bootstrap_servers: 'host[:port]' string (or list of 'host[:port]'
44
+ strings) that the consumer should contact to bootstrap initial
45
+ cluster metadata. This does not have to be the full node list.
46
+ It just needs to have at least one broker that will respond to a
47
+ Metadata API Request. Default port is 9092. If no servers are
48
+ specified, will default to localhost:9092.
49
+ client_id (str): A name for this client. This string is passed in
50
+ each request to servers and can be used to identify specific
51
+ server-side log entries that correspond to this client. Also
52
+ submitted to GroupCoordinator for logging with respect to
53
+ consumer group administration. Default: 'kafka-python-{version}'
54
+ client_rack (str): A rack identifier for this client. Sent to brokers
55
+ on FetchRequest v11+ (KIP-392, requires Kafka 2.4+ brokers with
56
+ ``replica.selector.class`` configured server-side). When set, the
57
+ broker may route fetches to a follower replica in the same rack
58
+ instead of the leader, reducing cross-rack traffic. Leave as ''
59
+ (default) to always fetch from the leader.
60
+ group_id (str or None): The name of the consumer group to join for dynamic
61
+ partition assignment (if enabled), and to use for fetching and
62
+ committing offsets. If None, auto-partition assignment (via
63
+ group coordinator) and offset commits are disabled.
64
+ Default: None
65
+ group_instance_id (str): A unique identifier of the consumer instance
66
+ provided by end user. Only non-empty strings are permitted. If set,
67
+ the consumer is treated as a static member, which means that only
68
+ one instance with this ID is allowed in the consumer group at any
69
+ time. This can be used in combination with a larger session timeout
70
+ to avoid group rebalances caused by transient unavailability (e.g.
71
+ process restarts). If not set, the consumer will join the group as
72
+ a dynamic member, which is the traditional behavior. Default: None
73
+ key_deserializer (kafka.serializer.Deserializer): Takes a
74
+ raw message key and returns a deserialized key.
75
+ Default: None.
76
+ value_deserializer (kafka.serializer.Deserializer): Takes a
77
+ raw message value and returns a deserialized value.
78
+ Default: None.
79
+ enable_incremental_fetch_sessions: (bool): Use incremental fetch sessions
80
+ when available / supported by kafka broker. See KIP-227. Default: True.
81
+ fetch_min_bytes (int): Minimum amount of data the server should
82
+ return for a fetch request, otherwise wait up to
83
+ fetch_max_wait_ms for more data to accumulate. Default: 1.
84
+ fetch_max_wait_ms (int): The maximum amount of time in milliseconds
85
+ the server will block before answering the fetch request if
86
+ there isn't sufficient data to immediately satisfy the
87
+ requirement given by fetch_min_bytes. Default: 500.
88
+ fetch_max_bytes (int): The maximum amount of data the server should
89
+ return for a fetch request. This is not an absolute maximum, if the
90
+ first message in the first non-empty partition of the fetch is
91
+ larger than this value, the message will still be returned to
92
+ ensure that the consumer can make progress. NOTE: consumer performs
93
+ fetches to multiple brokers in parallel so memory usage will depend
94
+ on the number of brokers containing partitions for the topic.
95
+ Supported Kafka version >= 0.10.1.0. Default: 52428800 (50 MB).
96
+ max_partition_fetch_bytes (int): The maximum amount of data
97
+ per-partition the server will return. The maximum total memory
98
+ used for a request = #partitions * max_partition_fetch_bytes.
99
+ This size must be at least as large as the maximum message size
100
+ the server allows or else it is possible for the producer to
101
+ send messages larger than the consumer can fetch. If that
102
+ happens, the consumer can get stuck trying to fetch a large
103
+ message on a certain partition. Default: 1048576.
104
+ request_timeout_ms (int): Client request timeout in milliseconds.
105
+ Default: 305000.
106
+ retry_backoff_ms (int): Milliseconds to backoff when retrying on
107
+ errors. Default: 100.
108
+ reconnect_backoff_ms (int): The amount of time in milliseconds to
109
+ wait before attempting to reconnect to a given host.
110
+ Default: 50.
111
+ reconnect_backoff_max_ms (int): The maximum amount of time in
112
+ milliseconds to backoff/wait when reconnecting to a broker that has
113
+ repeatedly failed to connect. If provided, the backoff per host
114
+ will increase exponentially for each consecutive connection
115
+ failure, up to this maximum. Once the maximum is reached,
116
+ reconnection attempts will continue periodically with this fixed
117
+ rate. To avoid connection storms, a randomization factor of 0.2
118
+ will be applied to the backoff resulting in a random range between
119
+ 20% below and 20% above the computed value. Default: 30000.
120
+ max_in_flight_requests_per_connection (int): Requests are pipelined
121
+ to kafka brokers up to this number of maximum requests per
122
+ broker connection. Default: 5.
123
+ auto_offset_reset (str): A policy for resetting offsets on
124
+ OffsetOutOfRange errors: 'earliest' will move to the oldest
125
+ available message, 'latest' will move to the most recent. Any
126
+ other value will raise the exception. Default: 'latest'.
127
+ enable_auto_commit (bool): If True , the consumer's offset will be
128
+ periodically committed in the background. Default: True.
129
+ auto_commit_interval_ms (int): Number of milliseconds between automatic
130
+ offset commits, if enable_auto_commit is True. Default: 5000.
131
+ default_offset_commit_callback (callable): Called as
132
+ callback(offsets, response) response will be either an Exception
133
+ or an OffsetCommitResponse struct. This callback can be used to
134
+ trigger custom actions when a commit request completes.
135
+ check_crcs (bool): Automatically check the CRC32 of the records
136
+ consumed. This ensures no on-the-wire or on-disk corruption to
137
+ the messages occurred. This check adds some overhead, so it may
138
+ be disabled in cases seeking extreme performance. Default: True
139
+ isolation_level (str): Configure KIP-98 transactional consumer by
140
+ setting to 'read_committed'. This will cause the consumer to
141
+ skip records from aborted transactions. Default: 'read_uncommitted'
142
+ allow_auto_create_topics (bool): Enable/disable auto topic creation
143
+ on metadata request. Only available with api_version >= (0, 11).
144
+ Default: True
145
+ metadata_max_age_ms (int): The period of time in milliseconds after
146
+ which we force a refresh of metadata, even if we haven't seen any
147
+ partition leadership changes to proactively discover any new
148
+ brokers or partitions. Default: 300000
149
+ partition_assignment_strategy (list): List of objects to use to
150
+ distribute partition ownership amongst consumer instances when
151
+ group management is used.
152
+ Default: [RangePartitionAssignor, RoundRobinPartitionAssignor]
153
+ max_poll_records (int): The maximum number of records returned in a
154
+ single call to :meth:`~kafka.KafkaConsumer.poll`. Default: 500
155
+ max_poll_interval_ms (int): The maximum delay between invocations of
156
+ :meth:`~kafka.KafkaConsumer.poll` when using consumer group
157
+ management. This places an upper bound on the amount of time that
158
+ the consumer can be idle before fetching more records. If
159
+ :meth:`~kafka.KafkaConsumer.poll` is not called before expiration
160
+ of this timeout, then the consumer is considered failed and the
161
+ group will rebalance in order to reassign the partitions to another
162
+ member. Default 300000
163
+ session_timeout_ms (int): The timeout used to detect failures when
164
+ using Kafka's group management facilities. The consumer sends
165
+ periodic heartbeats to indicate its liveness to the broker. If
166
+ no heartbeats are received by the broker before the expiration of
167
+ this session timeout, then the broker will remove this consumer
168
+ from the group and initiate a rebalance. Note that the value must
169
+ be in the allowable range as configured in the broker configuration
170
+ by group.min.session.timeout.ms and group.max.session.timeout.ms.
171
+ Default: 45000 for brokers 3.0+, otherwise 30000.
172
+ heartbeat_interval_ms (int): The expected time in milliseconds
173
+ between heartbeats to the consumer coordinator when using
174
+ Kafka's group management facilities. Heartbeats are used to ensure
175
+ that the consumer's session stays active and to facilitate
176
+ rebalancing when new consumers join or leave the group. The
177
+ value must be set lower than session_timeout_ms, but typically
178
+ should be set no higher than 1/3 of that value. It can be
179
+ adjusted even lower to control the expected time for normal
180
+ rebalances. Default: 3000
181
+ receive_message_max_bytes (int): Maximum allowed network frame size.
182
+ Used to avoid OOM when decoding malformed network message header.
183
+ Default: 1000000.
184
+ receive_buffer_bytes (int): The size of the TCP receive buffer
185
+ (SO_RCVBUF) to use when reading data. Default: None (relies on
186
+ system defaults). The java client defaults to 32768.
187
+ send_buffer_bytes (int): The size of the TCP send buffer
188
+ (SO_SNDBUF) to use when sending data. Default: None (relies on
189
+ system defaults). The java client defaults to 131072.
190
+ socket_options (list): List of tuple-arguments to socket.setsockopt
191
+ to apply to broker connection sockets. Default:
192
+ [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]
193
+ consumer_timeout_ms (int): number of milliseconds to block during
194
+ message iteration before raising StopIteration (i.e., ending the
195
+ iterator). Default block forever [float('inf')].
196
+ security_protocol (str): Protocol used to communicate with brokers.
197
+ Valid values are: PLAINTEXT, SSL, SASL_PLAINTEXT, SASL_SSL.
198
+ Default: PLAINTEXT.
199
+ ssl_context (ssl.SSLContext): Pre-configured SSLContext for wrapping
200
+ socket connections. If provided, all other ssl_* configurations
201
+ will be ignored. Default: None.
202
+ ssl_check_hostname (bool): Flag to configure whether ssl handshake
203
+ should verify that the certificate matches the brokers hostname.
204
+ Default: True.
205
+ ssl_cafile (str): Optional filename of ca file to use in certificate
206
+ verification. Default: None.
207
+ ssl_certfile (str): Optional filename of file in pem format containing
208
+ the client certificate, as well as any ca certificates needed to
209
+ establish the certificate's authenticity. Default: None.
210
+ ssl_keyfile (str): Optional filename containing the client private key.
211
+ Default: None.
212
+ ssl_password (str): Optional password to be used when loading the
213
+ certificate chain. Default: None.
214
+ ssl_crlfile (str): Optional filename containing the CRL to check for
215
+ certificate expiration. By default, no CRL check is done. When
216
+ providing a file, only the leaf certificate will be checked against
217
+ this CRL. Default: None.
218
+ ssl_ciphers (str): optionally set the available ciphers for ssl
219
+ connections. It should be a string in the OpenSSL cipher list
220
+ format. If no cipher can be selected (because compile-time options
221
+ or other configuration forbids use of all the specified ciphers),
222
+ an ssl.SSLError will be raised. See ssl.SSLContext.set_ciphers
223
+ api_version (tuple): Specify which Kafka API version to use. If set to
224
+ None, the client will infer the broker version from the results of
225
+ ApiVersionsRequest API. For brokers earlier than 0.10, which do not
226
+ support the ApiVersionsRequest API, api_version is required.
227
+ Note: Dynamic version checking is performed eagerly during __init__
228
+ and can raise KafkaTimeoutError if no connection can be made before
229
+ timeout (see bootstrap_timeout_ms below).
230
+ Different versions enable different functionality.
231
+
232
+ Examples::
233
+
234
+ (4, 3) most recent broker release, enable all supported features
235
+ (0, 11) enables message format v2 (internal)
236
+ (0, 10, 0) enables sasl authentication and message format v1
237
+ (0, 9) enables full group coordination features with automatic
238
+ partition assignment and rebalancing,
239
+ (0, 8, 2) enables kafka-storage offset commits with manual
240
+ partition assignment only,
241
+ (0, 8, 1) enables zookeeper-storage offset commits with manual
242
+ partition assignment only,
243
+ (0, 8, 0) enables basic functionality but requires manual
244
+ partition assignment and offset management.
245
+
246
+ Default: None
247
+ bootstrap_timeout_ms (int): number of milliseconds to wait for first
248
+ successful cluster bootstrap. If provided, an attempt to bootstrap
249
+ will raise KafkaTimeoutError if it is unable to fetch cluster
250
+ metadata before the configured timeout. Note that bootstrap will
251
+ be called eagerly from __init__() if api_version is None.
252
+ Default: 30000
253
+ connections_max_idle_ms: Close idle connections after the number of
254
+ milliseconds specified by this config. The broker closes idle
255
+ connections after connections.max.idle.ms, so this avoids hitting
256
+ unexpected socket disconnected errors on the client.
257
+ Default: 540000
258
+ metric_reporters (list): A list of classes to use as metrics reporters.
259
+ Implementing the AbstractMetricsReporter interface allows plugging
260
+ in classes that will be notified of new metric creation. Default: []
261
+ metrics_enabled (bool): Whether to track metrics on this instance. Default True.
262
+ metrics_num_samples (int): The number of samples maintained to compute
263
+ metrics. Default: 2
264
+ metrics_sample_window_ms (int): The maximum age in milliseconds of
265
+ samples used to compute metrics. Default: 30000
266
+ selector (selectors.BaseSelector): Provide a specific selector
267
+ implementation to use for I/O multiplexing.
268
+ Default: selectors.DefaultSelector
269
+ exclude_internal_topics (bool): Whether records from internal topics
270
+ (such as offsets) should be exposed to the consumer. If set to True
271
+ the only way to receive records from an internal topic is
272
+ subscribing to it. Requires 0.10+ Default: True
273
+ sasl_mechanism (str): Authentication mechanism when security_protocol
274
+ is configured for SASL_PLAINTEXT or SASL_SSL. Valid values are:
275
+ PLAIN, GSSAPI, OAUTHBEARER, SCRAM-SHA-256, SCRAM-SHA-512.
276
+ sasl_plain_username (str): username for sasl PLAIN and SCRAM authentication.
277
+ Required if sasl_mechanism is PLAIN or one of the SCRAM mechanisms.
278
+ sasl_plain_password (str): password for sasl PLAIN and SCRAM authentication.
279
+ Required if sasl_mechanism is PLAIN or one of the SCRAM mechanisms.
280
+ sasl_kerberos_name (str or gssapi.Name): Constructed gssapi.Name for use with
281
+ sasl mechanism handshake. If provided, sasl_kerberos_service_name and
282
+ sasl_kerberos_domain name are ignored. Default: None.
283
+ sasl_kerberos_service_name (str): Service name to include in GSSAPI
284
+ sasl mechanism handshake. Default: 'kafka'
285
+ sasl_kerberos_domain_name (str): kerberos domain name to use in GSSAPI
286
+ sasl mechanism handshake. Default: one of bootstrap servers
287
+ sasl_oauth_token_provider (kafka.net.sasl.oauth.AbstractTokenProvider): OAuthBearer
288
+ token provider instance. Default: None
289
+ proxy_url (str): URL to proxy socket connections through. Supports SOCKS5 only.
290
+ Requires scheme:// (e.g., socks5://foo.bar/). Default: None
291
+ kafka_client (callable): Custom class / callable for creating KafkaNetClient instances
292
+
293
+ Note:
294
+ Configuration parameters are described in more detail at
295
+ https://kafka.apache.org/documentation/#consumerconfigs
296
+ """
297
+ DEFAULT_CONFIG = {
298
+ 'bootstrap_servers': 'localhost',
299
+ 'client_id': 'kafka-python-' + __version__,
300
+ 'client_rack': '',
301
+ 'group_id': None,
302
+ 'group_instance_id': None,
303
+ 'key_deserializer': None,
304
+ 'value_deserializer': None,
305
+ 'enable_incremental_fetch_sessions': True,
306
+ 'fetch_max_wait_ms': 500,
307
+ 'fetch_min_bytes': 1,
308
+ 'fetch_max_bytes': 52428800,
309
+ 'max_partition_fetch_bytes': 1 * 1024 * 1024,
310
+ 'request_timeout_ms': 30000,
311
+ 'retry_backoff_ms': 100,
312
+ 'reconnect_backoff_ms': 50,
313
+ 'reconnect_backoff_max_ms': 30000,
314
+ 'max_in_flight_requests_per_connection': 5,
315
+ 'auto_offset_reset': 'latest',
316
+ 'enable_auto_commit': True,
317
+ 'auto_commit_interval_ms': 5000,
318
+ 'default_offset_commit_callback': lambda offsets, response: True,
319
+ 'check_crcs': True,
320
+ 'isolation_level': 'read_uncommitted',
321
+ 'allow_auto_create_topics': True,
322
+ 'metadata_max_age_ms': 5 * 60 * 1000,
323
+ 'client_dns_lookup': 'use_all_dns_ips',
324
+ 'partition_assignment_strategy': (RangePartitionAssignor, RoundRobinPartitionAssignor),
325
+ 'max_poll_records': 500,
326
+ 'max_poll_interval_ms': 300000,
327
+ 'session_timeout_ms': 45000,
328
+ 'heartbeat_interval_ms': 3000,
329
+ 'receive_buffer_bytes': None,
330
+ 'send_buffer_bytes': None,
331
+ 'receive_message_max_bytes': 1000000,
332
+ 'socket_options': [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)],
333
+ 'consumer_timeout_ms': float('inf'),
334
+ 'security_protocol': 'PLAINTEXT',
335
+ 'ssl_context': None,
336
+ 'ssl_check_hostname': True,
337
+ 'ssl_cafile': None,
338
+ 'ssl_certfile': None,
339
+ 'ssl_keyfile': None,
340
+ 'ssl_crlfile': None,
341
+ 'ssl_password': None,
342
+ 'ssl_ciphers': None,
343
+ 'api_version': None,
344
+ 'bootstrap_timeout_ms': 30000,
345
+ 'connections_max_idle_ms': 9 * 60 * 1000,
346
+ 'metric_reporters': [],
347
+ 'metrics_enabled': True,
348
+ 'metrics_num_samples': 2,
349
+ 'metrics_sample_window_ms': 30000,
350
+ 'metric_group_prefix': 'consumer',
351
+ 'selector': selectors.DefaultSelector,
352
+ 'exclude_internal_topics': True,
353
+ 'sasl_mechanism': None,
354
+ 'sasl_plain_username': None,
355
+ 'sasl_plain_password': None,
356
+ 'sasl_kerberos_name': None,
357
+ 'sasl_kerberos_service_name': 'kafka',
358
+ 'sasl_kerberos_domain_name': None,
359
+ 'sasl_oauth_token_provider': None,
360
+ 'proxy_url': None,
361
+ 'socks5_proxy': None, # deprecated
362
+ 'kafka_client': KafkaNetClient,
363
+ }
364
+ DEFAULT_SESSION_TIMEOUT_MS_PRE_KIP_735 = 30000
365
+
366
+ def __init__(self, *topics, **configs):
367
+ # Only check for extra config keys in top-level class
368
+ extra_configs = set(configs).difference(self.DEFAULT_CONFIG)
369
+ if extra_configs:
370
+ raise KafkaConfigurationError("Unrecognized configs: %s" % (extra_configs,))
371
+
372
+ self.config = copy.copy(self.DEFAULT_CONFIG)
373
+ self.config.update(configs)
374
+
375
+ deprecated = {'smallest': 'earliest', 'largest': 'latest'}
376
+ if self.config['auto_offset_reset'] in deprecated:
377
+ new_config = deprecated[self.config['auto_offset_reset']]
378
+ log.warning('use auto_offset_reset=%s (%s is deprecated)',
379
+ new_config, self.config['auto_offset_reset'])
380
+ self.config['auto_offset_reset'] = new_config
381
+
382
+ connections_max_idle_ms = self.config['connections_max_idle_ms']
383
+ request_timeout_ms = self.config['request_timeout_ms']
384
+ fetch_max_wait_ms = self.config['fetch_max_wait_ms']
385
+ if not (fetch_max_wait_ms < request_timeout_ms < connections_max_idle_ms):
386
+ raise KafkaConfigurationError(
387
+ "connections_max_idle_ms ({}) must be larger than "
388
+ "request_timeout_ms ({}) which must be larger than "
389
+ "fetch_max_wait_ms ({})."
390
+ .format(connections_max_idle_ms, request_timeout_ms, fetch_max_wait_ms))
391
+
392
+ if self.config['metrics_enabled']:
393
+ metrics_tags = {'client-id': self.config['client_id']}
394
+ metric_config = MetricConfig(samples=self.config['metrics_num_samples'],
395
+ time_window_ms=self.config['metrics_sample_window_ms'],
396
+ tags=metrics_tags)
397
+ reporters = [reporter() for reporter in self.config['metric_reporters']]
398
+ self._metrics = Metrics(metric_config, reporters)
399
+ else:
400
+ self._metrics = None
401
+
402
+ self._client = self.config['kafka_client'](metrics=self._metrics, **self.config)
403
+ self._manager = self._client._manager
404
+ self._cluster = self._manager.cluster
405
+ self._net = self._manager._net
406
+
407
+ # Drive the IO loop on a background thread so coroutines (heartbeat,
408
+ # metadata refresh) make progress without depending on user-thread
409
+ # poll() timing.
410
+ self._net.start()
411
+
412
+ # We currently depend on eager-resolution of api_version.
413
+ # If it wasn't provided as a config option, we need to bootstrap
414
+ # to get it.
415
+ if self._manager.broker_version_data is None:
416
+ self._manager.bootstrap(self.config['bootstrap_timeout_ms'])
417
+ self.config['api_version'] = self._manager.broker_version
418
+
419
+ # Coordinator configurations are different for older brokers
420
+ # max_poll_interval_ms is not supported directly -- it must the be
421
+ # the same as session_timeout_ms. If the user provides one of them,
422
+ # use it for both.
423
+ user_supplied_session_timeout = 'session_timeout_ms' in configs
424
+ user_supplied_max_poll_interval = 'max_poll_interval_ms' in configs
425
+
426
+ if not user_supplied_session_timeout:
427
+ if self.config['api_version'] < (0, 10, 1) and user_supplied_max_poll_interval:
428
+ self.config['session_timeout_ms'] = self.config['max_poll_interval_ms']
429
+
430
+ elif self.config['api_version'] < (3, 0):
431
+ # Prior to 3.0 the broker-side default max session timeout was 30000
432
+ self.config['session_timeout_ms'] = self.DEFAULT_SESSION_TIMEOUT_MS_PRE_KIP_735
433
+
434
+ if not user_supplied_max_poll_interval:
435
+ if self.config['api_version'] < (0, 10, 1):
436
+ self.config['max_poll_interval_ms'] = self.config['session_timeout_ms']
437
+
438
+ if self.config['group_instance_id'] is not None:
439
+ if self.config['group_id'] is None:
440
+ raise KafkaConfigurationError("group_instance_id requires group_id")
441
+
442
+ self._subscription = SubscriptionState(self.config['auto_offset_reset'])
443
+ self._fetcher = Fetcher(
444
+ self._client, self._subscription, metrics=self._metrics, **self.config)
445
+ self._coordinator = ConsumerCoordinator(
446
+ self._client, self._subscription, metrics=self._metrics,
447
+ assignors=self.config['partition_assignment_strategy'],
448
+ **self.config)
449
+ self._closed = False
450
+ self._iterator = None
451
+ self._consumer_timeout = float('inf')
452
+
453
+ if topics:
454
+ self._subscription.subscribe(topics=topics)
455
+ self._cluster.set_topics(topics)
456
+
457
+ def _validate_group_instance_id(self, group_instance_id):
458
+ # See also kafka.util.ensure_valid_topic_name
459
+ if not group_instance_id or not isinstance(group_instance_id, str):
460
+ raise KafkaConfigurationError("group_instance_id must be non-empty string")
461
+ if group_instance_id in (".", ".."):
462
+ raise KafkaConfigurationError("group_instance_id cannot be \".\" or \"..\"")
463
+ if len(group_instance_id) > 249:
464
+ raise KafkaConfigurationError("group_instance_id can't be longer than 249 characters")
465
+ if not re.match(r'^[A-Za-z0-9\.\_\-]+$', group_instance_id):
466
+ raise KafkaConfigurationError("group_instance_id is illegal: it contains a character other than ASCII alphanumerics, '.', '_' and '-'")
467
+
468
+ def bootstrap_connected(self):
469
+ """Return True if the bootstrap is connected."""
470
+ return self._client.bootstrap_connected()
471
+
472
+ def bootstrap(self, timeout_ms=None, refresh=False):
473
+ """Block until the consumer has bootstrapped cluster metadata.
474
+
475
+ Bootstrap is otherwise driven lazily by the IO thread when
476
+ metadata is first needed (e.g. on the first ``poll()`` or
477
+ ``topics()`` call). Call this to deterministically wait for
478
+ ``cluster.brokers()`` to be populated -- useful in tests and at
479
+ startup when the caller wants metadata available before issuing
480
+ the first request.
481
+
482
+ Arguments:
483
+ timeout_ms (int, optional): Maximum time to wait, in
484
+ milliseconds. ``None`` waits indefinitely. Default: None.
485
+ refresh (bool): If True, force a new bootstrap even when one
486
+ has already succeeded. Default: False.
487
+
488
+ Raises:
489
+ KafkaTimeoutError: If bootstrap does not complete within
490
+ ``timeout_ms``.
491
+ """
492
+ self._manager.bootstrap(timeout_ms=timeout_ms, refresh=refresh)
493
+
494
+ def assign(self, partitions):
495
+ """Manually assign a list of TopicPartitions to this consumer.
496
+
497
+ Arguments:
498
+ partitions (list of TopicPartition): Assignment for this instance.
499
+
500
+ Raises:
501
+ IllegalStateError: If consumer has already called
502
+ :meth:`~kafka.KafkaConsumer.subscribe`.
503
+
504
+ Warning:
505
+ It is not possible to use both manual partition assignment with
506
+ :meth:`~kafka.KafkaConsumer.assign` and group assignment with
507
+ :meth:`~kafka.KafkaConsumer.subscribe`.
508
+
509
+ Note:
510
+ This interface does not support incremental assignment and will
511
+ replace the previous assignment (if there was one).
512
+
513
+ Note:
514
+ Manual topic assignment through this method does not use the
515
+ consumer's group management functionality. As such, there will be
516
+ no rebalance operation triggered when group membership or cluster
517
+ and topic metadata change.
518
+ """
519
+ if not partitions:
520
+ self.unsubscribe()
521
+ else:
522
+ # make sure the offsets of topic partitions the consumer is unsubscribing from
523
+ # are committed since there will be no following rebalance
524
+ self._coordinator.maybe_auto_commit_offsets_now()
525
+ self._subscription.assign_from_user(partitions)
526
+ self._cluster.set_topics([tp.topic for tp in partitions])
527
+ log.debug("Subscribed to partition(s): %s", partitions)
528
+
529
+ def assignment(self):
530
+ """Get the TopicPartitions currently assigned to this consumer.
531
+
532
+ If partitions were directly assigned using
533
+ :meth:`~kafka.KafkaConsumer.assign`, then this will simply return the
534
+ same partitions that were previously assigned. If topics were
535
+ subscribed using :meth:`~kafka.KafkaConsumer.subscribe`, then this will
536
+ give the set of topic partitions currently assigned to the consumer
537
+ (which may be None if the assignment hasn't happened yet, or if the
538
+ partitions are in the process of being reassigned).
539
+
540
+ Returns:
541
+ set: {TopicPartition, ...}
542
+ """
543
+ return self._subscription.assigned_partitions()
544
+
545
+ def __enter__(self):
546
+ return self
547
+
548
+ def __exit__(self, exc_type, exc_val, exc_tb):
549
+ # Skip autocommit when the `with` block exited via exception: we
550
+ # can't know whether the in-flight record was successfully
551
+ # processed, so committing its offset would risk silently dropping
552
+ # an unprocessed message on next start. Clean exits commit normally.
553
+ self.close(autocommit=exc_type is None)
554
+
555
+ def close(self, autocommit=True, timeout_ms=None):
556
+ """Close the consumer, attempting any needed cleanup within a bounded
557
+ wall-clock budget.
558
+
559
+ Keyword Arguments:
560
+ autocommit (bool): If auto-commit is configured for this consumer,
561
+ this optional flag causes the consumer to attempt to commit any
562
+ pending consumed offsets prior to close. Default: True
563
+ timeout_ms (num, optional): Milliseconds to wait for auto-commit
564
+ and other in-flight close work. ``None`` falls back to
565
+ ``request_timeout_ms`` so close() can never hang indefinitely
566
+ even if the coordinator is unreachable. Default: None
567
+ """
568
+ if self._closed:
569
+ return
570
+ log.debug("Closing the KafkaConsumer.")
571
+ self._closed = True
572
+ # Cap the auto-commit retry loop -- ``_commit_offsets_sync_async``
573
+ # retries forever when given ``None`` (Timer(None).expired is always
574
+ # False), so a coordinator that's down or stuck would otherwise hang
575
+ # close() until process exit.
576
+ if timeout_ms is None:
577
+ timeout_ms = self.config['request_timeout_ms']
578
+ self._coordinator.close(autocommit=autocommit, timeout_ms=timeout_ms)
579
+ if self._metrics:
580
+ self._metrics.close()
581
+ self._client.close()
582
+ try:
583
+ self.config['key_deserializer'].close()
584
+ except AttributeError:
585
+ pass
586
+ try:
587
+ self.config['value_deserializer'].close()
588
+ except AttributeError:
589
+ pass
590
+ log.debug("The KafkaConsumer has closed.")
591
+
592
+ def commit_async(self, offsets=None, callback=None):
593
+ """Commit offsets to kafka asynchronously, optionally firing callback.
594
+
595
+ This commits offsets only to Kafka. The offsets committed using this API
596
+ will be used on the first fetch after every rebalance and also on
597
+ startup. As such, if you need to store offsets in anything other than
598
+ Kafka, this API should not be used. To avoid re-processing the last
599
+ message read if a consumer is restarted, the committed offset should be
600
+ the next message your application should consume, i.e.: last_offset + 1.
601
+
602
+ This is an asynchronous call and will not block. Any errors encountered
603
+ are either passed to the callback (if provided) or discarded.
604
+
605
+ Arguments:
606
+ offsets (dict, optional): {TopicPartition: OffsetAndMetadata} dict
607
+ to commit with the configured group_id. Defaults to currently
608
+ consumed offsets for all subscribed partitions.
609
+ callback (callable, optional): Called as callback(offsets, response)
610
+ with response as either an Exception or an OffsetCommitResponse
611
+ struct. This callback can be used to trigger custom actions when
612
+ a commit request completes.
613
+
614
+ Raises:
615
+ IncompatibleBrokerVersion: if broker version < 0.8.1
616
+ IllegalStateError: if group_id is None
617
+
618
+ Returns:
619
+ kafka.future.Future
620
+ """
621
+ if self.config['api_version'] < (0, 8, 1):
622
+ raise Errors.IncompatibleBrokerVersion('Requires >= Kafka 0.8.1')
623
+ if self.config['group_id'] is None:
624
+ raise Errors.IllegalStateError('Requires group_id')
625
+ if offsets is None:
626
+ offsets = self._subscription.all_consumed_offsets()
627
+ log.debug("Committing offsets: %s", offsets)
628
+ future = self._coordinator.commit_offsets_async(
629
+ offsets, callback=callback)
630
+ return future
631
+
632
+ def commit(self, offsets=None, timeout_ms=None):
633
+ """Commit offsets to kafka, blocking until success or error.
634
+
635
+ This commits offsets only to Kafka. The offsets committed using this API
636
+ will be used on the first fetch after every rebalance and also on
637
+ startup. As such, if you need to store offsets in anything other than
638
+ Kafka, this API should not be used. To avoid re-processing the last
639
+ message read if a consumer is restarted, the committed offset should be
640
+ the next message your application should consume, i.e.: last_offset + 1.
641
+
642
+ Blocks until either the commit succeeds or an unrecoverable error is
643
+ encountered (in which case it is thrown to the caller).
644
+
645
+ Currently only supports kafka-topic offset storage (not zookeeper).
646
+
647
+ Arguments:
648
+ offsets (dict, optional): {TopicPartition: OffsetAndMetadata} dict
649
+ to commit with the configured group_id. Defaults to currently
650
+ consumed offsets for all subscribed partitions.
651
+
652
+ Raises:
653
+ IncompatibleBrokerVersion: if broker version < 0.8.1
654
+ IllegalStateError: if group_id is None
655
+ """
656
+ if self.config['api_version'] < (0, 8, 1):
657
+ raise Errors.IncompatibleBrokerVersion('Requires >= Kafka 0.8.1')
658
+ if self.config['group_id'] is None:
659
+ raise Errors.IllegalStateError('Requires group_id')
660
+ if offsets is None:
661
+ offsets = self._subscription.all_consumed_offsets()
662
+ self._coordinator.commit_offsets_sync(offsets, timeout_ms=timeout_ms)
663
+
664
+ def group_metadata(self):
665
+ """Return a snapshot of this consumer's group membership (KIP-447).
666
+
667
+ Pass the result to KafkaProducer.send_offsets_to_transaction() so the
668
+ broker can fence stale instances of this consumer when committing
669
+ offsets inside a transaction. The snapshot is always safe to call:
670
+ if no group_id is configured (manual assignment) the returned
671
+ ConsumerGroupMetadata has group_id=None.
672
+
673
+ Returns:
674
+ ConsumerGroupMetadata
675
+ """
676
+ if self.config['group_id'] is None:
677
+ return ConsumerGroupMetadata(group_id=None)
678
+ return self._coordinator.group_metadata()
679
+
680
+ def committed(self, partition, metadata=False, timeout_ms=None):
681
+ """Get the last committed offset for the given partition.
682
+
683
+ This offset will be used as the position for the consumer
684
+ in the event of a failure.
685
+
686
+ This call will block to do a remote call to get the latest committed
687
+ offsets from the server.
688
+
689
+ Arguments:
690
+ partition (TopicPartition): The partition to check.
691
+ metadata (bool, optional): If True, return OffsetAndMetadata struct
692
+ instead of offset int. Default: False.
693
+
694
+ Returns:
695
+ The last committed offset (int or OffsetAndMetadata), or None if there was no prior commit.
696
+
697
+ Raises:
698
+ IncompatibleBrokerVersion: if broker version < 0.8.1
699
+ IllegalStateError: if group_id is None
700
+ TypeError: if partition is not TopicPartition
701
+ KafkaTimeoutError: if timeout_ms provided
702
+ BrokerResponseError: if OffsetFetchRequest raises an error.
703
+ """
704
+ if self.config['api_version'] < (0, 8, 1):
705
+ raise Errors.IncompatibleBrokerVersion('Requires >= Kafka 0.8.1')
706
+ if self.config['group_id'] is None:
707
+ raise Errors.IllegalStateError('Requires group_id')
708
+ if not isinstance(partition, TopicPartition):
709
+ raise TypeError('partition must be a TopicPartition namedtuple')
710
+ committed = self._coordinator.fetch_committed_offsets([partition], timeout_ms=timeout_ms)
711
+ if partition not in committed:
712
+ return None
713
+ return committed[partition] if metadata else committed[partition].offset
714
+
715
+ def _fetch_all_topic_metadata(self):
716
+ """A blocking call that fetches topic metadata for all topics in the
717
+ cluster that the user is authorized to view.
718
+ """
719
+ if self._cluster.metadata_refresh_in_progress:
720
+ future = self._cluster.request_update()
721
+ self._net.run(self._manager.wait_for, future, None)
722
+ stash = self._cluster.need_all_topic_metadata
723
+ self._cluster.need_all_topic_metadata = True
724
+ future = self._cluster.request_update()
725
+ self._net.run(self._manager.wait_for, future, None)
726
+ self._cluster.need_all_topic_metadata = stash
727
+
728
+ def topics(self):
729
+ """Get all topics the user is authorized to view.
730
+ This will always issue a remote call to the cluster to fetch the latest
731
+ information.
732
+
733
+ Returns:
734
+ set: topics
735
+ """
736
+ self._fetch_all_topic_metadata()
737
+ return self._cluster.topics()
738
+
739
+ def partitions_for_topic(self, topic):
740
+ """This method first checks the local metadata cache for information
741
+ about the topic. If the topic is not found (either because the topic
742
+ does not exist, the user is not authorized to view the topic, or the
743
+ metadata cache is not populated), then it will issue a metadata update
744
+ call to the cluster.
745
+
746
+ Arguments:
747
+ topic (str): Topic to check.
748
+
749
+ Returns:
750
+ set: Partition ids
751
+ """
752
+ partitions = self._cluster.partitions_for_topic(topic)
753
+ if partitions is None:
754
+ self._fetch_all_topic_metadata()
755
+ partitions = self._cluster.partitions_for_topic(topic)
756
+ return partitions or set()
757
+
758
+ def poll(self, timeout_ms=0, max_records=None, update_offsets=True):
759
+ """Fetch data from assigned topics / partitions.
760
+
761
+ Records are fetched and returned in batches by topic-partition.
762
+ On each poll, consumer will try to use the last consumed offset as the
763
+ starting offset and fetch sequentially. The last consumed offset can be
764
+ manually set through :meth:`~kafka.KafkaConsumer.seek` or automatically
765
+ set as the last committed offset for the subscribed list of partitions.
766
+
767
+ Incompatible with iterator interface -- use one or the other, not both.
768
+
769
+ Arguments:
770
+ timeout_ms (int, optional): Milliseconds spent waiting in poll if
771
+ data is not available in the buffer. If 0, returns immediately
772
+ with any records that are available currently in the buffer,
773
+ else returns empty. Must not be negative. Default: 0
774
+ max_records (int, optional): The maximum number of records returned
775
+ in a single call to :meth:`~kafka.KafkaConsumer.poll`.
776
+ Default: Inherit value from max_poll_records.
777
+
778
+ Raises:
779
+ ValueError: if timeout is < 0 or max_records <= 0.
780
+ TypeError: if max_records is not int.
781
+ IllegalStateError: if consumer already closed.
782
+
783
+ Returns:
784
+ dict[TopicPartition, list[ConsumerRecord]]: records since the last
785
+ fetch for the subscribed list of topics and partitions.
786
+ """
787
+ # Note: update_offsets is an internal-use only argument. It is used to
788
+ # support the python iterator interface, and which wraps consumer.poll()
789
+ # and requires that the partition offsets tracked by the fetcher are not
790
+ # updated until the iterator returns each record to the user. As such,
791
+ # the argument is not documented and should not be relied on by library
792
+ # users to not break in the future.
793
+ if timeout_ms < 0:
794
+ raise ValueError('Timeout must not be negative')
795
+ if max_records is None:
796
+ max_records = self.config['max_poll_records']
797
+ if not isinstance(max_records, int):
798
+ raise TypeError('max_records must be an integer')
799
+ if max_records <= 0:
800
+ raise ValueError('max_records must be positive')
801
+ if self._closed:
802
+ raise Errors.IllegalStateError('KafkaConsumer is closed')
803
+
804
+ # Poll for new data until the timeout expires
805
+ timer = Timer(timeout_ms)
806
+ while not self._closed:
807
+ records = self._poll_once(timer, max_records, update_offsets=update_offsets)
808
+ if records:
809
+ return records
810
+ elif timer.expired:
811
+ break
812
+ return {}
813
+
814
+ def _poll_once(self, timer, max_records, update_offsets=True):
815
+ """Do one round of polling. In addition to checking for new data, this does
816
+ any needed heart-beating, auto-commits, and offset updates.
817
+
818
+ Arguments:
819
+ timer (Timer): The maximum time in milliseconds to block.
820
+
821
+ Returns:
822
+ dict: Map of topic to list of records (may be empty).
823
+ """
824
+ if not self._coordinator.poll(timeout_ms=timer.timeout_ms):
825
+ log.debug('poll: timeout during coordinator.poll(); returning early')
826
+ return {}
827
+
828
+ self._refresh_committed_offsets(timeout_ms=timer.timeout_ms)
829
+ # Fire-and-forget: kicks ListOffsets reset for any remaining partitions.
830
+ # _reset_offsets_async self-drives metadata refresh + retry-backoff
831
+ # within request_timeout_ms.
832
+ self._fetcher.reset_offsets_if_needed()
833
+ # KIP-320: mark any positions whose cluster leader epoch has advanced
834
+ # beyond the position's epoch, then drive OffsetForLeaderEpoch
835
+ # validation in the background. Truncation surfaces on the next call.
836
+ self._fetcher.maybe_validate_positions()
837
+ self._fetcher.validate_offsets_if_needed()
838
+
839
+ # Cap the fetch wait by the heartbeat deadline so we don't block past
840
+ # when the coordinator wants to send the next heartbeat.
841
+ poll_timeout_ms = timer.timeout_ms
842
+ if self.config['group_id'] is not None:
843
+ poll_timeout_ms = min(poll_timeout_ms, self._coordinator.time_to_next_poll() * 1000)
844
+
845
+ records, idle = self._fetcher.fetch_records(
846
+ max_records, update_offsets=update_offsets, timeout_ms=poll_timeout_ms)
847
+ if not records and idle and poll_timeout_ms > 0:
848
+ # Nothing fetchable and nothing in flight (no assignment, all
849
+ # paused, or no resolvable positions). Sleep up to poll_timeout_ms
850
+ # to avoid busy-looping; poll_timeout_ms is already capped by the
851
+ # coordinator's next-action deadline.
852
+ poll_timeout_ms = min(poll_timeout_ms, self.config['retry_backoff_ms'])
853
+ time.sleep(poll_timeout_ms / 1000)
854
+ return records
855
+
856
+ def position(self, partition, timeout_ms=None):
857
+ """Get the offset of the next record that will be fetched
858
+
859
+ Arguments:
860
+ partition (TopicPartition): Partition to check
861
+
862
+ Raises:
863
+ TypeError: if partition is not a TopicPartition.
864
+ IllegalStateError: if partition is not assigned.
865
+
866
+ Returns:
867
+ int: Offset or None
868
+ """
869
+ if not isinstance(partition, TopicPartition):
870
+ raise TypeError('partition must be a TopicPartition namedtuple')
871
+ if not self._subscription.is_assigned(partition):
872
+ raise Errors.IllegalStateError('Partition is not assigned')
873
+
874
+ timer = Timer(timeout_ms)
875
+ # Phase 1: blocking refresh of committed offsets (network round-trip
876
+ # to the coordinator) and CPU-only marking of remaining partitions
877
+ # for reset by the configured policy.
878
+ self._refresh_committed_offsets(timeout_ms=timer.timeout_ms)
879
+ # Phase 2: ListOffsets reset is async; await its in-flight Task. The
880
+ # task's own loop is bounded by timer.timeout_ms so it doesn't run
881
+ # past the user's deadline.
882
+ reset_task = self._fetcher.reset_offsets_if_needed(timeout_ms=timer.timeout_ms)
883
+ if reset_task is not None and not timer.expired:
884
+ try:
885
+ self._net.run(self._manager.wait_for, reset_task, timer.timeout_ms)
886
+ except Errors.KafkaTimeoutError:
887
+ pass
888
+ # Phase 3 (KIP-320): mark any positions whose cluster leader epoch
889
+ # has advanced beyond the position's epoch and await the validation
890
+ # RPC. Surfaces LogTruncationError to the caller if truncation is
891
+ # detected (and auto_offset_reset is NONE).
892
+ self._fetcher.maybe_validate_positions()
893
+ validation_task = self._fetcher.validate_offsets_if_needed(
894
+ timeout_ms=timer.timeout_ms)
895
+ if validation_task is not None and not timer.expired:
896
+ try:
897
+ self._net.run(self._manager.wait_for, validation_task, timer.timeout_ms)
898
+ except Errors.KafkaTimeoutError:
899
+ pass
900
+ position = self._subscription.assignment[partition].position
901
+ if position is not None:
902
+ return position.offset
903
+
904
+ def highwater(self, partition):
905
+ """Last known highwater offset for a partition.
906
+
907
+ A highwater offset is the offset that will be assigned to the next
908
+ message that is produced. It may be useful for calculating lag, by
909
+ comparing with the reported position. Note that both position and
910
+ highwater refer to the *next* offset -- i.e., highwater offset is
911
+ one greater than the newest available message.
912
+
913
+ Highwater offsets are returned in FetchResponse messages, so will
914
+ not be available if no FetchRequests have been sent for this partition
915
+ yet.
916
+
917
+ Arguments:
918
+ partition (TopicPartition): Partition to check
919
+
920
+ Raises:
921
+ TypeError: if partition is not a TopicPartition.
922
+ IllegalStateError: if partition is not assigned.
923
+
924
+ Returns:
925
+ int or None: Offset if available
926
+ """
927
+ if not isinstance(partition, TopicPartition):
928
+ raise TypeError('partition must be a TopicPartition namedtuple')
929
+ if not self._subscription.is_assigned(partition):
930
+ raise Errors.IllegalStateError('Partition is not assigned')
931
+ return self._subscription.assignment[partition].highwater
932
+
933
+ def pause(self, *partitions):
934
+ """Suspend fetching from the requested partitions.
935
+
936
+ Future calls to :meth:`~kafka.KafkaConsumer.poll` will not return any
937
+ records from these partitions until they have been resumed using
938
+ :meth:`~kafka.KafkaConsumer.resume`.
939
+
940
+ Note: This method does not affect partition subscription. In particular,
941
+ it does not cause a group rebalance when automatic assignment is used.
942
+
943
+ Arguments:
944
+ *partitions (TopicPartition): Partitions to pause.
945
+ """
946
+ if not all([isinstance(p, TopicPartition) for p in partitions]):
947
+ raise TypeError('partitions must be TopicPartition namedtuples')
948
+ for partition in partitions:
949
+ log.debug("Pausing partition %s", partition)
950
+ self._subscription.pause(partition)
951
+ # Because the iterator checks is_fetchable() on each iteration
952
+ # we expect pauses to get handled automatically and therefore
953
+ # we do not need to reset the full iterator (forcing a full refetch)
954
+
955
+ def paused(self):
956
+ """Get the partitions that were previously paused using
957
+ :meth:`~kafka.KafkaConsumer.pause`.
958
+
959
+ Returns:
960
+ set: {partition (TopicPartition), ...}
961
+ """
962
+ return self._subscription.paused_partitions()
963
+
964
+ def resume(self, *partitions):
965
+ """Resume fetching from the specified (paused) partitions.
966
+
967
+ Arguments:
968
+ *partitions (TopicPartition): Partitions to resume.
969
+ """
970
+ if not all([isinstance(p, TopicPartition) for p in partitions]):
971
+ raise TypeError('partitions must be TopicPartition namedtuples')
972
+ for partition in partitions:
973
+ log.debug("Resuming partition %s", partition)
974
+ self._subscription.resume(partition)
975
+
976
+ def seek(self, partition, offset):
977
+ """Manually specify the fetch offset for a TopicPartition.
978
+
979
+ Overrides the fetch offsets that the consumer will use on the next
980
+ :meth:`~kafka.KafkaConsumer.poll`. If this API is invoked for the same
981
+ partition more than once, the latest offset will be used on the next
982
+ :meth:`~kafka.KafkaConsumer.poll`.
983
+
984
+ Note: You may lose data if this API is arbitrarily used in the middle of
985
+ consumption to reset the fetch offsets.
986
+
987
+ Arguments:
988
+ partition (TopicPartition): Partition for seek operation
989
+ offset (int): Message offset in partition
990
+
991
+ Raises:
992
+ ValueError: If offset is not an int >= 0; or if partition is not
993
+ currently assigned.
994
+ """
995
+ if not isinstance(partition, TopicPartition):
996
+ raise TypeError('partition must be a TopicPartition namedtuple')
997
+ if not isinstance(offset, int) or offset < 0:
998
+ raise ValueError('Offset must be int >= 0')
999
+ if partition not in self._subscription.assigned_partitions():
1000
+ raise ValueError('Unassigned partition')
1001
+ log.debug("Seeking to offset %s for partition %s", offset, partition)
1002
+ self._subscription.assignment[partition].seek(offset)
1003
+ self._iterator = None
1004
+
1005
+ def seek_to_beginning(self, *partitions):
1006
+ """Seek to the oldest available offset for partitions.
1007
+
1008
+ Arguments:
1009
+ *partitions: Optionally provide specific TopicPartitions, otherwise
1010
+ default to all assigned partitions.
1011
+
1012
+ Raises:
1013
+ ValueError: If any partition is not currently assigned, or if
1014
+ no partitions are assigned.
1015
+ """
1016
+ if not all([isinstance(p, TopicPartition) for p in partitions]):
1017
+ raise TypeError('partitions must be TopicPartition namedtuples')
1018
+ if not partitions:
1019
+ partitions = self._subscription.assigned_partitions()
1020
+ if not partitions:
1021
+ raise ValueError('No partitions are currently assigned')
1022
+ else:
1023
+ for p in partitions:
1024
+ if p not in self._subscription.assigned_partitions():
1025
+ raise ValueError('Unassigned partition: %s' % (p,))
1026
+
1027
+ for tp in partitions:
1028
+ log.debug("Seeking to beginning of partition %s", tp)
1029
+ self._subscription.request_offset_reset(tp, OffsetResetStrategy.EARLIEST)
1030
+ self._iterator = None
1031
+
1032
+ def seek_to_end(self, *partitions):
1033
+ """Seek to the most recent available offset for partitions.
1034
+
1035
+ Arguments:
1036
+ *partitions: Optionally provide specific TopicPartitions, otherwise
1037
+ default to all assigned partitions.
1038
+
1039
+ Raises:
1040
+ ValueError: If any partition is not currently assigned, or if
1041
+ no partitions are assigned.
1042
+ """
1043
+ if not all([isinstance(p, TopicPartition) for p in partitions]):
1044
+ raise TypeError('partitions must be TopicPartition namedtuples')
1045
+ if not partitions:
1046
+ partitions = self._subscription.assigned_partitions()
1047
+ if not partitions:
1048
+ raise ValueError('No partitions are currently assigned')
1049
+ else:
1050
+ for p in partitions:
1051
+ if p not in self._subscription.assigned_partitions():
1052
+ raise ValueError('Unassigned partition: %s' % (p,))
1053
+
1054
+ for tp in partitions:
1055
+ log.debug("Seeking to end of partition %s", tp)
1056
+ self._subscription.request_offset_reset(tp, OffsetResetStrategy.LATEST)
1057
+ self._iterator = None
1058
+
1059
+ def subscribe(self, topics=(), pattern=None, listener=None):
1060
+ """Subscribe to a list of topics, or a topic regex pattern.
1061
+
1062
+ Partitions will be dynamically assigned via a group coordinator.
1063
+ Topic subscriptions are not incremental: this list will replace the
1064
+ current assignment (if there is one).
1065
+
1066
+ This method is incompatible with :meth:`~kafka.KafkaConsumer.assign`.
1067
+
1068
+ Arguments:
1069
+ topics (list): List of topics for subscription.
1070
+ pattern (str): Pattern to match available topics. You must provide
1071
+ either topics or pattern, but not both.
1072
+ listener (ConsumerRebalanceListener): Optionally include listener
1073
+ callback, which will be called before and after each rebalance
1074
+ operation.
1075
+
1076
+ As part of group management, the consumer will keep track of the
1077
+ list of consumers that belong to a particular group and will
1078
+ trigger a rebalance operation if one of the following events
1079
+ trigger:
1080
+
1081
+ * Number of partitions change for any of the subscribed topics
1082
+ * Topic is created or deleted
1083
+ * An existing member of the consumer group dies
1084
+ * A new member is added to the consumer group
1085
+
1086
+ When any of these events are triggered, the provided listener
1087
+ will be invoked first to indicate that the consumer's assignment
1088
+ has been revoked, and then again when the new assignment has
1089
+ been received. Note that this listener will immediately override
1090
+ any listener set in a previous call to subscribe. It is
1091
+ guaranteed, however, that the partitions revoked/assigned
1092
+ through this interface are from topics subscribed in this call.
1093
+
1094
+ Raises:
1095
+ IllegalStateError: If called after previously calling
1096
+ :meth:`~kafka.KafkaConsumer.assign`.
1097
+ ValueError: If neither topics or pattern is provided.
1098
+ TypeError: If listener is not a ConsumerRebalanceListener.
1099
+ """
1100
+ # SubscriptionState handles error checking
1101
+ self._subscription.subscribe(topics=topics,
1102
+ pattern=pattern,
1103
+ listener=listener)
1104
+
1105
+ # Regex will need all topic metadata
1106
+ if pattern is not None:
1107
+ self._cluster.need_all_topic_metadata = True
1108
+ self._cluster.set_topics([])
1109
+ self._cluster.request_update()
1110
+ log.debug("Subscribed to topic pattern: %s", pattern)
1111
+ else:
1112
+ self._cluster.need_all_topic_metadata = False
1113
+ self._cluster.set_topics(self._subscription.group_subscription())
1114
+ log.debug("Subscribed to topic(s): %s", topics)
1115
+
1116
+ def subscription(self):
1117
+ """Get the current topic subscription.
1118
+
1119
+ Returns:
1120
+ set: {topic, ...}
1121
+ """
1122
+ if self._subscription.subscription is None:
1123
+ return None
1124
+ return self._subscription.subscription.copy()
1125
+
1126
+ def unsubscribe(self):
1127
+ """Unsubscribe from all topics and clear all assigned partitions."""
1128
+ # make sure the offsets of topic partitions the consumer is unsubscribing from
1129
+ # are committed since there will be no following rebalance
1130
+ self._coordinator.maybe_auto_commit_offsets_now()
1131
+ self._subscription.unsubscribe()
1132
+ if self.config['api_version'] >= (0, 9):
1133
+ self._coordinator.maybe_leave_group()
1134
+ self._cluster.need_all_topic_metadata = False
1135
+ self._cluster.set_topics([])
1136
+ log.debug("Unsubscribed all topics or patterns and assigned partitions")
1137
+ self._iterator = None
1138
+
1139
+ def metrics(self, raw=False):
1140
+ """Get metrics on consumer performance.
1141
+
1142
+ This is ported from the Java Consumer, for details see:
1143
+ https://kafka.apache.org/documentation/#consumer_monitoring
1144
+
1145
+ Warning:
1146
+ This is an unstable interface. It may change in future
1147
+ releases without warning.
1148
+ """
1149
+ if not self._metrics:
1150
+ return
1151
+ if raw:
1152
+ return self._metrics.metrics.copy()
1153
+
1154
+ metrics = {}
1155
+ for k, v in self._metrics.metrics.copy().items():
1156
+ if k.group not in metrics:
1157
+ metrics[k.group] = {}
1158
+ if k.name not in metrics[k.group]:
1159
+ metrics[k.group][k.name] = {}
1160
+ metrics[k.group][k.name] = v.value()
1161
+ return metrics
1162
+
1163
+ def offsets_for_times(self, timestamps, timeout_ms=None):
1164
+ """Look up the offsets for the given partitions by timestamp. The
1165
+ returned offset for each partition is the earliest offset whose
1166
+ timestamp is greater than or equal to the given timestamp in the
1167
+ corresponding partition.
1168
+
1169
+ This is a blocking call. The consumer does not have to be assigned the
1170
+ partitions.
1171
+
1172
+ If the message format version in a partition is before 0.10.0, i.e.
1173
+ the messages do not have timestamps, ``None`` will be returned for that
1174
+ partition. ``None`` will also be returned for the partition if there
1175
+ are no messages in it.
1176
+
1177
+ Note: This method may block indefinitely if the partition does not exist
1178
+ and no timeout_ms provided.
1179
+
1180
+ Arguments:
1181
+ timestamps (dict): ``{TopicPartition: int}`` mapping from partition
1182
+ to the timestamp to look up. Unit should be milliseconds since
1183
+ beginning of the epoch (midnight Jan 1, 1970 (UTC))
1184
+ timeout_ms (int, optional): Milliseconds to block fetching offsets.
1185
+
1186
+ Returns:
1187
+ ``{TopicPartition: OffsetAndTimestamp}``: mapping from partition
1188
+ to the offset and timestamp of the first message with timestamp
1189
+ greater than or equal to the target timestamp.
1190
+
1191
+ Raises:
1192
+ ValueError: If the target timestamp is negative
1193
+ UnsupportedVersionError: If the broker does not support looking
1194
+ up the offsets by timestamp.
1195
+ KafkaTimeoutError: If fetch failed in request_timeout_ms
1196
+ """
1197
+ timeout_ms = self.config['request_timeout_ms'] if timeout_ms is None else timeout_ms
1198
+ for tp, ts in timestamps.items():
1199
+ timestamps[tp] = int(ts)
1200
+ if ts < 0:
1201
+ raise ValueError(
1202
+ "The target time for partition {} is {}. The target time "
1203
+ "cannot be negative.".format(tp, ts))
1204
+ return self._fetcher.offsets_by_times(timestamps, timeout_ms)
1205
+
1206
+ def beginning_offsets(self, partitions, timeout_ms=None):
1207
+ """Get the first offset for the given partitions.
1208
+
1209
+ This method does not change the current consumer position of the
1210
+ partitions.
1211
+
1212
+ Note: This method may block indefinitely if the partition does not exist
1213
+ and no timeout_ms provided.
1214
+
1215
+ Arguments:
1216
+ partitions (list): List of TopicPartition instances to fetch
1217
+ offsets for.
1218
+ timeout_ms (int, optional): Milliseconds to block fetching offsets.
1219
+
1220
+ Returns:
1221
+ ``{TopicPartition: int}``: The earliest available offsets for the
1222
+ given partitions.
1223
+
1224
+ Raises:
1225
+ UnsupportedVersionError: If the broker does not support looking
1226
+ up the offsets by timestamp.
1227
+ KafkaTimeoutError: If fetch failed in timeout_ms.
1228
+ """
1229
+ timeout_ms = self.config['request_timeout_ms'] if timeout_ms is None else timeout_ms
1230
+ offsets = self._fetcher.beginning_offsets(partitions, timeout_ms)
1231
+ return offsets
1232
+
1233
+ def end_offsets(self, partitions, timeout_ms=None):
1234
+ """Get the last offset for the given partitions. The last offset of a
1235
+ partition is the offset of the upcoming message, i.e. the offset of the
1236
+ last available message + 1.
1237
+
1238
+ This method does not change the current consumer position of the
1239
+ partitions.
1240
+
1241
+ Note: This method may block indefinitely if the partition does not exist
1242
+ and no timeout_ms provided.
1243
+
1244
+ Arguments:
1245
+ partitions (list): List of TopicPartition instances to fetch
1246
+ offsets for.
1247
+ timeout_ms (int, optional): Milliseconds to block fetching offsets.
1248
+
1249
+ Returns:
1250
+ ``{TopicPartition: int}``: The end offsets for the given partitions.
1251
+
1252
+ Raises:
1253
+ UnsupportedVersionError: If the broker does not support looking
1254
+ up the offsets by timestamp.
1255
+ KafkaTimeoutError: If fetch failed in timeout_ms
1256
+ """
1257
+ timeout_ms = self.config['request_timeout_ms'] if timeout_ms is None else timeout_ms
1258
+ offsets = self._fetcher.end_offsets(partitions, timeout_ms)
1259
+ return offsets
1260
+
1261
+ def _refresh_committed_offsets(self, timeout_ms=None):
1262
+ """Refresh committed offsets for partitions still needing a position
1263
+ and mark any remaining partitions for reset by the configured policy.
1264
+
1265
+ This is the synchronous half of position resolution: a network
1266
+ round-trip to the coordinator (timer-bounded), followed by
1267
+ ``reset_missing_positions`` which is CPU-only. Partitions whose
1268
+ position can be filled from a committed offset are filled here;
1269
+ partitions without a committed offset are flagged for reset.
1270
+
1271
+ Callers that also want the reset to complete should follow up with
1272
+ ``self._fetcher.reset_offsets_if_needed()`` and either await the
1273
+ returned Task (e.g. via ``manager.wait_for``) or fire-and-forget.
1274
+
1275
+ Arguments:
1276
+ timeout_ms (int, optional): Milliseconds to block refreshing
1277
+ committed offsets.
1278
+
1279
+ Returns:
1280
+ bool: True if all assigned partitions now have a fetch position
1281
+ (no further reset needed); False if a reset is still
1282
+ pending or the committed-offset refresh timed out.
1283
+
1284
+ Raises:
1285
+ NoOffsetForPartitionError: If no offset is stored for a given
1286
+ partition and no offset reset policy is defined.
1287
+ """
1288
+ if self._subscription.has_all_fetch_positions():
1289
+ return True
1290
+
1291
+ if (self.config['api_version'] >= (0, 8, 1) and
1292
+ self.config['group_id'] is not None):
1293
+ # If there are any partitions which do not have a valid position and are not
1294
+ # awaiting reset, then we need to fetch committed offsets. We will only do a
1295
+ # coordinator lookup if there are partitions which have missing positions, so
1296
+ # a consumer with manually assigned partitions can avoid a coordinator dependence
1297
+ # by always ensuring that assigned partitions have an initial position.
1298
+ if not self._coordinator.refresh_committed_offsets_if_needed(timeout_ms=timeout_ms):
1299
+ return False
1300
+
1301
+ # If there are partitions still needing a position and a reset policy is defined,
1302
+ # mark them for reset using the default policy. If no reset strategy is defined and
1303
+ # there are partitions with a missing position, then we will raise an exception.
1304
+ self._subscription.reset_missing_positions()
1305
+ return self._subscription.has_all_fetch_positions()
1306
+
1307
+ def _message_generator_v2(self):
1308
+ timeout_ms = 1000 * max(0, self._consumer_timeout - time.monotonic())
1309
+ record_map = self.poll(timeout_ms=timeout_ms, update_offsets=False)
1310
+ for tp, records in record_map.items():
1311
+ # Generators are stateful, and it is possible that the tp / records
1312
+ # here may become stale during iteration -- i.e., we seek to a
1313
+ # different offset, pause consumption, or lose assignment.
1314
+ for record in records:
1315
+ # is_fetchable(tp) should handle assignment changes and offset
1316
+ # resets; for all other changes (e.g., seeks) we'll rely on the
1317
+ # outer function destroying the existing iterator/generator
1318
+ # via self._iterator = None
1319
+ if not self._subscription.is_fetchable(tp):
1320
+ log.debug("Not returning fetched records for partition %s"
1321
+ " since it is no longer fetchable", tp)
1322
+ break
1323
+ self._subscription.assignment[tp].position = OffsetAndMetadata(
1324
+ record.offset + 1, '', record.leader_epoch)
1325
+ yield record
1326
+
1327
+ def __iter__(self): # pylint: disable=non-iterator-returned
1328
+ return self
1329
+
1330
+ def __next__(self):
1331
+ if self._closed:
1332
+ raise StopIteration('KafkaConsumer closed')
1333
+ self._set_consumer_timeout()
1334
+ while time.monotonic() < self._consumer_timeout:
1335
+ if not self._iterator:
1336
+ self._iterator = self._message_generator_v2()
1337
+ try:
1338
+ return next(self._iterator)
1339
+ except StopIteration:
1340
+ self._iterator = None
1341
+ raise StopIteration()
1342
+
1343
+ def _set_consumer_timeout(self):
1344
+ # consumer_timeout_ms can be used to stop iteration early
1345
+ if self.config['consumer_timeout_ms'] >= 0:
1346
+ self._consumer_timeout = time.monotonic() + (
1347
+ self.config['consumer_timeout_ms'] / 1000.0)