-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
kafka.py
254 lines (210 loc) · 10.2 KB
/
kafka.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""Unbounded source and sink transforms for
`Kafka <href="http://kafka.apache.org/>`_.
These transforms are currently supported by Beam portable runners (for
example, portable Flink and Spark) as well as Dataflow runner.
**Setup**
Transforms provided in this module are cross-language transforms
implemented in the Beam Java SDK. During the pipeline construction, Python SDK
will connect to a Java expansion service to expand these transforms.
To facilitate this, a small amount of setup is needed before using these
transforms in a Beam Python pipeline.
There are several ways to setup cross-language Kafka transforms.
* Option 1: use the default expansion service
* Option 2: specify a custom expansion service
See below for details regarding each of these options.
*Option 1: Use the default expansion service*
This is the recommended and easiest setup option for using Python Kafka
transforms. This option is only available for Beam 2.22.0 and later.
This option requires following pre-requisites before running the Beam
pipeline.
* Install Java runtime in the computer from where the pipeline is constructed
and make sure that 'java' command is available.
In this option, Python SDK will either download (for released Beam version) or
build (when running from a Beam Git clone) an expansion service jar and use
that to expand transforms. Currently Kafka transforms use the
'beam-sdks-java-io-expansion-service' jar for this purpose.
*Option 2: specify a custom expansion service*
In this option, you startup your own expansion service and provide that as
a parameter when using the transforms provided in this module.
This option requires following pre-requisites before running the Beam
pipeline.
* Startup your own expansion service.
* Update your pipeline to provide the expansion service address when
initiating Kafka transforms provided in this module.
Flink Users can use the built-in Expansion Service of the Flink Runner's
Job Server. If you start Flink's Job Server, the expansion service will be
started on port 8097. For a different address, please set the
expansion_service parameter.
**More information**
For more information regarding cross-language transforms see:
- https://beam.apache.org/roadmap/portability/
For more information specific to Flink runner see:
- https://beam.apache.org/documentation/runners/flink/
"""
# pytype: skip-file
import typing
from apache_beam.transforms.external import BeamJarExpansionService
from apache_beam.transforms.external import ExternalTransform
from apache_beam.transforms.external import NamedTupleBasedPayloadBuilder
ReadFromKafkaSchema = typing.NamedTuple(
'ReadFromKafkaSchema',
[('consumer_config', typing.Mapping[str, str]),
('topics', typing.List[str]), ('key_deserializer', str),
('value_deserializer', str), ('start_read_time', typing.Optional[int]),
('max_num_records', typing.Optional[int]),
('max_read_time', typing.Optional[int]),
('commit_offset_in_finalize', bool), ('timestamp_policy', str)])
def default_io_expansion_service(append_args=None):
return BeamJarExpansionService(
'sdks:java:io:expansion-service:shadowJar', append_args=append_args)
class ReadFromKafka(ExternalTransform):
"""
An external PTransform which reads from Kafka and returns a KV pair for
each item in the specified Kafka topics. If no Kafka Deserializer for
key/value is provided, then the data will be returned as a raw byte array.
Experimental; no backwards compatibility guarantees.
"""
# Returns the key/value data as raw byte arrays
byte_array_deserializer = (
'org.apache.kafka.common.serialization.ByteArrayDeserializer')
processing_time_policy = 'ProcessingTime'
create_time_policy = 'CreateTime'
log_append_time = 'LogAppendTime'
URN_WITH_METADATA = (
'beam:transform:org.apache.beam:kafka_read_with_metadata:v1')
URN_WITHOUT_METADATA = (
'beam:transform:org.apache.beam:kafka_read_without_metadata:v1')
def __init__(
self,
consumer_config,
topics,
key_deserializer=byte_array_deserializer,
value_deserializer=byte_array_deserializer,
start_read_time=None,
max_num_records=None,
max_read_time=None,
commit_offset_in_finalize=False,
timestamp_policy=processing_time_policy,
with_metadata=False,
expansion_service=None,
):
"""
Initializes a read operation from Kafka.
:param consumer_config: A dictionary containing the consumer configuration.
:param topics: A list of topic strings.
:param key_deserializer: A fully-qualified Java class name of a Kafka
Deserializer for the topic's key, e.g.
'org.apache.kafka.common.serialization.LongDeserializer'.
Default: 'org.apache.kafka.common.serialization.ByteArrayDeserializer'.
:param value_deserializer: A fully-qualified Java class name of a Kafka
Deserializer for the topic's value, e.g.
'org.apache.kafka.common.serialization.LongDeserializer'.
Default: 'org.apache.kafka.common.serialization.ByteArrayDeserializer'.
:param start_read_time: Use timestamp to set up start offset in milliseconds
epoch.
:param max_num_records: Maximum amount of records to be read. Mainly used
for tests and demo applications.
:param max_read_time: Maximum amount of time in seconds the transform
executes. Mainly used for tests and demo applications.
:param commit_offset_in_finalize: Whether to commit offsets when finalizing.
:param timestamp_policy: The built-in timestamp policy which is used for
extracting timestamp from KafkaRecord.
:param with_metadata: whether the returned PCollection should contain
Kafka related metadata or not. If False (default), elements of the
returned PCollection will be of type 'bytes' if True, elements of the
returned PCollection will be of the type 'Row'. Note that, currently
this only works when using default key and value deserializers where
Java Kafka Reader reads keys and values as 'byte[]'.
:param expansion_service: The address (host:port) of the ExpansionService.
"""
if timestamp_policy not in [ReadFromKafka.processing_time_policy,
ReadFromKafka.create_time_policy,
ReadFromKafka.log_append_time]:
raise ValueError(
'timestamp_policy should be one of '
'[ProcessingTime, CreateTime, LogAppendTime]')
super().__init__(
self.URN_WITH_METADATA if with_metadata else self.URN_WITHOUT_METADATA,
NamedTupleBasedPayloadBuilder(
ReadFromKafkaSchema(
consumer_config=consumer_config,
topics=topics,
key_deserializer=key_deserializer,
value_deserializer=value_deserializer,
max_num_records=max_num_records,
max_read_time=max_read_time,
start_read_time=start_read_time,
commit_offset_in_finalize=commit_offset_in_finalize,
timestamp_policy=timestamp_policy)),
expansion_service or default_io_expansion_service(
append_args=['--experiments=use_unbounded_sdf_wrapper']))
# TODO(https://github.com/apache/beam/issues/21730): remove
# 'use_unbounded_sdf_wrapper' which opts default expansion
# service into using SDF wrapped legacy Kafka source instead of pure SDF
# Kafka source.
WriteToKafkaSchema = typing.NamedTuple(
'WriteToKafkaSchema',
[
('producer_config', typing.Mapping[str, str]),
('topic', str),
('key_serializer', str),
('value_serializer', str),
])
class WriteToKafka(ExternalTransform):
"""
An external PTransform which writes KV data to a specified Kafka topic.
If no Kafka Serializer for key/value is provided, then key/value are
assumed to be byte arrays.
Experimental; no backwards compatibility guarantees.
"""
# Default serializer which passes raw bytes to Kafka
byte_array_serializer = (
'org.apache.kafka.common.serialization.ByteArraySerializer')
URN = 'beam:transform:org.apache.beam:kafka_write:v1'
def __init__(
self,
producer_config,
topic,
key_serializer=byte_array_serializer,
value_serializer=byte_array_serializer,
expansion_service=None):
"""
Initializes a write operation to Kafka.
:param producer_config: A dictionary containing the producer configuration.
:param topic: A Kafka topic name.
:param key_deserializer: A fully-qualified Java class name of a Kafka
Serializer for the topic's key, e.g.
'org.apache.kafka.common.serialization.LongSerializer'.
Default: 'org.apache.kafka.common.serialization.ByteArraySerializer'.
:param value_deserializer: A fully-qualified Java class name of a Kafka
Serializer for the topic's value, e.g.
'org.apache.kafka.common.serialization.LongSerializer'.
Default: 'org.apache.kafka.common.serialization.ByteArraySerializer'.
:param expansion_service: The address (host:port) of the ExpansionService.
"""
super().__init__(
self.URN,
NamedTupleBasedPayloadBuilder(
WriteToKafkaSchema(
producer_config=producer_config,
topic=topic,
key_serializer=key_serializer,
value_serializer=value_serializer,
)),
expansion_service or default_io_expansion_service())