You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@kafka.apache.org by rs...@apache.org on 2019/10/17 12:42:45 UTC
[kafka] branch 2.3 updated: KAKFA-8950: Fix KafkaConsumer Fetcher
breaking on concurrent disconnect (#7511)
This is an automated email from the ASF dual-hosted git repository.
rsivaram pushed a commit to branch 2.3
in repository https://gitbox.apache.org/repos/asf/kafka.git
The following commit(s) were added to refs/heads/2.3 by this push:
new c8676c9 KAKFA-8950: Fix KafkaConsumer Fetcher breaking on concurrent disconnect (#7511)
c8676c9 is described below
commit c8676c996ebc4a583c1efade16393ca9a73f16e5
Author: Will James <ja...@gmail.com>
AuthorDate: Thu Oct 17 05:56:41 2019 -0500
KAKFA-8950: Fix KafkaConsumer Fetcher breaking on concurrent disconnect (#7511)
The KafkaConsumer Fetcher can sometimes get into an invalid state where it believes that there are ongoing fetch requests, but in fact there are none. This may be caused by the heartbeat thread concurrently handling a disconnection event just after the fetcher thread submits a request which would cause the Fetcher to enter an invalid state where it believes it has ongoing requests to the disconnected node but in fact it does not. This is due to a thread safety issue in the Fetcher whe [...]
This PR addresses that thread safety issue by ensuring that the pending node is added to the nodesWithPendingFetchRequests before the listener is added to the future, ensuring the finally block is called after the node is added.
Reviewers: Tom Lee, Jason Gustafson <ja...@confluent.io>, Rajini Sivaram <ra...@googlemail.com>
---
.../kafka/clients/consumer/internals/Fetcher.java | 128 +++++++++++----------
.../java/org/apache/kafka/clients/MockClient.java | 8 ++
.../clients/consumer/internals/FetcherTest.java | 28 +++++
3 files changed, 102 insertions(+), 62 deletions(-)
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/Fetcher.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/Fetcher.java
index e638963..7f3bb34 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/Fetcher.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/Fetcher.java
@@ -245,78 +245,82 @@ public class Fetcher<K, V> implements Closeable {
if (log.isDebugEnabled()) {
log.debug("Sending {} {} to broker {}", isolationLevel, data.toString(), fetchTarget);
}
- client.send(fetchTarget, request)
- .addListener(new RequestFutureListener<ClientResponse>() {
- @Override
- public void onSuccess(ClientResponse resp) {
- synchronized (Fetcher.this) {
- try {
- @SuppressWarnings("unchecked")
- FetchResponse<Records> response = (FetchResponse<Records>) resp.responseBody();
- FetchSessionHandler handler = sessionHandler(fetchTarget.id());
- if (handler == null) {
- log.error("Unable to find FetchSessionHandler for node {}. Ignoring fetch response.",
- fetchTarget.id());
- return;
- }
- if (!handler.handleResponse(response)) {
- return;
- }
+ RequestFuture<ClientResponse> future = client.send(fetchTarget, request);
+ // We add the node to the set of nodes with pending fetch requests before adding the
+ // listener because the future may have been fulfilled on another thread (e.g. during a
+ // disconnection being handled by the heartbeat thread) which will mean the listener
+ // will be invoked synchronously.
+ this.nodesWithPendingFetchRequests.add(entry.getKey().id());
+ future.addListener(new RequestFutureListener<ClientResponse>() {
+ @Override
+ public void onSuccess(ClientResponse resp) {
+ synchronized (Fetcher.this) {
+ try {
+ @SuppressWarnings("unchecked")
+ FetchResponse<Records> response = (FetchResponse<Records>) resp.responseBody();
+ FetchSessionHandler handler = sessionHandler(fetchTarget.id());
+ if (handler == null) {
+ log.error("Unable to find FetchSessionHandler for node {}. Ignoring fetch response.",
+ fetchTarget.id());
+ return;
+ }
+ if (!handler.handleResponse(response)) {
+ return;
+ }
- Set<TopicPartition> partitions = new HashSet<>(response.responseData().keySet());
- FetchResponseMetricAggregator metricAggregator = new FetchResponseMetricAggregator(sensors, partitions);
-
- for (Map.Entry<TopicPartition, FetchResponse.PartitionData<Records>> entry : response.responseData().entrySet()) {
- TopicPartition partition = entry.getKey();
- FetchRequest.PartitionData requestData = data.sessionPartitions().get(partition);
- if (requestData == null) {
- String message;
- if (data.metadata().isFull()) {
- message = MessageFormatter.arrayFormat(
- "Response for missing full request partition: partition={}; metadata={}",
- new Object[]{partition, data.metadata()}).getMessage();
- } else {
- message = MessageFormatter.arrayFormat(
- "Response for missing session request partition: partition={}; metadata={}; toSend={}; toForget={}",
- new Object[]{partition, data.metadata(), data.toSend(), data.toForget()}).getMessage();
- }
-
- // Received fetch response for missing session partition
- throw new IllegalStateException(message);
- } else {
- long fetchOffset = requestData.fetchOffset;
- FetchResponse.PartitionData<Records> fetchData = entry.getValue();
-
- log.debug("Fetch {} at offset {} for partition {} returned fetch data {}",
- isolationLevel, fetchOffset, partition, fetchData);
- completedFetches.add(new CompletedFetch(partition, fetchOffset, fetchData, metricAggregator,
- resp.requestHeader().apiVersion()));
- }
+ Set<TopicPartition> partitions = new HashSet<>(response.responseData().keySet());
+ FetchResponseMetricAggregator metricAggregator = new FetchResponseMetricAggregator(sensors, partitions);
+
+ for (Map.Entry<TopicPartition, FetchResponse.PartitionData<Records>> entry : response.responseData().entrySet()) {
+ TopicPartition partition = entry.getKey();
+ FetchRequest.PartitionData requestData = data.sessionPartitions().get(partition);
+ if (requestData == null) {
+ String message;
+ if (data.metadata().isFull()) {
+ message = MessageFormatter.arrayFormat(
+ "Response for missing full request partition: partition={}; metadata={}",
+ new Object[]{partition, data.metadata()}).getMessage();
+ } else {
+ message = MessageFormatter.arrayFormat(
+ "Response for missing session request partition: partition={}; metadata={}; toSend={}; toForget={}",
+ new Object[]{partition, data.metadata(), data.toSend(), data.toForget()}).getMessage();
}
- sensors.fetchLatency.record(resp.requestLatencyMs());
- } finally {
- nodesWithPendingFetchRequests.remove(fetchTarget.id());
+ // Received fetch response for missing session partition
+ throw new IllegalStateException(message);
+ } else {
+ long fetchOffset = requestData.fetchOffset;
+ FetchResponse.PartitionData<Records> fetchData = entry.getValue();
+
+ log.debug("Fetch {} at offset {} for partition {} returned fetch data {}",
+ isolationLevel, fetchOffset, partition, fetchData);
+ completedFetches.add(new CompletedFetch(partition, fetchOffset, fetchData, metricAggregator,
+ resp.requestHeader().apiVersion()));
}
}
+
+ sensors.fetchLatency.record(resp.requestLatencyMs());
+ } finally {
+ nodesWithPendingFetchRequests.remove(fetchTarget.id());
}
+ }
+ }
- @Override
- public void onFailure(RuntimeException e) {
- synchronized (Fetcher.this) {
- try {
- FetchSessionHandler handler = sessionHandler(fetchTarget.id());
- if (handler != null) {
- handler.handleError(e);
- }
- } finally {
- nodesWithPendingFetchRequests.remove(fetchTarget.id());
- }
+ @Override
+ public void onFailure(RuntimeException e) {
+ synchronized (Fetcher.this) {
+ try {
+ FetchSessionHandler handler = sessionHandler(fetchTarget.id());
+ if (handler != null) {
+ handler.handleError(e);
}
+ } finally {
+ nodesWithPendingFetchRequests.remove(fetchTarget.id());
}
- });
+ }
+ }
+ });
- this.nodesWithPendingFetchRequests.add(entry.getKey().id());
}
return fetchRequestMap.size();
}
diff --git a/clients/src/test/java/org/apache/kafka/clients/MockClient.java b/clients/src/test/java/org/apache/kafka/clients/MockClient.java
index b23005e..b75ac58 100644
--- a/clients/src/test/java/org/apache/kafka/clients/MockClient.java
+++ b/clients/src/test/java/org/apache/kafka/clients/MockClient.java
@@ -73,6 +73,7 @@ public class MockClient implements KafkaClient {
}
private int correlation;
+ private Runnable wakeupHook;
private final Time time;
private final MockMetadataUpdater metadataUpdater;
private final Map<String, ConnectionState> connections = new HashMap<>();
@@ -254,6 +255,9 @@ public class MockClient implements KafkaClient {
numBlockingWakeups--;
notify();
}
+ if (wakeupHook != null) {
+ wakeupHook.run();
+ }
}
private synchronized void maybeAwaitWakeup() {
@@ -545,6 +549,10 @@ public class MockClient implements KafkaClient {
return null;
}
+ public void setWakeupHook(Runnable wakeupHook) {
+ this.wakeupHook = wakeupHook;
+ }
+
/**
* The RequestMatcher provides a way to match a particular request to a response prepared
* through {@link #prepareResponse(RequestMatcher, AbstractResponse)}. Basically this allows testers
diff --git a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/FetcherTest.java b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/FetcherTest.java
index 30d3b72..a1cedd8 100644
--- a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/FetcherTest.java
+++ b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/FetcherTest.java
@@ -115,6 +115,7 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.Collectors;
@@ -3581,6 +3582,33 @@ public class FetcherTest {
assertEquals(selected.id(), -1);
}
+ @Test
+ public void testFetchCompletedBeforeHandlerAdded() {
+ buildFetcher();
+ assignFromUser(singleton(tp0));
+ subscriptions.seek(tp0, 0);
+ fetcher.sendFetches();
+ client.prepareResponse(fullFetchResponse(tp0, buildRecords(1L, 1, 1), Errors.NONE, 100L, 0));
+ consumerClient.poll(time.timer(0));
+ fetchedRecords();
+ Node node = fetcher.selectReadReplica(tp0, subscriptions.position(tp0).currentLeader.leader, time.milliseconds());
+
+ AtomicBoolean wokenUp = new AtomicBoolean(false);
+ client.setWakeupHook(() -> {
+ if (!wokenUp.getAndSet(true)) {
+ consumerClient.disconnectAsync(node);
+ consumerClient.poll(time.timer(0));
+ }
+ });
+
+ assertEquals(1, fetcher.sendFetches());
+
+ consumerClient.disconnectAsync(node);
+ consumerClient.poll(time.timer(0));
+
+ assertEquals(1, fetcher.sendFetches());
+ }
+
private MockClient.RequestMatcher listOffsetRequestMatcher(final long timestamp) {
// matches any list offset request with the provided timestamp
return new MockClient.RequestMatcher() {