You are viewing a plain text version of this content. The canonical link for it is here.
Posted to jira@kafka.apache.org by GitBox <gi...@apache.org> on 2020/08/26 17:20:23 UTC
[GitHub] [kafka] ning2008wisc opened a new pull request #9224: improve MM2 unit tests
ning2008wisc opened a new pull request #9224:
URL: https://github.com/apache/kafka/pull/9224
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc commented on a change in pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc commented on a change in pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#discussion_r535386444
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationBaseTest.java
##########
@@ -0,0 +1,617 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.Config;
+import org.apache.kafka.clients.admin.ConfigEntry;
+import org.apache.kafka.clients.admin.DescribeConfigsResult;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.clients.CommonClientConfigs;
+import org.apache.kafka.common.config.ConfigResource;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.config.SslConfigs;
+import org.apache.kafka.common.config.types.Password;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.connector.Connector;
+import org.apache.kafka.connect.mirror.MirrorClient;
+import org.apache.kafka.connect.mirror.MirrorHeartbeatConnector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.MirrorSourceConnector;
+import org.apache.kafka.connect.mirror.SourceAndTarget;
+import org.apache.kafka.connect.mirror.MirrorCheckpointConnector;
+import org.apache.kafka.connect.util.clusters.EmbeddedConnectCluster;
+import org.apache.kafka.connect.util.clusters.EmbeddedKafkaCluster;
+import org.apache.kafka.test.IntegrationTest;
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertNotNull;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import static org.apache.kafka.connect.mirror.TestUtils.generateRecords;
+
+/**
+ * Tests MM2 replication and failover/failback logic.
+ *
+ * MM2 is configured with active/active replication between two Kafka clusters. Tests validate that
+ * records sent to either cluster arrive at the other cluster. Then, a consumer group is migrated from
+ * one cluster to the other and back. Tests validate that consumer offsets are translated and replicated
+ * between clusters during this failover and failback.
+ */
+@Category(IntegrationTest.class)
+public abstract class MirrorConnectorsIntegrationBaseTest {
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationBaseTest.class);
+
+ private static final int NUM_RECORDS_PER_PARTITION = 10;
+ private static final int NUM_PARTITIONS = 10;
+ private static final int NUM_RECORDS_PRODUCED = NUM_PARTITIONS * NUM_RECORDS_PER_PARTITION;
+ private static final int RECORD_TRANSFER_DURATION_MS = 30_000;
+ private static final int CHECKPOINT_DURATION_MS = 20_000;
+ private static final int RECORD_CONSUME_DURATION_MS = 20_000;
+ private static final int OFFSET_SYNC_DURATION_MS = 30_000;
+ private static final int NUM_WORKERS = 3;
+ private static final int CONSUMER_POLL_TIMEOUT_MS = 500;
+ private static final int BROKER_RESTART_TIMEOUT_MS = 10_000;
+ private static final long DEFAULT_PRODUCE_SEND_DURATION_MS = TimeUnit.SECONDS.toMillis(120);
+ private static final String PRIMARY_CLUSTER_ALIAS = "primary";
+ private static final String BACKUP_CLUSTER_ALIAS = "backup";
+ private static final List<Class<? extends Connector>> CONNECTOR_LIST =
+ Arrays.asList(MirrorSourceConnector.class, MirrorCheckpointConnector.class, MirrorHeartbeatConnector.class);
+
+ private Map<String, String> mm2Props;
+ private MirrorMakerConfig mm2Config;
+ private EmbeddedConnectCluster primary;
+ private EmbeddedConnectCluster backup;
+
+ private final AtomicBoolean exited = new AtomicBoolean(false);
+ protected Properties primaryBrokerProps = new Properties();
+ protected Properties backupBrokerProps = new Properties();
+ private Map<String, String> primaryWorkerProps = new HashMap<>();
+ private Map<String, String> backupWorkerProps = new HashMap<>();
+ abstract Map<String, Object> getSslConfig();
+
+ protected void startClusters() throws InterruptedException {
+ primaryBrokerProps.put("auto.create.topics.enable", "false");
+ backupBrokerProps.put("auto.create.topics.enable", "false");
+
+ mm2Props = basicMM2Config();
+
+ final Map<String, Object> sslConfig = getSslConfig();
+ if (sslConfig != null) {
+ Properties sslProps = new Properties();
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, sslConfig.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG));
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, ((Password) sslConfig.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)).value());
+ sslProps.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL");
+
+ // set SSL config for kafka connect worker
+ backupWorkerProps.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> BACKUP_CLUSTER_ALIAS + "." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ // set SSL config for producer used by source task in MM2
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> BACKUP_CLUSTER_ALIAS + ".producer." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ }
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+ primaryWorkerProps = mm2Config.workerConfig(new SourceAndTarget(BACKUP_CLUSTER_ALIAS, PRIMARY_CLUSTER_ALIAS));
+ backupWorkerProps.putAll(mm2Config.workerConfig(new SourceAndTarget(PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS)));
+
+ primary = new EmbeddedConnectCluster.Builder()
+ .name(PRIMARY_CLUSTER_ALIAS + "-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(primaryBrokerProps)
+ .workerProps(primaryWorkerProps)
+ .build();
+
+ backup = new EmbeddedConnectCluster.Builder()
+ .name(BACKUP_CLUSTER_ALIAS + "-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(backupBrokerProps)
+ .workerProps(backupWorkerProps)
+ .build();
+
+ primary.start();
+ primary.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of " + PRIMARY_CLUSTER_ALIAS + "-connect-cluster did not start in time.");
+
+ backup.start();
+ backup.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of " + BACKUP_CLUSTER_ALIAS + "-connect-cluster did not start in time.");
+
+ createTopics();
+
+ warmUpConsumer();
+
+ log.info(PRIMARY_CLUSTER_ALIAS + " REST service: {}", primary.endpointForResource("connectors"));
+ log.info(BACKUP_CLUSTER_ALIAS + " REST service: {}", backup.endpointForResource("connectors"));
+ log.info(PRIMARY_CLUSTER_ALIAS + " brokers: {}", primary.kafka().bootstrapServers());
+ log.info(BACKUP_CLUSTER_ALIAS + " brokers: {}", backup.kafka().bootstrapServers());
+
+ // now that the brokers are running, we can finish setting up the Connectors
+ mm2Props.put(PRIMARY_CLUSTER_ALIAS + ".bootstrap.servers", primary.kafka().bootstrapServers());
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + ".bootstrap.servers", backup.kafka().bootstrapServers());
+
+ Exit.setExitProcedure((status, errorCode) -> exited.set(true));
+ }
+
+ public void shutdownClusters() {
+ for (String x : primary.connectors()) {
+ primary.deleteConnector(x);
+ }
+ for (String x : backup.connectors()) {
+ backup.deleteConnector(x);
+ }
+ deleteAllTopics(primary.kafka());
+ deleteAllTopics(backup.kafka());
+ primary.stop();
+ backup.stop();
+ try {
+ assertFalse(exited.get());
+ } finally {
+ Exit.resetExitProcedure();
+ }
+ }
+
+ @Test
+ public void testReplication() throws InterruptedException {
+ produceMessages(primary, "test-topic-1");
+ produceMessages(backup, "test-topic-1");
+ String consumerGroupName = "consumer-group-testReplication";
+ Map<String, Object> consumerProps = new HashMap<String, Object>() {{
+ put("group.id", consumerGroupName);
+ put("auto.offset.reset", "latest");
+ }};
+ // create consumers before starting the connectors so we don't need to wait for discovery
+ Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps, "test-topic-1");
+ waitForConsumingAllRecords(primaryConsumer, 0);
+
+ Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(consumerProps, "test-topic-1");
+ waitForConsumingAllRecords(backupConsumer, 0);
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS);
+ waitUntilMirrorMakerIsRunning(primary, CONNECTOR_LIST, mm2Config, BACKUP_CLUSTER_ALIAS, PRIMARY_CLUSTER_ALIAS);
+
+ MirrorClient primaryClient = new MirrorClient(mm2Config.clientConfig(PRIMARY_CLUSTER_ALIAS));
+ MirrorClient backupClient = new MirrorClient(mm2Config.clientConfig(BACKUP_CLUSTER_ALIAS));
+
+ assertEquals("topic config was not synced", TopicConfig.CLEANUP_POLICY_COMPACT,
+ getTopicConfig(backup.kafka(), "primary.test-topic-1", TopicConfig.CLEANUP_POLICY_CONFIG));
+
+ assertEquals("Records were not produced to primary cluster.", NUM_RECORDS_PRODUCED,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "test-topic-1").count());
+ assertEquals("Records were not replicated to backup cluster.", NUM_RECORDS_PRODUCED,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "primary.test-topic-1").count());
+ assertEquals("Records were not produced to backup cluster.", NUM_RECORDS_PRODUCED,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "test-topic-1").count());
+ assertEquals("Records were not replicated to primary cluster.", NUM_RECORDS_PRODUCED,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "backup.test-topic-1").count());
+
+ assertEquals("Primary cluster doesn't have all records from both clusters.", NUM_RECORDS_PRODUCED * 2,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED * 2, RECORD_TRANSFER_DURATION_MS, "backup.test-topic-1", "test-topic-1").count());
+ assertEquals("Backup cluster doesn't have all records from both clusters.", NUM_RECORDS_PRODUCED * 2,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED * 2, RECORD_TRANSFER_DURATION_MS, "primary.test-topic-1", "test-topic-1").count());
+
+ assertTrue("Heartbeats were not emitted to primary cluster.", primary.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "heartbeats").count() > 0);
+ assertTrue("Heartbeats were not emitted to backup cluster.", backup.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "heartbeats").count() > 0);
+ assertTrue("Heartbeats were not replicated downstream to backup cluster.", backup.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "primary.heartbeats").count() > 0);
+ assertTrue("Heartbeats were not replicated downstream to primary cluster.", primary.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "backup.heartbeats").count() > 0);
+
+ assertTrue("Did not find upstream primary cluster.", backupClient.upstreamClusters().contains(PRIMARY_CLUSTER_ALIAS));
+ assertEquals("Did not calculate replication hops correctly.", 1, backupClient.replicationHops(PRIMARY_CLUSTER_ALIAS));
+ assertTrue("Did not find upstream backup cluster.", primaryClient.upstreamClusters().contains(BACKUP_CLUSTER_ALIAS));
+ assertEquals("Did not calculate replication hops correctly.", 1, primaryClient.replicationHops(BACKUP_CLUSTER_ALIAS));
+ assertTrue("Checkpoints were not emitted downstream to backup cluster.", backup.kafka().consume(1,
+ CHECKPOINT_DURATION_MS, "primary.checkpoints.internal").count() > 0);
+
+ Map<TopicPartition, OffsetAndMetadata> backupOffsets = backupClient.remoteConsumerOffsets(consumerGroupName, PRIMARY_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS));
+
+ assertTrue("Offsets not translated downstream to backup cluster. Found: " + backupOffsets, backupOffsets.containsKey(
+ new TopicPartition("primary.test-topic-1", 0)));
+
+ // Failover consumer group to backup cluster.
+ primaryConsumer = backup.kafka().createConsumer(Collections.singletonMap("group.id", consumerGroupName));
+ primaryConsumer.assign(backupOffsets.keySet());
+ backupOffsets.forEach(primaryConsumer::seek);
+ primaryConsumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+ primaryConsumer.commitAsync();
+
+ assertTrue("Consumer failedover to zero offset.", primaryConsumer.position(new TopicPartition("primary.test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedover beyond expected offset.", primaryConsumer.position(
+ new TopicPartition("primary.test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+ assertTrue("Checkpoints were not emitted upstream to primary cluster.", primary.kafka().consume(1,
+ CHECKPOINT_DURATION_MS, "backup.checkpoints.internal").count() > 0);
+
+ primaryConsumer.close();
+
+ waitForCondition(() -> {
+ try {
+ return primaryClient.remoteConsumerOffsets(consumerGroupName, BACKUP_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS)).containsKey(new TopicPartition("backup.test-topic-1", 0));
+ } catch (Throwable e) {
+ return false;
+ }
+ }, CHECKPOINT_DURATION_MS, "Offsets not translated downstream to primary cluster.");
+
+ waitForCondition(() -> {
+ try {
+ return primaryClient.remoteConsumerOffsets(consumerGroupName, BACKUP_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS)).containsKey(new TopicPartition("test-topic-1", 0));
+ } catch (Throwable e) {
+ return false;
+ }
+ }, CHECKPOINT_DURATION_MS, "Offsets not translated upstream to primary cluster.");
+
+ Map<TopicPartition, OffsetAndMetadata> primaryOffsets = primaryClient.remoteConsumerOffsets(consumerGroupName, BACKUP_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS));
+
+ // Failback consumer group to primary cluster
+ backupConsumer = primary.kafka().createConsumer(Collections.singletonMap("group.id", consumerGroupName));
+ backupConsumer.assign(primaryOffsets.keySet());
+ primaryOffsets.forEach(backupConsumer::seek);
+ backupConsumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+ backupConsumer.commitAsync();
+
+ assertTrue("Consumer failedback to zero upstream offset.", backupConsumer.position(new TopicPartition("test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedback to zero downstream offset.", backupConsumer.position(new TopicPartition("backup.test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedback beyond expected upstream offset.", backupConsumer.position(
+ new TopicPartition("test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+ assertTrue("Consumer failedback beyond expected downstream offset.", backupConsumer.position(
+ new TopicPartition("backup.test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+
+ backupConsumer.close();
+
+ // create more matching topics
+ primary.kafka().createTopic("test-topic-2", NUM_PARTITIONS);
+ backup.kafka().createTopic("test-topic-3", NUM_PARTITIONS);
+
+ // only produce messages to the first partition
+ produceMessages(primary, "test-topic-2", 1);
+ produceMessages(backup, "test-topic-3", 1);
+
+ // expect total consumed messages equals to NUM_RECORDS_PER_PARTITION
+ assertEquals("Records were not produced to primary cluster.", NUM_RECORDS_PER_PARTITION,
+ primary.kafka().consume(NUM_RECORDS_PER_PARTITION, RECORD_TRANSFER_DURATION_MS, "test-topic-2").count());
+ assertEquals("Records were not produced to backup cluster.", NUM_RECORDS_PER_PARTITION,
+ backup.kafka().consume(NUM_RECORDS_PER_PARTITION, RECORD_TRANSFER_DURATION_MS, "test-topic-3").count());
+
+ assertEquals("New topic was not replicated to primary cluster.", NUM_RECORDS_PER_PARTITION,
+ primary.kafka().consume(NUM_RECORDS_PER_PARTITION, 2 * RECORD_TRANSFER_DURATION_MS, "backup.test-topic-3").count());
+ assertEquals("New topic was not replicated to backup cluster.", NUM_RECORDS_PER_PARTITION,
+ backup.kafka().consume(NUM_RECORDS_PER_PARTITION, 2 * RECORD_TRANSFER_DURATION_MS, "primary.test-topic-2").count());
+
+ }
+
+ @Test
+ public void testReplicationWithEmptyPartition() throws Exception {
+ String consumerGroupName = "consumer-group-testReplicationWithEmptyPartition";
+ Map<String, Object> consumerProps = Collections.singletonMap("group.id", consumerGroupName);
+
+ // create topic
+ String topic = "test-topic-with-empty-partition";
+ primary.kafka().createTopic(topic, NUM_PARTITIONS);
+
+ // produce to all test-topic-empty's partitions, except the last partition
+ produceMessages(primary, topic, NUM_PARTITIONS - 1);
+
+ // consume before starting the connectors so we don't need to wait for discovery
+ int expectedRecords = NUM_RECORDS_PER_PARTITION * (NUM_PARTITIONS - 1);
+ try (Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps, topic)) {
+ waitForConsumingAllRecords(primaryConsumer, expectedRecords);
+ }
+
+ // one way replication from primary to backup
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + "->" + PRIMARY_CLUSTER_ALIAS + ".enabled", "false");
+ mm2Config = new MirrorMakerConfig(mm2Props);
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS);
+
+ // sleep few seconds to have MM2 finish replication so that "end" consumer will consume some record
+ Thread.sleep(TimeUnit.SECONDS.toMillis(3));
+
+ // consume all records from backup cluster
+ try (Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(consumerProps,
+ PRIMARY_CLUSTER_ALIAS + "." + topic)) {
+ waitForConsumingAllRecords(backupConsumer, expectedRecords);
+ }
+
+ Admin backupClient = backup.kafka().createAdminClient();
+ // retrieve the consumer group offset from backup cluster
+ Map<TopicPartition, OffsetAndMetadata> remoteOffsets =
+ backupClient.listConsumerGroupOffsets(consumerGroupName).partitionsToOffsetAndMetadata().get();
+ // pinpoint the offset of the last partition which does not receive records
+ OffsetAndMetadata offset = remoteOffsets.get(new TopicPartition(PRIMARY_CLUSTER_ALIAS + "." + topic, NUM_PARTITIONS - 1));
+ // offset of the last partition should exist, but its value should be 0
+ assertNotNull("Offset of last partition was not replicated", offset);
+ assertEquals("Offset of last partition is not zero", 0, offset.offset());
+ }
+
+ @Test
+ public void testOneWayReplicationWithAutoOffsetSync() throws InterruptedException {
+ produceMessages(primary, "test-topic-1");
+ String consumerGroupName = "consumer-group-testOneWayReplicationWithAutoOffsetSync";
+ Map<String, Object> consumerProps = new HashMap<String, Object>() {{
+ put("group.id", consumerGroupName);
+ put("auto.offset.reset", "earliest");
+ }};
+ // create consumers before starting the connectors so we don't need to wait for discovery
+ try (Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps,
+ "test-topic-1")) {
+ // we need to wait for consuming all the records for MM2 replicating the expected offsets
+ waitForConsumingAllRecords(primaryConsumer, NUM_RECORDS_PRODUCED);
+ }
+
+ // enable automated consumer group offset sync
+ mm2Props.put("sync.group.offsets.enabled", "true");
+ mm2Props.put("sync.group.offsets.interval.seconds", "1");
+ // one way replication from primary to backup
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + "->" + PRIMARY_CLUSTER_ALIAS + ".enabled", "false");
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS);
+
+ // create a consumer at backup cluster with same consumer group Id to consume 1 topic
+ Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(
+ consumerProps, "primary.test-topic-1");
+
+ waitForConsumerGroupOffsetSync(backup, backupConsumer, Collections.singletonList("primary.test-topic-1"),
+ consumerGroupName, NUM_RECORDS_PRODUCED);
+
+ ConsumerRecords<byte[], byte[]> records = backupConsumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+
+ // the size of consumer record should be zero, because the offsets of the same consumer group
+ // have been automatically synchronized from primary to backup by the background job, so no
+ // more records to consume from the replicated topic by the same consumer group at backup cluster
+ assertEquals("consumer record size is not zero", 0, records.count());
+
+ // now create a new topic in primary cluster
+ primary.kafka().createTopic("test-topic-2", NUM_PARTITIONS);
+ backup.kafka().createTopic("primary.test-topic-2", 1);
+ // produce some records to the new topic in primary cluster
+ produceMessages(primary, "test-topic-2");
+
+ // create a consumer at primary cluster to consume the new topic
+ try (Consumer<byte[], byte[]> consumer1 = primary.kafka().createConsumerAndSubscribeTo(Collections.singletonMap(
+ "group.id", "consumer-group-1"), "test-topic-2")) {
+ // we need to wait for consuming all the records for MM2 replicating the expected offsets
+ waitForConsumingAllRecords(consumer1, NUM_RECORDS_PRODUCED);
+ }
+
+ // create a consumer at backup cluster with same consumer group Id to consume old and new topic
+ backupConsumer = backup.kafka().createConsumerAndSubscribeTo(Collections.singletonMap(
+ "group.id", consumerGroupName), "primary.test-topic-1", "primary.test-topic-2");
+
+ waitForConsumerGroupOffsetSync(backup, backupConsumer, Arrays.asList("primary.test-topic-1", "primary.test-topic-2"),
+ consumerGroupName, NUM_RECORDS_PRODUCED);
+
+ records = backupConsumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+ // similar reasoning as above, no more records to consume by the same consumer group at backup cluster
+ assertEquals("consumer record size is not zero", 0, records.count());
+ backupConsumer.close();
+ }
+
+ /*
+ * launch the connectors on kafka connect cluster and check if they are running
+ */
+ private static void waitUntilMirrorMakerIsRunning(EmbeddedConnectCluster connectCluster,
+ List<Class<? extends Connector>> connectorClasses, MirrorMakerConfig mm2Config,
+ String primary, String backup) throws InterruptedException {
+ for (int i = 0; i < connectorClasses.size(); i++) {
+ String connector = connectorClasses.get(i).getSimpleName();
+ connectCluster.configureConnector(connector, mm2Config.connectorBaseConfig(
+ new SourceAndTarget(primary, backup), connectorClasses.get(i)));
+ }
+
+ // we wait for the connector and tasks to come up for each connector, so that when we do the
+ // actual testing, we are certain that the tasks are up and running; this will prevent
+ // flaky tests where the connector and tasks didn't start up in time for the tests to be run
+ List<String> connectorNames = connectorClasses.stream().map(x -> x.getSimpleName())
+ .collect(Collectors.toList());
+ for (String connector : connectorNames) {
+ connectCluster.assertions().assertConnectorAndAtLeastNumTasksAreRunning(connector, 1,
+ "Connector " + connector + " tasks did not start in time on cluster: " + connectCluster);
+ }
+ }
+
+ /*
+ * delete all topics of the input kafka cluster
+ */
+ private static void deleteAllTopics(EmbeddedKafkaCluster cluster) {
+ Admin client = cluster.createAdminClient();
+ try {
+ client.deleteTopics(client.listTopics().names().get());
+ } catch (Throwable e) {
+ // should not run into exception normally. In case of Exception,
+ // simply fail the test and investigate
+ }
+ }
+
+ /*
+ * retrieve the config value based on the input cluster, topic and config name
+ */
+ private static String getTopicConfig(EmbeddedKafkaCluster cluster, String topic, String configName) {
+ Admin client = cluster.createAdminClient();
+ Collection<ConfigResource> cr = Collections.singleton(
+ new ConfigResource(ConfigResource.Type.TOPIC, topic));
+ try {
+ DescribeConfigsResult configsResult = client.describeConfigs(cr);
+ Config allConfigs = (Config) configsResult.all().get().values().toArray()[0];
+ Iterator<ConfigEntry> configIterator = allConfigs.entries().iterator();
+ while (configIterator.hasNext()) {
+ ConfigEntry currentConfig = configIterator.next();
+ if (currentConfig.name().equals(configName)) {
+ return currentConfig.value();
+ }
+ }
+ } catch (Throwable e) {
+ // should not run into exception normally. In case of Exception,
+ // simply fail the test and investigate
+ }
+ return null;
+ }
+
+ /*
+ * produce messages to the cluster and topic
+ */
+ protected void produceMessages(EmbeddedConnectCluster cluster, String topicName) {
+ Map<String, String> recordSent = generateRecords(NUM_RECORDS_PRODUCED);
+ for (Map.Entry<String, String> entry : recordSent.entrySet()) {
+ cluster.kafka().produce(topicName, entry.getKey(), entry.getValue());
+ }
+ }
+
+ /*
+ * produce messages to the cluster and topic partition less than numPartitions
+ */
+ protected void produceMessages(EmbeddedConnectCluster cluster, String topicName, int numPartitions) {
+ int cnt = 0;
+ for (int r = 0; r < NUM_RECORDS_PER_PARTITION; r++)
+ for (int p = 0; p < numPartitions; p++)
+ cluster.kafka().produce(topicName, p, "key", "value-" + cnt++);
+ }
+
+ /*
+ * given consumer group, topics and expected number of records, make sure the consumer group
+ * offsets are eventually synced to the expected offset numbers
+ */
+ private static <T> void waitForConsumerGroupOffsetSync(EmbeddedConnectCluster connect,
+ Consumer<T, T> consumer, List<String> topics, String consumerGroupId, int numRecords)
+ throws InterruptedException {
+ Admin adminClient = connect.kafka().createAdminClient();
+ List<TopicPartition> tps = new ArrayList<>(NUM_PARTITIONS * topics.size());
+ for (int partitionIndex = 0; partitionIndex < NUM_PARTITIONS; partitionIndex++) {
+ for (String topic : topics) {
+ tps.add(new TopicPartition(topic, partitionIndex));
+ }
+ }
+ long expectedTotalOffsets = numRecords * topics.size();
+
+ waitForCondition(() -> {
+ Map<TopicPartition, OffsetAndMetadata> consumerGroupOffsets =
+ adminClient.listConsumerGroupOffsets(consumerGroupId).partitionsToOffsetAndMetadata().get();
+ long consumerGroupOffsetTotal = consumerGroupOffsets.values().stream()
+ .mapToLong(metadata -> metadata.offset()).sum();
+
+ Map<TopicPartition, Long> offsets = consumer.endOffsets(tps, Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+ long totalOffsets = offsets.values().stream().mapToLong(l -> l).sum();
+
+ // make sure the consumer group offsets are synced to expected number
+ return totalOffsets == expectedTotalOffsets && consumerGroupOffsetTotal > 0;
+ }, OFFSET_SYNC_DURATION_MS, "Consumer group offset sync is not complete in time");
+ }
+
+ /*
+ * make sure the consumer to consume expected number of records
+ */
+ private static <T> void waitForConsumingAllRecords(Consumer<T, T> consumer, int numExpectedRecords)
+ throws InterruptedException {
+ final AtomicInteger totalConsumedRecords = new AtomicInteger(0);
+ waitForCondition(() -> {
+ ConsumerRecords<T, T> records = consumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+ return numExpectedRecords == totalConsumedRecords.addAndGet(records.count());
+ }, RECORD_CONSUME_DURATION_MS, "Consumer cannot consume all records in time");
+ consumer.commitSync();
+ consumer.close();
Review comment:
Closing the consumer will make the re-use of the same consumer instance in a clean state. I tried to remove `consumer.close();` and it caused test failures.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc edited a comment on pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc edited a comment on pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#issuecomment-714955565
Thanks @mimaison for your high-level advice and detailed review.
(1) I responded to your every comments. A "thumb-up" means I made the suggested change
(2) regarding the increased complexity, here is my analysis for each test case
(a) `testReplication`: This is an existing test and no new stuff are added, except checking if topic config are also mirrored. If we believe the topic config validation is trivial, I am more than happy to remove it
(b) `testReplicationWithEmptyPartition`: This is an existing test and no new stuff are added
(c) `testOneWayReplicationWithAutoOffsetSync`: This is an existing test and no new stuff are added
(d) `testWithBrokerRestart`: This is a **new** test, which introduced background producer and consumer, called `ThreadedProducer` and `ThreadedConsumer`. The purpose of background producer and consumer is to better test the failure case to avoid serialization (produce -> broker restart -> consumer) which can not reveal the insight that consumers consume the same records more than once when broker failure happens.
(e) `MirrorConnectorsIntegrationSSLTest`: This is a **new** test and it should be pretty lean and neat.
In addition, the **new** base test class `MirrorConnectorsIntegrationBaseTest` follows the existing practice of K-stream integration test structure https://github.com/apache/kafka/blob/trunk/streams/src/test/java/org/apache/kafka/streams/integration/ResetIntegrationWithSslTest.java#L37 so I assume it is likely the right way tp structure tests with more than one scenarios (SSL v.s. non-SSL)
If we have to control the complexity, I would prefer to drop `testWithBrokerRestart` and keep `MirrorConnectorsIntegrationSSLTest`, as it makes sense to run simple validation in SSL setup.
Thanks and would like to hear more thoughts and feedback.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc commented on pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc commented on pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#issuecomment-741520739
@rhauch I incorporated https://github.com/apache/kafka/pull/9698 in my latest version here
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc commented on pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc commented on pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#issuecomment-760310777
Thanks @mimaison so much for your multiple rounds of valuable feedback and comments which greatly improving the code quality of this PR
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc commented on pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc commented on pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#issuecomment-689622169
very appreciated for any feedback on what to test additionally and how to get close to the real scenario. Some of the ideas come from https://github.com/apache/kafka/blob/trunk/connect/runtime/src/test/java/org/apache/kafka/connect/integration/ConnectWorkerIntegrationTest.java
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] mimaison commented on a change in pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
mimaison commented on a change in pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#discussion_r538876091
##########
File path: connect/runtime/src/test/java/org/apache/kafka/connect/util/clusters/EmbeddedKafkaCluster.java
##########
@@ -278,6 +283,11 @@ protected boolean hasState(KafkaServer server, Predicate<BrokerState> desiredSta
return false;
}
}
+
+ public boolean sslEnabled() {
+ final String listeners = brokerConfig.getProperty(KafkaConfig$.MODULE$.ListenersProp());
+ return (listeners != null && listeners.contains("SSL")) ? true : false;
Review comment:
We can return `listeners != null && listeners.contains("SSL")`
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationSSLTest.java
##########
@@ -0,0 +1,98 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.common.network.Mode;
+import org.apache.kafka.connect.mirror.MirrorCheckpointConnector;
+import org.apache.kafka.connect.mirror.MirrorHeartbeatConnector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.MirrorSourceConnector;
+import org.apache.kafka.test.IntegrationTest;
+import org.apache.kafka.test.TestSslUtils;
+import org.apache.kafka.test.TestUtils;
+import kafka.server.KafkaConfig$;
+
+import org.junit.experimental.categories.Category;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+import org.junit.Before;
+import org.junit.After;
+import org.junit.Test;
+
+/**
+ * Tests MM2 replication with SSL enabled at backup kafka cluster
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationSSLTest extends MirrorConnectorsIntegrationBaseTest {
+
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationSSLTest.class);
+
+ private static final List<Class> CONNECTOR_LIST =
+ Arrays.asList(MirrorSourceConnector.class, MirrorCheckpointConnector.class, MirrorHeartbeatConnector.class);
+
+ @Before
+ public void setup() throws InterruptedException {
+ try {
+ Map<String, Object> sslConfig = TestSslUtils.createSslConfig(false, true, Mode.SERVER, TestUtils.tempFile(), "testCert");
+ backupBrokerProps.put(KafkaConfig$.MODULE$.ListenersProp(), "SSL://localhost:0");
+ backupBrokerProps.put(KafkaConfig$.MODULE$.InterBrokerListenerNameProp(), "SSL");
+ backupBrokerProps.putAll(sslConfig);
+ } catch (final Exception e) {
+ throw new RuntimeException(e);
Review comment:
This still needs to be addressed
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationBaseTest.java
##########
@@ -0,0 +1,577 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.Config;
+import org.apache.kafka.clients.admin.ConfigEntry;
+import org.apache.kafka.clients.admin.DescribeConfigsResult;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.config.ConfigResource;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.connector.Connector;
+import org.apache.kafka.connect.mirror.MirrorClient;
+import org.apache.kafka.connect.mirror.MirrorHeartbeatConnector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.MirrorSourceConnector;
+import org.apache.kafka.connect.mirror.SourceAndTarget;
+import org.apache.kafka.connect.mirror.MirrorCheckpointConnector;
+import org.apache.kafka.connect.util.clusters.EmbeddedConnectCluster;
+import org.apache.kafka.connect.util.clusters.EmbeddedKafkaCluster;
+import org.apache.kafka.test.IntegrationTest;
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertNotNull;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.junit.After;
+import org.junit.Before;
+
+import static org.apache.kafka.connect.mirror.TestUtils.generateRecords;
+
+/**
+ * Tests MM2 replication and failover/failback logic.
+ *
+ * MM2 is configured with active/active replication between two Kafka clusters. Tests validate that
+ * records sent to either cluster arrive at the other cluster. Then, a consumer group is migrated from
+ * one cluster to the other and back. Tests validate that consumer offsets are translated and replicated
+ * between clusters during this failover and failback.
+ */
+@Category(IntegrationTest.class)
+public abstract class MirrorConnectorsIntegrationBaseTest {
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationBaseTest.class);
+
+ private static final int NUM_RECORDS_PER_PARTITION = 10;
+ private static final int NUM_PARTITIONS = 10;
+ private static final int NUM_RECORDS_PRODUCED = NUM_PARTITIONS * NUM_RECORDS_PER_PARTITION;
+ private static final int RECORD_TRANSFER_DURATION_MS = 30_000;
+ private static final int CHECKPOINT_DURATION_MS = 20_000;
+ private static final int RECORD_CONSUME_DURATION_MS = 20_000;
+ private static final int OFFSET_SYNC_DURATION_MS = 30_000;
+ private static final int NUM_WORKERS = 3;
+ private static final Duration CONSUMER_POLL_TIMEOUT_MS = Duration.ofMillis(500);
+ private static final int BROKER_RESTART_TIMEOUT_MS = 10_000;
+ protected static final String PRIMARY_CLUSTER_ALIAS = "primary";
+ protected static final String BACKUP_CLUSTER_ALIAS = "backup";
+ private static final List<Class<? extends Connector>> CONNECTOR_LIST =
+ Arrays.asList(MirrorSourceConnector.class, MirrorCheckpointConnector.class, MirrorHeartbeatConnector.class);
+
+ protected Map<String, String> mm2Props = new HashMap<>();
+ private MirrorMakerConfig mm2Config;
+ private EmbeddedConnectCluster primary;
+ private EmbeddedConnectCluster backup;
+
+ private final AtomicBoolean exited = new AtomicBoolean(false);
+ protected Properties primaryBrokerProps = new Properties();
+ protected Properties backupBrokerProps = new Properties();
+ protected Map<String, String> primaryWorkerProps = new HashMap<>();
+ protected Map<String, String> backupWorkerProps = new HashMap<>();
+
+ @Before
+ public void startClusters() throws InterruptedException {
+ primaryBrokerProps.put("auto.create.topics.enable", "false");
+ backupBrokerProps.put("auto.create.topics.enable", "false");
+
+ mm2Props.putAll(basicMM2Config());
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+ primaryWorkerProps = mm2Config.workerConfig(new SourceAndTarget(BACKUP_CLUSTER_ALIAS, PRIMARY_CLUSTER_ALIAS));
+ backupWorkerProps.putAll(mm2Config.workerConfig(new SourceAndTarget(PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS)));
+
+ primary = new EmbeddedConnectCluster.Builder()
+ .name(PRIMARY_CLUSTER_ALIAS + "-connect-cluster")
+ .numWorkers(NUM_WORKERS)
+ .numBrokers(1)
+ .brokerProps(primaryBrokerProps)
+ .workerProps(primaryWorkerProps)
+ .build();
+
+ backup = new EmbeddedConnectCluster.Builder()
+ .name(BACKUP_CLUSTER_ALIAS + "-connect-cluster")
+ .numWorkers(NUM_WORKERS)
+ .numBrokers(1)
+ .brokerProps(backupBrokerProps)
+ .workerProps(backupWorkerProps)
+ .build();
+
+ primary.start();
+ primary.assertions().assertAtLeastNumWorkersAreUp(NUM_WORKERS,
+ "Workers of " + PRIMARY_CLUSTER_ALIAS + "-connect-cluster did not start in time.");
+
+ backup.start();
+ backup.assertions().assertAtLeastNumWorkersAreUp(NUM_WORKERS,
+ "Workers of " + BACKUP_CLUSTER_ALIAS + "-connect-cluster did not start in time.");
+
+ createTopics();
+
+ warmUpConsumer();
+
+ log.info(PRIMARY_CLUSTER_ALIAS + " REST service: {}", primary.endpointForResource("connectors"));
+ log.info(BACKUP_CLUSTER_ALIAS + " REST service: {}", backup.endpointForResource("connectors"));
+ log.info(PRIMARY_CLUSTER_ALIAS + " brokers: {}", primary.kafka().bootstrapServers());
+ log.info(BACKUP_CLUSTER_ALIAS + " brokers: {}", backup.kafka().bootstrapServers());
+
+ // now that the brokers are running, we can finish setting up the Connectors
+ mm2Props.put(PRIMARY_CLUSTER_ALIAS + ".bootstrap.servers", primary.kafka().bootstrapServers());
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + ".bootstrap.servers", backup.kafka().bootstrapServers());
+
+ Exit.setExitProcedure((status, errorCode) -> exited.set(true));
+ }
+
+ @After
+ public void shutdownClusters() throws Exception {
+ for (String x : primary.connectors()) {
+ primary.deleteConnector(x);
+ }
+ for (String x : backup.connectors()) {
+ backup.deleteConnector(x);
+ }
+ deleteAllTopics(primary.kafka());
+ deleteAllTopics(backup.kafka());
+ primary.stop();
+ backup.stop();
+ try {
+ assertFalse(exited.get());
+ } finally {
+ Exit.resetExitProcedure();
+ }
+ }
+
+ @Test
+ public void testReplication() throws Exception {
+ produceMessages(primary, "test-topic-1");
+ produceMessages(backup, "test-topic-1");
+ String consumerGroupName = "consumer-group-testReplication";
+ Map<String, Object> consumerProps = new HashMap<String, Object>() {{
+ put("group.id", consumerGroupName);
+ put("auto.offset.reset", "latest");
+ }};
+ // create consumers before starting the connectors so we don't need to wait for discovery
+ waitForConsumingAllRecords(primary.kafka().createConsumerAndSubscribeTo(consumerProps, "test-topic-1"), 0);
+ waitForConsumingAllRecords(backup.kafka().createConsumerAndSubscribeTo(consumerProps, "test-topic-1"), 0);
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS);
+ waitUntilMirrorMakerIsRunning(primary, CONNECTOR_LIST, mm2Config, BACKUP_CLUSTER_ALIAS, PRIMARY_CLUSTER_ALIAS);
+
+ MirrorClient primaryClient = new MirrorClient(mm2Config.clientConfig(PRIMARY_CLUSTER_ALIAS));
+ MirrorClient backupClient = new MirrorClient(mm2Config.clientConfig(BACKUP_CLUSTER_ALIAS));
+
+ assertEquals("topic config was not synced", TopicConfig.CLEANUP_POLICY_COMPACT,
+ getTopicConfig(backup.kafka(), "primary.test-topic-1", TopicConfig.CLEANUP_POLICY_CONFIG));
+
+ assertEquals("Records were not produced to primary cluster.", NUM_RECORDS_PRODUCED,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "test-topic-1").count());
+ assertEquals("Records were not replicated to backup cluster.", NUM_RECORDS_PRODUCED,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "primary.test-topic-1").count());
+ assertEquals("Records were not produced to backup cluster.", NUM_RECORDS_PRODUCED,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "test-topic-1").count());
+ assertEquals("Records were not replicated to primary cluster.", NUM_RECORDS_PRODUCED,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "backup.test-topic-1").count());
+
+ assertEquals("Primary cluster doesn't have all records from both clusters.", NUM_RECORDS_PRODUCED * 2,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED * 2, RECORD_TRANSFER_DURATION_MS, "backup.test-topic-1", "test-topic-1").count());
+ assertEquals("Backup cluster doesn't have all records from both clusters.", NUM_RECORDS_PRODUCED * 2,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED * 2, RECORD_TRANSFER_DURATION_MS, "primary.test-topic-1", "test-topic-1").count());
+
+ assertTrue("Heartbeats were not emitted to primary cluster.", primary.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "heartbeats").count() > 0);
+ assertTrue("Heartbeats were not emitted to backup cluster.", backup.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "heartbeats").count() > 0);
+ assertTrue("Heartbeats were not replicated downstream to backup cluster.", backup.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "primary.heartbeats").count() > 0);
+ assertTrue("Heartbeats were not replicated downstream to primary cluster.", primary.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "backup.heartbeats").count() > 0);
+
+ assertTrue("Did not find upstream primary cluster.", backupClient.upstreamClusters().contains(PRIMARY_CLUSTER_ALIAS));
+ assertEquals("Did not calculate replication hops correctly.", 1, backupClient.replicationHops(PRIMARY_CLUSTER_ALIAS));
+ assertTrue("Did not find upstream backup cluster.", primaryClient.upstreamClusters().contains(BACKUP_CLUSTER_ALIAS));
+ assertEquals("Did not calculate replication hops correctly.", 1, primaryClient.replicationHops(BACKUP_CLUSTER_ALIAS));
+ assertTrue("Checkpoints were not emitted downstream to backup cluster.", backup.kafka().consume(1,
+ CHECKPOINT_DURATION_MS, "primary.checkpoints.internal").count() > 0);
+
+ Map<TopicPartition, OffsetAndMetadata> backupOffsets = backupClient.remoteConsumerOffsets(consumerGroupName, PRIMARY_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS));
+
+ assertTrue("Offsets not translated downstream to backup cluster. Found: " + backupOffsets, backupOffsets.containsKey(
+ new TopicPartition("primary.test-topic-1", 0)));
+
+ // Failover consumer group to backup cluster.
+ try (Consumer<byte[], byte[]> primaryConsumer = backup.kafka().createConsumer(Collections.singletonMap("group.id", consumerGroupName))) {
+ primaryConsumer.assign(backupOffsets.keySet());
+ backupOffsets.forEach(primaryConsumer::seek);
+ primaryConsumer.poll(CONSUMER_POLL_TIMEOUT_MS);
+ primaryConsumer.commitAsync();
+
+ assertTrue("Consumer failedover to zero offset.", primaryConsumer.position(new TopicPartition("primary.test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedover beyond expected offset.", primaryConsumer.position(
+ new TopicPartition("primary.test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+ assertTrue("Checkpoints were not emitted upstream to primary cluster.", primary.kafka().consume(1,
+ CHECKPOINT_DURATION_MS, "backup.checkpoints.internal").count() > 0);
+ }
+
+ waitForCondition(() -> {
+ return primaryClient.remoteConsumerOffsets(consumerGroupName, BACKUP_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS)).containsKey(new TopicPartition("backup.test-topic-1", 0));
+ }, CHECKPOINT_DURATION_MS, "Offsets not translated downstream to primary cluster.");
+
+ waitForCondition(() -> {
+ return primaryClient.remoteConsumerOffsets(consumerGroupName, BACKUP_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS)).containsKey(new TopicPartition("test-topic-1", 0));
+ }, CHECKPOINT_DURATION_MS, "Offsets not translated upstream to primary cluster.");
+
+ Map<TopicPartition, OffsetAndMetadata> primaryOffsets = primaryClient.remoteConsumerOffsets(consumerGroupName, BACKUP_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS));
+
+ // Failback consumer group to primary cluster
+ try (Consumer<byte[], byte[]> backupConsumer = primary.kafka().createConsumer(Collections.singletonMap("group.id", consumerGroupName))) {
+ backupConsumer.assign(primaryOffsets.keySet());
+ primaryOffsets.forEach(backupConsumer::seek);
+ backupConsumer.poll(CONSUMER_POLL_TIMEOUT_MS);
+ backupConsumer.commitAsync();
+
+ assertTrue("Consumer failedback to zero upstream offset.", backupConsumer.position(new TopicPartition("test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedback to zero downstream offset.", backupConsumer.position(new TopicPartition("backup.test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedback beyond expected upstream offset.", backupConsumer.position(
+ new TopicPartition("test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+ assertTrue("Consumer failedback beyond expected downstream offset.", backupConsumer.position(
+ new TopicPartition("backup.test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+ }
+
+ // create more matching topics
+ primary.kafka().createTopic("test-topic-2", NUM_PARTITIONS);
+ backup.kafka().createTopic("test-topic-3", NUM_PARTITIONS);
+
+ // only produce messages to the first partition
+ produceMessages(primary, "test-topic-2", 1);
+ produceMessages(backup, "test-topic-3", 1);
+
+ // expect total consumed messages equals to NUM_RECORDS_PER_PARTITION
+ assertEquals("Records were not produced to primary cluster.", NUM_RECORDS_PER_PARTITION,
+ primary.kafka().consume(NUM_RECORDS_PER_PARTITION, RECORD_TRANSFER_DURATION_MS, "test-topic-2").count());
+ assertEquals("Records were not produced to backup cluster.", NUM_RECORDS_PER_PARTITION,
+ backup.kafka().consume(NUM_RECORDS_PER_PARTITION, RECORD_TRANSFER_DURATION_MS, "test-topic-3").count());
+
+ assertEquals("New topic was not replicated to primary cluster.", NUM_RECORDS_PER_PARTITION,
+ primary.kafka().consume(NUM_RECORDS_PER_PARTITION, 2 * RECORD_TRANSFER_DURATION_MS, "backup.test-topic-3").count());
+ assertEquals("New topic was not replicated to backup cluster.", NUM_RECORDS_PER_PARTITION,
+ backup.kafka().consume(NUM_RECORDS_PER_PARTITION, 2 * RECORD_TRANSFER_DURATION_MS, "primary.test-topic-2").count());
+
+ }
+
+ @Test
+ public void testReplicationWithEmptyPartition() throws Exception {
+ String consumerGroupName = "consumer-group-testReplicationWithEmptyPartition";
+ Map<String, Object> consumerProps = Collections.singletonMap("group.id", consumerGroupName);
+
+ // create topic
+ String topic = "test-topic-with-empty-partition";
+ primary.kafka().createTopic(topic, NUM_PARTITIONS);
+
+ // produce to all test-topic-empty's partitions, except the last partition
+ produceMessages(primary, topic, NUM_PARTITIONS - 1);
+
+ // consume before starting the connectors so we don't need to wait for discovery
+ int expectedRecords = NUM_RECORDS_PER_PARTITION * (NUM_PARTITIONS - 1);
+ try (Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps, topic)) {
+ waitForConsumingAllRecords(primaryConsumer, expectedRecords);
+ }
+
+ // one way replication from primary to backup
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + "->" + PRIMARY_CLUSTER_ALIAS + ".enabled", "false");
+ mm2Config = new MirrorMakerConfig(mm2Props);
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS);
+
+ // sleep few seconds to have MM2 finish replication so that "end" consumer will consume some record
+ Thread.sleep(TimeUnit.SECONDS.toMillis(3));
+
+ // consume all records from backup cluster
+ try (Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(consumerProps,
+ PRIMARY_CLUSTER_ALIAS + "." + topic)) {
+ waitForConsumingAllRecords(backupConsumer, expectedRecords);
+ }
+
+ Admin backupClient = backup.kafka().createAdminClient();
+ // retrieve the consumer group offset from backup cluster
+ Map<TopicPartition, OffsetAndMetadata> remoteOffsets =
+ backupClient.listConsumerGroupOffsets(consumerGroupName).partitionsToOffsetAndMetadata().get();
+ // pinpoint the offset of the last partition which does not receive records
+ OffsetAndMetadata offset = remoteOffsets.get(new TopicPartition(PRIMARY_CLUSTER_ALIAS + "." + topic, NUM_PARTITIONS - 1));
+ // offset of the last partition should exist, but its value should be 0
+ assertNotNull("Offset of last partition was not replicated", offset);
+ assertEquals("Offset of last partition is not zero", 0, offset.offset());
+ }
+
+ @Test
+ public void testOneWayReplicationWithAutoOffsetSync() throws InterruptedException {
+ produceMessages(primary, "test-topic-1");
+ String consumerGroupName = "consumer-group-testOneWayReplicationWithAutoOffsetSync";
+ Map<String, Object> consumerProps = new HashMap<String, Object>() {{
+ put("group.id", consumerGroupName);
+ put("auto.offset.reset", "earliest");
+ }};
+ // create consumers before starting the connectors so we don't need to wait for discovery
+ try (Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps,
+ "test-topic-1")) {
+ // we need to wait for consuming all the records for MM2 replicating the expected offsets
+ waitForConsumingAllRecords(primaryConsumer, NUM_RECORDS_PRODUCED);
+ }
+
+ // enable automated consumer group offset sync
+ mm2Props.put("sync.group.offsets.enabled", "true");
+ mm2Props.put("sync.group.offsets.interval.seconds", "1");
+ // one way replication from primary to backup
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + "->" + PRIMARY_CLUSTER_ALIAS + ".enabled", "false");
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS);
+
+ // create a consumer at backup cluster with same consumer group Id to consume 1 topic
+ Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(
+ consumerProps, "primary.test-topic-1");
+
+ waitForConsumerGroupOffsetSync(backup, backupConsumer, Collections.singletonList("primary.test-topic-1"),
+ consumerGroupName, NUM_RECORDS_PRODUCED);
+
+ ConsumerRecords<byte[], byte[]> records = backupConsumer.poll(CONSUMER_POLL_TIMEOUT_MS);
+
+ // the size of consumer record should be zero, because the offsets of the same consumer group
+ // have been automatically synchronized from primary to backup by the background job, so no
+ // more records to consume from the replicated topic by the same consumer group at backup cluster
+ assertEquals("consumer record size is not zero", 0, records.count());
+
+ // now create a new topic in primary cluster
+ primary.kafka().createTopic("test-topic-2", NUM_PARTITIONS);
+ backup.kafka().createTopic("primary.test-topic-2", 1);
+ // produce some records to the new topic in primary cluster
+ produceMessages(primary, "test-topic-2");
+
+ // create a consumer at primary cluster to consume the new topic
+ try (Consumer<byte[], byte[]> consumer1 = primary.kafka().createConsumerAndSubscribeTo(Collections.singletonMap(
+ "group.id", "consumer-group-1"), "test-topic-2")) {
+ // we need to wait for consuming all the records for MM2 replicating the expected offsets
+ waitForConsumingAllRecords(consumer1, NUM_RECORDS_PRODUCED);
+ }
+
+ // create a consumer at backup cluster with same consumer group Id to consume old and new topic
+ backupConsumer = backup.kafka().createConsumerAndSubscribeTo(Collections.singletonMap(
+ "group.id", consumerGroupName), "primary.test-topic-1", "primary.test-topic-2");
+
+ waitForConsumerGroupOffsetSync(backup, backupConsumer, Arrays.asList("primary.test-topic-1", "primary.test-topic-2"),
+ consumerGroupName, NUM_RECORDS_PRODUCED);
+
+ records = backupConsumer.poll(CONSUMER_POLL_TIMEOUT_MS);
+ // similar reasoning as above, no more records to consume by the same consumer group at backup cluster
+ assertEquals("consumer record size is not zero", 0, records.count());
+ backupConsumer.close();
+ }
+
+ /*
+ * launch the connectors on kafka connect cluster and check if they are running
+ */
+ private static void waitUntilMirrorMakerIsRunning(EmbeddedConnectCluster connectCluster,
+ List<Class<? extends Connector>> connectorClasses, MirrorMakerConfig mm2Config,
+ String primary, String backup) throws InterruptedException {
+ for (int i = 0; i < connectorClasses.size(); i++) {
Review comment:
We could use a "for each" loop here, something like:
```
for (Class<? extends Connector> connector : connectorClasses) {
connectCluster.configureConnector(connector.getSimpleName(), mm2Config.connectorBaseConfig(
new SourceAndTarget(primary, backup), connector));
}
```
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationBaseTest.java
##########
@@ -0,0 +1,617 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.Config;
+import org.apache.kafka.clients.admin.ConfigEntry;
+import org.apache.kafka.clients.admin.DescribeConfigsResult;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.clients.CommonClientConfigs;
+import org.apache.kafka.common.config.ConfigResource;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.config.SslConfigs;
+import org.apache.kafka.common.config.types.Password;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.connector.Connector;
+import org.apache.kafka.connect.mirror.MirrorClient;
+import org.apache.kafka.connect.mirror.MirrorHeartbeatConnector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.MirrorSourceConnector;
+import org.apache.kafka.connect.mirror.SourceAndTarget;
+import org.apache.kafka.connect.mirror.MirrorCheckpointConnector;
+import org.apache.kafka.connect.util.clusters.EmbeddedConnectCluster;
+import org.apache.kafka.connect.util.clusters.EmbeddedKafkaCluster;
+import org.apache.kafka.test.IntegrationTest;
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertNotNull;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import static org.apache.kafka.connect.mirror.TestUtils.generateRecords;
+
+/**
+ * Tests MM2 replication and failover/failback logic.
+ *
+ * MM2 is configured with active/active replication between two Kafka clusters. Tests validate that
+ * records sent to either cluster arrive at the other cluster. Then, a consumer group is migrated from
+ * one cluster to the other and back. Tests validate that consumer offsets are translated and replicated
+ * between clusters during this failover and failback.
+ */
+@Category(IntegrationTest.class)
+public abstract class MirrorConnectorsIntegrationBaseTest {
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationBaseTest.class);
+
+ private static final int NUM_RECORDS_PER_PARTITION = 10;
+ private static final int NUM_PARTITIONS = 10;
+ private static final int NUM_RECORDS_PRODUCED = NUM_PARTITIONS * NUM_RECORDS_PER_PARTITION;
+ private static final int RECORD_TRANSFER_DURATION_MS = 30_000;
+ private static final int CHECKPOINT_DURATION_MS = 20_000;
+ private static final int RECORD_CONSUME_DURATION_MS = 20_000;
+ private static final int OFFSET_SYNC_DURATION_MS = 30_000;
+ private static final int NUM_WORKERS = 3;
+ private static final int CONSUMER_POLL_TIMEOUT_MS = 500;
+ private static final int BROKER_RESTART_TIMEOUT_MS = 10_000;
+ private static final long DEFAULT_PRODUCE_SEND_DURATION_MS = TimeUnit.SECONDS.toMillis(120);
+ private static final String PRIMARY_CLUSTER_ALIAS = "primary";
+ private static final String BACKUP_CLUSTER_ALIAS = "backup";
+ private static final List<Class<? extends Connector>> CONNECTOR_LIST =
+ Arrays.asList(MirrorSourceConnector.class, MirrorCheckpointConnector.class, MirrorHeartbeatConnector.class);
+
+ private Map<String, String> mm2Props;
+ private MirrorMakerConfig mm2Config;
+ private EmbeddedConnectCluster primary;
+ private EmbeddedConnectCluster backup;
+
+ private final AtomicBoolean exited = new AtomicBoolean(false);
+ protected Properties primaryBrokerProps = new Properties();
+ protected Properties backupBrokerProps = new Properties();
+ private Map<String, String> primaryWorkerProps = new HashMap<>();
+ private Map<String, String> backupWorkerProps = new HashMap<>();
+ abstract Map<String, Object> getSslConfig();
+
+ protected void startClusters() throws InterruptedException {
+ primaryBrokerProps.put("auto.create.topics.enable", "false");
+ backupBrokerProps.put("auto.create.topics.enable", "false");
+
+ mm2Props = basicMM2Config();
+
+ final Map<String, Object> sslConfig = getSslConfig();
+ if (sslConfig != null) {
+ Properties sslProps = new Properties();
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, sslConfig.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG));
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, ((Password) sslConfig.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)).value());
+ sslProps.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL");
+
+ // set SSL config for kafka connect worker
+ backupWorkerProps.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> BACKUP_CLUSTER_ALIAS + "." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ // set SSL config for producer used by source task in MM2
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> BACKUP_CLUSTER_ALIAS + ".producer." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ }
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+ primaryWorkerProps = mm2Config.workerConfig(new SourceAndTarget(BACKUP_CLUSTER_ALIAS, PRIMARY_CLUSTER_ALIAS));
+ backupWorkerProps.putAll(mm2Config.workerConfig(new SourceAndTarget(PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS)));
+
+ primary = new EmbeddedConnectCluster.Builder()
+ .name(PRIMARY_CLUSTER_ALIAS + "-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(primaryBrokerProps)
+ .workerProps(primaryWorkerProps)
+ .build();
+
+ backup = new EmbeddedConnectCluster.Builder()
+ .name(BACKUP_CLUSTER_ALIAS + "-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(backupBrokerProps)
+ .workerProps(backupWorkerProps)
+ .build();
+
+ primary.start();
+ primary.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of " + PRIMARY_CLUSTER_ALIAS + "-connect-cluster did not start in time.");
+
+ backup.start();
+ backup.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of " + BACKUP_CLUSTER_ALIAS + "-connect-cluster did not start in time.");
+
+ createTopics();
+
+ warmUpConsumer();
+
+ log.info(PRIMARY_CLUSTER_ALIAS + " REST service: {}", primary.endpointForResource("connectors"));
+ log.info(BACKUP_CLUSTER_ALIAS + " REST service: {}", backup.endpointForResource("connectors"));
+ log.info(PRIMARY_CLUSTER_ALIAS + " brokers: {}", primary.kafka().bootstrapServers());
+ log.info(BACKUP_CLUSTER_ALIAS + " brokers: {}", backup.kafka().bootstrapServers());
+
+ // now that the brokers are running, we can finish setting up the Connectors
+ mm2Props.put(PRIMARY_CLUSTER_ALIAS + ".bootstrap.servers", primary.kafka().bootstrapServers());
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + ".bootstrap.servers", backup.kafka().bootstrapServers());
+
+ Exit.setExitProcedure((status, errorCode) -> exited.set(true));
+ }
+
+ public void shutdownClusters() {
+ for (String x : primary.connectors()) {
+ primary.deleteConnector(x);
+ }
+ for (String x : backup.connectors()) {
+ backup.deleteConnector(x);
+ }
+ deleteAllTopics(primary.kafka());
+ deleteAllTopics(backup.kafka());
+ primary.stop();
+ backup.stop();
+ try {
+ assertFalse(exited.get());
+ } finally {
+ Exit.resetExitProcedure();
+ }
+ }
+
+ @Test
+ public void testReplication() throws InterruptedException {
+ produceMessages(primary, "test-topic-1");
+ produceMessages(backup, "test-topic-1");
+ String consumerGroupName = "consumer-group-testReplication";
+ Map<String, Object> consumerProps = new HashMap<String, Object>() {{
+ put("group.id", consumerGroupName);
+ put("auto.offset.reset", "latest");
+ }};
+ // create consumers before starting the connectors so we don't need to wait for discovery
+ Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps, "test-topic-1");
+ waitForConsumingAllRecords(primaryConsumer, 0);
+
+ Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(consumerProps, "test-topic-1");
+ waitForConsumingAllRecords(backupConsumer, 0);
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS);
+ waitUntilMirrorMakerIsRunning(primary, CONNECTOR_LIST, mm2Config, BACKUP_CLUSTER_ALIAS, PRIMARY_CLUSTER_ALIAS);
+
+ MirrorClient primaryClient = new MirrorClient(mm2Config.clientConfig(PRIMARY_CLUSTER_ALIAS));
+ MirrorClient backupClient = new MirrorClient(mm2Config.clientConfig(BACKUP_CLUSTER_ALIAS));
+
+ assertEquals("topic config was not synced", TopicConfig.CLEANUP_POLICY_COMPACT,
+ getTopicConfig(backup.kafka(), "primary.test-topic-1", TopicConfig.CLEANUP_POLICY_CONFIG));
+
+ assertEquals("Records were not produced to primary cluster.", NUM_RECORDS_PRODUCED,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "test-topic-1").count());
+ assertEquals("Records were not replicated to backup cluster.", NUM_RECORDS_PRODUCED,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "primary.test-topic-1").count());
+ assertEquals("Records were not produced to backup cluster.", NUM_RECORDS_PRODUCED,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "test-topic-1").count());
+ assertEquals("Records were not replicated to primary cluster.", NUM_RECORDS_PRODUCED,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "backup.test-topic-1").count());
+
+ assertEquals("Primary cluster doesn't have all records from both clusters.", NUM_RECORDS_PRODUCED * 2,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED * 2, RECORD_TRANSFER_DURATION_MS, "backup.test-topic-1", "test-topic-1").count());
+ assertEquals("Backup cluster doesn't have all records from both clusters.", NUM_RECORDS_PRODUCED * 2,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED * 2, RECORD_TRANSFER_DURATION_MS, "primary.test-topic-1", "test-topic-1").count());
+
+ assertTrue("Heartbeats were not emitted to primary cluster.", primary.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "heartbeats").count() > 0);
+ assertTrue("Heartbeats were not emitted to backup cluster.", backup.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "heartbeats").count() > 0);
+ assertTrue("Heartbeats were not replicated downstream to backup cluster.", backup.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "primary.heartbeats").count() > 0);
+ assertTrue("Heartbeats were not replicated downstream to primary cluster.", primary.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "backup.heartbeats").count() > 0);
+
+ assertTrue("Did not find upstream primary cluster.", backupClient.upstreamClusters().contains(PRIMARY_CLUSTER_ALIAS));
+ assertEquals("Did not calculate replication hops correctly.", 1, backupClient.replicationHops(PRIMARY_CLUSTER_ALIAS));
+ assertTrue("Did not find upstream backup cluster.", primaryClient.upstreamClusters().contains(BACKUP_CLUSTER_ALIAS));
+ assertEquals("Did not calculate replication hops correctly.", 1, primaryClient.replicationHops(BACKUP_CLUSTER_ALIAS));
+ assertTrue("Checkpoints were not emitted downstream to backup cluster.", backup.kafka().consume(1,
+ CHECKPOINT_DURATION_MS, "primary.checkpoints.internal").count() > 0);
+
+ Map<TopicPartition, OffsetAndMetadata> backupOffsets = backupClient.remoteConsumerOffsets(consumerGroupName, PRIMARY_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS));
+
+ assertTrue("Offsets not translated downstream to backup cluster. Found: " + backupOffsets, backupOffsets.containsKey(
+ new TopicPartition("primary.test-topic-1", 0)));
+
+ // Failover consumer group to backup cluster.
+ primaryConsumer = backup.kafka().createConsumer(Collections.singletonMap("group.id", consumerGroupName));
+ primaryConsumer.assign(backupOffsets.keySet());
+ backupOffsets.forEach(primaryConsumer::seek);
+ primaryConsumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+ primaryConsumer.commitAsync();
+
+ assertTrue("Consumer failedover to zero offset.", primaryConsumer.position(new TopicPartition("primary.test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedover beyond expected offset.", primaryConsumer.position(
+ new TopicPartition("primary.test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+ assertTrue("Checkpoints were not emitted upstream to primary cluster.", primary.kafka().consume(1,
+ CHECKPOINT_DURATION_MS, "backup.checkpoints.internal").count() > 0);
+
+ primaryConsumer.close();
+
+ waitForCondition(() -> {
+ try {
+ return primaryClient.remoteConsumerOffsets(consumerGroupName, BACKUP_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS)).containsKey(new TopicPartition("backup.test-topic-1", 0));
+ } catch (Throwable e) {
+ return false;
+ }
+ }, CHECKPOINT_DURATION_MS, "Offsets not translated downstream to primary cluster.");
+
+ waitForCondition(() -> {
+ try {
+ return primaryClient.remoteConsumerOffsets(consumerGroupName, BACKUP_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS)).containsKey(new TopicPartition("test-topic-1", 0));
+ } catch (Throwable e) {
+ return false;
+ }
+ }, CHECKPOINT_DURATION_MS, "Offsets not translated upstream to primary cluster.");
+
+ Map<TopicPartition, OffsetAndMetadata> primaryOffsets = primaryClient.remoteConsumerOffsets(consumerGroupName, BACKUP_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS));
+
+ // Failback consumer group to primary cluster
+ backupConsumer = primary.kafka().createConsumer(Collections.singletonMap("group.id", consumerGroupName));
+ backupConsumer.assign(primaryOffsets.keySet());
+ primaryOffsets.forEach(backupConsumer::seek);
+ backupConsumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+ backupConsumer.commitAsync();
+
+ assertTrue("Consumer failedback to zero upstream offset.", backupConsumer.position(new TopicPartition("test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedback to zero downstream offset.", backupConsumer.position(new TopicPartition("backup.test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedback beyond expected upstream offset.", backupConsumer.position(
+ new TopicPartition("test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+ assertTrue("Consumer failedback beyond expected downstream offset.", backupConsumer.position(
+ new TopicPartition("backup.test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+
+ backupConsumer.close();
+
+ // create more matching topics
+ primary.kafka().createTopic("test-topic-2", NUM_PARTITIONS);
+ backup.kafka().createTopic("test-topic-3", NUM_PARTITIONS);
+
+ // only produce messages to the first partition
+ produceMessages(primary, "test-topic-2", 1);
+ produceMessages(backup, "test-topic-3", 1);
+
+ // expect total consumed messages equals to NUM_RECORDS_PER_PARTITION
+ assertEquals("Records were not produced to primary cluster.", NUM_RECORDS_PER_PARTITION,
+ primary.kafka().consume(NUM_RECORDS_PER_PARTITION, RECORD_TRANSFER_DURATION_MS, "test-topic-2").count());
+ assertEquals("Records were not produced to backup cluster.", NUM_RECORDS_PER_PARTITION,
+ backup.kafka().consume(NUM_RECORDS_PER_PARTITION, RECORD_TRANSFER_DURATION_MS, "test-topic-3").count());
+
+ assertEquals("New topic was not replicated to primary cluster.", NUM_RECORDS_PER_PARTITION,
+ primary.kafka().consume(NUM_RECORDS_PER_PARTITION, 2 * RECORD_TRANSFER_DURATION_MS, "backup.test-topic-3").count());
+ assertEquals("New topic was not replicated to backup cluster.", NUM_RECORDS_PER_PARTITION,
+ backup.kafka().consume(NUM_RECORDS_PER_PARTITION, 2 * RECORD_TRANSFER_DURATION_MS, "primary.test-topic-2").count());
+
+ }
+
+ @Test
+ public void testReplicationWithEmptyPartition() throws Exception {
+ String consumerGroupName = "consumer-group-testReplicationWithEmptyPartition";
+ Map<String, Object> consumerProps = Collections.singletonMap("group.id", consumerGroupName);
+
+ // create topic
+ String topic = "test-topic-with-empty-partition";
+ primary.kafka().createTopic(topic, NUM_PARTITIONS);
+
+ // produce to all test-topic-empty's partitions, except the last partition
+ produceMessages(primary, topic, NUM_PARTITIONS - 1);
+
+ // consume before starting the connectors so we don't need to wait for discovery
+ int expectedRecords = NUM_RECORDS_PER_PARTITION * (NUM_PARTITIONS - 1);
+ try (Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps, topic)) {
+ waitForConsumingAllRecords(primaryConsumer, expectedRecords);
+ }
+
+ // one way replication from primary to backup
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + "->" + PRIMARY_CLUSTER_ALIAS + ".enabled", "false");
+ mm2Config = new MirrorMakerConfig(mm2Props);
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS);
+
+ // sleep few seconds to have MM2 finish replication so that "end" consumer will consume some record
+ Thread.sleep(TimeUnit.SECONDS.toMillis(3));
+
+ // consume all records from backup cluster
+ try (Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(consumerProps,
+ PRIMARY_CLUSTER_ALIAS + "." + topic)) {
+ waitForConsumingAllRecords(backupConsumer, expectedRecords);
+ }
+
+ Admin backupClient = backup.kafka().createAdminClient();
+ // retrieve the consumer group offset from backup cluster
+ Map<TopicPartition, OffsetAndMetadata> remoteOffsets =
+ backupClient.listConsumerGroupOffsets(consumerGroupName).partitionsToOffsetAndMetadata().get();
+ // pinpoint the offset of the last partition which does not receive records
+ OffsetAndMetadata offset = remoteOffsets.get(new TopicPartition(PRIMARY_CLUSTER_ALIAS + "." + topic, NUM_PARTITIONS - 1));
+ // offset of the last partition should exist, but its value should be 0
+ assertNotNull("Offset of last partition was not replicated", offset);
+ assertEquals("Offset of last partition is not zero", 0, offset.offset());
+ }
+
+ @Test
+ public void testOneWayReplicationWithAutoOffsetSync() throws InterruptedException {
+ produceMessages(primary, "test-topic-1");
+ String consumerGroupName = "consumer-group-testOneWayReplicationWithAutoOffsetSync";
+ Map<String, Object> consumerProps = new HashMap<String, Object>() {{
+ put("group.id", consumerGroupName);
+ put("auto.offset.reset", "earliest");
+ }};
+ // create consumers before starting the connectors so we don't need to wait for discovery
+ try (Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps,
+ "test-topic-1")) {
+ // we need to wait for consuming all the records for MM2 replicating the expected offsets
+ waitForConsumingAllRecords(primaryConsumer, NUM_RECORDS_PRODUCED);
+ }
+
+ // enable automated consumer group offset sync
+ mm2Props.put("sync.group.offsets.enabled", "true");
+ mm2Props.put("sync.group.offsets.interval.seconds", "1");
+ // one way replication from primary to backup
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + "->" + PRIMARY_CLUSTER_ALIAS + ".enabled", "false");
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS);
+
+ // create a consumer at backup cluster with same consumer group Id to consume 1 topic
+ Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(
+ consumerProps, "primary.test-topic-1");
+
+ waitForConsumerGroupOffsetSync(backup, backupConsumer, Collections.singletonList("primary.test-topic-1"),
+ consumerGroupName, NUM_RECORDS_PRODUCED);
+
+ ConsumerRecords<byte[], byte[]> records = backupConsumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+
+ // the size of consumer record should be zero, because the offsets of the same consumer group
+ // have been automatically synchronized from primary to backup by the background job, so no
+ // more records to consume from the replicated topic by the same consumer group at backup cluster
+ assertEquals("consumer record size is not zero", 0, records.count());
+
+ // now create a new topic in primary cluster
+ primary.kafka().createTopic("test-topic-2", NUM_PARTITIONS);
+ backup.kafka().createTopic("primary.test-topic-2", 1);
+ // produce some records to the new topic in primary cluster
+ produceMessages(primary, "test-topic-2");
+
+ // create a consumer at primary cluster to consume the new topic
+ try (Consumer<byte[], byte[]> consumer1 = primary.kafka().createConsumerAndSubscribeTo(Collections.singletonMap(
+ "group.id", "consumer-group-1"), "test-topic-2")) {
+ // we need to wait for consuming all the records for MM2 replicating the expected offsets
+ waitForConsumingAllRecords(consumer1, NUM_RECORDS_PRODUCED);
+ }
+
+ // create a consumer at backup cluster with same consumer group Id to consume old and new topic
+ backupConsumer = backup.kafka().createConsumerAndSubscribeTo(Collections.singletonMap(
+ "group.id", consumerGroupName), "primary.test-topic-1", "primary.test-topic-2");
+
+ waitForConsumerGroupOffsetSync(backup, backupConsumer, Arrays.asList("primary.test-topic-1", "primary.test-topic-2"),
+ consumerGroupName, NUM_RECORDS_PRODUCED);
+
+ records = backupConsumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+ // similar reasoning as above, no more records to consume by the same consumer group at backup cluster
+ assertEquals("consumer record size is not zero", 0, records.count());
+ backupConsumer.close();
+ }
+
+ /*
+ * launch the connectors on kafka connect cluster and check if they are running
+ */
+ private static void waitUntilMirrorMakerIsRunning(EmbeddedConnectCluster connectCluster,
+ List<Class<? extends Connector>> connectorClasses, MirrorMakerConfig mm2Config,
+ String primary, String backup) throws InterruptedException {
+ for (int i = 0; i < connectorClasses.size(); i++) {
+ String connector = connectorClasses.get(i).getSimpleName();
+ connectCluster.configureConnector(connector, mm2Config.connectorBaseConfig(
+ new SourceAndTarget(primary, backup), connectorClasses.get(i)));
+ }
+
+ // we wait for the connector and tasks to come up for each connector, so that when we do the
+ // actual testing, we are certain that the tasks are up and running; this will prevent
+ // flaky tests where the connector and tasks didn't start up in time for the tests to be run
+ List<String> connectorNames = connectorClasses.stream().map(x -> x.getSimpleName())
+ .collect(Collectors.toList());
+ for (String connector : connectorNames) {
+ connectCluster.assertions().assertConnectorAndAtLeastNumTasksAreRunning(connector, 1,
+ "Connector " + connector + " tasks did not start in time on cluster: " + connectCluster);
+ }
+ }
+
+ /*
+ * delete all topics of the input kafka cluster
+ */
+ private static void deleteAllTopics(EmbeddedKafkaCluster cluster) {
+ Admin client = cluster.createAdminClient();
+ try {
+ client.deleteTopics(client.listTopics().names().get());
+ } catch (Throwable e) {
+ // should not run into exception normally. In case of Exception,
+ // simply fail the test and investigate
+ }
+ }
+
+ /*
+ * retrieve the config value based on the input cluster, topic and config name
+ */
+ private static String getTopicConfig(EmbeddedKafkaCluster cluster, String topic, String configName) {
+ Admin client = cluster.createAdminClient();
+ Collection<ConfigResource> cr = Collections.singleton(
+ new ConfigResource(ConfigResource.Type.TOPIC, topic));
+ try {
+ DescribeConfigsResult configsResult = client.describeConfigs(cr);
+ Config allConfigs = (Config) configsResult.all().get().values().toArray()[0];
+ Iterator<ConfigEntry> configIterator = allConfigs.entries().iterator();
+ while (configIterator.hasNext()) {
+ ConfigEntry currentConfig = configIterator.next();
+ if (currentConfig.name().equals(configName)) {
+ return currentConfig.value();
+ }
+ }
+ } catch (Throwable e) {
+ // should not run into exception normally. In case of Exception,
+ // simply fail the test and investigate
+ }
+ return null;
+ }
+
+ /*
+ * produce messages to the cluster and topic
+ */
+ protected void produceMessages(EmbeddedConnectCluster cluster, String topicName) {
+ Map<String, String> recordSent = generateRecords(NUM_RECORDS_PRODUCED);
+ for (Map.Entry<String, String> entry : recordSent.entrySet()) {
+ cluster.kafka().produce(topicName, entry.getKey(), entry.getValue());
+ }
+ }
+
+ /*
+ * produce messages to the cluster and topic partition less than numPartitions
+ */
+ protected void produceMessages(EmbeddedConnectCluster cluster, String topicName, int numPartitions) {
+ int cnt = 0;
+ for (int r = 0; r < NUM_RECORDS_PER_PARTITION; r++)
+ for (int p = 0; p < numPartitions; p++)
+ cluster.kafka().produce(topicName, p, "key", "value-" + cnt++);
+ }
+
+ /*
+ * given consumer group, topics and expected number of records, make sure the consumer group
+ * offsets are eventually synced to the expected offset numbers
+ */
+ private static <T> void waitForConsumerGroupOffsetSync(EmbeddedConnectCluster connect,
+ Consumer<T, T> consumer, List<String> topics, String consumerGroupId, int numRecords)
+ throws InterruptedException {
+ Admin adminClient = connect.kafka().createAdminClient();
+ List<TopicPartition> tps = new ArrayList<>(NUM_PARTITIONS * topics.size());
+ for (int partitionIndex = 0; partitionIndex < NUM_PARTITIONS; partitionIndex++) {
+ for (String topic : topics) {
+ tps.add(new TopicPartition(topic, partitionIndex));
+ }
+ }
+ long expectedTotalOffsets = numRecords * topics.size();
+
+ waitForCondition(() -> {
+ Map<TopicPartition, OffsetAndMetadata> consumerGroupOffsets =
+ adminClient.listConsumerGroupOffsets(consumerGroupId).partitionsToOffsetAndMetadata().get();
+ long consumerGroupOffsetTotal = consumerGroupOffsets.values().stream()
+ .mapToLong(metadata -> metadata.offset()).sum();
+
+ Map<TopicPartition, Long> offsets = consumer.endOffsets(tps, Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+ long totalOffsets = offsets.values().stream().mapToLong(l -> l).sum();
+
+ // make sure the consumer group offsets are synced to expected number
+ return totalOffsets == expectedTotalOffsets && consumerGroupOffsetTotal > 0;
+ }, OFFSET_SYNC_DURATION_MS, "Consumer group offset sync is not complete in time");
+ }
+
+ /*
+ * make sure the consumer to consume expected number of records
+ */
+ private static <T> void waitForConsumingAllRecords(Consumer<T, T> consumer, int numExpectedRecords)
+ throws InterruptedException {
+ final AtomicInteger totalConsumedRecords = new AtomicInteger(0);
+ waitForCondition(() -> {
+ ConsumerRecords<T, T> records = consumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+ return numExpectedRecords == totalConsumedRecords.addAndGet(records.count());
+ }, RECORD_CONSUME_DURATION_MS, "Consumer cannot consume all records in time");
+ consumer.commitSync();
+ consumer.close();
Review comment:
Yes but the code that created the consumer should close it. If I call `waitForConsumingAllRecords()`, I'd not expect it to close my consumer instance.
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationBaseTest.java
##########
@@ -0,0 +1,577 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.Config;
+import org.apache.kafka.clients.admin.ConfigEntry;
+import org.apache.kafka.clients.admin.DescribeConfigsResult;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.config.ConfigResource;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.connector.Connector;
+import org.apache.kafka.connect.mirror.MirrorClient;
+import org.apache.kafka.connect.mirror.MirrorHeartbeatConnector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.MirrorSourceConnector;
+import org.apache.kafka.connect.mirror.SourceAndTarget;
+import org.apache.kafka.connect.mirror.MirrorCheckpointConnector;
+import org.apache.kafka.connect.util.clusters.EmbeddedConnectCluster;
+import org.apache.kafka.connect.util.clusters.EmbeddedKafkaCluster;
+import org.apache.kafka.test.IntegrationTest;
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertNotNull;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.junit.After;
+import org.junit.Before;
+
+import static org.apache.kafka.connect.mirror.TestUtils.generateRecords;
+
+/**
+ * Tests MM2 replication and failover/failback logic.
+ *
+ * MM2 is configured with active/active replication between two Kafka clusters. Tests validate that
+ * records sent to either cluster arrive at the other cluster. Then, a consumer group is migrated from
+ * one cluster to the other and back. Tests validate that consumer offsets are translated and replicated
+ * between clusters during this failover and failback.
+ */
+@Category(IntegrationTest.class)
+public abstract class MirrorConnectorsIntegrationBaseTest {
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationBaseTest.class);
+
+ private static final int NUM_RECORDS_PER_PARTITION = 10;
+ private static final int NUM_PARTITIONS = 10;
+ private static final int NUM_RECORDS_PRODUCED = NUM_PARTITIONS * NUM_RECORDS_PER_PARTITION;
+ private static final int RECORD_TRANSFER_DURATION_MS = 30_000;
+ private static final int CHECKPOINT_DURATION_MS = 20_000;
+ private static final int RECORD_CONSUME_DURATION_MS = 20_000;
+ private static final int OFFSET_SYNC_DURATION_MS = 30_000;
+ private static final int NUM_WORKERS = 3;
+ private static final Duration CONSUMER_POLL_TIMEOUT_MS = Duration.ofMillis(500);
+ private static final int BROKER_RESTART_TIMEOUT_MS = 10_000;
+ protected static final String PRIMARY_CLUSTER_ALIAS = "primary";
+ protected static final String BACKUP_CLUSTER_ALIAS = "backup";
+ private static final List<Class<? extends Connector>> CONNECTOR_LIST =
+ Arrays.asList(MirrorSourceConnector.class, MirrorCheckpointConnector.class, MirrorHeartbeatConnector.class);
+
+ protected Map<String, String> mm2Props = new HashMap<>();
+ private MirrorMakerConfig mm2Config;
+ private EmbeddedConnectCluster primary;
+ private EmbeddedConnectCluster backup;
+
+ private final AtomicBoolean exited = new AtomicBoolean(false);
+ protected Properties primaryBrokerProps = new Properties();
+ protected Properties backupBrokerProps = new Properties();
+ protected Map<String, String> primaryWorkerProps = new HashMap<>();
+ protected Map<String, String> backupWorkerProps = new HashMap<>();
+
+ @Before
+ public void startClusters() throws InterruptedException {
+ primaryBrokerProps.put("auto.create.topics.enable", "false");
+ backupBrokerProps.put("auto.create.topics.enable", "false");
+
+ mm2Props.putAll(basicMM2Config());
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+ primaryWorkerProps = mm2Config.workerConfig(new SourceAndTarget(BACKUP_CLUSTER_ALIAS, PRIMARY_CLUSTER_ALIAS));
+ backupWorkerProps.putAll(mm2Config.workerConfig(new SourceAndTarget(PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS)));
+
+ primary = new EmbeddedConnectCluster.Builder()
+ .name(PRIMARY_CLUSTER_ALIAS + "-connect-cluster")
+ .numWorkers(NUM_WORKERS)
+ .numBrokers(1)
+ .brokerProps(primaryBrokerProps)
+ .workerProps(primaryWorkerProps)
+ .build();
+
+ backup = new EmbeddedConnectCluster.Builder()
+ .name(BACKUP_CLUSTER_ALIAS + "-connect-cluster")
+ .numWorkers(NUM_WORKERS)
+ .numBrokers(1)
+ .brokerProps(backupBrokerProps)
+ .workerProps(backupWorkerProps)
+ .build();
+
+ primary.start();
+ primary.assertions().assertAtLeastNumWorkersAreUp(NUM_WORKERS,
+ "Workers of " + PRIMARY_CLUSTER_ALIAS + "-connect-cluster did not start in time.");
+
+ backup.start();
+ backup.assertions().assertAtLeastNumWorkersAreUp(NUM_WORKERS,
+ "Workers of " + BACKUP_CLUSTER_ALIAS + "-connect-cluster did not start in time.");
+
+ createTopics();
+
+ warmUpConsumer();
+
+ log.info(PRIMARY_CLUSTER_ALIAS + " REST service: {}", primary.endpointForResource("connectors"));
+ log.info(BACKUP_CLUSTER_ALIAS + " REST service: {}", backup.endpointForResource("connectors"));
+ log.info(PRIMARY_CLUSTER_ALIAS + " brokers: {}", primary.kafka().bootstrapServers());
+ log.info(BACKUP_CLUSTER_ALIAS + " brokers: {}", backup.kafka().bootstrapServers());
+
+ // now that the brokers are running, we can finish setting up the Connectors
+ mm2Props.put(PRIMARY_CLUSTER_ALIAS + ".bootstrap.servers", primary.kafka().bootstrapServers());
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + ".bootstrap.servers", backup.kafka().bootstrapServers());
+
+ Exit.setExitProcedure((status, errorCode) -> exited.set(true));
+ }
+
+ @After
+ public void shutdownClusters() throws Exception {
+ for (String x : primary.connectors()) {
+ primary.deleteConnector(x);
+ }
+ for (String x : backup.connectors()) {
+ backup.deleteConnector(x);
+ }
+ deleteAllTopics(primary.kafka());
+ deleteAllTopics(backup.kafka());
+ primary.stop();
+ backup.stop();
+ try {
+ assertFalse(exited.get());
+ } finally {
+ Exit.resetExitProcedure();
+ }
+ }
+
+ @Test
+ public void testReplication() throws Exception {
+ produceMessages(primary, "test-topic-1");
+ produceMessages(backup, "test-topic-1");
+ String consumerGroupName = "consumer-group-testReplication";
+ Map<String, Object> consumerProps = new HashMap<String, Object>() {{
+ put("group.id", consumerGroupName);
+ put("auto.offset.reset", "latest");
+ }};
+ // create consumers before starting the connectors so we don't need to wait for discovery
+ waitForConsumingAllRecords(primary.kafka().createConsumerAndSubscribeTo(consumerProps, "test-topic-1"), 0);
+ waitForConsumingAllRecords(backup.kafka().createConsumerAndSubscribeTo(consumerProps, "test-topic-1"), 0);
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS);
+ waitUntilMirrorMakerIsRunning(primary, CONNECTOR_LIST, mm2Config, BACKUP_CLUSTER_ALIAS, PRIMARY_CLUSTER_ALIAS);
+
+ MirrorClient primaryClient = new MirrorClient(mm2Config.clientConfig(PRIMARY_CLUSTER_ALIAS));
+ MirrorClient backupClient = new MirrorClient(mm2Config.clientConfig(BACKUP_CLUSTER_ALIAS));
+
+ assertEquals("topic config was not synced", TopicConfig.CLEANUP_POLICY_COMPACT,
+ getTopicConfig(backup.kafka(), "primary.test-topic-1", TopicConfig.CLEANUP_POLICY_CONFIG));
+
+ assertEquals("Records were not produced to primary cluster.", NUM_RECORDS_PRODUCED,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "test-topic-1").count());
+ assertEquals("Records were not replicated to backup cluster.", NUM_RECORDS_PRODUCED,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "primary.test-topic-1").count());
+ assertEquals("Records were not produced to backup cluster.", NUM_RECORDS_PRODUCED,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "test-topic-1").count());
+ assertEquals("Records were not replicated to primary cluster.", NUM_RECORDS_PRODUCED,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "backup.test-topic-1").count());
+
+ assertEquals("Primary cluster doesn't have all records from both clusters.", NUM_RECORDS_PRODUCED * 2,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED * 2, RECORD_TRANSFER_DURATION_MS, "backup.test-topic-1", "test-topic-1").count());
+ assertEquals("Backup cluster doesn't have all records from both clusters.", NUM_RECORDS_PRODUCED * 2,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED * 2, RECORD_TRANSFER_DURATION_MS, "primary.test-topic-1", "test-topic-1").count());
+
+ assertTrue("Heartbeats were not emitted to primary cluster.", primary.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "heartbeats").count() > 0);
+ assertTrue("Heartbeats were not emitted to backup cluster.", backup.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "heartbeats").count() > 0);
+ assertTrue("Heartbeats were not replicated downstream to backup cluster.", backup.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "primary.heartbeats").count() > 0);
+ assertTrue("Heartbeats were not replicated downstream to primary cluster.", primary.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "backup.heartbeats").count() > 0);
+
+ assertTrue("Did not find upstream primary cluster.", backupClient.upstreamClusters().contains(PRIMARY_CLUSTER_ALIAS));
+ assertEquals("Did not calculate replication hops correctly.", 1, backupClient.replicationHops(PRIMARY_CLUSTER_ALIAS));
+ assertTrue("Did not find upstream backup cluster.", primaryClient.upstreamClusters().contains(BACKUP_CLUSTER_ALIAS));
+ assertEquals("Did not calculate replication hops correctly.", 1, primaryClient.replicationHops(BACKUP_CLUSTER_ALIAS));
+ assertTrue("Checkpoints were not emitted downstream to backup cluster.", backup.kafka().consume(1,
+ CHECKPOINT_DURATION_MS, "primary.checkpoints.internal").count() > 0);
+
+ Map<TopicPartition, OffsetAndMetadata> backupOffsets = backupClient.remoteConsumerOffsets(consumerGroupName, PRIMARY_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS));
+
+ assertTrue("Offsets not translated downstream to backup cluster. Found: " + backupOffsets, backupOffsets.containsKey(
+ new TopicPartition("primary.test-topic-1", 0)));
+
+ // Failover consumer group to backup cluster.
+ try (Consumer<byte[], byte[]> primaryConsumer = backup.kafka().createConsumer(Collections.singletonMap("group.id", consumerGroupName))) {
+ primaryConsumer.assign(backupOffsets.keySet());
+ backupOffsets.forEach(primaryConsumer::seek);
+ primaryConsumer.poll(CONSUMER_POLL_TIMEOUT_MS);
+ primaryConsumer.commitAsync();
+
+ assertTrue("Consumer failedover to zero offset.", primaryConsumer.position(new TopicPartition("primary.test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedover beyond expected offset.", primaryConsumer.position(
+ new TopicPartition("primary.test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+ assertTrue("Checkpoints were not emitted upstream to primary cluster.", primary.kafka().consume(1,
+ CHECKPOINT_DURATION_MS, "backup.checkpoints.internal").count() > 0);
+ }
+
+ waitForCondition(() -> {
+ return primaryClient.remoteConsumerOffsets(consumerGroupName, BACKUP_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS)).containsKey(new TopicPartition("backup.test-topic-1", 0));
+ }, CHECKPOINT_DURATION_MS, "Offsets not translated downstream to primary cluster.");
+
+ waitForCondition(() -> {
+ return primaryClient.remoteConsumerOffsets(consumerGroupName, BACKUP_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS)).containsKey(new TopicPartition("test-topic-1", 0));
+ }, CHECKPOINT_DURATION_MS, "Offsets not translated upstream to primary cluster.");
+
+ Map<TopicPartition, OffsetAndMetadata> primaryOffsets = primaryClient.remoteConsumerOffsets(consumerGroupName, BACKUP_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS));
+
+ // Failback consumer group to primary cluster
+ try (Consumer<byte[], byte[]> backupConsumer = primary.kafka().createConsumer(Collections.singletonMap("group.id", consumerGroupName))) {
+ backupConsumer.assign(primaryOffsets.keySet());
+ primaryOffsets.forEach(backupConsumer::seek);
+ backupConsumer.poll(CONSUMER_POLL_TIMEOUT_MS);
+ backupConsumer.commitAsync();
+
+ assertTrue("Consumer failedback to zero upstream offset.", backupConsumer.position(new TopicPartition("test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedback to zero downstream offset.", backupConsumer.position(new TopicPartition("backup.test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedback beyond expected upstream offset.", backupConsumer.position(
+ new TopicPartition("test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+ assertTrue("Consumer failedback beyond expected downstream offset.", backupConsumer.position(
+ new TopicPartition("backup.test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+ }
+
+ // create more matching topics
+ primary.kafka().createTopic("test-topic-2", NUM_PARTITIONS);
+ backup.kafka().createTopic("test-topic-3", NUM_PARTITIONS);
+
+ // only produce messages to the first partition
+ produceMessages(primary, "test-topic-2", 1);
+ produceMessages(backup, "test-topic-3", 1);
+
+ // expect total consumed messages equals to NUM_RECORDS_PER_PARTITION
+ assertEquals("Records were not produced to primary cluster.", NUM_RECORDS_PER_PARTITION,
+ primary.kafka().consume(NUM_RECORDS_PER_PARTITION, RECORD_TRANSFER_DURATION_MS, "test-topic-2").count());
+ assertEquals("Records were not produced to backup cluster.", NUM_RECORDS_PER_PARTITION,
+ backup.kafka().consume(NUM_RECORDS_PER_PARTITION, RECORD_TRANSFER_DURATION_MS, "test-topic-3").count());
+
+ assertEquals("New topic was not replicated to primary cluster.", NUM_RECORDS_PER_PARTITION,
+ primary.kafka().consume(NUM_RECORDS_PER_PARTITION, 2 * RECORD_TRANSFER_DURATION_MS, "backup.test-topic-3").count());
+ assertEquals("New topic was not replicated to backup cluster.", NUM_RECORDS_PER_PARTITION,
+ backup.kafka().consume(NUM_RECORDS_PER_PARTITION, 2 * RECORD_TRANSFER_DURATION_MS, "primary.test-topic-2").count());
+
+ }
+
+ @Test
+ public void testReplicationWithEmptyPartition() throws Exception {
+ String consumerGroupName = "consumer-group-testReplicationWithEmptyPartition";
+ Map<String, Object> consumerProps = Collections.singletonMap("group.id", consumerGroupName);
+
+ // create topic
+ String topic = "test-topic-with-empty-partition";
+ primary.kafka().createTopic(topic, NUM_PARTITIONS);
+
+ // produce to all test-topic-empty's partitions, except the last partition
+ produceMessages(primary, topic, NUM_PARTITIONS - 1);
+
+ // consume before starting the connectors so we don't need to wait for discovery
+ int expectedRecords = NUM_RECORDS_PER_PARTITION * (NUM_PARTITIONS - 1);
+ try (Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps, topic)) {
+ waitForConsumingAllRecords(primaryConsumer, expectedRecords);
+ }
+
+ // one way replication from primary to backup
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + "->" + PRIMARY_CLUSTER_ALIAS + ".enabled", "false");
+ mm2Config = new MirrorMakerConfig(mm2Props);
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS);
+
+ // sleep few seconds to have MM2 finish replication so that "end" consumer will consume some record
+ Thread.sleep(TimeUnit.SECONDS.toMillis(3));
+
+ // consume all records from backup cluster
+ try (Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(consumerProps,
+ PRIMARY_CLUSTER_ALIAS + "." + topic)) {
+ waitForConsumingAllRecords(backupConsumer, expectedRecords);
+ }
+
+ Admin backupClient = backup.kafka().createAdminClient();
+ // retrieve the consumer group offset from backup cluster
+ Map<TopicPartition, OffsetAndMetadata> remoteOffsets =
+ backupClient.listConsumerGroupOffsets(consumerGroupName).partitionsToOffsetAndMetadata().get();
+ // pinpoint the offset of the last partition which does not receive records
+ OffsetAndMetadata offset = remoteOffsets.get(new TopicPartition(PRIMARY_CLUSTER_ALIAS + "." + topic, NUM_PARTITIONS - 1));
+ // offset of the last partition should exist, but its value should be 0
+ assertNotNull("Offset of last partition was not replicated", offset);
+ assertEquals("Offset of last partition is not zero", 0, offset.offset());
+ }
+
+ @Test
+ public void testOneWayReplicationWithAutoOffsetSync() throws InterruptedException {
+ produceMessages(primary, "test-topic-1");
+ String consumerGroupName = "consumer-group-testOneWayReplicationWithAutoOffsetSync";
+ Map<String, Object> consumerProps = new HashMap<String, Object>() {{
+ put("group.id", consumerGroupName);
+ put("auto.offset.reset", "earliest");
+ }};
+ // create consumers before starting the connectors so we don't need to wait for discovery
+ try (Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps,
+ "test-topic-1")) {
+ // we need to wait for consuming all the records for MM2 replicating the expected offsets
+ waitForConsumingAllRecords(primaryConsumer, NUM_RECORDS_PRODUCED);
+ }
+
+ // enable automated consumer group offset sync
+ mm2Props.put("sync.group.offsets.enabled", "true");
+ mm2Props.put("sync.group.offsets.interval.seconds", "1");
+ // one way replication from primary to backup
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + "->" + PRIMARY_CLUSTER_ALIAS + ".enabled", "false");
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS);
+
+ // create a consumer at backup cluster with same consumer group Id to consume 1 topic
+ Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(
+ consumerProps, "primary.test-topic-1");
+
+ waitForConsumerGroupOffsetSync(backup, backupConsumer, Collections.singletonList("primary.test-topic-1"),
+ consumerGroupName, NUM_RECORDS_PRODUCED);
+
+ ConsumerRecords<byte[], byte[]> records = backupConsumer.poll(CONSUMER_POLL_TIMEOUT_MS);
+
+ // the size of consumer record should be zero, because the offsets of the same consumer group
+ // have been automatically synchronized from primary to backup by the background job, so no
+ // more records to consume from the replicated topic by the same consumer group at backup cluster
+ assertEquals("consumer record size is not zero", 0, records.count());
+
+ // now create a new topic in primary cluster
+ primary.kafka().createTopic("test-topic-2", NUM_PARTITIONS);
+ backup.kafka().createTopic("primary.test-topic-2", 1);
+ // produce some records to the new topic in primary cluster
+ produceMessages(primary, "test-topic-2");
+
+ // create a consumer at primary cluster to consume the new topic
+ try (Consumer<byte[], byte[]> consumer1 = primary.kafka().createConsumerAndSubscribeTo(Collections.singletonMap(
+ "group.id", "consumer-group-1"), "test-topic-2")) {
+ // we need to wait for consuming all the records for MM2 replicating the expected offsets
+ waitForConsumingAllRecords(consumer1, NUM_RECORDS_PRODUCED);
+ }
+
+ // create a consumer at backup cluster with same consumer group Id to consume old and new topic
+ backupConsumer = backup.kafka().createConsumerAndSubscribeTo(Collections.singletonMap(
+ "group.id", consumerGroupName), "primary.test-topic-1", "primary.test-topic-2");
+
+ waitForConsumerGroupOffsetSync(backup, backupConsumer, Arrays.asList("primary.test-topic-1", "primary.test-topic-2"),
+ consumerGroupName, NUM_RECORDS_PRODUCED);
+
+ records = backupConsumer.poll(CONSUMER_POLL_TIMEOUT_MS);
+ // similar reasoning as above, no more records to consume by the same consumer group at backup cluster
+ assertEquals("consumer record size is not zero", 0, records.count());
+ backupConsumer.close();
+ }
+
+ /*
+ * launch the connectors on kafka connect cluster and check if they are running
+ */
+ private static void waitUntilMirrorMakerIsRunning(EmbeddedConnectCluster connectCluster,
+ List<Class<? extends Connector>> connectorClasses, MirrorMakerConfig mm2Config,
+ String primary, String backup) throws InterruptedException {
+ for (int i = 0; i < connectorClasses.size(); i++) {
+ String connector = connectorClasses.get(i).getSimpleName();
+ connectCluster.configureConnector(connector, mm2Config.connectorBaseConfig(
+ new SourceAndTarget(primary, backup), connectorClasses.get(i)));
+ }
+
+ // we wait for the connector and tasks to come up for each connector, so that when we do the
+ // actual testing, we are certain that the tasks are up and running; this will prevent
+ // flaky tests where the connector and tasks didn't start up in time for the tests to be run
+ List<String> connectorNames = connectorClasses.stream().map(x -> x.getSimpleName())
+ .collect(Collectors.toList());
+ for (String connector : connectorNames) {
+ connectCluster.assertions().assertConnectorAndAtLeastNumTasksAreRunning(connector, 1,
+ "Connector " + connector + " tasks did not start in time on cluster: " + connectCluster);
+ }
+ }
+
+ /*
+ * delete all topics of the input kafka cluster
+ */
+ private static void deleteAllTopics(EmbeddedKafkaCluster cluster) throws Exception {
+ Admin client = cluster.createAdminClient();
+ client.deleteTopics(client.listTopics().names().get());
+ }
+
+ /*
+ * retrieve the config value based on the input cluster, topic and config name
+ */
+ private static String getTopicConfig(EmbeddedKafkaCluster cluster, String topic, String configName)
+ throws Exception {
+ Admin client = cluster.createAdminClient();
+ Collection<ConfigResource> cr = Collections.singleton(
+ new ConfigResource(ConfigResource.Type.TOPIC, topic));
+
+ DescribeConfigsResult configsResult = client.describeConfigs(cr);
+ Config allConfigs = (Config) configsResult.all().get().values().toArray()[0];
Review comment:
We can use `Config.get()` to directly access the configuration we want, see https://kafka.apache.org/26/javadoc/org/apache/kafka/clients/admin/Config.html#get-java.lang.String-
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationBaseTest.java
##########
@@ -0,0 +1,577 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.Config;
+import org.apache.kafka.clients.admin.ConfigEntry;
+import org.apache.kafka.clients.admin.DescribeConfigsResult;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.config.ConfigResource;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.connector.Connector;
+import org.apache.kafka.connect.mirror.MirrorClient;
+import org.apache.kafka.connect.mirror.MirrorHeartbeatConnector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.MirrorSourceConnector;
+import org.apache.kafka.connect.mirror.SourceAndTarget;
+import org.apache.kafka.connect.mirror.MirrorCheckpointConnector;
+import org.apache.kafka.connect.util.clusters.EmbeddedConnectCluster;
+import org.apache.kafka.connect.util.clusters.EmbeddedKafkaCluster;
+import org.apache.kafka.test.IntegrationTest;
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertNotNull;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.junit.After;
+import org.junit.Before;
+
+import static org.apache.kafka.connect.mirror.TestUtils.generateRecords;
+
+/**
+ * Tests MM2 replication and failover/failback logic.
+ *
+ * MM2 is configured with active/active replication between two Kafka clusters. Tests validate that
+ * records sent to either cluster arrive at the other cluster. Then, a consumer group is migrated from
+ * one cluster to the other and back. Tests validate that consumer offsets are translated and replicated
+ * between clusters during this failover and failback.
+ */
+@Category(IntegrationTest.class)
+public abstract class MirrorConnectorsIntegrationBaseTest {
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationBaseTest.class);
+
+ private static final int NUM_RECORDS_PER_PARTITION = 10;
+ private static final int NUM_PARTITIONS = 10;
+ private static final int NUM_RECORDS_PRODUCED = NUM_PARTITIONS * NUM_RECORDS_PER_PARTITION;
+ private static final int RECORD_TRANSFER_DURATION_MS = 30_000;
+ private static final int CHECKPOINT_DURATION_MS = 20_000;
+ private static final int RECORD_CONSUME_DURATION_MS = 20_000;
+ private static final int OFFSET_SYNC_DURATION_MS = 30_000;
+ private static final int NUM_WORKERS = 3;
+ private static final Duration CONSUMER_POLL_TIMEOUT_MS = Duration.ofMillis(500);
+ private static final int BROKER_RESTART_TIMEOUT_MS = 10_000;
+ protected static final String PRIMARY_CLUSTER_ALIAS = "primary";
+ protected static final String BACKUP_CLUSTER_ALIAS = "backup";
+ private static final List<Class<? extends Connector>> CONNECTOR_LIST =
+ Arrays.asList(MirrorSourceConnector.class, MirrorCheckpointConnector.class, MirrorHeartbeatConnector.class);
+
+ protected Map<String, String> mm2Props = new HashMap<>();
+ private MirrorMakerConfig mm2Config;
+ private EmbeddedConnectCluster primary;
+ private EmbeddedConnectCluster backup;
+
+ private final AtomicBoolean exited = new AtomicBoolean(false);
+ protected Properties primaryBrokerProps = new Properties();
+ protected Properties backupBrokerProps = new Properties();
+ protected Map<String, String> primaryWorkerProps = new HashMap<>();
+ protected Map<String, String> backupWorkerProps = new HashMap<>();
+
+ @Before
+ public void startClusters() throws InterruptedException {
+ primaryBrokerProps.put("auto.create.topics.enable", "false");
+ backupBrokerProps.put("auto.create.topics.enable", "false");
+
+ mm2Props.putAll(basicMM2Config());
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+ primaryWorkerProps = mm2Config.workerConfig(new SourceAndTarget(BACKUP_CLUSTER_ALIAS, PRIMARY_CLUSTER_ALIAS));
+ backupWorkerProps.putAll(mm2Config.workerConfig(new SourceAndTarget(PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS)));
+
+ primary = new EmbeddedConnectCluster.Builder()
+ .name(PRIMARY_CLUSTER_ALIAS + "-connect-cluster")
+ .numWorkers(NUM_WORKERS)
+ .numBrokers(1)
+ .brokerProps(primaryBrokerProps)
+ .workerProps(primaryWorkerProps)
+ .build();
+
+ backup = new EmbeddedConnectCluster.Builder()
+ .name(BACKUP_CLUSTER_ALIAS + "-connect-cluster")
+ .numWorkers(NUM_WORKERS)
+ .numBrokers(1)
+ .brokerProps(backupBrokerProps)
+ .workerProps(backupWorkerProps)
+ .build();
+
+ primary.start();
+ primary.assertions().assertAtLeastNumWorkersAreUp(NUM_WORKERS,
+ "Workers of " + PRIMARY_CLUSTER_ALIAS + "-connect-cluster did not start in time.");
+
+ backup.start();
+ backup.assertions().assertAtLeastNumWorkersAreUp(NUM_WORKERS,
+ "Workers of " + BACKUP_CLUSTER_ALIAS + "-connect-cluster did not start in time.");
+
+ createTopics();
+
+ warmUpConsumer();
+
+ log.info(PRIMARY_CLUSTER_ALIAS + " REST service: {}", primary.endpointForResource("connectors"));
+ log.info(BACKUP_CLUSTER_ALIAS + " REST service: {}", backup.endpointForResource("connectors"));
+ log.info(PRIMARY_CLUSTER_ALIAS + " brokers: {}", primary.kafka().bootstrapServers());
+ log.info(BACKUP_CLUSTER_ALIAS + " brokers: {}", backup.kafka().bootstrapServers());
+
+ // now that the brokers are running, we can finish setting up the Connectors
+ mm2Props.put(PRIMARY_CLUSTER_ALIAS + ".bootstrap.servers", primary.kafka().bootstrapServers());
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + ".bootstrap.servers", backup.kafka().bootstrapServers());
+
+ Exit.setExitProcedure((status, errorCode) -> exited.set(true));
+ }
+
+ @After
+ public void shutdownClusters() throws Exception {
+ for (String x : primary.connectors()) {
+ primary.deleteConnector(x);
+ }
+ for (String x : backup.connectors()) {
+ backup.deleteConnector(x);
+ }
+ deleteAllTopics(primary.kafka());
+ deleteAllTopics(backup.kafka());
+ primary.stop();
+ backup.stop();
+ try {
+ assertFalse(exited.get());
+ } finally {
+ Exit.resetExitProcedure();
+ }
+ }
+
+ @Test
+ public void testReplication() throws Exception {
+ produceMessages(primary, "test-topic-1");
+ produceMessages(backup, "test-topic-1");
+ String consumerGroupName = "consumer-group-testReplication";
+ Map<String, Object> consumerProps = new HashMap<String, Object>() {{
+ put("group.id", consumerGroupName);
+ put("auto.offset.reset", "latest");
+ }};
+ // create consumers before starting the connectors so we don't need to wait for discovery
+ waitForConsumingAllRecords(primary.kafka().createConsumerAndSubscribeTo(consumerProps, "test-topic-1"), 0);
+ waitForConsumingAllRecords(backup.kafka().createConsumerAndSubscribeTo(consumerProps, "test-topic-1"), 0);
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS);
+ waitUntilMirrorMakerIsRunning(primary, CONNECTOR_LIST, mm2Config, BACKUP_CLUSTER_ALIAS, PRIMARY_CLUSTER_ALIAS);
+
+ MirrorClient primaryClient = new MirrorClient(mm2Config.clientConfig(PRIMARY_CLUSTER_ALIAS));
+ MirrorClient backupClient = new MirrorClient(mm2Config.clientConfig(BACKUP_CLUSTER_ALIAS));
+
+ assertEquals("topic config was not synced", TopicConfig.CLEANUP_POLICY_COMPACT,
+ getTopicConfig(backup.kafka(), "primary.test-topic-1", TopicConfig.CLEANUP_POLICY_CONFIG));
+
+ assertEquals("Records were not produced to primary cluster.", NUM_RECORDS_PRODUCED,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "test-topic-1").count());
+ assertEquals("Records were not replicated to backup cluster.", NUM_RECORDS_PRODUCED,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "primary.test-topic-1").count());
+ assertEquals("Records were not produced to backup cluster.", NUM_RECORDS_PRODUCED,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "test-topic-1").count());
+ assertEquals("Records were not replicated to primary cluster.", NUM_RECORDS_PRODUCED,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "backup.test-topic-1").count());
+
+ assertEquals("Primary cluster doesn't have all records from both clusters.", NUM_RECORDS_PRODUCED * 2,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED * 2, RECORD_TRANSFER_DURATION_MS, "backup.test-topic-1", "test-topic-1").count());
+ assertEquals("Backup cluster doesn't have all records from both clusters.", NUM_RECORDS_PRODUCED * 2,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED * 2, RECORD_TRANSFER_DURATION_MS, "primary.test-topic-1", "test-topic-1").count());
+
+ assertTrue("Heartbeats were not emitted to primary cluster.", primary.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "heartbeats").count() > 0);
+ assertTrue("Heartbeats were not emitted to backup cluster.", backup.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "heartbeats").count() > 0);
+ assertTrue("Heartbeats were not replicated downstream to backup cluster.", backup.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "primary.heartbeats").count() > 0);
+ assertTrue("Heartbeats were not replicated downstream to primary cluster.", primary.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "backup.heartbeats").count() > 0);
+
+ assertTrue("Did not find upstream primary cluster.", backupClient.upstreamClusters().contains(PRIMARY_CLUSTER_ALIAS));
+ assertEquals("Did not calculate replication hops correctly.", 1, backupClient.replicationHops(PRIMARY_CLUSTER_ALIAS));
+ assertTrue("Did not find upstream backup cluster.", primaryClient.upstreamClusters().contains(BACKUP_CLUSTER_ALIAS));
+ assertEquals("Did not calculate replication hops correctly.", 1, primaryClient.replicationHops(BACKUP_CLUSTER_ALIAS));
+ assertTrue("Checkpoints were not emitted downstream to backup cluster.", backup.kafka().consume(1,
+ CHECKPOINT_DURATION_MS, "primary.checkpoints.internal").count() > 0);
+
+ Map<TopicPartition, OffsetAndMetadata> backupOffsets = backupClient.remoteConsumerOffsets(consumerGroupName, PRIMARY_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS));
+
+ assertTrue("Offsets not translated downstream to backup cluster. Found: " + backupOffsets, backupOffsets.containsKey(
+ new TopicPartition("primary.test-topic-1", 0)));
+
+ // Failover consumer group to backup cluster.
+ try (Consumer<byte[], byte[]> primaryConsumer = backup.kafka().createConsumer(Collections.singletonMap("group.id", consumerGroupName))) {
+ primaryConsumer.assign(backupOffsets.keySet());
+ backupOffsets.forEach(primaryConsumer::seek);
+ primaryConsumer.poll(CONSUMER_POLL_TIMEOUT_MS);
+ primaryConsumer.commitAsync();
+
+ assertTrue("Consumer failedover to zero offset.", primaryConsumer.position(new TopicPartition("primary.test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedover beyond expected offset.", primaryConsumer.position(
+ new TopicPartition("primary.test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+ assertTrue("Checkpoints were not emitted upstream to primary cluster.", primary.kafka().consume(1,
+ CHECKPOINT_DURATION_MS, "backup.checkpoints.internal").count() > 0);
+ }
+
+ waitForCondition(() -> {
+ return primaryClient.remoteConsumerOffsets(consumerGroupName, BACKUP_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS)).containsKey(new TopicPartition("backup.test-topic-1", 0));
+ }, CHECKPOINT_DURATION_MS, "Offsets not translated downstream to primary cluster.");
+
+ waitForCondition(() -> {
+ return primaryClient.remoteConsumerOffsets(consumerGroupName, BACKUP_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS)).containsKey(new TopicPartition("test-topic-1", 0));
+ }, CHECKPOINT_DURATION_MS, "Offsets not translated upstream to primary cluster.");
+
+ Map<TopicPartition, OffsetAndMetadata> primaryOffsets = primaryClient.remoteConsumerOffsets(consumerGroupName, BACKUP_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS));
+
+ // Failback consumer group to primary cluster
+ try (Consumer<byte[], byte[]> backupConsumer = primary.kafka().createConsumer(Collections.singletonMap("group.id", consumerGroupName))) {
+ backupConsumer.assign(primaryOffsets.keySet());
+ primaryOffsets.forEach(backupConsumer::seek);
+ backupConsumer.poll(CONSUMER_POLL_TIMEOUT_MS);
+ backupConsumer.commitAsync();
+
+ assertTrue("Consumer failedback to zero upstream offset.", backupConsumer.position(new TopicPartition("test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedback to zero downstream offset.", backupConsumer.position(new TopicPartition("backup.test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedback beyond expected upstream offset.", backupConsumer.position(
+ new TopicPartition("test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+ assertTrue("Consumer failedback beyond expected downstream offset.", backupConsumer.position(
+ new TopicPartition("backup.test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+ }
+
+ // create more matching topics
+ primary.kafka().createTopic("test-topic-2", NUM_PARTITIONS);
+ backup.kafka().createTopic("test-topic-3", NUM_PARTITIONS);
+
+ // only produce messages to the first partition
+ produceMessages(primary, "test-topic-2", 1);
+ produceMessages(backup, "test-topic-3", 1);
+
+ // expect total consumed messages equals to NUM_RECORDS_PER_PARTITION
+ assertEquals("Records were not produced to primary cluster.", NUM_RECORDS_PER_PARTITION,
+ primary.kafka().consume(NUM_RECORDS_PER_PARTITION, RECORD_TRANSFER_DURATION_MS, "test-topic-2").count());
+ assertEquals("Records were not produced to backup cluster.", NUM_RECORDS_PER_PARTITION,
+ backup.kafka().consume(NUM_RECORDS_PER_PARTITION, RECORD_TRANSFER_DURATION_MS, "test-topic-3").count());
+
+ assertEquals("New topic was not replicated to primary cluster.", NUM_RECORDS_PER_PARTITION,
+ primary.kafka().consume(NUM_RECORDS_PER_PARTITION, 2 * RECORD_TRANSFER_DURATION_MS, "backup.test-topic-3").count());
+ assertEquals("New topic was not replicated to backup cluster.", NUM_RECORDS_PER_PARTITION,
+ backup.kafka().consume(NUM_RECORDS_PER_PARTITION, 2 * RECORD_TRANSFER_DURATION_MS, "primary.test-topic-2").count());
+
+ }
+
+ @Test
+ public void testReplicationWithEmptyPartition() throws Exception {
+ String consumerGroupName = "consumer-group-testReplicationWithEmptyPartition";
+ Map<String, Object> consumerProps = Collections.singletonMap("group.id", consumerGroupName);
+
+ // create topic
+ String topic = "test-topic-with-empty-partition";
+ primary.kafka().createTopic(topic, NUM_PARTITIONS);
+
+ // produce to all test-topic-empty's partitions, except the last partition
+ produceMessages(primary, topic, NUM_PARTITIONS - 1);
+
+ // consume before starting the connectors so we don't need to wait for discovery
+ int expectedRecords = NUM_RECORDS_PER_PARTITION * (NUM_PARTITIONS - 1);
+ try (Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps, topic)) {
+ waitForConsumingAllRecords(primaryConsumer, expectedRecords);
+ }
+
+ // one way replication from primary to backup
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + "->" + PRIMARY_CLUSTER_ALIAS + ".enabled", "false");
+ mm2Config = new MirrorMakerConfig(mm2Props);
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS);
+
+ // sleep few seconds to have MM2 finish replication so that "end" consumer will consume some record
+ Thread.sleep(TimeUnit.SECONDS.toMillis(3));
+
+ // consume all records from backup cluster
+ try (Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(consumerProps,
+ PRIMARY_CLUSTER_ALIAS + "." + topic)) {
+ waitForConsumingAllRecords(backupConsumer, expectedRecords);
+ }
+
+ Admin backupClient = backup.kafka().createAdminClient();
+ // retrieve the consumer group offset from backup cluster
+ Map<TopicPartition, OffsetAndMetadata> remoteOffsets =
+ backupClient.listConsumerGroupOffsets(consumerGroupName).partitionsToOffsetAndMetadata().get();
+ // pinpoint the offset of the last partition which does not receive records
+ OffsetAndMetadata offset = remoteOffsets.get(new TopicPartition(PRIMARY_CLUSTER_ALIAS + "." + topic, NUM_PARTITIONS - 1));
+ // offset of the last partition should exist, but its value should be 0
+ assertNotNull("Offset of last partition was not replicated", offset);
+ assertEquals("Offset of last partition is not zero", 0, offset.offset());
+ }
+
+ @Test
+ public void testOneWayReplicationWithAutoOffsetSync() throws InterruptedException {
+ produceMessages(primary, "test-topic-1");
+ String consumerGroupName = "consumer-group-testOneWayReplicationWithAutoOffsetSync";
+ Map<String, Object> consumerProps = new HashMap<String, Object>() {{
+ put("group.id", consumerGroupName);
+ put("auto.offset.reset", "earliest");
+ }};
+ // create consumers before starting the connectors so we don't need to wait for discovery
+ try (Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps,
+ "test-topic-1")) {
+ // we need to wait for consuming all the records for MM2 replicating the expected offsets
+ waitForConsumingAllRecords(primaryConsumer, NUM_RECORDS_PRODUCED);
+ }
+
+ // enable automated consumer group offset sync
+ mm2Props.put("sync.group.offsets.enabled", "true");
+ mm2Props.put("sync.group.offsets.interval.seconds", "1");
+ // one way replication from primary to backup
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + "->" + PRIMARY_CLUSTER_ALIAS + ".enabled", "false");
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS);
+
+ // create a consumer at backup cluster with same consumer group Id to consume 1 topic
+ Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(
+ consumerProps, "primary.test-topic-1");
+
+ waitForConsumerGroupOffsetSync(backup, backupConsumer, Collections.singletonList("primary.test-topic-1"),
+ consumerGroupName, NUM_RECORDS_PRODUCED);
+
+ ConsumerRecords<byte[], byte[]> records = backupConsumer.poll(CONSUMER_POLL_TIMEOUT_MS);
+
+ // the size of consumer record should be zero, because the offsets of the same consumer group
+ // have been automatically synchronized from primary to backup by the background job, so no
+ // more records to consume from the replicated topic by the same consumer group at backup cluster
+ assertEquals("consumer record size is not zero", 0, records.count());
+
+ // now create a new topic in primary cluster
+ primary.kafka().createTopic("test-topic-2", NUM_PARTITIONS);
+ backup.kafka().createTopic("primary.test-topic-2", 1);
+ // produce some records to the new topic in primary cluster
+ produceMessages(primary, "test-topic-2");
+
+ // create a consumer at primary cluster to consume the new topic
+ try (Consumer<byte[], byte[]> consumer1 = primary.kafka().createConsumerAndSubscribeTo(Collections.singletonMap(
+ "group.id", "consumer-group-1"), "test-topic-2")) {
+ // we need to wait for consuming all the records for MM2 replicating the expected offsets
+ waitForConsumingAllRecords(consumer1, NUM_RECORDS_PRODUCED);
+ }
+
+ // create a consumer at backup cluster with same consumer group Id to consume old and new topic
+ backupConsumer = backup.kafka().createConsumerAndSubscribeTo(Collections.singletonMap(
+ "group.id", consumerGroupName), "primary.test-topic-1", "primary.test-topic-2");
+
+ waitForConsumerGroupOffsetSync(backup, backupConsumer, Arrays.asList("primary.test-topic-1", "primary.test-topic-2"),
+ consumerGroupName, NUM_RECORDS_PRODUCED);
+
+ records = backupConsumer.poll(CONSUMER_POLL_TIMEOUT_MS);
+ // similar reasoning as above, no more records to consume by the same consumer group at backup cluster
+ assertEquals("consumer record size is not zero", 0, records.count());
+ backupConsumer.close();
+ }
+
+ /*
+ * launch the connectors on kafka connect cluster and check if they are running
+ */
+ private static void waitUntilMirrorMakerIsRunning(EmbeddedConnectCluster connectCluster,
+ List<Class<? extends Connector>> connectorClasses, MirrorMakerConfig mm2Config,
+ String primary, String backup) throws InterruptedException {
+ for (int i = 0; i < connectorClasses.size(); i++) {
+ String connector = connectorClasses.get(i).getSimpleName();
+ connectCluster.configureConnector(connector, mm2Config.connectorBaseConfig(
+ new SourceAndTarget(primary, backup), connectorClasses.get(i)));
+ }
+
+ // we wait for the connector and tasks to come up for each connector, so that when we do the
+ // actual testing, we are certain that the tasks are up and running; this will prevent
+ // flaky tests where the connector and tasks didn't start up in time for the tests to be run
+ List<String> connectorNames = connectorClasses.stream().map(x -> x.getSimpleName())
Review comment:
This intermediate `List` is not really useful. We could just change the loop below to iterate over the connector classes and call `getSimpleName()` on each of them
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationBaseTest.java
##########
@@ -0,0 +1,577 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.Config;
+import org.apache.kafka.clients.admin.ConfigEntry;
+import org.apache.kafka.clients.admin.DescribeConfigsResult;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.config.ConfigResource;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.connector.Connector;
+import org.apache.kafka.connect.mirror.MirrorClient;
+import org.apache.kafka.connect.mirror.MirrorHeartbeatConnector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.MirrorSourceConnector;
+import org.apache.kafka.connect.mirror.SourceAndTarget;
+import org.apache.kafka.connect.mirror.MirrorCheckpointConnector;
+import org.apache.kafka.connect.util.clusters.EmbeddedConnectCluster;
+import org.apache.kafka.connect.util.clusters.EmbeddedKafkaCluster;
+import org.apache.kafka.test.IntegrationTest;
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertNotNull;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.junit.After;
+import org.junit.Before;
+
+import static org.apache.kafka.connect.mirror.TestUtils.generateRecords;
+
+/**
+ * Tests MM2 replication and failover/failback logic.
+ *
+ * MM2 is configured with active/active replication between two Kafka clusters. Tests validate that
+ * records sent to either cluster arrive at the other cluster. Then, a consumer group is migrated from
+ * one cluster to the other and back. Tests validate that consumer offsets are translated and replicated
+ * between clusters during this failover and failback.
+ */
+@Category(IntegrationTest.class)
+public abstract class MirrorConnectorsIntegrationBaseTest {
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationBaseTest.class);
+
+ private static final int NUM_RECORDS_PER_PARTITION = 10;
+ private static final int NUM_PARTITIONS = 10;
+ private static final int NUM_RECORDS_PRODUCED = NUM_PARTITIONS * NUM_RECORDS_PER_PARTITION;
+ private static final int RECORD_TRANSFER_DURATION_MS = 30_000;
+ private static final int CHECKPOINT_DURATION_MS = 20_000;
+ private static final int RECORD_CONSUME_DURATION_MS = 20_000;
+ private static final int OFFSET_SYNC_DURATION_MS = 30_000;
+ private static final int NUM_WORKERS = 3;
+ private static final Duration CONSUMER_POLL_TIMEOUT_MS = Duration.ofMillis(500);
+ private static final int BROKER_RESTART_TIMEOUT_MS = 10_000;
+ protected static final String PRIMARY_CLUSTER_ALIAS = "primary";
+ protected static final String BACKUP_CLUSTER_ALIAS = "backup";
+ private static final List<Class<? extends Connector>> CONNECTOR_LIST =
+ Arrays.asList(MirrorSourceConnector.class, MirrorCheckpointConnector.class, MirrorHeartbeatConnector.class);
+
+ protected Map<String, String> mm2Props = new HashMap<>();
+ private MirrorMakerConfig mm2Config;
+ private EmbeddedConnectCluster primary;
+ private EmbeddedConnectCluster backup;
+
+ private final AtomicBoolean exited = new AtomicBoolean(false);
+ protected Properties primaryBrokerProps = new Properties();
+ protected Properties backupBrokerProps = new Properties();
+ protected Map<String, String> primaryWorkerProps = new HashMap<>();
+ protected Map<String, String> backupWorkerProps = new HashMap<>();
+
+ @Before
+ public void startClusters() throws InterruptedException {
+ primaryBrokerProps.put("auto.create.topics.enable", "false");
+ backupBrokerProps.put("auto.create.topics.enable", "false");
+
+ mm2Props.putAll(basicMM2Config());
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+ primaryWorkerProps = mm2Config.workerConfig(new SourceAndTarget(BACKUP_CLUSTER_ALIAS, PRIMARY_CLUSTER_ALIAS));
+ backupWorkerProps.putAll(mm2Config.workerConfig(new SourceAndTarget(PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS)));
+
+ primary = new EmbeddedConnectCluster.Builder()
+ .name(PRIMARY_CLUSTER_ALIAS + "-connect-cluster")
+ .numWorkers(NUM_WORKERS)
+ .numBrokers(1)
+ .brokerProps(primaryBrokerProps)
+ .workerProps(primaryWorkerProps)
+ .build();
+
+ backup = new EmbeddedConnectCluster.Builder()
+ .name(BACKUP_CLUSTER_ALIAS + "-connect-cluster")
+ .numWorkers(NUM_WORKERS)
+ .numBrokers(1)
+ .brokerProps(backupBrokerProps)
+ .workerProps(backupWorkerProps)
+ .build();
+
+ primary.start();
+ primary.assertions().assertAtLeastNumWorkersAreUp(NUM_WORKERS,
+ "Workers of " + PRIMARY_CLUSTER_ALIAS + "-connect-cluster did not start in time.");
+
+ backup.start();
+ backup.assertions().assertAtLeastNumWorkersAreUp(NUM_WORKERS,
+ "Workers of " + BACKUP_CLUSTER_ALIAS + "-connect-cluster did not start in time.");
+
+ createTopics();
+
+ warmUpConsumer();
+
+ log.info(PRIMARY_CLUSTER_ALIAS + " REST service: {}", primary.endpointForResource("connectors"));
+ log.info(BACKUP_CLUSTER_ALIAS + " REST service: {}", backup.endpointForResource("connectors"));
+ log.info(PRIMARY_CLUSTER_ALIAS + " brokers: {}", primary.kafka().bootstrapServers());
+ log.info(BACKUP_CLUSTER_ALIAS + " brokers: {}", backup.kafka().bootstrapServers());
+
+ // now that the brokers are running, we can finish setting up the Connectors
+ mm2Props.put(PRIMARY_CLUSTER_ALIAS + ".bootstrap.servers", primary.kafka().bootstrapServers());
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + ".bootstrap.servers", backup.kafka().bootstrapServers());
+
+ Exit.setExitProcedure((status, errorCode) -> exited.set(true));
+ }
+
+ @After
+ public void shutdownClusters() throws Exception {
+ for (String x : primary.connectors()) {
+ primary.deleteConnector(x);
+ }
+ for (String x : backup.connectors()) {
+ backup.deleteConnector(x);
+ }
+ deleteAllTopics(primary.kafka());
+ deleteAllTopics(backup.kafka());
+ primary.stop();
+ backup.stop();
+ try {
+ assertFalse(exited.get());
+ } finally {
+ Exit.resetExitProcedure();
+ }
+ }
+
+ @Test
+ public void testReplication() throws Exception {
+ produceMessages(primary, "test-topic-1");
+ produceMessages(backup, "test-topic-1");
+ String consumerGroupName = "consumer-group-testReplication";
+ Map<String, Object> consumerProps = new HashMap<String, Object>() {{
+ put("group.id", consumerGroupName);
+ put("auto.offset.reset", "latest");
+ }};
+ // create consumers before starting the connectors so we don't need to wait for discovery
+ waitForConsumingAllRecords(primary.kafka().createConsumerAndSubscribeTo(consumerProps, "test-topic-1"), 0);
+ waitForConsumingAllRecords(backup.kafka().createConsumerAndSubscribeTo(consumerProps, "test-topic-1"), 0);
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS);
+ waitUntilMirrorMakerIsRunning(primary, CONNECTOR_LIST, mm2Config, BACKUP_CLUSTER_ALIAS, PRIMARY_CLUSTER_ALIAS);
+
+ MirrorClient primaryClient = new MirrorClient(mm2Config.clientConfig(PRIMARY_CLUSTER_ALIAS));
+ MirrorClient backupClient = new MirrorClient(mm2Config.clientConfig(BACKUP_CLUSTER_ALIAS));
+
+ assertEquals("topic config was not synced", TopicConfig.CLEANUP_POLICY_COMPACT,
+ getTopicConfig(backup.kafka(), "primary.test-topic-1", TopicConfig.CLEANUP_POLICY_CONFIG));
+
+ assertEquals("Records were not produced to primary cluster.", NUM_RECORDS_PRODUCED,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "test-topic-1").count());
+ assertEquals("Records were not replicated to backup cluster.", NUM_RECORDS_PRODUCED,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "primary.test-topic-1").count());
+ assertEquals("Records were not produced to backup cluster.", NUM_RECORDS_PRODUCED,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "test-topic-1").count());
+ assertEquals("Records were not replicated to primary cluster.", NUM_RECORDS_PRODUCED,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "backup.test-topic-1").count());
+
+ assertEquals("Primary cluster doesn't have all records from both clusters.", NUM_RECORDS_PRODUCED * 2,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED * 2, RECORD_TRANSFER_DURATION_MS, "backup.test-topic-1", "test-topic-1").count());
+ assertEquals("Backup cluster doesn't have all records from both clusters.", NUM_RECORDS_PRODUCED * 2,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED * 2, RECORD_TRANSFER_DURATION_MS, "primary.test-topic-1", "test-topic-1").count());
+
+ assertTrue("Heartbeats were not emitted to primary cluster.", primary.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "heartbeats").count() > 0);
+ assertTrue("Heartbeats were not emitted to backup cluster.", backup.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "heartbeats").count() > 0);
+ assertTrue("Heartbeats were not replicated downstream to backup cluster.", backup.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "primary.heartbeats").count() > 0);
+ assertTrue("Heartbeats were not replicated downstream to primary cluster.", primary.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "backup.heartbeats").count() > 0);
+
+ assertTrue("Did not find upstream primary cluster.", backupClient.upstreamClusters().contains(PRIMARY_CLUSTER_ALIAS));
+ assertEquals("Did not calculate replication hops correctly.", 1, backupClient.replicationHops(PRIMARY_CLUSTER_ALIAS));
+ assertTrue("Did not find upstream backup cluster.", primaryClient.upstreamClusters().contains(BACKUP_CLUSTER_ALIAS));
+ assertEquals("Did not calculate replication hops correctly.", 1, primaryClient.replicationHops(BACKUP_CLUSTER_ALIAS));
+ assertTrue("Checkpoints were not emitted downstream to backup cluster.", backup.kafka().consume(1,
+ CHECKPOINT_DURATION_MS, "primary.checkpoints.internal").count() > 0);
+
+ Map<TopicPartition, OffsetAndMetadata> backupOffsets = backupClient.remoteConsumerOffsets(consumerGroupName, PRIMARY_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS));
+
+ assertTrue("Offsets not translated downstream to backup cluster. Found: " + backupOffsets, backupOffsets.containsKey(
+ new TopicPartition("primary.test-topic-1", 0)));
+
+ // Failover consumer group to backup cluster.
+ try (Consumer<byte[], byte[]> primaryConsumer = backup.kafka().createConsumer(Collections.singletonMap("group.id", consumerGroupName))) {
+ primaryConsumer.assign(backupOffsets.keySet());
+ backupOffsets.forEach(primaryConsumer::seek);
+ primaryConsumer.poll(CONSUMER_POLL_TIMEOUT_MS);
+ primaryConsumer.commitAsync();
+
+ assertTrue("Consumer failedover to zero offset.", primaryConsumer.position(new TopicPartition("primary.test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedover beyond expected offset.", primaryConsumer.position(
+ new TopicPartition("primary.test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+ assertTrue("Checkpoints were not emitted upstream to primary cluster.", primary.kafka().consume(1,
+ CHECKPOINT_DURATION_MS, "backup.checkpoints.internal").count() > 0);
+ }
+
+ waitForCondition(() -> {
+ return primaryClient.remoteConsumerOffsets(consumerGroupName, BACKUP_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS)).containsKey(new TopicPartition("backup.test-topic-1", 0));
+ }, CHECKPOINT_DURATION_MS, "Offsets not translated downstream to primary cluster.");
+
+ waitForCondition(() -> {
+ return primaryClient.remoteConsumerOffsets(consumerGroupName, BACKUP_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS)).containsKey(new TopicPartition("test-topic-1", 0));
+ }, CHECKPOINT_DURATION_MS, "Offsets not translated upstream to primary cluster.");
+
+ Map<TopicPartition, OffsetAndMetadata> primaryOffsets = primaryClient.remoteConsumerOffsets(consumerGroupName, BACKUP_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS));
+
+ // Failback consumer group to primary cluster
+ try (Consumer<byte[], byte[]> backupConsumer = primary.kafka().createConsumer(Collections.singletonMap("group.id", consumerGroupName))) {
+ backupConsumer.assign(primaryOffsets.keySet());
+ primaryOffsets.forEach(backupConsumer::seek);
+ backupConsumer.poll(CONSUMER_POLL_TIMEOUT_MS);
+ backupConsumer.commitAsync();
+
+ assertTrue("Consumer failedback to zero upstream offset.", backupConsumer.position(new TopicPartition("test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedback to zero downstream offset.", backupConsumer.position(new TopicPartition("backup.test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedback beyond expected upstream offset.", backupConsumer.position(
+ new TopicPartition("test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+ assertTrue("Consumer failedback beyond expected downstream offset.", backupConsumer.position(
+ new TopicPartition("backup.test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+ }
+
+ // create more matching topics
+ primary.kafka().createTopic("test-topic-2", NUM_PARTITIONS);
+ backup.kafka().createTopic("test-topic-3", NUM_PARTITIONS);
+
+ // only produce messages to the first partition
+ produceMessages(primary, "test-topic-2", 1);
+ produceMessages(backup, "test-topic-3", 1);
+
+ // expect total consumed messages equals to NUM_RECORDS_PER_PARTITION
+ assertEquals("Records were not produced to primary cluster.", NUM_RECORDS_PER_PARTITION,
+ primary.kafka().consume(NUM_RECORDS_PER_PARTITION, RECORD_TRANSFER_DURATION_MS, "test-topic-2").count());
+ assertEquals("Records were not produced to backup cluster.", NUM_RECORDS_PER_PARTITION,
+ backup.kafka().consume(NUM_RECORDS_PER_PARTITION, RECORD_TRANSFER_DURATION_MS, "test-topic-3").count());
+
+ assertEquals("New topic was not replicated to primary cluster.", NUM_RECORDS_PER_PARTITION,
+ primary.kafka().consume(NUM_RECORDS_PER_PARTITION, 2 * RECORD_TRANSFER_DURATION_MS, "backup.test-topic-3").count());
+ assertEquals("New topic was not replicated to backup cluster.", NUM_RECORDS_PER_PARTITION,
+ backup.kafka().consume(NUM_RECORDS_PER_PARTITION, 2 * RECORD_TRANSFER_DURATION_MS, "primary.test-topic-2").count());
+
+ }
+
+ @Test
+ public void testReplicationWithEmptyPartition() throws Exception {
+ String consumerGroupName = "consumer-group-testReplicationWithEmptyPartition";
+ Map<String, Object> consumerProps = Collections.singletonMap("group.id", consumerGroupName);
+
+ // create topic
+ String topic = "test-topic-with-empty-partition";
+ primary.kafka().createTopic(topic, NUM_PARTITIONS);
+
+ // produce to all test-topic-empty's partitions, except the last partition
+ produceMessages(primary, topic, NUM_PARTITIONS - 1);
+
+ // consume before starting the connectors so we don't need to wait for discovery
+ int expectedRecords = NUM_RECORDS_PER_PARTITION * (NUM_PARTITIONS - 1);
+ try (Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps, topic)) {
+ waitForConsumingAllRecords(primaryConsumer, expectedRecords);
+ }
+
+ // one way replication from primary to backup
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + "->" + PRIMARY_CLUSTER_ALIAS + ".enabled", "false");
+ mm2Config = new MirrorMakerConfig(mm2Props);
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS);
+
+ // sleep few seconds to have MM2 finish replication so that "end" consumer will consume some record
+ Thread.sleep(TimeUnit.SECONDS.toMillis(3));
+
+ // consume all records from backup cluster
+ try (Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(consumerProps,
+ PRIMARY_CLUSTER_ALIAS + "." + topic)) {
+ waitForConsumingAllRecords(backupConsumer, expectedRecords);
+ }
+
+ Admin backupClient = backup.kafka().createAdminClient();
+ // retrieve the consumer group offset from backup cluster
+ Map<TopicPartition, OffsetAndMetadata> remoteOffsets =
+ backupClient.listConsumerGroupOffsets(consumerGroupName).partitionsToOffsetAndMetadata().get();
+ // pinpoint the offset of the last partition which does not receive records
+ OffsetAndMetadata offset = remoteOffsets.get(new TopicPartition(PRIMARY_CLUSTER_ALIAS + "." + topic, NUM_PARTITIONS - 1));
+ // offset of the last partition should exist, but its value should be 0
+ assertNotNull("Offset of last partition was not replicated", offset);
+ assertEquals("Offset of last partition is not zero", 0, offset.offset());
+ }
+
+ @Test
+ public void testOneWayReplicationWithAutoOffsetSync() throws InterruptedException {
+ produceMessages(primary, "test-topic-1");
+ String consumerGroupName = "consumer-group-testOneWayReplicationWithAutoOffsetSync";
+ Map<String, Object> consumerProps = new HashMap<String, Object>() {{
+ put("group.id", consumerGroupName);
+ put("auto.offset.reset", "earliest");
+ }};
+ // create consumers before starting the connectors so we don't need to wait for discovery
+ try (Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps,
+ "test-topic-1")) {
+ // we need to wait for consuming all the records for MM2 replicating the expected offsets
+ waitForConsumingAllRecords(primaryConsumer, NUM_RECORDS_PRODUCED);
+ }
+
+ // enable automated consumer group offset sync
+ mm2Props.put("sync.group.offsets.enabled", "true");
+ mm2Props.put("sync.group.offsets.interval.seconds", "1");
+ // one way replication from primary to backup
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + "->" + PRIMARY_CLUSTER_ALIAS + ".enabled", "false");
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS);
+
+ // create a consumer at backup cluster with same consumer group Id to consume 1 topic
+ Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(
+ consumerProps, "primary.test-topic-1");
+
+ waitForConsumerGroupOffsetSync(backup, backupConsumer, Collections.singletonList("primary.test-topic-1"),
+ consumerGroupName, NUM_RECORDS_PRODUCED);
+
+ ConsumerRecords<byte[], byte[]> records = backupConsumer.poll(CONSUMER_POLL_TIMEOUT_MS);
+
+ // the size of consumer record should be zero, because the offsets of the same consumer group
+ // have been automatically synchronized from primary to backup by the background job, so no
+ // more records to consume from the replicated topic by the same consumer group at backup cluster
+ assertEquals("consumer record size is not zero", 0, records.count());
+
+ // now create a new topic in primary cluster
+ primary.kafka().createTopic("test-topic-2", NUM_PARTITIONS);
+ backup.kafka().createTopic("primary.test-topic-2", 1);
+ // produce some records to the new topic in primary cluster
+ produceMessages(primary, "test-topic-2");
+
+ // create a consumer at primary cluster to consume the new topic
+ try (Consumer<byte[], byte[]> consumer1 = primary.kafka().createConsumerAndSubscribeTo(Collections.singletonMap(
+ "group.id", "consumer-group-1"), "test-topic-2")) {
+ // we need to wait for consuming all the records for MM2 replicating the expected offsets
+ waitForConsumingAllRecords(consumer1, NUM_RECORDS_PRODUCED);
+ }
+
+ // create a consumer at backup cluster with same consumer group Id to consume old and new topic
+ backupConsumer = backup.kafka().createConsumerAndSubscribeTo(Collections.singletonMap(
+ "group.id", consumerGroupName), "primary.test-topic-1", "primary.test-topic-2");
+
+ waitForConsumerGroupOffsetSync(backup, backupConsumer, Arrays.asList("primary.test-topic-1", "primary.test-topic-2"),
+ consumerGroupName, NUM_RECORDS_PRODUCED);
+
+ records = backupConsumer.poll(CONSUMER_POLL_TIMEOUT_MS);
+ // similar reasoning as above, no more records to consume by the same consumer group at backup cluster
+ assertEquals("consumer record size is not zero", 0, records.count());
+ backupConsumer.close();
+ }
+
+ /*
+ * launch the connectors on kafka connect cluster and check if they are running
+ */
+ private static void waitUntilMirrorMakerIsRunning(EmbeddedConnectCluster connectCluster,
+ List<Class<? extends Connector>> connectorClasses, MirrorMakerConfig mm2Config,
+ String primary, String backup) throws InterruptedException {
+ for (int i = 0; i < connectorClasses.size(); i++) {
+ String connector = connectorClasses.get(i).getSimpleName();
+ connectCluster.configureConnector(connector, mm2Config.connectorBaseConfig(
+ new SourceAndTarget(primary, backup), connectorClasses.get(i)));
+ }
+
+ // we wait for the connector and tasks to come up for each connector, so that when we do the
+ // actual testing, we are certain that the tasks are up and running; this will prevent
+ // flaky tests where the connector and tasks didn't start up in time for the tests to be run
+ List<String> connectorNames = connectorClasses.stream().map(x -> x.getSimpleName())
Review comment:
I'm assuming it's worth keeping this 2nd loop separate from the first one for performance reasons. At first glance it looks strange to iterate over the same collection twice in a row
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc commented on a change in pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc commented on a change in pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#discussion_r510500535
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationTest.java
##########
@@ -0,0 +1,372 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.errors.TimeoutException;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.mirror.MirrorCheckpointConnector;
+import org.apache.kafka.connect.mirror.MirrorClient;
+import org.apache.kafka.connect.mirror.MirrorHeartbeatConnector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.MirrorSourceConnector;
+import org.apache.kafka.connect.mirror.utils.ThreadedConsumer;
+import org.apache.kafka.connect.mirror.utils.ThreadedProducer;
+import org.apache.kafka.test.IntegrationTest;
+import org.junit.Before;
+import org.junit.After;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Collections;
+import java.util.Map;
+import java.util.HashMap;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertNotNull;
+
+/**
+ * Tests MM2 replication and failover/failback logic.
+ *
+ * MM2 is configured with active/active replication between two Kafka clusters. Tests validate that
+ * records sent to either cluster arrive at the other cluster. Then, a consumer group is migrated from
+ * one cluster to the other and back. Tests validate that consumer offsets are translated and replicated
+ * between clusters during this failover and failback.
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationTest extends MirrorConnectorsIntegrationBaseTest {
+
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationTest.class);
+
+ private static final List<Class> CONNECTOR_LIST =
+ Arrays.asList(MirrorSourceConnector.class, MirrorCheckpointConnector.class, MirrorHeartbeatConnector.class);
+
+ @Before
+ public void setup() throws InterruptedException {
Review comment:
in `MirrorConnectorsIntegrationSSLTest`, we put ssl config into `backupBrokerProps`, so the setup() of both `MirrorConnectorsIntegrationTest` and `MirrorConnectorsIntegrationSSLTest` will be slightly different
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] mimaison commented on a change in pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
mimaison commented on a change in pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#discussion_r527005533
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationSSLTest.java
##########
@@ -0,0 +1,98 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.common.network.Mode;
+import org.apache.kafka.connect.mirror.MirrorCheckpointConnector;
+import org.apache.kafka.connect.mirror.MirrorHeartbeatConnector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.MirrorSourceConnector;
+import org.apache.kafka.test.IntegrationTest;
+import org.apache.kafka.test.TestSslUtils;
+import org.apache.kafka.test.TestUtils;
+import kafka.server.KafkaConfig$;
+
+import org.junit.experimental.categories.Category;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+import org.junit.Before;
+import org.junit.After;
+import org.junit.Test;
+
+/**
+ * Tests MM2 replication with SSL enabled at backup kafka cluster
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationSSLTest extends MirrorConnectorsIntegrationBaseTest {
+
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationSSLTest.class);
+
+ private static final List<Class> CONNECTOR_LIST =
+ Arrays.asList(MirrorSourceConnector.class, MirrorCheckpointConnector.class, MirrorHeartbeatConnector.class);
+
+ @Before
+ public void setup() throws InterruptedException {
+ try {
+ Map<String, Object> sslConfig = TestSslUtils.createSslConfig(false, true, Mode.SERVER, TestUtils.tempFile(), "testCert");
+ backupBrokerProps.put(KafkaConfig$.MODULE$.ListenersProp(), "SSL://localhost:0");
+ backupBrokerProps.put(KafkaConfig$.MODULE$.InterBrokerListenerNameProp(), "SSL");
+ backupBrokerProps.putAll(sslConfig);
+ } catch (final Exception e) {
+ throw new RuntimeException(e);
+ }
+ startClusters();
+ }
+
+ @After
+ public void close() {
Review comment:
Yes it will
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc commented on pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc commented on pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#issuecomment-741395378
Hello @mimaison I addressed all your of comments, please take the final review.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc commented on pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc commented on pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#issuecomment-707526684
Hello @mimaison @ryannedolan this PR does not contain any functional change, it should be straightforward to review. Thanks for your time.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] mimaison commented on a change in pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
mimaison commented on a change in pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#discussion_r540226389
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationSSLTest.java
##########
@@ -0,0 +1,69 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import java.util.Map;
+import java.util.Properties;
+import java.util.stream.Collectors;
+
+import org.apache.kafka.clients.CommonClientConfigs;
+import org.apache.kafka.common.config.SslConfigs;
+import org.apache.kafka.common.config.types.Password;
+import org.apache.kafka.common.network.Mode;
+import org.apache.kafka.test.IntegrationTest;
+import org.apache.kafka.test.TestSslUtils;
+import org.apache.kafka.test.TestUtils;
+import kafka.server.KafkaConfig$;
+
+import org.junit.experimental.categories.Category;
+import org.junit.Before;
+
+/**
+ * Tests MM2 replication with SSL enabled at backup kafka cluster
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationSSLTest extends MirrorConnectorsIntegrationBaseTest {
+
+ private static Map<String, Object> sslConfig;
Review comment:
We don't need this field, this could be a local in `startClusters()`
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationBaseTest.java
##########
@@ -0,0 +1,599 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.Config;
+import org.apache.kafka.clients.admin.DescribeConfigsResult;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.config.ConfigResource;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.connector.Connector;
+import org.apache.kafka.connect.mirror.MirrorClient;
+import org.apache.kafka.connect.mirror.MirrorHeartbeatConnector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.MirrorSourceConnector;
+import org.apache.kafka.connect.mirror.SourceAndTarget;
+import org.apache.kafka.connect.mirror.MirrorCheckpointConnector;
+import org.apache.kafka.connect.util.clusters.EmbeddedConnectCluster;
+import org.apache.kafka.connect.util.clusters.EmbeddedKafkaCluster;
+import org.apache.kafka.connect.util.clusters.UngracefulShutdownException;
+import org.apache.kafka.test.IntegrationTest;
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertNotNull;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.junit.After;
+import org.junit.Before;
+
+import static org.apache.kafka.connect.mirror.TestUtils.generateRecords;
+
+/**
+ * Tests MM2 replication and failover/failback logic.
+ *
+ * MM2 is configured with active/active replication between two Kafka clusters. Tests validate that
+ * records sent to either cluster arrive at the other cluster. Then, a consumer group is migrated from
+ * one cluster to the other and back. Tests validate that consumer offsets are translated and replicated
+ * between clusters during this failover and failback.
+ */
+@Category(IntegrationTest.class)
+public abstract class MirrorConnectorsIntegrationBaseTest {
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationBaseTest.class);
+
+ private static final int NUM_RECORDS_PER_PARTITION = 10;
+ private static final int NUM_PARTITIONS = 10;
+ private static final int NUM_RECORDS_PRODUCED = NUM_PARTITIONS * NUM_RECORDS_PER_PARTITION;
+ private static final int RECORD_TRANSFER_DURATION_MS = 30_000;
+ private static final int CHECKPOINT_DURATION_MS = 20_000;
+ private static final int RECORD_CONSUME_DURATION_MS = 20_000;
+ private static final int OFFSET_SYNC_DURATION_MS = 30_000;
+ private static final int NUM_WORKERS = 3;
+ private static final Duration CONSUMER_POLL_TIMEOUT_MS = Duration.ofMillis(500);
+ private static final int BROKER_RESTART_TIMEOUT_MS = 10_000;
Review comment:
This field is unused
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/MirrorConnectorsIntegrationTest.java
##########
@@ -1,595 +0,0 @@
-/*
- * 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.
- */
-package org.apache.kafka.connect.mirror;
-
-import org.apache.kafka.clients.admin.Admin;
-import org.apache.kafka.clients.consumer.Consumer;
-import org.apache.kafka.clients.consumer.ConsumerRecord;
-import org.apache.kafka.clients.consumer.ConsumerRecords;
-import org.apache.kafka.clients.consumer.OffsetAndMetadata;
-import org.apache.kafka.common.TopicPartition;
-import org.apache.kafka.connect.util.clusters.EmbeddedConnectCluster;
-import org.apache.kafka.connect.util.clusters.EmbeddedKafkaCluster;
-import org.apache.kafka.connect.util.clusters.UngracefulShutdownException;
-import org.apache.kafka.test.IntegrationTest;
-import org.apache.kafka.common.utils.Exit;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.time.Duration;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-import java.util.Set;
-import java.util.concurrent.TimeoutException;
-import java.util.stream.Collectors;
-import java.util.stream.IntStream;
-
-import static org.apache.kafka.test.TestUtils.waitForCondition;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-/**
- * Tests MM2 replication and failover/failback logic.
- *
- * MM2 is configured with active/active replication between two Kafka clusters. Tests validate that
- * records sent to either cluster arrive at the other cluster. Then, a consumer group is migrated from
- * one cluster to the other and back. Tests validate that consumer offsets are translated and replicated
- * between clusters during this failover and failback.
- */
-@Category(IntegrationTest.class)
-public class MirrorConnectorsIntegrationTest {
-
- private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationTest.class);
-
- private static final int NUM_RECORDS_PER_PARTITION = 10;
- private static final int NUM_PARTITIONS = 10;
- private static final int NUM_RECORDS_PRODUCED = NUM_PARTITIONS * NUM_RECORDS_PER_PARTITION;
- private static final int RECORD_TRANSFER_DURATION_MS = 30_000;
- private static final int CHECKPOINT_DURATION_MS = 20_000;
- private static final int RECORD_CONSUME_DURATION_MS = 20_000;
- private static final int OFFSET_SYNC_DURATION_MS = 30_000;
-
- private volatile boolean shuttingDown;
- private Map<String, String> mm2Props;
- private MirrorMakerConfig mm2Config;
- private EmbeddedConnectCluster primary;
- private EmbeddedConnectCluster backup;
-
- private Exit.Procedure exitProcedure;
- private Exit.Procedure haltProcedure;
-
- @Before
- public void setup() throws InterruptedException {
- shuttingDown = false;
- exitProcedure = (code, message) -> {
- if (shuttingDown) {
- // ignore this since we're shutting down Connect and Kafka and timing isn't always great
- return;
- }
- if (code != 0) {
- String exitMessage = "Abrupt service exit with code " + code + " and message " + message;
- log.warn(exitMessage);
- throw new UngracefulShutdownException(exitMessage);
- }
- };
- haltProcedure = (code, message) -> {
- if (shuttingDown) {
- // ignore this since we're shutting down Connect and Kafka and timing isn't always great
- return;
- }
- if (code != 0) {
- String haltMessage = "Abrupt service halt with code " + code + " and message " + message;
- log.warn(haltMessage);
- throw new UngracefulShutdownException(haltMessage);
- }
- };
- // Override the exit and halt procedure that Connect and Kafka will use. For these integration tests,
- // we don't want to exit the JVM and instead simply want to fail the test
- Exit.setExitProcedure(exitProcedure);
- Exit.setHaltProcedure(haltProcedure);
-
- Properties brokerProps = new Properties();
- brokerProps.put("auto.create.topics.enable", "false");
-
- mm2Props = new HashMap<>();
- mm2Props.put("clusters", "primary, backup");
- mm2Props.put("max.tasks", "10");
- mm2Props.put("topics", "test-topic-.*, primary.test-topic-.*, backup.test-topic-.*");
- mm2Props.put("groups", "consumer-group-.*");
- mm2Props.put("primary->backup.enabled", "true");
- mm2Props.put("backup->primary.enabled", "true");
- mm2Props.put("sync.topic.acls.enabled", "false");
- mm2Props.put("emit.checkpoints.interval.seconds", "1");
- mm2Props.put("emit.heartbeats.interval.seconds", "1");
- mm2Props.put("refresh.topics.interval.seconds", "1");
- mm2Props.put("refresh.groups.interval.seconds", "1");
- mm2Props.put("checkpoints.topic.replication.factor", "1");
- mm2Props.put("heartbeats.topic.replication.factor", "1");
- mm2Props.put("offset-syncs.topic.replication.factor", "1");
- mm2Props.put("config.storage.replication.factor", "1");
- mm2Props.put("offset.storage.replication.factor", "1");
- mm2Props.put("status.storage.replication.factor", "1");
- mm2Props.put("replication.factor", "1");
-
- mm2Config = new MirrorMakerConfig(mm2Props);
- Map<String, String> primaryWorkerProps = mm2Config.workerConfig(new SourceAndTarget("backup", "primary"));
- Map<String, String> backupWorkerProps = mm2Config.workerConfig(new SourceAndTarget("primary", "backup"));
-
- primary = new EmbeddedConnectCluster.Builder()
- .name("primary-connect-cluster")
- .numWorkers(3)
- .numBrokers(1)
- .brokerProps(brokerProps)
- .workerProps(primaryWorkerProps)
- .maskExitProcedures(false)
- .build();
-
- backup = new EmbeddedConnectCluster.Builder()
- .name("backup-connect-cluster")
- .numWorkers(3)
- .numBrokers(1)
- .brokerProps(brokerProps)
- .workerProps(backupWorkerProps)
- .maskExitProcedures(false)
- .build();
-
- primary.start();
- primary.assertions().assertAtLeastNumWorkersAreUp(3,
- "Workers of primary-connect-cluster did not start in time.");
- backup.start();
- backup.assertions().assertAtLeastNumWorkersAreUp(3,
- "Workers of backup-connect-cluster did not start in time.");
-
- // create these topics before starting the connectors so we don't need to wait for discovery
- primary.kafka().createTopic("test-topic-1", NUM_PARTITIONS);
- primary.kafka().createTopic("backup.test-topic-1", 1);
- primary.kafka().createTopic("heartbeats", 1);
- backup.kafka().createTopic("test-topic-1", NUM_PARTITIONS);
- backup.kafka().createTopic("primary.test-topic-1", 1);
- backup.kafka().createTopic("heartbeats", 1);
-
- // produce to all partitions of test-topic-1
- produceMessages(primary, "test-topic-1", "message-1-");
- produceMessages(backup, "test-topic-1", "message-2-");
-
- // Generate some consumer activity on both clusters to ensure the checkpoint connector always starts promptly
- Map<String, Object> dummyProps = Collections.singletonMap("group.id", "consumer-group-dummy");
- Consumer<byte[], byte[]> dummyConsumer = primary.kafka().createConsumerAndSubscribeTo(dummyProps, "test-topic-1");
- consumeAllMessages(dummyConsumer);
- dummyConsumer.close();
- dummyConsumer = backup.kafka().createConsumerAndSubscribeTo(dummyProps, "test-topic-1");
- consumeAllMessages(dummyConsumer);
- dummyConsumer.close();
-
- log.info("primary REST service: {}", primary.endpointForResource("connectors"));
- log.info("backup REST service: {}", backup.endpointForResource("connectors"));
-
- log.info("primary brokers: {}", primary.kafka().bootstrapServers());
- log.info("backup brokers: {}", backup.kafka().bootstrapServers());
-
- // now that the brokers are running, we can finish setting up the Connectors
- mm2Props.put("primary.bootstrap.servers", primary.kafka().bootstrapServers());
- mm2Props.put("backup.bootstrap.servers", backup.kafka().bootstrapServers());
- mm2Config = new MirrorMakerConfig(mm2Props);
- }
-
-
- private void waitUntilMirrorMakerIsRunning(EmbeddedConnectCluster connectCluster,
- MirrorMakerConfig mm2Config, String primary, String backup) throws InterruptedException {
-
- connectCluster.configureConnector("MirrorSourceConnector",
- mm2Config.connectorBaseConfig(new SourceAndTarget(primary, backup), MirrorSourceConnector.class));
- connectCluster.configureConnector("MirrorCheckpointConnector",
- mm2Config.connectorBaseConfig(new SourceAndTarget(primary, backup), MirrorCheckpointConnector.class));
- connectCluster.configureConnector("MirrorHeartbeatConnector",
- mm2Config.connectorBaseConfig(new SourceAndTarget(primary, backup), MirrorHeartbeatConnector.class));
-
- // we wait for the connector and tasks to come up for each connector, so that when we do the
- // actual testing, we are certain that the tasks are up and running; this will prevent
- // flaky tests where the connector and tasks didn't start up in time for the tests to be
- // run
- Set<String> connectorNames = new HashSet<>(Arrays.asList("MirrorSourceConnector",
- "MirrorCheckpointConnector", "MirrorHeartbeatConnector"));
-
- for (String connector : connectorNames) {
- connectCluster.assertions().assertConnectorAndAtLeastNumTasksAreRunning(connector, 1,
- "Connector " + connector + " tasks did not start in time on cluster: " + connectCluster);
- }
- }
-
- @After
- public void close() {
- try {
- for (String x : primary.connectors()) {
- primary.deleteConnector(x);
- }
- for (String x : backup.connectors()) {
- backup.deleteConnector(x);
- }
- deleteAllTopics(primary.kafka());
- deleteAllTopics(backup.kafka());
- } finally {
- shuttingDown = true;
- try {
- try {
- primary.stop();
- } finally {
- backup.stop();
- }
- } finally {
- Exit.resetExitProcedure();
- Exit.resetHaltProcedure();
- }
- }
- }
-
- @Test
- public void testReplication() throws InterruptedException {
- String consumerGroupName = "consumer-group-testReplication";
- Map<String, Object> consumerProps = new HashMap<String, Object>() {{
- put("group.id", consumerGroupName);
- put("auto.offset.reset", "latest");
- }};
-
- // create consumers before starting the connectors so we don't need to wait for discovery
- Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps, "test-topic-1");
- consumeAllMessages(primaryConsumer, 0);
- primaryConsumer.close();
-
- Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(consumerProps, "test-topic-1");
- consumeAllMessages(backupConsumer, 0);
- backupConsumer.close();
-
- waitUntilMirrorMakerIsRunning(backup, mm2Config, "primary", "backup");
- waitUntilMirrorMakerIsRunning(primary, mm2Config, "backup", "primary");
- MirrorClient primaryClient = new MirrorClient(mm2Config.clientConfig("primary"));
- MirrorClient backupClient = new MirrorClient(mm2Config.clientConfig("backup"));
-
- assertEquals("Records were not produced to primary cluster.", NUM_RECORDS_PRODUCED,
- primary.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "test-topic-1").count());
- assertEquals("Records were not replicated to backup cluster.", NUM_RECORDS_PRODUCED,
- backup.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "primary.test-topic-1").count());
- assertEquals("Records were not produced to backup cluster.", NUM_RECORDS_PRODUCED,
- backup.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "test-topic-1").count());
- assertEquals("Records were not replicated to primary cluster.", NUM_RECORDS_PRODUCED,
- primary.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "backup.test-topic-1").count());
-
- assertEquals("Primary cluster doesn't have all records from both clusters.", NUM_RECORDS_PRODUCED * 2,
- primary.kafka().consume(NUM_RECORDS_PRODUCED * 2, RECORD_TRANSFER_DURATION_MS, "backup.test-topic-1", "test-topic-1").count());
- assertEquals("Backup cluster doesn't have all records from both clusters.", NUM_RECORDS_PRODUCED * 2,
- backup.kafka().consume(NUM_RECORDS_PRODUCED * 2, RECORD_TRANSFER_DURATION_MS, "primary.test-topic-1", "test-topic-1").count());
-
- assertTrue("Heartbeats were not emitted to primary cluster.",
- primary.kafka().consume(1, RECORD_TRANSFER_DURATION_MS, "heartbeats").count() > 0);
- assertTrue("Heartbeats were not emitted to backup cluster.",
- backup.kafka().consume(1, RECORD_TRANSFER_DURATION_MS, "heartbeats").count() > 0);
- assertTrue("Heartbeats were not replicated downstream to backup cluster.",
- backup.kafka().consume(1, RECORD_TRANSFER_DURATION_MS, "primary.heartbeats").count() > 0);
- assertTrue("Heartbeats were not replicated downstream to primary cluster.",
- primary.kafka().consume(1, RECORD_TRANSFER_DURATION_MS, "backup.heartbeats").count() > 0);
-
- assertTrue("Did not find upstream primary cluster.", backupClient.upstreamClusters().contains("primary"));
- assertEquals("Did not calculate replication hops correctly.", 1, backupClient.replicationHops("primary"));
- assertTrue("Did not find upstream backup cluster.", primaryClient.upstreamClusters().contains("backup"));
- assertEquals("Did not calculate replication hops correctly.", 1, primaryClient.replicationHops("backup"));
-
- assertTrue("Checkpoints were not emitted downstream to backup cluster.",
- backup.kafka().consume(1, CHECKPOINT_DURATION_MS, "primary.checkpoints.internal").count() > 0);
-
- Map<TopicPartition, OffsetAndMetadata> backupOffsets = backupClient.remoteConsumerOffsets(consumerGroupName, "primary",
- Duration.ofMillis(CHECKPOINT_DURATION_MS));
-
- assertTrue("Offsets not translated downstream to backup cluster. Found: " + backupOffsets, backupOffsets.containsKey(
- new TopicPartition("primary.test-topic-1", 0)));
-
- // Failover consumer group to backup cluster.
- backupConsumer = backup.kafka().createConsumer(consumerProps);
- backupConsumer.assign(allPartitions("test-topic-1", "primary.test-topic-1"));
- seek(backupConsumer, backupOffsets);
- consumeAllMessages(backupConsumer, 0);
-
- assertTrue("Consumer failedover to zero offset.", backupConsumer.position(new TopicPartition("primary.test-topic-1", 0)) > 0);
- assertTrue("Consumer failedover beyond expected offset.", backupConsumer.position(
- new TopicPartition("primary.test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
- assertTrue("Checkpoints were not emitted upstream to primary cluster.", primary.kafka().consume(1,
- CHECKPOINT_DURATION_MS, "backup.checkpoints.internal").count() > 0);
-
- backupConsumer.close();
-
- waitForCondition(() -> {
- try {
- return primaryClient.remoteConsumerOffsets(consumerGroupName, "backup",
- Duration.ofMillis(CHECKPOINT_DURATION_MS)).containsKey(new TopicPartition("backup.test-topic-1", 0));
- } catch (Throwable e) {
- return false;
- }
- }, CHECKPOINT_DURATION_MS, "Offsets not translated downstream to primary cluster.");
-
- waitForCondition(() -> {
- try {
- return primaryClient.remoteConsumerOffsets(consumerGroupName, "backup",
- Duration.ofMillis(CHECKPOINT_DURATION_MS)).containsKey(new TopicPartition("test-topic-1", 0));
- } catch (Throwable e) {
- return false;
- }
- }, CHECKPOINT_DURATION_MS, "Offsets not translated upstream to primary cluster.");
-
- Map<TopicPartition, OffsetAndMetadata> primaryOffsets = primaryClient.remoteConsumerOffsets(consumerGroupName, "backup",
- Duration.ofMillis(CHECKPOINT_DURATION_MS));
-
- primaryClient.close();
- backupClient.close();
Review comment:
It looks like we lost these lines and maybe some others too. These came from https://github.com/apache/kafka/pull/9698. Can you make sure we don't miss any existing logic?
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc commented on pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc commented on pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#issuecomment-713306404
@edoardocomar @rhauch given this PR does not contain functional change and have been pending over 45 days, could you please direct me to the right reviewers to take a look? Thanks
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc commented on a change in pull request #9224: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc commented on a change in pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#discussion_r485337705
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/TestUtils.java
##########
@@ -32,4 +71,141 @@
}
return props;
}
+
+ public static void waitUntilMirrorMakerIsRunning(EmbeddedConnectCluster connectCluster, List<Class> mirrorClasses,
Review comment:
This is the simple move from `MirrorConnectorsIntegrationTest` with generalization of connector class
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc commented on pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc commented on pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#issuecomment-731934229
@mimaison Thanks again for your previous detailed review. I updated the PR to resolve the exact 2 concerns you raised.
Very appreciated for your another review!
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc commented on a change in pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc commented on a change in pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#discussion_r527393326
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationSSLTest.java
##########
@@ -0,0 +1,89 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.common.network.Mode;
+import org.apache.kafka.connect.connector.Connector;
+import org.apache.kafka.connect.mirror.MirrorCheckpointConnector;
+import org.apache.kafka.connect.mirror.MirrorHeartbeatConnector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.MirrorSourceConnector;
+import org.apache.kafka.test.IntegrationTest;
+import org.apache.kafka.test.TestSslUtils;
+import org.apache.kafka.test.TestUtils;
+import kafka.server.KafkaConfig$;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import org.junit.experimental.categories.Category;
+import org.junit.Before;
+import org.junit.After;
+import org.junit.Test;
+
+/**
+ * Tests MM2 replication with SSL enabled at backup kafka cluster
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationSSLTest extends MirrorConnectorsIntegrationBaseTest {
+
+ private static final List<Class<? extends Connector>> CONNECTOR_LIST =
Review comment:
Good point. I am thinking in future, if we have test for `MirrorSinkConnector` (which will also extend the `MirrorConnectorsIntegrationBaseTest` class), it may be more flexible to have each extended test class to define what is the list of connectors to boot up?
I am also fine to move `CONNECTOR_LIST ` into the base class now and move it out later on when we have `MirrorSinkConnector`
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] mimaison commented on a change in pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
mimaison commented on a change in pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#discussion_r535095426
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationBaseTest.java
##########
@@ -0,0 +1,617 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.Config;
+import org.apache.kafka.clients.admin.ConfigEntry;
+import org.apache.kafka.clients.admin.DescribeConfigsResult;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.clients.CommonClientConfigs;
+import org.apache.kafka.common.config.ConfigResource;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.config.SslConfigs;
+import org.apache.kafka.common.config.types.Password;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.connector.Connector;
+import org.apache.kafka.connect.mirror.MirrorClient;
+import org.apache.kafka.connect.mirror.MirrorHeartbeatConnector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.MirrorSourceConnector;
+import org.apache.kafka.connect.mirror.SourceAndTarget;
+import org.apache.kafka.connect.mirror.MirrorCheckpointConnector;
+import org.apache.kafka.connect.util.clusters.EmbeddedConnectCluster;
+import org.apache.kafka.connect.util.clusters.EmbeddedKafkaCluster;
+import org.apache.kafka.test.IntegrationTest;
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertNotNull;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import static org.apache.kafka.connect.mirror.TestUtils.generateRecords;
+
+/**
+ * Tests MM2 replication and failover/failback logic.
+ *
+ * MM2 is configured with active/active replication between two Kafka clusters. Tests validate that
+ * records sent to either cluster arrive at the other cluster. Then, a consumer group is migrated from
+ * one cluster to the other and back. Tests validate that consumer offsets are translated and replicated
+ * between clusters during this failover and failback.
+ */
+@Category(IntegrationTest.class)
+public abstract class MirrorConnectorsIntegrationBaseTest {
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationBaseTest.class);
+
+ private static final int NUM_RECORDS_PER_PARTITION = 10;
+ private static final int NUM_PARTITIONS = 10;
+ private static final int NUM_RECORDS_PRODUCED = NUM_PARTITIONS * NUM_RECORDS_PER_PARTITION;
+ private static final int RECORD_TRANSFER_DURATION_MS = 30_000;
+ private static final int CHECKPOINT_DURATION_MS = 20_000;
+ private static final int RECORD_CONSUME_DURATION_MS = 20_000;
+ private static final int OFFSET_SYNC_DURATION_MS = 30_000;
+ private static final int NUM_WORKERS = 3;
Review comment:
This constant is unused. Should we use it instead of hardcoding `3` below when we create connect workers?
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationBaseTest.java
##########
@@ -0,0 +1,617 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.Config;
+import org.apache.kafka.clients.admin.ConfigEntry;
+import org.apache.kafka.clients.admin.DescribeConfigsResult;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.clients.CommonClientConfigs;
+import org.apache.kafka.common.config.ConfigResource;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.config.SslConfigs;
+import org.apache.kafka.common.config.types.Password;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.connector.Connector;
+import org.apache.kafka.connect.mirror.MirrorClient;
+import org.apache.kafka.connect.mirror.MirrorHeartbeatConnector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.MirrorSourceConnector;
+import org.apache.kafka.connect.mirror.SourceAndTarget;
+import org.apache.kafka.connect.mirror.MirrorCheckpointConnector;
+import org.apache.kafka.connect.util.clusters.EmbeddedConnectCluster;
+import org.apache.kafka.connect.util.clusters.EmbeddedKafkaCluster;
+import org.apache.kafka.test.IntegrationTest;
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertNotNull;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import static org.apache.kafka.connect.mirror.TestUtils.generateRecords;
+
+/**
+ * Tests MM2 replication and failover/failback logic.
+ *
+ * MM2 is configured with active/active replication between two Kafka clusters. Tests validate that
+ * records sent to either cluster arrive at the other cluster. Then, a consumer group is migrated from
+ * one cluster to the other and back. Tests validate that consumer offsets are translated and replicated
+ * between clusters during this failover and failback.
+ */
+@Category(IntegrationTest.class)
+public abstract class MirrorConnectorsIntegrationBaseTest {
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationBaseTest.class);
+
+ private static final int NUM_RECORDS_PER_PARTITION = 10;
+ private static final int NUM_PARTITIONS = 10;
+ private static final int NUM_RECORDS_PRODUCED = NUM_PARTITIONS * NUM_RECORDS_PER_PARTITION;
+ private static final int RECORD_TRANSFER_DURATION_MS = 30_000;
+ private static final int CHECKPOINT_DURATION_MS = 20_000;
+ private static final int RECORD_CONSUME_DURATION_MS = 20_000;
+ private static final int OFFSET_SYNC_DURATION_MS = 30_000;
+ private static final int NUM_WORKERS = 3;
+ private static final int CONSUMER_POLL_TIMEOUT_MS = 500;
+ private static final int BROKER_RESTART_TIMEOUT_MS = 10_000;
+ private static final long DEFAULT_PRODUCE_SEND_DURATION_MS = TimeUnit.SECONDS.toMillis(120);
Review comment:
This is unused too
##########
File path: connect/runtime/src/test/java/org/apache/kafka/connect/util/clusters/EmbeddedKafkaCluster.java
##########
@@ -161,6 +161,11 @@ private void start(int[] brokerPorts, String[] logDirs) {
producerProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers());
producerProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.ByteArraySerializer");
producerProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.ByteArraySerializer");
+ if (sslEnabled()) {
+ producerProps.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, brokerConfig.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG));
+ producerProps.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, ((Password) brokerConfig.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)).value());
Review comment:
Do we really need to cast to `Password` and call `value()`? Can't we just pass `brokerConfig.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)`?
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationBaseTest.java
##########
@@ -0,0 +1,617 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.Config;
+import org.apache.kafka.clients.admin.ConfigEntry;
+import org.apache.kafka.clients.admin.DescribeConfigsResult;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.clients.CommonClientConfigs;
+import org.apache.kafka.common.config.ConfigResource;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.config.SslConfigs;
+import org.apache.kafka.common.config.types.Password;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.connector.Connector;
+import org.apache.kafka.connect.mirror.MirrorClient;
+import org.apache.kafka.connect.mirror.MirrorHeartbeatConnector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.MirrorSourceConnector;
+import org.apache.kafka.connect.mirror.SourceAndTarget;
+import org.apache.kafka.connect.mirror.MirrorCheckpointConnector;
+import org.apache.kafka.connect.util.clusters.EmbeddedConnectCluster;
+import org.apache.kafka.connect.util.clusters.EmbeddedKafkaCluster;
+import org.apache.kafka.test.IntegrationTest;
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertNotNull;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import static org.apache.kafka.connect.mirror.TestUtils.generateRecords;
+
+/**
+ * Tests MM2 replication and failover/failback logic.
+ *
+ * MM2 is configured with active/active replication between two Kafka clusters. Tests validate that
+ * records sent to either cluster arrive at the other cluster. Then, a consumer group is migrated from
+ * one cluster to the other and back. Tests validate that consumer offsets are translated and replicated
+ * between clusters during this failover and failback.
+ */
+@Category(IntegrationTest.class)
+public abstract class MirrorConnectorsIntegrationBaseTest {
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationBaseTest.class);
+
+ private static final int NUM_RECORDS_PER_PARTITION = 10;
+ private static final int NUM_PARTITIONS = 10;
+ private static final int NUM_RECORDS_PRODUCED = NUM_PARTITIONS * NUM_RECORDS_PER_PARTITION;
+ private static final int RECORD_TRANSFER_DURATION_MS = 30_000;
+ private static final int CHECKPOINT_DURATION_MS = 20_000;
+ private static final int RECORD_CONSUME_DURATION_MS = 20_000;
+ private static final int OFFSET_SYNC_DURATION_MS = 30_000;
+ private static final int NUM_WORKERS = 3;
+ private static final int CONSUMER_POLL_TIMEOUT_MS = 500;
+ private static final int BROKER_RESTART_TIMEOUT_MS = 10_000;
+ private static final long DEFAULT_PRODUCE_SEND_DURATION_MS = TimeUnit.SECONDS.toMillis(120);
+ private static final String PRIMARY_CLUSTER_ALIAS = "primary";
+ private static final String BACKUP_CLUSTER_ALIAS = "backup";
+ private static final List<Class<? extends Connector>> CONNECTOR_LIST =
+ Arrays.asList(MirrorSourceConnector.class, MirrorCheckpointConnector.class, MirrorHeartbeatConnector.class);
+
+ private Map<String, String> mm2Props;
+ private MirrorMakerConfig mm2Config;
+ private EmbeddedConnectCluster primary;
+ private EmbeddedConnectCluster backup;
+
+ private final AtomicBoolean exited = new AtomicBoolean(false);
+ protected Properties primaryBrokerProps = new Properties();
+ protected Properties backupBrokerProps = new Properties();
+ private Map<String, String> primaryWorkerProps = new HashMap<>();
+ private Map<String, String> backupWorkerProps = new HashMap<>();
+ abstract Map<String, Object> getSslConfig();
+
+ protected void startClusters() throws InterruptedException {
+ primaryBrokerProps.put("auto.create.topics.enable", "false");
+ backupBrokerProps.put("auto.create.topics.enable", "false");
+
+ mm2Props = basicMM2Config();
+
+ final Map<String, Object> sslConfig = getSslConfig();
+ if (sslConfig != null) {
Review comment:
This should be done in the SSL class. The base class should not be aware of SSL and just use configurations from the concrete classes
##########
File path: connect/runtime/src/test/java/org/apache/kafka/connect/util/clusters/EmbeddedKafkaCluster.java
##########
@@ -278,6 +283,14 @@ protected boolean hasState(KafkaServer server, Predicate<BrokerState> desiredSta
return false;
}
}
+
+ public boolean sslEnabled() {
+ final Object listeners = brokerConfig.get(KafkaConfig$.MODULE$.ListenersProp());
Review comment:
`brokerConfig` is a `Properties`, so we can call `getProperty()` to get back a `String` directly
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationTest.java
##########
@@ -0,0 +1,44 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.junit.Before;
+import org.junit.After;
+import org.junit.experimental.categories.Category;
+
+import java.util.Map;
+
+import org.apache.kafka.test.IntegrationTest;
+
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationTest extends MirrorConnectorsIntegrationBaseTest {
+
+ @Before
+ public void setup() throws InterruptedException {
+ startClusters();
+ }
+
+ @After
Review comment:
Can we move this method to the base class?
##########
File path: connect/runtime/src/test/java/org/apache/kafka/connect/util/clusters/EmbeddedKafkaCluster.java
##########
@@ -444,7 +457,11 @@ public Admin createAdminClient() {
putIfAbsent(props, AUTO_OFFSET_RESET_CONFIG, "earliest");
putIfAbsent(props, KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.ByteArrayDeserializer");
putIfAbsent(props, VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.ByteArrayDeserializer");
-
+ if (sslEnabled()) {
+ putIfAbsent(props,SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, brokerConfig.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG));
+ putIfAbsent(props,SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, ((Password) brokerConfig.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)).value());
Review comment:
Same as above, I think we can just pass `brokerConfig.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)`?
##########
File path: connect/runtime/src/test/java/org/apache/kafka/connect/util/clusters/EmbeddedKafkaCluster.java
##########
@@ -278,6 +283,14 @@ protected boolean hasState(KafkaServer server, Predicate<BrokerState> desiredSta
return false;
}
}
+
+ public boolean sslEnabled() {
+ final Object listeners = brokerConfig.get(KafkaConfig$.MODULE$.ListenersProp());
+ if (listeners != null && listeners.toString().contains("SSL")) {
Review comment:
Instead of doing:
```
if (condition) {
return true;
} else {
return false;
}
```
You can do:
```
return condition;
```
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationBaseTest.java
##########
@@ -0,0 +1,617 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.Config;
+import org.apache.kafka.clients.admin.ConfigEntry;
+import org.apache.kafka.clients.admin.DescribeConfigsResult;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.clients.CommonClientConfigs;
+import org.apache.kafka.common.config.ConfigResource;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.config.SslConfigs;
+import org.apache.kafka.common.config.types.Password;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.connector.Connector;
+import org.apache.kafka.connect.mirror.MirrorClient;
+import org.apache.kafka.connect.mirror.MirrorHeartbeatConnector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.MirrorSourceConnector;
+import org.apache.kafka.connect.mirror.SourceAndTarget;
+import org.apache.kafka.connect.mirror.MirrorCheckpointConnector;
+import org.apache.kafka.connect.util.clusters.EmbeddedConnectCluster;
+import org.apache.kafka.connect.util.clusters.EmbeddedKafkaCluster;
+import org.apache.kafka.test.IntegrationTest;
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertNotNull;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import static org.apache.kafka.connect.mirror.TestUtils.generateRecords;
+
+/**
+ * Tests MM2 replication and failover/failback logic.
+ *
+ * MM2 is configured with active/active replication between two Kafka clusters. Tests validate that
+ * records sent to either cluster arrive at the other cluster. Then, a consumer group is migrated from
+ * one cluster to the other and back. Tests validate that consumer offsets are translated and replicated
+ * between clusters during this failover and failback.
+ */
+@Category(IntegrationTest.class)
+public abstract class MirrorConnectorsIntegrationBaseTest {
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationBaseTest.class);
+
+ private static final int NUM_RECORDS_PER_PARTITION = 10;
+ private static final int NUM_PARTITIONS = 10;
+ private static final int NUM_RECORDS_PRODUCED = NUM_PARTITIONS * NUM_RECORDS_PER_PARTITION;
+ private static final int RECORD_TRANSFER_DURATION_MS = 30_000;
+ private static final int CHECKPOINT_DURATION_MS = 20_000;
+ private static final int RECORD_CONSUME_DURATION_MS = 20_000;
+ private static final int OFFSET_SYNC_DURATION_MS = 30_000;
+ private static final int NUM_WORKERS = 3;
+ private static final int CONSUMER_POLL_TIMEOUT_MS = 500;
+ private static final int BROKER_RESTART_TIMEOUT_MS = 10_000;
+ private static final long DEFAULT_PRODUCE_SEND_DURATION_MS = TimeUnit.SECONDS.toMillis(120);
+ private static final String PRIMARY_CLUSTER_ALIAS = "primary";
+ private static final String BACKUP_CLUSTER_ALIAS = "backup";
+ private static final List<Class<? extends Connector>> CONNECTOR_LIST =
+ Arrays.asList(MirrorSourceConnector.class, MirrorCheckpointConnector.class, MirrorHeartbeatConnector.class);
+
+ private Map<String, String> mm2Props;
+ private MirrorMakerConfig mm2Config;
+ private EmbeddedConnectCluster primary;
+ private EmbeddedConnectCluster backup;
+
+ private final AtomicBoolean exited = new AtomicBoolean(false);
+ protected Properties primaryBrokerProps = new Properties();
+ protected Properties backupBrokerProps = new Properties();
+ private Map<String, String> primaryWorkerProps = new HashMap<>();
+ private Map<String, String> backupWorkerProps = new HashMap<>();
+ abstract Map<String, Object> getSslConfig();
Review comment:
Ideally we want to get rid of this method as it makes no sense in tests that are not SSL.
##########
File path: connect/runtime/src/test/java/org/apache/kafka/connect/util/clusters/EmbeddedKafkaCluster.java
##########
@@ -161,6 +161,11 @@ private void start(int[] brokerPorts, String[] logDirs) {
producerProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers());
producerProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.ByteArraySerializer");
producerProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.ByteArraySerializer");
+ if (sslEnabled()) {
+ producerProps.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, brokerConfig.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG));
Review comment:
A few lines in this file (like this one) contain tabs, we use spaces in Kafka
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationBaseTest.java
##########
@@ -0,0 +1,617 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.Config;
+import org.apache.kafka.clients.admin.ConfigEntry;
+import org.apache.kafka.clients.admin.DescribeConfigsResult;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.clients.CommonClientConfigs;
+import org.apache.kafka.common.config.ConfigResource;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.config.SslConfigs;
+import org.apache.kafka.common.config.types.Password;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.connector.Connector;
+import org.apache.kafka.connect.mirror.MirrorClient;
+import org.apache.kafka.connect.mirror.MirrorHeartbeatConnector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.MirrorSourceConnector;
+import org.apache.kafka.connect.mirror.SourceAndTarget;
+import org.apache.kafka.connect.mirror.MirrorCheckpointConnector;
+import org.apache.kafka.connect.util.clusters.EmbeddedConnectCluster;
+import org.apache.kafka.connect.util.clusters.EmbeddedKafkaCluster;
+import org.apache.kafka.test.IntegrationTest;
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertNotNull;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import static org.apache.kafka.connect.mirror.TestUtils.generateRecords;
+
+/**
+ * Tests MM2 replication and failover/failback logic.
+ *
+ * MM2 is configured with active/active replication between two Kafka clusters. Tests validate that
+ * records sent to either cluster arrive at the other cluster. Then, a consumer group is migrated from
+ * one cluster to the other and back. Tests validate that consumer offsets are translated and replicated
+ * between clusters during this failover and failback.
+ */
+@Category(IntegrationTest.class)
+public abstract class MirrorConnectorsIntegrationBaseTest {
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationBaseTest.class);
+
+ private static final int NUM_RECORDS_PER_PARTITION = 10;
+ private static final int NUM_PARTITIONS = 10;
+ private static final int NUM_RECORDS_PRODUCED = NUM_PARTITIONS * NUM_RECORDS_PER_PARTITION;
+ private static final int RECORD_TRANSFER_DURATION_MS = 30_000;
+ private static final int CHECKPOINT_DURATION_MS = 20_000;
+ private static final int RECORD_CONSUME_DURATION_MS = 20_000;
+ private static final int OFFSET_SYNC_DURATION_MS = 30_000;
+ private static final int NUM_WORKERS = 3;
+ private static final int CONSUMER_POLL_TIMEOUT_MS = 500;
Review comment:
This is always used with `Duration.ofMillis()`. Should we store the `Duration` object directly?
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationBaseTest.java
##########
@@ -0,0 +1,617 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.Config;
+import org.apache.kafka.clients.admin.ConfigEntry;
+import org.apache.kafka.clients.admin.DescribeConfigsResult;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.clients.CommonClientConfigs;
+import org.apache.kafka.common.config.ConfigResource;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.config.SslConfigs;
+import org.apache.kafka.common.config.types.Password;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.connector.Connector;
+import org.apache.kafka.connect.mirror.MirrorClient;
+import org.apache.kafka.connect.mirror.MirrorHeartbeatConnector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.MirrorSourceConnector;
+import org.apache.kafka.connect.mirror.SourceAndTarget;
+import org.apache.kafka.connect.mirror.MirrorCheckpointConnector;
+import org.apache.kafka.connect.util.clusters.EmbeddedConnectCluster;
+import org.apache.kafka.connect.util.clusters.EmbeddedKafkaCluster;
+import org.apache.kafka.test.IntegrationTest;
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertNotNull;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import static org.apache.kafka.connect.mirror.TestUtils.generateRecords;
+
+/**
+ * Tests MM2 replication and failover/failback logic.
+ *
+ * MM2 is configured with active/active replication between two Kafka clusters. Tests validate that
+ * records sent to either cluster arrive at the other cluster. Then, a consumer group is migrated from
+ * one cluster to the other and back. Tests validate that consumer offsets are translated and replicated
+ * between clusters during this failover and failback.
+ */
+@Category(IntegrationTest.class)
+public abstract class MirrorConnectorsIntegrationBaseTest {
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationBaseTest.class);
+
+ private static final int NUM_RECORDS_PER_PARTITION = 10;
+ private static final int NUM_PARTITIONS = 10;
+ private static final int NUM_RECORDS_PRODUCED = NUM_PARTITIONS * NUM_RECORDS_PER_PARTITION;
+ private static final int RECORD_TRANSFER_DURATION_MS = 30_000;
+ private static final int CHECKPOINT_DURATION_MS = 20_000;
+ private static final int RECORD_CONSUME_DURATION_MS = 20_000;
+ private static final int OFFSET_SYNC_DURATION_MS = 30_000;
+ private static final int NUM_WORKERS = 3;
+ private static final int CONSUMER_POLL_TIMEOUT_MS = 500;
+ private static final int BROKER_RESTART_TIMEOUT_MS = 10_000;
+ private static final long DEFAULT_PRODUCE_SEND_DURATION_MS = TimeUnit.SECONDS.toMillis(120);
+ private static final String PRIMARY_CLUSTER_ALIAS = "primary";
+ private static final String BACKUP_CLUSTER_ALIAS = "backup";
+ private static final List<Class<? extends Connector>> CONNECTOR_LIST =
+ Arrays.asList(MirrorSourceConnector.class, MirrorCheckpointConnector.class, MirrorHeartbeatConnector.class);
+
+ private Map<String, String> mm2Props;
+ private MirrorMakerConfig mm2Config;
+ private EmbeddedConnectCluster primary;
+ private EmbeddedConnectCluster backup;
+
+ private final AtomicBoolean exited = new AtomicBoolean(false);
+ protected Properties primaryBrokerProps = new Properties();
+ protected Properties backupBrokerProps = new Properties();
+ private Map<String, String> primaryWorkerProps = new HashMap<>();
+ private Map<String, String> backupWorkerProps = new HashMap<>();
+ abstract Map<String, Object> getSslConfig();
+
+ protected void startClusters() throws InterruptedException {
+ primaryBrokerProps.put("auto.create.topics.enable", "false");
+ backupBrokerProps.put("auto.create.topics.enable", "false");
+
+ mm2Props = basicMM2Config();
+
+ final Map<String, Object> sslConfig = getSslConfig();
+ if (sslConfig != null) {
+ Properties sslProps = new Properties();
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, sslConfig.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG));
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, ((Password) sslConfig.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)).value());
+ sslProps.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL");
+
+ // set SSL config for kafka connect worker
+ backupWorkerProps.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> BACKUP_CLUSTER_ALIAS + "." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ // set SSL config for producer used by source task in MM2
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> BACKUP_CLUSTER_ALIAS + ".producer." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ }
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+ primaryWorkerProps = mm2Config.workerConfig(new SourceAndTarget(BACKUP_CLUSTER_ALIAS, PRIMARY_CLUSTER_ALIAS));
+ backupWorkerProps.putAll(mm2Config.workerConfig(new SourceAndTarget(PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS)));
+
+ primary = new EmbeddedConnectCluster.Builder()
+ .name(PRIMARY_CLUSTER_ALIAS + "-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(primaryBrokerProps)
+ .workerProps(primaryWorkerProps)
+ .build();
+
+ backup = new EmbeddedConnectCluster.Builder()
+ .name(BACKUP_CLUSTER_ALIAS + "-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(backupBrokerProps)
+ .workerProps(backupWorkerProps)
+ .build();
+
+ primary.start();
+ primary.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of " + PRIMARY_CLUSTER_ALIAS + "-connect-cluster did not start in time.");
+
+ backup.start();
+ backup.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of " + BACKUP_CLUSTER_ALIAS + "-connect-cluster did not start in time.");
+
+ createTopics();
+
+ warmUpConsumer();
+
+ log.info(PRIMARY_CLUSTER_ALIAS + " REST service: {}", primary.endpointForResource("connectors"));
+ log.info(BACKUP_CLUSTER_ALIAS + " REST service: {}", backup.endpointForResource("connectors"));
+ log.info(PRIMARY_CLUSTER_ALIAS + " brokers: {}", primary.kafka().bootstrapServers());
+ log.info(BACKUP_CLUSTER_ALIAS + " brokers: {}", backup.kafka().bootstrapServers());
+
+ // now that the brokers are running, we can finish setting up the Connectors
+ mm2Props.put(PRIMARY_CLUSTER_ALIAS + ".bootstrap.servers", primary.kafka().bootstrapServers());
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + ".bootstrap.servers", backup.kafka().bootstrapServers());
+
+ Exit.setExitProcedure((status, errorCode) -> exited.set(true));
+ }
+
+ public void shutdownClusters() {
+ for (String x : primary.connectors()) {
+ primary.deleteConnector(x);
+ }
+ for (String x : backup.connectors()) {
+ backup.deleteConnector(x);
+ }
+ deleteAllTopics(primary.kafka());
+ deleteAllTopics(backup.kafka());
+ primary.stop();
+ backup.stop();
+ try {
+ assertFalse(exited.get());
+ } finally {
+ Exit.resetExitProcedure();
+ }
+ }
+
+ @Test
+ public void testReplication() throws InterruptedException {
+ produceMessages(primary, "test-topic-1");
+ produceMessages(backup, "test-topic-1");
+ String consumerGroupName = "consumer-group-testReplication";
+ Map<String, Object> consumerProps = new HashMap<String, Object>() {{
+ put("group.id", consumerGroupName);
+ put("auto.offset.reset", "latest");
+ }};
+ // create consumers before starting the connectors so we don't need to wait for discovery
+ Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps, "test-topic-1");
+ waitForConsumingAllRecords(primaryConsumer, 0);
+
+ Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(consumerProps, "test-topic-1");
+ waitForConsumingAllRecords(backupConsumer, 0);
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS);
+ waitUntilMirrorMakerIsRunning(primary, CONNECTOR_LIST, mm2Config, BACKUP_CLUSTER_ALIAS, PRIMARY_CLUSTER_ALIAS);
+
+ MirrorClient primaryClient = new MirrorClient(mm2Config.clientConfig(PRIMARY_CLUSTER_ALIAS));
+ MirrorClient backupClient = new MirrorClient(mm2Config.clientConfig(BACKUP_CLUSTER_ALIAS));
+
+ assertEquals("topic config was not synced", TopicConfig.CLEANUP_POLICY_COMPACT,
+ getTopicConfig(backup.kafka(), "primary.test-topic-1", TopicConfig.CLEANUP_POLICY_CONFIG));
+
+ assertEquals("Records were not produced to primary cluster.", NUM_RECORDS_PRODUCED,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "test-topic-1").count());
+ assertEquals("Records were not replicated to backup cluster.", NUM_RECORDS_PRODUCED,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "primary.test-topic-1").count());
+ assertEquals("Records were not produced to backup cluster.", NUM_RECORDS_PRODUCED,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "test-topic-1").count());
+ assertEquals("Records were not replicated to primary cluster.", NUM_RECORDS_PRODUCED,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "backup.test-topic-1").count());
+
+ assertEquals("Primary cluster doesn't have all records from both clusters.", NUM_RECORDS_PRODUCED * 2,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED * 2, RECORD_TRANSFER_DURATION_MS, "backup.test-topic-1", "test-topic-1").count());
+ assertEquals("Backup cluster doesn't have all records from both clusters.", NUM_RECORDS_PRODUCED * 2,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED * 2, RECORD_TRANSFER_DURATION_MS, "primary.test-topic-1", "test-topic-1").count());
+
+ assertTrue("Heartbeats were not emitted to primary cluster.", primary.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "heartbeats").count() > 0);
+ assertTrue("Heartbeats were not emitted to backup cluster.", backup.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "heartbeats").count() > 0);
+ assertTrue("Heartbeats were not replicated downstream to backup cluster.", backup.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "primary.heartbeats").count() > 0);
+ assertTrue("Heartbeats were not replicated downstream to primary cluster.", primary.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "backup.heartbeats").count() > 0);
+
+ assertTrue("Did not find upstream primary cluster.", backupClient.upstreamClusters().contains(PRIMARY_CLUSTER_ALIAS));
+ assertEquals("Did not calculate replication hops correctly.", 1, backupClient.replicationHops(PRIMARY_CLUSTER_ALIAS));
+ assertTrue("Did not find upstream backup cluster.", primaryClient.upstreamClusters().contains(BACKUP_CLUSTER_ALIAS));
+ assertEquals("Did not calculate replication hops correctly.", 1, primaryClient.replicationHops(BACKUP_CLUSTER_ALIAS));
+ assertTrue("Checkpoints were not emitted downstream to backup cluster.", backup.kafka().consume(1,
+ CHECKPOINT_DURATION_MS, "primary.checkpoints.internal").count() > 0);
+
+ Map<TopicPartition, OffsetAndMetadata> backupOffsets = backupClient.remoteConsumerOffsets(consumerGroupName, PRIMARY_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS));
+
+ assertTrue("Offsets not translated downstream to backup cluster. Found: " + backupOffsets, backupOffsets.containsKey(
+ new TopicPartition("primary.test-topic-1", 0)));
+
+ // Failover consumer group to backup cluster.
+ primaryConsumer = backup.kafka().createConsumer(Collections.singletonMap("group.id", consumerGroupName));
+ primaryConsumer.assign(backupOffsets.keySet());
+ backupOffsets.forEach(primaryConsumer::seek);
+ primaryConsumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+ primaryConsumer.commitAsync();
+
+ assertTrue("Consumer failedover to zero offset.", primaryConsumer.position(new TopicPartition("primary.test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedover beyond expected offset.", primaryConsumer.position(
+ new TopicPartition("primary.test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+ assertTrue("Checkpoints were not emitted upstream to primary cluster.", primary.kafka().consume(1,
+ CHECKPOINT_DURATION_MS, "backup.checkpoints.internal").count() > 0);
+
+ primaryConsumer.close();
+
+ waitForCondition(() -> {
+ try {
+ return primaryClient.remoteConsumerOffsets(consumerGroupName, BACKUP_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS)).containsKey(new TopicPartition("backup.test-topic-1", 0));
+ } catch (Throwable e) {
+ return false;
+ }
+ }, CHECKPOINT_DURATION_MS, "Offsets not translated downstream to primary cluster.");
+
+ waitForCondition(() -> {
+ try {
+ return primaryClient.remoteConsumerOffsets(consumerGroupName, BACKUP_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS)).containsKey(new TopicPartition("test-topic-1", 0));
+ } catch (Throwable e) {
Review comment:
I understand this was probably already there but we should avoid catching `Throwable`. I'm not sure the try/catch block is necessarily helping in this cases
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationBaseTest.java
##########
@@ -0,0 +1,617 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.Config;
+import org.apache.kafka.clients.admin.ConfigEntry;
+import org.apache.kafka.clients.admin.DescribeConfigsResult;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.clients.CommonClientConfigs;
+import org.apache.kafka.common.config.ConfigResource;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.config.SslConfigs;
+import org.apache.kafka.common.config.types.Password;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.connector.Connector;
+import org.apache.kafka.connect.mirror.MirrorClient;
+import org.apache.kafka.connect.mirror.MirrorHeartbeatConnector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.MirrorSourceConnector;
+import org.apache.kafka.connect.mirror.SourceAndTarget;
+import org.apache.kafka.connect.mirror.MirrorCheckpointConnector;
+import org.apache.kafka.connect.util.clusters.EmbeddedConnectCluster;
+import org.apache.kafka.connect.util.clusters.EmbeddedKafkaCluster;
+import org.apache.kafka.test.IntegrationTest;
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertNotNull;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import static org.apache.kafka.connect.mirror.TestUtils.generateRecords;
+
+/**
+ * Tests MM2 replication and failover/failback logic.
+ *
+ * MM2 is configured with active/active replication between two Kafka clusters. Tests validate that
+ * records sent to either cluster arrive at the other cluster. Then, a consumer group is migrated from
+ * one cluster to the other and back. Tests validate that consumer offsets are translated and replicated
+ * between clusters during this failover and failback.
+ */
+@Category(IntegrationTest.class)
+public abstract class MirrorConnectorsIntegrationBaseTest {
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationBaseTest.class);
+
+ private static final int NUM_RECORDS_PER_PARTITION = 10;
+ private static final int NUM_PARTITIONS = 10;
+ private static final int NUM_RECORDS_PRODUCED = NUM_PARTITIONS * NUM_RECORDS_PER_PARTITION;
+ private static final int RECORD_TRANSFER_DURATION_MS = 30_000;
+ private static final int CHECKPOINT_DURATION_MS = 20_000;
+ private static final int RECORD_CONSUME_DURATION_MS = 20_000;
+ private static final int OFFSET_SYNC_DURATION_MS = 30_000;
+ private static final int NUM_WORKERS = 3;
+ private static final int CONSUMER_POLL_TIMEOUT_MS = 500;
+ private static final int BROKER_RESTART_TIMEOUT_MS = 10_000;
+ private static final long DEFAULT_PRODUCE_SEND_DURATION_MS = TimeUnit.SECONDS.toMillis(120);
+ private static final String PRIMARY_CLUSTER_ALIAS = "primary";
+ private static final String BACKUP_CLUSTER_ALIAS = "backup";
+ private static final List<Class<? extends Connector>> CONNECTOR_LIST =
+ Arrays.asList(MirrorSourceConnector.class, MirrorCheckpointConnector.class, MirrorHeartbeatConnector.class);
+
+ private Map<String, String> mm2Props;
+ private MirrorMakerConfig mm2Config;
+ private EmbeddedConnectCluster primary;
+ private EmbeddedConnectCluster backup;
+
+ private final AtomicBoolean exited = new AtomicBoolean(false);
+ protected Properties primaryBrokerProps = new Properties();
+ protected Properties backupBrokerProps = new Properties();
+ private Map<String, String> primaryWorkerProps = new HashMap<>();
+ private Map<String, String> backupWorkerProps = new HashMap<>();
+ abstract Map<String, Object> getSslConfig();
+
+ protected void startClusters() throws InterruptedException {
+ primaryBrokerProps.put("auto.create.topics.enable", "false");
+ backupBrokerProps.put("auto.create.topics.enable", "false");
+
+ mm2Props = basicMM2Config();
+
+ final Map<String, Object> sslConfig = getSslConfig();
+ if (sslConfig != null) {
+ Properties sslProps = new Properties();
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, sslConfig.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG));
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, ((Password) sslConfig.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)).value());
+ sslProps.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL");
+
+ // set SSL config for kafka connect worker
+ backupWorkerProps.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> BACKUP_CLUSTER_ALIAS + "." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ // set SSL config for producer used by source task in MM2
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> BACKUP_CLUSTER_ALIAS + ".producer." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ }
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+ primaryWorkerProps = mm2Config.workerConfig(new SourceAndTarget(BACKUP_CLUSTER_ALIAS, PRIMARY_CLUSTER_ALIAS));
+ backupWorkerProps.putAll(mm2Config.workerConfig(new SourceAndTarget(PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS)));
+
+ primary = new EmbeddedConnectCluster.Builder()
+ .name(PRIMARY_CLUSTER_ALIAS + "-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(primaryBrokerProps)
+ .workerProps(primaryWorkerProps)
+ .build();
+
+ backup = new EmbeddedConnectCluster.Builder()
+ .name(BACKUP_CLUSTER_ALIAS + "-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(backupBrokerProps)
+ .workerProps(backupWorkerProps)
+ .build();
+
+ primary.start();
+ primary.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of " + PRIMARY_CLUSTER_ALIAS + "-connect-cluster did not start in time.");
+
+ backup.start();
+ backup.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of " + BACKUP_CLUSTER_ALIAS + "-connect-cluster did not start in time.");
+
+ createTopics();
+
+ warmUpConsumer();
+
+ log.info(PRIMARY_CLUSTER_ALIAS + " REST service: {}", primary.endpointForResource("connectors"));
+ log.info(BACKUP_CLUSTER_ALIAS + " REST service: {}", backup.endpointForResource("connectors"));
+ log.info(PRIMARY_CLUSTER_ALIAS + " brokers: {}", primary.kafka().bootstrapServers());
+ log.info(BACKUP_CLUSTER_ALIAS + " brokers: {}", backup.kafka().bootstrapServers());
+
+ // now that the brokers are running, we can finish setting up the Connectors
+ mm2Props.put(PRIMARY_CLUSTER_ALIAS + ".bootstrap.servers", primary.kafka().bootstrapServers());
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + ".bootstrap.servers", backup.kafka().bootstrapServers());
+
+ Exit.setExitProcedure((status, errorCode) -> exited.set(true));
+ }
+
+ public void shutdownClusters() {
+ for (String x : primary.connectors()) {
+ primary.deleteConnector(x);
+ }
+ for (String x : backup.connectors()) {
+ backup.deleteConnector(x);
+ }
+ deleteAllTopics(primary.kafka());
+ deleteAllTopics(backup.kafka());
+ primary.stop();
+ backup.stop();
+ try {
+ assertFalse(exited.get());
+ } finally {
+ Exit.resetExitProcedure();
+ }
+ }
+
+ @Test
+ public void testReplication() throws InterruptedException {
+ produceMessages(primary, "test-topic-1");
+ produceMessages(backup, "test-topic-1");
+ String consumerGroupName = "consumer-group-testReplication";
+ Map<String, Object> consumerProps = new HashMap<String, Object>() {{
+ put("group.id", consumerGroupName);
+ put("auto.offset.reset", "latest");
+ }};
+ // create consumers before starting the connectors so we don't need to wait for discovery
+ Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps, "test-topic-1");
+ waitForConsumingAllRecords(primaryConsumer, 0);
+
+ Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(consumerProps, "test-topic-1");
+ waitForConsumingAllRecords(backupConsumer, 0);
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS);
+ waitUntilMirrorMakerIsRunning(primary, CONNECTOR_LIST, mm2Config, BACKUP_CLUSTER_ALIAS, PRIMARY_CLUSTER_ALIAS);
+
+ MirrorClient primaryClient = new MirrorClient(mm2Config.clientConfig(PRIMARY_CLUSTER_ALIAS));
+ MirrorClient backupClient = new MirrorClient(mm2Config.clientConfig(BACKUP_CLUSTER_ALIAS));
+
+ assertEquals("topic config was not synced", TopicConfig.CLEANUP_POLICY_COMPACT,
+ getTopicConfig(backup.kafka(), "primary.test-topic-1", TopicConfig.CLEANUP_POLICY_CONFIG));
+
+ assertEquals("Records were not produced to primary cluster.", NUM_RECORDS_PRODUCED,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "test-topic-1").count());
+ assertEquals("Records were not replicated to backup cluster.", NUM_RECORDS_PRODUCED,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "primary.test-topic-1").count());
+ assertEquals("Records were not produced to backup cluster.", NUM_RECORDS_PRODUCED,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "test-topic-1").count());
+ assertEquals("Records were not replicated to primary cluster.", NUM_RECORDS_PRODUCED,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "backup.test-topic-1").count());
+
+ assertEquals("Primary cluster doesn't have all records from both clusters.", NUM_RECORDS_PRODUCED * 2,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED * 2, RECORD_TRANSFER_DURATION_MS, "backup.test-topic-1", "test-topic-1").count());
+ assertEquals("Backup cluster doesn't have all records from both clusters.", NUM_RECORDS_PRODUCED * 2,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED * 2, RECORD_TRANSFER_DURATION_MS, "primary.test-topic-1", "test-topic-1").count());
+
+ assertTrue("Heartbeats were not emitted to primary cluster.", primary.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "heartbeats").count() > 0);
+ assertTrue("Heartbeats were not emitted to backup cluster.", backup.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "heartbeats").count() > 0);
+ assertTrue("Heartbeats were not replicated downstream to backup cluster.", backup.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "primary.heartbeats").count() > 0);
+ assertTrue("Heartbeats were not replicated downstream to primary cluster.", primary.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "backup.heartbeats").count() > 0);
+
+ assertTrue("Did not find upstream primary cluster.", backupClient.upstreamClusters().contains(PRIMARY_CLUSTER_ALIAS));
+ assertEquals("Did not calculate replication hops correctly.", 1, backupClient.replicationHops(PRIMARY_CLUSTER_ALIAS));
+ assertTrue("Did not find upstream backup cluster.", primaryClient.upstreamClusters().contains(BACKUP_CLUSTER_ALIAS));
+ assertEquals("Did not calculate replication hops correctly.", 1, primaryClient.replicationHops(BACKUP_CLUSTER_ALIAS));
+ assertTrue("Checkpoints were not emitted downstream to backup cluster.", backup.kafka().consume(1,
+ CHECKPOINT_DURATION_MS, "primary.checkpoints.internal").count() > 0);
+
+ Map<TopicPartition, OffsetAndMetadata> backupOffsets = backupClient.remoteConsumerOffsets(consumerGroupName, PRIMARY_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS));
+
+ assertTrue("Offsets not translated downstream to backup cluster. Found: " + backupOffsets, backupOffsets.containsKey(
+ new TopicPartition("primary.test-topic-1", 0)));
+
+ // Failover consumer group to backup cluster.
+ primaryConsumer = backup.kafka().createConsumer(Collections.singletonMap("group.id", consumerGroupName));
+ primaryConsumer.assign(backupOffsets.keySet());
+ backupOffsets.forEach(primaryConsumer::seek);
+ primaryConsumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+ primaryConsumer.commitAsync();
+
+ assertTrue("Consumer failedover to zero offset.", primaryConsumer.position(new TopicPartition("primary.test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedover beyond expected offset.", primaryConsumer.position(
+ new TopicPartition("primary.test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+ assertTrue("Checkpoints were not emitted upstream to primary cluster.", primary.kafka().consume(1,
+ CHECKPOINT_DURATION_MS, "backup.checkpoints.internal").count() > 0);
+
+ primaryConsumer.close();
+
+ waitForCondition(() -> {
+ try {
+ return primaryClient.remoteConsumerOffsets(consumerGroupName, BACKUP_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS)).containsKey(new TopicPartition("backup.test-topic-1", 0));
+ } catch (Throwable e) {
+ return false;
+ }
+ }, CHECKPOINT_DURATION_MS, "Offsets not translated downstream to primary cluster.");
+
+ waitForCondition(() -> {
+ try {
+ return primaryClient.remoteConsumerOffsets(consumerGroupName, BACKUP_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS)).containsKey(new TopicPartition("test-topic-1", 0));
+ } catch (Throwable e) {
+ return false;
+ }
+ }, CHECKPOINT_DURATION_MS, "Offsets not translated upstream to primary cluster.");
+
+ Map<TopicPartition, OffsetAndMetadata> primaryOffsets = primaryClient.remoteConsumerOffsets(consumerGroupName, BACKUP_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS));
+
+ // Failback consumer group to primary cluster
+ backupConsumer = primary.kafka().createConsumer(Collections.singletonMap("group.id", consumerGroupName));
+ backupConsumer.assign(primaryOffsets.keySet());
+ primaryOffsets.forEach(backupConsumer::seek);
+ backupConsumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+ backupConsumer.commitAsync();
+
+ assertTrue("Consumer failedback to zero upstream offset.", backupConsumer.position(new TopicPartition("test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedback to zero downstream offset.", backupConsumer.position(new TopicPartition("backup.test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedback beyond expected upstream offset.", backupConsumer.position(
+ new TopicPartition("test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+ assertTrue("Consumer failedback beyond expected downstream offset.", backupConsumer.position(
+ new TopicPartition("backup.test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+
+ backupConsumer.close();
+
+ // create more matching topics
+ primary.kafka().createTopic("test-topic-2", NUM_PARTITIONS);
+ backup.kafka().createTopic("test-topic-3", NUM_PARTITIONS);
+
+ // only produce messages to the first partition
+ produceMessages(primary, "test-topic-2", 1);
+ produceMessages(backup, "test-topic-3", 1);
+
+ // expect total consumed messages equals to NUM_RECORDS_PER_PARTITION
+ assertEquals("Records were not produced to primary cluster.", NUM_RECORDS_PER_PARTITION,
+ primary.kafka().consume(NUM_RECORDS_PER_PARTITION, RECORD_TRANSFER_DURATION_MS, "test-topic-2").count());
+ assertEquals("Records were not produced to backup cluster.", NUM_RECORDS_PER_PARTITION,
+ backup.kafka().consume(NUM_RECORDS_PER_PARTITION, RECORD_TRANSFER_DURATION_MS, "test-topic-3").count());
+
+ assertEquals("New topic was not replicated to primary cluster.", NUM_RECORDS_PER_PARTITION,
+ primary.kafka().consume(NUM_RECORDS_PER_PARTITION, 2 * RECORD_TRANSFER_DURATION_MS, "backup.test-topic-3").count());
+ assertEquals("New topic was not replicated to backup cluster.", NUM_RECORDS_PER_PARTITION,
+ backup.kafka().consume(NUM_RECORDS_PER_PARTITION, 2 * RECORD_TRANSFER_DURATION_MS, "primary.test-topic-2").count());
+
+ }
+
+ @Test
+ public void testReplicationWithEmptyPartition() throws Exception {
+ String consumerGroupName = "consumer-group-testReplicationWithEmptyPartition";
+ Map<String, Object> consumerProps = Collections.singletonMap("group.id", consumerGroupName);
+
+ // create topic
+ String topic = "test-topic-with-empty-partition";
+ primary.kafka().createTopic(topic, NUM_PARTITIONS);
+
+ // produce to all test-topic-empty's partitions, except the last partition
+ produceMessages(primary, topic, NUM_PARTITIONS - 1);
+
+ // consume before starting the connectors so we don't need to wait for discovery
+ int expectedRecords = NUM_RECORDS_PER_PARTITION * (NUM_PARTITIONS - 1);
+ try (Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps, topic)) {
+ waitForConsumingAllRecords(primaryConsumer, expectedRecords);
+ }
+
+ // one way replication from primary to backup
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + "->" + PRIMARY_CLUSTER_ALIAS + ".enabled", "false");
+ mm2Config = new MirrorMakerConfig(mm2Props);
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS);
+
+ // sleep few seconds to have MM2 finish replication so that "end" consumer will consume some record
+ Thread.sleep(TimeUnit.SECONDS.toMillis(3));
+
+ // consume all records from backup cluster
+ try (Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(consumerProps,
+ PRIMARY_CLUSTER_ALIAS + "." + topic)) {
+ waitForConsumingAllRecords(backupConsumer, expectedRecords);
+ }
+
+ Admin backupClient = backup.kafka().createAdminClient();
+ // retrieve the consumer group offset from backup cluster
+ Map<TopicPartition, OffsetAndMetadata> remoteOffsets =
+ backupClient.listConsumerGroupOffsets(consumerGroupName).partitionsToOffsetAndMetadata().get();
+ // pinpoint the offset of the last partition which does not receive records
+ OffsetAndMetadata offset = remoteOffsets.get(new TopicPartition(PRIMARY_CLUSTER_ALIAS + "." + topic, NUM_PARTITIONS - 1));
+ // offset of the last partition should exist, but its value should be 0
+ assertNotNull("Offset of last partition was not replicated", offset);
+ assertEquals("Offset of last partition is not zero", 0, offset.offset());
+ }
+
+ @Test
+ public void testOneWayReplicationWithAutoOffsetSync() throws InterruptedException {
+ produceMessages(primary, "test-topic-1");
+ String consumerGroupName = "consumer-group-testOneWayReplicationWithAutoOffsetSync";
+ Map<String, Object> consumerProps = new HashMap<String, Object>() {{
+ put("group.id", consumerGroupName);
+ put("auto.offset.reset", "earliest");
+ }};
+ // create consumers before starting the connectors so we don't need to wait for discovery
+ try (Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps,
+ "test-topic-1")) {
+ // we need to wait for consuming all the records for MM2 replicating the expected offsets
+ waitForConsumingAllRecords(primaryConsumer, NUM_RECORDS_PRODUCED);
+ }
+
+ // enable automated consumer group offset sync
+ mm2Props.put("sync.group.offsets.enabled", "true");
+ mm2Props.put("sync.group.offsets.interval.seconds", "1");
+ // one way replication from primary to backup
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + "->" + PRIMARY_CLUSTER_ALIAS + ".enabled", "false");
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS);
+
+ // create a consumer at backup cluster with same consumer group Id to consume 1 topic
+ Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(
+ consumerProps, "primary.test-topic-1");
+
+ waitForConsumerGroupOffsetSync(backup, backupConsumer, Collections.singletonList("primary.test-topic-1"),
+ consumerGroupName, NUM_RECORDS_PRODUCED);
+
+ ConsumerRecords<byte[], byte[]> records = backupConsumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+
+ // the size of consumer record should be zero, because the offsets of the same consumer group
+ // have been automatically synchronized from primary to backup by the background job, so no
+ // more records to consume from the replicated topic by the same consumer group at backup cluster
+ assertEquals("consumer record size is not zero", 0, records.count());
+
+ // now create a new topic in primary cluster
+ primary.kafka().createTopic("test-topic-2", NUM_PARTITIONS);
+ backup.kafka().createTopic("primary.test-topic-2", 1);
+ // produce some records to the new topic in primary cluster
+ produceMessages(primary, "test-topic-2");
+
+ // create a consumer at primary cluster to consume the new topic
+ try (Consumer<byte[], byte[]> consumer1 = primary.kafka().createConsumerAndSubscribeTo(Collections.singletonMap(
+ "group.id", "consumer-group-1"), "test-topic-2")) {
+ // we need to wait for consuming all the records for MM2 replicating the expected offsets
+ waitForConsumingAllRecords(consumer1, NUM_RECORDS_PRODUCED);
+ }
+
+ // create a consumer at backup cluster with same consumer group Id to consume old and new topic
+ backupConsumer = backup.kafka().createConsumerAndSubscribeTo(Collections.singletonMap(
+ "group.id", consumerGroupName), "primary.test-topic-1", "primary.test-topic-2");
+
+ waitForConsumerGroupOffsetSync(backup, backupConsumer, Arrays.asList("primary.test-topic-1", "primary.test-topic-2"),
+ consumerGroupName, NUM_RECORDS_PRODUCED);
+
+ records = backupConsumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+ // similar reasoning as above, no more records to consume by the same consumer group at backup cluster
+ assertEquals("consumer record size is not zero", 0, records.count());
+ backupConsumer.close();
+ }
+
+ /*
+ * launch the connectors on kafka connect cluster and check if they are running
+ */
+ private static void waitUntilMirrorMakerIsRunning(EmbeddedConnectCluster connectCluster,
+ List<Class<? extends Connector>> connectorClasses, MirrorMakerConfig mm2Config,
+ String primary, String backup) throws InterruptedException {
+ for (int i = 0; i < connectorClasses.size(); i++) {
+ String connector = connectorClasses.get(i).getSimpleName();
+ connectCluster.configureConnector(connector, mm2Config.connectorBaseConfig(
+ new SourceAndTarget(primary, backup), connectorClasses.get(i)));
+ }
+
+ // we wait for the connector and tasks to come up for each connector, so that when we do the
+ // actual testing, we are certain that the tasks are up and running; this will prevent
+ // flaky tests where the connector and tasks didn't start up in time for the tests to be run
+ List<String> connectorNames = connectorClasses.stream().map(x -> x.getSimpleName())
+ .collect(Collectors.toList());
+ for (String connector : connectorNames) {
+ connectCluster.assertions().assertConnectorAndAtLeastNumTasksAreRunning(connector, 1,
+ "Connector " + connector + " tasks did not start in time on cluster: " + connectCluster);
+ }
+ }
+
+ /*
+ * delete all topics of the input kafka cluster
+ */
+ private static void deleteAllTopics(EmbeddedKafkaCluster cluster) {
+ Admin client = cluster.createAdminClient();
+ try {
+ client.deleteTopics(client.listTopics().names().get());
+ } catch (Throwable e) {
+ // should not run into exception normally. In case of Exception,
+ // simply fail the test and investigate
+ }
+ }
+
+ /*
+ * retrieve the config value based on the input cluster, topic and config name
+ */
+ private static String getTopicConfig(EmbeddedKafkaCluster cluster, String topic, String configName) {
+ Admin client = cluster.createAdminClient();
+ Collection<ConfigResource> cr = Collections.singleton(
+ new ConfigResource(ConfigResource.Type.TOPIC, topic));
+ try {
+ DescribeConfigsResult configsResult = client.describeConfigs(cr);
+ Config allConfigs = (Config) configsResult.all().get().values().toArray()[0];
+ Iterator<ConfigEntry> configIterator = allConfigs.entries().iterator();
Review comment:
Can we use `allConfigs.get()` to find the configs we want instead of searching for them?
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationBaseTest.java
##########
@@ -0,0 +1,617 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.Config;
+import org.apache.kafka.clients.admin.ConfigEntry;
+import org.apache.kafka.clients.admin.DescribeConfigsResult;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.clients.CommonClientConfigs;
+import org.apache.kafka.common.config.ConfigResource;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.config.SslConfigs;
+import org.apache.kafka.common.config.types.Password;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.connector.Connector;
+import org.apache.kafka.connect.mirror.MirrorClient;
+import org.apache.kafka.connect.mirror.MirrorHeartbeatConnector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.MirrorSourceConnector;
+import org.apache.kafka.connect.mirror.SourceAndTarget;
+import org.apache.kafka.connect.mirror.MirrorCheckpointConnector;
+import org.apache.kafka.connect.util.clusters.EmbeddedConnectCluster;
+import org.apache.kafka.connect.util.clusters.EmbeddedKafkaCluster;
+import org.apache.kafka.test.IntegrationTest;
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertNotNull;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import static org.apache.kafka.connect.mirror.TestUtils.generateRecords;
+
+/**
+ * Tests MM2 replication and failover/failback logic.
+ *
+ * MM2 is configured with active/active replication between two Kafka clusters. Tests validate that
+ * records sent to either cluster arrive at the other cluster. Then, a consumer group is migrated from
+ * one cluster to the other and back. Tests validate that consumer offsets are translated and replicated
+ * between clusters during this failover and failback.
+ */
+@Category(IntegrationTest.class)
+public abstract class MirrorConnectorsIntegrationBaseTest {
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationBaseTest.class);
+
+ private static final int NUM_RECORDS_PER_PARTITION = 10;
+ private static final int NUM_PARTITIONS = 10;
+ private static final int NUM_RECORDS_PRODUCED = NUM_PARTITIONS * NUM_RECORDS_PER_PARTITION;
+ private static final int RECORD_TRANSFER_DURATION_MS = 30_000;
+ private static final int CHECKPOINT_DURATION_MS = 20_000;
+ private static final int RECORD_CONSUME_DURATION_MS = 20_000;
+ private static final int OFFSET_SYNC_DURATION_MS = 30_000;
+ private static final int NUM_WORKERS = 3;
+ private static final int CONSUMER_POLL_TIMEOUT_MS = 500;
+ private static final int BROKER_RESTART_TIMEOUT_MS = 10_000;
+ private static final long DEFAULT_PRODUCE_SEND_DURATION_MS = TimeUnit.SECONDS.toMillis(120);
+ private static final String PRIMARY_CLUSTER_ALIAS = "primary";
+ private static final String BACKUP_CLUSTER_ALIAS = "backup";
+ private static final List<Class<? extends Connector>> CONNECTOR_LIST =
+ Arrays.asList(MirrorSourceConnector.class, MirrorCheckpointConnector.class, MirrorHeartbeatConnector.class);
+
+ private Map<String, String> mm2Props;
+ private MirrorMakerConfig mm2Config;
+ private EmbeddedConnectCluster primary;
+ private EmbeddedConnectCluster backup;
+
+ private final AtomicBoolean exited = new AtomicBoolean(false);
+ protected Properties primaryBrokerProps = new Properties();
+ protected Properties backupBrokerProps = new Properties();
+ private Map<String, String> primaryWorkerProps = new HashMap<>();
+ private Map<String, String> backupWorkerProps = new HashMap<>();
+ abstract Map<String, Object> getSslConfig();
+
+ protected void startClusters() throws InterruptedException {
+ primaryBrokerProps.put("auto.create.topics.enable", "false");
+ backupBrokerProps.put("auto.create.topics.enable", "false");
+
+ mm2Props = basicMM2Config();
+
+ final Map<String, Object> sslConfig = getSslConfig();
+ if (sslConfig != null) {
+ Properties sslProps = new Properties();
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, sslConfig.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG));
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, ((Password) sslConfig.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)).value());
+ sslProps.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL");
+
+ // set SSL config for kafka connect worker
+ backupWorkerProps.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> BACKUP_CLUSTER_ALIAS + "." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ // set SSL config for producer used by source task in MM2
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> BACKUP_CLUSTER_ALIAS + ".producer." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ }
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+ primaryWorkerProps = mm2Config.workerConfig(new SourceAndTarget(BACKUP_CLUSTER_ALIAS, PRIMARY_CLUSTER_ALIAS));
+ backupWorkerProps.putAll(mm2Config.workerConfig(new SourceAndTarget(PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS)));
+
+ primary = new EmbeddedConnectCluster.Builder()
+ .name(PRIMARY_CLUSTER_ALIAS + "-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(primaryBrokerProps)
+ .workerProps(primaryWorkerProps)
+ .build();
+
+ backup = new EmbeddedConnectCluster.Builder()
+ .name(BACKUP_CLUSTER_ALIAS + "-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(backupBrokerProps)
+ .workerProps(backupWorkerProps)
+ .build();
+
+ primary.start();
+ primary.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of " + PRIMARY_CLUSTER_ALIAS + "-connect-cluster did not start in time.");
+
+ backup.start();
+ backup.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of " + BACKUP_CLUSTER_ALIAS + "-connect-cluster did not start in time.");
+
+ createTopics();
+
+ warmUpConsumer();
+
+ log.info(PRIMARY_CLUSTER_ALIAS + " REST service: {}", primary.endpointForResource("connectors"));
+ log.info(BACKUP_CLUSTER_ALIAS + " REST service: {}", backup.endpointForResource("connectors"));
+ log.info(PRIMARY_CLUSTER_ALIAS + " brokers: {}", primary.kafka().bootstrapServers());
+ log.info(BACKUP_CLUSTER_ALIAS + " brokers: {}", backup.kafka().bootstrapServers());
+
+ // now that the brokers are running, we can finish setting up the Connectors
+ mm2Props.put(PRIMARY_CLUSTER_ALIAS + ".bootstrap.servers", primary.kafka().bootstrapServers());
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + ".bootstrap.servers", backup.kafka().bootstrapServers());
+
+ Exit.setExitProcedure((status, errorCode) -> exited.set(true));
+ }
+
+ public void shutdownClusters() {
+ for (String x : primary.connectors()) {
+ primary.deleteConnector(x);
+ }
+ for (String x : backup.connectors()) {
+ backup.deleteConnector(x);
+ }
+ deleteAllTopics(primary.kafka());
+ deleteAllTopics(backup.kafka());
+ primary.stop();
+ backup.stop();
+ try {
+ assertFalse(exited.get());
+ } finally {
+ Exit.resetExitProcedure();
+ }
+ }
+
+ @Test
+ public void testReplication() throws InterruptedException {
+ produceMessages(primary, "test-topic-1");
+ produceMessages(backup, "test-topic-1");
+ String consumerGroupName = "consumer-group-testReplication";
+ Map<String, Object> consumerProps = new HashMap<String, Object>() {{
+ put("group.id", consumerGroupName);
+ put("auto.offset.reset", "latest");
+ }};
+ // create consumers before starting the connectors so we don't need to wait for discovery
+ Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps, "test-topic-1");
+ waitForConsumingAllRecords(primaryConsumer, 0);
+
+ Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(consumerProps, "test-topic-1");
+ waitForConsumingAllRecords(backupConsumer, 0);
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS);
+ waitUntilMirrorMakerIsRunning(primary, CONNECTOR_LIST, mm2Config, BACKUP_CLUSTER_ALIAS, PRIMARY_CLUSTER_ALIAS);
+
+ MirrorClient primaryClient = new MirrorClient(mm2Config.clientConfig(PRIMARY_CLUSTER_ALIAS));
+ MirrorClient backupClient = new MirrorClient(mm2Config.clientConfig(BACKUP_CLUSTER_ALIAS));
+
+ assertEquals("topic config was not synced", TopicConfig.CLEANUP_POLICY_COMPACT,
+ getTopicConfig(backup.kafka(), "primary.test-topic-1", TopicConfig.CLEANUP_POLICY_CONFIG));
+
+ assertEquals("Records were not produced to primary cluster.", NUM_RECORDS_PRODUCED,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "test-topic-1").count());
+ assertEquals("Records were not replicated to backup cluster.", NUM_RECORDS_PRODUCED,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "primary.test-topic-1").count());
+ assertEquals("Records were not produced to backup cluster.", NUM_RECORDS_PRODUCED,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "test-topic-1").count());
+ assertEquals("Records were not replicated to primary cluster.", NUM_RECORDS_PRODUCED,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "backup.test-topic-1").count());
+
+ assertEquals("Primary cluster doesn't have all records from both clusters.", NUM_RECORDS_PRODUCED * 2,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED * 2, RECORD_TRANSFER_DURATION_MS, "backup.test-topic-1", "test-topic-1").count());
+ assertEquals("Backup cluster doesn't have all records from both clusters.", NUM_RECORDS_PRODUCED * 2,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED * 2, RECORD_TRANSFER_DURATION_MS, "primary.test-topic-1", "test-topic-1").count());
+
+ assertTrue("Heartbeats were not emitted to primary cluster.", primary.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "heartbeats").count() > 0);
+ assertTrue("Heartbeats were not emitted to backup cluster.", backup.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "heartbeats").count() > 0);
+ assertTrue("Heartbeats were not replicated downstream to backup cluster.", backup.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "primary.heartbeats").count() > 0);
+ assertTrue("Heartbeats were not replicated downstream to primary cluster.", primary.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "backup.heartbeats").count() > 0);
+
+ assertTrue("Did not find upstream primary cluster.", backupClient.upstreamClusters().contains(PRIMARY_CLUSTER_ALIAS));
+ assertEquals("Did not calculate replication hops correctly.", 1, backupClient.replicationHops(PRIMARY_CLUSTER_ALIAS));
+ assertTrue("Did not find upstream backup cluster.", primaryClient.upstreamClusters().contains(BACKUP_CLUSTER_ALIAS));
+ assertEquals("Did not calculate replication hops correctly.", 1, primaryClient.replicationHops(BACKUP_CLUSTER_ALIAS));
+ assertTrue("Checkpoints were not emitted downstream to backup cluster.", backup.kafka().consume(1,
+ CHECKPOINT_DURATION_MS, "primary.checkpoints.internal").count() > 0);
+
+ Map<TopicPartition, OffsetAndMetadata> backupOffsets = backupClient.remoteConsumerOffsets(consumerGroupName, PRIMARY_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS));
+
+ assertTrue("Offsets not translated downstream to backup cluster. Found: " + backupOffsets, backupOffsets.containsKey(
+ new TopicPartition("primary.test-topic-1", 0)));
+
+ // Failover consumer group to backup cluster.
+ primaryConsumer = backup.kafka().createConsumer(Collections.singletonMap("group.id", consumerGroupName));
+ primaryConsumer.assign(backupOffsets.keySet());
+ backupOffsets.forEach(primaryConsumer::seek);
+ primaryConsumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+ primaryConsumer.commitAsync();
+
+ assertTrue("Consumer failedover to zero offset.", primaryConsumer.position(new TopicPartition("primary.test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedover beyond expected offset.", primaryConsumer.position(
+ new TopicPartition("primary.test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+ assertTrue("Checkpoints were not emitted upstream to primary cluster.", primary.kafka().consume(1,
+ CHECKPOINT_DURATION_MS, "backup.checkpoints.internal").count() > 0);
+
+ primaryConsumer.close();
Review comment:
Closing a client in the middle of a test can be confusing. I wonder if we could wrap this whole block about `primaryConsumer` in a try with resource block. WDYT?
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationBaseTest.java
##########
@@ -0,0 +1,617 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.Config;
+import org.apache.kafka.clients.admin.ConfigEntry;
+import org.apache.kafka.clients.admin.DescribeConfigsResult;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.clients.CommonClientConfigs;
+import org.apache.kafka.common.config.ConfigResource;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.config.SslConfigs;
+import org.apache.kafka.common.config.types.Password;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.connector.Connector;
+import org.apache.kafka.connect.mirror.MirrorClient;
+import org.apache.kafka.connect.mirror.MirrorHeartbeatConnector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.MirrorSourceConnector;
+import org.apache.kafka.connect.mirror.SourceAndTarget;
+import org.apache.kafka.connect.mirror.MirrorCheckpointConnector;
+import org.apache.kafka.connect.util.clusters.EmbeddedConnectCluster;
+import org.apache.kafka.connect.util.clusters.EmbeddedKafkaCluster;
+import org.apache.kafka.test.IntegrationTest;
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertNotNull;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import static org.apache.kafka.connect.mirror.TestUtils.generateRecords;
+
+/**
+ * Tests MM2 replication and failover/failback logic.
+ *
+ * MM2 is configured with active/active replication between two Kafka clusters. Tests validate that
+ * records sent to either cluster arrive at the other cluster. Then, a consumer group is migrated from
+ * one cluster to the other and back. Tests validate that consumer offsets are translated and replicated
+ * between clusters during this failover and failback.
+ */
+@Category(IntegrationTest.class)
+public abstract class MirrorConnectorsIntegrationBaseTest {
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationBaseTest.class);
+
+ private static final int NUM_RECORDS_PER_PARTITION = 10;
+ private static final int NUM_PARTITIONS = 10;
+ private static final int NUM_RECORDS_PRODUCED = NUM_PARTITIONS * NUM_RECORDS_PER_PARTITION;
+ private static final int RECORD_TRANSFER_DURATION_MS = 30_000;
+ private static final int CHECKPOINT_DURATION_MS = 20_000;
+ private static final int RECORD_CONSUME_DURATION_MS = 20_000;
+ private static final int OFFSET_SYNC_DURATION_MS = 30_000;
+ private static final int NUM_WORKERS = 3;
+ private static final int CONSUMER_POLL_TIMEOUT_MS = 500;
+ private static final int BROKER_RESTART_TIMEOUT_MS = 10_000;
+ private static final long DEFAULT_PRODUCE_SEND_DURATION_MS = TimeUnit.SECONDS.toMillis(120);
+ private static final String PRIMARY_CLUSTER_ALIAS = "primary";
+ private static final String BACKUP_CLUSTER_ALIAS = "backup";
+ private static final List<Class<? extends Connector>> CONNECTOR_LIST =
+ Arrays.asList(MirrorSourceConnector.class, MirrorCheckpointConnector.class, MirrorHeartbeatConnector.class);
+
+ private Map<String, String> mm2Props;
+ private MirrorMakerConfig mm2Config;
+ private EmbeddedConnectCluster primary;
+ private EmbeddedConnectCluster backup;
+
+ private final AtomicBoolean exited = new AtomicBoolean(false);
+ protected Properties primaryBrokerProps = new Properties();
+ protected Properties backupBrokerProps = new Properties();
+ private Map<String, String> primaryWorkerProps = new HashMap<>();
+ private Map<String, String> backupWorkerProps = new HashMap<>();
+ abstract Map<String, Object> getSslConfig();
+
+ protected void startClusters() throws InterruptedException {
+ primaryBrokerProps.put("auto.create.topics.enable", "false");
+ backupBrokerProps.put("auto.create.topics.enable", "false");
+
+ mm2Props = basicMM2Config();
+
+ final Map<String, Object> sslConfig = getSslConfig();
+ if (sslConfig != null) {
+ Properties sslProps = new Properties();
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, sslConfig.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG));
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, ((Password) sslConfig.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)).value());
+ sslProps.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL");
+
+ // set SSL config for kafka connect worker
+ backupWorkerProps.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> BACKUP_CLUSTER_ALIAS + "." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ // set SSL config for producer used by source task in MM2
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> BACKUP_CLUSTER_ALIAS + ".producer." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ }
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+ primaryWorkerProps = mm2Config.workerConfig(new SourceAndTarget(BACKUP_CLUSTER_ALIAS, PRIMARY_CLUSTER_ALIAS));
+ backupWorkerProps.putAll(mm2Config.workerConfig(new SourceAndTarget(PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS)));
+
+ primary = new EmbeddedConnectCluster.Builder()
+ .name(PRIMARY_CLUSTER_ALIAS + "-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(primaryBrokerProps)
+ .workerProps(primaryWorkerProps)
+ .build();
+
+ backup = new EmbeddedConnectCluster.Builder()
+ .name(BACKUP_CLUSTER_ALIAS + "-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(backupBrokerProps)
+ .workerProps(backupWorkerProps)
+ .build();
+
+ primary.start();
+ primary.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of " + PRIMARY_CLUSTER_ALIAS + "-connect-cluster did not start in time.");
+
+ backup.start();
+ backup.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of " + BACKUP_CLUSTER_ALIAS + "-connect-cluster did not start in time.");
+
+ createTopics();
+
+ warmUpConsumer();
+
+ log.info(PRIMARY_CLUSTER_ALIAS + " REST service: {}", primary.endpointForResource("connectors"));
+ log.info(BACKUP_CLUSTER_ALIAS + " REST service: {}", backup.endpointForResource("connectors"));
+ log.info(PRIMARY_CLUSTER_ALIAS + " brokers: {}", primary.kafka().bootstrapServers());
+ log.info(BACKUP_CLUSTER_ALIAS + " brokers: {}", backup.kafka().bootstrapServers());
+
+ // now that the brokers are running, we can finish setting up the Connectors
+ mm2Props.put(PRIMARY_CLUSTER_ALIAS + ".bootstrap.servers", primary.kafka().bootstrapServers());
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + ".bootstrap.servers", backup.kafka().bootstrapServers());
+
+ Exit.setExitProcedure((status, errorCode) -> exited.set(true));
+ }
+
+ public void shutdownClusters() {
+ for (String x : primary.connectors()) {
+ primary.deleteConnector(x);
+ }
+ for (String x : backup.connectors()) {
+ backup.deleteConnector(x);
+ }
+ deleteAllTopics(primary.kafka());
+ deleteAllTopics(backup.kafka());
+ primary.stop();
+ backup.stop();
+ try {
+ assertFalse(exited.get());
+ } finally {
+ Exit.resetExitProcedure();
+ }
+ }
+
+ @Test
+ public void testReplication() throws InterruptedException {
+ produceMessages(primary, "test-topic-1");
+ produceMessages(backup, "test-topic-1");
+ String consumerGroupName = "consumer-group-testReplication";
+ Map<String, Object> consumerProps = new HashMap<String, Object>() {{
+ put("group.id", consumerGroupName);
+ put("auto.offset.reset", "latest");
+ }};
+ // create consumers before starting the connectors so we don't need to wait for discovery
+ Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps, "test-topic-1");
+ waitForConsumingAllRecords(primaryConsumer, 0);
+
+ Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(consumerProps, "test-topic-1");
+ waitForConsumingAllRecords(backupConsumer, 0);
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS);
+ waitUntilMirrorMakerIsRunning(primary, CONNECTOR_LIST, mm2Config, BACKUP_CLUSTER_ALIAS, PRIMARY_CLUSTER_ALIAS);
+
+ MirrorClient primaryClient = new MirrorClient(mm2Config.clientConfig(PRIMARY_CLUSTER_ALIAS));
+ MirrorClient backupClient = new MirrorClient(mm2Config.clientConfig(BACKUP_CLUSTER_ALIAS));
+
+ assertEquals("topic config was not synced", TopicConfig.CLEANUP_POLICY_COMPACT,
+ getTopicConfig(backup.kafka(), "primary.test-topic-1", TopicConfig.CLEANUP_POLICY_CONFIG));
+
+ assertEquals("Records were not produced to primary cluster.", NUM_RECORDS_PRODUCED,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "test-topic-1").count());
+ assertEquals("Records were not replicated to backup cluster.", NUM_RECORDS_PRODUCED,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "primary.test-topic-1").count());
+ assertEquals("Records were not produced to backup cluster.", NUM_RECORDS_PRODUCED,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "test-topic-1").count());
+ assertEquals("Records were not replicated to primary cluster.", NUM_RECORDS_PRODUCED,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "backup.test-topic-1").count());
+
+ assertEquals("Primary cluster doesn't have all records from both clusters.", NUM_RECORDS_PRODUCED * 2,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED * 2, RECORD_TRANSFER_DURATION_MS, "backup.test-topic-1", "test-topic-1").count());
+ assertEquals("Backup cluster doesn't have all records from both clusters.", NUM_RECORDS_PRODUCED * 2,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED * 2, RECORD_TRANSFER_DURATION_MS, "primary.test-topic-1", "test-topic-1").count());
+
+ assertTrue("Heartbeats were not emitted to primary cluster.", primary.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "heartbeats").count() > 0);
+ assertTrue("Heartbeats were not emitted to backup cluster.", backup.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "heartbeats").count() > 0);
+ assertTrue("Heartbeats were not replicated downstream to backup cluster.", backup.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "primary.heartbeats").count() > 0);
+ assertTrue("Heartbeats were not replicated downstream to primary cluster.", primary.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "backup.heartbeats").count() > 0);
+
+ assertTrue("Did not find upstream primary cluster.", backupClient.upstreamClusters().contains(PRIMARY_CLUSTER_ALIAS));
+ assertEquals("Did not calculate replication hops correctly.", 1, backupClient.replicationHops(PRIMARY_CLUSTER_ALIAS));
+ assertTrue("Did not find upstream backup cluster.", primaryClient.upstreamClusters().contains(BACKUP_CLUSTER_ALIAS));
+ assertEquals("Did not calculate replication hops correctly.", 1, primaryClient.replicationHops(BACKUP_CLUSTER_ALIAS));
+ assertTrue("Checkpoints were not emitted downstream to backup cluster.", backup.kafka().consume(1,
+ CHECKPOINT_DURATION_MS, "primary.checkpoints.internal").count() > 0);
+
+ Map<TopicPartition, OffsetAndMetadata> backupOffsets = backupClient.remoteConsumerOffsets(consumerGroupName, PRIMARY_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS));
+
+ assertTrue("Offsets not translated downstream to backup cluster. Found: " + backupOffsets, backupOffsets.containsKey(
+ new TopicPartition("primary.test-topic-1", 0)));
+
+ // Failover consumer group to backup cluster.
+ primaryConsumer = backup.kafka().createConsumer(Collections.singletonMap("group.id", consumerGroupName));
+ primaryConsumer.assign(backupOffsets.keySet());
+ backupOffsets.forEach(primaryConsumer::seek);
+ primaryConsumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+ primaryConsumer.commitAsync();
+
+ assertTrue("Consumer failedover to zero offset.", primaryConsumer.position(new TopicPartition("primary.test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedover beyond expected offset.", primaryConsumer.position(
+ new TopicPartition("primary.test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+ assertTrue("Checkpoints were not emitted upstream to primary cluster.", primary.kafka().consume(1,
+ CHECKPOINT_DURATION_MS, "backup.checkpoints.internal").count() > 0);
+
+ primaryConsumer.close();
+
+ waitForCondition(() -> {
+ try {
+ return primaryClient.remoteConsumerOffsets(consumerGroupName, BACKUP_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS)).containsKey(new TopicPartition("backup.test-topic-1", 0));
+ } catch (Throwable e) {
+ return false;
+ }
+ }, CHECKPOINT_DURATION_MS, "Offsets not translated downstream to primary cluster.");
+
+ waitForCondition(() -> {
+ try {
+ return primaryClient.remoteConsumerOffsets(consumerGroupName, BACKUP_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS)).containsKey(new TopicPartition("test-topic-1", 0));
+ } catch (Throwable e) {
+ return false;
+ }
+ }, CHECKPOINT_DURATION_MS, "Offsets not translated upstream to primary cluster.");
+
+ Map<TopicPartition, OffsetAndMetadata> primaryOffsets = primaryClient.remoteConsumerOffsets(consumerGroupName, BACKUP_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS));
+
+ // Failback consumer group to primary cluster
+ backupConsumer = primary.kafka().createConsumer(Collections.singletonMap("group.id", consumerGroupName));
+ backupConsumer.assign(primaryOffsets.keySet());
+ primaryOffsets.forEach(backupConsumer::seek);
+ backupConsumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+ backupConsumer.commitAsync();
+
+ assertTrue("Consumer failedback to zero upstream offset.", backupConsumer.position(new TopicPartition("test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedback to zero downstream offset.", backupConsumer.position(new TopicPartition("backup.test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedback beyond expected upstream offset.", backupConsumer.position(
+ new TopicPartition("test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+ assertTrue("Consumer failedback beyond expected downstream offset.", backupConsumer.position(
+ new TopicPartition("backup.test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+
+ backupConsumer.close();
+
+ // create more matching topics
+ primary.kafka().createTopic("test-topic-2", NUM_PARTITIONS);
+ backup.kafka().createTopic("test-topic-3", NUM_PARTITIONS);
+
+ // only produce messages to the first partition
+ produceMessages(primary, "test-topic-2", 1);
+ produceMessages(backup, "test-topic-3", 1);
+
+ // expect total consumed messages equals to NUM_RECORDS_PER_PARTITION
+ assertEquals("Records were not produced to primary cluster.", NUM_RECORDS_PER_PARTITION,
+ primary.kafka().consume(NUM_RECORDS_PER_PARTITION, RECORD_TRANSFER_DURATION_MS, "test-topic-2").count());
+ assertEquals("Records were not produced to backup cluster.", NUM_RECORDS_PER_PARTITION,
+ backup.kafka().consume(NUM_RECORDS_PER_PARTITION, RECORD_TRANSFER_DURATION_MS, "test-topic-3").count());
+
+ assertEquals("New topic was not replicated to primary cluster.", NUM_RECORDS_PER_PARTITION,
+ primary.kafka().consume(NUM_RECORDS_PER_PARTITION, 2 * RECORD_TRANSFER_DURATION_MS, "backup.test-topic-3").count());
+ assertEquals("New topic was not replicated to backup cluster.", NUM_RECORDS_PER_PARTITION,
+ backup.kafka().consume(NUM_RECORDS_PER_PARTITION, 2 * RECORD_TRANSFER_DURATION_MS, "primary.test-topic-2").count());
+
+ }
+
+ @Test
+ public void testReplicationWithEmptyPartition() throws Exception {
+ String consumerGroupName = "consumer-group-testReplicationWithEmptyPartition";
+ Map<String, Object> consumerProps = Collections.singletonMap("group.id", consumerGroupName);
+
+ // create topic
+ String topic = "test-topic-with-empty-partition";
+ primary.kafka().createTopic(topic, NUM_PARTITIONS);
+
+ // produce to all test-topic-empty's partitions, except the last partition
+ produceMessages(primary, topic, NUM_PARTITIONS - 1);
+
+ // consume before starting the connectors so we don't need to wait for discovery
+ int expectedRecords = NUM_RECORDS_PER_PARTITION * (NUM_PARTITIONS - 1);
+ try (Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps, topic)) {
+ waitForConsumingAllRecords(primaryConsumer, expectedRecords);
+ }
+
+ // one way replication from primary to backup
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + "->" + PRIMARY_CLUSTER_ALIAS + ".enabled", "false");
+ mm2Config = new MirrorMakerConfig(mm2Props);
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS);
+
+ // sleep few seconds to have MM2 finish replication so that "end" consumer will consume some record
+ Thread.sleep(TimeUnit.SECONDS.toMillis(3));
+
+ // consume all records from backup cluster
+ try (Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(consumerProps,
+ PRIMARY_CLUSTER_ALIAS + "." + topic)) {
+ waitForConsumingAllRecords(backupConsumer, expectedRecords);
+ }
+
+ Admin backupClient = backup.kafka().createAdminClient();
+ // retrieve the consumer group offset from backup cluster
+ Map<TopicPartition, OffsetAndMetadata> remoteOffsets =
+ backupClient.listConsumerGroupOffsets(consumerGroupName).partitionsToOffsetAndMetadata().get();
+ // pinpoint the offset of the last partition which does not receive records
+ OffsetAndMetadata offset = remoteOffsets.get(new TopicPartition(PRIMARY_CLUSTER_ALIAS + "." + topic, NUM_PARTITIONS - 1));
+ // offset of the last partition should exist, but its value should be 0
+ assertNotNull("Offset of last partition was not replicated", offset);
+ assertEquals("Offset of last partition is not zero", 0, offset.offset());
+ }
+
+ @Test
+ public void testOneWayReplicationWithAutoOffsetSync() throws InterruptedException {
+ produceMessages(primary, "test-topic-1");
+ String consumerGroupName = "consumer-group-testOneWayReplicationWithAutoOffsetSync";
+ Map<String, Object> consumerProps = new HashMap<String, Object>() {{
+ put("group.id", consumerGroupName);
+ put("auto.offset.reset", "earliest");
+ }};
+ // create consumers before starting the connectors so we don't need to wait for discovery
+ try (Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps,
+ "test-topic-1")) {
+ // we need to wait for consuming all the records for MM2 replicating the expected offsets
+ waitForConsumingAllRecords(primaryConsumer, NUM_RECORDS_PRODUCED);
+ }
+
+ // enable automated consumer group offset sync
+ mm2Props.put("sync.group.offsets.enabled", "true");
+ mm2Props.put("sync.group.offsets.interval.seconds", "1");
+ // one way replication from primary to backup
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + "->" + PRIMARY_CLUSTER_ALIAS + ".enabled", "false");
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS);
+
+ // create a consumer at backup cluster with same consumer group Id to consume 1 topic
+ Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(
+ consumerProps, "primary.test-topic-1");
+
+ waitForConsumerGroupOffsetSync(backup, backupConsumer, Collections.singletonList("primary.test-topic-1"),
+ consumerGroupName, NUM_RECORDS_PRODUCED);
+
+ ConsumerRecords<byte[], byte[]> records = backupConsumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+
+ // the size of consumer record should be zero, because the offsets of the same consumer group
+ // have been automatically synchronized from primary to backup by the background job, so no
+ // more records to consume from the replicated topic by the same consumer group at backup cluster
+ assertEquals("consumer record size is not zero", 0, records.count());
+
+ // now create a new topic in primary cluster
+ primary.kafka().createTopic("test-topic-2", NUM_PARTITIONS);
+ backup.kafka().createTopic("primary.test-topic-2", 1);
+ // produce some records to the new topic in primary cluster
+ produceMessages(primary, "test-topic-2");
+
+ // create a consumer at primary cluster to consume the new topic
+ try (Consumer<byte[], byte[]> consumer1 = primary.kafka().createConsumerAndSubscribeTo(Collections.singletonMap(
+ "group.id", "consumer-group-1"), "test-topic-2")) {
+ // we need to wait for consuming all the records for MM2 replicating the expected offsets
+ waitForConsumingAllRecords(consumer1, NUM_RECORDS_PRODUCED);
+ }
+
+ // create a consumer at backup cluster with same consumer group Id to consume old and new topic
+ backupConsumer = backup.kafka().createConsumerAndSubscribeTo(Collections.singletonMap(
+ "group.id", consumerGroupName), "primary.test-topic-1", "primary.test-topic-2");
+
+ waitForConsumerGroupOffsetSync(backup, backupConsumer, Arrays.asList("primary.test-topic-1", "primary.test-topic-2"),
+ consumerGroupName, NUM_RECORDS_PRODUCED);
+
+ records = backupConsumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+ // similar reasoning as above, no more records to consume by the same consumer group at backup cluster
+ assertEquals("consumer record size is not zero", 0, records.count());
+ backupConsumer.close();
+ }
+
+ /*
+ * launch the connectors on kafka connect cluster and check if they are running
+ */
+ private static void waitUntilMirrorMakerIsRunning(EmbeddedConnectCluster connectCluster,
+ List<Class<? extends Connector>> connectorClasses, MirrorMakerConfig mm2Config,
+ String primary, String backup) throws InterruptedException {
+ for (int i = 0; i < connectorClasses.size(); i++) {
+ String connector = connectorClasses.get(i).getSimpleName();
+ connectCluster.configureConnector(connector, mm2Config.connectorBaseConfig(
+ new SourceAndTarget(primary, backup), connectorClasses.get(i)));
+ }
+
+ // we wait for the connector and tasks to come up for each connector, so that when we do the
+ // actual testing, we are certain that the tasks are up and running; this will prevent
+ // flaky tests where the connector and tasks didn't start up in time for the tests to be run
+ List<String> connectorNames = connectorClasses.stream().map(x -> x.getSimpleName())
+ .collect(Collectors.toList());
+ for (String connector : connectorNames) {
+ connectCluster.assertions().assertConnectorAndAtLeastNumTasksAreRunning(connector, 1,
+ "Connector " + connector + " tasks did not start in time on cluster: " + connectCluster);
+ }
+ }
+
+ /*
+ * delete all topics of the input kafka cluster
+ */
+ private static void deleteAllTopics(EmbeddedKafkaCluster cluster) {
+ Admin client = cluster.createAdminClient();
+ try {
+ client.deleteTopics(client.listTopics().names().get());
+ } catch (Throwable e) {
+ // should not run into exception normally. In case of Exception,
+ // simply fail the test and investigate
+ }
+ }
+
+ /*
+ * retrieve the config value based on the input cluster, topic and config name
+ */
+ private static String getTopicConfig(EmbeddedKafkaCluster cluster, String topic, String configName) {
+ Admin client = cluster.createAdminClient();
+ Collection<ConfigResource> cr = Collections.singleton(
+ new ConfigResource(ConfigResource.Type.TOPIC, topic));
+ try {
+ DescribeConfigsResult configsResult = client.describeConfigs(cr);
+ Config allConfigs = (Config) configsResult.all().get().values().toArray()[0];
+ Iterator<ConfigEntry> configIterator = allConfigs.entries().iterator();
+ while (configIterator.hasNext()) {
+ ConfigEntry currentConfig = configIterator.next();
+ if (currentConfig.name().equals(configName)) {
+ return currentConfig.value();
+ }
+ }
+ } catch (Throwable e) {
+ // should not run into exception normally. In case of Exception,
+ // simply fail the test and investigate
+ }
+ return null;
+ }
+
+ /*
+ * produce messages to the cluster and topic
+ */
+ protected void produceMessages(EmbeddedConnectCluster cluster, String topicName) {
+ Map<String, String> recordSent = generateRecords(NUM_RECORDS_PRODUCED);
+ for (Map.Entry<String, String> entry : recordSent.entrySet()) {
+ cluster.kafka().produce(topicName, entry.getKey(), entry.getValue());
+ }
+ }
+
+ /*
+ * produce messages to the cluster and topic partition less than numPartitions
+ */
+ protected void produceMessages(EmbeddedConnectCluster cluster, String topicName, int numPartitions) {
+ int cnt = 0;
+ for (int r = 0; r < NUM_RECORDS_PER_PARTITION; r++)
+ for (int p = 0; p < numPartitions; p++)
+ cluster.kafka().produce(topicName, p, "key", "value-" + cnt++);
+ }
+
+ /*
+ * given consumer group, topics and expected number of records, make sure the consumer group
+ * offsets are eventually synced to the expected offset numbers
+ */
+ private static <T> void waitForConsumerGroupOffsetSync(EmbeddedConnectCluster connect,
+ Consumer<T, T> consumer, List<String> topics, String consumerGroupId, int numRecords)
+ throws InterruptedException {
+ Admin adminClient = connect.kafka().createAdminClient();
+ List<TopicPartition> tps = new ArrayList<>(NUM_PARTITIONS * topics.size());
+ for (int partitionIndex = 0; partitionIndex < NUM_PARTITIONS; partitionIndex++) {
+ for (String topic : topics) {
+ tps.add(new TopicPartition(topic, partitionIndex));
+ }
+ }
+ long expectedTotalOffsets = numRecords * topics.size();
+
+ waitForCondition(() -> {
+ Map<TopicPartition, OffsetAndMetadata> consumerGroupOffsets =
+ adminClient.listConsumerGroupOffsets(consumerGroupId).partitionsToOffsetAndMetadata().get();
+ long consumerGroupOffsetTotal = consumerGroupOffsets.values().stream()
+ .mapToLong(metadata -> metadata.offset()).sum();
+
+ Map<TopicPartition, Long> offsets = consumer.endOffsets(tps, Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+ long totalOffsets = offsets.values().stream().mapToLong(l -> l).sum();
+
+ // make sure the consumer group offsets are synced to expected number
+ return totalOffsets == expectedTotalOffsets && consumerGroupOffsetTotal > 0;
+ }, OFFSET_SYNC_DURATION_MS, "Consumer group offset sync is not complete in time");
+ }
+
+ /*
+ * make sure the consumer to consume expected number of records
+ */
+ private static <T> void waitForConsumingAllRecords(Consumer<T, T> consumer, int numExpectedRecords)
+ throws InterruptedException {
+ final AtomicInteger totalConsumedRecords = new AtomicInteger(0);
+ waitForCondition(() -> {
+ ConsumerRecords<T, T> records = consumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+ return numExpectedRecords == totalConsumedRecords.addAndGet(records.count());
+ }, RECORD_CONSUME_DURATION_MS, "Consumer cannot consume all records in time");
+ consumer.commitSync();
+ consumer.close();
Review comment:
I find it strange that this method closes the consumer it received.
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationSSLTest.java
##########
@@ -0,0 +1,98 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.common.network.Mode;
+import org.apache.kafka.connect.mirror.MirrorCheckpointConnector;
+import org.apache.kafka.connect.mirror.MirrorHeartbeatConnector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.MirrorSourceConnector;
+import org.apache.kafka.test.IntegrationTest;
+import org.apache.kafka.test.TestSslUtils;
+import org.apache.kafka.test.TestUtils;
+import kafka.server.KafkaConfig$;
+
+import org.junit.experimental.categories.Category;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+import org.junit.Before;
+import org.junit.After;
+import org.junit.Test;
+
+/**
+ * Tests MM2 replication with SSL enabled at backup kafka cluster
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationSSLTest extends MirrorConnectorsIntegrationBaseTest {
+
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationSSLTest.class);
+
+ private static final List<Class> CONNECTOR_LIST =
+ Arrays.asList(MirrorSourceConnector.class, MirrorCheckpointConnector.class, MirrorHeartbeatConnector.class);
+
+ @Before
+ public void setup() throws InterruptedException {
+ try {
+ Map<String, Object> sslConfig = TestSslUtils.createSslConfig(false, true, Mode.SERVER, TestUtils.tempFile(), "testCert");
+ backupBrokerProps.put(KafkaConfig$.MODULE$.ListenersProp(), "SSL://localhost:0");
+ backupBrokerProps.put(KafkaConfig$.MODULE$.InterBrokerListenerNameProp(), "SSL");
+ backupBrokerProps.putAll(sslConfig);
+ } catch (final Exception e) {
+ throw new RuntimeException(e);
Review comment:
But why is this needed here? I don't know what the other test is doing but I don't understand why it's used here
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationTest.java
##########
@@ -0,0 +1,372 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.errors.TimeoutException;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.mirror.MirrorCheckpointConnector;
+import org.apache.kafka.connect.mirror.MirrorClient;
+import org.apache.kafka.connect.mirror.MirrorHeartbeatConnector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.MirrorSourceConnector;
+import org.apache.kafka.connect.mirror.utils.ThreadedConsumer;
+import org.apache.kafka.connect.mirror.utils.ThreadedProducer;
+import org.apache.kafka.test.IntegrationTest;
+import org.junit.Before;
+import org.junit.After;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Collections;
+import java.util.Map;
+import java.util.HashMap;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertNotNull;
+
+/**
+ * Tests MM2 replication and failover/failback logic.
+ *
+ * MM2 is configured with active/active replication between two Kafka clusters. Tests validate that
+ * records sent to either cluster arrive at the other cluster. Then, a consumer group is migrated from
+ * one cluster to the other and back. Tests validate that consumer offsets are translated and replicated
+ * between clusters during this failover and failback.
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationTest extends MirrorConnectorsIntegrationBaseTest {
+
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationTest.class);
+
+ private static final List<Class> CONNECTOR_LIST =
+ Arrays.asList(MirrorSourceConnector.class, MirrorCheckpointConnector.class, MirrorHeartbeatConnector.class);
+
+ @Before
+ public void setup() throws InterruptedException {
Review comment:
Well in `MirrorConnectorsIntegrationSSLTest`, we can override it, but we should put the default implementation in the base class
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationBaseTest.java
##########
@@ -0,0 +1,407 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.CommonClientConfigs;
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.Config;
+import org.apache.kafka.clients.admin.ConfigEntry;
+import org.apache.kafka.clients.admin.DescribeConfigsResult;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.config.ConfigResource;
+import org.apache.kafka.common.config.SslConfigs;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.config.types.Password;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.connector.Connector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.SourceAndTarget;
+import org.apache.kafka.connect.util.clusters.EmbeddedConnectCluster;
+import org.apache.kafka.connect.util.clusters.EmbeddedKafkaCluster;
+import static org.apache.kafka.connect.mirror.TestUtils.expectedRecords;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+import org.apache.kafka.test.IntegrationTest;
+import kafka.server.KafkaConfig$;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import static org.junit.Assert.assertFalse;
+import org.junit.experimental.categories.Category;
+
+/**
+ * Common Test functions for MM2 integration tests
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationBaseTest {
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationBaseTest.class);
+
+ protected static final int NUM_RECORDS_PER_PARTITION = 10;
+ public static final int NUM_PARTITIONS = 10;
+ protected static final int NUM_RECORDS_PRODUCED = NUM_PARTITIONS * NUM_RECORDS_PER_PARTITION;
+ protected static final int RECORD_TRANSFER_DURATION_MS = 30_000;
+ protected static final int CHECKPOINT_DURATION_MS = 20_000;
+ protected static final int RECORD_CONSUME_DURATION_MS = 20_000;
+ protected static final int OFFSET_SYNC_DURATION_MS = 30_000;
+ protected static final int NUM_WORKERS = 3;
+ protected static final int CONSUMER_POLL_TIMEOUT_MS = 500;
+ protected static final int BROKER_RESTART_TIMEOUT_MS = 10_000;
+ protected static final String PRIMARY_CLUSTER_ALIAS = "primary";
+ protected static final String BACKUP_CLUSTER_ALIAS = "backup";
+
+ protected Map<String, String> mm2Props;
+ protected MirrorMakerConfig mm2Config;
+ protected EmbeddedConnectCluster primary;
+ protected EmbeddedConnectCluster backup;
+
+ private final AtomicBoolean exited = new AtomicBoolean(false);
+ private Properties primaryBrokerProps = new Properties();
+ protected Properties backupBrokerProps = new Properties();
+ private Map<String, String> primaryWorkerProps = new HashMap<>();
+ private Map<String, String> backupWorkerProps = new HashMap<>();
+ private Properties sslProps = new Properties();
+
+ private void loadSslPropsFromBrokerConfig() {
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, backupBrokerProps.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG));
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, ((Password) backupBrokerProps.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)).value());
+ sslProps.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL");
+ }
+
+ protected void setSslConfig() {
+ // set SSL config for kafka connect worker
+ backupWorkerProps.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> BACKUP_CLUSTER_ALIAS + "." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ // set SSL config for producer used by source task in MM2
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> BACKUP_CLUSTER_ALIAS + ".producer." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ }
+
+ protected void startClusters() throws InterruptedException {
+ primaryBrokerProps.put("auto.create.topics.enable", "false");
+ backupBrokerProps.put("auto.create.topics.enable", "false");
+
+ mm2Props = basicMM2Config();
+
+ // if backup kafka cluster contains ssl config, enable ssl of kafka connect and mm2
+ final Object listeners = backupBrokerProps.get(KafkaConfig$.MODULE$.ListenersProp());
+ if (listeners != null && listeners.toString().contains("SSL")) {
+ loadSslPropsFromBrokerConfig();
+ setSslConfig();
+ }
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+ primaryWorkerProps = mm2Config.workerConfig(new SourceAndTarget(BACKUP_CLUSTER_ALIAS, PRIMARY_CLUSTER_ALIAS));
+ backupWorkerProps.putAll(mm2Config.workerConfig(new SourceAndTarget(PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS)));
+
+ primary = new EmbeddedConnectCluster.Builder()
+ .name(PRIMARY_CLUSTER_ALIAS + "-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(primaryBrokerProps)
+ .workerProps(primaryWorkerProps)
+ .build();
+
+ backup = new EmbeddedConnectCluster.Builder()
+ .name(BACKUP_CLUSTER_ALIAS + "-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(backupBrokerProps)
+ .workerProps(backupWorkerProps)
+ .build();
+
+ primary.start();
+ primary.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of " + PRIMARY_CLUSTER_ALIAS + "-connect-cluster did not start in time.");
+
+ backup.start();
+ backup.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of " + BACKUP_CLUSTER_ALIAS + "-connect-cluster did not start in time.");
+
+ createTopics();
+
+ dummyConsumption();
+
+ log.info(PRIMARY_CLUSTER_ALIAS + " REST service: {}", primary.endpointForResource("connectors"));
+ log.info(BACKUP_CLUSTER_ALIAS + " REST service: {}", backup.endpointForResource("connectors"));
+ log.info(PRIMARY_CLUSTER_ALIAS + " brokers: {}", primary.kafka().bootstrapServers());
+ log.info(BACKUP_CLUSTER_ALIAS + " brokers: {}", backup.kafka().bootstrapServers());
+
+ // now that the brokers are running, we can finish setting up the Connectors
+ mm2Props.put(PRIMARY_CLUSTER_ALIAS + ".bootstrap.servers", primary.kafka().bootstrapServers());
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + ".bootstrap.servers", backup.kafka().bootstrapServers());
+
+ Exit.setExitProcedure((status, errorCode) -> exited.set(true));
+ }
+
+ public void shutdownClusters() {
+ for (String x : primary.connectors()) {
+ primary.deleteConnector(x);
+ }
+ for (String x : backup.connectors()) {
+ backup.deleteConnector(x);
+ }
+ deleteAllTopics(primary.kafka());
+ deleteAllTopics(backup.kafka());
+ primary.stop();
+ backup.stop();
+ try {
+ assertFalse(exited.get());
+ } finally {
+ Exit.resetExitProcedure();
+ }
+ }
+ /*
+ * launch the connectors on kafka connect cluster and check if they are running
+ */
+ protected static void waitUntilMirrorMakerIsRunning(EmbeddedConnectCluster connectCluster,
+ List<Class<? extends Connector>> connectorClasses, MirrorMakerConfig mm2Config,
+ String primary, String backup) throws InterruptedException {
+ for (int i = 0; i < connectorClasses.size(); i++) {
+ String connector = connectorClasses.get(i).getSimpleName();
+ connectCluster.configureConnector(connector, mm2Config.connectorBaseConfig(
+ new SourceAndTarget(primary, backup), connectorClasses.get(i)));
+ }
+
+ // we wait for the connector and tasks to come up for each connector, so that when we do the
+ // actual testing, we are certain that the tasks are up and running; this will prevent
+ // flaky tests where the connector and tasks didn't start up in time for the tests to be run
+ List<String> connectorNames = connectorClasses.stream().map(x -> x.getSimpleName())
+ .collect(Collectors.toList());
+ for (String connector : connectorNames) {
+ connectCluster.assertions().assertConnectorAndAtLeastNumTasksAreRunning(connector, 1,
+ "Connector " + connector + " tasks did not start in time on cluster: " + connectCluster);
+ }
+ }
+
+ /*
+ * delete all topics of the input kafka cluster
+ */
+ protected static void deleteAllTopics(EmbeddedKafkaCluster cluster) {
+ Admin client = cluster.createAdminClient();
+ try {
+ client.deleteTopics(client.listTopics().names().get());
+ } catch (Throwable e) {
+ // should not run into exception normally. In case of Exception,
+ // simply fail the test and investigate
Review comment:
Just let the Exception flow, that will automatically fail the test
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc commented on pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc commented on pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#issuecomment-719201216
A kind reminder for additional feedback and comments, based on my response above
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc commented on a change in pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc commented on a change in pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#discussion_r510486514
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationSSLTest.java
##########
@@ -0,0 +1,98 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.common.network.Mode;
+import org.apache.kafka.connect.mirror.MirrorCheckpointConnector;
+import org.apache.kafka.connect.mirror.MirrorHeartbeatConnector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.MirrorSourceConnector;
+import org.apache.kafka.test.IntegrationTest;
+import org.apache.kafka.test.TestSslUtils;
+import org.apache.kafka.test.TestUtils;
+import kafka.server.KafkaConfig$;
+
+import org.junit.experimental.categories.Category;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+import org.junit.Before;
+import org.junit.After;
+import org.junit.Test;
+
+/**
+ * Tests MM2 replication with SSL enabled at backup kafka cluster
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationSSLTest extends MirrorConnectorsIntegrationBaseTest {
+
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationSSLTest.class);
+
+ private static final List<Class> CONNECTOR_LIST =
+ Arrays.asList(MirrorSourceConnector.class, MirrorCheckpointConnector.class, MirrorHeartbeatConnector.class);
+
+ @Before
+ public void setup() throws InterruptedException {
+ try {
+ Map<String, Object> sslConfig = TestSslUtils.createSslConfig(false, true, Mode.SERVER, TestUtils.tempFile(), "testCert");
+ backupBrokerProps.put(KafkaConfig$.MODULE$.ListenersProp(), "SSL://localhost:0");
+ backupBrokerProps.put(KafkaConfig$.MODULE$.InterBrokerListenerNameProp(), "SSL");
+ backupBrokerProps.putAll(sslConfig);
+ } catch (final Exception e) {
+ throw new RuntimeException(e);
Review comment:
referred to the example at https://github.com/apache/kafka/blob/trunk/streams/src/test/java/org/apache/kafka/streams/integration/ResetIntegrationWithSslTest.java#L58
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc commented on pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc commented on pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#issuecomment-704353923
@mimaison I think this pr is ready for initial review. Please take your time when available. Thanks
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] mimaison merged pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
mimaison merged pull request #9224:
URL: https://github.com/apache/kafka/pull/9224
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc commented on a change in pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc commented on a change in pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#discussion_r527396144
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationBaseTest.java
##########
@@ -0,0 +1,407 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.CommonClientConfigs;
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.Config;
+import org.apache.kafka.clients.admin.ConfigEntry;
+import org.apache.kafka.clients.admin.DescribeConfigsResult;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.config.ConfigResource;
+import org.apache.kafka.common.config.SslConfigs;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.config.types.Password;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.connector.Connector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.SourceAndTarget;
+import org.apache.kafka.connect.util.clusters.EmbeddedConnectCluster;
+import org.apache.kafka.connect.util.clusters.EmbeddedKafkaCluster;
+import static org.apache.kafka.connect.mirror.TestUtils.expectedRecords;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+import org.apache.kafka.test.IntegrationTest;
+import kafka.server.KafkaConfig$;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import static org.junit.Assert.assertFalse;
+import org.junit.experimental.categories.Category;
+
+/**
+ * Common Test functions for MM2 integration tests
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationBaseTest {
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationBaseTest.class);
+
+ protected static final int NUM_RECORDS_PER_PARTITION = 10;
+ public static final int NUM_PARTITIONS = 10;
+ protected static final int NUM_RECORDS_PRODUCED = NUM_PARTITIONS * NUM_RECORDS_PER_PARTITION;
+ protected static final int RECORD_TRANSFER_DURATION_MS = 30_000;
+ protected static final int CHECKPOINT_DURATION_MS = 20_000;
+ protected static final int RECORD_CONSUME_DURATION_MS = 20_000;
+ protected static final int OFFSET_SYNC_DURATION_MS = 30_000;
+ protected static final int NUM_WORKERS = 3;
+ protected static final int CONSUMER_POLL_TIMEOUT_MS = 500;
+ protected static final int BROKER_RESTART_TIMEOUT_MS = 10_000;
+ protected static final String PRIMARY_CLUSTER_ALIAS = "primary";
+ protected static final String BACKUP_CLUSTER_ALIAS = "backup";
+
+ protected Map<String, String> mm2Props;
+ protected MirrorMakerConfig mm2Config;
+ protected EmbeddedConnectCluster primary;
+ protected EmbeddedConnectCluster backup;
+
+ private final AtomicBoolean exited = new AtomicBoolean(false);
+ private Properties primaryBrokerProps = new Properties();
+ protected Properties backupBrokerProps = new Properties();
+ private Map<String, String> primaryWorkerProps = new HashMap<>();
+ private Map<String, String> backupWorkerProps = new HashMap<>();
+ private Properties sslProps = new Properties();
+
+ private void loadSslPropsFromBrokerConfig() {
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, backupBrokerProps.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG));
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, ((Password) backupBrokerProps.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)).value());
+ sslProps.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL");
+ }
+
+ protected void setSslConfig() {
+ // set SSL config for kafka connect worker
+ backupWorkerProps.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> BACKUP_CLUSTER_ALIAS + "." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ // set SSL config for producer used by source task in MM2
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> BACKUP_CLUSTER_ALIAS + ".producer." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ }
+
+ protected void startClusters() throws InterruptedException {
+ primaryBrokerProps.put("auto.create.topics.enable", "false");
+ backupBrokerProps.put("auto.create.topics.enable", "false");
+
+ mm2Props = basicMM2Config();
+
+ // if backup kafka cluster contains ssl config, enable ssl of kafka connect and mm2
+ final Object listeners = backupBrokerProps.get(KafkaConfig$.MODULE$.ListenersProp());
+ if (listeners != null && listeners.toString().contains("SSL")) {
+ loadSslPropsFromBrokerConfig();
+ setSslConfig();
+ }
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+ primaryWorkerProps = mm2Config.workerConfig(new SourceAndTarget(BACKUP_CLUSTER_ALIAS, PRIMARY_CLUSTER_ALIAS));
+ backupWorkerProps.putAll(mm2Config.workerConfig(new SourceAndTarget(PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS)));
+
+ primary = new EmbeddedConnectCluster.Builder()
+ .name(PRIMARY_CLUSTER_ALIAS + "-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(primaryBrokerProps)
+ .workerProps(primaryWorkerProps)
+ .build();
+
+ backup = new EmbeddedConnectCluster.Builder()
+ .name(BACKUP_CLUSTER_ALIAS + "-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(backupBrokerProps)
+ .workerProps(backupWorkerProps)
+ .build();
+
+ primary.start();
+ primary.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of " + PRIMARY_CLUSTER_ALIAS + "-connect-cluster did not start in time.");
+
+ backup.start();
+ backup.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of " + BACKUP_CLUSTER_ALIAS + "-connect-cluster did not start in time.");
+
+ createTopics();
+
+ dummyConsumption();
+
+ log.info(PRIMARY_CLUSTER_ALIAS + " REST service: {}", primary.endpointForResource("connectors"));
+ log.info(BACKUP_CLUSTER_ALIAS + " REST service: {}", backup.endpointForResource("connectors"));
+ log.info(PRIMARY_CLUSTER_ALIAS + " brokers: {}", primary.kafka().bootstrapServers());
+ log.info(BACKUP_CLUSTER_ALIAS + " brokers: {}", backup.kafka().bootstrapServers());
+
+ // now that the brokers are running, we can finish setting up the Connectors
+ mm2Props.put(PRIMARY_CLUSTER_ALIAS + ".bootstrap.servers", primary.kafka().bootstrapServers());
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + ".bootstrap.servers", backup.kafka().bootstrapServers());
+
+ Exit.setExitProcedure((status, errorCode) -> exited.set(true));
+ }
+
+ public void shutdownClusters() {
+ for (String x : primary.connectors()) {
+ primary.deleteConnector(x);
+ }
+ for (String x : backup.connectors()) {
+ backup.deleteConnector(x);
+ }
+ deleteAllTopics(primary.kafka());
+ deleteAllTopics(backup.kafka());
+ primary.stop();
+ backup.stop();
+ try {
+ assertFalse(exited.get());
+ } finally {
+ Exit.resetExitProcedure();
+ }
+ }
+ /*
+ * launch the connectors on kafka connect cluster and check if they are running
+ */
+ protected static void waitUntilMirrorMakerIsRunning(EmbeddedConnectCluster connectCluster,
+ List<Class<? extends Connector>> connectorClasses, MirrorMakerConfig mm2Config,
+ String primary, String backup) throws InterruptedException {
+ for (int i = 0; i < connectorClasses.size(); i++) {
+ String connector = connectorClasses.get(i).getSimpleName();
+ connectCluster.configureConnector(connector, mm2Config.connectorBaseConfig(
+ new SourceAndTarget(primary, backup), connectorClasses.get(i)));
+ }
+
+ // we wait for the connector and tasks to come up for each connector, so that when we do the
+ // actual testing, we are certain that the tasks are up and running; this will prevent
+ // flaky tests where the connector and tasks didn't start up in time for the tests to be run
+ List<String> connectorNames = connectorClasses.stream().map(x -> x.getSimpleName())
+ .collect(Collectors.toList());
+ for (String connector : connectorNames) {
+ connectCluster.assertions().assertConnectorAndAtLeastNumTasksAreRunning(connector, 1,
+ "Connector " + connector + " tasks did not start in time on cluster: " + connectCluster);
+ }
+ }
+
+ /*
+ * delete all topics of the input kafka cluster
+ */
+ protected static void deleteAllTopics(EmbeddedKafkaCluster cluster) {
+ Admin client = cluster.createAdminClient();
+ try {
+ client.deleteTopics(client.listTopics().names().get());
+ } catch (Throwable e) {
+ // should not run into exception normally. In case of Exception,
+ // simply fail the test and investigate
Review comment:
since this is in Integration test, if we run into `catch`, the test should fail immediately, right? If you have suggestions on what to put here, I am happy to follow :)
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] mimaison commented on a change in pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
mimaison commented on a change in pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#discussion_r527014720
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationBaseTest.java
##########
@@ -0,0 +1,407 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.CommonClientConfigs;
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.Config;
+import org.apache.kafka.clients.admin.ConfigEntry;
+import org.apache.kafka.clients.admin.DescribeConfigsResult;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.config.ConfigResource;
+import org.apache.kafka.common.config.SslConfigs;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.config.types.Password;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.connector.Connector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.SourceAndTarget;
+import org.apache.kafka.connect.util.clusters.EmbeddedConnectCluster;
+import org.apache.kafka.connect.util.clusters.EmbeddedKafkaCluster;
+import static org.apache.kafka.connect.mirror.TestUtils.expectedRecords;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+import org.apache.kafka.test.IntegrationTest;
+import kafka.server.KafkaConfig$;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import static org.junit.Assert.assertFalse;
+import org.junit.experimental.categories.Category;
+
+/**
+ * Common Test functions for MM2 integration tests
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationBaseTest {
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationBaseTest.class);
+
+ protected static final int NUM_RECORDS_PER_PARTITION = 10;
+ public static final int NUM_PARTITIONS = 10;
+ protected static final int NUM_RECORDS_PRODUCED = NUM_PARTITIONS * NUM_RECORDS_PER_PARTITION;
+ protected static final int RECORD_TRANSFER_DURATION_MS = 30_000;
+ protected static final int CHECKPOINT_DURATION_MS = 20_000;
+ protected static final int RECORD_CONSUME_DURATION_MS = 20_000;
+ protected static final int OFFSET_SYNC_DURATION_MS = 30_000;
+ protected static final int NUM_WORKERS = 3;
+ protected static final int CONSUMER_POLL_TIMEOUT_MS = 500;
+ protected static final int BROKER_RESTART_TIMEOUT_MS = 10_000;
+ protected static final String PRIMARY_CLUSTER_ALIAS = "primary";
+ protected static final String BACKUP_CLUSTER_ALIAS = "backup";
+
+ protected Map<String, String> mm2Props;
+ protected MirrorMakerConfig mm2Config;
+ protected EmbeddedConnectCluster primary;
+ protected EmbeddedConnectCluster backup;
+
+ private final AtomicBoolean exited = new AtomicBoolean(false);
+ private Properties primaryBrokerProps = new Properties();
+ protected Properties backupBrokerProps = new Properties();
+ private Map<String, String> primaryWorkerProps = new HashMap<>();
+ private Map<String, String> backupWorkerProps = new HashMap<>();
+ private Properties sslProps = new Properties();
+
+ private void loadSslPropsFromBrokerConfig() {
Review comment:
Why do we have SSL specific methods here? Could we move all the SSL bits into the SSL class?
We have fields for the configurations. So we could set them accordingly (without or without SSL) in each concrete class. Then in the base class, we just use the fields to create the clusters without having to know if it's SSL or not.
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationBaseTest.java
##########
@@ -0,0 +1,407 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.CommonClientConfigs;
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.Config;
+import org.apache.kafka.clients.admin.ConfigEntry;
+import org.apache.kafka.clients.admin.DescribeConfigsResult;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.config.ConfigResource;
+import org.apache.kafka.common.config.SslConfigs;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.config.types.Password;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.connector.Connector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.SourceAndTarget;
+import org.apache.kafka.connect.util.clusters.EmbeddedConnectCluster;
+import org.apache.kafka.connect.util.clusters.EmbeddedKafkaCluster;
+import static org.apache.kafka.connect.mirror.TestUtils.expectedRecords;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+import org.apache.kafka.test.IntegrationTest;
+import kafka.server.KafkaConfig$;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import static org.junit.Assert.assertFalse;
+import org.junit.experimental.categories.Category;
+
+/**
+ * Common Test functions for MM2 integration tests
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationBaseTest {
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationBaseTest.class);
+
+ protected static final int NUM_RECORDS_PER_PARTITION = 10;
+ public static final int NUM_PARTITIONS = 10;
+ protected static final int NUM_RECORDS_PRODUCED = NUM_PARTITIONS * NUM_RECORDS_PER_PARTITION;
+ protected static final int RECORD_TRANSFER_DURATION_MS = 30_000;
+ protected static final int CHECKPOINT_DURATION_MS = 20_000;
+ protected static final int RECORD_CONSUME_DURATION_MS = 20_000;
+ protected static final int OFFSET_SYNC_DURATION_MS = 30_000;
+ protected static final int NUM_WORKERS = 3;
+ protected static final int CONSUMER_POLL_TIMEOUT_MS = 500;
+ protected static final int BROKER_RESTART_TIMEOUT_MS = 10_000;
+ protected static final String PRIMARY_CLUSTER_ALIAS = "primary";
+ protected static final String BACKUP_CLUSTER_ALIAS = "backup";
+
+ protected Map<String, String> mm2Props;
+ protected MirrorMakerConfig mm2Config;
+ protected EmbeddedConnectCluster primary;
+ protected EmbeddedConnectCluster backup;
+
+ private final AtomicBoolean exited = new AtomicBoolean(false);
+ private Properties primaryBrokerProps = new Properties();
+ protected Properties backupBrokerProps = new Properties();
+ private Map<String, String> primaryWorkerProps = new HashMap<>();
+ private Map<String, String> backupWorkerProps = new HashMap<>();
+ private Properties sslProps = new Properties();
+
+ private void loadSslPropsFromBrokerConfig() {
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, backupBrokerProps.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG));
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, ((Password) backupBrokerProps.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)).value());
+ sslProps.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL");
+ }
+
+ protected void setSslConfig() {
+ // set SSL config for kafka connect worker
+ backupWorkerProps.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> BACKUP_CLUSTER_ALIAS + "." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ // set SSL config for producer used by source task in MM2
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> BACKUP_CLUSTER_ALIAS + ".producer." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ }
+
+ protected void startClusters() throws InterruptedException {
+ primaryBrokerProps.put("auto.create.topics.enable", "false");
+ backupBrokerProps.put("auto.create.topics.enable", "false");
+
+ mm2Props = basicMM2Config();
+
+ // if backup kafka cluster contains ssl config, enable ssl of kafka connect and mm2
+ final Object listeners = backupBrokerProps.get(KafkaConfig$.MODULE$.ListenersProp());
+ if (listeners != null && listeners.toString().contains("SSL")) {
+ loadSslPropsFromBrokerConfig();
+ setSslConfig();
+ }
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+ primaryWorkerProps = mm2Config.workerConfig(new SourceAndTarget(BACKUP_CLUSTER_ALIAS, PRIMARY_CLUSTER_ALIAS));
+ backupWorkerProps.putAll(mm2Config.workerConfig(new SourceAndTarget(PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS)));
+
+ primary = new EmbeddedConnectCluster.Builder()
+ .name(PRIMARY_CLUSTER_ALIAS + "-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(primaryBrokerProps)
+ .workerProps(primaryWorkerProps)
+ .build();
+
+ backup = new EmbeddedConnectCluster.Builder()
+ .name(BACKUP_CLUSTER_ALIAS + "-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(backupBrokerProps)
+ .workerProps(backupWorkerProps)
+ .build();
+
+ primary.start();
+ primary.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of " + PRIMARY_CLUSTER_ALIAS + "-connect-cluster did not start in time.");
+
+ backup.start();
+ backup.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of " + BACKUP_CLUSTER_ALIAS + "-connect-cluster did not start in time.");
+
+ createTopics();
+
+ dummyConsumption();
+
+ log.info(PRIMARY_CLUSTER_ALIAS + " REST service: {}", primary.endpointForResource("connectors"));
+ log.info(BACKUP_CLUSTER_ALIAS + " REST service: {}", backup.endpointForResource("connectors"));
+ log.info(PRIMARY_CLUSTER_ALIAS + " brokers: {}", primary.kafka().bootstrapServers());
+ log.info(BACKUP_CLUSTER_ALIAS + " brokers: {}", backup.kafka().bootstrapServers());
+
+ // now that the brokers are running, we can finish setting up the Connectors
+ mm2Props.put(PRIMARY_CLUSTER_ALIAS + ".bootstrap.servers", primary.kafka().bootstrapServers());
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + ".bootstrap.servers", backup.kafka().bootstrapServers());
+
+ Exit.setExitProcedure((status, errorCode) -> exited.set(true));
+ }
+
+ public void shutdownClusters() {
+ for (String x : primary.connectors()) {
+ primary.deleteConnector(x);
+ }
+ for (String x : backup.connectors()) {
+ backup.deleteConnector(x);
+ }
+ deleteAllTopics(primary.kafka());
+ deleteAllTopics(backup.kafka());
+ primary.stop();
+ backup.stop();
+ try {
+ assertFalse(exited.get());
+ } finally {
+ Exit.resetExitProcedure();
+ }
+ }
+ /*
+ * launch the connectors on kafka connect cluster and check if they are running
+ */
+ protected static void waitUntilMirrorMakerIsRunning(EmbeddedConnectCluster connectCluster,
+ List<Class<? extends Connector>> connectorClasses, MirrorMakerConfig mm2Config,
+ String primary, String backup) throws InterruptedException {
+ for (int i = 0; i < connectorClasses.size(); i++) {
+ String connector = connectorClasses.get(i).getSimpleName();
+ connectCluster.configureConnector(connector, mm2Config.connectorBaseConfig(
+ new SourceAndTarget(primary, backup), connectorClasses.get(i)));
+ }
+
+ // we wait for the connector and tasks to come up for each connector, so that when we do the
+ // actual testing, we are certain that the tasks are up and running; this will prevent
+ // flaky tests where the connector and tasks didn't start up in time for the tests to be run
+ List<String> connectorNames = connectorClasses.stream().map(x -> x.getSimpleName())
+ .collect(Collectors.toList());
+ for (String connector : connectorNames) {
+ connectCluster.assertions().assertConnectorAndAtLeastNumTasksAreRunning(connector, 1,
+ "Connector " + connector + " tasks did not start in time on cluster: " + connectCluster);
+ }
+ }
+
+ /*
+ * delete all topics of the input kafka cluster
+ */
+ protected static void deleteAllTopics(EmbeddedKafkaCluster cluster) {
+ Admin client = cluster.createAdminClient();
+ try {
+ client.deleteTopics(client.listTopics().names().get());
+ } catch (Throwable e) {
+ // should not run into exception normally. In case of Exception,
+ // simply fail the test and investigate
Review comment:
By catching `Throwable`, aren't we silencing the error and not immediately failing the test?
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationSSLTest.java
##########
@@ -0,0 +1,89 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.common.network.Mode;
+import org.apache.kafka.connect.connector.Connector;
+import org.apache.kafka.connect.mirror.MirrorCheckpointConnector;
+import org.apache.kafka.connect.mirror.MirrorHeartbeatConnector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.MirrorSourceConnector;
+import org.apache.kafka.test.IntegrationTest;
+import org.apache.kafka.test.TestSslUtils;
+import org.apache.kafka.test.TestUtils;
+import kafka.server.KafkaConfig$;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import org.junit.experimental.categories.Category;
+import org.junit.Before;
+import org.junit.After;
+import org.junit.Test;
+
+/**
+ * Tests MM2 replication with SSL enabled at backup kafka cluster
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationSSLTest extends MirrorConnectorsIntegrationBaseTest {
+
+ private static final List<Class<? extends Connector>> CONNECTOR_LIST =
+ Arrays.asList(MirrorSourceConnector.class, MirrorCheckpointConnector.class, MirrorHeartbeatConnector.class);
+
+ @Before
+ public void setup() throws InterruptedException {
+ try {
+ Map<String, Object> sslConfig = TestSslUtils.createSslConfig(false, true, Mode.SERVER, TestUtils.tempFile(), "testCert");
+ backupBrokerProps.put(KafkaConfig$.MODULE$.ListenersProp(), "SSL://localhost:0");
+ backupBrokerProps.put(KafkaConfig$.MODULE$.InterBrokerListenerNameProp(), "SSL");
+ backupBrokerProps.putAll(sslConfig);
+ } catch (final Exception e) {
+ throw new RuntimeException(e);
+ }
+ startClusters();
+ }
+
+ @After
+ public void close() {
+ shutdownClusters();
+ }
+
+ @Test
+ public void testReplicationSSL() throws InterruptedException {
Review comment:
This test is not specific to SSL, why do we have it ?
Should instead all tests in MirrorConnectorsIntegrationTest go to the base class so we run them both with and without SSL?
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationBaseTest.java
##########
@@ -0,0 +1,407 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.CommonClientConfigs;
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.Config;
+import org.apache.kafka.clients.admin.ConfigEntry;
+import org.apache.kafka.clients.admin.DescribeConfigsResult;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.config.ConfigResource;
+import org.apache.kafka.common.config.SslConfigs;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.config.types.Password;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.connector.Connector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.SourceAndTarget;
+import org.apache.kafka.connect.util.clusters.EmbeddedConnectCluster;
+import org.apache.kafka.connect.util.clusters.EmbeddedKafkaCluster;
+import static org.apache.kafka.connect.mirror.TestUtils.expectedRecords;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+import org.apache.kafka.test.IntegrationTest;
+import kafka.server.KafkaConfig$;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import static org.junit.Assert.assertFalse;
+import org.junit.experimental.categories.Category;
+
+/**
+ * Common Test functions for MM2 integration tests
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationBaseTest {
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationBaseTest.class);
+
+ protected static final int NUM_RECORDS_PER_PARTITION = 10;
+ public static final int NUM_PARTITIONS = 10;
+ protected static final int NUM_RECORDS_PRODUCED = NUM_PARTITIONS * NUM_RECORDS_PER_PARTITION;
+ protected static final int RECORD_TRANSFER_DURATION_MS = 30_000;
+ protected static final int CHECKPOINT_DURATION_MS = 20_000;
+ protected static final int RECORD_CONSUME_DURATION_MS = 20_000;
+ protected static final int OFFSET_SYNC_DURATION_MS = 30_000;
+ protected static final int NUM_WORKERS = 3;
+ protected static final int CONSUMER_POLL_TIMEOUT_MS = 500;
+ protected static final int BROKER_RESTART_TIMEOUT_MS = 10_000;
+ protected static final String PRIMARY_CLUSTER_ALIAS = "primary";
+ protected static final String BACKUP_CLUSTER_ALIAS = "backup";
+
+ protected Map<String, String> mm2Props;
+ protected MirrorMakerConfig mm2Config;
+ protected EmbeddedConnectCluster primary;
+ protected EmbeddedConnectCluster backup;
+
+ private final AtomicBoolean exited = new AtomicBoolean(false);
+ private Properties primaryBrokerProps = new Properties();
+ protected Properties backupBrokerProps = new Properties();
+ private Map<String, String> primaryWorkerProps = new HashMap<>();
+ private Map<String, String> backupWorkerProps = new HashMap<>();
+ private Properties sslProps = new Properties();
+
+ private void loadSslPropsFromBrokerConfig() {
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, backupBrokerProps.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG));
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, ((Password) backupBrokerProps.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)).value());
+ sslProps.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL");
+ }
+
+ protected void setSslConfig() {
+ // set SSL config for kafka connect worker
+ backupWorkerProps.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> BACKUP_CLUSTER_ALIAS + "." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ // set SSL config for producer used by source task in MM2
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> BACKUP_CLUSTER_ALIAS + ".producer." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ }
+
+ protected void startClusters() throws InterruptedException {
+ primaryBrokerProps.put("auto.create.topics.enable", "false");
+ backupBrokerProps.put("auto.create.topics.enable", "false");
+
+ mm2Props = basicMM2Config();
+
+ // if backup kafka cluster contains ssl config, enable ssl of kafka connect and mm2
+ final Object listeners = backupBrokerProps.get(KafkaConfig$.MODULE$.ListenersProp());
+ if (listeners != null && listeners.toString().contains("SSL")) {
+ loadSslPropsFromBrokerConfig();
+ setSslConfig();
+ }
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+ primaryWorkerProps = mm2Config.workerConfig(new SourceAndTarget(BACKUP_CLUSTER_ALIAS, PRIMARY_CLUSTER_ALIAS));
+ backupWorkerProps.putAll(mm2Config.workerConfig(new SourceAndTarget(PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS)));
+
+ primary = new EmbeddedConnectCluster.Builder()
+ .name(PRIMARY_CLUSTER_ALIAS + "-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(primaryBrokerProps)
+ .workerProps(primaryWorkerProps)
+ .build();
+
+ backup = new EmbeddedConnectCluster.Builder()
+ .name(BACKUP_CLUSTER_ALIAS + "-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(backupBrokerProps)
+ .workerProps(backupWorkerProps)
+ .build();
+
+ primary.start();
+ primary.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of " + PRIMARY_CLUSTER_ALIAS + "-connect-cluster did not start in time.");
+
+ backup.start();
+ backup.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of " + BACKUP_CLUSTER_ALIAS + "-connect-cluster did not start in time.");
+
+ createTopics();
+
+ dummyConsumption();
+
+ log.info(PRIMARY_CLUSTER_ALIAS + " REST service: {}", primary.endpointForResource("connectors"));
+ log.info(BACKUP_CLUSTER_ALIAS + " REST service: {}", backup.endpointForResource("connectors"));
+ log.info(PRIMARY_CLUSTER_ALIAS + " brokers: {}", primary.kafka().bootstrapServers());
+ log.info(BACKUP_CLUSTER_ALIAS + " brokers: {}", backup.kafka().bootstrapServers());
+
+ // now that the brokers are running, we can finish setting up the Connectors
+ mm2Props.put(PRIMARY_CLUSTER_ALIAS + ".bootstrap.servers", primary.kafka().bootstrapServers());
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + ".bootstrap.servers", backup.kafka().bootstrapServers());
+
+ Exit.setExitProcedure((status, errorCode) -> exited.set(true));
+ }
+
+ public void shutdownClusters() {
+ for (String x : primary.connectors()) {
+ primary.deleteConnector(x);
+ }
+ for (String x : backup.connectors()) {
+ backup.deleteConnector(x);
+ }
+ deleteAllTopics(primary.kafka());
+ deleteAllTopics(backup.kafka());
+ primary.stop();
+ backup.stop();
+ try {
+ assertFalse(exited.get());
+ } finally {
+ Exit.resetExitProcedure();
+ }
+ }
+ /*
+ * launch the connectors on kafka connect cluster and check if they are running
+ */
+ protected static void waitUntilMirrorMakerIsRunning(EmbeddedConnectCluster connectCluster,
+ List<Class<? extends Connector>> connectorClasses, MirrorMakerConfig mm2Config,
+ String primary, String backup) throws InterruptedException {
+ for (int i = 0; i < connectorClasses.size(); i++) {
+ String connector = connectorClasses.get(i).getSimpleName();
+ connectCluster.configureConnector(connector, mm2Config.connectorBaseConfig(
+ new SourceAndTarget(primary, backup), connectorClasses.get(i)));
+ }
+
+ // we wait for the connector and tasks to come up for each connector, so that when we do the
+ // actual testing, we are certain that the tasks are up and running; this will prevent
+ // flaky tests where the connector and tasks didn't start up in time for the tests to be run
+ List<String> connectorNames = connectorClasses.stream().map(x -> x.getSimpleName())
+ .collect(Collectors.toList());
+ for (String connector : connectorNames) {
+ connectCluster.assertions().assertConnectorAndAtLeastNumTasksAreRunning(connector, 1,
+ "Connector " + connector + " tasks did not start in time on cluster: " + connectCluster);
+ }
+ }
+
+ /*
+ * delete all topics of the input kafka cluster
+ */
+ protected static void deleteAllTopics(EmbeddedKafkaCluster cluster) {
+ Admin client = cluster.createAdminClient();
+ try {
+ client.deleteTopics(client.listTopics().names().get());
+ } catch (Throwable e) {
+ // should not run into exception normally. In case of Exception,
+ // simply fail the test and investigate
+ }
+ }
+
+ /*
+ * retrieve the config value based on the input cluster, topic and config name
+ */
+ protected static String getTopicConfig(EmbeddedKafkaCluster cluster, String topic, String configName) {
+ Admin client = cluster.createAdminClient();
+ Collection<ConfigResource> cr = Collections.singleton(
+ new ConfigResource(ConfigResource.Type.TOPIC, topic));
+ try {
+ DescribeConfigsResult configsResult = client.describeConfigs(cr);
+ Config allConfigs = (Config) configsResult.all().get().values().toArray()[0];
+ Iterator<ConfigEntry> configIterator = allConfigs.entries().iterator();
+ while (configIterator.hasNext()) {
+ ConfigEntry currentConfig = configIterator.next();
+ if (currentConfig.name().equals(configName)) {
+ return currentConfig.value();
+ }
+ }
+ } catch (Throwable e) {
+ // should not run into exception normally. In case of Exception,
+ // simply fail the test and investigate
+ }
+ return null;
+ }
+
+ /*
+ * produce messages to the cluster and topic
+ */
+ protected void produceMessages(EmbeddedConnectCluster cluster, String topicName) {
+ Map<String, String> recordSent = expectedRecords(NUM_RECORDS_PRODUCED);
+ for (Map.Entry<String, String> entry : recordSent.entrySet()) {
+ cluster.kafka().produce(topicName, entry.getKey(), entry.getValue());
+ }
+ }
+
+ /*
+ * produce messages to the cluster and topic partition less than numPartitions
+ */
+ protected void produceMessages(EmbeddedConnectCluster cluster, String topicName, int numPartitions) {
+ int cnt = 0;
+ for (int r = 0; r < NUM_RECORDS_PER_PARTITION; r++)
+ for (int p = 0; p < numPartitions; p++)
+ cluster.kafka().produce(topicName, p, "key", "value-" + cnt++);
+ }
+
+ /*
+ * given consumer group, topics and expected number of records, make sure the consumer group
+ * offsets are eventually synced to the expected offset numbers
+ */
+ protected static <T> void waitForConsumerGroupOffsetSync(EmbeddedConnectCluster connect,
+ Consumer<T, T> consumer, List<String> topics, String consumerGroupId, int numRecords)
+ throws InterruptedException {
+ Admin adminClient = connect.kafka().createAdminClient();
+ List<TopicPartition> tps = new ArrayList<>(NUM_PARTITIONS * topics.size());
+ for (int partitionIndex = 0; partitionIndex < NUM_PARTITIONS; partitionIndex++) {
+ for (String topic : topics) {
+ tps.add(new TopicPartition(topic, partitionIndex));
+ }
+ }
+ long expectedTotalOffsets = numRecords * topics.size();
+
+ waitForCondition(() -> {
+ Map<TopicPartition, OffsetAndMetadata> consumerGroupOffsets =
+ adminClient.listConsumerGroupOffsets(consumerGroupId).partitionsToOffsetAndMetadata().get();
+ long consumerGroupOffsetTotal = consumerGroupOffsets.values().stream()
+ .mapToLong(metadata -> metadata.offset()).sum();
+
+ Map<TopicPartition, Long> offsets = consumer.endOffsets(tps, Duration.ofMillis(500));
+ long totalOffsets = offsets.values().stream().mapToLong(l -> l).sum();
+
+ // make sure the consumer group offsets are synced to expected number
+ return totalOffsets == expectedTotalOffsets && consumerGroupOffsetTotal > 0;
+ }, OFFSET_SYNC_DURATION_MS, "Consumer group offset sync is not complete in time");
+ }
+
+ /*
+ * make sure the consumer to consume expected number of records
+ */
+ protected static <T> void waitForConsumingAllRecords(Consumer<T, T> consumer, int numExpectedRecords)
+ throws InterruptedException {
+ final AtomicInteger totalConsumedRecords = new AtomicInteger(0);
+ waitForCondition(() -> {
+ ConsumerRecords<T, T> records = consumer.poll(Duration.ofMillis(500));
+ return numExpectedRecords == totalConsumedRecords.addAndGet(records.count());
+ }, RECORD_CONSUME_DURATION_MS, "Consumer cannot consume all records in time");
+ consumer.commitSync();
+ consumer.close();
+ }
+
+ /*
+ * MM2 config to use in integration tests
+ */
+ private static Map<String, String> basicMM2Config() {
+ Map<String, String> mm2Props = new HashMap<>();
+ mm2Props.put("clusters", PRIMARY_CLUSTER_ALIAS + ", " + BACKUP_CLUSTER_ALIAS);
+ mm2Props.put("max.tasks", "10");
+ mm2Props.put("topics", "test-topic-.*, primary.test-topic-.*, backup.test-topic-.*");
+ mm2Props.put("groups", "consumer-group-.*");
+ mm2Props.put(PRIMARY_CLUSTER_ALIAS + "->" + BACKUP_CLUSTER_ALIAS + ".enabled", "true");
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + "->" + PRIMARY_CLUSTER_ALIAS + ".enabled", "true");
+ mm2Props.put("sync.topic.acls.enabled", "false");
+ mm2Props.put("emit.checkpoints.interval.seconds", "1");
+ mm2Props.put("emit.heartbeats.interval.seconds", "1");
+ mm2Props.put("refresh.topics.interval.seconds", "1");
+ mm2Props.put("refresh.groups.interval.seconds", "1");
+ mm2Props.put("checkpoints.topic.replication.factor", "1");
+ mm2Props.put("heartbeats.topic.replication.factor", "1");
+ mm2Props.put("offset-syncs.topic.replication.factor", "1");
+ mm2Props.put("config.storage.replication.factor", "1");
+ mm2Props.put("offset.storage.replication.factor", "1");
+ mm2Props.put("status.storage.replication.factor", "1");
+ mm2Props.put("replication.factor", "1");
+
+ return mm2Props;
+ }
+
+ /*
+ * restart kafka broker and make sure it is successful
+ */
+ protected void restartKafkaBroker(EmbeddedKafkaCluster kafkaCluster) throws InterruptedException {
+
+ kafkaCluster.stopOnlyKafka();
+ log.trace("issue kafka stop");
+
+ // wait for the broker to be stopped
+ waitForCondition(() -> {
+ return kafkaCluster.runningBrokers().size() == 0;
+ }, BROKER_RESTART_TIMEOUT_MS, "Failed to stop kafka broker within");
+
+ kafkaCluster.startOnlyKafkaOnSamePorts();
+ log.trace("issue kafka start");
+
+ // wait for the kafka brokers to come back online
+ waitForCondition(() -> {
+ return kafkaCluster.runningBrokers().size() > 0;
+ }, BROKER_RESTART_TIMEOUT_MS, "Failed to start kafka broker within");
+ }
+
+ protected void createTopics() {
+ // to verify topic config will be sync-ed across clusters
+ Map<String, String> topicConfig = new HashMap<>();
+ topicConfig.put(TopicConfig.CLEANUP_POLICY_CONFIG, TopicConfig.CLEANUP_POLICY_COMPACT);
+ // create these topics before starting the connectors so we don't need to wait for discovery
+ primary.kafka().createTopic("test-topic-1", NUM_PARTITIONS, 1, topicConfig);
+ primary.kafka().createTopic("backup.test-topic-1", 1);
+ primary.kafka().createTopic("heartbeats", 1);
+ backup.kafka().createTopic("test-topic-1", NUM_PARTITIONS);
+ backup.kafka().createTopic("primary.test-topic-1", 1);
+ backup.kafka().createTopic("heartbeats", 1);
+ }
+
+ protected KafkaConsumer<String, String> createConsumer(EmbeddedConnectCluster connect, Map<String, Object> consumerProps, String... topics) {
+ Map<String, Object> props = new HashMap<>(consumerProps);
+
+ props.putIfAbsent(ConsumerConfig.GROUP_ID_CONFIG, UUID.randomUUID().toString());
+ props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, connect.kafka().bootstrapServers());
+ props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
+ props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
+ props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
+ props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
+
+ // ssl config
+ if (connect.kafka().sslEnabled()) {
+ props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ }
+ KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
+ consumer.subscribe(Arrays.asList(topics));
+ return consumer;
+ }
+
+ /*
+ * Generate some consumer activity on both clusters to ensure the checkpoint connector always starts promptly
+ */
+ protected void dummyConsumption() throws InterruptedException {
Review comment:
Can we find a better name?
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationBaseTest.java
##########
@@ -0,0 +1,407 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.CommonClientConfigs;
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.Config;
+import org.apache.kafka.clients.admin.ConfigEntry;
+import org.apache.kafka.clients.admin.DescribeConfigsResult;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.config.ConfigResource;
+import org.apache.kafka.common.config.SslConfigs;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.config.types.Password;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.connector.Connector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.SourceAndTarget;
+import org.apache.kafka.connect.util.clusters.EmbeddedConnectCluster;
+import org.apache.kafka.connect.util.clusters.EmbeddedKafkaCluster;
+import static org.apache.kafka.connect.mirror.TestUtils.expectedRecords;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+import org.apache.kafka.test.IntegrationTest;
+import kafka.server.KafkaConfig$;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import static org.junit.Assert.assertFalse;
+import org.junit.experimental.categories.Category;
+
+/**
+ * Common Test functions for MM2 integration tests
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationBaseTest {
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationBaseTest.class);
+
+ protected static final int NUM_RECORDS_PER_PARTITION = 10;
+ public static final int NUM_PARTITIONS = 10;
+ protected static final int NUM_RECORDS_PRODUCED = NUM_PARTITIONS * NUM_RECORDS_PER_PARTITION;
+ protected static final int RECORD_TRANSFER_DURATION_MS = 30_000;
+ protected static final int CHECKPOINT_DURATION_MS = 20_000;
+ protected static final int RECORD_CONSUME_DURATION_MS = 20_000;
+ protected static final int OFFSET_SYNC_DURATION_MS = 30_000;
+ protected static final int NUM_WORKERS = 3;
+ protected static final int CONSUMER_POLL_TIMEOUT_MS = 500;
+ protected static final int BROKER_RESTART_TIMEOUT_MS = 10_000;
+ protected static final String PRIMARY_CLUSTER_ALIAS = "primary";
+ protected static final String BACKUP_CLUSTER_ALIAS = "backup";
+
+ protected Map<String, String> mm2Props;
+ protected MirrorMakerConfig mm2Config;
+ protected EmbeddedConnectCluster primary;
+ protected EmbeddedConnectCluster backup;
+
+ private final AtomicBoolean exited = new AtomicBoolean(false);
+ private Properties primaryBrokerProps = new Properties();
+ protected Properties backupBrokerProps = new Properties();
+ private Map<String, String> primaryWorkerProps = new HashMap<>();
+ private Map<String, String> backupWorkerProps = new HashMap<>();
+ private Properties sslProps = new Properties();
+
+ private void loadSslPropsFromBrokerConfig() {
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, backupBrokerProps.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG));
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, ((Password) backupBrokerProps.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)).value());
+ sslProps.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL");
+ }
+
+ protected void setSslConfig() {
+ // set SSL config for kafka connect worker
+ backupWorkerProps.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> BACKUP_CLUSTER_ALIAS + "." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ // set SSL config for producer used by source task in MM2
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> BACKUP_CLUSTER_ALIAS + ".producer." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ }
+
+ protected void startClusters() throws InterruptedException {
+ primaryBrokerProps.put("auto.create.topics.enable", "false");
+ backupBrokerProps.put("auto.create.topics.enable", "false");
+
+ mm2Props = basicMM2Config();
+
+ // if backup kafka cluster contains ssl config, enable ssl of kafka connect and mm2
+ final Object listeners = backupBrokerProps.get(KafkaConfig$.MODULE$.ListenersProp());
+ if (listeners != null && listeners.toString().contains("SSL")) {
+ loadSslPropsFromBrokerConfig();
+ setSslConfig();
+ }
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+ primaryWorkerProps = mm2Config.workerConfig(new SourceAndTarget(BACKUP_CLUSTER_ALIAS, PRIMARY_CLUSTER_ALIAS));
+ backupWorkerProps.putAll(mm2Config.workerConfig(new SourceAndTarget(PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS)));
+
+ primary = new EmbeddedConnectCluster.Builder()
+ .name(PRIMARY_CLUSTER_ALIAS + "-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(primaryBrokerProps)
+ .workerProps(primaryWorkerProps)
+ .build();
+
+ backup = new EmbeddedConnectCluster.Builder()
+ .name(BACKUP_CLUSTER_ALIAS + "-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(backupBrokerProps)
+ .workerProps(backupWorkerProps)
+ .build();
+
+ primary.start();
+ primary.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of " + PRIMARY_CLUSTER_ALIAS + "-connect-cluster did not start in time.");
+
+ backup.start();
+ backup.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of " + BACKUP_CLUSTER_ALIAS + "-connect-cluster did not start in time.");
+
+ createTopics();
+
+ dummyConsumption();
+
+ log.info(PRIMARY_CLUSTER_ALIAS + " REST service: {}", primary.endpointForResource("connectors"));
+ log.info(BACKUP_CLUSTER_ALIAS + " REST service: {}", backup.endpointForResource("connectors"));
+ log.info(PRIMARY_CLUSTER_ALIAS + " brokers: {}", primary.kafka().bootstrapServers());
+ log.info(BACKUP_CLUSTER_ALIAS + " brokers: {}", backup.kafka().bootstrapServers());
+
+ // now that the brokers are running, we can finish setting up the Connectors
+ mm2Props.put(PRIMARY_CLUSTER_ALIAS + ".bootstrap.servers", primary.kafka().bootstrapServers());
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + ".bootstrap.servers", backup.kafka().bootstrapServers());
+
+ Exit.setExitProcedure((status, errorCode) -> exited.set(true));
+ }
+
+ public void shutdownClusters() {
+ for (String x : primary.connectors()) {
+ primary.deleteConnector(x);
+ }
+ for (String x : backup.connectors()) {
+ backup.deleteConnector(x);
+ }
+ deleteAllTopics(primary.kafka());
+ deleteAllTopics(backup.kafka());
+ primary.stop();
+ backup.stop();
+ try {
+ assertFalse(exited.get());
+ } finally {
+ Exit.resetExitProcedure();
+ }
+ }
+ /*
+ * launch the connectors on kafka connect cluster and check if they are running
+ */
+ protected static void waitUntilMirrorMakerIsRunning(EmbeddedConnectCluster connectCluster,
+ List<Class<? extends Connector>> connectorClasses, MirrorMakerConfig mm2Config,
+ String primary, String backup) throws InterruptedException {
+ for (int i = 0; i < connectorClasses.size(); i++) {
+ String connector = connectorClasses.get(i).getSimpleName();
+ connectCluster.configureConnector(connector, mm2Config.connectorBaseConfig(
+ new SourceAndTarget(primary, backup), connectorClasses.get(i)));
+ }
+
+ // we wait for the connector and tasks to come up for each connector, so that when we do the
+ // actual testing, we are certain that the tasks are up and running; this will prevent
+ // flaky tests where the connector and tasks didn't start up in time for the tests to be run
+ List<String> connectorNames = connectorClasses.stream().map(x -> x.getSimpleName())
+ .collect(Collectors.toList());
+ for (String connector : connectorNames) {
+ connectCluster.assertions().assertConnectorAndAtLeastNumTasksAreRunning(connector, 1,
+ "Connector " + connector + " tasks did not start in time on cluster: " + connectCluster);
+ }
+ }
+
+ /*
+ * delete all topics of the input kafka cluster
+ */
+ protected static void deleteAllTopics(EmbeddedKafkaCluster cluster) {
+ Admin client = cluster.createAdminClient();
+ try {
+ client.deleteTopics(client.listTopics().names().get());
+ } catch (Throwable e) {
+ // should not run into exception normally. In case of Exception,
+ // simply fail the test and investigate
+ }
+ }
+
+ /*
+ * retrieve the config value based on the input cluster, topic and config name
+ */
+ protected static String getTopicConfig(EmbeddedKafkaCluster cluster, String topic, String configName) {
+ Admin client = cluster.createAdminClient();
+ Collection<ConfigResource> cr = Collections.singleton(
+ new ConfigResource(ConfigResource.Type.TOPIC, topic));
+ try {
+ DescribeConfigsResult configsResult = client.describeConfigs(cr);
+ Config allConfigs = (Config) configsResult.all().get().values().toArray()[0];
+ Iterator<ConfigEntry> configIterator = allConfigs.entries().iterator();
+ while (configIterator.hasNext()) {
+ ConfigEntry currentConfig = configIterator.next();
+ if (currentConfig.name().equals(configName)) {
+ return currentConfig.value();
+ }
+ }
+ } catch (Throwable e) {
+ // should not run into exception normally. In case of Exception,
Review comment:
By catching Throwable, aren't we silencing the error and not immediately failing the test?
Also we should not be catching Throwable, if the JVM throws an Error we want it to fail the test and never want to handle it. There're a bunch of them in these files
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationSSLTest.java
##########
@@ -0,0 +1,89 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.common.network.Mode;
+import org.apache.kafka.connect.connector.Connector;
+import org.apache.kafka.connect.mirror.MirrorCheckpointConnector;
+import org.apache.kafka.connect.mirror.MirrorHeartbeatConnector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.MirrorSourceConnector;
+import org.apache.kafka.test.IntegrationTest;
+import org.apache.kafka.test.TestSslUtils;
+import org.apache.kafka.test.TestUtils;
+import kafka.server.KafkaConfig$;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import org.junit.experimental.categories.Category;
+import org.junit.Before;
+import org.junit.After;
+import org.junit.Test;
+
+/**
+ * Tests MM2 replication with SSL enabled at backup kafka cluster
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationSSLTest extends MirrorConnectorsIntegrationBaseTest {
+
+ private static final List<Class<? extends Connector>> CONNECTOR_LIST =
Review comment:
We have this field in both concrete class. Can we move it to the base class instead?
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationSSLTest.java
##########
@@ -0,0 +1,89 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.common.network.Mode;
+import org.apache.kafka.connect.connector.Connector;
+import org.apache.kafka.connect.mirror.MirrorCheckpointConnector;
+import org.apache.kafka.connect.mirror.MirrorHeartbeatConnector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.MirrorSourceConnector;
+import org.apache.kafka.test.IntegrationTest;
+import org.apache.kafka.test.TestSslUtils;
+import org.apache.kafka.test.TestUtils;
+import kafka.server.KafkaConfig$;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import org.junit.experimental.categories.Category;
+import org.junit.Before;
+import org.junit.After;
+import org.junit.Test;
+
+/**
+ * Tests MM2 replication with SSL enabled at backup kafka cluster
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationSSLTest extends MirrorConnectorsIntegrationBaseTest {
+
+ private static final List<Class<? extends Connector>> CONNECTOR_LIST =
+ Arrays.asList(MirrorSourceConnector.class, MirrorCheckpointConnector.class, MirrorHeartbeatConnector.class);
+
+ @Before
+ public void setup() throws InterruptedException {
+ try {
+ Map<String, Object> sslConfig = TestSslUtils.createSslConfig(false, true, Mode.SERVER, TestUtils.tempFile(), "testCert");
+ backupBrokerProps.put(KafkaConfig$.MODULE$.ListenersProp(), "SSL://localhost:0");
Review comment:
Is there a reason we are only enabling SSL in one of the 2 clusters?
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/TestUtils.java
##########
@@ -32,4 +32,15 @@
}
return props;
}
-}
+
+ /*
+ * return records with different but predictable key and value
+ */
+ public static Map<String, String> expectedRecords(int numRecords) {
Review comment:
Can we find a better name?
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationBaseTest.java
##########
@@ -0,0 +1,407 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.CommonClientConfigs;
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.Config;
+import org.apache.kafka.clients.admin.ConfigEntry;
+import org.apache.kafka.clients.admin.DescribeConfigsResult;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.config.ConfigResource;
+import org.apache.kafka.common.config.SslConfigs;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.config.types.Password;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.connector.Connector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.SourceAndTarget;
+import org.apache.kafka.connect.util.clusters.EmbeddedConnectCluster;
+import org.apache.kafka.connect.util.clusters.EmbeddedKafkaCluster;
+import static org.apache.kafka.connect.mirror.TestUtils.expectedRecords;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+import org.apache.kafka.test.IntegrationTest;
+import kafka.server.KafkaConfig$;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import static org.junit.Assert.assertFalse;
+import org.junit.experimental.categories.Category;
+
+/**
+ * Common Test functions for MM2 integration tests
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationBaseTest {
Review comment:
Should this class be `abstract`?
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/TestUtils.java
##########
@@ -32,4 +32,15 @@
}
return props;
}
-}
+
+ /*
+ * return records with different but predictable key and value
+ */
+ public static Map<String, String> expectedRecords(int numRecords) {
+ Map<String, String> expectedRecords = new HashMap<>();
+ for (int i = 0; i < numRecords; i++) {
+ expectedRecords.put("key-" + i, "message-" + i);
+ }
+ return expectedRecords;
+ }
+}
Review comment:
nit: we tend to have a new line at the end of files
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationBaseTest.java
##########
@@ -0,0 +1,407 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.CommonClientConfigs;
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.Config;
+import org.apache.kafka.clients.admin.ConfigEntry;
+import org.apache.kafka.clients.admin.DescribeConfigsResult;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.config.ConfigResource;
+import org.apache.kafka.common.config.SslConfigs;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.config.types.Password;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.connector.Connector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.SourceAndTarget;
+import org.apache.kafka.connect.util.clusters.EmbeddedConnectCluster;
+import org.apache.kafka.connect.util.clusters.EmbeddedKafkaCluster;
+import static org.apache.kafka.connect.mirror.TestUtils.expectedRecords;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+import org.apache.kafka.test.IntegrationTest;
+import kafka.server.KafkaConfig$;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import static org.junit.Assert.assertFalse;
+import org.junit.experimental.categories.Category;
+
+/**
+ * Common Test functions for MM2 integration tests
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationBaseTest {
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationBaseTest.class);
+
+ protected static final int NUM_RECORDS_PER_PARTITION = 10;
+ public static final int NUM_PARTITIONS = 10;
+ protected static final int NUM_RECORDS_PRODUCED = NUM_PARTITIONS * NUM_RECORDS_PER_PARTITION;
+ protected static final int RECORD_TRANSFER_DURATION_MS = 30_000;
+ protected static final int CHECKPOINT_DURATION_MS = 20_000;
+ protected static final int RECORD_CONSUME_DURATION_MS = 20_000;
+ protected static final int OFFSET_SYNC_DURATION_MS = 30_000;
+ protected static final int NUM_WORKERS = 3;
+ protected static final int CONSUMER_POLL_TIMEOUT_MS = 500;
+ protected static final int BROKER_RESTART_TIMEOUT_MS = 10_000;
+ protected static final String PRIMARY_CLUSTER_ALIAS = "primary";
+ protected static final String BACKUP_CLUSTER_ALIAS = "backup";
+
+ protected Map<String, String> mm2Props;
+ protected MirrorMakerConfig mm2Config;
+ protected EmbeddedConnectCluster primary;
+ protected EmbeddedConnectCluster backup;
+
+ private final AtomicBoolean exited = new AtomicBoolean(false);
+ private Properties primaryBrokerProps = new Properties();
+ protected Properties backupBrokerProps = new Properties();
+ private Map<String, String> primaryWorkerProps = new HashMap<>();
+ private Map<String, String> backupWorkerProps = new HashMap<>();
+ private Properties sslProps = new Properties();
+
+ private void loadSslPropsFromBrokerConfig() {
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, backupBrokerProps.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG));
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, ((Password) backupBrokerProps.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)).value());
+ sslProps.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL");
+ }
+
+ protected void setSslConfig() {
+ // set SSL config for kafka connect worker
+ backupWorkerProps.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> BACKUP_CLUSTER_ALIAS + "." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ // set SSL config for producer used by source task in MM2
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> BACKUP_CLUSTER_ALIAS + ".producer." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ }
+
+ protected void startClusters() throws InterruptedException {
+ primaryBrokerProps.put("auto.create.topics.enable", "false");
+ backupBrokerProps.put("auto.create.topics.enable", "false");
+
+ mm2Props = basicMM2Config();
+
+ // if backup kafka cluster contains ssl config, enable ssl of kafka connect and mm2
+ final Object listeners = backupBrokerProps.get(KafkaConfig$.MODULE$.ListenersProp());
+ if (listeners != null && listeners.toString().contains("SSL")) {
+ loadSslPropsFromBrokerConfig();
+ setSslConfig();
+ }
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+ primaryWorkerProps = mm2Config.workerConfig(new SourceAndTarget(BACKUP_CLUSTER_ALIAS, PRIMARY_CLUSTER_ALIAS));
+ backupWorkerProps.putAll(mm2Config.workerConfig(new SourceAndTarget(PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS)));
+
+ primary = new EmbeddedConnectCluster.Builder()
+ .name(PRIMARY_CLUSTER_ALIAS + "-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(primaryBrokerProps)
+ .workerProps(primaryWorkerProps)
+ .build();
+
+ backup = new EmbeddedConnectCluster.Builder()
+ .name(BACKUP_CLUSTER_ALIAS + "-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(backupBrokerProps)
+ .workerProps(backupWorkerProps)
+ .build();
+
+ primary.start();
+ primary.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of " + PRIMARY_CLUSTER_ALIAS + "-connect-cluster did not start in time.");
+
+ backup.start();
+ backup.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of " + BACKUP_CLUSTER_ALIAS + "-connect-cluster did not start in time.");
+
+ createTopics();
+
+ dummyConsumption();
+
+ log.info(PRIMARY_CLUSTER_ALIAS + " REST service: {}", primary.endpointForResource("connectors"));
+ log.info(BACKUP_CLUSTER_ALIAS + " REST service: {}", backup.endpointForResource("connectors"));
+ log.info(PRIMARY_CLUSTER_ALIAS + " brokers: {}", primary.kafka().bootstrapServers());
+ log.info(BACKUP_CLUSTER_ALIAS + " brokers: {}", backup.kafka().bootstrapServers());
+
+ // now that the brokers are running, we can finish setting up the Connectors
+ mm2Props.put(PRIMARY_CLUSTER_ALIAS + ".bootstrap.servers", primary.kafka().bootstrapServers());
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + ".bootstrap.servers", backup.kafka().bootstrapServers());
+
+ Exit.setExitProcedure((status, errorCode) -> exited.set(true));
+ }
+
+ public void shutdownClusters() {
+ for (String x : primary.connectors()) {
+ primary.deleteConnector(x);
+ }
+ for (String x : backup.connectors()) {
+ backup.deleteConnector(x);
+ }
+ deleteAllTopics(primary.kafka());
+ deleteAllTopics(backup.kafka());
+ primary.stop();
+ backup.stop();
+ try {
+ assertFalse(exited.get());
+ } finally {
+ Exit.resetExitProcedure();
+ }
+ }
+ /*
+ * launch the connectors on kafka connect cluster and check if they are running
+ */
+ protected static void waitUntilMirrorMakerIsRunning(EmbeddedConnectCluster connectCluster,
+ List<Class<? extends Connector>> connectorClasses, MirrorMakerConfig mm2Config,
+ String primary, String backup) throws InterruptedException {
+ for (int i = 0; i < connectorClasses.size(); i++) {
+ String connector = connectorClasses.get(i).getSimpleName();
+ connectCluster.configureConnector(connector, mm2Config.connectorBaseConfig(
+ new SourceAndTarget(primary, backup), connectorClasses.get(i)));
+ }
+
+ // we wait for the connector and tasks to come up for each connector, so that when we do the
+ // actual testing, we are certain that the tasks are up and running; this will prevent
+ // flaky tests where the connector and tasks didn't start up in time for the tests to be run
+ List<String> connectorNames = connectorClasses.stream().map(x -> x.getSimpleName())
+ .collect(Collectors.toList());
+ for (String connector : connectorNames) {
+ connectCluster.assertions().assertConnectorAndAtLeastNumTasksAreRunning(connector, 1,
+ "Connector " + connector + " tasks did not start in time on cluster: " + connectCluster);
+ }
+ }
+
+ /*
+ * delete all topics of the input kafka cluster
+ */
+ protected static void deleteAllTopics(EmbeddedKafkaCluster cluster) {
+ Admin client = cluster.createAdminClient();
+ try {
+ client.deleteTopics(client.listTopics().names().get());
+ } catch (Throwable e) {
+ // should not run into exception normally. In case of Exception,
+ // simply fail the test and investigate
+ }
+ }
+
+ /*
+ * retrieve the config value based on the input cluster, topic and config name
+ */
+ protected static String getTopicConfig(EmbeddedKafkaCluster cluster, String topic, String configName) {
+ Admin client = cluster.createAdminClient();
+ Collection<ConfigResource> cr = Collections.singleton(
+ new ConfigResource(ConfigResource.Type.TOPIC, topic));
+ try {
+ DescribeConfigsResult configsResult = client.describeConfigs(cr);
+ Config allConfigs = (Config) configsResult.all().get().values().toArray()[0];
+ Iterator<ConfigEntry> configIterator = allConfigs.entries().iterator();
+ while (configIterator.hasNext()) {
+ ConfigEntry currentConfig = configIterator.next();
+ if (currentConfig.name().equals(configName)) {
+ return currentConfig.value();
+ }
+ }
+ } catch (Throwable e) {
+ // should not run into exception normally. In case of Exception,
+ // simply fail the test and investigate
+ }
+ return null;
+ }
+
+ /*
+ * produce messages to the cluster and topic
+ */
+ protected void produceMessages(EmbeddedConnectCluster cluster, String topicName) {
+ Map<String, String> recordSent = expectedRecords(NUM_RECORDS_PRODUCED);
+ for (Map.Entry<String, String> entry : recordSent.entrySet()) {
+ cluster.kafka().produce(topicName, entry.getKey(), entry.getValue());
+ }
+ }
+
+ /*
+ * produce messages to the cluster and topic partition less than numPartitions
+ */
+ protected void produceMessages(EmbeddedConnectCluster cluster, String topicName, int numPartitions) {
+ int cnt = 0;
+ for (int r = 0; r < NUM_RECORDS_PER_PARTITION; r++)
+ for (int p = 0; p < numPartitions; p++)
+ cluster.kafka().produce(topicName, p, "key", "value-" + cnt++);
+ }
+
+ /*
+ * given consumer group, topics and expected number of records, make sure the consumer group
+ * offsets are eventually synced to the expected offset numbers
+ */
+ protected static <T> void waitForConsumerGroupOffsetSync(EmbeddedConnectCluster connect,
+ Consumer<T, T> consumer, List<String> topics, String consumerGroupId, int numRecords)
+ throws InterruptedException {
+ Admin adminClient = connect.kafka().createAdminClient();
+ List<TopicPartition> tps = new ArrayList<>(NUM_PARTITIONS * topics.size());
+ for (int partitionIndex = 0; partitionIndex < NUM_PARTITIONS; partitionIndex++) {
+ for (String topic : topics) {
+ tps.add(new TopicPartition(topic, partitionIndex));
+ }
+ }
+ long expectedTotalOffsets = numRecords * topics.size();
+
+ waitForCondition(() -> {
+ Map<TopicPartition, OffsetAndMetadata> consumerGroupOffsets =
+ adminClient.listConsumerGroupOffsets(consumerGroupId).partitionsToOffsetAndMetadata().get();
+ long consumerGroupOffsetTotal = consumerGroupOffsets.values().stream()
+ .mapToLong(metadata -> metadata.offset()).sum();
+
+ Map<TopicPartition, Long> offsets = consumer.endOffsets(tps, Duration.ofMillis(500));
+ long totalOffsets = offsets.values().stream().mapToLong(l -> l).sum();
+
+ // make sure the consumer group offsets are synced to expected number
+ return totalOffsets == expectedTotalOffsets && consumerGroupOffsetTotal > 0;
+ }, OFFSET_SYNC_DURATION_MS, "Consumer group offset sync is not complete in time");
+ }
+
+ /*
+ * make sure the consumer to consume expected number of records
+ */
+ protected static <T> void waitForConsumingAllRecords(Consumer<T, T> consumer, int numExpectedRecords)
+ throws InterruptedException {
+ final AtomicInteger totalConsumedRecords = new AtomicInteger(0);
+ waitForCondition(() -> {
+ ConsumerRecords<T, T> records = consumer.poll(Duration.ofMillis(500));
+ return numExpectedRecords == totalConsumedRecords.addAndGet(records.count());
+ }, RECORD_CONSUME_DURATION_MS, "Consumer cannot consume all records in time");
+ consumer.commitSync();
+ consumer.close();
+ }
+
+ /*
+ * MM2 config to use in integration tests
+ */
+ private static Map<String, String> basicMM2Config() {
+ Map<String, String> mm2Props = new HashMap<>();
+ mm2Props.put("clusters", PRIMARY_CLUSTER_ALIAS + ", " + BACKUP_CLUSTER_ALIAS);
+ mm2Props.put("max.tasks", "10");
+ mm2Props.put("topics", "test-topic-.*, primary.test-topic-.*, backup.test-topic-.*");
+ mm2Props.put("groups", "consumer-group-.*");
+ mm2Props.put(PRIMARY_CLUSTER_ALIAS + "->" + BACKUP_CLUSTER_ALIAS + ".enabled", "true");
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + "->" + PRIMARY_CLUSTER_ALIAS + ".enabled", "true");
+ mm2Props.put("sync.topic.acls.enabled", "false");
+ mm2Props.put("emit.checkpoints.interval.seconds", "1");
+ mm2Props.put("emit.heartbeats.interval.seconds", "1");
+ mm2Props.put("refresh.topics.interval.seconds", "1");
+ mm2Props.put("refresh.groups.interval.seconds", "1");
+ mm2Props.put("checkpoints.topic.replication.factor", "1");
+ mm2Props.put("heartbeats.topic.replication.factor", "1");
+ mm2Props.put("offset-syncs.topic.replication.factor", "1");
+ mm2Props.put("config.storage.replication.factor", "1");
+ mm2Props.put("offset.storage.replication.factor", "1");
+ mm2Props.put("status.storage.replication.factor", "1");
+ mm2Props.put("replication.factor", "1");
+
+ return mm2Props;
+ }
+
+ /*
+ * restart kafka broker and make sure it is successful
+ */
+ protected void restartKafkaBroker(EmbeddedKafkaCluster kafkaCluster) throws InterruptedException {
+
+ kafkaCluster.stopOnlyKafka();
+ log.trace("issue kafka stop");
+
+ // wait for the broker to be stopped
+ waitForCondition(() -> {
+ return kafkaCluster.runningBrokers().size() == 0;
+ }, BROKER_RESTART_TIMEOUT_MS, "Failed to stop kafka broker within");
+
+ kafkaCluster.startOnlyKafkaOnSamePorts();
+ log.trace("issue kafka start");
+
+ // wait for the kafka brokers to come back online
+ waitForCondition(() -> {
+ return kafkaCluster.runningBrokers().size() > 0;
+ }, BROKER_RESTART_TIMEOUT_MS, "Failed to start kafka broker within");
+ }
+
+ protected void createTopics() {
+ // to verify topic config will be sync-ed across clusters
+ Map<String, String> topicConfig = new HashMap<>();
Review comment:
We can use `Collections.singletonMap()`
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationBaseTest.java
##########
@@ -0,0 +1,407 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.CommonClientConfigs;
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.Config;
+import org.apache.kafka.clients.admin.ConfigEntry;
+import org.apache.kafka.clients.admin.DescribeConfigsResult;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.config.ConfigResource;
+import org.apache.kafka.common.config.SslConfigs;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.config.types.Password;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.connector.Connector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.SourceAndTarget;
+import org.apache.kafka.connect.util.clusters.EmbeddedConnectCluster;
+import org.apache.kafka.connect.util.clusters.EmbeddedKafkaCluster;
+import static org.apache.kafka.connect.mirror.TestUtils.expectedRecords;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+import org.apache.kafka.test.IntegrationTest;
+import kafka.server.KafkaConfig$;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import static org.junit.Assert.assertFalse;
+import org.junit.experimental.categories.Category;
+
+/**
+ * Common Test functions for MM2 integration tests
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationBaseTest {
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationBaseTest.class);
+
+ protected static final int NUM_RECORDS_PER_PARTITION = 10;
+ public static final int NUM_PARTITIONS = 10;
+ protected static final int NUM_RECORDS_PRODUCED = NUM_PARTITIONS * NUM_RECORDS_PER_PARTITION;
+ protected static final int RECORD_TRANSFER_DURATION_MS = 30_000;
+ protected static final int CHECKPOINT_DURATION_MS = 20_000;
+ protected static final int RECORD_CONSUME_DURATION_MS = 20_000;
+ protected static final int OFFSET_SYNC_DURATION_MS = 30_000;
+ protected static final int NUM_WORKERS = 3;
+ protected static final int CONSUMER_POLL_TIMEOUT_MS = 500;
+ protected static final int BROKER_RESTART_TIMEOUT_MS = 10_000;
+ protected static final String PRIMARY_CLUSTER_ALIAS = "primary";
+ protected static final String BACKUP_CLUSTER_ALIAS = "backup";
+
+ protected Map<String, String> mm2Props;
+ protected MirrorMakerConfig mm2Config;
+ protected EmbeddedConnectCluster primary;
+ protected EmbeddedConnectCluster backup;
+
+ private final AtomicBoolean exited = new AtomicBoolean(false);
+ private Properties primaryBrokerProps = new Properties();
+ protected Properties backupBrokerProps = new Properties();
+ private Map<String, String> primaryWorkerProps = new HashMap<>();
+ private Map<String, String> backupWorkerProps = new HashMap<>();
+ private Properties sslProps = new Properties();
+
+ private void loadSslPropsFromBrokerConfig() {
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, backupBrokerProps.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG));
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, ((Password) backupBrokerProps.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)).value());
+ sslProps.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL");
+ }
+
+ protected void setSslConfig() {
+ // set SSL config for kafka connect worker
+ backupWorkerProps.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> BACKUP_CLUSTER_ALIAS + "." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ // set SSL config for producer used by source task in MM2
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> BACKUP_CLUSTER_ALIAS + ".producer." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ }
+
+ protected void startClusters() throws InterruptedException {
+ primaryBrokerProps.put("auto.create.topics.enable", "false");
+ backupBrokerProps.put("auto.create.topics.enable", "false");
+
+ mm2Props = basicMM2Config();
+
+ // if backup kafka cluster contains ssl config, enable ssl of kafka connect and mm2
+ final Object listeners = backupBrokerProps.get(KafkaConfig$.MODULE$.ListenersProp());
+ if (listeners != null && listeners.toString().contains("SSL")) {
+ loadSslPropsFromBrokerConfig();
+ setSslConfig();
+ }
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+ primaryWorkerProps = mm2Config.workerConfig(new SourceAndTarget(BACKUP_CLUSTER_ALIAS, PRIMARY_CLUSTER_ALIAS));
+ backupWorkerProps.putAll(mm2Config.workerConfig(new SourceAndTarget(PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS)));
+
+ primary = new EmbeddedConnectCluster.Builder()
+ .name(PRIMARY_CLUSTER_ALIAS + "-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(primaryBrokerProps)
+ .workerProps(primaryWorkerProps)
+ .build();
+
+ backup = new EmbeddedConnectCluster.Builder()
+ .name(BACKUP_CLUSTER_ALIAS + "-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(backupBrokerProps)
+ .workerProps(backupWorkerProps)
+ .build();
+
+ primary.start();
+ primary.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of " + PRIMARY_CLUSTER_ALIAS + "-connect-cluster did not start in time.");
+
+ backup.start();
+ backup.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of " + BACKUP_CLUSTER_ALIAS + "-connect-cluster did not start in time.");
+
+ createTopics();
+
+ dummyConsumption();
+
+ log.info(PRIMARY_CLUSTER_ALIAS + " REST service: {}", primary.endpointForResource("connectors"));
+ log.info(BACKUP_CLUSTER_ALIAS + " REST service: {}", backup.endpointForResource("connectors"));
+ log.info(PRIMARY_CLUSTER_ALIAS + " brokers: {}", primary.kafka().bootstrapServers());
+ log.info(BACKUP_CLUSTER_ALIAS + " brokers: {}", backup.kafka().bootstrapServers());
+
+ // now that the brokers are running, we can finish setting up the Connectors
+ mm2Props.put(PRIMARY_CLUSTER_ALIAS + ".bootstrap.servers", primary.kafka().bootstrapServers());
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + ".bootstrap.servers", backup.kafka().bootstrapServers());
+
+ Exit.setExitProcedure((status, errorCode) -> exited.set(true));
+ }
+
+ public void shutdownClusters() {
+ for (String x : primary.connectors()) {
+ primary.deleteConnector(x);
+ }
+ for (String x : backup.connectors()) {
+ backup.deleteConnector(x);
+ }
+ deleteAllTopics(primary.kafka());
+ deleteAllTopics(backup.kafka());
+ primary.stop();
+ backup.stop();
+ try {
+ assertFalse(exited.get());
+ } finally {
+ Exit.resetExitProcedure();
+ }
+ }
+ /*
+ * launch the connectors on kafka connect cluster and check if they are running
+ */
+ protected static void waitUntilMirrorMakerIsRunning(EmbeddedConnectCluster connectCluster,
+ List<Class<? extends Connector>> connectorClasses, MirrorMakerConfig mm2Config,
+ String primary, String backup) throws InterruptedException {
+ for (int i = 0; i < connectorClasses.size(); i++) {
+ String connector = connectorClasses.get(i).getSimpleName();
+ connectCluster.configureConnector(connector, mm2Config.connectorBaseConfig(
+ new SourceAndTarget(primary, backup), connectorClasses.get(i)));
+ }
+
+ // we wait for the connector and tasks to come up for each connector, so that when we do the
+ // actual testing, we are certain that the tasks are up and running; this will prevent
+ // flaky tests where the connector and tasks didn't start up in time for the tests to be run
+ List<String> connectorNames = connectorClasses.stream().map(x -> x.getSimpleName())
+ .collect(Collectors.toList());
+ for (String connector : connectorNames) {
+ connectCluster.assertions().assertConnectorAndAtLeastNumTasksAreRunning(connector, 1,
+ "Connector " + connector + " tasks did not start in time on cluster: " + connectCluster);
+ }
+ }
+
+ /*
+ * delete all topics of the input kafka cluster
+ */
+ protected static void deleteAllTopics(EmbeddedKafkaCluster cluster) {
+ Admin client = cluster.createAdminClient();
+ try {
+ client.deleteTopics(client.listTopics().names().get());
+ } catch (Throwable e) {
+ // should not run into exception normally. In case of Exception,
+ // simply fail the test and investigate
+ }
+ }
+
+ /*
+ * retrieve the config value based on the input cluster, topic and config name
+ */
+ protected static String getTopicConfig(EmbeddedKafkaCluster cluster, String topic, String configName) {
+ Admin client = cluster.createAdminClient();
+ Collection<ConfigResource> cr = Collections.singleton(
+ new ConfigResource(ConfigResource.Type.TOPIC, topic));
+ try {
+ DescribeConfigsResult configsResult = client.describeConfigs(cr);
+ Config allConfigs = (Config) configsResult.all().get().values().toArray()[0];
+ Iterator<ConfigEntry> configIterator = allConfigs.entries().iterator();
+ while (configIterator.hasNext()) {
+ ConfigEntry currentConfig = configIterator.next();
+ if (currentConfig.name().equals(configName)) {
+ return currentConfig.value();
+ }
+ }
+ } catch (Throwable e) {
+ // should not run into exception normally. In case of Exception,
+ // simply fail the test and investigate
+ }
+ return null;
+ }
+
+ /*
+ * produce messages to the cluster and topic
+ */
+ protected void produceMessages(EmbeddedConnectCluster cluster, String topicName) {
+ Map<String, String> recordSent = expectedRecords(NUM_RECORDS_PRODUCED);
+ for (Map.Entry<String, String> entry : recordSent.entrySet()) {
+ cluster.kafka().produce(topicName, entry.getKey(), entry.getValue());
+ }
+ }
+
+ /*
+ * produce messages to the cluster and topic partition less than numPartitions
+ */
+ protected void produceMessages(EmbeddedConnectCluster cluster, String topicName, int numPartitions) {
+ int cnt = 0;
+ for (int r = 0; r < NUM_RECORDS_PER_PARTITION; r++)
+ for (int p = 0; p < numPartitions; p++)
+ cluster.kafka().produce(topicName, p, "key", "value-" + cnt++);
+ }
+
+ /*
+ * given consumer group, topics and expected number of records, make sure the consumer group
+ * offsets are eventually synced to the expected offset numbers
+ */
+ protected static <T> void waitForConsumerGroupOffsetSync(EmbeddedConnectCluster connect,
+ Consumer<T, T> consumer, List<String> topics, String consumerGroupId, int numRecords)
+ throws InterruptedException {
+ Admin adminClient = connect.kafka().createAdminClient();
+ List<TopicPartition> tps = new ArrayList<>(NUM_PARTITIONS * topics.size());
+ for (int partitionIndex = 0; partitionIndex < NUM_PARTITIONS; partitionIndex++) {
+ for (String topic : topics) {
+ tps.add(new TopicPartition(topic, partitionIndex));
+ }
+ }
+ long expectedTotalOffsets = numRecords * topics.size();
+
+ waitForCondition(() -> {
+ Map<TopicPartition, OffsetAndMetadata> consumerGroupOffsets =
+ adminClient.listConsumerGroupOffsets(consumerGroupId).partitionsToOffsetAndMetadata().get();
+ long consumerGroupOffsetTotal = consumerGroupOffsets.values().stream()
+ .mapToLong(metadata -> metadata.offset()).sum();
+
+ Map<TopicPartition, Long> offsets = consumer.endOffsets(tps, Duration.ofMillis(500));
+ long totalOffsets = offsets.values().stream().mapToLong(l -> l).sum();
+
+ // make sure the consumer group offsets are synced to expected number
+ return totalOffsets == expectedTotalOffsets && consumerGroupOffsetTotal > 0;
+ }, OFFSET_SYNC_DURATION_MS, "Consumer group offset sync is not complete in time");
+ }
+
+ /*
+ * make sure the consumer to consume expected number of records
+ */
+ protected static <T> void waitForConsumingAllRecords(Consumer<T, T> consumer, int numExpectedRecords)
+ throws InterruptedException {
+ final AtomicInteger totalConsumedRecords = new AtomicInteger(0);
+ waitForCondition(() -> {
+ ConsumerRecords<T, T> records = consumer.poll(Duration.ofMillis(500));
+ return numExpectedRecords == totalConsumedRecords.addAndGet(records.count());
+ }, RECORD_CONSUME_DURATION_MS, "Consumer cannot consume all records in time");
+ consumer.commitSync();
+ consumer.close();
+ }
+
+ /*
+ * MM2 config to use in integration tests
+ */
+ private static Map<String, String> basicMM2Config() {
+ Map<String, String> mm2Props = new HashMap<>();
+ mm2Props.put("clusters", PRIMARY_CLUSTER_ALIAS + ", " + BACKUP_CLUSTER_ALIAS);
+ mm2Props.put("max.tasks", "10");
+ mm2Props.put("topics", "test-topic-.*, primary.test-topic-.*, backup.test-topic-.*");
+ mm2Props.put("groups", "consumer-group-.*");
+ mm2Props.put(PRIMARY_CLUSTER_ALIAS + "->" + BACKUP_CLUSTER_ALIAS + ".enabled", "true");
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + "->" + PRIMARY_CLUSTER_ALIAS + ".enabled", "true");
+ mm2Props.put("sync.topic.acls.enabled", "false");
+ mm2Props.put("emit.checkpoints.interval.seconds", "1");
+ mm2Props.put("emit.heartbeats.interval.seconds", "1");
+ mm2Props.put("refresh.topics.interval.seconds", "1");
+ mm2Props.put("refresh.groups.interval.seconds", "1");
+ mm2Props.put("checkpoints.topic.replication.factor", "1");
+ mm2Props.put("heartbeats.topic.replication.factor", "1");
+ mm2Props.put("offset-syncs.topic.replication.factor", "1");
+ mm2Props.put("config.storage.replication.factor", "1");
+ mm2Props.put("offset.storage.replication.factor", "1");
+ mm2Props.put("status.storage.replication.factor", "1");
+ mm2Props.put("replication.factor", "1");
+
+ return mm2Props;
+ }
+
+ /*
+ * restart kafka broker and make sure it is successful
+ */
+ protected void restartKafkaBroker(EmbeddedKafkaCluster kafkaCluster) throws InterruptedException {
+
+ kafkaCluster.stopOnlyKafka();
+ log.trace("issue kafka stop");
+
+ // wait for the broker to be stopped
+ waitForCondition(() -> {
+ return kafkaCluster.runningBrokers().size() == 0;
+ }, BROKER_RESTART_TIMEOUT_MS, "Failed to stop kafka broker within");
+
+ kafkaCluster.startOnlyKafkaOnSamePorts();
+ log.trace("issue kafka start");
+
+ // wait for the kafka brokers to come back online
+ waitForCondition(() -> {
+ return kafkaCluster.runningBrokers().size() > 0;
+ }, BROKER_RESTART_TIMEOUT_MS, "Failed to start kafka broker within");
+ }
+
+ protected void createTopics() {
+ // to verify topic config will be sync-ed across clusters
+ Map<String, String> topicConfig = new HashMap<>();
+ topicConfig.put(TopicConfig.CLEANUP_POLICY_CONFIG, TopicConfig.CLEANUP_POLICY_COMPACT);
+ // create these topics before starting the connectors so we don't need to wait for discovery
+ primary.kafka().createTopic("test-topic-1", NUM_PARTITIONS, 1, topicConfig);
+ primary.kafka().createTopic("backup.test-topic-1", 1);
+ primary.kafka().createTopic("heartbeats", 1);
+ backup.kafka().createTopic("test-topic-1", NUM_PARTITIONS);
+ backup.kafka().createTopic("primary.test-topic-1", 1);
+ backup.kafka().createTopic("heartbeats", 1);
+ }
+
+ protected KafkaConsumer<String, String> createConsumer(EmbeddedConnectCluster connect, Map<String, Object> consumerProps, String... topics) {
+ Map<String, Object> props = new HashMap<>(consumerProps);
+
+ props.putIfAbsent(ConsumerConfig.GROUP_ID_CONFIG, UUID.randomUUID().toString());
+ props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, connect.kafka().bootstrapServers());
+ props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
+ props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
+ props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
Review comment:
We can use `StringDeserializer.class.getName()`
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationTest.java
##########
@@ -0,0 +1,370 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.errors.TimeoutException;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.connector.Connector;
+import org.apache.kafka.connect.mirror.MirrorCheckpointConnector;
+import org.apache.kafka.connect.mirror.MirrorClient;
+import org.apache.kafka.connect.mirror.MirrorHeartbeatConnector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.MirrorSourceConnector;
+import org.apache.kafka.connect.mirror.utils.ThreadedConsumer;
+import org.apache.kafka.connect.mirror.utils.ThreadedProducer;
+
+import org.junit.Before;
+import org.junit.After;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertNotNull;
+
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Collections;
+import java.util.Map;
+import java.util.HashMap;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+import org.apache.kafka.test.IntegrationTest;
+
+/**
+ * Tests MM2 replication and failover/failback logic.
+ *
+ * MM2 is configured with active/active replication between two Kafka clusters. Tests validate that
+ * records sent to either cluster arrive at the other cluster. Then, a consumer group is migrated from
+ * one cluster to the other and back. Tests validate that consumer offsets are translated and replicated
+ * between clusters during this failover and failback.
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationTest extends MirrorConnectorsIntegrationBaseTest {
+
+ private static final List<Class<? extends Connector>> CONNECTOR_LIST =
+ Arrays.asList(MirrorSourceConnector.class, MirrorCheckpointConnector.class, MirrorHeartbeatConnector.class);
+
+ @Before
+ public void setup() throws InterruptedException {
+ startClusters();
+ }
+
+ @After
+ public void close() {
+ shutdownClusters();
+ }
+
+ @Test
+ public void testReplication() throws InterruptedException {
+ produceMessages(primary, "test-topic-1");
+ produceMessages(backup, "test-topic-1");
+ String consumerGroupName = "consumer-group-testReplication";
+ Map<String, Object> consumerProps = new HashMap<String, Object>() {{
+ put("group.id", consumerGroupName);
+ put("auto.offset.reset", "latest");
+ }};
+ // create consumers before starting the connectors so we don't need to wait for discovery
+ Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps, "test-topic-1");
+ waitForConsumingAllRecords(primaryConsumer, 0);
+
+ Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(consumerProps, "test-topic-1");
+ waitForConsumingAllRecords(backupConsumer, 0);
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS);
+ waitUntilMirrorMakerIsRunning(primary, CONNECTOR_LIST, mm2Config, BACKUP_CLUSTER_ALIAS, PRIMARY_CLUSTER_ALIAS);
+
+ MirrorClient primaryClient = new MirrorClient(mm2Config.clientConfig(PRIMARY_CLUSTER_ALIAS));
+ MirrorClient backupClient = new MirrorClient(mm2Config.clientConfig(BACKUP_CLUSTER_ALIAS));
+
+ assertEquals("topic config was not synced", TopicConfig.CLEANUP_POLICY_COMPACT,
+ getTopicConfig(backup.kafka(), "primary.test-topic-1", TopicConfig.CLEANUP_POLICY_CONFIG));
+
+ assertEquals("Records were not produced to primary cluster.", NUM_RECORDS_PRODUCED,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "test-topic-1").count());
+ assertEquals("Records were not replicated to backup cluster.", NUM_RECORDS_PRODUCED,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "primary.test-topic-1").count());
+ assertEquals("Records were not produced to backup cluster.", NUM_RECORDS_PRODUCED,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "test-topic-1").count());
+ assertEquals("Records were not replicated to primary cluster.", NUM_RECORDS_PRODUCED,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "backup.test-topic-1").count());
+
+ assertEquals("Primary cluster doesn't have all records from both clusters.", NUM_RECORDS_PRODUCED * 2,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED * 2, RECORD_TRANSFER_DURATION_MS, "backup.test-topic-1", "test-topic-1").count());
+ assertEquals("Backup cluster doesn't have all records from both clusters.", NUM_RECORDS_PRODUCED * 2,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED * 2, RECORD_TRANSFER_DURATION_MS, "primary.test-topic-1", "test-topic-1").count());
+
+ assertTrue("Heartbeats were not emitted to primary cluster.", primary.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "heartbeats").count() > 0);
+ assertTrue("Heartbeats were not emitted to backup cluster.", backup.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "heartbeats").count() > 0);
+ assertTrue("Heartbeats were not replicated downstream to backup cluster.", backup.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "primary.heartbeats").count() > 0);
+ assertTrue("Heartbeats were not replicated downstream to primary cluster.", primary.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "backup.heartbeats").count() > 0);
+
+ assertTrue("Did not find upstream primary cluster.", backupClient.upstreamClusters().contains(PRIMARY_CLUSTER_ALIAS));
+ assertEquals("Did not calculate replication hops correctly.", 1, backupClient.replicationHops(PRIMARY_CLUSTER_ALIAS));
+ assertTrue("Did not find upstream backup cluster.", primaryClient.upstreamClusters().contains(BACKUP_CLUSTER_ALIAS));
+ assertEquals("Did not calculate replication hops correctly.", 1, primaryClient.replicationHops(BACKUP_CLUSTER_ALIAS));
+ assertTrue("Checkpoints were not emitted downstream to backup cluster.", backup.kafka().consume(1,
+ CHECKPOINT_DURATION_MS, "primary.checkpoints.internal").count() > 0);
+
+ Map<TopicPartition, OffsetAndMetadata> backupOffsets = backupClient.remoteConsumerOffsets(consumerGroupName, PRIMARY_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS));
+
+ assertTrue("Offsets not translated downstream to backup cluster. Found: " + backupOffsets, backupOffsets.containsKey(
+ new TopicPartition("primary.test-topic-1", 0)));
+
+ // Failover consumer group to backup cluster.
+ primaryConsumer = backup.kafka().createConsumer(Collections.singletonMap("group.id", consumerGroupName));
+ primaryConsumer.assign(backupOffsets.keySet());
+ backupOffsets.forEach(primaryConsumer::seek);
+ primaryConsumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+ primaryConsumer.commitAsync();
+
+ assertTrue("Consumer failedover to zero offset.", primaryConsumer.position(new TopicPartition("primary.test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedover beyond expected offset.", primaryConsumer.position(
+ new TopicPartition("primary.test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+ assertTrue("Checkpoints were not emitted upstream to primary cluster.", primary.kafka().consume(1,
+ CHECKPOINT_DURATION_MS, "backup.checkpoints.internal").count() > 0);
+
+ primaryConsumer.close();
+
+ waitForCondition(() -> {
+ try {
+ return primaryClient.remoteConsumerOffsets(consumerGroupName, BACKUP_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS)).containsKey(new TopicPartition("backup.test-topic-1", 0));
+ } catch (Throwable e) {
+ return false;
+ }
+ }, CHECKPOINT_DURATION_MS, "Offsets not translated downstream to primary cluster.");
+
+ waitForCondition(() -> {
+ try {
+ return primaryClient.remoteConsumerOffsets(consumerGroupName, BACKUP_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS)).containsKey(new TopicPartition("test-topic-1", 0));
+ } catch (Throwable e) {
+ return false;
+ }
+ }, CHECKPOINT_DURATION_MS, "Offsets not translated upstream to primary cluster.");
+
+ Map<TopicPartition, OffsetAndMetadata> primaryOffsets = primaryClient.remoteConsumerOffsets(consumerGroupName, BACKUP_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS));
+
+ // Failback consumer group to primary cluster
+ backupConsumer = primary.kafka().createConsumer(Collections.singletonMap("group.id", consumerGroupName));
+ backupConsumer.assign(primaryOffsets.keySet());
+ primaryOffsets.forEach(backupConsumer::seek);
+ backupConsumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+ backupConsumer.commitAsync();
+
+ assertTrue("Consumer failedback to zero upstream offset.", backupConsumer.position(new TopicPartition("test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedback to zero downstream offset.", backupConsumer.position(new TopicPartition("backup.test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedback beyond expected upstream offset.", backupConsumer.position(
+ new TopicPartition("test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+ assertTrue("Consumer failedback beyond expected downstream offset.", backupConsumer.position(
+ new TopicPartition("backup.test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+
+ backupConsumer.close();
+
+ // create more matching topics
+ primary.kafka().createTopic("test-topic-2", NUM_PARTITIONS);
+ backup.kafka().createTopic("test-topic-3", NUM_PARTITIONS);
+
+ // only produce messages to the first partition
+ produceMessages(primary, "test-topic-2", 1);
+ produceMessages(backup, "test-topic-3", 1);
+
+ // expect total consumed messages equals to NUM_RECORDS_PER_PARTITION
+ assertEquals("Records were not produced to primary cluster.", NUM_RECORDS_PER_PARTITION,
+ primary.kafka().consume(NUM_RECORDS_PER_PARTITION, RECORD_TRANSFER_DURATION_MS, "test-topic-2").count());
+ assertEquals("Records were not produced to backup cluster.", NUM_RECORDS_PER_PARTITION,
+ backup.kafka().consume(NUM_RECORDS_PER_PARTITION, RECORD_TRANSFER_DURATION_MS, "test-topic-3").count());
+
+ assertEquals("New topic was not replicated to primary cluster.", NUM_RECORDS_PER_PARTITION,
+ primary.kafka().consume(NUM_RECORDS_PER_PARTITION, 2 * RECORD_TRANSFER_DURATION_MS, "backup.test-topic-3").count());
+ assertEquals("New topic was not replicated to backup cluster.", NUM_RECORDS_PER_PARTITION,
+ backup.kafka().consume(NUM_RECORDS_PER_PARTITION, 2 * RECORD_TRANSFER_DURATION_MS, "primary.test-topic-2").count());
+
+ }
+
+ @Test
+ public void testReplicationWithEmptyPartition() throws Exception {
+ String consumerGroupName = "consumer-group-testReplicationWithEmptyPartition";
+ Map<String, Object> consumerProps = Collections.singletonMap("group.id", consumerGroupName);
+
+ // create topic
+ String topic = "test-topic-with-empty-partition";
+ primary.kafka().createTopic(topic, NUM_PARTITIONS);
+
+ // produce to all test-topic-empty's partitions, except the last partition
+ produceMessages(primary, topic, NUM_PARTITIONS - 1);
+
+ // consume before starting the connectors so we don't need to wait for discovery
+ int expectedRecords = NUM_RECORDS_PER_PARTITION * (NUM_PARTITIONS - 1);
+ try (Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps, topic)) {
+ waitForConsumingAllRecords(primaryConsumer, expectedRecords);
+ }
+
+ // one way replication from primary to backup
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + "->" + PRIMARY_CLUSTER_ALIAS + ".enabled", "false");
+ mm2Config = new MirrorMakerConfig(mm2Props);
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS);
+
+ // sleep few seconds to have MM2 finish replication so that "end" consumer will consume some record
+ Thread.sleep(TimeUnit.SECONDS.toMillis(3));
+
+ // consume all records from backup cluster
+ try (Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(consumerProps,
+ PRIMARY_CLUSTER_ALIAS + "." + topic)) {
+ waitForConsumingAllRecords(backupConsumer, expectedRecords);
+ }
+
+ Admin backupClient = backup.kafka().createAdminClient();
+ // retrieve the consumer group offset from backup cluster
+ Map<TopicPartition, OffsetAndMetadata> remoteOffsets =
+ backupClient.listConsumerGroupOffsets(consumerGroupName).partitionsToOffsetAndMetadata().get();
+ // pinpoint the offset of the last partition which does not receive records
+ OffsetAndMetadata offset = remoteOffsets.get(new TopicPartition(PRIMARY_CLUSTER_ALIAS + "." + topic, NUM_PARTITIONS - 1));
+ // offset of the last partition should exist, but its value should be 0
+ assertNotNull("Offset of last partition was not replicated", offset);
+ assertEquals("Offset of last partition is not zero", 0, offset.offset());
+ }
+
+ @Test
+ public void testOneWayReplicationWithAutoOffsetSync() throws InterruptedException {
+ produceMessages(primary, "test-topic-1");
+ String consumerGroupName = "consumer-group-testOneWayReplicationWithAutoOffsetSync";
+ Map<String, Object> consumerProps = new HashMap<String, Object>() {{
+ put("group.id", consumerGroupName);
+ put("auto.offset.reset", "earliest");
+ }};
+ // create consumers before starting the connectors so we don't need to wait for discovery
+ try (Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps,
+ "test-topic-1")) {
+ // we need to wait for consuming all the records for MM2 replicating the expected offsets
+ waitForConsumingAllRecords(primaryConsumer, NUM_RECORDS_PRODUCED);
+ }
+
+ // enable automated consumer group offset sync
+ mm2Props.put("sync.group.offsets.enabled", "true");
+ mm2Props.put("sync.group.offsets.interval.seconds", "1");
+ // one way replication from primary to backup
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + "->" + PRIMARY_CLUSTER_ALIAS + ".enabled", "false");
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS);
+
+ // create a consumer at backup cluster with same consumer group Id to consume 1 topic
+ Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(
+ consumerProps, "primary.test-topic-1");
+
+ waitForConsumerGroupOffsetSync(backup, backupConsumer, Collections.singletonList("primary.test-topic-1"),
+ consumerGroupName, NUM_RECORDS_PRODUCED);
+
+ ConsumerRecords<byte[], byte[]> records = backupConsumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+
+ // the size of consumer record should be zero, because the offsets of the same consumer group
+ // have been automatically synchronized from primary to backup by the background job, so no
+ // more records to consume from the replicated topic by the same consumer group at backup cluster
+ assertEquals("consumer record size is not zero", 0, records.count());
+
+ // now create a new topic in primary cluster
+ primary.kafka().createTopic("test-topic-2", NUM_PARTITIONS);
+ backup.kafka().createTopic("primary.test-topic-2", 1);
+ // produce some records to the new topic in primary cluster
+ produceMessages(primary, "test-topic-2");
+
+ // create a consumer at primary cluster to consume the new topic
+ try (Consumer<byte[], byte[]> consumer1 = primary.kafka().createConsumerAndSubscribeTo(Collections.singletonMap(
+ "group.id", "consumer-group-1"), "test-topic-2")) {
+ // we need to wait for consuming all the records for MM2 replicating the expected offsets
+ waitForConsumingAllRecords(consumer1, NUM_RECORDS_PRODUCED);
+ }
+
+ // create a consumer at backup cluster with same consumer group Id to consume old and new topic
+ backupConsumer = backup.kafka().createConsumerAndSubscribeTo(Collections.singletonMap(
+ "group.id", consumerGroupName), "primary.test-topic-1", "primary.test-topic-2");
+
+ waitForConsumerGroupOffsetSync(backup, backupConsumer, Arrays.asList("primary.test-topic-1", "primary.test-topic-2"),
+ consumerGroupName, NUM_RECORDS_PRODUCED);
+
+ records = backupConsumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+ // similar reasoning as above, no more records to consume by the same consumer group at backup cluster
+ assertEquals("consumer record size is not zero", 0, records.count());
+ backupConsumer.close();
+ }
+
+ /*
+ * This test is to validate MirrorSourceConnector follows "at most once" delivery guarantee
+ * under broker restart / failure
+ */
+ @Test
+ public void testWithBrokerRestart() throws InterruptedException {
Review comment:
I don't understand what this test is doing.
Why do we need background clients instead of producing upfront and consuming the data mirrorred at the end of the test?
It looks like we are testing the primary->backup scenario but we are restarting the backup cluster. The source connector should not interact with the backup cluster.
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationTest.java
##########
@@ -0,0 +1,370 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.errors.TimeoutException;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.connector.Connector;
+import org.apache.kafka.connect.mirror.MirrorCheckpointConnector;
+import org.apache.kafka.connect.mirror.MirrorClient;
+import org.apache.kafka.connect.mirror.MirrorHeartbeatConnector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.MirrorSourceConnector;
+import org.apache.kafka.connect.mirror.utils.ThreadedConsumer;
+import org.apache.kafka.connect.mirror.utils.ThreadedProducer;
+
+import org.junit.Before;
+import org.junit.After;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertNotNull;
+
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Collections;
+import java.util.Map;
+import java.util.HashMap;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+import org.apache.kafka.test.IntegrationTest;
+
+/**
+ * Tests MM2 replication and failover/failback logic.
+ *
+ * MM2 is configured with active/active replication between two Kafka clusters. Tests validate that
+ * records sent to either cluster arrive at the other cluster. Then, a consumer group is migrated from
+ * one cluster to the other and back. Tests validate that consumer offsets are translated and replicated
+ * between clusters during this failover and failback.
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationTest extends MirrorConnectorsIntegrationBaseTest {
+
+ private static final List<Class<? extends Connector>> CONNECTOR_LIST =
+ Arrays.asList(MirrorSourceConnector.class, MirrorCheckpointConnector.class, MirrorHeartbeatConnector.class);
+
+ @Before
+ public void setup() throws InterruptedException {
+ startClusters();
+ }
+
+ @After
+ public void close() {
+ shutdownClusters();
+ }
+
+ @Test
+ public void testReplication() throws InterruptedException {
+ produceMessages(primary, "test-topic-1");
+ produceMessages(backup, "test-topic-1");
+ String consumerGroupName = "consumer-group-testReplication";
+ Map<String, Object> consumerProps = new HashMap<String, Object>() {{
+ put("group.id", consumerGroupName);
+ put("auto.offset.reset", "latest");
+ }};
+ // create consumers before starting the connectors so we don't need to wait for discovery
+ Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps, "test-topic-1");
+ waitForConsumingAllRecords(primaryConsumer, 0);
+
+ Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(consumerProps, "test-topic-1");
+ waitForConsumingAllRecords(backupConsumer, 0);
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS);
+ waitUntilMirrorMakerIsRunning(primary, CONNECTOR_LIST, mm2Config, BACKUP_CLUSTER_ALIAS, PRIMARY_CLUSTER_ALIAS);
+
+ MirrorClient primaryClient = new MirrorClient(mm2Config.clientConfig(PRIMARY_CLUSTER_ALIAS));
+ MirrorClient backupClient = new MirrorClient(mm2Config.clientConfig(BACKUP_CLUSTER_ALIAS));
+
+ assertEquals("topic config was not synced", TopicConfig.CLEANUP_POLICY_COMPACT,
+ getTopicConfig(backup.kafka(), "primary.test-topic-1", TopicConfig.CLEANUP_POLICY_CONFIG));
+
+ assertEquals("Records were not produced to primary cluster.", NUM_RECORDS_PRODUCED,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "test-topic-1").count());
+ assertEquals("Records were not replicated to backup cluster.", NUM_RECORDS_PRODUCED,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "primary.test-topic-1").count());
+ assertEquals("Records were not produced to backup cluster.", NUM_RECORDS_PRODUCED,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "test-topic-1").count());
+ assertEquals("Records were not replicated to primary cluster.", NUM_RECORDS_PRODUCED,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "backup.test-topic-1").count());
+
+ assertEquals("Primary cluster doesn't have all records from both clusters.", NUM_RECORDS_PRODUCED * 2,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED * 2, RECORD_TRANSFER_DURATION_MS, "backup.test-topic-1", "test-topic-1").count());
+ assertEquals("Backup cluster doesn't have all records from both clusters.", NUM_RECORDS_PRODUCED * 2,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED * 2, RECORD_TRANSFER_DURATION_MS, "primary.test-topic-1", "test-topic-1").count());
+
+ assertTrue("Heartbeats were not emitted to primary cluster.", primary.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "heartbeats").count() > 0);
+ assertTrue("Heartbeats were not emitted to backup cluster.", backup.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "heartbeats").count() > 0);
+ assertTrue("Heartbeats were not replicated downstream to backup cluster.", backup.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "primary.heartbeats").count() > 0);
+ assertTrue("Heartbeats were not replicated downstream to primary cluster.", primary.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "backup.heartbeats").count() > 0);
+
+ assertTrue("Did not find upstream primary cluster.", backupClient.upstreamClusters().contains(PRIMARY_CLUSTER_ALIAS));
+ assertEquals("Did not calculate replication hops correctly.", 1, backupClient.replicationHops(PRIMARY_CLUSTER_ALIAS));
+ assertTrue("Did not find upstream backup cluster.", primaryClient.upstreamClusters().contains(BACKUP_CLUSTER_ALIAS));
+ assertEquals("Did not calculate replication hops correctly.", 1, primaryClient.replicationHops(BACKUP_CLUSTER_ALIAS));
+ assertTrue("Checkpoints were not emitted downstream to backup cluster.", backup.kafka().consume(1,
+ CHECKPOINT_DURATION_MS, "primary.checkpoints.internal").count() > 0);
+
+ Map<TopicPartition, OffsetAndMetadata> backupOffsets = backupClient.remoteConsumerOffsets(consumerGroupName, PRIMARY_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS));
+
+ assertTrue("Offsets not translated downstream to backup cluster. Found: " + backupOffsets, backupOffsets.containsKey(
+ new TopicPartition("primary.test-topic-1", 0)));
+
+ // Failover consumer group to backup cluster.
+ primaryConsumer = backup.kafka().createConsumer(Collections.singletonMap("group.id", consumerGroupName));
+ primaryConsumer.assign(backupOffsets.keySet());
+ backupOffsets.forEach(primaryConsumer::seek);
+ primaryConsumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+ primaryConsumer.commitAsync();
+
+ assertTrue("Consumer failedover to zero offset.", primaryConsumer.position(new TopicPartition("primary.test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedover beyond expected offset.", primaryConsumer.position(
+ new TopicPartition("primary.test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+ assertTrue("Checkpoints were not emitted upstream to primary cluster.", primary.kafka().consume(1,
+ CHECKPOINT_DURATION_MS, "backup.checkpoints.internal").count() > 0);
+
+ primaryConsumer.close();
+
+ waitForCondition(() -> {
+ try {
+ return primaryClient.remoteConsumerOffsets(consumerGroupName, BACKUP_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS)).containsKey(new TopicPartition("backup.test-topic-1", 0));
+ } catch (Throwable e) {
+ return false;
+ }
+ }, CHECKPOINT_DURATION_MS, "Offsets not translated downstream to primary cluster.");
+
+ waitForCondition(() -> {
+ try {
+ return primaryClient.remoteConsumerOffsets(consumerGroupName, BACKUP_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS)).containsKey(new TopicPartition("test-topic-1", 0));
+ } catch (Throwable e) {
+ return false;
+ }
+ }, CHECKPOINT_DURATION_MS, "Offsets not translated upstream to primary cluster.");
+
+ Map<TopicPartition, OffsetAndMetadata> primaryOffsets = primaryClient.remoteConsumerOffsets(consumerGroupName, BACKUP_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS));
+
+ // Failback consumer group to primary cluster
+ backupConsumer = primary.kafka().createConsumer(Collections.singletonMap("group.id", consumerGroupName));
+ backupConsumer.assign(primaryOffsets.keySet());
+ primaryOffsets.forEach(backupConsumer::seek);
+ backupConsumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+ backupConsumer.commitAsync();
+
+ assertTrue("Consumer failedback to zero upstream offset.", backupConsumer.position(new TopicPartition("test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedback to zero downstream offset.", backupConsumer.position(new TopicPartition("backup.test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedback beyond expected upstream offset.", backupConsumer.position(
+ new TopicPartition("test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+ assertTrue("Consumer failedback beyond expected downstream offset.", backupConsumer.position(
+ new TopicPartition("backup.test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+
+ backupConsumer.close();
+
+ // create more matching topics
+ primary.kafka().createTopic("test-topic-2", NUM_PARTITIONS);
+ backup.kafka().createTopic("test-topic-3", NUM_PARTITIONS);
+
+ // only produce messages to the first partition
+ produceMessages(primary, "test-topic-2", 1);
+ produceMessages(backup, "test-topic-3", 1);
+
+ // expect total consumed messages equals to NUM_RECORDS_PER_PARTITION
+ assertEquals("Records were not produced to primary cluster.", NUM_RECORDS_PER_PARTITION,
+ primary.kafka().consume(NUM_RECORDS_PER_PARTITION, RECORD_TRANSFER_DURATION_MS, "test-topic-2").count());
+ assertEquals("Records were not produced to backup cluster.", NUM_RECORDS_PER_PARTITION,
+ backup.kafka().consume(NUM_RECORDS_PER_PARTITION, RECORD_TRANSFER_DURATION_MS, "test-topic-3").count());
+
+ assertEquals("New topic was not replicated to primary cluster.", NUM_RECORDS_PER_PARTITION,
+ primary.kafka().consume(NUM_RECORDS_PER_PARTITION, 2 * RECORD_TRANSFER_DURATION_MS, "backup.test-topic-3").count());
+ assertEquals("New topic was not replicated to backup cluster.", NUM_RECORDS_PER_PARTITION,
+ backup.kafka().consume(NUM_RECORDS_PER_PARTITION, 2 * RECORD_TRANSFER_DURATION_MS, "primary.test-topic-2").count());
+
+ }
+
+ @Test
+ public void testReplicationWithEmptyPartition() throws Exception {
+ String consumerGroupName = "consumer-group-testReplicationWithEmptyPartition";
+ Map<String, Object> consumerProps = Collections.singletonMap("group.id", consumerGroupName);
+
+ // create topic
+ String topic = "test-topic-with-empty-partition";
+ primary.kafka().createTopic(topic, NUM_PARTITIONS);
+
+ // produce to all test-topic-empty's partitions, except the last partition
+ produceMessages(primary, topic, NUM_PARTITIONS - 1);
+
+ // consume before starting the connectors so we don't need to wait for discovery
+ int expectedRecords = NUM_RECORDS_PER_PARTITION * (NUM_PARTITIONS - 1);
+ try (Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps, topic)) {
+ waitForConsumingAllRecords(primaryConsumer, expectedRecords);
+ }
+
+ // one way replication from primary to backup
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + "->" + PRIMARY_CLUSTER_ALIAS + ".enabled", "false");
+ mm2Config = new MirrorMakerConfig(mm2Props);
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS);
+
+ // sleep few seconds to have MM2 finish replication so that "end" consumer will consume some record
+ Thread.sleep(TimeUnit.SECONDS.toMillis(3));
+
+ // consume all records from backup cluster
+ try (Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(consumerProps,
+ PRIMARY_CLUSTER_ALIAS + "." + topic)) {
+ waitForConsumingAllRecords(backupConsumer, expectedRecords);
+ }
+
+ Admin backupClient = backup.kafka().createAdminClient();
+ // retrieve the consumer group offset from backup cluster
+ Map<TopicPartition, OffsetAndMetadata> remoteOffsets =
+ backupClient.listConsumerGroupOffsets(consumerGroupName).partitionsToOffsetAndMetadata().get();
+ // pinpoint the offset of the last partition which does not receive records
+ OffsetAndMetadata offset = remoteOffsets.get(new TopicPartition(PRIMARY_CLUSTER_ALIAS + "." + topic, NUM_PARTITIONS - 1));
+ // offset of the last partition should exist, but its value should be 0
+ assertNotNull("Offset of last partition was not replicated", offset);
+ assertEquals("Offset of last partition is not zero", 0, offset.offset());
+ }
+
+ @Test
+ public void testOneWayReplicationWithAutoOffsetSync() throws InterruptedException {
+ produceMessages(primary, "test-topic-1");
+ String consumerGroupName = "consumer-group-testOneWayReplicationWithAutoOffsetSync";
+ Map<String, Object> consumerProps = new HashMap<String, Object>() {{
+ put("group.id", consumerGroupName);
+ put("auto.offset.reset", "earliest");
+ }};
+ // create consumers before starting the connectors so we don't need to wait for discovery
+ try (Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps,
+ "test-topic-1")) {
+ // we need to wait for consuming all the records for MM2 replicating the expected offsets
+ waitForConsumingAllRecords(primaryConsumer, NUM_RECORDS_PRODUCED);
+ }
+
+ // enable automated consumer group offset sync
+ mm2Props.put("sync.group.offsets.enabled", "true");
+ mm2Props.put("sync.group.offsets.interval.seconds", "1");
+ // one way replication from primary to backup
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + "->" + PRIMARY_CLUSTER_ALIAS + ".enabled", "false");
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS);
+
+ // create a consumer at backup cluster with same consumer group Id to consume 1 topic
+ Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(
+ consumerProps, "primary.test-topic-1");
+
+ waitForConsumerGroupOffsetSync(backup, backupConsumer, Collections.singletonList("primary.test-topic-1"),
+ consumerGroupName, NUM_RECORDS_PRODUCED);
+
+ ConsumerRecords<byte[], byte[]> records = backupConsumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+
+ // the size of consumer record should be zero, because the offsets of the same consumer group
+ // have been automatically synchronized from primary to backup by the background job, so no
+ // more records to consume from the replicated topic by the same consumer group at backup cluster
+ assertEquals("consumer record size is not zero", 0, records.count());
+
+ // now create a new topic in primary cluster
+ primary.kafka().createTopic("test-topic-2", NUM_PARTITIONS);
+ backup.kafka().createTopic("primary.test-topic-2", 1);
+ // produce some records to the new topic in primary cluster
+ produceMessages(primary, "test-topic-2");
+
+ // create a consumer at primary cluster to consume the new topic
+ try (Consumer<byte[], byte[]> consumer1 = primary.kafka().createConsumerAndSubscribeTo(Collections.singletonMap(
+ "group.id", "consumer-group-1"), "test-topic-2")) {
+ // we need to wait for consuming all the records for MM2 replicating the expected offsets
+ waitForConsumingAllRecords(consumer1, NUM_RECORDS_PRODUCED);
+ }
+
+ // create a consumer at backup cluster with same consumer group Id to consume old and new topic
+ backupConsumer = backup.kafka().createConsumerAndSubscribeTo(Collections.singletonMap(
+ "group.id", consumerGroupName), "primary.test-topic-1", "primary.test-topic-2");
+
+ waitForConsumerGroupOffsetSync(backup, backupConsumer, Arrays.asList("primary.test-topic-1", "primary.test-topic-2"),
+ consumerGroupName, NUM_RECORDS_PRODUCED);
+
+ records = backupConsumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+ // similar reasoning as above, no more records to consume by the same consumer group at backup cluster
+ assertEquals("consumer record size is not zero", 0, records.count());
+ backupConsumer.close();
+ }
+
+ /*
+ * This test is to validate MirrorSourceConnector follows "at most once" delivery guarantee
Review comment:
Isn't MM2/Connect using at least once by default? ie, the producer in the runtime can cause duplicates.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc commented on a change in pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc commented on a change in pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#discussion_r527391656
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/TestUtils.java
##########
@@ -32,4 +32,15 @@
}
return props;
}
-}
+
+ /*
+ * return records with different but predictable key and value
+ */
+ public static Map<String, String> expectedRecords(int numRecords) {
Review comment:
rename to `generateRecords` ?
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc commented on pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc commented on pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#issuecomment-739114982
@rhauch if your pr is merged first, I will be happy to rebase on https://github.com/apache/kafka/pull/9698
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc commented on pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc commented on pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#issuecomment-738115781
https://github.com/apache/kafka/pull/9224#discussion_r535179359
I think the `try catch` block is needed for several Exception.
```
/kafka/connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationSSLTest.java:41: error: unreported exception IOException; must be caught or declared to be thrown
sslConfig = TestSslUtils.createSslConfig(false, true, Mode.SERVER, TestUtils.tempFile(), "testCert");
```
```
/kafka/connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationSSLTest.java:42: error: unreported exception GeneralSecurityException; must be caught or declared to be thrown
sslConfig = TestSslUtils.createSslConfig(false, true, Mode.SERVER, TestUtils.tempFile(), "testCert");
```
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc commented on a change in pull request #9224: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc commented on a change in pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#discussion_r485361003
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/TestUtils.java
##########
@@ -32,4 +73,166 @@
}
return props;
}
+
+ /*
+ * launch the connectors on kafka connect cluster, then check if they are running
+ */
+ public static void waitUntilMirrorMakerIsRunning(EmbeddedConnectCluster connectCluster, List<Class> connectorClasses,
Review comment:
this is mostly copy-paste from `MirrorConnectorsIntegrationTest`
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc commented on a change in pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc commented on a change in pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#discussion_r527398919
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationTest.java
##########
@@ -0,0 +1,370 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.errors.TimeoutException;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.connector.Connector;
+import org.apache.kafka.connect.mirror.MirrorCheckpointConnector;
+import org.apache.kafka.connect.mirror.MirrorClient;
+import org.apache.kafka.connect.mirror.MirrorHeartbeatConnector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.MirrorSourceConnector;
+import org.apache.kafka.connect.mirror.utils.ThreadedConsumer;
+import org.apache.kafka.connect.mirror.utils.ThreadedProducer;
+
+import org.junit.Before;
+import org.junit.After;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertNotNull;
+
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Collections;
+import java.util.Map;
+import java.util.HashMap;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+import org.apache.kafka.test.IntegrationTest;
+
+/**
+ * Tests MM2 replication and failover/failback logic.
+ *
+ * MM2 is configured with active/active replication between two Kafka clusters. Tests validate that
+ * records sent to either cluster arrive at the other cluster. Then, a consumer group is migrated from
+ * one cluster to the other and back. Tests validate that consumer offsets are translated and replicated
+ * between clusters during this failover and failback.
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationTest extends MirrorConnectorsIntegrationBaseTest {
+
+ private static final List<Class<? extends Connector>> CONNECTOR_LIST =
+ Arrays.asList(MirrorSourceConnector.class, MirrorCheckpointConnector.class, MirrorHeartbeatConnector.class);
+
+ @Before
+ public void setup() throws InterruptedException {
+ startClusters();
+ }
+
+ @After
+ public void close() {
+ shutdownClusters();
+ }
+
+ @Test
+ public void testReplication() throws InterruptedException {
+ produceMessages(primary, "test-topic-1");
+ produceMessages(backup, "test-topic-1");
+ String consumerGroupName = "consumer-group-testReplication";
+ Map<String, Object> consumerProps = new HashMap<String, Object>() {{
+ put("group.id", consumerGroupName);
+ put("auto.offset.reset", "latest");
+ }};
+ // create consumers before starting the connectors so we don't need to wait for discovery
+ Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps, "test-topic-1");
+ waitForConsumingAllRecords(primaryConsumer, 0);
+
+ Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(consumerProps, "test-topic-1");
+ waitForConsumingAllRecords(backupConsumer, 0);
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS);
+ waitUntilMirrorMakerIsRunning(primary, CONNECTOR_LIST, mm2Config, BACKUP_CLUSTER_ALIAS, PRIMARY_CLUSTER_ALIAS);
+
+ MirrorClient primaryClient = new MirrorClient(mm2Config.clientConfig(PRIMARY_CLUSTER_ALIAS));
+ MirrorClient backupClient = new MirrorClient(mm2Config.clientConfig(BACKUP_CLUSTER_ALIAS));
+
+ assertEquals("topic config was not synced", TopicConfig.CLEANUP_POLICY_COMPACT,
+ getTopicConfig(backup.kafka(), "primary.test-topic-1", TopicConfig.CLEANUP_POLICY_CONFIG));
+
+ assertEquals("Records were not produced to primary cluster.", NUM_RECORDS_PRODUCED,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "test-topic-1").count());
+ assertEquals("Records were not replicated to backup cluster.", NUM_RECORDS_PRODUCED,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "primary.test-topic-1").count());
+ assertEquals("Records were not produced to backup cluster.", NUM_RECORDS_PRODUCED,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "test-topic-1").count());
+ assertEquals("Records were not replicated to primary cluster.", NUM_RECORDS_PRODUCED,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "backup.test-topic-1").count());
+
+ assertEquals("Primary cluster doesn't have all records from both clusters.", NUM_RECORDS_PRODUCED * 2,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED * 2, RECORD_TRANSFER_DURATION_MS, "backup.test-topic-1", "test-topic-1").count());
+ assertEquals("Backup cluster doesn't have all records from both clusters.", NUM_RECORDS_PRODUCED * 2,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED * 2, RECORD_TRANSFER_DURATION_MS, "primary.test-topic-1", "test-topic-1").count());
+
+ assertTrue("Heartbeats were not emitted to primary cluster.", primary.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "heartbeats").count() > 0);
+ assertTrue("Heartbeats were not emitted to backup cluster.", backup.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "heartbeats").count() > 0);
+ assertTrue("Heartbeats were not replicated downstream to backup cluster.", backup.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "primary.heartbeats").count() > 0);
+ assertTrue("Heartbeats were not replicated downstream to primary cluster.", primary.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "backup.heartbeats").count() > 0);
+
+ assertTrue("Did not find upstream primary cluster.", backupClient.upstreamClusters().contains(PRIMARY_CLUSTER_ALIAS));
+ assertEquals("Did not calculate replication hops correctly.", 1, backupClient.replicationHops(PRIMARY_CLUSTER_ALIAS));
+ assertTrue("Did not find upstream backup cluster.", primaryClient.upstreamClusters().contains(BACKUP_CLUSTER_ALIAS));
+ assertEquals("Did not calculate replication hops correctly.", 1, primaryClient.replicationHops(BACKUP_CLUSTER_ALIAS));
+ assertTrue("Checkpoints were not emitted downstream to backup cluster.", backup.kafka().consume(1,
+ CHECKPOINT_DURATION_MS, "primary.checkpoints.internal").count() > 0);
+
+ Map<TopicPartition, OffsetAndMetadata> backupOffsets = backupClient.remoteConsumerOffsets(consumerGroupName, PRIMARY_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS));
+
+ assertTrue("Offsets not translated downstream to backup cluster. Found: " + backupOffsets, backupOffsets.containsKey(
+ new TopicPartition("primary.test-topic-1", 0)));
+
+ // Failover consumer group to backup cluster.
+ primaryConsumer = backup.kafka().createConsumer(Collections.singletonMap("group.id", consumerGroupName));
+ primaryConsumer.assign(backupOffsets.keySet());
+ backupOffsets.forEach(primaryConsumer::seek);
+ primaryConsumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+ primaryConsumer.commitAsync();
+
+ assertTrue("Consumer failedover to zero offset.", primaryConsumer.position(new TopicPartition("primary.test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedover beyond expected offset.", primaryConsumer.position(
+ new TopicPartition("primary.test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+ assertTrue("Checkpoints were not emitted upstream to primary cluster.", primary.kafka().consume(1,
+ CHECKPOINT_DURATION_MS, "backup.checkpoints.internal").count() > 0);
+
+ primaryConsumer.close();
+
+ waitForCondition(() -> {
+ try {
+ return primaryClient.remoteConsumerOffsets(consumerGroupName, BACKUP_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS)).containsKey(new TopicPartition("backup.test-topic-1", 0));
+ } catch (Throwable e) {
+ return false;
+ }
+ }, CHECKPOINT_DURATION_MS, "Offsets not translated downstream to primary cluster.");
+
+ waitForCondition(() -> {
+ try {
+ return primaryClient.remoteConsumerOffsets(consumerGroupName, BACKUP_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS)).containsKey(new TopicPartition("test-topic-1", 0));
+ } catch (Throwable e) {
+ return false;
+ }
+ }, CHECKPOINT_DURATION_MS, "Offsets not translated upstream to primary cluster.");
+
+ Map<TopicPartition, OffsetAndMetadata> primaryOffsets = primaryClient.remoteConsumerOffsets(consumerGroupName, BACKUP_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS));
+
+ // Failback consumer group to primary cluster
+ backupConsumer = primary.kafka().createConsumer(Collections.singletonMap("group.id", consumerGroupName));
+ backupConsumer.assign(primaryOffsets.keySet());
+ primaryOffsets.forEach(backupConsumer::seek);
+ backupConsumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+ backupConsumer.commitAsync();
+
+ assertTrue("Consumer failedback to zero upstream offset.", backupConsumer.position(new TopicPartition("test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedback to zero downstream offset.", backupConsumer.position(new TopicPartition("backup.test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedback beyond expected upstream offset.", backupConsumer.position(
+ new TopicPartition("test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+ assertTrue("Consumer failedback beyond expected downstream offset.", backupConsumer.position(
+ new TopicPartition("backup.test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+
+ backupConsumer.close();
+
+ // create more matching topics
+ primary.kafka().createTopic("test-topic-2", NUM_PARTITIONS);
+ backup.kafka().createTopic("test-topic-3", NUM_PARTITIONS);
+
+ // only produce messages to the first partition
+ produceMessages(primary, "test-topic-2", 1);
+ produceMessages(backup, "test-topic-3", 1);
+
+ // expect total consumed messages equals to NUM_RECORDS_PER_PARTITION
+ assertEquals("Records were not produced to primary cluster.", NUM_RECORDS_PER_PARTITION,
+ primary.kafka().consume(NUM_RECORDS_PER_PARTITION, RECORD_TRANSFER_DURATION_MS, "test-topic-2").count());
+ assertEquals("Records were not produced to backup cluster.", NUM_RECORDS_PER_PARTITION,
+ backup.kafka().consume(NUM_RECORDS_PER_PARTITION, RECORD_TRANSFER_DURATION_MS, "test-topic-3").count());
+
+ assertEquals("New topic was not replicated to primary cluster.", NUM_RECORDS_PER_PARTITION,
+ primary.kafka().consume(NUM_RECORDS_PER_PARTITION, 2 * RECORD_TRANSFER_DURATION_MS, "backup.test-topic-3").count());
+ assertEquals("New topic was not replicated to backup cluster.", NUM_RECORDS_PER_PARTITION,
+ backup.kafka().consume(NUM_RECORDS_PER_PARTITION, 2 * RECORD_TRANSFER_DURATION_MS, "primary.test-topic-2").count());
+
+ }
+
+ @Test
+ public void testReplicationWithEmptyPartition() throws Exception {
+ String consumerGroupName = "consumer-group-testReplicationWithEmptyPartition";
+ Map<String, Object> consumerProps = Collections.singletonMap("group.id", consumerGroupName);
+
+ // create topic
+ String topic = "test-topic-with-empty-partition";
+ primary.kafka().createTopic(topic, NUM_PARTITIONS);
+
+ // produce to all test-topic-empty's partitions, except the last partition
+ produceMessages(primary, topic, NUM_PARTITIONS - 1);
+
+ // consume before starting the connectors so we don't need to wait for discovery
+ int expectedRecords = NUM_RECORDS_PER_PARTITION * (NUM_PARTITIONS - 1);
+ try (Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps, topic)) {
+ waitForConsumingAllRecords(primaryConsumer, expectedRecords);
+ }
+
+ // one way replication from primary to backup
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + "->" + PRIMARY_CLUSTER_ALIAS + ".enabled", "false");
+ mm2Config = new MirrorMakerConfig(mm2Props);
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS);
+
+ // sleep few seconds to have MM2 finish replication so that "end" consumer will consume some record
+ Thread.sleep(TimeUnit.SECONDS.toMillis(3));
+
+ // consume all records from backup cluster
+ try (Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(consumerProps,
+ PRIMARY_CLUSTER_ALIAS + "." + topic)) {
+ waitForConsumingAllRecords(backupConsumer, expectedRecords);
+ }
+
+ Admin backupClient = backup.kafka().createAdminClient();
+ // retrieve the consumer group offset from backup cluster
+ Map<TopicPartition, OffsetAndMetadata> remoteOffsets =
+ backupClient.listConsumerGroupOffsets(consumerGroupName).partitionsToOffsetAndMetadata().get();
+ // pinpoint the offset of the last partition which does not receive records
+ OffsetAndMetadata offset = remoteOffsets.get(new TopicPartition(PRIMARY_CLUSTER_ALIAS + "." + topic, NUM_PARTITIONS - 1));
+ // offset of the last partition should exist, but its value should be 0
+ assertNotNull("Offset of last partition was not replicated", offset);
+ assertEquals("Offset of last partition is not zero", 0, offset.offset());
+ }
+
+ @Test
+ public void testOneWayReplicationWithAutoOffsetSync() throws InterruptedException {
+ produceMessages(primary, "test-topic-1");
+ String consumerGroupName = "consumer-group-testOneWayReplicationWithAutoOffsetSync";
+ Map<String, Object> consumerProps = new HashMap<String, Object>() {{
+ put("group.id", consumerGroupName);
+ put("auto.offset.reset", "earliest");
+ }};
+ // create consumers before starting the connectors so we don't need to wait for discovery
+ try (Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps,
+ "test-topic-1")) {
+ // we need to wait for consuming all the records for MM2 replicating the expected offsets
+ waitForConsumingAllRecords(primaryConsumer, NUM_RECORDS_PRODUCED);
+ }
+
+ // enable automated consumer group offset sync
+ mm2Props.put("sync.group.offsets.enabled", "true");
+ mm2Props.put("sync.group.offsets.interval.seconds", "1");
+ // one way replication from primary to backup
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + "->" + PRIMARY_CLUSTER_ALIAS + ".enabled", "false");
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS);
+
+ // create a consumer at backup cluster with same consumer group Id to consume 1 topic
+ Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(
+ consumerProps, "primary.test-topic-1");
+
+ waitForConsumerGroupOffsetSync(backup, backupConsumer, Collections.singletonList("primary.test-topic-1"),
+ consumerGroupName, NUM_RECORDS_PRODUCED);
+
+ ConsumerRecords<byte[], byte[]> records = backupConsumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+
+ // the size of consumer record should be zero, because the offsets of the same consumer group
+ // have been automatically synchronized from primary to backup by the background job, so no
+ // more records to consume from the replicated topic by the same consumer group at backup cluster
+ assertEquals("consumer record size is not zero", 0, records.count());
+
+ // now create a new topic in primary cluster
+ primary.kafka().createTopic("test-topic-2", NUM_PARTITIONS);
+ backup.kafka().createTopic("primary.test-topic-2", 1);
+ // produce some records to the new topic in primary cluster
+ produceMessages(primary, "test-topic-2");
+
+ // create a consumer at primary cluster to consume the new topic
+ try (Consumer<byte[], byte[]> consumer1 = primary.kafka().createConsumerAndSubscribeTo(Collections.singletonMap(
+ "group.id", "consumer-group-1"), "test-topic-2")) {
+ // we need to wait for consuming all the records for MM2 replicating the expected offsets
+ waitForConsumingAllRecords(consumer1, NUM_RECORDS_PRODUCED);
+ }
+
+ // create a consumer at backup cluster with same consumer group Id to consume old and new topic
+ backupConsumer = backup.kafka().createConsumerAndSubscribeTo(Collections.singletonMap(
+ "group.id", consumerGroupName), "primary.test-topic-1", "primary.test-topic-2");
+
+ waitForConsumerGroupOffsetSync(backup, backupConsumer, Arrays.asList("primary.test-topic-1", "primary.test-topic-2"),
+ consumerGroupName, NUM_RECORDS_PRODUCED);
+
+ records = backupConsumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+ // similar reasoning as above, no more records to consume by the same consumer group at backup cluster
+ assertEquals("consumer record size is not zero", 0, records.count());
+ backupConsumer.close();
+ }
+
+ /*
+ * This test is to validate MirrorSourceConnector follows "at most once" delivery guarantee
+ * under broker restart / failure
+ */
+ @Test
+ public void testWithBrokerRestart() throws InterruptedException {
Review comment:
> Why do we need background clients instead of producing upfront and consuming the data mirrorred at the end of the test?
I think I answered the above question as the comments in the code. Please see below,
> // the purpose of background producer and consumer is to better test the failure case
> // to avoid serialization (produce -> broker restart -> consumer) by decoupling the
> // producer, embedded kafka and consumer. Since the consumer offsets are stored in
> // kafka topic at backup cluster and offset commit is periodic, when kafka broker (at backup)
> // restarts, duplicate records will be consumed, meaning "at least once" delivery guarantee
I believe this test has unique value and is more close to the realistic scenario, since the producer -> kafka -> consumer are always running on different machines, rather than one process or thread.
Due to the complexity limitation, I am happy to remove this test for now
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] mimaison commented on pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
mimaison commented on pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#issuecomment-719446426
@ning2008wisc Thanks for the quick update. It's still on my todo list but unfortunately I don't have time to do reviews this week. I hope to take another look next week.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc commented on a change in pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc commented on a change in pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#discussion_r510499941
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationSSLTest.java
##########
@@ -0,0 +1,98 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.common.network.Mode;
+import org.apache.kafka.connect.mirror.MirrorCheckpointConnector;
+import org.apache.kafka.connect.mirror.MirrorHeartbeatConnector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.MirrorSourceConnector;
+import org.apache.kafka.test.IntegrationTest;
+import org.apache.kafka.test.TestSslUtils;
+import org.apache.kafka.test.TestUtils;
+import kafka.server.KafkaConfig$;
+
+import org.junit.experimental.categories.Category;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+import org.junit.Before;
+import org.junit.After;
+import org.junit.Test;
+
+/**
+ * Tests MM2 replication with SSL enabled at backup kafka cluster
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationSSLTest extends MirrorConnectorsIntegrationBaseTest {
+
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationSSLTest.class);
+
+ private static final List<Class> CONNECTOR_LIST =
+ Arrays.asList(MirrorSourceConnector.class, MirrorCheckpointConnector.class, MirrorHeartbeatConnector.class);
+
+ @Before
+ public void setup() throws InterruptedException {
+ try {
+ Map<String, Object> sslConfig = TestSslUtils.createSslConfig(false, true, Mode.SERVER, TestUtils.tempFile(), "testCert");
+ backupBrokerProps.put(KafkaConfig$.MODULE$.ListenersProp(), "SSL://localhost:0");
+ backupBrokerProps.put(KafkaConfig$.MODULE$.InterBrokerListenerNameProp(), "SSL");
+ backupBrokerProps.putAll(sslConfig);
+ } catch (final Exception e) {
+ throw new RuntimeException(e);
+ }
+ startClusters();
+ }
+
+ @After
+ public void close() {
Review comment:
if move to base class, will close() still be called at demolition stage of test?
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc commented on pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc commented on pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#issuecomment-714955565
Thanks @mimaison for your high-level advice and detailed review.
(1) I responded to your every comments. A "thumb-up" means I made the suggested change
(2) regarding the increased complexity, here is my analysis for each test case
(a) `testReplication`: This is an existing test and no new stuff are added, except checking if topic config are also mirrored. If the topic config validation is trivial, I am happy to remove it
(b) `testReplicationWithEmptyPartition`: This is an existing test and no new stuff are added
(c) `testOneWayReplicationWithAutoOffsetSync`: This is an existing test and no new stuff are added
(d) `testWithBrokerRestart`: This is a **new** test, which introduced background producer and consumer, called `ThreadedProducer` and `ThreadedConsumer`. The purpose of background producer and consumer is to better test the failure case to avoid serialization (produce -> broker restart -> consumer) by decoupling the producer thread, embedded kafka and consumer thread.
(e) `MirrorConnectorsIntegrationSSLTest`: This is a **new** test and it should be pretty lean and neat.
In addition, the **new** base test class `MirrorConnectorsIntegrationBaseTest` follows the existing practice of K-stream integration test structure https://github.com/apache/kafka/blob/trunk/streams/src/test/java/org/apache/kafka/streams/integration/ResetIntegrationWithSslTest.java#L37 so I assume it is likely the right structure to extend from a base class.
If we have to control the complexity, I would prefer to drop `testWithBrokerRestart` and keep `MirrorConnectorsIntegrationSSLTest`, as it makes sense to run simple validation in SSL setup.
Thanks and would like to hear more thoughts and feedback.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc commented on pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc commented on pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#issuecomment-690907900
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc commented on pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc commented on pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#issuecomment-690907900
@ryannedolan @mimaison when possible, very appreciated for your attentions and feedback :) Thanks
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc edited a comment on pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc edited a comment on pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#issuecomment-714955565
Thanks @mimaison for your high-level advice and detailed review.
(1) I responded to your every comments. A "thumb-up" means I made the suggested change
(2) regarding the increased complexity, here is my analysis for each test case:
(2a) `testReplication`: This is an existing test and no new stuff are added, except checking if topic config are also mirrored. If we believe the topic config validation is trivial, I am more than happy to remove it
(2b) `testReplicationWithEmptyPartition`: This is an existing test and no new stuff are added
(2c) `testOneWayReplicationWithAutoOffsetSync`: This is an existing test and no new stuff are added
(2d) `testWithBrokerRestart`: This is a **new** test, which introduced background producer and consumer, called `ThreadedProducer` and `ThreadedConsumer`. The purpose of background producer and consumer is to better test the failure case to avoid serialization (produce -> broker restart -> consumer) which can not reveal the insight that consumers consume the same records more than once when broker failure happens.
(2e) `MirrorConnectorsIntegrationSSLTest`: This is a **new** test and it should be pretty lean and neat.
In addition, the **new** base test class `MirrorConnectorsIntegrationBaseTest` follows the existing practice of K-stream integration test structure https://github.com/apache/kafka/blob/trunk/streams/src/test/java/org/apache/kafka/streams/integration/ResetIntegrationWithSslTest.java#L37 so I assume it is likely the right way tp structure tests with more than one scenarios (SSL v.s. non-SSL)
If we have to control the complexity, I would prefer to drop `testWithBrokerRestart` and keep `MirrorConnectorsIntegrationSSLTest`, as it makes sense to run simple validation in SSL setup.
Thanks and would like to hear more thoughts and feedback.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc edited a comment on pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc edited a comment on pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#issuecomment-714955565
Thanks @mimaison for your high-level advice and detailed review.
(1) I responded to your every comments. A "thumb-up" means I made the suggested change
(2) regarding the increased complexity, here is my analysis for each test case
(a) `testReplication`: This is an existing test and no new stuff are added, except checking if topic config are also mirrored. If we believe the topic config validation is trivial, I am more than happy to remove it
(b) `testReplicationWithEmptyPartition`: This is an existing test and no new stuff are added
(c) `testOneWayReplicationWithAutoOffsetSync`: This is an existing test and no new stuff are added
(d) `testWithBrokerRestart`: This is a **new** test, which introduced background producer and consumer, called `ThreadedProducer` and `ThreadedConsumer`. The purpose of background producer and consumer is to better test the failure case to avoid serialization (produce -> broker restart -> consumer) which can not reveal the insight that consumers consume the same records more than once when broker failure happens.
(e) `MirrorConnectorsIntegrationSSLTest`: This is a **new** test and it should be pretty lean and neat.
In addition, the **new** base test class `MirrorConnectorsIntegrationBaseTest` follows the existing practice of K-stream integration test structure https://github.com/apache/kafka/blob/trunk/streams/src/test/java/org/apache/kafka/streams/integration/ResetIntegrationWithSslTest.java#L37 so I assume it is likely the right way tp structure tests with more than one scenarios (SSL v.s. non-SSL)
If we have to control the complexity, I would prefer to drop `testWithBrokerRestart` and keep `MirrorConnectorsIntegrationSSLTest`, as it makes sense to run simple validation in SSL setup.
Thanks and would like to hear more thoughts and feedback.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc commented on a change in pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc commented on a change in pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#discussion_r535846145
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationBaseTest.java
##########
@@ -0,0 +1,617 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.Config;
+import org.apache.kafka.clients.admin.ConfigEntry;
+import org.apache.kafka.clients.admin.DescribeConfigsResult;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.clients.CommonClientConfigs;
+import org.apache.kafka.common.config.ConfigResource;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.config.SslConfigs;
+import org.apache.kafka.common.config.types.Password;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.connector.Connector;
+import org.apache.kafka.connect.mirror.MirrorClient;
+import org.apache.kafka.connect.mirror.MirrorHeartbeatConnector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.MirrorSourceConnector;
+import org.apache.kafka.connect.mirror.SourceAndTarget;
+import org.apache.kafka.connect.mirror.MirrorCheckpointConnector;
+import org.apache.kafka.connect.util.clusters.EmbeddedConnectCluster;
+import org.apache.kafka.connect.util.clusters.EmbeddedKafkaCluster;
+import org.apache.kafka.test.IntegrationTest;
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertNotNull;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import static org.apache.kafka.connect.mirror.TestUtils.generateRecords;
+
+/**
+ * Tests MM2 replication and failover/failback logic.
+ *
+ * MM2 is configured with active/active replication between two Kafka clusters. Tests validate that
+ * records sent to either cluster arrive at the other cluster. Then, a consumer group is migrated from
+ * one cluster to the other and back. Tests validate that consumer offsets are translated and replicated
+ * between clusters during this failover and failback.
+ */
+@Category(IntegrationTest.class)
+public abstract class MirrorConnectorsIntegrationBaseTest {
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationBaseTest.class);
+
+ private static final int NUM_RECORDS_PER_PARTITION = 10;
+ private static final int NUM_PARTITIONS = 10;
+ private static final int NUM_RECORDS_PRODUCED = NUM_PARTITIONS * NUM_RECORDS_PER_PARTITION;
+ private static final int RECORD_TRANSFER_DURATION_MS = 30_000;
+ private static final int CHECKPOINT_DURATION_MS = 20_000;
+ private static final int RECORD_CONSUME_DURATION_MS = 20_000;
+ private static final int OFFSET_SYNC_DURATION_MS = 30_000;
+ private static final int NUM_WORKERS = 3;
+ private static final int CONSUMER_POLL_TIMEOUT_MS = 500;
+ private static final int BROKER_RESTART_TIMEOUT_MS = 10_000;
+ private static final long DEFAULT_PRODUCE_SEND_DURATION_MS = TimeUnit.SECONDS.toMillis(120);
+ private static final String PRIMARY_CLUSTER_ALIAS = "primary";
+ private static final String BACKUP_CLUSTER_ALIAS = "backup";
+ private static final List<Class<? extends Connector>> CONNECTOR_LIST =
+ Arrays.asList(MirrorSourceConnector.class, MirrorCheckpointConnector.class, MirrorHeartbeatConnector.class);
+
+ private Map<String, String> mm2Props;
+ private MirrorMakerConfig mm2Config;
+ private EmbeddedConnectCluster primary;
+ private EmbeddedConnectCluster backup;
+
+ private final AtomicBoolean exited = new AtomicBoolean(false);
+ protected Properties primaryBrokerProps = new Properties();
+ protected Properties backupBrokerProps = new Properties();
+ private Map<String, String> primaryWorkerProps = new HashMap<>();
+ private Map<String, String> backupWorkerProps = new HashMap<>();
+ abstract Map<String, Object> getSslConfig();
+
+ protected void startClusters() throws InterruptedException {
+ primaryBrokerProps.put("auto.create.topics.enable", "false");
+ backupBrokerProps.put("auto.create.topics.enable", "false");
+
+ mm2Props = basicMM2Config();
+
+ final Map<String, Object> sslConfig = getSslConfig();
+ if (sslConfig != null) {
+ Properties sslProps = new Properties();
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, sslConfig.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG));
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, ((Password) sslConfig.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)).value());
+ sslProps.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL");
+
+ // set SSL config for kafka connect worker
+ backupWorkerProps.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> BACKUP_CLUSTER_ALIAS + "." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ // set SSL config for producer used by source task in MM2
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> BACKUP_CLUSTER_ALIAS + ".producer." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ }
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+ primaryWorkerProps = mm2Config.workerConfig(new SourceAndTarget(BACKUP_CLUSTER_ALIAS, PRIMARY_CLUSTER_ALIAS));
+ backupWorkerProps.putAll(mm2Config.workerConfig(new SourceAndTarget(PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS)));
+
+ primary = new EmbeddedConnectCluster.Builder()
+ .name(PRIMARY_CLUSTER_ALIAS + "-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(primaryBrokerProps)
+ .workerProps(primaryWorkerProps)
+ .build();
+
+ backup = new EmbeddedConnectCluster.Builder()
+ .name(BACKUP_CLUSTER_ALIAS + "-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(backupBrokerProps)
+ .workerProps(backupWorkerProps)
+ .build();
+
+ primary.start();
+ primary.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of " + PRIMARY_CLUSTER_ALIAS + "-connect-cluster did not start in time.");
+
+ backup.start();
+ backup.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of " + BACKUP_CLUSTER_ALIAS + "-connect-cluster did not start in time.");
+
+ createTopics();
+
+ warmUpConsumer();
+
+ log.info(PRIMARY_CLUSTER_ALIAS + " REST service: {}", primary.endpointForResource("connectors"));
+ log.info(BACKUP_CLUSTER_ALIAS + " REST service: {}", backup.endpointForResource("connectors"));
+ log.info(PRIMARY_CLUSTER_ALIAS + " brokers: {}", primary.kafka().bootstrapServers());
+ log.info(BACKUP_CLUSTER_ALIAS + " brokers: {}", backup.kafka().bootstrapServers());
+
+ // now that the brokers are running, we can finish setting up the Connectors
+ mm2Props.put(PRIMARY_CLUSTER_ALIAS + ".bootstrap.servers", primary.kafka().bootstrapServers());
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + ".bootstrap.servers", backup.kafka().bootstrapServers());
+
+ Exit.setExitProcedure((status, errorCode) -> exited.set(true));
+ }
+
+ public void shutdownClusters() {
+ for (String x : primary.connectors()) {
+ primary.deleteConnector(x);
+ }
+ for (String x : backup.connectors()) {
+ backup.deleteConnector(x);
+ }
+ deleteAllTopics(primary.kafka());
+ deleteAllTopics(backup.kafka());
+ primary.stop();
+ backup.stop();
+ try {
+ assertFalse(exited.get());
+ } finally {
+ Exit.resetExitProcedure();
+ }
+ }
+
+ @Test
+ public void testReplication() throws InterruptedException {
+ produceMessages(primary, "test-topic-1");
+ produceMessages(backup, "test-topic-1");
+ String consumerGroupName = "consumer-group-testReplication";
+ Map<String, Object> consumerProps = new HashMap<String, Object>() {{
+ put("group.id", consumerGroupName);
+ put("auto.offset.reset", "latest");
+ }};
+ // create consumers before starting the connectors so we don't need to wait for discovery
+ Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps, "test-topic-1");
+ waitForConsumingAllRecords(primaryConsumer, 0);
+
+ Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(consumerProps, "test-topic-1");
+ waitForConsumingAllRecords(backupConsumer, 0);
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS);
+ waitUntilMirrorMakerIsRunning(primary, CONNECTOR_LIST, mm2Config, BACKUP_CLUSTER_ALIAS, PRIMARY_CLUSTER_ALIAS);
+
+ MirrorClient primaryClient = new MirrorClient(mm2Config.clientConfig(PRIMARY_CLUSTER_ALIAS));
+ MirrorClient backupClient = new MirrorClient(mm2Config.clientConfig(BACKUP_CLUSTER_ALIAS));
+
+ assertEquals("topic config was not synced", TopicConfig.CLEANUP_POLICY_COMPACT,
+ getTopicConfig(backup.kafka(), "primary.test-topic-1", TopicConfig.CLEANUP_POLICY_CONFIG));
+
+ assertEquals("Records were not produced to primary cluster.", NUM_RECORDS_PRODUCED,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "test-topic-1").count());
+ assertEquals("Records were not replicated to backup cluster.", NUM_RECORDS_PRODUCED,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "primary.test-topic-1").count());
+ assertEquals("Records were not produced to backup cluster.", NUM_RECORDS_PRODUCED,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "test-topic-1").count());
+ assertEquals("Records were not replicated to primary cluster.", NUM_RECORDS_PRODUCED,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "backup.test-topic-1").count());
+
+ assertEquals("Primary cluster doesn't have all records from both clusters.", NUM_RECORDS_PRODUCED * 2,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED * 2, RECORD_TRANSFER_DURATION_MS, "backup.test-topic-1", "test-topic-1").count());
+ assertEquals("Backup cluster doesn't have all records from both clusters.", NUM_RECORDS_PRODUCED * 2,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED * 2, RECORD_TRANSFER_DURATION_MS, "primary.test-topic-1", "test-topic-1").count());
+
+ assertTrue("Heartbeats were not emitted to primary cluster.", primary.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "heartbeats").count() > 0);
+ assertTrue("Heartbeats were not emitted to backup cluster.", backup.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "heartbeats").count() > 0);
+ assertTrue("Heartbeats were not replicated downstream to backup cluster.", backup.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "primary.heartbeats").count() > 0);
+ assertTrue("Heartbeats were not replicated downstream to primary cluster.", primary.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "backup.heartbeats").count() > 0);
+
+ assertTrue("Did not find upstream primary cluster.", backupClient.upstreamClusters().contains(PRIMARY_CLUSTER_ALIAS));
+ assertEquals("Did not calculate replication hops correctly.", 1, backupClient.replicationHops(PRIMARY_CLUSTER_ALIAS));
+ assertTrue("Did not find upstream backup cluster.", primaryClient.upstreamClusters().contains(BACKUP_CLUSTER_ALIAS));
+ assertEquals("Did not calculate replication hops correctly.", 1, primaryClient.replicationHops(BACKUP_CLUSTER_ALIAS));
+ assertTrue("Checkpoints were not emitted downstream to backup cluster.", backup.kafka().consume(1,
+ CHECKPOINT_DURATION_MS, "primary.checkpoints.internal").count() > 0);
+
+ Map<TopicPartition, OffsetAndMetadata> backupOffsets = backupClient.remoteConsumerOffsets(consumerGroupName, PRIMARY_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS));
+
+ assertTrue("Offsets not translated downstream to backup cluster. Found: " + backupOffsets, backupOffsets.containsKey(
+ new TopicPartition("primary.test-topic-1", 0)));
+
+ // Failover consumer group to backup cluster.
+ primaryConsumer = backup.kafka().createConsumer(Collections.singletonMap("group.id", consumerGroupName));
+ primaryConsumer.assign(backupOffsets.keySet());
+ backupOffsets.forEach(primaryConsumer::seek);
+ primaryConsumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+ primaryConsumer.commitAsync();
+
+ assertTrue("Consumer failedover to zero offset.", primaryConsumer.position(new TopicPartition("primary.test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedover beyond expected offset.", primaryConsumer.position(
+ new TopicPartition("primary.test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+ assertTrue("Checkpoints were not emitted upstream to primary cluster.", primary.kafka().consume(1,
+ CHECKPOINT_DURATION_MS, "backup.checkpoints.internal").count() > 0);
+
+ primaryConsumer.close();
+
+ waitForCondition(() -> {
+ try {
+ return primaryClient.remoteConsumerOffsets(consumerGroupName, BACKUP_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS)).containsKey(new TopicPartition("backup.test-topic-1", 0));
+ } catch (Throwable e) {
+ return false;
+ }
+ }, CHECKPOINT_DURATION_MS, "Offsets not translated downstream to primary cluster.");
+
+ waitForCondition(() -> {
+ try {
+ return primaryClient.remoteConsumerOffsets(consumerGroupName, BACKUP_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS)).containsKey(new TopicPartition("test-topic-1", 0));
+ } catch (Throwable e) {
+ return false;
+ }
+ }, CHECKPOINT_DURATION_MS, "Offsets not translated upstream to primary cluster.");
+
+ Map<TopicPartition, OffsetAndMetadata> primaryOffsets = primaryClient.remoteConsumerOffsets(consumerGroupName, BACKUP_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS));
+
+ // Failback consumer group to primary cluster
+ backupConsumer = primary.kafka().createConsumer(Collections.singletonMap("group.id", consumerGroupName));
+ backupConsumer.assign(primaryOffsets.keySet());
+ primaryOffsets.forEach(backupConsumer::seek);
+ backupConsumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+ backupConsumer.commitAsync();
+
+ assertTrue("Consumer failedback to zero upstream offset.", backupConsumer.position(new TopicPartition("test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedback to zero downstream offset.", backupConsumer.position(new TopicPartition("backup.test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedback beyond expected upstream offset.", backupConsumer.position(
+ new TopicPartition("test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+ assertTrue("Consumer failedback beyond expected downstream offset.", backupConsumer.position(
+ new TopicPartition("backup.test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+
+ backupConsumer.close();
+
+ // create more matching topics
+ primary.kafka().createTopic("test-topic-2", NUM_PARTITIONS);
+ backup.kafka().createTopic("test-topic-3", NUM_PARTITIONS);
+
+ // only produce messages to the first partition
+ produceMessages(primary, "test-topic-2", 1);
+ produceMessages(backup, "test-topic-3", 1);
+
+ // expect total consumed messages equals to NUM_RECORDS_PER_PARTITION
+ assertEquals("Records were not produced to primary cluster.", NUM_RECORDS_PER_PARTITION,
+ primary.kafka().consume(NUM_RECORDS_PER_PARTITION, RECORD_TRANSFER_DURATION_MS, "test-topic-2").count());
+ assertEquals("Records were not produced to backup cluster.", NUM_RECORDS_PER_PARTITION,
+ backup.kafka().consume(NUM_RECORDS_PER_PARTITION, RECORD_TRANSFER_DURATION_MS, "test-topic-3").count());
+
+ assertEquals("New topic was not replicated to primary cluster.", NUM_RECORDS_PER_PARTITION,
+ primary.kafka().consume(NUM_RECORDS_PER_PARTITION, 2 * RECORD_TRANSFER_DURATION_MS, "backup.test-topic-3").count());
+ assertEquals("New topic was not replicated to backup cluster.", NUM_RECORDS_PER_PARTITION,
+ backup.kafka().consume(NUM_RECORDS_PER_PARTITION, 2 * RECORD_TRANSFER_DURATION_MS, "primary.test-topic-2").count());
+
+ }
+
+ @Test
+ public void testReplicationWithEmptyPartition() throws Exception {
+ String consumerGroupName = "consumer-group-testReplicationWithEmptyPartition";
+ Map<String, Object> consumerProps = Collections.singletonMap("group.id", consumerGroupName);
+
+ // create topic
+ String topic = "test-topic-with-empty-partition";
+ primary.kafka().createTopic(topic, NUM_PARTITIONS);
+
+ // produce to all test-topic-empty's partitions, except the last partition
+ produceMessages(primary, topic, NUM_PARTITIONS - 1);
+
+ // consume before starting the connectors so we don't need to wait for discovery
+ int expectedRecords = NUM_RECORDS_PER_PARTITION * (NUM_PARTITIONS - 1);
+ try (Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps, topic)) {
+ waitForConsumingAllRecords(primaryConsumer, expectedRecords);
+ }
+
+ // one way replication from primary to backup
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + "->" + PRIMARY_CLUSTER_ALIAS + ".enabled", "false");
+ mm2Config = new MirrorMakerConfig(mm2Props);
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS);
+
+ // sleep few seconds to have MM2 finish replication so that "end" consumer will consume some record
+ Thread.sleep(TimeUnit.SECONDS.toMillis(3));
+
+ // consume all records from backup cluster
+ try (Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(consumerProps,
+ PRIMARY_CLUSTER_ALIAS + "." + topic)) {
+ waitForConsumingAllRecords(backupConsumer, expectedRecords);
+ }
+
+ Admin backupClient = backup.kafka().createAdminClient();
+ // retrieve the consumer group offset from backup cluster
+ Map<TopicPartition, OffsetAndMetadata> remoteOffsets =
+ backupClient.listConsumerGroupOffsets(consumerGroupName).partitionsToOffsetAndMetadata().get();
+ // pinpoint the offset of the last partition which does not receive records
+ OffsetAndMetadata offset = remoteOffsets.get(new TopicPartition(PRIMARY_CLUSTER_ALIAS + "." + topic, NUM_PARTITIONS - 1));
+ // offset of the last partition should exist, but its value should be 0
+ assertNotNull("Offset of last partition was not replicated", offset);
+ assertEquals("Offset of last partition is not zero", 0, offset.offset());
+ }
+
+ @Test
+ public void testOneWayReplicationWithAutoOffsetSync() throws InterruptedException {
+ produceMessages(primary, "test-topic-1");
+ String consumerGroupName = "consumer-group-testOneWayReplicationWithAutoOffsetSync";
+ Map<String, Object> consumerProps = new HashMap<String, Object>() {{
+ put("group.id", consumerGroupName);
+ put("auto.offset.reset", "earliest");
+ }};
+ // create consumers before starting the connectors so we don't need to wait for discovery
+ try (Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps,
+ "test-topic-1")) {
+ // we need to wait for consuming all the records for MM2 replicating the expected offsets
+ waitForConsumingAllRecords(primaryConsumer, NUM_RECORDS_PRODUCED);
+ }
+
+ // enable automated consumer group offset sync
+ mm2Props.put("sync.group.offsets.enabled", "true");
+ mm2Props.put("sync.group.offsets.interval.seconds", "1");
+ // one way replication from primary to backup
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + "->" + PRIMARY_CLUSTER_ALIAS + ".enabled", "false");
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS);
+
+ // create a consumer at backup cluster with same consumer group Id to consume 1 topic
+ Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(
+ consumerProps, "primary.test-topic-1");
+
+ waitForConsumerGroupOffsetSync(backup, backupConsumer, Collections.singletonList("primary.test-topic-1"),
+ consumerGroupName, NUM_RECORDS_PRODUCED);
+
+ ConsumerRecords<byte[], byte[]> records = backupConsumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+
+ // the size of consumer record should be zero, because the offsets of the same consumer group
+ // have been automatically synchronized from primary to backup by the background job, so no
+ // more records to consume from the replicated topic by the same consumer group at backup cluster
+ assertEquals("consumer record size is not zero", 0, records.count());
+
+ // now create a new topic in primary cluster
+ primary.kafka().createTopic("test-topic-2", NUM_PARTITIONS);
+ backup.kafka().createTopic("primary.test-topic-2", 1);
+ // produce some records to the new topic in primary cluster
+ produceMessages(primary, "test-topic-2");
+
+ // create a consumer at primary cluster to consume the new topic
+ try (Consumer<byte[], byte[]> consumer1 = primary.kafka().createConsumerAndSubscribeTo(Collections.singletonMap(
+ "group.id", "consumer-group-1"), "test-topic-2")) {
+ // we need to wait for consuming all the records for MM2 replicating the expected offsets
+ waitForConsumingAllRecords(consumer1, NUM_RECORDS_PRODUCED);
+ }
+
+ // create a consumer at backup cluster with same consumer group Id to consume old and new topic
+ backupConsumer = backup.kafka().createConsumerAndSubscribeTo(Collections.singletonMap(
+ "group.id", consumerGroupName), "primary.test-topic-1", "primary.test-topic-2");
+
+ waitForConsumerGroupOffsetSync(backup, backupConsumer, Arrays.asList("primary.test-topic-1", "primary.test-topic-2"),
+ consumerGroupName, NUM_RECORDS_PRODUCED);
+
+ records = backupConsumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+ // similar reasoning as above, no more records to consume by the same consumer group at backup cluster
+ assertEquals("consumer record size is not zero", 0, records.count());
+ backupConsumer.close();
+ }
+
+ /*
+ * launch the connectors on kafka connect cluster and check if they are running
+ */
+ private static void waitUntilMirrorMakerIsRunning(EmbeddedConnectCluster connectCluster,
+ List<Class<? extends Connector>> connectorClasses, MirrorMakerConfig mm2Config,
+ String primary, String backup) throws InterruptedException {
+ for (int i = 0; i < connectorClasses.size(); i++) {
+ String connector = connectorClasses.get(i).getSimpleName();
+ connectCluster.configureConnector(connector, mm2Config.connectorBaseConfig(
+ new SourceAndTarget(primary, backup), connectorClasses.get(i)));
+ }
+
+ // we wait for the connector and tasks to come up for each connector, so that when we do the
+ // actual testing, we are certain that the tasks are up and running; this will prevent
+ // flaky tests where the connector and tasks didn't start up in time for the tests to be run
+ List<String> connectorNames = connectorClasses.stream().map(x -> x.getSimpleName())
+ .collect(Collectors.toList());
+ for (String connector : connectorNames) {
+ connectCluster.assertions().assertConnectorAndAtLeastNumTasksAreRunning(connector, 1,
+ "Connector " + connector + " tasks did not start in time on cluster: " + connectCluster);
+ }
+ }
+
+ /*
+ * delete all topics of the input kafka cluster
+ */
+ private static void deleteAllTopics(EmbeddedKafkaCluster cluster) {
+ Admin client = cluster.createAdminClient();
+ try {
+ client.deleteTopics(client.listTopics().names().get());
+ } catch (Throwable e) {
+ // should not run into exception normally. In case of Exception,
+ // simply fail the test and investigate
+ }
+ }
+
+ /*
+ * retrieve the config value based on the input cluster, topic and config name
+ */
+ private static String getTopicConfig(EmbeddedKafkaCluster cluster, String topic, String configName) {
+ Admin client = cluster.createAdminClient();
+ Collection<ConfigResource> cr = Collections.singleton(
+ new ConfigResource(ConfigResource.Type.TOPIC, topic));
+ try {
+ DescribeConfigsResult configsResult = client.describeConfigs(cr);
+ Config allConfigs = (Config) configsResult.all().get().values().toArray()[0];
+ Iterator<ConfigEntry> configIterator = allConfigs.entries().iterator();
Review comment:
`allConfigs` is a `java.util.Collection` object and seems does not directly support `get()` https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] rhauch commented on pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
rhauch commented on pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#issuecomment-741519589
@ning2008wisc, https://issues.apache.org/jira/browse/KAFKA-10811 and #9698 have been merged (to multiple branches).
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] mimaison commented on pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
mimaison commented on pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#issuecomment-730467364
> If we have to control the complexity, I would prefer to drop testWithBrokerRestart and keep MirrorConnectorsIntegrationSSLTest, as it makes sense to run simple validation in SSL setup.
I think that would be a good idea. We can try to introduce this test in a follow up PR.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc edited a comment on pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc edited a comment on pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#issuecomment-714955565
Thanks @mimaison for your high-level advice and detailed review.
(1) I responded to your every comments. A "thumb-up" means I made the suggested change
(2) regarding the increased complexity, here is my analysis for each test case
(a) `testReplication`: This is an existing test and no new stuff are added, except checking if topic config are also mirrored. If we believe the topic config validation is trivial, I am more than happy to remove it
(b) `testReplicationWithEmptyPartition`: This is an existing test and no new stuff are added
(c) `testOneWayReplicationWithAutoOffsetSync`: This is an existing test and no new stuff are added
(d) `testWithBrokerRestart`: This is a **new** test, which introduced background producer and consumer, called `ThreadedProducer` and `ThreadedConsumer`. The purpose of background producer and consumer is to better test the failure case to avoid serialization (produce -> broker restart -> consumer) which can not reveal the insight that consumers consume the same records more than once when broker failure happens.
(e) `MirrorConnectorsIntegrationSSLTest`: This is a **new** test and it should be pretty lean and neat.
In addition, the **new** base test class `MirrorConnectorsIntegrationBaseTest` follows the existing practice of K-stream integration test structure https://github.com/apache/kafka/blob/trunk/streams/src/test/java/org/apache/kafka/streams/integration/ResetIntegrationWithSslTest.java#L37 so I assume it is likely the right way tp structure tests with more than one scenarios (SSL v.s. non-SSL)
If we have to control the complexity, I would prefer to drop `testWithBrokerRestart` and keep `MirrorConnectorsIntegrationSSLTest`, as it makes sense to run simple validation in SSL setup.
Thanks and would like to hear more thoughts and feedback.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc commented on a change in pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc commented on a change in pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#discussion_r527391154
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationBaseTest.java
##########
@@ -0,0 +1,407 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.CommonClientConfigs;
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.Config;
+import org.apache.kafka.clients.admin.ConfigEntry;
+import org.apache.kafka.clients.admin.DescribeConfigsResult;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.config.ConfigResource;
+import org.apache.kafka.common.config.SslConfigs;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.config.types.Password;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.connector.Connector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.SourceAndTarget;
+import org.apache.kafka.connect.util.clusters.EmbeddedConnectCluster;
+import org.apache.kafka.connect.util.clusters.EmbeddedKafkaCluster;
+import static org.apache.kafka.connect.mirror.TestUtils.expectedRecords;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+import org.apache.kafka.test.IntegrationTest;
+import kafka.server.KafkaConfig$;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import static org.junit.Assert.assertFalse;
+import org.junit.experimental.categories.Category;
+
+/**
+ * Common Test functions for MM2 integration tests
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationBaseTest {
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationBaseTest.class);
+
+ protected static final int NUM_RECORDS_PER_PARTITION = 10;
+ public static final int NUM_PARTITIONS = 10;
+ protected static final int NUM_RECORDS_PRODUCED = NUM_PARTITIONS * NUM_RECORDS_PER_PARTITION;
+ protected static final int RECORD_TRANSFER_DURATION_MS = 30_000;
+ protected static final int CHECKPOINT_DURATION_MS = 20_000;
+ protected static final int RECORD_CONSUME_DURATION_MS = 20_000;
+ protected static final int OFFSET_SYNC_DURATION_MS = 30_000;
+ protected static final int NUM_WORKERS = 3;
+ protected static final int CONSUMER_POLL_TIMEOUT_MS = 500;
+ protected static final int BROKER_RESTART_TIMEOUT_MS = 10_000;
+ protected static final String PRIMARY_CLUSTER_ALIAS = "primary";
+ protected static final String BACKUP_CLUSTER_ALIAS = "backup";
+
+ protected Map<String, String> mm2Props;
+ protected MirrorMakerConfig mm2Config;
+ protected EmbeddedConnectCluster primary;
+ protected EmbeddedConnectCluster backup;
+
+ private final AtomicBoolean exited = new AtomicBoolean(false);
+ private Properties primaryBrokerProps = new Properties();
+ protected Properties backupBrokerProps = new Properties();
+ private Map<String, String> primaryWorkerProps = new HashMap<>();
+ private Map<String, String> backupWorkerProps = new HashMap<>();
+ private Properties sslProps = new Properties();
+
+ private void loadSslPropsFromBrokerConfig() {
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, backupBrokerProps.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG));
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, ((Password) backupBrokerProps.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)).value());
+ sslProps.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL");
+ }
+
+ protected void setSslConfig() {
+ // set SSL config for kafka connect worker
+ backupWorkerProps.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> BACKUP_CLUSTER_ALIAS + "." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ // set SSL config for producer used by source task in MM2
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> BACKUP_CLUSTER_ALIAS + ".producer." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ }
+
+ protected void startClusters() throws InterruptedException {
+ primaryBrokerProps.put("auto.create.topics.enable", "false");
+ backupBrokerProps.put("auto.create.topics.enable", "false");
+
+ mm2Props = basicMM2Config();
+
+ // if backup kafka cluster contains ssl config, enable ssl of kafka connect and mm2
+ final Object listeners = backupBrokerProps.get(KafkaConfig$.MODULE$.ListenersProp());
+ if (listeners != null && listeners.toString().contains("SSL")) {
+ loadSslPropsFromBrokerConfig();
+ setSslConfig();
+ }
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+ primaryWorkerProps = mm2Config.workerConfig(new SourceAndTarget(BACKUP_CLUSTER_ALIAS, PRIMARY_CLUSTER_ALIAS));
+ backupWorkerProps.putAll(mm2Config.workerConfig(new SourceAndTarget(PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS)));
+
+ primary = new EmbeddedConnectCluster.Builder()
+ .name(PRIMARY_CLUSTER_ALIAS + "-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(primaryBrokerProps)
+ .workerProps(primaryWorkerProps)
+ .build();
+
+ backup = new EmbeddedConnectCluster.Builder()
+ .name(BACKUP_CLUSTER_ALIAS + "-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(backupBrokerProps)
+ .workerProps(backupWorkerProps)
+ .build();
+
+ primary.start();
+ primary.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of " + PRIMARY_CLUSTER_ALIAS + "-connect-cluster did not start in time.");
+
+ backup.start();
+ backup.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of " + BACKUP_CLUSTER_ALIAS + "-connect-cluster did not start in time.");
+
+ createTopics();
+
+ dummyConsumption();
+
+ log.info(PRIMARY_CLUSTER_ALIAS + " REST service: {}", primary.endpointForResource("connectors"));
+ log.info(BACKUP_CLUSTER_ALIAS + " REST service: {}", backup.endpointForResource("connectors"));
+ log.info(PRIMARY_CLUSTER_ALIAS + " brokers: {}", primary.kafka().bootstrapServers());
+ log.info(BACKUP_CLUSTER_ALIAS + " brokers: {}", backup.kafka().bootstrapServers());
+
+ // now that the brokers are running, we can finish setting up the Connectors
+ mm2Props.put(PRIMARY_CLUSTER_ALIAS + ".bootstrap.servers", primary.kafka().bootstrapServers());
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + ".bootstrap.servers", backup.kafka().bootstrapServers());
+
+ Exit.setExitProcedure((status, errorCode) -> exited.set(true));
+ }
+
+ public void shutdownClusters() {
+ for (String x : primary.connectors()) {
+ primary.deleteConnector(x);
+ }
+ for (String x : backup.connectors()) {
+ backup.deleteConnector(x);
+ }
+ deleteAllTopics(primary.kafka());
+ deleteAllTopics(backup.kafka());
+ primary.stop();
+ backup.stop();
+ try {
+ assertFalse(exited.get());
+ } finally {
+ Exit.resetExitProcedure();
+ }
+ }
+ /*
+ * launch the connectors on kafka connect cluster and check if they are running
+ */
+ protected static void waitUntilMirrorMakerIsRunning(EmbeddedConnectCluster connectCluster,
+ List<Class<? extends Connector>> connectorClasses, MirrorMakerConfig mm2Config,
+ String primary, String backup) throws InterruptedException {
+ for (int i = 0; i < connectorClasses.size(); i++) {
+ String connector = connectorClasses.get(i).getSimpleName();
+ connectCluster.configureConnector(connector, mm2Config.connectorBaseConfig(
+ new SourceAndTarget(primary, backup), connectorClasses.get(i)));
+ }
+
+ // we wait for the connector and tasks to come up for each connector, so that when we do the
+ // actual testing, we are certain that the tasks are up and running; this will prevent
+ // flaky tests where the connector and tasks didn't start up in time for the tests to be run
+ List<String> connectorNames = connectorClasses.stream().map(x -> x.getSimpleName())
+ .collect(Collectors.toList());
+ for (String connector : connectorNames) {
+ connectCluster.assertions().assertConnectorAndAtLeastNumTasksAreRunning(connector, 1,
+ "Connector " + connector + " tasks did not start in time on cluster: " + connectCluster);
+ }
+ }
+
+ /*
+ * delete all topics of the input kafka cluster
+ */
+ protected static void deleteAllTopics(EmbeddedKafkaCluster cluster) {
+ Admin client = cluster.createAdminClient();
+ try {
+ client.deleteTopics(client.listTopics().names().get());
+ } catch (Throwable e) {
+ // should not run into exception normally. In case of Exception,
+ // simply fail the test and investigate
+ }
+ }
+
+ /*
+ * retrieve the config value based on the input cluster, topic and config name
+ */
+ protected static String getTopicConfig(EmbeddedKafkaCluster cluster, String topic, String configName) {
+ Admin client = cluster.createAdminClient();
+ Collection<ConfigResource> cr = Collections.singleton(
+ new ConfigResource(ConfigResource.Type.TOPIC, topic));
+ try {
+ DescribeConfigsResult configsResult = client.describeConfigs(cr);
+ Config allConfigs = (Config) configsResult.all().get().values().toArray()[0];
+ Iterator<ConfigEntry> configIterator = allConfigs.entries().iterator();
+ while (configIterator.hasNext()) {
+ ConfigEntry currentConfig = configIterator.next();
+ if (currentConfig.name().equals(configName)) {
+ return currentConfig.value();
+ }
+ }
+ } catch (Throwable e) {
+ // should not run into exception normally. In case of Exception,
+ // simply fail the test and investigate
+ }
+ return null;
+ }
+
+ /*
+ * produce messages to the cluster and topic
+ */
+ protected void produceMessages(EmbeddedConnectCluster cluster, String topicName) {
+ Map<String, String> recordSent = expectedRecords(NUM_RECORDS_PRODUCED);
+ for (Map.Entry<String, String> entry : recordSent.entrySet()) {
+ cluster.kafka().produce(topicName, entry.getKey(), entry.getValue());
+ }
+ }
+
+ /*
+ * produce messages to the cluster and topic partition less than numPartitions
+ */
+ protected void produceMessages(EmbeddedConnectCluster cluster, String topicName, int numPartitions) {
+ int cnt = 0;
+ for (int r = 0; r < NUM_RECORDS_PER_PARTITION; r++)
+ for (int p = 0; p < numPartitions; p++)
+ cluster.kafka().produce(topicName, p, "key", "value-" + cnt++);
+ }
+
+ /*
+ * given consumer group, topics and expected number of records, make sure the consumer group
+ * offsets are eventually synced to the expected offset numbers
+ */
+ protected static <T> void waitForConsumerGroupOffsetSync(EmbeddedConnectCluster connect,
+ Consumer<T, T> consumer, List<String> topics, String consumerGroupId, int numRecords)
+ throws InterruptedException {
+ Admin adminClient = connect.kafka().createAdminClient();
+ List<TopicPartition> tps = new ArrayList<>(NUM_PARTITIONS * topics.size());
+ for (int partitionIndex = 0; partitionIndex < NUM_PARTITIONS; partitionIndex++) {
+ for (String topic : topics) {
+ tps.add(new TopicPartition(topic, partitionIndex));
+ }
+ }
+ long expectedTotalOffsets = numRecords * topics.size();
+
+ waitForCondition(() -> {
+ Map<TopicPartition, OffsetAndMetadata> consumerGroupOffsets =
+ adminClient.listConsumerGroupOffsets(consumerGroupId).partitionsToOffsetAndMetadata().get();
+ long consumerGroupOffsetTotal = consumerGroupOffsets.values().stream()
+ .mapToLong(metadata -> metadata.offset()).sum();
+
+ Map<TopicPartition, Long> offsets = consumer.endOffsets(tps, Duration.ofMillis(500));
+ long totalOffsets = offsets.values().stream().mapToLong(l -> l).sum();
+
+ // make sure the consumer group offsets are synced to expected number
+ return totalOffsets == expectedTotalOffsets && consumerGroupOffsetTotal > 0;
+ }, OFFSET_SYNC_DURATION_MS, "Consumer group offset sync is not complete in time");
+ }
+
+ /*
+ * make sure the consumer to consume expected number of records
+ */
+ protected static <T> void waitForConsumingAllRecords(Consumer<T, T> consumer, int numExpectedRecords)
+ throws InterruptedException {
+ final AtomicInteger totalConsumedRecords = new AtomicInteger(0);
+ waitForCondition(() -> {
+ ConsumerRecords<T, T> records = consumer.poll(Duration.ofMillis(500));
+ return numExpectedRecords == totalConsumedRecords.addAndGet(records.count());
+ }, RECORD_CONSUME_DURATION_MS, "Consumer cannot consume all records in time");
+ consumer.commitSync();
+ consumer.close();
+ }
+
+ /*
+ * MM2 config to use in integration tests
+ */
+ private static Map<String, String> basicMM2Config() {
+ Map<String, String> mm2Props = new HashMap<>();
+ mm2Props.put("clusters", PRIMARY_CLUSTER_ALIAS + ", " + BACKUP_CLUSTER_ALIAS);
+ mm2Props.put("max.tasks", "10");
+ mm2Props.put("topics", "test-topic-.*, primary.test-topic-.*, backup.test-topic-.*");
+ mm2Props.put("groups", "consumer-group-.*");
+ mm2Props.put(PRIMARY_CLUSTER_ALIAS + "->" + BACKUP_CLUSTER_ALIAS + ".enabled", "true");
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + "->" + PRIMARY_CLUSTER_ALIAS + ".enabled", "true");
+ mm2Props.put("sync.topic.acls.enabled", "false");
+ mm2Props.put("emit.checkpoints.interval.seconds", "1");
+ mm2Props.put("emit.heartbeats.interval.seconds", "1");
+ mm2Props.put("refresh.topics.interval.seconds", "1");
+ mm2Props.put("refresh.groups.interval.seconds", "1");
+ mm2Props.put("checkpoints.topic.replication.factor", "1");
+ mm2Props.put("heartbeats.topic.replication.factor", "1");
+ mm2Props.put("offset-syncs.topic.replication.factor", "1");
+ mm2Props.put("config.storage.replication.factor", "1");
+ mm2Props.put("offset.storage.replication.factor", "1");
+ mm2Props.put("status.storage.replication.factor", "1");
+ mm2Props.put("replication.factor", "1");
+
+ return mm2Props;
+ }
+
+ /*
+ * restart kafka broker and make sure it is successful
+ */
+ protected void restartKafkaBroker(EmbeddedKafkaCluster kafkaCluster) throws InterruptedException {
+
+ kafkaCluster.stopOnlyKafka();
+ log.trace("issue kafka stop");
+
+ // wait for the broker to be stopped
+ waitForCondition(() -> {
+ return kafkaCluster.runningBrokers().size() == 0;
+ }, BROKER_RESTART_TIMEOUT_MS, "Failed to stop kafka broker within");
+
+ kafkaCluster.startOnlyKafkaOnSamePorts();
+ log.trace("issue kafka start");
+
+ // wait for the kafka brokers to come back online
+ waitForCondition(() -> {
+ return kafkaCluster.runningBrokers().size() > 0;
+ }, BROKER_RESTART_TIMEOUT_MS, "Failed to start kafka broker within");
+ }
+
+ protected void createTopics() {
+ // to verify topic config will be sync-ed across clusters
+ Map<String, String> topicConfig = new HashMap<>();
+ topicConfig.put(TopicConfig.CLEANUP_POLICY_CONFIG, TopicConfig.CLEANUP_POLICY_COMPACT);
+ // create these topics before starting the connectors so we don't need to wait for discovery
+ primary.kafka().createTopic("test-topic-1", NUM_PARTITIONS, 1, topicConfig);
+ primary.kafka().createTopic("backup.test-topic-1", 1);
+ primary.kafka().createTopic("heartbeats", 1);
+ backup.kafka().createTopic("test-topic-1", NUM_PARTITIONS);
+ backup.kafka().createTopic("primary.test-topic-1", 1);
+ backup.kafka().createTopic("heartbeats", 1);
+ }
+
+ protected KafkaConsumer<String, String> createConsumer(EmbeddedConnectCluster connect, Map<String, Object> consumerProps, String... topics) {
+ Map<String, Object> props = new HashMap<>(consumerProps);
+
+ props.putIfAbsent(ConsumerConfig.GROUP_ID_CONFIG, UUID.randomUUID().toString());
+ props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, connect.kafka().bootstrapServers());
+ props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
+ props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
+ props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
+ props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
+
+ // ssl config
+ if (connect.kafka().sslEnabled()) {
+ props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ }
+ KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
+ consumer.subscribe(Arrays.asList(topics));
+ return consumer;
+ }
+
+ /*
+ * Generate some consumer activity on both clusters to ensure the checkpoint connector always starts promptly
+ */
+ protected void dummyConsumption() throws InterruptedException {
Review comment:
`warmUpConsumper` sounds better?
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc commented on a change in pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc commented on a change in pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#discussion_r527398230
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationTest.java
##########
@@ -0,0 +1,370 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.errors.TimeoutException;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.connector.Connector;
+import org.apache.kafka.connect.mirror.MirrorCheckpointConnector;
+import org.apache.kafka.connect.mirror.MirrorClient;
+import org.apache.kafka.connect.mirror.MirrorHeartbeatConnector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.MirrorSourceConnector;
+import org.apache.kafka.connect.mirror.utils.ThreadedConsumer;
+import org.apache.kafka.connect.mirror.utils.ThreadedProducer;
+
+import org.junit.Before;
+import org.junit.After;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertNotNull;
+
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Collections;
+import java.util.Map;
+import java.util.HashMap;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+import org.apache.kafka.test.IntegrationTest;
+
+/**
+ * Tests MM2 replication and failover/failback logic.
+ *
+ * MM2 is configured with active/active replication between two Kafka clusters. Tests validate that
+ * records sent to either cluster arrive at the other cluster. Then, a consumer group is migrated from
+ * one cluster to the other and back. Tests validate that consumer offsets are translated and replicated
+ * between clusters during this failover and failback.
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationTest extends MirrorConnectorsIntegrationBaseTest {
+
+ private static final List<Class<? extends Connector>> CONNECTOR_LIST =
+ Arrays.asList(MirrorSourceConnector.class, MirrorCheckpointConnector.class, MirrorHeartbeatConnector.class);
+
+ @Before
+ public void setup() throws InterruptedException {
+ startClusters();
+ }
+
+ @After
+ public void close() {
+ shutdownClusters();
+ }
+
+ @Test
+ public void testReplication() throws InterruptedException {
+ produceMessages(primary, "test-topic-1");
+ produceMessages(backup, "test-topic-1");
+ String consumerGroupName = "consumer-group-testReplication";
+ Map<String, Object> consumerProps = new HashMap<String, Object>() {{
+ put("group.id", consumerGroupName);
+ put("auto.offset.reset", "latest");
+ }};
+ // create consumers before starting the connectors so we don't need to wait for discovery
+ Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps, "test-topic-1");
+ waitForConsumingAllRecords(primaryConsumer, 0);
+
+ Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(consumerProps, "test-topic-1");
+ waitForConsumingAllRecords(backupConsumer, 0);
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS);
+ waitUntilMirrorMakerIsRunning(primary, CONNECTOR_LIST, mm2Config, BACKUP_CLUSTER_ALIAS, PRIMARY_CLUSTER_ALIAS);
+
+ MirrorClient primaryClient = new MirrorClient(mm2Config.clientConfig(PRIMARY_CLUSTER_ALIAS));
+ MirrorClient backupClient = new MirrorClient(mm2Config.clientConfig(BACKUP_CLUSTER_ALIAS));
+
+ assertEquals("topic config was not synced", TopicConfig.CLEANUP_POLICY_COMPACT,
+ getTopicConfig(backup.kafka(), "primary.test-topic-1", TopicConfig.CLEANUP_POLICY_CONFIG));
+
+ assertEquals("Records were not produced to primary cluster.", NUM_RECORDS_PRODUCED,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "test-topic-1").count());
+ assertEquals("Records were not replicated to backup cluster.", NUM_RECORDS_PRODUCED,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "primary.test-topic-1").count());
+ assertEquals("Records were not produced to backup cluster.", NUM_RECORDS_PRODUCED,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "test-topic-1").count());
+ assertEquals("Records were not replicated to primary cluster.", NUM_RECORDS_PRODUCED,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "backup.test-topic-1").count());
+
+ assertEquals("Primary cluster doesn't have all records from both clusters.", NUM_RECORDS_PRODUCED * 2,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED * 2, RECORD_TRANSFER_DURATION_MS, "backup.test-topic-1", "test-topic-1").count());
+ assertEquals("Backup cluster doesn't have all records from both clusters.", NUM_RECORDS_PRODUCED * 2,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED * 2, RECORD_TRANSFER_DURATION_MS, "primary.test-topic-1", "test-topic-1").count());
+
+ assertTrue("Heartbeats were not emitted to primary cluster.", primary.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "heartbeats").count() > 0);
+ assertTrue("Heartbeats were not emitted to backup cluster.", backup.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "heartbeats").count() > 0);
+ assertTrue("Heartbeats were not replicated downstream to backup cluster.", backup.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "primary.heartbeats").count() > 0);
+ assertTrue("Heartbeats were not replicated downstream to primary cluster.", primary.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "backup.heartbeats").count() > 0);
+
+ assertTrue("Did not find upstream primary cluster.", backupClient.upstreamClusters().contains(PRIMARY_CLUSTER_ALIAS));
+ assertEquals("Did not calculate replication hops correctly.", 1, backupClient.replicationHops(PRIMARY_CLUSTER_ALIAS));
+ assertTrue("Did not find upstream backup cluster.", primaryClient.upstreamClusters().contains(BACKUP_CLUSTER_ALIAS));
+ assertEquals("Did not calculate replication hops correctly.", 1, primaryClient.replicationHops(BACKUP_CLUSTER_ALIAS));
+ assertTrue("Checkpoints were not emitted downstream to backup cluster.", backup.kafka().consume(1,
+ CHECKPOINT_DURATION_MS, "primary.checkpoints.internal").count() > 0);
+
+ Map<TopicPartition, OffsetAndMetadata> backupOffsets = backupClient.remoteConsumerOffsets(consumerGroupName, PRIMARY_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS));
+
+ assertTrue("Offsets not translated downstream to backup cluster. Found: " + backupOffsets, backupOffsets.containsKey(
+ new TopicPartition("primary.test-topic-1", 0)));
+
+ // Failover consumer group to backup cluster.
+ primaryConsumer = backup.kafka().createConsumer(Collections.singletonMap("group.id", consumerGroupName));
+ primaryConsumer.assign(backupOffsets.keySet());
+ backupOffsets.forEach(primaryConsumer::seek);
+ primaryConsumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+ primaryConsumer.commitAsync();
+
+ assertTrue("Consumer failedover to zero offset.", primaryConsumer.position(new TopicPartition("primary.test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedover beyond expected offset.", primaryConsumer.position(
+ new TopicPartition("primary.test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+ assertTrue("Checkpoints were not emitted upstream to primary cluster.", primary.kafka().consume(1,
+ CHECKPOINT_DURATION_MS, "backup.checkpoints.internal").count() > 0);
+
+ primaryConsumer.close();
+
+ waitForCondition(() -> {
+ try {
+ return primaryClient.remoteConsumerOffsets(consumerGroupName, BACKUP_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS)).containsKey(new TopicPartition("backup.test-topic-1", 0));
+ } catch (Throwable e) {
+ return false;
+ }
+ }, CHECKPOINT_DURATION_MS, "Offsets not translated downstream to primary cluster.");
+
+ waitForCondition(() -> {
+ try {
+ return primaryClient.remoteConsumerOffsets(consumerGroupName, BACKUP_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS)).containsKey(new TopicPartition("test-topic-1", 0));
+ } catch (Throwable e) {
+ return false;
+ }
+ }, CHECKPOINT_DURATION_MS, "Offsets not translated upstream to primary cluster.");
+
+ Map<TopicPartition, OffsetAndMetadata> primaryOffsets = primaryClient.remoteConsumerOffsets(consumerGroupName, BACKUP_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS));
+
+ // Failback consumer group to primary cluster
+ backupConsumer = primary.kafka().createConsumer(Collections.singletonMap("group.id", consumerGroupName));
+ backupConsumer.assign(primaryOffsets.keySet());
+ primaryOffsets.forEach(backupConsumer::seek);
+ backupConsumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+ backupConsumer.commitAsync();
+
+ assertTrue("Consumer failedback to zero upstream offset.", backupConsumer.position(new TopicPartition("test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedback to zero downstream offset.", backupConsumer.position(new TopicPartition("backup.test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedback beyond expected upstream offset.", backupConsumer.position(
+ new TopicPartition("test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+ assertTrue("Consumer failedback beyond expected downstream offset.", backupConsumer.position(
+ new TopicPartition("backup.test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+
+ backupConsumer.close();
+
+ // create more matching topics
+ primary.kafka().createTopic("test-topic-2", NUM_PARTITIONS);
+ backup.kafka().createTopic("test-topic-3", NUM_PARTITIONS);
+
+ // only produce messages to the first partition
+ produceMessages(primary, "test-topic-2", 1);
+ produceMessages(backup, "test-topic-3", 1);
+
+ // expect total consumed messages equals to NUM_RECORDS_PER_PARTITION
+ assertEquals("Records were not produced to primary cluster.", NUM_RECORDS_PER_PARTITION,
+ primary.kafka().consume(NUM_RECORDS_PER_PARTITION, RECORD_TRANSFER_DURATION_MS, "test-topic-2").count());
+ assertEquals("Records were not produced to backup cluster.", NUM_RECORDS_PER_PARTITION,
+ backup.kafka().consume(NUM_RECORDS_PER_PARTITION, RECORD_TRANSFER_DURATION_MS, "test-topic-3").count());
+
+ assertEquals("New topic was not replicated to primary cluster.", NUM_RECORDS_PER_PARTITION,
+ primary.kafka().consume(NUM_RECORDS_PER_PARTITION, 2 * RECORD_TRANSFER_DURATION_MS, "backup.test-topic-3").count());
+ assertEquals("New topic was not replicated to backup cluster.", NUM_RECORDS_PER_PARTITION,
+ backup.kafka().consume(NUM_RECORDS_PER_PARTITION, 2 * RECORD_TRANSFER_DURATION_MS, "primary.test-topic-2").count());
+
+ }
+
+ @Test
+ public void testReplicationWithEmptyPartition() throws Exception {
+ String consumerGroupName = "consumer-group-testReplicationWithEmptyPartition";
+ Map<String, Object> consumerProps = Collections.singletonMap("group.id", consumerGroupName);
+
+ // create topic
+ String topic = "test-topic-with-empty-partition";
+ primary.kafka().createTopic(topic, NUM_PARTITIONS);
+
+ // produce to all test-topic-empty's partitions, except the last partition
+ produceMessages(primary, topic, NUM_PARTITIONS - 1);
+
+ // consume before starting the connectors so we don't need to wait for discovery
+ int expectedRecords = NUM_RECORDS_PER_PARTITION * (NUM_PARTITIONS - 1);
+ try (Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps, topic)) {
+ waitForConsumingAllRecords(primaryConsumer, expectedRecords);
+ }
+
+ // one way replication from primary to backup
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + "->" + PRIMARY_CLUSTER_ALIAS + ".enabled", "false");
+ mm2Config = new MirrorMakerConfig(mm2Props);
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS);
+
+ // sleep few seconds to have MM2 finish replication so that "end" consumer will consume some record
+ Thread.sleep(TimeUnit.SECONDS.toMillis(3));
+
+ // consume all records from backup cluster
+ try (Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(consumerProps,
+ PRIMARY_CLUSTER_ALIAS + "." + topic)) {
+ waitForConsumingAllRecords(backupConsumer, expectedRecords);
+ }
+
+ Admin backupClient = backup.kafka().createAdminClient();
+ // retrieve the consumer group offset from backup cluster
+ Map<TopicPartition, OffsetAndMetadata> remoteOffsets =
+ backupClient.listConsumerGroupOffsets(consumerGroupName).partitionsToOffsetAndMetadata().get();
+ // pinpoint the offset of the last partition which does not receive records
+ OffsetAndMetadata offset = remoteOffsets.get(new TopicPartition(PRIMARY_CLUSTER_ALIAS + "." + topic, NUM_PARTITIONS - 1));
+ // offset of the last partition should exist, but its value should be 0
+ assertNotNull("Offset of last partition was not replicated", offset);
+ assertEquals("Offset of last partition is not zero", 0, offset.offset());
+ }
+
+ @Test
+ public void testOneWayReplicationWithAutoOffsetSync() throws InterruptedException {
+ produceMessages(primary, "test-topic-1");
+ String consumerGroupName = "consumer-group-testOneWayReplicationWithAutoOffsetSync";
+ Map<String, Object> consumerProps = new HashMap<String, Object>() {{
+ put("group.id", consumerGroupName);
+ put("auto.offset.reset", "earliest");
+ }};
+ // create consumers before starting the connectors so we don't need to wait for discovery
+ try (Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps,
+ "test-topic-1")) {
+ // we need to wait for consuming all the records for MM2 replicating the expected offsets
+ waitForConsumingAllRecords(primaryConsumer, NUM_RECORDS_PRODUCED);
+ }
+
+ // enable automated consumer group offset sync
+ mm2Props.put("sync.group.offsets.enabled", "true");
+ mm2Props.put("sync.group.offsets.interval.seconds", "1");
+ // one way replication from primary to backup
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + "->" + PRIMARY_CLUSTER_ALIAS + ".enabled", "false");
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS);
+
+ // create a consumer at backup cluster with same consumer group Id to consume 1 topic
+ Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(
+ consumerProps, "primary.test-topic-1");
+
+ waitForConsumerGroupOffsetSync(backup, backupConsumer, Collections.singletonList("primary.test-topic-1"),
+ consumerGroupName, NUM_RECORDS_PRODUCED);
+
+ ConsumerRecords<byte[], byte[]> records = backupConsumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+
+ // the size of consumer record should be zero, because the offsets of the same consumer group
+ // have been automatically synchronized from primary to backup by the background job, so no
+ // more records to consume from the replicated topic by the same consumer group at backup cluster
+ assertEquals("consumer record size is not zero", 0, records.count());
+
+ // now create a new topic in primary cluster
+ primary.kafka().createTopic("test-topic-2", NUM_PARTITIONS);
+ backup.kafka().createTopic("primary.test-topic-2", 1);
+ // produce some records to the new topic in primary cluster
+ produceMessages(primary, "test-topic-2");
+
+ // create a consumer at primary cluster to consume the new topic
+ try (Consumer<byte[], byte[]> consumer1 = primary.kafka().createConsumerAndSubscribeTo(Collections.singletonMap(
+ "group.id", "consumer-group-1"), "test-topic-2")) {
+ // we need to wait for consuming all the records for MM2 replicating the expected offsets
+ waitForConsumingAllRecords(consumer1, NUM_RECORDS_PRODUCED);
+ }
+
+ // create a consumer at backup cluster with same consumer group Id to consume old and new topic
+ backupConsumer = backup.kafka().createConsumerAndSubscribeTo(Collections.singletonMap(
+ "group.id", consumerGroupName), "primary.test-topic-1", "primary.test-topic-2");
+
+ waitForConsumerGroupOffsetSync(backup, backupConsumer, Arrays.asList("primary.test-topic-1", "primary.test-topic-2"),
+ consumerGroupName, NUM_RECORDS_PRODUCED);
+
+ records = backupConsumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+ // similar reasoning as above, no more records to consume by the same consumer group at backup cluster
+ assertEquals("consumer record size is not zero", 0, records.count());
+ backupConsumer.close();
+ }
+
+ /*
+ * This test is to validate MirrorSourceConnector follows "at most once" delivery guarantee
Review comment:
sorry - it is a typo, should be "at least once". I am removing this test from this PR
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc commented on a change in pull request #9224: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc commented on a change in pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#discussion_r485337316
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/TestUtils.java
##########
@@ -16,12 +16,51 @@
*/
package org.apache.kafka.connect.mirror;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
import java.util.Map;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.Config;
+import org.apache.kafka.clients.admin.ConfigEntry;
+import org.apache.kafka.clients.admin.DescribeConfigsResult;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.config.ConfigResource;
+import org.apache.kafka.connect.util.clusters.EmbeddedConnectCluster;
+import org.apache.kafka.connect.util.clusters.EmbeddedKafkaCluster;
+
+import static org.apache.kafka.connect.mirror.TestUtils.NUM_WORKERS;
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+import static org.apache.kafka.connect.util.clusters.EmbeddedConnectClusterAssertions.CONNECTOR_SETUP_DURATION_MS;
+import static org.junit.Assert.assertTrue;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class TestUtils {
Review comment:
propose `TestUtils` to be the central place to host common functions that will be used by integration tests
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc commented on a change in pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc commented on a change in pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#discussion_r535856935
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationBaseTest.java
##########
@@ -0,0 +1,617 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.Config;
+import org.apache.kafka.clients.admin.ConfigEntry;
+import org.apache.kafka.clients.admin.DescribeConfigsResult;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.clients.CommonClientConfigs;
+import org.apache.kafka.common.config.ConfigResource;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.config.SslConfigs;
+import org.apache.kafka.common.config.types.Password;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.connector.Connector;
+import org.apache.kafka.connect.mirror.MirrorClient;
+import org.apache.kafka.connect.mirror.MirrorHeartbeatConnector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.MirrorSourceConnector;
+import org.apache.kafka.connect.mirror.SourceAndTarget;
+import org.apache.kafka.connect.mirror.MirrorCheckpointConnector;
+import org.apache.kafka.connect.util.clusters.EmbeddedConnectCluster;
+import org.apache.kafka.connect.util.clusters.EmbeddedKafkaCluster;
+import org.apache.kafka.test.IntegrationTest;
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertNotNull;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import static org.apache.kafka.connect.mirror.TestUtils.generateRecords;
+
+/**
+ * Tests MM2 replication and failover/failback logic.
+ *
+ * MM2 is configured with active/active replication between two Kafka clusters. Tests validate that
+ * records sent to either cluster arrive at the other cluster. Then, a consumer group is migrated from
+ * one cluster to the other and back. Tests validate that consumer offsets are translated and replicated
+ * between clusters during this failover and failback.
+ */
+@Category(IntegrationTest.class)
+public abstract class MirrorConnectorsIntegrationBaseTest {
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationBaseTest.class);
+
+ private static final int NUM_RECORDS_PER_PARTITION = 10;
+ private static final int NUM_PARTITIONS = 10;
+ private static final int NUM_RECORDS_PRODUCED = NUM_PARTITIONS * NUM_RECORDS_PER_PARTITION;
+ private static final int RECORD_TRANSFER_DURATION_MS = 30_000;
+ private static final int CHECKPOINT_DURATION_MS = 20_000;
+ private static final int RECORD_CONSUME_DURATION_MS = 20_000;
+ private static final int OFFSET_SYNC_DURATION_MS = 30_000;
+ private static final int NUM_WORKERS = 3;
+ private static final int CONSUMER_POLL_TIMEOUT_MS = 500;
+ private static final int BROKER_RESTART_TIMEOUT_MS = 10_000;
+ private static final long DEFAULT_PRODUCE_SEND_DURATION_MS = TimeUnit.SECONDS.toMillis(120);
+ private static final String PRIMARY_CLUSTER_ALIAS = "primary";
+ private static final String BACKUP_CLUSTER_ALIAS = "backup";
+ private static final List<Class<? extends Connector>> CONNECTOR_LIST =
+ Arrays.asList(MirrorSourceConnector.class, MirrorCheckpointConnector.class, MirrorHeartbeatConnector.class);
+
+ private Map<String, String> mm2Props;
+ private MirrorMakerConfig mm2Config;
+ private EmbeddedConnectCluster primary;
+ private EmbeddedConnectCluster backup;
+
+ private final AtomicBoolean exited = new AtomicBoolean(false);
+ protected Properties primaryBrokerProps = new Properties();
+ protected Properties backupBrokerProps = new Properties();
+ private Map<String, String> primaryWorkerProps = new HashMap<>();
+ private Map<String, String> backupWorkerProps = new HashMap<>();
+ abstract Map<String, Object> getSslConfig();
+
+ protected void startClusters() throws InterruptedException {
+ primaryBrokerProps.put("auto.create.topics.enable", "false");
+ backupBrokerProps.put("auto.create.topics.enable", "false");
+
+ mm2Props = basicMM2Config();
+
+ final Map<String, Object> sslConfig = getSslConfig();
+ if (sslConfig != null) {
+ Properties sslProps = new Properties();
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, sslConfig.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG));
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, ((Password) sslConfig.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)).value());
+ sslProps.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL");
+
+ // set SSL config for kafka connect worker
+ backupWorkerProps.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> BACKUP_CLUSTER_ALIAS + "." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ // set SSL config for producer used by source task in MM2
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> BACKUP_CLUSTER_ALIAS + ".producer." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ }
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+ primaryWorkerProps = mm2Config.workerConfig(new SourceAndTarget(BACKUP_CLUSTER_ALIAS, PRIMARY_CLUSTER_ALIAS));
+ backupWorkerProps.putAll(mm2Config.workerConfig(new SourceAndTarget(PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS)));
+
+ primary = new EmbeddedConnectCluster.Builder()
+ .name(PRIMARY_CLUSTER_ALIAS + "-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(primaryBrokerProps)
+ .workerProps(primaryWorkerProps)
+ .build();
+
+ backup = new EmbeddedConnectCluster.Builder()
+ .name(BACKUP_CLUSTER_ALIAS + "-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(backupBrokerProps)
+ .workerProps(backupWorkerProps)
+ .build();
+
+ primary.start();
+ primary.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of " + PRIMARY_CLUSTER_ALIAS + "-connect-cluster did not start in time.");
+
+ backup.start();
+ backup.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of " + BACKUP_CLUSTER_ALIAS + "-connect-cluster did not start in time.");
+
+ createTopics();
+
+ warmUpConsumer();
+
+ log.info(PRIMARY_CLUSTER_ALIAS + " REST service: {}", primary.endpointForResource("connectors"));
+ log.info(BACKUP_CLUSTER_ALIAS + " REST service: {}", backup.endpointForResource("connectors"));
+ log.info(PRIMARY_CLUSTER_ALIAS + " brokers: {}", primary.kafka().bootstrapServers());
+ log.info(BACKUP_CLUSTER_ALIAS + " brokers: {}", backup.kafka().bootstrapServers());
+
+ // now that the brokers are running, we can finish setting up the Connectors
+ mm2Props.put(PRIMARY_CLUSTER_ALIAS + ".bootstrap.servers", primary.kafka().bootstrapServers());
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + ".bootstrap.servers", backup.kafka().bootstrapServers());
+
+ Exit.setExitProcedure((status, errorCode) -> exited.set(true));
+ }
+
+ public void shutdownClusters() {
+ for (String x : primary.connectors()) {
+ primary.deleteConnector(x);
+ }
+ for (String x : backup.connectors()) {
+ backup.deleteConnector(x);
+ }
+ deleteAllTopics(primary.kafka());
+ deleteAllTopics(backup.kafka());
+ primary.stop();
+ backup.stop();
+ try {
+ assertFalse(exited.get());
+ } finally {
+ Exit.resetExitProcedure();
+ }
+ }
+
+ @Test
+ public void testReplication() throws InterruptedException {
+ produceMessages(primary, "test-topic-1");
+ produceMessages(backup, "test-topic-1");
+ String consumerGroupName = "consumer-group-testReplication";
+ Map<String, Object> consumerProps = new HashMap<String, Object>() {{
+ put("group.id", consumerGroupName);
+ put("auto.offset.reset", "latest");
+ }};
+ // create consumers before starting the connectors so we don't need to wait for discovery
+ Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps, "test-topic-1");
+ waitForConsumingAllRecords(primaryConsumer, 0);
+
+ Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(consumerProps, "test-topic-1");
+ waitForConsumingAllRecords(backupConsumer, 0);
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS);
+ waitUntilMirrorMakerIsRunning(primary, CONNECTOR_LIST, mm2Config, BACKUP_CLUSTER_ALIAS, PRIMARY_CLUSTER_ALIAS);
+
+ MirrorClient primaryClient = new MirrorClient(mm2Config.clientConfig(PRIMARY_CLUSTER_ALIAS));
+ MirrorClient backupClient = new MirrorClient(mm2Config.clientConfig(BACKUP_CLUSTER_ALIAS));
+
+ assertEquals("topic config was not synced", TopicConfig.CLEANUP_POLICY_COMPACT,
+ getTopicConfig(backup.kafka(), "primary.test-topic-1", TopicConfig.CLEANUP_POLICY_CONFIG));
+
+ assertEquals("Records were not produced to primary cluster.", NUM_RECORDS_PRODUCED,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "test-topic-1").count());
+ assertEquals("Records were not replicated to backup cluster.", NUM_RECORDS_PRODUCED,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "primary.test-topic-1").count());
+ assertEquals("Records were not produced to backup cluster.", NUM_RECORDS_PRODUCED,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "test-topic-1").count());
+ assertEquals("Records were not replicated to primary cluster.", NUM_RECORDS_PRODUCED,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "backup.test-topic-1").count());
+
+ assertEquals("Primary cluster doesn't have all records from both clusters.", NUM_RECORDS_PRODUCED * 2,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED * 2, RECORD_TRANSFER_DURATION_MS, "backup.test-topic-1", "test-topic-1").count());
+ assertEquals("Backup cluster doesn't have all records from both clusters.", NUM_RECORDS_PRODUCED * 2,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED * 2, RECORD_TRANSFER_DURATION_MS, "primary.test-topic-1", "test-topic-1").count());
+
+ assertTrue("Heartbeats were not emitted to primary cluster.", primary.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "heartbeats").count() > 0);
+ assertTrue("Heartbeats were not emitted to backup cluster.", backup.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "heartbeats").count() > 0);
+ assertTrue("Heartbeats were not replicated downstream to backup cluster.", backup.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "primary.heartbeats").count() > 0);
+ assertTrue("Heartbeats were not replicated downstream to primary cluster.", primary.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "backup.heartbeats").count() > 0);
+
+ assertTrue("Did not find upstream primary cluster.", backupClient.upstreamClusters().contains(PRIMARY_CLUSTER_ALIAS));
+ assertEquals("Did not calculate replication hops correctly.", 1, backupClient.replicationHops(PRIMARY_CLUSTER_ALIAS));
+ assertTrue("Did not find upstream backup cluster.", primaryClient.upstreamClusters().contains(BACKUP_CLUSTER_ALIAS));
+ assertEquals("Did not calculate replication hops correctly.", 1, primaryClient.replicationHops(BACKUP_CLUSTER_ALIAS));
+ assertTrue("Checkpoints were not emitted downstream to backup cluster.", backup.kafka().consume(1,
+ CHECKPOINT_DURATION_MS, "primary.checkpoints.internal").count() > 0);
+
+ Map<TopicPartition, OffsetAndMetadata> backupOffsets = backupClient.remoteConsumerOffsets(consumerGroupName, PRIMARY_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS));
+
+ assertTrue("Offsets not translated downstream to backup cluster. Found: " + backupOffsets, backupOffsets.containsKey(
+ new TopicPartition("primary.test-topic-1", 0)));
+
+ // Failover consumer group to backup cluster.
+ primaryConsumer = backup.kafka().createConsumer(Collections.singletonMap("group.id", consumerGroupName));
+ primaryConsumer.assign(backupOffsets.keySet());
+ backupOffsets.forEach(primaryConsumer::seek);
+ primaryConsumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+ primaryConsumer.commitAsync();
+
+ assertTrue("Consumer failedover to zero offset.", primaryConsumer.position(new TopicPartition("primary.test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedover beyond expected offset.", primaryConsumer.position(
+ new TopicPartition("primary.test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+ assertTrue("Checkpoints were not emitted upstream to primary cluster.", primary.kafka().consume(1,
+ CHECKPOINT_DURATION_MS, "backup.checkpoints.internal").count() > 0);
+
+ primaryConsumer.close();
Review comment:
yeah - I think we can do "try with resource block", updated
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc commented on a change in pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc commented on a change in pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#discussion_r527398919
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationTest.java
##########
@@ -0,0 +1,370 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.errors.TimeoutException;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.connector.Connector;
+import org.apache.kafka.connect.mirror.MirrorCheckpointConnector;
+import org.apache.kafka.connect.mirror.MirrorClient;
+import org.apache.kafka.connect.mirror.MirrorHeartbeatConnector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.MirrorSourceConnector;
+import org.apache.kafka.connect.mirror.utils.ThreadedConsumer;
+import org.apache.kafka.connect.mirror.utils.ThreadedProducer;
+
+import org.junit.Before;
+import org.junit.After;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertNotNull;
+
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Collections;
+import java.util.Map;
+import java.util.HashMap;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+import org.apache.kafka.test.IntegrationTest;
+
+/**
+ * Tests MM2 replication and failover/failback logic.
+ *
+ * MM2 is configured with active/active replication between two Kafka clusters. Tests validate that
+ * records sent to either cluster arrive at the other cluster. Then, a consumer group is migrated from
+ * one cluster to the other and back. Tests validate that consumer offsets are translated and replicated
+ * between clusters during this failover and failback.
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationTest extends MirrorConnectorsIntegrationBaseTest {
+
+ private static final List<Class<? extends Connector>> CONNECTOR_LIST =
+ Arrays.asList(MirrorSourceConnector.class, MirrorCheckpointConnector.class, MirrorHeartbeatConnector.class);
+
+ @Before
+ public void setup() throws InterruptedException {
+ startClusters();
+ }
+
+ @After
+ public void close() {
+ shutdownClusters();
+ }
+
+ @Test
+ public void testReplication() throws InterruptedException {
+ produceMessages(primary, "test-topic-1");
+ produceMessages(backup, "test-topic-1");
+ String consumerGroupName = "consumer-group-testReplication";
+ Map<String, Object> consumerProps = new HashMap<String, Object>() {{
+ put("group.id", consumerGroupName);
+ put("auto.offset.reset", "latest");
+ }};
+ // create consumers before starting the connectors so we don't need to wait for discovery
+ Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps, "test-topic-1");
+ waitForConsumingAllRecords(primaryConsumer, 0);
+
+ Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(consumerProps, "test-topic-1");
+ waitForConsumingAllRecords(backupConsumer, 0);
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS);
+ waitUntilMirrorMakerIsRunning(primary, CONNECTOR_LIST, mm2Config, BACKUP_CLUSTER_ALIAS, PRIMARY_CLUSTER_ALIAS);
+
+ MirrorClient primaryClient = new MirrorClient(mm2Config.clientConfig(PRIMARY_CLUSTER_ALIAS));
+ MirrorClient backupClient = new MirrorClient(mm2Config.clientConfig(BACKUP_CLUSTER_ALIAS));
+
+ assertEquals("topic config was not synced", TopicConfig.CLEANUP_POLICY_COMPACT,
+ getTopicConfig(backup.kafka(), "primary.test-topic-1", TopicConfig.CLEANUP_POLICY_CONFIG));
+
+ assertEquals("Records were not produced to primary cluster.", NUM_RECORDS_PRODUCED,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "test-topic-1").count());
+ assertEquals("Records were not replicated to backup cluster.", NUM_RECORDS_PRODUCED,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "primary.test-topic-1").count());
+ assertEquals("Records were not produced to backup cluster.", NUM_RECORDS_PRODUCED,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "test-topic-1").count());
+ assertEquals("Records were not replicated to primary cluster.", NUM_RECORDS_PRODUCED,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "backup.test-topic-1").count());
+
+ assertEquals("Primary cluster doesn't have all records from both clusters.", NUM_RECORDS_PRODUCED * 2,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED * 2, RECORD_TRANSFER_DURATION_MS, "backup.test-topic-1", "test-topic-1").count());
+ assertEquals("Backup cluster doesn't have all records from both clusters.", NUM_RECORDS_PRODUCED * 2,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED * 2, RECORD_TRANSFER_DURATION_MS, "primary.test-topic-1", "test-topic-1").count());
+
+ assertTrue("Heartbeats were not emitted to primary cluster.", primary.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "heartbeats").count() > 0);
+ assertTrue("Heartbeats were not emitted to backup cluster.", backup.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "heartbeats").count() > 0);
+ assertTrue("Heartbeats were not replicated downstream to backup cluster.", backup.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "primary.heartbeats").count() > 0);
+ assertTrue("Heartbeats were not replicated downstream to primary cluster.", primary.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "backup.heartbeats").count() > 0);
+
+ assertTrue("Did not find upstream primary cluster.", backupClient.upstreamClusters().contains(PRIMARY_CLUSTER_ALIAS));
+ assertEquals("Did not calculate replication hops correctly.", 1, backupClient.replicationHops(PRIMARY_CLUSTER_ALIAS));
+ assertTrue("Did not find upstream backup cluster.", primaryClient.upstreamClusters().contains(BACKUP_CLUSTER_ALIAS));
+ assertEquals("Did not calculate replication hops correctly.", 1, primaryClient.replicationHops(BACKUP_CLUSTER_ALIAS));
+ assertTrue("Checkpoints were not emitted downstream to backup cluster.", backup.kafka().consume(1,
+ CHECKPOINT_DURATION_MS, "primary.checkpoints.internal").count() > 0);
+
+ Map<TopicPartition, OffsetAndMetadata> backupOffsets = backupClient.remoteConsumerOffsets(consumerGroupName, PRIMARY_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS));
+
+ assertTrue("Offsets not translated downstream to backup cluster. Found: " + backupOffsets, backupOffsets.containsKey(
+ new TopicPartition("primary.test-topic-1", 0)));
+
+ // Failover consumer group to backup cluster.
+ primaryConsumer = backup.kafka().createConsumer(Collections.singletonMap("group.id", consumerGroupName));
+ primaryConsumer.assign(backupOffsets.keySet());
+ backupOffsets.forEach(primaryConsumer::seek);
+ primaryConsumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+ primaryConsumer.commitAsync();
+
+ assertTrue("Consumer failedover to zero offset.", primaryConsumer.position(new TopicPartition("primary.test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedover beyond expected offset.", primaryConsumer.position(
+ new TopicPartition("primary.test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+ assertTrue("Checkpoints were not emitted upstream to primary cluster.", primary.kafka().consume(1,
+ CHECKPOINT_DURATION_MS, "backup.checkpoints.internal").count() > 0);
+
+ primaryConsumer.close();
+
+ waitForCondition(() -> {
+ try {
+ return primaryClient.remoteConsumerOffsets(consumerGroupName, BACKUP_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS)).containsKey(new TopicPartition("backup.test-topic-1", 0));
+ } catch (Throwable e) {
+ return false;
+ }
+ }, CHECKPOINT_DURATION_MS, "Offsets not translated downstream to primary cluster.");
+
+ waitForCondition(() -> {
+ try {
+ return primaryClient.remoteConsumerOffsets(consumerGroupName, BACKUP_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS)).containsKey(new TopicPartition("test-topic-1", 0));
+ } catch (Throwable e) {
+ return false;
+ }
+ }, CHECKPOINT_DURATION_MS, "Offsets not translated upstream to primary cluster.");
+
+ Map<TopicPartition, OffsetAndMetadata> primaryOffsets = primaryClient.remoteConsumerOffsets(consumerGroupName, BACKUP_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS));
+
+ // Failback consumer group to primary cluster
+ backupConsumer = primary.kafka().createConsumer(Collections.singletonMap("group.id", consumerGroupName));
+ backupConsumer.assign(primaryOffsets.keySet());
+ primaryOffsets.forEach(backupConsumer::seek);
+ backupConsumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+ backupConsumer.commitAsync();
+
+ assertTrue("Consumer failedback to zero upstream offset.", backupConsumer.position(new TopicPartition("test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedback to zero downstream offset.", backupConsumer.position(new TopicPartition("backup.test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedback beyond expected upstream offset.", backupConsumer.position(
+ new TopicPartition("test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+ assertTrue("Consumer failedback beyond expected downstream offset.", backupConsumer.position(
+ new TopicPartition("backup.test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+
+ backupConsumer.close();
+
+ // create more matching topics
+ primary.kafka().createTopic("test-topic-2", NUM_PARTITIONS);
+ backup.kafka().createTopic("test-topic-3", NUM_PARTITIONS);
+
+ // only produce messages to the first partition
+ produceMessages(primary, "test-topic-2", 1);
+ produceMessages(backup, "test-topic-3", 1);
+
+ // expect total consumed messages equals to NUM_RECORDS_PER_PARTITION
+ assertEquals("Records were not produced to primary cluster.", NUM_RECORDS_PER_PARTITION,
+ primary.kafka().consume(NUM_RECORDS_PER_PARTITION, RECORD_TRANSFER_DURATION_MS, "test-topic-2").count());
+ assertEquals("Records were not produced to backup cluster.", NUM_RECORDS_PER_PARTITION,
+ backup.kafka().consume(NUM_RECORDS_PER_PARTITION, RECORD_TRANSFER_DURATION_MS, "test-topic-3").count());
+
+ assertEquals("New topic was not replicated to primary cluster.", NUM_RECORDS_PER_PARTITION,
+ primary.kafka().consume(NUM_RECORDS_PER_PARTITION, 2 * RECORD_TRANSFER_DURATION_MS, "backup.test-topic-3").count());
+ assertEquals("New topic was not replicated to backup cluster.", NUM_RECORDS_PER_PARTITION,
+ backup.kafka().consume(NUM_RECORDS_PER_PARTITION, 2 * RECORD_TRANSFER_DURATION_MS, "primary.test-topic-2").count());
+
+ }
+
+ @Test
+ public void testReplicationWithEmptyPartition() throws Exception {
+ String consumerGroupName = "consumer-group-testReplicationWithEmptyPartition";
+ Map<String, Object> consumerProps = Collections.singletonMap("group.id", consumerGroupName);
+
+ // create topic
+ String topic = "test-topic-with-empty-partition";
+ primary.kafka().createTopic(topic, NUM_PARTITIONS);
+
+ // produce to all test-topic-empty's partitions, except the last partition
+ produceMessages(primary, topic, NUM_PARTITIONS - 1);
+
+ // consume before starting the connectors so we don't need to wait for discovery
+ int expectedRecords = NUM_RECORDS_PER_PARTITION * (NUM_PARTITIONS - 1);
+ try (Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps, topic)) {
+ waitForConsumingAllRecords(primaryConsumer, expectedRecords);
+ }
+
+ // one way replication from primary to backup
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + "->" + PRIMARY_CLUSTER_ALIAS + ".enabled", "false");
+ mm2Config = new MirrorMakerConfig(mm2Props);
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS);
+
+ // sleep few seconds to have MM2 finish replication so that "end" consumer will consume some record
+ Thread.sleep(TimeUnit.SECONDS.toMillis(3));
+
+ // consume all records from backup cluster
+ try (Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(consumerProps,
+ PRIMARY_CLUSTER_ALIAS + "." + topic)) {
+ waitForConsumingAllRecords(backupConsumer, expectedRecords);
+ }
+
+ Admin backupClient = backup.kafka().createAdminClient();
+ // retrieve the consumer group offset from backup cluster
+ Map<TopicPartition, OffsetAndMetadata> remoteOffsets =
+ backupClient.listConsumerGroupOffsets(consumerGroupName).partitionsToOffsetAndMetadata().get();
+ // pinpoint the offset of the last partition which does not receive records
+ OffsetAndMetadata offset = remoteOffsets.get(new TopicPartition(PRIMARY_CLUSTER_ALIAS + "." + topic, NUM_PARTITIONS - 1));
+ // offset of the last partition should exist, but its value should be 0
+ assertNotNull("Offset of last partition was not replicated", offset);
+ assertEquals("Offset of last partition is not zero", 0, offset.offset());
+ }
+
+ @Test
+ public void testOneWayReplicationWithAutoOffsetSync() throws InterruptedException {
+ produceMessages(primary, "test-topic-1");
+ String consumerGroupName = "consumer-group-testOneWayReplicationWithAutoOffsetSync";
+ Map<String, Object> consumerProps = new HashMap<String, Object>() {{
+ put("group.id", consumerGroupName);
+ put("auto.offset.reset", "earliest");
+ }};
+ // create consumers before starting the connectors so we don't need to wait for discovery
+ try (Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps,
+ "test-topic-1")) {
+ // we need to wait for consuming all the records for MM2 replicating the expected offsets
+ waitForConsumingAllRecords(primaryConsumer, NUM_RECORDS_PRODUCED);
+ }
+
+ // enable automated consumer group offset sync
+ mm2Props.put("sync.group.offsets.enabled", "true");
+ mm2Props.put("sync.group.offsets.interval.seconds", "1");
+ // one way replication from primary to backup
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + "->" + PRIMARY_CLUSTER_ALIAS + ".enabled", "false");
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS);
+
+ // create a consumer at backup cluster with same consumer group Id to consume 1 topic
+ Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(
+ consumerProps, "primary.test-topic-1");
+
+ waitForConsumerGroupOffsetSync(backup, backupConsumer, Collections.singletonList("primary.test-topic-1"),
+ consumerGroupName, NUM_RECORDS_PRODUCED);
+
+ ConsumerRecords<byte[], byte[]> records = backupConsumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+
+ // the size of consumer record should be zero, because the offsets of the same consumer group
+ // have been automatically synchronized from primary to backup by the background job, so no
+ // more records to consume from the replicated topic by the same consumer group at backup cluster
+ assertEquals("consumer record size is not zero", 0, records.count());
+
+ // now create a new topic in primary cluster
+ primary.kafka().createTopic("test-topic-2", NUM_PARTITIONS);
+ backup.kafka().createTopic("primary.test-topic-2", 1);
+ // produce some records to the new topic in primary cluster
+ produceMessages(primary, "test-topic-2");
+
+ // create a consumer at primary cluster to consume the new topic
+ try (Consumer<byte[], byte[]> consumer1 = primary.kafka().createConsumerAndSubscribeTo(Collections.singletonMap(
+ "group.id", "consumer-group-1"), "test-topic-2")) {
+ // we need to wait for consuming all the records for MM2 replicating the expected offsets
+ waitForConsumingAllRecords(consumer1, NUM_RECORDS_PRODUCED);
+ }
+
+ // create a consumer at backup cluster with same consumer group Id to consume old and new topic
+ backupConsumer = backup.kafka().createConsumerAndSubscribeTo(Collections.singletonMap(
+ "group.id", consumerGroupName), "primary.test-topic-1", "primary.test-topic-2");
+
+ waitForConsumerGroupOffsetSync(backup, backupConsumer, Arrays.asList("primary.test-topic-1", "primary.test-topic-2"),
+ consumerGroupName, NUM_RECORDS_PRODUCED);
+
+ records = backupConsumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+ // similar reasoning as above, no more records to consume by the same consumer group at backup cluster
+ assertEquals("consumer record size is not zero", 0, records.count());
+ backupConsumer.close();
+ }
+
+ /*
+ * This test is to validate MirrorSourceConnector follows "at most once" delivery guarantee
+ * under broker restart / failure
+ */
+ @Test
+ public void testWithBrokerRestart() throws InterruptedException {
Review comment:
> Why do we need background clients instead of producing upfront and consuming the data mirrorred at the end of the test?
I think I answered the above question as the comments in the code. Please see below,
> // the purpose of background producer and consumer is to better test the failure case
> // to avoid serialization (produce -> broker restart -> consumer) by decoupling the
> // producer, embedded kafka and consumer. Since the consumer offsets are stored in
> // kafka topic at backup cluster and offset commit is periodic, when kafka broker (at backup)
> // restarts, duplicate records will be consumed, meaning "at least once" delivery guarantee
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc commented on pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc commented on pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#issuecomment-742127747
@mimaison thanks for pointing out. Fixed the checkstyle, sorry for just running the check for `connect/mirror`
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] mimaison commented on pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
mimaison commented on pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#issuecomment-742106800
@ning2008wisc There are a few checkstyle failures:
```
> Task :connect:runtime:checkstyleTest
[ant:checkstyle] [ERROR] /Users/mickael/github-ws/kafka/connect/runtime/src/test/java/org/apache/kafka/connect/util/clusters/EmbeddedKafkaCluster.java:458:30: ',' is not followed by whitespace. [WhitespaceAfter]
[ant:checkstyle] [ERROR] /Users/mickael/github-ws/kafka/connect/runtime/src/test/java/org/apache/kafka/connect/util/clusters/EmbeddedKafkaCluster.java:459:30: ',' is not followed by whitespace. [WhitespaceAfter]
[ant:checkstyle] [ERROR] /Users/mickael/github-ws/kafka/connect/runtime/src/test/java/org/apache/kafka/connect/util/clusters/EmbeddedKafkaCluster.java:460:30: ',' is not followed by whitespace. [WhitespaceAfter]
```
You can run `./gradlew connect:runtime:test` to reproduce
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc commented on pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc commented on pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#issuecomment-703412889

./gradlew connect:mirror:test -> all tests pass
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc commented on a change in pull request #9224: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc commented on a change in pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#discussion_r485362458
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationTest.java
##########
@@ -207,13 +173,16 @@ public void testReplication() throws InterruptedException {
mm2Config = new MirrorMakerConfig(mm2Props);
- waitUntilMirrorMakerIsRunning(backup, mm2Config, "primary", "backup");
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, "primary", "backup");
- waitUntilMirrorMakerIsRunning(primary, mm2Config, "backup", "primary");
+ waitUntilMirrorMakerIsRunning(primary, CONNECTOR_LIST, mm2Config, "backup", "primary");
MirrorClient primaryClient = new MirrorClient(mm2Config.clientConfig("primary"));
MirrorClient backupClient = new MirrorClient(mm2Config.clientConfig("backup"));
-
+
+ assertEquals("topic config was not synced", TopicConfig.CLEANUP_POLICY_COMPACT,
+ getTopicConfig(backup.kafka(), "primary.test-topic-1", TopicConfig.CLEANUP_POLICY_CONFIG));
Review comment:
Add a check for topic config sync, since the topic created on primary cluster has a "cleanup.policy" config
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc commented on pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc commented on pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#issuecomment-731014605
Thanks @mimaison for your suggestive and insightful feedback.
Regarding to your 2 major concerns, I agree and I believe there exists a feasible solution. I will update this PR early next week by addressing all your major and minor comments.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc edited a comment on pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc edited a comment on pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#issuecomment-714955565
Thanks @mimaison for your high-level advice and detailed review.
(1) I responded to your every comments. A "thumb-up" means I made the suggested change
(2) regarding the increased complexity, here is my analysis for each test case:
(2a) `testReplication`: This is an existing test and no new stuff are added, except checking if topic config are also mirrored. If we believe the topic config validation is trivial, I am more than happy to remove it
(2b) `testReplicationWithEmptyPartition`: This is an existing test and no new stuff are added
(2c) `testOneWayReplicationWithAutoOffsetSync`: This is an existing test and no new stuff are added
(2d) `testWithBrokerRestart`: This is a **new** test, which introduced background producer and consumer, called `ThreadedProducer` and `ThreadedConsumer`. The purpose of background producer and consumer is to better test the failure case to avoid serialization (produce -> broker restart -> consumer) which can not reveal the insight that consumers consume the same records more than once when broker failure happens.
(2e) `MirrorConnectorsIntegrationSSLTest`: This is a **new** test and it should be pretty lean and neat.
In addition, the **new** base test class `MirrorConnectorsIntegrationBaseTest` follows the existing practice of K-stream integration test structure https://github.com/apache/kafka/blob/trunk/streams/src/test/java/org/apache/kafka/streams/integration/ResetIntegrationWithSslTest.java#L37 so I assume it is likely the right way to structure tests with more than one scenarios (SSL v.s. non-SSL)
If we have to control the complexity, I would prefer to drop `testWithBrokerRestart` and keep `MirrorConnectorsIntegrationSSLTest`, as it makes sense to run simple validation in SSL setup.
Thanks and would like to hear more thoughts and feedback.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc edited a comment on pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc edited a comment on pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#issuecomment-731014605
Thanks @mimaison for your suggestive and insightful feedback.
Regarding to your 2 major concerns, I agree and I believe there exists a feasible solution, especially for a very lean SSL test. I will update this PR early next week by addressing all your major and minor comments.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc commented on a change in pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc commented on a change in pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#discussion_r527398919
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationTest.java
##########
@@ -0,0 +1,370 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.errors.TimeoutException;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.connector.Connector;
+import org.apache.kafka.connect.mirror.MirrorCheckpointConnector;
+import org.apache.kafka.connect.mirror.MirrorClient;
+import org.apache.kafka.connect.mirror.MirrorHeartbeatConnector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.MirrorSourceConnector;
+import org.apache.kafka.connect.mirror.utils.ThreadedConsumer;
+import org.apache.kafka.connect.mirror.utils.ThreadedProducer;
+
+import org.junit.Before;
+import org.junit.After;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertNotNull;
+
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Collections;
+import java.util.Map;
+import java.util.HashMap;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+import org.apache.kafka.test.IntegrationTest;
+
+/**
+ * Tests MM2 replication and failover/failback logic.
+ *
+ * MM2 is configured with active/active replication between two Kafka clusters. Tests validate that
+ * records sent to either cluster arrive at the other cluster. Then, a consumer group is migrated from
+ * one cluster to the other and back. Tests validate that consumer offsets are translated and replicated
+ * between clusters during this failover and failback.
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationTest extends MirrorConnectorsIntegrationBaseTest {
+
+ private static final List<Class<? extends Connector>> CONNECTOR_LIST =
+ Arrays.asList(MirrorSourceConnector.class, MirrorCheckpointConnector.class, MirrorHeartbeatConnector.class);
+
+ @Before
+ public void setup() throws InterruptedException {
+ startClusters();
+ }
+
+ @After
+ public void close() {
+ shutdownClusters();
+ }
+
+ @Test
+ public void testReplication() throws InterruptedException {
+ produceMessages(primary, "test-topic-1");
+ produceMessages(backup, "test-topic-1");
+ String consumerGroupName = "consumer-group-testReplication";
+ Map<String, Object> consumerProps = new HashMap<String, Object>() {{
+ put("group.id", consumerGroupName);
+ put("auto.offset.reset", "latest");
+ }};
+ // create consumers before starting the connectors so we don't need to wait for discovery
+ Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps, "test-topic-1");
+ waitForConsumingAllRecords(primaryConsumer, 0);
+
+ Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(consumerProps, "test-topic-1");
+ waitForConsumingAllRecords(backupConsumer, 0);
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS);
+ waitUntilMirrorMakerIsRunning(primary, CONNECTOR_LIST, mm2Config, BACKUP_CLUSTER_ALIAS, PRIMARY_CLUSTER_ALIAS);
+
+ MirrorClient primaryClient = new MirrorClient(mm2Config.clientConfig(PRIMARY_CLUSTER_ALIAS));
+ MirrorClient backupClient = new MirrorClient(mm2Config.clientConfig(BACKUP_CLUSTER_ALIAS));
+
+ assertEquals("topic config was not synced", TopicConfig.CLEANUP_POLICY_COMPACT,
+ getTopicConfig(backup.kafka(), "primary.test-topic-1", TopicConfig.CLEANUP_POLICY_CONFIG));
+
+ assertEquals("Records were not produced to primary cluster.", NUM_RECORDS_PRODUCED,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "test-topic-1").count());
+ assertEquals("Records were not replicated to backup cluster.", NUM_RECORDS_PRODUCED,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "primary.test-topic-1").count());
+ assertEquals("Records were not produced to backup cluster.", NUM_RECORDS_PRODUCED,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "test-topic-1").count());
+ assertEquals("Records were not replicated to primary cluster.", NUM_RECORDS_PRODUCED,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "backup.test-topic-1").count());
+
+ assertEquals("Primary cluster doesn't have all records from both clusters.", NUM_RECORDS_PRODUCED * 2,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED * 2, RECORD_TRANSFER_DURATION_MS, "backup.test-topic-1", "test-topic-1").count());
+ assertEquals("Backup cluster doesn't have all records from both clusters.", NUM_RECORDS_PRODUCED * 2,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED * 2, RECORD_TRANSFER_DURATION_MS, "primary.test-topic-1", "test-topic-1").count());
+
+ assertTrue("Heartbeats were not emitted to primary cluster.", primary.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "heartbeats").count() > 0);
+ assertTrue("Heartbeats were not emitted to backup cluster.", backup.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "heartbeats").count() > 0);
+ assertTrue("Heartbeats were not replicated downstream to backup cluster.", backup.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "primary.heartbeats").count() > 0);
+ assertTrue("Heartbeats were not replicated downstream to primary cluster.", primary.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "backup.heartbeats").count() > 0);
+
+ assertTrue("Did not find upstream primary cluster.", backupClient.upstreamClusters().contains(PRIMARY_CLUSTER_ALIAS));
+ assertEquals("Did not calculate replication hops correctly.", 1, backupClient.replicationHops(PRIMARY_CLUSTER_ALIAS));
+ assertTrue("Did not find upstream backup cluster.", primaryClient.upstreamClusters().contains(BACKUP_CLUSTER_ALIAS));
+ assertEquals("Did not calculate replication hops correctly.", 1, primaryClient.replicationHops(BACKUP_CLUSTER_ALIAS));
+ assertTrue("Checkpoints were not emitted downstream to backup cluster.", backup.kafka().consume(1,
+ CHECKPOINT_DURATION_MS, "primary.checkpoints.internal").count() > 0);
+
+ Map<TopicPartition, OffsetAndMetadata> backupOffsets = backupClient.remoteConsumerOffsets(consumerGroupName, PRIMARY_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS));
+
+ assertTrue("Offsets not translated downstream to backup cluster. Found: " + backupOffsets, backupOffsets.containsKey(
+ new TopicPartition("primary.test-topic-1", 0)));
+
+ // Failover consumer group to backup cluster.
+ primaryConsumer = backup.kafka().createConsumer(Collections.singletonMap("group.id", consumerGroupName));
+ primaryConsumer.assign(backupOffsets.keySet());
+ backupOffsets.forEach(primaryConsumer::seek);
+ primaryConsumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+ primaryConsumer.commitAsync();
+
+ assertTrue("Consumer failedover to zero offset.", primaryConsumer.position(new TopicPartition("primary.test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedover beyond expected offset.", primaryConsumer.position(
+ new TopicPartition("primary.test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+ assertTrue("Checkpoints were not emitted upstream to primary cluster.", primary.kafka().consume(1,
+ CHECKPOINT_DURATION_MS, "backup.checkpoints.internal").count() > 0);
+
+ primaryConsumer.close();
+
+ waitForCondition(() -> {
+ try {
+ return primaryClient.remoteConsumerOffsets(consumerGroupName, BACKUP_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS)).containsKey(new TopicPartition("backup.test-topic-1", 0));
+ } catch (Throwable e) {
+ return false;
+ }
+ }, CHECKPOINT_DURATION_MS, "Offsets not translated downstream to primary cluster.");
+
+ waitForCondition(() -> {
+ try {
+ return primaryClient.remoteConsumerOffsets(consumerGroupName, BACKUP_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS)).containsKey(new TopicPartition("test-topic-1", 0));
+ } catch (Throwable e) {
+ return false;
+ }
+ }, CHECKPOINT_DURATION_MS, "Offsets not translated upstream to primary cluster.");
+
+ Map<TopicPartition, OffsetAndMetadata> primaryOffsets = primaryClient.remoteConsumerOffsets(consumerGroupName, BACKUP_CLUSTER_ALIAS,
+ Duration.ofMillis(CHECKPOINT_DURATION_MS));
+
+ // Failback consumer group to primary cluster
+ backupConsumer = primary.kafka().createConsumer(Collections.singletonMap("group.id", consumerGroupName));
+ backupConsumer.assign(primaryOffsets.keySet());
+ primaryOffsets.forEach(backupConsumer::seek);
+ backupConsumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+ backupConsumer.commitAsync();
+
+ assertTrue("Consumer failedback to zero upstream offset.", backupConsumer.position(new TopicPartition("test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedback to zero downstream offset.", backupConsumer.position(new TopicPartition("backup.test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedback beyond expected upstream offset.", backupConsumer.position(
+ new TopicPartition("test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+ assertTrue("Consumer failedback beyond expected downstream offset.", backupConsumer.position(
+ new TopicPartition("backup.test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+
+ backupConsumer.close();
+
+ // create more matching topics
+ primary.kafka().createTopic("test-topic-2", NUM_PARTITIONS);
+ backup.kafka().createTopic("test-topic-3", NUM_PARTITIONS);
+
+ // only produce messages to the first partition
+ produceMessages(primary, "test-topic-2", 1);
+ produceMessages(backup, "test-topic-3", 1);
+
+ // expect total consumed messages equals to NUM_RECORDS_PER_PARTITION
+ assertEquals("Records were not produced to primary cluster.", NUM_RECORDS_PER_PARTITION,
+ primary.kafka().consume(NUM_RECORDS_PER_PARTITION, RECORD_TRANSFER_DURATION_MS, "test-topic-2").count());
+ assertEquals("Records were not produced to backup cluster.", NUM_RECORDS_PER_PARTITION,
+ backup.kafka().consume(NUM_RECORDS_PER_PARTITION, RECORD_TRANSFER_DURATION_MS, "test-topic-3").count());
+
+ assertEquals("New topic was not replicated to primary cluster.", NUM_RECORDS_PER_PARTITION,
+ primary.kafka().consume(NUM_RECORDS_PER_PARTITION, 2 * RECORD_TRANSFER_DURATION_MS, "backup.test-topic-3").count());
+ assertEquals("New topic was not replicated to backup cluster.", NUM_RECORDS_PER_PARTITION,
+ backup.kafka().consume(NUM_RECORDS_PER_PARTITION, 2 * RECORD_TRANSFER_DURATION_MS, "primary.test-topic-2").count());
+
+ }
+
+ @Test
+ public void testReplicationWithEmptyPartition() throws Exception {
+ String consumerGroupName = "consumer-group-testReplicationWithEmptyPartition";
+ Map<String, Object> consumerProps = Collections.singletonMap("group.id", consumerGroupName);
+
+ // create topic
+ String topic = "test-topic-with-empty-partition";
+ primary.kafka().createTopic(topic, NUM_PARTITIONS);
+
+ // produce to all test-topic-empty's partitions, except the last partition
+ produceMessages(primary, topic, NUM_PARTITIONS - 1);
+
+ // consume before starting the connectors so we don't need to wait for discovery
+ int expectedRecords = NUM_RECORDS_PER_PARTITION * (NUM_PARTITIONS - 1);
+ try (Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps, topic)) {
+ waitForConsumingAllRecords(primaryConsumer, expectedRecords);
+ }
+
+ // one way replication from primary to backup
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + "->" + PRIMARY_CLUSTER_ALIAS + ".enabled", "false");
+ mm2Config = new MirrorMakerConfig(mm2Props);
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS);
+
+ // sleep few seconds to have MM2 finish replication so that "end" consumer will consume some record
+ Thread.sleep(TimeUnit.SECONDS.toMillis(3));
+
+ // consume all records from backup cluster
+ try (Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(consumerProps,
+ PRIMARY_CLUSTER_ALIAS + "." + topic)) {
+ waitForConsumingAllRecords(backupConsumer, expectedRecords);
+ }
+
+ Admin backupClient = backup.kafka().createAdminClient();
+ // retrieve the consumer group offset from backup cluster
+ Map<TopicPartition, OffsetAndMetadata> remoteOffsets =
+ backupClient.listConsumerGroupOffsets(consumerGroupName).partitionsToOffsetAndMetadata().get();
+ // pinpoint the offset of the last partition which does not receive records
+ OffsetAndMetadata offset = remoteOffsets.get(new TopicPartition(PRIMARY_CLUSTER_ALIAS + "." + topic, NUM_PARTITIONS - 1));
+ // offset of the last partition should exist, but its value should be 0
+ assertNotNull("Offset of last partition was not replicated", offset);
+ assertEquals("Offset of last partition is not zero", 0, offset.offset());
+ }
+
+ @Test
+ public void testOneWayReplicationWithAutoOffsetSync() throws InterruptedException {
+ produceMessages(primary, "test-topic-1");
+ String consumerGroupName = "consumer-group-testOneWayReplicationWithAutoOffsetSync";
+ Map<String, Object> consumerProps = new HashMap<String, Object>() {{
+ put("group.id", consumerGroupName);
+ put("auto.offset.reset", "earliest");
+ }};
+ // create consumers before starting the connectors so we don't need to wait for discovery
+ try (Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps,
+ "test-topic-1")) {
+ // we need to wait for consuming all the records for MM2 replicating the expected offsets
+ waitForConsumingAllRecords(primaryConsumer, NUM_RECORDS_PRODUCED);
+ }
+
+ // enable automated consumer group offset sync
+ mm2Props.put("sync.group.offsets.enabled", "true");
+ mm2Props.put("sync.group.offsets.interval.seconds", "1");
+ // one way replication from primary to backup
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + "->" + PRIMARY_CLUSTER_ALIAS + ".enabled", "false");
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS);
+
+ // create a consumer at backup cluster with same consumer group Id to consume 1 topic
+ Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(
+ consumerProps, "primary.test-topic-1");
+
+ waitForConsumerGroupOffsetSync(backup, backupConsumer, Collections.singletonList("primary.test-topic-1"),
+ consumerGroupName, NUM_RECORDS_PRODUCED);
+
+ ConsumerRecords<byte[], byte[]> records = backupConsumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+
+ // the size of consumer record should be zero, because the offsets of the same consumer group
+ // have been automatically synchronized from primary to backup by the background job, so no
+ // more records to consume from the replicated topic by the same consumer group at backup cluster
+ assertEquals("consumer record size is not zero", 0, records.count());
+
+ // now create a new topic in primary cluster
+ primary.kafka().createTopic("test-topic-2", NUM_PARTITIONS);
+ backup.kafka().createTopic("primary.test-topic-2", 1);
+ // produce some records to the new topic in primary cluster
+ produceMessages(primary, "test-topic-2");
+
+ // create a consumer at primary cluster to consume the new topic
+ try (Consumer<byte[], byte[]> consumer1 = primary.kafka().createConsumerAndSubscribeTo(Collections.singletonMap(
+ "group.id", "consumer-group-1"), "test-topic-2")) {
+ // we need to wait for consuming all the records for MM2 replicating the expected offsets
+ waitForConsumingAllRecords(consumer1, NUM_RECORDS_PRODUCED);
+ }
+
+ // create a consumer at backup cluster with same consumer group Id to consume old and new topic
+ backupConsumer = backup.kafka().createConsumerAndSubscribeTo(Collections.singletonMap(
+ "group.id", consumerGroupName), "primary.test-topic-1", "primary.test-topic-2");
+
+ waitForConsumerGroupOffsetSync(backup, backupConsumer, Arrays.asList("primary.test-topic-1", "primary.test-topic-2"),
+ consumerGroupName, NUM_RECORDS_PRODUCED);
+
+ records = backupConsumer.poll(Duration.ofMillis(CONSUMER_POLL_TIMEOUT_MS));
+ // similar reasoning as above, no more records to consume by the same consumer group at backup cluster
+ assertEquals("consumer record size is not zero", 0, records.count());
+ backupConsumer.close();
+ }
+
+ /*
+ * This test is to validate MirrorSourceConnector follows "at most once" delivery guarantee
+ * under broker restart / failure
+ */
+ @Test
+ public void testWithBrokerRestart() throws InterruptedException {
Review comment:
> Why do we need background clients instead of producing upfront and consuming the data mirrorred at the end of the test?
I think I answered the above question as the comments in the code. Please see below,
> // the purpose of background producer and consumer is to better test the failure case
> // to avoid serialization (produce -> broker restart -> consumer) by decoupling the
> // producer, embedded kafka and consumer. Since the consumer offsets are stored in
> // kafka topic at backup cluster and offset commit is periodic, when kafka broker (at backup)
> // restarts, duplicate records will be consumed, meaning "at least once" delivery guarantee
I believe this test has unique value and is more close to the realistic scenario, since the producer -> kafka -> consumer are always running on different machines, rather than **within one** process or thread.
Due to the complexity limitation, I am happy to remove this test for now
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc commented on pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc commented on pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#issuecomment-742587762
@mimaison thanks so much for your careful review. I checked https://github.com/apache/kafka/pull/9698 again and make sure we do not miss anything at this moment.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc commented on a change in pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc commented on a change in pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#discussion_r527396830
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationBaseTest.java
##########
@@ -0,0 +1,407 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.CommonClientConfigs;
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.Config;
+import org.apache.kafka.clients.admin.ConfigEntry;
+import org.apache.kafka.clients.admin.DescribeConfigsResult;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.config.ConfigResource;
+import org.apache.kafka.common.config.SslConfigs;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.config.types.Password;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.connector.Connector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.SourceAndTarget;
+import org.apache.kafka.connect.util.clusters.EmbeddedConnectCluster;
+import org.apache.kafka.connect.util.clusters.EmbeddedKafkaCluster;
+import static org.apache.kafka.connect.mirror.TestUtils.expectedRecords;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+import org.apache.kafka.test.IntegrationTest;
+import kafka.server.KafkaConfig$;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import static org.junit.Assert.assertFalse;
+import org.junit.experimental.categories.Category;
+
+/**
+ * Common Test functions for MM2 integration tests
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationBaseTest {
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationBaseTest.class);
+
+ protected static final int NUM_RECORDS_PER_PARTITION = 10;
+ public static final int NUM_PARTITIONS = 10;
+ protected static final int NUM_RECORDS_PRODUCED = NUM_PARTITIONS * NUM_RECORDS_PER_PARTITION;
+ protected static final int RECORD_TRANSFER_DURATION_MS = 30_000;
+ protected static final int CHECKPOINT_DURATION_MS = 20_000;
+ protected static final int RECORD_CONSUME_DURATION_MS = 20_000;
+ protected static final int OFFSET_SYNC_DURATION_MS = 30_000;
+ protected static final int NUM_WORKERS = 3;
+ protected static final int CONSUMER_POLL_TIMEOUT_MS = 500;
+ protected static final int BROKER_RESTART_TIMEOUT_MS = 10_000;
+ protected static final String PRIMARY_CLUSTER_ALIAS = "primary";
+ protected static final String BACKUP_CLUSTER_ALIAS = "backup";
+
+ protected Map<String, String> mm2Props;
+ protected MirrorMakerConfig mm2Config;
+ protected EmbeddedConnectCluster primary;
+ protected EmbeddedConnectCluster backup;
+
+ private final AtomicBoolean exited = new AtomicBoolean(false);
+ private Properties primaryBrokerProps = new Properties();
+ protected Properties backupBrokerProps = new Properties();
+ private Map<String, String> primaryWorkerProps = new HashMap<>();
+ private Map<String, String> backupWorkerProps = new HashMap<>();
+ private Properties sslProps = new Properties();
+
+ private void loadSslPropsFromBrokerConfig() {
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, backupBrokerProps.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG));
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, ((Password) backupBrokerProps.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)).value());
+ sslProps.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL");
+ }
+
+ protected void setSslConfig() {
+ // set SSL config for kafka connect worker
+ backupWorkerProps.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> BACKUP_CLUSTER_ALIAS + "." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ // set SSL config for producer used by source task in MM2
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> BACKUP_CLUSTER_ALIAS + ".producer." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ }
+
+ protected void startClusters() throws InterruptedException {
+ primaryBrokerProps.put("auto.create.topics.enable", "false");
+ backupBrokerProps.put("auto.create.topics.enable", "false");
+
+ mm2Props = basicMM2Config();
+
+ // if backup kafka cluster contains ssl config, enable ssl of kafka connect and mm2
+ final Object listeners = backupBrokerProps.get(KafkaConfig$.MODULE$.ListenersProp());
+ if (listeners != null && listeners.toString().contains("SSL")) {
+ loadSslPropsFromBrokerConfig();
+ setSslConfig();
+ }
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+ primaryWorkerProps = mm2Config.workerConfig(new SourceAndTarget(BACKUP_CLUSTER_ALIAS, PRIMARY_CLUSTER_ALIAS));
+ backupWorkerProps.putAll(mm2Config.workerConfig(new SourceAndTarget(PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS)));
+
+ primary = new EmbeddedConnectCluster.Builder()
+ .name(PRIMARY_CLUSTER_ALIAS + "-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(primaryBrokerProps)
+ .workerProps(primaryWorkerProps)
+ .build();
+
+ backup = new EmbeddedConnectCluster.Builder()
+ .name(BACKUP_CLUSTER_ALIAS + "-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(backupBrokerProps)
+ .workerProps(backupWorkerProps)
+ .build();
+
+ primary.start();
+ primary.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of " + PRIMARY_CLUSTER_ALIAS + "-connect-cluster did not start in time.");
+
+ backup.start();
+ backup.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of " + BACKUP_CLUSTER_ALIAS + "-connect-cluster did not start in time.");
+
+ createTopics();
+
+ dummyConsumption();
+
+ log.info(PRIMARY_CLUSTER_ALIAS + " REST service: {}", primary.endpointForResource("connectors"));
+ log.info(BACKUP_CLUSTER_ALIAS + " REST service: {}", backup.endpointForResource("connectors"));
+ log.info(PRIMARY_CLUSTER_ALIAS + " brokers: {}", primary.kafka().bootstrapServers());
+ log.info(BACKUP_CLUSTER_ALIAS + " brokers: {}", backup.kafka().bootstrapServers());
+
+ // now that the brokers are running, we can finish setting up the Connectors
+ mm2Props.put(PRIMARY_CLUSTER_ALIAS + ".bootstrap.servers", primary.kafka().bootstrapServers());
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + ".bootstrap.servers", backup.kafka().bootstrapServers());
+
+ Exit.setExitProcedure((status, errorCode) -> exited.set(true));
+ }
+
+ public void shutdownClusters() {
+ for (String x : primary.connectors()) {
+ primary.deleteConnector(x);
+ }
+ for (String x : backup.connectors()) {
+ backup.deleteConnector(x);
+ }
+ deleteAllTopics(primary.kafka());
+ deleteAllTopics(backup.kafka());
+ primary.stop();
+ backup.stop();
+ try {
+ assertFalse(exited.get());
+ } finally {
+ Exit.resetExitProcedure();
+ }
+ }
+ /*
+ * launch the connectors on kafka connect cluster and check if they are running
+ */
+ protected static void waitUntilMirrorMakerIsRunning(EmbeddedConnectCluster connectCluster,
+ List<Class<? extends Connector>> connectorClasses, MirrorMakerConfig mm2Config,
+ String primary, String backup) throws InterruptedException {
+ for (int i = 0; i < connectorClasses.size(); i++) {
+ String connector = connectorClasses.get(i).getSimpleName();
+ connectCluster.configureConnector(connector, mm2Config.connectorBaseConfig(
+ new SourceAndTarget(primary, backup), connectorClasses.get(i)));
+ }
+
+ // we wait for the connector and tasks to come up for each connector, so that when we do the
+ // actual testing, we are certain that the tasks are up and running; this will prevent
+ // flaky tests where the connector and tasks didn't start up in time for the tests to be run
+ List<String> connectorNames = connectorClasses.stream().map(x -> x.getSimpleName())
+ .collect(Collectors.toList());
+ for (String connector : connectorNames) {
+ connectCluster.assertions().assertConnectorAndAtLeastNumTasksAreRunning(connector, 1,
+ "Connector " + connector + " tasks did not start in time on cluster: " + connectCluster);
+ }
+ }
+
+ /*
+ * delete all topics of the input kafka cluster
+ */
+ protected static void deleteAllTopics(EmbeddedKafkaCluster cluster) {
+ Admin client = cluster.createAdminClient();
+ try {
+ client.deleteTopics(client.listTopics().names().get());
+ } catch (Throwable e) {
+ // should not run into exception normally. In case of Exception,
+ // simply fail the test and investigate
+ }
+ }
+
+ /*
+ * retrieve the config value based on the input cluster, topic and config name
+ */
+ protected static String getTopicConfig(EmbeddedKafkaCluster cluster, String topic, String configName) {
+ Admin client = cluster.createAdminClient();
+ Collection<ConfigResource> cr = Collections.singleton(
+ new ConfigResource(ConfigResource.Type.TOPIC, topic));
+ try {
+ DescribeConfigsResult configsResult = client.describeConfigs(cr);
+ Config allConfigs = (Config) configsResult.all().get().values().toArray()[0];
+ Iterator<ConfigEntry> configIterator = allConfigs.entries().iterator();
+ while (configIterator.hasNext()) {
+ ConfigEntry currentConfig = configIterator.next();
+ if (currentConfig.name().equals(configName)) {
+ return currentConfig.value();
+ }
+ }
+ } catch (Throwable e) {
+ // should not run into exception normally. In case of Exception,
Review comment:
catching Throwable has been here since the original author wrote MM2. It seems a tricky thing and I am happy to hear your suggestions on what to put in the "catch" block.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc commented on a change in pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc commented on a change in pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#discussion_r527395668
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationSSLTest.java
##########
@@ -0,0 +1,89 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.common.network.Mode;
+import org.apache.kafka.connect.connector.Connector;
+import org.apache.kafka.connect.mirror.MirrorCheckpointConnector;
+import org.apache.kafka.connect.mirror.MirrorHeartbeatConnector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.MirrorSourceConnector;
+import org.apache.kafka.test.IntegrationTest;
+import org.apache.kafka.test.TestSslUtils;
+import org.apache.kafka.test.TestUtils;
+import kafka.server.KafkaConfig$;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import org.junit.experimental.categories.Category;
+import org.junit.Before;
+import org.junit.After;
+import org.junit.Test;
+
+/**
+ * Tests MM2 replication with SSL enabled at backup kafka cluster
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationSSLTest extends MirrorConnectorsIntegrationBaseTest {
+
+ private static final List<Class<? extends Connector>> CONNECTOR_LIST =
+ Arrays.asList(MirrorSourceConnector.class, MirrorCheckpointConnector.class, MirrorHeartbeatConnector.class);
+
+ @Before
+ public void setup() throws InterruptedException {
+ try {
+ Map<String, Object> sslConfig = TestSslUtils.createSslConfig(false, true, Mode.SERVER, TestUtils.tempFile(), "testCert");
+ backupBrokerProps.put(KafkaConfig$.MODULE$.ListenersProp(), "SSL://localhost:0");
Review comment:
Good question. The primary reasons are: (1) I have seen some MM2 use cases which mirror data from in-house Kafka cluster to public hosted Kafka. For example, https://issues.apache.org/jira/browse/KAFKA-10704 So this setup (non-SSL -> SSL) seems to represent a certain coverage of use cases. (2) There are 4 combinations between SSL and non-SSL, so adding all combinations are great, but also verbose. Proving MM2 can work with one SSL-enabled cluster should be convincing enough to claim "MM2 can mirror in SSL case".
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc edited a comment on pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc edited a comment on pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#issuecomment-714955565
Thanks @mimaison for your high-level advice and detailed review.
(1) I responded to your every comments. A "thumb-up" means I made the suggested change
(2) regarding the increased complexity, here is my analysis for each test case
(a) `testReplication`: This is an existing test and no new stuff are added, except checking if topic config are also mirrored. If we believe the topic config validation is trivial, I am more than happy to remove it
(b) `testReplicationWithEmptyPartition`: This is an existing test and no new stuff are added
(c) `testOneWayReplicationWithAutoOffsetSync`: This is an existing test and no new stuff are added
(d) `testWithBrokerRestart`: This is a **new** test, which introduced background producer and consumer, called `ThreadedProducer` and `ThreadedConsumer`. The purpose of background producer and consumer is to better test the failure case to avoid serialization (produce -> broker restart -> consumer) which can not reveal the insight that consumers consume the same records more than once when broker failure happens.
(e) `MirrorConnectorsIntegrationSSLTest`: This is a **new** test and it should be pretty lean and neat.
In addition, the **new** base test class `MirrorConnectorsIntegrationBaseTest` follows the existing practice of K-stream integration test structure https://github.com/apache/kafka/blob/trunk/streams/src/test/java/org/apache/kafka/streams/integration/ResetIntegrationWithSslTest.java#L37 so I assume it is likely the right way tp structure tests with more than one scenarios (SSL v.s. non-SSL)
If we have to control the complexity, I would prefer to drop `testWithBrokerRestart` and keep `MirrorConnectorsIntegrationSSLTest`, as it makes sense to run simple validation in SSL setup.
Thanks and would like to hear more thoughts and feedback.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] rhauch commented on pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
rhauch commented on pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#issuecomment-739083056
@ning2008wisc, @mimaison: Please see https://issues.apache.org/jira/browse/KAFKA-10811 and #9698 for a required fix to the `MirrorConnectorsIntegrationTest` to prevent the `testReplication()` method from prematurely terminating the builds. Please be sure this (or an equivalent) is incorporated into this refactoring.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc commented on a change in pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc commented on a change in pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#discussion_r527396830
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationBaseTest.java
##########
@@ -0,0 +1,407 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.CommonClientConfigs;
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.Config;
+import org.apache.kafka.clients.admin.ConfigEntry;
+import org.apache.kafka.clients.admin.DescribeConfigsResult;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.config.ConfigResource;
+import org.apache.kafka.common.config.SslConfigs;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.config.types.Password;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.connector.Connector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.SourceAndTarget;
+import org.apache.kafka.connect.util.clusters.EmbeddedConnectCluster;
+import org.apache.kafka.connect.util.clusters.EmbeddedKafkaCluster;
+import static org.apache.kafka.connect.mirror.TestUtils.expectedRecords;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+import org.apache.kafka.test.IntegrationTest;
+import kafka.server.KafkaConfig$;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import static org.junit.Assert.assertFalse;
+import org.junit.experimental.categories.Category;
+
+/**
+ * Common Test functions for MM2 integration tests
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationBaseTest {
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationBaseTest.class);
+
+ protected static final int NUM_RECORDS_PER_PARTITION = 10;
+ public static final int NUM_PARTITIONS = 10;
+ protected static final int NUM_RECORDS_PRODUCED = NUM_PARTITIONS * NUM_RECORDS_PER_PARTITION;
+ protected static final int RECORD_TRANSFER_DURATION_MS = 30_000;
+ protected static final int CHECKPOINT_DURATION_MS = 20_000;
+ protected static final int RECORD_CONSUME_DURATION_MS = 20_000;
+ protected static final int OFFSET_SYNC_DURATION_MS = 30_000;
+ protected static final int NUM_WORKERS = 3;
+ protected static final int CONSUMER_POLL_TIMEOUT_MS = 500;
+ protected static final int BROKER_RESTART_TIMEOUT_MS = 10_000;
+ protected static final String PRIMARY_CLUSTER_ALIAS = "primary";
+ protected static final String BACKUP_CLUSTER_ALIAS = "backup";
+
+ protected Map<String, String> mm2Props;
+ protected MirrorMakerConfig mm2Config;
+ protected EmbeddedConnectCluster primary;
+ protected EmbeddedConnectCluster backup;
+
+ private final AtomicBoolean exited = new AtomicBoolean(false);
+ private Properties primaryBrokerProps = new Properties();
+ protected Properties backupBrokerProps = new Properties();
+ private Map<String, String> primaryWorkerProps = new HashMap<>();
+ private Map<String, String> backupWorkerProps = new HashMap<>();
+ private Properties sslProps = new Properties();
+
+ private void loadSslPropsFromBrokerConfig() {
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, backupBrokerProps.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG));
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, ((Password) backupBrokerProps.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)).value());
+ sslProps.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL");
+ }
+
+ protected void setSslConfig() {
+ // set SSL config for kafka connect worker
+ backupWorkerProps.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> BACKUP_CLUSTER_ALIAS + "." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ // set SSL config for producer used by source task in MM2
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> BACKUP_CLUSTER_ALIAS + ".producer." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ }
+
+ protected void startClusters() throws InterruptedException {
+ primaryBrokerProps.put("auto.create.topics.enable", "false");
+ backupBrokerProps.put("auto.create.topics.enable", "false");
+
+ mm2Props = basicMM2Config();
+
+ // if backup kafka cluster contains ssl config, enable ssl of kafka connect and mm2
+ final Object listeners = backupBrokerProps.get(KafkaConfig$.MODULE$.ListenersProp());
+ if (listeners != null && listeners.toString().contains("SSL")) {
+ loadSslPropsFromBrokerConfig();
+ setSslConfig();
+ }
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+ primaryWorkerProps = mm2Config.workerConfig(new SourceAndTarget(BACKUP_CLUSTER_ALIAS, PRIMARY_CLUSTER_ALIAS));
+ backupWorkerProps.putAll(mm2Config.workerConfig(new SourceAndTarget(PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS)));
+
+ primary = new EmbeddedConnectCluster.Builder()
+ .name(PRIMARY_CLUSTER_ALIAS + "-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(primaryBrokerProps)
+ .workerProps(primaryWorkerProps)
+ .build();
+
+ backup = new EmbeddedConnectCluster.Builder()
+ .name(BACKUP_CLUSTER_ALIAS + "-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(backupBrokerProps)
+ .workerProps(backupWorkerProps)
+ .build();
+
+ primary.start();
+ primary.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of " + PRIMARY_CLUSTER_ALIAS + "-connect-cluster did not start in time.");
+
+ backup.start();
+ backup.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of " + BACKUP_CLUSTER_ALIAS + "-connect-cluster did not start in time.");
+
+ createTopics();
+
+ dummyConsumption();
+
+ log.info(PRIMARY_CLUSTER_ALIAS + " REST service: {}", primary.endpointForResource("connectors"));
+ log.info(BACKUP_CLUSTER_ALIAS + " REST service: {}", backup.endpointForResource("connectors"));
+ log.info(PRIMARY_CLUSTER_ALIAS + " brokers: {}", primary.kafka().bootstrapServers());
+ log.info(BACKUP_CLUSTER_ALIAS + " brokers: {}", backup.kafka().bootstrapServers());
+
+ // now that the brokers are running, we can finish setting up the Connectors
+ mm2Props.put(PRIMARY_CLUSTER_ALIAS + ".bootstrap.servers", primary.kafka().bootstrapServers());
+ mm2Props.put(BACKUP_CLUSTER_ALIAS + ".bootstrap.servers", backup.kafka().bootstrapServers());
+
+ Exit.setExitProcedure((status, errorCode) -> exited.set(true));
+ }
+
+ public void shutdownClusters() {
+ for (String x : primary.connectors()) {
+ primary.deleteConnector(x);
+ }
+ for (String x : backup.connectors()) {
+ backup.deleteConnector(x);
+ }
+ deleteAllTopics(primary.kafka());
+ deleteAllTopics(backup.kafka());
+ primary.stop();
+ backup.stop();
+ try {
+ assertFalse(exited.get());
+ } finally {
+ Exit.resetExitProcedure();
+ }
+ }
+ /*
+ * launch the connectors on kafka connect cluster and check if they are running
+ */
+ protected static void waitUntilMirrorMakerIsRunning(EmbeddedConnectCluster connectCluster,
+ List<Class<? extends Connector>> connectorClasses, MirrorMakerConfig mm2Config,
+ String primary, String backup) throws InterruptedException {
+ for (int i = 0; i < connectorClasses.size(); i++) {
+ String connector = connectorClasses.get(i).getSimpleName();
+ connectCluster.configureConnector(connector, mm2Config.connectorBaseConfig(
+ new SourceAndTarget(primary, backup), connectorClasses.get(i)));
+ }
+
+ // we wait for the connector and tasks to come up for each connector, so that when we do the
+ // actual testing, we are certain that the tasks are up and running; this will prevent
+ // flaky tests where the connector and tasks didn't start up in time for the tests to be run
+ List<String> connectorNames = connectorClasses.stream().map(x -> x.getSimpleName())
+ .collect(Collectors.toList());
+ for (String connector : connectorNames) {
+ connectCluster.assertions().assertConnectorAndAtLeastNumTasksAreRunning(connector, 1,
+ "Connector " + connector + " tasks did not start in time on cluster: " + connectCluster);
+ }
+ }
+
+ /*
+ * delete all topics of the input kafka cluster
+ */
+ protected static void deleteAllTopics(EmbeddedKafkaCluster cluster) {
+ Admin client = cluster.createAdminClient();
+ try {
+ client.deleteTopics(client.listTopics().names().get());
+ } catch (Throwable e) {
+ // should not run into exception normally. In case of Exception,
+ // simply fail the test and investigate
+ }
+ }
+
+ /*
+ * retrieve the config value based on the input cluster, topic and config name
+ */
+ protected static String getTopicConfig(EmbeddedKafkaCluster cluster, String topic, String configName) {
+ Admin client = cluster.createAdminClient();
+ Collection<ConfigResource> cr = Collections.singleton(
+ new ConfigResource(ConfigResource.Type.TOPIC, topic));
+ try {
+ DescribeConfigsResult configsResult = client.describeConfigs(cr);
+ Config allConfigs = (Config) configsResult.all().get().values().toArray()[0];
+ Iterator<ConfigEntry> configIterator = allConfigs.entries().iterator();
+ while (configIterator.hasNext()) {
+ ConfigEntry currentConfig = configIterator.next();
+ if (currentConfig.name().equals(configName)) {
+ return currentConfig.value();
+ }
+ }
+ } catch (Throwable e) {
+ // should not run into exception normally. In case of Exception,
Review comment:
catching Throwable has been there since the original author wrote MM2. It seems a tricky thing and I am happy to hear your suggestions on what to put in the "catch" block.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] mimaison commented on a change in pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
mimaison commented on a change in pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#discussion_r510011670
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationBaseTest.java
##########
@@ -0,0 +1,423 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.CommonClientConfigs;
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.Config;
+import org.apache.kafka.clients.admin.ConfigEntry;
+import org.apache.kafka.clients.admin.DescribeConfigsResult;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.config.ConfigResource;
+import org.apache.kafka.common.config.SslConfigs;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.config.types.Password;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.errors.ConnectException;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.SourceAndTarget;
+import org.apache.kafka.connect.util.clusters.EmbeddedConnectCluster;
+import org.apache.kafka.connect.util.clusters.EmbeddedKafkaCluster;
+import org.apache.kafka.test.IntegrationTest;
+import org.junit.experimental.categories.Category;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.kafka.connect.mirror.TestUtils.expectedRecords;
+import static org.apache.kafka.connect.util.clusters.EmbeddedConnectClusterAssertions.CONNECTOR_SETUP_DURATION_MS;
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+import kafka.server.KafkaConfig$;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertFalse;
+//import org.junit.After;
Review comment:
We can remove this
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationBaseTest.java
##########
@@ -0,0 +1,423 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.CommonClientConfigs;
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.Config;
+import org.apache.kafka.clients.admin.ConfigEntry;
+import org.apache.kafka.clients.admin.DescribeConfigsResult;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.config.ConfigResource;
+import org.apache.kafka.common.config.SslConfigs;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.config.types.Password;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.errors.ConnectException;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.SourceAndTarget;
+import org.apache.kafka.connect.util.clusters.EmbeddedConnectCluster;
+import org.apache.kafka.connect.util.clusters.EmbeddedKafkaCluster;
+import org.apache.kafka.test.IntegrationTest;
+import org.junit.experimental.categories.Category;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.kafka.connect.mirror.TestUtils.expectedRecords;
+import static org.apache.kafka.connect.util.clusters.EmbeddedConnectClusterAssertions.CONNECTOR_SETUP_DURATION_MS;
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+import kafka.server.KafkaConfig$;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertFalse;
+//import org.junit.After;
+
+/**
+ * Common Test functions for MM2 integration tests
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationBaseTest {
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationBaseTest.class);
+
+ protected static final int NUM_RECORDS_PER_PARTITION = 10;
+ public static final int NUM_PARTITIONS = 10;
+ protected static final int NUM_RECORDS_PRODUCED = NUM_PARTITIONS * NUM_RECORDS_PER_PARTITION;
+ protected static final int RECORD_TRANSFER_DURATION_MS = 30_000;
+ protected static final int CHECKPOINT_DURATION_MS = 20_000;
+ protected static final int RECORD_CONSUME_DURATION_MS = 20_000;
+ protected static final int OFFSET_SYNC_DURATION_MS = 30_000;
+ protected static final int NUM_WORKERS = 3;
+
+
+ protected Map<String, String> mm2Props;
+ protected MirrorMakerConfig mm2Config;
+ protected EmbeddedConnectCluster primary;
+ protected EmbeddedConnectCluster backup;
+
+ private final AtomicBoolean exited = new AtomicBoolean(false);
+ private Properties primaryBrokerProps = new Properties();
+ protected Properties backupBrokerProps = new Properties();
+ private Map<String, String> primaryWorkerProps;
+ private Map<String, String> backupWorkerProps = new HashMap<>();
+ private Properties sslProps = new Properties();
+
+ private void loadSslPropsFromBrokerConfig() {
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, backupBrokerProps.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG));
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, ((Password) backupBrokerProps.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)).value());
+ sslProps.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL");
+ }
+
+ protected void setSslConfig() {
+ // set SSL config for kafka connect worker
+ backupWorkerProps.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> "backup." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ // set SSL config for producer used by source task in MM2
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> "backup.producer." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ }
+
+ protected void startClusters() throws InterruptedException {
+ primaryBrokerProps.put("auto.create.topics.enable", "false");
+ backupBrokerProps.put("auto.create.topics.enable", "false");
+
+ mm2Props = basicMM2Config();
+
+ // if backup kafka cluster contains ssl config, enable ssl of kafka connect and mm2
+ final Object listeners = backupBrokerProps.get(KafkaConfig$.MODULE$.ListenersProp());
+ if (listeners != null && listeners.toString().contains("SSL")) {
+ loadSslPropsFromBrokerConfig();
+ setSslConfig();
+ }
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+ primaryWorkerProps = mm2Config.workerConfig(new SourceAndTarget("backup", "primary"));
+ backupWorkerProps.putAll(mm2Config.workerConfig(new SourceAndTarget("primary", "backup")));
+
+ primary = new EmbeddedConnectCluster.Builder()
+ .name("primary-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(primaryBrokerProps)
+ .workerProps(primaryWorkerProps)
+ .build();
+
+ backup = new EmbeddedConnectCluster.Builder()
+ .name("backup-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(backupBrokerProps)
+ .workerProps(backupWorkerProps)
+ .build();
+
+ primary.start();
+ primary.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of primary-connect-cluster did not start in time.");
+
+ backup.start();
+ backup.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of backup-connect-cluster did not start in time.");
+
+ createTopics();
+
+ dummyConsumption();
+
+ log.info("primary REST service: {}", primary.endpointForResource("connectors"));
+ log.info("backup REST service: {}", backup.endpointForResource("connectors"));
+ log.info("primary brokers: {}", primary.kafka().bootstrapServers());
+ log.info("backup brokers: {}", backup.kafka().bootstrapServers());
+
+ // now that the brokers are running, we can finish setting up the Connectors
+ mm2Props.put("primary.bootstrap.servers", primary.kafka().bootstrapServers());
+ mm2Props.put("backup.bootstrap.servers", backup.kafka().bootstrapServers());
+
+ Exit.setExitProcedure((status, errorCode) -> exited.set(true));
+ }
+
+ public void shutdownClusters() {
+ for (String x : primary.connectors()) {
+ primary.deleteConnector(x);
+ }
+ for (String x : backup.connectors()) {
+ backup.deleteConnector(x);
+ }
+ deleteAllTopics(primary.kafka());
+ deleteAllTopics(backup.kafka());
+ primary.stop();
+ backup.stop();
+ try {
+ assertFalse(exited.get());
+ } finally {
+ Exit.resetExitProcedure();
+ }
+ }
+ /*
+ * launch the connectors on kafka connect cluster and check if they are running
+ */
+ protected static void waitUntilMirrorMakerIsRunning(EmbeddedConnectCluster connectCluster,
+ List<Class> connectorClasses, MirrorMakerConfig mm2Config,
+ String primary, String backup) throws InterruptedException {
+ for (int i = 0; i < connectorClasses.size(); i++) {
+ String connector = connectorClasses.get(i).getSimpleName();
+ connectCluster.configureConnector(connector, mm2Config.connectorBaseConfig(
+ new SourceAndTarget(primary, backup), connectorClasses.get(i)));
+ }
+
+ // we wait for the connector and tasks to come up for each connector, so that when we do the
+ // actual testing, we are certain that the tasks are up and running; this will prevent
+ // flaky tests where the connector and tasks didn't start up in time for the tests to be
+ // run
+ List<String> connectorNames = connectorClasses.stream().map(x -> x.getSimpleName())
+ .collect(Collectors.toList());
+ for (String connector : connectorNames) {
+ connectCluster.assertions().assertConnectorAndAtLeastNumTasksAreRunning(connector, 1,
+ "Connector " + connector + " tasks did not start in time on cluster: " + connectCluster);
+ }
+ }
+
+ /*
+ * delete all topics of the input kafka cluster
+ */
+ protected static void deleteAllTopics(EmbeddedKafkaCluster cluster) {
+ Admin client = cluster.createAdminClient();
+ try {
+ client.deleteTopics(client.listTopics().names().get());
+ } catch (Throwable e) {
+ }
+ }
+
+ /*
+ * retrieve the config value based on the input cluster, topic and config name
+ */
+ protected static String getTopicConfig(EmbeddedKafkaCluster cluster, String topic, String configName) {
+ Admin client = cluster.createAdminClient();
+ Collection<ConfigResource> cr = Collections.singleton(
+ new ConfigResource(ConfigResource.Type.TOPIC, topic));
+ try {
+ DescribeConfigsResult configsResult = client.describeConfigs(cr);
+ Config allConfigs = (Config) configsResult.all().get().values().toArray()[0];
+ Iterator configIterator = allConfigs.entries().iterator();
Review comment:
`Iterator`-> `Iterator<ConfigEntry>`
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationBaseTest.java
##########
@@ -0,0 +1,423 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.CommonClientConfigs;
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.Config;
+import org.apache.kafka.clients.admin.ConfigEntry;
+import org.apache.kafka.clients.admin.DescribeConfigsResult;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.config.ConfigResource;
+import org.apache.kafka.common.config.SslConfigs;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.config.types.Password;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.errors.ConnectException;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.SourceAndTarget;
+import org.apache.kafka.connect.util.clusters.EmbeddedConnectCluster;
+import org.apache.kafka.connect.util.clusters.EmbeddedKafkaCluster;
+import org.apache.kafka.test.IntegrationTest;
+import org.junit.experimental.categories.Category;
Review comment:
This can go with the other `org.junit` imports below
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationTest.java
##########
@@ -0,0 +1,372 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.errors.TimeoutException;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.mirror.MirrorCheckpointConnector;
+import org.apache.kafka.connect.mirror.MirrorClient;
+import org.apache.kafka.connect.mirror.MirrorHeartbeatConnector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.MirrorSourceConnector;
+import org.apache.kafka.connect.mirror.utils.ThreadedConsumer;
+import org.apache.kafka.connect.mirror.utils.ThreadedProducer;
+import org.apache.kafka.test.IntegrationTest;
+import org.junit.Before;
+import org.junit.After;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Collections;
+import java.util.Map;
+import java.util.HashMap;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertNotNull;
+
+/**
+ * Tests MM2 replication and failover/failback logic.
+ *
+ * MM2 is configured with active/active replication between two Kafka clusters. Tests validate that
+ * records sent to either cluster arrive at the other cluster. Then, a consumer group is migrated from
+ * one cluster to the other and back. Tests validate that consumer offsets are translated and replicated
+ * between clusters during this failover and failback.
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationTest extends MirrorConnectorsIntegrationBaseTest {
+
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationTest.class);
Review comment:
It looks like this is not used, can we remove it?
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationTest.java
##########
@@ -0,0 +1,372 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.errors.TimeoutException;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.mirror.MirrorCheckpointConnector;
+import org.apache.kafka.connect.mirror.MirrorClient;
+import org.apache.kafka.connect.mirror.MirrorHeartbeatConnector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.MirrorSourceConnector;
+import org.apache.kafka.connect.mirror.utils.ThreadedConsumer;
+import org.apache.kafka.connect.mirror.utils.ThreadedProducer;
+import org.apache.kafka.test.IntegrationTest;
+import org.junit.Before;
+import org.junit.After;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Collections;
+import java.util.Map;
+import java.util.HashMap;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertNotNull;
+
+/**
+ * Tests MM2 replication and failover/failback logic.
+ *
+ * MM2 is configured with active/active replication between two Kafka clusters. Tests validate that
+ * records sent to either cluster arrive at the other cluster. Then, a consumer group is migrated from
+ * one cluster to the other and back. Tests validate that consumer offsets are translated and replicated
+ * between clusters during this failover and failback.
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationTest extends MirrorConnectorsIntegrationBaseTest {
+
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationTest.class);
+
+ private static final List<Class> CONNECTOR_LIST =
Review comment:
We can use `List<Class<? extends Connector>` to avoid the warning
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationTest.java
##########
@@ -0,0 +1,372 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.errors.TimeoutException;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.mirror.MirrorCheckpointConnector;
+import org.apache.kafka.connect.mirror.MirrorClient;
+import org.apache.kafka.connect.mirror.MirrorHeartbeatConnector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.MirrorSourceConnector;
+import org.apache.kafka.connect.mirror.utils.ThreadedConsumer;
+import org.apache.kafka.connect.mirror.utils.ThreadedProducer;
+import org.apache.kafka.test.IntegrationTest;
+import org.junit.Before;
+import org.junit.After;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Collections;
+import java.util.Map;
+import java.util.HashMap;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertNotNull;
+
+/**
+ * Tests MM2 replication and failover/failback logic.
+ *
+ * MM2 is configured with active/active replication between two Kafka clusters. Tests validate that
+ * records sent to either cluster arrive at the other cluster. Then, a consumer group is migrated from
+ * one cluster to the other and back. Tests validate that consumer offsets are translated and replicated
+ * between clusters during this failover and failback.
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationTest extends MirrorConnectorsIntegrationBaseTest {
+
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationTest.class);
+
+ private static final List<Class> CONNECTOR_LIST =
+ Arrays.asList(MirrorSourceConnector.class, MirrorCheckpointConnector.class, MirrorHeartbeatConnector.class);
+
+ @Before
+ public void setup() throws InterruptedException {
+ startClusters();
+ }
+
+ @After
+ public void close() {
+ shutdownClusters();
+ }
+
+ @Test
+ public void testReplication() throws InterruptedException {
+ produceMessages(primary, "test-topic-1");
+ produceMessages(backup, "test-topic-1");
+ String consumerGroupName = "consumer-group-testReplication";
+ Map<String, Object> consumerProps = new HashMap<String, Object>() {{
+ put("group.id", consumerGroupName);
+ put("auto.offset.reset", "latest");
+ }};
+ // create consumers before starting the connectors so we don't need to wait for discovery
+ Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps, "test-topic-1");
+ waitForConsumingAllRecords(primaryConsumer, 0);
+
+ Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(consumerProps, "test-topic-1");
+ waitForConsumingAllRecords(backupConsumer, 0);
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, "primary", "backup");
+ waitUntilMirrorMakerIsRunning(primary, CONNECTOR_LIST, mm2Config, "backup", "primary");
+
+ MirrorClient primaryClient = new MirrorClient(mm2Config.clientConfig("primary"));
+ MirrorClient backupClient = new MirrorClient(mm2Config.clientConfig("backup"));
+
+ assertEquals("topic config was not synced", TopicConfig.CLEANUP_POLICY_COMPACT,
+ getTopicConfig(backup.kafka(), "primary.test-topic-1", TopicConfig.CLEANUP_POLICY_CONFIG));
+
+ assertEquals("Records were not produced to primary cluster.", NUM_RECORDS_PRODUCED,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "test-topic-1").count());
+ assertEquals("Records were not replicated to backup cluster.", NUM_RECORDS_PRODUCED,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "primary.test-topic-1").count());
+ assertEquals("Records were not produced to backup cluster.", NUM_RECORDS_PRODUCED,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "test-topic-1").count());
+ assertEquals("Records were not replicated to primary cluster.", NUM_RECORDS_PRODUCED,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "backup.test-topic-1").count());
+
+ assertEquals("Primary cluster doesn't have all records from both clusters.", NUM_RECORDS_PRODUCED * 2,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED * 2, RECORD_TRANSFER_DURATION_MS, "backup.test-topic-1", "test-topic-1").count());
+ assertEquals("Backup cluster doesn't have all records from both clusters.", NUM_RECORDS_PRODUCED * 2,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED * 2, RECORD_TRANSFER_DURATION_MS, "primary.test-topic-1", "test-topic-1").count());
+
+ assertTrue("Heartbeats were not emitted to primary cluster.", primary.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "heartbeats").count() > 0);
+ assertTrue("Heartbeats were not emitted to backup cluster.", backup.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "heartbeats").count() > 0);
+ assertTrue("Heartbeats were not replicated downstream to backup cluster.", backup.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "primary.heartbeats").count() > 0);
+ assertTrue("Heartbeats were not replicated downstream to primary cluster.", primary.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "backup.heartbeats").count() > 0);
+
+ assertTrue("Did not find upstream primary cluster.", backupClient.upstreamClusters().contains("primary"));
+ assertEquals("Did not calculate replication hops correctly.", 1, backupClient.replicationHops("primary"));
+ assertTrue("Did not find upstream backup cluster.", primaryClient.upstreamClusters().contains("backup"));
+ assertEquals("Did not calculate replication hops correctly.", 1, primaryClient.replicationHops("backup"));
+ assertTrue("Checkpoints were not emitted downstream to backup cluster.", backup.kafka().consume(1,
+ CHECKPOINT_DURATION_MS, "primary.checkpoints.internal").count() > 0);
+
+ Map<TopicPartition, OffsetAndMetadata> backupOffsets = backupClient.remoteConsumerOffsets(consumerGroupName, "primary",
+ Duration.ofMillis(CHECKPOINT_DURATION_MS));
+
+ assertTrue("Offsets not translated downstream to backup cluster. Found: " + backupOffsets, backupOffsets.containsKey(
+ new TopicPartition("primary.test-topic-1", 0)));
+
+ // Failover consumer group to backup cluster.
+ primaryConsumer = backup.kafka().createConsumer(Collections.singletonMap("group.id", consumerGroupName));
+ primaryConsumer.assign(backupOffsets.keySet());
+ backupOffsets.forEach(primaryConsumer::seek);
+ primaryConsumer.poll(Duration.ofMillis(500));
+ primaryConsumer.commitAsync();
+
+ assertTrue("Consumer failedover to zero offset.", primaryConsumer.position(new TopicPartition("primary.test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedover beyond expected offset.", primaryConsumer.position(
+ new TopicPartition("primary.test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+ assertTrue("Checkpoints were not emitted upstream to primary cluster.", primary.kafka().consume(1,
+ CHECKPOINT_DURATION_MS, "backup.checkpoints.internal").count() > 0);
+
+ primaryConsumer.close();
+
+ waitForCondition(() -> {
+ try {
+ return primaryClient.remoteConsumerOffsets(consumerGroupName, "backup",
+ Duration.ofMillis(CHECKPOINT_DURATION_MS)).containsKey(new TopicPartition("backup.test-topic-1", 0));
+ } catch (Throwable e) {
+ return false;
+ }
+ }, CHECKPOINT_DURATION_MS, "Offsets not translated downstream to primary cluster.");
+
+ waitForCondition(() -> {
+ try {
+ return primaryClient.remoteConsumerOffsets(consumerGroupName, "backup",
+ Duration.ofMillis(CHECKPOINT_DURATION_MS)).containsKey(new TopicPartition("test-topic-1", 0));
+ } catch (Throwable e) {
+ return false;
+ }
+ }, CHECKPOINT_DURATION_MS, "Offsets not translated upstream to primary cluster.");
+
+ Map<TopicPartition, OffsetAndMetadata> primaryOffsets = primaryClient.remoteConsumerOffsets(consumerGroupName, "backup",
+ Duration.ofMillis(CHECKPOINT_DURATION_MS));
+
+ // Failback consumer group to primary cluster
+ backupConsumer = primary.kafka().createConsumer(Collections.singletonMap("group.id", consumerGroupName));
+ backupConsumer.assign(primaryOffsets.keySet());
+ primaryOffsets.forEach(backupConsumer::seek);
+ backupConsumer.poll(Duration.ofMillis(500));
+ backupConsumer.commitAsync();
+
+ assertTrue("Consumer failedback to zero upstream offset.", backupConsumer.position(new TopicPartition("test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedback to zero downstream offset.", backupConsumer.position(new TopicPartition("backup.test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedback beyond expected upstream offset.", backupConsumer.position(
+ new TopicPartition("test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+ assertTrue("Consumer failedback beyond expected downstream offset.", backupConsumer.position(
+ new TopicPartition("backup.test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+
+ backupConsumer.close();
+
+ // create more matching topics
+ primary.kafka().createTopic("test-topic-2", NUM_PARTITIONS);
+ backup.kafka().createTopic("test-topic-3", NUM_PARTITIONS);
+
+ // only produce messages to the first partition
+ produceMessages(primary, "test-topic-2", 1);
+ produceMessages(backup, "test-topic-3", 1);
+
+ // expect total consumed messages equals to NUM_RECORDS_PER_PARTITION
+ assertEquals("Records were not produced to primary cluster.", NUM_RECORDS_PER_PARTITION,
+ primary.kafka().consume(NUM_RECORDS_PER_PARTITION, RECORD_TRANSFER_DURATION_MS, "test-topic-2").count());
+ assertEquals("Records were not produced to backup cluster.", NUM_RECORDS_PER_PARTITION,
+ backup.kafka().consume(NUM_RECORDS_PER_PARTITION, RECORD_TRANSFER_DURATION_MS, "test-topic-3").count());
+
+ assertEquals("New topic was not replicated to primary cluster.", NUM_RECORDS_PER_PARTITION,
+ primary.kafka().consume(NUM_RECORDS_PER_PARTITION, 2 * RECORD_TRANSFER_DURATION_MS, "backup.test-topic-3").count());
+ assertEquals("New topic was not replicated to backup cluster.", NUM_RECORDS_PER_PARTITION,
+ backup.kafka().consume(NUM_RECORDS_PER_PARTITION, 2 * RECORD_TRANSFER_DURATION_MS, "primary.test-topic-2").count());
+
+ }
+
+ @Test
+ public void testReplicationWithEmptyPartition() throws Exception {
+ String consumerGroupName = "consumer-group-testReplicationWithEmptyPartition";
+ Map<String, Object> consumerProps = Collections.singletonMap("group.id", consumerGroupName);
+
+ // create topic
+ String topic = "test-topic-with-empty-partition";
+ primary.kafka().createTopic(topic, NUM_PARTITIONS);
+
+ // produce to all test-topic-empty's partitions, except the last partition
+ produceMessages(primary, topic, NUM_PARTITIONS - 1);
+
+ // consume before starting the connectors so we don't need to wait for discovery
+ int expectedRecords = NUM_RECORDS_PER_PARTITION * (NUM_PARTITIONS - 1);
+ try (Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps, topic)) {
+ waitForConsumingAllRecords(primaryConsumer, expectedRecords);
+ }
+
+ // one way replication from primary to backup
+ mm2Props.put("backup->primary.enabled", "false");
+ mm2Config = new MirrorMakerConfig(mm2Props);
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, "primary", "backup");
+
+ // sleep few seconds to have MM2 finish replication so that "end" consumer will consume some record
+ Thread.sleep(TimeUnit.SECONDS.toMillis(3));
+
+ // consume all records from backup cluster
+ try (Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(consumerProps, "primary." + topic)) {
+ waitForConsumingAllRecords(backupConsumer, expectedRecords);
+ }
+
+ Admin backupClient = backup.kafka().createAdminClient();
+ // retrieve the consumer group offset from backup cluster
+ Map<TopicPartition, OffsetAndMetadata> remoteOffsets =
+ backupClient.listConsumerGroupOffsets(consumerGroupName).partitionsToOffsetAndMetadata().get();
+ // pinpoint the offset of the last partition which does not receive records
+ OffsetAndMetadata offset = remoteOffsets.get(new TopicPartition("primary." + topic, NUM_PARTITIONS - 1));
+ // offset of the last partition should exist, but its value should be 0
+ assertNotNull("Offset of last partition was not replicated", offset);
+ assertEquals("Offset of last partition is not zero", 0, offset.offset());
+ }
+
+ @Test
+ public void testOneWayReplicationWithAutoOffsetSync() throws InterruptedException {
+ produceMessages(primary, "test-topic-1");
+ String consumerGroupName = "consumer-group-testOneWayReplicationWithAutoOffsetSync";
+ Map<String, Object> consumerProps = new HashMap<String, Object>() {{
+ put("group.id", consumerGroupName);
+ put("auto.offset.reset", "earliest");
+ }};
+ // create consumers before starting the connectors so we don't need to wait for discovery
+ try (Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps,
+ "test-topic-1")) {
+ // we need to wait for consuming all the records for MM2 replicating the expected offsets
+ waitForConsumingAllRecords(primaryConsumer, NUM_RECORDS_PRODUCED);
+ }
+
+ // enable automated consumer group offset sync
+ mm2Props.put("sync.group.offsets.enabled", "true");
+ mm2Props.put("sync.group.offsets.interval.seconds", "1");
+ // one way replication from primary to backup
+ mm2Props.put("backup->primary.enabled", "false");
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, "primary", "backup");
+
+ // create a consumer at backup cluster with same consumer group Id to consume 1 topic
+ Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(
+ consumerProps, "primary.test-topic-1");
+
+ waitForConsumerGroupOffsetSync(backup, backupConsumer, Collections.singletonList("primary.test-topic-1"),
+ consumerGroupName, NUM_RECORDS_PRODUCED);
+
+ ConsumerRecords records = backupConsumer.poll(Duration.ofMillis(500));
Review comment:
`ConsumerRecords` -> `ConsumerRecords<byte[], byte[]>`
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationBaseTest.java
##########
@@ -0,0 +1,423 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.CommonClientConfigs;
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.Config;
+import org.apache.kafka.clients.admin.ConfigEntry;
+import org.apache.kafka.clients.admin.DescribeConfigsResult;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.config.ConfigResource;
+import org.apache.kafka.common.config.SslConfigs;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.config.types.Password;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.errors.ConnectException;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.SourceAndTarget;
+import org.apache.kafka.connect.util.clusters.EmbeddedConnectCluster;
+import org.apache.kafka.connect.util.clusters.EmbeddedKafkaCluster;
+import org.apache.kafka.test.IntegrationTest;
+import org.junit.experimental.categories.Category;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.kafka.connect.mirror.TestUtils.expectedRecords;
+import static org.apache.kafka.connect.util.clusters.EmbeddedConnectClusterAssertions.CONNECTOR_SETUP_DURATION_MS;
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+import kafka.server.KafkaConfig$;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertFalse;
+//import org.junit.After;
+
+/**
+ * Common Test functions for MM2 integration tests
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationBaseTest {
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationBaseTest.class);
+
+ protected static final int NUM_RECORDS_PER_PARTITION = 10;
+ public static final int NUM_PARTITIONS = 10;
+ protected static final int NUM_RECORDS_PRODUCED = NUM_PARTITIONS * NUM_RECORDS_PER_PARTITION;
+ protected static final int RECORD_TRANSFER_DURATION_MS = 30_000;
+ protected static final int CHECKPOINT_DURATION_MS = 20_000;
+ protected static final int RECORD_CONSUME_DURATION_MS = 20_000;
+ protected static final int OFFSET_SYNC_DURATION_MS = 30_000;
+ protected static final int NUM_WORKERS = 3;
+
+
+ protected Map<String, String> mm2Props;
+ protected MirrorMakerConfig mm2Config;
+ protected EmbeddedConnectCluster primary;
+ protected EmbeddedConnectCluster backup;
+
+ private final AtomicBoolean exited = new AtomicBoolean(false);
+ private Properties primaryBrokerProps = new Properties();
+ protected Properties backupBrokerProps = new Properties();
+ private Map<String, String> primaryWorkerProps;
+ private Map<String, String> backupWorkerProps = new HashMap<>();
+ private Properties sslProps = new Properties();
+
+ private void loadSslPropsFromBrokerConfig() {
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, backupBrokerProps.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG));
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, ((Password) backupBrokerProps.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)).value());
+ sslProps.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL");
+ }
+
+ protected void setSslConfig() {
+ // set SSL config for kafka connect worker
+ backupWorkerProps.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> "backup." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ // set SSL config for producer used by source task in MM2
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> "backup.producer." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ }
+
+ protected void startClusters() throws InterruptedException {
+ primaryBrokerProps.put("auto.create.topics.enable", "false");
+ backupBrokerProps.put("auto.create.topics.enable", "false");
+
+ mm2Props = basicMM2Config();
+
+ // if backup kafka cluster contains ssl config, enable ssl of kafka connect and mm2
+ final Object listeners = backupBrokerProps.get(KafkaConfig$.MODULE$.ListenersProp());
+ if (listeners != null && listeners.toString().contains("SSL")) {
+ loadSslPropsFromBrokerConfig();
+ setSslConfig();
+ }
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+ primaryWorkerProps = mm2Config.workerConfig(new SourceAndTarget("backup", "primary"));
+ backupWorkerProps.putAll(mm2Config.workerConfig(new SourceAndTarget("primary", "backup")));
+
+ primary = new EmbeddedConnectCluster.Builder()
+ .name("primary-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(primaryBrokerProps)
+ .workerProps(primaryWorkerProps)
+ .build();
+
+ backup = new EmbeddedConnectCluster.Builder()
+ .name("backup-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(backupBrokerProps)
+ .workerProps(backupWorkerProps)
+ .build();
+
+ primary.start();
+ primary.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of primary-connect-cluster did not start in time.");
+
+ backup.start();
+ backup.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of backup-connect-cluster did not start in time.");
+
+ createTopics();
+
+ dummyConsumption();
+
+ log.info("primary REST service: {}", primary.endpointForResource("connectors"));
+ log.info("backup REST service: {}", backup.endpointForResource("connectors"));
+ log.info("primary brokers: {}", primary.kafka().bootstrapServers());
+ log.info("backup brokers: {}", backup.kafka().bootstrapServers());
+
+ // now that the brokers are running, we can finish setting up the Connectors
+ mm2Props.put("primary.bootstrap.servers", primary.kafka().bootstrapServers());
+ mm2Props.put("backup.bootstrap.servers", backup.kafka().bootstrapServers());
+
+ Exit.setExitProcedure((status, errorCode) -> exited.set(true));
+ }
+
+ public void shutdownClusters() {
+ for (String x : primary.connectors()) {
+ primary.deleteConnector(x);
+ }
+ for (String x : backup.connectors()) {
+ backup.deleteConnector(x);
+ }
+ deleteAllTopics(primary.kafka());
+ deleteAllTopics(backup.kafka());
+ primary.stop();
+ backup.stop();
+ try {
+ assertFalse(exited.get());
+ } finally {
+ Exit.resetExitProcedure();
+ }
+ }
+ /*
+ * launch the connectors on kafka connect cluster and check if they are running
+ */
+ protected static void waitUntilMirrorMakerIsRunning(EmbeddedConnectCluster connectCluster,
+ List<Class> connectorClasses, MirrorMakerConfig mm2Config,
+ String primary, String backup) throws InterruptedException {
+ for (int i = 0; i < connectorClasses.size(); i++) {
+ String connector = connectorClasses.get(i).getSimpleName();
+ connectCluster.configureConnector(connector, mm2Config.connectorBaseConfig(
+ new SourceAndTarget(primary, backup), connectorClasses.get(i)));
+ }
+
+ // we wait for the connector and tasks to come up for each connector, so that when we do the
+ // actual testing, we are certain that the tasks are up and running; this will prevent
+ // flaky tests where the connector and tasks didn't start up in time for the tests to be
+ // run
+ List<String> connectorNames = connectorClasses.stream().map(x -> x.getSimpleName())
+ .collect(Collectors.toList());
+ for (String connector : connectorNames) {
+ connectCluster.assertions().assertConnectorAndAtLeastNumTasksAreRunning(connector, 1,
+ "Connector " + connector + " tasks did not start in time on cluster: " + connectCluster);
+ }
+ }
+
+ /*
+ * delete all topics of the input kafka cluster
+ */
+ protected static void deleteAllTopics(EmbeddedKafkaCluster cluster) {
+ Admin client = cluster.createAdminClient();
+ try {
+ client.deleteTopics(client.listTopics().names().get());
+ } catch (Throwable e) {
+ }
+ }
+
+ /*
+ * retrieve the config value based on the input cluster, topic and config name
+ */
+ protected static String getTopicConfig(EmbeddedKafkaCluster cluster, String topic, String configName) {
+ Admin client = cluster.createAdminClient();
+ Collection<ConfigResource> cr = Collections.singleton(
+ new ConfigResource(ConfigResource.Type.TOPIC, topic));
+ try {
+ DescribeConfigsResult configsResult = client.describeConfigs(cr);
+ Config allConfigs = (Config) configsResult.all().get().values().toArray()[0];
+ Iterator configIterator = allConfigs.entries().iterator();
+ while (configIterator.hasNext()) {
+ ConfigEntry currentConfig = (ConfigEntry) configIterator.next();
+ if (currentConfig.name().equals(configName)) {
+ return currentConfig.value();
+ }
+ }
+ } catch (Throwable e) {
+ }
+ return null;
+ }
+
+ /*
+ * produce messages to the cluster and topic
+ */
+ protected void produceMessages(EmbeddedConnectCluster cluster, String topicName) {
+ Map<String, String> recordSent = expectedRecords(NUM_RECORDS_PRODUCED);
+ for (Map.Entry<String, String> entry : recordSent.entrySet()) {
+ cluster.kafka().produce(topicName, entry.getKey(), entry.getValue());
+ }
+ }
+
+ /*
+ * produce messages to the cluster and topic partition less than numPartitions
+ */
+ protected void produceMessages(EmbeddedConnectCluster cluster, String topicName, int numPartitions) {
+ int cnt = 0;
+ for (int r = 0; r < NUM_RECORDS_PER_PARTITION; r++)
+ for (int p = 0; p < numPartitions; p++)
+ cluster.kafka().produce(topicName, p, "key", "value-" + cnt++);
+ }
+
+ /*
+ * given consumer group, topics and expected number of records, make sure the consumer group
+ * offsets are eventually synced to the expected offset numbers
+ */
+ protected static <T> void waitForConsumerGroupOffsetSync(EmbeddedConnectCluster connect,
+ Consumer<T, T> consumer, List<String> topics, String consumerGroupId, int numRecords)
+ throws InterruptedException {
+ Admin adminClient = connect.kafka().createAdminClient();
+ List<TopicPartition> tps = new ArrayList<>(NUM_PARTITIONS * topics.size());
+ for (int partitionIndex = 0; partitionIndex < NUM_PARTITIONS; partitionIndex++) {
+ for (String topic : topics) {
+ tps.add(new TopicPartition(topic, partitionIndex));
+ }
+ }
+ long expectedTotalOffsets = numRecords * topics.size();
+
+ waitForCondition(() -> {
+ Map<TopicPartition, OffsetAndMetadata> consumerGroupOffsets =
+ adminClient.listConsumerGroupOffsets(consumerGroupId).partitionsToOffsetAndMetadata().get();
+ long consumerGroupOffsetTotal = consumerGroupOffsets.values().stream()
+ .mapToLong(metadata -> metadata.offset()).sum();
+
+ Map<TopicPartition, Long> offsets = consumer.endOffsets(tps, Duration.ofMillis(500));
+ long totalOffsets = offsets.values().stream().mapToLong(l -> l).sum();
+
+ // make sure the consumer group offsets are synced to expected number
+ return totalOffsets == expectedTotalOffsets && consumerGroupOffsetTotal > 0;
+ }, OFFSET_SYNC_DURATION_MS, "Consumer group offset sync is not complete in time");
+ }
+
+ /*
+ * make sure the consumer to consume expected number of records
+ */
+ protected static <T> void waitForConsumingAllRecords(Consumer<T, T> consumer, int numExpectedRecords)
+ throws InterruptedException {
+ final AtomicInteger totalConsumedRecords = new AtomicInteger(0);
+ waitForCondition(() -> {
+ ConsumerRecords<T, T> records = consumer.poll(Duration.ofMillis(500));
+ return numExpectedRecords == totalConsumedRecords.addAndGet(records.count());
+ }, RECORD_CONSUME_DURATION_MS, "Consumer cannot consume all records in time");
+ consumer.commitSync();
+ consumer.close();
+ }
+
+ /*
+ * MM2 config to use in integration tests
+ */
+ protected static Map<String, String> basicMM2Config() {
+ Map<String, String> mm2Props = new HashMap<>();
+ mm2Props.put("clusters", "primary, backup");
+ mm2Props.put("max.tasks", "10");
+ mm2Props.put("topics", "test-topic-.*, primary.test-topic-.*, backup.test-topic-.*");
+ mm2Props.put("groups", "consumer-group-.*");
+ mm2Props.put("primary->backup.enabled", "true");
+ mm2Props.put("backup->primary.enabled", "true");
+ mm2Props.put("sync.topic.acls.enabled", "false");
+ mm2Props.put("emit.checkpoints.interval.seconds", "1");
+ mm2Props.put("emit.heartbeats.interval.seconds", "1");
+ mm2Props.put("refresh.topics.interval.seconds", "1");
+ mm2Props.put("refresh.groups.interval.seconds", "1");
+ mm2Props.put("checkpoints.topic.replication.factor", "1");
+ mm2Props.put("heartbeats.topic.replication.factor", "1");
+ mm2Props.put("offset-syncs.topic.replication.factor", "1");
+ mm2Props.put("config.storage.replication.factor", "1");
+ mm2Props.put("offset.storage.replication.factor", "1");
+ mm2Props.put("status.storage.replication.factor", "1");
+ mm2Props.put("replication.factor", "1");
+
+ return mm2Props;
+ }
+
+ /*
+ * restart kafka broker and make sure it is successful
+ */
+ protected static void restartKafkaBroker(EmbeddedConnectCluster connect) throws InterruptedException {
+
+ connect.kafka().stopOnlyKafka();
+ log.trace("issue kafka stop");
+ connect.assertions().assertExactlyNumWorkersAreUp(NUM_WORKERS,
+ "Group of workers did not remain the same after broker shutdown");
+
+ // Allow for the workers to discover that the coordinator is unavailable, if the connector
+ // is set up on this current EmbeddedConnectCluster
+ Thread.sleep(TimeUnit.SECONDS.toMillis(10));
+
+ // Wait for the broker to be stopped
+ assertTrue("Failed to stop kafka broker within " + CONNECTOR_SETUP_DURATION_MS + "ms",
+ connect.kafka().runningBrokers().size() == 0);
+
+ connect.kafka().startOnlyKafkaOnSamePorts();
+ log.trace("issue kafka start");
+ // Allow for the kafka brokers to come back online
+ Thread.sleep(TimeUnit.SECONDS.toMillis(10));
+
+ connect.assertions().assertExactlyNumWorkersAreUp(NUM_WORKERS,
+ "Group of workers did not remain the same within the designated time.");
+
+ // Allow for the workers to rebalance and reach a steady state
+ Thread.sleep(TimeUnit.SECONDS.toMillis(10));
+
+ // Expect that the broker has started again
+ assertTrue("Failed to start kafka broker within " + CONNECTOR_SETUP_DURATION_MS + "ms",
+ connect.kafka().runningBrokers().size() > 0);
+ }
+
+ protected void createTopics() {
+ // to verify topic config will be sync-ed across clusters
+ Map<String, String> topicConfig = new HashMap<>();
+ topicConfig.put(TopicConfig.CLEANUP_POLICY_CONFIG, TopicConfig.CLEANUP_POLICY_COMPACT);
+ // create these topics before starting the connectors so we don't need to wait for discovery
+ primary.kafka().createTopic("test-topic-1", NUM_PARTITIONS, 1, topicConfig);
+ primary.kafka().createTopic("backup.test-topic-1", 1);
+ primary.kafka().createTopic("heartbeats", 1);
+ backup.kafka().createTopic("test-topic-1", NUM_PARTITIONS);
+ backup.kafka().createTopic("primary.test-topic-1", 1);
+ backup.kafka().createTopic("heartbeats", 1);
+ }
+
+ protected KafkaConsumer<String, String> createSslConsumer(Map<String, Object> consumerProps, String... topics) {
Review comment:
I find having a method specific for SSL strange. Callers should not have to know, this should be retrieved automatically based on the cluster being targeted
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationSSLTest.java
##########
@@ -0,0 +1,98 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.common.network.Mode;
+import org.apache.kafka.connect.mirror.MirrorCheckpointConnector;
+import org.apache.kafka.connect.mirror.MirrorHeartbeatConnector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.MirrorSourceConnector;
+import org.apache.kafka.test.IntegrationTest;
+import org.apache.kafka.test.TestSslUtils;
+import org.apache.kafka.test.TestUtils;
+import kafka.server.KafkaConfig$;
+
+import org.junit.experimental.categories.Category;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+import org.junit.Before;
+import org.junit.After;
+import org.junit.Test;
+
+/**
+ * Tests MM2 replication with SSL enabled at backup kafka cluster
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationSSLTest extends MirrorConnectorsIntegrationBaseTest {
+
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationSSLTest.class);
+
+ private static final List<Class> CONNECTOR_LIST =
+ Arrays.asList(MirrorSourceConnector.class, MirrorCheckpointConnector.class, MirrorHeartbeatConnector.class);
+
+ @Before
+ public void setup() throws InterruptedException {
+ try {
+ Map<String, Object> sslConfig = TestSslUtils.createSslConfig(false, true, Mode.SERVER, TestUtils.tempFile(), "testCert");
+ backupBrokerProps.put(KafkaConfig$.MODULE$.ListenersProp(), "SSL://localhost:0");
+ backupBrokerProps.put(KafkaConfig$.MODULE$.InterBrokerListenerNameProp(), "SSL");
+ backupBrokerProps.putAll(sslConfig);
+ } catch (final Exception e) {
+ throw new RuntimeException(e);
+ }
+ startClusters();
+ }
+
+ @After
+ public void close() {
+ shutdownClusters();
+ }
+
+ @Test
+ public void testReplicationSSL() throws InterruptedException {
+ produceMessages(primary, "test-topic-1");
+
+ // create consumers before starting the connectors so we don't need to wait for discovery
+ try (Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(
+ Collections.singletonMap("group.id", "consumer-group-1"), "test-topic-1")) {
+ // we need to wait for consuming all the records for MM2 replicating the expected offsets
+ waitForConsumingAllRecords(primaryConsumer, NUM_RECORDS_PRODUCED);
+ }
+
+ // one-way replication from primary -> backup
+ mm2Props.put("backup->primary.enabled", "false");
+ mm2Config = new MirrorMakerConfig(mm2Props);
+
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, "primary", "backup");
+
+ // sleep few seconds to let MM2 replicate some records for "end" consumer to consume them
+ Thread.sleep(TimeUnit.SECONDS.toMillis(3));
Review comment:
That looks pretty brittle? Is there a condition we can wait on?
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationBaseTest.java
##########
@@ -0,0 +1,423 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.CommonClientConfigs;
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.Config;
+import org.apache.kafka.clients.admin.ConfigEntry;
+import org.apache.kafka.clients.admin.DescribeConfigsResult;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.config.ConfigResource;
+import org.apache.kafka.common.config.SslConfigs;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.config.types.Password;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.errors.ConnectException;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.SourceAndTarget;
+import org.apache.kafka.connect.util.clusters.EmbeddedConnectCluster;
+import org.apache.kafka.connect.util.clusters.EmbeddedKafkaCluster;
+import org.apache.kafka.test.IntegrationTest;
+import org.junit.experimental.categories.Category;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.kafka.connect.mirror.TestUtils.expectedRecords;
+import static org.apache.kafka.connect.util.clusters.EmbeddedConnectClusterAssertions.CONNECTOR_SETUP_DURATION_MS;
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+import kafka.server.KafkaConfig$;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertFalse;
+//import org.junit.After;
+
+/**
+ * Common Test functions for MM2 integration tests
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationBaseTest {
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationBaseTest.class);
+
+ protected static final int NUM_RECORDS_PER_PARTITION = 10;
+ public static final int NUM_PARTITIONS = 10;
+ protected static final int NUM_RECORDS_PRODUCED = NUM_PARTITIONS * NUM_RECORDS_PER_PARTITION;
+ protected static final int RECORD_TRANSFER_DURATION_MS = 30_000;
+ protected static final int CHECKPOINT_DURATION_MS = 20_000;
+ protected static final int RECORD_CONSUME_DURATION_MS = 20_000;
+ protected static final int OFFSET_SYNC_DURATION_MS = 30_000;
+ protected static final int NUM_WORKERS = 3;
+
+
+ protected Map<String, String> mm2Props;
+ protected MirrorMakerConfig mm2Config;
+ protected EmbeddedConnectCluster primary;
+ protected EmbeddedConnectCluster backup;
+
+ private final AtomicBoolean exited = new AtomicBoolean(false);
+ private Properties primaryBrokerProps = new Properties();
+ protected Properties backupBrokerProps = new Properties();
+ private Map<String, String> primaryWorkerProps;
Review comment:
Should we do `new HashMap<>();` like the line below? Why is it different?
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationTest.java
##########
@@ -0,0 +1,372 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.errors.TimeoutException;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.mirror.MirrorCheckpointConnector;
+import org.apache.kafka.connect.mirror.MirrorClient;
+import org.apache.kafka.connect.mirror.MirrorHeartbeatConnector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.MirrorSourceConnector;
+import org.apache.kafka.connect.mirror.utils.ThreadedConsumer;
+import org.apache.kafka.connect.mirror.utils.ThreadedProducer;
+import org.apache.kafka.test.IntegrationTest;
+import org.junit.Before;
+import org.junit.After;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Collections;
+import java.util.Map;
+import java.util.HashMap;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertNotNull;
+
+/**
+ * Tests MM2 replication and failover/failback logic.
+ *
+ * MM2 is configured with active/active replication between two Kafka clusters. Tests validate that
+ * records sent to either cluster arrive at the other cluster. Then, a consumer group is migrated from
+ * one cluster to the other and back. Tests validate that consumer offsets are translated and replicated
+ * between clusters during this failover and failback.
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationTest extends MirrorConnectorsIntegrationBaseTest {
+
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationTest.class);
+
+ private static final List<Class> CONNECTOR_LIST =
+ Arrays.asList(MirrorSourceConnector.class, MirrorCheckpointConnector.class, MirrorHeartbeatConnector.class);
+
+ @Before
+ public void setup() throws InterruptedException {
Review comment:
Can we move this in the base class?
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationTest.java
##########
@@ -0,0 +1,372 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.errors.TimeoutException;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.mirror.MirrorCheckpointConnector;
+import org.apache.kafka.connect.mirror.MirrorClient;
+import org.apache.kafka.connect.mirror.MirrorHeartbeatConnector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.MirrorSourceConnector;
+import org.apache.kafka.connect.mirror.utils.ThreadedConsumer;
+import org.apache.kafka.connect.mirror.utils.ThreadedProducer;
+import org.apache.kafka.test.IntegrationTest;
+import org.junit.Before;
+import org.junit.After;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Collections;
+import java.util.Map;
+import java.util.HashMap;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertNotNull;
+
+/**
+ * Tests MM2 replication and failover/failback logic.
+ *
+ * MM2 is configured with active/active replication between two Kafka clusters. Tests validate that
+ * records sent to either cluster arrive at the other cluster. Then, a consumer group is migrated from
+ * one cluster to the other and back. Tests validate that consumer offsets are translated and replicated
+ * between clusters during this failover and failback.
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationTest extends MirrorConnectorsIntegrationBaseTest {
+
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationTest.class);
+
+ private static final List<Class> CONNECTOR_LIST =
+ Arrays.asList(MirrorSourceConnector.class, MirrorCheckpointConnector.class, MirrorHeartbeatConnector.class);
+
+ @Before
+ public void setup() throws InterruptedException {
+ startClusters();
+ }
+
+ @After
+ public void close() {
+ shutdownClusters();
+ }
+
+ @Test
+ public void testReplication() throws InterruptedException {
+ produceMessages(primary, "test-topic-1");
+ produceMessages(backup, "test-topic-1");
+ String consumerGroupName = "consumer-group-testReplication";
+ Map<String, Object> consumerProps = new HashMap<String, Object>() {{
+ put("group.id", consumerGroupName);
+ put("auto.offset.reset", "latest");
+ }};
+ // create consumers before starting the connectors so we don't need to wait for discovery
+ Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps, "test-topic-1");
+ waitForConsumingAllRecords(primaryConsumer, 0);
+
+ Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(consumerProps, "test-topic-1");
+ waitForConsumingAllRecords(backupConsumer, 0);
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, "primary", "backup");
+ waitUntilMirrorMakerIsRunning(primary, CONNECTOR_LIST, mm2Config, "backup", "primary");
+
+ MirrorClient primaryClient = new MirrorClient(mm2Config.clientConfig("primary"));
+ MirrorClient backupClient = new MirrorClient(mm2Config.clientConfig("backup"));
+
+ assertEquals("topic config was not synced", TopicConfig.CLEANUP_POLICY_COMPACT,
+ getTopicConfig(backup.kafka(), "primary.test-topic-1", TopicConfig.CLEANUP_POLICY_CONFIG));
+
+ assertEquals("Records were not produced to primary cluster.", NUM_RECORDS_PRODUCED,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "test-topic-1").count());
+ assertEquals("Records were not replicated to backup cluster.", NUM_RECORDS_PRODUCED,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "primary.test-topic-1").count());
+ assertEquals("Records were not produced to backup cluster.", NUM_RECORDS_PRODUCED,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "test-topic-1").count());
+ assertEquals("Records were not replicated to primary cluster.", NUM_RECORDS_PRODUCED,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "backup.test-topic-1").count());
+
+ assertEquals("Primary cluster doesn't have all records from both clusters.", NUM_RECORDS_PRODUCED * 2,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED * 2, RECORD_TRANSFER_DURATION_MS, "backup.test-topic-1", "test-topic-1").count());
+ assertEquals("Backup cluster doesn't have all records from both clusters.", NUM_RECORDS_PRODUCED * 2,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED * 2, RECORD_TRANSFER_DURATION_MS, "primary.test-topic-1", "test-topic-1").count());
+
+ assertTrue("Heartbeats were not emitted to primary cluster.", primary.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "heartbeats").count() > 0);
+ assertTrue("Heartbeats were not emitted to backup cluster.", backup.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "heartbeats").count() > 0);
+ assertTrue("Heartbeats were not replicated downstream to backup cluster.", backup.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "primary.heartbeats").count() > 0);
+ assertTrue("Heartbeats were not replicated downstream to primary cluster.", primary.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "backup.heartbeats").count() > 0);
+
+ assertTrue("Did not find upstream primary cluster.", backupClient.upstreamClusters().contains("primary"));
+ assertEquals("Did not calculate replication hops correctly.", 1, backupClient.replicationHops("primary"));
+ assertTrue("Did not find upstream backup cluster.", primaryClient.upstreamClusters().contains("backup"));
+ assertEquals("Did not calculate replication hops correctly.", 1, primaryClient.replicationHops("backup"));
+ assertTrue("Checkpoints were not emitted downstream to backup cluster.", backup.kafka().consume(1,
+ CHECKPOINT_DURATION_MS, "primary.checkpoints.internal").count() > 0);
+
+ Map<TopicPartition, OffsetAndMetadata> backupOffsets = backupClient.remoteConsumerOffsets(consumerGroupName, "primary",
+ Duration.ofMillis(CHECKPOINT_DURATION_MS));
+
+ assertTrue("Offsets not translated downstream to backup cluster. Found: " + backupOffsets, backupOffsets.containsKey(
+ new TopicPartition("primary.test-topic-1", 0)));
+
+ // Failover consumer group to backup cluster.
+ primaryConsumer = backup.kafka().createConsumer(Collections.singletonMap("group.id", consumerGroupName));
+ primaryConsumer.assign(backupOffsets.keySet());
+ backupOffsets.forEach(primaryConsumer::seek);
+ primaryConsumer.poll(Duration.ofMillis(500));
+ primaryConsumer.commitAsync();
+
+ assertTrue("Consumer failedover to zero offset.", primaryConsumer.position(new TopicPartition("primary.test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedover beyond expected offset.", primaryConsumer.position(
+ new TopicPartition("primary.test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+ assertTrue("Checkpoints were not emitted upstream to primary cluster.", primary.kafka().consume(1,
+ CHECKPOINT_DURATION_MS, "backup.checkpoints.internal").count() > 0);
+
+ primaryConsumer.close();
+
+ waitForCondition(() -> {
+ try {
+ return primaryClient.remoteConsumerOffsets(consumerGroupName, "backup",
+ Duration.ofMillis(CHECKPOINT_DURATION_MS)).containsKey(new TopicPartition("backup.test-topic-1", 0));
+ } catch (Throwable e) {
+ return false;
+ }
+ }, CHECKPOINT_DURATION_MS, "Offsets not translated downstream to primary cluster.");
+
+ waitForCondition(() -> {
+ try {
+ return primaryClient.remoteConsumerOffsets(consumerGroupName, "backup",
+ Duration.ofMillis(CHECKPOINT_DURATION_MS)).containsKey(new TopicPartition("test-topic-1", 0));
+ } catch (Throwable e) {
+ return false;
+ }
+ }, CHECKPOINT_DURATION_MS, "Offsets not translated upstream to primary cluster.");
+
+ Map<TopicPartition, OffsetAndMetadata> primaryOffsets = primaryClient.remoteConsumerOffsets(consumerGroupName, "backup",
+ Duration.ofMillis(CHECKPOINT_DURATION_MS));
+
+ // Failback consumer group to primary cluster
+ backupConsumer = primary.kafka().createConsumer(Collections.singletonMap("group.id", consumerGroupName));
+ backupConsumer.assign(primaryOffsets.keySet());
+ primaryOffsets.forEach(backupConsumer::seek);
+ backupConsumer.poll(Duration.ofMillis(500));
Review comment:
We seem to use `poll(Duration.ofMillis(500))` in many places, can we have a constant?
##########
File path: build.gradle
##########
@@ -2058,6 +2058,7 @@ project(':connect:mirror') {
testCompile libs.junitJupiterApi
testCompile libs.junitVintageEngine
testCompile libs.mockitoCore
+ testCompile libs.bcpkix
Review comment:
Is this needed at compile time? As far as I can tell, it's only needed when running the SSL test, so it could be `testRuntime libs.bcpkix`
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationBaseTest.java
##########
@@ -0,0 +1,423 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.CommonClientConfigs;
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.Config;
+import org.apache.kafka.clients.admin.ConfigEntry;
+import org.apache.kafka.clients.admin.DescribeConfigsResult;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.config.ConfigResource;
+import org.apache.kafka.common.config.SslConfigs;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.config.types.Password;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.errors.ConnectException;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.SourceAndTarget;
+import org.apache.kafka.connect.util.clusters.EmbeddedConnectCluster;
+import org.apache.kafka.connect.util.clusters.EmbeddedKafkaCluster;
+import org.apache.kafka.test.IntegrationTest;
+import org.junit.experimental.categories.Category;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.kafka.connect.mirror.TestUtils.expectedRecords;
+import static org.apache.kafka.connect.util.clusters.EmbeddedConnectClusterAssertions.CONNECTOR_SETUP_DURATION_MS;
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+import kafka.server.KafkaConfig$;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertFalse;
+//import org.junit.After;
+
+/**
+ * Common Test functions for MM2 integration tests
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationBaseTest {
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationBaseTest.class);
+
+ protected static final int NUM_RECORDS_PER_PARTITION = 10;
+ public static final int NUM_PARTITIONS = 10;
+ protected static final int NUM_RECORDS_PRODUCED = NUM_PARTITIONS * NUM_RECORDS_PER_PARTITION;
+ protected static final int RECORD_TRANSFER_DURATION_MS = 30_000;
+ protected static final int CHECKPOINT_DURATION_MS = 20_000;
+ protected static final int RECORD_CONSUME_DURATION_MS = 20_000;
+ protected static final int OFFSET_SYNC_DURATION_MS = 30_000;
+ protected static final int NUM_WORKERS = 3;
+
+
+ protected Map<String, String> mm2Props;
+ protected MirrorMakerConfig mm2Config;
+ protected EmbeddedConnectCluster primary;
+ protected EmbeddedConnectCluster backup;
+
+ private final AtomicBoolean exited = new AtomicBoolean(false);
+ private Properties primaryBrokerProps = new Properties();
+ protected Properties backupBrokerProps = new Properties();
+ private Map<String, String> primaryWorkerProps;
+ private Map<String, String> backupWorkerProps = new HashMap<>();
+ private Properties sslProps = new Properties();
+
+ private void loadSslPropsFromBrokerConfig() {
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, backupBrokerProps.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG));
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, ((Password) backupBrokerProps.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)).value());
+ sslProps.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL");
+ }
+
+ protected void setSslConfig() {
+ // set SSL config for kafka connect worker
+ backupWorkerProps.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> "backup." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ // set SSL config for producer used by source task in MM2
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> "backup.producer." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ }
+
+ protected void startClusters() throws InterruptedException {
+ primaryBrokerProps.put("auto.create.topics.enable", "false");
+ backupBrokerProps.put("auto.create.topics.enable", "false");
+
+ mm2Props = basicMM2Config();
+
+ // if backup kafka cluster contains ssl config, enable ssl of kafka connect and mm2
+ final Object listeners = backupBrokerProps.get(KafkaConfig$.MODULE$.ListenersProp());
+ if (listeners != null && listeners.toString().contains("SSL")) {
+ loadSslPropsFromBrokerConfig();
+ setSslConfig();
+ }
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+ primaryWorkerProps = mm2Config.workerConfig(new SourceAndTarget("backup", "primary"));
+ backupWorkerProps.putAll(mm2Config.workerConfig(new SourceAndTarget("primary", "backup")));
+
+ primary = new EmbeddedConnectCluster.Builder()
+ .name("primary-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(primaryBrokerProps)
+ .workerProps(primaryWorkerProps)
+ .build();
+
+ backup = new EmbeddedConnectCluster.Builder()
+ .name("backup-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(backupBrokerProps)
+ .workerProps(backupWorkerProps)
+ .build();
+
+ primary.start();
+ primary.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of primary-connect-cluster did not start in time.");
+
+ backup.start();
+ backup.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of backup-connect-cluster did not start in time.");
+
+ createTopics();
+
+ dummyConsumption();
+
+ log.info("primary REST service: {}", primary.endpointForResource("connectors"));
+ log.info("backup REST service: {}", backup.endpointForResource("connectors"));
+ log.info("primary brokers: {}", primary.kafka().bootstrapServers());
+ log.info("backup brokers: {}", backup.kafka().bootstrapServers());
+
+ // now that the brokers are running, we can finish setting up the Connectors
+ mm2Props.put("primary.bootstrap.servers", primary.kafka().bootstrapServers());
+ mm2Props.put("backup.bootstrap.servers", backup.kafka().bootstrapServers());
+
+ Exit.setExitProcedure((status, errorCode) -> exited.set(true));
+ }
+
+ public void shutdownClusters() {
+ for (String x : primary.connectors()) {
+ primary.deleteConnector(x);
+ }
+ for (String x : backup.connectors()) {
+ backup.deleteConnector(x);
+ }
+ deleteAllTopics(primary.kafka());
+ deleteAllTopics(backup.kafka());
+ primary.stop();
+ backup.stop();
+ try {
+ assertFalse(exited.get());
+ } finally {
+ Exit.resetExitProcedure();
+ }
+ }
+ /*
+ * launch the connectors on kafka connect cluster and check if they are running
+ */
+ protected static void waitUntilMirrorMakerIsRunning(EmbeddedConnectCluster connectCluster,
+ List<Class> connectorClasses, MirrorMakerConfig mm2Config,
+ String primary, String backup) throws InterruptedException {
+ for (int i = 0; i < connectorClasses.size(); i++) {
+ String connector = connectorClasses.get(i).getSimpleName();
+ connectCluster.configureConnector(connector, mm2Config.connectorBaseConfig(
+ new SourceAndTarget(primary, backup), connectorClasses.get(i)));
+ }
+
+ // we wait for the connector and tasks to come up for each connector, so that when we do the
+ // actual testing, we are certain that the tasks are up and running; this will prevent
+ // flaky tests where the connector and tasks didn't start up in time for the tests to be
+ // run
+ List<String> connectorNames = connectorClasses.stream().map(x -> x.getSimpleName())
+ .collect(Collectors.toList());
+ for (String connector : connectorNames) {
+ connectCluster.assertions().assertConnectorAndAtLeastNumTasksAreRunning(connector, 1,
+ "Connector " + connector + " tasks did not start in time on cluster: " + connectCluster);
+ }
+ }
+
+ /*
+ * delete all topics of the input kafka cluster
+ */
+ protected static void deleteAllTopics(EmbeddedKafkaCluster cluster) {
+ Admin client = cluster.createAdminClient();
+ try {
+ client.deleteTopics(client.listTopics().names().get());
+ } catch (Throwable e) {
Review comment:
What do we do if there's an exception? If it's expected, let's make it clear
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationBaseTest.java
##########
@@ -0,0 +1,423 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.CommonClientConfigs;
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.Config;
+import org.apache.kafka.clients.admin.ConfigEntry;
+import org.apache.kafka.clients.admin.DescribeConfigsResult;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.config.ConfigResource;
+import org.apache.kafka.common.config.SslConfigs;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.config.types.Password;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.errors.ConnectException;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.SourceAndTarget;
+import org.apache.kafka.connect.util.clusters.EmbeddedConnectCluster;
+import org.apache.kafka.connect.util.clusters.EmbeddedKafkaCluster;
+import org.apache.kafka.test.IntegrationTest;
+import org.junit.experimental.categories.Category;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.kafka.connect.mirror.TestUtils.expectedRecords;
+import static org.apache.kafka.connect.util.clusters.EmbeddedConnectClusterAssertions.CONNECTOR_SETUP_DURATION_MS;
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+import kafka.server.KafkaConfig$;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertFalse;
+//import org.junit.After;
+
+/**
+ * Common Test functions for MM2 integration tests
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationBaseTest {
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationBaseTest.class);
+
+ protected static final int NUM_RECORDS_PER_PARTITION = 10;
+ public static final int NUM_PARTITIONS = 10;
+ protected static final int NUM_RECORDS_PRODUCED = NUM_PARTITIONS * NUM_RECORDS_PER_PARTITION;
+ protected static final int RECORD_TRANSFER_DURATION_MS = 30_000;
+ protected static final int CHECKPOINT_DURATION_MS = 20_000;
+ protected static final int RECORD_CONSUME_DURATION_MS = 20_000;
+ protected static final int OFFSET_SYNC_DURATION_MS = 30_000;
+ protected static final int NUM_WORKERS = 3;
+
+
+ protected Map<String, String> mm2Props;
+ protected MirrorMakerConfig mm2Config;
+ protected EmbeddedConnectCluster primary;
+ protected EmbeddedConnectCluster backup;
+
+ private final AtomicBoolean exited = new AtomicBoolean(false);
+ private Properties primaryBrokerProps = new Properties();
+ protected Properties backupBrokerProps = new Properties();
+ private Map<String, String> primaryWorkerProps;
+ private Map<String, String> backupWorkerProps = new HashMap<>();
+ private Properties sslProps = new Properties();
+
+ private void loadSslPropsFromBrokerConfig() {
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, backupBrokerProps.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG));
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, ((Password) backupBrokerProps.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)).value());
+ sslProps.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL");
+ }
+
+ protected void setSslConfig() {
+ // set SSL config for kafka connect worker
+ backupWorkerProps.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> "backup." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ // set SSL config for producer used by source task in MM2
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> "backup.producer." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ }
+
+ protected void startClusters() throws InterruptedException {
+ primaryBrokerProps.put("auto.create.topics.enable", "false");
+ backupBrokerProps.put("auto.create.topics.enable", "false");
+
+ mm2Props = basicMM2Config();
+
+ // if backup kafka cluster contains ssl config, enable ssl of kafka connect and mm2
+ final Object listeners = backupBrokerProps.get(KafkaConfig$.MODULE$.ListenersProp());
+ if (listeners != null && listeners.toString().contains("SSL")) {
+ loadSslPropsFromBrokerConfig();
+ setSslConfig();
+ }
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+ primaryWorkerProps = mm2Config.workerConfig(new SourceAndTarget("backup", "primary"));
+ backupWorkerProps.putAll(mm2Config.workerConfig(new SourceAndTarget("primary", "backup")));
+
+ primary = new EmbeddedConnectCluster.Builder()
+ .name("primary-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(primaryBrokerProps)
+ .workerProps(primaryWorkerProps)
+ .build();
+
+ backup = new EmbeddedConnectCluster.Builder()
+ .name("backup-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(backupBrokerProps)
+ .workerProps(backupWorkerProps)
+ .build();
+
+ primary.start();
+ primary.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of primary-connect-cluster did not start in time.");
+
+ backup.start();
+ backup.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of backup-connect-cluster did not start in time.");
+
+ createTopics();
+
+ dummyConsumption();
+
+ log.info("primary REST service: {}", primary.endpointForResource("connectors"));
+ log.info("backup REST service: {}", backup.endpointForResource("connectors"));
+ log.info("primary brokers: {}", primary.kafka().bootstrapServers());
+ log.info("backup brokers: {}", backup.kafka().bootstrapServers());
+
+ // now that the brokers are running, we can finish setting up the Connectors
+ mm2Props.put("primary.bootstrap.servers", primary.kafka().bootstrapServers());
+ mm2Props.put("backup.bootstrap.servers", backup.kafka().bootstrapServers());
+
+ Exit.setExitProcedure((status, errorCode) -> exited.set(true));
+ }
+
+ public void shutdownClusters() {
+ for (String x : primary.connectors()) {
+ primary.deleteConnector(x);
+ }
+ for (String x : backup.connectors()) {
+ backup.deleteConnector(x);
+ }
+ deleteAllTopics(primary.kafka());
+ deleteAllTopics(backup.kafka());
+ primary.stop();
+ backup.stop();
+ try {
+ assertFalse(exited.get());
+ } finally {
+ Exit.resetExitProcedure();
+ }
+ }
+ /*
+ * launch the connectors on kafka connect cluster and check if they are running
+ */
+ protected static void waitUntilMirrorMakerIsRunning(EmbeddedConnectCluster connectCluster,
+ List<Class> connectorClasses, MirrorMakerConfig mm2Config,
+ String primary, String backup) throws InterruptedException {
+ for (int i = 0; i < connectorClasses.size(); i++) {
+ String connector = connectorClasses.get(i).getSimpleName();
+ connectCluster.configureConnector(connector, mm2Config.connectorBaseConfig(
+ new SourceAndTarget(primary, backup), connectorClasses.get(i)));
+ }
+
+ // we wait for the connector and tasks to come up for each connector, so that when we do the
+ // actual testing, we are certain that the tasks are up and running; this will prevent
+ // flaky tests where the connector and tasks didn't start up in time for the tests to be
+ // run
+ List<String> connectorNames = connectorClasses.stream().map(x -> x.getSimpleName())
+ .collect(Collectors.toList());
+ for (String connector : connectorNames) {
+ connectCluster.assertions().assertConnectorAndAtLeastNumTasksAreRunning(connector, 1,
+ "Connector " + connector + " tasks did not start in time on cluster: " + connectCluster);
+ }
+ }
+
+ /*
+ * delete all topics of the input kafka cluster
+ */
+ protected static void deleteAllTopics(EmbeddedKafkaCluster cluster) {
+ Admin client = cluster.createAdminClient();
+ try {
+ client.deleteTopics(client.listTopics().names().get());
+ } catch (Throwable e) {
+ }
+ }
+
+ /*
+ * retrieve the config value based on the input cluster, topic and config name
+ */
+ protected static String getTopicConfig(EmbeddedKafkaCluster cluster, String topic, String configName) {
+ Admin client = cluster.createAdminClient();
+ Collection<ConfigResource> cr = Collections.singleton(
+ new ConfigResource(ConfigResource.Type.TOPIC, topic));
+ try {
+ DescribeConfigsResult configsResult = client.describeConfigs(cr);
+ Config allConfigs = (Config) configsResult.all().get().values().toArray()[0];
+ Iterator configIterator = allConfigs.entries().iterator();
+ while (configIterator.hasNext()) {
+ ConfigEntry currentConfig = (ConfigEntry) configIterator.next();
+ if (currentConfig.name().equals(configName)) {
+ return currentConfig.value();
+ }
+ }
+ } catch (Throwable e) {
+ }
+ return null;
+ }
+
+ /*
+ * produce messages to the cluster and topic
+ */
+ protected void produceMessages(EmbeddedConnectCluster cluster, String topicName) {
+ Map<String, String> recordSent = expectedRecords(NUM_RECORDS_PRODUCED);
+ for (Map.Entry<String, String> entry : recordSent.entrySet()) {
+ cluster.kafka().produce(topicName, entry.getKey(), entry.getValue());
+ }
+ }
+
+ /*
+ * produce messages to the cluster and topic partition less than numPartitions
+ */
+ protected void produceMessages(EmbeddedConnectCluster cluster, String topicName, int numPartitions) {
+ int cnt = 0;
+ for (int r = 0; r < NUM_RECORDS_PER_PARTITION; r++)
+ for (int p = 0; p < numPartitions; p++)
+ cluster.kafka().produce(topicName, p, "key", "value-" + cnt++);
+ }
+
+ /*
+ * given consumer group, topics and expected number of records, make sure the consumer group
+ * offsets are eventually synced to the expected offset numbers
+ */
+ protected static <T> void waitForConsumerGroupOffsetSync(EmbeddedConnectCluster connect,
+ Consumer<T, T> consumer, List<String> topics, String consumerGroupId, int numRecords)
+ throws InterruptedException {
+ Admin adminClient = connect.kafka().createAdminClient();
+ List<TopicPartition> tps = new ArrayList<>(NUM_PARTITIONS * topics.size());
+ for (int partitionIndex = 0; partitionIndex < NUM_PARTITIONS; partitionIndex++) {
+ for (String topic : topics) {
+ tps.add(new TopicPartition(topic, partitionIndex));
+ }
+ }
+ long expectedTotalOffsets = numRecords * topics.size();
+
+ waitForCondition(() -> {
+ Map<TopicPartition, OffsetAndMetadata> consumerGroupOffsets =
+ adminClient.listConsumerGroupOffsets(consumerGroupId).partitionsToOffsetAndMetadata().get();
+ long consumerGroupOffsetTotal = consumerGroupOffsets.values().stream()
+ .mapToLong(metadata -> metadata.offset()).sum();
+
+ Map<TopicPartition, Long> offsets = consumer.endOffsets(tps, Duration.ofMillis(500));
+ long totalOffsets = offsets.values().stream().mapToLong(l -> l).sum();
+
+ // make sure the consumer group offsets are synced to expected number
+ return totalOffsets == expectedTotalOffsets && consumerGroupOffsetTotal > 0;
+ }, OFFSET_SYNC_DURATION_MS, "Consumer group offset sync is not complete in time");
+ }
+
+ /*
+ * make sure the consumer to consume expected number of records
+ */
+ protected static <T> void waitForConsumingAllRecords(Consumer<T, T> consumer, int numExpectedRecords)
+ throws InterruptedException {
+ final AtomicInteger totalConsumedRecords = new AtomicInteger(0);
+ waitForCondition(() -> {
+ ConsumerRecords<T, T> records = consumer.poll(Duration.ofMillis(500));
+ return numExpectedRecords == totalConsumedRecords.addAndGet(records.count());
+ }, RECORD_CONSUME_DURATION_MS, "Consumer cannot consume all records in time");
+ consumer.commitSync();
+ consumer.close();
+ }
+
+ /*
+ * MM2 config to use in integration tests
+ */
+ protected static Map<String, String> basicMM2Config() {
+ Map<String, String> mm2Props = new HashMap<>();
+ mm2Props.put("clusters", "primary, backup");
+ mm2Props.put("max.tasks", "10");
+ mm2Props.put("topics", "test-topic-.*, primary.test-topic-.*, backup.test-topic-.*");
+ mm2Props.put("groups", "consumer-group-.*");
+ mm2Props.put("primary->backup.enabled", "true");
+ mm2Props.put("backup->primary.enabled", "true");
+ mm2Props.put("sync.topic.acls.enabled", "false");
+ mm2Props.put("emit.checkpoints.interval.seconds", "1");
+ mm2Props.put("emit.heartbeats.interval.seconds", "1");
+ mm2Props.put("refresh.topics.interval.seconds", "1");
+ mm2Props.put("refresh.groups.interval.seconds", "1");
+ mm2Props.put("checkpoints.topic.replication.factor", "1");
+ mm2Props.put("heartbeats.topic.replication.factor", "1");
+ mm2Props.put("offset-syncs.topic.replication.factor", "1");
+ mm2Props.put("config.storage.replication.factor", "1");
+ mm2Props.put("offset.storage.replication.factor", "1");
+ mm2Props.put("status.storage.replication.factor", "1");
+ mm2Props.put("replication.factor", "1");
+
+ return mm2Props;
+ }
+
+ /*
+ * restart kafka broker and make sure it is successful
+ */
+ protected static void restartKafkaBroker(EmbeddedConnectCluster connect) throws InterruptedException {
+
+ connect.kafka().stopOnlyKafka();
+ log.trace("issue kafka stop");
+ connect.assertions().assertExactlyNumWorkersAreUp(NUM_WORKERS,
+ "Group of workers did not remain the same after broker shutdown");
+
+ // Allow for the workers to discover that the coordinator is unavailable, if the connector
+ // is set up on this current EmbeddedConnectCluster
+ Thread.sleep(TimeUnit.SECONDS.toMillis(10));
+
+ // Wait for the broker to be stopped
+ assertTrue("Failed to stop kafka broker within " + CONNECTOR_SETUP_DURATION_MS + "ms",
+ connect.kafka().runningBrokers().size() == 0);
+
+ connect.kafka().startOnlyKafkaOnSamePorts();
+ log.trace("issue kafka start");
+ // Allow for the kafka brokers to come back online
+ Thread.sleep(TimeUnit.SECONDS.toMillis(10));
+
+ connect.assertions().assertExactlyNumWorkersAreUp(NUM_WORKERS,
+ "Group of workers did not remain the same within the designated time.");
+
+ // Allow for the workers to rebalance and reach a steady state
+ Thread.sleep(TimeUnit.SECONDS.toMillis(10));
+
+ // Expect that the broker has started again
+ assertTrue("Failed to start kafka broker within " + CONNECTOR_SETUP_DURATION_MS + "ms",
+ connect.kafka().runningBrokers().size() > 0);
+ }
+
+ protected void createTopics() {
+ // to verify topic config will be sync-ed across clusters
+ Map<String, String> topicConfig = new HashMap<>();
+ topicConfig.put(TopicConfig.CLEANUP_POLICY_CONFIG, TopicConfig.CLEANUP_POLICY_COMPACT);
+ // create these topics before starting the connectors so we don't need to wait for discovery
+ primary.kafka().createTopic("test-topic-1", NUM_PARTITIONS, 1, topicConfig);
+ primary.kafka().createTopic("backup.test-topic-1", 1);
+ primary.kafka().createTopic("heartbeats", 1);
+ backup.kafka().createTopic("test-topic-1", NUM_PARTITIONS);
+ backup.kafka().createTopic("primary.test-topic-1", 1);
+ backup.kafka().createTopic("heartbeats", 1);
+ }
+
+ protected KafkaConsumer<String, String> createSslConsumer(Map<String, Object> consumerProps, String... topics) {
+ Map<String, Object> props = new HashMap<>(consumerProps);
+
+ if (props.get(ConsumerConfig.GROUP_ID_CONFIG) == null) {
+ props.put(ConsumerConfig.GROUP_ID_CONFIG, UUID.randomUUID().toString());
+ }
+ props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, backup.kafka().bootstrapServers());
+ props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
+ props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
+ props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
+ props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
+
+ // ssl config
+ props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+
+ KafkaConsumer<String, String> consumer;
+ try {
+ consumer = new KafkaConsumer<>(props);
+ } catch (Throwable t) {
+ throw new ConnectException("Failed to create consumer", t);
Review comment:
Why are we rethrowing as `ConnectException`?
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationSSLTest.java
##########
@@ -0,0 +1,98 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.common.network.Mode;
+import org.apache.kafka.connect.mirror.MirrorCheckpointConnector;
+import org.apache.kafka.connect.mirror.MirrorHeartbeatConnector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.MirrorSourceConnector;
+import org.apache.kafka.test.IntegrationTest;
+import org.apache.kafka.test.TestSslUtils;
+import org.apache.kafka.test.TestUtils;
+import kafka.server.KafkaConfig$;
+
+import org.junit.experimental.categories.Category;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+import org.junit.Before;
+import org.junit.After;
+import org.junit.Test;
+
+/**
+ * Tests MM2 replication with SSL enabled at backup kafka cluster
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationSSLTest extends MirrorConnectorsIntegrationBaseTest {
+
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationSSLTest.class);
+
+ private static final List<Class> CONNECTOR_LIST =
+ Arrays.asList(MirrorSourceConnector.class, MirrorCheckpointConnector.class, MirrorHeartbeatConnector.class);
+
+ @Before
+ public void setup() throws InterruptedException {
+ try {
+ Map<String, Object> sslConfig = TestSslUtils.createSslConfig(false, true, Mode.SERVER, TestUtils.tempFile(), "testCert");
+ backupBrokerProps.put(KafkaConfig$.MODULE$.ListenersProp(), "SSL://localhost:0");
+ backupBrokerProps.put(KafkaConfig$.MODULE$.InterBrokerListenerNameProp(), "SSL");
+ backupBrokerProps.putAll(sslConfig);
+ } catch (final Exception e) {
+ throw new RuntimeException(e);
Review comment:
Why are we rethrowing as `RuntimeException`?
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationSSLTest.java
##########
@@ -0,0 +1,98 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.common.network.Mode;
+import org.apache.kafka.connect.mirror.MirrorCheckpointConnector;
+import org.apache.kafka.connect.mirror.MirrorHeartbeatConnector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.MirrorSourceConnector;
+import org.apache.kafka.test.IntegrationTest;
+import org.apache.kafka.test.TestSslUtils;
+import org.apache.kafka.test.TestUtils;
+import kafka.server.KafkaConfig$;
+
+import org.junit.experimental.categories.Category;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+import org.junit.Before;
+import org.junit.After;
+import org.junit.Test;
+
+/**
+ * Tests MM2 replication with SSL enabled at backup kafka cluster
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationSSLTest extends MirrorConnectorsIntegrationBaseTest {
+
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationSSLTest.class);
+
+ private static final List<Class> CONNECTOR_LIST =
+ Arrays.asList(MirrorSourceConnector.class, MirrorCheckpointConnector.class, MirrorHeartbeatConnector.class);
+
+ @Before
+ public void setup() throws InterruptedException {
+ try {
+ Map<String, Object> sslConfig = TestSslUtils.createSslConfig(false, true, Mode.SERVER, TestUtils.tempFile(), "testCert");
+ backupBrokerProps.put(KafkaConfig$.MODULE$.ListenersProp(), "SSL://localhost:0");
+ backupBrokerProps.put(KafkaConfig$.MODULE$.InterBrokerListenerNameProp(), "SSL");
+ backupBrokerProps.putAll(sslConfig);
+ } catch (final Exception e) {
+ throw new RuntimeException(e);
+ }
+ startClusters();
+ }
+
+ @After
+ public void close() {
Review comment:
Can we move this in the base class?
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationSSLTest.java
##########
@@ -0,0 +1,98 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.common.network.Mode;
+import org.apache.kafka.connect.mirror.MirrorCheckpointConnector;
+import org.apache.kafka.connect.mirror.MirrorHeartbeatConnector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.MirrorSourceConnector;
+import org.apache.kafka.test.IntegrationTest;
+import org.apache.kafka.test.TestSslUtils;
+import org.apache.kafka.test.TestUtils;
+import kafka.server.KafkaConfig$;
+
+import org.junit.experimental.categories.Category;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+import org.junit.Before;
+import org.junit.After;
+import org.junit.Test;
+
+/**
+ * Tests MM2 replication with SSL enabled at backup kafka cluster
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationSSLTest extends MirrorConnectorsIntegrationBaseTest {
+
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationSSLTest.class);
Review comment:
It looks like this is not used anywhere
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationBaseTest.java
##########
@@ -0,0 +1,423 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.CommonClientConfigs;
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.Config;
+import org.apache.kafka.clients.admin.ConfigEntry;
+import org.apache.kafka.clients.admin.DescribeConfigsResult;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.config.ConfigResource;
+import org.apache.kafka.common.config.SslConfigs;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.config.types.Password;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.errors.ConnectException;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.SourceAndTarget;
+import org.apache.kafka.connect.util.clusters.EmbeddedConnectCluster;
+import org.apache.kafka.connect.util.clusters.EmbeddedKafkaCluster;
+import org.apache.kafka.test.IntegrationTest;
+import org.junit.experimental.categories.Category;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.kafka.connect.mirror.TestUtils.expectedRecords;
+import static org.apache.kafka.connect.util.clusters.EmbeddedConnectClusterAssertions.CONNECTOR_SETUP_DURATION_MS;
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+import kafka.server.KafkaConfig$;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertFalse;
+//import org.junit.After;
+
+/**
+ * Common Test functions for MM2 integration tests
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationBaseTest {
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationBaseTest.class);
+
+ protected static final int NUM_RECORDS_PER_PARTITION = 10;
+ public static final int NUM_PARTITIONS = 10;
+ protected static final int NUM_RECORDS_PRODUCED = NUM_PARTITIONS * NUM_RECORDS_PER_PARTITION;
+ protected static final int RECORD_TRANSFER_DURATION_MS = 30_000;
+ protected static final int CHECKPOINT_DURATION_MS = 20_000;
+ protected static final int RECORD_CONSUME_DURATION_MS = 20_000;
+ protected static final int OFFSET_SYNC_DURATION_MS = 30_000;
+ protected static final int NUM_WORKERS = 3;
+
+
+ protected Map<String, String> mm2Props;
+ protected MirrorMakerConfig mm2Config;
+ protected EmbeddedConnectCluster primary;
+ protected EmbeddedConnectCluster backup;
+
+ private final AtomicBoolean exited = new AtomicBoolean(false);
+ private Properties primaryBrokerProps = new Properties();
+ protected Properties backupBrokerProps = new Properties();
+ private Map<String, String> primaryWorkerProps;
+ private Map<String, String> backupWorkerProps = new HashMap<>();
+ private Properties sslProps = new Properties();
+
+ private void loadSslPropsFromBrokerConfig() {
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, backupBrokerProps.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG));
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, ((Password) backupBrokerProps.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)).value());
+ sslProps.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL");
+ }
+
+ protected void setSslConfig() {
+ // set SSL config for kafka connect worker
+ backupWorkerProps.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> "backup." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ // set SSL config for producer used by source task in MM2
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> "backup.producer." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ }
+
+ protected void startClusters() throws InterruptedException {
+ primaryBrokerProps.put("auto.create.topics.enable", "false");
+ backupBrokerProps.put("auto.create.topics.enable", "false");
+
+ mm2Props = basicMM2Config();
+
+ // if backup kafka cluster contains ssl config, enable ssl of kafka connect and mm2
+ final Object listeners = backupBrokerProps.get(KafkaConfig$.MODULE$.ListenersProp());
+ if (listeners != null && listeners.toString().contains("SSL")) {
+ loadSslPropsFromBrokerConfig();
+ setSslConfig();
+ }
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+ primaryWorkerProps = mm2Config.workerConfig(new SourceAndTarget("backup", "primary"));
+ backupWorkerProps.putAll(mm2Config.workerConfig(new SourceAndTarget("primary", "backup")));
+
+ primary = new EmbeddedConnectCluster.Builder()
+ .name("primary-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(primaryBrokerProps)
+ .workerProps(primaryWorkerProps)
+ .build();
+
+ backup = new EmbeddedConnectCluster.Builder()
+ .name("backup-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(backupBrokerProps)
+ .workerProps(backupWorkerProps)
+ .build();
+
+ primary.start();
+ primary.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of primary-connect-cluster did not start in time.");
+
+ backup.start();
+ backup.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of backup-connect-cluster did not start in time.");
+
+ createTopics();
+
+ dummyConsumption();
+
+ log.info("primary REST service: {}", primary.endpointForResource("connectors"));
+ log.info("backup REST service: {}", backup.endpointForResource("connectors"));
+ log.info("primary brokers: {}", primary.kafka().bootstrapServers());
+ log.info("backup brokers: {}", backup.kafka().bootstrapServers());
+
+ // now that the brokers are running, we can finish setting up the Connectors
+ mm2Props.put("primary.bootstrap.servers", primary.kafka().bootstrapServers());
+ mm2Props.put("backup.bootstrap.servers", backup.kafka().bootstrapServers());
+
+ Exit.setExitProcedure((status, errorCode) -> exited.set(true));
+ }
+
+ public void shutdownClusters() {
+ for (String x : primary.connectors()) {
+ primary.deleteConnector(x);
+ }
+ for (String x : backup.connectors()) {
+ backup.deleteConnector(x);
+ }
+ deleteAllTopics(primary.kafka());
+ deleteAllTopics(backup.kafka());
+ primary.stop();
+ backup.stop();
+ try {
+ assertFalse(exited.get());
+ } finally {
+ Exit.resetExitProcedure();
+ }
+ }
+ /*
+ * launch the connectors on kafka connect cluster and check if they are running
+ */
+ protected static void waitUntilMirrorMakerIsRunning(EmbeddedConnectCluster connectCluster,
+ List<Class> connectorClasses, MirrorMakerConfig mm2Config,
+ String primary, String backup) throws InterruptedException {
+ for (int i = 0; i < connectorClasses.size(); i++) {
+ String connector = connectorClasses.get(i).getSimpleName();
+ connectCluster.configureConnector(connector, mm2Config.connectorBaseConfig(
+ new SourceAndTarget(primary, backup), connectorClasses.get(i)));
+ }
+
+ // we wait for the connector and tasks to come up for each connector, so that when we do the
+ // actual testing, we are certain that the tasks are up and running; this will prevent
+ // flaky tests where the connector and tasks didn't start up in time for the tests to be
+ // run
+ List<String> connectorNames = connectorClasses.stream().map(x -> x.getSimpleName())
+ .collect(Collectors.toList());
+ for (String connector : connectorNames) {
+ connectCluster.assertions().assertConnectorAndAtLeastNumTasksAreRunning(connector, 1,
+ "Connector " + connector + " tasks did not start in time on cluster: " + connectCluster);
+ }
+ }
+
+ /*
+ * delete all topics of the input kafka cluster
+ */
+ protected static void deleteAllTopics(EmbeddedKafkaCluster cluster) {
+ Admin client = cluster.createAdminClient();
+ try {
+ client.deleteTopics(client.listTopics().names().get());
+ } catch (Throwable e) {
+ }
+ }
+
+ /*
+ * retrieve the config value based on the input cluster, topic and config name
+ */
+ protected static String getTopicConfig(EmbeddedKafkaCluster cluster, String topic, String configName) {
+ Admin client = cluster.createAdminClient();
+ Collection<ConfigResource> cr = Collections.singleton(
+ new ConfigResource(ConfigResource.Type.TOPIC, topic));
+ try {
+ DescribeConfigsResult configsResult = client.describeConfigs(cr);
+ Config allConfigs = (Config) configsResult.all().get().values().toArray()[0];
+ Iterator configIterator = allConfigs.entries().iterator();
+ while (configIterator.hasNext()) {
+ ConfigEntry currentConfig = (ConfigEntry) configIterator.next();
+ if (currentConfig.name().equals(configName)) {
+ return currentConfig.value();
+ }
+ }
+ } catch (Throwable e) {
+ }
+ return null;
+ }
+
+ /*
+ * produce messages to the cluster and topic
+ */
+ protected void produceMessages(EmbeddedConnectCluster cluster, String topicName) {
+ Map<String, String> recordSent = expectedRecords(NUM_RECORDS_PRODUCED);
+ for (Map.Entry<String, String> entry : recordSent.entrySet()) {
+ cluster.kafka().produce(topicName, entry.getKey(), entry.getValue());
+ }
+ }
+
+ /*
+ * produce messages to the cluster and topic partition less than numPartitions
+ */
+ protected void produceMessages(EmbeddedConnectCluster cluster, String topicName, int numPartitions) {
+ int cnt = 0;
+ for (int r = 0; r < NUM_RECORDS_PER_PARTITION; r++)
+ for (int p = 0; p < numPartitions; p++)
+ cluster.kafka().produce(topicName, p, "key", "value-" + cnt++);
+ }
+
+ /*
+ * given consumer group, topics and expected number of records, make sure the consumer group
+ * offsets are eventually synced to the expected offset numbers
+ */
+ protected static <T> void waitForConsumerGroupOffsetSync(EmbeddedConnectCluster connect,
+ Consumer<T, T> consumer, List<String> topics, String consumerGroupId, int numRecords)
+ throws InterruptedException {
+ Admin adminClient = connect.kafka().createAdminClient();
+ List<TopicPartition> tps = new ArrayList<>(NUM_PARTITIONS * topics.size());
+ for (int partitionIndex = 0; partitionIndex < NUM_PARTITIONS; partitionIndex++) {
+ for (String topic : topics) {
+ tps.add(new TopicPartition(topic, partitionIndex));
+ }
+ }
+ long expectedTotalOffsets = numRecords * topics.size();
+
+ waitForCondition(() -> {
+ Map<TopicPartition, OffsetAndMetadata> consumerGroupOffsets =
+ adminClient.listConsumerGroupOffsets(consumerGroupId).partitionsToOffsetAndMetadata().get();
+ long consumerGroupOffsetTotal = consumerGroupOffsets.values().stream()
+ .mapToLong(metadata -> metadata.offset()).sum();
+
+ Map<TopicPartition, Long> offsets = consumer.endOffsets(tps, Duration.ofMillis(500));
+ long totalOffsets = offsets.values().stream().mapToLong(l -> l).sum();
+
+ // make sure the consumer group offsets are synced to expected number
+ return totalOffsets == expectedTotalOffsets && consumerGroupOffsetTotal > 0;
+ }, OFFSET_SYNC_DURATION_MS, "Consumer group offset sync is not complete in time");
+ }
+
+ /*
+ * make sure the consumer to consume expected number of records
+ */
+ protected static <T> void waitForConsumingAllRecords(Consumer<T, T> consumer, int numExpectedRecords)
+ throws InterruptedException {
+ final AtomicInteger totalConsumedRecords = new AtomicInteger(0);
+ waitForCondition(() -> {
+ ConsumerRecords<T, T> records = consumer.poll(Duration.ofMillis(500));
+ return numExpectedRecords == totalConsumedRecords.addAndGet(records.count());
+ }, RECORD_CONSUME_DURATION_MS, "Consumer cannot consume all records in time");
+ consumer.commitSync();
+ consumer.close();
+ }
+
+ /*
+ * MM2 config to use in integration tests
+ */
+ protected static Map<String, String> basicMM2Config() {
+ Map<String, String> mm2Props = new HashMap<>();
+ mm2Props.put("clusters", "primary, backup");
+ mm2Props.put("max.tasks", "10");
+ mm2Props.put("topics", "test-topic-.*, primary.test-topic-.*, backup.test-topic-.*");
+ mm2Props.put("groups", "consumer-group-.*");
+ mm2Props.put("primary->backup.enabled", "true");
+ mm2Props.put("backup->primary.enabled", "true");
+ mm2Props.put("sync.topic.acls.enabled", "false");
+ mm2Props.put("emit.checkpoints.interval.seconds", "1");
+ mm2Props.put("emit.heartbeats.interval.seconds", "1");
+ mm2Props.put("refresh.topics.interval.seconds", "1");
+ mm2Props.put("refresh.groups.interval.seconds", "1");
+ mm2Props.put("checkpoints.topic.replication.factor", "1");
+ mm2Props.put("heartbeats.topic.replication.factor", "1");
+ mm2Props.put("offset-syncs.topic.replication.factor", "1");
+ mm2Props.put("config.storage.replication.factor", "1");
+ mm2Props.put("offset.storage.replication.factor", "1");
+ mm2Props.put("status.storage.replication.factor", "1");
+ mm2Props.put("replication.factor", "1");
+
+ return mm2Props;
+ }
+
+ /*
+ * restart kafka broker and make sure it is successful
+ */
+ protected static void restartKafkaBroker(EmbeddedConnectCluster connect) throws InterruptedException {
+
+ connect.kafka().stopOnlyKafka();
+ log.trace("issue kafka stop");
+ connect.assertions().assertExactlyNumWorkersAreUp(NUM_WORKERS,
+ "Group of workers did not remain the same after broker shutdown");
+
+ // Allow for the workers to discover that the coordinator is unavailable, if the connector
+ // is set up on this current EmbeddedConnectCluster
+ Thread.sleep(TimeUnit.SECONDS.toMillis(10));
+
+ // Wait for the broker to be stopped
+ assertTrue("Failed to stop kafka broker within " + CONNECTOR_SETUP_DURATION_MS + "ms",
+ connect.kafka().runningBrokers().size() == 0);
+
+ connect.kafka().startOnlyKafkaOnSamePorts();
+ log.trace("issue kafka start");
+ // Allow for the kafka brokers to come back online
+ Thread.sleep(TimeUnit.SECONDS.toMillis(10));
+
+ connect.assertions().assertExactlyNumWorkersAreUp(NUM_WORKERS,
+ "Group of workers did not remain the same within the designated time.");
+
+ // Allow for the workers to rebalance and reach a steady state
+ Thread.sleep(TimeUnit.SECONDS.toMillis(10));
+
+ // Expect that the broker has started again
+ assertTrue("Failed to start kafka broker within " + CONNECTOR_SETUP_DURATION_MS + "ms",
Review comment:
Should we use this check as a condition to wait? Sleeping 10 secs feels pretty brittle
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationBaseTest.java
##########
@@ -0,0 +1,423 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.CommonClientConfigs;
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.Config;
+import org.apache.kafka.clients.admin.ConfigEntry;
+import org.apache.kafka.clients.admin.DescribeConfigsResult;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.config.ConfigResource;
+import org.apache.kafka.common.config.SslConfigs;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.config.types.Password;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.errors.ConnectException;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.SourceAndTarget;
+import org.apache.kafka.connect.util.clusters.EmbeddedConnectCluster;
+import org.apache.kafka.connect.util.clusters.EmbeddedKafkaCluster;
+import org.apache.kafka.test.IntegrationTest;
+import org.junit.experimental.categories.Category;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.kafka.connect.mirror.TestUtils.expectedRecords;
+import static org.apache.kafka.connect.util.clusters.EmbeddedConnectClusterAssertions.CONNECTOR_SETUP_DURATION_MS;
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+import kafka.server.KafkaConfig$;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertFalse;
+//import org.junit.After;
+
+/**
+ * Common Test functions for MM2 integration tests
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationBaseTest {
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationBaseTest.class);
+
+ protected static final int NUM_RECORDS_PER_PARTITION = 10;
+ public static final int NUM_PARTITIONS = 10;
+ protected static final int NUM_RECORDS_PRODUCED = NUM_PARTITIONS * NUM_RECORDS_PER_PARTITION;
+ protected static final int RECORD_TRANSFER_DURATION_MS = 30_000;
+ protected static final int CHECKPOINT_DURATION_MS = 20_000;
+ protected static final int RECORD_CONSUME_DURATION_MS = 20_000;
+ protected static final int OFFSET_SYNC_DURATION_MS = 30_000;
+ protected static final int NUM_WORKERS = 3;
+
+
+ protected Map<String, String> mm2Props;
+ protected MirrorMakerConfig mm2Config;
+ protected EmbeddedConnectCluster primary;
+ protected EmbeddedConnectCluster backup;
+
+ private final AtomicBoolean exited = new AtomicBoolean(false);
+ private Properties primaryBrokerProps = new Properties();
+ protected Properties backupBrokerProps = new Properties();
Review comment:
Why is this field `protected` while `primaryBrokerProps` is `private`?
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationBaseTest.java
##########
@@ -0,0 +1,423 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.CommonClientConfigs;
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.Config;
+import org.apache.kafka.clients.admin.ConfigEntry;
+import org.apache.kafka.clients.admin.DescribeConfigsResult;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.config.ConfigResource;
+import org.apache.kafka.common.config.SslConfigs;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.config.types.Password;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.errors.ConnectException;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.SourceAndTarget;
+import org.apache.kafka.connect.util.clusters.EmbeddedConnectCluster;
+import org.apache.kafka.connect.util.clusters.EmbeddedKafkaCluster;
+import org.apache.kafka.test.IntegrationTest;
+import org.junit.experimental.categories.Category;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.kafka.connect.mirror.TestUtils.expectedRecords;
+import static org.apache.kafka.connect.util.clusters.EmbeddedConnectClusterAssertions.CONNECTOR_SETUP_DURATION_MS;
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+import kafka.server.KafkaConfig$;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertFalse;
+//import org.junit.After;
+
+/**
+ * Common Test functions for MM2 integration tests
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationBaseTest {
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationBaseTest.class);
+
+ protected static final int NUM_RECORDS_PER_PARTITION = 10;
+ public static final int NUM_PARTITIONS = 10;
+ protected static final int NUM_RECORDS_PRODUCED = NUM_PARTITIONS * NUM_RECORDS_PER_PARTITION;
+ protected static final int RECORD_TRANSFER_DURATION_MS = 30_000;
+ protected static final int CHECKPOINT_DURATION_MS = 20_000;
+ protected static final int RECORD_CONSUME_DURATION_MS = 20_000;
+ protected static final int OFFSET_SYNC_DURATION_MS = 30_000;
+ protected static final int NUM_WORKERS = 3;
+
+
+ protected Map<String, String> mm2Props;
+ protected MirrorMakerConfig mm2Config;
+ protected EmbeddedConnectCluster primary;
+ protected EmbeddedConnectCluster backup;
+
+ private final AtomicBoolean exited = new AtomicBoolean(false);
+ private Properties primaryBrokerProps = new Properties();
+ protected Properties backupBrokerProps = new Properties();
+ private Map<String, String> primaryWorkerProps;
+ private Map<String, String> backupWorkerProps = new HashMap<>();
+ private Properties sslProps = new Properties();
+
+ private void loadSslPropsFromBrokerConfig() {
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, backupBrokerProps.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG));
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, ((Password) backupBrokerProps.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)).value());
+ sslProps.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL");
+ }
+
+ protected void setSslConfig() {
+ // set SSL config for kafka connect worker
+ backupWorkerProps.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> "backup." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ // set SSL config for producer used by source task in MM2
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> "backup.producer." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ }
+
+ protected void startClusters() throws InterruptedException {
+ primaryBrokerProps.put("auto.create.topics.enable", "false");
+ backupBrokerProps.put("auto.create.topics.enable", "false");
+
+ mm2Props = basicMM2Config();
+
+ // if backup kafka cluster contains ssl config, enable ssl of kafka connect and mm2
+ final Object listeners = backupBrokerProps.get(KafkaConfig$.MODULE$.ListenersProp());
+ if (listeners != null && listeners.toString().contains("SSL")) {
+ loadSslPropsFromBrokerConfig();
+ setSslConfig();
+ }
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+ primaryWorkerProps = mm2Config.workerConfig(new SourceAndTarget("backup", "primary"));
+ backupWorkerProps.putAll(mm2Config.workerConfig(new SourceAndTarget("primary", "backup")));
+
+ primary = new EmbeddedConnectCluster.Builder()
+ .name("primary-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(primaryBrokerProps)
+ .workerProps(primaryWorkerProps)
+ .build();
+
+ backup = new EmbeddedConnectCluster.Builder()
+ .name("backup-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(backupBrokerProps)
+ .workerProps(backupWorkerProps)
+ .build();
+
+ primary.start();
+ primary.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of primary-connect-cluster did not start in time.");
+
+ backup.start();
+ backup.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of backup-connect-cluster did not start in time.");
+
+ createTopics();
+
+ dummyConsumption();
+
+ log.info("primary REST service: {}", primary.endpointForResource("connectors"));
+ log.info("backup REST service: {}", backup.endpointForResource("connectors"));
+ log.info("primary brokers: {}", primary.kafka().bootstrapServers());
+ log.info("backup brokers: {}", backup.kafka().bootstrapServers());
+
+ // now that the brokers are running, we can finish setting up the Connectors
+ mm2Props.put("primary.bootstrap.servers", primary.kafka().bootstrapServers());
+ mm2Props.put("backup.bootstrap.servers", backup.kafka().bootstrapServers());
+
+ Exit.setExitProcedure((status, errorCode) -> exited.set(true));
+ }
+
+ public void shutdownClusters() {
+ for (String x : primary.connectors()) {
+ primary.deleteConnector(x);
+ }
+ for (String x : backup.connectors()) {
+ backup.deleteConnector(x);
+ }
+ deleteAllTopics(primary.kafka());
+ deleteAllTopics(backup.kafka());
+ primary.stop();
+ backup.stop();
+ try {
+ assertFalse(exited.get());
+ } finally {
+ Exit.resetExitProcedure();
+ }
+ }
+ /*
+ * launch the connectors on kafka connect cluster and check if they are running
+ */
+ protected static void waitUntilMirrorMakerIsRunning(EmbeddedConnectCluster connectCluster,
+ List<Class> connectorClasses, MirrorMakerConfig mm2Config,
+ String primary, String backup) throws InterruptedException {
+ for (int i = 0; i < connectorClasses.size(); i++) {
+ String connector = connectorClasses.get(i).getSimpleName();
+ connectCluster.configureConnector(connector, mm2Config.connectorBaseConfig(
+ new SourceAndTarget(primary, backup), connectorClasses.get(i)));
+ }
+
+ // we wait for the connector and tasks to come up for each connector, so that when we do the
+ // actual testing, we are certain that the tasks are up and running; this will prevent
+ // flaky tests where the connector and tasks didn't start up in time for the tests to be
+ // run
+ List<String> connectorNames = connectorClasses.stream().map(x -> x.getSimpleName())
+ .collect(Collectors.toList());
+ for (String connector : connectorNames) {
+ connectCluster.assertions().assertConnectorAndAtLeastNumTasksAreRunning(connector, 1,
+ "Connector " + connector + " tasks did not start in time on cluster: " + connectCluster);
+ }
+ }
+
+ /*
+ * delete all topics of the input kafka cluster
+ */
+ protected static void deleteAllTopics(EmbeddedKafkaCluster cluster) {
+ Admin client = cluster.createAdminClient();
+ try {
+ client.deleteTopics(client.listTopics().names().get());
+ } catch (Throwable e) {
+ }
+ }
+
+ /*
+ * retrieve the config value based on the input cluster, topic and config name
+ */
+ protected static String getTopicConfig(EmbeddedKafkaCluster cluster, String topic, String configName) {
+ Admin client = cluster.createAdminClient();
+ Collection<ConfigResource> cr = Collections.singleton(
+ new ConfigResource(ConfigResource.Type.TOPIC, topic));
+ try {
+ DescribeConfigsResult configsResult = client.describeConfigs(cr);
+ Config allConfigs = (Config) configsResult.all().get().values().toArray()[0];
+ Iterator configIterator = allConfigs.entries().iterator();
+ while (configIterator.hasNext()) {
+ ConfigEntry currentConfig = (ConfigEntry) configIterator.next();
+ if (currentConfig.name().equals(configName)) {
+ return currentConfig.value();
+ }
+ }
+ } catch (Throwable e) {
+ }
+ return null;
+ }
+
+ /*
+ * produce messages to the cluster and topic
+ */
+ protected void produceMessages(EmbeddedConnectCluster cluster, String topicName) {
+ Map<String, String> recordSent = expectedRecords(NUM_RECORDS_PRODUCED);
+ for (Map.Entry<String, String> entry : recordSent.entrySet()) {
+ cluster.kafka().produce(topicName, entry.getKey(), entry.getValue());
+ }
+ }
+
+ /*
+ * produce messages to the cluster and topic partition less than numPartitions
+ */
+ protected void produceMessages(EmbeddedConnectCluster cluster, String topicName, int numPartitions) {
+ int cnt = 0;
+ for (int r = 0; r < NUM_RECORDS_PER_PARTITION; r++)
+ for (int p = 0; p < numPartitions; p++)
+ cluster.kafka().produce(topicName, p, "key", "value-" + cnt++);
+ }
+
+ /*
+ * given consumer group, topics and expected number of records, make sure the consumer group
+ * offsets are eventually synced to the expected offset numbers
+ */
+ protected static <T> void waitForConsumerGroupOffsetSync(EmbeddedConnectCluster connect,
+ Consumer<T, T> consumer, List<String> topics, String consumerGroupId, int numRecords)
+ throws InterruptedException {
+ Admin adminClient = connect.kafka().createAdminClient();
+ List<TopicPartition> tps = new ArrayList<>(NUM_PARTITIONS * topics.size());
+ for (int partitionIndex = 0; partitionIndex < NUM_PARTITIONS; partitionIndex++) {
+ for (String topic : topics) {
+ tps.add(new TopicPartition(topic, partitionIndex));
+ }
+ }
+ long expectedTotalOffsets = numRecords * topics.size();
+
+ waitForCondition(() -> {
+ Map<TopicPartition, OffsetAndMetadata> consumerGroupOffsets =
+ adminClient.listConsumerGroupOffsets(consumerGroupId).partitionsToOffsetAndMetadata().get();
+ long consumerGroupOffsetTotal = consumerGroupOffsets.values().stream()
+ .mapToLong(metadata -> metadata.offset()).sum();
+
+ Map<TopicPartition, Long> offsets = consumer.endOffsets(tps, Duration.ofMillis(500));
+ long totalOffsets = offsets.values().stream().mapToLong(l -> l).sum();
+
+ // make sure the consumer group offsets are synced to expected number
+ return totalOffsets == expectedTotalOffsets && consumerGroupOffsetTotal > 0;
+ }, OFFSET_SYNC_DURATION_MS, "Consumer group offset sync is not complete in time");
+ }
+
+ /*
+ * make sure the consumer to consume expected number of records
+ */
+ protected static <T> void waitForConsumingAllRecords(Consumer<T, T> consumer, int numExpectedRecords)
+ throws InterruptedException {
+ final AtomicInteger totalConsumedRecords = new AtomicInteger(0);
+ waitForCondition(() -> {
+ ConsumerRecords<T, T> records = consumer.poll(Duration.ofMillis(500));
+ return numExpectedRecords == totalConsumedRecords.addAndGet(records.count());
+ }, RECORD_CONSUME_DURATION_MS, "Consumer cannot consume all records in time");
+ consumer.commitSync();
+ consumer.close();
+ }
+
+ /*
+ * MM2 config to use in integration tests
+ */
+ protected static Map<String, String> basicMM2Config() {
+ Map<String, String> mm2Props = new HashMap<>();
+ mm2Props.put("clusters", "primary, backup");
+ mm2Props.put("max.tasks", "10");
+ mm2Props.put("topics", "test-topic-.*, primary.test-topic-.*, backup.test-topic-.*");
+ mm2Props.put("groups", "consumer-group-.*");
+ mm2Props.put("primary->backup.enabled", "true");
+ mm2Props.put("backup->primary.enabled", "true");
+ mm2Props.put("sync.topic.acls.enabled", "false");
+ mm2Props.put("emit.checkpoints.interval.seconds", "1");
+ mm2Props.put("emit.heartbeats.interval.seconds", "1");
+ mm2Props.put("refresh.topics.interval.seconds", "1");
+ mm2Props.put("refresh.groups.interval.seconds", "1");
+ mm2Props.put("checkpoints.topic.replication.factor", "1");
+ mm2Props.put("heartbeats.topic.replication.factor", "1");
+ mm2Props.put("offset-syncs.topic.replication.factor", "1");
+ mm2Props.put("config.storage.replication.factor", "1");
+ mm2Props.put("offset.storage.replication.factor", "1");
+ mm2Props.put("status.storage.replication.factor", "1");
+ mm2Props.put("replication.factor", "1");
+
+ return mm2Props;
+ }
+
+ /*
+ * restart kafka broker and make sure it is successful
+ */
+ protected static void restartKafkaBroker(EmbeddedConnectCluster connect) throws InterruptedException {
Review comment:
This restarts all brokers. I find it strange this takes a `EmbeddedConnectCluster`. Also I wonder why this is static.
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationTest.java
##########
@@ -0,0 +1,372 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.errors.TimeoutException;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.mirror.MirrorCheckpointConnector;
+import org.apache.kafka.connect.mirror.MirrorClient;
+import org.apache.kafka.connect.mirror.MirrorHeartbeatConnector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.MirrorSourceConnector;
+import org.apache.kafka.connect.mirror.utils.ThreadedConsumer;
+import org.apache.kafka.connect.mirror.utils.ThreadedProducer;
+import org.apache.kafka.test.IntegrationTest;
+import org.junit.Before;
+import org.junit.After;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Collections;
+import java.util.Map;
+import java.util.HashMap;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertNotNull;
+
+/**
+ * Tests MM2 replication and failover/failback logic.
+ *
+ * MM2 is configured with active/active replication between two Kafka clusters. Tests validate that
+ * records sent to either cluster arrive at the other cluster. Then, a consumer group is migrated from
+ * one cluster to the other and back. Tests validate that consumer offsets are translated and replicated
+ * between clusters during this failover and failback.
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationTest extends MirrorConnectorsIntegrationBaseTest {
+
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationTest.class);
+
+ private static final List<Class> CONNECTOR_LIST =
+ Arrays.asList(MirrorSourceConnector.class, MirrorCheckpointConnector.class, MirrorHeartbeatConnector.class);
+
+ @Before
+ public void setup() throws InterruptedException {
+ startClusters();
+ }
+
+ @After
+ public void close() {
+ shutdownClusters();
+ }
+
+ @Test
+ public void testReplication() throws InterruptedException {
+ produceMessages(primary, "test-topic-1");
+ produceMessages(backup, "test-topic-1");
+ String consumerGroupName = "consumer-group-testReplication";
+ Map<String, Object> consumerProps = new HashMap<String, Object>() {{
+ put("group.id", consumerGroupName);
+ put("auto.offset.reset", "latest");
+ }};
+ // create consumers before starting the connectors so we don't need to wait for discovery
+ Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps, "test-topic-1");
+ waitForConsumingAllRecords(primaryConsumer, 0);
+
+ Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(consumerProps, "test-topic-1");
+ waitForConsumingAllRecords(backupConsumer, 0);
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, "primary", "backup");
+ waitUntilMirrorMakerIsRunning(primary, CONNECTOR_LIST, mm2Config, "backup", "primary");
+
+ MirrorClient primaryClient = new MirrorClient(mm2Config.clientConfig("primary"));
+ MirrorClient backupClient = new MirrorClient(mm2Config.clientConfig("backup"));
+
+ assertEquals("topic config was not synced", TopicConfig.CLEANUP_POLICY_COMPACT,
+ getTopicConfig(backup.kafka(), "primary.test-topic-1", TopicConfig.CLEANUP_POLICY_CONFIG));
+
+ assertEquals("Records were not produced to primary cluster.", NUM_RECORDS_PRODUCED,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "test-topic-1").count());
+ assertEquals("Records were not replicated to backup cluster.", NUM_RECORDS_PRODUCED,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "primary.test-topic-1").count());
+ assertEquals("Records were not produced to backup cluster.", NUM_RECORDS_PRODUCED,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "test-topic-1").count());
+ assertEquals("Records were not replicated to primary cluster.", NUM_RECORDS_PRODUCED,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED, RECORD_TRANSFER_DURATION_MS, "backup.test-topic-1").count());
+
+ assertEquals("Primary cluster doesn't have all records from both clusters.", NUM_RECORDS_PRODUCED * 2,
+ primary.kafka().consume(NUM_RECORDS_PRODUCED * 2, RECORD_TRANSFER_DURATION_MS, "backup.test-topic-1", "test-topic-1").count());
+ assertEquals("Backup cluster doesn't have all records from both clusters.", NUM_RECORDS_PRODUCED * 2,
+ backup.kafka().consume(NUM_RECORDS_PRODUCED * 2, RECORD_TRANSFER_DURATION_MS, "primary.test-topic-1", "test-topic-1").count());
+
+ assertTrue("Heartbeats were not emitted to primary cluster.", primary.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "heartbeats").count() > 0);
+ assertTrue("Heartbeats were not emitted to backup cluster.", backup.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "heartbeats").count() > 0);
+ assertTrue("Heartbeats were not replicated downstream to backup cluster.", backup.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "primary.heartbeats").count() > 0);
+ assertTrue("Heartbeats were not replicated downstream to primary cluster.", primary.kafka().consume(1,
+ RECORD_TRANSFER_DURATION_MS, "backup.heartbeats").count() > 0);
+
+ assertTrue("Did not find upstream primary cluster.", backupClient.upstreamClusters().contains("primary"));
+ assertEquals("Did not calculate replication hops correctly.", 1, backupClient.replicationHops("primary"));
+ assertTrue("Did not find upstream backup cluster.", primaryClient.upstreamClusters().contains("backup"));
+ assertEquals("Did not calculate replication hops correctly.", 1, primaryClient.replicationHops("backup"));
+ assertTrue("Checkpoints were not emitted downstream to backup cluster.", backup.kafka().consume(1,
+ CHECKPOINT_DURATION_MS, "primary.checkpoints.internal").count() > 0);
+
+ Map<TopicPartition, OffsetAndMetadata> backupOffsets = backupClient.remoteConsumerOffsets(consumerGroupName, "primary",
+ Duration.ofMillis(CHECKPOINT_DURATION_MS));
+
+ assertTrue("Offsets not translated downstream to backup cluster. Found: " + backupOffsets, backupOffsets.containsKey(
+ new TopicPartition("primary.test-topic-1", 0)));
+
+ // Failover consumer group to backup cluster.
+ primaryConsumer = backup.kafka().createConsumer(Collections.singletonMap("group.id", consumerGroupName));
+ primaryConsumer.assign(backupOffsets.keySet());
+ backupOffsets.forEach(primaryConsumer::seek);
+ primaryConsumer.poll(Duration.ofMillis(500));
+ primaryConsumer.commitAsync();
+
+ assertTrue("Consumer failedover to zero offset.", primaryConsumer.position(new TopicPartition("primary.test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedover beyond expected offset.", primaryConsumer.position(
+ new TopicPartition("primary.test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+ assertTrue("Checkpoints were not emitted upstream to primary cluster.", primary.kafka().consume(1,
+ CHECKPOINT_DURATION_MS, "backup.checkpoints.internal").count() > 0);
+
+ primaryConsumer.close();
+
+ waitForCondition(() -> {
+ try {
+ return primaryClient.remoteConsumerOffsets(consumerGroupName, "backup",
+ Duration.ofMillis(CHECKPOINT_DURATION_MS)).containsKey(new TopicPartition("backup.test-topic-1", 0));
+ } catch (Throwable e) {
+ return false;
+ }
+ }, CHECKPOINT_DURATION_MS, "Offsets not translated downstream to primary cluster.");
+
+ waitForCondition(() -> {
+ try {
+ return primaryClient.remoteConsumerOffsets(consumerGroupName, "backup",
+ Duration.ofMillis(CHECKPOINT_DURATION_MS)).containsKey(new TopicPartition("test-topic-1", 0));
+ } catch (Throwable e) {
+ return false;
+ }
+ }, CHECKPOINT_DURATION_MS, "Offsets not translated upstream to primary cluster.");
+
+ Map<TopicPartition, OffsetAndMetadata> primaryOffsets = primaryClient.remoteConsumerOffsets(consumerGroupName, "backup",
+ Duration.ofMillis(CHECKPOINT_DURATION_MS));
+
+ // Failback consumer group to primary cluster
+ backupConsumer = primary.kafka().createConsumer(Collections.singletonMap("group.id", consumerGroupName));
+ backupConsumer.assign(primaryOffsets.keySet());
+ primaryOffsets.forEach(backupConsumer::seek);
+ backupConsumer.poll(Duration.ofMillis(500));
+ backupConsumer.commitAsync();
+
+ assertTrue("Consumer failedback to zero upstream offset.", backupConsumer.position(new TopicPartition("test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedback to zero downstream offset.", backupConsumer.position(new TopicPartition("backup.test-topic-1", 0)) > 0);
+ assertTrue("Consumer failedback beyond expected upstream offset.", backupConsumer.position(
+ new TopicPartition("test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+ assertTrue("Consumer failedback beyond expected downstream offset.", backupConsumer.position(
+ new TopicPartition("backup.test-topic-1", 0)) <= NUM_RECORDS_PRODUCED);
+
+ backupConsumer.close();
+
+ // create more matching topics
+ primary.kafka().createTopic("test-topic-2", NUM_PARTITIONS);
+ backup.kafka().createTopic("test-topic-3", NUM_PARTITIONS);
+
+ // only produce messages to the first partition
+ produceMessages(primary, "test-topic-2", 1);
+ produceMessages(backup, "test-topic-3", 1);
+
+ // expect total consumed messages equals to NUM_RECORDS_PER_PARTITION
+ assertEquals("Records were not produced to primary cluster.", NUM_RECORDS_PER_PARTITION,
+ primary.kafka().consume(NUM_RECORDS_PER_PARTITION, RECORD_TRANSFER_DURATION_MS, "test-topic-2").count());
+ assertEquals("Records were not produced to backup cluster.", NUM_RECORDS_PER_PARTITION,
+ backup.kafka().consume(NUM_RECORDS_PER_PARTITION, RECORD_TRANSFER_DURATION_MS, "test-topic-3").count());
+
+ assertEquals("New topic was not replicated to primary cluster.", NUM_RECORDS_PER_PARTITION,
+ primary.kafka().consume(NUM_RECORDS_PER_PARTITION, 2 * RECORD_TRANSFER_DURATION_MS, "backup.test-topic-3").count());
+ assertEquals("New topic was not replicated to backup cluster.", NUM_RECORDS_PER_PARTITION,
+ backup.kafka().consume(NUM_RECORDS_PER_PARTITION, 2 * RECORD_TRANSFER_DURATION_MS, "primary.test-topic-2").count());
+
+ }
+
+ @Test
+ public void testReplicationWithEmptyPartition() throws Exception {
+ String consumerGroupName = "consumer-group-testReplicationWithEmptyPartition";
+ Map<String, Object> consumerProps = Collections.singletonMap("group.id", consumerGroupName);
+
+ // create topic
+ String topic = "test-topic-with-empty-partition";
+ primary.kafka().createTopic(topic, NUM_PARTITIONS);
+
+ // produce to all test-topic-empty's partitions, except the last partition
+ produceMessages(primary, topic, NUM_PARTITIONS - 1);
+
+ // consume before starting the connectors so we don't need to wait for discovery
+ int expectedRecords = NUM_RECORDS_PER_PARTITION * (NUM_PARTITIONS - 1);
+ try (Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps, topic)) {
+ waitForConsumingAllRecords(primaryConsumer, expectedRecords);
+ }
+
+ // one way replication from primary to backup
+ mm2Props.put("backup->primary.enabled", "false");
+ mm2Config = new MirrorMakerConfig(mm2Props);
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, "primary", "backup");
+
+ // sleep few seconds to have MM2 finish replication so that "end" consumer will consume some record
+ Thread.sleep(TimeUnit.SECONDS.toMillis(3));
+
+ // consume all records from backup cluster
+ try (Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(consumerProps, "primary." + topic)) {
+ waitForConsumingAllRecords(backupConsumer, expectedRecords);
+ }
+
+ Admin backupClient = backup.kafka().createAdminClient();
+ // retrieve the consumer group offset from backup cluster
+ Map<TopicPartition, OffsetAndMetadata> remoteOffsets =
+ backupClient.listConsumerGroupOffsets(consumerGroupName).partitionsToOffsetAndMetadata().get();
+ // pinpoint the offset of the last partition which does not receive records
+ OffsetAndMetadata offset = remoteOffsets.get(new TopicPartition("primary." + topic, NUM_PARTITIONS - 1));
+ // offset of the last partition should exist, but its value should be 0
+ assertNotNull("Offset of last partition was not replicated", offset);
+ assertEquals("Offset of last partition is not zero", 0, offset.offset());
+ }
+
+ @Test
+ public void testOneWayReplicationWithAutoOffsetSync() throws InterruptedException {
+ produceMessages(primary, "test-topic-1");
+ String consumerGroupName = "consumer-group-testOneWayReplicationWithAutoOffsetSync";
+ Map<String, Object> consumerProps = new HashMap<String, Object>() {{
+ put("group.id", consumerGroupName);
+ put("auto.offset.reset", "earliest");
+ }};
+ // create consumers before starting the connectors so we don't need to wait for discovery
+ try (Consumer<byte[], byte[]> primaryConsumer = primary.kafka().createConsumerAndSubscribeTo(consumerProps,
+ "test-topic-1")) {
+ // we need to wait for consuming all the records for MM2 replicating the expected offsets
+ waitForConsumingAllRecords(primaryConsumer, NUM_RECORDS_PRODUCED);
+ }
+
+ // enable automated consumer group offset sync
+ mm2Props.put("sync.group.offsets.enabled", "true");
+ mm2Props.put("sync.group.offsets.interval.seconds", "1");
+ // one way replication from primary to backup
+ mm2Props.put("backup->primary.enabled", "false");
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+
+ waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, "primary", "backup");
+
+ // create a consumer at backup cluster with same consumer group Id to consume 1 topic
+ Consumer<byte[], byte[]> backupConsumer = backup.kafka().createConsumerAndSubscribeTo(
+ consumerProps, "primary.test-topic-1");
+
+ waitForConsumerGroupOffsetSync(backup, backupConsumer, Collections.singletonList("primary.test-topic-1"),
+ consumerGroupName, NUM_RECORDS_PRODUCED);
+
+ ConsumerRecords records = backupConsumer.poll(Duration.ofMillis(500));
+
+ // the size of consumer record should be zero, because the offsets of the same consumer group
+ // have been automatically synchronized from primary to backup by the background job, so no
+ // more records to consume from the replicated topic by the same consumer group at backup cluster
+ assertEquals("consumer record size is not zero", 0, records.count());
+
+ // now create a new topic in primary cluster
+ primary.kafka().createTopic("test-topic-2", NUM_PARTITIONS);
+ backup.kafka().createTopic("primary.test-topic-2", 1);
+ // produce some records to the new topic in primary cluster
+ produceMessages(primary, "test-topic-2");
+
+ // create a consumer at primary cluster to consume the new topic
+ try (Consumer<byte[], byte[]> consumer1 = primary.kafka().createConsumerAndSubscribeTo(Collections.singletonMap(
+ "group.id", "consumer-group-1"), "test-topic-2")) {
+ // we need to wait for consuming all the records for MM2 replicating the expected offsets
+ waitForConsumingAllRecords(consumer1, NUM_RECORDS_PRODUCED);
+ }
+
+ // create a consumer at backup cluster with same consumer group Id to consume old and new topic
+ backupConsumer = backup.kafka().createConsumerAndSubscribeTo(Collections.singletonMap(
+ "group.id", consumerGroupName), "primary.test-topic-1", "primary.test-topic-2");
+
+ waitForConsumerGroupOffsetSync(backup, backupConsumer, Arrays.asList("primary.test-topic-1", "primary.test-topic-2"),
+ consumerGroupName, NUM_RECORDS_PRODUCED);
+
+ records = backupConsumer.poll(Duration.ofMillis(500));
+ // similar reasoning as above, no more records to consume by the same consumer group at backup cluster
+ assertEquals("consumer record size is not zero", 0, records.count());
+ backupConsumer.close();
+ }
+
+ /*
+ * This test is to validate MirrorSourceConnector follows "at most once" delivery guarantee
+ * under broker restart / failure
+ */
+ @Test
+ public void testWithBrokerRestart() throws InterruptedException {
+ String consumerGroupName = "consumer-group-testWithBrokerRestart";
+ // test with a higher number of records
+ int numRecords = NUM_RECORDS_PRODUCED * 8;
+ // the sleep time between two produces used by background producer
+ int sleepMs = 50;
+ int joinTimeoutMs = 1000;
Review comment:
This is not used, can we remove it?
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationBaseTest.java
##########
@@ -0,0 +1,423 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.CommonClientConfigs;
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.Config;
+import org.apache.kafka.clients.admin.ConfigEntry;
+import org.apache.kafka.clients.admin.DescribeConfigsResult;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.config.ConfigResource;
+import org.apache.kafka.common.config.SslConfigs;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.config.types.Password;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.errors.ConnectException;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.SourceAndTarget;
+import org.apache.kafka.connect.util.clusters.EmbeddedConnectCluster;
+import org.apache.kafka.connect.util.clusters.EmbeddedKafkaCluster;
+import org.apache.kafka.test.IntegrationTest;
+import org.junit.experimental.categories.Category;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.kafka.connect.mirror.TestUtils.expectedRecords;
+import static org.apache.kafka.connect.util.clusters.EmbeddedConnectClusterAssertions.CONNECTOR_SETUP_DURATION_MS;
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+import kafka.server.KafkaConfig$;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertFalse;
+//import org.junit.After;
+
+/**
+ * Common Test functions for MM2 integration tests
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationBaseTest {
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationBaseTest.class);
+
+ protected static final int NUM_RECORDS_PER_PARTITION = 10;
+ public static final int NUM_PARTITIONS = 10;
+ protected static final int NUM_RECORDS_PRODUCED = NUM_PARTITIONS * NUM_RECORDS_PER_PARTITION;
+ protected static final int RECORD_TRANSFER_DURATION_MS = 30_000;
+ protected static final int CHECKPOINT_DURATION_MS = 20_000;
+ protected static final int RECORD_CONSUME_DURATION_MS = 20_000;
+ protected static final int OFFSET_SYNC_DURATION_MS = 30_000;
+ protected static final int NUM_WORKERS = 3;
+
+
+ protected Map<String, String> mm2Props;
+ protected MirrorMakerConfig mm2Config;
+ protected EmbeddedConnectCluster primary;
+ protected EmbeddedConnectCluster backup;
+
+ private final AtomicBoolean exited = new AtomicBoolean(false);
+ private Properties primaryBrokerProps = new Properties();
+ protected Properties backupBrokerProps = new Properties();
+ private Map<String, String> primaryWorkerProps;
+ private Map<String, String> backupWorkerProps = new HashMap<>();
+ private Properties sslProps = new Properties();
+
+ private void loadSslPropsFromBrokerConfig() {
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, backupBrokerProps.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG));
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, ((Password) backupBrokerProps.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)).value());
+ sslProps.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL");
+ }
+
+ protected void setSslConfig() {
+ // set SSL config for kafka connect worker
+ backupWorkerProps.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> "backup." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ // set SSL config for producer used by source task in MM2
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> "backup.producer." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ }
+
+ protected void startClusters() throws InterruptedException {
+ primaryBrokerProps.put("auto.create.topics.enable", "false");
+ backupBrokerProps.put("auto.create.topics.enable", "false");
+
+ mm2Props = basicMM2Config();
+
+ // if backup kafka cluster contains ssl config, enable ssl of kafka connect and mm2
+ final Object listeners = backupBrokerProps.get(KafkaConfig$.MODULE$.ListenersProp());
+ if (listeners != null && listeners.toString().contains("SSL")) {
+ loadSslPropsFromBrokerConfig();
+ setSslConfig();
+ }
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+ primaryWorkerProps = mm2Config.workerConfig(new SourceAndTarget("backup", "primary"));
+ backupWorkerProps.putAll(mm2Config.workerConfig(new SourceAndTarget("primary", "backup")));
+
+ primary = new EmbeddedConnectCluster.Builder()
+ .name("primary-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(primaryBrokerProps)
+ .workerProps(primaryWorkerProps)
+ .build();
+
+ backup = new EmbeddedConnectCluster.Builder()
+ .name("backup-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(backupBrokerProps)
+ .workerProps(backupWorkerProps)
+ .build();
+
+ primary.start();
+ primary.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of primary-connect-cluster did not start in time.");
+
+ backup.start();
+ backup.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of backup-connect-cluster did not start in time.");
+
+ createTopics();
+
+ dummyConsumption();
+
+ log.info("primary REST service: {}", primary.endpointForResource("connectors"));
+ log.info("backup REST service: {}", backup.endpointForResource("connectors"));
+ log.info("primary brokers: {}", primary.kafka().bootstrapServers());
+ log.info("backup brokers: {}", backup.kafka().bootstrapServers());
+
+ // now that the brokers are running, we can finish setting up the Connectors
+ mm2Props.put("primary.bootstrap.servers", primary.kafka().bootstrapServers());
+ mm2Props.put("backup.bootstrap.servers", backup.kafka().bootstrapServers());
+
+ Exit.setExitProcedure((status, errorCode) -> exited.set(true));
+ }
+
+ public void shutdownClusters() {
+ for (String x : primary.connectors()) {
+ primary.deleteConnector(x);
+ }
+ for (String x : backup.connectors()) {
+ backup.deleteConnector(x);
+ }
+ deleteAllTopics(primary.kafka());
+ deleteAllTopics(backup.kafka());
+ primary.stop();
+ backup.stop();
+ try {
+ assertFalse(exited.get());
+ } finally {
+ Exit.resetExitProcedure();
+ }
+ }
+ /*
+ * launch the connectors on kafka connect cluster and check if they are running
+ */
+ protected static void waitUntilMirrorMakerIsRunning(EmbeddedConnectCluster connectCluster,
+ List<Class> connectorClasses, MirrorMakerConfig mm2Config,
+ String primary, String backup) throws InterruptedException {
+ for (int i = 0; i < connectorClasses.size(); i++) {
+ String connector = connectorClasses.get(i).getSimpleName();
+ connectCluster.configureConnector(connector, mm2Config.connectorBaseConfig(
+ new SourceAndTarget(primary, backup), connectorClasses.get(i)));
+ }
+
+ // we wait for the connector and tasks to come up for each connector, so that when we do the
+ // actual testing, we are certain that the tasks are up and running; this will prevent
+ // flaky tests where the connector and tasks didn't start up in time for the tests to be
+ // run
+ List<String> connectorNames = connectorClasses.stream().map(x -> x.getSimpleName())
+ .collect(Collectors.toList());
+ for (String connector : connectorNames) {
+ connectCluster.assertions().assertConnectorAndAtLeastNumTasksAreRunning(connector, 1,
+ "Connector " + connector + " tasks did not start in time on cluster: " + connectCluster);
+ }
+ }
+
+ /*
+ * delete all topics of the input kafka cluster
+ */
+ protected static void deleteAllTopics(EmbeddedKafkaCluster cluster) {
+ Admin client = cluster.createAdminClient();
+ try {
+ client.deleteTopics(client.listTopics().names().get());
+ } catch (Throwable e) {
+ }
+ }
+
+ /*
+ * retrieve the config value based on the input cluster, topic and config name
+ */
+ protected static String getTopicConfig(EmbeddedKafkaCluster cluster, String topic, String configName) {
+ Admin client = cluster.createAdminClient();
+ Collection<ConfigResource> cr = Collections.singleton(
+ new ConfigResource(ConfigResource.Type.TOPIC, topic));
+ try {
+ DescribeConfigsResult configsResult = client.describeConfigs(cr);
+ Config allConfigs = (Config) configsResult.all().get().values().toArray()[0];
+ Iterator configIterator = allConfigs.entries().iterator();
+ while (configIterator.hasNext()) {
+ ConfigEntry currentConfig = (ConfigEntry) configIterator.next();
+ if (currentConfig.name().equals(configName)) {
+ return currentConfig.value();
+ }
+ }
+ } catch (Throwable e) {
+ }
+ return null;
+ }
+
+ /*
+ * produce messages to the cluster and topic
+ */
+ protected void produceMessages(EmbeddedConnectCluster cluster, String topicName) {
+ Map<String, String> recordSent = expectedRecords(NUM_RECORDS_PRODUCED);
+ for (Map.Entry<String, String> entry : recordSent.entrySet()) {
+ cluster.kafka().produce(topicName, entry.getKey(), entry.getValue());
+ }
+ }
+
+ /*
+ * produce messages to the cluster and topic partition less than numPartitions
+ */
+ protected void produceMessages(EmbeddedConnectCluster cluster, String topicName, int numPartitions) {
+ int cnt = 0;
+ for (int r = 0; r < NUM_RECORDS_PER_PARTITION; r++)
+ for (int p = 0; p < numPartitions; p++)
+ cluster.kafka().produce(topicName, p, "key", "value-" + cnt++);
+ }
+
+ /*
+ * given consumer group, topics and expected number of records, make sure the consumer group
+ * offsets are eventually synced to the expected offset numbers
+ */
+ protected static <T> void waitForConsumerGroupOffsetSync(EmbeddedConnectCluster connect,
+ Consumer<T, T> consumer, List<String> topics, String consumerGroupId, int numRecords)
+ throws InterruptedException {
+ Admin adminClient = connect.kafka().createAdminClient();
+ List<TopicPartition> tps = new ArrayList<>(NUM_PARTITIONS * topics.size());
+ for (int partitionIndex = 0; partitionIndex < NUM_PARTITIONS; partitionIndex++) {
+ for (String topic : topics) {
+ tps.add(new TopicPartition(topic, partitionIndex));
+ }
+ }
+ long expectedTotalOffsets = numRecords * topics.size();
+
+ waitForCondition(() -> {
+ Map<TopicPartition, OffsetAndMetadata> consumerGroupOffsets =
+ adminClient.listConsumerGroupOffsets(consumerGroupId).partitionsToOffsetAndMetadata().get();
+ long consumerGroupOffsetTotal = consumerGroupOffsets.values().stream()
+ .mapToLong(metadata -> metadata.offset()).sum();
+
+ Map<TopicPartition, Long> offsets = consumer.endOffsets(tps, Duration.ofMillis(500));
+ long totalOffsets = offsets.values().stream().mapToLong(l -> l).sum();
+
+ // make sure the consumer group offsets are synced to expected number
+ return totalOffsets == expectedTotalOffsets && consumerGroupOffsetTotal > 0;
+ }, OFFSET_SYNC_DURATION_MS, "Consumer group offset sync is not complete in time");
+ }
+
+ /*
+ * make sure the consumer to consume expected number of records
+ */
+ protected static <T> void waitForConsumingAllRecords(Consumer<T, T> consumer, int numExpectedRecords)
+ throws InterruptedException {
+ final AtomicInteger totalConsumedRecords = new AtomicInteger(0);
+ waitForCondition(() -> {
+ ConsumerRecords<T, T> records = consumer.poll(Duration.ofMillis(500));
+ return numExpectedRecords == totalConsumedRecords.addAndGet(records.count());
+ }, RECORD_CONSUME_DURATION_MS, "Consumer cannot consume all records in time");
+ consumer.commitSync();
+ consumer.close();
+ }
+
+ /*
+ * MM2 config to use in integration tests
+ */
+ protected static Map<String, String> basicMM2Config() {
+ Map<String, String> mm2Props = new HashMap<>();
+ mm2Props.put("clusters", "primary, backup");
Review comment:
Could the cluster aliases be constant as these are used all over the place
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationBaseTest.java
##########
@@ -0,0 +1,423 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.CommonClientConfigs;
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.Config;
+import org.apache.kafka.clients.admin.ConfigEntry;
+import org.apache.kafka.clients.admin.DescribeConfigsResult;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.config.ConfigResource;
+import org.apache.kafka.common.config.SslConfigs;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.config.types.Password;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.errors.ConnectException;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.SourceAndTarget;
+import org.apache.kafka.connect.util.clusters.EmbeddedConnectCluster;
+import org.apache.kafka.connect.util.clusters.EmbeddedKafkaCluster;
+import org.apache.kafka.test.IntegrationTest;
+import org.junit.experimental.categories.Category;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.kafka.connect.mirror.TestUtils.expectedRecords;
+import static org.apache.kafka.connect.util.clusters.EmbeddedConnectClusterAssertions.CONNECTOR_SETUP_DURATION_MS;
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+import kafka.server.KafkaConfig$;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertFalse;
+//import org.junit.After;
+
+/**
+ * Common Test functions for MM2 integration tests
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationBaseTest {
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationBaseTest.class);
+
+ protected static final int NUM_RECORDS_PER_PARTITION = 10;
+ public static final int NUM_PARTITIONS = 10;
+ protected static final int NUM_RECORDS_PRODUCED = NUM_PARTITIONS * NUM_RECORDS_PER_PARTITION;
+ protected static final int RECORD_TRANSFER_DURATION_MS = 30_000;
+ protected static final int CHECKPOINT_DURATION_MS = 20_000;
+ protected static final int RECORD_CONSUME_DURATION_MS = 20_000;
+ protected static final int OFFSET_SYNC_DURATION_MS = 30_000;
+ protected static final int NUM_WORKERS = 3;
+
+
+ protected Map<String, String> mm2Props;
+ protected MirrorMakerConfig mm2Config;
+ protected EmbeddedConnectCluster primary;
+ protected EmbeddedConnectCluster backup;
+
+ private final AtomicBoolean exited = new AtomicBoolean(false);
+ private Properties primaryBrokerProps = new Properties();
+ protected Properties backupBrokerProps = new Properties();
+ private Map<String, String> primaryWorkerProps;
+ private Map<String, String> backupWorkerProps = new HashMap<>();
+ private Properties sslProps = new Properties();
+
+ private void loadSslPropsFromBrokerConfig() {
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, backupBrokerProps.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG));
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, ((Password) backupBrokerProps.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)).value());
+ sslProps.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL");
+ }
+
+ protected void setSslConfig() {
+ // set SSL config for kafka connect worker
+ backupWorkerProps.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> "backup." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ // set SSL config for producer used by source task in MM2
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> "backup.producer." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ }
+
+ protected void startClusters() throws InterruptedException {
+ primaryBrokerProps.put("auto.create.topics.enable", "false");
+ backupBrokerProps.put("auto.create.topics.enable", "false");
+
+ mm2Props = basicMM2Config();
+
+ // if backup kafka cluster contains ssl config, enable ssl of kafka connect and mm2
+ final Object listeners = backupBrokerProps.get(KafkaConfig$.MODULE$.ListenersProp());
+ if (listeners != null && listeners.toString().contains("SSL")) {
+ loadSslPropsFromBrokerConfig();
+ setSslConfig();
+ }
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+ primaryWorkerProps = mm2Config.workerConfig(new SourceAndTarget("backup", "primary"));
+ backupWorkerProps.putAll(mm2Config.workerConfig(new SourceAndTarget("primary", "backup")));
+
+ primary = new EmbeddedConnectCluster.Builder()
+ .name("primary-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(primaryBrokerProps)
+ .workerProps(primaryWorkerProps)
+ .build();
+
+ backup = new EmbeddedConnectCluster.Builder()
+ .name("backup-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(backupBrokerProps)
+ .workerProps(backupWorkerProps)
+ .build();
+
+ primary.start();
+ primary.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of primary-connect-cluster did not start in time.");
+
+ backup.start();
+ backup.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of backup-connect-cluster did not start in time.");
+
+ createTopics();
+
+ dummyConsumption();
+
+ log.info("primary REST service: {}", primary.endpointForResource("connectors"));
+ log.info("backup REST service: {}", backup.endpointForResource("connectors"));
+ log.info("primary brokers: {}", primary.kafka().bootstrapServers());
+ log.info("backup brokers: {}", backup.kafka().bootstrapServers());
+
+ // now that the brokers are running, we can finish setting up the Connectors
+ mm2Props.put("primary.bootstrap.servers", primary.kafka().bootstrapServers());
+ mm2Props.put("backup.bootstrap.servers", backup.kafka().bootstrapServers());
+
+ Exit.setExitProcedure((status, errorCode) -> exited.set(true));
+ }
+
+ public void shutdownClusters() {
+ for (String x : primary.connectors()) {
+ primary.deleteConnector(x);
+ }
+ for (String x : backup.connectors()) {
+ backup.deleteConnector(x);
+ }
+ deleteAllTopics(primary.kafka());
+ deleteAllTopics(backup.kafka());
+ primary.stop();
+ backup.stop();
+ try {
+ assertFalse(exited.get());
+ } finally {
+ Exit.resetExitProcedure();
+ }
+ }
+ /*
+ * launch the connectors on kafka connect cluster and check if they are running
+ */
+ protected static void waitUntilMirrorMakerIsRunning(EmbeddedConnectCluster connectCluster,
+ List<Class> connectorClasses, MirrorMakerConfig mm2Config,
+ String primary, String backup) throws InterruptedException {
+ for (int i = 0; i < connectorClasses.size(); i++) {
+ String connector = connectorClasses.get(i).getSimpleName();
+ connectCluster.configureConnector(connector, mm2Config.connectorBaseConfig(
+ new SourceAndTarget(primary, backup), connectorClasses.get(i)));
+ }
+
+ // we wait for the connector and tasks to come up for each connector, so that when we do the
+ // actual testing, we are certain that the tasks are up and running; this will prevent
+ // flaky tests where the connector and tasks didn't start up in time for the tests to be
+ // run
+ List<String> connectorNames = connectorClasses.stream().map(x -> x.getSimpleName())
+ .collect(Collectors.toList());
+ for (String connector : connectorNames) {
+ connectCluster.assertions().assertConnectorAndAtLeastNumTasksAreRunning(connector, 1,
+ "Connector " + connector + " tasks did not start in time on cluster: " + connectCluster);
+ }
+ }
+
+ /*
+ * delete all topics of the input kafka cluster
+ */
+ protected static void deleteAllTopics(EmbeddedKafkaCluster cluster) {
+ Admin client = cluster.createAdminClient();
+ try {
+ client.deleteTopics(client.listTopics().names().get());
+ } catch (Throwable e) {
+ }
+ }
+
+ /*
+ * retrieve the config value based on the input cluster, topic and config name
+ */
+ protected static String getTopicConfig(EmbeddedKafkaCluster cluster, String topic, String configName) {
+ Admin client = cluster.createAdminClient();
+ Collection<ConfigResource> cr = Collections.singleton(
+ new ConfigResource(ConfigResource.Type.TOPIC, topic));
+ try {
+ DescribeConfigsResult configsResult = client.describeConfigs(cr);
+ Config allConfigs = (Config) configsResult.all().get().values().toArray()[0];
+ Iterator configIterator = allConfigs.entries().iterator();
+ while (configIterator.hasNext()) {
+ ConfigEntry currentConfig = (ConfigEntry) configIterator.next();
+ if (currentConfig.name().equals(configName)) {
+ return currentConfig.value();
+ }
+ }
+ } catch (Throwable e) {
+ }
+ return null;
+ }
+
+ /*
+ * produce messages to the cluster and topic
+ */
+ protected void produceMessages(EmbeddedConnectCluster cluster, String topicName) {
+ Map<String, String> recordSent = expectedRecords(NUM_RECORDS_PRODUCED);
+ for (Map.Entry<String, String> entry : recordSent.entrySet()) {
+ cluster.kafka().produce(topicName, entry.getKey(), entry.getValue());
+ }
+ }
+
+ /*
+ * produce messages to the cluster and topic partition less than numPartitions
+ */
+ protected void produceMessages(EmbeddedConnectCluster cluster, String topicName, int numPartitions) {
+ int cnt = 0;
+ for (int r = 0; r < NUM_RECORDS_PER_PARTITION; r++)
+ for (int p = 0; p < numPartitions; p++)
+ cluster.kafka().produce(topicName, p, "key", "value-" + cnt++);
+ }
+
+ /*
+ * given consumer group, topics and expected number of records, make sure the consumer group
+ * offsets are eventually synced to the expected offset numbers
+ */
+ protected static <T> void waitForConsumerGroupOffsetSync(EmbeddedConnectCluster connect,
+ Consumer<T, T> consumer, List<String> topics, String consumerGroupId, int numRecords)
+ throws InterruptedException {
+ Admin adminClient = connect.kafka().createAdminClient();
+ List<TopicPartition> tps = new ArrayList<>(NUM_PARTITIONS * topics.size());
+ for (int partitionIndex = 0; partitionIndex < NUM_PARTITIONS; partitionIndex++) {
+ for (String topic : topics) {
+ tps.add(new TopicPartition(topic, partitionIndex));
+ }
+ }
+ long expectedTotalOffsets = numRecords * topics.size();
+
+ waitForCondition(() -> {
+ Map<TopicPartition, OffsetAndMetadata> consumerGroupOffsets =
+ adminClient.listConsumerGroupOffsets(consumerGroupId).partitionsToOffsetAndMetadata().get();
+ long consumerGroupOffsetTotal = consumerGroupOffsets.values().stream()
+ .mapToLong(metadata -> metadata.offset()).sum();
+
+ Map<TopicPartition, Long> offsets = consumer.endOffsets(tps, Duration.ofMillis(500));
+ long totalOffsets = offsets.values().stream().mapToLong(l -> l).sum();
+
+ // make sure the consumer group offsets are synced to expected number
+ return totalOffsets == expectedTotalOffsets && consumerGroupOffsetTotal > 0;
+ }, OFFSET_SYNC_DURATION_MS, "Consumer group offset sync is not complete in time");
+ }
+
+ /*
+ * make sure the consumer to consume expected number of records
+ */
+ protected static <T> void waitForConsumingAllRecords(Consumer<T, T> consumer, int numExpectedRecords)
+ throws InterruptedException {
+ final AtomicInteger totalConsumedRecords = new AtomicInteger(0);
+ waitForCondition(() -> {
+ ConsumerRecords<T, T> records = consumer.poll(Duration.ofMillis(500));
+ return numExpectedRecords == totalConsumedRecords.addAndGet(records.count());
+ }, RECORD_CONSUME_DURATION_MS, "Consumer cannot consume all records in time");
+ consumer.commitSync();
+ consumer.close();
+ }
+
+ /*
+ * MM2 config to use in integration tests
+ */
+ protected static Map<String, String> basicMM2Config() {
+ Map<String, String> mm2Props = new HashMap<>();
+ mm2Props.put("clusters", "primary, backup");
+ mm2Props.put("max.tasks", "10");
+ mm2Props.put("topics", "test-topic-.*, primary.test-topic-.*, backup.test-topic-.*");
+ mm2Props.put("groups", "consumer-group-.*");
+ mm2Props.put("primary->backup.enabled", "true");
+ mm2Props.put("backup->primary.enabled", "true");
+ mm2Props.put("sync.topic.acls.enabled", "false");
+ mm2Props.put("emit.checkpoints.interval.seconds", "1");
+ mm2Props.put("emit.heartbeats.interval.seconds", "1");
+ mm2Props.put("refresh.topics.interval.seconds", "1");
+ mm2Props.put("refresh.groups.interval.seconds", "1");
+ mm2Props.put("checkpoints.topic.replication.factor", "1");
+ mm2Props.put("heartbeats.topic.replication.factor", "1");
+ mm2Props.put("offset-syncs.topic.replication.factor", "1");
+ mm2Props.put("config.storage.replication.factor", "1");
+ mm2Props.put("offset.storage.replication.factor", "1");
+ mm2Props.put("status.storage.replication.factor", "1");
+ mm2Props.put("replication.factor", "1");
+
+ return mm2Props;
+ }
+
+ /*
+ * restart kafka broker and make sure it is successful
+ */
+ protected static void restartKafkaBroker(EmbeddedConnectCluster connect) throws InterruptedException {
+
+ connect.kafka().stopOnlyKafka();
+ log.trace("issue kafka stop");
+ connect.assertions().assertExactlyNumWorkersAreUp(NUM_WORKERS,
+ "Group of workers did not remain the same after broker shutdown");
+
+ // Allow for the workers to discover that the coordinator is unavailable, if the connector
+ // is set up on this current EmbeddedConnectCluster
+ Thread.sleep(TimeUnit.SECONDS.toMillis(10));
+
+ // Wait for the broker to be stopped
+ assertTrue("Failed to stop kafka broker within " + CONNECTOR_SETUP_DURATION_MS + "ms",
+ connect.kafka().runningBrokers().size() == 0);
+
+ connect.kafka().startOnlyKafkaOnSamePorts();
+ log.trace("issue kafka start");
+ // Allow for the kafka brokers to come back online
+ Thread.sleep(TimeUnit.SECONDS.toMillis(10));
+
+ connect.assertions().assertExactlyNumWorkersAreUp(NUM_WORKERS,
+ "Group of workers did not remain the same within the designated time.");
+
+ // Allow for the workers to rebalance and reach a steady state
+ Thread.sleep(TimeUnit.SECONDS.toMillis(10));
+
+ // Expect that the broker has started again
+ assertTrue("Failed to start kafka broker within " + CONNECTOR_SETUP_DURATION_MS + "ms",
+ connect.kafka().runningBrokers().size() > 0);
+ }
+
+ protected void createTopics() {
+ // to verify topic config will be sync-ed across clusters
+ Map<String, String> topicConfig = new HashMap<>();
+ topicConfig.put(TopicConfig.CLEANUP_POLICY_CONFIG, TopicConfig.CLEANUP_POLICY_COMPACT);
+ // create these topics before starting the connectors so we don't need to wait for discovery
+ primary.kafka().createTopic("test-topic-1", NUM_PARTITIONS, 1, topicConfig);
+ primary.kafka().createTopic("backup.test-topic-1", 1);
+ primary.kafka().createTopic("heartbeats", 1);
+ backup.kafka().createTopic("test-topic-1", NUM_PARTITIONS);
+ backup.kafka().createTopic("primary.test-topic-1", 1);
+ backup.kafka().createTopic("heartbeats", 1);
+ }
+
+ protected KafkaConsumer<String, String> createSslConsumer(Map<String, Object> consumerProps, String... topics) {
+ Map<String, Object> props = new HashMap<>(consumerProps);
+
+ if (props.get(ConsumerConfig.GROUP_ID_CONFIG) == null) {
Review comment:
We can use `putIfAbstent()`
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationBaseTest.java
##########
@@ -0,0 +1,423 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.CommonClientConfigs;
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.Config;
+import org.apache.kafka.clients.admin.ConfigEntry;
+import org.apache.kafka.clients.admin.DescribeConfigsResult;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.config.ConfigResource;
+import org.apache.kafka.common.config.SslConfigs;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.config.types.Password;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.errors.ConnectException;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.SourceAndTarget;
+import org.apache.kafka.connect.util.clusters.EmbeddedConnectCluster;
+import org.apache.kafka.connect.util.clusters.EmbeddedKafkaCluster;
+import org.apache.kafka.test.IntegrationTest;
+import org.junit.experimental.categories.Category;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.kafka.connect.mirror.TestUtils.expectedRecords;
+import static org.apache.kafka.connect.util.clusters.EmbeddedConnectClusterAssertions.CONNECTOR_SETUP_DURATION_MS;
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+import kafka.server.KafkaConfig$;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertFalse;
+//import org.junit.After;
+
+/**
+ * Common Test functions for MM2 integration tests
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationBaseTest {
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationBaseTest.class);
+
+ protected static final int NUM_RECORDS_PER_PARTITION = 10;
+ public static final int NUM_PARTITIONS = 10;
+ protected static final int NUM_RECORDS_PRODUCED = NUM_PARTITIONS * NUM_RECORDS_PER_PARTITION;
+ protected static final int RECORD_TRANSFER_DURATION_MS = 30_000;
+ protected static final int CHECKPOINT_DURATION_MS = 20_000;
+ protected static final int RECORD_CONSUME_DURATION_MS = 20_000;
+ protected static final int OFFSET_SYNC_DURATION_MS = 30_000;
+ protected static final int NUM_WORKERS = 3;
+
+
+ protected Map<String, String> mm2Props;
+ protected MirrorMakerConfig mm2Config;
+ protected EmbeddedConnectCluster primary;
+ protected EmbeddedConnectCluster backup;
+
+ private final AtomicBoolean exited = new AtomicBoolean(false);
+ private Properties primaryBrokerProps = new Properties();
+ protected Properties backupBrokerProps = new Properties();
+ private Map<String, String> primaryWorkerProps;
+ private Map<String, String> backupWorkerProps = new HashMap<>();
+ private Properties sslProps = new Properties();
+
+ private void loadSslPropsFromBrokerConfig() {
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, backupBrokerProps.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG));
+ sslProps.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, ((Password) backupBrokerProps.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)).value());
+ sslProps.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL");
+ }
+
+ protected void setSslConfig() {
+ // set SSL config for kafka connect worker
+ backupWorkerProps.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> "backup." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ // set SSL config for producer used by source task in MM2
+ mm2Props.putAll(sslProps.entrySet().stream().collect(Collectors.toMap(
+ e -> "backup.producer." + String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))));
+ }
+
+ protected void startClusters() throws InterruptedException {
+ primaryBrokerProps.put("auto.create.topics.enable", "false");
+ backupBrokerProps.put("auto.create.topics.enable", "false");
+
+ mm2Props = basicMM2Config();
+
+ // if backup kafka cluster contains ssl config, enable ssl of kafka connect and mm2
+ final Object listeners = backupBrokerProps.get(KafkaConfig$.MODULE$.ListenersProp());
+ if (listeners != null && listeners.toString().contains("SSL")) {
+ loadSslPropsFromBrokerConfig();
+ setSslConfig();
+ }
+
+ mm2Config = new MirrorMakerConfig(mm2Props);
+ primaryWorkerProps = mm2Config.workerConfig(new SourceAndTarget("backup", "primary"));
+ backupWorkerProps.putAll(mm2Config.workerConfig(new SourceAndTarget("primary", "backup")));
+
+ primary = new EmbeddedConnectCluster.Builder()
+ .name("primary-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(primaryBrokerProps)
+ .workerProps(primaryWorkerProps)
+ .build();
+
+ backup = new EmbeddedConnectCluster.Builder()
+ .name("backup-connect-cluster")
+ .numWorkers(3)
+ .numBrokers(1)
+ .brokerProps(backupBrokerProps)
+ .workerProps(backupWorkerProps)
+ .build();
+
+ primary.start();
+ primary.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of primary-connect-cluster did not start in time.");
+
+ backup.start();
+ backup.assertions().assertAtLeastNumWorkersAreUp(3,
+ "Workers of backup-connect-cluster did not start in time.");
+
+ createTopics();
+
+ dummyConsumption();
+
+ log.info("primary REST service: {}", primary.endpointForResource("connectors"));
+ log.info("backup REST service: {}", backup.endpointForResource("connectors"));
+ log.info("primary brokers: {}", primary.kafka().bootstrapServers());
+ log.info("backup brokers: {}", backup.kafka().bootstrapServers());
+
+ // now that the brokers are running, we can finish setting up the Connectors
+ mm2Props.put("primary.bootstrap.servers", primary.kafka().bootstrapServers());
+ mm2Props.put("backup.bootstrap.servers", backup.kafka().bootstrapServers());
+
+ Exit.setExitProcedure((status, errorCode) -> exited.set(true));
+ }
+
+ public void shutdownClusters() {
+ for (String x : primary.connectors()) {
+ primary.deleteConnector(x);
+ }
+ for (String x : backup.connectors()) {
+ backup.deleteConnector(x);
+ }
+ deleteAllTopics(primary.kafka());
+ deleteAllTopics(backup.kafka());
+ primary.stop();
+ backup.stop();
+ try {
+ assertFalse(exited.get());
+ } finally {
+ Exit.resetExitProcedure();
+ }
+ }
+ /*
+ * launch the connectors on kafka connect cluster and check if they are running
+ */
+ protected static void waitUntilMirrorMakerIsRunning(EmbeddedConnectCluster connectCluster,
+ List<Class> connectorClasses, MirrorMakerConfig mm2Config,
+ String primary, String backup) throws InterruptedException {
+ for (int i = 0; i < connectorClasses.size(); i++) {
+ String connector = connectorClasses.get(i).getSimpleName();
+ connectCluster.configureConnector(connector, mm2Config.connectorBaseConfig(
+ new SourceAndTarget(primary, backup), connectorClasses.get(i)));
+ }
+
+ // we wait for the connector and tasks to come up for each connector, so that when we do the
+ // actual testing, we are certain that the tasks are up and running; this will prevent
+ // flaky tests where the connector and tasks didn't start up in time for the tests to be
+ // run
+ List<String> connectorNames = connectorClasses.stream().map(x -> x.getSimpleName())
+ .collect(Collectors.toList());
+ for (String connector : connectorNames) {
+ connectCluster.assertions().assertConnectorAndAtLeastNumTasksAreRunning(connector, 1,
+ "Connector " + connector + " tasks did not start in time on cluster: " + connectCluster);
+ }
+ }
+
+ /*
+ * delete all topics of the input kafka cluster
+ */
+ protected static void deleteAllTopics(EmbeddedKafkaCluster cluster) {
+ Admin client = cluster.createAdminClient();
+ try {
+ client.deleteTopics(client.listTopics().names().get());
+ } catch (Throwable e) {
+ }
+ }
+
+ /*
+ * retrieve the config value based on the input cluster, topic and config name
+ */
+ protected static String getTopicConfig(EmbeddedKafkaCluster cluster, String topic, String configName) {
+ Admin client = cluster.createAdminClient();
+ Collection<ConfigResource> cr = Collections.singleton(
+ new ConfigResource(ConfigResource.Type.TOPIC, topic));
+ try {
+ DescribeConfigsResult configsResult = client.describeConfigs(cr);
+ Config allConfigs = (Config) configsResult.all().get().values().toArray()[0];
+ Iterator configIterator = allConfigs.entries().iterator();
+ while (configIterator.hasNext()) {
+ ConfigEntry currentConfig = (ConfigEntry) configIterator.next();
+ if (currentConfig.name().equals(configName)) {
+ return currentConfig.value();
+ }
+ }
+ } catch (Throwable e) {
+ }
+ return null;
+ }
+
+ /*
+ * produce messages to the cluster and topic
+ */
+ protected void produceMessages(EmbeddedConnectCluster cluster, String topicName) {
+ Map<String, String> recordSent = expectedRecords(NUM_RECORDS_PRODUCED);
+ for (Map.Entry<String, String> entry : recordSent.entrySet()) {
+ cluster.kafka().produce(topicName, entry.getKey(), entry.getValue());
+ }
+ }
+
+ /*
+ * produce messages to the cluster and topic partition less than numPartitions
+ */
+ protected void produceMessages(EmbeddedConnectCluster cluster, String topicName, int numPartitions) {
+ int cnt = 0;
+ for (int r = 0; r < NUM_RECORDS_PER_PARTITION; r++)
+ for (int p = 0; p < numPartitions; p++)
+ cluster.kafka().produce(topicName, p, "key", "value-" + cnt++);
+ }
+
+ /*
+ * given consumer group, topics and expected number of records, make sure the consumer group
+ * offsets are eventually synced to the expected offset numbers
+ */
+ protected static <T> void waitForConsumerGroupOffsetSync(EmbeddedConnectCluster connect,
+ Consumer<T, T> consumer, List<String> topics, String consumerGroupId, int numRecords)
+ throws InterruptedException {
+ Admin adminClient = connect.kafka().createAdminClient();
+ List<TopicPartition> tps = new ArrayList<>(NUM_PARTITIONS * topics.size());
+ for (int partitionIndex = 0; partitionIndex < NUM_PARTITIONS; partitionIndex++) {
+ for (String topic : topics) {
+ tps.add(new TopicPartition(topic, partitionIndex));
+ }
+ }
+ long expectedTotalOffsets = numRecords * topics.size();
+
+ waitForCondition(() -> {
+ Map<TopicPartition, OffsetAndMetadata> consumerGroupOffsets =
+ adminClient.listConsumerGroupOffsets(consumerGroupId).partitionsToOffsetAndMetadata().get();
+ long consumerGroupOffsetTotal = consumerGroupOffsets.values().stream()
+ .mapToLong(metadata -> metadata.offset()).sum();
+
+ Map<TopicPartition, Long> offsets = consumer.endOffsets(tps, Duration.ofMillis(500));
+ long totalOffsets = offsets.values().stream().mapToLong(l -> l).sum();
+
+ // make sure the consumer group offsets are synced to expected number
+ return totalOffsets == expectedTotalOffsets && consumerGroupOffsetTotal > 0;
+ }, OFFSET_SYNC_DURATION_MS, "Consumer group offset sync is not complete in time");
+ }
+
+ /*
+ * make sure the consumer to consume expected number of records
+ */
+ protected static <T> void waitForConsumingAllRecords(Consumer<T, T> consumer, int numExpectedRecords)
+ throws InterruptedException {
+ final AtomicInteger totalConsumedRecords = new AtomicInteger(0);
+ waitForCondition(() -> {
+ ConsumerRecords<T, T> records = consumer.poll(Duration.ofMillis(500));
+ return numExpectedRecords == totalConsumedRecords.addAndGet(records.count());
+ }, RECORD_CONSUME_DURATION_MS, "Consumer cannot consume all records in time");
+ consumer.commitSync();
+ consumer.close();
+ }
+
+ /*
+ * MM2 config to use in integration tests
+ */
+ protected static Map<String, String> basicMM2Config() {
Review comment:
Can this be `private`?
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] mimaison commented on pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
mimaison commented on pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#issuecomment-724323408
@ning2008wisc I've not forgotten this PR, I just haven't had time to do reviews yet :(
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc commented on pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc commented on pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#issuecomment-690907900
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc commented on a change in pull request #9224: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc commented on a change in pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#discussion_r485363204
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationTest.java
##########
@@ -396,27 +330,67 @@ public void testOneWayReplicationWithAutoOffsetSync() throws InterruptedExceptio
try (Consumer<byte[], byte[]> consumer1 = primary.kafka().createConsumerAndSubscribeTo(Collections.singletonMap(
"group.id", "consumer-group-1"), "test-topic-2")) {
// we need to wait for consuming all the records for MM2 replicating the expected offsets
- waitForConsumingAllRecords(consumer1);
+ waitForConsumingAllRecords(consumer1, NUM_RECORDS_PRODUCED);
}
// create a consumer at backup cluster with same consumer group Id to consume old and new topic
consumer = backup.kafka().createConsumerAndSubscribeTo(Collections.singletonMap(
"group.id", "consumer-group-1"), "primary.test-topic-1", "primary.test-topic-2");
- waitForConsumerGroupOffsetSync(consumer, Arrays.asList("primary.test-topic-1", "primary.test-topic-2"), "consumer-group-1");
+ waitForConsumerGroupOffsetSync(backup, consumer, Arrays.asList("primary.test-topic-1", "primary.test-topic-2"),
+ "consumer-group-1", NUM_RECORDS_PRODUCED);
records = consumer.poll(Duration.ofMillis(500));
// similar reasoning as above, no more records to consume by the same consumer group at backup cluster
assertEquals("consumer record size is not zero", 0, records.count());
consumer.close();
-
}
+
+ @Test
+ public void testWithBrokerRestart() throws InterruptedException {
+ // test with a higher number of records
+ int numRecords = NUM_RECORDS_PRODUCED * 100;
+
+ produceRecords(Arrays.asList(primary), Arrays.asList("test-topic-1"), numRecords);
- private void deleteAllTopics(EmbeddedKafkaCluster cluster) {
- Admin client = cluster.createAdminClient();
- try {
- client.deleteTopics(client.listTopics().names().get());
- } catch (Throwable e) {
- }
+ // one way replication from primary to backup
+ mm2Props.put("backup->primary.enabled", "false");
+ mm2Config = new MirrorMakerConfig(mm2Props);
+
+ waitUntilMirrorMakerIsRunning(backup, SOURCE_CONNECTOR, mm2Config, "primary", "backup");
+
+ // have to sleep a little for MM to be ready for the following the kafka broker restart
+ Thread.sleep(TimeUnit.SECONDS.toMillis(1));
+
+ // restart kafka broker at backup cluster
+ restartKafkaBroker(backup);
+
+ Consumer<byte[], byte[]> consumer = backup.kafka().createConsumerAndSubscribeTo(
+ Collections.singletonMap("group.id", "consumer-group-1"), "primary.test-topic-1");
+ // verify the consumption equals to produce
+ waitForConsumingAllRecords(consumer, numRecords);
+ consumer.commitAsync();
+
+ // produce another set of records
+ produceRecords(Arrays.asList(primary), Arrays.asList("test-topic-1"), numRecords);
+ // restart kafka broker at primary cluster
+ restartKafkaBroker(primary);
+ // verify the consumption equals to produce
+ waitForConsumingAllRecords(consumer, numRecords);
+
+ consumer.close();
+ }
+
+ void createTopics() {
+ // to verify topic config will be sync-ed across clusters
+ Map<String, String> topicConfig = new HashMap<>();
+ topicConfig.put(TopicConfig.CLEANUP_POLICY_CONFIG, TopicConfig.CLEANUP_POLICY_COMPACT);
+ // create these topics before starting the connectors so we don't need to wait for discovery
+ primary.kafka().createTopic("test-topic-1", NUM_PARTITIONS, 1, topicConfig);
Review comment:
when creating `test-topic-1` topic on primary cluster, add a topic config. Later on, we will check if the config is synced from primary to backup cluster.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc commented on a change in pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc commented on a change in pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#discussion_r527508609
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationBaseTest.java
##########
@@ -0,0 +1,407 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.CommonClientConfigs;
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.Config;
+import org.apache.kafka.clients.admin.ConfigEntry;
+import org.apache.kafka.clients.admin.DescribeConfigsResult;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.config.ConfigResource;
+import org.apache.kafka.common.config.SslConfigs;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.config.types.Password;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.connector.Connector;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.SourceAndTarget;
+import org.apache.kafka.connect.util.clusters.EmbeddedConnectCluster;
+import org.apache.kafka.connect.util.clusters.EmbeddedKafkaCluster;
+import static org.apache.kafka.connect.mirror.TestUtils.expectedRecords;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+import org.apache.kafka.test.IntegrationTest;
+import kafka.server.KafkaConfig$;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import static org.junit.Assert.assertFalse;
+import org.junit.experimental.categories.Category;
+
+/**
+ * Common Test functions for MM2 integration tests
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationBaseTest {
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationBaseTest.class);
+
+ protected static final int NUM_RECORDS_PER_PARTITION = 10;
+ public static final int NUM_PARTITIONS = 10;
+ protected static final int NUM_RECORDS_PRODUCED = NUM_PARTITIONS * NUM_RECORDS_PER_PARTITION;
+ protected static final int RECORD_TRANSFER_DURATION_MS = 30_000;
+ protected static final int CHECKPOINT_DURATION_MS = 20_000;
+ protected static final int RECORD_CONSUME_DURATION_MS = 20_000;
+ protected static final int OFFSET_SYNC_DURATION_MS = 30_000;
+ protected static final int NUM_WORKERS = 3;
+ protected static final int CONSUMER_POLL_TIMEOUT_MS = 500;
+ protected static final int BROKER_RESTART_TIMEOUT_MS = 10_000;
+ protected static final String PRIMARY_CLUSTER_ALIAS = "primary";
+ protected static final String BACKUP_CLUSTER_ALIAS = "backup";
+
+ protected Map<String, String> mm2Props;
+ protected MirrorMakerConfig mm2Config;
+ protected EmbeddedConnectCluster primary;
+ protected EmbeddedConnectCluster backup;
+
+ private final AtomicBoolean exited = new AtomicBoolean(false);
+ private Properties primaryBrokerProps = new Properties();
+ protected Properties backupBrokerProps = new Properties();
+ private Map<String, String> primaryWorkerProps = new HashMap<>();
+ private Map<String, String> backupWorkerProps = new HashMap<>();
+ private Properties sslProps = new Properties();
+
+ private void loadSslPropsFromBrokerConfig() {
Review comment:
> Could we move all the SSL bits into the SSL class?
I believe yes
> We have fields for the configurations. So we could set them accordingly (without or without SSL) in each concrete class. Then in the base class, we just use the fields to create the clusters without having to know if it's SSL or not.
I agree
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc commented on pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc commented on pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#issuecomment-746543315
@mimaison thanks so much for all your efforts on reviewing. Really appreciated if you may have time before end of this year to do 1-2 final reviews to merge this PR.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] ning2008wisc commented on a change in pull request #9224: KAFKA-10304: refactor MM2 integration tests
Posted by GitBox <gi...@apache.org>.
ning2008wisc commented on a change in pull request #9224:
URL: https://github.com/apache/kafka/pull/9224#discussion_r510494608
##########
File path: connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsIntegrationBaseTest.java
##########
@@ -0,0 +1,423 @@
+/*
+ * 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.
+ */
+package org.apache.kafka.connect.mirror.integration;
+
+import org.apache.kafka.clients.CommonClientConfigs;
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.Config;
+import org.apache.kafka.clients.admin.ConfigEntry;
+import org.apache.kafka.clients.admin.DescribeConfigsResult;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.common.config.ConfigResource;
+import org.apache.kafka.common.config.SslConfigs;
+import org.apache.kafka.common.config.TopicConfig;
+import org.apache.kafka.common.config.types.Password;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.connect.errors.ConnectException;
+import org.apache.kafka.connect.mirror.MirrorMakerConfig;
+import org.apache.kafka.connect.mirror.SourceAndTarget;
+import org.apache.kafka.connect.util.clusters.EmbeddedConnectCluster;
+import org.apache.kafka.connect.util.clusters.EmbeddedKafkaCluster;
+import org.apache.kafka.test.IntegrationTest;
+import org.junit.experimental.categories.Category;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.kafka.connect.mirror.TestUtils.expectedRecords;
+import static org.apache.kafka.connect.util.clusters.EmbeddedConnectClusterAssertions.CONNECTOR_SETUP_DURATION_MS;
+import static org.apache.kafka.test.TestUtils.waitForCondition;
+import kafka.server.KafkaConfig$;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertFalse;
+//import org.junit.After;
+
+/**
+ * Common Test functions for MM2 integration tests
+ */
+@Category(IntegrationTest.class)
+public class MirrorConnectorsIntegrationBaseTest {
+ private static final Logger log = LoggerFactory.getLogger(MirrorConnectorsIntegrationBaseTest.class);
+
+ protected static final int NUM_RECORDS_PER_PARTITION = 10;
+ public static final int NUM_PARTITIONS = 10;
+ protected static final int NUM_RECORDS_PRODUCED = NUM_PARTITIONS * NUM_RECORDS_PER_PARTITION;
+ protected static final int RECORD_TRANSFER_DURATION_MS = 30_000;
+ protected static final int CHECKPOINT_DURATION_MS = 20_000;
+ protected static final int RECORD_CONSUME_DURATION_MS = 20_000;
+ protected static final int OFFSET_SYNC_DURATION_MS = 30_000;
+ protected static final int NUM_WORKERS = 3;
+
+
+ protected Map<String, String> mm2Props;
+ protected MirrorMakerConfig mm2Config;
+ protected EmbeddedConnectCluster primary;
+ protected EmbeddedConnectCluster backup;
+
+ private final AtomicBoolean exited = new AtomicBoolean(false);
+ private Properties primaryBrokerProps = new Properties();
+ protected Properties backupBrokerProps = new Properties();
Review comment:
because `backupBrokerProps` is referred in `MirrorConnectorsIntegrationSSLTest`
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org