-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
KafkaEmbedded.java
465 lines (399 loc) · 13.9 KB
/
KafkaEmbedded.java
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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
/*
* Copyright 2015-2017 the original author or authors.
*
* Licensed 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.
*/
package org.springframework.kafka.test.rule;
import static org.assertj.core.api.Assertions.assertThat;
import java.net.ServerSocket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import javax.net.ServerSocketFactory;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.exception.ZkInterruptedException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerRebalanceListener;
import org.apache.kafka.common.Node;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.protocol.Errors;
import org.apache.kafka.common.requests.MetadataResponse;
import org.apache.kafka.common.utils.Time;
import org.junit.rules.ExternalResource;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.kafka.test.core.BrokerAddress;
import org.springframework.retry.RetryCallback;
import org.springframework.retry.RetryContext;
import org.springframework.retry.backoff.ExponentialBackOffPolicy;
import org.springframework.retry.policy.SimpleRetryPolicy;
import org.springframework.retry.support.RetryTemplate;
import kafka.admin.AdminUtils;
import kafka.admin.AdminUtils$;
import kafka.server.KafkaConfig;
import kafka.server.KafkaConfig$;
import kafka.server.KafkaServer;
import kafka.server.NotRunning;
import kafka.utils.CoreUtils;
import kafka.utils.TestUtils;
import kafka.utils.ZKStringSerializer$;
import kafka.utils.ZkUtils;
import kafka.zk.EmbeddedZookeeper;
import scala.collection.JavaConversions;
import scala.collection.Set;
/**
* The {@link KafkaRule} implementation for the embedded Kafka Broker and Zookeeper.
*
* @author Marius Bogoevici
* @author Artem Bilan
* @author Gary Russell
*/
@SuppressWarnings("serial")
public class KafkaEmbedded extends ExternalResource implements KafkaRule, InitializingBean, DisposableBean {
private static final Log logger = LogFactory.getLog(KafkaEmbedded.class);
public static final String BEAN_NAME = "kafkaEmbedded";
public static final String SPRING_EMBEDDED_KAFKA_BROKERS = "spring.embedded.kafka.brokers";
public static final long METADATA_PROPAGATION_TIMEOUT = 10000L;
private final int count;
private final boolean controlledShutdown;
private final String[] topics;
private final int partitionsPerTopic;
private final List<KafkaServer> kafkaServers = new ArrayList<>();
private EmbeddedZookeeper zookeeper;
private ZkClient zookeeperClient;
private String zkConnect;
private Map<String, String> brokerProperties;
public KafkaEmbedded(int count) {
this(count, false);
}
/**
* Create embedded Kafka brokers.
* @param count the number of brokers.
* @param controlledShutdown passed into TestUtils.createBrokerConfig.
* @param topics the topics to create (2 partitions per).
*/
public KafkaEmbedded(int count, boolean controlledShutdown, String... topics) {
this(count, controlledShutdown, 2, topics);
}
/**
*
* Create embedded Kafka brokers.
* @param count the number of brokers.
* @param controlledShutdown passed into TestUtils.createBrokerConfig.
* @param partitions partitions per topic.
* @param topics the topics to create.
*/
public KafkaEmbedded(int count, boolean controlledShutdown, int partitions, String... topics) {
this.count = count;
this.controlledShutdown = controlledShutdown;
if (topics != null) {
this.topics = topics;
}
else {
this.topics = new String[0];
}
this.partitionsPerTopic = partitions;
}
/**
* Specify the properties to configure Kafka Broker before start, e.g.
* {@code auto.create.topics.enable}, {@code transaction.state.log.replication.factor} etc.
* @param brokerProperties the properties to use for configuring Kafka Broker(s).
* @return this for chaining configuration
* @see KafkaConfig
*/
public KafkaEmbedded brokerProperties(Map<String, String> brokerProperties) {
this.brokerProperties = brokerProperties;
return this;
}
@Override
public void afterPropertiesSet() throws Exception {
before();
}
@Override
public void before() throws Exception { //NOSONAR
startZookeeper();
int zkConnectionTimeout = 6000;
int zkSessionTimeout = 6000;
this.zkConnect = "127.0.0.1:" + this.zookeeper.port();
this.zookeeperClient = new ZkClient(this.zkConnect, zkSessionTimeout, zkConnectionTimeout,
ZKStringSerializer$.MODULE$);
this.kafkaServers.clear();
for (int i = 0; i < this.count; i++) {
ServerSocket ss = ServerSocketFactory.getDefault().createServerSocket(0);
int randomPort = ss.getLocalPort();
ss.close();
Properties brokerConfigProperties = TestUtils.createBrokerConfig(i, this.zkConnect, this.controlledShutdown,
true, randomPort,
scala.Option.apply(null),
scala.Option.apply(null),
scala.Option.apply(null),
true, false, 0, false, 0, false, 0, scala.Option.apply(null));
brokerConfigProperties.setProperty(KafkaConfig$.MODULE$.PortProp(), "" + randomPort);
brokerConfigProperties.setProperty("replica.socket.timeout.ms", "1000");
brokerConfigProperties.setProperty("controller.socket.timeout.ms", "1000");
brokerConfigProperties.setProperty("offsets.topic.replication.factor", "1");
if (this.brokerProperties != null) {
this.brokerProperties.forEach(brokerConfigProperties::setProperty);
}
KafkaServer server = TestUtils.createServer(new KafkaConfig(brokerConfigProperties), Time.SYSTEM);
this.kafkaServers.add(server);
}
ZkUtils zkUtils = new ZkUtils(getZkClient(), null, false);
Properties props = new Properties();
for (String topic : this.topics) {
AdminUtils.createTopic(zkUtils, topic, this.partitionsPerTopic, this.count, props, null);
}
System.setProperty(SPRING_EMBEDDED_KAFKA_BROKERS, getBrokersAsString());
}
@Override
public void destroy() throws Exception {
after();
}
@Override
public void after() {
System.getProperties().remove(SPRING_EMBEDDED_KAFKA_BROKERS);
for (KafkaServer kafkaServer : this.kafkaServers) {
try {
if (kafkaServer.brokerState().currentState() != (NotRunning.state())) {
kafkaServer.shutdown();
kafkaServer.awaitShutdown();
}
}
catch (Exception e) {
// do nothing
}
try {
CoreUtils.delete(kafkaServer.config().logDirs());
}
catch (Exception e) {
// do nothing
}
}
try {
this.zookeeperClient.close();
}
catch (ZkInterruptedException e) {
// do nothing
}
try {
this.zookeeper.shutdown();
}
catch (Exception e) {
// do nothing
}
}
@Override
public List<KafkaServer> getKafkaServers() {
return this.kafkaServers;
}
public KafkaServer getKafkaServer(int id) {
return this.kafkaServers.get(id);
}
public EmbeddedZookeeper getZookeeper() {
return this.zookeeper;
}
@Override
public ZkClient getZkClient() {
return this.zookeeperClient;
}
@Override
public String getZookeeperConnectionString() {
return this.zkConnect;
}
public BrokerAddress getBrokerAddress(int i) {
KafkaServer kafkaServer = this.kafkaServers.get(i);
return new BrokerAddress("127.0.0.1", kafkaServer.config().port());
}
@Override
public BrokerAddress[] getBrokerAddresses() {
List<BrokerAddress> addresses = new ArrayList<BrokerAddress>();
for (KafkaServer kafkaServer : this.kafkaServers) {
addresses.add(new BrokerAddress("127.0.0.1", kafkaServer.config().port()));
}
return addresses.toArray(new BrokerAddress[addresses.size()]);
}
@Override
public int getPartitionsPerTopic() {
return this.partitionsPerTopic;
}
public void bounce(BrokerAddress brokerAddress) {
for (KafkaServer kafkaServer : getKafkaServers()) {
if (brokerAddress.equals(new BrokerAddress(kafkaServer.config().hostName(), kafkaServer.config().port()))) {
kafkaServer.shutdown();
kafkaServer.awaitShutdown();
}
}
}
public void startZookeeper() {
this.zookeeper = new EmbeddedZookeeper();
}
public void bounce(int index, boolean waitForPropagation) {
this.kafkaServers.get(index).shutdown();
if (waitForPropagation) {
long initialTime = System.currentTimeMillis();
boolean canExit = false;
do {
try {
Thread.sleep(100);
}
catch (InterruptedException e) {
break;
}
canExit = true;
ZkUtils zkUtils = new ZkUtils(getZkClient(), null, false);
scala.collection.Map<String, Properties> topicProperties =
AdminUtils$.MODULE$.fetchAllTopicConfigs(zkUtils);
Set<MetadataResponse.TopicMetadata> topicMetadatas =
AdminUtils$.MODULE$.fetchTopicMetadataFromZk(topicProperties.keySet(), zkUtils);
for (MetadataResponse.TopicMetadata topicMetadata : JavaConversions.asJavaCollection(topicMetadatas)) {
if (Errors.forCode(topicMetadata.error().code()).exception() == null) {
for (MetadataResponse.PartitionMetadata partitionMetadata : topicMetadata.partitionMetadata()) {
Collection<Node> inSyncReplicas = partitionMetadata.isr();
for (Node node : inSyncReplicas) {
if (node.id() == index) {
canExit = false;
}
}
}
}
}
}
while (!canExit && (System.currentTimeMillis() - initialTime < METADATA_PROPAGATION_TIMEOUT));
}
}
public void bounce(int index) {
bounce(index, true);
}
public void restart(final int index) throws Exception { //NOSONAR
// retry restarting repeatedly, first attempts may fail
SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy(10,
Collections.<Class<? extends Throwable>, Boolean>singletonMap(Exception.class, true));
ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
backOffPolicy.setInitialInterval(100);
backOffPolicy.setMaxInterval(1000);
backOffPolicy.setMultiplier(2);
RetryTemplate retryTemplate = new RetryTemplate();
retryTemplate.setRetryPolicy(retryPolicy);
retryTemplate.setBackOffPolicy(backOffPolicy);
retryTemplate.execute(new RetryCallback<Void, Exception>() {
@Override
public Void doWithRetry(RetryContext context) throws Exception { //NOSONAR
KafkaEmbedded.this.kafkaServers.get(index).startup();
return null;
}
});
}
public void waitUntilSynced(String topic, int brokerId) {
long initialTime = System.currentTimeMillis();
boolean canExit = false;
do {
try {
Thread.sleep(100);
}
catch (InterruptedException e) {
break;
}
canExit = true;
ZkUtils zkUtils = new ZkUtils(getZkClient(), null, false);
MetadataResponse.TopicMetadata topicMetadata = AdminUtils$.MODULE$.fetchTopicMetadataFromZk(topic, zkUtils);
if (Errors.forCode(topicMetadata.error().code()).exception() == null) {
for (MetadataResponse.PartitionMetadata partitionMetadata : topicMetadata.partitionMetadata()) {
Collection<Node> isr = partitionMetadata.isr();
boolean containsIndex = false;
for (Node node : isr) {
if (node.id() == brokerId) {
containsIndex = true;
}
}
if (!containsIndex) {
canExit = false;
}
}
}
}
while (!canExit && (System.currentTimeMillis() - initialTime < METADATA_PROPAGATION_TIMEOUT));
}
@Override
public String getBrokersAsString() {
StringBuilder builder = new StringBuilder();
for (BrokerAddress brokerAddress : getBrokerAddresses()) {
builder.append(brokerAddress.toString()).append(',');
}
return builder.substring(0, builder.length() - 1);
}
@Override
public boolean isEmbedded() {
return true;
}
/**
* Subscribe a consumer to all the embedded topics.
* @param consumer the consumer.
* @throws Exception an exception.
*/
public void consumeFromAllEmbeddedTopics(Consumer<?, ?> consumer) throws Exception {
final CountDownLatch consumerLatch = new CountDownLatch(1);
consumer.subscribe(Arrays.asList(this.topics), new ConsumerRebalanceListener() {
@Override
public void onPartitionsRevoked(Collection<TopicPartition> partitions) {
}
@Override
public void onPartitionsAssigned(Collection<TopicPartition> partitions) {
consumerLatch.countDown();
}
});
consumer.poll(0); // force assignment
assertThat(consumerLatch.await(30, TimeUnit.SECONDS))
.as("Failed to be assigned partitions from the embedded topics")
.isTrue();
}
/**
* Subscribe a consumer to one of the embedded topics.
* @param consumer the consumer.
* @param topic the topic.
* @throws Exception an exception.
*/
public void consumeFromAnEmbeddedTopic(Consumer<?, ?> consumer, String topic) throws Exception {
consumeFromEmbeddedTopics(consumer, topic);
}
/**
* Subscribe a consumer to one or more of the embedded topics.
* @param consumer the consumer.
* @param topics the topics.
* @throws Exception an exception.
*/
public void consumeFromEmbeddedTopics(Consumer<?, ?> consumer, String... topics) throws Exception {
for (String topic : topics) {
assertThat(this.topics).as("topic '" + topic + "' is not in embedded topic list").contains(topic);
}
consumer.subscribe(Arrays.asList(topics), new ConsumerRebalanceListener() {
@Override
public void onPartitionsRevoked(Collection<TopicPartition> partitions) {
}
@Override
public void onPartitionsAssigned(Collection<TopicPartition> partitions) {
if (logger.isDebugEnabled()) {
logger.debug("partitions assigned: " + partitions);
}
}
});
logger.debug("Subscription Initiated");
}
}