You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@samza.apache.org by sh...@apache.org on 2019/03/28 06:00:58 UTC
[samza] branch master updated: SAMZA-2127: Upgrade to Kafka 2.0
(#951)
This is an automated email from the ASF dual-hosted git repository.
shanthoosh pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/samza.git
The following commit(s) were added to refs/heads/master by this push:
new 01c0605 SAMZA-2127: Upgrade to Kafka 2.0 (#951)
01c0605 is described below
commit 01c06055057e8c260e73bf3f7db7b9eb53af3745
Author: mynameborat <46...@users.noreply.github.com>
AuthorDate: Wed Mar 27 23:00:54 2019 -0700
SAMZA-2127: Upgrade to Kafka 2.0 (#951)
* Kafka 2.0 upgrade
* Migrated some of tests to use new Java APIs and remove scala code
* Addressed review comments; fixed all the remaining failures
* Remove unused code
* Minor cleanup
---
gradle/dependency-versions.gradle | 2 +-
.../samza/system/kafka/KafkaSystemAdmin.java | 194 ++++---
.../org/apache/samza/config/KafkaSerdeConfig.scala | 48 --
.../samza/config_deprecated/KafkaConfig.scala | 398 --------------
.../org/apache/samza/serializers/KafkaSerde.scala | 62 ---
.../samza/system/kafka/KafkaConsumerProxy.java | 12 +-
.../system/kafka/KafkaSystemAdminUtilsScala.scala | 107 ----
.../apache/samza/system/kafka/MessageSink.scala | 35 --
.../samza/system/kafka/TopicMetadataCache.scala | 78 ---
.../system/kafka_deprecated/BrokerProxy.scala | 332 -----------
.../DefaultFetchSimpleConsumer.scala | 66 ---
.../samza/system/kafka_deprecated/GetOffset.scala | 116 ----
.../system/kafka_deprecated/KafkaSystemAdmin.scala | 548 -------------------
.../kafka_deprecated/KafkaSystemConsumer.scala | 311 -----------
.../KafkaSystemConsumerMetrics.scala | 100 ----
.../kafka_deprecated/KafkaSystemFactory.scala | 179 ------
.../kafka_deprecated/KafkaSystemProducer.scala | 235 --------
.../KafkaSystemProducerMetrics.scala | 42 --
.../system/kafka_deprecated/MessageSink.scala | 35 --
.../kafka_deprecated/TopicMetadataCache.scala | 78 ---
.../samza/system/kafka_deprecated/Toss.scala | 28 -
.../samza/util/ClientUtilTopicMetadataStore.scala | 50 --
.../scala/org/apache/samza/util/KafkaUtil.scala | 5 +-
.../samza/system/kafka/MockKafkaProducer.java | 7 +-
.../system/kafka/TestKafkaSystemAdminJava.java | 101 +++-
.../kafka/TestKafkaCheckpointManager.scala | 42 +-
.../apache/samza/config/TestKafkaSerdeConfig.scala | 48 --
.../apache/samza/serializers/TestKafkaSerde.scala | 34 --
.../samza/system/kafka/TestKafkaSystemAdmin.scala | 169 +++---
.../system/kafka/TestTopicMetadataCache.scala | 139 -----
.../system/kafka_deprecated/TestBrokerProxy.scala | 434 ---------------
.../system/kafka_deprecated/TestGetOffset.scala | 110 ----
.../kafka_deprecated/TestKafkaSystemAdmin.scala | 310 -----------
.../kafka_deprecated/TestKafkaSystemConsumer.scala | 191 -------
.../kafka_deprecated/TestKafkaSystemFactory.scala | 98 ----
.../kafka_deprecated/TestKafkaSystemProducer.scala | 604 ---------------------
.../kafka_deprecated/TestTopicMetadataCache.scala | 139 -----
.../org/apache/samza/utils/TestKafkaUtil.scala | 1 -
.../samza/sql/fn/TestBuildOutputRecordUdf.java | 1 +
.../samza/processor/TestZkStreamProcessorBase.java | 12 +-
.../test/StandaloneIntegrationTestHarness.java | 84 ---
.../EndOfStreamIntegrationTest.java | 4 +-
.../controlmessages/WatermarkIntegrationTest.java | 4 +-
.../StreamApplicationIntegrationTestHarness.java | 112 ++--
.../samza/test/harness/IntegrationTestHarness.java | 217 ++++++++
.../samza/test/processor/TestStreamProcessor.java | 29 +-
.../processor/TestZkLocalApplicationRunner.java | 65 +--
.../samzasql/SamzaSqlIntegrationTestHarness.java | 4 +-
.../samza/test/table/TestLocalTableEndToEnd.java | 4 +-
.../TestLocalTableWithConfigRewriterEndToEnd.java | 4 +-
.../TestLocalTableWithLowLevelApiEndToEnd.java | 4 +-
.../TestLocalTableWithSideInputsEndToEnd.java | 4 +-
.../samza/test/table/TestRemoteTableEndToEnd.java | 4 +-
.../harness/AbstractIntegrationTestHarness.scala | 100 ----
.../harness/AbstractKafkaServerTestHarness.scala | 40 +-
.../harness/AbstractZookeeperTestHarness.scala | 8 +-
.../test/integration/StreamTaskTestUtil.scala | 89 ++-
57 files changed, 688 insertions(+), 5589 deletions(-)
diff --git a/gradle/dependency-versions.gradle b/gradle/dependency-versions.gradle
index a2517bd..c257994 100644
--- a/gradle/dependency-versions.gradle
+++ b/gradle/dependency-versions.gradle
@@ -34,7 +34,7 @@
jodaTimeVersion = "2.2"
joptSimpleVersion = "3.2"
junitVersion = "4.12"
- kafkaVersion = "0.11.0.2"
+ kafkaVersion = "2.0.1"
log4jVersion = "1.2.17"
log4j2Version = "2.11.0"
metricsVersion = "2.2.0"
diff --git a/samza-kafka/src/main/java/org/apache/samza/system/kafka/KafkaSystemAdmin.java b/samza-kafka/src/main/java/org/apache/samza/system/kafka/KafkaSystemAdmin.java
index 0ffd1a7..a208835 100644
--- a/samza-kafka/src/main/java/org/apache/samza/system/kafka/KafkaSystemAdmin.java
+++ b/samza-kafka/src/main/java/org/apache/samza/system/kafka/KafkaSystemAdmin.java
@@ -23,15 +23,15 @@ import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableSet;
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.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.function.Supplier;
+import java.util.function.Function;
import java.util.stream.Collectors;
-import kafka.utils.ZkUtils;
import org.apache.commons.lang3.NotImplementedException;
import org.apache.commons.lang3.StringUtils;
import org.apache.kafka.clients.admin.AdminClient;
@@ -39,18 +39,22 @@ import org.apache.kafka.clients.admin.CreateTopicsResult;
import org.apache.kafka.clients.admin.DeleteTopicsResult;
import org.apache.kafka.clients.admin.DescribeTopicsResult;
import org.apache.kafka.clients.admin.NewTopic;
+import org.apache.kafka.clients.admin.RecordsToDelete;
import org.apache.kafka.clients.admin.TopicDescription;
import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.PartitionInfo;
import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.config.TopicConfig;
import org.apache.kafka.common.errors.TopicExistsException;
import org.apache.samza.Partition;
import org.apache.samza.SamzaException;
+import org.apache.samza.config.ApplicationConfig;
import org.apache.samza.config.Config;
-import org.apache.samza.config.SystemConfig;
import org.apache.samza.config.KafkaConfig;
import org.apache.samza.config.MapConfig;
+import org.apache.samza.config.StreamConfig;
+import org.apache.samza.config.SystemConfig;
import org.apache.samza.system.StreamSpec;
import org.apache.samza.system.StreamValidationException;
import org.apache.samza.system.SystemAdmin;
@@ -58,7 +62,6 @@ import org.apache.samza.system.SystemStream;
import org.apache.samza.system.SystemStreamMetadata;
import org.apache.samza.system.SystemStreamPartition;
import org.apache.samza.util.ExponentialSleepStrategy;
-import org.apache.samza.util.ScalaJavaUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import scala.Function0;
@@ -70,8 +73,6 @@ import scala.runtime.AbstractFunction1;
import scala.runtime.AbstractFunction2;
import scala.runtime.BoxedUnit;
-import static org.apache.samza.config.KafkaConsumerConfig.*;
-
public class KafkaSystemAdmin implements SystemAdmin {
private static final Logger LOG = LoggerFactory.getLogger(KafkaSystemAdmin.class);
@@ -92,8 +93,6 @@ public class KafkaSystemAdmin implements SystemAdmin {
protected final Consumer metadataConsumer;
protected final Config config;
- protected kafka.admin.AdminClient adminClientForDelete = null;
-
// Custom properties to create a new coordinator stream.
private final Properties coordinatorStreamProperties;
@@ -130,7 +129,7 @@ public class KafkaSystemAdmin implements SystemAdmin {
KafkaConfig kafkaConfig = new KafkaConfig(config);
coordinatorStreamReplicationFactor = Integer.valueOf(kafkaConfig.getCoordinatorReplicationFactor());
- coordinatorStreamProperties = KafkaSystemAdminUtilsScala.getCoordinatorTopicProperties(kafkaConfig);
+ coordinatorStreamProperties = getCoordinatorStreamProperties(kafkaConfig);
Map<String, String> storeToChangelog =
JavaConverters.mapAsJavaMapConverter(kafkaConfig.getKafkaChangelogEnabledStores()).asJava();
@@ -154,9 +153,7 @@ public class KafkaSystemAdmin implements SystemAdmin {
SystemConfig systemConfig = new SystemConfig(config);
this.deleteCommittedMessages = systemConfig.deleteCommittedMessages(systemName);
- intermediateStreamProperties =
- JavaConverters.mapAsJavaMapConverter(KafkaSystemAdminUtilsScala.getIntermediateStreamProperties(config))
- .asJava();
+ intermediateStreamProperties = getIntermediateStreamProperties(config);
LOG.info(String.format("Created KafkaSystemAdmin for system %s", systemName));
}
@@ -184,13 +181,6 @@ public class KafkaSystemAdmin implements SystemAdmin {
LOG.warn("metadataConsumer.close for system " + systemName + " failed with exception.", e);
}
}
- if (adminClientForDelete != null) {
- try {
- adminClientForDelete.close();
- } catch (Exception e) {
- LOG.warn("AdminClient.close() for system {} failed with exception {}.", systemName, e);
- }
- }
if (adminClient != null) {
adminClient.close();
@@ -451,37 +441,7 @@ public class KafkaSystemAdmin implements SystemAdmin {
allUpcomingOffsets.putAll(offsetsForTopic.getUpcomingOffsets());
});
- scala.collection.immutable.Map<String, SystemStreamMetadata> result =
- KafkaSystemAdminUtilsScala.assembleMetadata(ScalaJavaUtil.toScalaMap(allOldestOffsets),
- ScalaJavaUtil.toScalaMap(allNewestOffsets), ScalaJavaUtil.toScalaMap(allUpcomingOffsets));
-
- LOG.debug("assembled SystemStreamMetadata is: {}", result);
- return JavaConverters.mapAsJavaMapConverter(result).asJava();
- }
-
- private String fetchNewestOffset(SystemStreamPartition ssp) {
- LOG.debug("Fetching newest offset for {}", ssp);
- String newestOffset;
-
- TopicPartition topicPartition = new TopicPartition(ssp.getStream(), ssp.getPartition().getPartitionId());
-
- // the offsets returned from the consumer is the Long type
- Long upcomingOffset =
- (Long) metadataConsumer.endOffsets(Collections.singletonList(topicPartition)).get(topicPartition);
-
- // Kafka's "latest" offset is always last message in stream's offset + 1,
- // so get newest message in stream by subtracting one. This is safe
- // even for key-deduplicated streams, since the last message will
- // never be deduplicated.
- if (upcomingOffset <= 0) {
- LOG.debug("Stripping newest offsets for {} because the topic appears empty.", topicPartition);
- newestOffset = null;
- } else {
- newestOffset = String.valueOf(upcomingOffset - 1);
- }
-
- LOG.info("Newest offset for ssp {} is: {}", ssp, newestOffset);
- return newestOffset;
+ return assembleMetadata(allOldestOffsets, allNewestOffsets, allUpcomingOffsets);
}
@Override
@@ -569,7 +529,7 @@ public class KafkaSystemAdmin implements SystemAdmin {
}
kafkaSpec = new KafkaStreamSpec(spec.getId(), topicName, systemName, spec.getPartitionCount(),
- topicMeta.replicationFactor(), topicMeta.kafkaProps());
+ topicMeta.getReplicationFactor(), topicMeta.getKafkaProperties());
} else if (spec.isCoordinatorStream()) {
kafkaSpec =
new KafkaStreamSpec(spec.getId(), spec.getPhysicalName(), systemName, 1, coordinatorStreamReplicationFactor,
@@ -628,10 +588,18 @@ public class KafkaSystemAdmin implements SystemAdmin {
@Override
public void deleteMessages(Map<SystemStreamPartition, String> offsets) {
if (deleteCommittedMessages) {
- if (adminClientForDelete == null) {
- adminClientForDelete = kafka.admin.AdminClient.create(createAdminClientProperties());
- }
- KafkaSystemAdminUtilsScala.deleteMessages(adminClientForDelete, offsets);
+ Map<TopicPartition, RecordsToDelete> recordsToDelete = offsets.entrySet()
+ .stream()
+ .collect(Collectors.toMap(entry ->
+ new TopicPartition(entry.getKey().getStream(), entry.getKey().getPartition().getPartitionId()),
+ entry -> RecordsToDelete.beforeOffset(Long.parseLong(entry.getValue()) + 1)));
+
+ adminClient.deleteRecords(recordsToDelete).all().whenComplete((ignored, exception) -> {
+ if (exception != null) {
+ LOG.error("Delete message failed for SSPs " + offsets.keySet() + " due to", exception);
+ }
+ });
+
deleteMessageCalled = true;
}
}
@@ -656,27 +624,9 @@ public class KafkaSystemAdmin implements SystemAdmin {
}
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, brokerList);
- // kafka.admin.AdminUtils requires zkConnect
- // this will change after we move to the new org.apache..AdminClient
- String zkConnect =
- config.get(String.format(KafkaConfig.CONSUMER_CONFIGS_CONFIG_KEY(), systemName, ZOOKEEPER_CONNECT));
- if (StringUtils.isBlank(zkConnect)) {
- throw new SamzaException("Missing zookeeper.connect config for admin for system " + systemName);
- }
- props.put(ZOOKEEPER_CONNECT, zkConnect);
-
return props;
}
- private Supplier<ZkUtils> getZkConnection() {
- String zkConnect =
- config.get(String.format(KafkaConfig.CONSUMER_CONFIGS_CONFIG_KEY(), systemName, ZOOKEEPER_CONNECT));
- if (StringUtils.isBlank(zkConnect)) {
- throw new SamzaException("Missing zookeeper.connect config for admin for system " + systemName);
- }
- return () -> ZkUtils.apply(zkConnect, 6000, 6000, false);
- }
-
@Override
public Set<SystemStream> getAllSystemStreams() {
return ((Set<String>) this.metadataConsumer.listTopics().keySet()).stream()
@@ -685,6 +635,79 @@ public class KafkaSystemAdmin implements SystemAdmin {
}
/**
+ * A helper method that takes oldest, newest, and upcoming offsets for each
+ * system stream partition, and creates a single map from stream name to
+ * SystemStreamMetadata.
+ *
+ * @param newestOffsets map of SSP to newest offset
+ * @param oldestOffsets map of SSP to oldest offset
+ * @param upcomingOffsets map of SSP to upcoming offset
+ * @return a {@link Map} from {@code system} to {@link SystemStreamMetadata}
+ */
+ @VisibleForTesting
+ static Map<String, SystemStreamMetadata> assembleMetadata(Map<SystemStreamPartition, String> oldestOffsets,
+ Map<SystemStreamPartition, String> newestOffsets, Map<SystemStreamPartition, String> upcomingOffsets) {
+ HashSet<SystemStreamPartition> allSSPs = new HashSet<>();
+ allSSPs.addAll(oldestOffsets.keySet());
+ allSSPs.addAll(newestOffsets.keySet());
+ allSSPs.addAll(upcomingOffsets.keySet());
+
+ Map<String, SystemStreamMetadata> assembledMetadata = allSSPs.stream()
+ .collect(Collectors.groupingBy(SystemStreamPartition::getStream))
+ .entrySet()
+ .stream()
+ .collect(Collectors.toMap(Map.Entry::getKey, entry -> {
+ Map<Partition, SystemStreamMetadata.SystemStreamPartitionMetadata> partitionMetadata =
+ entry.getValue()
+ .stream()
+ .collect(Collectors.toMap(SystemStreamPartition::getPartition, ssp ->
+ new SystemStreamMetadata.SystemStreamPartitionMetadata(
+ oldestOffsets.getOrDefault(ssp, null),
+ newestOffsets.getOrDefault(ssp, null),
+ upcomingOffsets.get(ssp))));
+ return new SystemStreamMetadata(entry.getKey(), partitionMetadata);
+ }));
+
+ return assembledMetadata;
+ }
+
+ /**
+ * Fetch stream properties for all intermediate streams.
+ *
+ * @param config kafka system config
+ * @return a {@link Map} from {@code streamId} to stream {@link Properties}
+ */
+ @VisibleForTesting
+ static Map<String, Properties> getIntermediateStreamProperties(Config config) {
+ Map<String, Properties> intermedidateStreamProperties = Collections.emptyMap();
+ ApplicationConfig appConfig = new ApplicationConfig(config);
+
+ if (appConfig.getAppMode() == ApplicationConfig.ApplicationMode.BATCH) {
+ StreamConfig streamConfig = new StreamConfig(config);
+ intermedidateStreamProperties = JavaConverters.asJavaCollectionConverter(streamConfig.getStreamIds())
+ .asJavaCollection()
+ .stream()
+ .filter(streamConfig::getIsIntermediateStream)
+ .collect(Collectors.toMap(Function.identity(), streamId -> {
+ Properties properties = new Properties();
+ properties.putAll(streamConfig.getStreamProperties(streamId));
+ properties.putIfAbsent(TopicConfig.RETENTION_MS_CONFIG, String.valueOf(KafkaConfig.DEFAULT_RETENTION_MS_FOR_BATCH()));
+ return properties;
+ }));
+ }
+
+ return intermedidateStreamProperties;
+ }
+
+ private Properties getCoordinatorStreamProperties(KafkaConfig config) {
+ Properties coordinatorStreamProperties = new Properties();
+ coordinatorStreamProperties.put(TopicConfig.CLEANUP_POLICY_CONFIG, TopicConfig.CLEANUP_POLICY_COMPACT);
+ coordinatorStreamProperties.put(TopicConfig.SEGMENT_BYTES_CONFIG, config.getCoordinatorSegmentBytes());
+
+ return coordinatorStreamProperties;
+ }
+
+ /**
* Container for metadata about offsets.
*/
private static class OffsetsMaps {
@@ -711,4 +734,29 @@ public class KafkaSystemAdmin implements SystemAdmin {
return upcomingOffsets;
}
}
+
+ /**
+ * A helper class for represent changelog related information.
+ */
+ private static class ChangelogInfo {
+ final int replicationFactor;
+ final Properties kafkaProperties;
+
+ /**
+ * @param replicationFactor The number of replicas for the changelog stream
+ * @param kafkaProperties The kafka specific properties that need to be used for changelog stream creation
+ */
+ ChangelogInfo(int replicationFactor, Properties kafkaProperties) {
+ this.replicationFactor = replicationFactor;
+ this.kafkaProperties = kafkaProperties;
+ }
+
+ public int getReplicationFactor() {
+ return replicationFactor;
+ }
+
+ public Properties getKafkaProperties() {
+ return kafkaProperties;
+ }
+ }
}
diff --git a/samza-kafka/src/main/scala/org/apache/samza/config/KafkaSerdeConfig.scala b/samza-kafka/src/main/scala/org/apache/samza/config/KafkaSerdeConfig.scala
deleted file mode 100644
index ed2bd40..0000000
--- a/samza-kafka/src/main/scala/org/apache/samza/config/KafkaSerdeConfig.scala
+++ /dev/null
@@ -1,48 +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.samza.config
-
-import java.util.Properties
-
-import kafka.utils.VerifiableProperties
-
-object KafkaSerdeConfig {
- // kafka serde config constants
- val ENCODER = SerializerConfig.SERIALIZER_PREFIX + ".encoder"
- val DECODER = SerializerConfig.SERIALIZER_PREFIX + ".decoder"
-
- implicit def Config2KafkaSerde(config: Config) = new KafkaSerdeConfig(config)
-}
-
-class KafkaSerdeConfig(config: Config) extends ScalaMapConfig(config) {
- def getKafkaEncoder(serializer: String) =
- getOption(KafkaSerdeConfig.ENCODER format serializer)
-
- def getKafkaDecoder(serializer: String) =
- getOption(KafkaSerdeConfig.DECODER format serializer)
-
- def getKafkaProperties(serializer: String) = {
- val properties = new Properties();
- val prefix = SerializerConfig.SERIALIZER_PREFIX format serializer + "."
- properties.putAll(config.subset(prefix, true))
-
- new VerifiableProperties(properties);
- }
-}
diff --git a/samza-kafka/src/main/scala/org/apache/samza/config_deprecated/KafkaConfig.scala b/samza-kafka/src/main/scala/org/apache/samza/config_deprecated/KafkaConfig.scala
deleted file mode 100644
index 9b5cb31..0000000
--- a/samza-kafka/src/main/scala/org/apache/samza/config_deprecated/KafkaConfig.scala
+++ /dev/null
@@ -1,398 +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.samza.config_deprecated
-
-
-import java.util
-import java.util.concurrent.TimeUnit
-import java.util.regex.Pattern
-import java.util.{Properties, UUID}
-
-import com.google.common.collect.ImmutableMap
-import kafka.consumer.ConsumerConfig
-import org.apache.kafka.clients.producer.ProducerConfig
-import org.apache.kafka.common.serialization.ByteArraySerializer
-import org.apache.samza.SamzaException
-import org.apache.samza.config.ApplicationConfig.ApplicationMode
-import org.apache.samza.config._
-import org.apache.samza.util.{Logging, StreamUtil}
-
-import scala.collection.JavaConverters._
-
-object KafkaConfig {
- val TOPIC_REPLICATION_FACTOR = "replication.factor"
- val TOPIC_DEFAULT_REPLICATION_FACTOR = "2"
-
- val REGEX_RESOLVED_STREAMS = "job.config.rewriter.%s.regex"
- val REGEX_RESOLVED_SYSTEM = "job.config.rewriter.%s.system"
- val REGEX_INHERITED_CONFIG = "job.config.rewriter.%s.config"
-
- val SEGMENT_BYTES = "segment.bytes"
-
- val CHECKPOINT_SYSTEM = "task.checkpoint.system"
- val CHECKPOINT_REPLICATION_FACTOR = "task.checkpoint." + TOPIC_REPLICATION_FACTOR
- val CHECKPOINT_SEGMENT_BYTES = "task.checkpoint." + SEGMENT_BYTES
-
- val CHANGELOG_STREAM_REPLICATION_FACTOR = "stores.%s.changelog." + TOPIC_REPLICATION_FACTOR
- val DEFAULT_CHANGELOG_STREAM_REPLICATION_FACTOR = CHANGELOG_STREAM_REPLICATION_FACTOR format "default"
- val CHANGELOG_STREAM_KAFKA_SETTINGS = "stores.%s.changelog.kafka."
- // The default segment size to use for changelog topics
- val CHANGELOG_DEFAULT_SEGMENT_SIZE = "536870912"
-
- // Helper regular expression definitions to extract/match configurations
- val CHANGELOG_STREAM_NAMES_REGEX = "stores\\.(.*)\\.changelog$"
-
- val JOB_COORDINATOR_REPLICATION_FACTOR = "job.coordinator." + TOPIC_REPLICATION_FACTOR
- val JOB_COORDINATOR_SEGMENT_BYTES = "job.coordinator." + SEGMENT_BYTES
-
- val CONSUMER_CONFIGS_CONFIG_KEY = "systems.%s.consumer.%s"
- val PRODUCER_BOOTSTRAP_SERVERS_CONFIG_KEY = "systems.%s.producer.bootstrap.servers"
- val PRODUCER_CONFIGS_CONFIG_KEY = "systems.%s.producer.%s"
- val CONSUMER_ZK_CONNECT_CONFIG_KEY = "systems.%s.consumer.zookeeper.connect"
-
- /**
- * Defines how low a queue can get for a single system/stream/partition
- * combination before trying to fetch more messages for it.
- */
- val CONSUMER_FETCH_THRESHOLD = SystemConfig.SYSTEM_ID_PREFIX + "samza.fetch.threshold"
-
- val DEFAULT_CHECKPOINT_SEGMENT_BYTES = 26214400
-
- /**
- * Defines how many bytes to use for the buffered prefetch messages for job as a whole.
- * The bytes for a single system/stream/partition are computed based on this.
- * This fetches wholes messages, hence this bytes limit is a soft one, and the actual usage can be
- * the bytes limit + size of max message in the partition for a given stream.
- * If the value of this property is > 0 then this takes precedence over CONSUMER_FETCH_THRESHOLD config.
- */
- val CONSUMER_FETCH_THRESHOLD_BYTES = SystemConfig.SYSTEM_ID_PREFIX + "samza.fetch.threshold.bytes"
-
- val DEFAULT_RETENTION_MS_FOR_BATCH = TimeUnit.DAYS.toMillis(1)
-
- implicit def Config2Kafka(config: Config) = new KafkaConfig(config)
-}
-
-class KafkaConfig(config: Config) extends ScalaMapConfig(config) {
- /**
- * Gets the System to use for reading/writing checkpoints. Uses the following precedence.
- *
- * 1. If task.checkpoint.system is defined, that value is used.
- * 2. If job.default.system is defined, that value is used.
- * 3. None
- */
- def getCheckpointSystem = Option(getOrElse(KafkaConfig.CHECKPOINT_SYSTEM, new JobConfig(config).getDefaultSystem.orNull))
-
- /**
- * Gets the replication factor for the checkpoint topic. Uses the following precedence.
- *
- * 1. If task.checkpoint.replication.factor is configured, that value is used.
- * 2. If systems.checkpoint-system.default.stream.replication.factor is configured, that value is used.
- * 3. None
- *
- * Note that the checkpoint-system has a similar precedence. See [[getCheckpointSystem]]
- */
- def getCheckpointReplicationFactor() = {
- val defaultReplicationFactor: String = getSystemDefaultReplicationFactor(getCheckpointSystem.orNull, "3")
- val replicationFactor = getOrDefault(KafkaConfig.CHECKPOINT_REPLICATION_FACTOR, defaultReplicationFactor)
-
- Option(replicationFactor)
- }
-
- private def getSystemDefaultReplicationFactor(systemName: String, defaultValue: String) = {
- val defaultReplicationFactor = new SystemConfig(config).getDefaultStreamProperties(systemName).getOrDefault(KafkaConfig.TOPIC_REPLICATION_FACTOR, defaultValue)
- defaultReplicationFactor
- }
-
- /**
- * Gets the segment bytes for the checkpoint topic. Uses the following precedence.
- *
- * 1. If task.checkpoint.segment.bytes is configured, that value is used.
- * 2. If systems.checkpoint-system.default.stream.segment.bytes is configured, that value is used.
- * 3. None
- *
- * Note that the checkpoint-system has a similar precedence. See [[getCheckpointSystem]]
- */
- def getCheckpointSegmentBytes() = {
- val defaultsegBytes = new SystemConfig(config).getDefaultStreamProperties(getCheckpointSystem.orNull).getInt(KafkaConfig.SEGMENT_BYTES, KafkaConfig.DEFAULT_CHECKPOINT_SEGMENT_BYTES)
- getInt(KafkaConfig.CHECKPOINT_SEGMENT_BYTES, defaultsegBytes)
- }
-
- /**
- * Gets the replication factor for the coordinator topic. Uses the following precedence.
- *
- * 1. If job.coordinator.replication.factor is configured, that value is used.
- * 2. If systems.coordinator-system.default.stream.replication.factor is configured, that value is used.
- * 3. 3
- *
- * Note that the coordinator-system has a similar precedence. See [[JobConfig.getCoordinatorSystemName]]
- */
- def getCoordinatorReplicationFactor = getOption(KafkaConfig.JOB_COORDINATOR_REPLICATION_FACTOR) match {
- case Some(rplFactor) => rplFactor
- case _ =>
- val coordinatorSystem = new JobConfig(config).getCoordinatorSystemNameOrNull
- val systemReplicationFactor = new SystemConfig(config).getDefaultStreamProperties(coordinatorSystem).getOrDefault(KafkaConfig.TOPIC_REPLICATION_FACTOR, "3")
- systemReplicationFactor
- }
-
- /**
- * Gets the segment bytes for the coordinator topic. Uses the following precedence.
- *
- * 1. If job.coordinator.segment.bytes is configured, that value is used.
- * 2. If systems.coordinator-system.default.stream.segment.bytes is configured, that value is used.
- * 3. None
- *
- * Note that the coordinator-system has a similar precedence. See [[JobConfig.getCoordinatorSystemName]]
- */
- def getCoordinatorSegmentBytes = getOption(KafkaConfig.JOB_COORDINATOR_SEGMENT_BYTES) match {
- case Some(segBytes) => segBytes
- case _ =>
- val coordinatorSystem = new JobConfig(config).getCoordinatorSystemNameOrNull
- val segBytes = new SystemConfig(config).getDefaultStreamProperties(coordinatorSystem).getOrDefault(KafkaConfig.SEGMENT_BYTES, "26214400")
- segBytes
- }
-
- // custom consumer config
- def getConsumerFetchThreshold(name: String) = getOption(KafkaConfig.CONSUMER_FETCH_THRESHOLD format name)
-
- def getConsumerFetchThresholdBytes(name: String) = getOption(KafkaConfig.CONSUMER_FETCH_THRESHOLD_BYTES format name)
-
- def isConsumerFetchThresholdBytesEnabled(name: String): Boolean = getConsumerFetchThresholdBytes(name).getOrElse("-1").toLong > 0
-
- /**
- * Returns a map of topic -> fetch.message.max.bytes value for all streams that
- * are defined with this property in the config.
- */
- def getFetchMessageMaxBytesTopics(systemName: String) = {
- val subConf = config.subset("systems.%s.streams." format systemName, true)
- subConf
- .asScala
- .filterKeys(k => k.endsWith(".consumer.fetch.message.max.bytes"))
- .map {
- case (fetchMessageMaxBytes, fetchSizeValue) =>
- (fetchMessageMaxBytes.replace(".consumer.fetch.message.max.bytes", ""), fetchSizeValue.toInt)
- }.toMap
- }
-
- /**
- * Returns a map of topic -> auto.offset.reset value for all streams that
- * are defined with this property in the config.
- */
- def getAutoOffsetResetTopics(systemName: String) = {
- val subConf = config.subset("systems.%s.streams." format systemName, true)
- subConf
- .asScala
- .filterKeys(k => k.endsWith(".consumer.auto.offset.reset"))
- .map {
- case (topicAutoOffsetReset, resetValue) =>
- (topicAutoOffsetReset.replace(".consumer.auto.offset.reset", ""), resetValue)
- }.toMap
- }
-
- // regex resolver
- def getRegexResolvedStreams(rewriterName: String) = getOption(KafkaConfig.REGEX_RESOLVED_STREAMS format rewriterName)
-
- def getRegexResolvedSystem(rewriterName: String) = getOption(KafkaConfig.REGEX_RESOLVED_SYSTEM format rewriterName)
-
- def getRegexResolvedInheritedConfig(rewriterName: String) = config.subset((KafkaConfig.REGEX_INHERITED_CONFIG format rewriterName) + ".", true)
-
- /**
- * Gets the replication factor for the changelog topics. Uses the following precedence.
- *
- * 1. If stores.myStore.changelog.replication.factor is configured, that value is used.
- * 2. If systems.changelog-system.default.stream.replication.factor is configured, that value is used.
- * 3. 2
- *
- * Note that the changelog-system has a similar precedence. See [[JavaStorageConfig]]
- */
- def getChangelogStreamReplicationFactor(name: String) = getOption(KafkaConfig.CHANGELOG_STREAM_REPLICATION_FACTOR format name).getOrElse(getDefaultChangelogStreamReplicationFactor)
-
- def getDefaultChangelogStreamReplicationFactor() = {
- val changelogSystem = new JavaStorageConfig(config).getChangelogSystem()
- getOption(KafkaConfig.DEFAULT_CHANGELOG_STREAM_REPLICATION_FACTOR).getOrElse(getSystemDefaultReplicationFactor(changelogSystem, "2"))
- }
-
- // The method returns a map of storenames to changelog topic names, which are configured to use kafka as the changelog stream
- def getKafkaChangelogEnabledStores() = {
- val changelogConfigs = config.regexSubset(KafkaConfig.CHANGELOG_STREAM_NAMES_REGEX).asScala
- var storeToChangelog = Map[String, String]()
- val storageConfig = new StorageConfig(config)
- val pattern = Pattern.compile(KafkaConfig.CHANGELOG_STREAM_NAMES_REGEX)
-
- for ((changelogConfig, cn) <- changelogConfigs) {
- // Lookup the factory for this particular stream and verify if it's a kafka system
-
- val matcher = pattern.matcher(changelogConfig)
- val storeName = if (matcher.find()) matcher.group(1) else throw new SamzaException("Unable to find store name in the changelog configuration: " + changelogConfig + " with SystemStream: " + cn)
-
- storageConfig.getChangelogStream(storeName).foreach(changelogName => {
- val systemStream = StreamUtil.getSystemStreamFromNames(changelogName)
- storeToChangelog += storeName -> systemStream.getStream
- })
- }
- storeToChangelog
- }
-
- // Get all kafka properties for changelog stream topic creation
- def getChangelogKafkaProperties(name: String) = {
- val filteredConfigs = config.subset(KafkaConfig.CHANGELOG_STREAM_KAFKA_SETTINGS format name, true)
- val kafkaChangeLogProperties = new Properties
-
- val appConfig = new ApplicationConfig(config)
- // SAMZA-1600: do not use the combination of "compact,delete" as cleanup policy until we pick up Kafka broker 0.11.0.57,
- // 1.0.2, or 1.1.0 (see KAFKA-6568)
-
- // Adjust changelog topic setting, when TTL is set on a RocksDB store
- // - Disable log compaction on Kafka changelog topic
- // - Set topic TTL to be the same as RocksDB TTL
- Option(config.get("stores.%s.rocksdb.ttl.ms" format name)) match {
- case Some(rocksDbTtl) =>
- if (!config.containsKey("stores.%s.changelog.kafka.cleanup.policy" format name)) {
- kafkaChangeLogProperties.setProperty("cleanup.policy", "delete")
- if (!config.containsKey("stores.%s.changelog.kafka.retention.ms" format name)) {
- kafkaChangeLogProperties.setProperty("retention.ms", String.valueOf(rocksDbTtl))
- }
- }
- case _ =>
- kafkaChangeLogProperties.setProperty("cleanup.policy", "compact")
- }
-
- kafkaChangeLogProperties.setProperty("segment.bytes", KafkaConfig.CHANGELOG_DEFAULT_SEGMENT_SIZE)
- kafkaChangeLogProperties.setProperty("delete.retention.ms", String.valueOf(new StorageConfig(config).getChangeLogDeleteRetentionInMs(name)))
- filteredConfigs.asScala.foreach { kv => kafkaChangeLogProperties.setProperty(kv._1, kv._2) }
- kafkaChangeLogProperties
- }
-
- // Set the checkpoint topic configs to have a very small segment size and
- // enable log compaction. This keeps job startup time small since there
- // are fewer useless (overwritten) messages to read from the checkpoint
- // topic.
- def getCheckpointTopicProperties() = {
- val segmentBytes: Int = getCheckpointSegmentBytes()
- val appConfig = new ApplicationConfig(config)
- val isStreamMode = appConfig.getAppMode == ApplicationMode.STREAM
- val properties = new Properties()
-
- if (isStreamMode) {
- properties.putAll(ImmutableMap.of(
- "cleanup.policy", "compact",
- "segment.bytes", String.valueOf(segmentBytes)))
- } else {
- properties.putAll(ImmutableMap.of(
- "cleanup.policy", "compact,delete",
- "retention.ms", String.valueOf(KafkaConfig.DEFAULT_RETENTION_MS_FOR_BATCH),
- "segment.bytes", String.valueOf(segmentBytes)))
- }
- properties
- }
-
- /**
- * @deprecated Use KafkaConsumerConfig
- */
- @Deprecated
- def getKafkaSystemConsumerConfig( systemName: String,
- clientId: String,
- groupId: String = "undefined-samza-consumer-group-%s" format UUID.randomUUID.toString,
- injectedProps: Map[String, String] = Map()) = {
-
- val subConf = config.subset("systems.%s.consumer." format systemName, true)
- val consumerProps = new Properties()
- consumerProps.putAll(subConf)
- consumerProps.put("group.id", groupId)
- consumerProps.put("client.id", clientId)
- consumerProps.putAll(injectedProps.asJava)
- new ConsumerConfig(consumerProps)
- }
-
- def getKafkaSystemProducerConfig( systemName: String,
- clientId: String,
- injectedProps: Map[String, String] = Map()) = {
-
- val subConf = config.subset("systems.%s.producer." format systemName, true)
- val producerProps = new util.HashMap[String, String]()
- producerProps.putAll(subConf)
- producerProps.put("client.id", clientId)
- producerProps.putAll(injectedProps.asJava)
- new KafkaProducerConfig(systemName, clientId, producerProps)
- }
-}
-
-class KafkaProducerConfig(val systemName: String,
- val clientId: String = "",
- properties: java.util.Map[String, String] = new util.HashMap[String, String]()) extends Logging {
-
- // Copied from new Kafka API - Workaround until KAFKA-1794 is resolved
- val RECONNECT_BACKOFF_MS_DEFAULT = 10L
-
- //Overrides specific to samza-kafka (these are considered as defaults in Samza & can be overridden by user
- val MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION_DEFAULT: java.lang.Integer = 1.asInstanceOf[Integer]
- val RETRIES_DEFAULT: java.lang.Integer = Integer.MAX_VALUE
- val LINGER_MS_DEFAULT: java.lang.Integer = 10
-
- def getProducerProperties = {
-
- val byteArraySerializerClassName = classOf[ByteArraySerializer].getCanonicalName
- val producerProperties: java.util.Map[String, Object] = new util.HashMap[String, Object]()
- producerProperties.putAll(properties)
-
- if (!producerProperties.containsKey(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG)) {
- debug("%s undefined. Defaulting to %s." format(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, byteArraySerializerClassName))
- producerProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, byteArraySerializerClassName)
- }
-
- if (!producerProperties.containsKey(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG)) {
- debug("%s undefined. Defaulting to %s." format(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, byteArraySerializerClassName))
- producerProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, byteArraySerializerClassName)
- }
-
- if (producerProperties.containsKey(ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION)
- && producerProperties.get(ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION).asInstanceOf[String].toInt > MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION_DEFAULT) {
- warn("Setting '%s' to a value other than %d does not guarantee message ordering because new messages will be sent without waiting for previous ones to be acknowledged."
- format(ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION, MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION_DEFAULT))
- } else {
- producerProperties.put(ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION, MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION_DEFAULT)
- }
-
- if (!producerProperties.containsKey(ProducerConfig.RETRIES_CONFIG)) {
- debug("%s undefined. Defaulting to %s." format(ProducerConfig.RETRIES_CONFIG, RETRIES_DEFAULT))
- producerProperties.put(ProducerConfig.RETRIES_CONFIG, RETRIES_DEFAULT)
- }
- producerProperties.get(ProducerConfig.RETRIES_CONFIG).toString.toInt // Verify int
-
- if (!producerProperties.containsKey(ProducerConfig.LINGER_MS_CONFIG)) {
- debug("%s undefined. Defaulting to %s." format(ProducerConfig.LINGER_MS_CONFIG, LINGER_MS_DEFAULT))
- producerProperties.put(ProducerConfig.LINGER_MS_CONFIG, LINGER_MS_DEFAULT)
- }
- producerProperties.get(ProducerConfig.LINGER_MS_CONFIG).toString.toInt // Verify int
-
- producerProperties
- }
-
- val reconnectIntervalMs = Option(properties.get(ProducerConfig.RECONNECT_BACKOFF_MS_CONFIG))
- .getOrElse(RECONNECT_BACKOFF_MS_DEFAULT).asInstanceOf[Long]
-
- val bootsrapServers = {
- if (properties.containsKey("metadata.broker.list"))
- warn("Kafka producer configuration contains 'metadata.broker.list'. This configuration is deprecated . Samza has been upgraded " +
- "to use Kafka's new producer API. Please update your configurations based on the documentation at http://kafka.apache.org/documentation.html#newproducerconfigs")
- Option(properties.get("bootstrap.servers"))
- .getOrElse(throw new SamzaException("No bootstrap servers defined in config for %s." format systemName))
- .asInstanceOf[String]
- }
-}
diff --git a/samza-kafka/src/main/scala/org/apache/samza/serializers/KafkaSerde.scala b/samza-kafka/src/main/scala/org/apache/samza/serializers/KafkaSerde.scala
deleted file mode 100644
index d626b79..0000000
--- a/samza-kafka/src/main/scala/org/apache/samza/serializers/KafkaSerde.scala
+++ /dev/null
@@ -1,62 +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.samza.serializers
-import java.nio.ByteBuffer
-import org.apache.samza.util.Util
-import kafka.serializer.Encoder
-import kafka.serializer.Decoder
-import kafka.utils.VerifiableProperties
-import org.apache.samza.config.Config
-import org.apache.samza.config.KafkaSerdeConfig.Config2KafkaSerde
-import org.apache.samza.SamzaException
-
-class KafkaSerde[T](encoder: Encoder[T], decoder: Decoder[T]) extends Serde[T] {
- def toBytes(obj: T): Array[Byte] = encoder.toBytes(obj)
- def fromBytes(bytes: Array[Byte]): T = decoder.fromBytes(bytes)
-}
-
-class KafkaSerdeFactory[T] extends SerdeFactory[T] {
- def getSerde(name: String, config: Config): Serde[T] = {
- val encoderClassName = config
- .getKafkaEncoder(name)
- .getOrElse(throw new SamzaException("No kafka encoder defined for %s" format name))
- val decoderClassName = config
- .getKafkaDecoder(name)
- .getOrElse(throw new SamzaException("No kafka decoder defined for %s" format name))
-
- val verifiableProperties = config.getKafkaProperties(name)
-
- val encoder = getObj[Encoder[T]](encoderClassName, verifiableProperties);
- val decoder = getObj[Decoder[T]](decoderClassName, verifiableProperties);
-
- new KafkaSerde(encoder, decoder)
- }
-
- /**
- * Instantiate a class instance from a given className and properties.
- */
- private def getObj[T](className: String, properties: VerifiableProperties) = {
- Class
- .forName(className)
- .getDeclaredConstructor(classOf[VerifiableProperties])
- .newInstance(properties)
- .asInstanceOf[T]
- }
-}
diff --git a/samza-kafka/src/main/scala/org/apache/samza/system/kafka/KafkaConsumerProxy.java b/samza-kafka/src/main/scala/org/apache/samza/system/kafka/KafkaConsumerProxy.java
index ac0a55c..f85f5bf 100644
--- a/samza-kafka/src/main/scala/org/apache/samza/system/kafka/KafkaConsumerProxy.java
+++ b/samza-kafka/src/main/scala/org/apache/samza/system/kafka/KafkaConsumerProxy.java
@@ -391,12 +391,16 @@ public class KafkaConsumerProxy<K, V> {
// populate the MetricNames first time
if (perPartitionMetrics.isEmpty()) {
- Map<String, String> tags = new HashMap<>();
- tags.put("client-id", clientId); // this is required by the KafkaConsumer to get the metrics
-
for (SystemStreamPartition ssp : ssps) {
TopicPartition tp = KafkaSystemConsumer.toTopicPartition(ssp);
- perPartitionMetrics.put(ssp, new MetricName(tp + ".records-lag", "consumer-fetch-manager-metrics", "", tags));
+
+ // These are required by the KafkaConsumer to get the metrics
+ HashMap<String, String> tags = new HashMap<>();
+ tags.put("client-id", clientId);
+ tags.put("topic", tp.topic());
+ tags.put("partition", Integer.toString(tp.partition()));
+
+ perPartitionMetrics.put(ssp, new MetricName("records-lag", "consumer-fetch-manager-metrics", "", tags));
}
}
diff --git a/samza-kafka/src/main/scala/org/apache/samza/system/kafka/KafkaSystemAdminUtilsScala.scala b/samza-kafka/src/main/scala/org/apache/samza/system/kafka/KafkaSystemAdminUtilsScala.scala
deleted file mode 100644
index 89ba1bb..0000000
--- a/samza-kafka/src/main/scala/org/apache/samza/system/kafka/KafkaSystemAdminUtilsScala.scala
+++ /dev/null
@@ -1,107 +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.samza.system.kafka
-
-import java.util
-import java.util.Properties
-
-import kafka.admin.AdminClient
-import kafka.utils.Logging
-import org.apache.kafka.common.TopicPartition
-import org.apache.samza.config.ApplicationConfig.ApplicationMode
-import org.apache.samza.config.{ApplicationConfig, Config, KafkaConfig, StreamConfig}
-import org.apache.samza.system.SystemStreamMetadata.SystemStreamPartitionMetadata
-import org.apache.samza.system.{SystemStreamMetadata, SystemStreamPartition}
-
-import scala.collection.JavaConverters._
-
-/**
- * A helper class for KafkaSystemAdmin
- *
- * @param replicationFactor The number of replicas for the changelog stream
- * @param kafkaProps The kafka specific properties that need to be used for changelog stream creation
- */
-case class ChangelogInfo(var replicationFactor: Int, var kafkaProps: Properties)
-
-
-// TODO move to org.apache.kafka.clients.admin.AdminClien from the kafka.admin.AdminClient
-object KafkaSystemAdminUtilsScala extends Logging {
-
- /**
- * A helper method that takes oldest, newest, and upcoming offsets for each
- * system stream partition, and creates a single map from stream name to
- * SystemStreamMetadata.
- */
- def assembleMetadata(oldestOffsets: Map[SystemStreamPartition, String], newestOffsets: Map[SystemStreamPartition, String], upcomingOffsets: Map[SystemStreamPartition, String]): Map[String, SystemStreamMetadata] = {
- val allMetadata = (oldestOffsets.keySet ++ newestOffsets.keySet ++ upcomingOffsets.keySet)
- .groupBy(_.getStream)
- .map {
- case (streamName, systemStreamPartitions) =>
- val streamPartitionMetadata = systemStreamPartitions
- .map(systemStreamPartition => {
- val partitionMetadata = new SystemStreamPartitionMetadata(
- // If the topic/partition is empty then oldest and newest will
- // be stripped of their offsets, so default to null.
- oldestOffsets.getOrElse(systemStreamPartition, null),
- newestOffsets.getOrElse(systemStreamPartition, null),
- upcomingOffsets(systemStreamPartition))
- (systemStreamPartition.getPartition, partitionMetadata)
- })
- .toMap
- val streamMetadata = new SystemStreamMetadata(streamName, streamPartitionMetadata.asJava)
- (streamName, streamMetadata)
- }
- .toMap
-
- // This is typically printed downstream and it can be spammy, so debug level here.
- debug("Got metadata: %s" format allMetadata)
-
- allMetadata
- }
-
- def getCoordinatorTopicProperties(config: KafkaConfig) = {
- val segmentBytes = config.getCoordinatorSegmentBytes
- (new Properties /: Map(
- "cleanup.policy" -> "compact",
- "segment.bytes" -> segmentBytes)) { case (props, (k, v)) => props.put(k, v); props }
- }
-
- def getIntermediateStreamProperties(config: Config): Map[String, Properties] = {
- val appConfig = new ApplicationConfig(config)
- if (appConfig.getAppMode == ApplicationMode.BATCH) {
- val streamConfig = new StreamConfig(config)
- streamConfig.getStreamIds().filter(streamConfig.getIsIntermediateStream(_)).map(streamId => {
- val properties = new Properties()
- properties.putAll(streamConfig.getStreamProperties(streamId))
- properties.putIfAbsent("retention.ms", String.valueOf(KafkaConfig.DEFAULT_RETENTION_MS_FOR_BATCH))
- (streamId, properties)
- }).toMap
- } else {
- Map()
- }
- }
-
- def deleteMessages(adminClient : AdminClient, offsets: util.Map[SystemStreamPartition, String]) = {
- val nextOffsets = offsets.asScala.toSeq.map { case (systemStreamPartition, offset) =>
- (new TopicPartition(systemStreamPartition.getStream, systemStreamPartition.getPartition.getPartitionId), offset.toLong + 1)
- }.toMap
- adminClient.deleteRecordsBefore(nextOffsets);
- }
-}
diff --git a/samza-kafka/src/main/scala/org/apache/samza/system/kafka/MessageSink.scala b/samza-kafka/src/main/scala/org/apache/samza/system/kafka/MessageSink.scala
deleted file mode 100644
index 50d4746..0000000
--- a/samza-kafka/src/main/scala/org/apache/samza/system/kafka/MessageSink.scala
+++ /dev/null
@@ -1,35 +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.samza.system.kafka
-
-import kafka.common.TopicAndPartition
-import kafka.message.MessageAndOffset
-
-private[kafka] trait MessageSink {
- def setIsAtHighWatermark(tp: TopicAndPartition, isAtHighWatermark: Boolean): Unit
-
- def addMessage(tp: TopicAndPartition, msg: MessageAndOffset, highWatermark: Long): Unit
-
- def abdicate(tp: TopicAndPartition, nextOffset: Long): Unit
-
- def refreshDropped(): Unit
-
- def needsMoreMessages(tp: TopicAndPartition): Boolean
-}
diff --git a/samza-kafka/src/main/scala/org/apache/samza/system/kafka/TopicMetadataCache.scala b/samza-kafka/src/main/scala/org/apache/samza/system/kafka/TopicMetadataCache.scala
deleted file mode 100644
index 8a3ab2b..0000000
--- a/samza-kafka/src/main/scala/org/apache/samza/system/kafka/TopicMetadataCache.scala
+++ /dev/null
@@ -1,78 +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.samza.system.kafka
-
-import org.apache.samza.util.Logging
-import kafka.api.TopicMetadata
-import org.apache.samza.util.KafkaUtil
-
-/**
- * TopicMetadataCache is used to cache all the topic metadata for Kafka per
- * (system, topic) partition. The cache access is thread safe. Each entry in
- * the cache is refreshed after a specified interval. The cache uses the passed
- * in getTopicInfoFromStore that retrieves the topic metadata from the store (usually zookeeper).
- */
-object TopicMetadataCache extends Logging {
- private case class MetadataInfo(var streamMetadata: TopicMetadata, var lastRefreshMs: Long)
- private val topicMetadataMap: scala.collection.mutable.Map[(String, String), MetadataInfo] = new scala.collection.mutable.HashMap[(String, String), MetadataInfo]
- private val lock = new Object
-
- // used to fetch the topic metadata from the store. Accepts a topic and system
- type FetchTopicMetadataType = (Set[String]) => Map[String, TopicMetadata]
-
- def getTopicMetadata(topics: Set[String], systemName: String, getTopicInfoFromStore: FetchTopicMetadataType, cacheTimeout: Long = 5000L, getTime: () => Long = { System.currentTimeMillis }): Map[String, TopicMetadata] = {
- lock synchronized {
- val time = getTime()
- val missingTopics = topics.filter(topic => !topicMetadataMap.contains(systemName, topic))
- val topicsWithBadOrExpiredMetadata = (topics -- missingTopics).filter(topic => {
- val metadata = topicMetadataMap(systemName, topic)
- hasBadErrorCode(metadata.streamMetadata) || ((time - metadata.lastRefreshMs) > cacheTimeout)
- })
- val topicsToRefresh = missingTopics ++ topicsWithBadOrExpiredMetadata
-
- if (topicsToRefresh.size > 0) {
- // Refresh topic information for any missing, expired, or bad topic metadata.
- topicMetadataMap ++= getTopicInfoFromStore(missingTopics ++ topicsWithBadOrExpiredMetadata)
- .map { case (topic, metadata) => ((systemName, topic), MetadataInfo(metadata, getTime())) }
- .toMap
- }
-
- // Use our new updated cache to return a map of topic -> metadata
- topicMetadataMap
- .filterKeys(topics.map(topic => (systemName, topic)))
- .map {
- case ((systemName, topic), metadata) =>
- (topic, metadata.streamMetadata)
- }.toMap
- }
- }
-
- def clear {
- topicMetadataMap.clear
- }
-
- /**
- * Helper method to check if a topic's metadata has a bad errorCode, or if a
- * partition's metadata has a bad errorCode.
- */
- def hasBadErrorCode(streamMetadata: TopicMetadata) = {
- KafkaUtil.isBadErrorCode(streamMetadata.error.code()) || streamMetadata.partitionsMetadata.exists(partitionMetadata => KafkaUtil.isBadErrorCode(partitionMetadata.error.code()))
- }
-}
diff --git a/samza-kafka/src/main/scala/org/apache/samza/system/kafka_deprecated/BrokerProxy.scala b/samza-kafka/src/main/scala/org/apache/samza/system/kafka_deprecated/BrokerProxy.scala
deleted file mode 100644
index a39752b..0000000
--- a/samza-kafka/src/main/scala/org/apache/samza/system/kafka_deprecated/BrokerProxy.scala
+++ /dev/null
@@ -1,332 +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.samza.system.kafka_deprecated
-
-import java.lang.Thread.UncaughtExceptionHandler
-import java.nio.channels.ClosedByInterruptException
-import java.util.concurrent.{ConcurrentHashMap, CountDownLatch}
-
-import kafka.api._
-import kafka.common.{ErrorMapping, NotLeaderForPartitionException, TopicAndPartition, UnknownTopicOrPartitionException}
-import kafka.consumer.ConsumerConfig
-import kafka.message.MessageSet
-import org.apache.samza.SamzaException
-import org.apache.samza.util.ExponentialSleepStrategy
-import org.apache.samza.util.KafkaUtil
-import org.apache.samza.util.Logging
-
-import scala.collection.JavaConverters._
-import scala.collection.concurrent
-
-/**
- * A BrokerProxy consolidates Kafka fetches meant for a particular broker and retrieves them all at once, providing
- * a way for consumers to retrieve those messages by topic and partition.
- */
-class BrokerProxy(
- val host: String,
- val port: Int,
- val system: String,
- val clientID: String,
- val metrics: KafkaSystemConsumerMetrics,
- val messageSink: MessageSink,
- val timeout: Int = ConsumerConfig.SocketTimeout,
- val bufferSize: Int = ConsumerConfig.SocketBufferSize,
- val fetchSize: StreamFetchSizes = new StreamFetchSizes,
- val consumerMinSize:Int = ConsumerConfig.MinFetchBytes,
- val consumerMaxWait:Int = ConsumerConfig.MaxFetchWaitMs,
- offsetGetter: GetOffset = new GetOffset("fail")) extends Toss with Logging {
-
- /**
- * How long should the fetcher thread sleep before checking if any TopicPartitions has been added to its purview
- */
- val sleepMSWhileNoTopicPartitions = 100
-
- /** What's the next offset for a particular partition? **/
- val nextOffsets:concurrent.Map[TopicAndPartition, Long] = new ConcurrentHashMap[TopicAndPartition, Long]().asScala
-
- /** Block on the first call to get message if the fetcher has not yet returned its initial results **/
- // TODO: It should be sufficient to just use the count down latch and await on it for each of the calls, but
- // VisualVM was showing the consumer thread spending all its time in the await method rather than returning
- // immediately, even though the process was proceeding normally. Hence the extra boolean. Should be investigated.
- val firstCallBarrier = new CountDownLatch(1)
- var firstCall = true
-
- var simpleConsumer = createSimpleConsumer()
-
- metrics.registerBrokerProxy(host, port)
-
- def createSimpleConsumer() = {
- val hostString = "%s:%d" format (host, port)
- info("Creating new SimpleConsumer for host %s for system %s" format (hostString, system))
-
- val sc = new DefaultFetchSimpleConsumer(host, port, timeout, bufferSize, clientID, fetchSize, consumerMinSize, consumerMaxWait)
- sc
- }
-
- def addTopicPartition(tp: TopicAndPartition, nextOffset: Option[String]) = {
- debug("Adding new topic and partition %s to queue for %s" format (tp, host))
-
- if (nextOffsets.asJava.containsKey(tp)) {
- toss("Already consuming TopicPartition %s" format tp)
- }
-
- val offset = if (nextOffset.isDefined && offsetGetter.isValidOffset(simpleConsumer, tp, nextOffset.get)) {
- nextOffset
- .get
- .toLong
- } else {
- warn("It appears that we received an invalid or empty offset %s for %s. Attempting to use Kafka's auto.offset.reset setting. This can result in data loss if processing continues." format (nextOffset, tp))
-
- offsetGetter.getResetOffset(simpleConsumer, tp)
- }
-
- debug("Got offset %s for new topic and partition %s." format (offset, tp))
-
- nextOffsets += tp -> offset
-
- metrics.topicPartitions.get((host, port)).set(nextOffsets.size)
- }
-
- def removeTopicPartition(tp: TopicAndPartition) = {
- if (nextOffsets.asJava.containsKey(tp)) {
- val offset = nextOffsets.remove(tp)
- metrics.topicPartitions.get((host, port)).set(nextOffsets.size)
- debug("Removed %s" format tp)
- offset
- } else {
- warn("Asked to remove topic and partition %s, but not in map (keys = %s)" format (tp, nextOffsets.keys.mkString(",")))
- None
- }
- }
-
- val thread = new Thread(new Runnable {
- def run {
- var reconnect = false
-
- try {
- (new ExponentialSleepStrategy).run(
- loop => {
- if (reconnect) {
- metrics.reconnects.get((host, port)).inc
- simpleConsumer.close()
- simpleConsumer = createSimpleConsumer()
- }
-
- while (!Thread.currentThread.isInterrupted) {
- messageSink.refreshDropped
- if (nextOffsets.size == 0) {
- debug("No TopicPartitions to fetch. Sleeping.")
- Thread.sleep(sleepMSWhileNoTopicPartitions)
- } else {
- fetchMessages
-
- // If we got here, fetchMessages didn't throw an exception, i.e. it was successful.
- // In that case, reset the loop delay, so that the next time an error occurs,
- // we start with a short retry delay.
- loop.reset
- }
- }
- },
-
- (exception, loop) => {
- warn("Restarting consumer due to %s. Releasing ownership of all partitions, and restarting consumer. Turn on debugging to get a full stack trace." format exception)
- debug("Exception detail:", exception)
- abdicateAll
- reconnect = true
- })
- } catch {
- case e: InterruptedException => info("Got interrupt exception in broker proxy thread.")
- case e: ClosedByInterruptException => info("Got closed by interrupt exception in broker proxy thread.")
- case e: OutOfMemoryError => throw new SamzaException("Got out of memory error in broker proxy thread.")
- case e: StackOverflowError => throw new SamzaException("Got stack overflow error in broker proxy thread.")
- }
-
- if (Thread.currentThread.isInterrupted) info("Shutting down due to interrupt.")
- }
- }, "BrokerProxy thread pointed at %s:%d for client %s" format (host, port, clientID))
-
- private def fetchMessages(): Unit = {
- val topicAndPartitionsToFetch = nextOffsets.filterKeys(messageSink.needsMoreMessages(_)).toList
-
- if (topicAndPartitionsToFetch.size > 0) {
- metrics.brokerReads.get((host, port)).inc
- val response: FetchResponse = simpleConsumer.defaultFetch(topicAndPartitionsToFetch: _*)
- firstCall = false
- firstCallBarrier.countDown()
-
- // Split response into errors and non errors, processing the errors first
- val (nonErrorResponses, errorResponses) = response.data.toSet.partition(_._2.error.code() == ErrorMapping.NoError)
-
- handleErrors(errorResponses, response)
-
- nonErrorResponses.foreach { case (tp, data) => moveMessagesToTheirQueue(tp, data) }
- } else {
- refreshLatencyMetrics
-
- debug("No topic/partitions need to be fetched for %s:%s right now. Sleeping %sms." format (host, port, sleepMSWhileNoTopicPartitions))
-
- metrics.brokerSkippedFetchRequests.get((host, port)).inc
-
- Thread.sleep(sleepMSWhileNoTopicPartitions)
- }
- }
-
- /**
- * Releases ownership for a single TopicAndPartition. The
- * KafkaSystemConsumer will try and find a new broker for the
- * TopicAndPartition.
- */
- def abdicate(tp: TopicAndPartition) = removeTopicPartition(tp) match {
- // Need to be mindful of a tp that was removed by another thread
- case Some(offset) => messageSink.abdicate(tp, offset)
- case None => warn("Tried to abdicate for topic partition not in map. Removed in interim?")
- }
-
- /**
- * Releases all TopicAndPartition ownership for this BrokerProxy thread. The
- * KafkaSystemConsumer will try and find a new broker for the
- * TopicAndPartition.
- */
- def abdicateAll {
- info("Abdicating all topic partitions.")
- val immutableNextOffsetsCopy = nextOffsets.toMap
- immutableNextOffsetsCopy.keySet.foreach(abdicate(_))
- }
-
- def handleErrors(errorResponses: Set[(TopicAndPartition, FetchResponsePartitionData)], response: FetchResponse) = {
- // FetchResponse should really return Option and a list of the errors so we don't have to find them ourselves
- case class Error(tp: TopicAndPartition, code: Short, exception: Exception)
-
- // Now subdivide the errors into three types: non-recoverable, not leader (== abdicate) and offset out of range (== get new offset)
-
- // Convert FetchResponse into easier-to-work-with Errors
- val errors = for (
- (topicAndPartition, responseData) <- errorResponses;
- error <- Option(response.error(topicAndPartition.topic, topicAndPartition.partition)) // Scala's being cranky about referring to error.getKey values...
- ) yield new Error(topicAndPartition, error.code(), error.exception())
-
- val (notLeaderOrUnknownTopic, otherErrors) = errors.partition { case (e) => e.code == ErrorMapping.NotLeaderForPartitionCode || e.code == ErrorMapping.UnknownTopicOrPartitionCode }
- val (offsetOutOfRangeErrors, remainingErrors) = otherErrors.partition(_.code == ErrorMapping.OffsetOutOfRangeCode)
-
- // Can recover from two types of errors: not leader (go find the new leader) and offset out of range (go get the new offset)
- // However, we want to bail as quickly as possible if there are non recoverable errors so that the state of the other
- // topic-partitions remains the same. That way, when we've rebuilt the simple consumer, we can come around and
- // handle the recoverable errors.
- remainingErrors.foreach(e => {
- warn("Got non-recoverable error codes during multifetch. Throwing an exception to trigger reconnect. Errors: %s" format remainingErrors.mkString(","))
- KafkaUtil.maybeThrowException(e.exception) })
-
- notLeaderOrUnknownTopic.foreach(e => {
- warn("Received (UnknownTopicOr|NotLeaderFor)Partition exception %s for %s. Abdicating" format(e.code, e.tp))
- abdicate(e.tp)
- })
-
- offsetOutOfRangeErrors.foreach(e => {
- warn("Received OffsetOutOfRange exception for %s. Current offset = %s" format (e.tp, nextOffsets.getOrElse(e.tp, "not found in map, likely removed in the interim")))
-
- try {
- val newOffset = offsetGetter.getResetOffset(simpleConsumer, e.tp)
- // Put the new offset into the map (if the tp still exists). Will catch it on the next go-around
- nextOffsets.replace(e.tp, newOffset)
- } catch {
- // UnknownTopic or NotLeader are routine events and handled via abdication. All others, bail.
- case _ @ (_:UnknownTopicOrPartitionException | _: NotLeaderForPartitionException) => warn("Received (UnknownTopicOr|NotLeaderFor)Partition exception %s for %s. Abdicating" format(e.code, e.tp))
- abdicate(e.tp)
- }
- })
- }
-
- def moveMessagesToTheirQueue(tp: TopicAndPartition, data: FetchResponsePartitionData) = {
- val messageSet: MessageSet = data.messages
- var nextOffset = nextOffsets(tp)
-
- messageSink.setIsAtHighWatermark(tp, data.hw == 0 || data.hw == nextOffset)
- require(messageSet != null)
- for (message <- messageSet.iterator) {
- messageSink.addMessage(tp, message, data.hw) // TODO: Verify this is correct
-
- nextOffset = message.nextOffset
-
- val bytesSize = message.message.payloadSize + message.message.keySize
- metrics.reads.get(tp).inc
- metrics.bytesRead.get(tp).inc(bytesSize)
- metrics.brokerBytesRead.get((host, port)).inc(bytesSize)
- metrics.offsets.get(tp).set(nextOffset)
- }
-
- nextOffsets.replace(tp, nextOffset) // use replace rather than put in case this tp was removed while we were fetching.
-
- // Update high water mark
- val hw = data.hw
- if (hw >= 0) {
- metrics.highWatermark.get(tp).set(hw)
- metrics.lag.get(tp).set(hw - nextOffset)
- } else {
- debug("Got a high water mark less than 0 (%d) for %s, so skipping." format (hw, tp))
- }
- }
- override def toString() = "BrokerProxy for %s:%d" format (host, port)
-
- def start {
- if (!thread.isAlive) {
- info("Starting " + toString)
- thread.setDaemon(true)
- thread.setName("Samza BrokerProxy " + thread.getName)
- thread.setUncaughtExceptionHandler(new UncaughtExceptionHandler {
- override def uncaughtException(t: Thread, e: Throwable) = error("Uncaught exception in broker proxy:", e)
- })
- thread.start
- } else {
- debug("Tried to start an already started broker proxy (%s). Ignoring." format toString)
- }
- }
-
- def stop {
- info("Shutting down " + toString)
-
- if (simpleConsumer != null) {
- info("closing simple consumer...")
- simpleConsumer.close
- }
-
- thread.interrupt
- thread.join
- }
-
- private def refreshLatencyMetrics {
- nextOffsets.foreach{
- case (topicAndPartition, offset) => {
- val latestOffset = simpleConsumer.earliestOrLatestOffset(topicAndPartition, -1, Request.OrdinaryConsumerId)
- trace("latest offset of %s is %s" format (topicAndPartition, latestOffset))
- if (latestOffset >= 0) {
- // only update the registered topicAndpartitions
- if(metrics.highWatermark.containsKey(topicAndPartition)) {
- metrics.highWatermark.get(topicAndPartition).set(latestOffset)
- }
- if(metrics.lag.containsKey(topicAndPartition)) {
- metrics.lag.get(topicAndPartition).set(latestOffset - offset)
- }
- }
- }
- }
- }
-}
diff --git a/samza-kafka/src/main/scala/org/apache/samza/system/kafka_deprecated/DefaultFetchSimpleConsumer.scala b/samza-kafka/src/main/scala/org/apache/samza/system/kafka_deprecated/DefaultFetchSimpleConsumer.scala
deleted file mode 100644
index 5f79ea5..0000000
--- a/samza-kafka/src/main/scala/org/apache/samza/system/kafka_deprecated/DefaultFetchSimpleConsumer.scala
+++ /dev/null
@@ -1,66 +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.samza.system.kafka_deprecated
-
-import kafka.consumer.SimpleConsumer
-import kafka.api._
-import kafka.common.TopicAndPartition
-import kafka.consumer.ConsumerConfig
-
-class DefaultFetchSimpleConsumer(host: scala.Predef.String, port: scala.Int, soTimeout: scala.Int, bufferSize: scala.Int,
- clientId: scala.Predef.String, fetchSize: StreamFetchSizes = new StreamFetchSizes,
- minBytes: Int = ConsumerConfig.MinFetchBytes, maxWait: Int = ConsumerConfig.MaxFetchWaitMs)
- extends SimpleConsumer(host, port, soTimeout, bufferSize, clientId) {
-
- def defaultFetch(fetches: (TopicAndPartition, Long)*) = {
- val fbr = new FetchRequestBuilder().maxWait(maxWait)
- .minBytes(minBytes)
- .clientId(clientId)
-
- fetches.foreach(f => fbr.addFetch(f._1.topic, f._1.partition, f._2, fetchSize.streamValue.getOrElse(f._1.topic, fetchSize.defaultValue)))
-
- this.fetch(fbr.build())
- }
-
- override def close(): Unit = super.close()
-
- override def send(request: TopicMetadataRequest): TopicMetadataResponse = super.send(request)
-
- override def fetch(request: FetchRequest): FetchResponse = super.fetch(request)
-
- override def getOffsetsBefore(request: OffsetRequest): OffsetResponse = super.getOffsetsBefore(request)
-
- override def commitOffsets(request: OffsetCommitRequest): OffsetCommitResponse = super.commitOffsets(request)
-
- override def fetchOffsets(request: OffsetFetchRequest): OffsetFetchResponse = super.fetchOffsets(request)
-
- override def earliestOrLatestOffset(topicAndPartition: TopicAndPartition, earliestOrLatest: Long, consumerId: Int): Long = super.earliestOrLatestOffset(topicAndPartition, earliestOrLatest, consumerId)
-}
-
-/**
- * a simple class for holding values for the stream's fetch size (fetch.message.max.bytes).
- * The stream-level fetch size values are put in the streamValue map streamName -> fetchSize.
- * If stream-level fetch size is not defined, use the default value. The default value is the
- * Kafka's default fetch size value or the system-level fetch size value (if defined).
- */
-case class StreamFetchSizes(defaultValue: Int = ConsumerConfig.MaxFetchSize, streamValue: Map[String, Int] = Map[String, Int]())
-
diff --git a/samza-kafka/src/main/scala/org/apache/samza/system/kafka_deprecated/GetOffset.scala b/samza-kafka/src/main/scala/org/apache/samza/system/kafka_deprecated/GetOffset.scala
deleted file mode 100644
index c4e7354..0000000
--- a/samza-kafka/src/main/scala/org/apache/samza/system/kafka_deprecated/GetOffset.scala
+++ /dev/null
@@ -1,116 +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.samza.system.kafka_deprecated
-
-import org.apache.kafka.common.errors.OffsetOutOfRangeException
-import kafka.api._
-import kafka.common.TopicAndPartition
-import kafka.api.PartitionOffsetRequestInfo
-import org.apache.samza.util.Logging
-import org.apache.samza.util.KafkaUtil
-
-/**
- * GetOffset validates offsets for topic partitions, and manages fetching new
- * offsets for topics using Kafka's auto.offset.reset configuration.
- */
-class GetOffset(
- /**
- * The default auto.offset.reset to use if a topic is not overridden in
- * autoOffsetResetTopics. Any value other than "earliest" or "latest" will
- * result in an exception when getRestOffset is called.
- */
- default: String,
-
- /**
- * Topic-level overrides for auto.offset.reset. Any value other than
- * "earliest" or "latest" will result in an exception when getRestOffset is
- * called.
- */
- autoOffsetResetTopics: Map[String, String] = Map()) extends Logging with Toss {
-
- /**
- * Checks if an offset is valid for a given topic/partition. Validity is
- * defined as an offset that returns a readable non-empty message set with
- * no exceptions.
- */
- def isValidOffset(consumer: DefaultFetchSimpleConsumer, topicAndPartition: TopicAndPartition, offset: String) = {
- info("Validating offset %s for topic and partition %s" format (offset, topicAndPartition))
-
- try {
- val messages = consumer.defaultFetch((topicAndPartition, offset.toLong))
-
- if (messages.hasError) {
- KafkaUtil.maybeThrowException(messages.error(topicAndPartition.topic, topicAndPartition.partition).exception())
- }
-
- info("Able to successfully read from offset %s for topic and partition %s. Using it to instantiate consumer." format (offset, topicAndPartition))
-
- true
- } catch {
- case e: OffsetOutOfRangeException => false
- }
- }
-
- /**
- * Uses a topic's auto.offset.reset setting (defined via the
- * autoOffsetResetTopics map in the constructor) to fetch either the
- * earliest or latest offset. If neither earliest or latest is defined for
- * the topic in question, the default supplied in the constructor will be
- * used.
- */
- def getResetOffset(consumer: DefaultFetchSimpleConsumer, topicAndPartition: TopicAndPartition) = {
- val offsetRequest = new OffsetRequest(Map(topicAndPartition -> new PartitionOffsetRequestInfo(getAutoOffset(topicAndPartition.topic), 1)))
- val offsetResponse = consumer.getOffsetsBefore(offsetRequest)
- val partitionOffsetResponse = offsetResponse
- .partitionErrorAndOffsets
- .get(topicAndPartition)
- .getOrElse(toss("Unable to find offset information for %s" format topicAndPartition))
-
- KafkaUtil.maybeThrowException(partitionOffsetResponse.error.exception())
-
- partitionOffsetResponse
- .offsets
- .headOption
- .getOrElse(toss("Got response, but no offsets defined for %s" format topicAndPartition))
- }
-
- /**
- * Returns either the earliest or latest setting (a Kafka constant) for a
- * given topic using the autoOffsetResetTopics map defined in the
- * constructor. If the topic is not defined in autoOffsetResetTopics, the
- * default value supplied in the constructor will be used. This is used in
- * conjunction with getResetOffset to fetch either the earliest or latest
- * offset for a topic.
- */
- private def getAutoOffset(topic: String): Long = {
- info("Checking if auto.offset.reset is defined for topic %s" format (topic))
- autoOffsetResetTopics.getOrElse(topic, default) match {
- case OffsetRequest.LargestTimeString =>
- info("Got reset of type %s." format OffsetRequest.LargestTimeString)
- OffsetRequest.LatestTime
- case OffsetRequest.SmallestTimeString =>
- info("Got reset of type %s." format OffsetRequest.SmallestTimeString)
- OffsetRequest.EarliestTime
- case other => toss("Can't get offset value for topic %s due to invalid value: %s" format (topic, other))
- }
- }
-}
diff --git a/samza-kafka/src/main/scala/org/apache/samza/system/kafka_deprecated/KafkaSystemAdmin.scala b/samza-kafka/src/main/scala/org/apache/samza/system/kafka_deprecated/KafkaSystemAdmin.scala
deleted file mode 100644
index 36c819f..0000000
--- a/samza-kafka/src/main/scala/org/apache/samza/system/kafka_deprecated/KafkaSystemAdmin.scala
+++ /dev/null
@@ -1,548 +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.samza.system.kafka_deprecated
-
-import java.util
-import java.util.{Properties, UUID}
-
-import com.google.common.annotations.VisibleForTesting
-import kafka.admin.{AdminClient, AdminUtils}
-import kafka.api._
-import kafka.common.TopicAndPartition
-import kafka.consumer.{ConsumerConfig, SimpleConsumer}
-import kafka.utils.ZkUtils
-import org.apache.kafka.clients.CommonClientConfigs
-import org.apache.kafka.common.errors.TopicExistsException
-import org.apache.kafka.common.TopicPartition
-import org.apache.samza.system.SystemStreamMetadata.SystemStreamPartitionMetadata
-import org.apache.samza.system._
-import org.apache.samza.system.kafka.KafkaStreamSpec
-import org.apache.samza.util.{ClientUtilTopicMetadataStore, ExponentialSleepStrategy, KafkaUtil, Logging}
-import org.apache.samza.{Partition, SamzaException}
-
-import scala.collection.JavaConverters._
-
-
-object KafkaSystemAdmin extends Logging {
-
- @VisibleForTesting @volatile var deleteMessagesCalled = false
- val CLEAR_STREAM_RETRIES = 3
-
- /**
- * A helper method that takes oldest, newest, and upcoming offsets for each
- * system stream partition, and creates a single map from stream name to
- * SystemStreamMetadata.
- */
- def assembleMetadata(oldestOffsets: Map[SystemStreamPartition, String], newestOffsets: Map[SystemStreamPartition, String], upcomingOffsets: Map[SystemStreamPartition, String]): Map[String, SystemStreamMetadata] = {
- val allMetadata = (oldestOffsets.keySet ++ newestOffsets.keySet ++ upcomingOffsets.keySet)
- .groupBy(_.getStream)
- .map {
- case (streamName, systemStreamPartitions) =>
- val streamPartitionMetadata = systemStreamPartitions
- .map(systemStreamPartition => {
- val partitionMetadata = new SystemStreamPartitionMetadata(
- // If the topic/partition is empty then oldest and newest will
- // be stripped of their offsets, so default to null.
- oldestOffsets.getOrElse(systemStreamPartition, null),
- newestOffsets.getOrElse(systemStreamPartition, null),
- upcomingOffsets(systemStreamPartition))
- (systemStreamPartition.getPartition, partitionMetadata)
- })
- .toMap
- val streamMetadata = new SystemStreamMetadata(streamName, streamPartitionMetadata.asJava)
- (streamName, streamMetadata)
- }
- .toMap
-
- // This is typically printed downstream and it can be spammy, so debug level here.
- debug("Got metadata: %s" format allMetadata)
-
- allMetadata
- }
-}
-
-/**
- * A helper class that is used to construct the changelog stream specific information
- *
- * @param replicationFactor The number of replicas for the changelog stream
- * @param kafkaProps The kafka specific properties that need to be used for changelog stream creation
- */
-case class ChangelogInfo(var replicationFactor: Int, var kafkaProps: Properties)
-
-/**
- * A Kafka-based implementation of SystemAdmin.
- */
-class KafkaSystemAdmin(
- /**
- * The system name to use when creating SystemStreamPartitions to return in
- * the getSystemStreamMetadata responser.
- */
- systemName: String,
-
- // TODO whenever Kafka decides to make the Set[Broker] class public, let's switch to Set[Broker] here.
- /**
- * List of brokers that are part of the Kafka system that we wish to
- * interact with. The format is host1:port1,host2:port2.
- */
- brokerListString: String,
-
- /**
- * A method that returns a ZkUtils for the Kafka system. This is invoked
- * when the system admin is attempting to create a coordinator stream.
- */
- connectZk: () => ZkUtils,
-
- /**
- * Custom properties to use when the system admin tries to create a new
- * coordinator stream.
- */
- coordinatorStreamProperties: Properties = new Properties,
-
- /**
- * The replication factor to use when the system admin creates a new
- * coordinator stream.
- */
- coordinatorStreamReplicationFactor: Int = 1,
-
- /**
- * The timeout to use for the simple consumer when fetching metadata from
- * Kafka. Equivalent to Kafka's socket.timeout.ms configuration.
- */
- timeout: Int = Int.MaxValue,
-
- /**
- * The buffer size to use for the simple consumer when fetching metadata
- * from Kafka. Equivalent to Kafka's socket.receive.buffer.bytes
- * configuration.
- */
- bufferSize: Int = ConsumerConfig.SocketBufferSize,
-
- /**
- * The client ID to use for the simple consumer when fetching metadata from
- * Kafka. Equivalent to Kafka's client.id configuration.
- */
- clientId: String = UUID.randomUUID.toString,
-
- /**
- * Replication factor for the Changelog topic in kafka
- * Kafka properties to be used during the Changelog topic creation
- */
- topicMetaInformation: Map[String, ChangelogInfo] = Map[String, ChangelogInfo](),
-
- /**
- * Kafka properties to be used during the intermediate topic creation
- */
- intermediateStreamProperties: Map[String, Properties] = Map(),
-
- /**
- * Whether deleteMessages() API can be used
- */
- deleteCommittedMessages: Boolean = false) extends SystemAdmin with Logging {
-
- import KafkaSystemAdmin._
-
- @volatile var running = false
- @volatile var adminClient: AdminClient = null
-
- override def start() = {
- if (!running) {
- running = true
- adminClient = createAdminClient()
- }
- }
-
- override def stop() = {
- if (running) {
- running = false
- adminClient.close()
- adminClient = null
- }
- }
-
- private def createAdminClient(): AdminClient = {
- val props = new Properties()
- props.put(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, brokerListString)
- AdminClient.create(props)
- }
-
- override def getSystemStreamPartitionCounts(streams: util.Set[String], cacheTTL: Long): util.Map[String, SystemStreamMetadata] = {
- getSystemStreamPartitionCounts(streams, new ExponentialSleepStrategy(initialDelayMs = 500), cacheTTL)
- }
-
- def getSystemStreamPartitionCounts(streams: util.Set[String], retryBackoff: ExponentialSleepStrategy, cacheTTL: Long = Long.MaxValue): util.Map[String, SystemStreamMetadata] = {
- debug("Fetching system stream partition count for: %s" format streams)
- var metadataTTL = cacheTTL
- retryBackoff.run(
- loop => {
- val metadata = TopicMetadataCache.getTopicMetadata(
- streams.asScala.toSet,
- systemName,
- getTopicMetadata,
- metadataTTL)
- val result = metadata.map {
- case (topic, topicMetadata) => {
- KafkaUtil.maybeThrowException(topicMetadata.error.exception())
- val partitionsMap = topicMetadata.partitionsMetadata.map {
- pm =>
- new Partition(pm.partitionId) -> new SystemStreamPartitionMetadata("", "", "")
- }.toMap[Partition, SystemStreamPartitionMetadata]
- (topic -> new SystemStreamMetadata(topic, partitionsMap.asJava))
- }
- }
- loop.done
- result.asJava
- },
-
- (exception, loop) => {
- warn("Unable to fetch last offsets for streams %s due to %s. Retrying." format (streams, exception))
- debug("Exception detail:", exception)
- if (metadataTTL == Long.MaxValue) {
- metadataTTL = 5000 // Revert to the default cache expiration
- }
- }
- ).getOrElse(throw new SamzaException("Failed to get system stream metadata"))
- }
-
- /**
- * Returns the offset for the message after the specified offset for each
- * SystemStreamPartition that was passed in.
- */
-
- override def getOffsetsAfter(offsets: java.util.Map[SystemStreamPartition, String]) = {
- // This is safe to do with Kafka, even if a topic is key-deduped. If the
- // offset doesn't exist on a compacted topic, Kafka will return the first
- // message AFTER the offset that was specified in the fetch request.
- offsets.asScala.mapValues(offset => (offset.toLong + 1).toString).asJava
- }
-
- override def getSystemStreamMetadata(streams: java.util.Set[String]) =
- getSystemStreamMetadata(streams, new ExponentialSleepStrategy(initialDelayMs = 500)).asJava
-
- /**
- * Given a set of stream names (topics), fetch metadata from Kafka for each
- * stream, and return a map from stream name to SystemStreamMetadata for
- * each stream. This method will return null for oldest and newest offsets
- * if a given SystemStreamPartition is empty. This method will block and
- * retry indefinitely until it gets a successful response from Kafka.
- */
- def getSystemStreamMetadata(streams: java.util.Set[String], retryBackoff: ExponentialSleepStrategy) = {
- debug("Fetching system stream metadata for: %s" format streams)
- var metadataTTL = Long.MaxValue // Trust the cache until we get an exception
- retryBackoff.run(
- loop => {
- val metadata = TopicMetadataCache.getTopicMetadata(
- streams.asScala.toSet,
- systemName,
- getTopicMetadata,
- metadataTTL)
-
- debug("Got metadata for streams: %s" format metadata)
-
- val brokersToTopicPartitions = getTopicsAndPartitionsByBroker(metadata)
- var oldestOffsets = Map[SystemStreamPartition, String]()
- var newestOffsets = Map[SystemStreamPartition, String]()
- var upcomingOffsets = Map[SystemStreamPartition, String]()
-
- // Get oldest, newest, and upcoming offsets for each topic and partition.
- for ((broker, topicsAndPartitions) <- brokersToTopicPartitions) {
- debug("Fetching offsets for %s:%s: %s" format (broker.host, broker.port, topicsAndPartitions))
-
- val consumer = new SimpleConsumer(broker.host, broker.port, timeout, bufferSize, clientId)
- try {
- upcomingOffsets ++= getOffsets(consumer, topicsAndPartitions, OffsetRequest.LatestTime)
- oldestOffsets ++= getOffsets(consumer, topicsAndPartitions, OffsetRequest.EarliestTime)
-
- // Kafka's "latest" offset is always last message in stream's offset +
- // 1, so get newest message in stream by subtracting one. this is safe
- // even for key-deduplicated streams, since the last message will
- // never be deduplicated.
- newestOffsets = upcomingOffsets.mapValues(offset => (offset.toLong - 1).toString)
- // Keep only oldest/newest offsets where there is a message. Should
- // return null offsets for empty streams.
- upcomingOffsets.foreach {
- case (topicAndPartition, offset) =>
- if (offset.toLong <= 0) {
- debug("Stripping newest offsets for %s because the topic appears empty." format topicAndPartition)
- newestOffsets -= topicAndPartition
- debug("Setting oldest offset to 0 to consume from beginning")
- oldestOffsets += (topicAndPartition -> "0")
- }
- }
- } finally {
- consumer.close
- }
- }
-
- val result = assembleMetadata(oldestOffsets, newestOffsets, upcomingOffsets)
- loop.done
- result
- },
-
- (exception, loop) => {
- warn("Unable to fetch last offsets for streams %s due to %s. Retrying." format (streams, exception))
- debug("Exception detail:", exception)
- metadataTTL = 5000 // Revert to the default cache expiration
- }).getOrElse(throw new SamzaException("Failed to get system stream metadata"))
- }
-
- /**
- * Helper method to use topic metadata cache when fetching metadata, so we
- * don't hammer Kafka more than we need to.
- */
- def getTopicMetadata(topics: Set[String]) = {
- new ClientUtilTopicMetadataStore(brokerListString, clientId, timeout)
- .getTopicInfo(topics)
- }
-
- /**
- * Break topic metadata topic/partitions into per-broker map so that we can
- * execute only one offset request per broker.
- */
- private def getTopicsAndPartitionsByBroker(metadata: Map[String, TopicMetadata]) = {
- val brokersToTopicPartitions = metadata
- .values
- // Convert the topic metadata to a Seq[(Broker, TopicAndPartition)]
- .flatMap(topicMetadata => {
- KafkaUtil.maybeThrowException(topicMetadata.error.exception())
- topicMetadata
- .partitionsMetadata
- // Convert Seq[PartitionMetadata] to Seq[(Broker, TopicAndPartition)]
- .map(partitionMetadata => {
- val topicAndPartition = new TopicAndPartition(topicMetadata.topic, partitionMetadata.partitionId)
- val leader = partitionMetadata
- .leader
- .getOrElse(throw new SamzaException("Need leaders for all partitions when fetching offsets. No leader available for TopicAndPartition: %s" format topicAndPartition))
- (leader, topicAndPartition)
- })
- })
-
- // Convert to a Map[Broker, Seq[(Broker, TopicAndPartition)]]
- .groupBy(_._1)
- // Convert to a Map[Broker, Set[TopicAndPartition]]
- .mapValues(_.map(_._2).toSet)
-
- debug("Got topic partition data for brokers: %s" format brokersToTopicPartitions)
-
- brokersToTopicPartitions
- }
-
- /**
- * Use a SimpleConsumer to fetch either the earliest or latest offset from
- * Kafka for each topic/partition in the topicsAndPartitions set. It is
- * assumed that all topics/partitions supplied reside on the broker that the
- * consumer is connected to.
- */
- private def getOffsets(consumer: SimpleConsumer, topicsAndPartitions: Set[TopicAndPartition], earliestOrLatest: Long) = {
- debug("Getting offsets for %s using earliest/latest value of %s." format (topicsAndPartitions, earliestOrLatest))
-
- var offsets = Map[SystemStreamPartition, String]()
- val partitionOffsetInfo = topicsAndPartitions
- .map(topicAndPartition => (topicAndPartition, PartitionOffsetRequestInfo(earliestOrLatest, 1)))
- .toMap
- val brokerOffsets = consumer
- .getOffsetsBefore(new OffsetRequest(partitionOffsetInfo))
- .partitionErrorAndOffsets
- .mapValues(partitionErrorAndOffset => {
- KafkaUtil.maybeThrowException(partitionErrorAndOffset.error.exception())
- partitionErrorAndOffset.offsets.head
- })
-
- for ((topicAndPartition, offset) <- brokerOffsets) {
- offsets += new SystemStreamPartition(systemName, topicAndPartition.topic, new Partition(topicAndPartition.partition)) -> offset.toString
- }
-
- debug("Got offsets for %s using earliest/latest value of %s: %s" format (topicsAndPartitions, earliestOrLatest, offsets))
-
- offsets
- }
-
- /**
- * @inheritdoc
- */
- override def createStream(spec: StreamSpec): Boolean = {
- info("Create topic %s in system %s" format (spec.getPhysicalName, systemName))
- val kSpec = toKafkaSpec(spec)
- var streamCreated = false
-
- new ExponentialSleepStrategy(initialDelayMs = 500).run(
- loop => {
- val zkClient = connectZk()
- try {
- AdminUtils.createTopic(
- zkClient,
- kSpec.getPhysicalName,
- kSpec.getPartitionCount,
- kSpec.getReplicationFactor,
- kSpec.getProperties)
- } finally {
- zkClient.close
- }
-
- streamCreated = true
- loop.done
- },
-
- (exception, loop) => {
- exception match {
- case e: TopicExistsException =>
- streamCreated = false
- loop.done
- case e: Exception =>
- warn("Failed to create topic %s: %s. Retrying." format (spec.getPhysicalName, e))
- debug("Exception detail:", e)
- }
- })
-
- streamCreated
- }
-
- /**
- * Converts a StreamSpec into a KafakStreamSpec. Special handling for coordinator and changelog stream.
- * @param spec a StreamSpec object
- * @return KafkaStreamSpec object
- */
- def toKafkaSpec(spec: StreamSpec): KafkaStreamSpec = {
- if (spec.isChangeLogStream) {
- val topicName = spec.getPhysicalName
- val topicMeta = topicMetaInformation.getOrElse(topicName, throw new StreamValidationException("Unable to find topic information for topic " + topicName))
- new KafkaStreamSpec(spec.getId, topicName, systemName, spec.getPartitionCount, topicMeta.replicationFactor,
- topicMeta.kafkaProps)
- } else if (spec.isCoordinatorStream){
- new KafkaStreamSpec(spec.getId, spec.getPhysicalName, systemName, 1, coordinatorStreamReplicationFactor,
- coordinatorStreamProperties)
- } else if (intermediateStreamProperties.contains(spec.getId)) {
- val kafkaSpec = KafkaStreamSpec.fromSpec(spec)
- val properties = kafkaSpec.getProperties
- properties.putAll(intermediateStreamProperties(spec.getId))
- kafkaSpec.copyWithProperties(properties)
- } else {
- KafkaStreamSpec.fromSpec(spec)
- }
- }
-
- /**
- * @inheritdoc
- *
- * Validates a stream in Kafka. Should not be called before createStream(),
- * since ClientUtils.fetchTopicMetadata(), used by different Kafka clients,
- * is not read-only and will auto-create a new topic.
- */
- override def validateStream(spec: StreamSpec): Unit = {
- val topicName = spec.getPhysicalName
- info("Validating topic %s." format topicName)
-
- val retryBackoff: ExponentialSleepStrategy = new ExponentialSleepStrategy
- var metadataTTL = Long.MaxValue // Trust the cache until we get an exception
- retryBackoff.run(
- loop => {
- val metadataStore = new ClientUtilTopicMetadataStore(brokerListString, clientId, timeout)
- val topicMetadataMap = TopicMetadataCache.getTopicMetadata(Set(topicName), systemName, metadataStore.getTopicInfo, metadataTTL)
- val topicMetadata = topicMetadataMap(topicName)
- KafkaUtil.maybeThrowException(topicMetadata.error.exception())
-
- val partitionCount = topicMetadata.partitionsMetadata.length
- if (partitionCount != spec.getPartitionCount) {
- throw new StreamValidationException("Topic validation failed for topic %s because partition count %s did not match expected partition count of %d" format (topicName, topicMetadata.partitionsMetadata.length, spec.getPartitionCount))
- }
-
- info("Successfully validated topic %s." format topicName)
- loop.done
- },
-
- (exception, loop) => {
- exception match {
- case e: StreamValidationException => throw e
- case e: Exception =>
- warn("While trying to validate topic %s: %s. Retrying." format (topicName, e))
- debug("Exception detail:", e)
- metadataTTL = 5000L // Revert to the default value
- }
- })
- }
-
- /**
- * @inheritdoc
- *
- * Delete a stream in Kafka. Deleting topics works only when the broker is configured with "delete.topic.enable=true".
- * Otherwise it's a no-op.
- */
- override def clearStream(spec: StreamSpec): Boolean = {
- info("Delete topic %s in system %s" format (spec.getPhysicalName, systemName))
- val kSpec = KafkaStreamSpec.fromSpec(spec)
- var retries = CLEAR_STREAM_RETRIES
- new ExponentialSleepStrategy().run(
- loop => {
- val zkClient = connectZk()
- try {
- AdminUtils.deleteTopic(
- zkClient,
- kSpec.getPhysicalName)
- } finally {
- zkClient.close
- }
-
- loop.done
- },
-
- (exception, loop) => {
- if (retries > 0) {
- warn("Exception while trying to delete topic %s: %s. Retrying." format (spec.getPhysicalName, exception))
- retries -= 1
- } else {
- warn("Fail to delete topic %s: %s" format (spec.getPhysicalName, exception))
- loop.done
- throw exception
- }
- })
-
- val topicMetadata = getTopicMetadata(Set(kSpec.getPhysicalName)).get(kSpec.getPhysicalName).get
- topicMetadata.partitionsMetadata.isEmpty
- }
-
- /**
- * @inheritdoc
- *
- * Delete records up to (and including) the provided ssp offsets for all system stream partitions specified in the map
- * This only works with Kafka cluster 0.11 or later. Otherwise it's a no-op.
- */
- override def deleteMessages(offsets: util.Map[SystemStreamPartition, String]) {
- if (!running) {
- throw new SamzaException(s"KafkaSystemAdmin has not started yet for system $systemName")
- }
- if (deleteCommittedMessages) {
- val nextOffsets = offsets.asScala.toSeq.map { case (systemStreamPartition, offset) =>
- (new TopicPartition(systemStreamPartition.getStream, systemStreamPartition.getPartition.getPartitionId), offset.toLong + 1)
- }.toMap
- adminClient.deleteRecordsBefore(nextOffsets)
- deleteMessagesCalled = true
- }
- }
-
- /**
- * Compare the two offsets. Returns x where x < 0 if offset1 < offset2;
- * x == 0 if offset1 == offset2; x > 0 if offset1 > offset2.
- *
- * Currently it's used in the context of the broadcast streams to detect
- * the mismatch between two streams when consuming the broadcast streams.
- */
- override def offsetComparator(offset1: String, offset2: String): Integer = {
- offset1.toLong compare offset2.toLong
- }
-}
diff --git a/samza-kafka/src/main/scala/org/apache/samza/system/kafka_deprecated/KafkaSystemConsumer.scala b/samza-kafka/src/main/scala/org/apache/samza/system/kafka_deprecated/KafkaSystemConsumer.scala
deleted file mode 100644
index 126765a..0000000
--- a/samza-kafka/src/main/scala/org/apache/samza/system/kafka_deprecated/KafkaSystemConsumer.scala
+++ /dev/null
@@ -1,311 +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.samza.system.kafka_deprecated
-
-import java.time.Instant
-import kafka.common.TopicAndPartition
-import org.apache.samza.util.Logging
-import kafka.message.Message
-import kafka.message.MessageAndOffset
-import org.apache.samza.Partition
-import org.apache.kafka.common.utils.Utils
-import org.apache.samza.util.Clock
-import kafka.serializer.DefaultDecoder
-import kafka.serializer.Decoder
-import org.apache.samza.util.BlockingEnvelopeMap
-import org.apache.samza.system.SystemStreamPartition
-import org.apache.samza.system.IncomingMessageEnvelope
-import kafka.consumer.ConsumerConfig
-import org.apache.samza.util.TopicMetadataStore
-import kafka.api.PartitionMetadata
-import kafka.api.TopicMetadata
-import org.apache.samza.util.ExponentialSleepStrategy
-import java.util.concurrent.ConcurrentHashMap
-import scala.collection.JavaConverters._
-import org.apache.samza.system.SystemAdmin
-
-object KafkaSystemConsumer {
-
- // Approximate additional shallow heap overhead per message in addition to the raw bytes
- // received from Kafka 4 + 64 + 4 + 4 + 4 = 80 bytes overhead.
- // As this overhead is a moving target, and not very large
- // compared to the message size its being ignore in the computation for now.
- val MESSAGE_SIZE_OVERHEAD = 4 + 64 + 4 + 4 + 4;
-
- def toTopicAndPartition(systemStreamPartition: SystemStreamPartition) = {
- val topic = systemStreamPartition.getStream
- val partitionId = systemStreamPartition.getPartition.getPartitionId
- TopicAndPartition(topic, partitionId)
- }
-}
-
-/**
- * Maintain a cache of BrokerProxies, returning the appropriate one for the
- * requested topic and partition.
- */
-private[kafka_deprecated] class KafkaSystemConsumer(
- systemName: String,
- systemAdmin: SystemAdmin,
- metrics: KafkaSystemConsumerMetrics,
- metadataStore: TopicMetadataStore,
- clientId: String,
- timeout: Int = ConsumerConfig.ConsumerTimeoutMs,
- bufferSize: Int = ConsumerConfig.SocketBufferSize,
- fetchSize: StreamFetchSizes = new StreamFetchSizes,
- consumerMinSize: Int = ConsumerConfig.MinFetchBytes,
- consumerMaxWait: Int = ConsumerConfig.MaxFetchWaitMs,
-
- /**
- * Defines a low water mark for how many messages we buffer before we start
- * executing fetch requests against brokers to get more messages. This value
- * is divided equally among all registered SystemStreamPartitions. For
- * example, if fetchThreshold is set to 50000, and there are 50
- * SystemStreamPartitions registered, then the per-partition threshold is
- * 1000. As soon as a SystemStreamPartition's buffered message count drops
- * below 1000, a fetch request will be executed to get more data for it.
- *
- * Increasing this parameter will decrease the latency between when a queue
- * is drained of messages and when new messages are enqueued, but also leads
- * to an increase in memory usage since more messages will be held in memory.
- */
- fetchThreshold: Int = 50000,
- /**
- * Defines a low water mark for how many bytes we buffer before we start
- * executing fetch requests against brokers to get more messages. This
- * value is divided by 2 because the messages are buffered twice, once in
- * KafkaConsumer and then in SystemConsumers. This value
- * is divided equally among all registered SystemStreamPartitions.
- * However this is a soft limit per partition, as the
- * bytes are cached at the message boundaries, and the actual usage can be
- * 1000 bytes + size of max message in the partition for a given stream.
- * The bytes if the size of the bytebuffer in Message. Hence, the
- * Object overhead is not taken into consideration. In this codebase
- * it seems to be quite small. Hence, even for 500000 messages this is around 4MB x 2 = 8MB,
- * which is not considerable.
- *
- * For example,
- * if fetchThresholdBytes is set to 100000 bytes, and there are 50
- * SystemStreamPartitions registered, then the per-partition threshold is
- * (100000 / 2) / 50 = 1000 bytes.
- * As this is a soft limit, the actual usage can be 1000 bytes + size of max message.
- * As soon as a SystemStreamPartition's buffered messages bytes drops
- * below 1000, a fetch request will be executed to get more data for it.
- *
- * Increasing this parameter will decrease the latency between when a queue
- * is drained of messages and when new messages are enqueued, but also leads
- * to an increase in memory usage since more messages will be held in memory.
- *
- * The default value is -1, which means this is not used. When the value
- * is > 0, then the fetchThreshold which is count based is ignored.
- */
- fetchThresholdBytes: Long = -1,
- /**
- * if(fetchThresholdBytes > 0) true else false
- */
- fetchLimitByBytesEnabled: Boolean = false,
- offsetGetter: GetOffset = new GetOffset("fail"),
- deserializer: Decoder[Object] = new DefaultDecoder().asInstanceOf[Decoder[Object]],
- keyDeserializer: Decoder[Object] = new DefaultDecoder().asInstanceOf[Decoder[Object]],
- retryBackoff: ExponentialSleepStrategy = new ExponentialSleepStrategy,
- clock: () => Long = { System.currentTimeMillis }) extends BlockingEnvelopeMap(
- metrics.registry,
- new Clock {
- def currentTimeMillis = clock()
- },
- classOf[KafkaSystemConsumerMetrics].getName) with Toss with Logging {
-
- type HostPort = (String, Int)
- val brokerProxies = scala.collection.mutable.Map[HostPort, BrokerProxy]()
- val topicPartitionsAndOffsets: scala.collection.concurrent.Map[TopicAndPartition, String] = new ConcurrentHashMap[TopicAndPartition, String]().asScala
- var perPartitionFetchThreshold = fetchThreshold
- var perPartitionFetchThresholdBytes = 0L
-
- def start() {
- if (topicPartitionsAndOffsets.size > 0) {
- perPartitionFetchThreshold = fetchThreshold / topicPartitionsAndOffsets.size
- // messages get double buffered, hence divide by 2
- if(fetchLimitByBytesEnabled) {
- perPartitionFetchThresholdBytes = (fetchThresholdBytes / 2) / topicPartitionsAndOffsets.size
- }
- }
-
- systemAdmin.start()
- refreshBrokers
- }
-
- override def register(systemStreamPartition: SystemStreamPartition, offset: String) {
- super.register(systemStreamPartition, offset)
-
- val topicAndPartition = KafkaSystemConsumer.toTopicAndPartition(systemStreamPartition)
- val existingOffset = topicPartitionsAndOffsets.getOrElseUpdate(topicAndPartition, offset)
- // register the older offset in the consumer
- if (systemAdmin.offsetComparator(existingOffset, offset) >= 0) {
- topicPartitionsAndOffsets.replace(topicAndPartition, offset)
- }
-
- metrics.registerTopicAndPartition(KafkaSystemConsumer.toTopicAndPartition(systemStreamPartition))
- }
-
- def stop() {
- systemAdmin.stop()
- brokerProxies.values.foreach(_.stop)
- }
-
- protected def createBrokerProxy(host: String, port: Int): BrokerProxy = {
- info("Creating new broker proxy for host: %s and port: %s" format(host, port))
- new BrokerProxy(host, port, systemName, clientId, metrics, sink, timeout, bufferSize, fetchSize, consumerMinSize, consumerMaxWait, offsetGetter)
- }
-
- protected def getPartitionMetadata(topicMetadata: TopicMetadata, partition: Int): Option[PartitionMetadata] = {
- topicMetadata.partitionsMetadata.find(_.partitionId == partition)
- }
-
- protected def getLeaderHostPort(partitionMetadata: Option[PartitionMetadata]): Option[(String, Int)] = {
- // Whatever we do, we can't say Broker, even though we're
- // manipulating it here. Broker is a private type and Scala doesn't seem
- // to care about that as long as you don't explicitly declare its type.
- val brokerOption = partitionMetadata.flatMap(_.leader)
-
- brokerOption match {
- case Some(broker) => Some(broker.host, broker.port)
- case _ => None
- }
- }
-
- def refreshBrokers {
- var tpToRefresh = topicPartitionsAndOffsets.keySet.toList
- info("Refreshing brokers for: %s" format topicPartitionsAndOffsets)
- retryBackoff.run(
- loop => {
- val topics = tpToRefresh.map(_.topic).toSet
- val topicMetadata = TopicMetadataCache.getTopicMetadata(topics, systemName, (topics: Set[String]) => metadataStore.getTopicInfo(topics))
-
- // addTopicPartition one at a time, leaving the to-be-done list intact in case of exceptions.
- // This avoids trying to re-add the same topic partition repeatedly
- def refresh() = {
- val head = tpToRefresh.head
- // refreshBrokers can be called from abdicate and refreshDropped,
- // both of which are triggered from BrokerProxy threads. To prevent
- // accidentally creating multiple objects for the same broker, or
- // accidentally not updating the topicPartitionsAndOffsets variable,
- // we need to lock.
- this.synchronized {
- // Check if we still need this TopicAndPartition inside the
- // critical section. If we don't, then notAValidEvent it.
- topicPartitionsAndOffsets.get(head) match {
- case Some(nextOffset) =>
- val partitionMetadata = getPartitionMetadata(topicMetadata(head.topic), head.partition)
- getLeaderHostPort(partitionMetadata) match {
- case Some((host, port)) =>
- debug("Got partition metadata for %s: %s" format(head, partitionMetadata.get))
- val brokerProxy = brokerProxies.getOrElseUpdate((host, port), createBrokerProxy(host, port))
- brokerProxy.addTopicPartition(head, Option(nextOffset))
- brokerProxy.start
- debug("Claimed topic-partition (%s) for (%s)".format(head, brokerProxy))
- topicPartitionsAndOffsets -= head
- case None => info("No metadata available for: %s. Will try to refresh and add to a consumer thread later." format head)
- }
- case _ => debug("Ignoring refresh for %s because we already added it from another thread." format head)
- }
- }
- tpToRefresh.tail
- }
-
- while (!tpToRefresh.isEmpty) {
- tpToRefresh = refresh()
- }
-
- loop.done
- },
-
- (exception, loop) => {
- warn("While refreshing brokers for %s: %s. Retrying." format (tpToRefresh.head, exception))
- debug("Exception detail:", exception)
- })
- }
-
- val sink = new MessageSink {
- var lastDroppedRefresh = clock()
-
- def refreshDropped() {
- if (topicPartitionsAndOffsets.size > 0 && clock() - lastDroppedRefresh > 10000) {
- refreshBrokers
- lastDroppedRefresh = clock()
- }
- }
-
- def setIsAtHighWatermark(tp: TopicAndPartition, isAtHighWatermark: Boolean) {
- setIsAtHead(toSystemStreamPartition(tp), isAtHighWatermark)
- }
-
- def needsMoreMessages(tp: TopicAndPartition) = {
- if(fetchLimitByBytesEnabled) {
- getMessagesSizeInQueue(toSystemStreamPartition(tp)) < perPartitionFetchThresholdBytes
- } else {
- getNumMessagesInQueue(toSystemStreamPartition(tp)) < perPartitionFetchThreshold
- }
- }
-
- def getMessageSize(message: Message): Integer = {
- message.size + KafkaSystemConsumer.MESSAGE_SIZE_OVERHEAD
- }
-
- def addMessage(tp: TopicAndPartition, msg: MessageAndOffset, highWatermark: Long) = {
- trace("Incoming message %s: %s." format (tp, msg))
-
- val systemStreamPartition = toSystemStreamPartition(tp)
- val isAtHead = highWatermark == msg.offset
- val offset = msg.offset.toString
- val key = if (msg.message.key != null) {
- keyDeserializer.fromBytes(Utils.readBytes(msg.message.key))
- } else {
- null
- }
- val message = if (!msg.message.isNull) {
- deserializer.fromBytes(Utils.readBytes(msg.message.payload))
- } else {
- null
- }
-
- val eventTime = if (!msg.message.isNull) msg.message.timestamp else 0L
- val arrivalTime = Instant.now().toEpochMilli()
- val ime = if(fetchLimitByBytesEnabled ) {
- new IncomingMessageEnvelope(systemStreamPartition, offset, key, message, getMessageSize(msg.message),
- eventTime, arrivalTime)
- } else {
- new IncomingMessageEnvelope(systemStreamPartition, offset, key, message, 0,
- eventTime, arrivalTime)
- }
- put(systemStreamPartition, ime)
-
- setIsAtHead(systemStreamPartition, isAtHead)
- }
-
- def abdicate(tp: TopicAndPartition, nextOffset: Long) {
- info("Abdicating for %s" format (tp))
- topicPartitionsAndOffsets += tp -> nextOffset.toString
- refreshBrokers
- }
-
- private def toSystemStreamPartition(tp: TopicAndPartition) = {
- new SystemStreamPartition(systemName, tp.topic, new Partition(tp.partition))
- }
- }
-}
diff --git a/samza-kafka/src/main/scala/org/apache/samza/system/kafka_deprecated/KafkaSystemConsumerMetrics.scala b/samza-kafka/src/main/scala/org/apache/samza/system/kafka_deprecated/KafkaSystemConsumerMetrics.scala
deleted file mode 100644
index 08b1a0c..0000000
--- a/samza-kafka/src/main/scala/org/apache/samza/system/kafka_deprecated/KafkaSystemConsumerMetrics.scala
+++ /dev/null
@@ -1,100 +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.samza.system.kafka_deprecated
-
-import org.apache.samza.metrics.MetricsHelper
-import org.apache.samza.metrics.MetricsRegistryMap
-import org.apache.samza.metrics.MetricsRegistry
-import java.util.concurrent.ConcurrentHashMap
-import kafka.common.TopicAndPartition
-import org.apache.samza.metrics.Counter
-import org.apache.samza.metrics.Gauge
-
-class KafkaSystemConsumerMetrics(val systemName: String = "unknown", val registry: MetricsRegistry = new MetricsRegistryMap) extends MetricsHelper {
- val offsets = new ConcurrentHashMap[TopicAndPartition, Counter]
- val bytesRead = new ConcurrentHashMap[TopicAndPartition, Counter]
- val reads = new ConcurrentHashMap[TopicAndPartition, Counter]
- val lag = new ConcurrentHashMap[TopicAndPartition, Gauge[Long]]
- val highWatermark = new ConcurrentHashMap[TopicAndPartition, Gauge[Long]]
-
- /*
- * (String, Int) = (host, port) of BrokerProxy.
- */
-
- val reconnects = new ConcurrentHashMap[(String, Int), Counter]
- val brokerBytesRead = new ConcurrentHashMap[(String, Int), Counter]
- val brokerReads = new ConcurrentHashMap[(String, Int), Counter]
- val brokerSkippedFetchRequests = new ConcurrentHashMap[(String, Int), Counter]
- val topicPartitions = new ConcurrentHashMap[(String, Int), Gauge[Int]]
-
- def registerTopicAndPartition(tp: TopicAndPartition) = {
- if (!offsets.contains(tp)) {
- offsets.put(tp, newCounter("%s-%s-offset-change" format (tp.topic, tp.partition)))
- bytesRead.put(tp, newCounter("%s-%s-bytes-read" format (tp.topic, tp.partition)))
- reads.put(tp, newCounter("%s-%s-messages-read" format (tp.topic, tp.partition)))
- highWatermark.put(tp, newGauge("%s-%s-high-watermark" format (tp.topic, tp.partition), -1L))
- lag.put(tp, newGauge("%s-%s-messages-behind-high-watermark" format (tp.topic, tp.partition), 0L))
- }
- }
-
- def registerBrokerProxy(host: String, port: Int) {
- reconnects.put((host, port), newCounter("%s-%s-reconnects" format (host, port)))
- brokerBytesRead.put((host, port), newCounter("%s-%s-bytes-read" format (host, port)))
- brokerReads.put((host, port), newCounter("%s-%s-messages-read" format (host, port)))
- brokerSkippedFetchRequests.put((host, port), newCounter("%s-%s-skipped-fetch-requests" format (host, port)))
- topicPartitions.put((host, port), newGauge("%s-%s-topic-partitions" format (host, port), 0))
- }
-
- // java friendlier interfaces
- // Gauges
- def setTopicPartitionValue(host: String, port: Int, value: Int) {
- topicPartitions.get((host,port)).set(value)
- }
- def setLagValue(topicAndPartition: TopicAndPartition, value: Long) {
- lag.get((topicAndPartition)).set(value);
- }
- def setHighWatermarkValue(topicAndPartition: TopicAndPartition, value: Long) {
- highWatermark.get((topicAndPartition)).set(value);
- }
-
- // Counters
- def incBrokerReads(host: String, port: Int) {
- brokerReads.get((host,port)).inc
- }
- def incReads(topicAndPartition: TopicAndPartition) {
- reads.get(topicAndPartition).inc;
- }
- def incBytesReads(topicAndPartition: TopicAndPartition, inc: Long) {
- bytesRead.get(topicAndPartition).inc(inc);
- }
- def incBrokerBytesReads(host: String, port: Int, incBytes: Long) {
- brokerBytesRead.get((host,port)).inc(incBytes)
- }
- def incBrokerSkippedFetchRequests(host: String, port: Int) {
- brokerSkippedFetchRequests.get((host,port)).inc()
- }
- def setOffsets(topicAndPartition: TopicAndPartition, offset: Long) {
- offsets.get(topicAndPartition).set(offset)
- }
- def incReconnects(host: String, port: Int) {
- reconnects.get((host,port)).inc()
- }
- override def getPrefix = systemName + "-"
-}
diff --git a/samza-kafka/src/main/scala/org/apache/samza/system/kafka_deprecated/KafkaSystemFactory.scala b/samza-kafka/src/main/scala/org/apache/samza/system/kafka_deprecated/KafkaSystemFactory.scala
deleted file mode 100644
index b4003d8..0000000
--- a/samza-kafka/src/main/scala/org/apache/samza/system/kafka_deprecated/KafkaSystemFactory.scala
+++ /dev/null
@@ -1,179 +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.samza.system.kafka_deprecated
-import java.util.Properties
-
-import kafka.utils.ZkUtils
-import org.apache.samza.SamzaException
-import org.apache.samza.config.ApplicationConfig.ApplicationMode
-import org.apache.samza.util.{ClientUtilTopicMetadataStore, ExponentialSleepStrategy, Logging}
-import org.apache.samza.config._
-import org.apache.samza.metrics.MetricsRegistry
-import org.apache.samza.config.KafkaConfig.Config2Kafka
-import org.apache.samza.config.TaskConfig.Config2Task
-import org.apache.kafka.clients.producer.KafkaProducer
-import org.apache.samza.system.SystemFactory
-import org.apache.samza.config.StorageConfig._
-import org.apache.samza.system.SystemProducer
-import org.apache.samza.system.SystemAdmin
-import org.apache.samza.system.SystemConsumer
-
-object KafkaSystemFactory extends Logging {
- def getInjectedProducerProperties(systemName: String, config: Config) = if (config.isChangelogSystem(systemName)) {
- warn("System name '%s' is being used as a changelog. Disabling compression since Kafka does not support compression for log compacted topics." format systemName)
- Map[String, String]("compression.type" -> "none")
- } else {
- Map[String, String]()
- }
-}
-
-class KafkaSystemFactory extends SystemFactory with Logging {
- def getConsumer(systemName: String, config: Config, registry: MetricsRegistry): SystemConsumer = {
- val kafkaConfig:org.apache.samza.config_deprecated.KafkaConfig = config
- val clientId = getClientId("samza-consumer", config)
- val metrics = new KafkaSystemConsumerMetrics(systemName, registry)
-
- // Kind of goofy to need a producer config for consumers, but we need metadata.
- val producerConfig = config.getKafkaSystemProducerConfig(systemName, clientId)
- val bootstrapServers = producerConfig.bootsrapServers
- val consumerConfig = kafkaConfig.getKafkaSystemConsumerConfig(systemName, clientId)
-
- val timeout = consumerConfig.socketTimeoutMs
- val bufferSize = consumerConfig.socketReceiveBufferBytes
- val fetchSize = new StreamFetchSizes(consumerConfig.fetchMessageMaxBytes, config.getFetchMessageMaxBytesTopics(systemName))
- val consumerMinSize = consumerConfig.fetchMinBytes
- val consumerMaxWait = consumerConfig.fetchWaitMaxMs
- val autoOffsetResetDefault = consumerConfig.autoOffsetReset
- val autoOffsetResetTopics = config.getAutoOffsetResetTopics(systemName)
- val fetchThreshold = config.getConsumerFetchThreshold(systemName).getOrElse("50000").toInt
- val fetchThresholdBytes = config.getConsumerFetchThresholdBytes(systemName).getOrElse("-1").toLong
- val offsetGetter = new GetOffset(autoOffsetResetDefault, autoOffsetResetTopics)
- val metadataStore = new ClientUtilTopicMetadataStore(bootstrapServers, clientId, timeout)
-
- new KafkaSystemConsumer(
- systemName = systemName,
- systemAdmin = getAdmin(systemName, config),
- metrics = metrics,
- metadataStore = metadataStore,
- clientId = clientId,
- timeout = timeout,
- bufferSize = bufferSize,
- fetchSize = fetchSize,
- consumerMinSize = consumerMinSize,
- consumerMaxWait = consumerMaxWait,
- fetchThreshold = fetchThreshold,
- fetchThresholdBytes = fetchThresholdBytes,
- fetchLimitByBytesEnabled = config.isConsumerFetchThresholdBytesEnabled(systemName),
- offsetGetter = offsetGetter)
- }
-
- def getProducer(systemName: String, config: Config, registry: MetricsRegistry): SystemProducer = {
- val clientId = getClientId("samza-producer", config)
- val injectedProps = KafkaSystemFactory.getInjectedProducerProperties(systemName, config)
- val producerConfig = config.getKafkaSystemProducerConfig(systemName, clientId, injectedProps)
- val getProducer = () => { new KafkaProducer[Array[Byte], Array[Byte]](producerConfig.getProducerProperties) }
- val metrics = new KafkaSystemProducerMetrics(systemName, registry)
-
- // Unlike consumer, no need to use encoders here, since they come for free
- // inside the producer configs. Kafka's producer will handle all of this
- // for us.
-
- new KafkaSystemProducer(
- systemName,
- new ExponentialSleepStrategy(initialDelayMs = producerConfig.reconnectIntervalMs),
- getProducer,
- metrics,
- dropProducerExceptions = config.getDropProducerErrors)
- }
-
- def getAdmin(systemName: String, config: Config): SystemAdmin = {
- val kafkaConfig:org.apache.samza.config_deprecated.KafkaConfig = config
- val clientId = getClientId("samza-admin", config)
- val producerConfig = config.getKafkaSystemProducerConfig(systemName, clientId)
- val bootstrapServers = producerConfig.bootsrapServers
- val consumerConfig = kafkaConfig.getKafkaSystemConsumerConfig(systemName, clientId)
- val timeout = consumerConfig.socketTimeoutMs
- val bufferSize = consumerConfig.socketReceiveBufferBytes
- val zkConnect = Option(consumerConfig.zkConnect)
- .getOrElse(throw new SamzaException("no zookeeper.connect defined in config"))
- val connectZk = () => {
- ZkUtils(zkConnect, 6000, 6000, false)
- }
- val coordinatorStreamProperties = getCoordinatorTopicProperties(config)
- val coordinatorStreamReplicationFactor = config.getCoordinatorReplicationFactor.toInt
- val storeToChangelog = config.getKafkaChangelogEnabledStores()
- // Construct the meta information for each topic, if the replication factor is not defined, we use 2 as the number of replicas for the change log stream.
- val topicMetaInformation = storeToChangelog.map{case (storeName, topicName) =>
- {
- val replicationFactor = config.getChangelogStreamReplicationFactor(storeName).toInt
- val changelogInfo = ChangelogInfo(replicationFactor, config.getChangelogKafkaProperties(storeName))
- info("Creating topic meta information for topic: %s with replication factor: %s" format (topicName, replicationFactor))
- (topicName, changelogInfo)
- }}
-
- val systemConfig = new SystemConfig(config)
- val deleteCommittedMessages = systemConfig.deleteCommittedMessages(systemName)
- val intermediateStreamProperties: Map[String, Properties] = getIntermediateStreamProperties(config)
- new KafkaSystemAdmin(
- systemName,
- bootstrapServers,
- connectZk,
- coordinatorStreamProperties,
- coordinatorStreamReplicationFactor,
- timeout,
- bufferSize,
- clientId,
- topicMetaInformation,
- intermediateStreamProperties,
- deleteCommittedMessages)
- }
-
- def getCoordinatorTopicProperties(config: Config) = {
- val segmentBytes = config.getCoordinatorSegmentBytes
- (new Properties /: Map(
- "cleanup.policy" -> "compact",
- "segment.bytes" -> segmentBytes)) { case (props, (k, v)) => props.put(k, v); props }
- }
-
- def getIntermediateStreamProperties(config : Config): Map[String, Properties] = {
- val appConfig = new ApplicationConfig(config)
- if (appConfig.getAppMode == ApplicationMode.BATCH) {
- val streamConfig = new StreamConfig(config)
- streamConfig.getStreamIds().filter(streamConfig.getIsIntermediateStream(_)).map(streamId => {
- val properties = new Properties()
- properties.putIfAbsent("retention.ms", String.valueOf(KafkaConfig.DEFAULT_RETENTION_MS_FOR_BATCH))
- (streamId, properties)
- }).toMap
- } else {
- Map()
- }
- }
- def getClientId(id: String, config: Config): String = getClientId(
- id,
- new JobConfig(config).getName.getOrElse(throw new ConfigException("Missing job name.")),
- new JobConfig(config)getJobId)
-
- def getClientId(id: String, jobName: String, jobId: String): String =
- "%s-%s-%s" format
- (id.replaceAll("[^A-Za-z0-9]", "_"),
- jobName.replaceAll("[^A-Za-z0-9]", "_"),
- jobId.replaceAll("[^A-Za-z0-9]", "_"))
-
-}
diff --git a/samza-kafka/src/main/scala/org/apache/samza/system/kafka_deprecated/KafkaSystemProducer.scala b/samza-kafka/src/main/scala/org/apache/samza/system/kafka_deprecated/KafkaSystemProducer.scala
deleted file mode 100644
index af39378..0000000
--- a/samza-kafka/src/main/scala/org/apache/samza/system/kafka_deprecated/KafkaSystemProducer.scala
+++ /dev/null
@@ -1,235 +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.samza.system.kafka_deprecated
-
-
-import java.util.concurrent.atomic.AtomicReference
-import java.util.concurrent.TimeUnit
-
-import org.apache.kafka.clients.producer.Callback
-import org.apache.kafka.clients.producer.Producer
-import org.apache.kafka.clients.producer.ProducerRecord
-import org.apache.kafka.clients.producer.RecordMetadata
-import org.apache.kafka.common.PartitionInfo
-import org.apache.samza.system.OutgoingMessageEnvelope
-import org.apache.samza.system.SystemProducer
-import org.apache.samza.system.SystemProducerException
-import org.apache.samza.util.ExponentialSleepStrategy
-import org.apache.samza.util.KafkaUtil
-import org.apache.samza.util.Logging
-import org.apache.samza.util.TimerUtil
-
-class KafkaSystemProducer(systemName: String,
- retryBackoff: ExponentialSleepStrategy = new ExponentialSleepStrategy,
- getProducer: () => Producer[Array[Byte], Array[Byte]],
- metrics: KafkaSystemProducerMetrics,
- val clock: () => Long = () => System.nanoTime,
- val dropProducerExceptions: Boolean = false) extends SystemProducer with Logging with TimerUtil {
-
- // Represents a fatal error that caused the producer to close.
- val fatalException: AtomicReference[SystemProducerException] = new AtomicReference[SystemProducerException]()
- val producerRef: AtomicReference[Producer[Array[Byte], Array[Byte]]] = new AtomicReference[Producer[Array[Byte], Array[Byte]]]()
- val producerCreationLock: Object = new Object
- @volatile var stopped = false
-
- def start(): Unit = {
- producerRef.set(getProducer())
- }
-
- def stop() {
- info("Stopping producer for system: " + this.systemName)
-
- stopped = true
- val currentProducer = producerRef.getAndSet(null)
- try {
- if (currentProducer != null) {
- currentProducer.close // Also performs the equivalent of a flush()
- }
-
- val exception = fatalException.get()
- if (exception != null) {
- error("Observed an earlier send() error while closing producer", exception)
- }
- } catch {
- case e: Exception => error("Error while closing producer for system: " + systemName, e)
- }
- }
-
- def register(source: String) {
- }
-
- def send(source: String, envelope: OutgoingMessageEnvelope) {
- trace("Enqueuing message: %s, %s." format (source, envelope))
-
- val topicName = envelope.getSystemStream.getStream
- if (topicName == null || topicName.isEmpty) {
- throw new IllegalArgumentException("Invalid system stream: " + envelope.getSystemStream)
- }
-
- val globalProducerException = fatalException.get()
- if (globalProducerException != null) {
- metrics.sendFailed.inc
- throw new SystemProducerException("Producer was unable to recover from previous exception.", globalProducerException)
- }
-
- val currentProducer = getOrCreateCurrentProducer
-
- // Java-based Kafka producer API requires an "Integer" type partitionKey and does not allow custom overriding of Partitioners
- // Any kind of custom partitioning has to be done on the client-side
- val partitions: java.util.List[PartitionInfo] = currentProducer.partitionsFor(topicName)
- val partitionKey = if (envelope.getPartitionKey != null) KafkaUtil.getIntegerPartitionKey(envelope, partitions) else null
- val record = new ProducerRecord(envelope.getSystemStream.getStream,
- partitionKey,
- envelope.getKey.asInstanceOf[Array[Byte]],
- envelope.getMessage.asInstanceOf[Array[Byte]])
-
- try {
- currentProducer.send(record, new Callback {
- def onCompletion(metadata: RecordMetadata, exception: Exception): Unit = {
- if (exception == null) {
- metrics.sendSuccess.inc
- } else {
- val producerException = new SystemProducerException("Failed to send message for Source: %s on System:%s Topic:%s Partition:%s"
- .format(source, systemName, topicName, partitionKey), exception)
-
- handleFatalSendException(currentProducer, producerException)
- }
- }
- })
- metrics.sends.inc
- } catch {
- case originalException : Exception =>
- val producerException = new SystemProducerException("Failed to send message for Source: %s on System:%s Topic:%s Partition:%s"
- .format(source, systemName, topicName, partitionKey), originalException)
-
- metrics.sendFailed.inc
- error("Got a synchronous error from Kafka producer.", producerException)
- // Synchronous exceptions are always recoverable so propagate it up and let the user decide
- throw producerException
- }
- }
-
- def flush(source: String) {
- updateTimer(metrics.flushNs) {
- metrics.flushes.inc
-
- val currentProducer = producerRef.get()
- if (currentProducer == null) {
- if (dropProducerExceptions) {
- // No producer to flush, but we're ignoring exceptions so just return.
- warn("Skipping flush because the Kafka producer is null.")
- metrics.flushFailed.inc
- return
- }
- throw new SystemProducerException("Kafka producer is null.")
- }
-
- // Flush only throws InterruptedException, all other errors are handled in send() callbacks
- currentProducer.flush()
-
- // Invariant: At this point either
- // 1. The producer is fine and there are no exceptions to handle OR
- // 2. The producer is closed and one or more sources have exceptions to handle
- // 2a. All new sends get a ProducerClosedException or IllegalStateException (depending on kafka version)
- // 2b. There are no messages in flight because the producer is closed
-
- // We must check for an exception AFTER flush() because when flush() returns all callbacks for messages sent
- // in that flush() are guaranteed to have completed and we update the exception in the callback.
- // If there is an exception, we rethrow it here to prevent the checkpoint.
- val exception = fatalException.get()
- if (exception != null) {
- metrics.flushFailed.inc
- throw new SystemProducerException("Flush failed. One or more batches of messages were not sent!", exception)
- }
- trace("Flushed %s." format source)
- }
- }
-
-
- /**
- * Handles a fatal exception by closing the producer and either recreating it or storing the exception
- * to rethrow later, depending on the value of dropProducerExceptions.
- *
- * @param currentProducer the current producer for which the exception occurred. Must not be null.
- * @param producerException the exception to handle.
- */
- private def handleFatalSendException(currentProducer: Producer[Array[Byte], Array[Byte]], producerException: SystemProducerException): Unit = {
- metrics.sendFailed.inc
- error(producerException)
- // The SystemProducer API is synchronous, so there's no way for us to guarantee that an exception will
- // be handled by the Task before we recreate the producer, and if it isn't handled, a concurrent send() from another
- // Task could send on the new producer before the first Task properly handled the exception and produce out of order messages.
- // So we have to handle it right here in the SystemProducer.
- if (dropProducerExceptions) {
- warn("Ignoring producer exception. All messages in the failed producer request will be dropped!")
-
- // Prevent each callback from closing and nulling producer for the same failure.
- if (currentProducer == producerRef.get()) {
- info("Closing producer for system %s." format systemName)
- try {
- // send()s can get ProducerClosedException if the producer is stopped after they get the currentProducer
- // reference but before producer.send() returns. That's ONLY ok when dropProducerExceptions is true.
- // Also, when producer.close(0) is invoked on the Kafka IO thread, when it returns there will be no more
- // messages sent over the wire. This is key to ensuring no out-of-order messages as a result of recreating
- // the producer.
- currentProducer.close(0, TimeUnit.MILLISECONDS)
- } catch {
- case exception: Exception => error("Exception while closing producer.", exception)
- }
- producerRef.compareAndSet(currentProducer, null)
- }
- } else {
- // If there is an exception in the callback, it means that the Kafka producer has exhausted the max-retries
- // Close producer to ensure messages queued in-flight are not sent and hence, avoid re-ordering
- // This works because there is only 1 IO thread and no IO can be done until the callback returns.
- // Do not create a new producer here! It cannot be done without data loss for all concurrency modes.
- fatalException.compareAndSet(null, producerException)
- try {
- currentProducer.close(0, TimeUnit.MILLISECONDS)
- } catch {
- case exception: Exception => error("Exception while closing producer.", exception)
- }
- }
- }
-
- /**
- * @return the current producer. Never returns null.
- */
- private def getOrCreateCurrentProducer = {
- var currentProducer = producerRef.get
-
- if (currentProducer == null) {
- if (dropProducerExceptions && !stopped) {
- // Note: While this lock prevents others from creating a new producer, they could still set it to null.
- producerCreationLock.synchronized {
- currentProducer = producerRef.get
- if (currentProducer == null) {
- currentProducer = getProducer()
- producerRef.set(currentProducer)
- }
- }
- // Invariant: currentProducer must not be null at this point.
- } else {
- throw new SystemProducerException("Kafka producer is null.")
- }
- }
- currentProducer
- }
-}
diff --git a/samza-kafka/src/main/scala/org/apache/samza/system/kafka_deprecated/KafkaSystemProducerMetrics.scala b/samza-kafka/src/main/scala/org/apache/samza/system/kafka_deprecated/KafkaSystemProducerMetrics.scala
deleted file mode 100644
index e3ff90a..0000000
--- a/samza-kafka/src/main/scala/org/apache/samza/system/kafka_deprecated/KafkaSystemProducerMetrics.scala
+++ /dev/null
@@ -1,42 +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.samza.system.kafka_deprecated
-
-import org.apache.samza.metrics.{MetricsHelper, MetricsRegistry, MetricsRegistryMap}
-
-class KafkaSystemProducerMetrics(val systemName: String = "unknown", val registry: MetricsRegistry = new MetricsRegistryMap) extends MetricsHelper {
- /* Tracks the number of calls made to send in KafkaSystemProducer */
- val sends = newCounter("producer-sends")
- /* Tracks the number of calls made to flush in KafkaSystemProducer */
- val flushes = newCounter("flushes")
- /* Tracks how long the flush call takes to complete */
- val flushNs = newTimer("flush-ns")
- /* Tracks the number of times the system producer retries a send request (due to RetriableException) */
- @Deprecated
- val retries = newCounter("producer-retries")
- /* Tracks the number of times flush operation failed */
- val flushFailed = newCounter("flush-failed")
- /* Tracks the number of send requests that was failed by the KafkaProducer (due to unrecoverable errors) */
- val sendFailed = newCounter("producer-send-failed")
- /* Tracks the number of send requests that was successfully completed by the KafkaProducer */
- val sendSuccess = newCounter("producer-send-success")
-
- override def getPrefix = systemName + "-"
-}
diff --git a/samza-kafka/src/main/scala/org/apache/samza/system/kafka_deprecated/MessageSink.scala b/samza-kafka/src/main/scala/org/apache/samza/system/kafka_deprecated/MessageSink.scala
deleted file mode 100644
index d63f805..0000000
--- a/samza-kafka/src/main/scala/org/apache/samza/system/kafka_deprecated/MessageSink.scala
+++ /dev/null
@@ -1,35 +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.samza.system.kafka_deprecated
-
-import kafka.common.TopicAndPartition
-import kafka.message.MessageAndOffset
-
-private[kafka_deprecated] trait MessageSink {
- def setIsAtHighWatermark(tp: TopicAndPartition, isAtHighWatermark: Boolean): Unit
-
- def addMessage(tp: TopicAndPartition, msg: MessageAndOffset, highWatermark: Long): Unit
-
- def abdicate(tp: TopicAndPartition, nextOffset: Long): Unit
-
- def refreshDropped(): Unit
-
- def needsMoreMessages(tp: TopicAndPartition): Boolean
-}
diff --git a/samza-kafka/src/main/scala/org/apache/samza/system/kafka_deprecated/TopicMetadataCache.scala b/samza-kafka/src/main/scala/org/apache/samza/system/kafka_deprecated/TopicMetadataCache.scala
deleted file mode 100644
index fbfd1c6..0000000
--- a/samza-kafka/src/main/scala/org/apache/samza/system/kafka_deprecated/TopicMetadataCache.scala
+++ /dev/null
@@ -1,78 +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.samza.system.kafka_deprecated
-
-import org.apache.samza.util.Logging
-import kafka.api.TopicMetadata
-import org.apache.samza.util.KafkaUtil
-
-/**
- * TopicMetadataCache is used to cache all the topic metadata for Kafka per
- * (system, topic) partition. The cache access is thread safe. Each entry in
- * the cache is refreshed after a specified interval. The cache uses the passed
- * in getTopicInfoFromStore that retrieves the topic metadata from the store (usually zookeeper).
- */
-object TopicMetadataCache extends Logging {
- private case class MetadataInfo(var streamMetadata: TopicMetadata, var lastRefreshMs: Long)
- private val topicMetadataMap: scala.collection.mutable.Map[(String, String), MetadataInfo] = new scala.collection.mutable.HashMap[(String, String), MetadataInfo]
- private val lock = new Object
-
- // used to fetch the topic metadata from the store. Accepts a topic and system
- type FetchTopicMetadataType = (Set[String]) => Map[String, TopicMetadata]
-
- def getTopicMetadata(topics: Set[String], systemName: String, getTopicInfoFromStore: FetchTopicMetadataType, cacheTimeout: Long = 5000L, getTime: () => Long = { System.currentTimeMillis }): Map[String, TopicMetadata] = {
- lock synchronized {
- val time = getTime()
- val missingTopics = topics.filter(topic => !topicMetadataMap.contains(systemName, topic))
- val topicsWithBadOrExpiredMetadata = (topics -- missingTopics).filter(topic => {
- val metadata = topicMetadataMap(systemName, topic)
- hasBadErrorCode(metadata.streamMetadata) || ((time - metadata.lastRefreshMs) > cacheTimeout)
- })
- val topicsToRefresh = missingTopics ++ topicsWithBadOrExpiredMetadata
-
- if (topicsToRefresh.size > 0) {
- // Refresh topic information for any missing, expired, or bad topic metadata.
- topicMetadataMap ++= getTopicInfoFromStore(missingTopics ++ topicsWithBadOrExpiredMetadata)
- .map { case (topic, metadata) => ((systemName, topic), MetadataInfo(metadata, getTime())) }
- .toMap
- }
-
- // Use our new updated cache to return a map of topic -> metadata
- topicMetadataMap
- .filterKeys(topics.map(topic => (systemName, topic)))
- .map {
- case ((systemName, topic), metadata) =>
- (topic, metadata.streamMetadata)
- }.toMap
- }
- }
-
- def clear {
- topicMetadataMap.clear
- }
-
- /**
- * Helper method to check if a topic's metadata has a bad errorCode, or if a
- * partition's metadata has a bad errorCode.
- */
- def hasBadErrorCode(streamMetadata: TopicMetadata) = {
- KafkaUtil.isBadErrorCode(streamMetadata.error.code()) || streamMetadata.partitionsMetadata.exists(partitionMetadata => KafkaUtil.isBadErrorCode(partitionMetadata.error.code()))
- }
-}
diff --git a/samza-kafka/src/main/scala/org/apache/samza/system/kafka_deprecated/Toss.scala b/samza-kafka/src/main/scala/org/apache/samza/system/kafka_deprecated/Toss.scala
deleted file mode 100644
index 2c3ec0f..0000000
--- a/samza-kafka/src/main/scala/org/apache/samza/system/kafka_deprecated/Toss.scala
+++ /dev/null
@@ -1,28 +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.samza.system.kafka_deprecated
-
-import org.apache.samza.SamzaException
-
-private[kafka_deprecated] trait Toss {
- def toss(s:String) = throw new SamzaException(s)
-}
diff --git a/samza-kafka/src/main/scala/org/apache/samza/util/ClientUtilTopicMetadataStore.scala b/samza-kafka/src/main/scala/org/apache/samza/util/ClientUtilTopicMetadataStore.scala
deleted file mode 100644
index 4cbdc7f..0000000
--- a/samza-kafka/src/main/scala/org/apache/samza/util/ClientUtilTopicMetadataStore.scala
+++ /dev/null
@@ -1,50 +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.samza.util
-
-import kafka.api.{ TopicMetadataResponse, TopicMetadata }
-import org.apache.samza.SamzaException
-import kafka.client.ClientUtils
-import java.util.concurrent.atomic.AtomicInteger
-
-trait TopicMetadataStore extends Logging {
- def getTopicInfo(topics: Set[String]): Map[String, TopicMetadata]
-}
-
-class ClientUtilTopicMetadataStore(brokersListString: String, clientId: String, timeout: Int = 6000) extends TopicMetadataStore {
- val brokers = ClientUtils.parseBrokerList(brokersListString)
- var corrID = new AtomicInteger(0)
-
- def getTopicInfo(topics: Set[String]) = {
- val currCorrId = corrID.getAndIncrement
-
- debug("Fetching topic metadata.")
- val response: TopicMetadataResponse = ClientUtils.fetchTopicMetadata(topics, brokers, clientId, timeout, currCorrId)
- debug("Got topic metadata response: %s" format(response))
-
- if (response.correlationId != currCorrId) {
- throw new SamzaException("CorrelationID did not match for request on topics %s (sent %d, got %d)" format (topics, currCorrId, response.correlationId))
- }
-
- response.topicsMetadata
- .map(metadata => (metadata.topic, metadata))
- .toMap
- }
-}
diff --git a/samza-kafka/src/main/scala/org/apache/samza/util/KafkaUtil.scala b/samza-kafka/src/main/scala/org/apache/samza/util/KafkaUtil.scala
index 90dfff3..cb91a76 100644
--- a/samza-kafka/src/main/scala/org/apache/samza/util/KafkaUtil.scala
+++ b/samza-kafka/src/main/scala/org/apache/samza/util/KafkaUtil.scala
@@ -20,6 +20,7 @@
package org.apache.samza.util
import java.util.concurrent.atomic.AtomicLong
+
import kafka.admin.AdminUtils
import kafka.utils.ZkUtils
import org.apache.kafka.common.PartitionInfo
@@ -28,7 +29,7 @@ import org.apache.samza.config.JobConfig.Config2Job
import org.apache.samza.execution.StreamManager
import org.apache.samza.system.OutgoingMessageEnvelope
import org.apache.kafka.common.errors.ReplicaNotAvailableException
-import kafka.common.ErrorMapping
+import org.apache.kafka.common.protocol.Errors
object KafkaUtil extends Logging {
/**
@@ -72,7 +73,7 @@ object KafkaUtil extends Logging {
* errorCode that's not NoError and also not ReplicaNotAvailableCode.
*/
def isBadErrorCode(code: Short) = {
- code != ErrorMapping.NoError && code != ErrorMapping.ReplicaNotAvailableCode
+ code != Errors.NONE.code() && code != Errors.REPLICA_NOT_AVAILABLE.code()
}
}
diff --git a/samza-kafka/src/test/java/org/apache/samza/system/kafka/MockKafkaProducer.java b/samza-kafka/src/test/java/org/apache/samza/system/kafka/MockKafkaProducer.java
index 789617c..95676b7 100644
--- a/samza-kafka/src/test/java/org/apache/samza/system/kafka/MockKafkaProducer.java
+++ b/samza-kafka/src/test/java/org/apache/samza/system/kafka/MockKafkaProducer.java
@@ -31,7 +31,6 @@ import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReferenceArray;
-import kafka.producer.ProducerClosedException;
import org.apache.kafka.clients.consumer.OffsetAndMetadata;
import org.apache.kafka.clients.producer.Callback;
import org.apache.kafka.clients.producer.Producer;
@@ -100,13 +99,13 @@ public class MockKafkaProducer implements Producer<byte[], byte[]> {
}
private RecordMetadata getRecordMetadata(ProducerRecord record) {
- return new RecordMetadata(new TopicPartition(record.topic(), record.partition() == null ? 0 : record.partition()), 0, this.msgsSent.get(), -1L, -1, -1, -1);
+ return new RecordMetadata(new TopicPartition(record.topic(), record.partition() == null ? 0 : record.partition()), 0, this.msgsSent.get(), -1L, -1L, -1, -1);
}
@Override
public Future<RecordMetadata> send(final ProducerRecord record, final Callback callback) {
if (closed) {
- throw new ProducerClosedException();
+ throw new IllegalStateException("Cannot perform operation after producer has been closed");
}
if (errorNext) {
if (!errorInCallback) {
@@ -253,7 +252,7 @@ public class MockKafkaProducer implements Producer<byte[], byte[]> {
public FutureSuccess(ProducerRecord record, int offset) {
this.record = record;
- this._metadata = new RecordMetadata(new TopicPartition(record.topic(), record.partition() == null ? 0 : record.partition()), 0, offset, RecordBatch.NO_TIMESTAMP, -1, -1, -1);
+ this._metadata = new RecordMetadata(new TopicPartition(record.topic(), record.partition() == null ? 0 : record.partition()), 0, offset, RecordBatch.NO_TIMESTAMP, -1L, -1, -1);
}
@Override
diff --git a/samza-kafka/src/test/java/org/apache/samza/system/kafka/TestKafkaSystemAdminJava.java b/samza-kafka/src/test/java/org/apache/samza/system/kafka/TestKafkaSystemAdminJava.java
index 1d305fb..9169b44 100644
--- a/samza-kafka/src/test/java/org/apache/samza/system/kafka/TestKafkaSystemAdminJava.java
+++ b/samza-kafka/src/test/java/org/apache/samza/system/kafka/TestKafkaSystemAdminJava.java
@@ -19,6 +19,7 @@
package org.apache.samza.system.kafka;
+import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import java.util.HashMap;
import java.util.Map;
@@ -32,20 +33,24 @@ import org.apache.samza.config.MapConfig;
import org.apache.samza.system.StreamSpec;
import org.apache.samza.system.StreamValidationException;
import org.apache.samza.system.SystemAdmin;
+import org.apache.samza.system.SystemStreamMetadata;
import org.apache.samza.system.SystemStreamPartition;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
+import static org.apache.samza.system.kafka.KafkaSystemAdmin.*;
import static org.junit.Assert.*;
public class TestKafkaSystemAdminJava extends TestKafkaSystemAdmin {
+ private static final String SYSTEM = "kafka";
+ private static final String TOPIC = "input";
@Test
public void testGetOffsetsAfter() {
- SystemStreamPartition ssp1 = new SystemStreamPartition(SYSTEM(), TOPIC(), new Partition(0));
- SystemStreamPartition ssp2 = new SystemStreamPartition(SYSTEM(), TOPIC(), new Partition(1));
+ SystemStreamPartition ssp1 = new SystemStreamPartition(SYSTEM, TOPIC, new Partition(0));
+ SystemStreamPartition ssp2 = new SystemStreamPartition(SYSTEM, TOPIC, new Partition(1));
Map<SystemStreamPartition, String> offsets = new HashMap<>();
offsets.put(ssp1, "1");
offsets.put(ssp2, "2");
@@ -64,14 +69,14 @@ public class TestKafkaSystemAdminJava extends TestKafkaSystemAdmin {
int changeLogPartitionFactor = 5;
Map<String, String> map = new HashMap<>();
Config config = new MapConfig(map);
- StreamSpec spec = new StreamSpec("id", topicName, SYSTEM(), defaultPartitionCount, config);
+ StreamSpec spec = new StreamSpec("id", topicName, SYSTEM, defaultPartitionCount, config);
KafkaSystemAdmin kafkaAdmin = systemAdmin();
KafkaStreamSpec kafkaSpec = kafkaAdmin.toKafkaSpec(spec);
Assert.assertEquals("id", kafkaSpec.getId());
Assert.assertEquals(topicName, kafkaSpec.getPhysicalName());
- Assert.assertEquals(SYSTEM(), kafkaSpec.getSystemName());
+ Assert.assertEquals(SYSTEM, kafkaSpec.getSystemName());
Assert.assertEquals(defaultPartitionCount, kafkaSpec.getPartitionCount());
// validate that conversion is using coordination metadata
@@ -81,8 +86,8 @@ public class TestKafkaSystemAdminJava extends TestKafkaSystemAdmin {
map.put(org.apache.samza.config.KafkaConfig.JOB_COORDINATOR_REPLICATION_FACTOR(),
String.valueOf(coordReplicatonFactor));
- KafkaSystemAdmin admin = Mockito.spy(createSystemAdmin(SYSTEM(), map));
- spec = StreamSpec.createCoordinatorStreamSpec(topicName, SYSTEM());
+ KafkaSystemAdmin admin = Mockito.spy(createSystemAdmin(SYSTEM, map));
+ spec = StreamSpec.createCoordinatorStreamSpec(topicName, SYSTEM);
kafkaSpec = admin.toKafkaSpec(spec);
Assert.assertEquals(coordReplicatonFactor, kafkaSpec.getReplicationFactor());
Assert.assertEquals("123", kafkaSpec.getProperties().getProperty("segment.bytes"));
@@ -91,21 +96,21 @@ public class TestKafkaSystemAdminJava extends TestKafkaSystemAdmin {
// validate that conversion is using changeLog metadata
map = new HashMap<>();
- map.put(JobConfig.JOB_DEFAULT_SYSTEM(), SYSTEM());
+ map.put(JobConfig.JOB_DEFAULT_SYSTEM(), SYSTEM);
map.put(String.format("stores.%s.changelog", "fakeStore"), topicName);
int changeLogReplicationFactor = 3;
map.put(String.format("stores.%s.changelog.replication.factor", "fakeStore"),
String.valueOf(changeLogReplicationFactor));
- admin = Mockito.spy(createSystemAdmin(SYSTEM(), map));
- spec = StreamSpec.createChangeLogStreamSpec(topicName, SYSTEM(), changeLogPartitionFactor);
+ admin = Mockito.spy(createSystemAdmin(SYSTEM, map));
+ spec = StreamSpec.createChangeLogStreamSpec(topicName, SYSTEM, changeLogPartitionFactor);
kafkaSpec = admin.toKafkaSpec(spec);
Assert.assertEquals(changeLogReplicationFactor, kafkaSpec.getReplicationFactor());
// same, but with missing topic info
try {
- admin = Mockito.spy(createSystemAdmin(SYSTEM(), map));
- spec = StreamSpec.createChangeLogStreamSpec("anotherTopic", SYSTEM(), changeLogPartitionFactor);
+ admin = Mockito.spy(createSystemAdmin(SYSTEM, map));
+ spec = StreamSpec.createChangeLogStreamSpec("anotherTopic", SYSTEM, changeLogPartitionFactor);
kafkaSpec = admin.toKafkaSpec(spec);
Assert.fail("toKafkaSpec should've failed for missing topic");
} catch (StreamValidationException e) {
@@ -124,8 +129,8 @@ public class TestKafkaSystemAdminJava extends TestKafkaSystemAdmin {
// legacy format
interStreamMap.put(String.format("systems.%s.streams.%s.p2", "testSystem", interStreamId), "v2");
- admin = Mockito.spy(createSystemAdmin(SYSTEM(), interStreamMap));
- spec = new StreamSpec(interStreamId, topicName, SYSTEM(), defaultPartitionCount, config);
+ admin = Mockito.spy(createSystemAdmin(SYSTEM, interStreamMap));
+ spec = new StreamSpec(interStreamId, topicName, SYSTEM, defaultPartitionCount, config);
kafkaSpec = admin.toKafkaSpec(spec);
Assert.assertEquals("v1", kafkaSpec.getProperties().getProperty("p1"));
Assert.assertEquals("v2", kafkaSpec.getProperties().getProperty("p2"));
@@ -154,14 +159,14 @@ public class TestKafkaSystemAdminJava extends TestKafkaSystemAdmin {
map.put(org.apache.samza.config.KafkaConfig.JOB_COORDINATOR_REPLICATION_FACTOR(),
String.valueOf(coordReplicatonFactor));
- KafkaSystemAdmin admin = Mockito.spy(createSystemAdmin(SYSTEM(), map));
- StreamSpec spec = StreamSpec.createCoordinatorStreamSpec(STREAM, SYSTEM());
+ KafkaSystemAdmin admin = Mockito.spy(createSystemAdmin(SYSTEM, map));
+ StreamSpec spec = StreamSpec.createCoordinatorStreamSpec(STREAM, SYSTEM);
Mockito.doAnswer(invocationOnMock -> {
StreamSpec internalSpec = (StreamSpec) invocationOnMock.callRealMethod();
assertTrue(internalSpec instanceof KafkaStreamSpec); // KafkaStreamSpec is used to carry replication factor
assertTrue(internalSpec.isCoordinatorStream());
- assertEquals(SYSTEM(), internalSpec.getSystemName());
+ assertEquals(SYSTEM, internalSpec.getSystemName());
assertEquals(STREAM, internalSpec.getPhysicalName());
assertEquals(1, internalSpec.getPartitionCount());
Assert.assertEquals(coordReplicatonFactor, ((KafkaStreamSpec) internalSpec).getReplicationFactor());
@@ -192,18 +197,18 @@ public class TestKafkaSystemAdminJava extends TestKafkaSystemAdmin {
final int REP_FACTOR = 2;
Map<String, String> map = new HashMap<>();
- map.put(JobConfig.JOB_DEFAULT_SYSTEM(), SYSTEM());
+ map.put(JobConfig.JOB_DEFAULT_SYSTEM(), SYSTEM);
map.put(String.format("stores.%s.changelog", "fakeStore"), topic);
map.put(String.format("stores.%s.changelog.replication.factor", "fakeStore"), String.valueOf(REP_FACTOR));
map.put(String.format("stores.%s.changelog.kafka.segment.bytes", "fakeStore"), "139");
- KafkaSystemAdmin admin = Mockito.spy(createSystemAdmin(SYSTEM(), map));
- StreamSpec spec = StreamSpec.createChangeLogStreamSpec(topic, SYSTEM(), PARTITIONS);
+ KafkaSystemAdmin admin = Mockito.spy(createSystemAdmin(SYSTEM, map));
+ StreamSpec spec = StreamSpec.createChangeLogStreamSpec(topic, SYSTEM, PARTITIONS);
Mockito.doAnswer(invocationOnMock -> {
StreamSpec internalSpec = (StreamSpec) invocationOnMock.callRealMethod();
assertTrue(internalSpec instanceof KafkaStreamSpec); // KafkaStreamSpec is used to carry replication factor
assertTrue(internalSpec.isChangeLogStream());
- assertEquals(SYSTEM(), internalSpec.getSystemName());
+ assertEquals(SYSTEM, internalSpec.getSystemName());
assertEquals(topic, internalSpec.getPhysicalName());
assertEquals(REP_FACTOR, ((KafkaStreamSpec) internalSpec).getReplicationFactor());
assertEquals(PARTITIONS, internalSpec.getPartitionCount());
@@ -275,11 +280,61 @@ public class TestKafkaSystemAdminJava extends TestKafkaSystemAdmin {
TopicDescription td = dtr.all().get().get(topicName);
Assert.fail("topic " + topicName + " should've been removed. td=" + td);
} catch (Exception e) {
- if (e.getCause() instanceof org.apache.kafka.common.errors.UnknownTopicOrPartitionException) {
- // expected
- } else {
+ if (!(e.getCause() instanceof org.apache.kafka.common.errors.UnknownTopicOrPartitionException)) {
Assert.fail("topic " + topicName + " should've been removed. Expected UnknownTopicOrPartitionException.");
}
}
}
+
+ @Test
+ public void testShouldAssembleMetadata () {
+ Map<SystemStreamPartition, String> oldestOffsets = new ImmutableMap.Builder<SystemStreamPartition, String>()
+ .put(new SystemStreamPartition(SYSTEM, "stream1", new Partition(0)), "o1")
+ .put(new SystemStreamPartition(SYSTEM, "stream2", new Partition(0)), "o2")
+ .put(new SystemStreamPartition(SYSTEM, "stream1", new Partition(1)), "o3")
+ .put(new SystemStreamPartition(SYSTEM, "stream2", new Partition(1)), "o4")
+ .build();
+
+ Map<SystemStreamPartition, String> newestOffsets = new ImmutableMap.Builder<SystemStreamPartition, String>()
+ .put(new SystemStreamPartition(SYSTEM, "stream1", new Partition(0)), "n1")
+ .put(new SystemStreamPartition(SYSTEM, "stream2", new Partition(0)), "n2")
+ .put(new SystemStreamPartition(SYSTEM, "stream1", new Partition(1)), "n3")
+ .put(new SystemStreamPartition(SYSTEM, "stream2", new Partition(1)), "n4")
+ .build();
+
+ Map<SystemStreamPartition, String> upcomingOffsets = new ImmutableMap.Builder<SystemStreamPartition, String>()
+ .put(new SystemStreamPartition(SYSTEM, "stream1", new Partition(0)), "u1")
+ .put(new SystemStreamPartition(SYSTEM, "stream2", new Partition(0)), "u2")
+ .put(new SystemStreamPartition(SYSTEM, "stream1", new Partition(1)), "u3")
+ .put(new SystemStreamPartition(SYSTEM, "stream2", new Partition(1)), "u4")
+ .build();
+
+ Map<String, SystemStreamMetadata> metadata = assembleMetadata(oldestOffsets, newestOffsets, upcomingOffsets);
+ assertNotNull(metadata);
+ assertEquals(2, metadata.size());
+ assertTrue(metadata.containsKey("stream1"));
+ assertTrue(metadata.containsKey("stream2"));
+ SystemStreamMetadata stream1Metadata = metadata.get("stream1");
+ SystemStreamMetadata stream2Metadata = metadata.get("stream2");
+ assertNotNull(stream1Metadata);
+ assertNotNull(stream2Metadata);
+ assertEquals("stream1", stream1Metadata.getStreamName());
+ assertEquals("stream2", stream2Metadata.getStreamName());
+ SystemStreamMetadata.SystemStreamPartitionMetadata expectedSystemStream1Partition0Metadata =
+ new SystemStreamMetadata.SystemStreamPartitionMetadata("o1", "n1", "u1");
+ SystemStreamMetadata.SystemStreamPartitionMetadata expectedSystemStream1Partition1Metadata =
+ new SystemStreamMetadata.SystemStreamPartitionMetadata("o3", "n3", "u3");
+ SystemStreamMetadata.SystemStreamPartitionMetadata expectedSystemStream2Partition0Metadata =
+ new SystemStreamMetadata.SystemStreamPartitionMetadata("o2", "n2", "u2");
+ SystemStreamMetadata.SystemStreamPartitionMetadata expectedSystemStream2Partition1Metadata =
+ new SystemStreamMetadata.SystemStreamPartitionMetadata("o4", "n4", "u4");
+ Map<Partition, SystemStreamMetadata.SystemStreamPartitionMetadata> stream1PartitionMetadata =
+ stream1Metadata.getSystemStreamPartitionMetadata();
+ Map<Partition, SystemStreamMetadata.SystemStreamPartitionMetadata> stream2PartitionMetadata =
+ stream2Metadata.getSystemStreamPartitionMetadata();
+ assertEquals(expectedSystemStream1Partition0Metadata, stream1PartitionMetadata.get(new Partition(0)));
+ assertEquals(expectedSystemStream1Partition1Metadata, stream1PartitionMetadata.get(new Partition(1)));
+ assertEquals(expectedSystemStream2Partition0Metadata, stream2PartitionMetadata.get(new Partition(0)));
+ assertEquals(expectedSystemStream2Partition1Metadata, stream2PartitionMetadata.get(new Partition(1)));
+ }
}
diff --git a/samza-kafka/src/test/scala/org/apache/samza/checkpoint/kafka/TestKafkaCheckpointManager.scala b/samza-kafka/src/test/scala/org/apache/samza/checkpoint/kafka/TestKafkaCheckpointManager.scala
index dbe82fc..bb67e5f 100644
--- a/samza-kafka/src/test/scala/org/apache/samza/checkpoint/kafka/TestKafkaCheckpointManager.scala
+++ b/samza-kafka/src/test/scala/org/apache/samza/checkpoint/kafka/TestKafkaCheckpointManager.scala
@@ -21,12 +21,9 @@ package org.apache.samza.checkpoint.kafka
import java.util.Properties
-import kafka.admin.AdminUtils
import kafka.integration.KafkaServerTestHarness
-import kafka.server.ConfigType
-import kafka.utils.{CoreUtils, TestUtils, ZkUtils}
+import kafka.utils.{CoreUtils, TestUtils}
import com.google.common.collect.ImmutableMap
-import org.apache.kafka.common.security.JaasUtils
import org.apache.samza.checkpoint.Checkpoint
import org.apache.samza.config._
import org.apache.samza.container.TaskName
@@ -91,6 +88,7 @@ class TestKafkaCheckpointManager extends KafkaServerTestHarness {
checkPointManager.register(taskName)
checkPointManager.start
checkPointManager.writeCheckpoint(taskName, new Checkpoint(ImmutableMap.of()))
+ checkPointManager.stop()
// Verifications after the test
@@ -109,15 +107,12 @@ class TestKafkaCheckpointManager extends KafkaServerTestHarness {
kcm1.stop
// check that start actually creates the topic with log compaction enabled
- val zkClient = ZkUtils(zkConnect, 6000, 6000, JaasUtils.isZkSecurityEnabled())
- val topicConfig = AdminUtils.fetchEntityConfig(zkClient, ConfigType.Topic, checkpointTopic)
+ val topicConfig = adminZkClient.getAllTopicConfigs().getOrElse(checkpointTopic, new Properties())
assertEquals(topicConfig, new KafkaConfig(config).getCheckpointTopicProperties())
assertEquals("compact", topicConfig.get("cleanup.policy"))
assertEquals("26214400", topicConfig.get("segment.bytes"))
- zkClient.close
-
// read before topic exists should result in a null checkpoint
val readCp = readCheckpoint(checkpointTopic, taskName)
assertNull(readCp)
@@ -130,7 +125,7 @@ class TestKafkaCheckpointManager extends KafkaServerTestHarness {
assertEquals(checkpoint2, readCheckpoint(checkpointTopic, taskName))
}
- @Test(expected = classOf[SamzaException])
+ @Test
def testWriteCheckpointShouldRetryFiniteTimesOnFailure(): Unit = {
val checkpointTopic = "checkpoint-topic-2"
val mockKafkaProducer: SystemProducer = Mockito.mock(classOf[SystemProducer])
@@ -148,9 +143,16 @@ class TestKafkaCheckpointManager extends KafkaServerTestHarness {
val checkPointManager = new KafkaCheckpointManager(spec, new MockSystemFactory, false, config, new NoOpMetricsRegistry)
checkPointManager.MaxRetryDurationInMillis = 1
- checkPointManager.register(taskName)
- checkPointManager.start
- checkPointManager.writeCheckpoint(taskName, new Checkpoint(ImmutableMap.of()))
+ try {
+ checkPointManager.register(taskName)
+ checkPointManager.start
+ checkPointManager.writeCheckpoint(taskName, new Checkpoint(ImmutableMap.of()))
+ } catch {
+ case _: SamzaException => info("Got SamzaException as expected.")
+ case unexpectedException: Throwable => fail("Expected SamzaException but got %s" format unexpectedException)
+ } finally {
+ checkPointManager.stop()
+ }
}
@Test
@@ -235,20 +237,8 @@ class TestKafkaCheckpointManager extends KafkaServerTestHarness {
kcm.stop
}
- private def createTopic(cpTopic: String, partNum: Int, props: Properties) = {
- val zkClient = ZkUtils(zkConnect, 6000, 6000, JaasUtils.isZkSecurityEnabled())
- try {
- AdminUtils.createTopic(
- zkClient,
- cpTopic,
- partNum,
- 1,
- props)
- } catch {
- case e: Exception => println(e.getMessage)
- } finally {
- zkClient.close
- }
+ private def createTopic(cpTopic: String, partNum: Int, props: Properties) {
+ adminZkClient.createTopic(cpTopic, partNum, 1, props)
}
}
diff --git a/samza-kafka/src/test/scala/org/apache/samza/config/TestKafkaSerdeConfig.scala b/samza-kafka/src/test/scala/org/apache/samza/config/TestKafkaSerdeConfig.scala
deleted file mode 100644
index 3871560..0000000
--- a/samza-kafka/src/test/scala/org/apache/samza/config/TestKafkaSerdeConfig.scala
+++ /dev/null
@@ -1,48 +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.samza.config
-
-import org.apache.samza.config.KafkaSerdeConfig.Config2KafkaSerde
-import org.junit.Assert._
-import org.junit.Test
-
-import scala.collection.JavaConverters._
-
-class TestKafkaSerdeConfig {
- val MAGIC_VAL = "1000"
-
- val paramsToTest = List(
- "serializers.registry.test.encoder", "serializers.registry.test.decoder")
-
- val config = new MapConfig(paramsToTest.map { m => (m, MAGIC_VAL) }.toMap.asJava)
-
- @Test
- def testKafkaConfigurationIsBackwardsCompatible {
- assertEquals(MAGIC_VAL, config.getKafkaEncoder("test").getOrElse(""))
- assertEquals(MAGIC_VAL, config.getKafkaDecoder("test").getOrElse(""))
- }
-
- @Test
- def testKafkaConfigurationProperties {
- val properties = config.getKafkaProperties("test")
- assertEquals(MAGIC_VAL, properties.getString("encoder"))
- assertEquals(MAGIC_VAL, properties.getString("decoder"))
- }
-}
diff --git a/samza-kafka/src/test/scala/org/apache/samza/serializers/TestKafkaSerde.scala b/samza-kafka/src/test/scala/org/apache/samza/serializers/TestKafkaSerde.scala
deleted file mode 100644
index 35bf688..0000000
--- a/samza-kafka/src/test/scala/org/apache/samza/serializers/TestKafkaSerde.scala
+++ /dev/null
@@ -1,34 +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.samza.serializers
-
-import kafka.serializer.StringEncoder
-import kafka.serializer.StringDecoder
-
-import org.junit.Assert._
-import org.junit.Test
-
-class TestKafkaSerde {
- @Test
- def testKafkaSerdeShouldWrapEncoderAndDecoders {
- val serde = new KafkaSerde(new StringEncoder, new StringDecoder)
- assertEquals("test", serde.fromBytes(serde.toBytes("test")))
- }
-}
diff --git a/samza-kafka/src/test/scala/org/apache/samza/system/kafka/TestKafkaSystemAdmin.scala b/samza-kafka/src/test/scala/org/apache/samza/system/kafka/TestKafkaSystemAdmin.scala
index a70a756..9dceb5e 100644
--- a/samza-kafka/src/test/scala/org/apache/samza/system/kafka/TestKafkaSystemAdmin.scala
+++ b/samza-kafka/src/test/scala/org/apache/samza/system/kafka/TestKafkaSystemAdmin.scala
@@ -21,22 +21,26 @@
package org.apache.samza.system.kafka
+import java.time.Duration
+import java.util.Collections
+import java.util.concurrent.TimeUnit
+
import com.google.common.collect.ImmutableSet
-import kafka.admin.AdminUtils
-import kafka.consumer.{Consumer, ConsumerConfig, ConsumerConnector}
import kafka.integration.KafkaServerTestHarness
import kafka.server.KafkaConfig
import kafka.utils.TestUtils
+import org.apache.kafka.clients.admin.{AdminClient, NewTopic}
+import org.apache.kafka.clients.consumer.{KafkaConsumer}
import org.apache.kafka.clients.producer.{KafkaProducer, ProducerRecord}
import org.apache.kafka.common.security.JaasUtils
import org.apache.samza.Partition
import org.apache.samza.config._
import org.apache.samza.system.SystemStreamMetadata.SystemStreamPartitionMetadata
import org.apache.samza.system.{StreamSpec, SystemStreamMetadata, SystemStreamPartition}
-import org.apache.samza.util.{ClientUtilTopicMetadataStore, KafkaUtil, TopicMetadataStore}
import org.junit.Assert._
import org.junit._
+import scala.collection.JavaConverters
import scala.collection.JavaConverters._
/**
@@ -57,9 +61,9 @@ object TestKafkaSystemAdmin extends KafkaServerTestHarness {
protected def numBrokers: Int = 3
var producer: KafkaProducer[Array[Byte], Array[Byte]] = null
- var metadataStore: TopicMetadataStore = null
var producerConfig: KafkaProducerConfig = null
var systemAdmin: KafkaSystemAdmin = null
+ var adminClient: AdminClient = null
override def generateConfigs(): Seq[KafkaConfig] = {
val props = TestUtils.createBrokerConfigs(numBrokers, zkConnect, enableDeleteTopic = true)
@@ -79,62 +83,59 @@ object TestKafkaSystemAdmin extends KafkaServerTestHarness {
producerConfig = new KafkaProducerConfig("kafka", "i001", map)
producer = new KafkaProducer[Array[Byte], Array[Byte]](producerConfig.getProducerProperties)
- metadataStore = new ClientUtilTopicMetadataStore(brokerList, "some-job-name")
systemAdmin = createSystemAdmin(SYSTEM, map)
+ adminClient = AdminClient.create(map.asInstanceOf[java.util.Map[String, Object]])
systemAdmin.start()
}
@AfterClass
override def tearDown() {
+ adminClient.close()
systemAdmin.stop()
producer.close()
super.tearDown()
}
def createTopic(topicName: String, partitionCount: Int) {
- AdminUtils.createTopic(
- zkUtils,
- topicName,
- partitionCount,
- REPLICATION_FACTOR)
+ val topicCreationFutures = adminClient.createTopics(Collections.singletonList(new NewTopic(topicName, partitionCount, REPLICATION_FACTOR.shortValue())))
+ topicCreationFutures.all().get() // wait on the future to make sure create topic call finishes
}
def validateTopic(topic: String, expectedPartitionCount: Int) {
var done = false
- var retries = 0
- val maxRetries = 100
+ var attempts = 0
- while (!done && retries < maxRetries) {
+ while (!done && attempts < 10) {
try {
- val topicMetadataMap = TopicMetadataCache.getTopicMetadata(Set(topic), SYSTEM, metadataStore.getTopicInfo)
- val topicMetadata = topicMetadataMap(topic)
-
- KafkaUtil.maybeThrowException(topicMetadata.error.exception())
+ attempts += 1
+ val topicDescriptionFutures = adminClient.describeTopics(
+ JavaConverters.asJavaCollectionConverter(Set(topic)).asJavaCollection).all()
+ val topicDescription = topicDescriptionFutures.get(500, TimeUnit.MILLISECONDS)
+ .get(topic)
- done = expectedPartitionCount == topicMetadata.partitionsMetadata.size
+ done = expectedPartitionCount == topicDescription.partitions().size()
} catch {
case e: Exception =>
- System.err.println("Got exception while validating test topics. Waiting and retrying.", e)
- retries += 1
- Thread.sleep(500)
+ System.err.println("Interrupted during validating test topics", e)
}
}
- if (retries >= maxRetries) {
- fail("Unable to successfully create topics. Tried to validate %s times." format retries)
+ if (!done) {
+ fail("Unable to successfully create topics. Tried to validate %s times." format attempts)
}
}
- def getConsumerConnector(): ConsumerConnector = {
+ def getKafkaConsumer(): KafkaConsumer[Any, Any] = {
val props = new java.util.Properties
- props.put("zookeeper.connect", zkConnect)
+ props.put("bootstrap.servers", brokerList)
props.put("group.id", "test")
- props.put("auto.offset.reset", "smallest")
+ props.put("auto.offset.reset", "earliest")
+ props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer")
+ props.put("value.deserializer", "org.apache.kafka.common.serialization.ByteArrayDeserializer")
- val consumerConfig = new ConsumerConfig(props)
- Consumer.create(consumerConfig)
+ new KafkaConsumer[Any, Any](props)
}
def createSystemAdmin(system: String, map: java.util.Map[String, String]) = {
@@ -147,17 +148,12 @@ object TestKafkaSystemAdmin extends KafkaServerTestHarness {
map.put(KAFKA_CONSUMER_PROPERTY_PREFIX + KafkaConsumerConfig.ZOOKEEPER_CONNECT, zkConnect)
val config: Config = new MapConfig(map)
- val res = KafkaSystemAdminUtilsScala.getIntermediateStreamProperties(config)
-
- val clientId = KafkaConsumerConfig.createClientId("clientPrefix", config);
+ val clientId = KafkaConsumerConfig.createClientId("clientPrefix", config)
// extract kafka client configs
val consumerConfig = KafkaConsumerConfig.getKafkaSystemConsumerConfig(config, system, clientId)
- new KafkaSystemAdmin(
- system,
- config,
- KafkaSystemConsumer.createKafkaConsumerImpl(system, consumerConfig))
+ new KafkaSystemAdmin(system, config, KafkaSystemConsumer.createKafkaConsumerImpl(system, consumerConfig))
}
}
@@ -170,50 +166,12 @@ class TestKafkaSystemAdmin {
import TestKafkaSystemAdmin._
@Test
- def testShouldAssembleMetadata {
- val oldestOffsets = Map(
- new SystemStreamPartition(SYSTEM, "stream1", new Partition(0)) -> "o1",
- new SystemStreamPartition(SYSTEM, "stream2", new Partition(0)) -> "o2",
- new SystemStreamPartition(SYSTEM, "stream1", new Partition(1)) -> "o3",
- new SystemStreamPartition(SYSTEM, "stream2", new Partition(1)) -> "o4")
- val newestOffsets = Map(
- new SystemStreamPartition(SYSTEM, "stream1", new Partition(0)) -> "n1",
- new SystemStreamPartition(SYSTEM, "stream2", new Partition(0)) -> "n2",
- new SystemStreamPartition(SYSTEM, "stream1", new Partition(1)) -> "n3",
- new SystemStreamPartition(SYSTEM, "stream2", new Partition(1)) -> "n4")
- val upcomingOffsets = Map(
- new SystemStreamPartition(SYSTEM, "stream1", new Partition(0)) -> "u1",
- new SystemStreamPartition(SYSTEM, "stream2", new Partition(0)) -> "u2",
- new SystemStreamPartition(SYSTEM, "stream1", new Partition(1)) -> "u3",
- new SystemStreamPartition(SYSTEM, "stream2", new Partition(1)) -> "u4")
- val metadata = KafkaSystemAdminUtilsScala.assembleMetadata(oldestOffsets, newestOffsets, upcomingOffsets)
- assertNotNull(metadata)
- assertEquals(2, metadata.size)
- assertTrue(metadata.contains("stream1"))
- assertTrue(metadata.contains("stream2"))
- val stream1Metadata = metadata("stream1")
- val stream2Metadata = metadata("stream2")
- assertNotNull(stream1Metadata)
- assertNotNull(stream2Metadata)
- assertEquals("stream1", stream1Metadata.getStreamName)
- assertEquals("stream2", stream2Metadata.getStreamName)
- val expectedSystemStream1Partition0Metadata = new SystemStreamPartitionMetadata("o1", "n1", "u1")
- val expectedSystemStream1Partition1Metadata = new SystemStreamPartitionMetadata("o3", "n3", "u3")
- val expectedSystemStream2Partition0Metadata = new SystemStreamPartitionMetadata("o2", "n2", "u2")
- val expectedSystemStream2Partition1Metadata = new SystemStreamPartitionMetadata("o4", "n4", "u4")
- val stream1PartitionMetadata = stream1Metadata.getSystemStreamPartitionMetadata
- val stream2PartitionMetadata = stream2Metadata.getSystemStreamPartitionMetadata
- assertEquals(expectedSystemStream1Partition0Metadata, stream1PartitionMetadata.get(new Partition(0)))
- assertEquals(expectedSystemStream1Partition1Metadata, stream1PartitionMetadata.get(new Partition(1)))
- assertEquals(expectedSystemStream2Partition0Metadata, stream2PartitionMetadata.get(new Partition(0)))
- assertEquals(expectedSystemStream2Partition1Metadata, stream2PartitionMetadata.get(new Partition(1)))
- }
-
- @Test
def testShouldGetOldestNewestAndNextOffsets {
- // Create an empty topic with 50 partitions, but with no offsets.
- createTopic(TOPIC, 50)
- validateTopic(TOPIC, 50)
+ // Reduced the partition count to 25 instead of 50 to prevent tests from failing. In the current setup,
+ // embedded Kafka brings up 3 brokers for test and replication fetcher runs into issue with higher number partition.
+ // Create an empty topic with 25 partitions, but with no offsets.
+ createTopic(TOPIC, 25)
+ validateTopic(TOPIC, 25)
// Verify the empty topic behaves as expected.
var metadata = systemAdmin.getSystemStreamMetadata(Set(TOPIC).asJava)
@@ -221,7 +179,7 @@ class TestKafkaSystemAdmin {
assertNotNull(metadata.get(TOPIC))
// Verify partition count.
var sspMetadata = metadata.get(TOPIC).getSystemStreamPartitionMetadata
- assertEquals(50, sspMetadata.size)
+ assertEquals(25, sspMetadata.size)
// Empty topics should have null for latest offset and 0 for earliest offset
assertEquals("0", sspMetadata.get(new Partition(0)).getOldestOffset)
assertNull(sspMetadata.get(new Partition(0)).getNewestOffset)
@@ -230,45 +188,50 @@ class TestKafkaSystemAdmin {
// Add a new message to one of the partitions, and verify that it works as
// expected.
- producer.send(new ProducerRecord(TOPIC, 48, "key1".getBytes, "val1".getBytes)).get()
+ producer.send(new ProducerRecord(TOPIC, 24, "key1".getBytes, "val1".getBytes)).get()
metadata = systemAdmin.getSystemStreamMetadata(Set(TOPIC).asJava)
assertEquals(1, metadata.size)
val streamName = metadata.keySet.asScala.head
assertEquals(TOPIC, streamName)
sspMetadata = metadata.get(streamName).getSystemStreamPartitionMetadata
// key1 gets hash-mod'd to partition 48.
- assertEquals("0", sspMetadata.get(new Partition(48)).getOldestOffset)
- assertEquals("0", sspMetadata.get(new Partition(48)).getNewestOffset)
- assertEquals("1", sspMetadata.get(new Partition(48)).getUpcomingOffset)
+ assertEquals("0", sspMetadata.get(new Partition(24)).getOldestOffset)
+ assertEquals("0", sspMetadata.get(new Partition(24)).getNewestOffset)
+ assertEquals("1", sspMetadata.get(new Partition(24)).getUpcomingOffset)
// Some other partition should be empty.
assertEquals("0", sspMetadata.get(new Partition(3)).getOldestOffset)
assertNull(sspMetadata.get(new Partition(3)).getNewestOffset)
assertEquals("0", sspMetadata.get(new Partition(3)).getUpcomingOffset)
// Add a second message to one of the same partition.
- producer.send(new ProducerRecord(TOPIC, 48, "key1".getBytes, "val2".getBytes)).get()
+ producer.send(new ProducerRecord(TOPIC, 24, "key1".getBytes, "val2".getBytes)).get()
metadata = systemAdmin.getSystemStreamMetadata(Set(TOPIC).asJava)
assertEquals(1, metadata.size)
assertEquals(TOPIC, streamName)
sspMetadata = metadata.get(streamName).getSystemStreamPartitionMetadata
// key1 gets hash-mod'd to partition 48.
- assertEquals("0", sspMetadata.get(new Partition(48)).getOldestOffset)
- assertEquals("1", sspMetadata.get(new Partition(48)).getNewestOffset)
- assertEquals("2", sspMetadata.get(new Partition(48)).getUpcomingOffset)
+ assertEquals("0", sspMetadata.get(new Partition(24)).getOldestOffset)
+ assertEquals("1", sspMetadata.get(new Partition(24)).getNewestOffset)
+ assertEquals("2", sspMetadata.get(new Partition(24)).getUpcomingOffset)
// Validate that a fetch will return the message.
- val connector = getConsumerConnector
- var stream = connector.createMessageStreams(Map(TOPIC -> 1))(TOPIC).head.iterator
- var message = stream.next
- var text = new String(message.message, "UTF-8")
- connector.shutdown
+ val consumer = getKafkaConsumer
+ consumer.subscribe(JavaConverters.setAsJavaSetConverter(Set(TOPIC)).asJava)
+ val records = consumer.poll(Duration.ofMillis(10000))
+ consumer.close()
+
+ assertTrue(records.count() == 2)
+ val stream = records.iterator()
+ var message = stream.next()
+
+ var text = new String(message.value().asInstanceOf[Array[Byte]], "UTF-8")
// First message should match the earliest expected offset.
- assertEquals(sspMetadata.get(new Partition(48)).getOldestOffset, message.offset.toString)
+ assertEquals(sspMetadata.get(new Partition(24)).getOldestOffset, message.offset.toString)
assertEquals("val1", text)
// Second message should match the earliest expected offset.
- message = stream.next
- text = new String(message.message, "UTF-8")
- assertEquals(sspMetadata.get(new Partition(48)).getNewestOffset, message.offset.toString)
+ message = stream.next()
+ text = new String(message.value().asInstanceOf[Array[Byte]], "UTF-8")
+ assertEquals(sspMetadata.get(new Partition(24)).getNewestOffset, message.offset.toString)
assertEquals("val2", text)
}
@@ -294,19 +257,18 @@ class TestKafkaSystemAdmin {
@Test
def testShouldCreateCoordinatorStream {
val topic = "test-coordinator-stream"
+ val expectedReplicationFactor = 3
val map = new java.util.HashMap[String, String]()
- map.put(org.apache.samza.config.KafkaConfig.JOB_COORDINATOR_REPLICATION_FACTOR, "3")
+ map.put(org.apache.samza.config.KafkaConfig.JOB_COORDINATOR_REPLICATION_FACTOR, expectedReplicationFactor.toString)
val systemAdmin = createSystemAdmin(SYSTEM, map)
val spec = StreamSpec.createCoordinatorStreamSpec(topic, "kafka")
+ val actualReplicationFactor = systemAdmin.toKafkaSpec(spec).getReplicationFactor
+ // Ensure we respect the replication factor passed to system admin
+ assertEquals(expectedReplicationFactor, actualReplicationFactor)
+
systemAdmin.createStream(spec)
validateTopic(topic, 1)
- val topicMetadataMap = TopicMetadataCache.getTopicMetadata(Set(topic), "kafka", metadataStore.getTopicInfo)
- assertTrue(topicMetadataMap.contains(topic))
- val topicMetadata = topicMetadataMap(topic)
- val partitionMetadata = topicMetadata.partitionsMetadata.head
- assertEquals(0, partitionMetadata.partitionId)
- assertEquals(3, partitionMetadata.replicas.size)
}
@Test
@@ -336,6 +298,5 @@ class TestKafkaSystemAdmin {
assertEquals("0", producer.send(new ProducerRecord(TOPIC2, 13, "key4".getBytes, "val4".getBytes)).get().offset().toString)
assertEquals("2", systemAdmin.getSSPMetadata(ImmutableSet.of(sspUnderTest)).get(sspUnderTest).getNewestOffset)
assertEquals("0", systemAdmin.getSSPMetadata(ImmutableSet.of(otherSsp)).get(otherSsp).getNewestOffset)
-
}
}
\ No newline at end of file
diff --git a/samza-kafka/src/test/scala/org/apache/samza/system/kafka/TestTopicMetadataCache.scala b/samza-kafka/src/test/scala/org/apache/samza/system/kafka/TestTopicMetadataCache.scala
deleted file mode 100644
index 9cc2f63..0000000
--- a/samza-kafka/src/test/scala/org/apache/samza/system/kafka/TestTopicMetadataCache.scala
+++ /dev/null
@@ -1,139 +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.samza.system.kafka
-
-import java.util.concurrent.CountDownLatch
-import java.util.concurrent.atomic.{AtomicBoolean, AtomicInteger}
-
-import kafka.api.TopicMetadata
-import org.I0Itec.zkclient.ZkClient
-import org.apache.samza.util.Clock
-import org.apache.samza.util.TopicMetadataStore
-import org.junit.Assert._
-import org.junit.Before
-import org.junit.Test
-import kafka.common.ErrorMapping
-import kafka.api.PartitionMetadata
-import org.apache.kafka.common.protocol.Errors
-
-class TestTopicMetadataCache {
-
- class MockTime extends Clock {
- var currentValue = 0
-
- def currentTimeMillis: Long = currentValue
- }
-
- class MockTopicMetadataStore extends TopicMetadataStore {
- var mockCache = Map(
- "topic1" -> new TopicMetadata("topic1", List.empty, Errors.NONE),
- "topic2" -> new TopicMetadata("topic2", List.empty, Errors.NONE))
- var numberOfCalls: AtomicInteger = new AtomicInteger(0)
-
- def getTopicInfo(topics: Set[String]) = {
- var topicMetadata = Map[String, TopicMetadata]()
- topics.foreach(topic => topicMetadata += topic -> mockCache(topic))
- numberOfCalls.getAndIncrement
- topicMetadata
- }
-
- def setErrorCode(topic: String, errorCode: Short) {
- mockCache += topic -> new TopicMetadata(topic, List.empty, Errors.forCode(errorCode))
- }
- }
-
- @Before def setup {
- TopicMetadataCache.clear
- }
-
- @Test
- def testBasicMetadataCacheFunctionality {
- val mockStore = new MockTopicMetadataStore
- val mockTime = new MockTime
-
- // Retrieve a topic from the cache. Initially cache is empty and store is queried to get the data
- mockStore.setErrorCode("topic1", 3)
- var metadata = TopicMetadataCache.getTopicMetadata(Set("topic1"), "kafka", mockStore.getTopicInfo, 5, mockTime.currentTimeMillis)
- assertEquals("topic1", metadata("topic1").topic)
- assertEquals(3, metadata("topic1").error.code)
- assertEquals(1, mockStore.numberOfCalls.get())
-
- // Retrieve the same topic from the cache which has an error code. Ensure the store is called to refresh the cache
- mockTime.currentValue = 5
- mockStore.setErrorCode("topic1", 0)
- metadata = TopicMetadataCache.getTopicMetadata(Set("topic1"), "kafka", mockStore.getTopicInfo, 5, mockTime.currentTimeMillis)
- assertEquals("topic1", metadata("topic1").topic)
- assertEquals(0, metadata("topic1").error.code)
- assertEquals(2, mockStore.numberOfCalls.get())
-
- // Retrieve the same topic from the cache with refresh rate greater than the last update. Ensure the store is not
- // called
- metadata = TopicMetadataCache.getTopicMetadata(Set("topic1"), "kafka", mockStore.getTopicInfo, 5, mockTime.currentTimeMillis)
- assertEquals("topic1", metadata("topic1").topic)
- assertEquals(0, metadata("topic1").error.code)
- assertEquals(2, mockStore.numberOfCalls.get())
-
- // Ensure that refresh happens when refresh rate is less than the last update. Ensure the store is called
- mockTime.currentValue = 11
- metadata = TopicMetadataCache.getTopicMetadata(Set("topic1"), "kafka", mockStore.getTopicInfo, 5, mockTime.currentTimeMillis)
- assertEquals("topic1", metadata("topic1").topic)
- assertEquals(0, metadata("topic1").error.code)
- assertEquals(3, mockStore.numberOfCalls.get())
- }
-
- @Test
- def testMultiThreadedInteractionForTopicMetadataCache {
- val mockStore = new MockTopicMetadataStore
- val mockTime = new MockTime
- val waitForThreadStart = new CountDownLatch(3)
- val numAssertionSuccess = new AtomicBoolean(true)
- // Add topic to the cache from multiple threads and ensure the store is called only once
- val threads = new Array[Thread](3)
-
- mockTime.currentValue = 17
- for (i <- 0 until 3) {
- threads(i) = new Thread(new Runnable {
- def run {
- waitForThreadStart.countDown()
- waitForThreadStart.await()
- val metadata = TopicMetadataCache.getTopicMetadata(Set("topic1"), "kafka", mockStore.getTopicInfo, 5, mockTime.currentTimeMillis)
- numAssertionSuccess.compareAndSet(true, metadata("topic1").topic.equals("topic1"))
- numAssertionSuccess.compareAndSet(true, metadata("topic1").error.code == 0)
- }
- })
- threads(i).start()
- }
- for (i <- 0 until 3) {
- threads(i).join
- }
- assertTrue(numAssertionSuccess.get())
- assertEquals(1, mockStore.numberOfCalls.get())
- }
-
- @Test
- def testBadErrorCodes {
- val partitionMetadataBad = new PartitionMetadata(0, None, Seq(), error = Errors.LEADER_NOT_AVAILABLE)
- val partitionMetadataGood = new PartitionMetadata(0, None, Seq(), error = Errors.NONE)
- assertTrue(TopicMetadataCache.hasBadErrorCode(new TopicMetadata("test", List.empty, Errors.REQUEST_TIMED_OUT)))
- assertTrue(TopicMetadataCache.hasBadErrorCode(new TopicMetadata("test", List(partitionMetadataBad), Errors.NONE)))
- assertFalse(TopicMetadataCache.hasBadErrorCode(new TopicMetadata("test", List.empty, Errors.NONE)))
- assertFalse(TopicMetadataCache.hasBadErrorCode(new TopicMetadata("test", List(partitionMetadataGood), Errors.NONE)))
- }
-}
diff --git a/samza-kafka/src/test/scala/org/apache/samza/system/kafka_deprecated/TestBrokerProxy.scala b/samza-kafka/src/test/scala/org/apache/samza/system/kafka_deprecated/TestBrokerProxy.scala
deleted file mode 100644
index 702e674..0000000
--- a/samza-kafka/src/test/scala/org/apache/samza/system/kafka_deprecated/TestBrokerProxy.scala
+++ /dev/null
@@ -1,434 +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.samza.system.kafka_deprecated
-
-import java.nio.ByteBuffer
-import java.util.concurrent.CountDownLatch
-
-import kafka.api.{PartitionOffsetsResponse, _}
-import kafka.common.TopicAndPartition
-import kafka.consumer.SimpleConsumer
-import kafka.message.{ByteBufferMessageSet, Message, MessageAndOffset, MessageSet}
-import org.apache.kafka.common.protocol.Errors
-import org.apache.samza.SamzaException
-import org.apache.samza.util.Logging
-import org.junit.Assert._
-import org.junit._
-import org.mockito.Matchers._
-import org.mockito.Mockito._
-import org.mockito.invocation.InvocationOnMock
-import org.mockito.stubbing.Answer
-import org.mockito.{Matchers, Mockito}
-
-import scala.collection.JavaConverters._
-
-class TestBrokerProxy extends Logging {
- val tp2 = new TopicAndPartition("Redbird", 2013)
- var fetchTp1 = true // control whether fetching tp1 messages or not
-
- @Test def brokerProxyRetrievesMessagesCorrectly() = {
- val (bp, tp, sink) = getMockBrokerProxy()
-
- bp.start
- bp.addTopicPartition(tp, Option("0"))
- // Add tp2, which should never receive messages since sink disables it.
- bp.addTopicPartition(tp2, Option("0"))
- Thread.sleep(1000)
- assertEquals(2, sink.receivedMessages.size)
- assertEquals(42, sink.receivedMessages(0)._2.offset)
- assertEquals(84, sink.receivedMessages(1)._2.offset)
- }
-
- @Test def brokerProxySkipsFetchForEmptyRequests() = {
- val (bp, tp, sink) = getMockBrokerProxy()
-
- bp.start
- // Only add tp2, which should never receive messages since sink disables it.
- bp.addTopicPartition(tp2, Option("0"))
- Thread.sleep(1000)
- assertEquals(0, sink.receivedMessages.size)
- assertTrue(bp.metrics.brokerSkippedFetchRequests.get((bp.host, bp.port)).getCount > 0)
- assertEquals(0, bp.metrics.brokerReads.get((bp.host, bp.port)).getCount)
- }
-
- @Test def brokerProxyThrowsExceptionOnDuplicateTopicPartitions() = {
- val (bp, tp, _) = getMockBrokerProxy()
- bp.start
- bp.addTopicPartition(tp, Option("0"))
-
- try {
- bp.addTopicPartition(tp, Option("1"))
- fail("Should have thrown an exception")
- } catch {
- case se: SamzaException => assertEquals(se.getMessage, "Already consuming TopicPartition [Redbird,2012]")
- case other: Exception => fail("Got some other exception than what we were expecting: " + other)
- }
- }
-
- def getMockBrokerProxy() = {
- val sink = new MessageSink {
- val receivedMessages = new scala.collection.mutable.ListBuffer[(TopicAndPartition, MessageAndOffset, Boolean)]()
-
- def abdicate(tp: TopicAndPartition, nextOffset: Long) {}
-
- def refreshDropped() {}
-
- def addMessage(tp: TopicAndPartition, msg: MessageAndOffset, highWatermark: Long) {
- receivedMessages += ((tp, msg, msg.offset.equals(highWatermark)))
- }
-
- def setIsAtHighWatermark(tp: TopicAndPartition, isAtHighWatermark: Boolean) {
- }
-
- // Never need messages for tp2.
- def needsMoreMessages(tp: TopicAndPartition): Boolean = !tp.equals(tp2) && fetchTp1
- }
-
- val system = "daSystem"
- val host = "host"
- val port = 2222
- val tp = new TopicAndPartition("Redbird", 2012)
- val metrics = new KafkaSystemConsumerMetrics(system)
-
- metrics.registerBrokerProxy(host, port)
- metrics.registerTopicAndPartition(tp)
- metrics.topicPartitions.get((host, port)).set(1)
-
- val bp = new BrokerProxy(
- host,
- port,
- system,
- "daClientId",
- metrics,
- sink,
- offsetGetter = new GetOffset("fail", Map("Redbird" -> "largest"))) {
-
- override val sleepMSWhileNoTopicPartitions = 100
- // Speed up for test
- var alreadyCreatedConsumer = false
-
- // Scala traits and Mockito mocks don't mix, unfortunately.
- override def createSimpleConsumer() = {
- if (alreadyCreatedConsumer) {
- System.err.println("Should only be creating one consumer in this test!")
- throw new InterruptedException("Should only be creating one consumer in this test!")
- }
- alreadyCreatedConsumer = true
-
- new DefaultFetchSimpleConsumer("a", 1, 2, 3, "b", new StreamFetchSizes(42)) {
- val sc = Mockito.mock(classOf[SimpleConsumer])
- val mockOffsetResponse = {
- val offsetResponse = Mockito.mock(classOf[OffsetResponse])
- val partitionOffsetResponse = {
- val por = Mockito.mock(classOf[PartitionOffsetsResponse])
- when(por.offsets).thenReturn(List(1l).toSeq)
- por
- }
-
- val map = scala.Predef.Map[TopicAndPartition, PartitionOffsetsResponse](tp -> partitionOffsetResponse, tp2 -> partitionOffsetResponse)
- when(offsetResponse.partitionErrorAndOffsets).thenReturn(map)
- offsetResponse
- }
-
- when(sc.getOffsetsBefore(any(classOf[OffsetRequest]))).thenReturn(mockOffsetResponse)
-
- val fetchResponse = {
- val fetchResponse = Mockito.mock(classOf[FetchResponse])
-
- val messageSet = {
- val messageSet = Mockito.mock(classOf[ByteBufferMessageSet])
-
- def getMessage() = new Message(Mockito.mock(classOf[ByteBuffer]))
- val messages = List(new MessageAndOffset(getMessage, 42), new MessageAndOffset(getMessage, 84))
-
- when(messageSet.sizeInBytes).thenReturn(43)
- when(messageSet.size).thenReturn(44)
- when(messageSet.iterator).thenReturn(messages.iterator)
- when(messageSet.head).thenReturn(messages.head)
- messageSet
- }
-
- val fetchResponsePartitionData = FetchResponsePartitionData(Errors.NONE, 500, messageSet)
- val map = scala.Predef.Map[TopicAndPartition, FetchResponsePartitionData](tp -> fetchResponsePartitionData)
-
- when(fetchResponse.data).thenReturn(map.toSeq)
- when(fetchResponse.messageSet(any(classOf[String]), any(classOf[Int]))).thenReturn(messageSet)
- fetchResponse
- }
- when(sc.fetch(any(classOf[FetchRequest]))).thenReturn(fetchResponse)
-
- override def close() = sc.close()
-
- override def send(request: TopicMetadataRequest): TopicMetadataResponse = sc.send(request)
-
- override def fetch(request: FetchRequest): FetchResponse = {
- // Verify that we only get fetch requests for one tp, even though
- // two were registered. This is to verify that
- // sink.needsMoreMessages works.
- assertEquals(1, request.requestInfo.size)
- sc.fetch(request)
- }
-
- when(sc.earliestOrLatestOffset(any(classOf[TopicAndPartition]), any(classOf[Long]), any(classOf[Int]))).thenReturn(100)
-
- override def getOffsetsBefore(request: OffsetRequest): OffsetResponse = sc.getOffsetsBefore(request)
-
- override def commitOffsets(request: OffsetCommitRequest): OffsetCommitResponse = sc.commitOffsets(request)
-
- override def fetchOffsets(request: OffsetFetchRequest): OffsetFetchResponse = sc.fetchOffsets(request)
-
- override def earliestOrLatestOffset(topicAndPartition: TopicAndPartition, earliestOrLatest: Long, consumerId: Int): Long = sc.earliestOrLatestOffset(topicAndPartition, earliestOrLatest, consumerId)
- }
- }
-
- }
-
- (bp, tp, sink)
- }
-
- @Test def brokerProxyUpdateLatencyMetrics() = {
- val (bp, tp, _) = getMockBrokerProxy()
-
- bp.start
- bp.addTopicPartition(tp, Option("0"))
- Thread.sleep(1000)
- // update when fetching messages
- assertEquals(500, bp.metrics.highWatermark.get(tp).getValue)
- assertEquals(415, bp.metrics.lag.get(tp).getValue)
-
- fetchTp1 = false
- Thread.sleep(1000)
- // update when not fetching messages
- assertEquals(100, bp.metrics.highWatermark.get(tp).getValue)
- assertEquals(15, bp.metrics.lag.get(tp).getValue)
-
- fetchTp1 = true
- }
-
- @Test def brokerProxyCorrectlyHandlesOffsetOutOfRange(): Unit = {
- // Need to wait for the thread to do some work before ending the test
- val countdownLatch = new CountDownLatch(1)
- var failString: String = null
-
- val mockMessageSink = mock(classOf[MessageSink])
- when(mockMessageSink.needsMoreMessages(any())).thenReturn(true)
-
- val doNothingMetrics = new KafkaSystemConsumerMetrics()
-
- val tp = new TopicAndPartition("topic", 42)
-
- val mockOffsetGetter = mock(classOf[GetOffset])
- // This will be used by the simple consumer below, and this is the response that simple consumer needs
- when(mockOffsetGetter.isValidOffset(any(classOf[DefaultFetchSimpleConsumer]), Matchers.eq(tp), Matchers.eq("0"))).thenReturn(true)
- when(mockOffsetGetter.getResetOffset(any(classOf[DefaultFetchSimpleConsumer]), Matchers.eq(tp))).thenReturn(1492l)
-
- var callsToCreateSimpleConsumer = 0
- val mockSimpleConsumer = mock(classOf[DefaultFetchSimpleConsumer])
-
- // Create an answer that first indicates offset out of range on first invocation and on second
- // verifies that the parameters have been updated to what we expect them to be
- val answer = new Answer[FetchResponse]() {
- var invocationCount = 0
-
- def answer(invocation: InvocationOnMock): FetchResponse = {
- val arguments = invocation.getArguments()(0).asInstanceOf[List[Object]](0).asInstanceOf[(String, Long)]
-
- if (invocationCount == 0) {
- if (arguments !=(tp, 0)) {
- failString = "First invocation did not have the right arguments: " + arguments
- countdownLatch.countDown()
- }
- val mfr = mock(classOf[FetchResponse])
- when(mfr.hasError).thenReturn(true)
- when(mfr.error("topic", 42)).thenReturn(Errors.OFFSET_OUT_OF_RANGE)
-
- val messageSet = mock(classOf[MessageSet])
- when(messageSet.iterator).thenReturn(Iterator.empty)
- val response = mock(classOf[FetchResponsePartitionData])
- when(response.error).thenReturn(Errors.OFFSET_OUT_OF_RANGE)
- val responseMap = Map(tp -> response)
- when(mfr.data).thenReturn(responseMap.toSeq)
- invocationCount += 1
- mfr
- } else {
- if (arguments !=(tp, 1492)) {
- failString = "On second invocation, arguments were not correct: " + arguments
- }
- countdownLatch.countDown()
- Thread.currentThread().interrupt()
- null
- }
- }
- }
-
- when(mockSimpleConsumer.defaultFetch(any())).thenAnswer(answer)
-
- // So now we have a fetch response that will fail. Prime the mockGetOffset to send us to a new offset
-
- val bp = new BrokerProxy("host", 423, "system", "clientID", doNothingMetrics, mockMessageSink, Int.MaxValue, 1024000, new StreamFetchSizes(256 * 1024), 524288, 1000, mockOffsetGetter) {
-
- override def createSimpleConsumer() = {
- if (callsToCreateSimpleConsumer > 1) {
- failString = "Tried to create more than one simple consumer"
- countdownLatch.countDown()
- }
- callsToCreateSimpleConsumer += 1
- mockSimpleConsumer
- }
- }
-
- bp.addTopicPartition(tp, Option("0"))
- bp.start
- countdownLatch.await()
- bp.stop
- if (failString != null) {
- fail(failString)
- }
- }
-
- /**
- * Test that makes sure that BrokerProxy abdicates all TopicAndPartitions
- * that it owns when a consumer failure occurs.
- */
- @Test def brokerProxyAbdicatesOnConnectionFailure(): Unit = {
- val countdownLatch = new CountDownLatch(1)
- var abdicated: Option[TopicAndPartition] = None
- @volatile var refreshDroppedCount = 0
- val mockMessageSink = new MessageSink {
- override def setIsAtHighWatermark(tp: TopicAndPartition, isAtHighWatermark: Boolean) {
- }
-
- override def addMessage(tp: TopicAndPartition, msg: MessageAndOffset, highWatermark: Long) {
- }
-
- override def abdicate(tp: TopicAndPartition, nextOffset: Long) {
- abdicated = Some(tp)
- countdownLatch.countDown
- }
-
- override def refreshDropped() {
- refreshDroppedCount += 1
- }
-
- override def needsMoreMessages(tp: TopicAndPartition): Boolean = {
- true
- }
- }
-
- val doNothingMetrics = new KafkaSystemConsumerMetrics()
- val tp = new TopicAndPartition("topic", 42)
- val mockOffsetGetter = mock(classOf[GetOffset])
- val mockSimpleConsumer = mock(classOf[DefaultFetchSimpleConsumer])
-
- when(mockOffsetGetter.isValidOffset(any(classOf[DefaultFetchSimpleConsumer]), Matchers.eq(tp), Matchers.eq("0"))).thenReturn(true)
- when(mockOffsetGetter.getResetOffset(any(classOf[DefaultFetchSimpleConsumer]), Matchers.eq(tp))).thenReturn(1492l)
- when(mockSimpleConsumer.defaultFetch(any())).thenThrow(new SamzaException("Pretend this is a ClosedChannelException. Can't use ClosedChannelException because it's checked, and Mockito doesn't like that."))
-
- val bp = new BrokerProxy("host", 567, "system", "clientID", doNothingMetrics, mockMessageSink, Int.MaxValue, 1024000, new StreamFetchSizes(256 * 1024), 524288, 1000, mockOffsetGetter) {
- override def createSimpleConsumer() = {
- mockSimpleConsumer
- }
- }
-
- val waitForRefresh = () => {
- val currentRefreshDroppedCount = refreshDroppedCount
- while (refreshDroppedCount == currentRefreshDroppedCount) {
- Thread.sleep(100)
- }
- }
-
- bp.addTopicPartition(tp, Option("0"))
- bp.start
- // BP should refresh on startup.
- waitForRefresh()
- countdownLatch.await()
- // BP should continue refreshing after it's abdicated all TopicAndPartitions.
- waitForRefresh()
- bp.stop
- assertEquals(tp, abdicated.getOrElse(null))
- }
-
- @Test def brokerProxyAbdicatesHardErrors(): Unit = {
- val doNothingMetrics = new KafkaSystemConsumerMetrics
- val mockMessageSink = new MessageSink {
- override def needsMoreMessages(tp: TopicAndPartition): Boolean = true
- override def abdicate(tp: TopicAndPartition, nextOffset: Long) {}
- override def addMessage(tp: TopicAndPartition, msg: MessageAndOffset, highWatermark: Long) {}
- override def refreshDropped() {throw new OutOfMemoryError("Test - OOME")}
- override def setIsAtHighWatermark(tp: TopicAndPartition, isAtHighWatermark: Boolean): Unit = {}
- }
- val mockOffsetGetter = mock(classOf[GetOffset])
- val mockSimpleConsumer = mock(classOf[DefaultFetchSimpleConsumer])
-
- val bp = new BrokerProxy("host", 658, "system", "clientID", doNothingMetrics, mockMessageSink, Int.MaxValue, 1024000, new StreamFetchSizes(256 * 1024), 524288, 1000, mockOffsetGetter) {
- override def createSimpleConsumer() = {
- mockSimpleConsumer
- }
- }
- var caughtError = false
- try {
- bp.thread.run
- } catch {
- case e: SamzaException => {
- assertEquals(e.getMessage, "Got out of memory error in broker proxy thread.")
- info("Received OutOfMemoryError in broker proxy.")
- caughtError = true
- }
- }
- assertEquals(true, caughtError)
- val mockMessageSink2 = new MessageSink {
- override def needsMoreMessages(tp: TopicAndPartition): Boolean = true
- override def abdicate(tp: TopicAndPartition, nextOffset: Long): Unit = {}
- override def addMessage(tp: TopicAndPartition, msg: MessageAndOffset, highWatermark: Long): Unit = {}
- override def refreshDropped(): Unit = {throw new StackOverflowError("Test - SOE")}
- override def setIsAtHighWatermark(tp: TopicAndPartition, isAtHighWatermark: Boolean): Unit = {}
- }
- caughtError = false
- val bp2 = new BrokerProxy("host", 689, "system", "clientID2", doNothingMetrics, mockMessageSink2, Int.MaxValue, 1024000, new StreamFetchSizes(256 * 1024), 524288, 1000, mockOffsetGetter) {
- override def createSimpleConsumer() = {
- mockSimpleConsumer
- }
- }
- try {
- bp2.thread.run
- } catch {
- case e: SamzaException => {
- assertEquals(e.getMessage, "Got stack overflow error in broker proxy thread.")
- info("Received StackOverflowError in broker proxy.")
- caughtError = true
- }
- }
- assertEquals(true, caughtError)
- }
-
- @Test
- def brokerProxyStopCloseConsumer: Unit = {
- val mockSimpleConsumer = mock(classOf[DefaultFetchSimpleConsumer])
- val bp = new BrokerProxy("host", 0, "system", "clientID", new KafkaSystemConsumerMetrics(), null){
- override def createSimpleConsumer() = {
- mockSimpleConsumer
- }
- }
- bp.start
- bp.stop
- verify(mockSimpleConsumer).close
- }
-}
diff --git a/samza-kafka/src/test/scala/org/apache/samza/system/kafka_deprecated/TestGetOffset.scala b/samza-kafka/src/test/scala/org/apache/samza/system/kafka_deprecated/TestGetOffset.scala
deleted file mode 100644
index 21ee4cd..0000000
--- a/samza-kafka/src/test/scala/org/apache/samza/system/kafka_deprecated/TestGetOffset.scala
+++ /dev/null
@@ -1,110 +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.samza.system.kafka_deprecated
-
-import java.nio.ByteBuffer
-
-import kafka.api._
-import kafka.common.TopicAndPartition
-import kafka.consumer.SimpleConsumer
-import kafka.message.Message
-import kafka.message.ByteBufferMessageSet
-import org.apache.kafka.common.errors.OffsetOutOfRangeException
-import org.junit._
-import org.junit.Assert._
-import org.mockito.Mockito
-import org.mockito.Mockito._
-import org.mockito.Matchers._
-import org.mockito.invocation.InvocationOnMock
-import org.mockito.stubbing.Answer
-
-class TestGetOffset {
-
- private val outOfRangeOffset : String = "0"
-
- /**
- * An empty message set is still a valid offset. It just means that the
- * offset was for the upcoming message, which hasn't yet been written. The
- * fetch request times out in such a case, and an empty message set is
- * returned.
- */
- @Test
- def testIsValidOffsetWorksWithEmptyMessageSet {
- val getOffset = new GetOffset(OffsetRequest.LargestTimeString)
- // Should not throw an exception.
- assertTrue(getOffset.isValidOffset(getMockDefaultFetchSimpleConsumer, TopicAndPartition("foo", 1), "1234"))
- }
-
- /**
- * An empty message set is still a valid offset. It just means that the
- * offset was for the upcoming message, which hasn't yet been written. The
- * fetch request times out in such a case, and an empty message set is
- * returned.
- */
- @Test
- def testIsValidOffsetWorksWithOffsetOutOfRangeException {
- val getOffset = new GetOffset(OffsetRequest.LargestTimeString)
- // Should not throw an exception.
- assertFalse(getOffset.isValidOffset(getMockDefaultFetchSimpleConsumer, TopicAndPartition("foo", 1), outOfRangeOffset))
- }
-
- /**
- * Create a default fetch simple consumer that returns empty message sets.
- */
- def getMockDefaultFetchSimpleConsumer = {
- new DefaultFetchSimpleConsumer("", 0, 0, 0, "") {
- val sc = Mockito.mock(classOf[SimpleConsumer])
-
- // Build an empty fetch response.
- val fetchResponse = {
- val fetchResponse = Mockito.mock(classOf[FetchResponse])
- val messageSet = {
- val messageSet = Mockito.mock(classOf[ByteBufferMessageSet])
- val messages = List()
-
- def getMessage() = new Message(Mockito.mock(classOf[ByteBuffer]))
-
- when(messageSet.sizeInBytes).thenReturn(0)
- when(messageSet.size).thenReturn(0)
- when(messageSet.iterator).thenReturn(messages.iterator)
-
- messageSet
- }
- when(fetchResponse.messageSet(any(classOf[String]), any(classOf[Int]))).thenReturn(messageSet)
-
- fetchResponse
- }
-
- doAnswer(new Answer[FetchResponse] {
- override def answer(invocation: InvocationOnMock): FetchResponse = {
- if (invocation.getArgumentAt(0, classOf[FetchRequest]).requestInfo.exists(
- req => req._2.offset.toString.equals(outOfRangeOffset))) {
- throw new OffsetOutOfRangeException("test exception")
- }
- fetchResponse
- }
- }).when(sc).fetch(any(classOf[FetchRequest]))
-
- override def fetch(request: FetchRequest): FetchResponse = {
- sc.fetch(request)
- }
- }
- }
-}
diff --git a/samza-kafka/src/test/scala/org/apache/samza/system/kafka_deprecated/TestKafkaSystemAdmin.scala b/samza-kafka/src/test/scala/org/apache/samza/system/kafka_deprecated/TestKafkaSystemAdmin.scala
deleted file mode 100644
index 93dad09..0000000
--- a/samza-kafka/src/test/scala/org/apache/samza/system/kafka_deprecated/TestKafkaSystemAdmin.scala
+++ /dev/null
@@ -1,310 +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.samza.system.kafka_deprecated
-
-import java.util.{Properties, UUID}
-
-import kafka.admin.AdminUtils
-import org.apache.kafka.common.errors.LeaderNotAvailableException
-import org.apache.kafka.common.protocol.Errors
-import kafka.consumer.{Consumer, ConsumerConfig, ConsumerConnector}
-import kafka.integration.KafkaServerTestHarness
-import kafka.server.KafkaConfig
-import kafka.utils.{TestUtils, ZkUtils}
-import org.apache.kafka.clients.producer.{KafkaProducer, ProducerRecord}
-import org.apache.kafka.common.security.JaasUtils
-import org.apache.samza.Partition
-import org.apache.samza.config.KafkaProducerConfig
-import org.apache.samza.system.SystemStreamMetadata.SystemStreamPartitionMetadata
-import org.apache.samza.system.{StreamSpec, SystemStreamMetadata, SystemStreamPartition}
-import org.apache.samza.util.{ClientUtilTopicMetadataStore, ExponentialSleepStrategy, KafkaUtil, TopicMetadataStore}
-import org.junit.Assert._
-import org.junit._
-
-import scala.collection.JavaConverters._
-
-/**
- * README: New tests should be added to the Java tests. See TestKafkaSystemAdminJava
- */
-object TestKafkaSystemAdmin extends KafkaServerTestHarness {
-
- val SYSTEM = "kafka"
- val TOPIC = "input"
- val TOPIC2 = "input2"
- val TOTAL_PARTITIONS = 50
- val REPLICATION_FACTOR = 2
- val zkSecure = JaasUtils.isZkSecurityEnabled()
-
- protected def numBrokers: Int = 3
-
- var producer: KafkaProducer[Array[Byte], Array[Byte]] = null
- var metadataStore: TopicMetadataStore = null
- var producerConfig: KafkaProducerConfig = null
- var systemAdmin: KafkaSystemAdmin = null
-
- override def generateConfigs(): Seq[KafkaConfig] = {
- val props = TestUtils.createBrokerConfigs(numBrokers, zkConnect, true)
- props.map(KafkaConfig.fromProps)
- }
-
- @BeforeClass
- override def setUp() {
- super.setUp()
- val config = new java.util.HashMap[String, String]()
- config.put("bootstrap.servers", brokerList)
- config.put("acks", "all")
- config.put("serializer.class", "kafka.serializer.StringEncoder")
- producerConfig = new KafkaProducerConfig("kafka", "i001", config)
- producer = new KafkaProducer[Array[Byte], Array[Byte]](producerConfig.getProducerProperties)
- metadataStore = new ClientUtilTopicMetadataStore(brokerList, "some-job-name")
- systemAdmin = new KafkaSystemAdmin(SYSTEM, brokerList, connectZk = () => ZkUtils(zkConnect, 6000, 6000, zkSecure))
- systemAdmin.start()
- }
-
- @AfterClass
- override def tearDown() {
- systemAdmin.stop()
- producer.close()
- super.tearDown()
- }
-
- def createTopic(topicName: String, partitionCount: Int) {
- AdminUtils.createTopic(
- zkUtils,
- topicName,
- partitionCount,
- REPLICATION_FACTOR)
- }
-
- def validateTopic(topic: String, expectedPartitionCount: Int) {
- var done = false
- var retries = 0
- val maxRetries = 100
-
- while (!done && retries < maxRetries) {
- try {
- val topicMetadataMap = TopicMetadataCache.getTopicMetadata(Set(topic), SYSTEM, metadataStore.getTopicInfo)
- val topicMetadata = topicMetadataMap(topic)
-
- KafkaUtil.maybeThrowException(topicMetadata.error.exception())
-
- done = expectedPartitionCount == topicMetadata.partitionsMetadata.size
- } catch {
- case e: Exception =>
- System.err.println("Got exception while validating test topics. Waiting and retrying.", e)
- retries += 1
- Thread.sleep(500)
- }
- }
-
- if (retries >= maxRetries) {
- fail("Unable to successfully create topics. Tried to validate %s times." format retries)
- }
- }
-
- def getConsumerConnector(): ConsumerConnector = {
- val props = new Properties
-
- props.put("zookeeper.connect", zkConnect)
- props.put("group.id", "test")
- props.put("auto.offset.reset", "smallest")
-
- val consumerConfig = new ConsumerConfig(props)
- Consumer.create(consumerConfig)
- }
-
- def createSystemAdmin(coordinatorStreamProperties: Properties, coordinatorStreamReplicationFactor: Int, topicMetaInformation: Map[String, ChangelogInfo]): KafkaSystemAdmin = {
- new KafkaSystemAdmin(SYSTEM, brokerList, connectZk = () => ZkUtils(zkConnect, 6000, 6000, zkSecure), coordinatorStreamProperties,
- coordinatorStreamReplicationFactor, 10000, ConsumerConfig.SocketBufferSize, UUID.randomUUID.toString, topicMetaInformation, Map(), false)
- }
-
-}
-
-/**
- * Test creates a local ZK and Kafka cluster, and uses it to create and test
- * topics for to verify that offset APIs in SystemAdmin work as expected.
- */
-class TestKafkaSystemAdmin {
- import TestKafkaSystemAdmin._
-
- @Test
- def testShouldAssembleMetadata {
- val oldestOffsets = Map(
- new SystemStreamPartition(SYSTEM, "stream1", new Partition(0)) -> "o1",
- new SystemStreamPartition(SYSTEM, "stream2", new Partition(0)) -> "o2",
- new SystemStreamPartition(SYSTEM, "stream1", new Partition(1)) -> "o3",
- new SystemStreamPartition(SYSTEM, "stream2", new Partition(1)) -> "o4")
- val newestOffsets = Map(
- new SystemStreamPartition(SYSTEM, "stream1", new Partition(0)) -> "n1",
- new SystemStreamPartition(SYSTEM, "stream2", new Partition(0)) -> "n2",
- new SystemStreamPartition(SYSTEM, "stream1", new Partition(1)) -> "n3",
- new SystemStreamPartition(SYSTEM, "stream2", new Partition(1)) -> "n4")
- val upcomingOffsets = Map(
- new SystemStreamPartition(SYSTEM, "stream1", new Partition(0)) -> "u1",
- new SystemStreamPartition(SYSTEM, "stream2", new Partition(0)) -> "u2",
- new SystemStreamPartition(SYSTEM, "stream1", new Partition(1)) -> "u3",
- new SystemStreamPartition(SYSTEM, "stream2", new Partition(1)) -> "u4")
- val metadata = KafkaSystemAdmin.assembleMetadata(oldestOffsets, newestOffsets, upcomingOffsets)
- assertNotNull(metadata)
- assertEquals(2, metadata.size)
- assertTrue(metadata.contains("stream1"))
- assertTrue(metadata.contains("stream2"))
- val stream1Metadata = metadata("stream1")
- val stream2Metadata = metadata("stream2")
- assertNotNull(stream1Metadata)
- assertNotNull(stream2Metadata)
- assertEquals("stream1", stream1Metadata.getStreamName)
- assertEquals("stream2", stream2Metadata.getStreamName)
- val expectedSystemStream1Partition0Metadata = new SystemStreamPartitionMetadata("o1", "n1", "u1")
- val expectedSystemStream1Partition1Metadata = new SystemStreamPartitionMetadata("o3", "n3", "u3")
- val expectedSystemStream2Partition0Metadata = new SystemStreamPartitionMetadata("o2", "n2", "u2")
- val expectedSystemStream2Partition1Metadata = new SystemStreamPartitionMetadata("o4", "n4", "u4")
- val stream1PartitionMetadata = stream1Metadata.getSystemStreamPartitionMetadata
- val stream2PartitionMetadata = stream2Metadata.getSystemStreamPartitionMetadata
- assertEquals(expectedSystemStream1Partition0Metadata, stream1PartitionMetadata.get(new Partition(0)))
- assertEquals(expectedSystemStream1Partition1Metadata, stream1PartitionMetadata.get(new Partition(1)))
- assertEquals(expectedSystemStream2Partition0Metadata, stream2PartitionMetadata.get(new Partition(0)))
- assertEquals(expectedSystemStream2Partition1Metadata, stream2PartitionMetadata.get(new Partition(1)))
- }
-
- @Test
- def testShouldGetOldestNewestAndNextOffsets {
- // Create an empty topic with 50 partitions, but with no offsets.
- createTopic(TOPIC, 50)
- validateTopic(TOPIC, 50)
-
- // Verify the empty topic behaves as expected.
- var metadata = systemAdmin.getSystemStreamMetadata(Set(TOPIC).asJava)
- assertEquals(1, metadata.size)
- assertNotNull(metadata.get(TOPIC))
- // Verify partition count.
- var sspMetadata = metadata.get(TOPIC).getSystemStreamPartitionMetadata
- assertEquals(50, sspMetadata.size)
- // Empty topics should have null for latest offset and 0 for earliest offset
- assertEquals("0", sspMetadata.get(new Partition(0)).getOldestOffset)
- assertNull(sspMetadata.get(new Partition(0)).getNewestOffset)
- // Empty Kafka topics should have a next offset of 0.
- assertEquals("0", sspMetadata.get(new Partition(0)).getUpcomingOffset)
-
- // Add a new message to one of the partitions, and verify that it works as
- // expected.
- producer.send(new ProducerRecord(TOPIC, 48, "key1".getBytes, "val1".getBytes)).get()
- metadata = systemAdmin.getSystemStreamMetadata(Set(TOPIC).asJava)
- assertEquals(1, metadata.size)
- val streamName = metadata.keySet.asScala.head
- assertEquals(TOPIC, streamName)
- sspMetadata = metadata.get(streamName).getSystemStreamPartitionMetadata
- // key1 gets hash-mod'd to partition 48.
- assertEquals("0", sspMetadata.get(new Partition(48)).getOldestOffset)
- assertEquals("0", sspMetadata.get(new Partition(48)).getNewestOffset)
- assertEquals("1", sspMetadata.get(new Partition(48)).getUpcomingOffset)
- // Some other partition should be empty.
- assertEquals("0", sspMetadata.get(new Partition(3)).getOldestOffset)
- assertNull(sspMetadata.get(new Partition(3)).getNewestOffset)
- assertEquals("0", sspMetadata.get(new Partition(3)).getUpcomingOffset)
-
- // Add a second message to one of the same partition.
- producer.send(new ProducerRecord(TOPIC, 48, "key1".getBytes, "val2".getBytes)).get()
- metadata = systemAdmin.getSystemStreamMetadata(Set(TOPIC).asJava)
- assertEquals(1, metadata.size)
- assertEquals(TOPIC, streamName)
- sspMetadata = metadata.get(streamName).getSystemStreamPartitionMetadata
- // key1 gets hash-mod'd to partition 48.
- assertEquals("0", sspMetadata.get(new Partition(48)).getOldestOffset)
- assertEquals("1", sspMetadata.get(new Partition(48)).getNewestOffset)
- assertEquals("2", sspMetadata.get(new Partition(48)).getUpcomingOffset)
-
- // Validate that a fetch will return the message.
- val connector = getConsumerConnector
- var stream = connector.createMessageStreams(Map(TOPIC -> 1))(TOPIC).head.iterator
- var message = stream.next
- var text = new String(message.message, "UTF-8")
- connector.shutdown
- // First message should match the earliest expected offset.
- assertEquals(sspMetadata.get(new Partition(48)).getOldestOffset, message.offset.toString)
- assertEquals("val1", text)
- // Second message should match the earliest expected offset.
- message = stream.next
- text = new String(message.message, "UTF-8")
- assertEquals(sspMetadata.get(new Partition(48)).getNewestOffset, message.offset.toString)
- assertEquals("val2", text)
- }
-
- @Test
- def testNonExistentTopic {
- val initialOffsets = systemAdmin.getSystemStreamMetadata(Set("non-existent-topic").asJava)
- val metadata = initialOffsets.asScala.getOrElse("non-existent-topic", fail("missing metadata"))
- assertEquals(metadata, new SystemStreamMetadata("non-existent-topic", Map(
- new Partition(0) -> new SystemStreamPartitionMetadata("0", null, "0")).asJava))
- }
-
- @Test
- def testOffsetsAfter {
- val ssp1 = new SystemStreamPartition("test-system", "test-stream", new Partition(0))
- val ssp2 = new SystemStreamPartition("test-system", "test-stream", new Partition(1))
- val offsetsAfter = systemAdmin.getOffsetsAfter(Map(
- ssp1 -> "1",
- ssp2 -> "2").asJava)
- assertEquals("2", offsetsAfter.get(ssp1))
- assertEquals("3", offsetsAfter.get(ssp2))
- }
-
- @Test
- def testShouldCreateCoordinatorStream {
- val topic = "test-coordinator-stream"
- val systemAdmin = new KafkaSystemAdmin(SYSTEM, brokerList, () => ZkUtils(zkConnect, 6000, 6000, zkSecure), coordinatorStreamReplicationFactor = 3)
-
- val spec = StreamSpec.createCoordinatorStreamSpec(topic, "kafka")
- systemAdmin.createStream(spec)
- validateTopic(topic, 1)
- val topicMetadataMap = TopicMetadataCache.getTopicMetadata(Set(topic), "kafka", metadataStore.getTopicInfo)
- assertTrue(topicMetadataMap.contains(topic))
- val topicMetadata = topicMetadataMap(topic)
- val partitionMetadata = topicMetadata.partitionsMetadata.head
- assertEquals(0, partitionMetadata.partitionId)
- assertEquals(3, partitionMetadata.replicas.size)
- }
-
- class KafkaSystemAdminWithTopicMetadataError extends KafkaSystemAdmin(SYSTEM, brokerList, () => ZkUtils(zkConnect, 6000, 6000, zkSecure)) {
- import kafka.api.TopicMetadata
- var metadataCallCount = 0
-
- // Simulate Kafka telling us that the leader for the topic is not available
- override def getTopicMetadata(topics: Set[String]) = {
- metadataCallCount += 1
- val topicMetadata = TopicMetadata(topic = "quux", partitionsMetadata = Seq(), error = Errors.LEADER_NOT_AVAILABLE)
- Map("quux" -> topicMetadata)
- }
- }
-
- @Test
- def testShouldRetryOnTopicMetadataError {
- val systemAdmin = new KafkaSystemAdminWithTopicMetadataError
- val retryBackoff = new ExponentialSleepStrategy.Mock(maxCalls = 3)
- try {
- systemAdmin.getSystemStreamMetadata(Set("quux").asJava, retryBackoff)
- fail("expected CallLimitReached to be thrown")
- } catch {
- case e: ExponentialSleepStrategy.CallLimitReached => ()
- }
- }
-}
diff --git a/samza-kafka/src/test/scala/org/apache/samza/system/kafka_deprecated/TestKafkaSystemConsumer.scala b/samza-kafka/src/test/scala/org/apache/samza/system/kafka_deprecated/TestKafkaSystemConsumer.scala
deleted file mode 100644
index ac37619..0000000
--- a/samza-kafka/src/test/scala/org/apache/samza/system/kafka_deprecated/TestKafkaSystemConsumer.scala
+++ /dev/null
@@ -1,191 +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.samza.system.kafka_deprecated
-
-import kafka.api.TopicMetadata
-import kafka.api.PartitionMetadata
-import kafka.cluster.Broker
-import kafka.common.TopicAndPartition
-import kafka.message.Message
-import kafka.message.MessageAndOffset
-import org.apache.kafka.common.protocol.Errors
-import org.apache.samza.system.IncomingMessageEnvelope
-import org.apache.samza.system.SystemStreamPartition
-import org.apache.samza.Partition
-import org.apache.samza.util.TopicMetadataStore
-import org.junit.Test
-import org.junit.Assert._
-import org.apache.samza.system.SystemAdmin
-import org.mockito.Mockito._
-import org.mockito.Matchers._
-
-class TestKafkaSystemConsumer {
- val systemAdmin: SystemAdmin = mock(classOf[KafkaSystemAdmin])
- private val SSP: SystemStreamPartition = new SystemStreamPartition("test", "test", new Partition(0))
- private val envelope: IncomingMessageEnvelope = new IncomingMessageEnvelope(SSP, null, null, null)
- private val envelopeWithSize: IncomingMessageEnvelope = new IncomingMessageEnvelope(SSP, null, null, null, 100)
- private val clientId = "TestClientId"
-
- @Test
- def testFetchThresholdShouldDivideEvenlyAmongPartitions {
- val metadataStore = new MockMetadataStore
- val consumer = new KafkaSystemConsumer("", systemAdmin, new KafkaSystemConsumerMetrics, metadataStore, clientId, fetchThreshold = 50000) {
- override def refreshBrokers {
- }
- }
-
- for (i <- 0 until 50) {
- consumer.register(new SystemStreamPartition("test-system", "test-stream", new Partition(i)), "0")
- }
-
- consumer.start
-
- assertEquals(1000, consumer.perPartitionFetchThreshold)
- }
-
- @Test
- def testBrokerCreationShouldTriggerStart {
- val systemName = "test-system"
- val streamName = "test-stream"
- val metrics = new KafkaSystemConsumerMetrics
- // Lie and tell the store that the partition metadata is empty. We can't
- // use partition metadata because it has Broker in its constructor, which
- // is package private to Kafka.
- val metadataStore = new MockMetadataStore(Map(streamName -> TopicMetadata(streamName, Seq.empty, Errors.NONE)))
- var hosts = List[String]()
- var getHostPortCount = 0
- val consumer = new KafkaSystemConsumer(systemName, systemAdmin, metrics, metadataStore, clientId) {
- override def getLeaderHostPort(partitionMetadata: Option[PartitionMetadata]): Option[(String, Int)] = {
- // Generate a unique host every time getHostPort is called.
- getHostPortCount += 1
- Some("localhost-%s" format getHostPortCount, 0)
- }
-
- override def createBrokerProxy(host: String, port: Int): BrokerProxy = {
- new BrokerProxy(host, port, systemName, "", metrics, sink) {
- override def addTopicPartition(tp: TopicAndPartition, nextOffset: Option[String]) = {
- // Skip this since we normally do verification of offsets, which
- // tries to connect to Kafka. Rather than mock that, just forget it.
- nextOffsets.size
- }
-
- override def start {
- hosts :+= host
- }
- }
- }
- }
-
- consumer.register(new SystemStreamPartition(systemName, streamName, new Partition(0)), "1")
- assertEquals(0, hosts.size)
- consumer.start
- assertEquals(List("localhost-1"), hosts)
- // Should trigger a refresh with a new host.
- consumer.sink.abdicate(new TopicAndPartition(streamName, 0), 2)
- assertEquals(List("localhost-1", "localhost-2"), hosts)
- }
-
- @Test
- def testConsumerRegisterOlderOffsetOfTheSamzaSSP {
- when(systemAdmin.offsetComparator(anyString, anyString)).thenCallRealMethod()
-
- val metadataStore = new MockMetadataStore
- val consumer = new KafkaSystemConsumer("", systemAdmin, new KafkaSystemConsumerMetrics, metadataStore, clientId, fetchThreshold = 50000)
- val ssp0 = new SystemStreamPartition("test-system", "test-stream", new Partition(0))
- val ssp1 = new SystemStreamPartition("test-system", "test-stream", new Partition(1))
- val ssp2 = new SystemStreamPartition("test-system", "test-stream", new Partition(2))
-
- consumer.register(ssp0, "0")
- consumer.register(ssp0, "5")
- consumer.register(ssp1, "2")
- consumer.register(ssp1, "3")
- consumer.register(ssp2, "0")
-
- assertEquals("0", consumer.topicPartitionsAndOffsets(KafkaSystemConsumer.toTopicAndPartition(ssp0)))
- assertEquals("2", consumer.topicPartitionsAndOffsets(KafkaSystemConsumer.toTopicAndPartition(ssp1)))
- assertEquals("0", consumer.topicPartitionsAndOffsets(KafkaSystemConsumer.toTopicAndPartition(ssp2)))
- }
-
- @Test
- def testFetchThresholdBytesShouldDivideEvenlyAmongPartitions {
- val metadataStore = new MockMetadataStore
- val consumer = new KafkaSystemConsumer("", systemAdmin, new KafkaSystemConsumerMetrics, metadataStore, clientId,
- fetchThreshold = 50000, fetchThresholdBytes = 60000L, fetchLimitByBytesEnabled = true) {
- override def refreshBrokers {
- }
- }
-
- for (i <- 0 until 10) {
- consumer.register(new SystemStreamPartition("test-system", "test-stream", new Partition(i)), "0")
- }
-
- consumer.start
-
- assertEquals(5000, consumer.perPartitionFetchThreshold)
- assertEquals(3000, consumer.perPartitionFetchThresholdBytes)
- }
-
- @Test
- def testFetchThresholdBytes {
- val metadataStore = new MockMetadataStore
- val consumer = new KafkaSystemConsumer("test-system", systemAdmin, new KafkaSystemConsumerMetrics, metadataStore, clientId,
- fetchThreshold = 50000, fetchThresholdBytes = 60000L, fetchLimitByBytesEnabled = true) {
- override def refreshBrokers {
- }
- }
-
- for (i <- 0 until 10) {
- consumer.register(new SystemStreamPartition("test-system", "test-stream", new Partition(i)), "0")
- }
-
- consumer.start
-
- val msg = Array[Byte](5, 112, 9, 126)
- val msgAndOffset: MessageAndOffset = MessageAndOffset(new Message(msg), 887654)
- // 4 data + 18 Message overhead + 80 IncomingMessageEnvelope overhead
- consumer.sink.addMessage(new TopicAndPartition("test-stream", 0), msgAndOffset, 887354)
-
- assertEquals(106, consumer.getMessagesSizeInQueue(new SystemStreamPartition("test-system", "test-stream", new Partition(0))))
- }
-
- @Test
- def testFetchThresholdBytesDisabled {
- val metadataStore = new MockMetadataStore
- val consumer = new KafkaSystemConsumer("", systemAdmin, new KafkaSystemConsumerMetrics, metadataStore, clientId,
- fetchThreshold = 50000, fetchThresholdBytes = 60000L) {
- override def refreshBrokers {
- }
- }
-
- for (i <- 0 until 10) {
- consumer.register(new SystemStreamPartition("test-system", "test-stream", new Partition(i)), "0")
- }
-
- consumer.start
-
- assertEquals(5000, consumer.perPartitionFetchThreshold)
- assertEquals(0, consumer.perPartitionFetchThresholdBytes)
- assertEquals(0, consumer.getMessagesSizeInQueue(new SystemStreamPartition("test-system", "test-stream", new Partition(0))))
- }
-}
-
-class MockMetadataStore(var metadata: Map[String, TopicMetadata] = Map()) extends TopicMetadataStore {
- def getTopicInfo(topics: Set[String]): Map[String, TopicMetadata] = metadata
-}
diff --git a/samza-kafka/src/test/scala/org/apache/samza/system/kafka_deprecated/TestKafkaSystemFactory.scala b/samza-kafka/src/test/scala/org/apache/samza/system/kafka_deprecated/TestKafkaSystemFactory.scala
deleted file mode 100644
index 41a48f3..0000000
--- a/samza-kafka/src/test/scala/org/apache/samza/system/kafka_deprecated/TestKafkaSystemFactory.scala
+++ /dev/null
@@ -1,98 +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.samza.system.kafka_deprecated
-
-import org.apache.samza.SamzaException
-import org.apache.samza.config.MapConfig
-import org.apache.samza.config.StorageConfig
-import org.apache.samza.metrics.MetricsRegistryMap
-import org.junit.Assert._
-import org.junit.Test
-
-import scala.collection.JavaConverters._
-
-class TestKafkaSystemFactory {
- @Test
- def testFailWhenNoSerdeDefined {
- val producerFactory = new KafkaSystemFactory
- try {
- producerFactory.getProducer(
- "test",
- new MapConfig(Map[String, String]().asJava),
- new MetricsRegistryMap)
- fail("Expected to get a Samza exception.")
- } catch {
- case e: SamzaException => None // expected
- case e: Exception => fail("Expected SamzaException, but got " + e)
- }
- }
-
- @Test
- def testFailWhenSerdeIsInvalid {
- val producerFactory = new KafkaSystemFactory
- val config = new MapConfig(Map[String, String](
- "streams.test.serde" -> "failme").asJava)
- try {
- producerFactory.getProducer(
- "test",
- config,
- new MetricsRegistryMap)
- fail("Expected to get a Samza exception.")
- } catch {
- case e: SamzaException => None // expected
- case e: Exception => fail("Expected SamzaException, but got " + e)
- }
- }
-
- @Test
- def testHappyPath {
- val producerFactory = new KafkaSystemFactory
- val config = new MapConfig(Map[String, String](
- "job.name" -> "test",
- "systems.test.producer.bootstrap.servers" -> "",
- "systems.test.samza.key.serde" -> "json",
- "systems.test.samza.msg.serde" -> "json",
- "serializers.registry.json.class" -> "samza.serializers.JsonSerdeFactory").asJava)
- var producer = producerFactory.getProducer(
- "test",
- config,
- new MetricsRegistryMap)
- assertNotNull(producer)
- assertTrue(producer.isInstanceOf[KafkaSystemProducer])
- producer = producerFactory.getProducer(
- "test",
- config,
- new MetricsRegistryMap)
- assertNotNull(producer)
- assertTrue(producer.isInstanceOf[KafkaSystemProducer])
- }
-
- @Test
- def testInjectedProducerProps {
- val configMap = Map[String, String](
- StorageConfig.FACTORY.format("system1") -> "some.factory.Class",
- StorageConfig.CHANGELOG_STREAM.format("system1") -> "system1.stream1",
- StorageConfig.FACTORY.format("system2") -> "some.factory.Class")
- val config = new MapConfig(configMap.asJava)
- assertEquals(Map[String, String](), KafkaSystemFactory.getInjectedProducerProperties("system3", config))
- assertEquals(Map[String, String](), KafkaSystemFactory.getInjectedProducerProperties("system2", config))
- assertEquals(Map[String, String]("compression.type" -> "none"), KafkaSystemFactory.getInjectedProducerProperties("system1", config))
- }
-}
diff --git a/samza-kafka/src/test/scala/org/apache/samza/system/kafka_deprecated/TestKafkaSystemProducer.scala b/samza-kafka/src/test/scala/org/apache/samza/system/kafka_deprecated/TestKafkaSystemProducer.scala
deleted file mode 100644
index 16a1287..0000000
--- a/samza-kafka/src/test/scala/org/apache/samza/system/kafka_deprecated/TestKafkaSystemProducer.scala
+++ /dev/null
@@ -1,604 +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.samza.system.kafka_deprecated
-
-import org.apache.kafka.clients.producer._
-import org.apache.kafka.common.errors.{RecordTooLargeException, SerializationException, TimeoutException}
-import org.apache.kafka.test.MockSerializer
-import org.apache.samza.system.kafka.MockKafkaProducer
-import org.apache.samza.system.{OutgoingMessageEnvelope, SystemProducerException, SystemStream}
-import org.junit.Assert._
-import org.junit.Test
-import org.scalatest.Assertions.intercept
-
-
-class TestKafkaSystemProducer {
- val systemStream = new SystemStream("testSystem", "testStream")
- val someMessage = new OutgoingMessageEnvelope(systemStream, "test".getBytes)
-
- @Test
- def testKafkaProducer {
- val mockProducer = new MockProducer(true, new MockSerializer, new MockSerializer)
- val systemProducer = new KafkaSystemProducer(systemName = "test",
- getProducer = () => mockProducer,
- metrics = new KafkaSystemProducerMetrics)
- systemProducer.register("test")
- systemProducer.start
- systemProducer.send("test", someMessage)
- assertEquals(1, systemProducer.producerRef.get().asInstanceOf[MockProducer[Array[Byte], Array[Byte]]].history().size())
- systemProducer.stop
- }
-
- @Test
- def testKafkaProducerUsingMockKafkaProducer {
- val mockProducer = new MockKafkaProducer(1, "test", 1)
- val systemProducer = new KafkaSystemProducer(systemName = "test",
- getProducer = () => mockProducer,
- metrics = new KafkaSystemProducerMetrics)
- systemProducer.register("test")
- systemProducer.start()
- systemProducer.send("test", someMessage)
- assertEquals(1, mockProducer.getMsgsSent)
- systemProducer.stop()
- }
-
- @Test
- def testKafkaProducerBufferedSend {
- val msg1 = new OutgoingMessageEnvelope(systemStream, "a".getBytes)
- val msg2 = new OutgoingMessageEnvelope(systemStream, "b".getBytes)
- val msg3 = new OutgoingMessageEnvelope(systemStream, "c".getBytes)
-
- val mockProducer = new MockKafkaProducer(1, "test", 1)
- val producerMetrics = new KafkaSystemProducerMetrics
- val systemProducer = new KafkaSystemProducer(systemName = "test",
- getProducer = () => mockProducer,
- metrics = producerMetrics)
- systemProducer.register("test")
- systemProducer.start()
- systemProducer.send("test", msg1)
-
- mockProducer.setShouldBuffer(true)
- systemProducer.send("test", msg2)
- systemProducer.send("test", msg3)
- assertEquals(1, mockProducer.getMsgsSent)
-
- val sendThread: Thread = mockProducer.startDelayedSendThread(2000)
- sendThread.join()
-
- assertEquals(3, mockProducer.getMsgsSent)
- systemProducer.stop()
- }
-
- @Test
- def testKafkaProducerFlushSuccessful {
- val msg1 = new OutgoingMessageEnvelope(systemStream, "a".getBytes)
- val msg2 = new OutgoingMessageEnvelope(systemStream, "b".getBytes)
- val msg3 = new OutgoingMessageEnvelope(systemStream, "c".getBytes)
-
- val mockProducer = new MockKafkaProducer(1, "test", 1)
- val systemProducer = new KafkaSystemProducer(systemName = "test",
- getProducer = () => mockProducer,
- metrics = new KafkaSystemProducerMetrics)
- systemProducer.register("test")
- systemProducer.start()
- systemProducer.send("test", msg1)
-
- mockProducer.setShouldBuffer(true)
- systemProducer.send("test", msg2)
- systemProducer.send("test", msg3)
- assertEquals(1, mockProducer.getMsgsSent)
- mockProducer.startDelayedSendThread(2000)
- systemProducer.flush("test")
- assertEquals(3, mockProducer.getMsgsSent)
- systemProducer.stop()
- }
-
- @Test
- def testKafkaProducerFlushWithException {
- val msg1 = new OutgoingMessageEnvelope(systemStream, "a".getBytes)
- val msg2 = new OutgoingMessageEnvelope(systemStream, "b".getBytes)
- val msg3 = new OutgoingMessageEnvelope(systemStream, "c".getBytes)
- val msg4 = new OutgoingMessageEnvelope(systemStream, "d".getBytes)
-
- val mockProducer = new MockKafkaProducer(1, "test", 1)
- val systemProducer = new KafkaSystemProducer(systemName = "test",
- getProducer = () => mockProducer,
- metrics = new KafkaSystemProducerMetrics())
- systemProducer.register("test")
- systemProducer.start()
- systemProducer.send("test", msg1)
-
- mockProducer.setShouldBuffer(true)
- systemProducer.send("test", msg2)
- mockProducer.setErrorNext(true, true, new RecordTooLargeException())
- systemProducer.send("test", msg3)
- systemProducer.send("test", msg4)
-
- assertEquals(1, mockProducer.getMsgsSent)
-
- mockProducer.startDelayedSendThread(2000)
- val thrown = intercept[SystemProducerException] {
- systemProducer.flush("test")
- }
- assertTrue(thrown.isInstanceOf[SystemProducerException])
- assertEquals(3, mockProducer.getMsgsSent) // msg1, msg2 and msg4 will be sent
- systemProducer.stop()
- }
-
- @Test
- def testKafkaProducerWithRetriableException {
- val msg1 = new OutgoingMessageEnvelope(systemStream, "a".getBytes)
- val msg2 = new OutgoingMessageEnvelope(systemStream, "b".getBytes)
- val msg3 = new OutgoingMessageEnvelope(systemStream, "c".getBytes)
- val msg4 = new OutgoingMessageEnvelope(systemStream, "d".getBytes)
-
- val mockProducer = new MockKafkaProducer(1, "test", 1)
- val producerMetrics = new KafkaSystemProducerMetrics()
- val producer = new KafkaSystemProducer(systemName = "test",
- getProducer = () => mockProducer,
- metrics = producerMetrics)
-
- producer.register("test")
- producer.start()
- producer.send("test", msg1)
- producer.send("test", msg2)
- producer.send("test", msg3)
- producer.flush("test")
-
- mockProducer.setErrorNext(true, true, new TimeoutException())
-
- producer.send("test", msg4)
- val thrown = intercept[SystemProducerException] {
- producer.flush("test")
- }
- assertTrue(thrown.isInstanceOf[SystemProducerException])
- assertTrue(thrown.getCause.getCause.isInstanceOf[TimeoutException])
- assertEquals(3, mockProducer.getMsgsSent)
- producer.stop()
- }
-
- /**
- * If there's an exception, we should:
- * 1. Close the producer (from the one-and-only kafka send thread) to prevent subsequent sends from going out of order.
- * 2. Record the original exception
- * 3. Throw the exception every time a KafkaSystemProducer method is invoked until the container fails.
- *
- * Assumptions:
- * 1. SystemProducer.flush() can happen concurrently with SystemProducer.send() for a particular TaskInstance (task.async.commit)
- * 2. SystemProducer.flush() cannot happen concurrently with itself for a particular task instance
- * 3. Any exception thrown from SystemProducer.flush() will prevent the checkpointing and fail the container
- * 4. A single KafkaProducer is shared by all the tasks so any failure from one task can affect the others.
- *
- * Conclusions:
- * It is only safe to handle the async exceptions from by closing the producer and failing the container.
- * This prevents race conditons with setting/clearing exceptions and recreating the producer that could cause data
- * loss by checkpointing a failed offset.
- *
- * Inaccuracies:
- * A real kafka producer succeeds or fails all the messages in a batch. In other words, the messages of a batch all
- * fail or they all succeed together. This test, however, fails individual callbacks in order to test boundary
- * conditions where the batches align perfectly around the failed send().
- */
- @Test
- def testKafkaProducerWithFatalExceptions {
- val msg1 = new OutgoingMessageEnvelope(systemStream, "a".getBytes)
- val msg2 = new OutgoingMessageEnvelope(systemStream, "b".getBytes)
- val msg3 = new OutgoingMessageEnvelope(systemStream, "c".getBytes)
- val msg4 = new OutgoingMessageEnvelope(systemStream, "d".getBytes)
- val msg5 = new OutgoingMessageEnvelope(systemStream, "e".getBytes)
- val producerMetrics = new KafkaSystemProducerMetrics()
-
- val mockProducer = new MockKafkaProducer(1, "test", 1)
- val producer = new KafkaSystemProducer(systemName = "test",
- getProducer = () => {
- mockProducer.open() // A new producer would not already be closed, so reset it.
- mockProducer
- },
- metrics = producerMetrics)
- producer.register("test")
- producer.start()
-
- producer.send("test", msg1)
- producer.send("test", msg2)
- mockProducer.setErrorNext(true, true, new RecordTooLargeException())
- producer.send("test", msg3) // Callback exception
- assertTrue(mockProducer.isClosed)
- assertNotNull(producer.producerRef.get())
- assertEquals("Should NOT have created a new producer", 1, mockProducer.getOpenCount)
-
- val senderException = intercept[SystemProducerException] {
- producer.send("test", msg4) // Should fail because the producer is closed.
- }
- assertTrue(senderException.getCause.getCause.isInstanceOf[RecordTooLargeException])
-
- val callbackException = intercept[SystemProducerException] {
- producer.flush("test") // Should throw the callback exception
- }
- assertTrue(callbackException.getCause.getCause.isInstanceOf[RecordTooLargeException])
-
- val postFlushException = intercept[SystemProducerException] {
- producer.send("test", msg5) // Should not be able to send again after flush
- }
- assertTrue(postFlushException.getCause.getCause.isInstanceOf[RecordTooLargeException])
-
- val callbackException2 = intercept[SystemProducerException] {
- producer.flush("test") // Should rethrow the exception
- }
- assertTrue(callbackException2.getCause.getCause.isInstanceOf[RecordTooLargeException])
- assertEquals(2, mockProducer.getMsgsSent) // only the messages before the error get sent
- producer.stop()
- }
-
- /**
- * Recapping from [[testKafkaProducerWithFatalExceptions]]:
- *
- * If there's an exception, we should:
- * 1. Close the producer (from the one-and-only kafka send thread) to prevent subsequent sends from going out of order.
- * 2. Record the original exception
- * 3. Throw the exception every time a KafkaSystemProducer method is invoked until the container fails.
- *
- * This test focuses on point 3. Particularly it ensures that the failures are handled properly across multiple sources
- * which share the same producer.
- */
- @Test
- def testKafkaProducerWithFatalExceptionsMultipleSources {
- val msg1 = new OutgoingMessageEnvelope(systemStream, "a".getBytes)
- val msg2 = new OutgoingMessageEnvelope(systemStream, "b".getBytes)
- val msg3 = new OutgoingMessageEnvelope(systemStream, "c".getBytes)
- val msg4 = new OutgoingMessageEnvelope(systemStream, "d".getBytes)
- val msg5 = new OutgoingMessageEnvelope(systemStream, "e".getBytes)
- val msg6 = new OutgoingMessageEnvelope(systemStream, "f".getBytes)
- val msg7 = new OutgoingMessageEnvelope(systemStream, "g".getBytes)
- val producerMetrics = new KafkaSystemProducerMetrics()
-
- val mockProducer = new MockKafkaProducer(1, "test", 1)
- val producer = new KafkaSystemProducer(systemName = "test",
- getProducer = () => {
- mockProducer.open() // A new producer would not already be closed, so reset it.
- mockProducer
- },
- metrics = producerMetrics)
- producer.register("test1")
- producer.register("test2")
-
- producer.start()
-
- // Initial sends
- producer.send("test1", msg1)
- producer.send("test2", msg2)
-
- // Inject error for next send
- mockProducer.setErrorNext(true, true, new RecordTooLargeException())
- producer.send("test1", msg3) // Callback exception
- assertTrue(mockProducer.isClosed)
- assertNotNull(producer.producerRef.get())
- assertEquals("Should NOT have created a new producer", 1, mockProducer.getOpenCount)
-
- // Subsequent sends
- val senderException = intercept[SystemProducerException] {
- producer.send("test1", msg4) // Should fail because the producer is closed.
- }
- assertTrue(senderException.getCause.getCause.isInstanceOf[RecordTooLargeException])
-
- val callbackException = intercept[SystemProducerException] {
- producer.send("test2", msg4) // First send from separate source gets a producer closed exception
- }
- assertTrue(callbackException.getCause.getCause.isInstanceOf[RecordTooLargeException])
-
- val callbackException2 = intercept[SystemProducerException] {
- producer.send("test2", msg5) // Second send should still get the error
- }
- assertTrue(callbackException2.getCause.getCause.isInstanceOf[RecordTooLargeException])
-
- // Flushes
- val callbackException3 = intercept[SystemProducerException] {
- producer.flush("test2") // Should rethrow the closed exception in flush
- }
- assertTrue(callbackException3.isInstanceOf[SystemProducerException])
- assertTrue(callbackException3.getCause.getCause.isInstanceOf[RecordTooLargeException])
- intercept[SystemProducerException] {
- producer.send("test2", msg6) // Should still not be able to send after flush
- }
-
- val thrown3 = intercept[SystemProducerException] {
- producer.flush("test1") // Should throw the callback exception
- }
- assertTrue(thrown3.isInstanceOf[SystemProducerException])
- assertTrue(thrown3.getCause.getCause.isInstanceOf[RecordTooLargeException])
-
- intercept[SystemProducerException] {
- producer.send("test1", msg7) // Should still not be able to send after flush
- }
-
- intercept[SystemProducerException] {
- producer.flush("test1") // Should throw the callback exception
- }
- assertEquals(2, mockProducer.getMsgsSent)
- producer.stop()
- }
-
- @Test
- def testKafkaProducerWithNonFatalExceptionsMultipleSources {
- val msg1 = new OutgoingMessageEnvelope(systemStream, "a".getBytes)
- val msg2 = new OutgoingMessageEnvelope(systemStream, "b".getBytes)
- val msg3 = new OutgoingMessageEnvelope(systemStream, "c".getBytes)
- val msg4 = new OutgoingMessageEnvelope(systemStream, "d".getBytes)
- val msg5 = new OutgoingMessageEnvelope(systemStream, "e".getBytes)
- val producerMetrics = new KafkaSystemProducerMetrics()
-
- val mockProducer = new MockKafkaProducer(1, "test", 1)
- val producer = new KafkaSystemProducer(systemName = "test",
- getProducer = () => {
- mockProducer.open() // A new producer would not already be closed, so reset it.
- mockProducer
- },
- metrics = producerMetrics)
- producer.register("test1")
- producer.register("test2")
- producer.start()
-
- producer.send("test1", msg1)
- producer.send("test2", msg2)
- mockProducer.setErrorNext(true, false, new SerializationException())
- val sendException = intercept[SystemProducerException] {
- producer.send("test1", msg3) // User-thread exception
- }
- assertTrue(sendException.getCause.isInstanceOf[SerializationException])
- assertFalse(mockProducer.isClosed)
- assertNotNull(producer.producerRef.get())
- assertEquals("Should NOT have created a new producer", 1, mockProducer.getOpenCount)
-
- producer.send("test1", msg3) // Should be able to resend msg3
- producer.send("test2", msg4) // Second source should not be affected
-
- producer.flush("test1") // Flush should be unaffected
-
- producer.send("test1", msg5) // Should be able to send again after flush
-
- assertEquals(5, mockProducer.getMsgsSent) // only the messages before the error get sent
- producer.stop()
- }
-
- /**
- * If there's an exception and the user configured task.drop.producer.errors, we should:
- * 1. Close the producer (from the one-and-only kafka send thread) to prevent subsequent sends from going out of order.
- * 2. Recreate the producer.
- * 3. Ignore any messages that were dropped (user knows they're signing up for this if they enable the option)
- *
- * Assumptions:
- * 1. SystemProducer.flush() can happen concurrently with SystemProducer.send() for a particular TaskInstance (task.async.commit)
- * 2. SystemProducer.flush() cannot happen concurrently with itself for a particular task instance
- * 3. Any exception thrown from SystemProducer.flush() will prevent the checkpointing and fail the container
- * 4. A single KafkaProducer is shared by all the tasks so any failure from one task can affect the others.
- *
- * Conclusions:
- * If the user is ok with dropping messages for the sake of availability, we will swallow all exceptions and
- * recreate the producer to recover. There are no guarantees how many messages are lost, but the send-failed metric
- * should be accurate, so users should alert on that.
- *
- * Inaccuracies:
- * A real kafka producer succeeds or fails all the messages in a batch. In other words, the messages of a batch all
- * fail or they all succeed together. This test, however, fails individual callbacks in order to test boundary
- * conditions where the batches align perfectly around the failed send().
- */
- @Test
- def testKafkaProducerWithFatalExceptionsDroppingExceptions {
- val msg1 = new OutgoingMessageEnvelope(systemStream, "a".getBytes)
- val msg2 = new OutgoingMessageEnvelope(systemStream, "b".getBytes)
- val msg3 = new OutgoingMessageEnvelope(systemStream, "c".getBytes)
- val msg4 = new OutgoingMessageEnvelope(systemStream, "d".getBytes)
- val msg5 = new OutgoingMessageEnvelope(systemStream, "e".getBytes)
- val producerMetrics = new KafkaSystemProducerMetrics()
-
- val mockProducer = new MockKafkaProducer(1, "test", 1)
- val producer = new KafkaSystemProducer(systemName = "test",
- getProducer = () => {
- mockProducer.open() // A new producer would not already be closed, so reset it.
- mockProducer
- },
- metrics = producerMetrics,
- dropProducerExceptions = true) // Here's where we enable exception dropping.
- producer.register("test")
- producer.start()
-
- producer.send("test", msg1)
- producer.send("test", msg2)
- mockProducer.setErrorNext(true, true, new RecordTooLargeException())
- producer.send("test", msg3) // Callback exception
- assertTrue(mockProducer.isClosed)
- assertNull(producer.producerRef.get())
- assertEquals("Should not have created a new producer", 1, mockProducer.getOpenCount)
-
- producer.send("test", msg4) // Should succeed because the producer recovered.
- assertFalse(mockProducer.isClosed)
- assertNotNull(producer.producerRef.get())
- assertEquals("Should have created a new producer", 2, mockProducer.getOpenCount)
- producer.flush("test") // Should not throw
-
- producer.send("test", msg5) // Should be able to send again after flush
- assertEquals("Should not have created a new producer", 2, mockProducer.getOpenCount)
- producer.flush("test")
-
- assertEquals(4, mockProducer.getMsgsSent) // every message except the one with the error should get sent
- producer.stop()
- }
-
- /**
- * Recapping from [[testKafkaProducerWithFatalExceptionsDroppingExceptions]]:
- *
- * If there's an exception, we should:
- * 1. Close the producer (from the one-and-only kafka send thread) to prevent subsequent sends from going out of order.
- * 2. Recreate the producer.
- * 3. Ignore any messages that were dropped (user knows they're signing up for this if they enable the option)
- *
- * This test ensures that the failures are handled properly across multiple sources
- * which share the same producer.
- */
- @Test
- def testKafkaProducerWithFatalExceptionsMultipleSourcesDroppingExceptions {
- val msg1 = new OutgoingMessageEnvelope(systemStream, "a".getBytes)
- val msg2 = new OutgoingMessageEnvelope(systemStream, "b".getBytes)
- val msg3 = new OutgoingMessageEnvelope(systemStream, "c".getBytes)
- val msg4 = new OutgoingMessageEnvelope(systemStream, "d".getBytes)
- val msg5 = new OutgoingMessageEnvelope(systemStream, "e".getBytes)
- val msg6 = new OutgoingMessageEnvelope(systemStream, "f".getBytes)
- val msg7 = new OutgoingMessageEnvelope(systemStream, "g".getBytes)
- val producerMetrics = new KafkaSystemProducerMetrics()
-
- val mockProducer = new MockKafkaProducer(1, "test", 1)
- val producer = new KafkaSystemProducer(systemName = "test",
- getProducer = () => {
- mockProducer.open() // A new producer would not already be closed, so reset it.
- mockProducer
- },
- metrics = producerMetrics,
- dropProducerExceptions = true) // Here's where we enable exception dropping.
- producer.register("test1")
- producer.register("test2")
-
- producer.start()
-
- // Initial sends
- producer.send("test1", msg1)
- producer.send("test2", msg2)
-
- // Inject error for next send
- mockProducer.setErrorNext(true, true, new RecordTooLargeException())
- producer.send("test1", msg3) // Callback exception
- assertTrue(mockProducer.isClosed)
- assertNull(producer.producerRef.get())
- assertEquals("Should not have created a new producer", 1, mockProducer.getOpenCount)
-
- // Subsequent sends
- producer.send("test1", msg4) // Should succeed because the producer recovered.
- assertFalse(mockProducer.isClosed)
- assertEquals("Should have created a new producer", 2, mockProducer.getOpenCount)
- assertNotNull(producer.producerRef.get())
- producer.send("test2", msg5) // Second source should also not have any error.
- assertEquals("Should not have created a new producer", 2, mockProducer.getOpenCount)
-
- // Flushes
- producer.flush("test2") // Should not throw for test2
- producer.send("test2", msg6) // Should still work after flush
-
- producer.flush("test1") // Should not throw for test1 either
- producer.send("test1", msg7)
-
- assertEquals(6, mockProducer.getMsgsSent) // every message except the one with the error should get sent
- producer.stop()
- }
-
- @Test
- def testKafkaProducerWithNonFatalExceptionsMultipleSourcesDroppingExceptions {
- val msg1 = new OutgoingMessageEnvelope(systemStream, "a".getBytes)
- val msg2 = new OutgoingMessageEnvelope(systemStream, "b".getBytes)
- val msg3 = new OutgoingMessageEnvelope(systemStream, "c".getBytes)
- val msg4 = new OutgoingMessageEnvelope(systemStream, "d".getBytes)
- val msg5 = new OutgoingMessageEnvelope(systemStream, "e".getBytes)
- val producerMetrics = new KafkaSystemProducerMetrics()
-
- val mockProducer = new MockKafkaProducer(1, "test", 1)
- val producer = new KafkaSystemProducer(systemName = "test",
- getProducer = () => {
- mockProducer.open() // A new producer would not already be closed, so reset it.
- mockProducer
- },
- metrics = producerMetrics,
- dropProducerExceptions = true) // Here's where we enable exception dropping.
- producer.register("test1")
- producer.register("test2")
- producer.start()
-
- producer.send("test1", msg1)
- producer.send("test2", msg2)
- mockProducer.setErrorNext(true, false, new SerializationException())
- val sendException = intercept[SystemProducerException] {
- producer.send("test1", msg3) // User-thread exception
- }
- assertTrue(sendException.getCause.isInstanceOf[SerializationException])
- assertFalse(mockProducer.isClosed)
- assertNotNull(producer.producerRef.get()) // Synchronous error; producer should not be recreated
- assertEquals("Should NOT have created a new producer", 1, mockProducer.getOpenCount)
-
- producer.send("test1", msg3) // Should be able to resend msg3
- assertFalse(mockProducer.isClosed)
- assertEquals("Should NOT have created a new producer", 1, mockProducer.getOpenCount)
- assertNotNull(producer.producerRef.get())
- producer.send("test2", msg4) // Second source should not be affected
-
- producer.flush("test1") // Flush should be unaffected
-
- producer.send("test1", msg5) // Should be able to send again after flush
-
- assertEquals(5, mockProducer.getMsgsSent) // only the messages before the error get sent
- producer.stop()
- }
-
- @Test
- def testKafkaProducerFlushMsgsWhenStop {
- val msg1 = new OutgoingMessageEnvelope(systemStream, "a".getBytes)
- val msg2 = new OutgoingMessageEnvelope(systemStream, "b".getBytes)
- val msg3 = new OutgoingMessageEnvelope(systemStream, "c".getBytes)
- val msg4 = new OutgoingMessageEnvelope(new SystemStream("test2", "test"), "d".getBytes)
-
- val mockProducer = new MockKafkaProducer(1, "test", 1)
- val systemProducer = new KafkaSystemProducer(systemName = "test",
- getProducer = () => mockProducer,
- metrics = new KafkaSystemProducerMetrics)
- systemProducer.register("test")
- systemProducer.register("test2")
- systemProducer.start()
- systemProducer.send("test", msg1)
-
- mockProducer.setShouldBuffer(true)
- systemProducer.send("test", msg2)
- systemProducer.send("test", msg3)
- systemProducer.send("test2", msg4)
- assertEquals(1, mockProducer.getMsgsSent)
- mockProducer.startDelayedSendThread(2000)
- assertEquals(1, mockProducer.getMsgsSent)
- systemProducer.stop()
- assertEquals(4, mockProducer.getMsgsSent)
- }
-
- @Test
- def testSystemStreamNameNullOrEmpty {
- val omeStreamNameNull = new OutgoingMessageEnvelope(new SystemStream("test", null), "a".getBytes)
- val omeStreamNameEmpty = new OutgoingMessageEnvelope(new SystemStream("test", ""), "a".getBytes)
- val mockProducer = new MockKafkaProducer(1, "testMock", 1)
- val producer = new KafkaSystemProducer(systemName = "test", getProducer = () => mockProducer,
- metrics = new KafkaSystemProducerMetrics)
-
- val thrownNull = intercept[IllegalArgumentException] {
- producer.register("test1")
- producer.start()
- producer.send("testSrc1", omeStreamNameNull)
- assertEquals(0, mockProducer.getMsgsSent)
- }
- val thrownEmpty = intercept[IllegalArgumentException] {
- producer.register("test2")
- producer.start()
- producer.send("testSrc2", omeStreamNameEmpty)
- assertEquals(0, mockProducer.getMsgsSent)
- }
- assertTrue(thrownNull.getMessage() == "Invalid system stream: " + omeStreamNameNull.getSystemStream)
- assertTrue(thrownEmpty.getMessage() == "Invalid system stream: " + omeStreamNameEmpty.getSystemStream)
- }
-}
diff --git a/samza-kafka/src/test/scala/org/apache/samza/system/kafka_deprecated/TestTopicMetadataCache.scala b/samza-kafka/src/test/scala/org/apache/samza/system/kafka_deprecated/TestTopicMetadataCache.scala
deleted file mode 100644
index dda011b..0000000
--- a/samza-kafka/src/test/scala/org/apache/samza/system/kafka_deprecated/TestTopicMetadataCache.scala
+++ /dev/null
@@ -1,139 +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.samza.system.kafka_deprecated
-
-import java.util.concurrent.CountDownLatch
-import java.util.concurrent.atomic.{AtomicBoolean, AtomicInteger}
-
-import kafka.api.TopicMetadata
-import org.I0Itec.zkclient.ZkClient
-import org.apache.samza.util.Clock
-import org.apache.samza.util.TopicMetadataStore
-import org.junit.Assert._
-import org.junit.Before
-import org.junit.Test
-import kafka.common.ErrorMapping
-import kafka.api.PartitionMetadata
-import org.apache.kafka.common.protocol.Errors
-
-class TestTopicMetadataCache {
-
- class MockTime extends Clock {
- var currentValue = 0
-
- def currentTimeMillis: Long = currentValue
- }
-
- class MockTopicMetadataStore extends TopicMetadataStore {
- var mockCache = Map(
- "topic1" -> new TopicMetadata("topic1", List.empty, Errors.NONE),
- "topic2" -> new TopicMetadata("topic2", List.empty, Errors.NONE))
- var numberOfCalls: AtomicInteger = new AtomicInteger(0)
-
- def getTopicInfo(topics: Set[String]) = {
- var topicMetadata = Map[String, TopicMetadata]()
- topics.foreach(topic => topicMetadata += topic -> mockCache(topic))
- numberOfCalls.getAndIncrement
- topicMetadata
- }
-
- def setErrorCode(topic: String, errorCode: Short) {
- mockCache += topic -> new TopicMetadata(topic, List.empty, Errors.forCode(errorCode))
- }
- }
-
- @Before def setup {
- TopicMetadataCache.clear
- }
-
- @Test
- def testBasicMetadataCacheFunctionality {
- val mockStore = new MockTopicMetadataStore
- val mockTime = new MockTime
-
- // Retrieve a topic from the cache. Initially cache is empty and store is queried to get the data
- mockStore.setErrorCode("topic1", 3)
- var metadata = TopicMetadataCache.getTopicMetadata(Set("topic1"), "kafka", mockStore.getTopicInfo, 5, mockTime.currentTimeMillis)
- assertEquals("topic1", metadata("topic1").topic)
- assertEquals(3, metadata("topic1").error.code)
- assertEquals(1, mockStore.numberOfCalls.get())
-
- // Retrieve the same topic from the cache which has an error code. Ensure the store is called to refresh the cache
- mockTime.currentValue = 5
- mockStore.setErrorCode("topic1", 0)
- metadata = TopicMetadataCache.getTopicMetadata(Set("topic1"), "kafka", mockStore.getTopicInfo, 5, mockTime.currentTimeMillis)
- assertEquals("topic1", metadata("topic1").topic)
- assertEquals(0, metadata("topic1").error.code)
- assertEquals(2, mockStore.numberOfCalls.get())
-
- // Retrieve the same topic from the cache with refresh rate greater than the last update. Ensure the store is not
- // called
- metadata = TopicMetadataCache.getTopicMetadata(Set("topic1"), "kafka", mockStore.getTopicInfo, 5, mockTime.currentTimeMillis)
- assertEquals("topic1", metadata("topic1").topic)
- assertEquals(0, metadata("topic1").error.code)
- assertEquals(2, mockStore.numberOfCalls.get())
-
- // Ensure that refresh happens when refresh rate is less than the last update. Ensure the store is called
- mockTime.currentValue = 11
- metadata = TopicMetadataCache.getTopicMetadata(Set("topic1"), "kafka", mockStore.getTopicInfo, 5, mockTime.currentTimeMillis)
- assertEquals("topic1", metadata("topic1").topic)
- assertEquals(0, metadata("topic1").error.code)
- assertEquals(3, mockStore.numberOfCalls.get())
- }
-
- @Test
- def testMultiThreadedInteractionForTopicMetadataCache {
- val mockStore = new MockTopicMetadataStore
- val mockTime = new MockTime
- val waitForThreadStart = new CountDownLatch(3)
- val numAssertionSuccess = new AtomicBoolean(true)
- // Add topic to the cache from multiple threads and ensure the store is called only once
- val threads = new Array[Thread](3)
-
- mockTime.currentValue = 17
- for (i <- 0 until 3) {
- threads(i) = new Thread(new Runnable {
- def run {
- waitForThreadStart.countDown()
- waitForThreadStart.await()
- val metadata = TopicMetadataCache.getTopicMetadata(Set("topic1"), "kafka", mockStore.getTopicInfo, 5, mockTime.currentTimeMillis)
- numAssertionSuccess.compareAndSet(true, metadata("topic1").topic.equals("topic1"))
- numAssertionSuccess.compareAndSet(true, metadata("topic1").error.code == 0)
- }
- })
- threads(i).start()
- }
- for (i <- 0 until 3) {
- threads(i).join
- }
- assertTrue(numAssertionSuccess.get())
- assertEquals(1, mockStore.numberOfCalls.get())
- }
-
- @Test
- def testBadErrorCodes {
- val partitionMetadataBad = new PartitionMetadata(0, None, Seq(), error = Errors.LEADER_NOT_AVAILABLE)
- val partitionMetadataGood = new PartitionMetadata(0, None, Seq(), error = Errors.NONE)
- assertTrue(TopicMetadataCache.hasBadErrorCode(new TopicMetadata("test", List.empty, Errors.REQUEST_TIMED_OUT)))
- assertTrue(TopicMetadataCache.hasBadErrorCode(new TopicMetadata("test", List(partitionMetadataBad), Errors.NONE)))
- assertFalse(TopicMetadataCache.hasBadErrorCode(new TopicMetadata("test", List.empty, Errors.NONE)))
- assertFalse(TopicMetadataCache.hasBadErrorCode(new TopicMetadata("test", List(partitionMetadataGood), Errors.NONE)))
- }
-}
diff --git a/samza-kafka/src/test/scala/org/apache/samza/utils/TestKafkaUtil.scala b/samza-kafka/src/test/scala/org/apache/samza/utils/TestKafkaUtil.scala
index 3548aea..d7989ec 100644
--- a/samza-kafka/src/test/scala/org/apache/samza/utils/TestKafkaUtil.scala
+++ b/samza-kafka/src/test/scala/org/apache/samza/utils/TestKafkaUtil.scala
@@ -22,7 +22,6 @@ package org.apache.samza.utils
import org.junit.Test
import org.scalatest.{Matchers => ScalaTestMatchers}
import org.apache.samza.util.KafkaUtil
-import kafka.common.ErrorMapping
import org.apache.kafka.common.protocol.Errors
class TestKafkaUtil extends ScalaTestMatchers {
diff --git a/samza-sql/src/test/java/org/apache/samza/sql/fn/TestBuildOutputRecordUdf.java b/samza-sql/src/test/java/org/apache/samza/sql/fn/TestBuildOutputRecordUdf.java
index 9747c65..be03ca7 100644
--- a/samza-sql/src/test/java/org/apache/samza/sql/fn/TestBuildOutputRecordUdf.java
+++ b/samza-sql/src/test/java/org/apache/samza/sql/fn/TestBuildOutputRecordUdf.java
@@ -21,6 +21,7 @@ package org.apache.samza.sql.fn;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Collections;
import org.apache.samza.sql.SamzaSqlRelRecord;
import org.junit.Assert;
import org.junit.Test;
diff --git a/samza-test/src/test/java/org/apache/samza/processor/TestZkStreamProcessorBase.java b/samza-test/src/test/java/org/apache/samza/processor/TestZkStreamProcessorBase.java
index 7e236d1..1555912 100644
--- a/samza-test/src/test/java/org/apache/samza/processor/TestZkStreamProcessorBase.java
+++ b/samza-test/src/test/java/org/apache/samza/processor/TestZkStreamProcessorBase.java
@@ -34,8 +34,6 @@ import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.ZkConnection;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
-import org.apache.kafka.clients.consumer.KafkaConsumer;
-import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.samza.config.ApplicationConfig;
import org.apache.samza.config.Config;
@@ -57,8 +55,8 @@ import org.apache.samza.task.MessageCollector;
import org.apache.samza.task.StreamTask;
import org.apache.samza.task.StreamTaskFactory;
import org.apache.samza.task.TaskCoordinator;
-import org.apache.samza.test.StandaloneIntegrationTestHarness;
import org.apache.samza.test.StandaloneTestUtils;
+import org.apache.samza.test.harness.IntegrationTestHarness;
import org.apache.samza.util.Util;
import org.apache.samza.zk.TestZkUtils;
import org.apache.zookeeper.ZooKeeper;
@@ -68,7 +66,7 @@ import org.junit.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class TestZkStreamProcessorBase extends StandaloneIntegrationTestHarness {
+public class TestZkStreamProcessorBase extends IntegrationTestHarness {
private static final String TASK_SHUTDOWN_MS = "2000";
private static final String JOB_DEBOUNCE_TIME_MS = "2000";
private static final String BARRIER_TIMEOUT_MS = "2000";
@@ -172,8 +170,8 @@ public class TestZkStreamProcessorBase extends StandaloneIntegrationTestHarness
}
protected void createTopics(String inputTopic, String outputTopic) {
- TestUtils.createTopic(zkUtils(), inputTopic, 5, 1, servers(), new Properties());
- TestUtils.createTopic(zkUtils(), outputTopic, 5, 1, servers(), new Properties());
+ TestUtils.createTopic(kafkaZkClient(), inputTopic, 5, 1, servers(), new Properties());
+ TestUtils.createTopic(kafkaZkClient(), outputTopic, 5, 1, servers(), new Properties());
}
protected Map<String, String> createConfigs(String testSystem, String inputTopic, String outputTopic,
@@ -210,7 +208,6 @@ public class TestZkStreamProcessorBase extends StandaloneIntegrationTestHarness
* Produces the provided number of messages to the topic.
*/
protected void produceMessages(final int start, String topic, int numMessages) {
- KafkaProducer producer = getKafkaProducer();
for (int i = start; i < numMessages + start; i++) {
try {
LOG.info("producing " + i);
@@ -267,7 +264,6 @@ public class TestZkStreamProcessorBase extends StandaloneIntegrationTestHarness
* and asserts that the number of consumed messages is as expected.
*/
protected void verifyNumMessages(String topic, final Map<Integer, Boolean> expectedValues, int expectedNumMessages) {
- KafkaConsumer consumer = getKafkaConsumer();
consumer.subscribe(Collections.singletonList(topic));
Map<Integer, Boolean> map = new HashMap<>(expectedValues);
diff --git a/samza-test/src/test/java/org/apache/samza/test/StandaloneIntegrationTestHarness.java b/samza-test/src/test/java/org/apache/samza/test/StandaloneIntegrationTestHarness.java
deleted file mode 100644
index f5ac4bc..0000000
--- a/samza-test/src/test/java/org/apache/samza/test/StandaloneIntegrationTestHarness.java
+++ /dev/null
@@ -1,84 +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.samza.test;
-
-import kafka.utils.TestUtils;
-import org.apache.kafka.clients.consumer.KafkaConsumer;
-import org.apache.kafka.clients.producer.KafkaProducer;
-import org.apache.kafka.common.protocol.SecurityProtocol;
-import org.apache.kafka.common.serialization.ByteArraySerializer;
-import org.apache.kafka.common.serialization.StringSerializer;
-import org.apache.samza.test.harness.AbstractIntegrationTestHarness;
-import scala.Option$;
-
-import java.io.File;
-import java.util.Properties;
-
-public abstract class StandaloneIntegrationTestHarness extends AbstractIntegrationTestHarness {
- private KafkaProducer producer = null;
- private KafkaConsumer consumer = null;
-
- @Override
- public void setUp() {
- super.setUp();
- producer = TestUtils.createNewProducer(
- bootstrapServers(),
- 1,
- 60 * 1000L,
- 1024L * 1024L,
- 0,
- 0L,
- 5 * 1000L,
- SecurityProtocol.PLAINTEXT,
- null,
- Option$.MODULE$.<Properties>apply(new Properties()),
- new StringSerializer(),
- new ByteArraySerializer(),
- Option$.MODULE$.<Properties>apply(new Properties()));
-
- consumer = TestUtils.createNewConsumer(
- bootstrapServers(),
- "group",
- "earliest",
- 4096L,
- "org.apache.kafka.clients.consumer.RangeAssignor",
- 30000,
- SecurityProtocol.PLAINTEXT,
- Option$.MODULE$.<File>empty(),
- Option$.MODULE$.<Properties>empty(),
- Option$.MODULE$.<Properties>empty());
- }
-
- @Override
- public void tearDown() {
- consumer.close();
- producer.close();
- super.tearDown();
- }
-
- public KafkaProducer getKafkaProducer() {
- return producer;
- }
-
- public KafkaConsumer getKafkaConsumer() {
- return consumer;
- }
-}
-
diff --git a/samza-test/src/test/java/org/apache/samza/test/controlmessages/EndOfStreamIntegrationTest.java b/samza-test/src/test/java/org/apache/samza/test/controlmessages/EndOfStreamIntegrationTest.java
index 45b5668..b571ae0 100644
--- a/samza-test/src/test/java/org/apache/samza/test/controlmessages/EndOfStreamIntegrationTest.java
+++ b/samza-test/src/test/java/org/apache/samza/test/controlmessages/EndOfStreamIntegrationTest.java
@@ -42,7 +42,7 @@ import org.apache.samza.serializers.NoOpSerde;
import org.apache.samza.standalone.PassthroughJobCoordinatorFactory;
import org.apache.samza.test.controlmessages.TestData.PageView;
import org.apache.samza.test.controlmessages.TestData.PageViewJsonSerdeFactory;
-import org.apache.samza.test.harness.AbstractIntegrationTestHarness;
+import org.apache.samza.test.harness.IntegrationTestHarness;
import org.apache.samza.test.util.ArraySystemFactory;
import org.apache.samza.test.util.Base64Serializer;
import org.junit.Test;
@@ -53,7 +53,7 @@ import static org.junit.Assert.assertEquals;
* This test uses an array as a bounded input source, and does a partitionBy() and sink() after reading the input.
* It verifies the pipeline will stop and the number of output messages should equal to the input.
*/
-public class EndOfStreamIntegrationTest extends AbstractIntegrationTestHarness {
+public class EndOfStreamIntegrationTest extends IntegrationTestHarness {
private static final String[] PAGEKEYS = {"inbox", "home", "search", "pymk", "group", "job"};
diff --git a/samza-test/src/test/java/org/apache/samza/test/controlmessages/WatermarkIntegrationTest.java b/samza-test/src/test/java/org/apache/samza/test/controlmessages/WatermarkIntegrationTest.java
index 12b6f6d..9436fb2 100644
--- a/samza-test/src/test/java/org/apache/samza/test/controlmessages/WatermarkIntegrationTest.java
+++ b/samza-test/src/test/java/org/apache/samza/test/controlmessages/WatermarkIntegrationTest.java
@@ -70,7 +70,7 @@ import org.apache.samza.task.StreamOperatorTask;
import org.apache.samza.task.TestStreamOperatorTask;
import org.apache.samza.test.controlmessages.TestData.PageView;
import org.apache.samza.test.controlmessages.TestData.PageViewJsonSerdeFactory;
-import org.apache.samza.test.harness.AbstractIntegrationTestHarness;
+import org.apache.samza.test.harness.IntegrationTestHarness;
import org.apache.samza.test.util.SimpleSystemAdmin;
import org.apache.samza.test.util.TestStreamConsumer;
import org.junit.Test;
@@ -78,7 +78,7 @@ import org.junit.Test;
import static org.junit.Assert.assertEquals;
-public class WatermarkIntegrationTest extends AbstractIntegrationTestHarness {
+public class WatermarkIntegrationTest extends IntegrationTestHarness {
private static int offset = 1;
private static final String TEST_SYSTEM = "test";
diff --git a/samza-test/src/test/java/org/apache/samza/test/framework/StreamApplicationIntegrationTestHarness.java b/samza-test/src/test/java/org/apache/samza/test/framework/StreamApplicationIntegrationTestHarness.java
index 05f5a35..39c7f59 100644
--- a/samza-test/src/test/java/org/apache/samza/test/framework/StreamApplicationIntegrationTestHarness.java
+++ b/samza-test/src/test/java/org/apache/samza/test/framework/StreamApplicationIntegrationTestHarness.java
@@ -18,7 +18,6 @@
*/
package org.apache.samza.test.framework;
-import java.io.File;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collection;
@@ -27,14 +26,9 @@ import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
-import kafka.utils.TestUtils;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
-import org.apache.kafka.clients.consumer.KafkaConsumer;
-import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
-import org.apache.kafka.common.protocol.SecurityProtocol;
-import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.samza.application.SamzaApplication;
import org.apache.samza.config.Config;
import org.apache.samza.config.KafkaConfig;
@@ -42,10 +36,11 @@ import org.apache.samza.config.MapConfig;
import org.apache.samza.execution.TestStreamManager;
import org.apache.samza.runtime.ApplicationRunner;
import org.apache.samza.runtime.ApplicationRunners;
-import org.apache.samza.system.kafka.KafkaSystemAdmin;
-import org.apache.samza.test.harness.AbstractIntegrationTestHarness;
-import scala.Option;
-import scala.Option$;
+import org.apache.samza.test.harness.IntegrationTestHarness;
+
+import static org.apache.kafka.clients.consumer.ConsumerConfig.*;
+import static org.apache.kafka.clients.producer.ProducerConfig.*;
+
/**
* Harness for writing integration tests for {@link SamzaApplication}s.
@@ -96,58 +91,10 @@ import scala.Option$;
* }
* }}</pre>
*/
-public class StreamApplicationIntegrationTestHarness extends AbstractIntegrationTestHarness {
- private KafkaProducer producer;
- private KafkaConsumer consumer;
- protected KafkaSystemAdmin systemAdmin;
-
- private int numEmptyPolls = 3;
+public class StreamApplicationIntegrationTestHarness extends IntegrationTestHarness {
private static final Duration POLL_TIMEOUT_MS = Duration.ofSeconds(20);
- private static final String DEFAULT_DESERIALIZER = "org.apache.kafka.common.serialization.StringDeserializer";
-
- /**
- * Starts a single kafka broker, and a single embedded zookeeper server in their own threads.
- * Sub-classes should invoke {@link #zkConnect()} and {@link #bootstrapUrl()}s to
- * obtain the urls (and ports) of the started zookeeper and kafka broker.
- */
- @Override
- public void setUp() {
- super.setUp();
-
- Properties consumerDeserializerProperties = new Properties();
- consumerDeserializerProperties.setProperty("key.deserializer", DEFAULT_DESERIALIZER);
- consumerDeserializerProperties.setProperty("value.deserializer", DEFAULT_DESERIALIZER);
-
- producer = TestUtils.createNewProducer(
- bootstrapServers(), // bootstrap-server url
- 1, // acks
- 60 * 1000L, // maxBlockMs
- 1024L * 1024L, // buffer size
- 0, // numRetries
- 0L, // lingerMs
- 5 * 1000L, // requestTimeout
- SecurityProtocol.PLAINTEXT,
- null,
- Option.apply(new Properties()),
- new StringSerializer(),
- new StringSerializer(),
- Option.apply(new Properties()));
-
- consumer = TestUtils.createNewConsumer(
- bootstrapServers(),
- "group", // groupId
- "earliest", // auto-offset-reset
- 4096L, // per-partition fetch size
- "org.apache.kafka.clients.consumer.RangeAssignor", // partition Assigner
- 30000,
- SecurityProtocol.PLAINTEXT,
- Option$.MODULE$.<File>empty(),
- Option$.MODULE$.<Properties>empty(),
- Option$.MODULE$.<Properties>apply(consumerDeserializerProperties));
-
- systemAdmin = createSystemAdmin("kafka");
- systemAdmin.start();
- }
+ private static final int DEFAULT_REPLICATION_FACTOR = 1;
+ private int numEmptyPolls = 3;
/**
* Creates a kafka topic with the provided name and the number of partitions
@@ -155,7 +102,7 @@ public class StreamApplicationIntegrationTestHarness extends AbstractIntegration
* @param numPartitions the number of partitions in the topic
*/
public void createTopic(String topicName, int numPartitions) {
- TestUtils.createTopic(zkUtils(), topicName, numPartitions, 1, servers(), new Properties());
+ createTopic(topicName, numPartitions, DEFAULT_REPLICATION_FACTOR);
}
/**
@@ -166,7 +113,7 @@ public class StreamApplicationIntegrationTestHarness extends AbstractIntegration
* @param val the value in the message
*/
public void produceMessage(String topicName, int partitionId, String key, String val) {
- producer.send(new ProducerRecord(topicName, partitionId, key, val));
+ producer.send(new ProducerRecord<>(topicName, partitionId, key, val));
producer.flush();
}
@@ -193,7 +140,7 @@ public class StreamApplicationIntegrationTestHarness extends AbstractIntegration
consumer.subscribe(topics);
while (emptyPollCount < numEmptyPolls && recordList.size() < threshold) {
- ConsumerRecords<String, String> records = consumer.poll(POLL_TIMEOUT_MS.toMillis());
+ ConsumerRecords<String, String> records = consumer.poll(POLL_TIMEOUT_MS);
if (!records.isEmpty()) {
Iterator<ConsumerRecord<String, String>> iterator = records.iterator();
while (iterator.hasNext() && recordList.size() < threshold) {
@@ -262,17 +209,6 @@ public class StreamApplicationIntegrationTestHarness extends AbstractIntegration
}
/**
- * Shutdown and clear Zookeeper and Kafka broker state.
- */
- @Override
- public void tearDown() {
- systemAdmin.stop();
- producer.close();
- consumer.close();
- super.tearDown();
- }
-
- /**
* Container for any necessary context created during runApplication. Allows tests to access objects created within
* runApplication in order to do verification.
*/
@@ -293,4 +229,30 @@ public class StreamApplicationIntegrationTestHarness extends AbstractIntegration
return this.config;
}
}
+
+ @Override
+ protected Properties createProducerConfigs() {
+ Properties producerProps = super.createProducerConfigs();
+ /*
+ * Stream application tests uses string serde for both key and value.
+ * The default serde for the test producer in IntegrationTestHarness uses
+ * byte serde for value and string for key.
+ */
+ producerProps.setProperty(KEY_SERIALIZER_CLASS_CONFIG, STRING_SERIALIZER);
+ producerProps.setProperty(VALUE_SERIALIZER_CLASS_CONFIG, STRING_SERIALIZER);
+ return producerProps;
+ }
+
+ @Override
+ protected Properties createConsumerConfigs() {
+ Properties consumerProps = super.createConsumerConfigs();
+ /*
+ * Stream application tests uses string serde for both key and value.
+ * The default serde for the test producer in IntegrationTestHarness uses
+ * byte serde for value and string for key.
+ */
+ consumerProps.setProperty(KEY_DESERIALIZER_CLASS_CONFIG, STRING_DESERIALIZER);
+ consumerProps.setProperty(VALUE_DESERIALIZER_CLASS_CONFIG, STRING_DESERIALIZER);
+ return consumerProps;
+ }
}
diff --git a/samza-test/src/test/java/org/apache/samza/test/harness/IntegrationTestHarness.java b/samza-test/src/test/java/org/apache/samza/test/harness/IntegrationTestHarness.java
new file mode 100644
index 0000000..f97a59a
--- /dev/null
+++ b/samza-test/src/test/java/org/apache/samza/test/harness/IntegrationTestHarness.java
@@ -0,0 +1,217 @@
+/*
+ * 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.samza.test.harness;
+
+import com.google.common.collect.ImmutableMap;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Properties;
+import java.util.concurrent.TimeUnit;
+import org.apache.kafka.clients.CommonClientConfigs;
+import org.apache.kafka.clients.admin.AdminClient;
+import org.apache.kafka.clients.admin.CreatePartitionsResult;
+import org.apache.kafka.clients.admin.CreateTopicsResult;
+import org.apache.kafka.clients.admin.DeleteTopicsResult;
+import org.apache.kafka.clients.admin.NewPartitions;
+import org.apache.kafka.clients.admin.NewTopic;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.clients.producer.KafkaProducer;
+import org.apache.kafka.common.serialization.ByteArrayDeserializer;
+import org.apache.kafka.common.serialization.ByteArraySerializer;
+import org.apache.kafka.common.serialization.StringDeserializer;
+import org.apache.kafka.common.serialization.StringSerializer;
+import org.apache.samza.config.Config;
+import org.apache.samza.config.JobConfig;
+import org.apache.samza.config.KafkaConsumerConfig;
+import org.apache.samza.config.MapConfig;
+import org.apache.samza.context.ExternalContext;
+import org.apache.samza.runtime.ApplicationRunner;
+import org.apache.samza.system.kafka.KafkaSystemAdmin;
+import org.apache.samza.system.kafka.KafkaSystemConsumer;
+
+import static org.apache.kafka.clients.consumer.ConsumerConfig.*;
+import static org.apache.kafka.clients.producer.ProducerConfig.*;
+
+
+/**
+ * An integration test harness on top of {@link AbstractKafkaServerTestHarness}.
+ * It provides additional helper functions to consume, produce and manage topics in Kafka.
+ */
+public class IntegrationTestHarness extends AbstractKafkaServerTestHarness {
+ private static final long ADMIN_OPERATION_WAIT_DURATION_MS = 5000;
+ private static final String BYTE_ARRAY_SERIALIZER = ByteArraySerializer.class.getName();
+ private static final String BYTE_ARRAY_DESERIALIZER = ByteArrayDeserializer.class.getName();
+
+ protected static final String STRING_SERIALIZER = StringSerializer.class.getName();
+ protected static final String STRING_DESERIALIZER = StringDeserializer.class.getName();
+
+ private AdminClient adminClient;
+ protected KafkaConsumer consumer;
+ protected KafkaProducer producer;
+ protected KafkaSystemAdmin systemAdmin;
+
+ /**
+ * Starts a single kafka broker, and a single embedded zookeeper server in their own threads.
+ * Sub-classes should invoke {@link #zkConnect()} and {@link #bootstrapUrl()}s to
+ * obtain the urls (and ports) of the started zookeeper and kafka broker.
+ */
+ @Override
+ public void setUp() {
+ super.setUp();
+ producer = new KafkaProducer<>(createProducerConfigs());
+ consumer = new KafkaConsumer<>(createConsumerConfigs());
+
+ Properties kafkaConfig = new Properties();
+ kafkaConfig.setProperty(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers());
+ adminClient = AdminClient.create(kafkaConfig);
+
+ systemAdmin = createSystemAdmin("kafka");
+ systemAdmin.start();
+ }
+
+ /**
+ * Shutdown and clear Zookeeper and Kafka broker state.
+ */
+ @Override
+ public void tearDown() {
+ systemAdmin.stop();
+
+ /*
+ * Close joins on AdminClientRunnable thread and at times, it takes longer than the test timeouts, resulting
+ * in test failures. Using a bounded close ensures tests passes successfully. Note, in the event of timeout,
+ * close notifies AdminClientRunnable thread which in turn closes the underlying client quietly and
+ * it shouldn't impact the tests nor have any side effects.
+ */
+ adminClient.close(ADMIN_OPERATION_WAIT_DURATION_MS, TimeUnit.MILLISECONDS);
+ consumer.close();
+ producer.close();
+ super.tearDown();
+ }
+
+ /**
+ * Returns the bootstrap servers configuration string to be used by clients.
+ *
+ * @return bootstrap servers string.
+ */
+ protected String bootstrapServers() {
+ return bootstrapUrl();
+ }
+
+ /**
+ * Overrides of the method should provide the following configurations
+ * 1. boostrap.servers
+ * 2. key.serializer
+ * 3. value.serializer
+ *
+ * @return {@link Properties} for the test kafka producer
+ */
+ protected Properties createProducerConfigs() {
+ Properties producerProps = new Properties();
+ producerProps.setProperty(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers());
+ producerProps.setProperty(KEY_SERIALIZER_CLASS_CONFIG, STRING_SERIALIZER);
+ producerProps.setProperty(VALUE_SERIALIZER_CLASS_CONFIG, BYTE_ARRAY_SERIALIZER);
+ return producerProps;
+ }
+
+ /**
+ * Overrides of method should provide the following mandatory configurations
+ * 1. bootstrap.servers
+ * 2. key.deserializer
+ * 3. value.deserializer
+ * 4. auto.offset.reset
+ * 5. group.id
+ *
+ * @return {@link Properties} for the test kafka consumer
+ */
+ protected Properties createConsumerConfigs() {
+ Properties consumerProps = new Properties();
+ consumerProps.setProperty(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers());
+ consumerProps.setProperty(GROUP_ID_CONFIG, "group");
+ consumerProps.setProperty(AUTO_OFFSET_RESET_CONFIG, "earliest");
+ consumerProps.setProperty(KEY_DESERIALIZER_CLASS_CONFIG, STRING_DESERIALIZER);
+ consumerProps.setProperty(VALUE_DESERIALIZER_CLASS_CONFIG, BYTE_ARRAY_DESERIALIZER);
+ return consumerProps;
+ }
+
+ protected void executeRun(ApplicationRunner applicationRunner, Config config) {
+ applicationRunner.run(buildExternalContext(config).orElse(null));
+ }
+
+ protected boolean createTopic(String topicName, int numPartitions, int replicationFactor) {
+ return createTopics(Collections.singleton(new NewTopic(topicName, numPartitions, (short) replicationFactor)));
+ }
+
+ protected boolean createTopics(Collection<NewTopic> newTopics) {
+ boolean createStatus = true;
+
+ try {
+ CreateTopicsResult resultFuture =
+ adminClient.createTopics(newTopics);
+ resultFuture.all().get(ADMIN_OPERATION_WAIT_DURATION_MS, TimeUnit.MILLISECONDS);
+ } catch (Exception e) {
+ createStatus = false;
+ }
+
+ return createStatus;
+ }
+
+ protected boolean deleteTopics(Collection<String> topics) {
+ boolean deleteStatus = true;
+
+ try {
+ DeleteTopicsResult resultFutures = adminClient.deleteTopics(topics);
+ resultFutures.all().get(ADMIN_OPERATION_WAIT_DURATION_MS, TimeUnit.MILLISECONDS);
+ } catch (Exception e) {
+ deleteStatus = false;
+ }
+
+ return deleteStatus;
+ }
+
+ protected CreatePartitionsResult increasePartitionsTo(String topicName, int numPartitions) {
+ return adminClient.createPartitions(ImmutableMap.of(topicName, NewPartitions.increaseTo(numPartitions)));
+ }
+
+ private Optional<ExternalContext> buildExternalContext(Config config) {
+ /*
+ * By default, use an empty ExternalContext here. In a custom fork of Samza, this can be implemented to pass
+ * a non-empty ExternalContext. Only config should be used to build the external context. In the future, components
+ * like the application descriptor may not be available.
+ */
+ return Optional.empty();
+ }
+
+ private KafkaSystemAdmin createSystemAdmin(String system) {
+ String kafkaConsumerPropertyPrefix = "systems." + system + ".consumer.";
+
+ Map<String, String> map = new HashMap<>();
+ map.put(kafkaConsumerPropertyPrefix + CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, brokerList());
+ map.put(JobConfig.JOB_NAME(), "test.job");
+
+ Config config = new MapConfig(map);
+ HashMap<String, Object> consumerConfig =
+ KafkaConsumerConfig.getKafkaSystemConsumerConfig(config, system, KafkaConsumerConfig.createClientId("kafka-admin-consumer", config));
+
+ return new KafkaSystemAdmin(system, new MapConfig(map), KafkaSystemConsumer.createKafkaConsumerImpl(system, consumerConfig));
+ }
+}
diff --git a/samza-test/src/test/java/org/apache/samza/test/processor/TestStreamProcessor.java b/samza-test/src/test/java/org/apache/samza/test/processor/TestStreamProcessor.java
index cf41148..0c8cea4 100644
--- a/samza-test/src/test/java/org/apache/samza/test/processor/TestStreamProcessor.java
+++ b/samza-test/src/test/java/org/apache/samza/test/processor/TestStreamProcessor.java
@@ -19,6 +19,7 @@
package org.apache.samza.test.processor;
+import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
@@ -34,8 +35,10 @@ import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
-import org.apache.kafka.common.protocol.SecurityProtocol;
+import org.apache.kafka.common.security.auth.SecurityProtocol;
+import org.apache.kafka.common.serialization.ByteArrayDeserializer;
import org.apache.kafka.common.serialization.ByteArraySerializer;
+import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.samza.SamzaException;
import org.apache.samza.config.Config;
@@ -46,8 +49,8 @@ import org.apache.samza.runtime.ProcessorLifecycleListener;
import org.apache.samza.task.AsyncStreamTaskAdapter;
import org.apache.samza.task.AsyncStreamTaskFactory;
import org.apache.samza.task.StreamTaskFactory;
-import org.apache.samza.test.StandaloneIntegrationTestHarness;
import org.apache.samza.test.StandaloneTestUtils;
+import org.apache.samza.test.harness.IntegrationTestHarness;
import org.junit.Assert;
import org.junit.Test;
import scala.Option$;
@@ -58,7 +61,7 @@ import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.mock;
-public class TestStreamProcessor extends StandaloneIntegrationTestHarness {
+public class TestStreamProcessor extends IntegrationTestHarness {
public static final String PROCESSOR_ID = "1";
@@ -148,8 +151,8 @@ public class TestStreamProcessor extends StandaloneIntegrationTestHarness {
}
private void createTopics(String inputTopic, String outputTopic) {
- TestUtils.createTopic(zkUtils(), inputTopic, 1, 1, servers(), new Properties());
- TestUtils.createTopic(zkUtils(), outputTopic, 1, 1, servers(), new Properties());
+ TestUtils.createTopic(kafkaZkClient(), inputTopic, 1, 1, servers(), new Properties());
+ TestUtils.createTopic(kafkaZkClient(), outputTopic, 1, 1, servers(), new Properties());
}
private Map<String, String> createConfigs(String processorId, String testSystem, String inputTopic, String outputTopic, int messageCount) {
@@ -255,7 +258,7 @@ public class TestStreamProcessor extends StandaloneIntegrationTestHarness {
}
private void initConsumer(String bootstrapServer) {
- consumer = TestUtils.createNewConsumer(
+ consumer = TestUtils.createConsumer(
bootstrapServer,
"group",
"earliest",
@@ -263,9 +266,11 @@ public class TestStreamProcessor extends StandaloneIntegrationTestHarness {
"org.apache.kafka.clients.consumer.RangeAssignor",
30000,
SecurityProtocol.PLAINTEXT,
- Option$.MODULE$.empty(),
- Option$.MODULE$.empty(),
- Option$.MODULE$.empty());
+ Option$.MODULE$.<File>empty(),
+ Option$.MODULE$.<Properties>empty(),
+ new StringDeserializer(),
+ new ByteArrayDeserializer(),
+ Option$.MODULE$.<Properties>empty());
}
private void initProcessorListener() {
@@ -280,7 +285,7 @@ public class TestStreamProcessor extends StandaloneIntegrationTestHarness {
}
private void initProducer(String bootstrapServer) {
- producer = TestUtils.createNewProducer(
+ producer = TestUtils.createProducer(
bootstrapServer,
1,
60 * 1000L,
@@ -290,10 +295,10 @@ public class TestStreamProcessor extends StandaloneIntegrationTestHarness {
5 * 1000L,
SecurityProtocol.PLAINTEXT,
null,
- Option$.MODULE$.apply(new Properties()),
+ Option$.MODULE$.<Properties>apply(new Properties()),
new StringSerializer(),
new ByteArraySerializer(),
- Option$.MODULE$.apply(new Properties()));
+ Option$.MODULE$.<Properties>apply(new Properties()));
}
}
}
diff --git a/samza-test/src/test/java/org/apache/samza/test/processor/TestZkLocalApplicationRunner.java b/samza-test/src/test/java/org/apache/samza/test/processor/TestZkLocalApplicationRunner.java
index 0c35af6..e6ce045 100644
--- a/samza-test/src/test/java/org/apache/samza/test/processor/TestZkLocalApplicationRunner.java
+++ b/samza-test/src/test/java/org/apache/samza/test/processor/TestZkLocalApplicationRunner.java
@@ -30,7 +30,6 @@ import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import java.util.Properties;
import java.util.UUID;
import java.util.Objects;
import java.util.Set;
@@ -38,11 +37,8 @@ import java.util.HashSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
-import kafka.admin.AdminUtils;
-import kafka.admin.RackAwareMode;
-import kafka.utils.TestUtils;
import org.I0Itec.zkclient.ZkClient;
-import org.apache.kafka.clients.producer.KafkaProducer;
+import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.samza.Partition;
import org.apache.samza.application.TaskApplication;
@@ -69,8 +65,8 @@ import org.apache.samza.metrics.MetricsRegistryMap;
import org.apache.samza.runtime.ApplicationRunner;
import org.apache.samza.runtime.ApplicationRunners;
import org.apache.samza.system.SystemStreamPartition;
-import org.apache.samza.test.StandaloneIntegrationTestHarness;
import org.apache.samza.test.StandaloneTestUtils;
+import org.apache.samza.test.harness.IntegrationTestHarness;
import org.apache.samza.util.NoOpMetricsRegistry;
import org.apache.samza.util.Util;
import org.apache.samza.zk.ZkStringSerializer;
@@ -85,8 +81,8 @@ import org.junit.rules.Timeout;
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.*;
+
/**
* Integration tests for {@link org.apache.samza.runtime.LocalApplicationRunner} with {@link ZkJobCoordinatorFactory}.
@@ -95,7 +91,7 @@ import static org.junit.Assert.assertTrue;
* through {@link org.apache.samza.runtime.LocalApplicationRunner} to verify the guarantees made in stand alone execution
* environment.
*/
-public class TestZkLocalApplicationRunner extends StandaloneIntegrationTestHarness {
+public class TestZkLocalApplicationRunner extends IntegrationTestHarness {
private static final Logger LOGGER = LoggerFactory.getLogger(TestZkLocalApplicationRunner.class);
@@ -156,42 +152,25 @@ public class TestZkLocalApplicationRunner extends StandaloneIntegrationTestHarne
zkUtils = new ZkUtils(zkKeyBuilder, zkClient, ZK_CONNECTION_TIMEOUT_MS, ZK_SESSION_TIMEOUT_MS, new NoOpMetricsRegistry());
zkUtils.connect();
- for (String kafkaTopic : ImmutableList.of(inputKafkaTopic, outputKafkaTopic)) {
- LOGGER.info("Creating kafka topic: {}.", kafkaTopic);
- TestUtils.createTopic(zkUtils(), kafkaTopic, 5, 1, servers(), new Properties());
- if (AdminUtils.topicExists(zkUtils(), kafkaTopic)) {
- LOGGER.info("Topic: {} was created", kafkaTopic);
- } else {
- Assert.fail(String.format("Unable to create kafka topic: %s.", kafkaTopic));
- }
- }
- for (String kafkaTopic : ImmutableList.of(inputSinglePartitionKafkaTopic, outputSinglePartitionKafkaTopic)) {
- LOGGER.info("Creating kafka topic: {}.", kafkaTopic);
- TestUtils.createTopic(zkUtils(), kafkaTopic, 1, 1, servers(), new Properties());
- if (AdminUtils.topicExists(zkUtils(), kafkaTopic)) {
- LOGGER.info("Topic: {} was created", kafkaTopic);
- } else {
- Assert.fail(String.format("Unable to create kafka topic: %s.", kafkaTopic));
- }
- }
+ List<NewTopic> newTopics =
+ ImmutableList.of(inputKafkaTopic, outputKafkaTopic, inputSinglePartitionKafkaTopic, outputSinglePartitionKafkaTopic)
+ .stream()
+ .map(topic -> new NewTopic(topic, 5, (short) 1))
+ .collect(Collectors.toList());
+
+ assertTrue("Encountered errors during test setup. Failed to create topics.", createTopics(newTopics));
}
+ @Override
public void tearDown() {
+ deleteTopics(ImmutableList.of(
+ inputKafkaTopic, outputKafkaTopic, inputSinglePartitionKafkaTopic, outputSinglePartitionKafkaTopic));
SharedContextFactories.clearAll();
- for (String kafkaTopic : ImmutableList.of(inputKafkaTopic, outputKafkaTopic)) {
- LOGGER.info("Deleting kafka topic: {}.", kafkaTopic);
- AdminUtils.deleteTopic(zkUtils(), kafkaTopic);
- }
- for (String kafkaTopic : ImmutableList.of(inputSinglePartitionKafkaTopic, outputSinglePartitionKafkaTopic)) {
- LOGGER.info("Deleting kafka topic: {}.", kafkaTopic);
- AdminUtils.deleteTopic(zkUtils(), kafkaTopic);
- }
zkUtils.close();
super.tearDown();
}
private void publishKafkaEvents(String topic, int startIndex, int endIndex, String streamProcessorId) {
- KafkaProducer producer = getKafkaProducer();
for (int eventIndex = startIndex; eventIndex < endIndex; eventIndex++) {
try {
LOGGER.info("Publish kafka event with index : {} for stream processor: {}.", eventIndex, streamProcessorId);
@@ -704,7 +683,7 @@ public class TestZkLocalApplicationRunner extends StandaloneIntegrationTestHarne
Assert.assertEquals(5, ssps.size());
// Increase the partition count of input kafka topic to 100.
- AdminUtils.addPartitions(zkUtils(), inputKafkaTopic, 100, "", true, RackAwareMode.Enforced$.MODULE$);
+ increasePartitionsTo(inputKafkaTopic, 100);
long jobModelWaitTimeInMillis = 10;
while (Objects.equals(zkUtils.getJobModelVersion(), jobModelVersion)) {
@@ -756,7 +735,7 @@ public class TestZkLocalApplicationRunner extends StandaloneIntegrationTestHarne
public void testStatefulSamzaApplicationShouldRedistributeInputPartitionsToCorrectTasksWhenAInputStreamIsExpanded() throws Exception {
// Setup input topics.
String statefulInputKafkaTopic = String.format("test-input-topic-%s", UUID.randomUUID().toString());
- TestUtils.createTopic(zkUtils(), statefulInputKafkaTopic, 32, 1, servers(), new Properties());
+ createTopic(statefulInputKafkaTopic, 32, 1);
// Generate configuration for the test.
Map<String, String> configMap = buildStreamApplicationConfigMap(ImmutableList.of(statefulInputKafkaTopic), testStreamAppName, testStreamAppId);
@@ -797,7 +776,7 @@ public class TestZkLocalApplicationRunner extends StandaloneIntegrationTestHarne
Assert.assertEquals(expectedTaskAssignments, actualTaskAssignments);
// Increase the partition count of the input kafka topic to 64.
- AdminUtils.addPartitions(zkUtils(), statefulInputKafkaTopic, 64, "", true, RackAwareMode.Enforced$.MODULE$);
+ increasePartitionsTo(statefulInputKafkaTopic, 64);
// Wait for the JobModel version to change due to the increase in the input partition count.
long jobModelWaitTimeInMillis = 10;
@@ -855,8 +834,8 @@ public class TestZkLocalApplicationRunner extends StandaloneIntegrationTestHarne
// Setup the two input kafka topics.
String statefulInputKafkaTopic1 = String.format("test-input-topic-%s", UUID.randomUUID().toString());
String statefulInputKafkaTopic2 = String.format("test-input-topic-%s", UUID.randomUUID().toString());
- TestUtils.createTopic(zkUtils(), statefulInputKafkaTopic1, 32, 1, servers(), new Properties());
- TestUtils.createTopic(zkUtils(), statefulInputKafkaTopic2, 32, 1, servers(), new Properties());
+ createTopic(statefulInputKafkaTopic1, 32, 1);
+ createTopic(statefulInputKafkaTopic2, 32, 1);
// Generate configuration for the test.
Map<String, String> configMap = buildStreamApplicationConfigMap(ImmutableList.of(statefulInputKafkaTopic1, statefulInputKafkaTopic2),
@@ -902,10 +881,10 @@ public class TestZkLocalApplicationRunner extends StandaloneIntegrationTestHarne
Assert.assertEquals(expectedTaskAssignments, actualTaskAssignments);
// Increase the partition count of the input kafka topic1 to 64.
- AdminUtils.addPartitions(zkUtils(), statefulInputKafkaTopic1, 64, "", true, RackAwareMode.Enforced$.MODULE$);
+ increasePartitionsTo(statefulInputKafkaTopic1, 64);
// Increase the partition count of the input kafka topic2 to 64.
- AdminUtils.addPartitions(zkUtils(), statefulInputKafkaTopic2, 64, "", true, RackAwareMode.Enforced$.MODULE$);
+ increasePartitionsTo(statefulInputKafkaTopic2, 64);
// Wait for the JobModel version to change due to the increase in the input partition count.
long jobModelWaitTimeInMillis = 10;
diff --git a/samza-test/src/test/java/org/apache/samza/test/samzasql/SamzaSqlIntegrationTestHarness.java b/samza-test/src/test/java/org/apache/samza/test/samzasql/SamzaSqlIntegrationTestHarness.java
index 475617c..4ab543d 100644
--- a/samza-test/src/test/java/org/apache/samza/test/samzasql/SamzaSqlIntegrationTestHarness.java
+++ b/samza-test/src/test/java/org/apache/samza/test/samzasql/SamzaSqlIntegrationTestHarness.java
@@ -20,10 +20,10 @@ package org.apache.samza.test.samzasql;
import org.apache.samza.config.Config;
import org.apache.samza.sql.runner.SamzaSqlApplicationRunner;
-import org.apache.samza.test.harness.AbstractIntegrationTestHarness;
+import org.apache.samza.test.harness.IntegrationTestHarness;
-public class SamzaSqlIntegrationTestHarness extends AbstractIntegrationTestHarness {
+public class SamzaSqlIntegrationTestHarness extends IntegrationTestHarness {
protected void runApplication(Config config) {
SamzaSqlApplicationRunner runner = new SamzaSqlApplicationRunner(true, config);
executeRun(runner, config);
diff --git a/samza-test/src/test/java/org/apache/samza/test/table/TestLocalTableEndToEnd.java b/samza-test/src/test/java/org/apache/samza/test/table/TestLocalTableEndToEnd.java
index e2b2ad0..c3f0ba5 100644
--- a/samza-test/src/test/java/org/apache/samza/test/table/TestLocalTableEndToEnd.java
+++ b/samza-test/src/test/java/org/apache/samza/test/table/TestLocalTableEndToEnd.java
@@ -47,7 +47,7 @@ import org.apache.samza.standalone.PassthroughJobCoordinatorFactory;
import org.apache.samza.storage.kv.inmemory.descriptors.InMemoryTableDescriptor;
import org.apache.samza.table.ReadWriteTable;
import org.apache.samza.table.Table;
-import org.apache.samza.test.harness.AbstractIntegrationTestHarness;
+import org.apache.samza.test.harness.IntegrationTestHarness;
import org.apache.samza.test.util.ArraySystemFactory;
import org.apache.samza.test.util.Base64Serializer;
@@ -68,7 +68,7 @@ import static org.junit.Assert.assertTrue;
/**
* This test class tests sendTo() and join() for local tables
*/
-public class TestLocalTableEndToEnd extends AbstractIntegrationTestHarness {
+public class TestLocalTableEndToEnd extends IntegrationTestHarness {
@Test
public void testSendTo() throws Exception {
diff --git a/samza-test/src/test/java/org/apache/samza/test/table/TestLocalTableWithConfigRewriterEndToEnd.java b/samza-test/src/test/java/org/apache/samza/test/table/TestLocalTableWithConfigRewriterEndToEnd.java
index 5eb6c03..c84945d 100644
--- a/samza-test/src/test/java/org/apache/samza/test/table/TestLocalTableWithConfigRewriterEndToEnd.java
+++ b/samza-test/src/test/java/org/apache/samza/test/table/TestLocalTableWithConfigRewriterEndToEnd.java
@@ -39,7 +39,7 @@ import org.apache.samza.system.descriptors.GenericInputDescriptor;
import org.apache.samza.table.TableConfigGenerator;
import org.apache.samza.table.descriptors.TableDescriptor;
import org.apache.samza.task.StreamTaskFactory;
-import org.apache.samza.test.harness.AbstractIntegrationTestHarness;
+import org.apache.samza.test.harness.IntegrationTestHarness;
import org.apache.samza.test.util.Base64Serializer;
import org.junit.Test;
@@ -48,7 +48,7 @@ import static org.apache.samza.test.table.TestLocalTableEndToEnd.getBaseJobConfi
import static org.apache.samza.test.table.TestLocalTableWithLowLevelApiEndToEnd.MyStreamTask;
-public class TestLocalTableWithConfigRewriterEndToEnd extends AbstractIntegrationTestHarness {
+public class TestLocalTableWithConfigRewriterEndToEnd extends IntegrationTestHarness {
@Test
public void testWithConfigRewriter() throws Exception {
diff --git a/samza-test/src/test/java/org/apache/samza/test/table/TestLocalTableWithLowLevelApiEndToEnd.java b/samza-test/src/test/java/org/apache/samza/test/table/TestLocalTableWithLowLevelApiEndToEnd.java
index 6cefe2b..164e74b 100644
--- a/samza-test/src/test/java/org/apache/samza/test/table/TestLocalTableWithLowLevelApiEndToEnd.java
+++ b/samza-test/src/test/java/org/apache/samza/test/table/TestLocalTableWithLowLevelApiEndToEnd.java
@@ -40,7 +40,7 @@ import org.apache.samza.task.MessageCollector;
import org.apache.samza.task.StreamTask;
import org.apache.samza.task.StreamTaskFactory;
import org.apache.samza.task.TaskCoordinator;
-import org.apache.samza.test.harness.AbstractIntegrationTestHarness;
+import org.apache.samza.test.harness.IntegrationTestHarness;
import org.apache.samza.test.util.Base64Serializer;
import org.junit.Assert;
@@ -49,7 +49,7 @@ import org.junit.Test;
import static org.apache.samza.test.table.TestLocalTableEndToEnd.getBaseJobConfig;
-public class TestLocalTableWithLowLevelApiEndToEnd extends AbstractIntegrationTestHarness {
+public class TestLocalTableWithLowLevelApiEndToEnd extends IntegrationTestHarness {
@Test
public void testTableWithLowLevelApi() throws Exception {
diff --git a/samza-test/src/test/java/org/apache/samza/test/table/TestLocalTableWithSideInputsEndToEnd.java b/samza-test/src/test/java/org/apache/samza/test/table/TestLocalTableWithSideInputsEndToEnd.java
index 74e2105..2490707 100644
--- a/samza-test/src/test/java/org/apache/samza/test/table/TestLocalTableWithSideInputsEndToEnd.java
+++ b/samza-test/src/test/java/org/apache/samza/test/table/TestLocalTableWithSideInputsEndToEnd.java
@@ -45,7 +45,7 @@ import org.apache.samza.test.framework.TestRunner;
import org.apache.samza.test.framework.system.descriptors.InMemoryInputDescriptor;
import org.apache.samza.test.framework.system.descriptors.InMemoryOutputDescriptor;
import org.apache.samza.test.framework.system.descriptors.InMemorySystemDescriptor;
-import org.apache.samza.test.harness.AbstractIntegrationTestHarness;
+import org.apache.samza.test.harness.IntegrationTestHarness;
import org.junit.Test;
import static org.apache.samza.test.table.TestTableData.EnrichedPageView;
@@ -56,7 +56,7 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
-public class TestLocalTableWithSideInputsEndToEnd extends AbstractIntegrationTestHarness {
+public class TestLocalTableWithSideInputsEndToEnd extends IntegrationTestHarness {
private static final String PAGEVIEW_STREAM = "pageview";
private static final String PROFILE_STREAM = "profile";
private static final String ENRICHED_PAGEVIEW_STREAM = "enrichedpageview";
diff --git a/samza-test/src/test/java/org/apache/samza/test/table/TestRemoteTableEndToEnd.java b/samza-test/src/test/java/org/apache/samza/test/table/TestRemoteTableEndToEnd.java
index 9db3a44..b92b5b5 100644
--- a/samza-test/src/test/java/org/apache/samza/test/table/TestRemoteTableEndToEnd.java
+++ b/samza-test/src/test/java/org/apache/samza/test/table/TestRemoteTableEndToEnd.java
@@ -59,7 +59,7 @@ import org.apache.samza.table.descriptors.RemoteTableDescriptor;
import org.apache.samza.table.remote.TableRateLimiter;
import org.apache.samza.table.remote.TableReadFunction;
import org.apache.samza.table.remote.TableWriteFunction;
-import org.apache.samza.test.harness.AbstractIntegrationTestHarness;
+import org.apache.samza.test.harness.IntegrationTestHarness;
import org.apache.samza.test.util.Base64Serializer;
import org.apache.samza.util.RateLimiter;
@@ -79,7 +79,7 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.withSettings;
-public class TestRemoteTableEndToEnd extends AbstractIntegrationTestHarness {
+public class TestRemoteTableEndToEnd extends IntegrationTestHarness {
static Map<String, List<EnrichedPageView>> writtenRecords = new HashMap<>();
diff --git a/samza-test/src/test/scala/org/apache/samza/test/harness/AbstractIntegrationTestHarness.scala b/samza-test/src/test/scala/org/apache/samza/test/harness/AbstractIntegrationTestHarness.scala
deleted file mode 100644
index 1340ca1..0000000
--- a/samza-test/src/test/scala/org/apache/samza/test/harness/AbstractIntegrationTestHarness.scala
+++ /dev/null
@@ -1,100 +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.samza.test.harness
-
-import java.util.Properties
-
-import kafka.server.KafkaConfig
-import kafka.utils.TestUtils
-import org.apache.samza.config.{Config, JobConfig, KafkaConsumerConfig, MapConfig}
-import org.apache.samza.context.ExternalContext
-import org.apache.samza.runtime.ApplicationRunner
-import org.apache.samza.system.kafka.{KafkaSystemAdmin, KafkaSystemConsumer}
-
-/**
- * Integration test harness for Kafka
- * We do this because java does not support trait and we are making it an
- * abstract class so that user's java test class can extend it.
- */
-abstract class AbstractIntegrationTestHarness extends AbstractKafkaServerTestHarness {
-
- def generateConfigs() =
- TestUtils.createBrokerConfigs(clusterSize(), zkConnect, enableControlledShutdown = false).map(KafkaConfig.fromProps(_, overridingProps()))
-
- /**
- * User can override this method to return the number of brokers they want.
- * By default only one broker will be launched.
- *
- * @return the number of brokers needed in the Kafka cluster for the test.
- */
- def clusterSize(): Int = 1
-
- /**
- * User can override this method to apply customized configurations to the brokers.
- * By default the only configuration is number of partitions when topics get automatically created. The default value
- * is 1.
- *
- * @return The configurations to be used by brokers.
- */
- def overridingProps(): Properties = {
- val props = new Properties()
- props.setProperty(KafkaConfig.NumPartitionsProp, 1.toString)
- props
- }
-
- /**
- * Returns the bootstrap servers configuration string to be used by clients.
- *
- * @return bootstrap servers string.
- */
- def bootstrapServers(): String = super.bootstrapUrl
-
- def createSystemAdmin(system: String): KafkaSystemAdmin = {
-
- val map: java.util.Map[String, String] = new java.util.HashMap();
-
- val KAFKA_CONSUMER_PROPERTY_PREFIX: String = "systems." + system + ".consumer."
- val KAFKA_PRODUCER_PROPERTY_PREFIX: String = "systems." + system + ".consumer."
-
- map.put(KAFKA_CONSUMER_PROPERTY_PREFIX +
- org.apache.kafka.clients.consumer.ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, brokerList)
- map.put(JobConfig.JOB_NAME, "test.job")
-
- map.put(KAFKA_CONSUMER_PROPERTY_PREFIX +
- KafkaConsumerConfig.ZOOKEEPER_CONNECT, zkConnect)
-
- val config = new MapConfig(map)
- val consumerConfig = KafkaConsumerConfig.getKafkaSystemConsumerConfig(config, system, KafkaConsumerConfig.createClientId("kafka-admin-consumer", config))
-
- new KafkaSystemAdmin(system, new MapConfig(map), KafkaSystemConsumer.createKafkaConsumerImpl(system, consumerConfig));
- }
-
- protected def executeRun(applicationRunner: ApplicationRunner, config: Config): Unit = {
- applicationRunner.run(buildExternalContext(config).orNull)
- }
-
- private def buildExternalContext(config: Config): Option[ExternalContext] = {
- /*
- * By default, use an empty ExternalContext here. In a custom fork of Samza, this can be implemented to pass
- * a non-empty ExternalContext. Only config should be used to build the external context. In the future, components
- * like the application descriptor may not be available.
- */
- None
- }
-}
\ No newline at end of file
diff --git a/samza-test/src/test/scala/org/apache/samza/test/harness/AbstractKafkaServerTestHarness.scala b/samza-test/src/test/scala/org/apache/samza/test/harness/AbstractKafkaServerTestHarness.scala
index 41abd99..6b11e70 100644
--- a/samza-test/src/test/scala/org/apache/samza/test/harness/AbstractKafkaServerTestHarness.scala
+++ b/samza-test/src/test/scala/org/apache/samza/test/harness/AbstractKafkaServerTestHarness.scala
@@ -24,9 +24,11 @@ import java.util.Properties
import kafka.common.KafkaException
import kafka.server.{KafkaConfig, KafkaServer}
-import kafka.utils.{TestUtils, CoreUtils}
-import org.apache.kafka.common.protocol.SecurityProtocol
-import org.apache.kafka.common.security.auth.KafkaPrincipal
+import kafka.utils.{CoreUtils, TestUtils}
+import kafka.zk.{AdminZkClient, KafkaZkClient}
+import org.apache.kafka.common.security.JaasUtils
+import org.apache.kafka.common.security.auth.{KafkaPrincipal, SecurityProtocol}
+import org.apache.kafka.common.utils.Time
import org.junit.{After, Before}
import scala.collection.mutable
@@ -40,6 +42,8 @@ abstract class AbstractKafkaServerTestHarness extends AbstractZookeeperTestHarne
var instanceConfigs: Seq[KafkaConfig] = null
var servers: mutable.Buffer[KafkaServer] = null
var brokerList: String = null
+ var kafkaZkClient: KafkaZkClient = null
+ var adminZkClient: AdminZkClient = null
var alive: Array[Boolean] = null
val kafkaPrincipalType = KafkaPrincipal.USER_TYPE
val setClusterAcl: Option[() => Unit] = None
@@ -48,7 +52,30 @@ abstract class AbstractKafkaServerTestHarness extends AbstractZookeeperTestHarne
* Implementations must override this method to return a set of KafkaConfigs. This method will be invoked for every
* test and should not reuse previous configurations unless they select their ports randomly when servers are started.
*/
- def generateConfigs(): Seq[KafkaConfig]
+ def generateConfigs(): Seq[KafkaConfig] = {
+ TestUtils.createBrokerConfigs(clusterSize, zkConnect, false).map(KafkaConfig.fromProps(_, overridingProps))
+ }
+
+ /**
+ * User can override this method to return the number of brokers they want.
+ * By default only one broker will be launched.
+ *
+ * @return the number of brokers needed in the Kafka cluster for the test.
+ */
+ def clusterSize = 1
+
+ /**
+ * User can override this method to apply customized configurations to the brokers.
+ * By default the only configuration is number of partitions when topics get automatically created. The default value
+ * is 1.
+ *
+ * @return The configurations to be used by brokers.
+ */
+ def overridingProps: Properties = {
+ val props = new Properties
+ props.setProperty(KafkaConfig.NumPartitionsProp, 1.toString)
+ props
+ }
def configs: Seq[KafkaConfig] = {
if (instanceConfigs == null)
@@ -95,6 +122,8 @@ abstract class AbstractKafkaServerTestHarness extends AbstractZookeeperTestHarne
// if the test case requires setting up a cluster ACL,
// then it needs to be implemented.
setClusterAcl.foreach(_.apply())
+ kafkaZkClient = KafkaZkClient(zkConnect, JaasUtils.isZkSecurityEnabled, zkSessionTimeout, zkConnectionTimeout, 100, Time.SYSTEM)
+ adminZkClient = new AdminZkClient(kafkaZkClient)
}
@After
@@ -103,6 +132,9 @@ abstract class AbstractKafkaServerTestHarness extends AbstractZookeeperTestHarne
servers.foreach(_.shutdown())
servers.foreach(server => CoreUtils.delete(server.config.logDirs))
}
+
+ if (kafkaZkClient != null)
+ CoreUtils.swallow(kafkaZkClient.close(), null)
super.tearDown()
}
diff --git a/samza-test/src/test/scala/org/apache/samza/test/harness/AbstractZookeeperTestHarness.scala b/samza-test/src/test/scala/org/apache/samza/test/harness/AbstractZookeeperTestHarness.scala
index 3af302d..69fe68c 100644
--- a/samza-test/src/test/scala/org/apache/samza/test/harness/AbstractZookeeperTestHarness.scala
+++ b/samza-test/src/test/scala/org/apache/samza/test/harness/AbstractZookeeperTestHarness.scala
@@ -18,8 +18,8 @@
*/
package org.apache.samza.test.harness
-import kafka.utils.{ZkUtils, Logging, CoreUtils}
-import kafka.zk.{EmbeddedZookeeper, ZkFourLetterWords}
+import kafka.utils.{CoreUtils, Logging, ZkUtils}
+import kafka.zk.{EmbeddedZookeeper, KafkaZkClient, ZkFourLetterWords}
import org.junit.{After, Before}
import org.apache.kafka.common.security.JaasUtils
import javax.security.auth.login.Configuration
@@ -55,9 +55,9 @@ abstract class AbstractZookeeperTestHarness extends Logging {
@After
def tearDown() {
if (zkUtils != null)
- CoreUtils.swallow(zkUtils.close())
+ CoreUtils.swallow(zkUtils.close(), null)
if (zookeeper != null)
- CoreUtils.swallow(zookeeper.shutdown())
+ CoreUtils.swallow(zookeeper.shutdown(), null)
def isDown: Boolean = {
try {
diff --git a/samza-test/src/test/scala/org/apache/samza/test/integration/StreamTaskTestUtil.scala b/samza-test/src/test/scala/org/apache/samza/test/integration/StreamTaskTestUtil.scala
index d248dac..5772d40 100644
--- a/samza-test/src/test/scala/org/apache/samza/test/integration/StreamTaskTestUtil.scala
+++ b/samza-test/src/test/scala/org/apache/samza/test/integration/StreamTaskTestUtil.scala
@@ -19,20 +19,19 @@
package org.apache.samza.test.integration
+import java.time.Duration
import java.util
-import java.util.Properties
+import java.util.{Collections, Properties}
import java.util.concurrent.{CountDownLatch, TimeUnit}
import javax.security.auth.login.Configuration
-import kafka.admin.AdminUtils
-import kafka.consumer.{Consumer, ConsumerConfig}
-import kafka.message.MessageAndMetadata
import kafka.server.{KafkaConfig, KafkaServer}
-import kafka.utils.{CoreUtils, TestUtils, ZkUtils}
+import kafka.utils.{CoreUtils, TestUtils}
import kafka.zk.EmbeddedZookeeper
+import org.apache.kafka.clients.admin.{AdminClient, NewTopic}
+import org.apache.kafka.clients.consumer.{ConsumerRecord, KafkaConsumer}
import org.apache.kafka.clients.producer.{KafkaProducer, Producer, ProducerConfig, ProducerRecord}
-import org.apache.kafka.common.protocol.SecurityProtocol
-import org.apache.kafka.common.security.JaasUtils
+import org.apache.kafka.common.security.auth.SecurityProtocol
import org.apache.samza.Partition
import org.apache.samza.checkpoint.Checkpoint
import org.apache.samza.config._
@@ -43,10 +42,8 @@ import org.apache.samza.job.model.{ContainerModel, JobModel}
import org.apache.samza.job.{ApplicationStatus, JobRunner, StreamJob}
import org.apache.samza.metrics.MetricsRegistryMap
import org.apache.samza.storage.ChangelogStreamManager
-import org.apache.samza.system.kafka.TopicMetadataCache
import org.apache.samza.system.{IncomingMessageEnvelope, SystemStreamPartition}
import org.apache.samza.task._
-import org.apache.samza.util.{ClientUtilTopicMetadataStore, KafkaUtil, TopicMetadataStore}
import org.junit.Assert._
import scala.collection.JavaConverters._
@@ -67,18 +64,16 @@ object StreamTaskTestUtil {
val zkConnectionTimeout = 6000
val zkSessionTimeout = 6000
- var zkUtils: ZkUtils = null
var zookeeper: EmbeddedZookeeper = null
var brokers: String = null
def zkPort: Int = zookeeper.port
def zkConnect: String = s"127.0.0.1:$zkPort"
var producer: Producer[Array[Byte], Array[Byte]] = null
+ var adminClient: AdminClient = null
val cp1 = new Checkpoint(Map(new SystemStreamPartition("kafka", "topic", new Partition(0)) -> "123").asJava)
val cp2 = new Checkpoint(Map(new SystemStreamPartition("kafka", "topic", new Partition(0)) -> "12345").asJava)
- var metadataStore: TopicMetadataStore = null
-
/*
* This is the default job configuration. Each test class can override the default configuration below.
*/
@@ -111,8 +106,6 @@ object StreamTaskTestUtil {
def beforeSetupServers {
zookeeper = new EmbeddedZookeeper()
- zkUtils = ZkUtils(zkConnect, zkSessionTimeout, zkConnectionTimeout, JaasUtils.isZkSecurityEnabled())
-
val props = TestUtils.createBrokerConfigs(3, zkConnect, true)
val configs = props.map(p => {
@@ -137,46 +130,36 @@ object StreamTaskTestUtil {
config.put(ProducerConfig.LINGER_MS_CONFIG, "0")
val producerConfig = new KafkaProducerConfig("kafka", "i001", config)
+ adminClient = AdminClient.create(config.asInstanceOf[util.Map[String, Object]])
producer = new KafkaProducer[Array[Byte], Array[Byte]](producerConfig.getProducerProperties)
- metadataStore = new ClientUtilTopicMetadataStore(brokers, "some-job-name")
createTopics
validateTopics
}
def createTopics {
- AdminUtils.createTopic(
- zkUtils,
- INPUT_TOPIC,
- TOTAL_TASK_NAMES,
- REPLICATION_FACTOR)
+ adminClient.createTopics(Collections.singleton(new NewTopic(INPUT_TOPIC, TOTAL_TASK_NAMES, REPLICATION_FACTOR.shortValue())))
}
def validateTopics {
- val topics = Set(INPUT_TOPIC)
var done = false
var retries = 0
- while (!done && retries < 100) {
+ while (!done && retries < 10) {
try {
- val topicMetadataMap = TopicMetadataCache.getTopicMetadata(topics, "kafka", metadataStore.getTopicInfo)
-
- topics.foreach(topic => {
- val topicMetadata = topicMetadataMap(topic)
-
- KafkaUtil.maybeThrowException(topicMetadata.error.exception())
- })
+ val topicDescriptionFutures = adminClient.describeTopics(Collections.singleton(INPUT_TOPIC)).all()
+ val topicDescription = topicDescriptionFutures.get(500, TimeUnit.MILLISECONDS)
+ .get(INPUT_TOPIC)
- done = true
+ done = topicDescription.partitions().size() == TOTAL_TASK_NAMES
+ retries += 1
} catch {
case e: Exception =>
- System.err.println("Got exception while validating test topics. Waiting and retrying.", e)
- retries += 1
- Thread.sleep(500)
+ System.err.println("Interrupted during validating test topics", e)
}
}
- if (retries >= 100) {
+ if (retries >= 10) {
fail("Unable to successfully create topics. Tried to validate %s times." format retries)
}
}
@@ -185,10 +168,10 @@ object StreamTaskTestUtil {
servers.foreach(_.shutdown())
servers.foreach(server => CoreUtils.delete(server.config.logDirs))
- if (zkUtils != null)
- CoreUtils.swallow(zkUtils.close())
+ if (adminClient != null)
+ CoreUtils.swallow(adminClient.close(), null)
if (zookeeper != null)
- CoreUtils.swallow(zookeeper.shutdown())
+ CoreUtils.swallow(zookeeper.shutdown(), null)
Configuration.setConfiguration(null)
}
@@ -253,27 +236,33 @@ class StreamTaskTestUtil {
def readAll(topic: String, maxOffsetInclusive: Int, group: String): List[String] = {
val props = new Properties
- props.put("zookeeper.connect", zkConnect)
+ props.put("bootstrap.servers", brokers)
props.put("group.id", group)
- props.put("auto.offset.reset", "smallest")
+ props.put("auto.offset.reset", "earliest")
+ props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer")
+ props.put("value.deserializer", "org.apache.kafka.common.serialization.ByteArrayDeserializer")
- val consumerConfig = new ConsumerConfig(props)
- val consumerConnector = Consumer.create(consumerConfig)
- val stream = consumerConnector.createMessageStreams(Map(topic -> 1))(topic).head.iterator
- var message: MessageAndMetadata[Array[Byte], Array[Byte]] = null
+ val consumerConnector = new KafkaConsumer(props)
+ consumerConnector.subscribe(Set(topic).asJava)
+
+ var stream = consumerConnector.poll(Duration.ofMillis(10000)).iterator()
+ var message: ConsumerRecord[Nothing, Nothing] = null
var messages = ArrayBuffer[String]()
while (message == null || message.offset < maxOffsetInclusive) {
- message = stream.next
- if (message.message == null) {
- messages += null
+ if (stream.hasNext) {
+ message = stream.next
+ if (message.value() == null) {
+ messages += null
+ } else {
+ messages += new String(message.value, "UTF-8")
+ }
+ System.out.println("StreamTaskTestUtil.readAll(): offset=%s, message=%s" format (message.offset, messages.last))
} else {
- messages += new String(message.message, "UTF-8")
+ stream = consumerConnector.poll(Duration.ofMillis(100)).iterator()
}
- System.err.println("StreamTaskTestUtil.readAll(): offset=%s, message=%s" format (message.offset, messages.last))
- }
- consumerConnector.shutdown
+ }
messages.toList
}