You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@kafka.apache.org by jg...@apache.org on 2019/01/24 02:27:19 UTC
[kafka] branch 2.0 updated: KAFKA-6833;
Producer should await metadata for unknown partitions (#6073)
(#6154)
This is an automated email from the ASF dual-hosted git repository.
jgus pushed a commit to branch 2.0
in repository https://gitbox.apache.org/repos/asf/kafka.git
The following commit(s) were added to refs/heads/2.0 by this push:
new 8397a08 KAFKA-6833; Producer should await metadata for unknown partitions (#6073) (#6154)
8397a08 is described below
commit 8397a0802ee3b741e728300e09839e657b6bec13
Author: Robert Yokota <ra...@gmail.com>
AuthorDate: Wed Jan 23 18:27:09 2019 -0800
KAFKA-6833; Producer should await metadata for unknown partitions (#6073) (#6154)
This patch changes the behavior of KafkaProducer.waitOnMetadata to wait up to max.block.ms when the partition specified in the produce request is out of the range of partitions present in the metadata. This improves the user experience in the case when partitions are added to a topic and a client attempts to produce to one of the new partitions before the metadata has propagated to the brokers. Tested with unit tests.
Reviewers: Arjun Satish <ar...@confluent.io>, Jason Gustafson <ja...@confluent.io>
---
.../kafka/clients/producer/KafkaProducer.java | 31 ++--
.../kafka/clients/producer/KafkaProducerTest.java | 177 ++++++++++++---------
.../kafka/api/BaseProducerSendTest.scala | 30 +++-
.../kafka/api/ProducerFailureHandlingTest.scala | 14 +-
4 files changed, 152 insertions(+), 100 deletions(-)
diff --git a/clients/src/main/java/org/apache/kafka/clients/producer/KafkaProducer.java b/clients/src/main/java/org/apache/kafka/clients/producer/KafkaProducer.java
index fec3345..0ebcfb6 100644
--- a/clients/src/main/java/org/apache/kafka/clients/producer/KafkaProducer.java
+++ b/clients/src/main/java/org/apache/kafka/clients/producer/KafkaProducer.java
@@ -925,12 +925,15 @@ public class KafkaProducer<K, V> implements Producer<K, V> {
long begin = time.milliseconds();
long remainingWaitMs = maxWaitMs;
long elapsed;
- // Issue metadata requests until we have metadata for the topic or maxWaitTimeMs is exceeded.
- // In case we already have cached metadata for the topic, but the requested partition is greater
- // than expected, issue an update request only once. This is necessary in case the metadata
+ // Issue metadata requests until we have metadata for the topic and the requested partition,
+ // or until maxWaitTimeMs is exceeded. This is necessary in case the metadata
// is stale and the number of partitions for this topic has increased in the meantime.
do {
- log.trace("Requesting metadata update for topic {}.", topic);
+ if (partition != null) {
+ log.trace("Requesting metadata update for partition {} of topic {}.", partition, topic);
+ } else {
+ log.trace("Requesting metadata update for topic {}.", topic);
+ }
metadata.add(topic);
int version = metadata.requestUpdate();
sender.wakeup();
@@ -938,22 +941,24 @@ public class KafkaProducer<K, V> implements Producer<K, V> {
metadata.awaitUpdate(version, remainingWaitMs);
} catch (TimeoutException ex) {
// Rethrow with original maxWaitMs to prevent logging exception with remainingWaitMs
- throw new TimeoutException("Failed to update metadata after " + maxWaitMs + " ms.");
+ throw new TimeoutException(
+ String.format("Topic %s not present in metadata after %d ms.",
+ topic, maxWaitMs));
}
cluster = metadata.fetch();
elapsed = time.milliseconds() - begin;
- if (elapsed >= maxWaitMs)
- throw new TimeoutException("Failed to update metadata after " + maxWaitMs + " ms.");
+ if (elapsed >= maxWaitMs) {
+ throw new TimeoutException(partitionsCount == null ?
+ String.format("Topic %s not present in metadata after %d ms.",
+ topic, maxWaitMs) :
+ String.format("Partition %d of topic %s with partition count %d is not present in metadata after %d ms.",
+ partition, topic, partitionsCount, maxWaitMs));
+ }
if (cluster.unauthorizedTopics().contains(topic))
throw new TopicAuthorizationException(topic);
remainingWaitMs = maxWaitMs - elapsed;
partitionsCount = cluster.partitionCountForTopic(topic);
- } while (partitionsCount == null);
-
- if (partition != null && partition >= partitionsCount) {
- throw new KafkaException(
- String.format("Invalid partition given with record: %d is not in the range [0...%d).", partition, partitionsCount));
- }
+ } while (partitionsCount == null || (partition != null && partition >= partitionsCount));
return new ClusterAndWaitTime(cluster, elapsed);
}
diff --git a/clients/src/test/java/org/apache/kafka/clients/producer/KafkaProducerTest.java b/clients/src/test/java/org/apache/kafka/clients/producer/KafkaProducerTest.java
index ad72a9e..943a704 100644
--- a/clients/src/test/java/org/apache/kafka/clients/producer/KafkaProducerTest.java
+++ b/clients/src/test/java/org/apache/kafka/clients/producer/KafkaProducerTest.java
@@ -59,6 +59,7 @@ import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
+import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
@@ -72,6 +73,27 @@ import static org.junit.Assert.fail;
@RunWith(PowerMockRunner.class)
@PowerMockIgnore("javax.management.*")
public class KafkaProducerTest {
+ private String topic = "topic";
+ private Collection<Node> nodes = Collections.singletonList(new Node(0, "host1", 1000));
+ private final Cluster emptyCluster = new Cluster(null, nodes,
+ Collections.emptySet(),
+ Collections.emptySet(),
+ Collections.emptySet());
+ private final Cluster onePartitionCluster = new Cluster(
+ "dummy",
+ Collections.singletonList(new Node(0, "host1", 1000)),
+ Collections.singletonList(new PartitionInfo(topic, 0, null, null, null)),
+ Collections.emptySet(),
+ Collections.emptySet());
+ private final Cluster threePartitionCluster = new Cluster(
+ "dummy",
+ Collections.singletonList(new Node(0, "host1", 1000)),
+ Arrays.asList(
+ new PartitionInfo(topic, 0, null, null, null),
+ new PartitionInfo(topic, 1, null, null, null),
+ new PartitionInfo(topic, 2, null, null, null)),
+ Collections.emptySet(),
+ Collections.emptySet());
@Test
public void testConstructorWithSerializers() {
@@ -269,24 +291,12 @@ public class KafkaProducerTest {
Metadata metadata = PowerMock.createNiceMock(Metadata.class);
MemberModifier.field(KafkaProducer.class, "metadata").set(producer, metadata);
- String topic = "topic";
ProducerRecord<String, String> record = new ProducerRecord<>(topic, "value");
- Collection<Node> nodes = Collections.singletonList(new Node(0, "host1", 1000));
- final Cluster emptyCluster = new Cluster(null, nodes,
- Collections.<PartitionInfo>emptySet(),
- Collections.<String>emptySet(),
- Collections.<String>emptySet());
- final Cluster cluster = new Cluster(
- "dummy",
- Collections.singletonList(new Node(0, "host1", 1000)),
- Arrays.asList(new PartitionInfo(topic, 0, null, null, null)),
- Collections.<String>emptySet(),
- Collections.<String>emptySet());
// Expect exactly one fetch for each attempt to refresh while topic metadata is not available
final int refreshAttempts = 5;
EasyMock.expect(metadata.fetch()).andReturn(emptyCluster).times(refreshAttempts - 1);
- EasyMock.expect(metadata.fetch()).andReturn(cluster).once();
+ EasyMock.expect(metadata.fetch()).andReturn(onePartitionCluster).once();
EasyMock.expect(metadata.fetch()).andThrow(new IllegalStateException("Unexpected call to metadata.fetch()")).anyTimes();
PowerMock.replay(metadata);
producer.send(record);
@@ -294,7 +304,7 @@ public class KafkaProducerTest {
// Expect exactly one fetch if topic metadata is available
PowerMock.reset(metadata);
- EasyMock.expect(metadata.fetch()).andReturn(cluster).once();
+ EasyMock.expect(metadata.fetch()).andReturn(onePartitionCluster).once();
EasyMock.expect(metadata.fetch()).andThrow(new IllegalStateException("Unexpected call to metadata.fetch()")).anyTimes();
PowerMock.replay(metadata);
producer.send(record, null);
@@ -302,88 +312,109 @@ public class KafkaProducerTest {
// Expect exactly one fetch if topic metadata is available
PowerMock.reset(metadata);
- EasyMock.expect(metadata.fetch()).andReturn(cluster).once();
+ EasyMock.expect(metadata.fetch()).andReturn(onePartitionCluster).once();
EasyMock.expect(metadata.fetch()).andThrow(new IllegalStateException("Unexpected call to metadata.fetch()")).anyTimes();
PowerMock.replay(metadata);
producer.partitionsFor(topic);
PowerMock.verify(metadata);
}
+ @Test
+ public void testMetadataTimeoutWithMissingTopic() throws Exception {
+ Properties props = new Properties();
+ props.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9999");
+ props.setProperty(ProducerConfig.MAX_BLOCK_MS_CONFIG, "600000");
+ KafkaProducer<String, String> producer = new KafkaProducer<>(props, new StringSerializer(), new StringSerializer());
+ long refreshBackoffMs = 500L;
+ long metadataExpireMs = 60000L;
+ final Metadata metadata = new Metadata(refreshBackoffMs, metadataExpireMs, true,
+ true, new ClusterResourceListeners());
+ final Time time = new MockTime();
+ MemberModifier.field(KafkaProducer.class, "metadata").set(producer, metadata);
+ MemberModifier.field(KafkaProducer.class, "time").set(producer, time);
+
+ Thread t = new Thread() {
+ @Override
+ public void run() {
+ long startTimeMs = System.currentTimeMillis();
+ for (int i = 0; i < 10; i++) {
+ while (!metadata.updateRequested() && System.currentTimeMillis() - startTimeMs < 1000)
+ yield();
+ metadata.update(Cluster.empty(), Collections.singleton(topic), time.milliseconds());
+ time.sleep(60 * 1000L);
+ }
+ }
+ };
+ t.start();
+ // Create a record with a partition higher than the initial (outdated) partition range
+ ProducerRecord<String, String> record = new ProducerRecord<>(topic, 2, null, "value");
+ try {
+ producer.send(record).get();
+ fail("Expect ExecutionException");
+ } catch (ExecutionException e) {
+ // skip
+ }
+ Assert.assertTrue("Topic should still exist in metadata", metadata.containsTopic(topic));
+ }
+
@PrepareOnlyThisForTest(Metadata.class)
@Test
- public void testMetadataFetchOnStaleMetadata() throws Exception {
+ public void testMetadataWithPartitionOutOfRange() throws Exception {
Properties props = new Properties();
props.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9999");
KafkaProducer<String, String> producer = new KafkaProducer<>(props, new StringSerializer(), new StringSerializer());
Metadata metadata = PowerMock.createNiceMock(Metadata.class);
MemberModifier.field(KafkaProducer.class, "metadata").set(producer, metadata);
- String topic = "topic";
- ProducerRecord<String, String> initialRecord = new ProducerRecord<>(topic, "value");
- // Create a record with a partition higher than the initial (outdated) partition range
- ProducerRecord<String, String> extendedRecord = new ProducerRecord<>(topic, 2, null, "value");
- Collection<Node> nodes = Collections.singletonList(new Node(0, "host1", 1000));
- final Cluster emptyCluster = new Cluster(null, nodes,
- Collections.<PartitionInfo>emptySet(),
- Collections.<String>emptySet(),
- Collections.<String>emptySet());
- final Cluster initialCluster = new Cluster(
- "dummy",
- Collections.singletonList(new Node(0, "host1", 1000)),
- Arrays.asList(new PartitionInfo(topic, 0, null, null, null)),
- Collections.<String>emptySet(),
- Collections.<String>emptySet());
- final Cluster extendedCluster = new Cluster(
- "dummy",
- Collections.singletonList(new Node(0, "host1", 1000)),
- Arrays.asList(
- new PartitionInfo(topic, 0, null, null, null),
- new PartitionInfo(topic, 1, null, null, null),
- new PartitionInfo(topic, 2, null, null, null)),
- Collections.<String>emptySet(),
- Collections.<String>emptySet());
+ ProducerRecord<String, String> record = new ProducerRecord<>(topic, 2, null, "value");
- // Expect exactly one fetch for each attempt to refresh while topic metadata is not available
+ // Expect exactly one fetch for each attempt to refresh while topic metadata is stale
final int refreshAttempts = 5;
- EasyMock.expect(metadata.fetch()).andReturn(emptyCluster).times(refreshAttempts - 1);
- EasyMock.expect(metadata.fetch()).andReturn(initialCluster).once();
+ EasyMock.expect(metadata.fetch()).andReturn(onePartitionCluster).times(refreshAttempts - 1);
+ EasyMock.expect(metadata.fetch()).andReturn(threePartitionCluster).once();
EasyMock.expect(metadata.fetch()).andThrow(new IllegalStateException("Unexpected call to metadata.fetch()")).anyTimes();
PowerMock.replay(metadata);
- producer.send(initialRecord);
+ producer.send(record);
PowerMock.verify(metadata);
+ }
- // Expect exactly one fetch if topic metadata is available and records are still within range
- PowerMock.reset(metadata);
- EasyMock.expect(metadata.fetch()).andReturn(initialCluster).once();
- EasyMock.expect(metadata.fetch()).andThrow(new IllegalStateException("Unexpected call to metadata.fetch()")).anyTimes();
- PowerMock.replay(metadata);
- producer.send(initialRecord, null);
- PowerMock.verify(metadata);
+ @Test
+ public void testMetadataTimeoutWithPartitionOutOfRange() throws Exception {
+ Properties props = new Properties();
+ props.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9999");
+ props.setProperty(ProducerConfig.MAX_BLOCK_MS_CONFIG, "600000");
+ KafkaProducer<String, String> producer = new KafkaProducer<>(props, new StringSerializer(), new StringSerializer());
- // Expect exactly two fetches if topic metadata is available but metadata response still returns
- // the same partition size (either because metadata are still stale at the broker too or because
- // there weren't any partitions added in the first place).
- PowerMock.reset(metadata);
- EasyMock.expect(metadata.fetch()).andReturn(initialCluster).once();
- EasyMock.expect(metadata.fetch()).andReturn(initialCluster).once();
- EasyMock.expect(metadata.fetch()).andThrow(new IllegalStateException("Unexpected call to metadata.fetch()")).anyTimes();
- PowerMock.replay(metadata);
+ long refreshBackoffMs = 500L;
+ long metadataExpireMs = 60000L;
+ final Metadata metadata = new Metadata(refreshBackoffMs, metadataExpireMs, true,
+ true, new ClusterResourceListeners());
+ final Time time = new MockTime();
+ MemberModifier.field(KafkaProducer.class, "metadata").set(producer, metadata);
+ MemberModifier.field(KafkaProducer.class, "time").set(producer, time);
+
+ Thread t = new Thread() {
+ @Override
+ public void run() {
+ long startTimeMs = System.currentTimeMillis();
+ for (int i = 0; i < 10; i++) {
+ while (!metadata.updateRequested() && System.currentTimeMillis() - startTimeMs < 1000)
+ yield();
+ metadata.update(onePartitionCluster, Collections.emptySet(), time.milliseconds());
+ time.sleep(60 * 1000L);
+ }
+ }
+ };
+ t.start();
+ // Create a record with a partition higher than the initial (outdated) partition range
+ ProducerRecord<String, String> record = new ProducerRecord<>(topic, 2, null, "value");
try {
- producer.send(extendedRecord, null);
- fail("Expected KafkaException to be raised");
- } catch (KafkaException e) {
- // expected
+ producer.send(record).get();
+ fail("Expect ExecutionException");
+ } catch (ExecutionException e) {
+ // skip
}
- PowerMock.verify(metadata);
-
- // Expect exactly two fetches if topic metadata is available but outdated for the given record
- PowerMock.reset(metadata);
- EasyMock.expect(metadata.fetch()).andReturn(initialCluster).once();
- EasyMock.expect(metadata.fetch()).andReturn(extendedCluster).once();
- EasyMock.expect(metadata.fetch()).andThrow(new IllegalStateException("Unexpected call to metadata.fetch()")).anyTimes();
- PowerMock.replay(metadata);
- producer.send(extendedRecord, null);
- PowerMock.verify(metadata);
+ Assert.assertTrue("Topic should still exist in metadata", metadata.containsTopic(topic));
}
@Test
diff --git a/core/src/test/scala/integration/kafka/api/BaseProducerSendTest.scala b/core/src/test/scala/integration/kafka/api/BaseProducerSendTest.scala
index dc4041f..3bcf668 100644
--- a/core/src/test/scala/integration/kafka/api/BaseProducerSendTest.scala
+++ b/core/src/test/scala/integration/kafka/api/BaseProducerSendTest.scala
@@ -21,20 +21,21 @@ import java.nio.charset.StandardCharsets
import java.util.Properties
import java.util.concurrent.TimeUnit
-import collection.JavaConverters._
import kafka.integration.KafkaServerTestHarness
import kafka.log.LogConfig
import kafka.server.KafkaConfig
import kafka.utils.TestUtils
import org.apache.kafka.clients.consumer.{ConsumerRecord, KafkaConsumer}
import org.apache.kafka.clients.producer._
-import org.apache.kafka.common.{KafkaException, TopicPartition}
+import org.apache.kafka.common.errors.TimeoutException
import org.apache.kafka.common.record.TimestampType
import org.apache.kafka.common.security.auth.SecurityProtocol
+import org.apache.kafka.common.{KafkaException, TopicPartition}
import org.junit.Assert._
import org.junit.{After, Before, Test}
import scala.collection.mutable.{ArrayBuffer, Buffer}
+import scala.collection.JavaConverters._
import scala.concurrent.ExecutionException
abstract class BaseProducerSendTest extends KafkaServerTestHarness {
@@ -68,9 +69,19 @@ abstract class BaseProducerSendTest extends KafkaServerTestHarness {
super.tearDown()
}
- protected def createProducer(brokerList: String, retries: Int = 0, lingerMs: Long = 0, props: Option[Properties] = None): KafkaProducer[Array[Byte],Array[Byte]] = {
- val producer = TestUtils.createProducer(brokerList, securityProtocol = securityProtocol, trustStoreFile = trustStoreFile,
- saslProperties = clientSaslProperties, retries = retries, lingerMs = lingerMs, props = props)
+ protected def createProducer(brokerList: String,
+ retries: Int = 0,
+ lingerMs: Long = 0,
+ maxBlockMs: Long = 60 * 1000L,
+ props: Option[Properties] = None): KafkaProducer[Array[Byte],Array[Byte]] = {
+ val producer = TestUtils.createProducer(brokerList,
+ securityProtocol = securityProtocol,
+ trustStoreFile = trustStoreFile,
+ saslProperties = clientSaslProperties,
+ retries = retries,
+ lingerMs = lingerMs,
+ maxBlockMs = maxBlockMs,
+ props = props)
registerProducer(producer)
}
@@ -346,7 +357,7 @@ abstract class BaseProducerSendTest extends KafkaServerTestHarness {
*/
@Test
def testSendBeforeAndAfterPartitionExpansion() {
- val producer = createProducer(brokerList)
+ val producer = createProducer(brokerList, maxBlockMs = 5 * 1000L)
// create topic
createTopic(topic, 1, 2)
@@ -366,10 +377,13 @@ abstract class BaseProducerSendTest extends KafkaServerTestHarness {
// Trying to send a record to a partition beyond topic's partition range before adding the partition should fail.
val partition1 = 1
try {
- producer.send(new ProducerRecord(topic, partition1, null, "value".getBytes(StandardCharsets.UTF_8)))
+ producer.send(new ProducerRecord(topic, partition1, null, "value".getBytes(StandardCharsets.UTF_8))).get()
fail("Should not allow sending a record to a partition not present in the metadata")
} catch {
- case _: KafkaException => // this is ok
+ case e: ExecutionException => e.getCause match {
+ case _: TimeoutException => // this is ok
+ case ex => throw new Exception("Sending to a partition not present in the metadata should result in a TimeoutException", ex)
+ }
}
val existingAssignment = zkClient.getReplicaAssignmentForTopics(Set(topic)).map {
diff --git a/core/src/test/scala/integration/kafka/api/ProducerFailureHandlingTest.scala b/core/src/test/scala/integration/kafka/api/ProducerFailureHandlingTest.scala
index 9b77c2d..6fda4d1 100644
--- a/core/src/test/scala/integration/kafka/api/ProducerFailureHandlingTest.scala
+++ b/core/src/test/scala/integration/kafka/api/ProducerFailureHandlingTest.scala
@@ -17,7 +17,7 @@
package kafka.api
-import java.util.concurrent.{ExecutionException, TimeoutException}
+import java.util.concurrent.ExecutionException
import java.util.Properties
import kafka.integration.KafkaServerTestHarness
@@ -25,7 +25,6 @@ import kafka.log.LogConfig
import kafka.server.KafkaConfig
import kafka.utils.TestUtils
import org.apache.kafka.clients.producer._
-import org.apache.kafka.common.KafkaException
import org.apache.kafka.common.errors._
import org.apache.kafka.common.internals.Topic
import org.apache.kafka.common.record.{DefaultRecord, DefaultRecordBatch}
@@ -182,8 +181,8 @@ class ProducerFailureHandlingTest extends KafkaServerTestHarness {
}
/**
- * Send with invalid partition id should throw KafkaException when partition is higher than the upper bound of
- * partitions.
+ * Send with invalid partition id should return ExecutionException caused by TimeoutException
+ * when partition is higher than the upper bound of partitions.
*/
@Test
def testInvalidPartition() {
@@ -192,8 +191,11 @@ class ProducerFailureHandlingTest extends KafkaServerTestHarness {
// create a record with incorrect partition id (higher than the number of partitions), send should fail
val higherRecord = new ProducerRecord(topic1, 1, "key".getBytes, "value".getBytes)
- intercept[KafkaException] {
- producer1.send(higherRecord)
+ intercept[ExecutionException] {
+ producer1.send(higherRecord).get
+ }.getCause match {
+ case _: TimeoutException => // this is ok
+ case ex => throw new Exception("Sending to a partition not present in the metadata should result in a TimeoutException", ex)
}
}