Skip to content

Commit 7041ed3

Browse files
KAFKA-19960: Close pending tasks on shutdown. (#21422)
This PR fixes a bug when KS doesn't close stores if the shutdown was triggered during rebalance where an active tasks gets converted to a standby one and put into pendingTasksToInit * Added logic to close pending tasks to init. * Made standby task closure similar to the one for active tasks. * Added a separate method for getting standby tasks from task registry. * Added an integration test that reproduces the issue. Reviewers: Matthias J. Sax <matthias@confluent.io>
1 parent c076210 commit 7041ed3

8 files changed

Lines changed: 376 additions & 12 deletions

File tree

‎streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/KafkaStreamsWrapper.java‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,11 @@ public List<StreamThread> streamThreads() {
4848
public void setStreamThreadStateListener(final StreamThread.StateListener listener) {
4949
if (state == State.CREATED) {
5050
for (final StreamThread thread : threads) {
51-
thread.setStateListener(listener);
51+
final StreamThread.StateListener originalListener = thread.getStateListener();
52+
thread.setStateListener((t, newState, oldState) -> {
53+
originalListener.onChange(t, newState, oldState);
54+
listener.onChange(t, newState, oldState);
55+
});
5256
}
5357
} else {
5458
throw new IllegalStateException("Can only set StateListener in CREATED state. " +
Lines changed: 244 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,244 @@
1+
/*
2+
* Licensed to the Apache Software Foundation (ASF) under one or more
3+
* contributor license agreements. See the NOTICE file distributed with
4+
* this work for additional information regarding copyright ownership.
5+
* The ASF licenses this file to You under the Apache License, Version 2.0
6+
* (the "License"); you may not use this file except in compliance with
7+
* the License. You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
package org.apache.kafka.streams.integration;
18+
19+
import org.apache.kafka.clients.consumer.ConsumerConfig;
20+
import org.apache.kafka.common.serialization.LongSerializer;
21+
import org.apache.kafka.common.serialization.Serdes;
22+
import org.apache.kafka.common.serialization.StringSerializer;
23+
import org.apache.kafka.common.utils.Bytes;
24+
import org.apache.kafka.common.utils.MockTime;
25+
import org.apache.kafka.streams.KafkaStreams;
26+
import org.apache.kafka.streams.KeyValue;
27+
import org.apache.kafka.streams.StreamsConfig;
28+
import org.apache.kafka.streams.TopologyWrapper;
29+
import org.apache.kafka.streams.integration.utils.EmbeddedKafkaCluster;
30+
import org.apache.kafka.streams.integration.utils.IntegrationTestUtils;
31+
import org.apache.kafka.streams.processor.StateStore;
32+
import org.apache.kafka.streams.processor.StateStoreContext;
33+
import org.apache.kafka.streams.processor.internals.StreamThread;
34+
import org.apache.kafka.streams.state.KeyValueStore;
35+
import org.apache.kafka.streams.state.StoreBuilder;
36+
import org.apache.kafka.streams.state.internals.AbstractStoreBuilder;
37+
import org.apache.kafka.streams.state.internals.CacheFlushListener;
38+
import org.apache.kafka.streams.state.internals.CachedStateStore;
39+
import org.apache.kafka.streams.state.internals.RocksDBStore;
40+
import org.apache.kafka.test.MockApiProcessorSupplier;
41+
import org.apache.kafka.test.TestUtils;
42+
43+
import org.junit.jupiter.api.AfterEach;
44+
import org.junit.jupiter.api.BeforeEach;
45+
import org.junit.jupiter.api.Test;
46+
import org.junit.jupiter.api.TestInfo;
47+
48+
import java.io.IOException;
49+
import java.time.Duration;
50+
import java.util.List;
51+
import java.util.Properties;
52+
import java.util.concurrent.CountDownLatch;
53+
import java.util.concurrent.atomic.AtomicInteger;
54+
55+
import static org.apache.kafka.streams.utils.TestUtils.safeUniqueTestName;
56+
import static org.junit.jupiter.api.Assertions.assertEquals;
57+
58+
public class RebalanceTaskClosureIntegrationTest {
59+
60+
private static final int NUM_BROKERS = 1;
61+
protected static final String INPUT_TOPIC_NAME = "input-topic";
62+
private static final int NUM_PARTITIONS = 3;
63+
64+
private final EmbeddedKafkaCluster cluster = new EmbeddedKafkaCluster(NUM_BROKERS);
65+
66+
private KafkaStreamsWrapper streams1;
67+
private KafkaStreamsWrapper streams2;
68+
private String safeTestName;
69+
70+
@BeforeEach
71+
public void before(final TestInfo testInfo) throws InterruptedException, IOException {
72+
cluster.start();
73+
cluster.createTopic(INPUT_TOPIC_NAME, NUM_PARTITIONS, 1);
74+
safeTestName = safeUniqueTestName(testInfo);
75+
}
76+
77+
@AfterEach
78+
public void after() {
79+
cluster.stop();
80+
if (streams1 != null) {
81+
streams1.close(Duration.ofSeconds(30));
82+
}
83+
if (streams2 != null) {
84+
streams2.close(Duration.ofSeconds(30));
85+
}
86+
}
87+
88+
/**
89+
* The conditions that we need to meet:
90+
* <p><ul>
91+
* <li>There is a task with an open store in {@link org.apache.kafka.streams.processor.internals.TasksRegistry#pendingTasksToInit}</li>
92+
* <li>StreamThread gets into PENDING_SHUTDOWN state, so that {@link StreamThread#isStartingRunningOrPartitionAssigned} returns false
93+
* before we call {@link StreamThread#checkStateUpdater} that would move the task to the StateUpdater </li>
94+
* </ul><p>
95+
* If all conditions are met, {@code TaskManager} needs to correctly close the open store during shutdown.
96+
* <p>
97+
* In order to have a task with an open store in the pending task list we first need to have an active task that gets converted
98+
* to a standby one during rebalance(see {@link org.apache.kafka.streams.processor.internals.TaskManager#closeAndRecycleTasks}).
99+
* Second, we need to avoid the second rebalance, to avoid that the pending tasks is closed during such a rebalance, ie, before we enter the shutdown phase.
100+
* <p>
101+
* For that this test:
102+
* <p><ul>
103+
* <li>starts a KS app and waits for it to fully start</li>
104+
* <li>starts another KS app which will trigger reassignment</li>
105+
* <li>waits for {@link CachedStateStore#clearCache} to be called(it's called during task recycle) and locks on it</li>
106+
* <li>sends a message with wrong types to crash the stream thread (this avoids a second rebalance, and enters shutdown directly)</li>
107+
* <li>shutdowns the first KS app</li>
108+
* <li>releases the lock</li>
109+
* </ul><p>
110+
* At this point {@link org.apache.kafka.streams.processor.internals.TaskManager#shutdown} will be called,
111+
* and we will have a pending task to init with an open store(because tasks keep their stores open during recycle).
112+
* <p>
113+
* This test verifies that the open store is closed during shutdown.
114+
*/
115+
@Test
116+
public void shouldClosePendingTasksToInitAfterRebalance() throws Exception {
117+
final CountDownLatch recycleLatch = new CountDownLatch(1);
118+
final CountDownLatch pendingShutdownLatch = new CountDownLatch(1);
119+
// Count how many times we initialize and close stores
120+
final AtomicInteger initCount = new AtomicInteger();
121+
final AtomicInteger closeCount = new AtomicInteger();
122+
final StoreBuilder<KeyValueStore<Bytes, byte[]>> storeBuilder = new AbstractStoreBuilder<>("testStateStore", Serdes.Integer(), Serdes.ByteArray(), new MockTime()) {
123+
124+
@Override
125+
public KeyValueStore<Bytes, byte[]> build() {
126+
return new TestRocksDBStore(name, recycleLatch, pendingShutdownLatch, initCount, closeCount);
127+
}
128+
};
129+
130+
final TopologyWrapper topology = new TopologyWrapper();
131+
topology.addSource("ingest", INPUT_TOPIC_NAME);
132+
topology.addProcessor("my-processor", new MockApiProcessorSupplier<>(), "ingest");
133+
topology.addStateStore(storeBuilder, "my-processor");
134+
135+
streams1 = new KafkaStreamsWrapper(topology, props("1"));
136+
streams1.setStreamThreadStateListener((t, newState, oldState) -> {
137+
if (newState == StreamThread.State.PENDING_SHUTDOWN) {
138+
pendingShutdownLatch.countDown();
139+
}
140+
});
141+
streams1.start();
142+
143+
TestUtils.waitForCondition(() -> streams1.state() == KafkaStreams.State.RUNNING, "Streams never reached RUNNING state");
144+
145+
streams2 = new KafkaStreamsWrapper(topology, props("2"));
146+
streams2.start();
147+
148+
TestUtils.waitForCondition(() -> streams2.state() == KafkaStreams.State.RUNNING, "Streams never reached RUNNING state");
149+
150+
// starting the second KS app triggered a rebalance. Which in turn will recycle active tasks that need to become standby.
151+
// That's exactly what we are waiting for
152+
recycleLatch.await();
153+
154+
// sending a message with wrong key and value types to trigger a stream thread failure and avoid the second rebalance
155+
// note that writing this message does not trigger the crash right away -- the thread is still blocked inside `poll()` waiting for the shutdown latch to unlock to complete the previous, still ongoing rebalance
156+
IntegrationTestUtils.produceKeyValuesSynchronously(INPUT_TOPIC_NAME, List.of(new KeyValue<>("key", 1L)),
157+
TestUtils.producerConfig(cluster.bootstrapServers(), StringSerializer.class, LongSerializer.class, new Properties()), cluster.time);
158+
// Now we can close both apps. The StreamThreadStateListener will unblock the clearCache call, letting the rebalance finish.
159+
// After the rebalance finished, the "poison pill" record gets picked up crashing the thread,
160+
// and starting the shutdown directly
161+
// We don't want to let the rebalance finish before we trigger the shutdown, because we want the stream thread to stop before it gets to moving pending tasks from task registry to state updater.
162+
streams1.close();
163+
streams2.close();
164+
165+
assertEquals(initCount.get(), closeCount.get());
166+
}
167+
168+
private Properties props(final String storePathSuffix) {
169+
final Properties streamsConfiguration = new Properties();
170+
171+
streamsConfiguration.put(StreamsConfig.APPLICATION_ID_CONFIG, safeTestName);
172+
streamsConfiguration.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, cluster.bootstrapServers());
173+
streamsConfiguration.put(ConsumerConfig.DEFAULT_API_TIMEOUT_MS_CONFIG, 1000);
174+
streamsConfiguration.put(ConsumerConfig.REQUEST_TIMEOUT_MS_CONFIG, 1000);
175+
streamsConfiguration.put(StreamsConfig.STATE_DIR_CONFIG, TestUtils.tempDirectory().getPath() + "/" + storePathSuffix);
176+
streamsConfiguration.put(StreamsConfig.STATESTORE_CACHE_MAX_BYTES_CONFIG, 0);
177+
streamsConfiguration.put(StreamsConfig.COMMIT_INTERVAL_MS_CONFIG, 100L);
178+
streamsConfiguration.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.LongSerde.class);
179+
streamsConfiguration.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.StringSerde.class);
180+
streamsConfiguration.put(StreamsConfig.NUM_STANDBY_REPLICAS_CONFIG, 1);
181+
streamsConfiguration.put("internal.leave.group.on.close", true);
182+
183+
return streamsConfiguration;
184+
}
185+
186+
private static class TestRocksDBStore extends RocksDBStore implements CachedStateStore<Bytes, byte[]> {
187+
188+
private final CountDownLatch recycleLatch;
189+
private final CountDownLatch pendingShutdownLatch;
190+
private final AtomicInteger initCount;
191+
private final AtomicInteger closeCount;
192+
193+
public TestRocksDBStore(final String name,
194+
final CountDownLatch recycleLatch,
195+
final CountDownLatch pendingShutdownLatch,
196+
final AtomicInteger initCount,
197+
final AtomicInteger closeCount) {
198+
super(name, "rocksdb");
199+
this.recycleLatch = recycleLatch;
200+
this.pendingShutdownLatch = pendingShutdownLatch;
201+
this.initCount = initCount;
202+
this.closeCount = closeCount;
203+
}
204+
205+
@Override
206+
public void init(final StateStoreContext stateStoreContext,
207+
final StateStore root) {
208+
initCount.incrementAndGet();
209+
super.init(stateStoreContext, root);
210+
}
211+
212+
@Override
213+
public boolean setFlushListener(final CacheFlushListener<Bytes, byte[]> listener,
214+
final boolean sendOldValues) {
215+
return false;
216+
}
217+
218+
@Override
219+
public void flushCache() {
220+
}
221+
222+
@Override
223+
public void clearCache() {
224+
// Clear cache is called during recycle, so we use it as a hook
225+
recycleLatch.countDown();
226+
try {
227+
// after we signaled via recycleLatch, that the task was converted into a "pending task",
228+
// we block the rebalance to complete, until we get the shutdown signal,
229+
// to avoid that the "pending task" get fully initialized
230+
// (otherwise, we don't have a pending task when the shutdown happens)
231+
pendingShutdownLatch.await();
232+
} catch (final InterruptedException e) {
233+
throw new RuntimeException(e);
234+
}
235+
}
236+
237+
@Override
238+
public synchronized void close() {
239+
closeCount.incrementAndGet();
240+
super.close();
241+
}
242+
}
243+
244+
}

‎streams/src/main/java/org/apache/kafka/streams/processor/internals/TaskManager.java‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1486,10 +1486,20 @@ void shutdown(final boolean clean) {
14861486
// TODO: change type to `StreamTask`
14871487
final Set<Task> activeTasks = new TreeSet<>(Comparator.comparing(Task::id));
14881488
activeTasks.addAll(tasks.activeTasks());
1489+
// TODO: change type to `StandbyTask`
1490+
final Set<Task> standbyTasks = new TreeSet<>(Comparator.comparing(Task::id));
1491+
standbyTasks.addAll(tasks.standbyTasks());
1492+
1493+
final Set<Task> pendingActiveTasks = tasks.drainPendingActiveTasksToInit();
1494+
activeTasks.addAll(pendingActiveTasks);
1495+
tasks.addPendingTasksToClose(pendingActiveTasks);
1496+
final Set<Task> pendingStandbyTasks = tasks.drainPendingStandbyTasksToInit();
1497+
standbyTasks.addAll(pendingStandbyTasks);
1498+
tasks.addPendingTasksToClose(pendingStandbyTasks);
14891499

14901500
executeAndMaybeSwallow(
14911501
clean,
1492-
() -> closeAndCleanUpTasks(activeTasks, standbyTaskIterable(), clean),
1502+
() -> closeAndCleanUpTasks(activeTasks, standbyTasks, clean),
14931503
e -> firstException.compareAndSet(null, e),
14941504
e -> log.warn("Ignoring an exception while unlocking remaining task directories.", e)
14951505
);
@@ -1597,7 +1607,7 @@ private Collection<Task> tryCloseCleanActiveTasks(final Collection<Task> activeT
15971607
final boolean clean,
15981608
final AtomicReference<RuntimeException> firstException) {
15991609
if (!clean) {
1600-
return activeTaskIterable();
1610+
return activeTasksToClose;
16011611
}
16021612
final Comparator<Task> byId = Comparator.comparing(Task::id);
16031613
final Set<Task> tasksToCommit = new TreeSet<>(byId);
@@ -1655,7 +1665,7 @@ private Collection<Task> tryCloseCleanActiveTasks(final Collection<Task> activeT
16551665
}
16561666
}
16571667

1658-
for (final Task task : activeTaskIterable()) {
1668+
for (final Task task : activeTasksToClose) {
16591669
try {
16601670
task.postCommit(true);
16611671
} catch (final RuntimeException e) {
@@ -1690,7 +1700,7 @@ private Collection<Task> tryCloseCleanStandbyTasks(final Collection<Task> standb
16901700
final boolean clean,
16911701
final AtomicReference<RuntimeException> firstException) {
16921702
if (!clean) {
1693-
return standbyTaskIterable();
1703+
return standbyTasksToClose;
16941704
}
16951705
final Set<Task> tasksToCloseDirty = new HashSet<>();
16961706

‎streams/src/main/java/org/apache/kafka/streams/processor/internals/Tasks.java‎

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ class Tasks implements TasksRegistry {
5858
private final Map<TaskId, Set<TopicPartition>> pendingActiveTasksToCreate = new HashMap<>();
5959
private final Map<TaskId, Set<TopicPartition>> pendingStandbyTasksToCreate = new HashMap<>();
6060
private final Set<Task> pendingTasksToInit = new HashSet<>();
61+
private final Set<Task> pendingTasksToClose = new HashSet<>();
6162
private final Set<TaskId> failedTaskIds = new HashSet<>();
6263

6364
// TODO: convert to Stream/StandbyTask when we remove TaskManager#StateMachineTask with mocks
@@ -124,6 +125,20 @@ public Set<Task> drainPendingActiveTasksToInit() {
124125
return result;
125126
}
126127

128+
@Override
129+
public Set<Task> drainPendingStandbyTasksToInit() {
130+
final Set<Task> result = new HashSet<>();
131+
final Iterator<Task> iterator = pendingTasksToInit.iterator();
132+
while (iterator.hasNext()) {
133+
final Task task = iterator.next();
134+
if (!task.isActive()) {
135+
result.add(task);
136+
iterator.remove();
137+
}
138+
}
139+
return result;
140+
}
141+
127142
@Override
128143
public Set<Task> pendingTasksToInit() {
129144
return Collections.unmodifiableSet(pendingTasksToInit);
@@ -139,6 +154,21 @@ public boolean hasPendingTasksToInit() {
139154
return !pendingTasksToInit.isEmpty();
140155
}
141156

157+
@Override
158+
public Set<Task> pendingTasksToClose() {
159+
return Collections.unmodifiableSet(pendingTasksToClose);
160+
}
161+
162+
@Override
163+
public void addPendingTasksToClose(final Collection<Task> tasks) {
164+
pendingTasksToClose.addAll(tasks);
165+
}
166+
167+
@Override
168+
public boolean hasPendingTasksToClose() {
169+
return !pendingTasksToClose.isEmpty();
170+
}
171+
142172
@Override
143173
public void addActiveTasks(final Collection<Task> newTasks) {
144174
if (!newTasks.isEmpty()) {
@@ -193,7 +223,9 @@ public synchronized void removeTask(final Task taskToRemove) {
193223
throw new IllegalStateException("Attempted to remove a task that is not closed or suspended: " + taskId);
194224
}
195225

196-
if (taskToRemove.isActive()) {
226+
if (pendingTasksToClose.contains(taskToRemove)) {
227+
pendingTasksToClose.remove(taskToRemove);
228+
} else if (taskToRemove.isActive()) {
197229
if (activeTasksPerId.remove(taskId) == null) {
198230
throw new IllegalArgumentException("Attempted to remove an active task that is not owned: " + taskId);
199231
}
@@ -203,7 +235,7 @@ public synchronized void removeTask(final Task taskToRemove) {
203235
throw new IllegalArgumentException("Attempted to remove a standby task that is not owned: " + taskId);
204236
}
205237
}
206-
failedTaskIds.remove(taskToRemove.id());
238+
failedTaskIds.remove(taskId);
207239
}
208240

209241
@Override
@@ -312,6 +344,11 @@ public synchronized Collection<Task> activeTasks() {
312344
return Collections.unmodifiableCollection(activeTasksPerId.values());
313345
}
314346

347+
@Override
348+
public synchronized Collection<Task> standbyTasks() {
349+
return Collections.unmodifiableCollection(standbyTasksPerId.values());
350+
}
351+
315352
/**
316353
* All tasks returned by any of the getters are read-only and should NOT be modified;
317354
* and the returned task could be modified by other threads concurrently

0 commit comments

Comments
 (0)