hc99 commited on
Commit
83d24b2
·
verified ·
1 Parent(s): 73cc8d2

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. testbed/dpkp__kafka-python/.covrc +3 -0
  2. testbed/dpkp__kafka-python/.gitignore +17 -0
  3. testbed/dpkp__kafka-python/.travis.yml +46 -0
  4. testbed/dpkp__kafka-python/AUTHORS.md +51 -0
  5. testbed/dpkp__kafka-python/CHANGES.md +1204 -0
  6. testbed/dpkp__kafka-python/LICENSE +202 -0
  7. testbed/dpkp__kafka-python/MANIFEST.in +5 -0
  8. testbed/dpkp__kafka-python/Makefile +59 -0
  9. testbed/dpkp__kafka-python/README.rst +172 -0
  10. testbed/dpkp__kafka-python/benchmarks/README.md +4 -0
  11. testbed/dpkp__kafka-python/benchmarks/consumer_performance.py +181 -0
  12. testbed/dpkp__kafka-python/benchmarks/load_example.py +66 -0
  13. testbed/dpkp__kafka-python/benchmarks/producer_performance.py +160 -0
  14. testbed/dpkp__kafka-python/benchmarks/record_batch_compose.py +77 -0
  15. testbed/dpkp__kafka-python/benchmarks/record_batch_read.py +82 -0
  16. testbed/dpkp__kafka-python/benchmarks/varint_speed.py +443 -0
  17. testbed/dpkp__kafka-python/build_integration.sh +73 -0
  18. testbed/dpkp__kafka-python/example.py +82 -0
  19. testbed/dpkp__kafka-python/kafka/__init__.py +34 -0
  20. testbed/dpkp__kafka-python/kafka/admin/__init__.py +14 -0
  21. testbed/dpkp__kafka-python/kafka/admin/acl_resource.py +244 -0
  22. testbed/dpkp__kafka-python/kafka/admin/client.py +1342 -0
  23. testbed/dpkp__kafka-python/kafka/admin/config_resource.py +36 -0
  24. testbed/dpkp__kafka-python/kafka/admin/new_partitions.py +19 -0
  25. testbed/dpkp__kafka-python/kafka/admin/new_topic.py +34 -0
  26. testbed/dpkp__kafka-python/kafka/client_async.py +1077 -0
  27. testbed/dpkp__kafka-python/kafka/cluster.py +397 -0
  28. testbed/dpkp__kafka-python/kafka/codec.py +326 -0
  29. testbed/dpkp__kafka-python/kafka/conn.py +1534 -0
  30. testbed/dpkp__kafka-python/kafka/errors.py +538 -0
  31. testbed/dpkp__kafka-python/kafka/future.py +83 -0
  32. testbed/dpkp__kafka-python/kafka/metrics/measurable.py +29 -0
  33. testbed/dpkp__kafka-python/kafka/metrics/stat.py +23 -0
  34. testbed/dpkp__kafka-python/kafka/metrics/stats/sensor.py +134 -0
  35. testbed/dpkp__kafka-python/kafka/oauth/__init__.py +3 -0
  36. testbed/dpkp__kafka-python/kafka/oauth/abstract.py +42 -0
  37. testbed/dpkp__kafka-python/kafka/partitioner/default.py +102 -0
  38. testbed/dpkp__kafka-python/kafka/producer/__init__.py +7 -0
  39. testbed/dpkp__kafka-python/kafka/producer/future.py +71 -0
  40. testbed/dpkp__kafka-python/kafka/producer/kafka.py +749 -0
  41. testbed/dpkp__kafka-python/kafka/producer/record_accumulator.py +590 -0
  42. testbed/dpkp__kafka-python/kafka/producer/sender.py +517 -0
  43. testbed/dpkp__kafka-python/kafka/protocol/__init__.py +47 -0
  44. testbed/dpkp__kafka-python/kafka/protocol/abstract.py +19 -0
  45. testbed/dpkp__kafka-python/kafka/protocol/admin.py +965 -0
  46. testbed/dpkp__kafka-python/kafka/protocol/api.py +97 -0
  47. testbed/dpkp__kafka-python/kafka/protocol/commit.py +255 -0
  48. testbed/dpkp__kafka-python/kafka/protocol/fetch.py +386 -0
  49. testbed/dpkp__kafka-python/kafka/protocol/frame.py +30 -0
  50. testbed/dpkp__kafka-python/kafka/protocol/message.py +216 -0
testbed/dpkp__kafka-python/.covrc ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ [run]
2
+ omit =
3
+ kafka/vendor/*
testbed/dpkp__kafka-python/.gitignore ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.egg-info
2
+ *.pyc
3
+ .tox
4
+ build
5
+ dist
6
+ MANIFEST
7
+ env
8
+ servers/*/kafka-bin*
9
+ servers/*/resources/ssl*
10
+ .coverage*
11
+ .noseids
12
+ docs/_build
13
+ .cache*
14
+ .idea/
15
+ integration-test/
16
+ tests-env/
17
+ .pytest_cache/
testbed/dpkp__kafka-python/.travis.yml ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ language: python
2
+
3
+ dist: xenial
4
+
5
+ python:
6
+ - 2.7
7
+ - 3.4
8
+ - 3.7
9
+ - 3.8
10
+ - pypy2.7-6.0
11
+
12
+ env:
13
+ - KAFKA_VERSION=0.8.2.2
14
+ - KAFKA_VERSION=0.9.0.1
15
+ - KAFKA_VERSION=0.10.2.2
16
+ - KAFKA_VERSION=0.11.0.3
17
+ - KAFKA_VERSION=1.1.1
18
+ - KAFKA_VERSION=2.4.0
19
+ - KAFKA_VERSION=2.5.0
20
+ - KAFKA_VERSION=2.6.0
21
+
22
+ addons:
23
+ apt:
24
+ packages:
25
+ - libsnappy-dev
26
+ - libzstd-dev
27
+ - openjdk-8-jdk
28
+
29
+ cache:
30
+ directories:
31
+ - $HOME/.cache/pip
32
+ - servers/dist
33
+
34
+ before_install:
35
+ - source travis_java_install.sh
36
+ - ./build_integration.sh
37
+
38
+ install:
39
+ - pip install tox coveralls
40
+ - pip install .
41
+
42
+ script:
43
+ - tox -e `if [ "$TRAVIS_PYTHON_VERSION" == "pypy2.7-6.0" ]; then echo pypy; else echo py${TRAVIS_PYTHON_VERSION/./}; fi`
44
+
45
+ after_success:
46
+ - coveralls
testbed/dpkp__kafka-python/AUTHORS.md ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Current Maintainer
2
+ * Dana Powers, [@dpkp](https://github.com/dpkp)
3
+
4
+ # Original Author and First Commit
5
+ * David Arthur, [@mumrah](https://github.com/mumrah)
6
+
7
+ # Contributors - 2015 (alpha by username)
8
+ * Alex Couture-Beil, [@alexcb](https://github.com/alexcb)
9
+ * Ali-Akber Saifee, [@alisaifee](https://github.com/alisaifee)
10
+ * Christophe-Marie Duquesne, [@chmduquesne](https://github.com/chmduquesne)
11
+ * Thomas Dimson, [@cosbynator](https://github.com/cosbynator)
12
+ * Kasper Jacobsen, [@Dinoshauer](https://github.com/Dinoshauer)
13
+ * Ross Duggan, [@duggan](https://github.com/duggan)
14
+ * Enrico Canzonieri, [@ecanzonieri](https://github.com/ecanzonieri)
15
+ * haosdent, [@haosdent](https://github.com/haosdent)
16
+ * Arturo Filastò, [@hellais](https://github.com/hellais)
17
+ * Job Evers‐Meltzer, [@jobevers](https://github.com/jobevers)
18
+ * Martin Olveyra, [@kalessin](https://github.com/kalessin)
19
+ * Kubilay Kocak, [@koobs](https://github.com/koobs)
20
+ * Matthew L Daniel <mdaniel@gmail.com>
21
+ * Eric Hewitt, [@meandthewallaby](https://github.com/meandthewallaby)
22
+ * Oliver Jowett [@mutability](https://github.com/mutability)
23
+ * Shaolei Zhou, [@reAsOn2010](https://github.com/reAsOn2010)
24
+ * Oskari Saarenmaa, [@saaros](https://github.com/saaros)
25
+ * John Anderson, [@sontek](https://github.com/sontek)
26
+ * Eduard Iskandarov, [@toidi](https://github.com/toidi)
27
+ * Todd Palino, [@toddpalino](https://github.com/toddpalino)
28
+ * trbs, [@trbs](https://github.com/trbs)
29
+ * Viktor Shlapakov, [@vshlapakov](https://github.com/vshlapakov)
30
+ * Will Daly, [@wedaly](https://github.com/wedaly)
31
+ * Warren Kiser, [@wkiser](https://github.com/wkiser)
32
+ * William Ting, [@wting](https://github.com/wting)
33
+ * Zack Dever, [@zackdever](https://github.com/zackdever)
34
+
35
+ # More Contributors
36
+ * Bruno Renié, [@brutasse](https://github.com/brutasse)
37
+ * Thomas Dimson, [@cosbynator](https://github.com/cosbynator)
38
+ * Jesse Myers, [@jessemyers](https://github.com/jessemyers)
39
+ * Mahendra M, [@mahendra](https://github.com/mahendra)
40
+ * Miguel Eduardo Gil Biraud, [@mgilbir](https://github.com/mgilbir)
41
+ * Marc Labbé, [@mrtheb](https://github.com/mrtheb)
42
+ * Patrick Lucas, [@patricklucas](https://github.com/patricklucas)
43
+ * Omar Ghishan, [@rdiomar](https://github.com/rdiomar) - RIP, Omar. 2014
44
+ * Ivan Pouzyrevsky, [@sandello](https://github.com/sandello)
45
+ * Lou Marvin Caraig, [@se7entyse7en](https://github.com/se7entyse7en)
46
+ * waliaashish85, [@waliaashish85](https://github.com/waliaashish85)
47
+ * Mark Roberts, [@wizzat](https://github.com/wizzat)
48
+ * Christophe Lecointe [@christophelec](https://github.com/christophelec)
49
+ * Mohamed Helmi Hichri [@hellich](https://github.com/hellich)
50
+
51
+ Thanks to all who have contributed!
testbed/dpkp__kafka-python/CHANGES.md ADDED
@@ -0,0 +1,1204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 2.0.2 (Sep 29, 2020)
2
+
3
+ Consumer
4
+ * KIP-54: Implement sticky partition assignment strategy (aynroot / PR #2057)
5
+ * Fix consumer deadlock when heartbeat thread request timeout (huangcuiyang / PR #2064)
6
+
7
+ Compatibility
8
+ * Python 3.8 support (Photonios / PR #2088)
9
+
10
+ Cleanups
11
+ * Bump dev requirements (jeffwidman / PR #2129)
12
+ * Fix crc32c deprecation warning (crc32c==2.1) (jeffwidman / PR #2128)
13
+ * Lint cleanup (jeffwidman / PR #2126)
14
+ * Fix initialization order in KafkaClient (pecalleja / PR #2119)
15
+ * Allow installing crc32c via extras (mishas / PR #2069)
16
+ * Remove unused imports (jameslamb / PR #2046)
17
+
18
+ Admin Client
19
+ * Merge _find_coordinator_id methods (jeffwidman / PR #2127)
20
+ * Feature: delete consumergroups (swenzel / PR #2040)
21
+ * Allow configurable timeouts in admin client check version (sunnyakaxd / PR #2107)
22
+ * Enhancement for Kafka Admin Client's "Describe Consumer Group" (Apurva007 / PR #2035)
23
+
24
+ Protocol
25
+ * Add support for zstd compression (gabriel-tincu / PR #2021)
26
+ * Add protocol support for brokers 1.1.0 - 2.5.0 (gabriel-tincu / PR #2038)
27
+ * Add ProduceRequest/ProduceResponse v6/v7/v8 (gabriel-tincu / PR #2020)
28
+ * Fix parsing NULL header values (kvfi / PR #2024)
29
+
30
+ Tests
31
+ * Add 2.5.0 to automated CI tests (gabriel-tincu / PR #2038)
32
+ * Add 2.1.1 to build_integration (gabriel-tincu / PR #2019)
33
+
34
+ Documentation / Logging / Errors
35
+ * Disable logging during producer object gc (gioele / PR #2043)
36
+ * Update example.py; use threading instead of multiprocessing (Mostafa-Elmenbawy / PR #2081)
37
+ * Fix typo in exception message (haracejacob / PR #2096)
38
+ * Add kafka.structs docstrings (Mostafa-Elmenbawy / PR #2080)
39
+ * Fix broken compatibility page link (anuragrana / PR #2045)
40
+ * Rename README to README.md (qhzxc0015 / PR #2055)
41
+ * Fix docs by adding SASL mention (jeffwidman / #1990)
42
+
43
+ # 2.0.1 (Feb 19, 2020)
44
+
45
+ Admin Client
46
+ * KAFKA-8962: Use least_loaded_node() for AdminClient.describe_topics() (jeffwidman / PR #2000)
47
+ * Fix AdminClient topic error parsing in MetadataResponse (jtribble / PR #1997)
48
+
49
+ # 2.0.0 (Feb 10, 2020)
50
+
51
+ This release includes breaking changes for any application code that has not
52
+ migrated from older Simple-style classes to newer Kafka-style classes.
53
+
54
+ Deprecation
55
+ * Remove deprecated SimpleClient, Producer, Consumer, Unittest (jeffwidman / PR #1196)
56
+
57
+ Admin Client
58
+ * Use the controller for topic metadata requests (TylerLubeck / PR #1995)
59
+ * Implement list_topics, describe_topics, and describe_cluster (TylerLubeck / PR #1993)
60
+ * Implement __eq__ and __hash__ for ACL objects (TylerLubeck / PR #1955)
61
+ * Fixes KafkaAdminClient returning `IncompatibleBrokerVersion` when passing an `api_version` (ian28223 / PR #1953)
62
+ * Admin protocol updates (TylerLubeck / PR #1948)
63
+ * Fix describe config for multi-broker clusters (jlandersen / PR #1869)
64
+
65
+ Miscellaneous Bugfixes / Improvements
66
+ * Enable SCRAM-SHA-256 and SCRAM-SHA-512 for sasl (swenzel / PR #1918)
67
+ * Fix slots usage and use more slots (carsonip / PR #1987)
68
+ * Optionally return OffsetAndMetadata from consumer.committed(tp) (dpkp / PR #1979)
69
+ * Reset conn configs on exception in conn.check_version() (dpkp / PR #1977)
70
+ * Do not block on sender thread join after timeout in producer.close() (dpkp / PR #1974)
71
+ * Implement methods to convert a Struct object to a pythonic object (TylerLubeck / PR #1951)
72
+
73
+ Test Infrastructure / Documentation / Maintenance
74
+ * Update 2.4.0 resource files for sasl integration (dpkp)
75
+ * Add kafka 2.4.0 to CI testing (vvuibert / PR #1972)
76
+ * convert test_admin_integration to pytest (ulrikjohansson / PR #1923)
77
+ * xfail test_describe_configs_topic_resource_returns_configs (dpkp / Issue #1929)
78
+ * Add crc32c to README and docs (dpkp)
79
+ * Improve docs for reconnect_backoff_max_ms (dpkp / PR #1976)
80
+ * Fix simple typo: managementment -> management (timgates42 / PR #1966)
81
+ * Fix typos (carsonip / PR #1938)
82
+ * Fix doc import paths (jeffwidman / PR #1933)
83
+ * Update docstring to match conn.py's (dabcoder / PR #1921)
84
+ * Do not log topic-specific errors in full metadata fetch (dpkp / PR #1980)
85
+ * Raise AssertionError if consumer closed in poll() (dpkp / PR #1978)
86
+ * Log retriable coordinator NodeNotReady, TooManyInFlightRequests as debug not error (dpkp / PR #1975)
87
+ * Remove unused import (jeffwidman)
88
+ * Remove some dead code (jeffwidman)
89
+ * Fix a benchmark to Use print() function in both Python 2 and Python 3 (cclauss / PR #1983)
90
+ * Fix a test to use ==/!= to compare str, bytes, and int literals (cclauss / PR #1984)
91
+ * Fix benchmarks to use pyperf (carsonip / PR #1986)
92
+ * Remove unused/empty .gitsubmodules file (jeffwidman / PR #1928)
93
+ * Remove deprecated `ConnectionError` (jeffwidman / PR #1816)
94
+
95
+
96
+ # 1.4.7 (Sep 30, 2019)
97
+
98
+ This is a minor release focused on KafkaConsumer performance, Admin Client
99
+ improvements, and Client concurrency. The KafkaConsumer iterator implementation
100
+ has been greatly simplified so that it just wraps consumer.poll(). The prior
101
+ implementation will remain available for a few more releases using the optional
102
+ KafkaConsumer config: `legacy_iterator=True` . This is expected to improve
103
+ consumer throughput substantially and help reduce heartbeat failures / group
104
+ rebalancing.
105
+
106
+ Client
107
+ * Send socket data via non-blocking IO with send buffer (dpkp / PR #1912)
108
+ * Rely on socket selector to detect completed connection attempts (dpkp / PR #1909)
109
+ * Improve connection lock handling; always use context manager (melor,dpkp / PR #1895)
110
+ * Reduce client poll timeout when there are no in-flight requests (dpkp / PR #1823)
111
+
112
+ KafkaConsumer
113
+ * Do not use wakeup when sending fetch requests from consumer (dpkp / PR #1911)
114
+ * Wrap `consumer.poll()` for KafkaConsumer iteration (dpkp / PR #1902)
115
+ * Allow the coordinator to auto-commit on old brokers (justecorruptio / PR #1832)
116
+ * Reduce internal client poll timeout for (legacy) consumer iterator interface (dpkp / PR #1824)
117
+ * Use dedicated connection for group coordinator (dpkp / PR #1822)
118
+ * Change coordinator lock acquisition order (dpkp / PR #1821)
119
+ * Make `partitions_for_topic` a read-through cache (Baisang / PR #1781,#1809)
120
+ * Fix consumer hanging indefinitely on topic deletion while rebalancing (commanderdishwasher / PR #1782)
121
+
122
+ Miscellaneous Bugfixes / Improvements
123
+ * Fix crc32c avilability on non-intel architectures (ossdev07 / PR #1904)
124
+ * Load system default SSL CAs if `ssl_cafile` is not provided (iAnomaly / PR #1883)
125
+ * Catch py3 TimeoutError in BrokerConnection send/recv (dpkp / PR #1820)
126
+ * Added a function to determine if bootstrap is successfully connected (Wayde2014 / PR #1876)
127
+
128
+ Admin Client
129
+ * Add ACL api support to KafkaAdminClient (ulrikjohansson / PR #1833)
130
+ * Add `sasl_kerberos_domain_name` config to KafkaAdminClient (jeffwidman / PR #1852)
131
+ * Update `security_protocol` config documentation for KafkaAdminClient (cardy31 / PR #1849)
132
+ * Break FindCoordinator into request/response methods in KafkaAdminClient (jeffwidman / PR #1871)
133
+ * Break consumer operations into request / response methods in KafkaAdminClient (jeffwidman / PR #1845)
134
+ * Parallelize calls to `_send_request_to_node()` in KafkaAdminClient (davidheitman / PR #1807)
135
+
136
+ Test Infrastructure / Documentation / Maintenance
137
+ * Add Kafka 2.3.0 to test matrix and compatibility docs (dpkp / PR #1915)
138
+ * Convert remaining `KafkaConsumer` tests to `pytest` (jeffwidman / PR #1886)
139
+ * Bump integration tests to 0.10.2.2 and 0.11.0.3 (jeffwidman / #1890)
140
+ * Cleanup handling of `KAFKA_VERSION` env var in tests (jeffwidman / PR #1887)
141
+ * Minor test cleanup (jeffwidman / PR #1885)
142
+ * Use `socket.SOCK_STREAM` in test assertions (iv-m / PR #1879)
143
+ * Sanity test for `consumer.topics()` and `consumer.partitions_for_topic()` (Baisang / PR #1829)
144
+ * Cleanup seconds conversion in client poll timeout calculation (jeffwidman / PR #1825)
145
+ * Remove unused imports (jeffwidman / PR #1808)
146
+ * Cleanup python nits in RangePartitionAssignor (jeffwidman / PR #1805)
147
+ * Update links to kafka consumer config docs (jeffwidman)
148
+ * Fix minor documentation typos (carsonip / PR #1865)
149
+ * Remove unused/weird comment line (jeffwidman / PR #1813)
150
+ * Update docs for `api_version_auto_timeout_ms` (jeffwidman / PR #1812)
151
+
152
+
153
+ # 1.4.6 (Apr 2, 2019)
154
+
155
+ This is a patch release primarily focused on bugs related to concurrency,
156
+ SSL connections and testing, and SASL authentication:
157
+
158
+ Client Concurrency Issues (Race Conditions / Deadlocks)
159
+ * Fix race condition in `protocol.send_bytes` (isamaru / PR #1752)
160
+ * Do not call `state_change_callback` with lock (dpkp / PR #1775)
161
+ * Additional BrokerConnection locks to synchronize protocol/IFR state (dpkp / PR #1768)
162
+ * Send pending requests before waiting for responses (dpkp / PR #1762)
163
+ * Avoid race condition on `client._conns` in send() (dpkp / PR #1772)
164
+ * Hold lock during `client.check_version` (dpkp / PR #1771)
165
+
166
+ Producer Wakeup / TimeoutError
167
+ * Dont wakeup during `maybe_refresh_metadata` -- it is only called by poll() (dpkp / PR #1769)
168
+ * Dont do client wakeup when sending from sender thread (dpkp / PR #1761)
169
+
170
+ SSL - Python3.7 Support / Bootstrap Hostname Verification / Testing
171
+ * Wrap SSL sockets after connecting for python3.7 compatibility (dpkp / PR #1754)
172
+ * Allow configuration of SSL Ciphers (dpkp / PR #1755)
173
+ * Maintain shadow cluster metadata for bootstrapping (dpkp / PR #1753)
174
+ * Generate SSL certificates for local testing (dpkp / PR #1756)
175
+ * Rename ssl.keystore.location and ssl.truststore.location config files (dpkp)
176
+ * Reset reconnect backoff on SSL connection (dpkp / PR #1777)
177
+
178
+ SASL - OAuthBearer support / api version bugfix
179
+ * Fix 0.8.2 protocol quick detection / fix SASL version check (dpkp / PR #1763)
180
+ * Update sasl configuration docstrings to include supported mechanisms (dpkp)
181
+ * Support SASL OAuthBearer Authentication (pt2pham / PR #1750)
182
+
183
+ Miscellaneous Bugfixes
184
+ * Dont force metadata refresh when closing unneeded bootstrap connections (dpkp / PR #1773)
185
+ * Fix possible AttributeError during conn._close_socket (dpkp / PR #1776)
186
+ * Return connection state explicitly after close in connect() (dpkp / PR #1778)
187
+ * Fix flaky conn tests that use time.time (dpkp / PR #1758)
188
+ * Add py to requirements-dev (dpkp)
189
+ * Fixups to benchmark scripts for py3 / new KafkaFixture interface (dpkp)
190
+
191
+
192
+ # 1.4.5 (Mar 14, 2019)
193
+
194
+ This release is primarily focused on addressing lock contention
195
+ and other coordination issues between the KafkaConsumer and the
196
+ background heartbeat thread that was introduced in the 1.4 release.
197
+
198
+ Consumer
199
+ * connections_max_idle_ms must be larger than request_timeout_ms (jeffwidman / PR #1688)
200
+ * Avoid race condition during close() / join heartbeat thread (dpkp / PR #1735)
201
+ * Use last offset from fetch v4 if available to avoid getting stuck in compacted topic (keithks / PR #1724)
202
+ * Synchronize puts to KafkaConsumer protocol buffer during async sends (dpkp / PR #1733)
203
+ * Improve KafkaConsumer join group / only enable Heartbeat Thread during stable group (dpkp / PR #1695)
204
+ * Remove unused `skip_double_compressed_messages` (jeffwidman / PR #1677)
205
+ * Fix commit_offsets_async() callback (Faqa / PR #1712)
206
+
207
+ Client
208
+ * Retry bootstrapping after backoff when necessary (dpkp / PR #1736)
209
+ * Recheck connecting nodes sooner when refreshing metadata (dpkp / PR #1737)
210
+ * Avoid probing broker versions twice on newer brokers (dpkp / PR #1738)
211
+ * Move all network connections and writes to KafkaClient.poll() (dpkp / PR #1729)
212
+ * Do not require client lock for read-only operations (dpkp / PR #1730)
213
+ * Timeout all unconnected conns (incl SSL) after request_timeout_ms (dpkp / PR #1696)
214
+
215
+ Admin Client
216
+ * Fix AttributeError in response topic error codes checking (jeffwidman)
217
+ * Fix response error checking in KafkaAdminClient send_to_controller (jeffwidman)
218
+ * Fix NotControllerError check (jeffwidman)
219
+
220
+ Core/Protocol
221
+ * Fix default protocol parser version / 0.8.2 version probe (dpkp / PR #1740)
222
+ * Make NotEnoughReplicasError/NotEnoughReplicasAfterAppendError retriable (le-linh / PR #1722)
223
+
224
+ Bugfixes
225
+ * Use copy() in metrics() to avoid thread safety issues (emeric254 / PR #1682)
226
+
227
+ Test Infrastructure
228
+ * Mock dns lookups in test_conn (dpkp / PR #1739)
229
+ * Use test.fixtures.version not test.conftest.version to avoid warnings (dpkp / PR #1731)
230
+ * Fix test_legacy_correct_metadata_response on x86 arch (stanislavlevin / PR #1718)
231
+ * Travis CI: 'sudo' tag is now deprecated in Travis (cclauss / PR #1698)
232
+ * Use Popen.communicate() instead of Popen.wait() (Baisang / PR #1689)
233
+
234
+ Compatibility
235
+ * Catch thrown OSError by python 3.7 when creating a connection (danjo133 / PR #1694)
236
+ * Update travis test coverage: 2.7, 3.4, 3.7, pypy2.7 (jeffwidman, dpkp / PR #1614)
237
+ * Drop dependency on sphinxcontrib-napoleon (stanislavlevin / PR #1715)
238
+ * Remove unused import from kafka/producer/record_accumulator.py (jeffwidman / PR #1705)
239
+ * Fix SSL connection testing in Python 3.7 (seanthegeek, silentben / PR #1669)
240
+
241
+
242
+ # 1.4.4 (Nov 20, 2018)
243
+
244
+ Bugfixes
245
+ * (Attempt to) Fix deadlock between consumer and heartbeat (zhgjun / dpkp #1628)
246
+ * Fix Metrics dict memory leak (kishorenc #1569)
247
+
248
+ Client
249
+ * Support Kafka record headers (hnousiainen #1574)
250
+ * Set socket timeout for the write-side of wake socketpair (Fleurer #1577)
251
+ * Add kerberos domain name config for gssapi sasl mechanism handshake (the-sea #1542)
252
+ * Support smaller topic metadata fetch during bootstrap (andyxning #1541)
253
+ * Use TypeError for invalid timeout type (jeffwidman #1636)
254
+ * Break poll if closed (dpkp)
255
+
256
+ Admin Client
257
+ * Add KafkaAdminClient class (llamahunter #1540)
258
+ * Fix list_consumer_groups() to query all brokers (jeffwidman #1635)
259
+ * Stop using broker-errors for client-side problems (jeffwidman #1639)
260
+ * Fix send to controller (jeffwidman #1640)
261
+ * Add group coordinator lookup (jeffwidman #1641)
262
+ * Fix describe_groups (jeffwidman #1642)
263
+ * Add list_consumer_group_offsets() (jeffwidman #1643)
264
+ * Remove support for api versions as strings from KafkaAdminClient (jeffwidman #1644)
265
+ * Set a clear default value for `validate_only`/`include_synonyms` (jeffwidman #1645)
266
+ * Bugfix: Always set this_groups_coordinator_id (jeffwidman #1650)
267
+
268
+ Consumer
269
+ * Fix linter warning on import of ConsumerRebalanceListener (ben-harack #1591)
270
+ * Remove ConsumerTimeout (emord #1587)
271
+ * Return future from commit_offsets_async() (ekimekim #1560)
272
+
273
+ Core / Protocol
274
+ * Add protocol structs for {Describe,Create,Delete} Acls (ulrikjohansson #1646/partial)
275
+ * Pre-compile pack/unpack function calls (billyevans / jeffwidman #1619)
276
+ * Don't use `kafka.common` internally (jeffwidman #1509)
277
+ * Be explicit with tuples for %s formatting (jeffwidman #1634)
278
+
279
+ Documentation
280
+ * Document connections_max_idle_ms (jeffwidman #1531)
281
+ * Fix sphinx url (jeffwidman #1610)
282
+ * Update remote urls: snappy, https, etc (jeffwidman #1603)
283
+ * Minor cleanup of testing doc (jeffwidman #1613)
284
+ * Various docstring / pep8 / code hygiene cleanups (jeffwidman #1647)
285
+
286
+ Test Infrastructure
287
+ * Stop pinning `pylint` (jeffwidman #1611)
288
+ * (partial) Migrate from `Unittest` to `pytest` (jeffwidman #1620)
289
+ * Minor aesthetic cleanup of partitioner tests (jeffwidman #1618)
290
+ * Cleanup fixture imports (jeffwidman #1616)
291
+ * Fix typo in test file name (jeffwidman)
292
+ * Remove unused ivy_root variable (jeffwidman)
293
+ * Add test fixtures for kafka versions 1.0.2 -> 2.0.1 (dpkp)
294
+ * Bump travis test for 1.x brokers to 1.1.1 (dpkp)
295
+
296
+ Logging / Error Messages
297
+ * raising logging level on messages signalling data loss (sibiryakov #1553)
298
+ * Stop using deprecated log.warn() (jeffwidman #1615)
299
+ * Fix typo in logging message (jeffwidman)
300
+
301
+ Compatibility
302
+ * Vendor enum34 (jeffwidman #1604)
303
+ * Bump vendored `six` to `1.11.0` (jeffwidman #1602)
304
+ * Vendor `six` consistently (jeffwidman #1605)
305
+ * Prevent `pylint` import errors on `six.moves` (jeffwidman #1609)
306
+
307
+
308
+ # 1.4.3 (May 26, 2018)
309
+
310
+ Compatibility
311
+ * Fix for python 3.7 support: remove 'async' keyword from SimpleProducer (dpkp #1454)
312
+
313
+ Client
314
+ * Improve BrokerConnection initialization time (romulorosa #1475)
315
+ * Ignore MetadataResponses with empty broker list (dpkp #1506)
316
+ * Improve connection handling when bootstrap list is invalid (dpkp #1507)
317
+
318
+ Consumer
319
+ * Check for immediate failure when looking up coordinator in heartbeat thread (dpkp #1457)
320
+
321
+ Core / Protocol
322
+ * Always acquire client lock before coordinator lock to avoid deadlocks (dpkp #1464)
323
+ * Added AlterConfigs and DescribeConfigs apis (StephenSorriaux #1472)
324
+ * Fix CreatePartitionsRequest_v0 (StephenSorriaux #1469)
325
+ * Add codec validators to record parser and builder for all formats (tvoinarovskyi #1447)
326
+ * Fix MemoryRecord bugs re error handling and add test coverage (tvoinarovskyi #1448)
327
+ * Force lz4 to disable Kafka-unsupported block linking when encoding (mnito #1476)
328
+ * Stop shadowing `ConnectionError` (jeffwidman #1492)
329
+
330
+ Documentation
331
+ * Document methods that return None (jeffwidman #1504)
332
+ * Minor doc capitalization cleanup (jeffwidman)
333
+ * Adds add_callback/add_errback example to docs (Berkodev #1441)
334
+ * Fix KafkaConsumer docstring for request_timeout_ms default (dpkp #1459)
335
+
336
+ Test Infrastructure
337
+ * Skip flakey SimpleProducer test (dpkp)
338
+ * Fix skipped integration tests if KAFKA_VERSION unset (dpkp #1453)
339
+
340
+ Logging / Error Messages
341
+ * Stop using deprecated log.warn() (jeffwidman)
342
+ * Change levels for some heartbeat thread logging (dpkp #1456)
343
+ * Log Heartbeat thread start / close for debugging (dpkp)
344
+
345
+
346
+ # 1.4.2 (Mar 10, 2018)
347
+
348
+ Bugfixes
349
+ * Close leaked selector in version check (dpkp #1425)
350
+ * Fix `BrokerConnection.connection_delay()` to return milliseconds (dpkp #1414)
351
+ * Use local copies in `Fetcher._fetchable_partitions` to avoid mutation errors (dpkp #1400)
352
+ * Fix error var name in `_unpack` (j2gg0s #1403)
353
+ * Fix KafkaConsumer compacted offset handling (dpkp #1397)
354
+ * Fix byte size estimation with kafka producer (blakeembrey #1393)
355
+ * Fix coordinator timeout in consumer poll interface (braedon #1384)
356
+
357
+ Client
358
+ * Add `BrokerConnection.connect_blocking()` to improve bootstrap to multi-address hostnames (dpkp #1411)
359
+ * Short-circuit `BrokerConnection.close()` if already disconnected (dpkp #1424)
360
+ * Only increase reconnect backoff if all addrinfos have been tried (dpkp #1423)
361
+ * Make BrokerConnection .host / .port / .afi immutable to avoid incorrect 'metadata changed' checks (dpkp #1422)
362
+ * Connect with sockaddrs to support non-zero ipv6 scope ids (dpkp #1433)
363
+ * Check timeout type in KafkaClient constructor (asdaraujo #1293)
364
+ * Update string representation of SimpleClient (asdaraujo #1293)
365
+ * Do not validate `api_version` against known versions (dpkp #1434)
366
+
367
+ Consumer
368
+ * Avoid tight poll loop in consumer when brokers are down (dpkp #1415)
369
+ * Validate `max_records` in KafkaConsumer.poll (dpkp #1398)
370
+ * KAFKA-5512: Awake heartbeat thread when it is time to poll (dpkp #1439)
371
+
372
+ Producer
373
+ * Validate that serializers generate bytes-like (or None) data (dpkp #1420)
374
+
375
+ Core / Protocol
376
+ * Support alternative lz4 package: lz4framed (everpcpc #1395)
377
+ * Use hardware accelerated CRC32C function if available (tvoinarovskyi #1389)
378
+ * Add Admin CreatePartitions API call (alexef #1386)
379
+
380
+ Test Infrastructure
381
+ * Close KafkaConsumer instances during tests (dpkp #1410)
382
+ * Introduce new fixtures to prepare for migration to pytest (asdaraujo #1293)
383
+ * Removed pytest-catchlog dependency (asdaraujo #1380)
384
+ * Fixes racing condition when message is sent to broker before topic logs are created (asdaraujo #1293)
385
+ * Add kafka 1.0.1 release to test fixtures (dpkp #1437)
386
+
387
+ Logging / Error Messages
388
+ * Re-enable logging during broker version check (dpkp #1430)
389
+ * Connection logging cleanups (dpkp #1432)
390
+ * Remove old CommitFailed error message from coordinator (dpkp #1436)
391
+
392
+
393
+ # 1.4.1 (Feb 9, 2018)
394
+
395
+ Bugfixes
396
+ * Fix consumer poll stuck error when no available partition (ckyoog #1375)
397
+ * Increase some integration test timeouts (dpkp #1374)
398
+ * Use raw in case string overriden (jeffwidman #1373)
399
+ * Fix pending completion IndexError bug caused by multiple threads (dpkp #1372)
400
+
401
+
402
+ # 1.4.0 (Feb 6, 2018)
403
+
404
+ This is a substantial release. Although there are no known 'showstopper' bugs as of release,
405
+ we do recommend you test any planned upgrade to your application prior to running in production.
406
+
407
+ Some of the major changes include:
408
+ * We have officially dropped python 2.6 support
409
+ * The KafkaConsumer now includes a background thread to handle coordinator heartbeats
410
+ * API protocol handling has been separated from networking code into a new class, KafkaProtocol
411
+ * Added support for kafka message format v2
412
+ * Refactored DNS lookups during kafka broker connections
413
+ * SASL authentication is working (we think)
414
+ * Removed several circular references to improve gc on close()
415
+
416
+ Thanks to all contributors -- the state of the kafka-python community is strong!
417
+
418
+ Detailed changelog are listed below:
419
+
420
+ Client
421
+ * Fixes for SASL support
422
+ * Refactor SASL/gssapi support (dpkp #1248 #1249 #1257 #1262 #1280)
423
+ * Add security layer negotiation to the GSSAPI authentication (asdaraujo #1283)
424
+ * Fix overriding sasl_kerberos_service_name in KafkaConsumer / KafkaProducer (natedogs911 #1264)
425
+ * Fix typo in _try_authenticate_plain (everpcpc #1333)
426
+ * Fix for Python 3 byte string handling in SASL auth (christophelec #1353)
427
+ * Move callback processing from BrokerConnection to KafkaClient (dpkp #1258)
428
+ * Use socket timeout of request_timeout_ms to prevent blocking forever on send (dpkp #1281)
429
+ * Refactor dns lookup in BrokerConnection (dpkp #1312)
430
+ * Read all available socket bytes (dpkp #1332)
431
+ * Honor reconnect_backoff in conn.connect() (dpkp #1342)
432
+
433
+ Consumer
434
+ * KAFKA-3977: Defer fetch parsing for space efficiency, and to raise exceptions to user (dpkp #1245)
435
+ * KAFKA-4034: Avoid unnecessary consumer coordinator lookup (dpkp #1254)
436
+ * Handle lookup_coordinator send failures (dpkp #1279)
437
+ * KAFKA-3888 Use background thread to process consumer heartbeats (dpkp #1266)
438
+ * Improve KafkaConsumer cleanup (dpkp #1339)
439
+ * Fix coordinator join_future race condition (dpkp #1338)
440
+ * Avoid KeyError when filtering fetchable partitions (dpkp #1344)
441
+ * Name heartbeat thread with group_id; use backoff when polling (dpkp #1345)
442
+ * KAFKA-3949: Avoid race condition when subscription changes during rebalance (dpkp #1364)
443
+ * Fix #1239 regression to avoid consuming duplicate compressed messages from mid-batch (dpkp #1367)
444
+
445
+ Producer
446
+ * Fix timestamp not passed to RecordMetadata (tvoinarovskyi #1273)
447
+ * Raise non-API exceptions (jeffwidman #1316)
448
+ * Fix reconnect_backoff_max_ms default config bug in KafkaProducer (YaoC #1352)
449
+
450
+ Core / Protocol
451
+ * Add kafka.protocol.parser.KafkaProtocol w/ receive and send (dpkp #1230)
452
+ * Refactor MessageSet and Message into LegacyRecordBatch to later support v2 message format (tvoinarovskyi #1252)
453
+ * Add DefaultRecordBatch implementation aka V2 message format parser/builder. (tvoinarovskyi #1185)
454
+ * optimize util.crc32 (ofek #1304)
455
+ * Raise better struct pack/unpack errors (jeffwidman #1320)
456
+ * Add Request/Response structs for kafka broker 1.0.0 (dpkp #1368)
457
+
458
+ Bugfixes
459
+ * use python standard max value (lukekingbru #1303)
460
+ * changed for to use enumerate() (TheAtomicOption #1301)
461
+ * Explicitly check for None rather than falsey (jeffwidman #1269)
462
+ * Minor Exception cleanup (jeffwidman #1317)
463
+ * Use non-deprecated exception handling (jeffwidman a699f6a)
464
+ * Remove assertion with side effect in client.wakeup() (bgedik #1348)
465
+ * use absolute imports everywhere (kevinkjt2000 #1362)
466
+
467
+ Test Infrastructure
468
+ * Use 0.11.0.2 kafka broker for integration testing (dpkp #1357 #1244)
469
+ * Add a Makefile to help build the project, generate docs, and run tests (tvoinarovskyi #1247)
470
+ * Add fixture support for 1.0.0 broker (dpkp #1275)
471
+ * Add kafka 1.0.0 to travis integration tests (dpkp #1365)
472
+ * Change fixture default host to localhost (asdaraujo #1305)
473
+ * Minor test cleanups (dpkp #1343)
474
+ * Use latest pytest 3.4.0, but drop pytest-sugar due to incompatibility (dpkp #1361)
475
+
476
+ Documentation
477
+ * Expand metrics docs (jeffwidman #1243)
478
+ * Fix docstring (jeffwidman #1261)
479
+ * Added controlled thread shutdown to example.py (TheAtomicOption #1268)
480
+ * Add license to wheel (jeffwidman #1286)
481
+ * Use correct casing for MB (jeffwidman #1298)
482
+
483
+ Logging / Error Messages
484
+ * Fix two bugs in printing bytes instance (jeffwidman #1296)
485
+
486
+
487
+ # 1.3.5 (Oct 7, 2017)
488
+
489
+ Bugfixes
490
+ * Fix partition assignment race condition (jeffwidman #1240)
491
+ * Fix consumer bug when seeking / resetting to the middle of a compressed messageset (dpkp #1239)
492
+ * Fix traceback sent to stderr not logging (dbgasaway #1221)
493
+ * Stop using mutable types for default arg values (jeffwidman #1213)
494
+ * Remove a few unused imports (jameslamb #1188)
495
+
496
+ Client
497
+ * Refactor BrokerConnection to use asynchronous receive_bytes pipe (dpkp #1032)
498
+
499
+ Consumer
500
+ * Drop unused sleep kwarg to poll (dpkp #1177)
501
+ * Enable KafkaConsumer beginning_offsets() and end_offsets() with older broker versions (buptljy #1200)
502
+ * Validate consumer subscription topic strings (nikeee #1238)
503
+
504
+ Documentation
505
+ * Small fixes to SASL documentation and logging; validate security_protocol (dpkp #1231)
506
+ * Various typo and grammar fixes (jeffwidman)
507
+
508
+
509
+ # 1.3.4 (Aug 13, 2017)
510
+
511
+ Bugfixes
512
+ * Avoid multiple connection attempts when refreshing metadata (dpkp #1067)
513
+ * Catch socket.errors when sending / recving bytes on wake socketpair (dpkp #1069)
514
+ * Deal with brokers that reappear with different IP address (originsmike #1085)
515
+ * Fix join-time-max and sync-time-max metrics to use Max() measure function (billyevans #1146)
516
+ * Raise AssertionError when decompression unsupported (bts-webber #1159)
517
+ * Catch ssl.EOFErrors on Python3.3 so we close the failing conn (Ormod #1162)
518
+ * Select on sockets to avoid busy polling during bootstrap (dpkp #1175)
519
+ * Initialize metadata_snapshot in group coordinator to avoid unnecessary rebalance (dpkp #1174)
520
+
521
+ Client
522
+ * Timeout idle connections via connections_max_idle_ms (dpkp #1068)
523
+ * Warn, dont raise, on DNS lookup failures (dpkp #1091)
524
+ * Support exponential backoff for broker reconnections -- KIP-144 (dpkp #1124)
525
+ * Add gssapi support (Kerberos) for SASL (Harald-Berghoff #1152)
526
+ * Add private map of api key -> min/max versions to BrokerConnection (dpkp #1169)
527
+
528
+ Consumer
529
+ * Backoff on unavailable group coordinator retry (dpkp #1125)
530
+ * Only change_subscription on pattern subscription when topics change (Artimi #1132)
531
+ * Add offsets_for_times, beginning_offsets and end_offsets APIs (tvoinarovskyi #1161)
532
+
533
+ Producer
534
+ * Raise KafkaTimeoutError when flush times out (infecto)
535
+ * Set producer atexit timeout to 0 to match del (Ormod #1126)
536
+
537
+ Core / Protocol
538
+ * 0.11.0.0 protocol updates (only - no client support yet) (dpkp #1127)
539
+ * Make UnknownTopicOrPartitionError retriable error (tvoinarovskyi)
540
+
541
+ Test Infrastructure
542
+ * pylint 1.7.0+ supports python 3.6 and merge py36 into common testenv (jianbin-wei #1095)
543
+ * Add kafka 0.10.2.1 into integration testing version (jianbin-wei #1096)
544
+ * Disable automated tests for python 2.6 and kafka 0.8.0 and 0.8.1.1 (jianbin-wei #1096)
545
+ * Support manual py26 testing; dont advertise 3.3 support (dpkp)
546
+ * Add 0.11.0.0 server resources, fix tests for 0.11 brokers (dpkp)
547
+ * Use fixture hostname, dont assume localhost (dpkp)
548
+ * Add 0.11.0.0 to travis test matrix, remove 0.10.1.1; use scala 2.11 artifacts (dpkp #1176)
549
+
550
+ Logging / Error Messages
551
+ * Improve error message when expiring batches in KafkaProducer (dpkp #1077)
552
+ * Update producer.send docstring -- raises KafkaTimeoutError (infecto)
553
+ * Use logging's built-in string interpolation (jeffwidman)
554
+ * Fix produce timeout message (melor #1151)
555
+ * Fix producer batch expiry messages to use seconds (dnwe)
556
+
557
+ Documentation
558
+ * Fix typo in KafkaClient docstring (jeffwidman #1054)
559
+ * Update README: Prefer python-lz4 over lz4tools (kiri11 #1057)
560
+ * Fix poll() hyperlink in KafkaClient (jeffwidman)
561
+ * Update RTD links with https / .io (jeffwidman #1074)
562
+ * Describe consumer thread-safety (ecksun)
563
+ * Fix typo in consumer integration test (jeffwidman)
564
+ * Note max_in_flight_requests_per_connection > 1 may change order of messages (tvoinarovskyi #1149)
565
+
566
+
567
+ # 1.3.3 (Mar 14, 2017)
568
+
569
+ Core / Protocol
570
+ * Derive all api classes from Request / Response base classes (dpkp 1030)
571
+ * Prefer python-lz4 if available (dpkp 1024)
572
+ * Fix kwarg handing in kafka.protocol.struct.Struct (dpkp 1025)
573
+ * Fixed couple of "leaks" when gc is disabled (Mephius 979)
574
+ * Added `max_bytes` option and FetchRequest_v3 usage. (Drizzt1991 962)
575
+ * CreateTopicsRequest / Response v1 (dpkp 1012)
576
+ * Add MetadataRequest_v2 and MetadataResponse_v2 structures for KIP-78 (Drizzt1991 974)
577
+ * KIP-88 / KAFKA-3853: OffsetFetch v2 structs (jeffwidman 971)
578
+ * DRY-up the MetadataRequest_v1 struct (jeffwidman 966)
579
+ * Add JoinGroup v1 structs (jeffwidman 965)
580
+ * DRY-up the OffsetCommitResponse Structs (jeffwidman 970)
581
+ * DRY-up the OffsetFetch structs (jeffwidman 964)
582
+ * time --> timestamp to match Java API (jeffwidman 969)
583
+ * Add support for offsetRequestV1 messages (jlafaye 951)
584
+ * Add FetchRequest/Response_v3 structs (jeffwidman 943)
585
+ * Add CreateTopics / DeleteTopics Structs (jeffwidman 944)
586
+
587
+ Test Infrastructure
588
+ * Add python3.6 to travis test suite, drop python3.3 (exponea 992)
589
+ * Update to 0.10.1.1 for integration testing (dpkp 953)
590
+ * Update vendored berkerpeksag/selectors34 to ff61b82 (Mephius 979)
591
+ * Remove dead code (jeffwidman 967)
592
+ * Update pytest fixtures to new yield syntax (jeffwidman 919)
593
+
594
+ Consumer
595
+ * Avoid re-encoding message for crc check (dpkp 1027)
596
+ * Optionally skip auto-commit during consumer.close (dpkp 1031)
597
+ * Return copy of consumer subscription set (dpkp 1029)
598
+ * Short-circuit group coordinator requests when NodeNotReady (dpkp 995)
599
+ * Avoid unknown coordinator after client poll (dpkp 1023)
600
+ * No longer configure a default consumer group (dpkp 1016)
601
+ * Dont refresh metadata on failed group coordinator request unless needed (dpkp 1006)
602
+ * Fail-fast on timeout constraint violations during KafkaConsumer creation (harelba 986)
603
+ * Default max_poll_records to Java default of 500 (jeffwidman 947)
604
+ * For 0.8.2, only attempt connection to coordinator if least_loaded_node succeeds (dpkp)
605
+
606
+ Producer
607
+ * change default timeout of KafkaProducer.close() to threading.TIMEOUT_MAX on py3 (mmyjona 991)
608
+
609
+ Client
610
+ * Add optional kwarg to ready/is_ready to disable metadata-priority logic (dpkp 1017)
611
+ * When closing a broker connection without error, fail in-flight-requests with Cancelled (dpkp 1010)
612
+ * Catch socket errors during ssl handshake (dpkp 1007)
613
+ * Drop old brokers when rebuilding broker metadata (dpkp 1005)
614
+ * Drop bad disconnect test -- just use the mocked-socket test (dpkp 982)
615
+ * Add support for Python built without ssl (minagawa-sho 954)
616
+ * Do not re-close a disconnected connection (dpkp)
617
+ * Drop unused last_failure time from BrokerConnection (dpkp)
618
+ * Use connection state functions where possible (dpkp)
619
+ * Pass error to BrokerConnection.close() (dpkp)
620
+
621
+ Bugfixes
622
+ * Free lz4 decompression context to avoid leak (dpkp 1024)
623
+ * Fix sasl reconnect bug: auth future must be reset on close (dpkp 1003)
624
+ * Fix raise exception from SubscriptionState.assign_from_subscribed (qntln 960)
625
+ * Fix blackout calculation: mark last_attempt time during connection close (dpkp 1008)
626
+ * Fix buffer pool reallocation after raising timeout (dpkp 999)
627
+
628
+ Logging / Error Messages
629
+ * Add client info logging re bootstrap; log connection attempts to balance with close (dpkp)
630
+ * Minor additional logging for consumer coordinator (dpkp)
631
+ * Add more debug-level connection logging (dpkp)
632
+ * Do not need str(self) when formatting to %s (dpkp)
633
+ * Add new broker response errors (dpkp)
634
+ * Small style fixes in kafka.errors (dpkp)
635
+ * Include the node id in BrokerConnection logging (dpkp 1009)
636
+ * Replace %s with %r in producer debug log message (chekunkov 973)
637
+
638
+ Documentation
639
+ * Sphinx documentation updates (jeffwidman 1019)
640
+ * Add sphinx formatting to hyperlink methods (jeffwidman 898)
641
+ * Fix BrokerConnection api_version docs default (jeffwidman 909)
642
+ * PEP-8: Spacing & removed unused imports (jeffwidman 899)
643
+ * Move BrokerConnection docstring to class (jeffwidman 968)
644
+ * Move docstring so it shows up in Sphinx/RTD (jeffwidman 952)
645
+ * Remove non-pip install instructions (jeffwidman 940)
646
+ * Spelling and grammar changes (melissacrawford396 923)
647
+ * Fix typo: coorelation --> correlation (jeffwidman 929)
648
+ * Make SSL warning list the correct Python versions (jeffwidman 924)
649
+ * Fixup comment reference to _maybe_connect (dpkp)
650
+ * Add ClusterMetadata sphinx documentation (dpkp)
651
+
652
+ Legacy Client
653
+ * Add send_list_offset_request for searching offset by timestamp (charsyam 1001)
654
+ * Use select to poll sockets for read to reduce CPU usage (jianbin-wei 958)
655
+ * Use select.select without instance bounding (adamwen829 949)
656
+
657
+
658
+ # 1.3.2 (Dec 28, 2016)
659
+
660
+ Core
661
+ * Add kafka.serializer interfaces (dpkp 912)
662
+ * from kafka import ConsumerRebalanceListener, OffsetAndMetadata
663
+ * Use 0.10.0.1 for integration tests (dpkp 803)
664
+
665
+ Consumer
666
+ * KAFKA-3007: KafkaConsumer max_poll_records (dpkp 831)
667
+ * Raise exception if given a non-str topic (ssaamm 824)
668
+ * Immediately update metadata for pattern subscription (laz2 915)
669
+
670
+ Producer
671
+ * Update Partitioners for use with KafkaProducer (barrotsteindev 827)
672
+ * Sort partitions before calling partitioner (ms7s 905)
673
+ * Added ssl_password config option to KafkaProducer class (kierkegaard13 830)
674
+
675
+ Client
676
+ * Always check for request timeouts (dpkp 887)
677
+ * When hostname lookup is necessary, do every connect (benauthor 812)
678
+
679
+ Bugfixes
680
+ * Fix errorcode check when socket.connect_ex raises an exception (guojh 907)
681
+ * Fix fetcher bug when processing offset out of range (sibiryakov 860)
682
+ * Fix possible request draining in ensure_active_group (dpkp 896)
683
+ * Fix metadata refresh handling with 0.10+ brokers when topic list is empty (sibiryakov 867)
684
+ * KafkaProducer should set timestamp in Message if provided (Drizzt1991 875)
685
+ * Fix murmur2 bug handling python2 bytes that do not ascii encode (dpkp 815)
686
+ * Monkeypatch max_in_flight_requests_per_connection when checking broker version (dpkp 834)
687
+ * Fix message timestamp_type (qix 828)
688
+
689
+ Logging / Error Messages
690
+ * Always include an error for logging when the coordinator is marked dead (dpkp 890)
691
+ * Only string-ify BrokerResponseError args if provided (dpkp 889)
692
+ * Update warning re advertised.listeners / advertised.host.name (jeffwidman 878)
693
+ * Fix unrecognized sasl_mechanism error message (sharego 883)
694
+
695
+ Documentation
696
+ * Add docstring for max_records (jeffwidman 897)
697
+ * Fixup doc references to max_in_flight_requests_per_connection
698
+ * Fix typo: passowrd --> password (jeffwidman 901)
699
+ * Fix documentation typo 'Defualt' -> 'Default'. (rolando 895)
700
+ * Added doc for `max_poll_records` option (Drizzt1991 881)
701
+ * Remove old design notes from Kafka 8 era (jeffwidman 876)
702
+ * Fix documentation typos (jeffwidman 874)
703
+ * Fix quota violation exception message (dpkp 809)
704
+ * Add comment for round robin partitioner with different subscriptions
705
+ * Improve KafkaProducer docstring for retries configuration
706
+
707
+
708
+ # 1.3.1 (Aug 8, 2016)
709
+
710
+ Bugfixes
711
+ * Fix AttributeError in BrokerConnectionMetrics after reconnecting
712
+
713
+
714
+ # 1.3.0 (Aug 4, 2016)
715
+
716
+ Incompatible Changes
717
+ * Delete KafkaConnection class (dpkp 769)
718
+ * Rename partition_assignment -> assignment in MemberMetadata for consistency
719
+ * Move selectors34 and socketpair to kafka.vendor (dpkp 785)
720
+ * Change api_version config to tuple; deprecate str with warning (dpkp 761)
721
+ * Rename _DEFAULT_CONFIG -> DEFAULT_CONFIG in KafkaProducer (dpkp 788)
722
+
723
+ Improvements
724
+ * Vendor six 1.10.0 to eliminate runtime dependency (dpkp 785)
725
+ * Add KafkaProducer and KafkaConsumer.metrics() with instrumentation similar to java client (dpkp 754 / 772 / 794)
726
+ * Support Sasl PLAIN authentication (larsjsol PR 779)
727
+ * Add checksum and size to RecordMetadata and ConsumerRecord (KAFKA-3196 / 770 / 594)
728
+ * Use MetadataRequest v1 for 0.10+ api_version (dpkp 762)
729
+ * Fix KafkaConsumer autocommit for 0.8 brokers (dpkp 756 / 706)
730
+ * Improve error logging (dpkp 760 / 759)
731
+ * Adapt benchmark scripts from https://github.com/mrafayaleem/kafka-jython (dpkp 754)
732
+ * Add api_version config to KafkaClient (dpkp 761)
733
+ * New Metadata method with_partitions() (dpkp 787)
734
+ * Use socket_options configuration to setsockopts(). Default TCP_NODELAY (dpkp 783)
735
+ * Expose selector type as config option (dpkp 764)
736
+ * Drain pending requests to the coordinator before initiating group rejoin (dpkp 798)
737
+ * Send combined size and payload bytes to socket to avoid potentially split packets with TCP_NODELAY (dpkp 797)
738
+
739
+ Bugfixes
740
+ * Ignore socket.error when checking for protocol out of sync prior to socket close (dpkp 792)
741
+ * Fix offset fetch when partitions are manually assigned (KAFKA-3960 / 786)
742
+ * Change pickle_method to use python3 special attributes (jpaulodit 777)
743
+ * Fix ProduceResponse v2 throttle_time_ms
744
+ * Always encode size with MessageSet (#771)
745
+ * Avoid buffer overread when compressing messageset in KafkaProducer
746
+ * Explicit format string argument indices for python 2.6 compatibility
747
+ * Simplify RecordMetadata; short circuit callbacks (#768)
748
+ * Fix autocommit when partitions assigned manually (KAFKA-3486 / #767 / #626)
749
+ * Handle metadata updates during consumer rebalance (KAFKA-3117 / #766 / #701)
750
+ * Add a consumer config option to exclude internal topics (KAFKA-2832 / #765)
751
+ * Protect writes to wakeup socket with threading lock (#763 / #709)
752
+ * Fetcher spending unnecessary time during metrics recording (KAFKA-3785)
753
+ * Always use absolute_import (dpkp)
754
+
755
+ Test / Fixtures
756
+ * Catch select errors while capturing test fixture logs
757
+ * Fix consumer group test race condition (dpkp 795)
758
+ * Retry fixture failures on a different port (dpkp 796)
759
+ * Dump fixture logs on failure
760
+
761
+ Documentation
762
+ * Fix misspelling of password (ssaamm 793)
763
+ * Document the ssl_password config option (ssaamm 780)
764
+ * Fix typo in KafkaConsumer documentation (ssaamm 775)
765
+ * Expand consumer.fetcher inline comments
766
+ * Update kafka configuration links -> 0.10.0.0 docs
767
+ * Fixup metrics_sample_window_ms docstring in consumer
768
+
769
+
770
+ # 1.2.5 (July 15, 2016)
771
+
772
+ Bugfixes
773
+ * Fix bug causing KafkaProducer to double-compress message batches on retry
774
+ * Check for double-compressed messages in KafkaConsumer, log warning and optionally skip
775
+ * Drop recursion in _unpack_message_set; only decompress once
776
+
777
+
778
+ # 1.2.4 (July 8, 2016)
779
+
780
+ Bugfixes
781
+ * Update consumer_timeout_ms docstring - KafkaConsumer raises StopIteration, no longer ConsumerTimeout
782
+ * Use explicit subscription state flag to handle seek() during message iteration
783
+ * Fix consumer iteration on compacted topics (dpkp PR 752)
784
+ * Support ssl_password config when loading cert chains (amckemie PR 750)
785
+
786
+
787
+ # 1.2.3 (July 2, 2016)
788
+
789
+ Patch Improvements
790
+ * Fix gc error log: avoid AttributeError in _unregister_cleanup (dpkp PR 747)
791
+ * Wakeup socket optimizations (dpkp PR 740)
792
+ * Assert will be disabled by "python -O" (tyronecai PR 736)
793
+ * Randomize order of topics/partitions processed by fetcher to improve balance (dpkp PR 732)
794
+ * Allow client.check_version timeout to be set in Producer and Consumer constructors (eastlondoner PR 647)
795
+
796
+
797
+ # 1.2.2 (June 21, 2016)
798
+
799
+ Bugfixes
800
+ * Clarify timeout unit in KafkaProducer close and flush (ms7s PR 734)
801
+ * Avoid busy poll during metadata refresh failure with retry_backoff_ms (dpkp PR 733)
802
+ * Check_version should scan nodes until version found or timeout (dpkp PR 731)
803
+ * Fix bug which could cause least_loaded_node to always return the same unavailable node (dpkp PR 730)
804
+ * Fix producer garbage collection with weakref in atexit handler (dpkp PR 728)
805
+ * Close client selector to fix fd leak (msmith PR 729)
806
+ * Tweak spelling mistake in error const (steve8918 PR 719)
807
+ * Rearrange connection tests to separate legacy KafkaConnection
808
+
809
+
810
+ # 1.2.1 (June 1, 2016)
811
+
812
+ Bugfixes
813
+ * Fix regression in MessageSet decoding wrt PartialMessages (#716)
814
+ * Catch response decode errors and log details (#715)
815
+ * Fix Legacy support url (#712 - JonasGroeger)
816
+ * Update sphinx docs re 0.10 broker support
817
+
818
+
819
+ # 1.2.0 (May 24, 2016)
820
+
821
+ This release officially adds support for Kafka 0.10
822
+ * Add protocol support for ApiVersionRequest (dpkp PR 678)
823
+ * KAFKA-3025: Message v1 -- add timetamp and relative offsets (dpkp PR 693)
824
+ * Use Fetch/Produce API v2 for brokers >= 0.10 (uses message format v1) (dpkp PR 694)
825
+ * Use standard LZ4 framing for v1 messages / kafka 0.10 (dpkp PR 695)
826
+
827
+ Consumers
828
+ * Update SimpleConsumer / legacy protocol to handle compressed messages (paulcavallaro PR 684)
829
+
830
+ Producers
831
+ * KAFKA-3388: Fix expiration of batches sitting in the accumulator (dpkp PR 699)
832
+ * KAFKA-3197: when max.in.flight.request.per.connection = 1, attempt to guarantee ordering (dpkp PR 698)
833
+ * Don't use soon-to-be-reserved keyword await as function name (FutureProduceResult) (dpkp PR 697)
834
+
835
+ Clients
836
+ * Fix socket leaks in KafkaClient (dpkp PR 696)
837
+
838
+ Documentation
839
+ <none>
840
+
841
+ Internals
842
+ * Support SSL CRL [requires python 2.7.9+ / 3.4+] (vincentbernat PR 683)
843
+ * Use original hostname for SSL checks (vincentbernat PR 682)
844
+ * Always pass encoded message bytes to MessageSet.encode()
845
+ * Raise ValueError on protocol encode/decode errors
846
+ * Supplement socket.gaierror exception in BrokerConnection.connect() (erikbeebe PR 687)
847
+ * BrokerConnection check_version: expect 0.9 to fail with CorrelationIdError
848
+ * Fix small bug in Sensor (zackdever PR 679)
849
+
850
+
851
+ # 1.1.1 (Apr 26, 2016)
852
+
853
+ quick bugfixes
854
+ * fix throttle_time_ms sensor handling (zackdever pr 667)
855
+ * improve handling of disconnected sockets (easypost pr 666 / dpkp)
856
+ * disable standard metadata refresh triggers during bootstrap (dpkp)
857
+ * more predictable future callback/errback exceptions (zackdever pr 670)
858
+ * avoid some exceptions in coordinator.__del__ (dpkp pr 668)
859
+
860
+
861
+ # 1.1.0 (Apr 25, 2016)
862
+
863
+ Consumers
864
+ * Avoid resending FetchRequests that are pending on internal queue
865
+ * Log debug messages when skipping fetched messages due to offset checks
866
+ * KAFKA-3013: Include topic-partition in exception for expired batches
867
+ * KAFKA-3318: clean up consumer logging and error messages
868
+ * Improve unknown coordinator error handling
869
+ * Improve auto-commit error handling when group_id is None
870
+ * Add paused() API (zackdever PR 602)
871
+ * Add default_offset_commit_callback to KafkaConsumer DEFAULT_CONFIGS
872
+
873
+ Producers
874
+ <none>
875
+
876
+ Clients
877
+ * Support SSL connections
878
+ * Use selectors module for non-blocking IO
879
+ * Refactor KafkaClient connection management
880
+ * Fix AttributeError in __del__
881
+ * SimpleClient: catch errors thrown by _get_leader_for_partition (zackdever PR 606)
882
+
883
+ Documentation
884
+ * Fix serializer/deserializer examples in README
885
+ * Update max.block.ms docstring
886
+ * Remove errant next(consumer) from consumer documentation
887
+ * Add producer.flush() to usage docs
888
+
889
+ Internals
890
+ * Add initial metrics implementation (zackdever PR 637)
891
+ * KAFKA-2136: support Fetch and Produce v1 (throttle_time_ms)
892
+ * Use version-indexed lists for request/response protocol structs (dpkp PR 630)
893
+ * Split kafka.common into kafka.structs and kafka.errors
894
+ * Handle partial socket send() (dpkp PR 611)
895
+ * Fix windows support (dpkp PR 603)
896
+ * IPv6 support (TimEvens PR 615; Roguelazer PR 642)
897
+
898
+
899
+ # 1.0.2 (Mar 14, 2016)
900
+
901
+ Consumers
902
+ * Improve KafkaConsumer Heartbeat handling (dpkp PR 583)
903
+ * Fix KafkaConsumer.position bug (stefanth PR 578)
904
+ * Raise TypeError when partition is not a TopicPartition (dpkp PR 587)
905
+ * KafkaConsumer.poll should sleep to prevent tight-loops (dpkp PR 597)
906
+
907
+ Producers
908
+ * Fix producer threading bug that can crash sender (dpkp PR 590)
909
+ * Fix bug in producer buffer pool reallocation (dpkp PR 585)
910
+ * Remove spurious warnings when closing sync SimpleProducer (twm PR 567)
911
+ * Fix FutureProduceResult.await() on python2.6 (dpkp)
912
+ * Add optional timeout parameter to KafkaProducer.flush() (dpkp)
913
+ * KafkaProducer Optimizations (zackdever PR 598)
914
+
915
+ Clients
916
+ * Improve error handling in SimpleClient.load_metadata_for_topics (dpkp)
917
+ * Improve handling of KafkaClient.least_loaded_node failure (dpkp PR 588)
918
+
919
+ Documentation
920
+ * Fix KafkaError import error in docs (shichao-an PR 564)
921
+ * Fix serializer / deserializer examples (scribu PR 573)
922
+
923
+ Internals
924
+ * Update to Kafka 0.9.0.1 for integration testing
925
+ * Fix ifr.future.failure in conn.py (mortenlj PR 566)
926
+ * Improve Zookeeper / Kafka Fixture management (dpkp)
927
+
928
+
929
+ # 1.0.1 (Feb 19, 2016)
930
+
931
+ Consumers
932
+ * Add RangePartitionAssignor (and use as default); add assignor tests (dpkp PR 550)
933
+ * Make sure all consumers are in same generation before stopping group test
934
+ * Verify node ready before sending offset fetch request from coordinator
935
+ * Improve warning when offset fetch request returns unknown topic / partition
936
+
937
+ Producers
938
+ * Warn if pending batches failed during flush
939
+ * Fix concurrency bug in RecordAccumulator.ready()
940
+ * Fix bug in SimpleBufferPool memory condition waiting / timeout
941
+ * Support batch_size = 0 in producer buffers (dpkp PR 558)
942
+ * Catch duplicate batch.done() calls [e.g., maybe_expire then a response errback]
943
+
944
+ Clients
945
+
946
+ Documentation
947
+ * Improve kafka.cluster docstrings
948
+ * Migrate load_example.py to KafkaProducer / KafkaConsumer
949
+
950
+ Internals
951
+ * Don't override system rcvbuf or sndbuf unless configured explicitly (dpkp PR 557)
952
+ * Some attributes may not exist in __del__ if we failed assertions
953
+ * Break up some circular references and close client wake pipes on __del__ (aisch PR 554)
954
+
955
+
956
+ # 1.0.0 (Feb 15, 2016)
957
+
958
+ This release includes significant code changes. Users of older kafka-python
959
+ versions are encouraged to test upgrades before deploying to production as
960
+ some interfaces and configuration options have changed.
961
+
962
+ Users of SimpleConsumer / SimpleProducer / SimpleClient (formerly KafkaClient)
963
+ from prior releases should migrate to KafkaConsumer / KafkaProducer. Low-level
964
+ APIs (Simple*) are no longer being actively maintained and will be removed in a
965
+ future release.
966
+
967
+ For comprehensive API documentation, please see python help() / docstrings,
968
+ kafka-python.readthedocs.org, or run `tox -e docs` from source to build
969
+ documentation locally.
970
+
971
+ Consumers
972
+ * KafkaConsumer re-written to emulate the new 0.9 kafka consumer (java client)
973
+ and support coordinated consumer groups (feature requires >= 0.9.0.0 brokers)
974
+
975
+ * Methods no longer available:
976
+
977
+ * configure [initialize a new consumer instead]
978
+ * set_topic_partitions [use subscribe() or assign()]
979
+ * fetch_messages [use poll() or iterator interface]
980
+ * get_partition_offsets
981
+ * offsets [use committed(partition)]
982
+ * task_done [handled internally by auto-commit; or commit offsets manually]
983
+
984
+ * Configuration changes (consistent with updated java client):
985
+
986
+ * lots of new configuration parameters -- see docs for details
987
+ * auto_offset_reset: previously values were 'smallest' or 'largest', now
988
+ values are 'earliest' or 'latest'
989
+ * fetch_wait_max_ms is now fetch_max_wait_ms
990
+ * max_partition_fetch_bytes is now max_partition_fetch_bytes
991
+ * deserializer_class is now value_deserializer and key_deserializer
992
+ * auto_commit_enable is now enable_auto_commit
993
+ * auto_commit_interval_messages was removed
994
+ * socket_timeout_ms was removed
995
+ * refresh_leader_backoff_ms was removed
996
+
997
+ * SimpleConsumer and MultiProcessConsumer are now deprecated and will be removed
998
+ in a future release. Users are encouraged to migrate to KafkaConsumer.
999
+
1000
+ Producers
1001
+ * new producer class: KafkaProducer. Exposes the same interface as official java client.
1002
+ Async by default; returned future.get() can be called for synchronous blocking
1003
+ * SimpleProducer is now deprecated and will be removed in a future release. Users are
1004
+ encouraged to migrate to KafkaProducer.
1005
+
1006
+ Clients
1007
+ * synchronous KafkaClient renamed to SimpleClient. For backwards compatibility, you
1008
+ will get a SimpleClient via `from kafka import KafkaClient`. This will change in
1009
+ a future release.
1010
+ * All client calls use non-blocking IO under the hood.
1011
+ * Add probe method check_version() to infer broker versions.
1012
+
1013
+ Documentation
1014
+ * Updated README and sphinx documentation to address new classes.
1015
+ * Docstring improvements to make python help() easier to use.
1016
+
1017
+ Internals
1018
+ * Old protocol stack is deprecated. It has been moved to kafka.protocol.legacy
1019
+ and may be removed in a future release.
1020
+ * Protocol layer re-written using Type classes, Schemas and Structs (modeled on
1021
+ the java client).
1022
+ * Add support for LZ4 compression (including broken framing header checksum).
1023
+
1024
+
1025
+ # 0.9.5 (Dec 6, 2015)
1026
+
1027
+ Consumers
1028
+ * Initial support for consumer coordinator: offsets only (toddpalino PR 420)
1029
+ * Allow blocking until some messages are received in SimpleConsumer (saaros PR 457)
1030
+ * Support subclass config changes in KafkaConsumer (zackdever PR 446)
1031
+ * Support retry semantics in MultiProcessConsumer (barricadeio PR 456)
1032
+ * Support partition_info in MultiProcessConsumer (scrapinghub PR 418)
1033
+ * Enable seek() to an absolute offset in SimpleConsumer (haosdent PR 412)
1034
+ * Add KafkaConsumer.close() (ucarion PR 426)
1035
+
1036
+ Producers
1037
+ * Catch client.reinit() exceptions in async producer (dpkp)
1038
+ * Producer.stop() now blocks until async thread completes (dpkp PR 485)
1039
+ * Catch errors during load_metadata_for_topics in async producer (bschopman PR 467)
1040
+ * Add compression-level support for codecs that support it (trbs PR 454)
1041
+ * Fix translation of Java murmur2 code, fix byte encoding for Python 3 (chrischamberlin PR 439)
1042
+ * Only call stop() on not-stopped producer objects (docker-hub PR 435)
1043
+ * Allow null payload for deletion feature (scrapinghub PR 409)
1044
+
1045
+ Clients
1046
+ * Use non-blocking io for broker aware requests (ecanzonieri PR 473)
1047
+ * Use debug logging level for metadata request (ecanzonieri PR 415)
1048
+ * Catch KafkaUnavailableError in _send_broker_aware_request (mutability PR 436)
1049
+ * Lower logging level on replica not available and commit (ecanzonieri PR 415)
1050
+
1051
+ Documentation
1052
+ * Update docs and links wrt maintainer change (mumrah -> dpkp)
1053
+
1054
+ Internals
1055
+ * Add py35 to tox testing
1056
+ * Update travis config to use container infrastructure
1057
+ * Add 0.8.2.2 and 0.9.0.0 resources for integration tests; update default official releases
1058
+ * new pylint disables for pylint 1.5.1 (zackdever PR 481)
1059
+ * Fix python3 / python2 comments re queue/Queue (dpkp)
1060
+ * Add Murmur2Partitioner to kafka __all__ imports (dpkp Issue 471)
1061
+ * Include LICENSE in PyPI sdist (koobs PR 441)
1062
+
1063
+ # 0.9.4 (June 11, 2015)
1064
+
1065
+ Consumers
1066
+ * Refactor SimpleConsumer internal fetch handling (dpkp PR 399)
1067
+ * Handle exceptions in SimpleConsumer commit() and reset_partition_offset() (dpkp PR 404)
1068
+ * Improve FailedPayloadsError handling in KafkaConsumer (dpkp PR 398)
1069
+ * KafkaConsumer: avoid raising KeyError in task_done (dpkp PR 389)
1070
+ * MultiProcessConsumer -- support configured partitions list (dpkp PR 380)
1071
+ * Fix SimpleConsumer leadership change handling (dpkp PR 393)
1072
+ * Fix SimpleConsumer connection error handling (reAsOn2010 PR 392)
1073
+ * Improve Consumer handling of 'falsy' partition values (wting PR 342)
1074
+ * Fix _offsets call error in KafkaConsumer (hellais PR 376)
1075
+ * Fix str/bytes bug in KafkaConsumer (dpkp PR 365)
1076
+ * Register atexit handlers for consumer and producer thread/multiprocess cleanup (dpkp PR 360)
1077
+ * Always fetch commit offsets in base consumer unless group is None (dpkp PR 356)
1078
+ * Stop consumer threads on delete (dpkp PR 357)
1079
+ * Deprecate metadata_broker_list in favor of bootstrap_servers in KafkaConsumer (dpkp PR 340)
1080
+ * Support pass-through parameters in multiprocess consumer (scrapinghub PR 336)
1081
+ * Enable offset commit on SimpleConsumer.seek (ecanzonieri PR 350)
1082
+ * Improve multiprocess consumer partition distribution (scrapinghub PR 335)
1083
+ * Ignore messages with offset less than requested (wkiser PR 328)
1084
+ * Handle OffsetOutOfRange in SimpleConsumer (ecanzonieri PR 296)
1085
+
1086
+ Producers
1087
+ * Add Murmur2Partitioner (dpkp PR 378)
1088
+ * Log error types in SimpleProducer and SimpleConsumer (dpkp PR 405)
1089
+ * SimpleProducer support configuration of fail_on_error (dpkp PR 396)
1090
+ * Deprecate KeyedProducer.send() (dpkp PR 379)
1091
+ * Further improvements to async producer code (dpkp PR 388)
1092
+ * Add more configuration parameters for async producer (dpkp)
1093
+ * Deprecate SimpleProducer batch_send=True in favor of async (dpkp)
1094
+ * Improve async producer error handling and retry logic (vshlapakov PR 331)
1095
+ * Support message keys in async producer (vshlapakov PR 329)
1096
+ * Use threading instead of multiprocessing for Async Producer (vshlapakov PR 330)
1097
+ * Stop threads on __del__ (chmduquesne PR 324)
1098
+ * Fix leadership failover handling in KeyedProducer (dpkp PR 314)
1099
+
1100
+ KafkaClient
1101
+ * Add .topics property for list of known topics (dpkp)
1102
+ * Fix request / response order guarantee bug in KafkaClient (dpkp PR 403)
1103
+ * Improve KafkaClient handling of connection failures in _get_conn (dpkp)
1104
+ * Client clears local metadata cache before updating from server (dpkp PR 367)
1105
+ * KafkaClient should return a response or error for each request - enable better retry handling (dpkp PR 366)
1106
+ * Improve str/bytes conversion in KafkaClient and KafkaConsumer (dpkp PR 332)
1107
+ * Always return sorted partition ids in client.get_partition_ids_for_topic() (dpkp PR 315)
1108
+
1109
+ Documentation
1110
+ * Cleanup Usage Documentation
1111
+ * Improve KafkaConsumer documentation (dpkp PR 341)
1112
+ * Update consumer documentation (sontek PR 317)
1113
+ * Add doc configuration for tox (sontek PR 316)
1114
+ * Switch to .rst doc format (sontek PR 321)
1115
+ * Fixup google groups link in README (sontek PR 320)
1116
+ * Automate documentation at kafka-python.readthedocs.org
1117
+
1118
+ Internals
1119
+ * Switch integration testing from 0.8.2.0 to 0.8.2.1 (dpkp PR 402)
1120
+ * Fix most flaky tests, improve debug logging, improve fixture handling (dpkp)
1121
+ * General style cleanups (dpkp PR 394)
1122
+ * Raise error on duplicate topic-partition payloads in protocol grouping (dpkp)
1123
+ * Use module-level loggers instead of simply 'kafka' (dpkp)
1124
+ * Remove pkg_resources check for __version__ at runtime (dpkp PR 387)
1125
+ * Make external API consistently support python3 strings for topic (kecaps PR 361)
1126
+ * Fix correlation id overflow (dpkp PR 355)
1127
+ * Cleanup kafka/common structs (dpkp PR 338)
1128
+ * Use context managers in gzip_encode / gzip_decode (dpkp PR 337)
1129
+ * Save failed request as FailedPayloadsError attribute (jobevers PR 302)
1130
+ * Remove unused kafka.queue (mumrah)
1131
+
1132
+ # 0.9.3 (Feb 3, 2015)
1133
+
1134
+ * Add coveralls.io support (sontek PR 307)
1135
+ * Fix python2.6 threading.Event bug in ReentrantTimer (dpkp PR 312)
1136
+ * Add kafka 0.8.2.0 to travis integration tests (dpkp PR 310)
1137
+ * Auto-convert topics to utf-8 bytes in Producer (sontek PR 306)
1138
+ * Fix reference cycle between SimpleConsumer and ReentrantTimer (zhaopengzp PR 309)
1139
+ * Add Sphinx API docs (wedaly PR 282)
1140
+ * Handle additional error cases exposed by 0.8.2.0 kafka server (dpkp PR 295)
1141
+ * Refactor error class management (alexcb PR 289)
1142
+ * Expose KafkaConsumer in __all__ for easy imports (Dinoshauer PR 286)
1143
+ * SimpleProducer starts on random partition by default (alexcb PR 288)
1144
+ * Add keys to compressed messages (meandthewallaby PR 281)
1145
+ * Add new high-level KafkaConsumer class based on java client api (dpkp PR 234)
1146
+ * Add KeyedProducer.send_messages api (pubnub PR 277)
1147
+ * Fix consumer pending() method (jettify PR 276)
1148
+ * Update low-level demo in README (sunisdown PR 274)
1149
+ * Include key in KeyedProducer messages (se7entyse7en PR 268)
1150
+ * Fix SimpleConsumer timeout behavior in get_messages (dpkp PR 238)
1151
+ * Fix error in consumer.py test against max_buffer_size (rthille/wizzat PR 225/242)
1152
+ * Improve string concat performance on pypy / py3 (dpkp PR 233)
1153
+ * Reorg directory layout for consumer/producer/partitioners (dpkp/wizzat PR 232/243)
1154
+ * Add OffsetCommitContext (locationlabs PR 217)
1155
+ * Metadata Refactor (dpkp PR 223)
1156
+ * Add Python 3 support (brutasse/wizzat - PR 227)
1157
+ * Minor cleanups - imports / README / PyPI classifiers (dpkp - PR 221)
1158
+ * Fix socket test (dpkp - PR 222)
1159
+ * Fix exception catching bug in test_failover_integration (zever - PR 216)
1160
+
1161
+ # 0.9.2 (Aug 26, 2014)
1162
+
1163
+ * Warn users that async producer does not reliably handle failures (dpkp - PR 213)
1164
+ * Fix spurious ConsumerFetchSizeTooSmall error in consumer (DataDog - PR 136)
1165
+ * Use PyLint for static error checking (dpkp - PR 208)
1166
+ * Strictly enforce str message type in producer.send_messages (dpkp - PR 211)
1167
+ * Add test timers via nose-timer plugin; list 10 slowest timings by default (dpkp)
1168
+ * Move fetching last known offset logic to a stand alone function (zever - PR 177)
1169
+ * Improve KafkaConnection and add more tests (dpkp - PR 196)
1170
+ * Raise TypeError if necessary when encoding strings (mdaniel - PR 204)
1171
+ * Use Travis-CI to publish tagged releases to pypi (tkuhlman / mumrah)
1172
+ * Use official binary tarballs for integration tests and parallelize travis tests (dpkp - PR 193)
1173
+ * Improve new-topic creation handling (wizzat - PR 174)
1174
+
1175
+ # 0.9.1 (Aug 10, 2014)
1176
+
1177
+ * Add codec parameter to Producers to enable compression (patricklucas - PR 166)
1178
+ * Support IPv6 hosts and network (snaury - PR 169)
1179
+ * Remove dependency on distribute (patricklucas - PR 163)
1180
+ * Fix connection error timeout and improve tests (wizzat - PR 158)
1181
+ * SimpleProducer randomization of initial round robin ordering (alexcb - PR 139)
1182
+ * Fix connection timeout in KafkaClient and KafkaConnection (maciejkula - PR 161)
1183
+ * Fix seek + commit behavior (wizzat - PR 148)
1184
+
1185
+
1186
+ # 0.9.0 (Mar 21, 2014)
1187
+
1188
+ * Connection refactor and test fixes (wizzat - PR 134)
1189
+ * Fix when partition has no leader (mrtheb - PR 109)
1190
+ * Change Producer API to take topic as send argument, not as instance variable (rdiomar - PR 111)
1191
+ * Substantial refactor and Test Fixing (rdiomar - PR 88)
1192
+ * Fix Multiprocess Consumer on windows (mahendra - PR 62)
1193
+ * Improve fault tolerance; add integration tests (jimjh)
1194
+ * PEP8 / Flakes / Style cleanups (Vetoshkin Nikita; mrtheb - PR 59)
1195
+ * Setup Travis CI (jimjh - PR 53/54)
1196
+ * Fix import of BufferUnderflowError (jimjh - PR 49)
1197
+ * Fix code examples in README (StevenLeRoux - PR 47/48)
1198
+
1199
+ # 0.8.0
1200
+
1201
+ * Changing auto_commit to False in [SimpleConsumer](kafka/consumer.py), until 0.8.1 is release offset commits are unsupported
1202
+ * Adding fetch_size_bytes to SimpleConsumer constructor to allow for user-configurable fetch sizes
1203
+ * Allow SimpleConsumer to automatically increase the fetch size if a partial message is read and no other messages were read during that fetch request. The increase factor is 1.5
1204
+ * Exception classes moved to kafka.common
testbed/dpkp__kafka-python/LICENSE ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2015 David Arthur
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
testbed/dpkp__kafka-python/MANIFEST.in ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ recursive-include kafka *.py
2
+ include README.rst
3
+ include LICENSE
4
+ include AUTHORS.md
5
+ include CHANGES.md
testbed/dpkp__kafka-python/Makefile ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Some simple testing tasks (sorry, UNIX only).
2
+
3
+ FLAGS=
4
+ KAFKA_VERSION=0.11.0.2
5
+ SCALA_VERSION=2.12
6
+
7
+ setup:
8
+ pip install -r requirements-dev.txt
9
+ pip install -Ue .
10
+
11
+ servers/$(KAFKA_VERSION)/kafka-bin:
12
+ KAFKA_VERSION=$(KAFKA_VERSION) SCALA_VERSION=$(SCALA_VERSION) ./build_integration.sh
13
+
14
+ build-integration: servers/$(KAFKA_VERSION)/kafka-bin
15
+
16
+ # Test and produce coverage using tox. This is the same as is run on Travis
17
+ test37: build-integration
18
+ KAFKA_VERSION=$(KAFKA_VERSION) SCALA_VERSION=$(SCALA_VERSION) tox -e py37 -- $(FLAGS)
19
+
20
+ test27: build-integration
21
+ KAFKA_VERSION=$(KAFKA_VERSION) SCALA_VERSION=$(SCALA_VERSION) tox -e py27 -- $(FLAGS)
22
+
23
+ # Test using py.test directly if you want to use local python. Useful for other
24
+ # platforms that require manual installation for C libraries, ie. Windows.
25
+ test-local: build-integration
26
+ KAFKA_VERSION=$(KAFKA_VERSION) SCALA_VERSION=$(SCALA_VERSION) py.test \
27
+ --pylint --pylint-rcfile=pylint.rc --pylint-error-types=EF $(FLAGS) kafka test
28
+
29
+ cov-local: build-integration
30
+ KAFKA_VERSION=$(KAFKA_VERSION) SCALA_VERSION=$(SCALA_VERSION) py.test \
31
+ --pylint --pylint-rcfile=pylint.rc --pylint-error-types=EF --cov=kafka \
32
+ --cov-config=.covrc --cov-report html $(FLAGS) kafka test
33
+ @echo "open file://`pwd`/htmlcov/index.html"
34
+
35
+ # Check the readme for syntax errors, which can lead to invalid formatting on
36
+ # PyPi homepage (https://pypi.python.org/pypi/kafka-python)
37
+ check-readme:
38
+ python setup.py check -rms
39
+
40
+ clean:
41
+ rm -rf `find . -name __pycache__`
42
+ rm -f `find . -type f -name '*.py[co]' `
43
+ rm -f `find . -type f -name '*~' `
44
+ rm -f `find . -type f -name '.*~' `
45
+ rm -f `find . -type f -name '@*' `
46
+ rm -f `find . -type f -name '#*#' `
47
+ rm -f `find . -type f -name '*.orig' `
48
+ rm -f `find . -type f -name '*.rej' `
49
+ rm -f .coverage
50
+ rm -rf htmlcov
51
+ rm -rf docs/_build/
52
+ rm -rf cover
53
+ rm -rf dist
54
+
55
+ doc:
56
+ make -C docs html
57
+ @echo "open file://`pwd`/docs/_build/html/index.html"
58
+
59
+ .PHONY: all test37 test27 test-local cov-local clean doc
testbed/dpkp__kafka-python/README.rst ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Kafka Python client
2
+ ------------------------
3
+
4
+ .. image:: https://img.shields.io/badge/kafka-2.6%2C%202.5%2C%202.4%2C%202.3%2C%202.2%2C%202.1%2C%202.0%2C%201.1%2C%201.0%2C%200.11%2C%200.10%2C%200.9%2C%200.8-brightgreen.svg
5
+ :target: https://kafka-python.readthedocs.io/en/master/compatibility.html
6
+ .. image:: https://img.shields.io/pypi/pyversions/kafka-python.svg
7
+ :target: https://pypi.python.org/pypi/kafka-python
8
+ .. image:: https://coveralls.io/repos/dpkp/kafka-python/badge.svg?branch=master&service=github
9
+ :target: https://coveralls.io/github/dpkp/kafka-python?branch=master
10
+ .. image:: https://travis-ci.org/dpkp/kafka-python.svg?branch=master
11
+ :target: https://travis-ci.org/dpkp/kafka-python
12
+ .. image:: https://img.shields.io/badge/license-Apache%202-blue.svg
13
+ :target: https://github.com/dpkp/kafka-python/blob/master/LICENSE
14
+
15
+ Python client for the Apache Kafka distributed stream processing system.
16
+ kafka-python is designed to function much like the official java client, with a
17
+ sprinkling of pythonic interfaces (e.g., consumer iterators).
18
+
19
+ kafka-python is best used with newer brokers (0.9+), but is backwards-compatible with
20
+ older versions (to 0.8.0). Some features will only be enabled on newer brokers.
21
+ For example, fully coordinated consumer groups -- i.e., dynamic partition
22
+ assignment to multiple consumers in the same group -- requires use of 0.9+ kafka
23
+ brokers. Supporting this feature for earlier broker releases would require
24
+ writing and maintaining custom leadership election and membership / health
25
+ check code (perhaps using zookeeper or consul). For older brokers, you can
26
+ achieve something similar by manually assigning different partitions to each
27
+ consumer instance with config management tools like chef, ansible, etc. This
28
+ approach will work fine, though it does not support rebalancing on failures.
29
+ See <https://kafka-python.readthedocs.io/en/master/compatibility.html>
30
+ for more details.
31
+
32
+ Please note that the master branch may contain unreleased features. For release
33
+ documentation, please see readthedocs and/or python's inline help.
34
+
35
+ >>> pip install kafka-python
36
+
37
+
38
+ KafkaConsumer
39
+ *************
40
+
41
+ KafkaConsumer is a high-level message consumer, intended to operate as similarly
42
+ as possible to the official java client. Full support for coordinated
43
+ consumer groups requires use of kafka brokers that support the Group APIs: kafka v0.9+.
44
+
45
+ See <https://kafka-python.readthedocs.io/en/master/apidoc/KafkaConsumer.html>
46
+ for API and configuration details.
47
+
48
+ The consumer iterator returns ConsumerRecords, which are simple namedtuples
49
+ that expose basic message attributes: topic, partition, offset, key, and value:
50
+
51
+ >>> from kafka import KafkaConsumer
52
+ >>> consumer = KafkaConsumer('my_favorite_topic')
53
+ >>> for msg in consumer:
54
+ ... print (msg)
55
+
56
+ >>> # join a consumer group for dynamic partition assignment and offset commits
57
+ >>> from kafka import KafkaConsumer
58
+ >>> consumer = KafkaConsumer('my_favorite_topic', group_id='my_favorite_group')
59
+ >>> for msg in consumer:
60
+ ... print (msg)
61
+
62
+ >>> # manually assign the partition list for the consumer
63
+ >>> from kafka import TopicPartition
64
+ >>> consumer = KafkaConsumer(bootstrap_servers='localhost:1234')
65
+ >>> consumer.assign([TopicPartition('foobar', 2)])
66
+ >>> msg = next(consumer)
67
+
68
+ >>> # Deserialize msgpack-encoded values
69
+ >>> consumer = KafkaConsumer(value_deserializer=msgpack.loads)
70
+ >>> consumer.subscribe(['msgpackfoo'])
71
+ >>> for msg in consumer:
72
+ ... assert isinstance(msg.value, dict)
73
+
74
+ >>> # Access record headers. The returned value is a list of tuples
75
+ >>> # with str, bytes for key and value
76
+ >>> for msg in consumer:
77
+ ... print (msg.headers)
78
+
79
+ >>> # Get consumer metrics
80
+ >>> metrics = consumer.metrics()
81
+
82
+
83
+ KafkaProducer
84
+ *************
85
+
86
+ KafkaProducer is a high-level, asynchronous message producer. The class is
87
+ intended to operate as similarly as possible to the official java client.
88
+ See <https://kafka-python.readthedocs.io/en/master/apidoc/KafkaProducer.html>
89
+ for more details.
90
+
91
+ >>> from kafka import KafkaProducer
92
+ >>> producer = KafkaProducer(bootstrap_servers='localhost:1234')
93
+ >>> for _ in range(100):
94
+ ... producer.send('foobar', b'some_message_bytes')
95
+
96
+ >>> # Block until a single message is sent (or timeout)
97
+ >>> future = producer.send('foobar', b'another_message')
98
+ >>> result = future.get(timeout=60)
99
+
100
+ >>> # Block until all pending messages are at least put on the network
101
+ >>> # NOTE: This does not guarantee delivery or success! It is really
102
+ >>> # only useful if you configure internal batching using linger_ms
103
+ >>> producer.flush()
104
+
105
+ >>> # Use a key for hashed-partitioning
106
+ >>> producer.send('foobar', key=b'foo', value=b'bar')
107
+
108
+ >>> # Serialize json messages
109
+ >>> import json
110
+ >>> producer = KafkaProducer(value_serializer=lambda v: json.dumps(v).encode('utf-8'))
111
+ >>> producer.send('fizzbuzz', {'foo': 'bar'})
112
+
113
+ >>> # Serialize string keys
114
+ >>> producer = KafkaProducer(key_serializer=str.encode)
115
+ >>> producer.send('flipflap', key='ping', value=b'1234')
116
+
117
+ >>> # Compress messages
118
+ >>> producer = KafkaProducer(compression_type='gzip')
119
+ >>> for i in range(1000):
120
+ ... producer.send('foobar', b'msg %d' % i)
121
+
122
+ >>> # Include record headers. The format is list of tuples with string key
123
+ >>> # and bytes value.
124
+ >>> producer.send('foobar', value=b'c29tZSB2YWx1ZQ==', headers=[('content-encoding', b'base64')])
125
+
126
+ >>> # Get producer performance metrics
127
+ >>> metrics = producer.metrics()
128
+
129
+
130
+ Thread safety
131
+ *************
132
+
133
+ The KafkaProducer can be used across threads without issue, unlike the
134
+ KafkaConsumer which cannot.
135
+
136
+ While it is possible to use the KafkaConsumer in a thread-local manner,
137
+ multiprocessing is recommended.
138
+
139
+
140
+ Compression
141
+ ***********
142
+
143
+ kafka-python supports the following compression formats:
144
+
145
+ - gzip
146
+ - LZ4
147
+ - Snappy
148
+ - Zstandard (zstd)
149
+
150
+ gzip is supported natively, the others require installing additional libraries.
151
+ See <https://kafka-python.readthedocs.io/en/master/install.html> for more information.
152
+
153
+
154
+ Optimized CRC32 Validation
155
+ **************************
156
+
157
+ Kafka uses CRC32 checksums to validate messages. kafka-python includes a pure
158
+ python implementation for compatibility. To improve performance for high-throughput
159
+ applications, kafka-python will use `crc32c` for optimized native code if installed.
160
+ See <https://kafka-python.readthedocs.io/en/master/install.html> for installation instructions.
161
+ See https://pypi.org/project/crc32c/ for details on the underlying crc32c lib.
162
+
163
+
164
+ Protocol
165
+ ********
166
+
167
+ A secondary goal of kafka-python is to provide an easy-to-use protocol layer
168
+ for interacting with kafka brokers via the python repl. This is useful for
169
+ testing, probing, and general experimentation. The protocol support is
170
+ leveraged to enable a KafkaClient.check_version() method that
171
+ probes a kafka broker and attempts to identify which version it is running
172
+ (0.8.0 to 2.6+).
testbed/dpkp__kafka-python/benchmarks/README.md ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ The `record_batch_*` benchmarks in this section are written using
2
+ ``pyperf`` library, created by Victor Stinner. For more information on
3
+ how to get reliable results of test runs please consult
4
+ https://pyperf.readthedocs.io/en/latest/run_benchmark.html.
testbed/dpkp__kafka-python/benchmarks/consumer_performance.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # Adapted from https://github.com/mrafayaleem/kafka-jython
3
+
4
+ from __future__ import absolute_import, print_function
5
+
6
+ import argparse
7
+ import logging
8
+ import pprint
9
+ import sys
10
+ import threading
11
+ import traceback
12
+
13
+ from kafka.vendor.six.moves import range
14
+
15
+ from kafka import KafkaConsumer, KafkaProducer
16
+ from test.fixtures import KafkaFixture, ZookeeperFixture
17
+
18
+ logging.basicConfig(level=logging.ERROR)
19
+
20
+
21
+ def start_brokers(n):
22
+ print('Starting {0} {1}-node cluster...'.format(KafkaFixture.kafka_version, n))
23
+ print('-> 1 Zookeeper')
24
+ zk = ZookeeperFixture.instance()
25
+ print('---> {0}:{1}'.format(zk.host, zk.port))
26
+ print()
27
+
28
+ partitions = min(n, 3)
29
+ replicas = min(n, 3)
30
+ print('-> {0} Brokers [{1} partitions / {2} replicas]'.format(n, partitions, replicas))
31
+ brokers = [
32
+ KafkaFixture.instance(i, zk, zk_chroot='',
33
+ partitions=partitions, replicas=replicas)
34
+ for i in range(n)
35
+ ]
36
+ for broker in brokers:
37
+ print('---> {0}:{1}'.format(broker.host, broker.port))
38
+ print()
39
+ return brokers
40
+
41
+
42
+ class ConsumerPerformance(object):
43
+
44
+ @staticmethod
45
+ def run(args):
46
+ try:
47
+ props = {}
48
+ for prop in args.consumer_config:
49
+ k, v = prop.split('=')
50
+ try:
51
+ v = int(v)
52
+ except ValueError:
53
+ pass
54
+ if v == 'None':
55
+ v = None
56
+ props[k] = v
57
+
58
+ if args.brokers:
59
+ brokers = start_brokers(args.brokers)
60
+ props['bootstrap_servers'] = ['{0}:{1}'.format(broker.host, broker.port)
61
+ for broker in brokers]
62
+ print('---> bootstrap_servers={0}'.format(props['bootstrap_servers']))
63
+ print()
64
+
65
+ print('-> Producing records')
66
+ record = bytes(bytearray(args.record_size))
67
+ producer = KafkaProducer(compression_type=args.fixture_compression,
68
+ **props)
69
+ for i in range(args.num_records):
70
+ producer.send(topic=args.topic, value=record)
71
+ producer.flush()
72
+ producer.close()
73
+ print('-> OK!')
74
+ print()
75
+
76
+ print('Initializing Consumer...')
77
+ props['auto_offset_reset'] = 'earliest'
78
+ if 'consumer_timeout_ms' not in props:
79
+ props['consumer_timeout_ms'] = 10000
80
+ props['metrics_sample_window_ms'] = args.stats_interval * 1000
81
+ for k, v in props.items():
82
+ print('---> {0}={1}'.format(k, v))
83
+ consumer = KafkaConsumer(args.topic, **props)
84
+ print('---> group_id={0}'.format(consumer.config['group_id']))
85
+ print('---> report stats every {0} secs'.format(args.stats_interval))
86
+ print('---> raw metrics? {0}'.format(args.raw_metrics))
87
+ timer_stop = threading.Event()
88
+ timer = StatsReporter(args.stats_interval, consumer,
89
+ event=timer_stop,
90
+ raw_metrics=args.raw_metrics)
91
+ timer.start()
92
+ print('-> OK!')
93
+ print()
94
+
95
+ records = 0
96
+ for msg in consumer:
97
+ records += 1
98
+ if records >= args.num_records:
99
+ break
100
+ print('Consumed {0} records'.format(records))
101
+
102
+ timer_stop.set()
103
+
104
+ except Exception:
105
+ exc_info = sys.exc_info()
106
+ traceback.print_exception(*exc_info)
107
+ sys.exit(1)
108
+
109
+
110
+ class StatsReporter(threading.Thread):
111
+ def __init__(self, interval, consumer, event=None, raw_metrics=False):
112
+ super(StatsReporter, self).__init__()
113
+ self.interval = interval
114
+ self.consumer = consumer
115
+ self.event = event
116
+ self.raw_metrics = raw_metrics
117
+
118
+ def print_stats(self):
119
+ metrics = self.consumer.metrics()
120
+ if self.raw_metrics:
121
+ pprint.pprint(metrics)
122
+ else:
123
+ print('{records-consumed-rate} records/sec ({bytes-consumed-rate} B/sec),'
124
+ ' {fetch-latency-avg} latency,'
125
+ ' {fetch-rate} fetch/s,'
126
+ ' {fetch-size-avg} fetch size,'
127
+ ' {records-lag-max} max record lag,'
128
+ ' {records-per-request-avg} records/req'
129
+ .format(**metrics['consumer-fetch-manager-metrics']))
130
+
131
+
132
+ def print_final(self):
133
+ self.print_stats()
134
+
135
+ def run(self):
136
+ while self.event and not self.event.wait(self.interval):
137
+ self.print_stats()
138
+ else:
139
+ self.print_final()
140
+
141
+
142
+ def get_args_parser():
143
+ parser = argparse.ArgumentParser(
144
+ description='This tool is used to verify the consumer performance.')
145
+
146
+ parser.add_argument(
147
+ '--topic', type=str,
148
+ help='Topic for consumer test',
149
+ default='kafka-python-benchmark-test')
150
+ parser.add_argument(
151
+ '--num-records', type=int,
152
+ help='number of messages to consume',
153
+ default=1000000)
154
+ parser.add_argument(
155
+ '--record-size', type=int,
156
+ help='message size in bytes',
157
+ default=100)
158
+ parser.add_argument(
159
+ '--consumer-config', type=str, nargs='+', default=(),
160
+ help='kafka consumer related configuration properties like '
161
+ 'bootstrap_servers,client_id etc..')
162
+ parser.add_argument(
163
+ '--fixture-compression', type=str,
164
+ help='specify a compression type for use with broker fixtures / producer')
165
+ parser.add_argument(
166
+ '--brokers', type=int,
167
+ help='Number of kafka brokers to start',
168
+ default=0)
169
+ parser.add_argument(
170
+ '--stats-interval', type=int,
171
+ help='Interval in seconds for stats reporting to console',
172
+ default=5)
173
+ parser.add_argument(
174
+ '--raw-metrics', action='store_true',
175
+ help='Enable this flag to print full metrics dict on each interval')
176
+ return parser
177
+
178
+
179
+ if __name__ == '__main__':
180
+ args = get_args_parser().parse_args()
181
+ ConsumerPerformance.run(args)
testbed/dpkp__kafka-python/benchmarks/load_example.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ from __future__ import print_function
3
+ import threading, logging, time
4
+
5
+ from kafka import KafkaConsumer, KafkaProducer
6
+
7
+ msg_size = 524288
8
+
9
+ producer_stop = threading.Event()
10
+ consumer_stop = threading.Event()
11
+
12
+ class Producer(threading.Thread):
13
+ big_msg = b'1' * msg_size
14
+
15
+ def run(self):
16
+ producer = KafkaProducer(bootstrap_servers='localhost:9092')
17
+ self.sent = 0
18
+
19
+ while not producer_stop.is_set():
20
+ producer.send('my-topic', self.big_msg)
21
+ self.sent += 1
22
+ producer.flush()
23
+
24
+
25
+ class Consumer(threading.Thread):
26
+
27
+ def run(self):
28
+ consumer = KafkaConsumer(bootstrap_servers='localhost:9092',
29
+ auto_offset_reset='earliest')
30
+ consumer.subscribe(['my-topic'])
31
+ self.valid = 0
32
+ self.invalid = 0
33
+
34
+ for message in consumer:
35
+ if len(message.value) == msg_size:
36
+ self.valid += 1
37
+ else:
38
+ self.invalid += 1
39
+
40
+ if consumer_stop.is_set():
41
+ break
42
+
43
+ consumer.close()
44
+
45
+ def main():
46
+ threads = [
47
+ Producer(),
48
+ Consumer()
49
+ ]
50
+
51
+ for t in threads:
52
+ t.start()
53
+
54
+ time.sleep(10)
55
+ producer_stop.set()
56
+ consumer_stop.set()
57
+ print('Messages sent: %d' % threads[0].sent)
58
+ print('Messages recvd: %d' % threads[1].valid)
59
+ print('Messages invalid: %d' % threads[1].invalid)
60
+
61
+ if __name__ == "__main__":
62
+ logging.basicConfig(
63
+ format='%(asctime)s.%(msecs)s:%(name)s:%(thread)d:%(levelname)s:%(process)d:%(message)s',
64
+ level=logging.INFO
65
+ )
66
+ main()
testbed/dpkp__kafka-python/benchmarks/producer_performance.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # Adapted from https://github.com/mrafayaleem/kafka-jython
3
+
4
+ from __future__ import absolute_import, print_function
5
+
6
+ import argparse
7
+ import pprint
8
+ import sys
9
+ import threading
10
+ import traceback
11
+
12
+ from kafka.vendor.six.moves import range
13
+
14
+ from kafka import KafkaProducer
15
+ from test.fixtures import KafkaFixture, ZookeeperFixture
16
+
17
+
18
+ def start_brokers(n):
19
+ print('Starting {0} {1}-node cluster...'.format(KafkaFixture.kafka_version, n))
20
+ print('-> 1 Zookeeper')
21
+ zk = ZookeeperFixture.instance()
22
+ print('---> {0}:{1}'.format(zk.host, zk.port))
23
+ print()
24
+
25
+ partitions = min(n, 3)
26
+ replicas = min(n, 3)
27
+ print('-> {0} Brokers [{1} partitions / {2} replicas]'.format(n, partitions, replicas))
28
+ brokers = [
29
+ KafkaFixture.instance(i, zk, zk_chroot='',
30
+ partitions=partitions, replicas=replicas)
31
+ for i in range(n)
32
+ ]
33
+ for broker in brokers:
34
+ print('---> {0}:{1}'.format(broker.host, broker.port))
35
+ print()
36
+ return brokers
37
+
38
+
39
+ class ProducerPerformance(object):
40
+
41
+ @staticmethod
42
+ def run(args):
43
+ try:
44
+ props = {}
45
+ for prop in args.producer_config:
46
+ k, v = prop.split('=')
47
+ try:
48
+ v = int(v)
49
+ except ValueError:
50
+ pass
51
+ if v == 'None':
52
+ v = None
53
+ props[k] = v
54
+
55
+ if args.brokers:
56
+ brokers = start_brokers(args.brokers)
57
+ props['bootstrap_servers'] = ['{0}:{1}'.format(broker.host, broker.port)
58
+ for broker in brokers]
59
+ print("---> bootstrap_servers={0}".format(props['bootstrap_servers']))
60
+ print()
61
+ print('-> OK!')
62
+ print()
63
+
64
+ print('Initializing producer...')
65
+ record = bytes(bytearray(args.record_size))
66
+ props['metrics_sample_window_ms'] = args.stats_interval * 1000
67
+
68
+ producer = KafkaProducer(**props)
69
+ for k, v in props.items():
70
+ print('---> {0}={1}'.format(k, v))
71
+ print('---> send {0} byte records'.format(args.record_size))
72
+ print('---> report stats every {0} secs'.format(args.stats_interval))
73
+ print('---> raw metrics? {0}'.format(args.raw_metrics))
74
+ timer_stop = threading.Event()
75
+ timer = StatsReporter(args.stats_interval, producer,
76
+ event=timer_stop,
77
+ raw_metrics=args.raw_metrics)
78
+ timer.start()
79
+ print('-> OK!')
80
+ print()
81
+
82
+ for i in range(args.num_records):
83
+ producer.send(topic=args.topic, value=record)
84
+ producer.flush()
85
+
86
+ timer_stop.set()
87
+
88
+ except Exception:
89
+ exc_info = sys.exc_info()
90
+ traceback.print_exception(*exc_info)
91
+ sys.exit(1)
92
+
93
+
94
+ class StatsReporter(threading.Thread):
95
+ def __init__(self, interval, producer, event=None, raw_metrics=False):
96
+ super(StatsReporter, self).__init__()
97
+ self.interval = interval
98
+ self.producer = producer
99
+ self.event = event
100
+ self.raw_metrics = raw_metrics
101
+
102
+ def print_stats(self):
103
+ metrics = self.producer.metrics()
104
+ if self.raw_metrics:
105
+ pprint.pprint(metrics)
106
+ else:
107
+ print('{record-send-rate} records/sec ({byte-rate} B/sec),'
108
+ ' {request-latency-avg} latency,'
109
+ ' {record-size-avg} record size,'
110
+ ' {batch-size-avg} batch size,'
111
+ ' {records-per-request-avg} records/req'
112
+ .format(**metrics['producer-metrics']))
113
+
114
+ def print_final(self):
115
+ self.print_stats()
116
+
117
+ def run(self):
118
+ while self.event and not self.event.wait(self.interval):
119
+ self.print_stats()
120
+ else:
121
+ self.print_final()
122
+
123
+
124
+ def get_args_parser():
125
+ parser = argparse.ArgumentParser(
126
+ description='This tool is used to verify the producer performance.')
127
+
128
+ parser.add_argument(
129
+ '--topic', type=str,
130
+ help='Topic name for test',
131
+ default='kafka-python-benchmark-test')
132
+ parser.add_argument(
133
+ '--num-records', type=int,
134
+ help='number of messages to produce',
135
+ default=1000000)
136
+ parser.add_argument(
137
+ '--record-size', type=int,
138
+ help='message size in bytes',
139
+ default=100)
140
+ parser.add_argument(
141
+ '--producer-config', type=str, nargs='+', default=(),
142
+ help='kafka producer related configuaration properties like '
143
+ 'bootstrap_servers,client_id etc..')
144
+ parser.add_argument(
145
+ '--brokers', type=int,
146
+ help='Number of kafka brokers to start',
147
+ default=0)
148
+ parser.add_argument(
149
+ '--stats-interval', type=int,
150
+ help='Interval in seconds for stats reporting to console',
151
+ default=5)
152
+ parser.add_argument(
153
+ '--raw-metrics', action='store_true',
154
+ help='Enable this flag to print full metrics dict on each interval')
155
+ return parser
156
+
157
+
158
+ if __name__ == '__main__':
159
+ args = get_args_parser().parse_args()
160
+ ProducerPerformance.run(args)
testbed/dpkp__kafka-python/benchmarks/record_batch_compose.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import print_function
3
+ import hashlib
4
+ import itertools
5
+ import os
6
+ import random
7
+
8
+ import pyperf
9
+
10
+ from kafka.record.memory_records import MemoryRecordsBuilder
11
+
12
+
13
+ DEFAULT_BATCH_SIZE = 1600 * 1024
14
+ KEY_SIZE = 6
15
+ VALUE_SIZE = 60
16
+ TIMESTAMP_RANGE = [1505824130000, 1505824140000]
17
+
18
+ # With values above v1 record is 100 bytes, so 10 000 bytes for 100 messages
19
+ MESSAGES_PER_BATCH = 100
20
+
21
+
22
+ def random_bytes(length):
23
+ buffer = bytearray(length)
24
+ for i in range(length):
25
+ buffer[i] = random.randint(0, 255)
26
+ return bytes(buffer)
27
+
28
+
29
+ def prepare():
30
+ return iter(itertools.cycle([
31
+ (random_bytes(KEY_SIZE),
32
+ random_bytes(VALUE_SIZE),
33
+ random.randint(*TIMESTAMP_RANGE)
34
+ )
35
+ for _ in range(int(MESSAGES_PER_BATCH * 1.94))
36
+ ]))
37
+
38
+
39
+ def finalize(results):
40
+ # Just some strange code to make sure PyPy does execute the main code
41
+ # properly, without optimizing it away
42
+ hash_val = hashlib.md5()
43
+ for buf in results:
44
+ hash_val.update(buf)
45
+ print(hash_val, file=open(os.devnull, "w"))
46
+
47
+
48
+ def func(loops, magic):
49
+ # Jit can optimize out the whole function if the result is the same each
50
+ # time, so we need some randomized input data )
51
+ precomputed_samples = prepare()
52
+ results = []
53
+
54
+ # Main benchmark code.
55
+ t0 = pyperf.perf_counter()
56
+ for _ in range(loops):
57
+ batch = MemoryRecordsBuilder(
58
+ magic, batch_size=DEFAULT_BATCH_SIZE, compression_type=0)
59
+ for _ in range(MESSAGES_PER_BATCH):
60
+ key, value, timestamp = next(precomputed_samples)
61
+ size = batch.append(
62
+ timestamp=timestamp, key=key, value=value)
63
+ assert size
64
+ batch.close()
65
+ results.append(batch.buffer())
66
+
67
+ res = pyperf.perf_counter() - t0
68
+
69
+ finalize(results)
70
+
71
+ return res
72
+
73
+
74
+ runner = pyperf.Runner()
75
+ runner.bench_time_func('batch_append_v0', func, 0)
76
+ runner.bench_time_func('batch_append_v1', func, 1)
77
+ runner.bench_time_func('batch_append_v2', func, 2)
testbed/dpkp__kafka-python/benchmarks/record_batch_read.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ from __future__ import print_function
3
+ import hashlib
4
+ import itertools
5
+ import os
6
+ import random
7
+
8
+ import pyperf
9
+
10
+ from kafka.record.memory_records import MemoryRecords, MemoryRecordsBuilder
11
+
12
+
13
+ DEFAULT_BATCH_SIZE = 1600 * 1024
14
+ KEY_SIZE = 6
15
+ VALUE_SIZE = 60
16
+ TIMESTAMP_RANGE = [1505824130000, 1505824140000]
17
+
18
+ BATCH_SAMPLES = 5
19
+ MESSAGES_PER_BATCH = 100
20
+
21
+
22
+ def random_bytes(length):
23
+ buffer = bytearray(length)
24
+ for i in range(length):
25
+ buffer[i] = random.randint(0, 255)
26
+ return bytes(buffer)
27
+
28
+
29
+ def prepare(magic):
30
+ samples = []
31
+ for _ in range(BATCH_SAMPLES):
32
+ batch = MemoryRecordsBuilder(
33
+ magic, batch_size=DEFAULT_BATCH_SIZE, compression_type=0)
34
+ for _ in range(MESSAGES_PER_BATCH):
35
+ size = batch.append(
36
+ random.randint(*TIMESTAMP_RANGE),
37
+ random_bytes(KEY_SIZE),
38
+ random_bytes(VALUE_SIZE),
39
+ headers=[])
40
+ assert size
41
+ batch.close()
42
+ samples.append(bytes(batch.buffer()))
43
+
44
+ return iter(itertools.cycle(samples))
45
+
46
+
47
+ def finalize(results):
48
+ # Just some strange code to make sure PyPy does execute the code above
49
+ # properly
50
+ hash_val = hashlib.md5()
51
+ for buf in results:
52
+ hash_val.update(buf)
53
+ print(hash_val, file=open(os.devnull, "w"))
54
+
55
+
56
+ def func(loops, magic):
57
+ # Jit can optimize out the whole function if the result is the same each
58
+ # time, so we need some randomized input data )
59
+ precomputed_samples = prepare(magic)
60
+ results = []
61
+
62
+ # Main benchmark code.
63
+ batch_data = next(precomputed_samples)
64
+ t0 = pyperf.perf_counter()
65
+ for _ in range(loops):
66
+ records = MemoryRecords(batch_data)
67
+ while records.has_next():
68
+ batch = records.next_batch()
69
+ batch.validate_crc()
70
+ for record in batch:
71
+ results.append(record.value)
72
+
73
+ res = pyperf.perf_counter() - t0
74
+ finalize(results)
75
+
76
+ return res
77
+
78
+
79
+ runner = pyperf.Runner()
80
+ runner.bench_time_func('batch_read_v0', func, 0)
81
+ runner.bench_time_func('batch_read_v1', func, 1)
82
+ runner.bench_time_func('batch_read_v2', func, 2)
testbed/dpkp__kafka-python/benchmarks/varint_speed.py ADDED
@@ -0,0 +1,443 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ from __future__ import print_function
3
+ import pyperf
4
+ from kafka.vendor import six
5
+
6
+
7
+ test_data = [
8
+ (b"\x00", 0),
9
+ (b"\x01", -1),
10
+ (b"\x02", 1),
11
+ (b"\x7E", 63),
12
+ (b"\x7F", -64),
13
+ (b"\x80\x01", 64),
14
+ (b"\x81\x01", -65),
15
+ (b"\xFE\x7F", 8191),
16
+ (b"\xFF\x7F", -8192),
17
+ (b"\x80\x80\x01", 8192),
18
+ (b"\x81\x80\x01", -8193),
19
+ (b"\xFE\xFF\x7F", 1048575),
20
+ (b"\xFF\xFF\x7F", -1048576),
21
+ (b"\x80\x80\x80\x01", 1048576),
22
+ (b"\x81\x80\x80\x01", -1048577),
23
+ (b"\xFE\xFF\xFF\x7F", 134217727),
24
+ (b"\xFF\xFF\xFF\x7F", -134217728),
25
+ (b"\x80\x80\x80\x80\x01", 134217728),
26
+ (b"\x81\x80\x80\x80\x01", -134217729),
27
+ (b"\xFE\xFF\xFF\xFF\x7F", 17179869183),
28
+ (b"\xFF\xFF\xFF\xFF\x7F", -17179869184),
29
+ (b"\x80\x80\x80\x80\x80\x01", 17179869184),
30
+ (b"\x81\x80\x80\x80\x80\x01", -17179869185),
31
+ (b"\xFE\xFF\xFF\xFF\xFF\x7F", 2199023255551),
32
+ (b"\xFF\xFF\xFF\xFF\xFF\x7F", -2199023255552),
33
+ (b"\x80\x80\x80\x80\x80\x80\x01", 2199023255552),
34
+ (b"\x81\x80\x80\x80\x80\x80\x01", -2199023255553),
35
+ (b"\xFE\xFF\xFF\xFF\xFF\xFF\x7F", 281474976710655),
36
+ (b"\xFF\xFF\xFF\xFF\xFF\xFF\x7F", -281474976710656),
37
+ (b"\x80\x80\x80\x80\x80\x80\x80\x01", 281474976710656),
38
+ (b"\x81\x80\x80\x80\x80\x80\x80\x01", -281474976710657),
39
+ (b"\xFE\xFF\xFF\xFF\xFF\xFF\xFF\x7F", 36028797018963967),
40
+ (b"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x7F", -36028797018963968),
41
+ (b"\x80\x80\x80\x80\x80\x80\x80\x80\x01", 36028797018963968),
42
+ (b"\x81\x80\x80\x80\x80\x80\x80\x80\x01", -36028797018963969),
43
+ (b"\xFE\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x7F", 4611686018427387903),
44
+ (b"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x7F", -4611686018427387904),
45
+ (b"\x80\x80\x80\x80\x80\x80\x80\x80\x80\x01", 4611686018427387904),
46
+ (b"\x81\x80\x80\x80\x80\x80\x80\x80\x80\x01", -4611686018427387905),
47
+ ]
48
+
49
+
50
+ BENCH_VALUES_ENC = [
51
+ 60, # 1 byte
52
+ -8192, # 2 bytes
53
+ 1048575, # 3 bytes
54
+ 134217727, # 4 bytes
55
+ -17179869184, # 5 bytes
56
+ 2199023255551, # 6 bytes
57
+ ]
58
+
59
+ BENCH_VALUES_DEC = [
60
+ b"\x7E", # 1 byte
61
+ b"\xFF\x7F", # 2 bytes
62
+ b"\xFE\xFF\x7F", # 3 bytes
63
+ b"\xFF\xFF\xFF\x7F", # 4 bytes
64
+ b"\x80\x80\x80\x80\x01", # 5 bytes
65
+ b"\xFE\xFF\xFF\xFF\xFF\x7F", # 6 bytes
66
+ ]
67
+ BENCH_VALUES_DEC = list(map(bytearray, BENCH_VALUES_DEC))
68
+
69
+
70
+ def _assert_valid_enc(enc_func):
71
+ for encoded, decoded in test_data:
72
+ assert enc_func(decoded) == encoded, decoded
73
+
74
+
75
+ def _assert_valid_dec(dec_func):
76
+ for encoded, decoded in test_data:
77
+ res, pos = dec_func(bytearray(encoded))
78
+ assert res == decoded, (decoded, res)
79
+ assert pos == len(encoded), (decoded, pos)
80
+
81
+
82
+ def _assert_valid_size(size_func):
83
+ for encoded, decoded in test_data:
84
+ assert size_func(decoded) == len(encoded), decoded
85
+
86
+
87
+ def encode_varint_1(num):
88
+ """ Encode an integer to a varint presentation. See
89
+ https://developers.google.com/protocol-buffers/docs/encoding?csw=1#varints
90
+ on how those can be produced.
91
+
92
+ Arguments:
93
+ num (int): Value to encode
94
+
95
+ Returns:
96
+ bytearray: Encoded presentation of integer with length from 1 to 10
97
+ bytes
98
+ """
99
+ # Shift sign to the end of number
100
+ num = (num << 1) ^ (num >> 63)
101
+ # Max 10 bytes. We assert those are allocated
102
+ buf = bytearray(10)
103
+
104
+ for i in range(10):
105
+ # 7 lowest bits from the number and set 8th if we still have pending
106
+ # bits left to encode
107
+ buf[i] = num & 0x7f | (0x80 if num > 0x7f else 0)
108
+ num = num >> 7
109
+ if num == 0:
110
+ break
111
+ else:
112
+ # Max size of endcoded double is 10 bytes for unsigned values
113
+ raise ValueError("Out of double range")
114
+ return buf[:i + 1]
115
+
116
+ _assert_valid_enc(encode_varint_1)
117
+
118
+
119
+ def encode_varint_2(value, int2byte=six.int2byte):
120
+ value = (value << 1) ^ (value >> 63)
121
+
122
+ bits = value & 0x7f
123
+ value >>= 7
124
+ res = b""
125
+ while value:
126
+ res += int2byte(0x80 | bits)
127
+ bits = value & 0x7f
128
+ value >>= 7
129
+ return res + int2byte(bits)
130
+
131
+ _assert_valid_enc(encode_varint_2)
132
+
133
+
134
+ def encode_varint_3(value, buf):
135
+ append = buf.append
136
+ value = (value << 1) ^ (value >> 63)
137
+
138
+ bits = value & 0x7f
139
+ value >>= 7
140
+ while value:
141
+ append(0x80 | bits)
142
+ bits = value & 0x7f
143
+ value >>= 7
144
+ append(bits)
145
+ return value
146
+
147
+
148
+ for encoded, decoded in test_data:
149
+ res = bytearray()
150
+ encode_varint_3(decoded, res)
151
+ assert res == encoded
152
+
153
+
154
+ def encode_varint_4(value, int2byte=six.int2byte):
155
+ value = (value << 1) ^ (value >> 63)
156
+
157
+ if value <= 0x7f: # 1 byte
158
+ return int2byte(value)
159
+ if value <= 0x3fff: # 2 bytes
160
+ return int2byte(0x80 | (value & 0x7f)) + int2byte(value >> 7)
161
+ if value <= 0x1fffff: # 3 bytes
162
+ return int2byte(0x80 | (value & 0x7f)) + \
163
+ int2byte(0x80 | ((value >> 7) & 0x7f)) + \
164
+ int2byte(value >> 14)
165
+ if value <= 0xfffffff: # 4 bytes
166
+ return int2byte(0x80 | (value & 0x7f)) + \
167
+ int2byte(0x80 | ((value >> 7) & 0x7f)) + \
168
+ int2byte(0x80 | ((value >> 14) & 0x7f)) + \
169
+ int2byte(value >> 21)
170
+ if value <= 0x7ffffffff: # 5 bytes
171
+ return int2byte(0x80 | (value & 0x7f)) + \
172
+ int2byte(0x80 | ((value >> 7) & 0x7f)) + \
173
+ int2byte(0x80 | ((value >> 14) & 0x7f)) + \
174
+ int2byte(0x80 | ((value >> 21) & 0x7f)) + \
175
+ int2byte(value >> 28)
176
+ else:
177
+ # Return to general algorithm
178
+ bits = value & 0x7f
179
+ value >>= 7
180
+ res = b""
181
+ while value:
182
+ res += int2byte(0x80 | bits)
183
+ bits = value & 0x7f
184
+ value >>= 7
185
+ return res + int2byte(bits)
186
+
187
+
188
+ _assert_valid_enc(encode_varint_4)
189
+
190
+ # import dis
191
+ # dis.dis(encode_varint_4)
192
+
193
+
194
+ def encode_varint_5(value, buf, pos=0):
195
+ value = (value << 1) ^ (value >> 63)
196
+
197
+ bits = value & 0x7f
198
+ value >>= 7
199
+ while value:
200
+ buf[pos] = 0x80 | bits
201
+ bits = value & 0x7f
202
+ value >>= 7
203
+ pos += 1
204
+ buf[pos] = bits
205
+ return pos + 1
206
+
207
+ for encoded, decoded in test_data:
208
+ res = bytearray(10)
209
+ written = encode_varint_5(decoded, res)
210
+ assert res[:written] == encoded
211
+
212
+
213
+ def encode_varint_6(value, buf):
214
+ append = buf.append
215
+ value = (value << 1) ^ (value >> 63)
216
+
217
+ if value <= 0x7f: # 1 byte
218
+ append(value)
219
+ return 1
220
+ if value <= 0x3fff: # 2 bytes
221
+ append(0x80 | (value & 0x7f))
222
+ append(value >> 7)
223
+ return 2
224
+ if value <= 0x1fffff: # 3 bytes
225
+ append(0x80 | (value & 0x7f))
226
+ append(0x80 | ((value >> 7) & 0x7f))
227
+ append(value >> 14)
228
+ return 3
229
+ if value <= 0xfffffff: # 4 bytes
230
+ append(0x80 | (value & 0x7f))
231
+ append(0x80 | ((value >> 7) & 0x7f))
232
+ append(0x80 | ((value >> 14) & 0x7f))
233
+ append(value >> 21)
234
+ return 4
235
+ if value <= 0x7ffffffff: # 5 bytes
236
+ append(0x80 | (value & 0x7f))
237
+ append(0x80 | ((value >> 7) & 0x7f))
238
+ append(0x80 | ((value >> 14) & 0x7f))
239
+ append(0x80 | ((value >> 21) & 0x7f))
240
+ append(value >> 28)
241
+ return 5
242
+ else:
243
+ # Return to general algorithm
244
+ bits = value & 0x7f
245
+ value >>= 7
246
+ i = 0
247
+ while value:
248
+ append(0x80 | bits)
249
+ bits = value & 0x7f
250
+ value >>= 7
251
+ i += 1
252
+ append(bits)
253
+ return i
254
+
255
+
256
+ for encoded, decoded in test_data:
257
+ res = bytearray()
258
+ encode_varint_6(decoded, res)
259
+ assert res == encoded
260
+
261
+
262
+ def size_of_varint_1(value):
263
+ """ Number of bytes needed to encode an integer in variable-length format.
264
+ """
265
+ value = (value << 1) ^ (value >> 63)
266
+ res = 0
267
+ while True:
268
+ res += 1
269
+ value = value >> 7
270
+ if value == 0:
271
+ break
272
+ return res
273
+
274
+ _assert_valid_size(size_of_varint_1)
275
+
276
+
277
+ def size_of_varint_2(value):
278
+ """ Number of bytes needed to encode an integer in variable-length format.
279
+ """
280
+ value = (value << 1) ^ (value >> 63)
281
+ if value <= 0x7f:
282
+ return 1
283
+ if value <= 0x3fff:
284
+ return 2
285
+ if value <= 0x1fffff:
286
+ return 3
287
+ if value <= 0xfffffff:
288
+ return 4
289
+ if value <= 0x7ffffffff:
290
+ return 5
291
+ if value <= 0x3ffffffffff:
292
+ return 6
293
+ if value <= 0x1ffffffffffff:
294
+ return 7
295
+ if value <= 0xffffffffffffff:
296
+ return 8
297
+ if value <= 0x7fffffffffffffff:
298
+ return 9
299
+ return 10
300
+
301
+ _assert_valid_size(size_of_varint_2)
302
+
303
+
304
+ if six.PY3:
305
+ def _read_byte(memview, pos):
306
+ """ Read a byte from memoryview as an integer
307
+
308
+ Raises:
309
+ IndexError: if position is out of bounds
310
+ """
311
+ return memview[pos]
312
+ else:
313
+ def _read_byte(memview, pos):
314
+ """ Read a byte from memoryview as an integer
315
+
316
+ Raises:
317
+ IndexError: if position is out of bounds
318
+ """
319
+ return ord(memview[pos])
320
+
321
+
322
+ def decode_varint_1(buffer, pos=0):
323
+ """ Decode an integer from a varint presentation. See
324
+ https://developers.google.com/protocol-buffers/docs/encoding?csw=1#varints
325
+ on how those can be produced.
326
+
327
+ Arguments:
328
+ buffer (bytes-like): any object acceptable by ``memoryview``
329
+ pos (int): optional position to read from
330
+
331
+ Returns:
332
+ (int, int): Decoded int value and next read position
333
+ """
334
+ value = 0
335
+ shift = 0
336
+ memview = memoryview(buffer)
337
+ for i in range(pos, pos + 10):
338
+ try:
339
+ byte = _read_byte(memview, i)
340
+ except IndexError:
341
+ raise ValueError("End of byte stream")
342
+ if byte & 0x80 != 0:
343
+ value |= (byte & 0x7f) << shift
344
+ shift += 7
345
+ else:
346
+ value |= byte << shift
347
+ break
348
+ else:
349
+ # Max size of endcoded double is 10 bytes for unsigned values
350
+ raise ValueError("Out of double range")
351
+ # Normalize sign
352
+ return (value >> 1) ^ -(value & 1), i + 1
353
+
354
+ _assert_valid_dec(decode_varint_1)
355
+
356
+
357
+ def decode_varint_2(buffer, pos=0):
358
+ result = 0
359
+ shift = 0
360
+ while 1:
361
+ b = buffer[pos]
362
+ result |= ((b & 0x7f) << shift)
363
+ pos += 1
364
+ if not (b & 0x80):
365
+ # result = result_type(() & mask)
366
+ return ((result >> 1) ^ -(result & 1), pos)
367
+ shift += 7
368
+ if shift >= 64:
369
+ raise ValueError("Out of int64 range")
370
+
371
+
372
+ _assert_valid_dec(decode_varint_2)
373
+
374
+
375
+ def decode_varint_3(buffer, pos=0):
376
+ result = buffer[pos]
377
+ if not (result & 0x81):
378
+ return (result >> 1), pos + 1
379
+ if not (result & 0x80):
380
+ return (result >> 1) ^ (~0), pos + 1
381
+
382
+ result &= 0x7f
383
+ pos += 1
384
+ shift = 7
385
+ while 1:
386
+ b = buffer[pos]
387
+ result |= ((b & 0x7f) << shift)
388
+ pos += 1
389
+ if not (b & 0x80):
390
+ return ((result >> 1) ^ -(result & 1), pos)
391
+ shift += 7
392
+ if shift >= 64:
393
+ raise ValueError("Out of int64 range")
394
+
395
+
396
+ _assert_valid_dec(decode_varint_3)
397
+
398
+ # import dis
399
+ # dis.dis(decode_varint_3)
400
+
401
+ runner = pyperf.Runner()
402
+ # Encode algorithms returning a bytes result
403
+ for bench_func in [
404
+ encode_varint_1,
405
+ encode_varint_2,
406
+ encode_varint_4]:
407
+ for i, value in enumerate(BENCH_VALUES_ENC):
408
+ runner.bench_func(
409
+ '{}_{}byte'.format(bench_func.__name__, i + 1),
410
+ bench_func, value)
411
+
412
+ # Encode algorithms writing to the buffer
413
+ for bench_func in [
414
+ encode_varint_3,
415
+ encode_varint_5,
416
+ encode_varint_6]:
417
+ for i, value in enumerate(BENCH_VALUES_ENC):
418
+ fname = bench_func.__name__
419
+ runner.timeit(
420
+ '{}_{}byte'.format(fname, i + 1),
421
+ stmt="{}({}, buffer)".format(fname, value),
422
+ setup="from __main__ import {}; buffer = bytearray(10)".format(
423
+ fname)
424
+ )
425
+
426
+ # Size algorithms
427
+ for bench_func in [
428
+ size_of_varint_1,
429
+ size_of_varint_2]:
430
+ for i, value in enumerate(BENCH_VALUES_ENC):
431
+ runner.bench_func(
432
+ '{}_{}byte'.format(bench_func.__name__, i + 1),
433
+ bench_func, value)
434
+
435
+ # Decode algorithms
436
+ for bench_func in [
437
+ decode_varint_1,
438
+ decode_varint_2,
439
+ decode_varint_3]:
440
+ for i, value in enumerate(BENCH_VALUES_DEC):
441
+ runner.bench_func(
442
+ '{}_{}byte'.format(bench_func.__name__, i + 1),
443
+ bench_func, value)
testbed/dpkp__kafka-python/build_integration.sh ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ : ${ALL_RELEASES:="0.8.2.2 0.9.0.1 0.10.1.1 0.10.2.2 0.11.0.3 1.0.2 1.1.1 2.0.1 2.1.1 2.2.1 2.3.0 2.4.0 2.5.0"}
4
+ : ${SCALA_VERSION:=2.11}
5
+ : ${DIST_BASE_URL:=https://archive.apache.org/dist/kafka/}
6
+ : ${KAFKA_SRC_GIT:=https://github.com/apache/kafka.git}
7
+
8
+ # On travis CI, empty KAFKA_VERSION means skip integration tests
9
+ # so we don't try to get binaries
10
+ # Otherwise it means test all official releases, so we get all of them!
11
+ if [ -z "$KAFKA_VERSION" -a -z "$TRAVIS" ]; then
12
+ KAFKA_VERSION=$ALL_RELEASES
13
+ fi
14
+
15
+ pushd servers
16
+ mkdir -p dist
17
+ pushd dist
18
+ for kafka in $KAFKA_VERSION; do
19
+ if [ "$kafka" == "trunk" ]; then
20
+ if [ ! -d "$kafka" ]; then
21
+ git clone $KAFKA_SRC_GIT $kafka
22
+ fi
23
+ pushd $kafka
24
+ git pull
25
+ ./gradlew -PscalaVersion=$SCALA_VERSION -Pversion=$kafka releaseTarGz -x signArchives
26
+ popd
27
+ # Not sure how to construct the .tgz name accurately, so use a wildcard (ugh)
28
+ tar xzvf $kafka/core/build/distributions/kafka_*.tgz -C ../$kafka/
29
+ rm $kafka/core/build/distributions/kafka_*.tgz
30
+ rm -rf ../$kafka/kafka-bin
31
+ mv ../$kafka/kafka_* ../$kafka/kafka-bin
32
+ else
33
+ echo "-------------------------------------"
34
+ echo "Checking kafka binaries for ${kafka}"
35
+ echo
36
+ if [ "$kafka" == "0.8.0" ]; then
37
+ KAFKA_ARTIFACT="kafka_2.8.0-${kafka}.tar.gz"
38
+ else if [ "$kafka" \> "2.4.0" ]; then
39
+ KAFKA_ARTIFACT="kafka_2.12-${kafka}.tgz"
40
+ else
41
+ KAFKA_ARTIFACT="kafka_${SCALA_VERSION}-${kafka}.tgz"
42
+ fi
43
+ fi
44
+ if [ ! -f "../$kafka/kafka-bin/bin/kafka-run-class.sh" ]; then
45
+ if [ -f "${KAFKA_ARTIFACT}" ]; then
46
+ echo "Using cached artifact: ${KAFKA_ARTIFACT}"
47
+ else
48
+ echo "Downloading kafka ${kafka} tarball"
49
+ TARBALL=${DIST_BASE_URL}${kafka}/${KAFKA_ARTIFACT}
50
+ if command -v wget 2>/dev/null; then
51
+ wget -N $TARBALL
52
+ else
53
+ echo "wget not found... using curl"
54
+ curl -f $TARBALL -o ${KAFKA_ARTIFACT}
55
+ fi
56
+ fi
57
+ echo
58
+ echo "Extracting kafka ${kafka} binaries"
59
+ tar xzvf ${KAFKA_ARTIFACT} -C ../$kafka/
60
+ rm -rf ../$kafka/kafka-bin
61
+ mv ../$kafka/${KAFKA_ARTIFACT/%.t*/} ../$kafka/kafka-bin
62
+ if [ ! -f "../$kafka/kafka-bin/bin/kafka-run-class.sh" ]; then
63
+ echo "Extraction Failed ($kafka/kafka-bin/bin/kafka-run-class.sh does not exist)!"
64
+ exit 1
65
+ fi
66
+ else
67
+ echo "$kafka is already installed in servers/$kafka/ -- skipping"
68
+ fi
69
+ fi
70
+ echo
71
+ done
72
+ popd
73
+ popd
testbed/dpkp__kafka-python/example.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ import threading, time
3
+
4
+ from kafka import KafkaAdminClient, KafkaConsumer, KafkaProducer
5
+ from kafka.admin import NewTopic
6
+
7
+
8
+ class Producer(threading.Thread):
9
+ def __init__(self):
10
+ threading.Thread.__init__(self)
11
+ self.stop_event = threading.Event()
12
+
13
+ def stop(self):
14
+ self.stop_event.set()
15
+
16
+ def run(self):
17
+ producer = KafkaProducer(bootstrap_servers='localhost:9092')
18
+
19
+ while not self.stop_event.is_set():
20
+ producer.send('my-topic', b"test")
21
+ producer.send('my-topic', b"\xc2Hola, mundo!")
22
+ time.sleep(1)
23
+
24
+ producer.close()
25
+
26
+
27
+ class Consumer(threading.Thread):
28
+ def __init__(self):
29
+ threading.Thread.__init__(self)
30
+ self.stop_event = threading.Event()
31
+
32
+ def stop(self):
33
+ self.stop_event.set()
34
+
35
+ def run(self):
36
+ consumer = KafkaConsumer(bootstrap_servers='localhost:9092',
37
+ auto_offset_reset='earliest',
38
+ consumer_timeout_ms=1000)
39
+ consumer.subscribe(['my-topic'])
40
+
41
+ while not self.stop_event.is_set():
42
+ for message in consumer:
43
+ print(message)
44
+ if self.stop_event.is_set():
45
+ break
46
+
47
+ consumer.close()
48
+
49
+
50
+ def main():
51
+ # Create 'my-topic' Kafka topic
52
+ try:
53
+ admin = KafkaAdminClient(bootstrap_servers='localhost:9092')
54
+
55
+ topic = NewTopic(name='my-topic',
56
+ num_partitions=1,
57
+ replication_factor=1)
58
+ admin.create_topics([topic])
59
+ except Exception:
60
+ pass
61
+
62
+ tasks = [
63
+ Producer(),
64
+ Consumer()
65
+ ]
66
+
67
+ # Start threads of a publisher/producer and a subscriber/consumer to 'my-topic' Kafka topic
68
+ for t in tasks:
69
+ t.start()
70
+
71
+ time.sleep(10)
72
+
73
+ # Stop threads
74
+ for task in tasks:
75
+ task.stop()
76
+
77
+ for task in tasks:
78
+ task.join()
79
+
80
+
81
+ if __name__ == "__main__":
82
+ main()
testbed/dpkp__kafka-python/kafka/__init__.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+
3
+ __title__ = 'kafka'
4
+ from kafka.version import __version__
5
+ __author__ = 'Dana Powers'
6
+ __license__ = 'Apache License 2.0'
7
+ __copyright__ = 'Copyright 2016 Dana Powers, David Arthur, and Contributors'
8
+
9
+ # Set default logging handler to avoid "No handler found" warnings.
10
+ import logging
11
+ try: # Python 2.7+
12
+ from logging import NullHandler
13
+ except ImportError:
14
+ class NullHandler(logging.Handler):
15
+ def emit(self, record):
16
+ pass
17
+
18
+ logging.getLogger(__name__).addHandler(NullHandler())
19
+
20
+
21
+ from kafka.admin import KafkaAdminClient
22
+ from kafka.client_async import KafkaClient
23
+ from kafka.consumer import KafkaConsumer
24
+ from kafka.consumer.subscription_state import ConsumerRebalanceListener
25
+ from kafka.producer import KafkaProducer
26
+ from kafka.conn import BrokerConnection
27
+ from kafka.serializer import Serializer, Deserializer
28
+ from kafka.structs import TopicPartition, OffsetAndMetadata
29
+
30
+
31
+ __all__ = [
32
+ 'BrokerConnection', 'ConsumerRebalanceListener', 'KafkaAdminClient',
33
+ 'KafkaClient', 'KafkaConsumer', 'KafkaProducer',
34
+ ]
testbed/dpkp__kafka-python/kafka/admin/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+
3
+ from kafka.admin.config_resource import ConfigResource, ConfigResourceType
4
+ from kafka.admin.client import KafkaAdminClient
5
+ from kafka.admin.acl_resource import (ACL, ACLFilter, ResourcePattern, ResourcePatternFilter, ACLOperation,
6
+ ResourceType, ACLPermissionType, ACLResourcePatternType)
7
+ from kafka.admin.new_topic import NewTopic
8
+ from kafka.admin.new_partitions import NewPartitions
9
+
10
+ __all__ = [
11
+ 'ConfigResource', 'ConfigResourceType', 'KafkaAdminClient', 'NewTopic', 'NewPartitions', 'ACL', 'ACLFilter',
12
+ 'ResourcePattern', 'ResourcePatternFilter', 'ACLOperation', 'ResourceType', 'ACLPermissionType',
13
+ 'ACLResourcePatternType'
14
+ ]
testbed/dpkp__kafka-python/kafka/admin/acl_resource.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+ from kafka.errors import IllegalArgumentError
3
+
4
+ # enum in stdlib as of py3.4
5
+ try:
6
+ from enum import IntEnum # pylint: disable=import-error
7
+ except ImportError:
8
+ # vendored backport module
9
+ from kafka.vendor.enum34 import IntEnum
10
+
11
+
12
+ class ResourceType(IntEnum):
13
+ """Type of kafka resource to set ACL for
14
+
15
+ The ANY value is only valid in a filter context
16
+ """
17
+
18
+ UNKNOWN = 0,
19
+ ANY = 1,
20
+ CLUSTER = 4,
21
+ DELEGATION_TOKEN = 6,
22
+ GROUP = 3,
23
+ TOPIC = 2,
24
+ TRANSACTIONAL_ID = 5
25
+
26
+
27
+ class ACLOperation(IntEnum):
28
+ """Type of operation
29
+
30
+ The ANY value is only valid in a filter context
31
+ """
32
+
33
+ ANY = 1,
34
+ ALL = 2,
35
+ READ = 3,
36
+ WRITE = 4,
37
+ CREATE = 5,
38
+ DELETE = 6,
39
+ ALTER = 7,
40
+ DESCRIBE = 8,
41
+ CLUSTER_ACTION = 9,
42
+ DESCRIBE_CONFIGS = 10,
43
+ ALTER_CONFIGS = 11,
44
+ IDEMPOTENT_WRITE = 12
45
+
46
+
47
+ class ACLPermissionType(IntEnum):
48
+ """An enumerated type of permissions
49
+
50
+ The ANY value is only valid in a filter context
51
+ """
52
+
53
+ ANY = 1,
54
+ DENY = 2,
55
+ ALLOW = 3
56
+
57
+
58
+ class ACLResourcePatternType(IntEnum):
59
+ """An enumerated type of resource patterns
60
+
61
+ More details on the pattern types and how they work
62
+ can be found in KIP-290 (Support for prefixed ACLs)
63
+ https://cwiki.apache.org/confluence/display/KAFKA/KIP-290%3A+Support+for+Prefixed+ACLs
64
+ """
65
+
66
+ ANY = 1,
67
+ MATCH = 2,
68
+ LITERAL = 3,
69
+ PREFIXED = 4
70
+
71
+
72
+ class ACLFilter(object):
73
+ """Represents a filter to use with describing and deleting ACLs
74
+
75
+ The difference between this class and the ACL class is mainly that
76
+ we allow using ANY with the operation, permission, and resource type objects
77
+ to fetch ALCs matching any of the properties.
78
+
79
+ To make a filter matching any principal, set principal to None
80
+ """
81
+
82
+ def __init__(
83
+ self,
84
+ principal,
85
+ host,
86
+ operation,
87
+ permission_type,
88
+ resource_pattern
89
+ ):
90
+ self.principal = principal
91
+ self.host = host
92
+ self.operation = operation
93
+ self.permission_type = permission_type
94
+ self.resource_pattern = resource_pattern
95
+
96
+ self.validate()
97
+
98
+ def validate(self):
99
+ if not isinstance(self.operation, ACLOperation):
100
+ raise IllegalArgumentError("operation must be an ACLOperation object, and cannot be ANY")
101
+ if not isinstance(self.permission_type, ACLPermissionType):
102
+ raise IllegalArgumentError("permission_type must be an ACLPermissionType object, and cannot be ANY")
103
+ if not isinstance(self.resource_pattern, ResourcePatternFilter):
104
+ raise IllegalArgumentError("resource_pattern must be a ResourcePatternFilter object")
105
+
106
+ def __repr__(self):
107
+ return "<ACL principal={principal}, resource={resource}, operation={operation}, type={type}, host={host}>".format(
108
+ principal=self.principal,
109
+ host=self.host,
110
+ operation=self.operation.name,
111
+ type=self.permission_type.name,
112
+ resource=self.resource_pattern
113
+ )
114
+
115
+ def __eq__(self, other):
116
+ return all((
117
+ self.principal == other.principal,
118
+ self.host == other.host,
119
+ self.operation == other.operation,
120
+ self.permission_type == other.permission_type,
121
+ self.resource_pattern == other.resource_pattern
122
+ ))
123
+
124
+ def __hash__(self):
125
+ return hash((
126
+ self.principal,
127
+ self.host,
128
+ self.operation,
129
+ self.permission_type,
130
+ self.resource_pattern,
131
+ ))
132
+
133
+
134
+ class ACL(ACLFilter):
135
+ """Represents a concrete ACL for a specific ResourcePattern
136
+
137
+ In kafka an ACL is a 4-tuple of (principal, host, operation, permission_type)
138
+ that limits who can do what on a specific resource (or since KIP-290 a resource pattern)
139
+
140
+ Terminology:
141
+ Principal -> This is the identifier for the user. Depending on the authorization method used (SSL, SASL etc)
142
+ the principal will look different. See http://kafka.apache.org/documentation/#security_authz for details.
143
+ The principal must be on the format "User:<name>" or kafka will treat it as invalid. It's possible to use
144
+ other principal types than "User" if using a custom authorizer for the cluster.
145
+ Host -> This must currently be an IP address. It cannot be a range, and it cannot be a domain name.
146
+ It can be set to "*", which is special cased in kafka to mean "any host"
147
+ Operation -> Which client operation this ACL refers to. Has different meaning depending
148
+ on the resource type the ACL refers to. See https://docs.confluent.io/current/kafka/authorization.html#acl-format
149
+ for a list of which combinations of resource/operation that unlocks which kafka APIs
150
+ Permission Type: Whether this ACL is allowing or denying access
151
+ Resource Pattern -> This is a representation of the resource or resource pattern that the ACL
152
+ refers to. See the ResourcePattern class for details.
153
+
154
+ """
155
+
156
+ def __init__(
157
+ self,
158
+ principal,
159
+ host,
160
+ operation,
161
+ permission_type,
162
+ resource_pattern
163
+ ):
164
+ super(ACL, self).__init__(principal, host, operation, permission_type, resource_pattern)
165
+ self.validate()
166
+
167
+ def validate(self):
168
+ if self.operation == ACLOperation.ANY:
169
+ raise IllegalArgumentError("operation cannot be ANY")
170
+ if self.permission_type == ACLPermissionType.ANY:
171
+ raise IllegalArgumentError("permission_type cannot be ANY")
172
+ if not isinstance(self.resource_pattern, ResourcePattern):
173
+ raise IllegalArgumentError("resource_pattern must be a ResourcePattern object")
174
+
175
+
176
+ class ResourcePatternFilter(object):
177
+ def __init__(
178
+ self,
179
+ resource_type,
180
+ resource_name,
181
+ pattern_type
182
+ ):
183
+ self.resource_type = resource_type
184
+ self.resource_name = resource_name
185
+ self.pattern_type = pattern_type
186
+
187
+ self.validate()
188
+
189
+ def validate(self):
190
+ if not isinstance(self.resource_type, ResourceType):
191
+ raise IllegalArgumentError("resource_type must be a ResourceType object")
192
+ if not isinstance(self.pattern_type, ACLResourcePatternType):
193
+ raise IllegalArgumentError("pattern_type must be an ACLResourcePatternType object")
194
+
195
+ def __repr__(self):
196
+ return "<ResourcePattern type={}, name={}, pattern={}>".format(
197
+ self.resource_type.name,
198
+ self.resource_name,
199
+ self.pattern_type.name
200
+ )
201
+
202
+ def __eq__(self, other):
203
+ return all((
204
+ self.resource_type == other.resource_type,
205
+ self.resource_name == other.resource_name,
206
+ self.pattern_type == other.pattern_type,
207
+ ))
208
+
209
+ def __hash__(self):
210
+ return hash((
211
+ self.resource_type,
212
+ self.resource_name,
213
+ self.pattern_type
214
+ ))
215
+
216
+
217
+ class ResourcePattern(ResourcePatternFilter):
218
+ """A resource pattern to apply the ACL to
219
+
220
+ Resource patterns are used to be able to specify which resources an ACL
221
+ describes in a more flexible way than just pointing to a literal topic name for example.
222
+ Since KIP-290 (kafka 2.0) it's possible to set an ACL for a prefixed resource name, which
223
+ can cut down considerably on the number of ACLs needed when the number of topics and
224
+ consumer groups start to grow.
225
+ The default pattern_type is LITERAL, and it describes a specific resource. This is also how
226
+ ACLs worked before the introduction of prefixed ACLs
227
+ """
228
+
229
+ def __init__(
230
+ self,
231
+ resource_type,
232
+ resource_name,
233
+ pattern_type=ACLResourcePatternType.LITERAL
234
+ ):
235
+ super(ResourcePattern, self).__init__(resource_type, resource_name, pattern_type)
236
+ self.validate()
237
+
238
+ def validate(self):
239
+ if self.resource_type == ResourceType.ANY:
240
+ raise IllegalArgumentError("resource_type cannot be ANY")
241
+ if self.pattern_type in [ACLResourcePatternType.ANY, ACLResourcePatternType.MATCH]:
242
+ raise IllegalArgumentError(
243
+ "pattern_type cannot be {} on a concrete ResourcePattern".format(self.pattern_type.name)
244
+ )
testbed/dpkp__kafka-python/kafka/admin/client.py ADDED
@@ -0,0 +1,1342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+
3
+ from collections import defaultdict
4
+ import copy
5
+ import logging
6
+ import socket
7
+
8
+ from . import ConfigResourceType
9
+ from kafka.vendor import six
10
+
11
+ from kafka.admin.acl_resource import ACLOperation, ACLPermissionType, ACLFilter, ACL, ResourcePattern, ResourceType, \
12
+ ACLResourcePatternType
13
+ from kafka.client_async import KafkaClient, selectors
14
+ from kafka.coordinator.protocol import ConsumerProtocolMemberMetadata, ConsumerProtocolMemberAssignment, ConsumerProtocol
15
+ import kafka.errors as Errors
16
+ from kafka.errors import (
17
+ IncompatibleBrokerVersion, KafkaConfigurationError, NotControllerError,
18
+ UnrecognizedBrokerVersion, IllegalArgumentError)
19
+ from kafka.metrics import MetricConfig, Metrics
20
+ from kafka.protocol.admin import (
21
+ CreateTopicsRequest, DeleteTopicsRequest, DescribeConfigsRequest, AlterConfigsRequest, CreatePartitionsRequest,
22
+ ListGroupsRequest, DescribeGroupsRequest, DescribeAclsRequest, CreateAclsRequest, DeleteAclsRequest,
23
+ DeleteGroupsRequest
24
+ )
25
+ from kafka.protocol.commit import GroupCoordinatorRequest, OffsetFetchRequest
26
+ from kafka.protocol.metadata import MetadataRequest
27
+ from kafka.protocol.types import Array
28
+ from kafka.structs import TopicPartition, OffsetAndMetadata, MemberInformation, GroupInformation
29
+ from kafka.version import __version__
30
+
31
+
32
+ log = logging.getLogger(__name__)
33
+
34
+
35
+ class KafkaAdminClient(object):
36
+ """A class for administering the Kafka cluster.
37
+
38
+ Warning:
39
+ This is an unstable interface that was recently added and is subject to
40
+ change without warning. In particular, many methods currently return
41
+ raw protocol tuples. In future releases, we plan to make these into
42
+ nicer, more pythonic objects. Unfortunately, this will likely break
43
+ those interfaces.
44
+
45
+ The KafkaAdminClient class will negotiate for the latest version of each message
46
+ protocol format supported by both the kafka-python client library and the
47
+ Kafka broker. Usage of optional fields from protocol versions that are not
48
+ supported by the broker will result in IncompatibleBrokerVersion exceptions.
49
+
50
+ Use of this class requires a minimum broker version >= 0.10.0.0.
51
+
52
+ Keyword Arguments:
53
+ bootstrap_servers: 'host[:port]' string (or list of 'host[:port]'
54
+ strings) that the consumer should contact to bootstrap initial
55
+ cluster metadata. This does not have to be the full node list.
56
+ It just needs to have at least one broker that will respond to a
57
+ Metadata API Request. Default port is 9092. If no servers are
58
+ specified, will default to localhost:9092.
59
+ client_id (str): a name for this client. This string is passed in
60
+ each request to servers and can be used to identify specific
61
+ server-side log entries that correspond to this client. Also
62
+ submitted to GroupCoordinator for logging with respect to
63
+ consumer group administration. Default: 'kafka-python-{version}'
64
+ reconnect_backoff_ms (int): The amount of time in milliseconds to
65
+ wait before attempting to reconnect to a given host.
66
+ Default: 50.
67
+ reconnect_backoff_max_ms (int): The maximum amount of time in
68
+ milliseconds to backoff/wait when reconnecting to a broker that has
69
+ repeatedly failed to connect. If provided, the backoff per host
70
+ will increase exponentially for each consecutive connection
71
+ failure, up to this maximum. Once the maximum is reached,
72
+ reconnection attempts will continue periodically with this fixed
73
+ rate. To avoid connection storms, a randomization factor of 0.2
74
+ will be applied to the backoff resulting in a random range between
75
+ 20% below and 20% above the computed value. Default: 1000.
76
+ request_timeout_ms (int): Client request timeout in milliseconds.
77
+ Default: 30000.
78
+ connections_max_idle_ms: Close idle connections after the number of
79
+ milliseconds specified by this config. The broker closes idle
80
+ connections after connections.max.idle.ms, so this avoids hitting
81
+ unexpected socket disconnected errors on the client.
82
+ Default: 540000
83
+ retry_backoff_ms (int): Milliseconds to backoff when retrying on
84
+ errors. Default: 100.
85
+ max_in_flight_requests_per_connection (int): Requests are pipelined
86
+ to kafka brokers up to this number of maximum requests per
87
+ broker connection. Default: 5.
88
+ receive_buffer_bytes (int): The size of the TCP receive buffer
89
+ (SO_RCVBUF) to use when reading data. Default: None (relies on
90
+ system defaults). Java client defaults to 32768.
91
+ send_buffer_bytes (int): The size of the TCP send buffer
92
+ (SO_SNDBUF) to use when sending data. Default: None (relies on
93
+ system defaults). Java client defaults to 131072.
94
+ socket_options (list): List of tuple-arguments to socket.setsockopt
95
+ to apply to broker connection sockets. Default:
96
+ [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]
97
+ metadata_max_age_ms (int): The period of time in milliseconds after
98
+ which we force a refresh of metadata even if we haven't seen any
99
+ partition leadership changes to proactively discover any new
100
+ brokers or partitions. Default: 300000
101
+ security_protocol (str): Protocol used to communicate with brokers.
102
+ Valid values are: PLAINTEXT, SSL, SASL_PLAINTEXT, SASL_SSL.
103
+ Default: PLAINTEXT.
104
+ ssl_context (ssl.SSLContext): Pre-configured SSLContext for wrapping
105
+ socket connections. If provided, all other ssl_* configurations
106
+ will be ignored. Default: None.
107
+ ssl_check_hostname (bool): Flag to configure whether SSL handshake
108
+ should verify that the certificate matches the broker's hostname.
109
+ Default: True.
110
+ ssl_cafile (str): Optional filename of CA file to use in certificate
111
+ verification. Default: None.
112
+ ssl_certfile (str): Optional filename of file in PEM format containing
113
+ the client certificate, as well as any CA certificates needed to
114
+ establish the certificate's authenticity. Default: None.
115
+ ssl_keyfile (str): Optional filename containing the client private key.
116
+ Default: None.
117
+ ssl_password (str): Optional password to be used when loading the
118
+ certificate chain. Default: None.
119
+ ssl_crlfile (str): Optional filename containing the CRL to check for
120
+ certificate expiration. By default, no CRL check is done. When
121
+ providing a file, only the leaf certificate will be checked against
122
+ this CRL. The CRL can only be checked with Python 3.4+ or 2.7.9+.
123
+ Default: None.
124
+ api_version (tuple): Specify which Kafka API version to use. If set
125
+ to None, KafkaClient will attempt to infer the broker version by
126
+ probing various APIs. Example: (0, 10, 2). Default: None
127
+ api_version_auto_timeout_ms (int): number of milliseconds to throw a
128
+ timeout exception from the constructor when checking the broker
129
+ api version. Only applies if api_version is None
130
+ selector (selectors.BaseSelector): Provide a specific selector
131
+ implementation to use for I/O multiplexing.
132
+ Default: selectors.DefaultSelector
133
+ metrics (kafka.metrics.Metrics): Optionally provide a metrics
134
+ instance for capturing network IO stats. Default: None.
135
+ metric_group_prefix (str): Prefix for metric names. Default: ''
136
+ sasl_mechanism (str): Authentication mechanism when security_protocol
137
+ is configured for SASL_PLAINTEXT or SASL_SSL. Valid values are:
138
+ PLAIN, GSSAPI, OAUTHBEARER, SCRAM-SHA-256, SCRAM-SHA-512.
139
+ sasl_plain_username (str): username for sasl PLAIN and SCRAM authentication.
140
+ Required if sasl_mechanism is PLAIN or one of the SCRAM mechanisms.
141
+ sasl_plain_password (str): password for sasl PLAIN and SCRAM authentication.
142
+ Required if sasl_mechanism is PLAIN or one of the SCRAM mechanisms.
143
+ sasl_kerberos_service_name (str): Service name to include in GSSAPI
144
+ sasl mechanism handshake. Default: 'kafka'
145
+ sasl_kerberos_domain_name (str): kerberos domain name to use in GSSAPI
146
+ sasl mechanism handshake. Default: one of bootstrap servers
147
+ sasl_oauth_token_provider (AbstractTokenProvider): OAuthBearer token provider
148
+ instance. (See kafka.oauth.abstract). Default: None
149
+
150
+ """
151
+ DEFAULT_CONFIG = {
152
+ # client configs
153
+ 'bootstrap_servers': 'localhost',
154
+ 'client_id': 'kafka-python-' + __version__,
155
+ 'request_timeout_ms': 30000,
156
+ 'connections_max_idle_ms': 9 * 60 * 1000,
157
+ 'reconnect_backoff_ms': 50,
158
+ 'reconnect_backoff_max_ms': 1000,
159
+ 'max_in_flight_requests_per_connection': 5,
160
+ 'receive_buffer_bytes': None,
161
+ 'send_buffer_bytes': None,
162
+ 'socket_options': [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)],
163
+ 'sock_chunk_bytes': 4096, # undocumented experimental option
164
+ 'sock_chunk_buffer_count': 1000, # undocumented experimental option
165
+ 'retry_backoff_ms': 100,
166
+ 'metadata_max_age_ms': 300000,
167
+ 'security_protocol': 'PLAINTEXT',
168
+ 'ssl_context': None,
169
+ 'ssl_check_hostname': True,
170
+ 'ssl_cafile': None,
171
+ 'ssl_certfile': None,
172
+ 'ssl_keyfile': None,
173
+ 'ssl_password': None,
174
+ 'ssl_crlfile': None,
175
+ 'api_version': None,
176
+ 'api_version_auto_timeout_ms': 2000,
177
+ 'selector': selectors.DefaultSelector,
178
+ 'sasl_mechanism': None,
179
+ 'sasl_plain_username': None,
180
+ 'sasl_plain_password': None,
181
+ 'sasl_kerberos_service_name': 'kafka',
182
+ 'sasl_kerberos_domain_name': None,
183
+ 'sasl_oauth_token_provider': None,
184
+
185
+ # metrics configs
186
+ 'metric_reporters': [],
187
+ 'metrics_num_samples': 2,
188
+ 'metrics_sample_window_ms': 30000,
189
+ }
190
+
191
+ def __init__(self, **configs):
192
+ log.debug("Starting KafkaAdminClient with configuration: %s", configs)
193
+ extra_configs = set(configs).difference(self.DEFAULT_CONFIG)
194
+ if extra_configs:
195
+ raise KafkaConfigurationError("Unrecognized configs: {}".format(extra_configs))
196
+
197
+ self.config = copy.copy(self.DEFAULT_CONFIG)
198
+ self.config.update(configs)
199
+
200
+ # Configure metrics
201
+ metrics_tags = {'client-id': self.config['client_id']}
202
+ metric_config = MetricConfig(samples=self.config['metrics_num_samples'],
203
+ time_window_ms=self.config['metrics_sample_window_ms'],
204
+ tags=metrics_tags)
205
+ reporters = [reporter() for reporter in self.config['metric_reporters']]
206
+ self._metrics = Metrics(metric_config, reporters)
207
+
208
+ self._client = KafkaClient(metrics=self._metrics,
209
+ metric_group_prefix='admin',
210
+ **self.config)
211
+ self._client.check_version(timeout=(self.config['api_version_auto_timeout_ms'] / 1000))
212
+
213
+ # Get auto-discovered version from client if necessary
214
+ if self.config['api_version'] is None:
215
+ self.config['api_version'] = self._client.config['api_version']
216
+
217
+ self._closed = False
218
+ self._refresh_controller_id()
219
+ log.debug("KafkaAdminClient started.")
220
+
221
+ def close(self):
222
+ """Close the KafkaAdminClient connection to the Kafka broker."""
223
+ if not hasattr(self, '_closed') or self._closed:
224
+ log.info("KafkaAdminClient already closed.")
225
+ return
226
+
227
+ self._metrics.close()
228
+ self._client.close()
229
+ self._closed = True
230
+ log.debug("KafkaAdminClient is now closed.")
231
+
232
+ def _matching_api_version(self, operation):
233
+ """Find the latest version of the protocol operation supported by both
234
+ this library and the broker.
235
+
236
+ This resolves to the lesser of either the latest api version this
237
+ library supports, or the max version supported by the broker.
238
+
239
+ :param operation: A list of protocol operation versions from kafka.protocol.
240
+ :return: The max matching version number between client and broker.
241
+ """
242
+ broker_api_versions = self._client.get_api_versions()
243
+ api_key = operation[0].API_KEY
244
+ if broker_api_versions is None or api_key not in broker_api_versions:
245
+ raise IncompatibleBrokerVersion(
246
+ "Kafka broker does not support the '{}' Kafka protocol."
247
+ .format(operation[0].__name__))
248
+ min_version, max_version = broker_api_versions[api_key]
249
+ version = min(len(operation) - 1, max_version)
250
+ if version < min_version:
251
+ # max library version is less than min broker version. Currently,
252
+ # no Kafka versions specify a min msg version. Maybe in the future?
253
+ raise IncompatibleBrokerVersion(
254
+ "No version of the '{}' Kafka protocol is supported by both the client and broker."
255
+ .format(operation[0].__name__))
256
+ return version
257
+
258
+ def _validate_timeout(self, timeout_ms):
259
+ """Validate the timeout is set or use the configuration default.
260
+
261
+ :param timeout_ms: The timeout provided by api call, in milliseconds.
262
+ :return: The timeout to use for the operation.
263
+ """
264
+ return timeout_ms or self.config['request_timeout_ms']
265
+
266
+ def _refresh_controller_id(self):
267
+ """Determine the Kafka cluster controller."""
268
+ version = self._matching_api_version(MetadataRequest)
269
+ if 1 <= version <= 6:
270
+ request = MetadataRequest[version]()
271
+ future = self._send_request_to_node(self._client.least_loaded_node(), request)
272
+
273
+ self._wait_for_futures([future])
274
+
275
+ response = future.value
276
+ controller_id = response.controller_id
277
+ # verify the controller is new enough to support our requests
278
+ controller_version = self._client.check_version(controller_id, timeout=(self.config['api_version_auto_timeout_ms'] / 1000))
279
+ if controller_version < (0, 10, 0):
280
+ raise IncompatibleBrokerVersion(
281
+ "The controller appears to be running Kafka {}. KafkaAdminClient requires brokers >= 0.10.0.0."
282
+ .format(controller_version))
283
+ self._controller_id = controller_id
284
+ else:
285
+ raise UnrecognizedBrokerVersion(
286
+ "Kafka Admin interface cannot determine the controller using MetadataRequest_v{}."
287
+ .format(version))
288
+
289
+ def _find_coordinator_id_send_request(self, group_id):
290
+ """Send a FindCoordinatorRequest to a broker.
291
+
292
+ :param group_id: The consumer group ID. This is typically the group
293
+ name as a string.
294
+ :return: A message future
295
+ """
296
+ # TODO add support for dynamically picking version of
297
+ # GroupCoordinatorRequest which was renamed to FindCoordinatorRequest.
298
+ # When I experimented with this, the coordinator value returned in
299
+ # GroupCoordinatorResponse_v1 didn't match the value returned by
300
+ # GroupCoordinatorResponse_v0 and I couldn't figure out why.
301
+ version = 0
302
+ # version = self._matching_api_version(GroupCoordinatorRequest)
303
+ if version <= 0:
304
+ request = GroupCoordinatorRequest[version](group_id)
305
+ else:
306
+ raise NotImplementedError(
307
+ "Support for GroupCoordinatorRequest_v{} has not yet been added to KafkaAdminClient."
308
+ .format(version))
309
+ return self._send_request_to_node(self._client.least_loaded_node(), request)
310
+
311
+ def _find_coordinator_id_process_response(self, response):
312
+ """Process a FindCoordinatorResponse.
313
+
314
+ :param response: a FindCoordinatorResponse.
315
+ :return: The node_id of the broker that is the coordinator.
316
+ """
317
+ if response.API_VERSION <= 0:
318
+ error_type = Errors.for_code(response.error_code)
319
+ if error_type is not Errors.NoError:
320
+ # Note: When error_type.retriable, Java will retry... see
321
+ # KafkaAdminClient's handleFindCoordinatorError method
322
+ raise error_type(
323
+ "FindCoordinatorRequest failed with response '{}'."
324
+ .format(response))
325
+ else:
326
+ raise NotImplementedError(
327
+ "Support for FindCoordinatorRequest_v{} has not yet been added to KafkaAdminClient."
328
+ .format(response.API_VERSION))
329
+ return response.coordinator_id
330
+
331
+ def _find_coordinator_ids(self, group_ids):
332
+ """Find the broker node_ids of the coordinators of the given groups.
333
+
334
+ Sends a FindCoordinatorRequest message to the cluster for each group_id.
335
+ Will block until the FindCoordinatorResponse is received for all groups.
336
+ Any errors are immediately raised.
337
+
338
+ :param group_ids: A list of consumer group IDs. This is typically the group
339
+ name as a string.
340
+ :return: A dict of {group_id: node_id} where node_id is the id of the
341
+ broker that is the coordinator for the corresponding group.
342
+ """
343
+ groups_futures = {
344
+ group_id: self._find_coordinator_id_send_request(group_id)
345
+ for group_id in group_ids
346
+ }
347
+ self._wait_for_futures(groups_futures.values())
348
+ groups_coordinators = {
349
+ group_id: self._find_coordinator_id_process_response(future.value)
350
+ for group_id, future in groups_futures.items()
351
+ }
352
+ return groups_coordinators
353
+
354
+ def _send_request_to_node(self, node_id, request):
355
+ """Send a Kafka protocol message to a specific broker.
356
+
357
+ Returns a future that may be polled for status and results.
358
+
359
+ :param node_id: The broker id to which to send the message.
360
+ :param request: The message to send.
361
+ :return: A future object that may be polled for status and results.
362
+ :exception: The exception if the message could not be sent.
363
+ """
364
+ while not self._client.ready(node_id):
365
+ # poll until the connection to broker is ready, otherwise send()
366
+ # will fail with NodeNotReadyError
367
+ self._client.poll()
368
+ return self._client.send(node_id, request)
369
+
370
+ def _send_request_to_controller(self, request):
371
+ """Send a Kafka protocol message to the cluster controller.
372
+
373
+ Will block until the message result is received.
374
+
375
+ :param request: The message to send.
376
+ :return: The Kafka protocol response for the message.
377
+ """
378
+ tries = 2 # in case our cached self._controller_id is outdated
379
+ while tries:
380
+ tries -= 1
381
+ future = self._send_request_to_node(self._controller_id, request)
382
+
383
+ self._wait_for_futures([future])
384
+
385
+ response = future.value
386
+ # In Java, the error field name is inconsistent:
387
+ # - CreateTopicsResponse / CreatePartitionsResponse uses topic_errors
388
+ # - DeleteTopicsResponse uses topic_error_codes
389
+ # So this is a little brittle in that it assumes all responses have
390
+ # one of these attributes and that they always unpack into
391
+ # (topic, error_code) tuples.
392
+ topic_error_tuples = (response.topic_errors if hasattr(response, 'topic_errors')
393
+ else response.topic_error_codes)
394
+ # Also small py2/py3 compatibility -- py3 can ignore extra values
395
+ # during unpack via: for x, y, *rest in list_of_values. py2 cannot.
396
+ # So for now we have to map across the list and explicitly drop any
397
+ # extra values (usually the error_message)
398
+ for topic, error_code in map(lambda e: e[:2], topic_error_tuples):
399
+ error_type = Errors.for_code(error_code)
400
+ if tries and error_type is NotControllerError:
401
+ # No need to inspect the rest of the errors for
402
+ # non-retriable errors because NotControllerError should
403
+ # either be thrown for all errors or no errors.
404
+ self._refresh_controller_id()
405
+ break
406
+ elif error_type is not Errors.NoError:
407
+ raise error_type(
408
+ "Request '{}' failed with response '{}'."
409
+ .format(request, response))
410
+ else:
411
+ return response
412
+ raise RuntimeError("This should never happen, please file a bug with full stacktrace if encountered")
413
+
414
+ @staticmethod
415
+ def _convert_new_topic_request(new_topic):
416
+ return (
417
+ new_topic.name,
418
+ new_topic.num_partitions,
419
+ new_topic.replication_factor,
420
+ [
421
+ (partition_id, replicas) for partition_id, replicas in new_topic.replica_assignments.items()
422
+ ],
423
+ [
424
+ (config_key, config_value) for config_key, config_value in new_topic.topic_configs.items()
425
+ ]
426
+ )
427
+
428
+ def create_topics(self, new_topics, timeout_ms=None, validate_only=False):
429
+ """Create new topics in the cluster.
430
+
431
+ :param new_topics: A list of NewTopic objects.
432
+ :param timeout_ms: Milliseconds to wait for new topics to be created
433
+ before the broker returns.
434
+ :param validate_only: If True, don't actually create new topics.
435
+ Not supported by all versions. Default: False
436
+ :return: Appropriate version of CreateTopicResponse class.
437
+ """
438
+ version = self._matching_api_version(CreateTopicsRequest)
439
+ timeout_ms = self._validate_timeout(timeout_ms)
440
+ if version == 0:
441
+ if validate_only:
442
+ raise IncompatibleBrokerVersion(
443
+ "validate_only requires CreateTopicsRequest >= v1, which is not supported by Kafka {}."
444
+ .format(self.config['api_version']))
445
+ request = CreateTopicsRequest[version](
446
+ create_topic_requests=[self._convert_new_topic_request(new_topic) for new_topic in new_topics],
447
+ timeout=timeout_ms
448
+ )
449
+ elif version <= 3:
450
+ request = CreateTopicsRequest[version](
451
+ create_topic_requests=[self._convert_new_topic_request(new_topic) for new_topic in new_topics],
452
+ timeout=timeout_ms,
453
+ validate_only=validate_only
454
+ )
455
+ else:
456
+ raise NotImplementedError(
457
+ "Support for CreateTopics v{} has not yet been added to KafkaAdminClient."
458
+ .format(version))
459
+ # TODO convert structs to a more pythonic interface
460
+ # TODO raise exceptions if errors
461
+ return self._send_request_to_controller(request)
462
+
463
+ def delete_topics(self, topics, timeout_ms=None):
464
+ """Delete topics from the cluster.
465
+
466
+ :param topics: A list of topic name strings.
467
+ :param timeout_ms: Milliseconds to wait for topics to be deleted
468
+ before the broker returns.
469
+ :return: Appropriate version of DeleteTopicsResponse class.
470
+ """
471
+ version = self._matching_api_version(DeleteTopicsRequest)
472
+ timeout_ms = self._validate_timeout(timeout_ms)
473
+ if version <= 3:
474
+ request = DeleteTopicsRequest[version](
475
+ topics=topics,
476
+ timeout=timeout_ms
477
+ )
478
+ response = self._send_request_to_controller(request)
479
+ else:
480
+ raise NotImplementedError(
481
+ "Support for DeleteTopics v{} has not yet been added to KafkaAdminClient."
482
+ .format(version))
483
+ return response
484
+
485
+
486
+ def _get_cluster_metadata(self, topics=None, auto_topic_creation=False):
487
+ """
488
+ topics == None means "get all topics"
489
+ """
490
+ version = self._matching_api_version(MetadataRequest)
491
+ if version <= 3:
492
+ if auto_topic_creation:
493
+ raise IncompatibleBrokerVersion(
494
+ "auto_topic_creation requires MetadataRequest >= v4, which"
495
+ " is not supported by Kafka {}"
496
+ .format(self.config['api_version']))
497
+
498
+ request = MetadataRequest[version](topics=topics)
499
+ elif version <= 5:
500
+ request = MetadataRequest[version](
501
+ topics=topics,
502
+ allow_auto_topic_creation=auto_topic_creation
503
+ )
504
+
505
+ future = self._send_request_to_node(
506
+ self._client.least_loaded_node(),
507
+ request
508
+ )
509
+ self._wait_for_futures([future])
510
+ return future.value
511
+
512
+ def list_topics(self):
513
+ metadata = self._get_cluster_metadata(topics=None)
514
+ obj = metadata.to_object()
515
+ return [t['topic'] for t in obj['topics']]
516
+
517
+ def describe_topics(self, topics=None):
518
+ metadata = self._get_cluster_metadata(topics=topics)
519
+ obj = metadata.to_object()
520
+ return obj['topics']
521
+
522
+ def describe_cluster(self):
523
+ metadata = self._get_cluster_metadata()
524
+ obj = metadata.to_object()
525
+ obj.pop('topics') # We have 'describe_topics' for this
526
+ return obj
527
+
528
+ @staticmethod
529
+ def _convert_describe_acls_response_to_acls(describe_response):
530
+ version = describe_response.API_VERSION
531
+
532
+ error = Errors.for_code(describe_response.error_code)
533
+ acl_list = []
534
+ for resources in describe_response.resources:
535
+ if version == 0:
536
+ resource_type, resource_name, acls = resources
537
+ resource_pattern_type = ACLResourcePatternType.LITERAL.value
538
+ elif version <= 1:
539
+ resource_type, resource_name, resource_pattern_type, acls = resources
540
+ else:
541
+ raise NotImplementedError(
542
+ "Support for DescribeAcls Response v{} has not yet been added to KafkaAdmin."
543
+ .format(version)
544
+ )
545
+ for acl in acls:
546
+ principal, host, operation, permission_type = acl
547
+ conv_acl = ACL(
548
+ principal=principal,
549
+ host=host,
550
+ operation=ACLOperation(operation),
551
+ permission_type=ACLPermissionType(permission_type),
552
+ resource_pattern=ResourcePattern(
553
+ ResourceType(resource_type),
554
+ resource_name,
555
+ ACLResourcePatternType(resource_pattern_type)
556
+ )
557
+ )
558
+ acl_list.append(conv_acl)
559
+
560
+ return (acl_list, error,)
561
+
562
+ def describe_acls(self, acl_filter):
563
+ """Describe a set of ACLs
564
+
565
+ Used to return a set of ACLs matching the supplied ACLFilter.
566
+ The cluster must be configured with an authorizer for this to work, or
567
+ you will get a SecurityDisabledError
568
+
569
+ :param acl_filter: an ACLFilter object
570
+ :return: tuple of a list of matching ACL objects and a KafkaError (NoError if successful)
571
+ """
572
+
573
+ version = self._matching_api_version(DescribeAclsRequest)
574
+ if version == 0:
575
+ request = DescribeAclsRequest[version](
576
+ resource_type=acl_filter.resource_pattern.resource_type,
577
+ resource_name=acl_filter.resource_pattern.resource_name,
578
+ principal=acl_filter.principal,
579
+ host=acl_filter.host,
580
+ operation=acl_filter.operation,
581
+ permission_type=acl_filter.permission_type
582
+ )
583
+ elif version <= 1:
584
+ request = DescribeAclsRequest[version](
585
+ resource_type=acl_filter.resource_pattern.resource_type,
586
+ resource_name=acl_filter.resource_pattern.resource_name,
587
+ resource_pattern_type_filter=acl_filter.resource_pattern.pattern_type,
588
+ principal=acl_filter.principal,
589
+ host=acl_filter.host,
590
+ operation=acl_filter.operation,
591
+ permission_type=acl_filter.permission_type
592
+
593
+ )
594
+ else:
595
+ raise NotImplementedError(
596
+ "Support for DescribeAcls v{} has not yet been added to KafkaAdmin."
597
+ .format(version)
598
+ )
599
+
600
+ future = self._send_request_to_node(self._client.least_loaded_node(), request)
601
+ self._wait_for_futures([future])
602
+ response = future.value
603
+
604
+ error_type = Errors.for_code(response.error_code)
605
+ if error_type is not Errors.NoError:
606
+ # optionally we could retry if error_type.retriable
607
+ raise error_type(
608
+ "Request '{}' failed with response '{}'."
609
+ .format(request, response))
610
+
611
+ return self._convert_describe_acls_response_to_acls(response)
612
+
613
+ @staticmethod
614
+ def _convert_create_acls_resource_request_v0(acl):
615
+
616
+ return (
617
+ acl.resource_pattern.resource_type,
618
+ acl.resource_pattern.resource_name,
619
+ acl.principal,
620
+ acl.host,
621
+ acl.operation,
622
+ acl.permission_type
623
+ )
624
+
625
+ @staticmethod
626
+ def _convert_create_acls_resource_request_v1(acl):
627
+
628
+ return (
629
+ acl.resource_pattern.resource_type,
630
+ acl.resource_pattern.resource_name,
631
+ acl.resource_pattern.pattern_type,
632
+ acl.principal,
633
+ acl.host,
634
+ acl.operation,
635
+ acl.permission_type
636
+ )
637
+
638
+ @staticmethod
639
+ def _convert_create_acls_response_to_acls(acls, create_response):
640
+ version = create_response.API_VERSION
641
+
642
+ creations_error = []
643
+ creations_success = []
644
+ for i, creations in enumerate(create_response.creation_responses):
645
+ if version <= 1:
646
+ error_code, error_message = creations
647
+ acl = acls[i]
648
+ error = Errors.for_code(error_code)
649
+ else:
650
+ raise NotImplementedError(
651
+ "Support for DescribeAcls Response v{} has not yet been added to KafkaAdmin."
652
+ .format(version)
653
+ )
654
+
655
+ if error is Errors.NoError:
656
+ creations_success.append(acl)
657
+ else:
658
+ creations_error.append((acl, error,))
659
+
660
+ return {"succeeded": creations_success, "failed": creations_error}
661
+
662
+ def create_acls(self, acls):
663
+ """Create a list of ACLs
664
+
665
+ This endpoint only accepts a list of concrete ACL objects, no ACLFilters.
666
+ Throws TopicAlreadyExistsError if topic is already present.
667
+
668
+ :param acls: a list of ACL objects
669
+ :return: dict of successes and failures
670
+ """
671
+
672
+ for acl in acls:
673
+ if not isinstance(acl, ACL):
674
+ raise IllegalArgumentError("acls must contain ACL objects")
675
+
676
+ version = self._matching_api_version(CreateAclsRequest)
677
+ if version == 0:
678
+ request = CreateAclsRequest[version](
679
+ creations=[self._convert_create_acls_resource_request_v0(acl) for acl in acls]
680
+ )
681
+ elif version <= 1:
682
+ request = CreateAclsRequest[version](
683
+ creations=[self._convert_create_acls_resource_request_v1(acl) for acl in acls]
684
+ )
685
+ else:
686
+ raise NotImplementedError(
687
+ "Support for CreateAcls v{} has not yet been added to KafkaAdmin."
688
+ .format(version)
689
+ )
690
+
691
+ future = self._send_request_to_node(self._client.least_loaded_node(), request)
692
+ self._wait_for_futures([future])
693
+ response = future.value
694
+
695
+ return self._convert_create_acls_response_to_acls(acls, response)
696
+
697
+ @staticmethod
698
+ def _convert_delete_acls_resource_request_v0(acl):
699
+ return (
700
+ acl.resource_pattern.resource_type,
701
+ acl.resource_pattern.resource_name,
702
+ acl.principal,
703
+ acl.host,
704
+ acl.operation,
705
+ acl.permission_type
706
+ )
707
+
708
+ @staticmethod
709
+ def _convert_delete_acls_resource_request_v1(acl):
710
+ return (
711
+ acl.resource_pattern.resource_type,
712
+ acl.resource_pattern.resource_name,
713
+ acl.resource_pattern.pattern_type,
714
+ acl.principal,
715
+ acl.host,
716
+ acl.operation,
717
+ acl.permission_type
718
+ )
719
+
720
+ @staticmethod
721
+ def _convert_delete_acls_response_to_matching_acls(acl_filters, delete_response):
722
+ version = delete_response.API_VERSION
723
+ filter_result_list = []
724
+ for i, filter_responses in enumerate(delete_response.filter_responses):
725
+ filter_error_code, filter_error_message, matching_acls = filter_responses
726
+ filter_error = Errors.for_code(filter_error_code)
727
+ acl_result_list = []
728
+ for acl in matching_acls:
729
+ if version == 0:
730
+ error_code, error_message, resource_type, resource_name, principal, host, operation, permission_type = acl
731
+ resource_pattern_type = ACLResourcePatternType.LITERAL.value
732
+ elif version == 1:
733
+ error_code, error_message, resource_type, resource_name, resource_pattern_type, principal, host, operation, permission_type = acl
734
+ else:
735
+ raise NotImplementedError(
736
+ "Support for DescribeAcls Response v{} has not yet been added to KafkaAdmin."
737
+ .format(version)
738
+ )
739
+ acl_error = Errors.for_code(error_code)
740
+ conv_acl = ACL(
741
+ principal=principal,
742
+ host=host,
743
+ operation=ACLOperation(operation),
744
+ permission_type=ACLPermissionType(permission_type),
745
+ resource_pattern=ResourcePattern(
746
+ ResourceType(resource_type),
747
+ resource_name,
748
+ ACLResourcePatternType(resource_pattern_type)
749
+ )
750
+ )
751
+ acl_result_list.append((conv_acl, acl_error,))
752
+ filter_result_list.append((acl_filters[i], acl_result_list, filter_error,))
753
+ return filter_result_list
754
+
755
+ def delete_acls(self, acl_filters):
756
+ """Delete a set of ACLs
757
+
758
+ Deletes all ACLs matching the list of input ACLFilter
759
+
760
+ :param acl_filters: a list of ACLFilter
761
+ :return: a list of 3-tuples corresponding to the list of input filters.
762
+ The tuples hold (the input ACLFilter, list of affected ACLs, KafkaError instance)
763
+ """
764
+
765
+ for acl in acl_filters:
766
+ if not isinstance(acl, ACLFilter):
767
+ raise IllegalArgumentError("acl_filters must contain ACLFilter type objects")
768
+
769
+ version = self._matching_api_version(DeleteAclsRequest)
770
+
771
+ if version == 0:
772
+ request = DeleteAclsRequest[version](
773
+ filters=[self._convert_delete_acls_resource_request_v0(acl) for acl in acl_filters]
774
+ )
775
+ elif version <= 1:
776
+ request = DeleteAclsRequest[version](
777
+ filters=[self._convert_delete_acls_resource_request_v1(acl) for acl in acl_filters]
778
+ )
779
+ else:
780
+ raise NotImplementedError(
781
+ "Support for DeleteAcls v{} has not yet been added to KafkaAdmin."
782
+ .format(version)
783
+ )
784
+
785
+ future = self._send_request_to_node(self._client.least_loaded_node(), request)
786
+ self._wait_for_futures([future])
787
+ response = future.value
788
+
789
+ return self._convert_delete_acls_response_to_matching_acls(acl_filters, response)
790
+
791
+ @staticmethod
792
+ def _convert_describe_config_resource_request(config_resource):
793
+ return (
794
+ config_resource.resource_type,
795
+ config_resource.name,
796
+ [
797
+ config_key for config_key, config_value in config_resource.configs.items()
798
+ ] if config_resource.configs else None
799
+ )
800
+
801
+ def describe_configs(self, config_resources, include_synonyms=False):
802
+ """Fetch configuration parameters for one or more Kafka resources.
803
+
804
+ :param config_resources: An list of ConfigResource objects.
805
+ Any keys in ConfigResource.configs dict will be used to filter the
806
+ result. Setting the configs dict to None will get all values. An
807
+ empty dict will get zero values (as per Kafka protocol).
808
+ :param include_synonyms: If True, return synonyms in response. Not
809
+ supported by all versions. Default: False.
810
+ :return: Appropriate version of DescribeConfigsResponse class.
811
+ """
812
+
813
+ # Break up requests by type - a broker config request must be sent to the specific broker.
814
+ # All other (currently just topic resources) can be sent to any broker.
815
+ broker_resources = []
816
+ topic_resources = []
817
+
818
+ for config_resource in config_resources:
819
+ if config_resource.resource_type == ConfigResourceType.BROKER:
820
+ broker_resources.append(self._convert_describe_config_resource_request(config_resource))
821
+ else:
822
+ topic_resources.append(self._convert_describe_config_resource_request(config_resource))
823
+
824
+ futures = []
825
+ version = self._matching_api_version(DescribeConfigsRequest)
826
+ if version == 0:
827
+ if include_synonyms:
828
+ raise IncompatibleBrokerVersion(
829
+ "include_synonyms requires DescribeConfigsRequest >= v1, which is not supported by Kafka {}."
830
+ .format(self.config['api_version']))
831
+
832
+ if len(broker_resources) > 0:
833
+ for broker_resource in broker_resources:
834
+ try:
835
+ broker_id = int(broker_resource[1])
836
+ except ValueError:
837
+ raise ValueError("Broker resource names must be an integer or a string represented integer")
838
+
839
+ futures.append(self._send_request_to_node(
840
+ broker_id,
841
+ DescribeConfigsRequest[version](resources=[broker_resource])
842
+ ))
843
+
844
+ if len(topic_resources) > 0:
845
+ futures.append(self._send_request_to_node(
846
+ self._client.least_loaded_node(),
847
+ DescribeConfigsRequest[version](resources=topic_resources)
848
+ ))
849
+
850
+ elif version <= 2:
851
+ if len(broker_resources) > 0:
852
+ for broker_resource in broker_resources:
853
+ try:
854
+ broker_id = int(broker_resource[1])
855
+ except ValueError:
856
+ raise ValueError("Broker resource names must be an integer or a string represented integer")
857
+
858
+ futures.append(self._send_request_to_node(
859
+ broker_id,
860
+ DescribeConfigsRequest[version](
861
+ resources=[broker_resource],
862
+ include_synonyms=include_synonyms)
863
+ ))
864
+
865
+ if len(topic_resources) > 0:
866
+ futures.append(self._send_request_to_node(
867
+ self._client.least_loaded_node(),
868
+ DescribeConfigsRequest[version](resources=topic_resources, include_synonyms=include_synonyms)
869
+ ))
870
+ else:
871
+ raise NotImplementedError(
872
+ "Support for DescribeConfigs v{} has not yet been added to KafkaAdminClient.".format(version))
873
+
874
+ self._wait_for_futures(futures)
875
+ return [f.value for f in futures]
876
+
877
+ @staticmethod
878
+ def _convert_alter_config_resource_request(config_resource):
879
+ return (
880
+ config_resource.resource_type,
881
+ config_resource.name,
882
+ [
883
+ (config_key, config_value) for config_key, config_value in config_resource.configs.items()
884
+ ]
885
+ )
886
+
887
+ def alter_configs(self, config_resources):
888
+ """Alter configuration parameters of one or more Kafka resources.
889
+
890
+ Warning:
891
+ This is currently broken for BROKER resources because those must be
892
+ sent to that specific broker, versus this always picks the
893
+ least-loaded node. See the comment in the source code for details.
894
+ We would happily accept a PR fixing this.
895
+
896
+ :param config_resources: A list of ConfigResource objects.
897
+ :return: Appropriate version of AlterConfigsResponse class.
898
+ """
899
+ version = self._matching_api_version(AlterConfigsRequest)
900
+ if version <= 1:
901
+ request = AlterConfigsRequest[version](
902
+ resources=[self._convert_alter_config_resource_request(config_resource) for config_resource in config_resources]
903
+ )
904
+ else:
905
+ raise NotImplementedError(
906
+ "Support for AlterConfigs v{} has not yet been added to KafkaAdminClient."
907
+ .format(version))
908
+ # TODO the Java client has the note:
909
+ # // We must make a separate AlterConfigs request for every BROKER resource we want to alter
910
+ # // and send the request to that specific broker. Other resources are grouped together into
911
+ # // a single request that may be sent to any broker.
912
+ #
913
+ # So this is currently broken as it always sends to the least_loaded_node()
914
+ future = self._send_request_to_node(self._client.least_loaded_node(), request)
915
+
916
+ self._wait_for_futures([future])
917
+ response = future.value
918
+ return response
919
+
920
+ # alter replica logs dir protocol not yet implemented
921
+ # Note: have to lookup the broker with the replica assignment and send the request to that broker
922
+
923
+ # describe log dirs protocol not yet implemented
924
+ # Note: have to lookup the broker with the replica assignment and send the request to that broker
925
+
926
+ @staticmethod
927
+ def _convert_create_partitions_request(topic_name, new_partitions):
928
+ return (
929
+ topic_name,
930
+ (
931
+ new_partitions.total_count,
932
+ new_partitions.new_assignments
933
+ )
934
+ )
935
+
936
+ def create_partitions(self, topic_partitions, timeout_ms=None, validate_only=False):
937
+ """Create additional partitions for an existing topic.
938
+
939
+ :param topic_partitions: A map of topic name strings to NewPartition objects.
940
+ :param timeout_ms: Milliseconds to wait for new partitions to be
941
+ created before the broker returns.
942
+ :param validate_only: If True, don't actually create new partitions.
943
+ Default: False
944
+ :return: Appropriate version of CreatePartitionsResponse class.
945
+ """
946
+ version = self._matching_api_version(CreatePartitionsRequest)
947
+ timeout_ms = self._validate_timeout(timeout_ms)
948
+ if version <= 1:
949
+ request = CreatePartitionsRequest[version](
950
+ topic_partitions=[self._convert_create_partitions_request(topic_name, new_partitions) for topic_name, new_partitions in topic_partitions.items()],
951
+ timeout=timeout_ms,
952
+ validate_only=validate_only
953
+ )
954
+ else:
955
+ raise NotImplementedError(
956
+ "Support for CreatePartitions v{} has not yet been added to KafkaAdminClient."
957
+ .format(version))
958
+ return self._send_request_to_controller(request)
959
+
960
+ # delete records protocol not yet implemented
961
+ # Note: send the request to the partition leaders
962
+
963
+ # create delegation token protocol not yet implemented
964
+ # Note: send the request to the least_loaded_node()
965
+
966
+ # renew delegation token protocol not yet implemented
967
+ # Note: send the request to the least_loaded_node()
968
+
969
+ # expire delegation_token protocol not yet implemented
970
+ # Note: send the request to the least_loaded_node()
971
+
972
+ # describe delegation_token protocol not yet implemented
973
+ # Note: send the request to the least_loaded_node()
974
+
975
+ def _describe_consumer_groups_send_request(self, group_id, group_coordinator_id, include_authorized_operations=False):
976
+ """Send a DescribeGroupsRequest to the group's coordinator.
977
+
978
+ :param group_id: The group name as a string
979
+ :param group_coordinator_id: The node_id of the groups' coordinator
980
+ broker.
981
+ :return: A message future.
982
+ """
983
+ version = self._matching_api_version(DescribeGroupsRequest)
984
+ if version <= 2:
985
+ if include_authorized_operations:
986
+ raise IncompatibleBrokerVersion(
987
+ "include_authorized_operations requests "
988
+ "DescribeGroupsRequest >= v3, which is not "
989
+ "supported by Kafka {}".format(version)
990
+ )
991
+ # Note: KAFKA-6788 A potential optimization is to group the
992
+ # request per coordinator and send one request with a list of
993
+ # all consumer groups. Java still hasn't implemented this
994
+ # because the error checking is hard to get right when some
995
+ # groups error and others don't.
996
+ request = DescribeGroupsRequest[version](groups=(group_id,))
997
+ elif version <= 3:
998
+ request = DescribeGroupsRequest[version](
999
+ groups=(group_id,),
1000
+ include_authorized_operations=include_authorized_operations
1001
+ )
1002
+ else:
1003
+ raise NotImplementedError(
1004
+ "Support for DescribeGroupsRequest_v{} has not yet been added to KafkaAdminClient."
1005
+ .format(version))
1006
+ return self._send_request_to_node(group_coordinator_id, request)
1007
+
1008
+ def _describe_consumer_groups_process_response(self, response):
1009
+ """Process a DescribeGroupsResponse into a group description."""
1010
+ if response.API_VERSION <= 3:
1011
+ assert len(response.groups) == 1
1012
+ for response_field, response_name in zip(response.SCHEMA.fields, response.SCHEMA.names):
1013
+ if isinstance(response_field, Array):
1014
+ described_groups_field_schema = response_field.array_of
1015
+ described_group = response.__dict__[response_name][0]
1016
+ described_group_information_list = []
1017
+ protocol_type_is_consumer = False
1018
+ for (described_group_information, group_information_name, group_information_field) in zip(described_group, described_groups_field_schema.names, described_groups_field_schema.fields):
1019
+ if group_information_name == 'protocol_type':
1020
+ protocol_type = described_group_information
1021
+ protocol_type_is_consumer = (protocol_type == ConsumerProtocol.PROTOCOL_TYPE or not protocol_type)
1022
+ if isinstance(group_information_field, Array):
1023
+ member_information_list = []
1024
+ member_schema = group_information_field.array_of
1025
+ for members in described_group_information:
1026
+ member_information = []
1027
+ for (member, member_field, member_name) in zip(members, member_schema.fields, member_schema.names):
1028
+ if protocol_type_is_consumer:
1029
+ if member_name == 'member_metadata' and member:
1030
+ member_information.append(ConsumerProtocolMemberMetadata.decode(member))
1031
+ elif member_name == 'member_assignment' and member:
1032
+ member_information.append(ConsumerProtocolMemberAssignment.decode(member))
1033
+ else:
1034
+ member_information.append(member)
1035
+ member_info_tuple = MemberInformation._make(member_information)
1036
+ member_information_list.append(member_info_tuple)
1037
+ described_group_information_list.append(member_information_list)
1038
+ else:
1039
+ described_group_information_list.append(described_group_information)
1040
+ # Version 3 of the DescribeGroups API introduced the "authorized_operations" field.
1041
+ # This will cause the namedtuple to fail.
1042
+ # Therefore, appending a placeholder of None in it.
1043
+ if response.API_VERSION <=2:
1044
+ described_group_information_list.append(None)
1045
+ group_description = GroupInformation._make(described_group_information_list)
1046
+ error_code = group_description.error_code
1047
+ error_type = Errors.for_code(error_code)
1048
+ # Java has the note: KAFKA-6789, we can retry based on the error code
1049
+ if error_type is not Errors.NoError:
1050
+ raise error_type(
1051
+ "DescribeGroupsResponse failed with response '{}'."
1052
+ .format(response))
1053
+ else:
1054
+ raise NotImplementedError(
1055
+ "Support for DescribeGroupsResponse_v{} has not yet been added to KafkaAdminClient."
1056
+ .format(response.API_VERSION))
1057
+ return group_description
1058
+
1059
+ def describe_consumer_groups(self, group_ids, group_coordinator_id=None, include_authorized_operations=False):
1060
+ """Describe a set of consumer groups.
1061
+
1062
+ Any errors are immediately raised.
1063
+
1064
+ :param group_ids: A list of consumer group IDs. These are typically the
1065
+ group names as strings.
1066
+ :param group_coordinator_id: The node_id of the groups' coordinator
1067
+ broker. If set to None, it will query the cluster for each group to
1068
+ find that group's coordinator. Explicitly specifying this can be
1069
+ useful for avoiding extra network round trips if you already know
1070
+ the group coordinator. This is only useful when all the group_ids
1071
+ have the same coordinator, otherwise it will error. Default: None.
1072
+ :param include_authorized_operations: Whether or not to include
1073
+ information about the operations a group is allowed to perform.
1074
+ Only supported on API version >= v3. Default: False.
1075
+ :return: A list of group descriptions. For now the group descriptions
1076
+ are the raw results from the DescribeGroupsResponse. Long-term, we
1077
+ plan to change this to return namedtuples as well as decoding the
1078
+ partition assignments.
1079
+ """
1080
+ group_descriptions = []
1081
+
1082
+ if group_coordinator_id is not None:
1083
+ groups_coordinators = {group_id: group_coordinator_id for group_id in group_ids}
1084
+ else:
1085
+ groups_coordinators = self._find_coordinator_ids(group_ids)
1086
+
1087
+ futures = [
1088
+ self._describe_consumer_groups_send_request(
1089
+ group_id,
1090
+ coordinator_id,
1091
+ include_authorized_operations)
1092
+ for group_id, coordinator_id in groups_coordinators.items()
1093
+ ]
1094
+ self._wait_for_futures(futures)
1095
+
1096
+ for future in futures:
1097
+ response = future.value
1098
+ group_description = self._describe_consumer_groups_process_response(response)
1099
+ group_descriptions.append(group_description)
1100
+
1101
+ return group_descriptions
1102
+
1103
+ def _list_consumer_groups_send_request(self, broker_id):
1104
+ """Send a ListGroupsRequest to a broker.
1105
+
1106
+ :param broker_id: The broker's node_id.
1107
+ :return: A message future
1108
+ """
1109
+ version = self._matching_api_version(ListGroupsRequest)
1110
+ if version <= 2:
1111
+ request = ListGroupsRequest[version]()
1112
+ else:
1113
+ raise NotImplementedError(
1114
+ "Support for ListGroupsRequest_v{} has not yet been added to KafkaAdminClient."
1115
+ .format(version))
1116
+ return self._send_request_to_node(broker_id, request)
1117
+
1118
+ def _list_consumer_groups_process_response(self, response):
1119
+ """Process a ListGroupsResponse into a list of groups."""
1120
+ if response.API_VERSION <= 2:
1121
+ error_type = Errors.for_code(response.error_code)
1122
+ if error_type is not Errors.NoError:
1123
+ raise error_type(
1124
+ "ListGroupsRequest failed with response '{}'."
1125
+ .format(response))
1126
+ else:
1127
+ raise NotImplementedError(
1128
+ "Support for ListGroupsResponse_v{} has not yet been added to KafkaAdminClient."
1129
+ .format(response.API_VERSION))
1130
+ return response.groups
1131
+
1132
+ def list_consumer_groups(self, broker_ids=None):
1133
+ """List all consumer groups known to the cluster.
1134
+
1135
+ This returns a list of Consumer Group tuples. The tuples are
1136
+ composed of the consumer group name and the consumer group protocol
1137
+ type.
1138
+
1139
+ Only consumer groups that store their offsets in Kafka are returned.
1140
+ The protocol type will be an empty string for groups created using
1141
+ Kafka < 0.9 APIs because, although they store their offsets in Kafka,
1142
+ they don't use Kafka for group coordination. For groups created using
1143
+ Kafka >= 0.9, the protocol type will typically be "consumer".
1144
+
1145
+ As soon as any error is encountered, it is immediately raised.
1146
+
1147
+ :param broker_ids: A list of broker node_ids to query for consumer
1148
+ groups. If set to None, will query all brokers in the cluster.
1149
+ Explicitly specifying broker(s) can be useful for determining which
1150
+ consumer groups are coordinated by those broker(s). Default: None
1151
+ :return list: List of tuples of Consumer Groups.
1152
+ :exception GroupCoordinatorNotAvailableError: The coordinator is not
1153
+ available, so cannot process requests.
1154
+ :exception GroupLoadInProgressError: The coordinator is loading and
1155
+ hence can't process requests.
1156
+ """
1157
+ # While we return a list, internally use a set to prevent duplicates
1158
+ # because if a group coordinator fails after being queried, and its
1159
+ # consumer groups move to new brokers that haven't yet been queried,
1160
+ # then the same group could be returned by multiple brokers.
1161
+ consumer_groups = set()
1162
+ if broker_ids is None:
1163
+ broker_ids = [broker.nodeId for broker in self._client.cluster.brokers()]
1164
+ futures = [self._list_consumer_groups_send_request(b) for b in broker_ids]
1165
+ self._wait_for_futures(futures)
1166
+ for f in futures:
1167
+ response = f.value
1168
+ consumer_groups.update(self._list_consumer_groups_process_response(response))
1169
+ return list(consumer_groups)
1170
+
1171
+ def _list_consumer_group_offsets_send_request(self, group_id,
1172
+ group_coordinator_id, partitions=None):
1173
+ """Send an OffsetFetchRequest to a broker.
1174
+
1175
+ :param group_id: The consumer group id name for which to fetch offsets.
1176
+ :param group_coordinator_id: The node_id of the group's coordinator
1177
+ broker.
1178
+ :return: A message future
1179
+ """
1180
+ version = self._matching_api_version(OffsetFetchRequest)
1181
+ if version <= 3:
1182
+ if partitions is None:
1183
+ if version <= 1:
1184
+ raise ValueError(
1185
+ """OffsetFetchRequest_v{} requires specifying the
1186
+ partitions for which to fetch offsets. Omitting the
1187
+ partitions is only supported on brokers >= 0.10.2.
1188
+ For details, see KIP-88.""".format(version))
1189
+ topics_partitions = None
1190
+ else:
1191
+ # transform from [TopicPartition("t1", 1), TopicPartition("t1", 2)] to [("t1", [1, 2])]
1192
+ topics_partitions_dict = defaultdict(set)
1193
+ for topic, partition in partitions:
1194
+ topics_partitions_dict[topic].add(partition)
1195
+ topics_partitions = list(six.iteritems(topics_partitions_dict))
1196
+ request = OffsetFetchRequest[version](group_id, topics_partitions)
1197
+ else:
1198
+ raise NotImplementedError(
1199
+ "Support for OffsetFetchRequest_v{} has not yet been added to KafkaAdminClient."
1200
+ .format(version))
1201
+ return self._send_request_to_node(group_coordinator_id, request)
1202
+
1203
+ def _list_consumer_group_offsets_process_response(self, response):
1204
+ """Process an OffsetFetchResponse.
1205
+
1206
+ :param response: an OffsetFetchResponse.
1207
+ :return: A dictionary composed of TopicPartition keys and
1208
+ OffsetAndMetada values.
1209
+ """
1210
+ if response.API_VERSION <= 3:
1211
+
1212
+ # OffsetFetchResponse_v1 lacks a top-level error_code
1213
+ if response.API_VERSION > 1:
1214
+ error_type = Errors.for_code(response.error_code)
1215
+ if error_type is not Errors.NoError:
1216
+ # optionally we could retry if error_type.retriable
1217
+ raise error_type(
1218
+ "OffsetFetchResponse failed with response '{}'."
1219
+ .format(response))
1220
+
1221
+ # transform response into a dictionary with TopicPartition keys and
1222
+ # OffsetAndMetada values--this is what the Java AdminClient returns
1223
+ offsets = {}
1224
+ for topic, partitions in response.topics:
1225
+ for partition, offset, metadata, error_code in partitions:
1226
+ error_type = Errors.for_code(error_code)
1227
+ if error_type is not Errors.NoError:
1228
+ raise error_type(
1229
+ "Unable to fetch consumer group offsets for topic {}, partition {}"
1230
+ .format(topic, partition))
1231
+ offsets[TopicPartition(topic, partition)] = OffsetAndMetadata(offset, metadata)
1232
+ else:
1233
+ raise NotImplementedError(
1234
+ "Support for OffsetFetchResponse_v{} has not yet been added to KafkaAdminClient."
1235
+ .format(response.API_VERSION))
1236
+ return offsets
1237
+
1238
+ def list_consumer_group_offsets(self, group_id, group_coordinator_id=None,
1239
+ partitions=None):
1240
+ """Fetch Consumer Offsets for a single consumer group.
1241
+
1242
+ Note:
1243
+ This does not verify that the group_id or partitions actually exist
1244
+ in the cluster.
1245
+
1246
+ As soon as any error is encountered, it is immediately raised.
1247
+
1248
+ :param group_id: The consumer group id name for which to fetch offsets.
1249
+ :param group_coordinator_id: The node_id of the group's coordinator
1250
+ broker. If set to None, will query the cluster to find the group
1251
+ coordinator. Explicitly specifying this can be useful to prevent
1252
+ that extra network round trip if you already know the group
1253
+ coordinator. Default: None.
1254
+ :param partitions: A list of TopicPartitions for which to fetch
1255
+ offsets. On brokers >= 0.10.2, this can be set to None to fetch all
1256
+ known offsets for the consumer group. Default: None.
1257
+ :return dictionary: A dictionary with TopicPartition keys and
1258
+ OffsetAndMetada values. Partitions that are not specified and for
1259
+ which the group_id does not have a recorded offset are omitted. An
1260
+ offset value of `-1` indicates the group_id has no offset for that
1261
+ TopicPartition. A `-1` can only happen for partitions that are
1262
+ explicitly specified.
1263
+ """
1264
+ if group_coordinator_id is None:
1265
+ group_coordinator_id = self._find_coordinator_ids([group_id])[group_id]
1266
+ future = self._list_consumer_group_offsets_send_request(
1267
+ group_id, group_coordinator_id, partitions)
1268
+ self._wait_for_futures([future])
1269
+ response = future.value
1270
+ return self._list_consumer_group_offsets_process_response(response)
1271
+
1272
+ def delete_consumer_groups(self, group_ids, group_coordinator_id=None):
1273
+ """Delete Consumer Group Offsets for given consumer groups.
1274
+
1275
+ Note:
1276
+ This does not verify that the group ids actually exist and
1277
+ group_coordinator_id is the correct coordinator for all these groups.
1278
+
1279
+ The result needs checking for potential errors.
1280
+
1281
+ :param group_ids: The consumer group ids of the groups which are to be deleted.
1282
+ :param group_coordinator_id: The node_id of the broker which is the coordinator for
1283
+ all the groups. Use only if all groups are coordinated by the same broker.
1284
+ If set to None, will query the cluster to find the coordinator for every single group.
1285
+ Explicitly specifying this can be useful to prevent
1286
+ that extra network round trips if you already know the group
1287
+ coordinator. Default: None.
1288
+ :return: A list of tuples (group_id, KafkaError)
1289
+ """
1290
+ if group_coordinator_id is not None:
1291
+ futures = [self._delete_consumer_groups_send_request(group_ids, group_coordinator_id)]
1292
+ else:
1293
+ coordinators_groups = defaultdict(list)
1294
+ for group_id, coordinator_id in self._find_coordinator_ids(group_ids).items():
1295
+ coordinators_groups[coordinator_id].append(group_id)
1296
+ futures = [
1297
+ self._delete_consumer_groups_send_request(group_ids, coordinator_id)
1298
+ for coordinator_id, group_ids in coordinators_groups.items()
1299
+ ]
1300
+
1301
+ self._wait_for_futures(futures)
1302
+
1303
+ results = []
1304
+ for f in futures:
1305
+ results.extend(self._convert_delete_groups_response(f.value))
1306
+ return results
1307
+
1308
+ def _convert_delete_groups_response(self, response):
1309
+ if response.API_VERSION <= 1:
1310
+ results = []
1311
+ for group_id, error_code in response.results:
1312
+ results.append((group_id, Errors.for_code(error_code)))
1313
+ return results
1314
+ else:
1315
+ raise NotImplementedError(
1316
+ "Support for DeleteGroupsResponse_v{} has not yet been added to KafkaAdminClient."
1317
+ .format(response.API_VERSION))
1318
+
1319
+ def _delete_consumer_groups_send_request(self, group_ids, group_coordinator_id):
1320
+ """Send a DeleteGroups request to a broker.
1321
+
1322
+ :param group_ids: The consumer group ids of the groups which are to be deleted.
1323
+ :param group_coordinator_id: The node_id of the broker which is the coordinator for
1324
+ all the groups.
1325
+ :return: A message future
1326
+ """
1327
+ version = self._matching_api_version(DeleteGroupsRequest)
1328
+ if version <= 1:
1329
+ request = DeleteGroupsRequest[version](group_ids)
1330
+ else:
1331
+ raise NotImplementedError(
1332
+ "Support for DeleteGroupsRequest_v{} has not yet been added to KafkaAdminClient."
1333
+ .format(version))
1334
+ return self._send_request_to_node(group_coordinator_id, request)
1335
+
1336
+ def _wait_for_futures(self, futures):
1337
+ while not all(future.succeeded() for future in futures):
1338
+ for future in futures:
1339
+ self._client.poll(future=future)
1340
+
1341
+ if future.failed():
1342
+ raise future.exception # pylint: disable-msg=raising-bad-type
testbed/dpkp__kafka-python/kafka/admin/config_resource.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+
3
+ # enum in stdlib as of py3.4
4
+ try:
5
+ from enum import IntEnum # pylint: disable=import-error
6
+ except ImportError:
7
+ # vendored backport module
8
+ from kafka.vendor.enum34 import IntEnum
9
+
10
+
11
+ class ConfigResourceType(IntEnum):
12
+ """An enumerated type of config resources"""
13
+
14
+ BROKER = 4,
15
+ TOPIC = 2
16
+
17
+
18
+ class ConfigResource(object):
19
+ """A class for specifying config resources.
20
+ Arguments:
21
+ resource_type (ConfigResourceType): the type of kafka resource
22
+ name (string): The name of the kafka resource
23
+ configs ({key : value}): A maps of config keys to values.
24
+ """
25
+
26
+ def __init__(
27
+ self,
28
+ resource_type,
29
+ name,
30
+ configs=None
31
+ ):
32
+ if not isinstance(resource_type, (ConfigResourceType)):
33
+ resource_type = ConfigResourceType[str(resource_type).upper()] # pylint: disable-msg=unsubscriptable-object
34
+ self.resource_type = resource_type
35
+ self.name = name
36
+ self.configs = configs
testbed/dpkp__kafka-python/kafka/admin/new_partitions.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+
3
+
4
+ class NewPartitions(object):
5
+ """A class for new partition creation on existing topics. Note that the length of new_assignments, if specified,
6
+ must be the difference between the new total number of partitions and the existing number of partitions.
7
+ Arguments:
8
+ total_count (int): the total number of partitions that should exist on the topic
9
+ new_assignments ([[int]]): an array of arrays of replica assignments for new partitions.
10
+ If not set, broker assigns replicas per an internal algorithm.
11
+ """
12
+
13
+ def __init__(
14
+ self,
15
+ total_count,
16
+ new_assignments=None
17
+ ):
18
+ self.total_count = total_count
19
+ self.new_assignments = new_assignments
testbed/dpkp__kafka-python/kafka/admin/new_topic.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+
3
+ from kafka.errors import IllegalArgumentError
4
+
5
+
6
+ class NewTopic(object):
7
+ """ A class for new topic creation
8
+ Arguments:
9
+ name (string): name of the topic
10
+ num_partitions (int): number of partitions
11
+ or -1 if replica_assignment has been specified
12
+ replication_factor (int): replication factor or -1 if
13
+ replica assignment is specified
14
+ replica_assignment (dict of int: [int]): A mapping containing
15
+ partition id and replicas to assign to it.
16
+ topic_configs (dict of str: str): A mapping of config key
17
+ and value for the topic.
18
+ """
19
+
20
+ def __init__(
21
+ self,
22
+ name,
23
+ num_partitions,
24
+ replication_factor,
25
+ replica_assignments=None,
26
+ topic_configs=None,
27
+ ):
28
+ if not (num_partitions == -1 or replication_factor == -1) ^ (replica_assignments is None):
29
+ raise IllegalArgumentError('either num_partitions/replication_factor or replica_assignment must be specified')
30
+ self.name = name
31
+ self.num_partitions = num_partitions
32
+ self.replication_factor = replication_factor
33
+ self.replica_assignments = replica_assignments or {}
34
+ self.topic_configs = topic_configs or {}
testbed/dpkp__kafka-python/kafka/client_async.py ADDED
@@ -0,0 +1,1077 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import, division
2
+
3
+ import collections
4
+ import copy
5
+ import logging
6
+ import random
7
+ import socket
8
+ import threading
9
+ import time
10
+ import weakref
11
+
12
+ # selectors in stdlib as of py3.4
13
+ try:
14
+ import selectors # pylint: disable=import-error
15
+ except ImportError:
16
+ # vendored backport module
17
+ from kafka.vendor import selectors34 as selectors
18
+
19
+ from kafka.vendor import six
20
+
21
+ from kafka.cluster import ClusterMetadata
22
+ from kafka.conn import BrokerConnection, ConnectionStates, collect_hosts, get_ip_port_afi
23
+ from kafka import errors as Errors
24
+ from kafka.future import Future
25
+ from kafka.metrics import AnonMeasurable
26
+ from kafka.metrics.stats import Avg, Count, Rate
27
+ from kafka.metrics.stats.rate import TimeUnit
28
+ from kafka.protocol.metadata import MetadataRequest
29
+ from kafka.util import Dict, WeakMethod
30
+ # Although this looks unused, it actually monkey-patches socket.socketpair()
31
+ # and should be left in as long as we're using socket.socketpair() in this file
32
+ from kafka.vendor import socketpair
33
+ from kafka.version import __version__
34
+
35
+ if six.PY2:
36
+ ConnectionError = None
37
+
38
+
39
+ log = logging.getLogger('kafka.client')
40
+
41
+
42
+ class KafkaClient(object):
43
+ """
44
+ A network client for asynchronous request/response network I/O.
45
+
46
+ This is an internal class used to implement the user-facing producer and
47
+ consumer clients.
48
+
49
+ This class is not thread-safe!
50
+
51
+ Attributes:
52
+ cluster (:any:`ClusterMetadata`): Local cache of cluster metadata, retrieved
53
+ via MetadataRequests during :meth:`~kafka.KafkaClient.poll`.
54
+
55
+ Keyword Arguments:
56
+ bootstrap_servers: 'host[:port]' string (or list of 'host[:port]'
57
+ strings) that the client should contact to bootstrap initial
58
+ cluster metadata. This does not have to be the full node list.
59
+ It just needs to have at least one broker that will respond to a
60
+ Metadata API Request. Default port is 9092. If no servers are
61
+ specified, will default to localhost:9092.
62
+ client_id (str): a name for this client. This string is passed in
63
+ each request to servers and can be used to identify specific
64
+ server-side log entries that correspond to this client. Also
65
+ submitted to GroupCoordinator for logging with respect to
66
+ consumer group administration. Default: 'kafka-python-{version}'
67
+ reconnect_backoff_ms (int): The amount of time in milliseconds to
68
+ wait before attempting to reconnect to a given host.
69
+ Default: 50.
70
+ reconnect_backoff_max_ms (int): The maximum amount of time in
71
+ milliseconds to backoff/wait when reconnecting to a broker that has
72
+ repeatedly failed to connect. If provided, the backoff per host
73
+ will increase exponentially for each consecutive connection
74
+ failure, up to this maximum. Once the maximum is reached,
75
+ reconnection attempts will continue periodically with this fixed
76
+ rate. To avoid connection storms, a randomization factor of 0.2
77
+ will be applied to the backoff resulting in a random range between
78
+ 20% below and 20% above the computed value. Default: 1000.
79
+ request_timeout_ms (int): Client request timeout in milliseconds.
80
+ Default: 30000.
81
+ connections_max_idle_ms: Close idle connections after the number of
82
+ milliseconds specified by this config. The broker closes idle
83
+ connections after connections.max.idle.ms, so this avoids hitting
84
+ unexpected socket disconnected errors on the client.
85
+ Default: 540000
86
+ retry_backoff_ms (int): Milliseconds to backoff when retrying on
87
+ errors. Default: 100.
88
+ max_in_flight_requests_per_connection (int): Requests are pipelined
89
+ to kafka brokers up to this number of maximum requests per
90
+ broker connection. Default: 5.
91
+ receive_buffer_bytes (int): The size of the TCP receive buffer
92
+ (SO_RCVBUF) to use when reading data. Default: None (relies on
93
+ system defaults). Java client defaults to 32768.
94
+ send_buffer_bytes (int): The size of the TCP send buffer
95
+ (SO_SNDBUF) to use when sending data. Default: None (relies on
96
+ system defaults). Java client defaults to 131072.
97
+ socket_options (list): List of tuple-arguments to socket.setsockopt
98
+ to apply to broker connection sockets. Default:
99
+ [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]
100
+ metadata_max_age_ms (int): The period of time in milliseconds after
101
+ which we force a refresh of metadata even if we haven't seen any
102
+ partition leadership changes to proactively discover any new
103
+ brokers or partitions. Default: 300000
104
+ security_protocol (str): Protocol used to communicate with brokers.
105
+ Valid values are: PLAINTEXT, SSL, SASL_PLAINTEXT, SASL_SSL.
106
+ Default: PLAINTEXT.
107
+ ssl_context (ssl.SSLContext): Pre-configured SSLContext for wrapping
108
+ socket connections. If provided, all other ssl_* configurations
109
+ will be ignored. Default: None.
110
+ ssl_check_hostname (bool): Flag to configure whether SSL handshake
111
+ should verify that the certificate matches the broker's hostname.
112
+ Default: True.
113
+ ssl_cafile (str): Optional filename of CA file to use in certificate
114
+ verification. Default: None.
115
+ ssl_certfile (str): Optional filename of file in PEM format containing
116
+ the client certificate, as well as any CA certificates needed to
117
+ establish the certificate's authenticity. Default: None.
118
+ ssl_keyfile (str): Optional filename containing the client private key.
119
+ Default: None.
120
+ ssl_password (str): Optional password to be used when loading the
121
+ certificate chain. Default: None.
122
+ ssl_crlfile (str): Optional filename containing the CRL to check for
123
+ certificate expiration. By default, no CRL check is done. When
124
+ providing a file, only the leaf certificate will be checked against
125
+ this CRL. The CRL can only be checked with Python 3.4+ or 2.7.9+.
126
+ Default: None.
127
+ ssl_ciphers (str): optionally set the available ciphers for ssl
128
+ connections. It should be a string in the OpenSSL cipher list
129
+ format. If no cipher can be selected (because compile-time options
130
+ or other configuration forbids use of all the specified ciphers),
131
+ an ssl.SSLError will be raised. See ssl.SSLContext.set_ciphers
132
+ api_version (tuple): Specify which Kafka API version to use. If set
133
+ to None, KafkaClient will attempt to infer the broker version by
134
+ probing various APIs. Example: (0, 10, 2). Default: None
135
+ api_version_auto_timeout_ms (int): number of milliseconds to throw a
136
+ timeout exception from the constructor when checking the broker
137
+ api version. Only applies if api_version is None
138
+ selector (selectors.BaseSelector): Provide a specific selector
139
+ implementation to use for I/O multiplexing.
140
+ Default: selectors.DefaultSelector
141
+ metrics (kafka.metrics.Metrics): Optionally provide a metrics
142
+ instance for capturing network IO stats. Default: None.
143
+ metric_group_prefix (str): Prefix for metric names. Default: ''
144
+ sasl_mechanism (str): Authentication mechanism when security_protocol
145
+ is configured for SASL_PLAINTEXT or SASL_SSL. Valid values are:
146
+ PLAIN, GSSAPI, OAUTHBEARER, SCRAM-SHA-256, SCRAM-SHA-512.
147
+ sasl_plain_username (str): username for sasl PLAIN and SCRAM authentication.
148
+ Required if sasl_mechanism is PLAIN or one of the SCRAM mechanisms.
149
+ sasl_plain_password (str): password for sasl PLAIN and SCRAM authentication.
150
+ Required if sasl_mechanism is PLAIN or one of the SCRAM mechanisms.
151
+ sasl_kerberos_service_name (str): Service name to include in GSSAPI
152
+ sasl mechanism handshake. Default: 'kafka'
153
+ sasl_kerberos_domain_name (str): kerberos domain name to use in GSSAPI
154
+ sasl mechanism handshake. Default: one of bootstrap servers
155
+ sasl_oauth_token_provider (AbstractTokenProvider): OAuthBearer token provider
156
+ instance. (See kafka.oauth.abstract). Default: None
157
+ """
158
+
159
+ DEFAULT_CONFIG = {
160
+ 'bootstrap_servers': 'localhost',
161
+ 'bootstrap_topics_filter': set(),
162
+ 'client_id': 'kafka-python-' + __version__,
163
+ 'request_timeout_ms': 30000,
164
+ 'wakeup_timeout_ms': 3000,
165
+ 'connections_max_idle_ms': 9 * 60 * 1000,
166
+ 'reconnect_backoff_ms': 50,
167
+ 'reconnect_backoff_max_ms': 1000,
168
+ 'max_in_flight_requests_per_connection': 5,
169
+ 'receive_buffer_bytes': None,
170
+ 'send_buffer_bytes': None,
171
+ 'socket_options': [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)],
172
+ 'sock_chunk_bytes': 4096, # undocumented experimental option
173
+ 'sock_chunk_buffer_count': 1000, # undocumented experimental option
174
+ 'retry_backoff_ms': 100,
175
+ 'metadata_max_age_ms': 300000,
176
+ 'security_protocol': 'PLAINTEXT',
177
+ 'ssl_context': None,
178
+ 'ssl_check_hostname': True,
179
+ 'ssl_cafile': None,
180
+ 'ssl_certfile': None,
181
+ 'ssl_keyfile': None,
182
+ 'ssl_password': None,
183
+ 'ssl_crlfile': None,
184
+ 'ssl_ciphers': None,
185
+ 'api_version': None,
186
+ 'api_version_auto_timeout_ms': 2000,
187
+ 'selector': selectors.DefaultSelector,
188
+ 'metrics': None,
189
+ 'metric_group_prefix': '',
190
+ 'sasl_mechanism': None,
191
+ 'sasl_plain_username': None,
192
+ 'sasl_plain_password': None,
193
+ 'sasl_kerberos_service_name': 'kafka',
194
+ 'sasl_kerberos_domain_name': None,
195
+ 'sasl_oauth_token_provider': None
196
+ }
197
+
198
+ def __init__(self, **configs):
199
+ self.config = copy.copy(self.DEFAULT_CONFIG)
200
+ for key in self.config:
201
+ if key in configs:
202
+ self.config[key] = configs[key]
203
+
204
+ # these properties need to be set on top of the initialization pipeline
205
+ # because they are used when __del__ method is called
206
+ self._closed = False
207
+ self._wake_r, self._wake_w = socket.socketpair()
208
+ self._selector = self.config['selector']()
209
+
210
+ self.cluster = ClusterMetadata(**self.config)
211
+ self._topics = set() # empty set will fetch all topic metadata
212
+ self._metadata_refresh_in_progress = False
213
+ self._conns = Dict() # object to support weakrefs
214
+ self._api_versions = None
215
+ self._connecting = set()
216
+ self._sending = set()
217
+ self._refresh_on_disconnects = True
218
+ self._last_bootstrap = 0
219
+ self._bootstrap_fails = 0
220
+ self._wake_r.setblocking(False)
221
+ self._wake_w.settimeout(self.config['wakeup_timeout_ms'] / 1000.0)
222
+ self._wake_lock = threading.Lock()
223
+
224
+ self._lock = threading.RLock()
225
+
226
+ # when requests complete, they are transferred to this queue prior to
227
+ # invocation. The purpose is to avoid invoking them while holding the
228
+ # lock above.
229
+ self._pending_completion = collections.deque()
230
+
231
+ self._selector.register(self._wake_r, selectors.EVENT_READ)
232
+ self._idle_expiry_manager = IdleConnectionManager(self.config['connections_max_idle_ms'])
233
+ self._sensors = None
234
+ if self.config['metrics']:
235
+ self._sensors = KafkaClientMetrics(self.config['metrics'],
236
+ self.config['metric_group_prefix'],
237
+ weakref.proxy(self._conns))
238
+
239
+ self._num_bootstrap_hosts = len(collect_hosts(self.config['bootstrap_servers']))
240
+
241
+ # Check Broker Version if not set explicitly
242
+ if self.config['api_version'] is None:
243
+ check_timeout = self.config['api_version_auto_timeout_ms'] / 1000
244
+ self.config['api_version'] = self.check_version(timeout=check_timeout)
245
+
246
+ def _can_bootstrap(self):
247
+ effective_failures = self._bootstrap_fails // self._num_bootstrap_hosts
248
+ backoff_factor = 2 ** effective_failures
249
+ backoff_ms = min(self.config['reconnect_backoff_ms'] * backoff_factor,
250
+ self.config['reconnect_backoff_max_ms'])
251
+
252
+ backoff_ms *= random.uniform(0.8, 1.2)
253
+
254
+ next_at = self._last_bootstrap + backoff_ms / 1000.0
255
+ now = time.time()
256
+ if next_at > now:
257
+ return False
258
+ return True
259
+
260
+ def _can_connect(self, node_id):
261
+ if node_id not in self._conns:
262
+ if self.cluster.broker_metadata(node_id):
263
+ return True
264
+ return False
265
+ conn = self._conns[node_id]
266
+ return conn.disconnected() and not conn.blacked_out()
267
+
268
+ def _conn_state_change(self, node_id, sock, conn):
269
+ with self._lock:
270
+ if conn.connecting():
271
+ # SSL connections can enter this state 2x (second during Handshake)
272
+ if node_id not in self._connecting:
273
+ self._connecting.add(node_id)
274
+ try:
275
+ self._selector.register(sock, selectors.EVENT_WRITE, conn)
276
+ except KeyError:
277
+ self._selector.modify(sock, selectors.EVENT_WRITE, conn)
278
+
279
+ if self.cluster.is_bootstrap(node_id):
280
+ self._last_bootstrap = time.time()
281
+
282
+ elif conn.connected():
283
+ log.debug("Node %s connected", node_id)
284
+ if node_id in self._connecting:
285
+ self._connecting.remove(node_id)
286
+
287
+ try:
288
+ self._selector.modify(sock, selectors.EVENT_READ, conn)
289
+ except KeyError:
290
+ self._selector.register(sock, selectors.EVENT_READ, conn)
291
+
292
+ if self._sensors:
293
+ self._sensors.connection_created.record()
294
+
295
+ self._idle_expiry_manager.update(node_id)
296
+
297
+ if self.cluster.is_bootstrap(node_id):
298
+ self._bootstrap_fails = 0
299
+
300
+ else:
301
+ for node_id in list(self._conns.keys()):
302
+ if self.cluster.is_bootstrap(node_id):
303
+ self._conns.pop(node_id).close()
304
+
305
+ # Connection failures imply that our metadata is stale, so let's refresh
306
+ elif conn.state is ConnectionStates.DISCONNECTED:
307
+ if node_id in self._connecting:
308
+ self._connecting.remove(node_id)
309
+ try:
310
+ self._selector.unregister(sock)
311
+ except KeyError:
312
+ pass
313
+
314
+ if self._sensors:
315
+ self._sensors.connection_closed.record()
316
+
317
+ idle_disconnect = False
318
+ if self._idle_expiry_manager.is_expired(node_id):
319
+ idle_disconnect = True
320
+ self._idle_expiry_manager.remove(node_id)
321
+
322
+ # If the connection has already by popped from self._conns,
323
+ # we can assume the disconnect was intentional and not a failure
324
+ if node_id not in self._conns:
325
+ pass
326
+
327
+ elif self.cluster.is_bootstrap(node_id):
328
+ self._bootstrap_fails += 1
329
+
330
+ elif self._refresh_on_disconnects and not self._closed and not idle_disconnect:
331
+ log.warning("Node %s connection failed -- refreshing metadata", node_id)
332
+ self.cluster.request_update()
333
+
334
+ def maybe_connect(self, node_id, wakeup=True):
335
+ """Queues a node for asynchronous connection during the next .poll()"""
336
+ if self._can_connect(node_id):
337
+ self._connecting.add(node_id)
338
+ # Wakeup signal is useful in case another thread is
339
+ # blocked waiting for incoming network traffic while holding
340
+ # the client lock in poll().
341
+ if wakeup:
342
+ self.wakeup()
343
+ return True
344
+ return False
345
+
346
+ def _should_recycle_connection(self, conn):
347
+ # Never recycle unless disconnected
348
+ if not conn.disconnected():
349
+ return False
350
+
351
+ # Otherwise, only recycle when broker metadata has changed
352
+ broker = self.cluster.broker_metadata(conn.node_id)
353
+ if broker is None:
354
+ return False
355
+
356
+ host, _, afi = get_ip_port_afi(broker.host)
357
+ if conn.host != host or conn.port != broker.port:
358
+ log.info("Broker metadata change detected for node %s"
359
+ " from %s:%s to %s:%s", conn.node_id, conn.host, conn.port,
360
+ broker.host, broker.port)
361
+ return True
362
+
363
+ return False
364
+
365
+ def _maybe_connect(self, node_id):
366
+ """Idempotent non-blocking connection attempt to the given node id."""
367
+ with self._lock:
368
+ conn = self._conns.get(node_id)
369
+
370
+ if conn is None:
371
+ broker = self.cluster.broker_metadata(node_id)
372
+ assert broker, 'Broker id %s not in current metadata' % (node_id,)
373
+
374
+ log.debug("Initiating connection to node %s at %s:%s",
375
+ node_id, broker.host, broker.port)
376
+ host, port, afi = get_ip_port_afi(broker.host)
377
+ cb = WeakMethod(self._conn_state_change)
378
+ conn = BrokerConnection(host, broker.port, afi,
379
+ state_change_callback=cb,
380
+ node_id=node_id,
381
+ **self.config)
382
+ self._conns[node_id] = conn
383
+
384
+ # Check if existing connection should be recreated because host/port changed
385
+ elif self._should_recycle_connection(conn):
386
+ self._conns.pop(node_id)
387
+ return False
388
+
389
+ elif conn.connected():
390
+ return True
391
+
392
+ conn.connect()
393
+ return conn.connected()
394
+
395
+ def ready(self, node_id, metadata_priority=True):
396
+ """Check whether a node is connected and ok to send more requests.
397
+
398
+ Arguments:
399
+ node_id (int): the id of the node to check
400
+ metadata_priority (bool): Mark node as not-ready if a metadata
401
+ refresh is required. Default: True
402
+
403
+ Returns:
404
+ bool: True if we are ready to send to the given node
405
+ """
406
+ self.maybe_connect(node_id)
407
+ return self.is_ready(node_id, metadata_priority=metadata_priority)
408
+
409
+ def connected(self, node_id):
410
+ """Return True iff the node_id is connected."""
411
+ conn = self._conns.get(node_id)
412
+ if conn is None:
413
+ return False
414
+ return conn.connected()
415
+
416
+ def _close(self):
417
+ if not self._closed:
418
+ self._closed = True
419
+ self._wake_r.close()
420
+ self._wake_w.close()
421
+ self._selector.close()
422
+
423
+ def close(self, node_id=None):
424
+ """Close one or all broker connections.
425
+
426
+ Arguments:
427
+ node_id (int, optional): the id of the node to close
428
+ """
429
+ with self._lock:
430
+ if node_id is None:
431
+ self._close()
432
+ conns = list(self._conns.values())
433
+ self._conns.clear()
434
+ for conn in conns:
435
+ conn.close()
436
+ elif node_id in self._conns:
437
+ self._conns.pop(node_id).close()
438
+ else:
439
+ log.warning("Node %s not found in current connection list; skipping", node_id)
440
+ return
441
+
442
+ def __del__(self):
443
+ self._close()
444
+
445
+ def is_disconnected(self, node_id):
446
+ """Check whether the node connection has been disconnected or failed.
447
+
448
+ A disconnected node has either been closed or has failed. Connection
449
+ failures are usually transient and can be resumed in the next ready()
450
+ call, but there are cases where transient failures need to be caught
451
+ and re-acted upon.
452
+
453
+ Arguments:
454
+ node_id (int): the id of the node to check
455
+
456
+ Returns:
457
+ bool: True iff the node exists and is disconnected
458
+ """
459
+ conn = self._conns.get(node_id)
460
+ if conn is None:
461
+ return False
462
+ return conn.disconnected()
463
+
464
+ def connection_delay(self, node_id):
465
+ """
466
+ Return the number of milliseconds to wait, based on the connection
467
+ state, before attempting to send data. When disconnected, this respects
468
+ the reconnect backoff time. When connecting, returns 0 to allow
469
+ non-blocking connect to finish. When connected, returns a very large
470
+ number to handle slow/stalled connections.
471
+
472
+ Arguments:
473
+ node_id (int): The id of the node to check
474
+
475
+ Returns:
476
+ int: The number of milliseconds to wait.
477
+ """
478
+ conn = self._conns.get(node_id)
479
+ if conn is None:
480
+ return 0
481
+ return conn.connection_delay()
482
+
483
+ def is_ready(self, node_id, metadata_priority=True):
484
+ """Check whether a node is ready to send more requests.
485
+
486
+ In addition to connection-level checks, this method also is used to
487
+ block additional requests from being sent during a metadata refresh.
488
+
489
+ Arguments:
490
+ node_id (int): id of the node to check
491
+ metadata_priority (bool): Mark node as not-ready if a metadata
492
+ refresh is required. Default: True
493
+
494
+ Returns:
495
+ bool: True if the node is ready and metadata is not refreshing
496
+ """
497
+ if not self._can_send_request(node_id):
498
+ return False
499
+
500
+ # if we need to update our metadata now declare all requests unready to
501
+ # make metadata requests first priority
502
+ if metadata_priority:
503
+ if self._metadata_refresh_in_progress:
504
+ return False
505
+ if self.cluster.ttl() == 0:
506
+ return False
507
+ return True
508
+
509
+ def _can_send_request(self, node_id):
510
+ conn = self._conns.get(node_id)
511
+ if not conn:
512
+ return False
513
+ return conn.connected() and conn.can_send_more()
514
+
515
+ def send(self, node_id, request, wakeup=True):
516
+ """Send a request to a specific node. Bytes are placed on an
517
+ internal per-connection send-queue. Actual network I/O will be
518
+ triggered in a subsequent call to .poll()
519
+
520
+ Arguments:
521
+ node_id (int): destination node
522
+ request (Struct): request object (not-encoded)
523
+ wakeup (bool): optional flag to disable thread-wakeup
524
+
525
+ Raises:
526
+ AssertionError: if node_id is not in current cluster metadata
527
+
528
+ Returns:
529
+ Future: resolves to Response struct or Error
530
+ """
531
+ conn = self._conns.get(node_id)
532
+ if not conn or not self._can_send_request(node_id):
533
+ self.maybe_connect(node_id, wakeup=wakeup)
534
+ return Future().failure(Errors.NodeNotReadyError(node_id))
535
+
536
+ # conn.send will queue the request internally
537
+ # we will need to call send_pending_requests()
538
+ # to trigger network I/O
539
+ future = conn.send(request, blocking=False)
540
+ self._sending.add(conn)
541
+
542
+ # Wakeup signal is useful in case another thread is
543
+ # blocked waiting for incoming network traffic while holding
544
+ # the client lock in poll().
545
+ if wakeup:
546
+ self.wakeup()
547
+
548
+ return future
549
+
550
+ def poll(self, timeout_ms=None, future=None):
551
+ """Try to read and write to sockets.
552
+
553
+ This method will also attempt to complete node connections, refresh
554
+ stale metadata, and run previously-scheduled tasks.
555
+
556
+ Arguments:
557
+ timeout_ms (int, optional): maximum amount of time to wait (in ms)
558
+ for at least one response. Must be non-negative. The actual
559
+ timeout will be the minimum of timeout, request timeout and
560
+ metadata timeout. Default: request_timeout_ms
561
+ future (Future, optional): if provided, blocks until future.is_done
562
+
563
+ Returns:
564
+ list: responses received (can be empty)
565
+ """
566
+ if future is not None:
567
+ timeout_ms = 100
568
+ elif timeout_ms is None:
569
+ timeout_ms = self.config['request_timeout_ms']
570
+ elif not isinstance(timeout_ms, (int, float)):
571
+ raise TypeError('Invalid type for timeout: %s' % type(timeout_ms))
572
+
573
+ # Loop for futures, break after first loop if None
574
+ responses = []
575
+ while True:
576
+ with self._lock:
577
+ if self._closed:
578
+ break
579
+
580
+ # Attempt to complete pending connections
581
+ for node_id in list(self._connecting):
582
+ self._maybe_connect(node_id)
583
+
584
+ # Send a metadata request if needed
585
+ metadata_timeout_ms = self._maybe_refresh_metadata()
586
+
587
+ # If we got a future that is already done, don't block in _poll
588
+ if future is not None and future.is_done:
589
+ timeout = 0
590
+ else:
591
+ idle_connection_timeout_ms = self._idle_expiry_manager.next_check_ms()
592
+ timeout = min(
593
+ timeout_ms,
594
+ metadata_timeout_ms,
595
+ idle_connection_timeout_ms,
596
+ self.config['request_timeout_ms'])
597
+ # if there are no requests in flight, do not block longer than the retry backoff
598
+ if self.in_flight_request_count() == 0:
599
+ timeout = min(timeout, self.config['retry_backoff_ms'])
600
+ timeout = max(0, timeout) # avoid negative timeouts
601
+
602
+ self._poll(timeout / 1000)
603
+
604
+ # called without the lock to avoid deadlock potential
605
+ # if handlers need to acquire locks
606
+ responses.extend(self._fire_pending_completed_requests())
607
+
608
+ # If all we had was a timeout (future is None) - only do one poll
609
+ # If we do have a future, we keep looping until it is done
610
+ if future is None or future.is_done:
611
+ break
612
+
613
+ return responses
614
+
615
+ def _register_send_sockets(self):
616
+ while self._sending:
617
+ conn = self._sending.pop()
618
+ try:
619
+ key = self._selector.get_key(conn._sock)
620
+ events = key.events | selectors.EVENT_WRITE
621
+ self._selector.modify(key.fileobj, events, key.data)
622
+ except KeyError:
623
+ self._selector.register(conn._sock, selectors.EVENT_WRITE, conn)
624
+
625
+ def _poll(self, timeout):
626
+ # This needs to be locked, but since it is only called from within the
627
+ # locked section of poll(), there is no additional lock acquisition here
628
+ processed = set()
629
+
630
+ # Send pending requests first, before polling for responses
631
+ self._register_send_sockets()
632
+
633
+ start_select = time.time()
634
+ ready = self._selector.select(timeout)
635
+ end_select = time.time()
636
+ if self._sensors:
637
+ self._sensors.select_time.record((end_select - start_select) * 1000000000)
638
+
639
+ for key, events in ready:
640
+ if key.fileobj is self._wake_r:
641
+ self._clear_wake_fd()
642
+ continue
643
+
644
+ # Send pending requests if socket is ready to write
645
+ if events & selectors.EVENT_WRITE:
646
+ conn = key.data
647
+ if conn.connecting():
648
+ conn.connect()
649
+ else:
650
+ if conn.send_pending_requests_v2():
651
+ # If send is complete, we dont need to track write readiness
652
+ # for this socket anymore
653
+ if key.events ^ selectors.EVENT_WRITE:
654
+ self._selector.modify(
655
+ key.fileobj,
656
+ key.events ^ selectors.EVENT_WRITE,
657
+ key.data)
658
+ else:
659
+ self._selector.unregister(key.fileobj)
660
+
661
+ if not (events & selectors.EVENT_READ):
662
+ continue
663
+ conn = key.data
664
+ processed.add(conn)
665
+
666
+ if not conn.in_flight_requests:
667
+ # if we got an EVENT_READ but there were no in-flight requests, one of
668
+ # two things has happened:
669
+ #
670
+ # 1. The remote end closed the connection (because it died, or because
671
+ # a firewall timed out, or whatever)
672
+ # 2. The protocol is out of sync.
673
+ #
674
+ # either way, we can no longer safely use this connection
675
+ #
676
+ # Do a 1-byte read to check protocol didnt get out of sync, and then close the conn
677
+ try:
678
+ unexpected_data = key.fileobj.recv(1)
679
+ if unexpected_data: # anything other than a 0-byte read means protocol issues
680
+ log.warning('Protocol out of sync on %r, closing', conn)
681
+ except socket.error:
682
+ pass
683
+ conn.close(Errors.KafkaConnectionError('Socket EVENT_READ without in-flight-requests'))
684
+ continue
685
+
686
+ self._idle_expiry_manager.update(conn.node_id)
687
+ self._pending_completion.extend(conn.recv())
688
+
689
+ # Check for additional pending SSL bytes
690
+ if self.config['security_protocol'] in ('SSL', 'SASL_SSL'):
691
+ # TODO: optimize
692
+ for conn in self._conns.values():
693
+ if conn not in processed and conn.connected() and conn._sock.pending():
694
+ self._pending_completion.extend(conn.recv())
695
+
696
+ for conn in six.itervalues(self._conns):
697
+ if conn.requests_timed_out():
698
+ log.warning('%s timed out after %s ms. Closing connection.',
699
+ conn, conn.config['request_timeout_ms'])
700
+ conn.close(error=Errors.RequestTimedOutError(
701
+ 'Request timed out after %s ms' %
702
+ conn.config['request_timeout_ms']))
703
+
704
+ if self._sensors:
705
+ self._sensors.io_time.record((time.time() - end_select) * 1000000000)
706
+
707
+ self._maybe_close_oldest_connection()
708
+
709
+ def in_flight_request_count(self, node_id=None):
710
+ """Get the number of in-flight requests for a node or all nodes.
711
+
712
+ Arguments:
713
+ node_id (int, optional): a specific node to check. If unspecified,
714
+ return the total for all nodes
715
+
716
+ Returns:
717
+ int: pending in-flight requests for the node, or all nodes if None
718
+ """
719
+ if node_id is not None:
720
+ conn = self._conns.get(node_id)
721
+ if conn is None:
722
+ return 0
723
+ return len(conn.in_flight_requests)
724
+ else:
725
+ return sum([len(conn.in_flight_requests)
726
+ for conn in list(self._conns.values())])
727
+
728
+ def _fire_pending_completed_requests(self):
729
+ responses = []
730
+ while True:
731
+ try:
732
+ # We rely on deque.popleft remaining threadsafe
733
+ # to allow both the heartbeat thread and the main thread
734
+ # to process responses
735
+ response, future = self._pending_completion.popleft()
736
+ except IndexError:
737
+ break
738
+ future.success(response)
739
+ responses.append(response)
740
+ return responses
741
+
742
+ def least_loaded_node(self):
743
+ """Choose the node with fewest outstanding requests, with fallbacks.
744
+
745
+ This method will prefer a node with an existing connection and no
746
+ in-flight-requests. If no such node is found, a node will be chosen
747
+ randomly from disconnected nodes that are not "blacked out" (i.e.,
748
+ are not subject to a reconnect backoff). If no node metadata has been
749
+ obtained, will return a bootstrap node (subject to exponential backoff).
750
+
751
+ Returns:
752
+ node_id or None if no suitable node was found
753
+ """
754
+ nodes = [broker.nodeId for broker in self.cluster.brokers()]
755
+ random.shuffle(nodes)
756
+
757
+ inflight = float('inf')
758
+ found = None
759
+ for node_id in nodes:
760
+ conn = self._conns.get(node_id)
761
+ connected = conn is not None and conn.connected()
762
+ blacked_out = conn is not None and conn.blacked_out()
763
+ curr_inflight = len(conn.in_flight_requests) if conn is not None else 0
764
+ if connected and curr_inflight == 0:
765
+ # if we find an established connection
766
+ # with no in-flight requests, we can stop right away
767
+ return node_id
768
+ elif not blacked_out and curr_inflight < inflight:
769
+ # otherwise if this is the best we have found so far, record that
770
+ inflight = curr_inflight
771
+ found = node_id
772
+
773
+ return found
774
+
775
+ def set_topics(self, topics):
776
+ """Set specific topics to track for metadata.
777
+
778
+ Arguments:
779
+ topics (list of str): topics to check for metadata
780
+
781
+ Returns:
782
+ Future: resolves after metadata request/response
783
+ """
784
+ if set(topics).difference(self._topics):
785
+ future = self.cluster.request_update()
786
+ else:
787
+ future = Future().success(set(topics))
788
+ self._topics = set(topics)
789
+ return future
790
+
791
+ def add_topic(self, topic):
792
+ """Add a topic to the list of topics tracked via metadata.
793
+
794
+ Arguments:
795
+ topic (str): topic to track
796
+
797
+ Returns:
798
+ Future: resolves after metadata request/response
799
+ """
800
+ if topic in self._topics:
801
+ return Future().success(set(self._topics))
802
+
803
+ self._topics.add(topic)
804
+ return self.cluster.request_update()
805
+
806
+ # This method should be locked when running multi-threaded
807
+ def _maybe_refresh_metadata(self, wakeup=False):
808
+ """Send a metadata request if needed.
809
+
810
+ Returns:
811
+ int: milliseconds until next refresh
812
+ """
813
+ ttl = self.cluster.ttl()
814
+ wait_for_in_progress_ms = self.config['request_timeout_ms'] if self._metadata_refresh_in_progress else 0
815
+ metadata_timeout = max(ttl, wait_for_in_progress_ms)
816
+
817
+ if metadata_timeout > 0:
818
+ return metadata_timeout
819
+
820
+ # Beware that the behavior of this method and the computation of
821
+ # timeouts for poll() are highly dependent on the behavior of
822
+ # least_loaded_node()
823
+ node_id = self.least_loaded_node()
824
+ if node_id is None:
825
+ log.debug("Give up sending metadata request since no node is available");
826
+ return self.config['reconnect_backoff_ms']
827
+
828
+ if self._can_send_request(node_id):
829
+ topics = list(self._topics)
830
+ if not topics and self.cluster.is_bootstrap(node_id):
831
+ topics = list(self.config['bootstrap_topics_filter'])
832
+
833
+ if self.cluster.need_all_topic_metadata or not topics:
834
+ topics = [] if self.config['api_version'] < (0, 10) else None
835
+ api_version = 0 if self.config['api_version'] < (0, 10) else 1
836
+ request = MetadataRequest[api_version](topics)
837
+ log.debug("Sending metadata request %s to node %s", request, node_id)
838
+ future = self.send(node_id, request, wakeup=wakeup)
839
+ future.add_callback(self.cluster.update_metadata)
840
+ future.add_errback(self.cluster.failed_update)
841
+
842
+ self._metadata_refresh_in_progress = True
843
+ def refresh_done(val_or_error):
844
+ self._metadata_refresh_in_progress = False
845
+ future.add_callback(refresh_done)
846
+ future.add_errback(refresh_done)
847
+ return self.config['request_timeout_ms']
848
+
849
+ # If there's any connection establishment underway, wait until it completes. This prevents
850
+ # the client from unnecessarily connecting to additional nodes while a previous connection
851
+ # attempt has not been completed.
852
+ if self._connecting:
853
+ return self.config['reconnect_backoff_ms']
854
+
855
+ if self.maybe_connect(node_id, wakeup=wakeup):
856
+ log.debug("Initializing connection to node %s for metadata request", node_id)
857
+ return self.config['reconnect_backoff_ms']
858
+
859
+ # connected but can't send more, OR connecting
860
+ # In either case we just need to wait for a network event
861
+ # to let us know the selected connection might be usable again.
862
+ return float('inf')
863
+
864
+ def get_api_versions(self):
865
+ """Return the ApiVersions map, if available.
866
+
867
+ Note: A call to check_version must previously have succeeded and returned
868
+ version 0.10.0 or later
869
+
870
+ Returns: a map of dict mapping {api_key : (min_version, max_version)},
871
+ or None if ApiVersion is not supported by the kafka cluster.
872
+ """
873
+ return self._api_versions
874
+
875
+ def check_version(self, node_id=None, timeout=2, strict=False):
876
+ """Attempt to guess the version of a Kafka broker.
877
+
878
+ Note: It is possible that this method blocks longer than the
879
+ specified timeout. This can happen if the entire cluster
880
+ is down and the client enters a bootstrap backoff sleep.
881
+ This is only possible if node_id is None.
882
+
883
+ Returns: version tuple, i.e. (0, 10), (0, 9), (0, 8, 2), ...
884
+
885
+ Raises:
886
+ NodeNotReadyError (if node_id is provided)
887
+ NoBrokersAvailable (if node_id is None)
888
+ UnrecognizedBrokerVersion: please file bug if seen!
889
+ AssertionError (if strict=True): please file bug if seen!
890
+ """
891
+ self._lock.acquire()
892
+ end = time.time() + timeout
893
+ while time.time() < end:
894
+
895
+ # It is possible that least_loaded_node falls back to bootstrap,
896
+ # which can block for an increasing backoff period
897
+ try_node = node_id or self.least_loaded_node()
898
+ if try_node is None:
899
+ self._lock.release()
900
+ raise Errors.NoBrokersAvailable()
901
+ self._maybe_connect(try_node)
902
+ conn = self._conns[try_node]
903
+
904
+ # We will intentionally cause socket failures
905
+ # These should not trigger metadata refresh
906
+ self._refresh_on_disconnects = False
907
+ try:
908
+ remaining = end - time.time()
909
+ version = conn.check_version(timeout=remaining, strict=strict, topics=list(self.config['bootstrap_topics_filter']))
910
+ if version >= (0, 10, 0):
911
+ # cache the api versions map if it's available (starting
912
+ # in 0.10 cluster version)
913
+ self._api_versions = conn.get_api_versions()
914
+ self._lock.release()
915
+ return version
916
+ except Errors.NodeNotReadyError:
917
+ # Only raise to user if this is a node-specific request
918
+ if node_id is not None:
919
+ self._lock.release()
920
+ raise
921
+ finally:
922
+ self._refresh_on_disconnects = True
923
+
924
+ # Timeout
925
+ else:
926
+ self._lock.release()
927
+ raise Errors.NoBrokersAvailable()
928
+
929
+ def wakeup(self):
930
+ with self._wake_lock:
931
+ try:
932
+ self._wake_w.sendall(b'x')
933
+ except socket.timeout:
934
+ log.warning('Timeout to send to wakeup socket!')
935
+ raise Errors.KafkaTimeoutError()
936
+ except socket.error:
937
+ log.warning('Unable to send to wakeup socket!')
938
+
939
+ def _clear_wake_fd(self):
940
+ # reading from wake socket should only happen in a single thread
941
+ while True:
942
+ try:
943
+ self._wake_r.recv(1024)
944
+ except socket.error:
945
+ break
946
+
947
+ def _maybe_close_oldest_connection(self):
948
+ expired_connection = self._idle_expiry_manager.poll_expired_connection()
949
+ if expired_connection:
950
+ conn_id, ts = expired_connection
951
+ idle_ms = (time.time() - ts) * 1000
952
+ log.info('Closing idle connection %s, last active %d ms ago', conn_id, idle_ms)
953
+ self.close(node_id=conn_id)
954
+
955
+ def bootstrap_connected(self):
956
+ """Return True if a bootstrap node is connected"""
957
+ for node_id in self._conns:
958
+ if not self.cluster.is_bootstrap(node_id):
959
+ continue
960
+ if self._conns[node_id].connected():
961
+ return True
962
+ else:
963
+ return False
964
+
965
+
966
+ # OrderedDict requires python2.7+
967
+ try:
968
+ from collections import OrderedDict
969
+ except ImportError:
970
+ # If we dont have OrderedDict, we'll fallback to dict with O(n) priority reads
971
+ OrderedDict = dict
972
+
973
+
974
+ class IdleConnectionManager(object):
975
+ def __init__(self, connections_max_idle_ms):
976
+ if connections_max_idle_ms > 0:
977
+ self.connections_max_idle = connections_max_idle_ms / 1000
978
+ else:
979
+ self.connections_max_idle = float('inf')
980
+ self.next_idle_close_check_time = None
981
+ self.update_next_idle_close_check_time(time.time())
982
+ self.lru_connections = OrderedDict()
983
+
984
+ def update(self, conn_id):
985
+ # order should reflect last-update
986
+ if conn_id in self.lru_connections:
987
+ del self.lru_connections[conn_id]
988
+ self.lru_connections[conn_id] = time.time()
989
+
990
+ def remove(self, conn_id):
991
+ if conn_id in self.lru_connections:
992
+ del self.lru_connections[conn_id]
993
+
994
+ def is_expired(self, conn_id):
995
+ if conn_id not in self.lru_connections:
996
+ return None
997
+ return time.time() >= self.lru_connections[conn_id] + self.connections_max_idle
998
+
999
+ def next_check_ms(self):
1000
+ now = time.time()
1001
+ if not self.lru_connections:
1002
+ return float('inf')
1003
+ elif self.next_idle_close_check_time <= now:
1004
+ return 0
1005
+ else:
1006
+ return int((self.next_idle_close_check_time - now) * 1000)
1007
+
1008
+ def update_next_idle_close_check_time(self, ts):
1009
+ self.next_idle_close_check_time = ts + self.connections_max_idle
1010
+
1011
+ def poll_expired_connection(self):
1012
+ if time.time() < self.next_idle_close_check_time:
1013
+ return None
1014
+
1015
+ if not len(self.lru_connections):
1016
+ return None
1017
+
1018
+ oldest_conn_id = None
1019
+ oldest_ts = None
1020
+ if OrderedDict is dict:
1021
+ for conn_id, ts in self.lru_connections.items():
1022
+ if oldest_conn_id is None or ts < oldest_ts:
1023
+ oldest_conn_id = conn_id
1024
+ oldest_ts = ts
1025
+ else:
1026
+ (oldest_conn_id, oldest_ts) = next(iter(self.lru_connections.items()))
1027
+
1028
+ self.update_next_idle_close_check_time(oldest_ts)
1029
+
1030
+ if time.time() >= oldest_ts + self.connections_max_idle:
1031
+ return (oldest_conn_id, oldest_ts)
1032
+ else:
1033
+ return None
1034
+
1035
+
1036
+ class KafkaClientMetrics(object):
1037
+ def __init__(self, metrics, metric_group_prefix, conns):
1038
+ self.metrics = metrics
1039
+ self.metric_group_name = metric_group_prefix + '-metrics'
1040
+
1041
+ self.connection_closed = metrics.sensor('connections-closed')
1042
+ self.connection_closed.add(metrics.metric_name(
1043
+ 'connection-close-rate', self.metric_group_name,
1044
+ 'Connections closed per second in the window.'), Rate())
1045
+ self.connection_created = metrics.sensor('connections-created')
1046
+ self.connection_created.add(metrics.metric_name(
1047
+ 'connection-creation-rate', self.metric_group_name,
1048
+ 'New connections established per second in the window.'), Rate())
1049
+
1050
+ self.select_time = metrics.sensor('select-time')
1051
+ self.select_time.add(metrics.metric_name(
1052
+ 'select-rate', self.metric_group_name,
1053
+ 'Number of times the I/O layer checked for new I/O to perform per'
1054
+ ' second'), Rate(sampled_stat=Count()))
1055
+ self.select_time.add(metrics.metric_name(
1056
+ 'io-wait-time-ns-avg', self.metric_group_name,
1057
+ 'The average length of time the I/O thread spent waiting for a'
1058
+ ' socket ready for reads or writes in nanoseconds.'), Avg())
1059
+ self.select_time.add(metrics.metric_name(
1060
+ 'io-wait-ratio', self.metric_group_name,
1061
+ 'The fraction of time the I/O thread spent waiting.'),
1062
+ Rate(time_unit=TimeUnit.NANOSECONDS))
1063
+
1064
+ self.io_time = metrics.sensor('io-time')
1065
+ self.io_time.add(metrics.metric_name(
1066
+ 'io-time-ns-avg', self.metric_group_name,
1067
+ 'The average length of time for I/O per select call in nanoseconds.'),
1068
+ Avg())
1069
+ self.io_time.add(metrics.metric_name(
1070
+ 'io-ratio', self.metric_group_name,
1071
+ 'The fraction of time the I/O thread spent doing I/O'),
1072
+ Rate(time_unit=TimeUnit.NANOSECONDS))
1073
+
1074
+ metrics.add_metric(metrics.metric_name(
1075
+ 'connection-count', self.metric_group_name,
1076
+ 'The current number of active connections.'), AnonMeasurable(
1077
+ lambda config, now: len(conns)))
testbed/dpkp__kafka-python/kafka/cluster.py ADDED
@@ -0,0 +1,397 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+
3
+ import collections
4
+ import copy
5
+ import logging
6
+ import threading
7
+ import time
8
+
9
+ from kafka.vendor import six
10
+
11
+ from kafka import errors as Errors
12
+ from kafka.conn import collect_hosts
13
+ from kafka.future import Future
14
+ from kafka.structs import BrokerMetadata, PartitionMetadata, TopicPartition
15
+
16
+ log = logging.getLogger(__name__)
17
+
18
+
19
+ class ClusterMetadata(object):
20
+ """
21
+ A class to manage kafka cluster metadata.
22
+
23
+ This class does not perform any IO. It simply updates internal state
24
+ given API responses (MetadataResponse, GroupCoordinatorResponse).
25
+
26
+ Keyword Arguments:
27
+ retry_backoff_ms (int): Milliseconds to backoff when retrying on
28
+ errors. Default: 100.
29
+ metadata_max_age_ms (int): The period of time in milliseconds after
30
+ which we force a refresh of metadata even if we haven't seen any
31
+ partition leadership changes to proactively discover any new
32
+ brokers or partitions. Default: 300000
33
+ bootstrap_servers: 'host[:port]' string (or list of 'host[:port]'
34
+ strings) that the client should contact to bootstrap initial
35
+ cluster metadata. This does not have to be the full node list.
36
+ It just needs to have at least one broker that will respond to a
37
+ Metadata API Request. Default port is 9092. If no servers are
38
+ specified, will default to localhost:9092.
39
+ """
40
+ DEFAULT_CONFIG = {
41
+ 'retry_backoff_ms': 100,
42
+ 'metadata_max_age_ms': 300000,
43
+ 'bootstrap_servers': [],
44
+ }
45
+
46
+ def __init__(self, **configs):
47
+ self._brokers = {} # node_id -> BrokerMetadata
48
+ self._partitions = {} # topic -> partition -> PartitionMetadata
49
+ self._broker_partitions = collections.defaultdict(set) # node_id -> {TopicPartition...}
50
+ self._groups = {} # group_name -> node_id
51
+ self._last_refresh_ms = 0
52
+ self._last_successful_refresh_ms = 0
53
+ self._need_update = True
54
+ self._future = None
55
+ self._listeners = set()
56
+ self._lock = threading.Lock()
57
+ self.need_all_topic_metadata = False
58
+ self.unauthorized_topics = set()
59
+ self.internal_topics = set()
60
+ self.controller = None
61
+
62
+ self.config = copy.copy(self.DEFAULT_CONFIG)
63
+ for key in self.config:
64
+ if key in configs:
65
+ self.config[key] = configs[key]
66
+
67
+ self._bootstrap_brokers = self._generate_bootstrap_brokers()
68
+ self._coordinator_brokers = {}
69
+
70
+ def _generate_bootstrap_brokers(self):
71
+ # collect_hosts does not perform DNS, so we should be fine to re-use
72
+ bootstrap_hosts = collect_hosts(self.config['bootstrap_servers'])
73
+
74
+ brokers = {}
75
+ for i, (host, port, _) in enumerate(bootstrap_hosts):
76
+ node_id = 'bootstrap-%s' % i
77
+ brokers[node_id] = BrokerMetadata(node_id, host, port, None)
78
+ return brokers
79
+
80
+ def is_bootstrap(self, node_id):
81
+ return node_id in self._bootstrap_brokers
82
+
83
+ def brokers(self):
84
+ """Get all BrokerMetadata
85
+
86
+ Returns:
87
+ set: {BrokerMetadata, ...}
88
+ """
89
+ return set(self._brokers.values()) or set(self._bootstrap_brokers.values())
90
+
91
+ def broker_metadata(self, broker_id):
92
+ """Get BrokerMetadata
93
+
94
+ Arguments:
95
+ broker_id (int): node_id for a broker to check
96
+
97
+ Returns:
98
+ BrokerMetadata or None if not found
99
+ """
100
+ return (
101
+ self._brokers.get(broker_id) or
102
+ self._bootstrap_brokers.get(broker_id) or
103
+ self._coordinator_brokers.get(broker_id)
104
+ )
105
+
106
+ def partitions_for_topic(self, topic):
107
+ """Return set of all partitions for topic (whether available or not)
108
+
109
+ Arguments:
110
+ topic (str): topic to check for partitions
111
+
112
+ Returns:
113
+ set: {partition (int), ...}
114
+ """
115
+ if topic not in self._partitions:
116
+ return None
117
+ return set(self._partitions[topic].keys())
118
+
119
+ def available_partitions_for_topic(self, topic):
120
+ """Return set of partitions with known leaders
121
+
122
+ Arguments:
123
+ topic (str): topic to check for partitions
124
+
125
+ Returns:
126
+ set: {partition (int), ...}
127
+ None if topic not found.
128
+ """
129
+ if topic not in self._partitions:
130
+ return None
131
+ return set([partition for partition, metadata
132
+ in six.iteritems(self._partitions[topic])
133
+ if metadata.leader != -1])
134
+
135
+ def leader_for_partition(self, partition):
136
+ """Return node_id of leader, -1 unavailable, None if unknown."""
137
+ if partition.topic not in self._partitions:
138
+ return None
139
+ elif partition.partition not in self._partitions[partition.topic]:
140
+ return None
141
+ return self._partitions[partition.topic][partition.partition].leader
142
+
143
+ def partitions_for_broker(self, broker_id):
144
+ """Return TopicPartitions for which the broker is a leader.
145
+
146
+ Arguments:
147
+ broker_id (int): node id for a broker
148
+
149
+ Returns:
150
+ set: {TopicPartition, ...}
151
+ None if the broker either has no partitions or does not exist.
152
+ """
153
+ return self._broker_partitions.get(broker_id)
154
+
155
+ def coordinator_for_group(self, group):
156
+ """Return node_id of group coordinator.
157
+
158
+ Arguments:
159
+ group (str): name of consumer group
160
+
161
+ Returns:
162
+ int: node_id for group coordinator
163
+ None if the group does not exist.
164
+ """
165
+ return self._groups.get(group)
166
+
167
+ def ttl(self):
168
+ """Milliseconds until metadata should be refreshed"""
169
+ now = time.time() * 1000
170
+ if self._need_update:
171
+ ttl = 0
172
+ else:
173
+ metadata_age = now - self._last_successful_refresh_ms
174
+ ttl = self.config['metadata_max_age_ms'] - metadata_age
175
+
176
+ retry_age = now - self._last_refresh_ms
177
+ next_retry = self.config['retry_backoff_ms'] - retry_age
178
+
179
+ return max(ttl, next_retry, 0)
180
+
181
+ def refresh_backoff(self):
182
+ """Return milliseconds to wait before attempting to retry after failure"""
183
+ return self.config['retry_backoff_ms']
184
+
185
+ def request_update(self):
186
+ """Flags metadata for update, return Future()
187
+
188
+ Actual update must be handled separately. This method will only
189
+ change the reported ttl()
190
+
191
+ Returns:
192
+ kafka.future.Future (value will be the cluster object after update)
193
+ """
194
+ with self._lock:
195
+ self._need_update = True
196
+ if not self._future or self._future.is_done:
197
+ self._future = Future()
198
+ return self._future
199
+
200
+ def topics(self, exclude_internal_topics=True):
201
+ """Get set of known topics.
202
+
203
+ Arguments:
204
+ exclude_internal_topics (bool): Whether records from internal topics
205
+ (such as offsets) should be exposed to the consumer. If set to
206
+ True the only way to receive records from an internal topic is
207
+ subscribing to it. Default True
208
+
209
+ Returns:
210
+ set: {topic (str), ...}
211
+ """
212
+ topics = set(self._partitions.keys())
213
+ if exclude_internal_topics:
214
+ return topics - self.internal_topics
215
+ else:
216
+ return topics
217
+
218
+ def failed_update(self, exception):
219
+ """Update cluster state given a failed MetadataRequest."""
220
+ f = None
221
+ with self._lock:
222
+ if self._future:
223
+ f = self._future
224
+ self._future = None
225
+ if f:
226
+ f.failure(exception)
227
+ self._last_refresh_ms = time.time() * 1000
228
+
229
+ def update_metadata(self, metadata):
230
+ """Update cluster state given a MetadataResponse.
231
+
232
+ Arguments:
233
+ metadata (MetadataResponse): broker response to a metadata request
234
+
235
+ Returns: None
236
+ """
237
+ # In the common case where we ask for a single topic and get back an
238
+ # error, we should fail the future
239
+ if len(metadata.topics) == 1 and metadata.topics[0][0] != 0:
240
+ error_code, topic = metadata.topics[0][:2]
241
+ error = Errors.for_code(error_code)(topic)
242
+ return self.failed_update(error)
243
+
244
+ if not metadata.brokers:
245
+ log.warning("No broker metadata found in MetadataResponse -- ignoring.")
246
+ return self.failed_update(Errors.MetadataEmptyBrokerList(metadata))
247
+
248
+ _new_brokers = {}
249
+ for broker in metadata.brokers:
250
+ if metadata.API_VERSION == 0:
251
+ node_id, host, port = broker
252
+ rack = None
253
+ else:
254
+ node_id, host, port, rack = broker
255
+ _new_brokers.update({
256
+ node_id: BrokerMetadata(node_id, host, port, rack)
257
+ })
258
+
259
+ if metadata.API_VERSION == 0:
260
+ _new_controller = None
261
+ else:
262
+ _new_controller = _new_brokers.get(metadata.controller_id)
263
+
264
+ _new_partitions = {}
265
+ _new_broker_partitions = collections.defaultdict(set)
266
+ _new_unauthorized_topics = set()
267
+ _new_internal_topics = set()
268
+
269
+ for topic_data in metadata.topics:
270
+ if metadata.API_VERSION == 0:
271
+ error_code, topic, partitions = topic_data
272
+ is_internal = False
273
+ else:
274
+ error_code, topic, is_internal, partitions = topic_data
275
+ if is_internal:
276
+ _new_internal_topics.add(topic)
277
+ error_type = Errors.for_code(error_code)
278
+ if error_type is Errors.NoError:
279
+ _new_partitions[topic] = {}
280
+ for p_error, partition, leader, replicas, isr in partitions:
281
+ _new_partitions[topic][partition] = PartitionMetadata(
282
+ topic=topic, partition=partition, leader=leader,
283
+ replicas=replicas, isr=isr, error=p_error)
284
+ if leader != -1:
285
+ _new_broker_partitions[leader].add(
286
+ TopicPartition(topic, partition))
287
+
288
+ # Specific topic errors can be ignored if this is a full metadata fetch
289
+ elif self.need_all_topic_metadata:
290
+ continue
291
+
292
+ elif error_type is Errors.LeaderNotAvailableError:
293
+ log.warning("Topic %s is not available during auto-create"
294
+ " initialization", topic)
295
+ elif error_type is Errors.UnknownTopicOrPartitionError:
296
+ log.error("Topic %s not found in cluster metadata", topic)
297
+ elif error_type is Errors.TopicAuthorizationFailedError:
298
+ log.error("Topic %s is not authorized for this client", topic)
299
+ _new_unauthorized_topics.add(topic)
300
+ elif error_type is Errors.InvalidTopicError:
301
+ log.error("'%s' is not a valid topic name", topic)
302
+ else:
303
+ log.error("Error fetching metadata for topic %s: %s",
304
+ topic, error_type)
305
+
306
+ with self._lock:
307
+ self._brokers = _new_brokers
308
+ self.controller = _new_controller
309
+ self._partitions = _new_partitions
310
+ self._broker_partitions = _new_broker_partitions
311
+ self.unauthorized_topics = _new_unauthorized_topics
312
+ self.internal_topics = _new_internal_topics
313
+ f = None
314
+ if self._future:
315
+ f = self._future
316
+ self._future = None
317
+ self._need_update = False
318
+
319
+ now = time.time() * 1000
320
+ self._last_refresh_ms = now
321
+ self._last_successful_refresh_ms = now
322
+
323
+ if f:
324
+ f.success(self)
325
+ log.debug("Updated cluster metadata to %s", self)
326
+
327
+ for listener in self._listeners:
328
+ listener(self)
329
+
330
+ if self.need_all_topic_metadata:
331
+ # the listener may change the interested topics,
332
+ # which could cause another metadata refresh.
333
+ # If we have already fetched all topics, however,
334
+ # another fetch should be unnecessary.
335
+ self._need_update = False
336
+
337
+ def add_listener(self, listener):
338
+ """Add a callback function to be called on each metadata update"""
339
+ self._listeners.add(listener)
340
+
341
+ def remove_listener(self, listener):
342
+ """Remove a previously added listener callback"""
343
+ self._listeners.remove(listener)
344
+
345
+ def add_group_coordinator(self, group, response):
346
+ """Update with metadata for a group coordinator
347
+
348
+ Arguments:
349
+ group (str): name of group from GroupCoordinatorRequest
350
+ response (GroupCoordinatorResponse): broker response
351
+
352
+ Returns:
353
+ string: coordinator node_id if metadata is updated, None on error
354
+ """
355
+ log.debug("Updating coordinator for %s: %s", group, response)
356
+ error_type = Errors.for_code(response.error_code)
357
+ if error_type is not Errors.NoError:
358
+ log.error("GroupCoordinatorResponse error: %s", error_type)
359
+ self._groups[group] = -1
360
+ return
361
+
362
+ # Use a coordinator-specific node id so that group requests
363
+ # get a dedicated connection
364
+ node_id = 'coordinator-{}'.format(response.coordinator_id)
365
+ coordinator = BrokerMetadata(
366
+ node_id,
367
+ response.host,
368
+ response.port,
369
+ None)
370
+
371
+ log.info("Group coordinator for %s is %s", group, coordinator)
372
+ self._coordinator_brokers[node_id] = coordinator
373
+ self._groups[group] = node_id
374
+ return node_id
375
+
376
+ def with_partitions(self, partitions_to_add):
377
+ """Returns a copy of cluster metadata with partitions added"""
378
+ new_metadata = ClusterMetadata(**self.config)
379
+ new_metadata._brokers = copy.deepcopy(self._brokers)
380
+ new_metadata._partitions = copy.deepcopy(self._partitions)
381
+ new_metadata._broker_partitions = copy.deepcopy(self._broker_partitions)
382
+ new_metadata._groups = copy.deepcopy(self._groups)
383
+ new_metadata.internal_topics = copy.deepcopy(self.internal_topics)
384
+ new_metadata.unauthorized_topics = copy.deepcopy(self.unauthorized_topics)
385
+
386
+ for partition in partitions_to_add:
387
+ new_metadata._partitions[partition.topic][partition.partition] = partition
388
+
389
+ if partition.leader is not None and partition.leader != -1:
390
+ new_metadata._broker_partitions[partition.leader].add(
391
+ TopicPartition(partition.topic, partition.partition))
392
+
393
+ return new_metadata
394
+
395
+ def __str__(self):
396
+ return 'ClusterMetadata(brokers: %d, topics: %d, groups: %d)' % \
397
+ (len(self._brokers), len(self._partitions), len(self._groups))
testbed/dpkp__kafka-python/kafka/codec.py ADDED
@@ -0,0 +1,326 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+
3
+ import gzip
4
+ import io
5
+ import platform
6
+ import struct
7
+
8
+ from kafka.vendor import six
9
+ from kafka.vendor.six.moves import range
10
+
11
+ _XERIAL_V1_HEADER = (-126, b'S', b'N', b'A', b'P', b'P', b'Y', 0, 1, 1)
12
+ _XERIAL_V1_FORMAT = 'bccccccBii'
13
+ ZSTD_MAX_OUTPUT_SIZE = 1024 * 1024
14
+
15
+ try:
16
+ import snappy
17
+ except ImportError:
18
+ snappy = None
19
+
20
+ try:
21
+ import zstandard as zstd
22
+ except ImportError:
23
+ zstd = None
24
+
25
+ try:
26
+ import lz4.frame as lz4
27
+
28
+ def _lz4_compress(payload, **kwargs):
29
+ # Kafka does not support LZ4 dependent blocks
30
+ try:
31
+ # For lz4>=0.12.0
32
+ kwargs.pop('block_linked', None)
33
+ return lz4.compress(payload, block_linked=False, **kwargs)
34
+ except TypeError:
35
+ # For earlier versions of lz4
36
+ kwargs.pop('block_mode', None)
37
+ return lz4.compress(payload, block_mode=1, **kwargs)
38
+
39
+ except ImportError:
40
+ lz4 = None
41
+
42
+ try:
43
+ import lz4f
44
+ except ImportError:
45
+ lz4f = None
46
+
47
+ try:
48
+ import lz4framed
49
+ except ImportError:
50
+ lz4framed = None
51
+
52
+ try:
53
+ import xxhash
54
+ except ImportError:
55
+ xxhash = None
56
+
57
+ PYPY = bool(platform.python_implementation() == 'PyPy')
58
+
59
+ def has_gzip():
60
+ return True
61
+
62
+
63
+ def has_snappy():
64
+ return snappy is not None
65
+
66
+
67
+ def has_zstd():
68
+ return zstd is not None
69
+
70
+
71
+ def has_lz4():
72
+ if lz4 is not None:
73
+ return True
74
+ if lz4f is not None:
75
+ return True
76
+ if lz4framed is not None:
77
+ return True
78
+ return False
79
+
80
+
81
+ def gzip_encode(payload, compresslevel=None):
82
+ if not compresslevel:
83
+ compresslevel = 9
84
+
85
+ buf = io.BytesIO()
86
+
87
+ # Gzip context manager introduced in python 2.7
88
+ # so old-fashioned way until we decide to not support 2.6
89
+ gzipper = gzip.GzipFile(fileobj=buf, mode="w", compresslevel=compresslevel)
90
+ try:
91
+ gzipper.write(payload)
92
+ finally:
93
+ gzipper.close()
94
+
95
+ return buf.getvalue()
96
+
97
+
98
+ def gzip_decode(payload):
99
+ buf = io.BytesIO(payload)
100
+
101
+ # Gzip context manager introduced in python 2.7
102
+ # so old-fashioned way until we decide to not support 2.6
103
+ gzipper = gzip.GzipFile(fileobj=buf, mode='r')
104
+ try:
105
+ return gzipper.read()
106
+ finally:
107
+ gzipper.close()
108
+
109
+
110
+ def snappy_encode(payload, xerial_compatible=True, xerial_blocksize=32*1024):
111
+ """Encodes the given data with snappy compression.
112
+
113
+ If xerial_compatible is set then the stream is encoded in a fashion
114
+ compatible with the xerial snappy library.
115
+
116
+ The block size (xerial_blocksize) controls how frequent the blocking occurs
117
+ 32k is the default in the xerial library.
118
+
119
+ The format winds up being:
120
+
121
+
122
+ +-------------+------------+--------------+------------+--------------+
123
+ | Header | Block1 len | Block1 data | Blockn len | Blockn data |
124
+ +-------------+------------+--------------+------------+--------------+
125
+ | 16 bytes | BE int32 | snappy bytes | BE int32 | snappy bytes |
126
+ +-------------+------------+--------------+------------+--------------+
127
+
128
+
129
+ It is important to note that the blocksize is the amount of uncompressed
130
+ data presented to snappy at each block, whereas the blocklen is the number
131
+ of bytes that will be present in the stream; so the length will always be
132
+ <= blocksize.
133
+
134
+ """
135
+
136
+ if not has_snappy():
137
+ raise NotImplementedError("Snappy codec is not available")
138
+
139
+ if not xerial_compatible:
140
+ return snappy.compress(payload)
141
+
142
+ out = io.BytesIO()
143
+ for fmt, dat in zip(_XERIAL_V1_FORMAT, _XERIAL_V1_HEADER):
144
+ out.write(struct.pack('!' + fmt, dat))
145
+
146
+ # Chunk through buffers to avoid creating intermediate slice copies
147
+ if PYPY:
148
+ # on pypy, snappy.compress() on a sliced buffer consumes the entire
149
+ # buffer... likely a python-snappy bug, so just use a slice copy
150
+ chunker = lambda payload, i, size: payload[i:size+i]
151
+
152
+ elif six.PY2:
153
+ # Sliced buffer avoids additional copies
154
+ # pylint: disable-msg=undefined-variable
155
+ chunker = lambda payload, i, size: buffer(payload, i, size)
156
+ else:
157
+ # snappy.compress does not like raw memoryviews, so we have to convert
158
+ # tobytes, which is a copy... oh well. it's the thought that counts.
159
+ # pylint: disable-msg=undefined-variable
160
+ chunker = lambda payload, i, size: memoryview(payload)[i:size+i].tobytes()
161
+
162
+ for chunk in (chunker(payload, i, xerial_blocksize)
163
+ for i in range(0, len(payload), xerial_blocksize)):
164
+
165
+ block = snappy.compress(chunk)
166
+ block_size = len(block)
167
+ out.write(struct.pack('!i', block_size))
168
+ out.write(block)
169
+
170
+ return out.getvalue()
171
+
172
+
173
+ def _detect_xerial_stream(payload):
174
+ """Detects if the data given might have been encoded with the blocking mode
175
+ of the xerial snappy library.
176
+
177
+ This mode writes a magic header of the format:
178
+ +--------+--------------+------------+---------+--------+
179
+ | Marker | Magic String | Null / Pad | Version | Compat |
180
+ +--------+--------------+------------+---------+--------+
181
+ | byte | c-string | byte | int32 | int32 |
182
+ +--------+--------------+------------+---------+--------+
183
+ | -126 | 'SNAPPY' | \0 | | |
184
+ +--------+--------------+------------+---------+--------+
185
+
186
+ The pad appears to be to ensure that SNAPPY is a valid cstring
187
+ The version is the version of this format as written by xerial,
188
+ in the wild this is currently 1 as such we only support v1.
189
+
190
+ Compat is there to claim the miniumum supported version that
191
+ can read a xerial block stream, presently in the wild this is
192
+ 1.
193
+ """
194
+
195
+ if len(payload) > 16:
196
+ header = struct.unpack('!' + _XERIAL_V1_FORMAT, bytes(payload)[:16])
197
+ return header == _XERIAL_V1_HEADER
198
+ return False
199
+
200
+
201
+ def snappy_decode(payload):
202
+ if not has_snappy():
203
+ raise NotImplementedError("Snappy codec is not available")
204
+
205
+ if _detect_xerial_stream(payload):
206
+ # TODO ? Should become a fileobj ?
207
+ out = io.BytesIO()
208
+ byt = payload[16:]
209
+ length = len(byt)
210
+ cursor = 0
211
+
212
+ while cursor < length:
213
+ block_size = struct.unpack_from('!i', byt[cursor:])[0]
214
+ # Skip the block size
215
+ cursor += 4
216
+ end = cursor + block_size
217
+ out.write(snappy.decompress(byt[cursor:end]))
218
+ cursor = end
219
+
220
+ out.seek(0)
221
+ return out.read()
222
+ else:
223
+ return snappy.decompress(payload)
224
+
225
+
226
+ if lz4:
227
+ lz4_encode = _lz4_compress # pylint: disable-msg=no-member
228
+ elif lz4f:
229
+ lz4_encode = lz4f.compressFrame # pylint: disable-msg=no-member
230
+ elif lz4framed:
231
+ lz4_encode = lz4framed.compress # pylint: disable-msg=no-member
232
+ else:
233
+ lz4_encode = None
234
+
235
+
236
+ def lz4f_decode(payload):
237
+ """Decode payload using interoperable LZ4 framing. Requires Kafka >= 0.10"""
238
+ # pylint: disable-msg=no-member
239
+ ctx = lz4f.createDecompContext()
240
+ data = lz4f.decompressFrame(payload, ctx)
241
+ lz4f.freeDecompContext(ctx)
242
+
243
+ # lz4f python module does not expose how much of the payload was
244
+ # actually read if the decompression was only partial.
245
+ if data['next'] != 0:
246
+ raise RuntimeError('lz4f unable to decompress full payload')
247
+ return data['decomp']
248
+
249
+
250
+ if lz4:
251
+ lz4_decode = lz4.decompress # pylint: disable-msg=no-member
252
+ elif lz4f:
253
+ lz4_decode = lz4f_decode
254
+ elif lz4framed:
255
+ lz4_decode = lz4framed.decompress # pylint: disable-msg=no-member
256
+ else:
257
+ lz4_decode = None
258
+
259
+
260
+ def lz4_encode_old_kafka(payload):
261
+ """Encode payload for 0.8/0.9 brokers -- requires an incorrect header checksum."""
262
+ assert xxhash is not None
263
+ data = lz4_encode(payload)
264
+ header_size = 7
265
+ flg = data[4]
266
+ if not isinstance(flg, int):
267
+ flg = ord(flg)
268
+
269
+ content_size_bit = ((flg >> 3) & 1)
270
+ if content_size_bit:
271
+ # Old kafka does not accept the content-size field
272
+ # so we need to discard it and reset the header flag
273
+ flg -= 8
274
+ data = bytearray(data)
275
+ data[4] = flg
276
+ data = bytes(data)
277
+ payload = data[header_size+8:]
278
+ else:
279
+ payload = data[header_size:]
280
+
281
+ # This is the incorrect hc
282
+ hc = xxhash.xxh32(data[0:header_size-1]).digest()[-2:-1] # pylint: disable-msg=no-member
283
+
284
+ return b''.join([
285
+ data[0:header_size-1],
286
+ hc,
287
+ payload
288
+ ])
289
+
290
+
291
+ def lz4_decode_old_kafka(payload):
292
+ assert xxhash is not None
293
+ # Kafka's LZ4 code has a bug in its header checksum implementation
294
+ header_size = 7
295
+ if isinstance(payload[4], int):
296
+ flg = payload[4]
297
+ else:
298
+ flg = ord(payload[4])
299
+ content_size_bit = ((flg >> 3) & 1)
300
+ if content_size_bit:
301
+ header_size += 8
302
+
303
+ # This should be the correct hc
304
+ hc = xxhash.xxh32(payload[4:header_size-1]).digest()[-2:-1] # pylint: disable-msg=no-member
305
+
306
+ munged_payload = b''.join([
307
+ payload[0:header_size-1],
308
+ hc,
309
+ payload[header_size:]
310
+ ])
311
+ return lz4_decode(munged_payload)
312
+
313
+
314
+ def zstd_encode(payload):
315
+ if not zstd:
316
+ raise NotImplementedError("Zstd codec is not available")
317
+ return zstd.ZstdCompressor().compress(payload)
318
+
319
+
320
+ def zstd_decode(payload):
321
+ if not zstd:
322
+ raise NotImplementedError("Zstd codec is not available")
323
+ try:
324
+ return zstd.ZstdDecompressor().decompress(payload)
325
+ except zstd.ZstdError:
326
+ return zstd.ZstdDecompressor().decompress(payload, max_output_size=ZSTD_MAX_OUTPUT_SIZE)
testbed/dpkp__kafka-python/kafka/conn.py ADDED
@@ -0,0 +1,1534 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import, division
2
+
3
+ import copy
4
+ import errno
5
+ import io
6
+ import logging
7
+ from random import shuffle, uniform
8
+
9
+ # selectors in stdlib as of py3.4
10
+ try:
11
+ import selectors # pylint: disable=import-error
12
+ except ImportError:
13
+ # vendored backport module
14
+ from kafka.vendor import selectors34 as selectors
15
+
16
+ import socket
17
+ import struct
18
+ import threading
19
+ import time
20
+
21
+ from kafka.vendor import six
22
+
23
+ import kafka.errors as Errors
24
+ from kafka.future import Future
25
+ from kafka.metrics.stats import Avg, Count, Max, Rate
26
+ from kafka.oauth.abstract import AbstractTokenProvider
27
+ from kafka.protocol.admin import SaslHandShakeRequest, DescribeAclsRequest_v2, DescribeClientQuotasRequest
28
+ from kafka.protocol.commit import OffsetFetchRequest
29
+ from kafka.protocol.offset import OffsetRequest
30
+ from kafka.protocol.produce import ProduceRequest
31
+ from kafka.protocol.metadata import MetadataRequest
32
+ from kafka.protocol.fetch import FetchRequest
33
+ from kafka.protocol.parser import KafkaProtocol
34
+ from kafka.protocol.types import Int32, Int8
35
+ from kafka.scram import ScramClient
36
+ from kafka.version import __version__
37
+
38
+
39
+ if six.PY2:
40
+ ConnectionError = socket.error
41
+ TimeoutError = socket.error
42
+ BlockingIOError = Exception
43
+
44
+ log = logging.getLogger(__name__)
45
+
46
+ DEFAULT_KAFKA_PORT = 9092
47
+
48
+ SASL_QOP_AUTH = 1
49
+ SASL_QOP_AUTH_INT = 2
50
+ SASL_QOP_AUTH_CONF = 4
51
+
52
+ try:
53
+ import ssl
54
+ ssl_available = True
55
+ try:
56
+ SSLEOFError = ssl.SSLEOFError
57
+ SSLWantReadError = ssl.SSLWantReadError
58
+ SSLWantWriteError = ssl.SSLWantWriteError
59
+ SSLZeroReturnError = ssl.SSLZeroReturnError
60
+ except AttributeError:
61
+ # support older ssl libraries
62
+ log.warning('Old SSL module detected.'
63
+ ' SSL error handling may not operate cleanly.'
64
+ ' Consider upgrading to Python 3.3 or 2.7.9')
65
+ SSLEOFError = ssl.SSLError
66
+ SSLWantReadError = ssl.SSLError
67
+ SSLWantWriteError = ssl.SSLError
68
+ SSLZeroReturnError = ssl.SSLError
69
+ except ImportError:
70
+ # support Python without ssl libraries
71
+ ssl_available = False
72
+ class SSLWantReadError(Exception):
73
+ pass
74
+ class SSLWantWriteError(Exception):
75
+ pass
76
+
77
+ # needed for SASL_GSSAPI authentication:
78
+ try:
79
+ import gssapi
80
+ from gssapi.raw.misc import GSSError
81
+ except ImportError:
82
+ #no gssapi available, will disable gssapi mechanism
83
+ gssapi = None
84
+ GSSError = None
85
+
86
+
87
+ AFI_NAMES = {
88
+ socket.AF_UNSPEC: "unspecified",
89
+ socket.AF_INET: "IPv4",
90
+ socket.AF_INET6: "IPv6",
91
+ }
92
+
93
+
94
+ class ConnectionStates(object):
95
+ DISCONNECTING = '<disconnecting>'
96
+ DISCONNECTED = '<disconnected>'
97
+ CONNECTING = '<connecting>'
98
+ HANDSHAKE = '<handshake>'
99
+ CONNECTED = '<connected>'
100
+ AUTHENTICATING = '<authenticating>'
101
+
102
+
103
+ class BrokerConnection(object):
104
+ """Initialize a Kafka broker connection
105
+
106
+ Keyword Arguments:
107
+ client_id (str): a name for this client. This string is passed in
108
+ each request to servers and can be used to identify specific
109
+ server-side log entries that correspond to this client. Also
110
+ submitted to GroupCoordinator for logging with respect to
111
+ consumer group administration. Default: 'kafka-python-{version}'
112
+ reconnect_backoff_ms (int): The amount of time in milliseconds to
113
+ wait before attempting to reconnect to a given host.
114
+ Default: 50.
115
+ reconnect_backoff_max_ms (int): The maximum amount of time in
116
+ milliseconds to backoff/wait when reconnecting to a broker that has
117
+ repeatedly failed to connect. If provided, the backoff per host
118
+ will increase exponentially for each consecutive connection
119
+ failure, up to this maximum. Once the maximum is reached,
120
+ reconnection attempts will continue periodically with this fixed
121
+ rate. To avoid connection storms, a randomization factor of 0.2
122
+ will be applied to the backoff resulting in a random range between
123
+ 20% below and 20% above the computed value. Default: 1000.
124
+ request_timeout_ms (int): Client request timeout in milliseconds.
125
+ Default: 30000.
126
+ max_in_flight_requests_per_connection (int): Requests are pipelined
127
+ to kafka brokers up to this number of maximum requests per
128
+ broker connection. Default: 5.
129
+ receive_buffer_bytes (int): The size of the TCP receive buffer
130
+ (SO_RCVBUF) to use when reading data. Default: None (relies on
131
+ system defaults). Java client defaults to 32768.
132
+ send_buffer_bytes (int): The size of the TCP send buffer
133
+ (SO_SNDBUF) to use when sending data. Default: None (relies on
134
+ system defaults). Java client defaults to 131072.
135
+ socket_options (list): List of tuple-arguments to socket.setsockopt
136
+ to apply to broker connection sockets. Default:
137
+ [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]
138
+ security_protocol (str): Protocol used to communicate with brokers.
139
+ Valid values are: PLAINTEXT, SSL, SASL_PLAINTEXT, SASL_SSL.
140
+ Default: PLAINTEXT.
141
+ ssl_context (ssl.SSLContext): pre-configured SSLContext for wrapping
142
+ socket connections. If provided, all other ssl_* configurations
143
+ will be ignored. Default: None.
144
+ ssl_check_hostname (bool): flag to configure whether ssl handshake
145
+ should verify that the certificate matches the brokers hostname.
146
+ default: True.
147
+ ssl_cafile (str): optional filename of ca file to use in certificate
148
+ verification. default: None.
149
+ ssl_certfile (str): optional filename of file in pem format containing
150
+ the client certificate, as well as any ca certificates needed to
151
+ establish the certificate's authenticity. default: None.
152
+ ssl_keyfile (str): optional filename containing the client private key.
153
+ default: None.
154
+ ssl_password (callable, str, bytes, bytearray): optional password or
155
+ callable function that returns a password, for decrypting the
156
+ client private key. Default: None.
157
+ ssl_crlfile (str): optional filename containing the CRL to check for
158
+ certificate expiration. By default, no CRL check is done. When
159
+ providing a file, only the leaf certificate will be checked against
160
+ this CRL. The CRL can only be checked with Python 3.4+ or 2.7.9+.
161
+ default: None.
162
+ ssl_ciphers (str): optionally set the available ciphers for ssl
163
+ connections. It should be a string in the OpenSSL cipher list
164
+ format. If no cipher can be selected (because compile-time options
165
+ or other configuration forbids use of all the specified ciphers),
166
+ an ssl.SSLError will be raised. See ssl.SSLContext.set_ciphers
167
+ api_version (tuple): Specify which Kafka API version to use.
168
+ Accepted values are: (0, 8, 0), (0, 8, 1), (0, 8, 2), (0, 9),
169
+ (0, 10). Default: (0, 8, 2)
170
+ api_version_auto_timeout_ms (int): number of milliseconds to throw a
171
+ timeout exception from the constructor when checking the broker
172
+ api version. Only applies if api_version is None
173
+ selector (selectors.BaseSelector): Provide a specific selector
174
+ implementation to use for I/O multiplexing.
175
+ Default: selectors.DefaultSelector
176
+ state_change_callback (callable): function to be called when the
177
+ connection state changes from CONNECTING to CONNECTED etc.
178
+ metrics (kafka.metrics.Metrics): Optionally provide a metrics
179
+ instance for capturing network IO stats. Default: None.
180
+ metric_group_prefix (str): Prefix for metric names. Default: ''
181
+ sasl_mechanism (str): Authentication mechanism when security_protocol
182
+ is configured for SASL_PLAINTEXT or SASL_SSL. Valid values are:
183
+ PLAIN, GSSAPI, OAUTHBEARER, SCRAM-SHA-256, SCRAM-SHA-512.
184
+ sasl_plain_username (str): username for sasl PLAIN and SCRAM authentication.
185
+ Required if sasl_mechanism is PLAIN or one of the SCRAM mechanisms.
186
+ sasl_plain_password (str): password for sasl PLAIN and SCRAM authentication.
187
+ Required if sasl_mechanism is PLAIN or one of the SCRAM mechanisms.
188
+ sasl_kerberos_service_name (str): Service name to include in GSSAPI
189
+ sasl mechanism handshake. Default: 'kafka'
190
+ sasl_kerberos_domain_name (str): kerberos domain name to use in GSSAPI
191
+ sasl mechanism handshake. Default: one of bootstrap servers
192
+ sasl_oauth_token_provider (AbstractTokenProvider): OAuthBearer token provider
193
+ instance. (See kafka.oauth.abstract). Default: None
194
+ """
195
+
196
+ DEFAULT_CONFIG = {
197
+ 'client_id': 'kafka-python-' + __version__,
198
+ 'node_id': 0,
199
+ 'request_timeout_ms': 30000,
200
+ 'reconnect_backoff_ms': 50,
201
+ 'reconnect_backoff_max_ms': 1000,
202
+ 'max_in_flight_requests_per_connection': 5,
203
+ 'receive_buffer_bytes': None,
204
+ 'send_buffer_bytes': None,
205
+ 'socket_options': [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)],
206
+ 'sock_chunk_bytes': 4096, # undocumented experimental option
207
+ 'sock_chunk_buffer_count': 1000, # undocumented experimental option
208
+ 'security_protocol': 'PLAINTEXT',
209
+ 'ssl_context': None,
210
+ 'ssl_check_hostname': True,
211
+ 'ssl_cafile': None,
212
+ 'ssl_certfile': None,
213
+ 'ssl_keyfile': None,
214
+ 'ssl_crlfile': None,
215
+ 'ssl_password': None,
216
+ 'ssl_ciphers': None,
217
+ 'api_version': (0, 8, 2), # default to most restrictive
218
+ 'selector': selectors.DefaultSelector,
219
+ 'state_change_callback': lambda node_id, sock, conn: True,
220
+ 'metrics': None,
221
+ 'metric_group_prefix': '',
222
+ 'sasl_mechanism': None,
223
+ 'sasl_plain_username': None,
224
+ 'sasl_plain_password': None,
225
+ 'sasl_kerberos_service_name': 'kafka',
226
+ 'sasl_kerberos_domain_name': None,
227
+ 'sasl_oauth_token_provider': None
228
+ }
229
+ SECURITY_PROTOCOLS = ('PLAINTEXT', 'SSL', 'SASL_PLAINTEXT', 'SASL_SSL')
230
+ SASL_MECHANISMS = ('PLAIN', 'GSSAPI', 'OAUTHBEARER', "SCRAM-SHA-256", "SCRAM-SHA-512")
231
+
232
+ def __init__(self, host, port, afi, **configs):
233
+ self.host = host
234
+ self.port = port
235
+ self.afi = afi
236
+ self._sock_afi = afi
237
+ self._sock_addr = None
238
+ self._api_versions = None
239
+
240
+ self.config = copy.copy(self.DEFAULT_CONFIG)
241
+ for key in self.config:
242
+ if key in configs:
243
+ self.config[key] = configs[key]
244
+
245
+ self.node_id = self.config.pop('node_id')
246
+
247
+ if self.config['receive_buffer_bytes'] is not None:
248
+ self.config['socket_options'].append(
249
+ (socket.SOL_SOCKET, socket.SO_RCVBUF,
250
+ self.config['receive_buffer_bytes']))
251
+ if self.config['send_buffer_bytes'] is not None:
252
+ self.config['socket_options'].append(
253
+ (socket.SOL_SOCKET, socket.SO_SNDBUF,
254
+ self.config['send_buffer_bytes']))
255
+
256
+ assert self.config['security_protocol'] in self.SECURITY_PROTOCOLS, (
257
+ 'security_protocol must be in ' + ', '.join(self.SECURITY_PROTOCOLS))
258
+
259
+ if self.config['security_protocol'] in ('SSL', 'SASL_SSL'):
260
+ assert ssl_available, "Python wasn't built with SSL support"
261
+
262
+ if self.config['security_protocol'] in ('SASL_PLAINTEXT', 'SASL_SSL'):
263
+ assert self.config['sasl_mechanism'] in self.SASL_MECHANISMS, (
264
+ 'sasl_mechanism must be in ' + ', '.join(self.SASL_MECHANISMS))
265
+ if self.config['sasl_mechanism'] in ('PLAIN', 'SCRAM-SHA-256', 'SCRAM-SHA-512'):
266
+ assert self.config['sasl_plain_username'] is not None, (
267
+ 'sasl_plain_username required for PLAIN or SCRAM sasl'
268
+ )
269
+ assert self.config['sasl_plain_password'] is not None, (
270
+ 'sasl_plain_password required for PLAIN or SCRAM sasl'
271
+ )
272
+ if self.config['sasl_mechanism'] == 'GSSAPI':
273
+ assert gssapi is not None, 'GSSAPI lib not available'
274
+ assert self.config['sasl_kerberos_service_name'] is not None, 'sasl_kerberos_service_name required for GSSAPI sasl'
275
+ if self.config['sasl_mechanism'] == 'OAUTHBEARER':
276
+ token_provider = self.config['sasl_oauth_token_provider']
277
+ assert token_provider is not None, 'sasl_oauth_token_provider required for OAUTHBEARER sasl'
278
+ assert callable(getattr(token_provider, "token", None)), 'sasl_oauth_token_provider must implement method #token()'
279
+ # This is not a general lock / this class is not generally thread-safe yet
280
+ # However, to avoid pushing responsibility for maintaining
281
+ # per-connection locks to the upstream client, we will use this lock to
282
+ # make sure that access to the protocol buffer is synchronized
283
+ # when sends happen on multiple threads
284
+ self._lock = threading.Lock()
285
+
286
+ # the protocol parser instance manages actual tracking of the
287
+ # sequence of in-flight requests to responses, which should
288
+ # function like a FIFO queue. For additional request data,
289
+ # including tracking request futures and timestamps, we
290
+ # can use a simple dictionary of correlation_id => request data
291
+ self.in_flight_requests = dict()
292
+
293
+ self._protocol = KafkaProtocol(
294
+ client_id=self.config['client_id'],
295
+ api_version=self.config['api_version'])
296
+ self.state = ConnectionStates.DISCONNECTED
297
+ self._reset_reconnect_backoff()
298
+ self._sock = None
299
+ self._send_buffer = b''
300
+ self._ssl_context = None
301
+ if self.config['ssl_context'] is not None:
302
+ self._ssl_context = self.config['ssl_context']
303
+ self._sasl_auth_future = None
304
+ self.last_attempt = 0
305
+ self._gai = []
306
+ self._sensors = None
307
+ if self.config['metrics']:
308
+ self._sensors = BrokerConnectionMetrics(self.config['metrics'],
309
+ self.config['metric_group_prefix'],
310
+ self.node_id)
311
+
312
+ def _dns_lookup(self):
313
+ self._gai = dns_lookup(self.host, self.port, self.afi)
314
+ if not self._gai:
315
+ log.error('DNS lookup failed for %s:%i (%s)',
316
+ self.host, self.port, self.afi)
317
+ return False
318
+ return True
319
+
320
+ def _next_afi_sockaddr(self):
321
+ if not self._gai:
322
+ if not self._dns_lookup():
323
+ return
324
+ afi, _, __, ___, sockaddr = self._gai.pop(0)
325
+ return (afi, sockaddr)
326
+
327
+ def connect_blocking(self, timeout=float('inf')):
328
+ if self.connected():
329
+ return True
330
+ timeout += time.time()
331
+ # First attempt to perform dns lookup
332
+ # note that the underlying interface, socket.getaddrinfo,
333
+ # has no explicit timeout so we may exceed the user-specified timeout
334
+ self._dns_lookup()
335
+
336
+ # Loop once over all returned dns entries
337
+ selector = None
338
+ while self._gai:
339
+ while time.time() < timeout:
340
+ self.connect()
341
+ if self.connected():
342
+ if selector is not None:
343
+ selector.close()
344
+ return True
345
+ elif self.connecting():
346
+ if selector is None:
347
+ selector = self.config['selector']()
348
+ selector.register(self._sock, selectors.EVENT_WRITE)
349
+ selector.select(1)
350
+ elif self.disconnected():
351
+ if selector is not None:
352
+ selector.close()
353
+ selector = None
354
+ break
355
+ else:
356
+ break
357
+ return False
358
+
359
+ def connect(self):
360
+ """Attempt to connect and return ConnectionState"""
361
+ if self.state is ConnectionStates.DISCONNECTED and not self.blacked_out():
362
+ self.last_attempt = time.time()
363
+ next_lookup = self._next_afi_sockaddr()
364
+ if not next_lookup:
365
+ self.close(Errors.KafkaConnectionError('DNS failure'))
366
+ return self.state
367
+ else:
368
+ log.debug('%s: creating new socket', self)
369
+ assert self._sock is None
370
+ self._sock_afi, self._sock_addr = next_lookup
371
+ self._sock = socket.socket(self._sock_afi, socket.SOCK_STREAM)
372
+
373
+ for option in self.config['socket_options']:
374
+ log.debug('%s: setting socket option %s', self, option)
375
+ self._sock.setsockopt(*option)
376
+
377
+ self._sock.setblocking(False)
378
+ self.state = ConnectionStates.CONNECTING
379
+ self.config['state_change_callback'](self.node_id, self._sock, self)
380
+ log.info('%s: connecting to %s:%d [%s %s]', self, self.host,
381
+ self.port, self._sock_addr, AFI_NAMES[self._sock_afi])
382
+
383
+ if self.state is ConnectionStates.CONNECTING:
384
+ # in non-blocking mode, use repeated calls to socket.connect_ex
385
+ # to check connection status
386
+ ret = None
387
+ try:
388
+ ret = self._sock.connect_ex(self._sock_addr)
389
+ except socket.error as err:
390
+ ret = err.errno
391
+
392
+ # Connection succeeded
393
+ if not ret or ret == errno.EISCONN:
394
+ log.debug('%s: established TCP connection', self)
395
+
396
+ if self.config['security_protocol'] in ('SSL', 'SASL_SSL'):
397
+ log.debug('%s: initiating SSL handshake', self)
398
+ self.state = ConnectionStates.HANDSHAKE
399
+ self.config['state_change_callback'](self.node_id, self._sock, self)
400
+ # _wrap_ssl can alter the connection state -- disconnects on failure
401
+ self._wrap_ssl()
402
+
403
+ elif self.config['security_protocol'] == 'SASL_PLAINTEXT':
404
+ log.debug('%s: initiating SASL authentication', self)
405
+ self.state = ConnectionStates.AUTHENTICATING
406
+ self.config['state_change_callback'](self.node_id, self._sock, self)
407
+
408
+ else:
409
+ # security_protocol PLAINTEXT
410
+ log.info('%s: Connection complete.', self)
411
+ self.state = ConnectionStates.CONNECTED
412
+ self._reset_reconnect_backoff()
413
+ self.config['state_change_callback'](self.node_id, self._sock, self)
414
+
415
+ # Connection failed
416
+ # WSAEINVAL == 10022, but errno.WSAEINVAL is not available on non-win systems
417
+ elif ret not in (errno.EINPROGRESS, errno.EALREADY, errno.EWOULDBLOCK, 10022):
418
+ log.error('Connect attempt to %s returned error %s.'
419
+ ' Disconnecting.', self, ret)
420
+ errstr = errno.errorcode.get(ret, 'UNKNOWN')
421
+ self.close(Errors.KafkaConnectionError('{} {}'.format(ret, errstr)))
422
+ return self.state
423
+
424
+ # Needs retry
425
+ else:
426
+ pass
427
+
428
+ if self.state is ConnectionStates.HANDSHAKE:
429
+ if self._try_handshake():
430
+ log.debug('%s: completed SSL handshake.', self)
431
+ if self.config['security_protocol'] == 'SASL_SSL':
432
+ log.debug('%s: initiating SASL authentication', self)
433
+ self.state = ConnectionStates.AUTHENTICATING
434
+ else:
435
+ log.info('%s: Connection complete.', self)
436
+ self.state = ConnectionStates.CONNECTED
437
+ self._reset_reconnect_backoff()
438
+ self.config['state_change_callback'](self.node_id, self._sock, self)
439
+
440
+ if self.state is ConnectionStates.AUTHENTICATING:
441
+ assert self.config['security_protocol'] in ('SASL_PLAINTEXT', 'SASL_SSL')
442
+ if self._try_authenticate():
443
+ # _try_authenticate has side-effects: possibly disconnected on socket errors
444
+ if self.state is ConnectionStates.AUTHENTICATING:
445
+ log.info('%s: Connection complete.', self)
446
+ self.state = ConnectionStates.CONNECTED
447
+ self._reset_reconnect_backoff()
448
+ self.config['state_change_callback'](self.node_id, self._sock, self)
449
+
450
+ if self.state not in (ConnectionStates.CONNECTED,
451
+ ConnectionStates.DISCONNECTED):
452
+ # Connection timed out
453
+ request_timeout = self.config['request_timeout_ms'] / 1000.0
454
+ if time.time() > request_timeout + self.last_attempt:
455
+ log.error('Connection attempt to %s timed out', self)
456
+ self.close(Errors.KafkaConnectionError('timeout'))
457
+ return self.state
458
+
459
+ return self.state
460
+
461
+ def _wrap_ssl(self):
462
+ assert self.config['security_protocol'] in ('SSL', 'SASL_SSL')
463
+ if self._ssl_context is None:
464
+ log.debug('%s: configuring default SSL Context', self)
465
+ self._ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) # pylint: disable=no-member
466
+ self._ssl_context.options |= ssl.OP_NO_SSLv2 # pylint: disable=no-member
467
+ self._ssl_context.options |= ssl.OP_NO_SSLv3 # pylint: disable=no-member
468
+ self._ssl_context.verify_mode = ssl.CERT_OPTIONAL
469
+ if self.config['ssl_check_hostname']:
470
+ self._ssl_context.check_hostname = True
471
+ if self.config['ssl_cafile']:
472
+ log.info('%s: Loading SSL CA from %s', self, self.config['ssl_cafile'])
473
+ self._ssl_context.load_verify_locations(self.config['ssl_cafile'])
474
+ self._ssl_context.verify_mode = ssl.CERT_REQUIRED
475
+ else:
476
+ log.info('%s: Loading system default SSL CAs from %s', self, ssl.get_default_verify_paths())
477
+ self._ssl_context.load_default_certs()
478
+ if self.config['ssl_certfile'] and self.config['ssl_keyfile']:
479
+ log.info('%s: Loading SSL Cert from %s', self, self.config['ssl_certfile'])
480
+ log.info('%s: Loading SSL Key from %s', self, self.config['ssl_keyfile'])
481
+ self._ssl_context.load_cert_chain(
482
+ certfile=self.config['ssl_certfile'],
483
+ keyfile=self.config['ssl_keyfile'],
484
+ password=self.config['ssl_password'])
485
+ if self.config['ssl_crlfile']:
486
+ if not hasattr(ssl, 'VERIFY_CRL_CHECK_LEAF'):
487
+ raise RuntimeError('This version of Python does not support ssl_crlfile!')
488
+ log.info('%s: Loading SSL CRL from %s', self, self.config['ssl_crlfile'])
489
+ self._ssl_context.load_verify_locations(self.config['ssl_crlfile'])
490
+ # pylint: disable=no-member
491
+ self._ssl_context.verify_flags |= ssl.VERIFY_CRL_CHECK_LEAF
492
+ if self.config['ssl_ciphers']:
493
+ log.info('%s: Setting SSL Ciphers: %s', self, self.config['ssl_ciphers'])
494
+ self._ssl_context.set_ciphers(self.config['ssl_ciphers'])
495
+ log.debug('%s: wrapping socket in ssl context', self)
496
+ try:
497
+ self._sock = self._ssl_context.wrap_socket(
498
+ self._sock,
499
+ server_hostname=self.host,
500
+ do_handshake_on_connect=False)
501
+ except ssl.SSLError as e:
502
+ log.exception('%s: Failed to wrap socket in SSLContext!', self)
503
+ self.close(e)
504
+
505
+ def _try_handshake(self):
506
+ assert self.config['security_protocol'] in ('SSL', 'SASL_SSL')
507
+ try:
508
+ self._sock.do_handshake()
509
+ return True
510
+ # old ssl in python2.6 will swallow all SSLErrors here...
511
+ except (SSLWantReadError, SSLWantWriteError):
512
+ pass
513
+ except (SSLZeroReturnError, ConnectionError, TimeoutError, SSLEOFError):
514
+ log.warning('SSL connection closed by server during handshake.')
515
+ self.close(Errors.KafkaConnectionError('SSL connection closed by server during handshake'))
516
+ # Other SSLErrors will be raised to user
517
+
518
+ return False
519
+
520
+ def _try_authenticate(self):
521
+ assert self.config['api_version'] is None or self.config['api_version'] >= (0, 10)
522
+
523
+ if self._sasl_auth_future is None:
524
+ # Build a SaslHandShakeRequest message
525
+ request = SaslHandShakeRequest[0](self.config['sasl_mechanism'])
526
+ future = Future()
527
+ sasl_response = self._send(request)
528
+ sasl_response.add_callback(self._handle_sasl_handshake_response, future)
529
+ sasl_response.add_errback(lambda f, e: f.failure(e), future)
530
+ self._sasl_auth_future = future
531
+
532
+ for r, f in self.recv():
533
+ f.success(r)
534
+
535
+ # A connection error could trigger close() which will reset the future
536
+ if self._sasl_auth_future is None:
537
+ return False
538
+ elif self._sasl_auth_future.failed():
539
+ ex = self._sasl_auth_future.exception
540
+ if not isinstance(ex, Errors.KafkaConnectionError):
541
+ raise ex # pylint: disable-msg=raising-bad-type
542
+ return self._sasl_auth_future.succeeded()
543
+
544
+ def _handle_sasl_handshake_response(self, future, response):
545
+ error_type = Errors.for_code(response.error_code)
546
+ if error_type is not Errors.NoError:
547
+ error = error_type(self)
548
+ self.close(error=error)
549
+ return future.failure(error_type(self))
550
+
551
+ if self.config['sasl_mechanism'] not in response.enabled_mechanisms:
552
+ return future.failure(
553
+ Errors.UnsupportedSaslMechanismError(
554
+ 'Kafka broker does not support %s sasl mechanism. Enabled mechanisms are: %s'
555
+ % (self.config['sasl_mechanism'], response.enabled_mechanisms)))
556
+ elif self.config['sasl_mechanism'] == 'PLAIN':
557
+ return self._try_authenticate_plain(future)
558
+ elif self.config['sasl_mechanism'] == 'GSSAPI':
559
+ return self._try_authenticate_gssapi(future)
560
+ elif self.config['sasl_mechanism'] == 'OAUTHBEARER':
561
+ return self._try_authenticate_oauth(future)
562
+ elif self.config['sasl_mechanism'].startswith("SCRAM-SHA-"):
563
+ return self._try_authenticate_scram(future)
564
+ else:
565
+ return future.failure(
566
+ Errors.UnsupportedSaslMechanismError(
567
+ 'kafka-python does not support SASL mechanism %s' %
568
+ self.config['sasl_mechanism']))
569
+
570
+ def _send_bytes(self, data):
571
+ """Send some data via non-blocking IO
572
+
573
+ Note: this method is not synchronized internally; you should
574
+ always hold the _lock before calling
575
+
576
+ Returns: number of bytes
577
+ Raises: socket exception
578
+ """
579
+ total_sent = 0
580
+ while total_sent < len(data):
581
+ try:
582
+ sent_bytes = self._sock.send(data[total_sent:])
583
+ total_sent += sent_bytes
584
+ except (SSLWantReadError, SSLWantWriteError):
585
+ break
586
+ except (ConnectionError, TimeoutError) as e:
587
+ if six.PY2 and e.errno == errno.EWOULDBLOCK:
588
+ break
589
+ raise
590
+ except BlockingIOError:
591
+ if six.PY3:
592
+ break
593
+ raise
594
+ return total_sent
595
+
596
+ def _send_bytes_blocking(self, data):
597
+ self._sock.settimeout(self.config['request_timeout_ms'] / 1000)
598
+ total_sent = 0
599
+ try:
600
+ while total_sent < len(data):
601
+ sent_bytes = self._sock.send(data[total_sent:])
602
+ total_sent += sent_bytes
603
+ if total_sent != len(data):
604
+ raise ConnectionError('Buffer overrun during socket send')
605
+ return total_sent
606
+ finally:
607
+ self._sock.settimeout(0.0)
608
+
609
+ def _recv_bytes_blocking(self, n):
610
+ self._sock.settimeout(self.config['request_timeout_ms'] / 1000)
611
+ try:
612
+ data = b''
613
+ while len(data) < n:
614
+ fragment = self._sock.recv(n - len(data))
615
+ if not fragment:
616
+ raise ConnectionError('Connection reset during recv')
617
+ data += fragment
618
+ return data
619
+ finally:
620
+ self._sock.settimeout(0.0)
621
+
622
+ def _try_authenticate_plain(self, future):
623
+ if self.config['security_protocol'] == 'SASL_PLAINTEXT':
624
+ log.warning('%s: Sending username and password in the clear', self)
625
+
626
+ data = b''
627
+ # Send PLAIN credentials per RFC-4616
628
+ msg = bytes('\0'.join([self.config['sasl_plain_username'],
629
+ self.config['sasl_plain_username'],
630
+ self.config['sasl_plain_password']]).encode('utf-8'))
631
+ size = Int32.encode(len(msg))
632
+
633
+ err = None
634
+ close = False
635
+ with self._lock:
636
+ if not self._can_send_recv():
637
+ err = Errors.NodeNotReadyError(str(self))
638
+ close = False
639
+ else:
640
+ try:
641
+ self._send_bytes_blocking(size + msg)
642
+
643
+ # The server will send a zero sized message (that is Int32(0)) on success.
644
+ # The connection is closed on failure
645
+ data = self._recv_bytes_blocking(4)
646
+
647
+ except (ConnectionError, TimeoutError) as e:
648
+ log.exception("%s: Error receiving reply from server", self)
649
+ err = Errors.KafkaConnectionError("%s: %s" % (self, e))
650
+ close = True
651
+
652
+ if err is not None:
653
+ if close:
654
+ self.close(error=err)
655
+ return future.failure(err)
656
+
657
+ if data != b'\x00\x00\x00\x00':
658
+ error = Errors.AuthenticationFailedError('Unrecognized response during authentication')
659
+ return future.failure(error)
660
+
661
+ log.info('%s: Authenticated as %s via PLAIN', self, self.config['sasl_plain_username'])
662
+ return future.success(True)
663
+
664
+ def _try_authenticate_scram(self, future):
665
+ if self.config['security_protocol'] == 'SASL_PLAINTEXT':
666
+ log.warning('%s: Exchanging credentials in the clear', self)
667
+
668
+ scram_client = ScramClient(
669
+ self.config['sasl_plain_username'], self.config['sasl_plain_password'], self.config['sasl_mechanism']
670
+ )
671
+
672
+ err = None
673
+ close = False
674
+ with self._lock:
675
+ if not self._can_send_recv():
676
+ err = Errors.NodeNotReadyError(str(self))
677
+ close = False
678
+ else:
679
+ try:
680
+ client_first = scram_client.first_message().encode('utf-8')
681
+ size = Int32.encode(len(client_first))
682
+ self._send_bytes_blocking(size + client_first)
683
+
684
+ (data_len,) = struct.unpack('>i', self._recv_bytes_blocking(4))
685
+ server_first = self._recv_bytes_blocking(data_len).decode('utf-8')
686
+ scram_client.process_server_first_message(server_first)
687
+
688
+ client_final = scram_client.final_message().encode('utf-8')
689
+ size = Int32.encode(len(client_final))
690
+ self._send_bytes_blocking(size + client_final)
691
+
692
+ (data_len,) = struct.unpack('>i', self._recv_bytes_blocking(4))
693
+ server_final = self._recv_bytes_blocking(data_len).decode('utf-8')
694
+ scram_client.process_server_final_message(server_final)
695
+
696
+ except (ConnectionError, TimeoutError) as e:
697
+ log.exception("%s: Error receiving reply from server", self)
698
+ err = Errors.KafkaConnectionError("%s: %s" % (self, e))
699
+ close = True
700
+
701
+ if err is not None:
702
+ if close:
703
+ self.close(error=err)
704
+ return future.failure(err)
705
+
706
+ log.info(
707
+ '%s: Authenticated as %s via %s', self, self.config['sasl_plain_username'], self.config['sasl_mechanism']
708
+ )
709
+ return future.success(True)
710
+
711
+ def _try_authenticate_gssapi(self, future):
712
+ kerberos_damin_name = self.config['sasl_kerberos_domain_name'] or self.host
713
+ auth_id = self.config['sasl_kerberos_service_name'] + '@' + kerberos_damin_name
714
+ gssapi_name = gssapi.Name(
715
+ auth_id,
716
+ name_type=gssapi.NameType.hostbased_service
717
+ ).canonicalize(gssapi.MechType.kerberos)
718
+ log.debug('%s: GSSAPI name: %s', self, gssapi_name)
719
+
720
+ err = None
721
+ close = False
722
+ with self._lock:
723
+ if not self._can_send_recv():
724
+ err = Errors.NodeNotReadyError(str(self))
725
+ close = False
726
+ else:
727
+ # Establish security context and negotiate protection level
728
+ # For reference RFC 2222, section 7.2.1
729
+ try:
730
+ # Exchange tokens until authentication either succeeds or fails
731
+ client_ctx = gssapi.SecurityContext(name=gssapi_name, usage='initiate')
732
+ received_token = None
733
+ while not client_ctx.complete:
734
+ # calculate an output token from kafka token (or None if first iteration)
735
+ output_token = client_ctx.step(received_token)
736
+
737
+ # pass output token to kafka, or send empty response if the security
738
+ # context is complete (output token is None in that case)
739
+ if output_token is None:
740
+ self._send_bytes_blocking(Int32.encode(0))
741
+ else:
742
+ msg = output_token
743
+ size = Int32.encode(len(msg))
744
+ self._send_bytes_blocking(size + msg)
745
+
746
+ # The server will send a token back. Processing of this token either
747
+ # establishes a security context, or it needs further token exchange.
748
+ # The gssapi will be able to identify the needed next step.
749
+ # The connection is closed on failure.
750
+ header = self._recv_bytes_blocking(4)
751
+ (token_size,) = struct.unpack('>i', header)
752
+ received_token = self._recv_bytes_blocking(token_size)
753
+
754
+ # Process the security layer negotiation token, sent by the server
755
+ # once the security context is established.
756
+
757
+ # unwraps message containing supported protection levels and msg size
758
+ msg = client_ctx.unwrap(received_token).message
759
+ # Kafka currently doesn't support integrity or confidentiality security layers, so we
760
+ # simply set QoP to 'auth' only (first octet). We reuse the max message size proposed
761
+ # by the server
762
+ msg = Int8.encode(SASL_QOP_AUTH & Int8.decode(io.BytesIO(msg[0:1]))) + msg[1:]
763
+ # add authorization identity to the response, GSS-wrap and send it
764
+ msg = client_ctx.wrap(msg + auth_id.encode(), False).message
765
+ size = Int32.encode(len(msg))
766
+ self._send_bytes_blocking(size + msg)
767
+
768
+ except (ConnectionError, TimeoutError) as e:
769
+ log.exception("%s: Error receiving reply from server", self)
770
+ err = Errors.KafkaConnectionError("%s: %s" % (self, e))
771
+ close = True
772
+ except Exception as e:
773
+ err = e
774
+ close = True
775
+
776
+ if err is not None:
777
+ if close:
778
+ self.close(error=err)
779
+ return future.failure(err)
780
+
781
+ log.info('%s: Authenticated as %s via GSSAPI', self, gssapi_name)
782
+ return future.success(True)
783
+
784
+ def _try_authenticate_oauth(self, future):
785
+ data = b''
786
+
787
+ msg = bytes(self._build_oauth_client_request().encode("utf-8"))
788
+ size = Int32.encode(len(msg))
789
+
790
+ err = None
791
+ close = False
792
+ with self._lock:
793
+ if not self._can_send_recv():
794
+ err = Errors.NodeNotReadyError(str(self))
795
+ close = False
796
+ else:
797
+ try:
798
+ # Send SASL OAuthBearer request with OAuth token
799
+ self._send_bytes_blocking(size + msg)
800
+
801
+ # The server will send a zero sized message (that is Int32(0)) on success.
802
+ # The connection is closed on failure
803
+ data = self._recv_bytes_blocking(4)
804
+
805
+ except (ConnectionError, TimeoutError) as e:
806
+ log.exception("%s: Error receiving reply from server", self)
807
+ err = Errors.KafkaConnectionError("%s: %s" % (self, e))
808
+ close = True
809
+
810
+ if err is not None:
811
+ if close:
812
+ self.close(error=err)
813
+ return future.failure(err)
814
+
815
+ if data != b'\x00\x00\x00\x00':
816
+ error = Errors.AuthenticationFailedError('Unrecognized response during authentication')
817
+ return future.failure(error)
818
+
819
+ log.info('%s: Authenticated via OAuth', self)
820
+ return future.success(True)
821
+
822
+ def _build_oauth_client_request(self):
823
+ token_provider = self.config['sasl_oauth_token_provider']
824
+ return "n,,\x01auth=Bearer {}{}\x01\x01".format(token_provider.token(), self._token_extensions())
825
+
826
+ def _token_extensions(self):
827
+ """
828
+ Return a string representation of the OPTIONAL key-value pairs that can be sent with an OAUTHBEARER
829
+ initial request.
830
+ """
831
+ token_provider = self.config['sasl_oauth_token_provider']
832
+
833
+ # Only run if the #extensions() method is implemented by the clients Token Provider class
834
+ # Builds up a string separated by \x01 via a dict of key value pairs
835
+ if callable(getattr(token_provider, "extensions", None)) and len(token_provider.extensions()) > 0:
836
+ msg = "\x01".join(["{}={}".format(k, v) for k, v in token_provider.extensions().items()])
837
+ return "\x01" + msg
838
+ else:
839
+ return ""
840
+
841
+ def blacked_out(self):
842
+ """
843
+ Return true if we are disconnected from the given node and can't
844
+ re-establish a connection yet
845
+ """
846
+ if self.state is ConnectionStates.DISCONNECTED:
847
+ if time.time() < self.last_attempt + self._reconnect_backoff:
848
+ return True
849
+ return False
850
+
851
+ def connection_delay(self):
852
+ """
853
+ Return the number of milliseconds to wait, based on the connection
854
+ state, before attempting to send data. When disconnected, this respects
855
+ the reconnect backoff time. When connecting or connected, returns a very
856
+ large number to handle slow/stalled connections.
857
+ """
858
+ time_waited = time.time() - (self.last_attempt or 0)
859
+ if self.state is ConnectionStates.DISCONNECTED:
860
+ return max(self._reconnect_backoff - time_waited, 0) * 1000
861
+ else:
862
+ # When connecting or connected, we should be able to delay
863
+ # indefinitely since other events (connection or data acked) will
864
+ # cause a wakeup once data can be sent.
865
+ return float('inf')
866
+
867
+ def connected(self):
868
+ """Return True iff socket is connected."""
869
+ return self.state is ConnectionStates.CONNECTED
870
+
871
+ def connecting(self):
872
+ """Returns True if still connecting (this may encompass several
873
+ different states, such as SSL handshake, authorization, etc)."""
874
+ return self.state in (ConnectionStates.CONNECTING,
875
+ ConnectionStates.HANDSHAKE,
876
+ ConnectionStates.AUTHENTICATING)
877
+
878
+ def disconnected(self):
879
+ """Return True iff socket is closed"""
880
+ return self.state is ConnectionStates.DISCONNECTED
881
+
882
+ def _reset_reconnect_backoff(self):
883
+ self._failures = 0
884
+ self._reconnect_backoff = self.config['reconnect_backoff_ms'] / 1000.0
885
+
886
+ def _update_reconnect_backoff(self):
887
+ # Do not mark as failure if there are more dns entries available to try
888
+ if len(self._gai) > 0:
889
+ return
890
+ if self.config['reconnect_backoff_max_ms'] > self.config['reconnect_backoff_ms']:
891
+ self._failures += 1
892
+ self._reconnect_backoff = self.config['reconnect_backoff_ms'] * 2 ** (self._failures - 1)
893
+ self._reconnect_backoff = min(self._reconnect_backoff, self.config['reconnect_backoff_max_ms'])
894
+ self._reconnect_backoff *= uniform(0.8, 1.2)
895
+ self._reconnect_backoff /= 1000.0
896
+ log.debug('%s: reconnect backoff %s after %s failures', self, self._reconnect_backoff, self._failures)
897
+
898
+ def _close_socket(self):
899
+ if hasattr(self, '_sock') and self._sock is not None:
900
+ self._sock.close()
901
+ self._sock = None
902
+
903
+ def __del__(self):
904
+ self._close_socket()
905
+
906
+ def close(self, error=None):
907
+ """Close socket and fail all in-flight-requests.
908
+
909
+ Arguments:
910
+ error (Exception, optional): pending in-flight-requests
911
+ will be failed with this exception.
912
+ Default: kafka.errors.KafkaConnectionError.
913
+ """
914
+ if self.state is ConnectionStates.DISCONNECTED:
915
+ return
916
+ with self._lock:
917
+ if self.state is ConnectionStates.DISCONNECTED:
918
+ return
919
+ log.info('%s: Closing connection. %s', self, error or '')
920
+ self._update_reconnect_backoff()
921
+ self._sasl_auth_future = None
922
+ self._protocol = KafkaProtocol(
923
+ client_id=self.config['client_id'],
924
+ api_version=self.config['api_version'])
925
+ self._send_buffer = b''
926
+ if error is None:
927
+ error = Errors.Cancelled(str(self))
928
+ ifrs = list(self.in_flight_requests.items())
929
+ self.in_flight_requests.clear()
930
+ self.state = ConnectionStates.DISCONNECTED
931
+ # To avoid race conditions and/or deadlocks
932
+ # keep a reference to the socket but leave it
933
+ # open until after the state_change_callback
934
+ # This should give clients a change to deregister
935
+ # the socket fd from selectors cleanly.
936
+ sock = self._sock
937
+ self._sock = None
938
+
939
+ # drop lock before state change callback and processing futures
940
+ self.config['state_change_callback'](self.node_id, sock, self)
941
+ sock.close()
942
+ for (_correlation_id, (future, _timestamp)) in ifrs:
943
+ future.failure(error)
944
+
945
+ def _can_send_recv(self):
946
+ """Return True iff socket is ready for requests / responses"""
947
+ return self.state in (ConnectionStates.AUTHENTICATING,
948
+ ConnectionStates.CONNECTED)
949
+
950
+ def send(self, request, blocking=True):
951
+ """Queue request for async network send, return Future()"""
952
+ future = Future()
953
+ if self.connecting():
954
+ return future.failure(Errors.NodeNotReadyError(str(self)))
955
+ elif not self.connected():
956
+ return future.failure(Errors.KafkaConnectionError(str(self)))
957
+ elif not self.can_send_more():
958
+ return future.failure(Errors.TooManyInFlightRequests(str(self)))
959
+ return self._send(request, blocking=blocking)
960
+
961
+ def _send(self, request, blocking=True):
962
+ future = Future()
963
+ with self._lock:
964
+ if not self._can_send_recv():
965
+ # In this case, since we created the future above,
966
+ # we know there are no callbacks/errbacks that could fire w/
967
+ # lock. So failing + returning inline should be safe
968
+ return future.failure(Errors.NodeNotReadyError(str(self)))
969
+
970
+ correlation_id = self._protocol.send_request(request)
971
+
972
+ log.debug('%s Request %d: %s', self, correlation_id, request)
973
+ if request.expect_response():
974
+ sent_time = time.time()
975
+ assert correlation_id not in self.in_flight_requests, 'Correlation ID already in-flight!'
976
+ self.in_flight_requests[correlation_id] = (future, sent_time)
977
+ else:
978
+ future.success(None)
979
+
980
+ # Attempt to replicate behavior from prior to introduction of
981
+ # send_pending_requests() / async sends
982
+ if blocking:
983
+ self.send_pending_requests()
984
+
985
+ return future
986
+
987
+ def send_pending_requests(self):
988
+ """Attempts to send pending requests messages via blocking IO
989
+ If all requests have been sent, return True
990
+ Otherwise, if the socket is blocked and there are more bytes to send,
991
+ return False.
992
+ """
993
+ try:
994
+ with self._lock:
995
+ if not self._can_send_recv():
996
+ return False
997
+ data = self._protocol.send_bytes()
998
+ total_bytes = self._send_bytes_blocking(data)
999
+
1000
+ if self._sensors:
1001
+ self._sensors.bytes_sent.record(total_bytes)
1002
+ return True
1003
+
1004
+ except (ConnectionError, TimeoutError) as e:
1005
+ log.exception("Error sending request data to %s", self)
1006
+ error = Errors.KafkaConnectionError("%s: %s" % (self, e))
1007
+ self.close(error=error)
1008
+ return False
1009
+
1010
+ def send_pending_requests_v2(self):
1011
+ """Attempts to send pending requests messages via non-blocking IO
1012
+ If all requests have been sent, return True
1013
+ Otherwise, if the socket is blocked and there are more bytes to send,
1014
+ return False.
1015
+ """
1016
+ try:
1017
+ with self._lock:
1018
+ if not self._can_send_recv():
1019
+ return False
1020
+
1021
+ # _protocol.send_bytes returns encoded requests to send
1022
+ # we send them via _send_bytes()
1023
+ # and hold leftover bytes in _send_buffer
1024
+ if not self._send_buffer:
1025
+ self._send_buffer = self._protocol.send_bytes()
1026
+
1027
+ total_bytes = 0
1028
+ if self._send_buffer:
1029
+ total_bytes = self._send_bytes(self._send_buffer)
1030
+ self._send_buffer = self._send_buffer[total_bytes:]
1031
+
1032
+ if self._sensors:
1033
+ self._sensors.bytes_sent.record(total_bytes)
1034
+ # Return True iff send buffer is empty
1035
+ return len(self._send_buffer) == 0
1036
+
1037
+ except (ConnectionError, TimeoutError, Exception) as e:
1038
+ log.exception("Error sending request data to %s", self)
1039
+ error = Errors.KafkaConnectionError("%s: %s" % (self, e))
1040
+ self.close(error=error)
1041
+ return False
1042
+
1043
+ def can_send_more(self):
1044
+ """Return True unless there are max_in_flight_requests_per_connection."""
1045
+ max_ifrs = self.config['max_in_flight_requests_per_connection']
1046
+ return len(self.in_flight_requests) < max_ifrs
1047
+
1048
+ def recv(self):
1049
+ """Non-blocking network receive.
1050
+
1051
+ Return list of (response, future) tuples
1052
+ """
1053
+ responses = self._recv()
1054
+ if not responses and self.requests_timed_out():
1055
+ log.warning('%s timed out after %s ms. Closing connection.',
1056
+ self, self.config['request_timeout_ms'])
1057
+ self.close(error=Errors.RequestTimedOutError(
1058
+ 'Request timed out after %s ms' %
1059
+ self.config['request_timeout_ms']))
1060
+ return ()
1061
+
1062
+ # augment responses w/ correlation_id, future, and timestamp
1063
+ for i, (correlation_id, response) in enumerate(responses):
1064
+ try:
1065
+ with self._lock:
1066
+ (future, timestamp) = self.in_flight_requests.pop(correlation_id)
1067
+ except KeyError:
1068
+ self.close(Errors.KafkaConnectionError('Received unrecognized correlation id'))
1069
+ return ()
1070
+ latency_ms = (time.time() - timestamp) * 1000
1071
+ if self._sensors:
1072
+ self._sensors.request_time.record(latency_ms)
1073
+
1074
+ log.debug('%s Response %d (%s ms): %s', self, correlation_id, latency_ms, response)
1075
+ responses[i] = (response, future)
1076
+
1077
+ return responses
1078
+
1079
+ def _recv(self):
1080
+ """Take all available bytes from socket, return list of any responses from parser"""
1081
+ recvd = []
1082
+ err = None
1083
+ with self._lock:
1084
+ if not self._can_send_recv():
1085
+ log.warning('%s cannot recv: socket not connected', self)
1086
+ return ()
1087
+
1088
+ while len(recvd) < self.config['sock_chunk_buffer_count']:
1089
+ try:
1090
+ data = self._sock.recv(self.config['sock_chunk_bytes'])
1091
+ # We expect socket.recv to raise an exception if there are no
1092
+ # bytes available to read from the socket in non-blocking mode.
1093
+ # but if the socket is disconnected, we will get empty data
1094
+ # without an exception raised
1095
+ if not data:
1096
+ log.error('%s: socket disconnected', self)
1097
+ err = Errors.KafkaConnectionError('socket disconnected')
1098
+ break
1099
+ else:
1100
+ recvd.append(data)
1101
+
1102
+ except (SSLWantReadError, SSLWantWriteError):
1103
+ break
1104
+ except (ConnectionError, TimeoutError) as e:
1105
+ if six.PY2 and e.errno == errno.EWOULDBLOCK:
1106
+ break
1107
+ log.exception('%s: Error receiving network data'
1108
+ ' closing socket', self)
1109
+ err = Errors.KafkaConnectionError(e)
1110
+ break
1111
+ except BlockingIOError:
1112
+ if six.PY3:
1113
+ break
1114
+ # For PY2 this is a catchall and should be re-raised
1115
+ raise
1116
+
1117
+ # Only process bytes if there was no connection exception
1118
+ if err is None:
1119
+ recvd_data = b''.join(recvd)
1120
+ if self._sensors:
1121
+ self._sensors.bytes_received.record(len(recvd_data))
1122
+
1123
+ # We need to keep the lock through protocol receipt
1124
+ # so that we ensure that the processed byte order is the
1125
+ # same as the received byte order
1126
+ try:
1127
+ return self._protocol.receive_bytes(recvd_data)
1128
+ except Errors.KafkaProtocolError as e:
1129
+ err = e
1130
+
1131
+ self.close(error=err)
1132
+ return ()
1133
+
1134
+ def requests_timed_out(self):
1135
+ with self._lock:
1136
+ if self.in_flight_requests:
1137
+ get_timestamp = lambda v: v[1]
1138
+ oldest_at = min(map(get_timestamp,
1139
+ self.in_flight_requests.values()))
1140
+ timeout = self.config['request_timeout_ms'] / 1000.0
1141
+ if time.time() >= oldest_at + timeout:
1142
+ return True
1143
+ return False
1144
+
1145
+ def _handle_api_version_response(self, response):
1146
+ error_type = Errors.for_code(response.error_code)
1147
+ assert error_type is Errors.NoError, "API version check failed"
1148
+ self._api_versions = dict([
1149
+ (api_key, (min_version, max_version))
1150
+ for api_key, min_version, max_version in response.api_versions
1151
+ ])
1152
+ return self._api_versions
1153
+
1154
+ def get_api_versions(self):
1155
+ if self._api_versions is not None:
1156
+ return self._api_versions
1157
+
1158
+ version = self.check_version()
1159
+ if version < (0, 10, 0):
1160
+ raise Errors.UnsupportedVersionError(
1161
+ "ApiVersion not supported by cluster version {} < 0.10.0"
1162
+ .format(version))
1163
+ # _api_versions is set as a side effect of check_versions() on a cluster
1164
+ # that supports 0.10.0 or later
1165
+ return self._api_versions
1166
+
1167
+ def _infer_broker_version_from_api_versions(self, api_versions):
1168
+ # The logic here is to check the list of supported request versions
1169
+ # in reverse order. As soon as we find one that works, return it
1170
+ test_cases = [
1171
+ # format (<broker version>, <needed struct>)
1172
+ ((2, 6, 0), DescribeClientQuotasRequest[0]),
1173
+ ((2, 5, 0), DescribeAclsRequest_v2),
1174
+ ((2, 4, 0), ProduceRequest[8]),
1175
+ ((2, 3, 0), FetchRequest[11]),
1176
+ ((2, 2, 0), OffsetRequest[5]),
1177
+ ((2, 1, 0), FetchRequest[10]),
1178
+ ((2, 0, 0), FetchRequest[8]),
1179
+ ((1, 1, 0), FetchRequest[7]),
1180
+ ((1, 0, 0), MetadataRequest[5]),
1181
+ ((0, 11, 0), MetadataRequest[4]),
1182
+ ((0, 10, 2), OffsetFetchRequest[2]),
1183
+ ((0, 10, 1), MetadataRequest[2]),
1184
+ ]
1185
+
1186
+ # Get the best match of test cases
1187
+ for broker_version, struct in sorted(test_cases, reverse=True):
1188
+ if struct.API_KEY not in api_versions:
1189
+ continue
1190
+ min_version, max_version = api_versions[struct.API_KEY]
1191
+ if min_version <= struct.API_VERSION <= max_version:
1192
+ return broker_version
1193
+
1194
+ # We know that ApiVersionResponse is only supported in 0.10+
1195
+ # so if all else fails, choose that
1196
+ return (0, 10, 0)
1197
+
1198
+ def check_version(self, timeout=2, strict=False, topics=[]):
1199
+ """Attempt to guess the broker version.
1200
+
1201
+ Note: This is a blocking call.
1202
+
1203
+ Returns: version tuple, i.e. (0, 10), (0, 9), (0, 8, 2), ...
1204
+ """
1205
+ timeout_at = time.time() + timeout
1206
+ log.info('Probing node %s broker version', self.node_id)
1207
+ # Monkeypatch some connection configurations to avoid timeouts
1208
+ override_config = {
1209
+ 'request_timeout_ms': timeout * 1000,
1210
+ 'max_in_flight_requests_per_connection': 5
1211
+ }
1212
+ stashed = {}
1213
+ for key in override_config:
1214
+ stashed[key] = self.config[key]
1215
+ self.config[key] = override_config[key]
1216
+
1217
+ def reset_override_configs():
1218
+ for key in stashed:
1219
+ self.config[key] = stashed[key]
1220
+
1221
+ # kafka kills the connection when it doesn't recognize an API request
1222
+ # so we can send a test request and then follow immediately with a
1223
+ # vanilla MetadataRequest. If the server did not recognize the first
1224
+ # request, both will be failed with a ConnectionError that wraps
1225
+ # socket.error (32, 54, or 104)
1226
+ from kafka.protocol.admin import ApiVersionRequest, ListGroupsRequest
1227
+ from kafka.protocol.commit import OffsetFetchRequest, GroupCoordinatorRequest
1228
+
1229
+ test_cases = [
1230
+ # All cases starting from 0.10 will be based on ApiVersionResponse
1231
+ ((0, 10), ApiVersionRequest[0]()),
1232
+ ((0, 9), ListGroupsRequest[0]()),
1233
+ ((0, 8, 2), GroupCoordinatorRequest[0]('kafka-python-default-group')),
1234
+ ((0, 8, 1), OffsetFetchRequest[0]('kafka-python-default-group', [])),
1235
+ ((0, 8, 0), MetadataRequest[0](topics)),
1236
+ ]
1237
+
1238
+ for version, request in test_cases:
1239
+ if not self.connect_blocking(timeout_at - time.time()):
1240
+ reset_override_configs()
1241
+ raise Errors.NodeNotReadyError()
1242
+ f = self.send(request)
1243
+ # HACK: sleeping to wait for socket to send bytes
1244
+ time.sleep(0.1)
1245
+ # when broker receives an unrecognized request API
1246
+ # it abruptly closes our socket.
1247
+ # so we attempt to send a second request immediately
1248
+ # that we believe it will definitely recognize (metadata)
1249
+ # the attempt to write to a disconnected socket should
1250
+ # immediately fail and allow us to infer that the prior
1251
+ # request was unrecognized
1252
+ mr = self.send(MetadataRequest[0](topics))
1253
+
1254
+ selector = self.config['selector']()
1255
+ selector.register(self._sock, selectors.EVENT_READ)
1256
+ while not (f.is_done and mr.is_done):
1257
+ selector.select(1)
1258
+ for response, future in self.recv():
1259
+ future.success(response)
1260
+ selector.close()
1261
+
1262
+ if f.succeeded():
1263
+ if isinstance(request, ApiVersionRequest[0]):
1264
+ # Starting from 0.10 kafka broker we determine version
1265
+ # by looking at ApiVersionResponse
1266
+ api_versions = self._handle_api_version_response(f.value)
1267
+ version = self._infer_broker_version_from_api_versions(api_versions)
1268
+ log.info('Broker version identified as %s', '.'.join(map(str, version)))
1269
+ log.info('Set configuration api_version=%s to skip auto'
1270
+ ' check_version requests on startup', version)
1271
+ break
1272
+
1273
+ # Only enable strict checking to verify that we understand failure
1274
+ # modes. For most users, the fact that the request failed should be
1275
+ # enough to rule out a particular broker version.
1276
+ if strict:
1277
+ # If the socket flush hack did not work (which should force the
1278
+ # connection to close and fail all pending requests), then we
1279
+ # get a basic Request Timeout. This is not ideal, but we'll deal
1280
+ if isinstance(f.exception, Errors.RequestTimedOutError):
1281
+ pass
1282
+
1283
+ # 0.9 brokers do not close the socket on unrecognized api
1284
+ # requests (bug...). In this case we expect to see a correlation
1285
+ # id mismatch
1286
+ elif (isinstance(f.exception, Errors.CorrelationIdError) and
1287
+ version == (0, 10)):
1288
+ pass
1289
+ elif six.PY2:
1290
+ assert isinstance(f.exception.args[0], socket.error)
1291
+ assert f.exception.args[0].errno in (32, 54, 104)
1292
+ else:
1293
+ assert isinstance(f.exception.args[0], ConnectionError)
1294
+ log.info("Broker is not v%s -- it did not recognize %s",
1295
+ version, request.__class__.__name__)
1296
+ else:
1297
+ reset_override_configs()
1298
+ raise Errors.UnrecognizedBrokerVersion()
1299
+
1300
+ reset_override_configs()
1301
+ return version
1302
+
1303
+ def __str__(self):
1304
+ return "<BrokerConnection node_id=%s host=%s:%d %s [%s %s]>" % (
1305
+ self.node_id, self.host, self.port, self.state,
1306
+ AFI_NAMES[self._sock_afi], self._sock_addr)
1307
+
1308
+
1309
+ class BrokerConnectionMetrics(object):
1310
+ def __init__(self, metrics, metric_group_prefix, node_id):
1311
+ self.metrics = metrics
1312
+
1313
+ # Any broker may have registered summary metrics already
1314
+ # but if not, we need to create them so we can set as parents below
1315
+ all_conns_transferred = metrics.get_sensor('bytes-sent-received')
1316
+ if not all_conns_transferred:
1317
+ metric_group_name = metric_group_prefix + '-metrics'
1318
+
1319
+ bytes_transferred = metrics.sensor('bytes-sent-received')
1320
+ bytes_transferred.add(metrics.metric_name(
1321
+ 'network-io-rate', metric_group_name,
1322
+ 'The average number of network operations (reads or writes) on all'
1323
+ ' connections per second.'), Rate(sampled_stat=Count()))
1324
+
1325
+ bytes_sent = metrics.sensor('bytes-sent',
1326
+ parents=[bytes_transferred])
1327
+ bytes_sent.add(metrics.metric_name(
1328
+ 'outgoing-byte-rate', metric_group_name,
1329
+ 'The average number of outgoing bytes sent per second to all'
1330
+ ' servers.'), Rate())
1331
+ bytes_sent.add(metrics.metric_name(
1332
+ 'request-rate', metric_group_name,
1333
+ 'The average number of requests sent per second.'),
1334
+ Rate(sampled_stat=Count()))
1335
+ bytes_sent.add(metrics.metric_name(
1336
+ 'request-size-avg', metric_group_name,
1337
+ 'The average size of all requests in the window.'), Avg())
1338
+ bytes_sent.add(metrics.metric_name(
1339
+ 'request-size-max', metric_group_name,
1340
+ 'The maximum size of any request sent in the window.'), Max())
1341
+
1342
+ bytes_received = metrics.sensor('bytes-received',
1343
+ parents=[bytes_transferred])
1344
+ bytes_received.add(metrics.metric_name(
1345
+ 'incoming-byte-rate', metric_group_name,
1346
+ 'Bytes/second read off all sockets'), Rate())
1347
+ bytes_received.add(metrics.metric_name(
1348
+ 'response-rate', metric_group_name,
1349
+ 'Responses received sent per second.'),
1350
+ Rate(sampled_stat=Count()))
1351
+
1352
+ request_latency = metrics.sensor('request-latency')
1353
+ request_latency.add(metrics.metric_name(
1354
+ 'request-latency-avg', metric_group_name,
1355
+ 'The average request latency in ms.'),
1356
+ Avg())
1357
+ request_latency.add(metrics.metric_name(
1358
+ 'request-latency-max', metric_group_name,
1359
+ 'The maximum request latency in ms.'),
1360
+ Max())
1361
+
1362
+ # if one sensor of the metrics has been registered for the connection,
1363
+ # then all other sensors should have been registered; and vice versa
1364
+ node_str = 'node-{0}'.format(node_id)
1365
+ node_sensor = metrics.get_sensor(node_str + '.bytes-sent')
1366
+ if not node_sensor:
1367
+ metric_group_name = metric_group_prefix + '-node-metrics.' + node_str
1368
+
1369
+ bytes_sent = metrics.sensor(
1370
+ node_str + '.bytes-sent',
1371
+ parents=[metrics.get_sensor('bytes-sent')])
1372
+ bytes_sent.add(metrics.metric_name(
1373
+ 'outgoing-byte-rate', metric_group_name,
1374
+ 'The average number of outgoing bytes sent per second.'),
1375
+ Rate())
1376
+ bytes_sent.add(metrics.metric_name(
1377
+ 'request-rate', metric_group_name,
1378
+ 'The average number of requests sent per second.'),
1379
+ Rate(sampled_stat=Count()))
1380
+ bytes_sent.add(metrics.metric_name(
1381
+ 'request-size-avg', metric_group_name,
1382
+ 'The average size of all requests in the window.'),
1383
+ Avg())
1384
+ bytes_sent.add(metrics.metric_name(
1385
+ 'request-size-max', metric_group_name,
1386
+ 'The maximum size of any request sent in the window.'),
1387
+ Max())
1388
+
1389
+ bytes_received = metrics.sensor(
1390
+ node_str + '.bytes-received',
1391
+ parents=[metrics.get_sensor('bytes-received')])
1392
+ bytes_received.add(metrics.metric_name(
1393
+ 'incoming-byte-rate', metric_group_name,
1394
+ 'Bytes/second read off node-connection socket'),
1395
+ Rate())
1396
+ bytes_received.add(metrics.metric_name(
1397
+ 'response-rate', metric_group_name,
1398
+ 'The average number of responses received per second.'),
1399
+ Rate(sampled_stat=Count()))
1400
+
1401
+ request_time = metrics.sensor(
1402
+ node_str + '.latency',
1403
+ parents=[metrics.get_sensor('request-latency')])
1404
+ request_time.add(metrics.metric_name(
1405
+ 'request-latency-avg', metric_group_name,
1406
+ 'The average request latency in ms.'),
1407
+ Avg())
1408
+ request_time.add(metrics.metric_name(
1409
+ 'request-latency-max', metric_group_name,
1410
+ 'The maximum request latency in ms.'),
1411
+ Max())
1412
+
1413
+ self.bytes_sent = metrics.sensor(node_str + '.bytes-sent')
1414
+ self.bytes_received = metrics.sensor(node_str + '.bytes-received')
1415
+ self.request_time = metrics.sensor(node_str + '.latency')
1416
+
1417
+
1418
+ def _address_family(address):
1419
+ """
1420
+ Attempt to determine the family of an address (or hostname)
1421
+
1422
+ :return: either socket.AF_INET or socket.AF_INET6 or socket.AF_UNSPEC if the address family
1423
+ could not be determined
1424
+ """
1425
+ if address.startswith('[') and address.endswith(']'):
1426
+ return socket.AF_INET6
1427
+ for af in (socket.AF_INET, socket.AF_INET6):
1428
+ try:
1429
+ socket.inet_pton(af, address)
1430
+ return af
1431
+ except (ValueError, AttributeError, socket.error):
1432
+ continue
1433
+ return socket.AF_UNSPEC
1434
+
1435
+
1436
+ def get_ip_port_afi(host_and_port_str):
1437
+ """
1438
+ Parse the IP and port from a string in the format of:
1439
+
1440
+ * host_or_ip <- Can be either IPv4 address literal or hostname/fqdn
1441
+ * host_or_ipv4:port <- Can be either IPv4 address literal or hostname/fqdn
1442
+ * [host_or_ip] <- IPv6 address literal
1443
+ * [host_or_ip]:port. <- IPv6 address literal
1444
+
1445
+ .. note:: IPv6 address literals with ports *must* be enclosed in brackets
1446
+
1447
+ .. note:: If the port is not specified, default will be returned.
1448
+
1449
+ :return: tuple (host, port, afi), afi will be socket.AF_INET or socket.AF_INET6 or socket.AF_UNSPEC
1450
+ """
1451
+ host_and_port_str = host_and_port_str.strip()
1452
+ if host_and_port_str.startswith('['):
1453
+ af = socket.AF_INET6
1454
+ host, rest = host_and_port_str[1:].split(']')
1455
+ if rest:
1456
+ port = int(rest[1:])
1457
+ else:
1458
+ port = DEFAULT_KAFKA_PORT
1459
+ return host, port, af
1460
+ else:
1461
+ if ':' not in host_and_port_str:
1462
+ af = _address_family(host_and_port_str)
1463
+ return host_and_port_str, DEFAULT_KAFKA_PORT, af
1464
+ else:
1465
+ # now we have something with a colon in it and no square brackets. It could be
1466
+ # either an IPv6 address literal (e.g., "::1") or an IP:port pair or a host:port pair
1467
+ try:
1468
+ # if it decodes as an IPv6 address, use that
1469
+ socket.inet_pton(socket.AF_INET6, host_and_port_str)
1470
+ return host_and_port_str, DEFAULT_KAFKA_PORT, socket.AF_INET6
1471
+ except AttributeError:
1472
+ log.warning('socket.inet_pton not available on this platform.'
1473
+ ' consider `pip install win_inet_pton`')
1474
+ pass
1475
+ except (ValueError, socket.error):
1476
+ # it's a host:port pair
1477
+ pass
1478
+ host, port = host_and_port_str.rsplit(':', 1)
1479
+ port = int(port)
1480
+
1481
+ af = _address_family(host)
1482
+ return host, port, af
1483
+
1484
+
1485
+ def collect_hosts(hosts, randomize=True):
1486
+ """
1487
+ Collects a comma-separated set of hosts (host:port) and optionally
1488
+ randomize the returned list.
1489
+ """
1490
+
1491
+ if isinstance(hosts, six.string_types):
1492
+ hosts = hosts.strip().split(',')
1493
+
1494
+ result = []
1495
+ afi = socket.AF_INET
1496
+ for host_port in hosts:
1497
+
1498
+ host, port, afi = get_ip_port_afi(host_port)
1499
+
1500
+ if port < 0:
1501
+ port = DEFAULT_KAFKA_PORT
1502
+
1503
+ result.append((host, port, afi))
1504
+
1505
+ if randomize:
1506
+ shuffle(result)
1507
+
1508
+ return result
1509
+
1510
+
1511
+ def is_inet_4_or_6(gai):
1512
+ """Given a getaddrinfo struct, return True iff ipv4 or ipv6"""
1513
+ return gai[0] in (socket.AF_INET, socket.AF_INET6)
1514
+
1515
+
1516
+ def dns_lookup(host, port, afi=socket.AF_UNSPEC):
1517
+ """Returns a list of getaddrinfo structs, optionally filtered to an afi (ipv4 / ipv6)"""
1518
+ # XXX: all DNS functions in Python are blocking. If we really
1519
+ # want to be non-blocking here, we need to use a 3rd-party
1520
+ # library like python-adns, or move resolution onto its
1521
+ # own thread. This will be subject to the default libc
1522
+ # name resolution timeout (5s on most Linux boxes)
1523
+ try:
1524
+ return list(filter(is_inet_4_or_6,
1525
+ socket.getaddrinfo(host, port, afi,
1526
+ socket.SOCK_STREAM)))
1527
+ except socket.gaierror as ex:
1528
+ log.warning('DNS lookup failed for %s:%d,'
1529
+ ' exception was %s. Is your'
1530
+ ' advertised.listeners (called'
1531
+ ' advertised.host.name before Kafka 9)'
1532
+ ' correct and resolvable?',
1533
+ host, port, ex)
1534
+ return []
testbed/dpkp__kafka-python/kafka/errors.py ADDED
@@ -0,0 +1,538 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+
3
+ import inspect
4
+ import sys
5
+
6
+
7
+ class KafkaError(RuntimeError):
8
+ retriable = False
9
+ # whether metadata should be refreshed on error
10
+ invalid_metadata = False
11
+
12
+ def __str__(self):
13
+ if not self.args:
14
+ return self.__class__.__name__
15
+ return '{0}: {1}'.format(self.__class__.__name__,
16
+ super(KafkaError, self).__str__())
17
+
18
+
19
+ class IllegalStateError(KafkaError):
20
+ pass
21
+
22
+
23
+ class IllegalArgumentError(KafkaError):
24
+ pass
25
+
26
+
27
+ class NoBrokersAvailable(KafkaError):
28
+ retriable = True
29
+ invalid_metadata = True
30
+
31
+
32
+ class NodeNotReadyError(KafkaError):
33
+ retriable = True
34
+
35
+
36
+ class KafkaProtocolError(KafkaError):
37
+ retriable = True
38
+
39
+
40
+ class CorrelationIdError(KafkaProtocolError):
41
+ retriable = True
42
+
43
+
44
+ class Cancelled(KafkaError):
45
+ retriable = True
46
+
47
+
48
+ class TooManyInFlightRequests(KafkaError):
49
+ retriable = True
50
+
51
+
52
+ class StaleMetadata(KafkaError):
53
+ retriable = True
54
+ invalid_metadata = True
55
+
56
+
57
+ class MetadataEmptyBrokerList(KafkaError):
58
+ retriable = True
59
+
60
+
61
+ class UnrecognizedBrokerVersion(KafkaError):
62
+ pass
63
+
64
+
65
+ class IncompatibleBrokerVersion(KafkaError):
66
+ pass
67
+
68
+
69
+ class CommitFailedError(KafkaError):
70
+ def __init__(self, *args, **kwargs):
71
+ super(CommitFailedError, self).__init__(
72
+ """Commit cannot be completed since the group has already
73
+ rebalanced and assigned the partitions to another member.
74
+ This means that the time between subsequent calls to poll()
75
+ was longer than the configured max_poll_interval_ms, which
76
+ typically implies that the poll loop is spending too much
77
+ time message processing. You can address this either by
78
+ increasing the rebalance timeout with max_poll_interval_ms,
79
+ or by reducing the maximum size of batches returned in poll()
80
+ with max_poll_records.
81
+ """, *args, **kwargs)
82
+
83
+
84
+ class AuthenticationMethodNotSupported(KafkaError):
85
+ pass
86
+
87
+
88
+ class AuthenticationFailedError(KafkaError):
89
+ retriable = False
90
+
91
+
92
+ class BrokerResponseError(KafkaError):
93
+ errno = None
94
+ message = None
95
+ description = None
96
+
97
+ def __str__(self):
98
+ """Add errno to standard KafkaError str"""
99
+ return '[Error {0}] {1}'.format(
100
+ self.errno,
101
+ super(BrokerResponseError, self).__str__())
102
+
103
+
104
+ class NoError(BrokerResponseError):
105
+ errno = 0
106
+ message = 'NO_ERROR'
107
+ description = 'No error--it worked!'
108
+
109
+
110
+ class UnknownError(BrokerResponseError):
111
+ errno = -1
112
+ message = 'UNKNOWN'
113
+ description = 'An unexpected server error.'
114
+
115
+
116
+ class OffsetOutOfRangeError(BrokerResponseError):
117
+ errno = 1
118
+ message = 'OFFSET_OUT_OF_RANGE'
119
+ description = ('The requested offset is outside the range of offsets'
120
+ ' maintained by the server for the given topic/partition.')
121
+
122
+
123
+ class CorruptRecordException(BrokerResponseError):
124
+ errno = 2
125
+ message = 'CORRUPT_MESSAGE'
126
+ description = ('This message has failed its CRC checksum, exceeds the'
127
+ ' valid size, or is otherwise corrupt.')
128
+
129
+ # Backward compatibility
130
+ InvalidMessageError = CorruptRecordException
131
+
132
+
133
+ class UnknownTopicOrPartitionError(BrokerResponseError):
134
+ errno = 3
135
+ message = 'UNKNOWN_TOPIC_OR_PARTITION'
136
+ description = ('This request is for a topic or partition that does not'
137
+ ' exist on this broker.')
138
+ retriable = True
139
+ invalid_metadata = True
140
+
141
+
142
+ class InvalidFetchRequestError(BrokerResponseError):
143
+ errno = 4
144
+ message = 'INVALID_FETCH_SIZE'
145
+ description = 'The message has a negative size.'
146
+
147
+
148
+ class LeaderNotAvailableError(BrokerResponseError):
149
+ errno = 5
150
+ message = 'LEADER_NOT_AVAILABLE'
151
+ description = ('This error is thrown if we are in the middle of a'
152
+ ' leadership election and there is currently no leader for'
153
+ ' this partition and hence it is unavailable for writes.')
154
+ retriable = True
155
+ invalid_metadata = True
156
+
157
+
158
+ class NotLeaderForPartitionError(BrokerResponseError):
159
+ errno = 6
160
+ message = 'NOT_LEADER_FOR_PARTITION'
161
+ description = ('This error is thrown if the client attempts to send'
162
+ ' messages to a replica that is not the leader for some'
163
+ ' partition. It indicates that the clients metadata is out'
164
+ ' of date.')
165
+ retriable = True
166
+ invalid_metadata = True
167
+
168
+
169
+ class RequestTimedOutError(BrokerResponseError):
170
+ errno = 7
171
+ message = 'REQUEST_TIMED_OUT'
172
+ description = ('This error is thrown if the request exceeds the'
173
+ ' user-specified time limit in the request.')
174
+ retriable = True
175
+
176
+
177
+ class BrokerNotAvailableError(BrokerResponseError):
178
+ errno = 8
179
+ message = 'BROKER_NOT_AVAILABLE'
180
+ description = ('This is not a client facing error and is used mostly by'
181
+ ' tools when a broker is not alive.')
182
+
183
+
184
+ class ReplicaNotAvailableError(BrokerResponseError):
185
+ errno = 9
186
+ message = 'REPLICA_NOT_AVAILABLE'
187
+ description = ('If replica is expected on a broker, but is not (this can be'
188
+ ' safely ignored).')
189
+
190
+
191
+ class MessageSizeTooLargeError(BrokerResponseError):
192
+ errno = 10
193
+ message = 'MESSAGE_SIZE_TOO_LARGE'
194
+ description = ('The server has a configurable maximum message size to avoid'
195
+ ' unbounded memory allocation. This error is thrown if the'
196
+ ' client attempt to produce a message larger than this'
197
+ ' maximum.')
198
+
199
+
200
+ class StaleControllerEpochError(BrokerResponseError):
201
+ errno = 11
202
+ message = 'STALE_CONTROLLER_EPOCH'
203
+ description = 'Internal error code for broker-to-broker communication.'
204
+
205
+
206
+ class OffsetMetadataTooLargeError(BrokerResponseError):
207
+ errno = 12
208
+ message = 'OFFSET_METADATA_TOO_LARGE'
209
+ description = ('If you specify a string larger than configured maximum for'
210
+ ' offset metadata.')
211
+
212
+
213
+ # TODO is this deprecated? https://cwiki.apache.org/confluence/display/KAFKA/A+Guide+To+The+Kafka+Protocol#AGuideToTheKafkaProtocol-ErrorCodes
214
+ class StaleLeaderEpochCodeError(BrokerResponseError):
215
+ errno = 13
216
+ message = 'STALE_LEADER_EPOCH_CODE'
217
+
218
+
219
+ class GroupLoadInProgressError(BrokerResponseError):
220
+ errno = 14
221
+ message = 'OFFSETS_LOAD_IN_PROGRESS'
222
+ description = ('The broker returns this error code for an offset fetch'
223
+ ' request if it is still loading offsets (after a leader'
224
+ ' change for that offsets topic partition), or in response'
225
+ ' to group membership requests (such as heartbeats) when'
226
+ ' group metadata is being loaded by the coordinator.')
227
+ retriable = True
228
+
229
+
230
+ class GroupCoordinatorNotAvailableError(BrokerResponseError):
231
+ errno = 15
232
+ message = 'CONSUMER_COORDINATOR_NOT_AVAILABLE'
233
+ description = ('The broker returns this error code for group coordinator'
234
+ ' requests, offset commits, and most group management'
235
+ ' requests if the offsets topic has not yet been created, or'
236
+ ' if the group coordinator is not active.')
237
+ retriable = True
238
+
239
+
240
+ class NotCoordinatorForGroupError(BrokerResponseError):
241
+ errno = 16
242
+ message = 'NOT_COORDINATOR_FOR_CONSUMER'
243
+ description = ('The broker returns this error code if it receives an offset'
244
+ ' fetch or commit request for a group that it is not a'
245
+ ' coordinator for.')
246
+ retriable = True
247
+
248
+
249
+ class InvalidTopicError(BrokerResponseError):
250
+ errno = 17
251
+ message = 'INVALID_TOPIC'
252
+ description = ('For a request which attempts to access an invalid topic'
253
+ ' (e.g. one which has an illegal name), or if an attempt'
254
+ ' is made to write to an internal topic (such as the'
255
+ ' consumer offsets topic).')
256
+
257
+
258
+ class RecordListTooLargeError(BrokerResponseError):
259
+ errno = 18
260
+ message = 'RECORD_LIST_TOO_LARGE'
261
+ description = ('If a message batch in a produce request exceeds the maximum'
262
+ ' configured segment size.')
263
+
264
+
265
+ class NotEnoughReplicasError(BrokerResponseError):
266
+ errno = 19
267
+ message = 'NOT_ENOUGH_REPLICAS'
268
+ description = ('Returned from a produce request when the number of in-sync'
269
+ ' replicas is lower than the configured minimum and'
270
+ ' requiredAcks is -1.')
271
+ retriable = True
272
+
273
+
274
+ class NotEnoughReplicasAfterAppendError(BrokerResponseError):
275
+ errno = 20
276
+ message = 'NOT_ENOUGH_REPLICAS_AFTER_APPEND'
277
+ description = ('Returned from a produce request when the message was'
278
+ ' written to the log, but with fewer in-sync replicas than'
279
+ ' required.')
280
+ retriable = True
281
+
282
+
283
+ class InvalidRequiredAcksError(BrokerResponseError):
284
+ errno = 21
285
+ message = 'INVALID_REQUIRED_ACKS'
286
+ description = ('Returned from a produce request if the requested'
287
+ ' requiredAcks is invalid (anything other than -1, 1, or 0).')
288
+
289
+
290
+ class IllegalGenerationError(BrokerResponseError):
291
+ errno = 22
292
+ message = 'ILLEGAL_GENERATION'
293
+ description = ('Returned from group membership requests (such as heartbeats)'
294
+ ' when the generation id provided in the request is not the'
295
+ ' current generation.')
296
+
297
+
298
+ class InconsistentGroupProtocolError(BrokerResponseError):
299
+ errno = 23
300
+ message = 'INCONSISTENT_GROUP_PROTOCOL'
301
+ description = ('Returned in join group when the member provides a protocol'
302
+ ' type or set of protocols which is not compatible with the'
303
+ ' current group.')
304
+
305
+
306
+ class InvalidGroupIdError(BrokerResponseError):
307
+ errno = 24
308
+ message = 'INVALID_GROUP_ID'
309
+ description = 'Returned in join group when the groupId is empty or null.'
310
+
311
+
312
+ class UnknownMemberIdError(BrokerResponseError):
313
+ errno = 25
314
+ message = 'UNKNOWN_MEMBER_ID'
315
+ description = ('Returned from group requests (offset commits/fetches,'
316
+ ' heartbeats, etc) when the memberId is not in the current'
317
+ ' generation.')
318
+
319
+
320
+ class InvalidSessionTimeoutError(BrokerResponseError):
321
+ errno = 26
322
+ message = 'INVALID_SESSION_TIMEOUT'
323
+ description = ('Return in join group when the requested session timeout is'
324
+ ' outside of the allowed range on the broker')
325
+
326
+
327
+ class RebalanceInProgressError(BrokerResponseError):
328
+ errno = 27
329
+ message = 'REBALANCE_IN_PROGRESS'
330
+ description = ('Returned in heartbeat requests when the coordinator has'
331
+ ' begun rebalancing the group. This indicates to the client'
332
+ ' that it should rejoin the group.')
333
+
334
+
335
+ class InvalidCommitOffsetSizeError(BrokerResponseError):
336
+ errno = 28
337
+ message = 'INVALID_COMMIT_OFFSET_SIZE'
338
+ description = ('This error indicates that an offset commit was rejected'
339
+ ' because of oversize metadata.')
340
+
341
+
342
+ class TopicAuthorizationFailedError(BrokerResponseError):
343
+ errno = 29
344
+ message = 'TOPIC_AUTHORIZATION_FAILED'
345
+ description = ('Returned by the broker when the client is not authorized to'
346
+ ' access the requested topic.')
347
+
348
+
349
+ class GroupAuthorizationFailedError(BrokerResponseError):
350
+ errno = 30
351
+ message = 'GROUP_AUTHORIZATION_FAILED'
352
+ description = ('Returned by the broker when the client is not authorized to'
353
+ ' access a particular groupId.')
354
+
355
+
356
+ class ClusterAuthorizationFailedError(BrokerResponseError):
357
+ errno = 31
358
+ message = 'CLUSTER_AUTHORIZATION_FAILED'
359
+ description = ('Returned by the broker when the client is not authorized to'
360
+ ' use an inter-broker or administrative API.')
361
+
362
+
363
+ class InvalidTimestampError(BrokerResponseError):
364
+ errno = 32
365
+ message = 'INVALID_TIMESTAMP'
366
+ description = 'The timestamp of the message is out of acceptable range.'
367
+
368
+
369
+ class UnsupportedSaslMechanismError(BrokerResponseError):
370
+ errno = 33
371
+ message = 'UNSUPPORTED_SASL_MECHANISM'
372
+ description = 'The broker does not support the requested SASL mechanism.'
373
+
374
+
375
+ class IllegalSaslStateError(BrokerResponseError):
376
+ errno = 34
377
+ message = 'ILLEGAL_SASL_STATE'
378
+ description = 'Request is not valid given the current SASL state.'
379
+
380
+
381
+ class UnsupportedVersionError(BrokerResponseError):
382
+ errno = 35
383
+ message = 'UNSUPPORTED_VERSION'
384
+ description = 'The version of API is not supported.'
385
+
386
+
387
+ class TopicAlreadyExistsError(BrokerResponseError):
388
+ errno = 36
389
+ message = 'TOPIC_ALREADY_EXISTS'
390
+ description = 'Topic with this name already exists.'
391
+
392
+
393
+ class InvalidPartitionsError(BrokerResponseError):
394
+ errno = 37
395
+ message = 'INVALID_PARTITIONS'
396
+ description = 'Number of partitions is invalid.'
397
+
398
+
399
+ class InvalidReplicationFactorError(BrokerResponseError):
400
+ errno = 38
401
+ message = 'INVALID_REPLICATION_FACTOR'
402
+ description = 'Replication-factor is invalid.'
403
+
404
+
405
+ class InvalidReplicationAssignmentError(BrokerResponseError):
406
+ errno = 39
407
+ message = 'INVALID_REPLICATION_ASSIGNMENT'
408
+ description = 'Replication assignment is invalid.'
409
+
410
+
411
+ class InvalidConfigurationError(BrokerResponseError):
412
+ errno = 40
413
+ message = 'INVALID_CONFIG'
414
+ description = 'Configuration is invalid.'
415
+
416
+
417
+ class NotControllerError(BrokerResponseError):
418
+ errno = 41
419
+ message = 'NOT_CONTROLLER'
420
+ description = 'This is not the correct controller for this cluster.'
421
+ retriable = True
422
+
423
+
424
+ class InvalidRequestError(BrokerResponseError):
425
+ errno = 42
426
+ message = 'INVALID_REQUEST'
427
+ description = ('This most likely occurs because of a request being'
428
+ ' malformed by the client library or the message was'
429
+ ' sent to an incompatible broker. See the broker logs'
430
+ ' for more details.')
431
+
432
+
433
+ class UnsupportedForMessageFormatError(BrokerResponseError):
434
+ errno = 43
435
+ message = 'UNSUPPORTED_FOR_MESSAGE_FORMAT'
436
+ description = ('The message format version on the broker does not'
437
+ ' support this request.')
438
+
439
+
440
+ class PolicyViolationError(BrokerResponseError):
441
+ errno = 44
442
+ message = 'POLICY_VIOLATION'
443
+ description = 'Request parameters do not satisfy the configured policy.'
444
+
445
+
446
+ class SecurityDisabledError(BrokerResponseError):
447
+ errno = 54
448
+ message = 'SECURITY_DISABLED'
449
+ description = 'Security features are disabled.'
450
+
451
+
452
+ class NonEmptyGroupError(BrokerResponseError):
453
+ errno = 68
454
+ message = 'NON_EMPTY_GROUP'
455
+ description = 'The group is not empty.'
456
+
457
+
458
+ class GroupIdNotFoundError(BrokerResponseError):
459
+ errno = 69
460
+ message = 'GROUP_ID_NOT_FOUND'
461
+ description = 'The group id does not exist.'
462
+
463
+
464
+ class KafkaUnavailableError(KafkaError):
465
+ pass
466
+
467
+
468
+ class KafkaTimeoutError(KafkaError):
469
+ pass
470
+
471
+
472
+ class FailedPayloadsError(KafkaError):
473
+ def __init__(self, payload, *args):
474
+ super(FailedPayloadsError, self).__init__(*args)
475
+ self.payload = payload
476
+
477
+
478
+ class KafkaConnectionError(KafkaError):
479
+ retriable = True
480
+ invalid_metadata = True
481
+
482
+
483
+ class ProtocolError(KafkaError):
484
+ pass
485
+
486
+
487
+ class UnsupportedCodecError(KafkaError):
488
+ pass
489
+
490
+
491
+ class KafkaConfigurationError(KafkaError):
492
+ pass
493
+
494
+
495
+ class QuotaViolationError(KafkaError):
496
+ pass
497
+
498
+
499
+ class AsyncProducerQueueFull(KafkaError):
500
+ def __init__(self, failed_msgs, *args):
501
+ super(AsyncProducerQueueFull, self).__init__(*args)
502
+ self.failed_msgs = failed_msgs
503
+
504
+
505
+ def _iter_broker_errors():
506
+ for name, obj in inspect.getmembers(sys.modules[__name__]):
507
+ if inspect.isclass(obj) and issubclass(obj, BrokerResponseError) and obj != BrokerResponseError:
508
+ yield obj
509
+
510
+
511
+ kafka_errors = dict([(x.errno, x) for x in _iter_broker_errors()])
512
+
513
+
514
+ def for_code(error_code):
515
+ return kafka_errors.get(error_code, UnknownError)
516
+
517
+
518
+ def check_error(response):
519
+ if isinstance(response, Exception):
520
+ raise response
521
+ if response.error:
522
+ error_class = kafka_errors.get(response.error, UnknownError)
523
+ raise error_class(response)
524
+
525
+
526
+ RETRY_BACKOFF_ERROR_TYPES = (
527
+ KafkaUnavailableError, LeaderNotAvailableError,
528
+ KafkaConnectionError, FailedPayloadsError
529
+ )
530
+
531
+
532
+ RETRY_REFRESH_ERROR_TYPES = (
533
+ NotLeaderForPartitionError, UnknownTopicOrPartitionError,
534
+ LeaderNotAvailableError, KafkaConnectionError
535
+ )
536
+
537
+
538
+ RETRY_ERROR_TYPES = RETRY_BACKOFF_ERROR_TYPES + RETRY_REFRESH_ERROR_TYPES
testbed/dpkp__kafka-python/kafka/future.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+
3
+ import functools
4
+ import logging
5
+
6
+ log = logging.getLogger(__name__)
7
+
8
+
9
+ class Future(object):
10
+ error_on_callbacks = False # and errbacks
11
+
12
+ def __init__(self):
13
+ self.is_done = False
14
+ self.value = None
15
+ self.exception = None
16
+ self._callbacks = []
17
+ self._errbacks = []
18
+
19
+ def succeeded(self):
20
+ return self.is_done and not bool(self.exception)
21
+
22
+ def failed(self):
23
+ return self.is_done and bool(self.exception)
24
+
25
+ def retriable(self):
26
+ try:
27
+ return self.exception.retriable
28
+ except AttributeError:
29
+ return False
30
+
31
+ def success(self, value):
32
+ assert not self.is_done, 'Future is already complete'
33
+ self.value = value
34
+ self.is_done = True
35
+ if self._callbacks:
36
+ self._call_backs('callback', self._callbacks, self.value)
37
+ return self
38
+
39
+ def failure(self, e):
40
+ assert not self.is_done, 'Future is already complete'
41
+ self.exception = e if type(e) is not type else e()
42
+ assert isinstance(self.exception, BaseException), (
43
+ 'future failed without an exception')
44
+ self.is_done = True
45
+ self._call_backs('errback', self._errbacks, self.exception)
46
+ return self
47
+
48
+ def add_callback(self, f, *args, **kwargs):
49
+ if args or kwargs:
50
+ f = functools.partial(f, *args, **kwargs)
51
+ if self.is_done and not self.exception:
52
+ self._call_backs('callback', [f], self.value)
53
+ else:
54
+ self._callbacks.append(f)
55
+ return self
56
+
57
+ def add_errback(self, f, *args, **kwargs):
58
+ if args or kwargs:
59
+ f = functools.partial(f, *args, **kwargs)
60
+ if self.is_done and self.exception:
61
+ self._call_backs('errback', [f], self.exception)
62
+ else:
63
+ self._errbacks.append(f)
64
+ return self
65
+
66
+ def add_both(self, f, *args, **kwargs):
67
+ self.add_callback(f, *args, **kwargs)
68
+ self.add_errback(f, *args, **kwargs)
69
+ return self
70
+
71
+ def chain(self, future):
72
+ self.add_callback(future.success)
73
+ self.add_errback(future.failure)
74
+ return self
75
+
76
+ def _call_backs(self, back_type, backs, value):
77
+ for f in backs:
78
+ try:
79
+ f(value)
80
+ except Exception as e:
81
+ log.exception('Error processing %s', back_type)
82
+ if self.error_on_callbacks:
83
+ raise e
testbed/dpkp__kafka-python/kafka/metrics/measurable.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+
3
+ import abc
4
+
5
+
6
+ class AbstractMeasurable(object):
7
+ """A measurable quantity that can be registered as a metric"""
8
+ @abc.abstractmethod
9
+ def measure(self, config, now):
10
+ """
11
+ Measure this quantity and return the result
12
+
13
+ Arguments:
14
+ config (MetricConfig): The configuration for this metric
15
+ now (int): The POSIX time in milliseconds the measurement
16
+ is being taken
17
+
18
+ Returns:
19
+ The measured value
20
+ """
21
+ raise NotImplementedError
22
+
23
+
24
+ class AnonMeasurable(AbstractMeasurable):
25
+ def __init__(self, measure_fn):
26
+ self._measure_fn = measure_fn
27
+
28
+ def measure(self, config, now):
29
+ return float(self._measure_fn(config, now))
testbed/dpkp__kafka-python/kafka/metrics/stat.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+
3
+ import abc
4
+
5
+
6
+ class AbstractStat(object):
7
+ """
8
+ An AbstractStat is a quantity such as average, max, etc that is computed
9
+ off the stream of updates to a sensor
10
+ """
11
+ __metaclass__ = abc.ABCMeta
12
+
13
+ @abc.abstractmethod
14
+ def record(self, config, value, time_ms):
15
+ """
16
+ Record the given value
17
+
18
+ Arguments:
19
+ config (MetricConfig): The configuration to use for this metric
20
+ value (float): The value to record
21
+ timeMs (int): The POSIX time in milliseconds this value occurred
22
+ """
23
+ raise NotImplementedError
testbed/dpkp__kafka-python/kafka/metrics/stats/sensor.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+
3
+ import threading
4
+ import time
5
+
6
+ from kafka.errors import QuotaViolationError
7
+ from kafka.metrics import KafkaMetric
8
+
9
+
10
+ class Sensor(object):
11
+ """
12
+ A sensor applies a continuous sequence of numerical values
13
+ to a set of associated metrics. For example a sensor on
14
+ message size would record a sequence of message sizes using
15
+ the `record(double)` api and would maintain a set
16
+ of metrics about request sizes such as the average or max.
17
+ """
18
+ def __init__(self, registry, name, parents, config,
19
+ inactive_sensor_expiration_time_seconds):
20
+ if not name:
21
+ raise ValueError('name must be non-empty')
22
+ self._lock = threading.RLock()
23
+ self._registry = registry
24
+ self._name = name
25
+ self._parents = parents or []
26
+ self._metrics = []
27
+ self._stats = []
28
+ self._config = config
29
+ self._inactive_sensor_expiration_time_ms = (
30
+ inactive_sensor_expiration_time_seconds * 1000)
31
+ self._last_record_time = time.time() * 1000
32
+ self._check_forest(set())
33
+
34
+ def _check_forest(self, sensors):
35
+ """Validate that this sensor doesn't end up referencing itself."""
36
+ if self in sensors:
37
+ raise ValueError('Circular dependency in sensors: %s is its own'
38
+ 'parent.' % (self.name,))
39
+ sensors.add(self)
40
+ for parent in self._parents:
41
+ parent._check_forest(sensors)
42
+
43
+ @property
44
+ def name(self):
45
+ """
46
+ The name this sensor is registered with.
47
+ This name will be unique among all registered sensors.
48
+ """
49
+ return self._name
50
+
51
+ @property
52
+ def metrics(self):
53
+ return tuple(self._metrics)
54
+
55
+ def record(self, value=1.0, time_ms=None):
56
+ """
57
+ Record a value at a known time.
58
+ Arguments:
59
+ value (double): The value we are recording
60
+ time_ms (int): A POSIX timestamp in milliseconds.
61
+ Default: The time when record() is evaluated (now)
62
+
63
+ Raises:
64
+ QuotaViolationException: if recording this value moves a
65
+ metric beyond its configured maximum or minimum bound
66
+ """
67
+ if time_ms is None:
68
+ time_ms = time.time() * 1000
69
+ self._last_record_time = time_ms
70
+ with self._lock: # XXX high volume, might be performance issue
71
+ # increment all the stats
72
+ for stat in self._stats:
73
+ stat.record(self._config, value, time_ms)
74
+ self._check_quotas(time_ms)
75
+ for parent in self._parents:
76
+ parent.record(value, time_ms)
77
+
78
+ def _check_quotas(self, time_ms):
79
+ """
80
+ Check if we have violated our quota for any metric that
81
+ has a configured quota
82
+ """
83
+ for metric in self._metrics:
84
+ if metric.config and metric.config.quota:
85
+ value = metric.value(time_ms)
86
+ if not metric.config.quota.is_acceptable(value):
87
+ raise QuotaViolationError("'%s' violated quota. Actual: "
88
+ "%d, Threshold: %d" %
89
+ (metric.metric_name,
90
+ value,
91
+ metric.config.quota.bound))
92
+
93
+ def add_compound(self, compound_stat, config=None):
94
+ """
95
+ Register a compound statistic with this sensor which
96
+ yields multiple measurable quantities (like a histogram)
97
+
98
+ Arguments:
99
+ stat (AbstractCompoundStat): The stat to register
100
+ config (MetricConfig): The configuration for this stat.
101
+ If None then the stat will use the default configuration
102
+ for this sensor.
103
+ """
104
+ if not compound_stat:
105
+ raise ValueError('compound stat must be non-empty')
106
+ self._stats.append(compound_stat)
107
+ for named_measurable in compound_stat.stats():
108
+ metric = KafkaMetric(named_measurable.name, named_measurable.stat,
109
+ config or self._config)
110
+ self._registry.register_metric(metric)
111
+ self._metrics.append(metric)
112
+
113
+ def add(self, metric_name, stat, config=None):
114
+ """
115
+ Register a metric with this sensor
116
+
117
+ Arguments:
118
+ metric_name (MetricName): The name of the metric
119
+ stat (AbstractMeasurableStat): The statistic to keep
120
+ config (MetricConfig): A special configuration for this metric.
121
+ If None use the sensor default configuration.
122
+ """
123
+ with self._lock:
124
+ metric = KafkaMetric(metric_name, stat, config or self._config)
125
+ self._registry.register_metric(metric)
126
+ self._metrics.append(metric)
127
+ self._stats.append(stat)
128
+
129
+ def has_expired(self):
130
+ """
131
+ Return True if the Sensor is eligible for removal due to inactivity.
132
+ """
133
+ return ((time.time() * 1000 - self._last_record_time) >
134
+ self._inactive_sensor_expiration_time_ms)
testbed/dpkp__kafka-python/kafka/oauth/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from __future__ import absolute_import
2
+
3
+ from kafka.oauth.abstract import AbstractTokenProvider
testbed/dpkp__kafka-python/kafka/oauth/abstract.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+
3
+ import abc
4
+
5
+ # This statement is compatible with both Python 2.7 & 3+
6
+ ABC = abc.ABCMeta('ABC', (object,), {'__slots__': ()})
7
+
8
+ class AbstractTokenProvider(ABC):
9
+ """
10
+ A Token Provider must be used for the SASL OAuthBearer protocol.
11
+
12
+ The implementation should ensure token reuse so that multiple
13
+ calls at connect time do not create multiple tokens. The implementation
14
+ should also periodically refresh the token in order to guarantee
15
+ that each call returns an unexpired token. A timeout error should
16
+ be returned after a short period of inactivity so that the
17
+ broker can log debugging info and retry.
18
+
19
+ Token Providers MUST implement the token() method
20
+ """
21
+
22
+ def __init__(self, **config):
23
+ pass
24
+
25
+ @abc.abstractmethod
26
+ def token(self):
27
+ """
28
+ Returns a (str) ID/Access Token to be sent to the Kafka
29
+ client.
30
+ """
31
+ pass
32
+
33
+ def extensions(self):
34
+ """
35
+ This is an OPTIONAL method that may be implemented.
36
+
37
+ Returns a map of key-value pairs that can
38
+ be sent with the SASL/OAUTHBEARER initial client request. If
39
+ not implemented, the values are ignored. This feature is only available
40
+ in Kafka >= 2.1.0.
41
+ """
42
+ return {}
testbed/dpkp__kafka-python/kafka/partitioner/default.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+
3
+ import random
4
+
5
+ from kafka.vendor import six
6
+
7
+
8
+ class DefaultPartitioner(object):
9
+ """Default partitioner.
10
+
11
+ Hashes key to partition using murmur2 hashing (from java client)
12
+ If key is None, selects partition randomly from available,
13
+ or from all partitions if none are currently available
14
+ """
15
+ @classmethod
16
+ def __call__(cls, key, all_partitions, available):
17
+ """
18
+ Get the partition corresponding to key
19
+ :param key: partitioning key
20
+ :param all_partitions: list of all partitions sorted by partition ID
21
+ :param available: list of available partitions in no particular order
22
+ :return: one of the values from all_partitions or available
23
+ """
24
+ if key is None:
25
+ if available:
26
+ return random.choice(available)
27
+ return random.choice(all_partitions)
28
+
29
+ idx = murmur2(key)
30
+ idx &= 0x7fffffff
31
+ idx %= len(all_partitions)
32
+ return all_partitions[idx]
33
+
34
+
35
+ # https://github.com/apache/kafka/blob/0.8.2/clients/src/main/java/org/apache/kafka/common/utils/Utils.java#L244
36
+ def murmur2(data):
37
+ """Pure-python Murmur2 implementation.
38
+
39
+ Based on java client, see org.apache.kafka.common.utils.Utils.murmur2
40
+
41
+ Args:
42
+ data (bytes): opaque bytes
43
+
44
+ Returns: MurmurHash2 of data
45
+ """
46
+ # Python2 bytes is really a str, causing the bitwise operations below to fail
47
+ # so convert to bytearray.
48
+ if six.PY2:
49
+ data = bytearray(bytes(data))
50
+
51
+ length = len(data)
52
+ seed = 0x9747b28c
53
+ # 'm' and 'r' are mixing constants generated offline.
54
+ # They're not really 'magic', they just happen to work well.
55
+ m = 0x5bd1e995
56
+ r = 24
57
+
58
+ # Initialize the hash to a random value
59
+ h = seed ^ length
60
+ length4 = length // 4
61
+
62
+ for i in range(length4):
63
+ i4 = i * 4
64
+ k = ((data[i4 + 0] & 0xff) +
65
+ ((data[i4 + 1] & 0xff) << 8) +
66
+ ((data[i4 + 2] & 0xff) << 16) +
67
+ ((data[i4 + 3] & 0xff) << 24))
68
+ k &= 0xffffffff
69
+ k *= m
70
+ k &= 0xffffffff
71
+ k ^= (k % 0x100000000) >> r # k ^= k >>> r
72
+ k &= 0xffffffff
73
+ k *= m
74
+ k &= 0xffffffff
75
+
76
+ h *= m
77
+ h &= 0xffffffff
78
+ h ^= k
79
+ h &= 0xffffffff
80
+
81
+ # Handle the last few bytes of the input array
82
+ extra_bytes = length % 4
83
+ if extra_bytes >= 3:
84
+ h ^= (data[(length & ~3) + 2] & 0xff) << 16
85
+ h &= 0xffffffff
86
+ if extra_bytes >= 2:
87
+ h ^= (data[(length & ~3) + 1] & 0xff) << 8
88
+ h &= 0xffffffff
89
+ if extra_bytes >= 1:
90
+ h ^= (data[length & ~3] & 0xff)
91
+ h &= 0xffffffff
92
+ h *= m
93
+ h &= 0xffffffff
94
+
95
+ h ^= (h % 0x100000000) >> 13 # h >>> 13;
96
+ h &= 0xffffffff
97
+ h *= m
98
+ h &= 0xffffffff
99
+ h ^= (h % 0x100000000) >> 15 # h >>> 15;
100
+ h &= 0xffffffff
101
+
102
+ return h
testbed/dpkp__kafka-python/kafka/producer/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+
3
+ from kafka.producer.kafka import KafkaProducer
4
+
5
+ __all__ = [
6
+ 'KafkaProducer'
7
+ ]
testbed/dpkp__kafka-python/kafka/producer/future.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+
3
+ import collections
4
+ import threading
5
+
6
+ from kafka import errors as Errors
7
+ from kafka.future import Future
8
+
9
+
10
+ class FutureProduceResult(Future):
11
+ def __init__(self, topic_partition):
12
+ super(FutureProduceResult, self).__init__()
13
+ self.topic_partition = topic_partition
14
+ self._latch = threading.Event()
15
+
16
+ def success(self, value):
17
+ ret = super(FutureProduceResult, self).success(value)
18
+ self._latch.set()
19
+ return ret
20
+
21
+ def failure(self, error):
22
+ ret = super(FutureProduceResult, self).failure(error)
23
+ self._latch.set()
24
+ return ret
25
+
26
+ def wait(self, timeout=None):
27
+ # wait() on python2.6 returns None instead of the flag value
28
+ return self._latch.wait(timeout) or self._latch.is_set()
29
+
30
+
31
+ class FutureRecordMetadata(Future):
32
+ def __init__(self, produce_future, relative_offset, timestamp_ms, checksum, serialized_key_size, serialized_value_size, serialized_header_size):
33
+ super(FutureRecordMetadata, self).__init__()
34
+ self._produce_future = produce_future
35
+ # packing args as a tuple is a minor speed optimization
36
+ self.args = (relative_offset, timestamp_ms, checksum, serialized_key_size, serialized_value_size, serialized_header_size)
37
+ produce_future.add_callback(self._produce_success)
38
+ produce_future.add_errback(self.failure)
39
+
40
+ def _produce_success(self, offset_and_timestamp):
41
+ offset, produce_timestamp_ms, log_start_offset = offset_and_timestamp
42
+
43
+ # Unpacking from args tuple is minor speed optimization
44
+ (relative_offset, timestamp_ms, checksum,
45
+ serialized_key_size, serialized_value_size, serialized_header_size) = self.args
46
+
47
+ # None is when Broker does not support the API (<0.10) and
48
+ # -1 is when the broker is configured for CREATE_TIME timestamps
49
+ if produce_timestamp_ms is not None and produce_timestamp_ms != -1:
50
+ timestamp_ms = produce_timestamp_ms
51
+ if offset != -1 and relative_offset is not None:
52
+ offset += relative_offset
53
+ tp = self._produce_future.topic_partition
54
+ metadata = RecordMetadata(tp[0], tp[1], tp, offset, timestamp_ms, log_start_offset,
55
+ checksum, serialized_key_size,
56
+ serialized_value_size, serialized_header_size)
57
+ self.success(metadata)
58
+
59
+ def get(self, timeout=None):
60
+ if not self.is_done and not self._produce_future.wait(timeout):
61
+ raise Errors.KafkaTimeoutError(
62
+ "Timeout after waiting for %s secs." % (timeout,))
63
+ assert self.is_done
64
+ if self.failed():
65
+ raise self.exception # pylint: disable-msg=raising-bad-type
66
+ return self.value
67
+
68
+
69
+ RecordMetadata = collections.namedtuple(
70
+ 'RecordMetadata', ['topic', 'partition', 'topic_partition', 'offset', 'timestamp', 'log_start_offset',
71
+ 'checksum', 'serialized_key_size', 'serialized_value_size', 'serialized_header_size'])
testbed/dpkp__kafka-python/kafka/producer/kafka.py ADDED
@@ -0,0 +1,749 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+
3
+ import atexit
4
+ import copy
5
+ import logging
6
+ import socket
7
+ import threading
8
+ import time
9
+ import weakref
10
+
11
+ from kafka.vendor import six
12
+
13
+ import kafka.errors as Errors
14
+ from kafka.client_async import KafkaClient, selectors
15
+ from kafka.codec import has_gzip, has_snappy, has_lz4, has_zstd
16
+ from kafka.metrics import MetricConfig, Metrics
17
+ from kafka.partitioner.default import DefaultPartitioner
18
+ from kafka.producer.future import FutureRecordMetadata, FutureProduceResult
19
+ from kafka.producer.record_accumulator import AtomicInteger, RecordAccumulator
20
+ from kafka.producer.sender import Sender
21
+ from kafka.record.default_records import DefaultRecordBatchBuilder
22
+ from kafka.record.legacy_records import LegacyRecordBatchBuilder
23
+ from kafka.serializer import Serializer
24
+ from kafka.structs import TopicPartition
25
+
26
+
27
+ log = logging.getLogger(__name__)
28
+ PRODUCER_CLIENT_ID_SEQUENCE = AtomicInteger()
29
+
30
+
31
+ class KafkaProducer(object):
32
+ """A Kafka client that publishes records to the Kafka cluster.
33
+
34
+ The producer is thread safe and sharing a single producer instance across
35
+ threads will generally be faster than having multiple instances.
36
+
37
+ The producer consists of a pool of buffer space that holds records that
38
+ haven't yet been transmitted to the server as well as a background I/O
39
+ thread that is responsible for turning these records into requests and
40
+ transmitting them to the cluster.
41
+
42
+ :meth:`~kafka.KafkaProducer.send` is asynchronous. When called it adds the
43
+ record to a buffer of pending record sends and immediately returns. This
44
+ allows the producer to batch together individual records for efficiency.
45
+
46
+ The 'acks' config controls the criteria under which requests are considered
47
+ complete. The "all" setting will result in blocking on the full commit of
48
+ the record, the slowest but most durable setting.
49
+
50
+ If the request fails, the producer can automatically retry, unless
51
+ 'retries' is configured to 0. Enabling retries also opens up the
52
+ possibility of duplicates (see the documentation on message
53
+ delivery semantics for details:
54
+ https://kafka.apache.org/documentation.html#semantics
55
+ ).
56
+
57
+ The producer maintains buffers of unsent records for each partition. These
58
+ buffers are of a size specified by the 'batch_size' config. Making this
59
+ larger can result in more batching, but requires more memory (since we will
60
+ generally have one of these buffers for each active partition).
61
+
62
+ By default a buffer is available to send immediately even if there is
63
+ additional unused space in the buffer. However if you want to reduce the
64
+ number of requests you can set 'linger_ms' to something greater than 0.
65
+ This will instruct the producer to wait up to that number of milliseconds
66
+ before sending a request in hope that more records will arrive to fill up
67
+ the same batch. This is analogous to Nagle's algorithm in TCP. Note that
68
+ records that arrive close together in time will generally batch together
69
+ even with linger_ms=0 so under heavy load batching will occur regardless of
70
+ the linger configuration; however setting this to something larger than 0
71
+ can lead to fewer, more efficient requests when not under maximal load at
72
+ the cost of a small amount of latency.
73
+
74
+ The buffer_memory controls the total amount of memory available to the
75
+ producer for buffering. If records are sent faster than they can be
76
+ transmitted to the server then this buffer space will be exhausted. When
77
+ the buffer space is exhausted additional send calls will block.
78
+
79
+ The key_serializer and value_serializer instruct how to turn the key and
80
+ value objects the user provides into bytes.
81
+
82
+ Keyword Arguments:
83
+ bootstrap_servers: 'host[:port]' string (or list of 'host[:port]'
84
+ strings) that the producer should contact to bootstrap initial
85
+ cluster metadata. This does not have to be the full node list.
86
+ It just needs to have at least one broker that will respond to a
87
+ Metadata API Request. Default port is 9092. If no servers are
88
+ specified, will default to localhost:9092.
89
+ client_id (str): a name for this client. This string is passed in
90
+ each request to servers and can be used to identify specific
91
+ server-side log entries that correspond to this client.
92
+ Default: 'kafka-python-producer-#' (appended with a unique number
93
+ per instance)
94
+ key_serializer (callable): used to convert user-supplied keys to bytes
95
+ If not None, called as f(key), should return bytes. Default: None.
96
+ value_serializer (callable): used to convert user-supplied message
97
+ values to bytes. If not None, called as f(value), should return
98
+ bytes. Default: None.
99
+ acks (0, 1, 'all'): The number of acknowledgments the producer requires
100
+ the leader to have received before considering a request complete.
101
+ This controls the durability of records that are sent. The
102
+ following settings are common:
103
+
104
+ 0: Producer will not wait for any acknowledgment from the server.
105
+ The message will immediately be added to the socket
106
+ buffer and considered sent. No guarantee can be made that the
107
+ server has received the record in this case, and the retries
108
+ configuration will not take effect (as the client won't
109
+ generally know of any failures). The offset given back for each
110
+ record will always be set to -1.
111
+ 1: Wait for leader to write the record to its local log only.
112
+ Broker will respond without awaiting full acknowledgement from
113
+ all followers. In this case should the leader fail immediately
114
+ after acknowledging the record but before the followers have
115
+ replicated it then the record will be lost.
116
+ all: Wait for the full set of in-sync replicas to write the record.
117
+ This guarantees that the record will not be lost as long as at
118
+ least one in-sync replica remains alive. This is the strongest
119
+ available guarantee.
120
+ If unset, defaults to acks=1.
121
+ compression_type (str): The compression type for all data generated by
122
+ the producer. Valid values are 'gzip', 'snappy', 'lz4', 'zstd' or None.
123
+ Compression is of full batches of data, so the efficacy of batching
124
+ will also impact the compression ratio (more batching means better
125
+ compression). Default: None.
126
+ retries (int): Setting a value greater than zero will cause the client
127
+ to resend any record whose send fails with a potentially transient
128
+ error. Note that this retry is no different than if the client
129
+ resent the record upon receiving the error. Allowing retries
130
+ without setting max_in_flight_requests_per_connection to 1 will
131
+ potentially change the ordering of records because if two batches
132
+ are sent to a single partition, and the first fails and is retried
133
+ but the second succeeds, then the records in the second batch may
134
+ appear first.
135
+ Default: 0.
136
+ batch_size (int): Requests sent to brokers will contain multiple
137
+ batches, one for each partition with data available to be sent.
138
+ A small batch size will make batching less common and may reduce
139
+ throughput (a batch size of zero will disable batching entirely).
140
+ Default: 16384
141
+ linger_ms (int): The producer groups together any records that arrive
142
+ in between request transmissions into a single batched request.
143
+ Normally this occurs only under load when records arrive faster
144
+ than they can be sent out. However in some circumstances the client
145
+ may want to reduce the number of requests even under moderate load.
146
+ This setting accomplishes this by adding a small amount of
147
+ artificial delay; that is, rather than immediately sending out a
148
+ record the producer will wait for up to the given delay to allow
149
+ other records to be sent so that the sends can be batched together.
150
+ This can be thought of as analogous to Nagle's algorithm in TCP.
151
+ This setting gives the upper bound on the delay for batching: once
152
+ we get batch_size worth of records for a partition it will be sent
153
+ immediately regardless of this setting, however if we have fewer
154
+ than this many bytes accumulated for this partition we will
155
+ 'linger' for the specified time waiting for more records to show
156
+ up. This setting defaults to 0 (i.e. no delay). Setting linger_ms=5
157
+ would have the effect of reducing the number of requests sent but
158
+ would add up to 5ms of latency to records sent in the absence of
159
+ load. Default: 0.
160
+ partitioner (callable): Callable used to determine which partition
161
+ each message is assigned to. Called (after key serialization):
162
+ partitioner(key_bytes, all_partitions, available_partitions).
163
+ The default partitioner implementation hashes each non-None key
164
+ using the same murmur2 algorithm as the java client so that
165
+ messages with the same key are assigned to the same partition.
166
+ When a key is None, the message is delivered to a random partition
167
+ (filtered to partitions with available leaders only, if possible).
168
+ buffer_memory (int): The total bytes of memory the producer should use
169
+ to buffer records waiting to be sent to the server. If records are
170
+ sent faster than they can be delivered to the server the producer
171
+ will block up to max_block_ms, raising an exception on timeout.
172
+ In the current implementation, this setting is an approximation.
173
+ Default: 33554432 (32MB)
174
+ connections_max_idle_ms: Close idle connections after the number of
175
+ milliseconds specified by this config. The broker closes idle
176
+ connections after connections.max.idle.ms, so this avoids hitting
177
+ unexpected socket disconnected errors on the client.
178
+ Default: 540000
179
+ max_block_ms (int): Number of milliseconds to block during
180
+ :meth:`~kafka.KafkaProducer.send` and
181
+ :meth:`~kafka.KafkaProducer.partitions_for`. These methods can be
182
+ blocked either because the buffer is full or metadata unavailable.
183
+ Blocking in the user-supplied serializers or partitioner will not be
184
+ counted against this timeout. Default: 60000.
185
+ max_request_size (int): The maximum size of a request. This is also
186
+ effectively a cap on the maximum record size. Note that the server
187
+ has its own cap on record size which may be different from this.
188
+ This setting will limit the number of record batches the producer
189
+ will send in a single request to avoid sending huge requests.
190
+ Default: 1048576.
191
+ metadata_max_age_ms (int): The period of time in milliseconds after
192
+ which we force a refresh of metadata even if we haven't seen any
193
+ partition leadership changes to proactively discover any new
194
+ brokers or partitions. Default: 300000
195
+ retry_backoff_ms (int): Milliseconds to backoff when retrying on
196
+ errors. Default: 100.
197
+ request_timeout_ms (int): Client request timeout in milliseconds.
198
+ Default: 30000.
199
+ receive_buffer_bytes (int): The size of the TCP receive buffer
200
+ (SO_RCVBUF) to use when reading data. Default: None (relies on
201
+ system defaults). Java client defaults to 32768.
202
+ send_buffer_bytes (int): The size of the TCP send buffer
203
+ (SO_SNDBUF) to use when sending data. Default: None (relies on
204
+ system defaults). Java client defaults to 131072.
205
+ socket_options (list): List of tuple-arguments to socket.setsockopt
206
+ to apply to broker connection sockets. Default:
207
+ [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]
208
+ reconnect_backoff_ms (int): The amount of time in milliseconds to
209
+ wait before attempting to reconnect to a given host.
210
+ Default: 50.
211
+ reconnect_backoff_max_ms (int): The maximum amount of time in
212
+ milliseconds to backoff/wait when reconnecting to a broker that has
213
+ repeatedly failed to connect. If provided, the backoff per host
214
+ will increase exponentially for each consecutive connection
215
+ failure, up to this maximum. Once the maximum is reached,
216
+ reconnection attempts will continue periodically with this fixed
217
+ rate. To avoid connection storms, a randomization factor of 0.2
218
+ will be applied to the backoff resulting in a random range between
219
+ 20% below and 20% above the computed value. Default: 1000.
220
+ max_in_flight_requests_per_connection (int): Requests are pipelined
221
+ to kafka brokers up to this number of maximum requests per
222
+ broker connection. Note that if this setting is set to be greater
223
+ than 1 and there are failed sends, there is a risk of message
224
+ re-ordering due to retries (i.e., if retries are enabled).
225
+ Default: 5.
226
+ security_protocol (str): Protocol used to communicate with brokers.
227
+ Valid values are: PLAINTEXT, SSL, SASL_PLAINTEXT, SASL_SSL.
228
+ Default: PLAINTEXT.
229
+ ssl_context (ssl.SSLContext): pre-configured SSLContext for wrapping
230
+ socket connections. If provided, all other ssl_* configurations
231
+ will be ignored. Default: None.
232
+ ssl_check_hostname (bool): flag to configure whether ssl handshake
233
+ should verify that the certificate matches the brokers hostname.
234
+ default: true.
235
+ ssl_cafile (str): optional filename of ca file to use in certificate
236
+ veriication. default: none.
237
+ ssl_certfile (str): optional filename of file in pem format containing
238
+ the client certificate, as well as any ca certificates needed to
239
+ establish the certificate's authenticity. default: none.
240
+ ssl_keyfile (str): optional filename containing the client private key.
241
+ default: none.
242
+ ssl_password (str): optional password to be used when loading the
243
+ certificate chain. default: none.
244
+ ssl_crlfile (str): optional filename containing the CRL to check for
245
+ certificate expiration. By default, no CRL check is done. When
246
+ providing a file, only the leaf certificate will be checked against
247
+ this CRL. The CRL can only be checked with Python 3.4+ or 2.7.9+.
248
+ default: none.
249
+ ssl_ciphers (str): optionally set the available ciphers for ssl
250
+ connections. It should be a string in the OpenSSL cipher list
251
+ format. If no cipher can be selected (because compile-time options
252
+ or other configuration forbids use of all the specified ciphers),
253
+ an ssl.SSLError will be raised. See ssl.SSLContext.set_ciphers
254
+ api_version (tuple): Specify which Kafka API version to use. If set to
255
+ None, the client will attempt to infer the broker version by probing
256
+ various APIs. Example: (0, 10, 2). Default: None
257
+ api_version_auto_timeout_ms (int): number of milliseconds to throw a
258
+ timeout exception from the constructor when checking the broker
259
+ api version. Only applies if api_version set to None.
260
+ metric_reporters (list): A list of classes to use as metrics reporters.
261
+ Implementing the AbstractMetricsReporter interface allows plugging
262
+ in classes that will be notified of new metric creation. Default: []
263
+ metrics_num_samples (int): The number of samples maintained to compute
264
+ metrics. Default: 2
265
+ metrics_sample_window_ms (int): The maximum age in milliseconds of
266
+ samples used to compute metrics. Default: 30000
267
+ selector (selectors.BaseSelector): Provide a specific selector
268
+ implementation to use for I/O multiplexing.
269
+ Default: selectors.DefaultSelector
270
+ sasl_mechanism (str): Authentication mechanism when security_protocol
271
+ is configured for SASL_PLAINTEXT or SASL_SSL. Valid values are:
272
+ PLAIN, GSSAPI, OAUTHBEARER, SCRAM-SHA-256, SCRAM-SHA-512.
273
+ sasl_plain_username (str): username for sasl PLAIN and SCRAM authentication.
274
+ Required if sasl_mechanism is PLAIN or one of the SCRAM mechanisms.
275
+ sasl_plain_password (str): password for sasl PLAIN and SCRAM authentication.
276
+ Required if sasl_mechanism is PLAIN or one of the SCRAM mechanisms.
277
+ sasl_kerberos_service_name (str): Service name to include in GSSAPI
278
+ sasl mechanism handshake. Default: 'kafka'
279
+ sasl_kerberos_domain_name (str): kerberos domain name to use in GSSAPI
280
+ sasl mechanism handshake. Default: one of bootstrap servers
281
+ sasl_oauth_token_provider (AbstractTokenProvider): OAuthBearer token provider
282
+ instance. (See kafka.oauth.abstract). Default: None
283
+
284
+ Note:
285
+ Configuration parameters are described in more detail at
286
+ https://kafka.apache.org/0100/configuration.html#producerconfigs
287
+ """
288
+ DEFAULT_CONFIG = {
289
+ 'bootstrap_servers': 'localhost',
290
+ 'client_id': None,
291
+ 'key_serializer': None,
292
+ 'value_serializer': None,
293
+ 'acks': 1,
294
+ 'bootstrap_topics_filter': set(),
295
+ 'compression_type': None,
296
+ 'retries': 0,
297
+ 'batch_size': 16384,
298
+ 'linger_ms': 0,
299
+ 'partitioner': DefaultPartitioner(),
300
+ 'buffer_memory': 33554432,
301
+ 'connections_max_idle_ms': 9 * 60 * 1000,
302
+ 'max_block_ms': 60000,
303
+ 'max_request_size': 1048576,
304
+ 'metadata_max_age_ms': 300000,
305
+ 'retry_backoff_ms': 100,
306
+ 'request_timeout_ms': 30000,
307
+ 'receive_buffer_bytes': None,
308
+ 'send_buffer_bytes': None,
309
+ 'socket_options': [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)],
310
+ 'sock_chunk_bytes': 4096, # undocumented experimental option
311
+ 'sock_chunk_buffer_count': 1000, # undocumented experimental option
312
+ 'reconnect_backoff_ms': 50,
313
+ 'reconnect_backoff_max_ms': 1000,
314
+ 'max_in_flight_requests_per_connection': 5,
315
+ 'security_protocol': 'PLAINTEXT',
316
+ 'ssl_context': None,
317
+ 'ssl_check_hostname': True,
318
+ 'ssl_cafile': None,
319
+ 'ssl_certfile': None,
320
+ 'ssl_keyfile': None,
321
+ 'ssl_crlfile': None,
322
+ 'ssl_password': None,
323
+ 'ssl_ciphers': None,
324
+ 'api_version': None,
325
+ 'api_version_auto_timeout_ms': 2000,
326
+ 'metric_reporters': [],
327
+ 'metrics_num_samples': 2,
328
+ 'metrics_sample_window_ms': 30000,
329
+ 'selector': selectors.DefaultSelector,
330
+ 'sasl_mechanism': None,
331
+ 'sasl_plain_username': None,
332
+ 'sasl_plain_password': None,
333
+ 'sasl_kerberos_service_name': 'kafka',
334
+ 'sasl_kerberos_domain_name': None,
335
+ 'sasl_oauth_token_provider': None
336
+ }
337
+
338
+ _COMPRESSORS = {
339
+ 'gzip': (has_gzip, LegacyRecordBatchBuilder.CODEC_GZIP),
340
+ 'snappy': (has_snappy, LegacyRecordBatchBuilder.CODEC_SNAPPY),
341
+ 'lz4': (has_lz4, LegacyRecordBatchBuilder.CODEC_LZ4),
342
+ 'zstd': (has_zstd, DefaultRecordBatchBuilder.CODEC_ZSTD),
343
+ None: (lambda: True, LegacyRecordBatchBuilder.CODEC_NONE),
344
+ }
345
+
346
+ def __init__(self, **configs):
347
+ log.debug("Starting the Kafka producer") # trace
348
+ self.config = copy.copy(self.DEFAULT_CONFIG)
349
+ for key in self.config:
350
+ if key in configs:
351
+ self.config[key] = configs.pop(key)
352
+
353
+ # Only check for extra config keys in top-level class
354
+ assert not configs, 'Unrecognized configs: %s' % (configs,)
355
+
356
+ if self.config['client_id'] is None:
357
+ self.config['client_id'] = 'kafka-python-producer-%s' % \
358
+ (PRODUCER_CLIENT_ID_SEQUENCE.increment(),)
359
+
360
+ if self.config['acks'] == 'all':
361
+ self.config['acks'] = -1
362
+
363
+ # api_version was previously a str. accept old format for now
364
+ if isinstance(self.config['api_version'], str):
365
+ deprecated = self.config['api_version']
366
+ if deprecated == 'auto':
367
+ self.config['api_version'] = None
368
+ else:
369
+ self.config['api_version'] = tuple(map(int, deprecated.split('.')))
370
+ log.warning('use api_version=%s [tuple] -- "%s" as str is deprecated',
371
+ str(self.config['api_version']), deprecated)
372
+
373
+ # Configure metrics
374
+ metrics_tags = {'client-id': self.config['client_id']}
375
+ metric_config = MetricConfig(samples=self.config['metrics_num_samples'],
376
+ time_window_ms=self.config['metrics_sample_window_ms'],
377
+ tags=metrics_tags)
378
+ reporters = [reporter() for reporter in self.config['metric_reporters']]
379
+ self._metrics = Metrics(metric_config, reporters)
380
+
381
+ client = KafkaClient(metrics=self._metrics, metric_group_prefix='producer',
382
+ wakeup_timeout_ms=self.config['max_block_ms'],
383
+ **self.config)
384
+
385
+ # Get auto-discovered version from client if necessary
386
+ if self.config['api_version'] is None:
387
+ self.config['api_version'] = client.config['api_version']
388
+
389
+ if self.config['compression_type'] == 'lz4':
390
+ assert self.config['api_version'] >= (0, 8, 2), 'LZ4 Requires >= Kafka 0.8.2 Brokers'
391
+
392
+ if self.config['compression_type'] == 'zstd':
393
+ assert self.config['api_version'] >= (2, 1, 0), 'Zstd Requires >= Kafka 2.1.0 Brokers'
394
+
395
+ # Check compression_type for library support
396
+ ct = self.config['compression_type']
397
+ if ct not in self._COMPRESSORS:
398
+ raise ValueError("Not supported codec: {}".format(ct))
399
+ else:
400
+ checker, compression_attrs = self._COMPRESSORS[ct]
401
+ assert checker(), "Libraries for {} compression codec not found".format(ct)
402
+ self.config['compression_attrs'] = compression_attrs
403
+
404
+ message_version = self._max_usable_produce_magic()
405
+ self._accumulator = RecordAccumulator(message_version=message_version, metrics=self._metrics, **self.config)
406
+ self._metadata = client.cluster
407
+ guarantee_message_order = bool(self.config['max_in_flight_requests_per_connection'] == 1)
408
+ self._sender = Sender(client, self._metadata,
409
+ self._accumulator, self._metrics,
410
+ guarantee_message_order=guarantee_message_order,
411
+ **self.config)
412
+ self._sender.daemon = True
413
+ self._sender.start()
414
+ self._closed = False
415
+
416
+ self._cleanup = self._cleanup_factory()
417
+ atexit.register(self._cleanup)
418
+ log.debug("Kafka producer started")
419
+
420
+ def bootstrap_connected(self):
421
+ """Return True if the bootstrap is connected."""
422
+ return self._sender.bootstrap_connected()
423
+
424
+ def _cleanup_factory(self):
425
+ """Build a cleanup clojure that doesn't increase our ref count"""
426
+ _self = weakref.proxy(self)
427
+ def wrapper():
428
+ try:
429
+ _self.close(timeout=0)
430
+ except (ReferenceError, AttributeError):
431
+ pass
432
+ return wrapper
433
+
434
+ def _unregister_cleanup(self):
435
+ if getattr(self, '_cleanup', None):
436
+ if hasattr(atexit, 'unregister'):
437
+ atexit.unregister(self._cleanup) # pylint: disable=no-member
438
+
439
+ # py2 requires removing from private attribute...
440
+ else:
441
+
442
+ # ValueError on list.remove() if the exithandler no longer exists
443
+ # but that is fine here
444
+ try:
445
+ atexit._exithandlers.remove( # pylint: disable=no-member
446
+ (self._cleanup, (), {}))
447
+ except ValueError:
448
+ pass
449
+ self._cleanup = None
450
+
451
+ def __del__(self):
452
+ # Disable logger during destruction to avoid touching dangling references
453
+ class NullLogger(object):
454
+ def __getattr__(self, name):
455
+ return lambda *args: None
456
+
457
+ global log
458
+ log = NullLogger()
459
+
460
+ self.close()
461
+
462
+ def close(self, timeout=None):
463
+ """Close this producer.
464
+
465
+ Arguments:
466
+ timeout (float, optional): timeout in seconds to wait for completion.
467
+ """
468
+
469
+ # drop our atexit handler now to avoid leaks
470
+ self._unregister_cleanup()
471
+
472
+ if not hasattr(self, '_closed') or self._closed:
473
+ log.info('Kafka producer closed')
474
+ return
475
+ if timeout is None:
476
+ # threading.TIMEOUT_MAX is available in Python3.3+
477
+ timeout = getattr(threading, 'TIMEOUT_MAX', float('inf'))
478
+ if getattr(threading, 'TIMEOUT_MAX', False):
479
+ assert 0 <= timeout <= getattr(threading, 'TIMEOUT_MAX')
480
+ else:
481
+ assert timeout >= 0
482
+
483
+ log.info("Closing the Kafka producer with %s secs timeout.", timeout)
484
+ invoked_from_callback = bool(threading.current_thread() is self._sender)
485
+ if timeout > 0:
486
+ if invoked_from_callback:
487
+ log.warning("Overriding close timeout %s secs to 0 in order to"
488
+ " prevent useless blocking due to self-join. This"
489
+ " means you have incorrectly invoked close with a"
490
+ " non-zero timeout from the producer call-back.",
491
+ timeout)
492
+ else:
493
+ # Try to close gracefully.
494
+ if self._sender is not None:
495
+ self._sender.initiate_close()
496
+ self._sender.join(timeout)
497
+
498
+ if self._sender is not None and self._sender.is_alive():
499
+ log.info("Proceeding to force close the producer since pending"
500
+ " requests could not be completed within timeout %s.",
501
+ timeout)
502
+ self._sender.force_close()
503
+
504
+ self._metrics.close()
505
+ try:
506
+ self.config['key_serializer'].close()
507
+ except AttributeError:
508
+ pass
509
+ try:
510
+ self.config['value_serializer'].close()
511
+ except AttributeError:
512
+ pass
513
+ self._closed = True
514
+ log.debug("The Kafka producer has closed.")
515
+
516
+ def partitions_for(self, topic):
517
+ """Returns set of all known partitions for the topic."""
518
+ max_wait = self.config['max_block_ms'] / 1000.0
519
+ return self._wait_on_metadata(topic, max_wait)
520
+
521
+ def _max_usable_produce_magic(self):
522
+ if self.config['api_version'] >= (0, 11):
523
+ return 2
524
+ elif self.config['api_version'] >= (0, 10):
525
+ return 1
526
+ else:
527
+ return 0
528
+
529
+ def _estimate_size_in_bytes(self, key, value, headers=[]):
530
+ magic = self._max_usable_produce_magic()
531
+ if magic == 2:
532
+ return DefaultRecordBatchBuilder.estimate_size_in_bytes(
533
+ key, value, headers)
534
+ else:
535
+ return LegacyRecordBatchBuilder.estimate_size_in_bytes(
536
+ magic, self.config['compression_type'], key, value)
537
+
538
+ def send(self, topic, value=None, key=None, headers=None, partition=None, timestamp_ms=None):
539
+ """Publish a message to a topic.
540
+
541
+ Arguments:
542
+ topic (str): topic where the message will be published
543
+ value (optional): message value. Must be type bytes, or be
544
+ serializable to bytes via configured value_serializer. If value
545
+ is None, key is required and message acts as a 'delete'.
546
+ See kafka compaction documentation for more details:
547
+ https://kafka.apache.org/documentation.html#compaction
548
+ (compaction requires kafka >= 0.8.1)
549
+ partition (int, optional): optionally specify a partition. If not
550
+ set, the partition will be selected using the configured
551
+ 'partitioner'.
552
+ key (optional): a key to associate with the message. Can be used to
553
+ determine which partition to send the message to. If partition
554
+ is None (and producer's partitioner config is left as default),
555
+ then messages with the same key will be delivered to the same
556
+ partition (but if key is None, partition is chosen randomly).
557
+ Must be type bytes, or be serializable to bytes via configured
558
+ key_serializer.
559
+ headers (optional): a list of header key value pairs. List items
560
+ are tuples of str key and bytes value.
561
+ timestamp_ms (int, optional): epoch milliseconds (from Jan 1 1970 UTC)
562
+ to use as the message timestamp. Defaults to current time.
563
+
564
+ Returns:
565
+ FutureRecordMetadata: resolves to RecordMetadata
566
+
567
+ Raises:
568
+ KafkaTimeoutError: if unable to fetch topic metadata, or unable
569
+ to obtain memory buffer prior to configured max_block_ms
570
+ """
571
+ assert value is not None or self.config['api_version'] >= (0, 8, 1), (
572
+ 'Null messages require kafka >= 0.8.1')
573
+ assert not (value is None and key is None), 'Need at least one: key or value'
574
+ key_bytes = value_bytes = None
575
+ try:
576
+ self._wait_on_metadata(topic, self.config['max_block_ms'] / 1000.0)
577
+
578
+ key_bytes = self._serialize(
579
+ self.config['key_serializer'],
580
+ topic, key)
581
+ value_bytes = self._serialize(
582
+ self.config['value_serializer'],
583
+ topic, value)
584
+ assert type(key_bytes) in (bytes, bytearray, memoryview, type(None))
585
+ assert type(value_bytes) in (bytes, bytearray, memoryview, type(None))
586
+
587
+ partition = self._partition(topic, partition, key, value,
588
+ key_bytes, value_bytes)
589
+
590
+ if headers is None:
591
+ headers = []
592
+ assert type(headers) == list
593
+ assert all(type(item) == tuple and len(item) == 2 and type(item[0]) == str and type(item[1]) == bytes for item in headers)
594
+
595
+ message_size = self._estimate_size_in_bytes(key_bytes, value_bytes, headers)
596
+ self._ensure_valid_record_size(message_size)
597
+
598
+ tp = TopicPartition(topic, partition)
599
+ log.debug("Sending (key=%r value=%r headers=%r) to %s", key, value, headers, tp)
600
+ result = self._accumulator.append(tp, timestamp_ms,
601
+ key_bytes, value_bytes, headers,
602
+ self.config['max_block_ms'],
603
+ estimated_size=message_size)
604
+ future, batch_is_full, new_batch_created = result
605
+ if batch_is_full or new_batch_created:
606
+ log.debug("Waking up the sender since %s is either full or"
607
+ " getting a new batch", tp)
608
+ self._sender.wakeup()
609
+
610
+ return future
611
+ # handling exceptions and record the errors;
612
+ # for API exceptions return them in the future,
613
+ # for other exceptions raise directly
614
+ except Errors.BrokerResponseError as e:
615
+ log.debug("Exception occurred during message send: %s", e)
616
+ return FutureRecordMetadata(
617
+ FutureProduceResult(TopicPartition(topic, partition)),
618
+ -1, None, None,
619
+ len(key_bytes) if key_bytes is not None else -1,
620
+ len(value_bytes) if value_bytes is not None else -1,
621
+ sum(len(h_key.encode("utf-8")) + len(h_value) for h_key, h_value in headers) if headers else -1,
622
+ ).failure(e)
623
+
624
+ def flush(self, timeout=None):
625
+ """
626
+ Invoking this method makes all buffered records immediately available
627
+ to send (even if linger_ms is greater than 0) and blocks on the
628
+ completion of the requests associated with these records. The
629
+ post-condition of :meth:`~kafka.KafkaProducer.flush` is that any
630
+ previously sent record will have completed
631
+ (e.g. Future.is_done() == True). A request is considered completed when
632
+ either it is successfully acknowledged according to the 'acks'
633
+ configuration for the producer, or it results in an error.
634
+
635
+ Other threads can continue sending messages while one thread is blocked
636
+ waiting for a flush call to complete; however, no guarantee is made
637
+ about the completion of messages sent after the flush call begins.
638
+
639
+ Arguments:
640
+ timeout (float, optional): timeout in seconds to wait for completion.
641
+
642
+ Raises:
643
+ KafkaTimeoutError: failure to flush buffered records within the
644
+ provided timeout
645
+ """
646
+ log.debug("Flushing accumulated records in producer.") # trace
647
+ self._accumulator.begin_flush()
648
+ self._sender.wakeup()
649
+ self._accumulator.await_flush_completion(timeout=timeout)
650
+
651
+ def _ensure_valid_record_size(self, size):
652
+ """Validate that the record size isn't too large."""
653
+ if size > self.config['max_request_size']:
654
+ raise Errors.MessageSizeTooLargeError(
655
+ "The message is %d bytes when serialized which is larger than"
656
+ " the maximum request size you have configured with the"
657
+ " max_request_size configuration" % (size,))
658
+ if size > self.config['buffer_memory']:
659
+ raise Errors.MessageSizeTooLargeError(
660
+ "The message is %d bytes when serialized which is larger than"
661
+ " the total memory buffer you have configured with the"
662
+ " buffer_memory configuration." % (size,))
663
+
664
+ def _wait_on_metadata(self, topic, max_wait):
665
+ """
666
+ Wait for cluster metadata including partitions for the given topic to
667
+ be available.
668
+
669
+ Arguments:
670
+ topic (str): topic we want metadata for
671
+ max_wait (float): maximum time in secs for waiting on the metadata
672
+
673
+ Returns:
674
+ set: partition ids for the topic
675
+
676
+ Raises:
677
+ KafkaTimeoutError: if partitions for topic were not obtained before
678
+ specified max_wait timeout
679
+ """
680
+ # add topic to metadata topic list if it is not there already.
681
+ self._sender.add_topic(topic)
682
+ begin = time.time()
683
+ elapsed = 0.0
684
+ metadata_event = None
685
+ while True:
686
+ partitions = self._metadata.partitions_for_topic(topic)
687
+ if partitions is not None:
688
+ return partitions
689
+
690
+ if not metadata_event:
691
+ metadata_event = threading.Event()
692
+
693
+ log.debug("Requesting metadata update for topic %s", topic)
694
+
695
+ metadata_event.clear()
696
+ future = self._metadata.request_update()
697
+ future.add_both(lambda e, *args: e.set(), metadata_event)
698
+ self._sender.wakeup()
699
+ metadata_event.wait(max_wait - elapsed)
700
+ elapsed = time.time() - begin
701
+ if not metadata_event.is_set():
702
+ raise Errors.KafkaTimeoutError(
703
+ "Failed to update metadata after %.1f secs." % (max_wait,))
704
+ elif topic in self._metadata.unauthorized_topics:
705
+ raise Errors.TopicAuthorizationFailedError(topic)
706
+ else:
707
+ log.debug("_wait_on_metadata woke after %s secs.", elapsed)
708
+
709
+ def _serialize(self, f, topic, data):
710
+ if not f:
711
+ return data
712
+ if isinstance(f, Serializer):
713
+ return f.serialize(topic, data)
714
+ return f(data)
715
+
716
+ def _partition(self, topic, partition, key, value,
717
+ serialized_key, serialized_value):
718
+ if partition is not None:
719
+ assert partition >= 0
720
+ assert partition in self._metadata.partitions_for_topic(topic), 'Unrecognized partition'
721
+ return partition
722
+
723
+ all_partitions = sorted(self._metadata.partitions_for_topic(topic))
724
+ available = list(self._metadata.available_partitions_for_topic(topic))
725
+ return self.config['partitioner'](serialized_key,
726
+ all_partitions,
727
+ available)
728
+
729
+ def metrics(self, raw=False):
730
+ """Get metrics on producer performance.
731
+
732
+ This is ported from the Java Producer, for details see:
733
+ https://kafka.apache.org/documentation/#producer_monitoring
734
+
735
+ Warning:
736
+ This is an unstable interface. It may change in future
737
+ releases without warning.
738
+ """
739
+ if raw:
740
+ return self._metrics.metrics.copy()
741
+
742
+ metrics = {}
743
+ for k, v in six.iteritems(self._metrics.metrics.copy()):
744
+ if k.group not in metrics:
745
+ metrics[k.group] = {}
746
+ if k.name not in metrics[k.group]:
747
+ metrics[k.group][k.name] = {}
748
+ metrics[k.group][k.name] = v.value()
749
+ return metrics
testbed/dpkp__kafka-python/kafka/producer/record_accumulator.py ADDED
@@ -0,0 +1,590 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+
3
+ import collections
4
+ import copy
5
+ import logging
6
+ import threading
7
+ import time
8
+
9
+ import kafka.errors as Errors
10
+ from kafka.producer.buffer import SimpleBufferPool
11
+ from kafka.producer.future import FutureRecordMetadata, FutureProduceResult
12
+ from kafka.record.memory_records import MemoryRecordsBuilder
13
+ from kafka.structs import TopicPartition
14
+
15
+
16
+ log = logging.getLogger(__name__)
17
+
18
+
19
+ class AtomicInteger(object):
20
+ def __init__(self, val=0):
21
+ self._lock = threading.Lock()
22
+ self._val = val
23
+
24
+ def increment(self):
25
+ with self._lock:
26
+ self._val += 1
27
+ return self._val
28
+
29
+ def decrement(self):
30
+ with self._lock:
31
+ self._val -= 1
32
+ return self._val
33
+
34
+ def get(self):
35
+ return self._val
36
+
37
+
38
+ class ProducerBatch(object):
39
+ def __init__(self, tp, records, buffer):
40
+ self.max_record_size = 0
41
+ now = time.time()
42
+ self.created = now
43
+ self.drained = None
44
+ self.attempts = 0
45
+ self.last_attempt = now
46
+ self.last_append = now
47
+ self.records = records
48
+ self.topic_partition = tp
49
+ self.produce_future = FutureProduceResult(tp)
50
+ self._retry = False
51
+ self._buffer = buffer # We only save it, we don't write to it
52
+
53
+ @property
54
+ def record_count(self):
55
+ return self.records.next_offset()
56
+
57
+ def try_append(self, timestamp_ms, key, value, headers):
58
+ metadata = self.records.append(timestamp_ms, key, value, headers)
59
+ if metadata is None:
60
+ return None
61
+
62
+ self.max_record_size = max(self.max_record_size, metadata.size)
63
+ self.last_append = time.time()
64
+ future = FutureRecordMetadata(self.produce_future, metadata.offset,
65
+ metadata.timestamp, metadata.crc,
66
+ len(key) if key is not None else -1,
67
+ len(value) if value is not None else -1,
68
+ sum(len(h_key.encode("utf-8")) + len(h_val) for h_key, h_val in headers) if headers else -1)
69
+ return future
70
+
71
+ def done(self, base_offset=None, timestamp_ms=None, exception=None, log_start_offset=None, global_error=None):
72
+ level = logging.DEBUG if exception is None else logging.WARNING
73
+ log.log(level, "Produced messages to topic-partition %s with base offset"
74
+ " %s log start offset %s and error %s.", self.topic_partition, base_offset,
75
+ log_start_offset, global_error) # trace
76
+ if self.produce_future.is_done:
77
+ log.warning('Batch is already closed -- ignoring batch.done()')
78
+ return
79
+ elif exception is None:
80
+ self.produce_future.success((base_offset, timestamp_ms, log_start_offset))
81
+ else:
82
+ self.produce_future.failure(exception)
83
+
84
+ def maybe_expire(self, request_timeout_ms, retry_backoff_ms, linger_ms, is_full):
85
+ """Expire batches if metadata is not available
86
+
87
+ A batch whose metadata is not available should be expired if one
88
+ of the following is true:
89
+
90
+ * the batch is not in retry AND request timeout has elapsed after
91
+ it is ready (full or linger.ms has reached).
92
+
93
+ * the batch is in retry AND request timeout has elapsed after the
94
+ backoff period ended.
95
+ """
96
+ now = time.time()
97
+ since_append = now - self.last_append
98
+ since_ready = now - (self.created + linger_ms / 1000.0)
99
+ since_backoff = now - (self.last_attempt + retry_backoff_ms / 1000.0)
100
+ timeout = request_timeout_ms / 1000.0
101
+
102
+ error = None
103
+ if not self.in_retry() and is_full and timeout < since_append:
104
+ error = "%d seconds have passed since last append" % (since_append,)
105
+ elif not self.in_retry() and timeout < since_ready:
106
+ error = "%d seconds have passed since batch creation plus linger time" % (since_ready,)
107
+ elif self.in_retry() and timeout < since_backoff:
108
+ error = "%d seconds have passed since last attempt plus backoff time" % (since_backoff,)
109
+
110
+ if error:
111
+ self.records.close()
112
+ self.done(-1, None, Errors.KafkaTimeoutError(
113
+ "Batch for %s containing %s record(s) expired: %s" % (
114
+ self.topic_partition, self.records.next_offset(), error)))
115
+ return True
116
+ return False
117
+
118
+ def in_retry(self):
119
+ return self._retry
120
+
121
+ def set_retry(self):
122
+ self._retry = True
123
+
124
+ def buffer(self):
125
+ return self._buffer
126
+
127
+ def __str__(self):
128
+ return 'ProducerBatch(topic_partition=%s, record_count=%d)' % (
129
+ self.topic_partition, self.records.next_offset())
130
+
131
+
132
+ class RecordAccumulator(object):
133
+ """
134
+ This class maintains a dequeue per TopicPartition that accumulates messages
135
+ into MessageSets to be sent to the server.
136
+
137
+ The accumulator attempts to bound memory use, and append calls will block
138
+ when that memory is exhausted.
139
+
140
+ Keyword Arguments:
141
+ batch_size (int): Requests sent to brokers will contain multiple
142
+ batches, one for each partition with data available to be sent.
143
+ A small batch size will make batching less common and may reduce
144
+ throughput (a batch size of zero will disable batching entirely).
145
+ Default: 16384
146
+ buffer_memory (int): The total bytes of memory the producer should use
147
+ to buffer records waiting to be sent to the server. If records are
148
+ sent faster than they can be delivered to the server the producer
149
+ will block up to max_block_ms, raising an exception on timeout.
150
+ In the current implementation, this setting is an approximation.
151
+ Default: 33554432 (32MB)
152
+ compression_attrs (int): The compression type for all data generated by
153
+ the producer. Valid values are gzip(1), snappy(2), lz4(3), or
154
+ none(0).
155
+ Compression is of full batches of data, so the efficacy of batching
156
+ will also impact the compression ratio (more batching means better
157
+ compression). Default: None.
158
+ linger_ms (int): An artificial delay time to add before declaring a
159
+ messageset (that isn't full) ready for sending. This allows
160
+ time for more records to arrive. Setting a non-zero linger_ms
161
+ will trade off some latency for potentially better throughput
162
+ due to more batching (and hence fewer, larger requests).
163
+ Default: 0
164
+ retry_backoff_ms (int): An artificial delay time to retry the
165
+ produce request upon receiving an error. This avoids exhausting
166
+ all retries in a short period of time. Default: 100
167
+ """
168
+ DEFAULT_CONFIG = {
169
+ 'buffer_memory': 33554432,
170
+ 'batch_size': 16384,
171
+ 'compression_attrs': 0,
172
+ 'linger_ms': 0,
173
+ 'retry_backoff_ms': 100,
174
+ 'message_version': 0,
175
+ 'metrics': None,
176
+ 'metric_group_prefix': 'producer-metrics',
177
+ }
178
+
179
+ def __init__(self, **configs):
180
+ self.config = copy.copy(self.DEFAULT_CONFIG)
181
+ for key in self.config:
182
+ if key in configs:
183
+ self.config[key] = configs.pop(key)
184
+
185
+ self._closed = False
186
+ self._flushes_in_progress = AtomicInteger()
187
+ self._appends_in_progress = AtomicInteger()
188
+ self._batches = collections.defaultdict(collections.deque) # TopicPartition: [ProducerBatch]
189
+ self._tp_locks = {None: threading.Lock()} # TopicPartition: Lock, plus a lock to add entries
190
+ self._free = SimpleBufferPool(self.config['buffer_memory'],
191
+ self.config['batch_size'],
192
+ metrics=self.config['metrics'],
193
+ metric_group_prefix=self.config['metric_group_prefix'])
194
+ self._incomplete = IncompleteProducerBatches()
195
+ # The following variables should only be accessed by the sender thread,
196
+ # so we don't need to protect them w/ locking.
197
+ self.muted = set()
198
+ self._drain_index = 0
199
+
200
+ def append(self, tp, timestamp_ms, key, value, headers, max_time_to_block_ms,
201
+ estimated_size=0):
202
+ """Add a record to the accumulator, return the append result.
203
+
204
+ The append result will contain the future metadata, and flag for
205
+ whether the appended batch is full or a new batch is created
206
+
207
+ Arguments:
208
+ tp (TopicPartition): The topic/partition to which this record is
209
+ being sent
210
+ timestamp_ms (int): The timestamp of the record (epoch ms)
211
+ key (bytes): The key for the record
212
+ value (bytes): The value for the record
213
+ headers (List[Tuple[str, bytes]]): The header fields for the record
214
+ max_time_to_block_ms (int): The maximum time in milliseconds to
215
+ block for buffer memory to be available
216
+
217
+ Returns:
218
+ tuple: (future, batch_is_full, new_batch_created)
219
+ """
220
+ assert isinstance(tp, TopicPartition), 'not TopicPartition'
221
+ assert not self._closed, 'RecordAccumulator is closed'
222
+ # We keep track of the number of appending thread to make sure we do
223
+ # not miss batches in abortIncompleteBatches().
224
+ self._appends_in_progress.increment()
225
+ try:
226
+ if tp not in self._tp_locks:
227
+ with self._tp_locks[None]:
228
+ if tp not in self._tp_locks:
229
+ self._tp_locks[tp] = threading.Lock()
230
+
231
+ with self._tp_locks[tp]:
232
+ # check if we have an in-progress batch
233
+ dq = self._batches[tp]
234
+ if dq:
235
+ last = dq[-1]
236
+ future = last.try_append(timestamp_ms, key, value, headers)
237
+ if future is not None:
238
+ batch_is_full = len(dq) > 1 or last.records.is_full()
239
+ return future, batch_is_full, False
240
+
241
+ size = max(self.config['batch_size'], estimated_size)
242
+ log.debug("Allocating a new %d byte message buffer for %s", size, tp) # trace
243
+ buf = self._free.allocate(size, max_time_to_block_ms)
244
+ with self._tp_locks[tp]:
245
+ # Need to check if producer is closed again after grabbing the
246
+ # dequeue lock.
247
+ assert not self._closed, 'RecordAccumulator is closed'
248
+
249
+ if dq:
250
+ last = dq[-1]
251
+ future = last.try_append(timestamp_ms, key, value, headers)
252
+ if future is not None:
253
+ # Somebody else found us a batch, return the one we
254
+ # waited for! Hopefully this doesn't happen often...
255
+ self._free.deallocate(buf)
256
+ batch_is_full = len(dq) > 1 or last.records.is_full()
257
+ return future, batch_is_full, False
258
+
259
+ records = MemoryRecordsBuilder(
260
+ self.config['message_version'],
261
+ self.config['compression_attrs'],
262
+ self.config['batch_size']
263
+ )
264
+
265
+ batch = ProducerBatch(tp, records, buf)
266
+ future = batch.try_append(timestamp_ms, key, value, headers)
267
+ if not future:
268
+ raise Exception()
269
+
270
+ dq.append(batch)
271
+ self._incomplete.add(batch)
272
+ batch_is_full = len(dq) > 1 or batch.records.is_full()
273
+ return future, batch_is_full, True
274
+ finally:
275
+ self._appends_in_progress.decrement()
276
+
277
+ def abort_expired_batches(self, request_timeout_ms, cluster):
278
+ """Abort the batches that have been sitting in RecordAccumulator for
279
+ more than the configured request_timeout due to metadata being
280
+ unavailable.
281
+
282
+ Arguments:
283
+ request_timeout_ms (int): milliseconds to timeout
284
+ cluster (ClusterMetadata): current metadata for kafka cluster
285
+
286
+ Returns:
287
+ list of ProducerBatch that were expired
288
+ """
289
+ expired_batches = []
290
+ to_remove = []
291
+ count = 0
292
+ for tp in list(self._batches.keys()):
293
+ assert tp in self._tp_locks, 'TopicPartition not in locks dict'
294
+
295
+ # We only check if the batch should be expired if the partition
296
+ # does not have a batch in flight. This is to avoid the later
297
+ # batches get expired when an earlier batch is still in progress.
298
+ # This protection only takes effect when user sets
299
+ # max.in.flight.request.per.connection=1. Otherwise the expiration
300
+ # order is not guranteed.
301
+ if tp in self.muted:
302
+ continue
303
+
304
+ with self._tp_locks[tp]:
305
+ # iterate over the batches and expire them if they have stayed
306
+ # in accumulator for more than request_timeout_ms
307
+ dq = self._batches[tp]
308
+ for batch in dq:
309
+ is_full = bool(bool(batch != dq[-1]) or batch.records.is_full())
310
+ # check if the batch is expired
311
+ if batch.maybe_expire(request_timeout_ms,
312
+ self.config['retry_backoff_ms'],
313
+ self.config['linger_ms'],
314
+ is_full):
315
+ expired_batches.append(batch)
316
+ to_remove.append(batch)
317
+ count += 1
318
+ self.deallocate(batch)
319
+ else:
320
+ # Stop at the first batch that has not expired.
321
+ break
322
+
323
+ # Python does not allow us to mutate the dq during iteration
324
+ # Assuming expired batches are infrequent, this is better than
325
+ # creating a new copy of the deque for iteration on every loop
326
+ if to_remove:
327
+ for batch in to_remove:
328
+ dq.remove(batch)
329
+ to_remove = []
330
+
331
+ if expired_batches:
332
+ log.warning("Expired %d batches in accumulator", count) # trace
333
+
334
+ return expired_batches
335
+
336
+ def reenqueue(self, batch):
337
+ """Re-enqueue the given record batch in the accumulator to retry."""
338
+ now = time.time()
339
+ batch.attempts += 1
340
+ batch.last_attempt = now
341
+ batch.last_append = now
342
+ batch.set_retry()
343
+ assert batch.topic_partition in self._tp_locks, 'TopicPartition not in locks dict'
344
+ assert batch.topic_partition in self._batches, 'TopicPartition not in batches'
345
+ dq = self._batches[batch.topic_partition]
346
+ with self._tp_locks[batch.topic_partition]:
347
+ dq.appendleft(batch)
348
+
349
+ def ready(self, cluster):
350
+ """
351
+ Get a list of nodes whose partitions are ready to be sent, and the
352
+ earliest time at which any non-sendable partition will be ready;
353
+ Also return the flag for whether there are any unknown leaders for the
354
+ accumulated partition batches.
355
+
356
+ A destination node is ready to send if:
357
+
358
+ * There is at least one partition that is not backing off its send
359
+ * and those partitions are not muted (to prevent reordering if
360
+ max_in_flight_requests_per_connection is set to 1)
361
+ * and any of the following are true:
362
+
363
+ * The record set is full
364
+ * The record set has sat in the accumulator for at least linger_ms
365
+ milliseconds
366
+ * The accumulator is out of memory and threads are blocking waiting
367
+ for data (in this case all partitions are immediately considered
368
+ ready).
369
+ * The accumulator has been closed
370
+
371
+ Arguments:
372
+ cluster (ClusterMetadata):
373
+
374
+ Returns:
375
+ tuple:
376
+ ready_nodes (set): node_ids that have ready batches
377
+ next_ready_check (float): secs until next ready after backoff
378
+ unknown_leaders_exist (bool): True if metadata refresh needed
379
+ """
380
+ ready_nodes = set()
381
+ next_ready_check = 9999999.99
382
+ unknown_leaders_exist = False
383
+ now = time.time()
384
+
385
+ exhausted = bool(self._free.queued() > 0)
386
+ # several threads are accessing self._batches -- to simplify
387
+ # concurrent access, we iterate over a snapshot of partitions
388
+ # and lock each partition separately as needed
389
+ partitions = list(self._batches.keys())
390
+ for tp in partitions:
391
+ leader = cluster.leader_for_partition(tp)
392
+ if leader is None or leader == -1:
393
+ unknown_leaders_exist = True
394
+ continue
395
+ elif leader in ready_nodes:
396
+ continue
397
+ elif tp in self.muted:
398
+ continue
399
+
400
+ with self._tp_locks[tp]:
401
+ dq = self._batches[tp]
402
+ if not dq:
403
+ continue
404
+ batch = dq[0]
405
+ retry_backoff = self.config['retry_backoff_ms'] / 1000.0
406
+ linger = self.config['linger_ms'] / 1000.0
407
+ backing_off = bool(batch.attempts > 0 and
408
+ batch.last_attempt + retry_backoff > now)
409
+ waited_time = now - batch.last_attempt
410
+ time_to_wait = retry_backoff if backing_off else linger
411
+ time_left = max(time_to_wait - waited_time, 0)
412
+ full = bool(len(dq) > 1 or batch.records.is_full())
413
+ expired = bool(waited_time >= time_to_wait)
414
+
415
+ sendable = (full or expired or exhausted or self._closed or
416
+ self._flush_in_progress())
417
+
418
+ if sendable and not backing_off:
419
+ ready_nodes.add(leader)
420
+ else:
421
+ # Note that this results in a conservative estimate since
422
+ # an un-sendable partition may have a leader that will
423
+ # later be found to have sendable data. However, this is
424
+ # good enough since we'll just wake up and then sleep again
425
+ # for the remaining time.
426
+ next_ready_check = min(time_left, next_ready_check)
427
+
428
+ return ready_nodes, next_ready_check, unknown_leaders_exist
429
+
430
+ def has_unsent(self):
431
+ """Return whether there is any unsent record in the accumulator."""
432
+ for tp in list(self._batches.keys()):
433
+ with self._tp_locks[tp]:
434
+ dq = self._batches[tp]
435
+ if len(dq):
436
+ return True
437
+ return False
438
+
439
+ def drain(self, cluster, nodes, max_size):
440
+ """
441
+ Drain all the data for the given nodes and collate them into a list of
442
+ batches that will fit within the specified size on a per-node basis.
443
+ This method attempts to avoid choosing the same topic-node repeatedly.
444
+
445
+ Arguments:
446
+ cluster (ClusterMetadata): The current cluster metadata
447
+ nodes (list): list of node_ids to drain
448
+ max_size (int): maximum number of bytes to drain
449
+
450
+ Returns:
451
+ dict: {node_id: list of ProducerBatch} with total size less than the
452
+ requested max_size.
453
+ """
454
+ if not nodes:
455
+ return {}
456
+
457
+ now = time.time()
458
+ batches = {}
459
+ for node_id in nodes:
460
+ size = 0
461
+ partitions = list(cluster.partitions_for_broker(node_id))
462
+ ready = []
463
+ # to make starvation less likely this loop doesn't start at 0
464
+ self._drain_index %= len(partitions)
465
+ start = self._drain_index
466
+ while True:
467
+ tp = partitions[self._drain_index]
468
+ if tp in self._batches and tp not in self.muted:
469
+ with self._tp_locks[tp]:
470
+ dq = self._batches[tp]
471
+ if dq:
472
+ first = dq[0]
473
+ backoff = (
474
+ bool(first.attempts > 0) and
475
+ bool(first.last_attempt +
476
+ self.config['retry_backoff_ms'] / 1000.0
477
+ > now)
478
+ )
479
+ # Only drain the batch if it is not during backoff
480
+ if not backoff:
481
+ if (size + first.records.size_in_bytes() > max_size
482
+ and len(ready) > 0):
483
+ # there is a rare case that a single batch
484
+ # size is larger than the request size due
485
+ # to compression; in this case we will
486
+ # still eventually send this batch in a
487
+ # single request
488
+ break
489
+ else:
490
+ batch = dq.popleft()
491
+ batch.records.close()
492
+ size += batch.records.size_in_bytes()
493
+ ready.append(batch)
494
+ batch.drained = now
495
+
496
+ self._drain_index += 1
497
+ self._drain_index %= len(partitions)
498
+ if start == self._drain_index:
499
+ break
500
+
501
+ batches[node_id] = ready
502
+ return batches
503
+
504
+ def deallocate(self, batch):
505
+ """Deallocate the record batch."""
506
+ self._incomplete.remove(batch)
507
+ self._free.deallocate(batch.buffer())
508
+
509
+ def _flush_in_progress(self):
510
+ """Are there any threads currently waiting on a flush?"""
511
+ return self._flushes_in_progress.get() > 0
512
+
513
+ def begin_flush(self):
514
+ """
515
+ Initiate the flushing of data from the accumulator...this makes all
516
+ requests immediately ready
517
+ """
518
+ self._flushes_in_progress.increment()
519
+
520
+ def await_flush_completion(self, timeout=None):
521
+ """
522
+ Mark all partitions as ready to send and block until the send is complete
523
+ """
524
+ try:
525
+ for batch in self._incomplete.all():
526
+ log.debug('Waiting on produce to %s',
527
+ batch.produce_future.topic_partition)
528
+ if not batch.produce_future.wait(timeout=timeout):
529
+ raise Errors.KafkaTimeoutError('Timeout waiting for future')
530
+ if not batch.produce_future.is_done:
531
+ raise Errors.UnknownError('Future not done')
532
+
533
+ if batch.produce_future.failed():
534
+ log.warning(batch.produce_future.exception)
535
+ finally:
536
+ self._flushes_in_progress.decrement()
537
+
538
+ def abort_incomplete_batches(self):
539
+ """
540
+ This function is only called when sender is closed forcefully. It will fail all the
541
+ incomplete batches and return.
542
+ """
543
+ # We need to keep aborting the incomplete batch until no thread is trying to append to
544
+ # 1. Avoid losing batches.
545
+ # 2. Free up memory in case appending threads are blocked on buffer full.
546
+ # This is a tight loop but should be able to get through very quickly.
547
+ while True:
548
+ self._abort_batches()
549
+ if not self._appends_in_progress.get():
550
+ break
551
+ # After this point, no thread will append any messages because they will see the close
552
+ # flag set. We need to do the last abort after no thread was appending in case the there was a new
553
+ # batch appended by the last appending thread.
554
+ self._abort_batches()
555
+ self._batches.clear()
556
+
557
+ def _abort_batches(self):
558
+ """Go through incomplete batches and abort them."""
559
+ error = Errors.IllegalStateError("Producer is closed forcefully.")
560
+ for batch in self._incomplete.all():
561
+ tp = batch.topic_partition
562
+ # Close the batch before aborting
563
+ with self._tp_locks[tp]:
564
+ batch.records.close()
565
+ batch.done(exception=error)
566
+ self.deallocate(batch)
567
+
568
+ def close(self):
569
+ """Close this accumulator and force all the record buffers to be drained."""
570
+ self._closed = True
571
+
572
+
573
+ class IncompleteProducerBatches(object):
574
+ """A threadsafe helper class to hold ProducerBatches that haven't been ack'd yet"""
575
+
576
+ def __init__(self):
577
+ self._incomplete = set()
578
+ self._lock = threading.Lock()
579
+
580
+ def add(self, batch):
581
+ with self._lock:
582
+ return self._incomplete.add(batch)
583
+
584
+ def remove(self, batch):
585
+ with self._lock:
586
+ return self._incomplete.remove(batch)
587
+
588
+ def all(self):
589
+ with self._lock:
590
+ return list(self._incomplete)
testbed/dpkp__kafka-python/kafka/producer/sender.py ADDED
@@ -0,0 +1,517 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import, division
2
+
3
+ import collections
4
+ import copy
5
+ import logging
6
+ import threading
7
+ import time
8
+
9
+ from kafka.vendor import six
10
+
11
+ from kafka import errors as Errors
12
+ from kafka.metrics.measurable import AnonMeasurable
13
+ from kafka.metrics.stats import Avg, Max, Rate
14
+ from kafka.protocol.produce import ProduceRequest
15
+ from kafka.structs import TopicPartition
16
+ from kafka.version import __version__
17
+
18
+ log = logging.getLogger(__name__)
19
+
20
+
21
+ class Sender(threading.Thread):
22
+ """
23
+ The background thread that handles the sending of produce requests to the
24
+ Kafka cluster. This thread makes metadata requests to renew its view of the
25
+ cluster and then sends produce requests to the appropriate nodes.
26
+ """
27
+ DEFAULT_CONFIG = {
28
+ 'max_request_size': 1048576,
29
+ 'acks': 1,
30
+ 'retries': 0,
31
+ 'request_timeout_ms': 30000,
32
+ 'guarantee_message_order': False,
33
+ 'client_id': 'kafka-python-' + __version__,
34
+ 'api_version': (0, 8, 0),
35
+ }
36
+
37
+ def __init__(self, client, metadata, accumulator, metrics, **configs):
38
+ super(Sender, self).__init__()
39
+ self.config = copy.copy(self.DEFAULT_CONFIG)
40
+ for key in self.config:
41
+ if key in configs:
42
+ self.config[key] = configs.pop(key)
43
+
44
+ self.name = self.config['client_id'] + '-network-thread'
45
+ self._client = client
46
+ self._accumulator = accumulator
47
+ self._metadata = client.cluster
48
+ self._running = True
49
+ self._force_close = False
50
+ self._topics_to_add = set()
51
+ self._sensors = SenderMetrics(metrics, self._client, self._metadata)
52
+
53
+ def run(self):
54
+ """The main run loop for the sender thread."""
55
+ log.debug("Starting Kafka producer I/O thread.")
56
+
57
+ # main loop, runs until close is called
58
+ while self._running:
59
+ try:
60
+ self.run_once()
61
+ except Exception:
62
+ log.exception("Uncaught error in kafka producer I/O thread")
63
+
64
+ log.debug("Beginning shutdown of Kafka producer I/O thread, sending"
65
+ " remaining records.")
66
+
67
+ # okay we stopped accepting requests but there may still be
68
+ # requests in the accumulator or waiting for acknowledgment,
69
+ # wait until these are completed.
70
+ while (not self._force_close
71
+ and (self._accumulator.has_unsent()
72
+ or self._client.in_flight_request_count() > 0)):
73
+ try:
74
+ self.run_once()
75
+ except Exception:
76
+ log.exception("Uncaught error in kafka producer I/O thread")
77
+
78
+ if self._force_close:
79
+ # We need to fail all the incomplete batches and wake up the
80
+ # threads waiting on the futures.
81
+ self._accumulator.abort_incomplete_batches()
82
+
83
+ try:
84
+ self._client.close()
85
+ except Exception:
86
+ log.exception("Failed to close network client")
87
+
88
+ log.debug("Shutdown of Kafka producer I/O thread has completed.")
89
+
90
+ def run_once(self):
91
+ """Run a single iteration of sending."""
92
+ while self._topics_to_add:
93
+ self._client.add_topic(self._topics_to_add.pop())
94
+
95
+ # get the list of partitions with data ready to send
96
+ result = self._accumulator.ready(self._metadata)
97
+ ready_nodes, next_ready_check_delay, unknown_leaders_exist = result
98
+
99
+ # if there are any partitions whose leaders are not known yet, force
100
+ # metadata update
101
+ if unknown_leaders_exist:
102
+ log.debug('Unknown leaders exist, requesting metadata update')
103
+ self._metadata.request_update()
104
+
105
+ # remove any nodes we aren't ready to send to
106
+ not_ready_timeout = float('inf')
107
+ for node in list(ready_nodes):
108
+ if not self._client.is_ready(node):
109
+ log.debug('Node %s not ready; delaying produce of accumulated batch', node)
110
+ self._client.maybe_connect(node, wakeup=False)
111
+ ready_nodes.remove(node)
112
+ not_ready_timeout = min(not_ready_timeout,
113
+ self._client.connection_delay(node))
114
+
115
+ # create produce requests
116
+ batches_by_node = self._accumulator.drain(
117
+ self._metadata, ready_nodes, self.config['max_request_size'])
118
+
119
+ if self.config['guarantee_message_order']:
120
+ # Mute all the partitions drained
121
+ for batch_list in six.itervalues(batches_by_node):
122
+ for batch in batch_list:
123
+ self._accumulator.muted.add(batch.topic_partition)
124
+
125
+ expired_batches = self._accumulator.abort_expired_batches(
126
+ self.config['request_timeout_ms'], self._metadata)
127
+ for expired_batch in expired_batches:
128
+ self._sensors.record_errors(expired_batch.topic_partition.topic, expired_batch.record_count)
129
+
130
+ self._sensors.update_produce_request_metrics(batches_by_node)
131
+ requests = self._create_produce_requests(batches_by_node)
132
+ # If we have any nodes that are ready to send + have sendable data,
133
+ # poll with 0 timeout so this can immediately loop and try sending more
134
+ # data. Otherwise, the timeout is determined by nodes that have
135
+ # partitions with data that isn't yet sendable (e.g. lingering, backing
136
+ # off). Note that this specifically does not include nodes with
137
+ # sendable data that aren't ready to send since they would cause busy
138
+ # looping.
139
+ poll_timeout_ms = min(next_ready_check_delay * 1000, not_ready_timeout)
140
+ if ready_nodes:
141
+ log.debug("Nodes with data ready to send: %s", ready_nodes) # trace
142
+ log.debug("Created %d produce requests: %s", len(requests), requests) # trace
143
+ poll_timeout_ms = 0
144
+
145
+ for node_id, request in six.iteritems(requests):
146
+ batches = batches_by_node[node_id]
147
+ log.debug('Sending Produce Request: %r', request)
148
+ (self._client.send(node_id, request, wakeup=False)
149
+ .add_callback(
150
+ self._handle_produce_response, node_id, time.time(), batches)
151
+ .add_errback(
152
+ self._failed_produce, batches, node_id))
153
+
154
+ # if some partitions are already ready to be sent, the select time
155
+ # would be 0; otherwise if some partition already has some data
156
+ # accumulated but not ready yet, the select time will be the time
157
+ # difference between now and its linger expiry time; otherwise the
158
+ # select time will be the time difference between now and the
159
+ # metadata expiry time
160
+ self._client.poll(timeout_ms=poll_timeout_ms)
161
+
162
+ def initiate_close(self):
163
+ """Start closing the sender (won't complete until all data is sent)."""
164
+ self._running = False
165
+ self._accumulator.close()
166
+ self.wakeup()
167
+
168
+ def force_close(self):
169
+ """Closes the sender without sending out any pending messages."""
170
+ self._force_close = True
171
+ self.initiate_close()
172
+
173
+ def add_topic(self, topic):
174
+ # This is generally called from a separate thread
175
+ # so this needs to be a thread-safe operation
176
+ # we assume that checking set membership across threads
177
+ # is ok where self._client._topics should never
178
+ # remove topics for a producer instance, only add them.
179
+ if topic not in self._client._topics:
180
+ self._topics_to_add.add(topic)
181
+ self.wakeup()
182
+
183
+ def _failed_produce(self, batches, node_id, error):
184
+ log.debug("Error sending produce request to node %d: %s", node_id, error) # trace
185
+ for batch in batches:
186
+ self._complete_batch(batch, error, -1, None)
187
+
188
+ def _handle_produce_response(self, node_id, send_time, batches, response):
189
+ """Handle a produce response."""
190
+ # if we have a response, parse it
191
+ log.debug('Parsing produce response: %r', response)
192
+ if response:
193
+ batches_by_partition = dict([(batch.topic_partition, batch)
194
+ for batch in batches])
195
+
196
+ for topic, partitions in response.topics:
197
+ for partition_info in partitions:
198
+ global_error = None
199
+ log_start_offset = None
200
+ if response.API_VERSION < 2:
201
+ partition, error_code, offset = partition_info
202
+ ts = None
203
+ elif 2 <= response.API_VERSION <= 4:
204
+ partition, error_code, offset, ts = partition_info
205
+ elif 5 <= response.API_VERSION <= 7:
206
+ partition, error_code, offset, ts, log_start_offset = partition_info
207
+ else:
208
+ # the ignored parameter is record_error of type list[(batch_index: int, error_message: str)]
209
+ partition, error_code, offset, ts, log_start_offset, _, global_error = partition_info
210
+ tp = TopicPartition(topic, partition)
211
+ error = Errors.for_code(error_code)
212
+ batch = batches_by_partition[tp]
213
+ self._complete_batch(batch, error, offset, ts, log_start_offset, global_error)
214
+
215
+ if response.API_VERSION > 0:
216
+ self._sensors.record_throttle_time(response.throttle_time_ms, node=node_id)
217
+
218
+ else:
219
+ # this is the acks = 0 case, just complete all requests
220
+ for batch in batches:
221
+ self._complete_batch(batch, None, -1, None)
222
+
223
+ def _complete_batch(self, batch, error, base_offset, timestamp_ms=None, log_start_offset=None, global_error=None):
224
+ """Complete or retry the given batch of records.
225
+
226
+ Arguments:
227
+ batch (RecordBatch): The record batch
228
+ error (Exception): The error (or None if none)
229
+ base_offset (int): The base offset assigned to the records if successful
230
+ timestamp_ms (int, optional): The timestamp returned by the broker for this batch
231
+ log_start_offset (int): The start offset of the log at the time this produce response was created
232
+ global_error (str): The summarising error message
233
+ """
234
+ # Standardize no-error to None
235
+ if error is Errors.NoError:
236
+ error = None
237
+
238
+ if error is not None and self._can_retry(batch, error):
239
+ # retry
240
+ log.warning("Got error produce response on topic-partition %s,"
241
+ " retrying (%d attempts left). Error: %s",
242
+ batch.topic_partition,
243
+ self.config['retries'] - batch.attempts - 1,
244
+ global_error or error)
245
+ self._accumulator.reenqueue(batch)
246
+ self._sensors.record_retries(batch.topic_partition.topic, batch.record_count)
247
+ else:
248
+ if error is Errors.TopicAuthorizationFailedError:
249
+ error = error(batch.topic_partition.topic)
250
+
251
+ # tell the user the result of their request
252
+ batch.done(base_offset, timestamp_ms, error, log_start_offset, global_error)
253
+ self._accumulator.deallocate(batch)
254
+ if error is not None:
255
+ self._sensors.record_errors(batch.topic_partition.topic, batch.record_count)
256
+
257
+ if getattr(error, 'invalid_metadata', False):
258
+ self._metadata.request_update()
259
+
260
+ # Unmute the completed partition.
261
+ if self.config['guarantee_message_order']:
262
+ self._accumulator.muted.remove(batch.topic_partition)
263
+
264
+ def _can_retry(self, batch, error):
265
+ """
266
+ We can retry a send if the error is transient and the number of
267
+ attempts taken is fewer than the maximum allowed
268
+ """
269
+ return (batch.attempts < self.config['retries']
270
+ and getattr(error, 'retriable', False))
271
+
272
+ def _create_produce_requests(self, collated):
273
+ """
274
+ Transfer the record batches into a list of produce requests on a
275
+ per-node basis.
276
+
277
+ Arguments:
278
+ collated: {node_id: [RecordBatch]}
279
+
280
+ Returns:
281
+ dict: {node_id: ProduceRequest} (version depends on api_version)
282
+ """
283
+ requests = {}
284
+ for node_id, batches in six.iteritems(collated):
285
+ requests[node_id] = self._produce_request(
286
+ node_id, self.config['acks'],
287
+ self.config['request_timeout_ms'], batches)
288
+ return requests
289
+
290
+ def _produce_request(self, node_id, acks, timeout, batches):
291
+ """Create a produce request from the given record batches.
292
+
293
+ Returns:
294
+ ProduceRequest (version depends on api_version)
295
+ """
296
+ produce_records_by_partition = collections.defaultdict(dict)
297
+ for batch in batches:
298
+ topic = batch.topic_partition.topic
299
+ partition = batch.topic_partition.partition
300
+
301
+ buf = batch.records.buffer()
302
+ produce_records_by_partition[topic][partition] = buf
303
+
304
+ kwargs = {}
305
+ if self.config['api_version'] >= (2, 1):
306
+ version = 7
307
+ elif self.config['api_version'] >= (2, 0):
308
+ version = 6
309
+ elif self.config['api_version'] >= (1, 1):
310
+ version = 5
311
+ elif self.config['api_version'] >= (1, 0):
312
+ version = 4
313
+ elif self.config['api_version'] >= (0, 11):
314
+ version = 3
315
+ kwargs = dict(transactional_id=None)
316
+ elif self.config['api_version'] >= (0, 10):
317
+ version = 2
318
+ elif self.config['api_version'] == (0, 9):
319
+ version = 1
320
+ else:
321
+ version = 0
322
+ return ProduceRequest[version](
323
+ required_acks=acks,
324
+ timeout=timeout,
325
+ topics=[(topic, list(partition_info.items()))
326
+ for topic, partition_info
327
+ in six.iteritems(produce_records_by_partition)],
328
+ **kwargs
329
+ )
330
+
331
+ def wakeup(self):
332
+ """Wake up the selector associated with this send thread."""
333
+ self._client.wakeup()
334
+
335
+ def bootstrap_connected(self):
336
+ return self._client.bootstrap_connected()
337
+
338
+
339
+ class SenderMetrics(object):
340
+
341
+ def __init__(self, metrics, client, metadata):
342
+ self.metrics = metrics
343
+ self._client = client
344
+ self._metadata = metadata
345
+
346
+ sensor_name = 'batch-size'
347
+ self.batch_size_sensor = self.metrics.sensor(sensor_name)
348
+ self.add_metric('batch-size-avg', Avg(),
349
+ sensor_name=sensor_name,
350
+ description='The average number of bytes sent per partition per-request.')
351
+ self.add_metric('batch-size-max', Max(),
352
+ sensor_name=sensor_name,
353
+ description='The max number of bytes sent per partition per-request.')
354
+
355
+ sensor_name = 'compression-rate'
356
+ self.compression_rate_sensor = self.metrics.sensor(sensor_name)
357
+ self.add_metric('compression-rate-avg', Avg(),
358
+ sensor_name=sensor_name,
359
+ description='The average compression rate of record batches.')
360
+
361
+ sensor_name = 'queue-time'
362
+ self.queue_time_sensor = self.metrics.sensor(sensor_name)
363
+ self.add_metric('record-queue-time-avg', Avg(),
364
+ sensor_name=sensor_name,
365
+ description='The average time in ms record batches spent in the record accumulator.')
366
+ self.add_metric('record-queue-time-max', Max(),
367
+ sensor_name=sensor_name,
368
+ description='The maximum time in ms record batches spent in the record accumulator.')
369
+
370
+ sensor_name = 'produce-throttle-time'
371
+ self.produce_throttle_time_sensor = self.metrics.sensor(sensor_name)
372
+ self.add_metric('produce-throttle-time-avg', Avg(),
373
+ sensor_name=sensor_name,
374
+ description='The average throttle time in ms')
375
+ self.add_metric('produce-throttle-time-max', Max(),
376
+ sensor_name=sensor_name,
377
+ description='The maximum throttle time in ms')
378
+
379
+ sensor_name = 'records-per-request'
380
+ self.records_per_request_sensor = self.metrics.sensor(sensor_name)
381
+ self.add_metric('record-send-rate', Rate(),
382
+ sensor_name=sensor_name,
383
+ description='The average number of records sent per second.')
384
+ self.add_metric('records-per-request-avg', Avg(),
385
+ sensor_name=sensor_name,
386
+ description='The average number of records per request.')
387
+
388
+ sensor_name = 'bytes'
389
+ self.byte_rate_sensor = self.metrics.sensor(sensor_name)
390
+ self.add_metric('byte-rate', Rate(),
391
+ sensor_name=sensor_name,
392
+ description='The average number of bytes sent per second.')
393
+
394
+ sensor_name = 'record-retries'
395
+ self.retry_sensor = self.metrics.sensor(sensor_name)
396
+ self.add_metric('record-retry-rate', Rate(),
397
+ sensor_name=sensor_name,
398
+ description='The average per-second number of retried record sends')
399
+
400
+ sensor_name = 'errors'
401
+ self.error_sensor = self.metrics.sensor(sensor_name)
402
+ self.add_metric('record-error-rate', Rate(),
403
+ sensor_name=sensor_name,
404
+ description='The average per-second number of record sends that resulted in errors')
405
+
406
+ sensor_name = 'record-size-max'
407
+ self.max_record_size_sensor = self.metrics.sensor(sensor_name)
408
+ self.add_metric('record-size-max', Max(),
409
+ sensor_name=sensor_name,
410
+ description='The maximum record size across all batches')
411
+ self.add_metric('record-size-avg', Avg(),
412
+ sensor_name=sensor_name,
413
+ description='The average maximum record size per batch')
414
+
415
+ self.add_metric('requests-in-flight',
416
+ AnonMeasurable(lambda *_: self._client.in_flight_request_count()),
417
+ description='The current number of in-flight requests awaiting a response.')
418
+
419
+ self.add_metric('metadata-age',
420
+ AnonMeasurable(lambda _, now: (now - self._metadata._last_successful_refresh_ms) / 1000),
421
+ description='The age in seconds of the current producer metadata being used.')
422
+
423
+ def add_metric(self, metric_name, measurable, group_name='producer-metrics',
424
+ description=None, tags=None,
425
+ sensor_name=None):
426
+ m = self.metrics
427
+ metric = m.metric_name(metric_name, group_name, description, tags)
428
+ if sensor_name:
429
+ sensor = m.sensor(sensor_name)
430
+ sensor.add(metric, measurable)
431
+ else:
432
+ m.add_metric(metric, measurable)
433
+
434
+ def maybe_register_topic_metrics(self, topic):
435
+
436
+ def sensor_name(name):
437
+ return 'topic.{0}.{1}'.format(topic, name)
438
+
439
+ # if one sensor of the metrics has been registered for the topic,
440
+ # then all other sensors should have been registered; and vice versa
441
+ if not self.metrics.get_sensor(sensor_name('records-per-batch')):
442
+
443
+ self.add_metric('record-send-rate', Rate(),
444
+ sensor_name=sensor_name('records-per-batch'),
445
+ group_name='producer-topic-metrics.' + topic,
446
+ description= 'Records sent per second for topic ' + topic)
447
+
448
+ self.add_metric('byte-rate', Rate(),
449
+ sensor_name=sensor_name('bytes'),
450
+ group_name='producer-topic-metrics.' + topic,
451
+ description='Bytes per second for topic ' + topic)
452
+
453
+ self.add_metric('compression-rate', Avg(),
454
+ sensor_name=sensor_name('compression-rate'),
455
+ group_name='producer-topic-metrics.' + topic,
456
+ description='Average Compression ratio for topic ' + topic)
457
+
458
+ self.add_metric('record-retry-rate', Rate(),
459
+ sensor_name=sensor_name('record-retries'),
460
+ group_name='producer-topic-metrics.' + topic,
461
+ description='Record retries per second for topic ' + topic)
462
+
463
+ self.add_metric('record-error-rate', Rate(),
464
+ sensor_name=sensor_name('record-errors'),
465
+ group_name='producer-topic-metrics.' + topic,
466
+ description='Record errors per second for topic ' + topic)
467
+
468
+ def update_produce_request_metrics(self, batches_map):
469
+ for node_batch in batches_map.values():
470
+ records = 0
471
+ total_bytes = 0
472
+ for batch in node_batch:
473
+ # register all per-topic metrics at once
474
+ topic = batch.topic_partition.topic
475
+ self.maybe_register_topic_metrics(topic)
476
+
477
+ # per-topic record send rate
478
+ topic_records_count = self.metrics.get_sensor(
479
+ 'topic.' + topic + '.records-per-batch')
480
+ topic_records_count.record(batch.record_count)
481
+
482
+ # per-topic bytes send rate
483
+ topic_byte_rate = self.metrics.get_sensor(
484
+ 'topic.' + topic + '.bytes')
485
+ topic_byte_rate.record(batch.records.size_in_bytes())
486
+
487
+ # per-topic compression rate
488
+ topic_compression_rate = self.metrics.get_sensor(
489
+ 'topic.' + topic + '.compression-rate')
490
+ topic_compression_rate.record(batch.records.compression_rate())
491
+
492
+ # global metrics
493
+ self.batch_size_sensor.record(batch.records.size_in_bytes())
494
+ if batch.drained:
495
+ self.queue_time_sensor.record(batch.drained - batch.created)
496
+ self.compression_rate_sensor.record(batch.records.compression_rate())
497
+ self.max_record_size_sensor.record(batch.max_record_size)
498
+ records += batch.record_count
499
+ total_bytes += batch.records.size_in_bytes()
500
+
501
+ self.records_per_request_sensor.record(records)
502
+ self.byte_rate_sensor.record(total_bytes)
503
+
504
+ def record_retries(self, topic, count):
505
+ self.retry_sensor.record(count)
506
+ sensor = self.metrics.get_sensor('topic.' + topic + '.record-retries')
507
+ if sensor:
508
+ sensor.record(count)
509
+
510
+ def record_errors(self, topic, count):
511
+ self.error_sensor.record(count)
512
+ sensor = self.metrics.get_sensor('topic.' + topic + '.record-errors')
513
+ if sensor:
514
+ sensor.record(count)
515
+
516
+ def record_throttle_time(self, throttle_time_ms, node=None):
517
+ self.produce_throttle_time_sensor.record(throttle_time_ms)
testbed/dpkp__kafka-python/kafka/protocol/__init__.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+
3
+
4
+ API_KEYS = {
5
+ 0: 'Produce',
6
+ 1: 'Fetch',
7
+ 2: 'ListOffsets',
8
+ 3: 'Metadata',
9
+ 4: 'LeaderAndIsr',
10
+ 5: 'StopReplica',
11
+ 6: 'UpdateMetadata',
12
+ 7: 'ControlledShutdown',
13
+ 8: 'OffsetCommit',
14
+ 9: 'OffsetFetch',
15
+ 10: 'FindCoordinator',
16
+ 11: 'JoinGroup',
17
+ 12: 'Heartbeat',
18
+ 13: 'LeaveGroup',
19
+ 14: 'SyncGroup',
20
+ 15: 'DescribeGroups',
21
+ 16: 'ListGroups',
22
+ 17: 'SaslHandshake',
23
+ 18: 'ApiVersions',
24
+ 19: 'CreateTopics',
25
+ 20: 'DeleteTopics',
26
+ 21: 'DeleteRecords',
27
+ 22: 'InitProducerId',
28
+ 23: 'OffsetForLeaderEpoch',
29
+ 24: 'AddPartitionsToTxn',
30
+ 25: 'AddOffsetsToTxn',
31
+ 26: 'EndTxn',
32
+ 27: 'WriteTxnMarkers',
33
+ 28: 'TxnOffsetCommit',
34
+ 29: 'DescribeAcls',
35
+ 30: 'CreateAcls',
36
+ 31: 'DeleteAcls',
37
+ 32: 'DescribeConfigs',
38
+ 33: 'AlterConfigs',
39
+ 36: 'SaslAuthenticate',
40
+ 37: 'CreatePartitions',
41
+ 38: 'CreateDelegationToken',
42
+ 39: 'RenewDelegationToken',
43
+ 40: 'ExpireDelegationToken',
44
+ 41: 'DescribeDelegationToken',
45
+ 42: 'DeleteGroups',
46
+ 48: 'DescribeClientQuotas',
47
+ }
testbed/dpkp__kafka-python/kafka/protocol/abstract.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+
3
+ import abc
4
+
5
+
6
+ class AbstractType(object):
7
+ __metaclass__ = abc.ABCMeta
8
+
9
+ @abc.abstractmethod
10
+ def encode(cls, value): # pylint: disable=no-self-argument
11
+ pass
12
+
13
+ @abc.abstractmethod
14
+ def decode(cls, data): # pylint: disable=no-self-argument
15
+ pass
16
+
17
+ @classmethod
18
+ def repr(cls, value):
19
+ return repr(value)
testbed/dpkp__kafka-python/kafka/protocol/admin.py ADDED
@@ -0,0 +1,965 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+
3
+ from kafka.protocol.api import Request, Response
4
+ from kafka.protocol.types import Array, Boolean, Bytes, Int8, Int16, Int32, Int64, Schema, String, Float64
5
+
6
+
7
+ class ApiVersionResponse_v0(Response):
8
+ API_KEY = 18
9
+ API_VERSION = 0
10
+ SCHEMA = Schema(
11
+ ('error_code', Int16),
12
+ ('api_versions', Array(
13
+ ('api_key', Int16),
14
+ ('min_version', Int16),
15
+ ('max_version', Int16)))
16
+ )
17
+
18
+
19
+ class ApiVersionResponse_v1(Response):
20
+ API_KEY = 18
21
+ API_VERSION = 1
22
+ SCHEMA = Schema(
23
+ ('error_code', Int16),
24
+ ('api_versions', Array(
25
+ ('api_key', Int16),
26
+ ('min_version', Int16),
27
+ ('max_version', Int16))),
28
+ ('throttle_time_ms', Int32)
29
+ )
30
+
31
+
32
+ class ApiVersionResponse_v2(Response):
33
+ API_KEY = 18
34
+ API_VERSION = 2
35
+ SCHEMA = ApiVersionResponse_v1.SCHEMA
36
+
37
+
38
+ class ApiVersionRequest_v0(Request):
39
+ API_KEY = 18
40
+ API_VERSION = 0
41
+ RESPONSE_TYPE = ApiVersionResponse_v0
42
+ SCHEMA = Schema()
43
+
44
+
45
+ class ApiVersionRequest_v1(Request):
46
+ API_KEY = 18
47
+ API_VERSION = 1
48
+ RESPONSE_TYPE = ApiVersionResponse_v1
49
+ SCHEMA = ApiVersionRequest_v0.SCHEMA
50
+
51
+
52
+ class ApiVersionRequest_v2(Request):
53
+ API_KEY = 18
54
+ API_VERSION = 2
55
+ RESPONSE_TYPE = ApiVersionResponse_v1
56
+ SCHEMA = ApiVersionRequest_v0.SCHEMA
57
+
58
+
59
+ ApiVersionRequest = [
60
+ ApiVersionRequest_v0, ApiVersionRequest_v1, ApiVersionRequest_v2,
61
+ ]
62
+ ApiVersionResponse = [
63
+ ApiVersionResponse_v0, ApiVersionResponse_v1, ApiVersionResponse_v2,
64
+ ]
65
+
66
+
67
+ class CreateTopicsResponse_v0(Response):
68
+ API_KEY = 19
69
+ API_VERSION = 0
70
+ SCHEMA = Schema(
71
+ ('topic_errors', Array(
72
+ ('topic', String('utf-8')),
73
+ ('error_code', Int16)))
74
+ )
75
+
76
+
77
+ class CreateTopicsResponse_v1(Response):
78
+ API_KEY = 19
79
+ API_VERSION = 1
80
+ SCHEMA = Schema(
81
+ ('topic_errors', Array(
82
+ ('topic', String('utf-8')),
83
+ ('error_code', Int16),
84
+ ('error_message', String('utf-8'))))
85
+ )
86
+
87
+
88
+ class CreateTopicsResponse_v2(Response):
89
+ API_KEY = 19
90
+ API_VERSION = 2
91
+ SCHEMA = Schema(
92
+ ('throttle_time_ms', Int32),
93
+ ('topic_errors', Array(
94
+ ('topic', String('utf-8')),
95
+ ('error_code', Int16),
96
+ ('error_message', String('utf-8'))))
97
+ )
98
+
99
+ class CreateTopicsResponse_v3(Response):
100
+ API_KEY = 19
101
+ API_VERSION = 3
102
+ SCHEMA = CreateTopicsResponse_v2.SCHEMA
103
+
104
+
105
+ class CreateTopicsRequest_v0(Request):
106
+ API_KEY = 19
107
+ API_VERSION = 0
108
+ RESPONSE_TYPE = CreateTopicsResponse_v0
109
+ SCHEMA = Schema(
110
+ ('create_topic_requests', Array(
111
+ ('topic', String('utf-8')),
112
+ ('num_partitions', Int32),
113
+ ('replication_factor', Int16),
114
+ ('replica_assignment', Array(
115
+ ('partition_id', Int32),
116
+ ('replicas', Array(Int32)))),
117
+ ('configs', Array(
118
+ ('config_key', String('utf-8')),
119
+ ('config_value', String('utf-8')))))),
120
+ ('timeout', Int32)
121
+ )
122
+
123
+
124
+ class CreateTopicsRequest_v1(Request):
125
+ API_KEY = 19
126
+ API_VERSION = 1
127
+ RESPONSE_TYPE = CreateTopicsResponse_v1
128
+ SCHEMA = Schema(
129
+ ('create_topic_requests', Array(
130
+ ('topic', String('utf-8')),
131
+ ('num_partitions', Int32),
132
+ ('replication_factor', Int16),
133
+ ('replica_assignment', Array(
134
+ ('partition_id', Int32),
135
+ ('replicas', Array(Int32)))),
136
+ ('configs', Array(
137
+ ('config_key', String('utf-8')),
138
+ ('config_value', String('utf-8')))))),
139
+ ('timeout', Int32),
140
+ ('validate_only', Boolean)
141
+ )
142
+
143
+
144
+ class CreateTopicsRequest_v2(Request):
145
+ API_KEY = 19
146
+ API_VERSION = 2
147
+ RESPONSE_TYPE = CreateTopicsResponse_v2
148
+ SCHEMA = CreateTopicsRequest_v1.SCHEMA
149
+
150
+
151
+ class CreateTopicsRequest_v3(Request):
152
+ API_KEY = 19
153
+ API_VERSION = 3
154
+ RESPONSE_TYPE = CreateTopicsResponse_v3
155
+ SCHEMA = CreateTopicsRequest_v1.SCHEMA
156
+
157
+
158
+ CreateTopicsRequest = [
159
+ CreateTopicsRequest_v0, CreateTopicsRequest_v1,
160
+ CreateTopicsRequest_v2, CreateTopicsRequest_v3,
161
+ ]
162
+ CreateTopicsResponse = [
163
+ CreateTopicsResponse_v0, CreateTopicsResponse_v1,
164
+ CreateTopicsResponse_v2, CreateTopicsResponse_v3,
165
+ ]
166
+
167
+
168
+ class DeleteTopicsResponse_v0(Response):
169
+ API_KEY = 20
170
+ API_VERSION = 0
171
+ SCHEMA = Schema(
172
+ ('topic_error_codes', Array(
173
+ ('topic', String('utf-8')),
174
+ ('error_code', Int16)))
175
+ )
176
+
177
+
178
+ class DeleteTopicsResponse_v1(Response):
179
+ API_KEY = 20
180
+ API_VERSION = 1
181
+ SCHEMA = Schema(
182
+ ('throttle_time_ms', Int32),
183
+ ('topic_error_codes', Array(
184
+ ('topic', String('utf-8')),
185
+ ('error_code', Int16)))
186
+ )
187
+
188
+
189
+ class DeleteTopicsResponse_v2(Response):
190
+ API_KEY = 20
191
+ API_VERSION = 2
192
+ SCHEMA = DeleteTopicsResponse_v1.SCHEMA
193
+
194
+
195
+ class DeleteTopicsResponse_v3(Response):
196
+ API_KEY = 20
197
+ API_VERSION = 3
198
+ SCHEMA = DeleteTopicsResponse_v1.SCHEMA
199
+
200
+
201
+ class DeleteTopicsRequest_v0(Request):
202
+ API_KEY = 20
203
+ API_VERSION = 0
204
+ RESPONSE_TYPE = DeleteTopicsResponse_v0
205
+ SCHEMA = Schema(
206
+ ('topics', Array(String('utf-8'))),
207
+ ('timeout', Int32)
208
+ )
209
+
210
+
211
+ class DeleteTopicsRequest_v1(Request):
212
+ API_KEY = 20
213
+ API_VERSION = 1
214
+ RESPONSE_TYPE = DeleteTopicsResponse_v1
215
+ SCHEMA = DeleteTopicsRequest_v0.SCHEMA
216
+
217
+
218
+ class DeleteTopicsRequest_v2(Request):
219
+ API_KEY = 20
220
+ API_VERSION = 2
221
+ RESPONSE_TYPE = DeleteTopicsResponse_v2
222
+ SCHEMA = DeleteTopicsRequest_v0.SCHEMA
223
+
224
+
225
+ class DeleteTopicsRequest_v3(Request):
226
+ API_KEY = 20
227
+ API_VERSION = 3
228
+ RESPONSE_TYPE = DeleteTopicsResponse_v3
229
+ SCHEMA = DeleteTopicsRequest_v0.SCHEMA
230
+
231
+
232
+ DeleteTopicsRequest = [
233
+ DeleteTopicsRequest_v0, DeleteTopicsRequest_v1,
234
+ DeleteTopicsRequest_v2, DeleteTopicsRequest_v3,
235
+ ]
236
+ DeleteTopicsResponse = [
237
+ DeleteTopicsResponse_v0, DeleteTopicsResponse_v1,
238
+ DeleteTopicsResponse_v2, DeleteTopicsResponse_v3,
239
+ ]
240
+
241
+
242
+ class ListGroupsResponse_v0(Response):
243
+ API_KEY = 16
244
+ API_VERSION = 0
245
+ SCHEMA = Schema(
246
+ ('error_code', Int16),
247
+ ('groups', Array(
248
+ ('group', String('utf-8')),
249
+ ('protocol_type', String('utf-8'))))
250
+ )
251
+
252
+
253
+ class ListGroupsResponse_v1(Response):
254
+ API_KEY = 16
255
+ API_VERSION = 1
256
+ SCHEMA = Schema(
257
+ ('throttle_time_ms', Int32),
258
+ ('error_code', Int16),
259
+ ('groups', Array(
260
+ ('group', String('utf-8')),
261
+ ('protocol_type', String('utf-8'))))
262
+ )
263
+
264
+ class ListGroupsResponse_v2(Response):
265
+ API_KEY = 16
266
+ API_VERSION = 2
267
+ SCHEMA = ListGroupsResponse_v1.SCHEMA
268
+
269
+
270
+ class ListGroupsRequest_v0(Request):
271
+ API_KEY = 16
272
+ API_VERSION = 0
273
+ RESPONSE_TYPE = ListGroupsResponse_v0
274
+ SCHEMA = Schema()
275
+
276
+
277
+ class ListGroupsRequest_v1(Request):
278
+ API_KEY = 16
279
+ API_VERSION = 1
280
+ RESPONSE_TYPE = ListGroupsResponse_v1
281
+ SCHEMA = ListGroupsRequest_v0.SCHEMA
282
+
283
+ class ListGroupsRequest_v2(Request):
284
+ API_KEY = 16
285
+ API_VERSION = 1
286
+ RESPONSE_TYPE = ListGroupsResponse_v2
287
+ SCHEMA = ListGroupsRequest_v0.SCHEMA
288
+
289
+
290
+ ListGroupsRequest = [
291
+ ListGroupsRequest_v0, ListGroupsRequest_v1,
292
+ ListGroupsRequest_v2,
293
+ ]
294
+ ListGroupsResponse = [
295
+ ListGroupsResponse_v0, ListGroupsResponse_v1,
296
+ ListGroupsResponse_v2,
297
+ ]
298
+
299
+
300
+ class DescribeGroupsResponse_v0(Response):
301
+ API_KEY = 15
302
+ API_VERSION = 0
303
+ SCHEMA = Schema(
304
+ ('groups', Array(
305
+ ('error_code', Int16),
306
+ ('group', String('utf-8')),
307
+ ('state', String('utf-8')),
308
+ ('protocol_type', String('utf-8')),
309
+ ('protocol', String('utf-8')),
310
+ ('members', Array(
311
+ ('member_id', String('utf-8')),
312
+ ('client_id', String('utf-8')),
313
+ ('client_host', String('utf-8')),
314
+ ('member_metadata', Bytes),
315
+ ('member_assignment', Bytes)))))
316
+ )
317
+
318
+
319
+ class DescribeGroupsResponse_v1(Response):
320
+ API_KEY = 15
321
+ API_VERSION = 1
322
+ SCHEMA = Schema(
323
+ ('throttle_time_ms', Int32),
324
+ ('groups', Array(
325
+ ('error_code', Int16),
326
+ ('group', String('utf-8')),
327
+ ('state', String('utf-8')),
328
+ ('protocol_type', String('utf-8')),
329
+ ('protocol', String('utf-8')),
330
+ ('members', Array(
331
+ ('member_id', String('utf-8')),
332
+ ('client_id', String('utf-8')),
333
+ ('client_host', String('utf-8')),
334
+ ('member_metadata', Bytes),
335
+ ('member_assignment', Bytes)))))
336
+ )
337
+
338
+
339
+ class DescribeGroupsResponse_v2(Response):
340
+ API_KEY = 15
341
+ API_VERSION = 2
342
+ SCHEMA = DescribeGroupsResponse_v1.SCHEMA
343
+
344
+
345
+ class DescribeGroupsResponse_v3(Response):
346
+ API_KEY = 15
347
+ API_VERSION = 3
348
+ SCHEMA = Schema(
349
+ ('throttle_time_ms', Int32),
350
+ ('groups', Array(
351
+ ('error_code', Int16),
352
+ ('group', String('utf-8')),
353
+ ('state', String('utf-8')),
354
+ ('protocol_type', String('utf-8')),
355
+ ('protocol', String('utf-8')),
356
+ ('members', Array(
357
+ ('member_id', String('utf-8')),
358
+ ('client_id', String('utf-8')),
359
+ ('client_host', String('utf-8')),
360
+ ('member_metadata', Bytes),
361
+ ('member_assignment', Bytes)))),
362
+ ('authorized_operations', Int32))
363
+ )
364
+
365
+
366
+ class DescribeGroupsRequest_v0(Request):
367
+ API_KEY = 15
368
+ API_VERSION = 0
369
+ RESPONSE_TYPE = DescribeGroupsResponse_v0
370
+ SCHEMA = Schema(
371
+ ('groups', Array(String('utf-8')))
372
+ )
373
+
374
+
375
+ class DescribeGroupsRequest_v1(Request):
376
+ API_KEY = 15
377
+ API_VERSION = 1
378
+ RESPONSE_TYPE = DescribeGroupsResponse_v1
379
+ SCHEMA = DescribeGroupsRequest_v0.SCHEMA
380
+
381
+
382
+ class DescribeGroupsRequest_v2(Request):
383
+ API_KEY = 15
384
+ API_VERSION = 2
385
+ RESPONSE_TYPE = DescribeGroupsResponse_v2
386
+ SCHEMA = DescribeGroupsRequest_v0.SCHEMA
387
+
388
+
389
+ class DescribeGroupsRequest_v3(Request):
390
+ API_KEY = 15
391
+ API_VERSION = 3
392
+ RESPONSE_TYPE = DescribeGroupsResponse_v2
393
+ SCHEMA = Schema(
394
+ ('groups', Array(String('utf-8'))),
395
+ ('include_authorized_operations', Boolean)
396
+ )
397
+
398
+
399
+ DescribeGroupsRequest = [
400
+ DescribeGroupsRequest_v0, DescribeGroupsRequest_v1,
401
+ DescribeGroupsRequest_v2, DescribeGroupsRequest_v3,
402
+ ]
403
+ DescribeGroupsResponse = [
404
+ DescribeGroupsResponse_v0, DescribeGroupsResponse_v1,
405
+ DescribeGroupsResponse_v2, DescribeGroupsResponse_v3,
406
+ ]
407
+
408
+
409
+ class SaslHandShakeResponse_v0(Response):
410
+ API_KEY = 17
411
+ API_VERSION = 0
412
+ SCHEMA = Schema(
413
+ ('error_code', Int16),
414
+ ('enabled_mechanisms', Array(String('utf-8')))
415
+ )
416
+
417
+
418
+ class SaslHandShakeResponse_v1(Response):
419
+ API_KEY = 17
420
+ API_VERSION = 1
421
+ SCHEMA = SaslHandShakeResponse_v0.SCHEMA
422
+
423
+
424
+ class SaslHandShakeRequest_v0(Request):
425
+ API_KEY = 17
426
+ API_VERSION = 0
427
+ RESPONSE_TYPE = SaslHandShakeResponse_v0
428
+ SCHEMA = Schema(
429
+ ('mechanism', String('utf-8'))
430
+ )
431
+
432
+
433
+ class SaslHandShakeRequest_v1(Request):
434
+ API_KEY = 17
435
+ API_VERSION = 1
436
+ RESPONSE_TYPE = SaslHandShakeResponse_v1
437
+ SCHEMA = SaslHandShakeRequest_v0.SCHEMA
438
+
439
+
440
+ SaslHandShakeRequest = [SaslHandShakeRequest_v0, SaslHandShakeRequest_v1]
441
+ SaslHandShakeResponse = [SaslHandShakeResponse_v0, SaslHandShakeResponse_v1]
442
+
443
+
444
+ class DescribeAclsResponse_v0(Response):
445
+ API_KEY = 29
446
+ API_VERSION = 0
447
+ SCHEMA = Schema(
448
+ ('throttle_time_ms', Int32),
449
+ ('error_code', Int16),
450
+ ('error_message', String('utf-8')),
451
+ ('resources', Array(
452
+ ('resource_type', Int8),
453
+ ('resource_name', String('utf-8')),
454
+ ('acls', Array(
455
+ ('principal', String('utf-8')),
456
+ ('host', String('utf-8')),
457
+ ('operation', Int8),
458
+ ('permission_type', Int8)))))
459
+ )
460
+
461
+
462
+ class DescribeAclsResponse_v1(Response):
463
+ API_KEY = 29
464
+ API_VERSION = 1
465
+ SCHEMA = Schema(
466
+ ('throttle_time_ms', Int32),
467
+ ('error_code', Int16),
468
+ ('error_message', String('utf-8')),
469
+ ('resources', Array(
470
+ ('resource_type', Int8),
471
+ ('resource_name', String('utf-8')),
472
+ ('resource_pattern_type', Int8),
473
+ ('acls', Array(
474
+ ('principal', String('utf-8')),
475
+ ('host', String('utf-8')),
476
+ ('operation', Int8),
477
+ ('permission_type', Int8)))))
478
+ )
479
+
480
+
481
+ class DescribeAclsResponse_v2(Response):
482
+ API_KEY = 29
483
+ API_VERSION = 2
484
+ SCHEMA = DescribeAclsResponse_v1.SCHEMA
485
+
486
+
487
+ class DescribeAclsRequest_v0(Request):
488
+ API_KEY = 29
489
+ API_VERSION = 0
490
+ RESPONSE_TYPE = DescribeAclsResponse_v0
491
+ SCHEMA = Schema(
492
+ ('resource_type', Int8),
493
+ ('resource_name', String('utf-8')),
494
+ ('principal', String('utf-8')),
495
+ ('host', String('utf-8')),
496
+ ('operation', Int8),
497
+ ('permission_type', Int8)
498
+ )
499
+
500
+
501
+ class DescribeAclsRequest_v1(Request):
502
+ API_KEY = 29
503
+ API_VERSION = 1
504
+ RESPONSE_TYPE = DescribeAclsResponse_v1
505
+ SCHEMA = Schema(
506
+ ('resource_type', Int8),
507
+ ('resource_name', String('utf-8')),
508
+ ('resource_pattern_type_filter', Int8),
509
+ ('principal', String('utf-8')),
510
+ ('host', String('utf-8')),
511
+ ('operation', Int8),
512
+ ('permission_type', Int8)
513
+ )
514
+
515
+
516
+ class DescribeAclsRequest_v2(Request):
517
+ """
518
+ Enable flexible version
519
+ """
520
+ API_KEY = 29
521
+ API_VERSION = 2
522
+ RESPONSE_TYPE = DescribeAclsResponse_v2
523
+ SCHEMA = DescribeAclsRequest_v1.SCHEMA
524
+
525
+
526
+ DescribeAclsRequest = [DescribeAclsRequest_v0, DescribeAclsRequest_v1]
527
+ DescribeAclsResponse = [DescribeAclsResponse_v0, DescribeAclsResponse_v1]
528
+
529
+ class CreateAclsResponse_v0(Response):
530
+ API_KEY = 30
531
+ API_VERSION = 0
532
+ SCHEMA = Schema(
533
+ ('throttle_time_ms', Int32),
534
+ ('creation_responses', Array(
535
+ ('error_code', Int16),
536
+ ('error_message', String('utf-8'))))
537
+ )
538
+
539
+ class CreateAclsResponse_v1(Response):
540
+ API_KEY = 30
541
+ API_VERSION = 1
542
+ SCHEMA = CreateAclsResponse_v0.SCHEMA
543
+
544
+ class CreateAclsRequest_v0(Request):
545
+ API_KEY = 30
546
+ API_VERSION = 0
547
+ RESPONSE_TYPE = CreateAclsResponse_v0
548
+ SCHEMA = Schema(
549
+ ('creations', Array(
550
+ ('resource_type', Int8),
551
+ ('resource_name', String('utf-8')),
552
+ ('principal', String('utf-8')),
553
+ ('host', String('utf-8')),
554
+ ('operation', Int8),
555
+ ('permission_type', Int8)))
556
+ )
557
+
558
+ class CreateAclsRequest_v1(Request):
559
+ API_KEY = 30
560
+ API_VERSION = 1
561
+ RESPONSE_TYPE = CreateAclsResponse_v1
562
+ SCHEMA = Schema(
563
+ ('creations', Array(
564
+ ('resource_type', Int8),
565
+ ('resource_name', String('utf-8')),
566
+ ('resource_pattern_type', Int8),
567
+ ('principal', String('utf-8')),
568
+ ('host', String('utf-8')),
569
+ ('operation', Int8),
570
+ ('permission_type', Int8)))
571
+ )
572
+
573
+ CreateAclsRequest = [CreateAclsRequest_v0, CreateAclsRequest_v1]
574
+ CreateAclsResponse = [CreateAclsResponse_v0, CreateAclsResponse_v1]
575
+
576
+ class DeleteAclsResponse_v0(Response):
577
+ API_KEY = 31
578
+ API_VERSION = 0
579
+ SCHEMA = Schema(
580
+ ('throttle_time_ms', Int32),
581
+ ('filter_responses', Array(
582
+ ('error_code', Int16),
583
+ ('error_message', String('utf-8')),
584
+ ('matching_acls', Array(
585
+ ('error_code', Int16),
586
+ ('error_message', String('utf-8')),
587
+ ('resource_type', Int8),
588
+ ('resource_name', String('utf-8')),
589
+ ('principal', String('utf-8')),
590
+ ('host', String('utf-8')),
591
+ ('operation', Int8),
592
+ ('permission_type', Int8)))))
593
+ )
594
+
595
+ class DeleteAclsResponse_v1(Response):
596
+ API_KEY = 31
597
+ API_VERSION = 1
598
+ SCHEMA = Schema(
599
+ ('throttle_time_ms', Int32),
600
+ ('filter_responses', Array(
601
+ ('error_code', Int16),
602
+ ('error_message', String('utf-8')),
603
+ ('matching_acls', Array(
604
+ ('error_code', Int16),
605
+ ('error_message', String('utf-8')),
606
+ ('resource_type', Int8),
607
+ ('resource_name', String('utf-8')),
608
+ ('resource_pattern_type', Int8),
609
+ ('principal', String('utf-8')),
610
+ ('host', String('utf-8')),
611
+ ('operation', Int8),
612
+ ('permission_type', Int8)))))
613
+ )
614
+
615
+ class DeleteAclsRequest_v0(Request):
616
+ API_KEY = 31
617
+ API_VERSION = 0
618
+ RESPONSE_TYPE = DeleteAclsResponse_v0
619
+ SCHEMA = Schema(
620
+ ('filters', Array(
621
+ ('resource_type', Int8),
622
+ ('resource_name', String('utf-8')),
623
+ ('principal', String('utf-8')),
624
+ ('host', String('utf-8')),
625
+ ('operation', Int8),
626
+ ('permission_type', Int8)))
627
+ )
628
+
629
+ class DeleteAclsRequest_v1(Request):
630
+ API_KEY = 31
631
+ API_VERSION = 1
632
+ RESPONSE_TYPE = DeleteAclsResponse_v1
633
+ SCHEMA = Schema(
634
+ ('filters', Array(
635
+ ('resource_type', Int8),
636
+ ('resource_name', String('utf-8')),
637
+ ('resource_pattern_type_filter', Int8),
638
+ ('principal', String('utf-8')),
639
+ ('host', String('utf-8')),
640
+ ('operation', Int8),
641
+ ('permission_type', Int8)))
642
+ )
643
+
644
+ DeleteAclsRequest = [DeleteAclsRequest_v0, DeleteAclsRequest_v1]
645
+ DeleteAclsResponse = [DeleteAclsResponse_v0, DeleteAclsResponse_v1]
646
+
647
+ class AlterConfigsResponse_v0(Response):
648
+ API_KEY = 33
649
+ API_VERSION = 0
650
+ SCHEMA = Schema(
651
+ ('throttle_time_ms', Int32),
652
+ ('resources', Array(
653
+ ('error_code', Int16),
654
+ ('error_message', String('utf-8')),
655
+ ('resource_type', Int8),
656
+ ('resource_name', String('utf-8'))))
657
+ )
658
+
659
+
660
+ class AlterConfigsResponse_v1(Response):
661
+ API_KEY = 33
662
+ API_VERSION = 1
663
+ SCHEMA = AlterConfigsResponse_v0.SCHEMA
664
+
665
+
666
+ class AlterConfigsRequest_v0(Request):
667
+ API_KEY = 33
668
+ API_VERSION = 0
669
+ RESPONSE_TYPE = AlterConfigsResponse_v0
670
+ SCHEMA = Schema(
671
+ ('resources', Array(
672
+ ('resource_type', Int8),
673
+ ('resource_name', String('utf-8')),
674
+ ('config_entries', Array(
675
+ ('config_name', String('utf-8')),
676
+ ('config_value', String('utf-8')))))),
677
+ ('validate_only', Boolean)
678
+ )
679
+
680
+ class AlterConfigsRequest_v1(Request):
681
+ API_KEY = 33
682
+ API_VERSION = 1
683
+ RESPONSE_TYPE = AlterConfigsResponse_v1
684
+ SCHEMA = AlterConfigsRequest_v0.SCHEMA
685
+
686
+ AlterConfigsRequest = [AlterConfigsRequest_v0, AlterConfigsRequest_v1]
687
+ AlterConfigsResponse = [AlterConfigsResponse_v0, AlterConfigsRequest_v1]
688
+
689
+
690
+ class DescribeConfigsResponse_v0(Response):
691
+ API_KEY = 32
692
+ API_VERSION = 0
693
+ SCHEMA = Schema(
694
+ ('throttle_time_ms', Int32),
695
+ ('resources', Array(
696
+ ('error_code', Int16),
697
+ ('error_message', String('utf-8')),
698
+ ('resource_type', Int8),
699
+ ('resource_name', String('utf-8')),
700
+ ('config_entries', Array(
701
+ ('config_names', String('utf-8')),
702
+ ('config_value', String('utf-8')),
703
+ ('read_only', Boolean),
704
+ ('is_default', Boolean),
705
+ ('is_sensitive', Boolean)))))
706
+ )
707
+
708
+ class DescribeConfigsResponse_v1(Response):
709
+ API_KEY = 32
710
+ API_VERSION = 1
711
+ SCHEMA = Schema(
712
+ ('throttle_time_ms', Int32),
713
+ ('resources', Array(
714
+ ('error_code', Int16),
715
+ ('error_message', String('utf-8')),
716
+ ('resource_type', Int8),
717
+ ('resource_name', String('utf-8')),
718
+ ('config_entries', Array(
719
+ ('config_names', String('utf-8')),
720
+ ('config_value', String('utf-8')),
721
+ ('read_only', Boolean),
722
+ ('is_default', Boolean),
723
+ ('is_sensitive', Boolean),
724
+ ('config_synonyms', Array(
725
+ ('config_name', String('utf-8')),
726
+ ('config_value', String('utf-8')),
727
+ ('config_source', Int8)))))))
728
+ )
729
+
730
+ class DescribeConfigsResponse_v2(Response):
731
+ API_KEY = 32
732
+ API_VERSION = 2
733
+ SCHEMA = Schema(
734
+ ('throttle_time_ms', Int32),
735
+ ('resources', Array(
736
+ ('error_code', Int16),
737
+ ('error_message', String('utf-8')),
738
+ ('resource_type', Int8),
739
+ ('resource_name', String('utf-8')),
740
+ ('config_entries', Array(
741
+ ('config_names', String('utf-8')),
742
+ ('config_value', String('utf-8')),
743
+ ('read_only', Boolean),
744
+ ('config_source', Int8),
745
+ ('is_sensitive', Boolean),
746
+ ('config_synonyms', Array(
747
+ ('config_name', String('utf-8')),
748
+ ('config_value', String('utf-8')),
749
+ ('config_source', Int8)))))))
750
+ )
751
+
752
+ class DescribeConfigsRequest_v0(Request):
753
+ API_KEY = 32
754
+ API_VERSION = 0
755
+ RESPONSE_TYPE = DescribeConfigsResponse_v0
756
+ SCHEMA = Schema(
757
+ ('resources', Array(
758
+ ('resource_type', Int8),
759
+ ('resource_name', String('utf-8')),
760
+ ('config_names', Array(String('utf-8')))))
761
+ )
762
+
763
+ class DescribeConfigsRequest_v1(Request):
764
+ API_KEY = 32
765
+ API_VERSION = 1
766
+ RESPONSE_TYPE = DescribeConfigsResponse_v1
767
+ SCHEMA = Schema(
768
+ ('resources', Array(
769
+ ('resource_type', Int8),
770
+ ('resource_name', String('utf-8')),
771
+ ('config_names', Array(String('utf-8'))))),
772
+ ('include_synonyms', Boolean)
773
+ )
774
+
775
+
776
+ class DescribeConfigsRequest_v2(Request):
777
+ API_KEY = 32
778
+ API_VERSION = 2
779
+ RESPONSE_TYPE = DescribeConfigsResponse_v2
780
+ SCHEMA = DescribeConfigsRequest_v1.SCHEMA
781
+
782
+
783
+ DescribeConfigsRequest = [
784
+ DescribeConfigsRequest_v0, DescribeConfigsRequest_v1,
785
+ DescribeConfigsRequest_v2,
786
+ ]
787
+ DescribeConfigsResponse = [
788
+ DescribeConfigsResponse_v0, DescribeConfigsResponse_v1,
789
+ DescribeConfigsResponse_v2,
790
+ ]
791
+
792
+
793
+ class SaslAuthenticateResponse_v0(Response):
794
+ API_KEY = 36
795
+ API_VERSION = 0
796
+ SCHEMA = Schema(
797
+ ('error_code', Int16),
798
+ ('error_message', String('utf-8')),
799
+ ('sasl_auth_bytes', Bytes)
800
+ )
801
+
802
+
803
+ class SaslAuthenticateResponse_v1(Response):
804
+ API_KEY = 36
805
+ API_VERSION = 1
806
+ SCHEMA = Schema(
807
+ ('error_code', Int16),
808
+ ('error_message', String('utf-8')),
809
+ ('sasl_auth_bytes', Bytes),
810
+ ('session_lifetime_ms', Int64)
811
+ )
812
+
813
+
814
+ class SaslAuthenticateRequest_v0(Request):
815
+ API_KEY = 36
816
+ API_VERSION = 0
817
+ RESPONSE_TYPE = SaslAuthenticateResponse_v0
818
+ SCHEMA = Schema(
819
+ ('sasl_auth_bytes', Bytes)
820
+ )
821
+
822
+
823
+ class SaslAuthenticateRequest_v1(Request):
824
+ API_KEY = 36
825
+ API_VERSION = 1
826
+ RESPONSE_TYPE = SaslAuthenticateResponse_v1
827
+ SCHEMA = SaslAuthenticateRequest_v0.SCHEMA
828
+
829
+
830
+ SaslAuthenticateRequest = [
831
+ SaslAuthenticateRequest_v0, SaslAuthenticateRequest_v1,
832
+ ]
833
+ SaslAuthenticateResponse = [
834
+ SaslAuthenticateResponse_v0, SaslAuthenticateResponse_v1,
835
+ ]
836
+
837
+
838
+ class CreatePartitionsResponse_v0(Response):
839
+ API_KEY = 37
840
+ API_VERSION = 0
841
+ SCHEMA = Schema(
842
+ ('throttle_time_ms', Int32),
843
+ ('topic_errors', Array(
844
+ ('topic', String('utf-8')),
845
+ ('error_code', Int16),
846
+ ('error_message', String('utf-8'))))
847
+ )
848
+
849
+
850
+ class CreatePartitionsResponse_v1(Response):
851
+ API_KEY = 37
852
+ API_VERSION = 1
853
+ SCHEMA = CreatePartitionsResponse_v0.SCHEMA
854
+
855
+
856
+ class CreatePartitionsRequest_v0(Request):
857
+ API_KEY = 37
858
+ API_VERSION = 0
859
+ RESPONSE_TYPE = CreatePartitionsResponse_v0
860
+ SCHEMA = Schema(
861
+ ('topic_partitions', Array(
862
+ ('topic', String('utf-8')),
863
+ ('new_partitions', Schema(
864
+ ('count', Int32),
865
+ ('assignment', Array(Array(Int32))))))),
866
+ ('timeout', Int32),
867
+ ('validate_only', Boolean)
868
+ )
869
+
870
+
871
+ class CreatePartitionsRequest_v1(Request):
872
+ API_KEY = 37
873
+ API_VERSION = 1
874
+ SCHEMA = CreatePartitionsRequest_v0.SCHEMA
875
+ RESPONSE_TYPE = CreatePartitionsResponse_v1
876
+
877
+
878
+ CreatePartitionsRequest = [
879
+ CreatePartitionsRequest_v0, CreatePartitionsRequest_v1,
880
+ ]
881
+ CreatePartitionsResponse = [
882
+ CreatePartitionsResponse_v0, CreatePartitionsResponse_v1,
883
+ ]
884
+
885
+
886
+ class DeleteGroupsResponse_v0(Response):
887
+ API_KEY = 42
888
+ API_VERSION = 0
889
+ SCHEMA = Schema(
890
+ ("throttle_time_ms", Int32),
891
+ ("results", Array(
892
+ ("group_id", String("utf-8")),
893
+ ("error_code", Int16)))
894
+ )
895
+
896
+
897
+ class DeleteGroupsResponse_v1(Response):
898
+ API_KEY = 42
899
+ API_VERSION = 1
900
+ SCHEMA = DeleteGroupsResponse_v0.SCHEMA
901
+
902
+
903
+ class DeleteGroupsRequest_v0(Request):
904
+ API_KEY = 42
905
+ API_VERSION = 0
906
+ RESPONSE_TYPE = DeleteGroupsResponse_v0
907
+ SCHEMA = Schema(
908
+ ("groups_names", Array(String("utf-8")))
909
+ )
910
+
911
+
912
+ class DeleteGroupsRequest_v1(Request):
913
+ API_KEY = 42
914
+ API_VERSION = 1
915
+ RESPONSE_TYPE = DeleteGroupsResponse_v1
916
+ SCHEMA = DeleteGroupsRequest_v0.SCHEMA
917
+
918
+
919
+ DeleteGroupsRequest = [
920
+ DeleteGroupsRequest_v0, DeleteGroupsRequest_v1
921
+ ]
922
+
923
+ DeleteGroupsResponse = [
924
+ DeleteGroupsResponse_v0, DeleteGroupsResponse_v1
925
+ ]
926
+
927
+
928
+ class DescribeClientQuotasResponse_v0(Request):
929
+ API_KEY = 48
930
+ API_VERSION = 0
931
+ SCHEMA = Schema(
932
+ ('throttle_time_ms', Int32),
933
+ ('error_code', Int16),
934
+ ('error_message', String('utf-8')),
935
+ ('entries', Array(
936
+ ('entity', Array(
937
+ ('entity_type', String('utf-8')),
938
+ ('entity_name', String('utf-8')))),
939
+ ('values', Array(
940
+ ('name', String('utf-8')),
941
+ ('value', Float64))))),
942
+ )
943
+
944
+
945
+ class DescribeClientQuotasRequest_v0(Request):
946
+ API_KEY = 48
947
+ API_VERSION = 0
948
+ RESPONSE_TYPE = DescribeClientQuotasResponse_v0
949
+ SCHEMA = Schema(
950
+ ('components', Array(
951
+ ('entity_type', String('utf-8')),
952
+ ('match_type', Int8),
953
+ ('match', String('utf-8')),
954
+ )),
955
+ ('strict', Boolean)
956
+ )
957
+
958
+
959
+ DescribeClientQuotasRequest = [
960
+ DescribeClientQuotasRequest_v0,
961
+ ]
962
+
963
+ DescribeClientQuotasResponse = [
964
+ DescribeClientQuotasResponse_v0,
965
+ ]
testbed/dpkp__kafka-python/kafka/protocol/api.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+
3
+ import abc
4
+
5
+ from kafka.protocol.struct import Struct
6
+ from kafka.protocol.types import Int16, Int32, String, Schema, Array
7
+
8
+
9
+ class RequestHeader(Struct):
10
+ SCHEMA = Schema(
11
+ ('api_key', Int16),
12
+ ('api_version', Int16),
13
+ ('correlation_id', Int32),
14
+ ('client_id', String('utf-8'))
15
+ )
16
+
17
+ def __init__(self, request, correlation_id=0, client_id='kafka-python'):
18
+ super(RequestHeader, self).__init__(
19
+ request.API_KEY, request.API_VERSION, correlation_id, client_id
20
+ )
21
+
22
+
23
+ class Request(Struct):
24
+ __metaclass__ = abc.ABCMeta
25
+
26
+ @abc.abstractproperty
27
+ def API_KEY(self):
28
+ """Integer identifier for api request"""
29
+ pass
30
+
31
+ @abc.abstractproperty
32
+ def API_VERSION(self):
33
+ """Integer of api request version"""
34
+ pass
35
+
36
+ @abc.abstractproperty
37
+ def SCHEMA(self):
38
+ """An instance of Schema() representing the request structure"""
39
+ pass
40
+
41
+ @abc.abstractproperty
42
+ def RESPONSE_TYPE(self):
43
+ """The Response class associated with the api request"""
44
+ pass
45
+
46
+ def expect_response(self):
47
+ """Override this method if an api request does not always generate a response"""
48
+ return True
49
+
50
+ def to_object(self):
51
+ return _to_object(self.SCHEMA, self)
52
+
53
+
54
+ class Response(Struct):
55
+ __metaclass__ = abc.ABCMeta
56
+
57
+ @abc.abstractproperty
58
+ def API_KEY(self):
59
+ """Integer identifier for api request/response"""
60
+ pass
61
+
62
+ @abc.abstractproperty
63
+ def API_VERSION(self):
64
+ """Integer of api request/response version"""
65
+ pass
66
+
67
+ @abc.abstractproperty
68
+ def SCHEMA(self):
69
+ """An instance of Schema() representing the response structure"""
70
+ pass
71
+
72
+ def to_object(self):
73
+ return _to_object(self.SCHEMA, self)
74
+
75
+
76
+ def _to_object(schema, data):
77
+ obj = {}
78
+ for idx, (name, _type) in enumerate(zip(schema.names, schema.fields)):
79
+ if isinstance(data, Struct):
80
+ val = data.get_item(name)
81
+ else:
82
+ val = data[idx]
83
+
84
+ if isinstance(_type, Schema):
85
+ obj[name] = _to_object(_type, val)
86
+ elif isinstance(_type, Array):
87
+ if isinstance(_type.array_of, (Array, Schema)):
88
+ obj[name] = [
89
+ _to_object(_type.array_of, x)
90
+ for x in val
91
+ ]
92
+ else:
93
+ obj[name] = val
94
+ else:
95
+ obj[name] = val
96
+
97
+ return obj
testbed/dpkp__kafka-python/kafka/protocol/commit.py ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+
3
+ from kafka.protocol.api import Request, Response
4
+ from kafka.protocol.types import Array, Int8, Int16, Int32, Int64, Schema, String
5
+
6
+
7
+ class OffsetCommitResponse_v0(Response):
8
+ API_KEY = 8
9
+ API_VERSION = 0
10
+ SCHEMA = Schema(
11
+ ('topics', Array(
12
+ ('topic', String('utf-8')),
13
+ ('partitions', Array(
14
+ ('partition', Int32),
15
+ ('error_code', Int16)))))
16
+ )
17
+
18
+
19
+ class OffsetCommitResponse_v1(Response):
20
+ API_KEY = 8
21
+ API_VERSION = 1
22
+ SCHEMA = OffsetCommitResponse_v0.SCHEMA
23
+
24
+
25
+ class OffsetCommitResponse_v2(Response):
26
+ API_KEY = 8
27
+ API_VERSION = 2
28
+ SCHEMA = OffsetCommitResponse_v1.SCHEMA
29
+
30
+
31
+ class OffsetCommitResponse_v3(Response):
32
+ API_KEY = 8
33
+ API_VERSION = 3
34
+ SCHEMA = Schema(
35
+ ('throttle_time_ms', Int32),
36
+ ('topics', Array(
37
+ ('topic', String('utf-8')),
38
+ ('partitions', Array(
39
+ ('partition', Int32),
40
+ ('error_code', Int16)))))
41
+ )
42
+
43
+
44
+ class OffsetCommitRequest_v0(Request):
45
+ API_KEY = 8
46
+ API_VERSION = 0 # Zookeeper-backed storage
47
+ RESPONSE_TYPE = OffsetCommitResponse_v0
48
+ SCHEMA = Schema(
49
+ ('consumer_group', String('utf-8')),
50
+ ('topics', Array(
51
+ ('topic', String('utf-8')),
52
+ ('partitions', Array(
53
+ ('partition', Int32),
54
+ ('offset', Int64),
55
+ ('metadata', String('utf-8'))))))
56
+ )
57
+
58
+
59
+ class OffsetCommitRequest_v1(Request):
60
+ API_KEY = 8
61
+ API_VERSION = 1 # Kafka-backed storage
62
+ RESPONSE_TYPE = OffsetCommitResponse_v1
63
+ SCHEMA = Schema(
64
+ ('consumer_group', String('utf-8')),
65
+ ('consumer_group_generation_id', Int32),
66
+ ('consumer_id', String('utf-8')),
67
+ ('topics', Array(
68
+ ('topic', String('utf-8')),
69
+ ('partitions', Array(
70
+ ('partition', Int32),
71
+ ('offset', Int64),
72
+ ('timestamp', Int64),
73
+ ('metadata', String('utf-8'))))))
74
+ )
75
+
76
+
77
+ class OffsetCommitRequest_v2(Request):
78
+ API_KEY = 8
79
+ API_VERSION = 2 # added retention_time, dropped timestamp
80
+ RESPONSE_TYPE = OffsetCommitResponse_v2
81
+ SCHEMA = Schema(
82
+ ('consumer_group', String('utf-8')),
83
+ ('consumer_group_generation_id', Int32),
84
+ ('consumer_id', String('utf-8')),
85
+ ('retention_time', Int64),
86
+ ('topics', Array(
87
+ ('topic', String('utf-8')),
88
+ ('partitions', Array(
89
+ ('partition', Int32),
90
+ ('offset', Int64),
91
+ ('metadata', String('utf-8'))))))
92
+ )
93
+ DEFAULT_GENERATION_ID = -1
94
+ DEFAULT_RETENTION_TIME = -1
95
+
96
+
97
+ class OffsetCommitRequest_v3(Request):
98
+ API_KEY = 8
99
+ API_VERSION = 3
100
+ RESPONSE_TYPE = OffsetCommitResponse_v3
101
+ SCHEMA = OffsetCommitRequest_v2.SCHEMA
102
+
103
+
104
+ OffsetCommitRequest = [
105
+ OffsetCommitRequest_v0, OffsetCommitRequest_v1,
106
+ OffsetCommitRequest_v2, OffsetCommitRequest_v3
107
+ ]
108
+ OffsetCommitResponse = [
109
+ OffsetCommitResponse_v0, OffsetCommitResponse_v1,
110
+ OffsetCommitResponse_v2, OffsetCommitResponse_v3
111
+ ]
112
+
113
+
114
+ class OffsetFetchResponse_v0(Response):
115
+ API_KEY = 9
116
+ API_VERSION = 0
117
+ SCHEMA = Schema(
118
+ ('topics', Array(
119
+ ('topic', String('utf-8')),
120
+ ('partitions', Array(
121
+ ('partition', Int32),
122
+ ('offset', Int64),
123
+ ('metadata', String('utf-8')),
124
+ ('error_code', Int16)))))
125
+ )
126
+
127
+
128
+ class OffsetFetchResponse_v1(Response):
129
+ API_KEY = 9
130
+ API_VERSION = 1
131
+ SCHEMA = OffsetFetchResponse_v0.SCHEMA
132
+
133
+
134
+ class OffsetFetchResponse_v2(Response):
135
+ # Added in KIP-88
136
+ API_KEY = 9
137
+ API_VERSION = 2
138
+ SCHEMA = Schema(
139
+ ('topics', Array(
140
+ ('topic', String('utf-8')),
141
+ ('partitions', Array(
142
+ ('partition', Int32),
143
+ ('offset', Int64),
144
+ ('metadata', String('utf-8')),
145
+ ('error_code', Int16))))),
146
+ ('error_code', Int16)
147
+ )
148
+
149
+
150
+ class OffsetFetchResponse_v3(Response):
151
+ API_KEY = 9
152
+ API_VERSION = 3
153
+ SCHEMA = Schema(
154
+ ('throttle_time_ms', Int32),
155
+ ('topics', Array(
156
+ ('topic', String('utf-8')),
157
+ ('partitions', Array(
158
+ ('partition', Int32),
159
+ ('offset', Int64),
160
+ ('metadata', String('utf-8')),
161
+ ('error_code', Int16))))),
162
+ ('error_code', Int16)
163
+ )
164
+
165
+
166
+ class OffsetFetchRequest_v0(Request):
167
+ API_KEY = 9
168
+ API_VERSION = 0 # zookeeper-backed storage
169
+ RESPONSE_TYPE = OffsetFetchResponse_v0
170
+ SCHEMA = Schema(
171
+ ('consumer_group', String('utf-8')),
172
+ ('topics', Array(
173
+ ('topic', String('utf-8')),
174
+ ('partitions', Array(Int32))))
175
+ )
176
+
177
+
178
+ class OffsetFetchRequest_v1(Request):
179
+ API_KEY = 9
180
+ API_VERSION = 1 # kafka-backed storage
181
+ RESPONSE_TYPE = OffsetFetchResponse_v1
182
+ SCHEMA = OffsetFetchRequest_v0.SCHEMA
183
+
184
+
185
+ class OffsetFetchRequest_v2(Request):
186
+ # KIP-88: Allows passing null topics to return offsets for all partitions
187
+ # that the consumer group has a stored offset for, even if no consumer in
188
+ # the group is currently consuming that partition.
189
+ API_KEY = 9
190
+ API_VERSION = 2
191
+ RESPONSE_TYPE = OffsetFetchResponse_v2
192
+ SCHEMA = OffsetFetchRequest_v1.SCHEMA
193
+
194
+
195
+ class OffsetFetchRequest_v3(Request):
196
+ API_KEY = 9
197
+ API_VERSION = 3
198
+ RESPONSE_TYPE = OffsetFetchResponse_v3
199
+ SCHEMA = OffsetFetchRequest_v2.SCHEMA
200
+
201
+
202
+ OffsetFetchRequest = [
203
+ OffsetFetchRequest_v0, OffsetFetchRequest_v1,
204
+ OffsetFetchRequest_v2, OffsetFetchRequest_v3,
205
+ ]
206
+ OffsetFetchResponse = [
207
+ OffsetFetchResponse_v0, OffsetFetchResponse_v1,
208
+ OffsetFetchResponse_v2, OffsetFetchResponse_v3,
209
+ ]
210
+
211
+
212
+ class GroupCoordinatorResponse_v0(Response):
213
+ API_KEY = 10
214
+ API_VERSION = 0
215
+ SCHEMA = Schema(
216
+ ('error_code', Int16),
217
+ ('coordinator_id', Int32),
218
+ ('host', String('utf-8')),
219
+ ('port', Int32)
220
+ )
221
+
222
+
223
+ class GroupCoordinatorResponse_v1(Response):
224
+ API_KEY = 10
225
+ API_VERSION = 1
226
+ SCHEMA = Schema(
227
+ ('error_code', Int16),
228
+ ('error_message', String('utf-8')),
229
+ ('coordinator_id', Int32),
230
+ ('host', String('utf-8')),
231
+ ('port', Int32)
232
+ )
233
+
234
+
235
+ class GroupCoordinatorRequest_v0(Request):
236
+ API_KEY = 10
237
+ API_VERSION = 0
238
+ RESPONSE_TYPE = GroupCoordinatorResponse_v0
239
+ SCHEMA = Schema(
240
+ ('consumer_group', String('utf-8'))
241
+ )
242
+
243
+
244
+ class GroupCoordinatorRequest_v1(Request):
245
+ API_KEY = 10
246
+ API_VERSION = 1
247
+ RESPONSE_TYPE = GroupCoordinatorResponse_v1
248
+ SCHEMA = Schema(
249
+ ('coordinator_key', String('utf-8')),
250
+ ('coordinator_type', Int8)
251
+ )
252
+
253
+
254
+ GroupCoordinatorRequest = [GroupCoordinatorRequest_v0, GroupCoordinatorRequest_v1]
255
+ GroupCoordinatorResponse = [GroupCoordinatorResponse_v0, GroupCoordinatorResponse_v1]
testbed/dpkp__kafka-python/kafka/protocol/fetch.py ADDED
@@ -0,0 +1,386 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+
3
+ from kafka.protocol.api import Request, Response
4
+ from kafka.protocol.types import Array, Int8, Int16, Int32, Int64, Schema, String, Bytes
5
+
6
+
7
+ class FetchResponse_v0(Response):
8
+ API_KEY = 1
9
+ API_VERSION = 0
10
+ SCHEMA = Schema(
11
+ ('topics', Array(
12
+ ('topics', String('utf-8')),
13
+ ('partitions', Array(
14
+ ('partition', Int32),
15
+ ('error_code', Int16),
16
+ ('highwater_offset', Int64),
17
+ ('message_set', Bytes)))))
18
+ )
19
+
20
+
21
+ class FetchResponse_v1(Response):
22
+ API_KEY = 1
23
+ API_VERSION = 1
24
+ SCHEMA = Schema(
25
+ ('throttle_time_ms', Int32),
26
+ ('topics', Array(
27
+ ('topics', String('utf-8')),
28
+ ('partitions', Array(
29
+ ('partition', Int32),
30
+ ('error_code', Int16),
31
+ ('highwater_offset', Int64),
32
+ ('message_set', Bytes)))))
33
+ )
34
+
35
+
36
+ class FetchResponse_v2(Response):
37
+ API_KEY = 1
38
+ API_VERSION = 2
39
+ SCHEMA = FetchResponse_v1.SCHEMA # message format changed internally
40
+
41
+
42
+ class FetchResponse_v3(Response):
43
+ API_KEY = 1
44
+ API_VERSION = 3
45
+ SCHEMA = FetchResponse_v2.SCHEMA
46
+
47
+
48
+ class FetchResponse_v4(Response):
49
+ API_KEY = 1
50
+ API_VERSION = 4
51
+ SCHEMA = Schema(
52
+ ('throttle_time_ms', Int32),
53
+ ('topics', Array(
54
+ ('topics', String('utf-8')),
55
+ ('partitions', Array(
56
+ ('partition', Int32),
57
+ ('error_code', Int16),
58
+ ('highwater_offset', Int64),
59
+ ('last_stable_offset', Int64),
60
+ ('aborted_transactions', Array(
61
+ ('producer_id', Int64),
62
+ ('first_offset', Int64))),
63
+ ('message_set', Bytes)))))
64
+ )
65
+
66
+
67
+ class FetchResponse_v5(Response):
68
+ API_KEY = 1
69
+ API_VERSION = 5
70
+ SCHEMA = Schema(
71
+ ('throttle_time_ms', Int32),
72
+ ('topics', Array(
73
+ ('topics', String('utf-8')),
74
+ ('partitions', Array(
75
+ ('partition', Int32),
76
+ ('error_code', Int16),
77
+ ('highwater_offset', Int64),
78
+ ('last_stable_offset', Int64),
79
+ ('log_start_offset', Int64),
80
+ ('aborted_transactions', Array(
81
+ ('producer_id', Int64),
82
+ ('first_offset', Int64))),
83
+ ('message_set', Bytes)))))
84
+ )
85
+
86
+
87
+ class FetchResponse_v6(Response):
88
+ """
89
+ Same as FetchResponse_v5. The version number is bumped up to indicate that the client supports KafkaStorageException.
90
+ The KafkaStorageException will be translated to NotLeaderForPartitionException in the response if version <= 5
91
+ """
92
+ API_KEY = 1
93
+ API_VERSION = 6
94
+ SCHEMA = FetchResponse_v5.SCHEMA
95
+
96
+
97
+ class FetchResponse_v7(Response):
98
+ """
99
+ Add error_code and session_id to response
100
+ """
101
+ API_KEY = 1
102
+ API_VERSION = 7
103
+ SCHEMA = Schema(
104
+ ('throttle_time_ms', Int32),
105
+ ('error_code', Int16),
106
+ ('session_id', Int32),
107
+ ('topics', Array(
108
+ ('topics', String('utf-8')),
109
+ ('partitions', Array(
110
+ ('partition', Int32),
111
+ ('error_code', Int16),
112
+ ('highwater_offset', Int64),
113
+ ('last_stable_offset', Int64),
114
+ ('log_start_offset', Int64),
115
+ ('aborted_transactions', Array(
116
+ ('producer_id', Int64),
117
+ ('first_offset', Int64))),
118
+ ('message_set', Bytes)))))
119
+ )
120
+
121
+
122
+ class FetchResponse_v8(Response):
123
+ API_KEY = 1
124
+ API_VERSION = 8
125
+ SCHEMA = FetchResponse_v7.SCHEMA
126
+
127
+
128
+ class FetchResponse_v9(Response):
129
+ API_KEY = 1
130
+ API_VERSION = 9
131
+ SCHEMA = FetchResponse_v7.SCHEMA
132
+
133
+
134
+ class FetchResponse_v10(Response):
135
+ API_KEY = 1
136
+ API_VERSION = 10
137
+ SCHEMA = FetchResponse_v7.SCHEMA
138
+
139
+
140
+ class FetchResponse_v11(Response):
141
+ API_KEY = 1
142
+ API_VERSION = 11
143
+ SCHEMA = Schema(
144
+ ('throttle_time_ms', Int32),
145
+ ('error_code', Int16),
146
+ ('session_id', Int32),
147
+ ('topics', Array(
148
+ ('topics', String('utf-8')),
149
+ ('partitions', Array(
150
+ ('partition', Int32),
151
+ ('error_code', Int16),
152
+ ('highwater_offset', Int64),
153
+ ('last_stable_offset', Int64),
154
+ ('log_start_offset', Int64),
155
+ ('aborted_transactions', Array(
156
+ ('producer_id', Int64),
157
+ ('first_offset', Int64))),
158
+ ('preferred_read_replica', Int32),
159
+ ('message_set', Bytes)))))
160
+ )
161
+
162
+
163
+ class FetchRequest_v0(Request):
164
+ API_KEY = 1
165
+ API_VERSION = 0
166
+ RESPONSE_TYPE = FetchResponse_v0
167
+ SCHEMA = Schema(
168
+ ('replica_id', Int32),
169
+ ('max_wait_time', Int32),
170
+ ('min_bytes', Int32),
171
+ ('topics', Array(
172
+ ('topic', String('utf-8')),
173
+ ('partitions', Array(
174
+ ('partition', Int32),
175
+ ('offset', Int64),
176
+ ('max_bytes', Int32)))))
177
+ )
178
+
179
+
180
+ class FetchRequest_v1(Request):
181
+ API_KEY = 1
182
+ API_VERSION = 1
183
+ RESPONSE_TYPE = FetchResponse_v1
184
+ SCHEMA = FetchRequest_v0.SCHEMA
185
+
186
+
187
+ class FetchRequest_v2(Request):
188
+ API_KEY = 1
189
+ API_VERSION = 2
190
+ RESPONSE_TYPE = FetchResponse_v2
191
+ SCHEMA = FetchRequest_v1.SCHEMA
192
+
193
+
194
+ class FetchRequest_v3(Request):
195
+ API_KEY = 1
196
+ API_VERSION = 3
197
+ RESPONSE_TYPE = FetchResponse_v3
198
+ SCHEMA = Schema(
199
+ ('replica_id', Int32),
200
+ ('max_wait_time', Int32),
201
+ ('min_bytes', Int32),
202
+ ('max_bytes', Int32), # This new field is only difference from FR_v2
203
+ ('topics', Array(
204
+ ('topic', String('utf-8')),
205
+ ('partitions', Array(
206
+ ('partition', Int32),
207
+ ('offset', Int64),
208
+ ('max_bytes', Int32)))))
209
+ )
210
+
211
+
212
+ class FetchRequest_v4(Request):
213
+ # Adds isolation_level field
214
+ API_KEY = 1
215
+ API_VERSION = 4
216
+ RESPONSE_TYPE = FetchResponse_v4
217
+ SCHEMA = Schema(
218
+ ('replica_id', Int32),
219
+ ('max_wait_time', Int32),
220
+ ('min_bytes', Int32),
221
+ ('max_bytes', Int32),
222
+ ('isolation_level', Int8),
223
+ ('topics', Array(
224
+ ('topic', String('utf-8')),
225
+ ('partitions', Array(
226
+ ('partition', Int32),
227
+ ('offset', Int64),
228
+ ('max_bytes', Int32)))))
229
+ )
230
+
231
+
232
+ class FetchRequest_v5(Request):
233
+ # This may only be used in broker-broker api calls
234
+ API_KEY = 1
235
+ API_VERSION = 5
236
+ RESPONSE_TYPE = FetchResponse_v5
237
+ SCHEMA = Schema(
238
+ ('replica_id', Int32),
239
+ ('max_wait_time', Int32),
240
+ ('min_bytes', Int32),
241
+ ('max_bytes', Int32),
242
+ ('isolation_level', Int8),
243
+ ('topics', Array(
244
+ ('topic', String('utf-8')),
245
+ ('partitions', Array(
246
+ ('partition', Int32),
247
+ ('fetch_offset', Int64),
248
+ ('log_start_offset', Int64),
249
+ ('max_bytes', Int32)))))
250
+ )
251
+
252
+
253
+ class FetchRequest_v6(Request):
254
+ """
255
+ The body of FETCH_REQUEST_V6 is the same as FETCH_REQUEST_V5.
256
+ The version number is bumped up to indicate that the client supports KafkaStorageException.
257
+ The KafkaStorageException will be translated to NotLeaderForPartitionException in the response if version <= 5
258
+ """
259
+ API_KEY = 1
260
+ API_VERSION = 6
261
+ RESPONSE_TYPE = FetchResponse_v6
262
+ SCHEMA = FetchRequest_v5.SCHEMA
263
+
264
+
265
+ class FetchRequest_v7(Request):
266
+ """
267
+ Add incremental fetch requests
268
+ """
269
+ API_KEY = 1
270
+ API_VERSION = 7
271
+ RESPONSE_TYPE = FetchResponse_v7
272
+ SCHEMA = Schema(
273
+ ('replica_id', Int32),
274
+ ('max_wait_time', Int32),
275
+ ('min_bytes', Int32),
276
+ ('max_bytes', Int32),
277
+ ('isolation_level', Int8),
278
+ ('session_id', Int32),
279
+ ('session_epoch', Int32),
280
+ ('topics', Array(
281
+ ('topic', String('utf-8')),
282
+ ('partitions', Array(
283
+ ('partition', Int32),
284
+ ('fetch_offset', Int64),
285
+ ('log_start_offset', Int64),
286
+ ('max_bytes', Int32))))),
287
+ ('forgotten_topics_data', Array(
288
+ ('topic', String),
289
+ ('partitions', Array(Int32))
290
+ )),
291
+ )
292
+
293
+
294
+ class FetchRequest_v8(Request):
295
+ """
296
+ bump used to indicate that on quota violation brokers send out responses before throttling.
297
+ """
298
+ API_KEY = 1
299
+ API_VERSION = 8
300
+ RESPONSE_TYPE = FetchResponse_v8
301
+ SCHEMA = FetchRequest_v7.SCHEMA
302
+
303
+
304
+ class FetchRequest_v9(Request):
305
+ """
306
+ adds the current leader epoch (see KIP-320)
307
+ """
308
+ API_KEY = 1
309
+ API_VERSION = 9
310
+ RESPONSE_TYPE = FetchResponse_v9
311
+ SCHEMA = Schema(
312
+ ('replica_id', Int32),
313
+ ('max_wait_time', Int32),
314
+ ('min_bytes', Int32),
315
+ ('max_bytes', Int32),
316
+ ('isolation_level', Int8),
317
+ ('session_id', Int32),
318
+ ('session_epoch', Int32),
319
+ ('topics', Array(
320
+ ('topic', String('utf-8')),
321
+ ('partitions', Array(
322
+ ('partition', Int32),
323
+ ('current_leader_epoch', Int32),
324
+ ('fetch_offset', Int64),
325
+ ('log_start_offset', Int64),
326
+ ('max_bytes', Int32))))),
327
+ ('forgotten_topics_data', Array(
328
+ ('topic', String),
329
+ ('partitions', Array(Int32)),
330
+ )),
331
+ )
332
+
333
+
334
+ class FetchRequest_v10(Request):
335
+ """
336
+ bumped up to indicate ZStandard capability. (see KIP-110)
337
+ """
338
+ API_KEY = 1
339
+ API_VERSION = 10
340
+ RESPONSE_TYPE = FetchResponse_v10
341
+ SCHEMA = FetchRequest_v9.SCHEMA
342
+
343
+
344
+ class FetchRequest_v11(Request):
345
+ """
346
+ added rack ID to support read from followers (KIP-392)
347
+ """
348
+ API_KEY = 1
349
+ API_VERSION = 11
350
+ RESPONSE_TYPE = FetchResponse_v11
351
+ SCHEMA = Schema(
352
+ ('replica_id', Int32),
353
+ ('max_wait_time', Int32),
354
+ ('min_bytes', Int32),
355
+ ('max_bytes', Int32),
356
+ ('isolation_level', Int8),
357
+ ('session_id', Int32),
358
+ ('session_epoch', Int32),
359
+ ('topics', Array(
360
+ ('topic', String('utf-8')),
361
+ ('partitions', Array(
362
+ ('partition', Int32),
363
+ ('current_leader_epoch', Int32),
364
+ ('fetch_offset', Int64),
365
+ ('log_start_offset', Int64),
366
+ ('max_bytes', Int32))))),
367
+ ('forgotten_topics_data', Array(
368
+ ('topic', String),
369
+ ('partitions', Array(Int32))
370
+ )),
371
+ ('rack_id', String('utf-8')),
372
+ )
373
+
374
+
375
+ FetchRequest = [
376
+ FetchRequest_v0, FetchRequest_v1, FetchRequest_v2,
377
+ FetchRequest_v3, FetchRequest_v4, FetchRequest_v5,
378
+ FetchRequest_v6, FetchRequest_v7, FetchRequest_v8,
379
+ FetchRequest_v9, FetchRequest_v10, FetchRequest_v11,
380
+ ]
381
+ FetchResponse = [
382
+ FetchResponse_v0, FetchResponse_v1, FetchResponse_v2,
383
+ FetchResponse_v3, FetchResponse_v4, FetchResponse_v5,
384
+ FetchResponse_v6, FetchResponse_v7, FetchResponse_v8,
385
+ FetchResponse_v9, FetchResponse_v10, FetchResponse_v11,
386
+ ]
testbed/dpkp__kafka-python/kafka/protocol/frame.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class KafkaBytes(bytearray):
2
+ def __init__(self, size):
3
+ super(KafkaBytes, self).__init__(size)
4
+ self._idx = 0
5
+
6
+ def read(self, nbytes=None):
7
+ if nbytes is None:
8
+ nbytes = len(self) - self._idx
9
+ start = self._idx
10
+ self._idx += nbytes
11
+ if self._idx > len(self):
12
+ self._idx = len(self)
13
+ return bytes(self[start:self._idx])
14
+
15
+ def write(self, data):
16
+ start = self._idx
17
+ self._idx += len(data)
18
+ self[start:self._idx] = data
19
+
20
+ def seek(self, idx):
21
+ self._idx = idx
22
+
23
+ def tell(self):
24
+ return self._idx
25
+
26
+ def __str__(self):
27
+ return 'KafkaBytes(%d)' % len(self)
28
+
29
+ def __repr__(self):
30
+ return str(self)
testbed/dpkp__kafka-python/kafka/protocol/message.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+
3
+ import io
4
+ import time
5
+
6
+ from kafka.codec import (has_gzip, has_snappy, has_lz4, has_zstd,
7
+ gzip_decode, snappy_decode, zstd_decode,
8
+ lz4_decode, lz4_decode_old_kafka)
9
+ from kafka.protocol.frame import KafkaBytes
10
+ from kafka.protocol.struct import Struct
11
+ from kafka.protocol.types import (
12
+ Int8, Int32, Int64, Bytes, Schema, AbstractType
13
+ )
14
+ from kafka.util import crc32, WeakMethod
15
+
16
+
17
+ class Message(Struct):
18
+ SCHEMAS = [
19
+ Schema(
20
+ ('crc', Int32),
21
+ ('magic', Int8),
22
+ ('attributes', Int8),
23
+ ('key', Bytes),
24
+ ('value', Bytes)),
25
+ Schema(
26
+ ('crc', Int32),
27
+ ('magic', Int8),
28
+ ('attributes', Int8),
29
+ ('timestamp', Int64),
30
+ ('key', Bytes),
31
+ ('value', Bytes)),
32
+ ]
33
+ SCHEMA = SCHEMAS[1]
34
+ CODEC_MASK = 0x07
35
+ CODEC_GZIP = 0x01
36
+ CODEC_SNAPPY = 0x02
37
+ CODEC_LZ4 = 0x03
38
+ CODEC_ZSTD = 0x04
39
+ TIMESTAMP_TYPE_MASK = 0x08
40
+ HEADER_SIZE = 22 # crc(4), magic(1), attributes(1), timestamp(8), key+value size(4*2)
41
+
42
+ def __init__(self, value, key=None, magic=0, attributes=0, crc=0,
43
+ timestamp=None):
44
+ assert value is None or isinstance(value, bytes), 'value must be bytes'
45
+ assert key is None or isinstance(key, bytes), 'key must be bytes'
46
+ assert magic > 0 or timestamp is None, 'timestamp not supported in v0'
47
+
48
+ # Default timestamp to now for v1 messages
49
+ if magic > 0 and timestamp is None:
50
+ timestamp = int(time.time() * 1000)
51
+ self.timestamp = timestamp
52
+ self.crc = crc
53
+ self._validated_crc = None
54
+ self.magic = magic
55
+ self.attributes = attributes
56
+ self.key = key
57
+ self.value = value
58
+ self.encode = WeakMethod(self._encode_self)
59
+
60
+ @property
61
+ def timestamp_type(self):
62
+ """0 for CreateTime; 1 for LogAppendTime; None if unsupported.
63
+
64
+ Value is determined by broker; produced messages should always set to 0
65
+ Requires Kafka >= 0.10 / message version >= 1
66
+ """
67
+ if self.magic == 0:
68
+ return None
69
+ elif self.attributes & self.TIMESTAMP_TYPE_MASK:
70
+ return 1
71
+ else:
72
+ return 0
73
+
74
+ def _encode_self(self, recalc_crc=True):
75
+ version = self.magic
76
+ if version == 1:
77
+ fields = (self.crc, self.magic, self.attributes, self.timestamp, self.key, self.value)
78
+ elif version == 0:
79
+ fields = (self.crc, self.magic, self.attributes, self.key, self.value)
80
+ else:
81
+ raise ValueError('Unrecognized message version: %s' % (version,))
82
+ message = Message.SCHEMAS[version].encode(fields)
83
+ if not recalc_crc:
84
+ return message
85
+ self.crc = crc32(message[4:])
86
+ crc_field = self.SCHEMAS[version].fields[0]
87
+ return crc_field.encode(self.crc) + message[4:]
88
+
89
+ @classmethod
90
+ def decode(cls, data):
91
+ _validated_crc = None
92
+ if isinstance(data, bytes):
93
+ _validated_crc = crc32(data[4:])
94
+ data = io.BytesIO(data)
95
+ # Partial decode required to determine message version
96
+ base_fields = cls.SCHEMAS[0].fields[0:3]
97
+ crc, magic, attributes = [field.decode(data) for field in base_fields]
98
+ remaining = cls.SCHEMAS[magic].fields[3:]
99
+ fields = [field.decode(data) for field in remaining]
100
+ if magic == 1:
101
+ timestamp = fields[0]
102
+ else:
103
+ timestamp = None
104
+ msg = cls(fields[-1], key=fields[-2],
105
+ magic=magic, attributes=attributes, crc=crc,
106
+ timestamp=timestamp)
107
+ msg._validated_crc = _validated_crc
108
+ return msg
109
+
110
+ def validate_crc(self):
111
+ if self._validated_crc is None:
112
+ raw_msg = self._encode_self(recalc_crc=False)
113
+ self._validated_crc = crc32(raw_msg[4:])
114
+ if self.crc == self._validated_crc:
115
+ return True
116
+ return False
117
+
118
+ def is_compressed(self):
119
+ return self.attributes & self.CODEC_MASK != 0
120
+
121
+ def decompress(self):
122
+ codec = self.attributes & self.CODEC_MASK
123
+ assert codec in (self.CODEC_GZIP, self.CODEC_SNAPPY, self.CODEC_LZ4, self.CODEC_ZSTD)
124
+ if codec == self.CODEC_GZIP:
125
+ assert has_gzip(), 'Gzip decompression unsupported'
126
+ raw_bytes = gzip_decode(self.value)
127
+ elif codec == self.CODEC_SNAPPY:
128
+ assert has_snappy(), 'Snappy decompression unsupported'
129
+ raw_bytes = snappy_decode(self.value)
130
+ elif codec == self.CODEC_LZ4:
131
+ assert has_lz4(), 'LZ4 decompression unsupported'
132
+ if self.magic == 0:
133
+ raw_bytes = lz4_decode_old_kafka(self.value)
134
+ else:
135
+ raw_bytes = lz4_decode(self.value)
136
+ elif codec == self.CODEC_ZSTD:
137
+ assert has_zstd(), "ZSTD decompression unsupported"
138
+ raw_bytes = zstd_decode(self.value)
139
+ else:
140
+ raise Exception('This should be impossible')
141
+
142
+ return MessageSet.decode(raw_bytes, bytes_to_read=len(raw_bytes))
143
+
144
+ def __hash__(self):
145
+ return hash(self._encode_self(recalc_crc=False))
146
+
147
+
148
+ class PartialMessage(bytes):
149
+ def __repr__(self):
150
+ return 'PartialMessage(%s)' % (self,)
151
+
152
+
153
+ class MessageSet(AbstractType):
154
+ ITEM = Schema(
155
+ ('offset', Int64),
156
+ ('message', Bytes)
157
+ )
158
+ HEADER_SIZE = 12 # offset + message_size
159
+
160
+ @classmethod
161
+ def encode(cls, items, prepend_size=True):
162
+ # RecordAccumulator encodes messagesets internally
163
+ if isinstance(items, (io.BytesIO, KafkaBytes)):
164
+ size = Int32.decode(items)
165
+ if prepend_size:
166
+ # rewind and return all the bytes
167
+ items.seek(items.tell() - 4)
168
+ size += 4
169
+ return items.read(size)
170
+
171
+ encoded_values = []
172
+ for (offset, message) in items:
173
+ encoded_values.append(Int64.encode(offset))
174
+ encoded_values.append(Bytes.encode(message))
175
+ encoded = b''.join(encoded_values)
176
+ if prepend_size:
177
+ return Bytes.encode(encoded)
178
+ else:
179
+ return encoded
180
+
181
+ @classmethod
182
+ def decode(cls, data, bytes_to_read=None):
183
+ """Compressed messages should pass in bytes_to_read (via message size)
184
+ otherwise, we decode from data as Int32
185
+ """
186
+ if isinstance(data, bytes):
187
+ data = io.BytesIO(data)
188
+ if bytes_to_read is None:
189
+ bytes_to_read = Int32.decode(data)
190
+
191
+ # if FetchRequest max_bytes is smaller than the available message set
192
+ # the server returns partial data for the final message
193
+ # So create an internal buffer to avoid over-reading
194
+ raw = io.BytesIO(data.read(bytes_to_read))
195
+
196
+ items = []
197
+ while bytes_to_read:
198
+ try:
199
+ offset = Int64.decode(raw)
200
+ msg_bytes = Bytes.decode(raw)
201
+ bytes_to_read -= 8 + 4 + len(msg_bytes)
202
+ items.append((offset, len(msg_bytes), Message.decode(msg_bytes)))
203
+ except ValueError:
204
+ # PartialMessage to signal that max_bytes may be too small
205
+ items.append((None, None, PartialMessage()))
206
+ break
207
+ return items
208
+
209
+ @classmethod
210
+ def repr(cls, messages):
211
+ if isinstance(messages, (KafkaBytes, io.BytesIO)):
212
+ offset = messages.tell()
213
+ decoded = cls.decode(messages)
214
+ messages.seek(offset)
215
+ messages = decoded
216
+ return str([cls.ITEM.repr(m) for m in messages])