You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@fluss.apache.org by ja...@apache.org on 2026/07/19 14:35:04 UTC
(fluss) branch main updated: [kv] Close KV tablets concurrently during shutdown (#3651)
This is an automated email from the ASF dual-hosted git repository.
wuchong pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/fluss.git
The following commit(s) were added to refs/heads/main by this push:
new 7d410bc0f [kv] Close KV tablets concurrently during shutdown (#3651)
7d410bc0f is described below
commit 7d410bc0f560c47b5b5f12f2a8f7e58d13662856
Author: yunhong <33...@qq.com>
AuthorDate: Sun Jul 19 22:34:59 2026 +0800
[kv] Close KV tablets concurrently during shutdown (#3651)
---
.../java/org/apache/fluss/server/ServerBase.java | 54 ++++--
.../org/apache/fluss/server/TabletManagerBase.java | 37 ++++
.../java/org/apache/fluss/server/kv/KvManager.java | 16 +-
.../java/org/apache/fluss/server/kv/KvTablet.java | 2 +-
.../org/apache/fluss/server/log/LogManager.java | 106 +++++-------
.../apache/fluss/server/tablet/TabletServer.java | 79 +++++++--
.../org/apache/fluss/server/ServerBaseTest.java | 190 +++++++++++++++++++++
.../apache/fluss/server/TabletManagerBaseTest.java | 110 ++++++++++++
.../org/apache/fluss/server/kv/KvManagerTest.java | 105 ++++++++++++
.../apache/fluss/server/log/LogManagerTest.java | 21 +++
.../server/tablet/TabletServerShutdownITCase.java | 54 ++++--
.../server/tablet/TabletServerShutdownTest.java | 133 +++++++++++++++
12 files changed, 793 insertions(+), 114 deletions(-)
diff --git a/fluss-server/src/main/java/org/apache/fluss/server/ServerBase.java b/fluss-server/src/main/java/org/apache/fluss/server/ServerBase.java
index 762aaba06..64b7ed768 100644
--- a/fluss-server/src/main/java/org/apache/fluss/server/ServerBase.java
+++ b/fluss-server/src/main/java/org/apache/fluss/server/ServerBase.java
@@ -36,6 +36,7 @@ import org.apache.fluss.server.utils.ShutdownHookUtil;
import org.apache.fluss.server.utils.SignalHandler;
import org.apache.fluss.utils.AutoCloseableAsync;
import org.apache.fluss.utils.ExceptionUtils;
+import org.apache.fluss.utils.concurrent.ExecutorThreadFactory;
import org.apache.fluss.utils.concurrent.FutureUtils;
import org.slf4j.Logger;
@@ -49,6 +50,7 @@ import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicBoolean;
import static org.apache.fluss.server.utils.LogShutdownUtil.shutdownLogIfPossible;
@@ -77,12 +79,14 @@ public abstract class ServerBase implements AutoCloseableAsync, FatalErrorHandle
protected FileSystem remoteFileSystem;
protected PluginManager pluginManager;
+ private final AtomicBoolean fatalErrorShutdownTriggered = new AtomicBoolean();
+
+ private Thread shutDownHook;
+
protected ServerBase(Configuration conf) {
this.conf = conf;
}
- private Thread shutDownHook;
-
protected static Configuration loadConfiguration(String[] args, String serverClassName) {
try {
return ConfigurationParserUtils.loadCommonConfiguration(args, serverClassName);
@@ -175,20 +179,44 @@ public abstract class ServerBase implements AutoCloseableAsync, FatalErrorHandle
"Fatal error occurred while running the {}. Shutting it down...",
getServerName(),
exception);
- if (ExceptionUtils.isJvmFatalError(exception)) {
- System.exit(-1);
- } else {
- closeAsync(Result.FAILURE);
- FutureUtils.orTimeout(
- getTerminationFuture(),
- FATAL_ERROR_SHUTDOWN_TIMEOUT_MS,
- TimeUnit.MILLISECONDS,
- String.format(
- "Waiting for %s shutting down timed out after %s ms.",
- getServerName(), FATAL_ERROR_SHUTDOWN_TIMEOUT_MS));
+ if (ExceptionUtils.isJvmFatalOrOutOfMemoryError(exception)) {
+ exitJvm();
+ } else if (fatalErrorShutdownTriggered.compareAndSet(false, true)) {
+ try {
+ FutureUtils.orTimeout(
+ getTerminationFuture(),
+ FATAL_ERROR_SHUTDOWN_TIMEOUT_MS,
+ TimeUnit.MILLISECONDS,
+ String.format(
+ "Waiting for %s shutting down timed out after %s ms.",
+ getServerName(), FATAL_ERROR_SHUTDOWN_TIMEOUT_MS));
+ startFatalErrorShutdownThread();
+ } catch (Throwable shutdownFailure) {
+ try {
+ LOG.error(
+ "Failed to start fatal-error shutdown for {}. Terminating the process.",
+ getServerName(),
+ shutdownFailure);
+ } finally {
+ exitJvm();
+ }
+ }
}
}
+ @VisibleForTesting
+ void startFatalErrorShutdownThread() {
+ Thread shutdownThread =
+ new ExecutorThreadFactory(getServerName() + "-fatal-error-shutdown")
+ .newThread(() -> closeAsync(Result.FAILURE));
+ shutdownThread.start();
+ }
+
+ @VisibleForTesting
+ void exitJvm() {
+ System.exit(-1);
+ }
+
@Override
public CompletableFuture<Void> closeAsync() {
ShutdownHookUtil.removeShutdownHook(shutDownHook, getServerName(), LOG);
diff --git a/fluss-server/src/main/java/org/apache/fluss/server/TabletManagerBase.java b/fluss-server/src/main/java/org/apache/fluss/server/TabletManagerBase.java
index 5eb88df77..6ab15dc83 100644
--- a/fluss-server/src/main/java/org/apache/fluss/server/TabletManagerBase.java
+++ b/fluss-server/src/main/java/org/apache/fluss/server/TabletManagerBase.java
@@ -43,14 +43,17 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
+import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
+import java.util.function.Consumer;
import java.util.stream.Collectors;
import static org.apache.fluss.utils.FlussPaths.KV_TABLET_DIR_PREFIX;
@@ -149,6 +152,40 @@ public abstract class TabletManagerBase {
return Executors.newFixedThreadPool(recoveryThreads, new ExecutorThreadFactory(poolName));
}
+ /**
+ * Closes the given tablets concurrently and returns a future that completes after all close
+ * operations have finished.
+ *
+ * <p>The closing thread pool is shut down automatically after all close operations complete.
+ * The caller is responsible for handling exceptions inside the close action if one failed
+ * tablet should not prevent the remaining shutdown steps from running.
+ *
+ * @param tablets tablets to close
+ * @param poolName name of the closing thread pool
+ * @param closeAction action that closes a tablet
+ * @param <T> type of tablet
+ * @return a future that completes after all tablets have been closed
+ */
+ protected <T> CompletableFuture<Void> closeTabletsConcurrently(
+ Collection<T> tablets, String poolName, Consumer<T> closeAction) {
+ LOG.info(
+ "Closing {} tablets with up to {} threads in pool {}.",
+ tablets.size(),
+ recoveryThreads,
+ poolName);
+ ExecutorService closingPool = createThreadPool(poolName);
+ List<CompletableFuture<Void>> closingFutures = new ArrayList<>(tablets.size());
+ for (T tablet : tablets) {
+ closingFutures.add(
+ CompletableFuture.runAsync(() -> closeAction.accept(tablet), closingPool));
+ }
+
+ CompletableFuture<Void> closingFuture =
+ CompletableFuture.allOf(
+ closingFutures.toArray(new CompletableFuture<?>[closingFutures.size()]));
+ return closingFuture.whenComplete((ignored, throwable) -> closingPool.shutdown());
+ }
+
/**
* Get the tablet directory with given directory name for the given data directory, table path
* and table bucket.
diff --git a/fluss-server/src/main/java/org/apache/fluss/server/kv/KvManager.java b/fluss-server/src/main/java/org/apache/fluss/server/kv/KvManager.java
index 9f2f1f426..6a5c6079c 100644
--- a/fluss-server/src/main/java/org/apache/fluss/server/kv/KvManager.java
+++ b/fluss-server/src/main/java/org/apache/fluss/server/kv/KvManager.java
@@ -206,13 +206,7 @@ public final class KvManager extends TabletManagerBase implements ServerReconfig
LOG.info("Shutting down KvManager");
isShutdown = true;
List<KvTablet> kvs = new ArrayList<>(currentKvs.values());
- for (KvTablet kvTablet : kvs) {
- try {
- kvTablet.close();
- } catch (Exception e) {
- LOG.warn("Exception while closing kv tablet {}.", kvTablet.getTableBucket(), e);
- }
- }
+ closeTabletsConcurrently(kvs, "kv-tablet-closing", this::closeKvTablet).join();
arrowBufferAllocator.close();
memorySegmentPool.close();
if (sharedRocksDBRateLimiter != null) {
@@ -221,6 +215,14 @@ public final class KvManager extends TabletManagerBase implements ServerReconfig
LOG.info("Shut down KvManager complete.");
}
+ private void closeKvTablet(KvTablet kvTablet) {
+ try {
+ kvTablet.close();
+ } catch (Exception e) {
+ LOG.warn("Exception while closing kv tablet {}.", kvTablet.getTableBucket(), e);
+ }
+ }
+
/**
* If the kv already exists, just return a copy of the existing kv. Otherwise, create a kv for
* the given table and the given bucket.
diff --git a/fluss-server/src/main/java/org/apache/fluss/server/kv/KvTablet.java b/fluss-server/src/main/java/org/apache/fluss/server/kv/KvTablet.java
index 0683f5e05..da6b51826 100644
--- a/fluss-server/src/main/java/org/apache/fluss/server/kv/KvTablet.java
+++ b/fluss-server/src/main/java/org/apache/fluss/server/kv/KvTablet.java
@@ -842,7 +842,7 @@ public final class KvTablet {
}
public void close() throws Exception {
- LOG.info("close kv tablet {} for table {}.", tableBucket, physicalPath);
+ LOG.debug("close kv tablet {} for table {}.", tableBucket, physicalPath);
inWriteLock(
kvLock,
() -> {
diff --git a/fluss-server/src/main/java/org/apache/fluss/server/log/LogManager.java b/fluss-server/src/main/java/org/apache/fluss/server/log/LogManager.java
index f85ff0627..818871995 100644
--- a/fluss-server/src/main/java/org/apache/fluss/server/log/LogManager.java
+++ b/fluss-server/src/main/java/org/apache/fluss/server/log/LogManager.java
@@ -59,6 +59,8 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
@@ -473,70 +475,69 @@ public final class LogManager extends TabletManagerBase {
logsByDataDir.computeIfAbsent(dataDir, ignored -> new ArrayList<>()).add(logTablet);
}
- List<LogShutdownTask> shutdownTasks = new ArrayList<>();
+ Map<File, CompletableFuture<Void>> closingFuturesByDataDir = new LinkedHashMap<>();
for (Map.Entry<File, List<LogTablet>> entry : logsByDataDir.entrySet()) {
- shutdownTasks.add(shutdownLogsInDir(entry.getKey(), entry.getValue()));
+ File dataDir = entry.getKey();
+ List<LogTablet> logs = entry.getValue();
+ String dataDirAbsolutePath = dataDir.getAbsolutePath();
+ LOG.info("Shutting down {} logs in dir {}", logs.size(), dataDirAbsolutePath);
+ closingFuturesByDataDir.put(
+ dataDir,
+ closeTabletsConcurrently(
+ logs,
+ "log-tablet-closing-" + dataDirAbsolutePath,
+ this::closeLogTablet));
}
- try {
- for (LogShutdownTask shutdownTask : shutdownTasks) {
- waitForShutdownLogsInDir(shutdownTask);
- }
- } finally {
- for (LogShutdownTask shutdownTask : shutdownTasks) {
- shutdownTask.pool.shutdown();
- }
+ for (Map.Entry<File, List<LogTablet>> entry : logsByDataDir.entrySet()) {
+ waitForShutdownLogsInDir(
+ entry.getKey(), entry.getValue(), closingFuturesByDataDir.get(entry.getKey()));
}
LOG.info("Shut down LogManager complete.");
}
- private LogShutdownTask shutdownLogsInDir(File dataDir, List<LogTablet> logs) {
- String dataDirAbsolutePath = dataDir.getAbsolutePath();
- LOG.info("Shutting down {} logs in dir {}", logs.size(), dataDirAbsolutePath);
-
- List<Future<?>> jobsForTabletDir = new ArrayList<>();
- ExecutorService pool = createThreadPool("log-tablet-closing-" + dataDirAbsolutePath);
- for (LogTablet logTablet : logs) {
- Runnable runnable =
- () -> {
- try {
- logTablet.flush(true);
- logTablet.close();
- } catch (IOException e) {
- throw new FlussRuntimeException(e);
- }
- };
- jobsForTabletDir.add(pool.submit(runnable));
+ private void closeLogTablet(LogTablet logTablet) {
+ try {
+ logTablet.flush(true);
+ logTablet.close();
+ } catch (IOException e) {
+ LOG.warn("Exception while closing log tablet {}.", logTablet.getTableBucket(), e);
+ throw new FlussRuntimeException(e);
+ } catch (RuntimeException | Error e) {
+ LOG.warn("Exception while closing log tablet {}.", logTablet.getTableBucket(), e);
+ throw e;
}
- return new LogShutdownTask(dataDir, logs, pool, jobsForTabletDir);
}
- private void waitForShutdownLogsInDir(LogShutdownTask shutdownTask) {
- for (Future<?> future : shutdownTask.jobs) {
- try {
- future.get();
- } catch (InterruptedException e) {
- LOG.warn("Interrupted while shutting down LogManager.");
- } catch (ExecutionException e) {
- LOG.warn("There was an error in one of the threads during LogManager shutdown", e);
- }
+ private void waitForShutdownLogsInDir(
+ File dataDir, List<LogTablet> logs, CompletableFuture<Void> closingFuture) {
+ boolean closeSucceeded;
+ try {
+ closingFuture.join();
+ closeSucceeded = true;
+ } catch (CompletionException e) {
+ closeSucceeded = false;
+ LOG.warn(
+ "One or more log tablets in directory {} failed to close. See preceding warnings for details.",
+ dataDir);
}
- checkpointRecoveryOffsets(shutdownTask.dataDir, shutdownTask.logs);
+ checkpointRecoveryOffsets(dataDir, logs);
// mark that the shutdown was clean by creating marker file for log dirs that all logs have
// been recovered at startup time.
- if (loadLogsCompletedFlag) {
+ if (loadLogsCompletedFlag && closeSucceeded) {
try {
- LOG.debug("Writing clean shutdown marker for directory {}.", shutdownTask.dataDir);
- Files.createFile(new File(shutdownTask.dataDir, CLEAN_SHUTDOWN_FILE).toPath());
+ LOG.debug("Writing clean shutdown marker for directory {}.", dataDir);
+ Files.createFile(new File(dataDir, CLEAN_SHUTDOWN_FILE).toPath());
} catch (IOException e) {
- LOG.warn(
- "Failed to write clean shutdown marker for directory {}.",
- shutdownTask.dataDir,
- e);
+ LOG.warn("Failed to write clean shutdown marker for directory {}.", dataDir, e);
}
+ } else if (!closeSucceeded) {
+ LOG.warn(
+ "Skipping clean shutdown marker for directory {} because not all logs closed successfully.",
+ dataDir);
}
}
@@ -678,19 +679,4 @@ public final class LogManager extends TabletManagerBase {
LOG.warn("Failed to delete empty directory {}: {}", dir, e.getMessage());
}
}
-
- private static final class LogShutdownTask {
- private final File dataDir;
- private final List<LogTablet> logs;
- private final ExecutorService pool;
- private final List<Future<?>> jobs;
-
- private LogShutdownTask(
- File dataDir, List<LogTablet> logs, ExecutorService pool, List<Future<?>> jobs) {
- this.dataDir = dataDir;
- this.logs = logs;
- this.pool = pool;
- this.jobs = jobs;
- }
- }
}
diff --git a/fluss-server/src/main/java/org/apache/fluss/server/tablet/TabletServer.java b/fluss-server/src/main/java/org/apache/fluss/server/tablet/TabletServer.java
index afbb3ffe0..3d1ad4ef7 100644
--- a/fluss-server/src/main/java/org/apache/fluss/server/tablet/TabletServer.java
+++ b/fluss-server/src/main/java/org/apache/fluss/server/tablet/TabletServer.java
@@ -70,6 +70,7 @@ import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
+import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@@ -431,7 +432,7 @@ public class TabletServer extends ServerBase {
exception = ExceptionUtils.firstOrSuppressed(t, exception);
}
- final Collection<CompletableFuture<Void>> terminationFutures = new ArrayList<>(2);
+ final Collection<CompletableFuture<Void>> terminationFutures = new ArrayList<>(1);
try {
if (metricRegistry != null) {
terminationFutures.add(metricRegistry.closeAsync());
@@ -440,14 +441,26 @@ public class TabletServer extends ServerBase {
exception = ExceptionUtils.firstOrSuppressed(t, exception);
}
+ CompletableFuture<Void> rpcServerTerminationFuture =
+ CompletableFuture.completedFuture(null);
try {
- if (rpcServer != null) {
- terminationFutures.add(rpcServer.closeAsync());
- }
+ rpcServerTerminationFuture = shutdownRpcServer();
} catch (Throwable t) {
exception = ExceptionUtils.firstOrSuppressed(t, exception);
}
+ // Stop dispatching new RPC calls and drain the request processors before shutting down
+ // the components that can access tablets. RPC calls may leave delayed operations
+ // behind; ReplicaManager is shut down below before the tablet managers to stop those
+ // operations as well as snapshot and replica-fetcher activity.
+ try {
+ rpcServerTerminationFuture.join();
+ } catch (Throwable t) {
+ exception =
+ ExceptionUtils.firstOrSuppressed(
+ ExceptionUtils.stripCompletionException(t), exception);
+ }
+
try {
if (tabletService != null) {
tabletService.shutdown();
@@ -489,23 +502,23 @@ public class TabletServer extends ServerBase {
if (scannerManager != null) {
scannerManager.close();
}
+ } catch (Throwable t) {
+ exception = ExceptionUtils.firstOrSuppressed(t, exception);
+ }
- if (kvManager != null) {
- kvManager.shutdown();
- }
-
- if (remoteLogManager != null) {
- remoteLogManager.close();
- }
-
- if (logManager != null) {
- logManager.shutdown();
- }
+ try {
+ shutdownReplicaManager();
+ } catch (Throwable t) {
+ exception = ExceptionUtils.firstOrSuppressed(t, exception);
+ }
- if (replicaManager != null) {
- replicaManager.shutdown();
- }
+ try {
+ shutdownTabletManagers();
+ } catch (Throwable t) {
+ exception = ExceptionUtils.firstOrSuppressed(t, exception);
+ }
+ try {
if (localDiskManager != null) {
localDiskManager.close();
}
@@ -541,6 +554,36 @@ public class TabletServer extends ServerBase {
}
}
+ @VisibleForTesting
+ CompletableFuture<Void> shutdownRpcServer() {
+ if (rpcServer != null) {
+ return rpcServer.closeAsync();
+ }
+ return CompletableFuture.completedFuture(null);
+ }
+
+ @VisibleForTesting
+ void shutdownReplicaManager() throws InterruptedException {
+ if (replicaManager != null) {
+ replicaManager.shutdown();
+ }
+ }
+
+ @VisibleForTesting
+ void shutdownTabletManagers() throws IOException {
+ if (kvManager != null) {
+ kvManager.shutdown();
+ }
+
+ if (remoteLogManager != null) {
+ remoteLogManager.close();
+ }
+
+ if (logManager != null) {
+ logManager.shutdown();
+ }
+ }
+
private void controlledShutDown() {
long startTime = System.currentTimeMillis();
LOG.info("Starting controlled shutdown.");
diff --git a/fluss-server/src/test/java/org/apache/fluss/server/ServerBaseTest.java b/fluss-server/src/test/java/org/apache/fluss/server/ServerBaseTest.java
new file mode 100644
index 000000000..5fb3ca3e5
--- /dev/null
+++ b/fluss-server/src/test/java/org/apache/fluss/server/ServerBaseTest.java
@@ -0,0 +1,190 @@
+/*
+ * 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.fluss.server;
+
+import org.apache.fluss.config.Configuration;
+import org.apache.fluss.exception.FlussRuntimeException;
+import org.apache.fluss.server.authorizer.Authorizer;
+
+import org.junit.jupiter.api.Test;
+
+import javax.annotation.Nullable;
+
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CountDownLatch;
+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.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/** Test for {@link ServerBase}. */
+final class ServerBaseTest {
+
+ @Test
+ void testFatalErrorTriggersShutdownOnDedicatedThread() throws Exception {
+ CountDownLatch shutdownStarted = new CountDownLatch(1);
+ CountDownLatch finishShutdown = new CountDownLatch(1);
+ AtomicReference<Thread> fatalErrorCaller = new AtomicReference<>();
+ AtomicReference<Thread> shutdownThread = new AtomicReference<>();
+ TestingServer server = new TestingServer(shutdownStarted, finishShutdown, shutdownThread);
+ ExecutorService callerExecutor = Executors.newSingleThreadExecutor();
+ Future<?> fatalErrorCall =
+ callerExecutor.submit(
+ () -> {
+ fatalErrorCaller.set(Thread.currentThread());
+ server.onFatalError(new FlussRuntimeException("Expected fatal error."));
+ });
+
+ try {
+ fatalErrorCall.get(5, TimeUnit.SECONDS);
+ assertThat(shutdownStarted.await(5, TimeUnit.SECONDS)).isTrue();
+ assertThat(server.getTerminationFuture().isDone()).isFalse();
+ assertThat(shutdownThread.get()).isNotEqualTo(fatalErrorCaller.get());
+
+ server.onFatalError(new FlussRuntimeException("Another expected fatal error."));
+ assertThat(server.getShutdownCalls()).isOne();
+
+ finishShutdown.countDown();
+ assertThat(server.getTerminationFuture().get(5, TimeUnit.SECONDS))
+ .isEqualTo(ServerBase.Result.FAILURE);
+ } finally {
+ finishShutdown.countDown();
+ callerExecutor.shutdownNow();
+ }
+ }
+
+ @Test
+ void testOutOfMemoryErrorTerminatesJvmWithoutStartingShutdown() {
+ TestingServer server = createTestingServer();
+
+ server.onFatalError(new OutOfMemoryError("Expected out-of-memory error."));
+
+ assertThat(server.getJvmExitCalls()).isOne();
+ assertThat(server.getShutdownCalls()).isZero();
+ }
+
+ @Test
+ void testShutdownThreadStartFailureTerminatesJvm() {
+ TestingServer server = createTestingServer();
+ server.failFatalErrorShutdownThreadStart();
+
+ try {
+ server.onFatalError(new FlussRuntimeException("Expected fatal error."));
+
+ assertThat(server.getJvmExitCalls()).isOne();
+ assertThat(server.getShutdownCalls()).isZero();
+ } finally {
+ server.completeTermination();
+ }
+ }
+
+ private static TestingServer createTestingServer() {
+ return new TestingServer(
+ new CountDownLatch(1), new CountDownLatch(0), new AtomicReference<>());
+ }
+
+ private static final class TestingServer extends ServerBase {
+ private final CountDownLatch shutdownStarted;
+ private final CountDownLatch finishShutdown;
+ private final AtomicReference<Thread> shutdownThread;
+ private final CompletableFuture<Result> terminationFuture = new CompletableFuture<>();
+ private final AtomicInteger shutdownCalls = new AtomicInteger();
+ private final AtomicInteger jvmExitCalls = new AtomicInteger();
+ private boolean failFatalErrorShutdownThreadStart;
+
+ private TestingServer(
+ CountDownLatch shutdownStarted,
+ CountDownLatch finishShutdown,
+ AtomicReference<Thread> shutdownThread) {
+ super(new Configuration());
+ this.shutdownStarted = shutdownStarted;
+ this.finishShutdown = finishShutdown;
+ this.shutdownThread = shutdownThread;
+ }
+
+ @Override
+ protected void startServices() {}
+
+ @Override
+ protected CompletableFuture<Result> closeAsync(Result result) {
+ shutdownCalls.incrementAndGet();
+ shutdownThread.set(Thread.currentThread());
+ shutdownStarted.countDown();
+ await(finishShutdown);
+ terminationFuture.complete(result);
+ return terminationFuture;
+ }
+
+ @Override
+ protected CompletableFuture<Result> getTerminationFuture() {
+ return terminationFuture;
+ }
+
+ @Override
+ protected String getServerName() {
+ return "testing-server";
+ }
+
+ @Override
+ void startFatalErrorShutdownThread() {
+ if (failFatalErrorShutdownThreadStart) {
+ throw new OutOfMemoryError("unable to create new native thread");
+ }
+ super.startFatalErrorShutdownThread();
+ }
+
+ @Override
+ void exitJvm() {
+ jvmExitCalls.incrementAndGet();
+ }
+
+ @Override
+ public @Nullable Authorizer getAuthorizer() {
+ return null;
+ }
+
+ private int getShutdownCalls() {
+ return shutdownCalls.get();
+ }
+
+ private int getJvmExitCalls() {
+ return jvmExitCalls.get();
+ }
+
+ private void failFatalErrorShutdownThreadStart() {
+ failFatalErrorShutdownThreadStart = true;
+ }
+
+ private void completeTermination() {
+ terminationFuture.complete(Result.FAILURE);
+ }
+
+ private static void await(CountDownLatch latch) {
+ try {
+ latch.await();
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new FlussRuntimeException("Interrupted while waiting to finish shutdown.", e);
+ }
+ }
+ }
+}
diff --git a/fluss-server/src/test/java/org/apache/fluss/server/TabletManagerBaseTest.java b/fluss-server/src/test/java/org/apache/fluss/server/TabletManagerBaseTest.java
new file mode 100644
index 000000000..498c9b95f
--- /dev/null
+++ b/fluss-server/src/test/java/org/apache/fluss/server/TabletManagerBaseTest.java
@@ -0,0 +1,110 @@
+/*
+ * 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.fluss.server;
+
+import org.apache.fluss.config.Configuration;
+import org.apache.fluss.exception.FlussRuntimeException;
+
+import org.junit.jupiter.api.Test;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Consumer;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+/** Test for {@link TabletManagerBase}. */
+final class TabletManagerBaseTest {
+
+ @Test
+ void testCloseTabletsConcurrentlyWaitsForAllTasksAndShutsDownPoolOnFailure() throws Exception {
+ TestingTabletManager tabletManager = new TestingTabletManager(2);
+ CountDownLatch failedCloseAttempted = new CountDownLatch(1);
+ CountDownLatch blockedCloseStarted = new CountDownLatch(1);
+ CountDownLatch finishBlockedClose = new CountDownLatch(1);
+ AtomicBoolean blockedCloseCompleted = new AtomicBoolean();
+
+ CompletableFuture<Void> closingFuture =
+ tabletManager.closeTablets(
+ Arrays.asList(0, 1),
+ tablet -> {
+ if (tablet == 0) {
+ failedCloseAttempted.countDown();
+ throw new FlussRuntimeException("Expected close failure.");
+ }
+
+ blockedCloseStarted.countDown();
+ await(finishBlockedClose);
+ blockedCloseCompleted.set(true);
+ });
+
+ try {
+ assertThat(failedCloseAttempted.await(10, TimeUnit.SECONDS)).isTrue();
+ assertThat(blockedCloseStarted.await(10, TimeUnit.SECONDS)).isTrue();
+ assertThat(closingFuture.isDone()).isFalse();
+ } finally {
+ finishBlockedClose.countDown();
+ }
+
+ assertThatThrownBy(() -> closingFuture.get(10, TimeUnit.SECONDS))
+ .isInstanceOf(ExecutionException.class)
+ .hasCauseInstanceOf(FlussRuntimeException.class);
+ assertThat(blockedCloseCompleted.get()).isTrue();
+ assertThat(tabletManager.getClosingPool().isShutdown()).isTrue();
+ }
+
+ private static void await(CountDownLatch latch) {
+ try {
+ latch.await();
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new FlussRuntimeException("Interrupted while waiting to finish tablet close.", e);
+ }
+ }
+
+ private static final class TestingTabletManager extends TabletManagerBase {
+ private ExecutorService closingPool;
+
+ private TestingTabletManager(int closingThreads) {
+ super(TabletType.KV, Collections.emptyList(), new Configuration(), closingThreads);
+ }
+
+ private CompletableFuture<Void> closeTablets(
+ List<Integer> tablets, Consumer<Integer> closeAction) {
+ return closeTabletsConcurrently(tablets, "testing-tablet-closing", closeAction);
+ }
+
+ @Override
+ protected ExecutorService createThreadPool(String poolName) {
+ closingPool = super.createThreadPool(poolName);
+ return closingPool;
+ }
+
+ private ExecutorService getClosingPool() {
+ return closingPool;
+ }
+ }
+}
diff --git a/fluss-server/src/test/java/org/apache/fluss/server/kv/KvManagerTest.java b/fluss-server/src/test/java/org/apache/fluss/server/kv/KvManagerTest.java
index 2c54c1665..530e92f4f 100644
--- a/fluss-server/src/test/java/org/apache/fluss/server/kv/KvManagerTest.java
+++ b/fluss-server/src/test/java/org/apache/fluss/server/kv/KvManagerTest.java
@@ -20,6 +20,7 @@ package org.apache.fluss.server.kv;
import org.apache.fluss.config.ConfigOptions;
import org.apache.fluss.config.Configuration;
import org.apache.fluss.config.TableConfig;
+import org.apache.fluss.exception.FlussRuntimeException;
import org.apache.fluss.metadata.KvFormat;
import org.apache.fluss.metadata.LogFormat;
import org.apache.fluss.metadata.PhysicalTablePath;
@@ -37,6 +38,7 @@ import org.apache.fluss.server.log.LogManager;
import org.apache.fluss.server.log.LogTablet;
import org.apache.fluss.server.metrics.group.TestingMetricGroups;
import org.apache.fluss.server.storage.LocalDiskManager;
+import org.apache.fluss.server.utils.ResourceGuard;
import org.apache.fluss.server.zk.NOPErrorHandler;
import org.apache.fluss.server.zk.ZooKeeperClient;
import org.apache.fluss.server.zk.ZooKeeperExtension;
@@ -58,16 +60,23 @@ import javax.annotation.Nullable;
import java.io.File;
import java.io.IOException;
+import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
import static org.apache.fluss.compression.ArrowCompressionInfo.DEFAULT_COMPRESSION;
import static org.apache.fluss.record.TestData.DATA1_SCHEMA_PK;
import static org.apache.fluss.record.TestData.DATA2_SCHEMA;
+import static org.apache.fluss.testutils.common.CommonTestUtils.waitUntil;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
/** Test for {@link KvManager} . */
final class KvManagerTest {
@@ -325,6 +334,102 @@ final class KvManagerTest {
assertThat(kv).isNotPresent();
}
+ @Test
+ void testShutdownClosesKvTabletsConcurrently() throws Exception {
+ int maxClosingThreads = 2;
+ recreateKvManager(maxClosingThreads);
+
+ List<KvTablet> kvTablets = new ArrayList<>();
+ for (int bucket = 0; bucket < 3; bucket++) {
+ kvTablets.add(getOrCreateKv(tablePath1, null, new TableBucket(16001L, bucket)));
+ }
+
+ List<ResourceGuard.Lease> leases = new ArrayList<>();
+ for (KvTablet kvTablet : kvTablets) {
+ leases.add(kvTablet.getRocksDBKv().getResourceGuard().acquireResource());
+ }
+
+ KvManager managerToShutdown = kvManager;
+ kvManager = null;
+ ExecutorService shutdownExecutor = Executors.newSingleThreadExecutor();
+ Future<?> shutdownFuture = shutdownExecutor.submit(managerToShutdown::shutdown);
+ try {
+ waitUntil(
+ () ->
+ kvTablets.stream()
+ .filter(
+ kvTablet ->
+ kvTablet.getRocksDBKv()
+ .getResourceGuard()
+ .isClosed())
+ .count()
+ == maxClosingThreads,
+ Duration.ofSeconds(10),
+ "The configured number of KvTablets should start closing concurrently.");
+ assertThat(
+ kvTablets.stream()
+ .filter(
+ kvTablet ->
+ kvTablet.getRocksDBKv()
+ .getResourceGuard()
+ .isClosed())
+ .count())
+ .isEqualTo(maxClosingThreads);
+ assertThat(shutdownFuture.isDone()).isFalse();
+
+ int releasedLease = -1;
+ for (int index = 0; index < kvTablets.size(); index++) {
+ if (kvTablets.get(index).getRocksDBKv().getResourceGuard().isClosed()) {
+ leases.get(index).close();
+ releasedLease = index;
+ break;
+ }
+ }
+ assertThat(releasedLease).isNotNegative();
+ waitUntil(
+ () ->
+ kvTablets.stream()
+ .filter(
+ kvTablet ->
+ kvTablet.getRocksDBKv()
+ .getResourceGuard()
+ .isClosed())
+ .count()
+ == kvTablets.size(),
+ Duration.ofSeconds(10),
+ "The queued KvTablet should start closing after a worker becomes available.");
+ assertThat(shutdownFuture.isDone()).isFalse();
+ } finally {
+ leases.forEach(ResourceGuard.Lease::close);
+ try {
+ shutdownFuture.get(30, TimeUnit.SECONDS);
+ } finally {
+ shutdownExecutor.shutdownNow();
+ }
+ }
+
+ assertThat(kvTablets)
+ .allSatisfy(
+ kvTablet ->
+ assertThatThrownBy(kvTablet.getRocksDBKv()::checkIfRocksDBClosed)
+ .isInstanceOf(FlussRuntimeException.class));
+ }
+
+ private void recreateKvManager(int closingThreads) throws Exception {
+ KvManager previousKvManager = kvManager;
+ kvManager = null;
+ previousKvManager.shutdown();
+ conf.set(ConfigOptions.NETTY_SERVER_NUM_WORKER_THREADS, closingThreads);
+ kvManager =
+ KvManager.create(
+ conf,
+ zkClient,
+ logManager,
+ TestingMetricGroups.TABLET_SERVER_METRICS,
+ localDiskManager);
+ kvManager.startup();
+ }
+
private void initTableBuckets(@Nullable String partitionName) {
if (partitionName == null) {
tableBucket1 = new TableBucket(15001L, 1);
diff --git a/fluss-server/src/test/java/org/apache/fluss/server/log/LogManagerTest.java b/fluss-server/src/test/java/org/apache/fluss/server/log/LogManagerTest.java
index 8706edfde..81d20249b 100644
--- a/fluss-server/src/test/java/org/apache/fluss/server/log/LogManagerTest.java
+++ b/fluss-server/src/test/java/org/apache/fluss/server/log/LogManagerTest.java
@@ -292,6 +292,27 @@ final class LogManagerTest extends LogTestBase {
assertThat(new File(dataDir, CLEAN_SHUTDOWN_FILE).exists()).isFalse();
}
+ @Test
+ @Tag(ServerTestTags.JBOD_MULTI_DIR_TAG)
+ void testSkipCleanShutdownMarkerForDataDirWithFailedLogClose() throws Exception {
+ File failedDataDir = new File(tempDir, "data-1");
+ File healthyDataDir = new File(tempDir, "data-2");
+ initTableBuckets(null);
+
+ LogTablet failedLog = createLog(tablePath1, tableBucket1, failedDataDir);
+ failedLog.appendAsLeader(genMemoryLogRecordsByObject(DATA1));
+ createLog(tablePath2, tableBucket2, healthyDataDir)
+ .appendAsLeader(genMemoryLogRecordsByObject(DATA1));
+
+ // Make the shutdown flush fail by closing the underlying file channels first.
+ failedLog.close();
+ logManager.shutdown();
+ logManager = null;
+
+ assertThat(new File(failedDataDir, CLEAN_SHUTDOWN_FILE)).doesNotExist();
+ assertThat(new File(healthyDataDir, CLEAN_SHUTDOWN_FILE)).exists();
+ }
+
@ParameterizedTest
@MethodSource("partitionProvider")
void testSameTableNameInDifferentDb(String partitionName) throws Exception {
diff --git a/fluss-server/src/test/java/org/apache/fluss/server/tablet/TabletServerShutdownITCase.java b/fluss-server/src/test/java/org/apache/fluss/server/tablet/TabletServerShutdownITCase.java
index 95e66f252..1460553fd 100644
--- a/fluss-server/src/test/java/org/apache/fluss/server/tablet/TabletServerShutdownITCase.java
+++ b/fluss-server/src/test/java/org/apache/fluss/server/tablet/TabletServerShutdownITCase.java
@@ -25,6 +25,8 @@ import org.apache.fluss.metadata.TableBucket;
import org.apache.fluss.metadata.TableDescriptor;
import org.apache.fluss.metadata.TablePath;
import org.apache.fluss.rpc.gateway.TabletServerGateway;
+import org.apache.fluss.rpc.messages.ErrorMessage;
+import org.apache.fluss.rpc.protocol.Errors;
import org.apache.fluss.server.log.LogSegment;
import org.apache.fluss.server.testutils.FlussClusterExtension;
import org.apache.fluss.server.zk.ZooKeeperClient;
@@ -40,6 +42,7 @@ import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
+import java.util.concurrent.ExecutionException;
import static org.apache.fluss.record.TestData.DATA1;
import static org.apache.fluss.record.TestData.DATA_1_WITH_KEY_AND_VALUE;
@@ -50,7 +53,6 @@ import static org.apache.fluss.testutils.DataTestUtils.genKvRecordBatch;
import static org.apache.fluss.testutils.DataTestUtils.genMemoryLogRecordsByObject;
import static org.apache.fluss.testutils.common.CommonTestUtils.retry;
import static org.assertj.core.api.Assertions.assertThat;
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
/** The ITCase for tabletServer shutdown (controlled shutdown). */
public class TabletServerShutdownITCase {
@@ -100,17 +102,37 @@ public class TabletServerShutdownITCase {
.activeLogSegment();
logSegment.deleteIfExists();
- // should get RetriableException since the leader server is shutdown
- // and new Leader will be on new server
- assertThatThrownBy(() -> writeData(leaderGateWay, tableId, isLogTable))
- .cause()
- .isInstanceOf(RetriableException.class);
+ ErrorMessage errorResponse = null;
+ ExecutionException requestFailure = null;
+ try {
+ errorResponse = writeData(leaderGateWay, tableId, isLogTable);
+ } catch (ExecutionException e) {
+ requestFailure = e;
+ }
- // should only has 2 tablet servers
- FLUSS_CLUSTER_EXTENSION.assertHasTabletServerNumber(2);
+ TabletServer leaderServer = FLUSS_CLUSTER_EXTENSION.getTabletServerById(leader);
+ try {
+ // The storage IOException should trigger the fatal error handler and stop the leader
+ // server. The failed request may either receive the storage error response or fail when
+ // the RPC connection is closed, depending on which completes first.
+ FLUSS_CLUSTER_EXTENSION.assertHasTabletServerNumber(2);
+ } finally {
+ // Wait for the fatal shutdown to finish before reusing the same server ID and data dir.
+ leaderServer.closeAsync().get();
+ FLUSS_CLUSTER_EXTENSION.startTabletServer(leader, true);
+ }
- // restart the shutdown server
- FLUSS_CLUSTER_EXTENSION.startTabletServer(leader, true);
+ if (requestFailure != null) {
+ assertThat(requestFailure).cause().isInstanceOf(RetriableException.class);
+ } else {
+ assertThat(errorResponse).isNotNull();
+ assertThat(errorResponse.hasErrorCode()).isTrue();
+ assertThat(errorResponse.getErrorCode())
+ .isEqualTo(
+ isLogTable
+ ? Errors.LOG_STORAGE_EXCEPTION.code()
+ : Errors.KV_STORAGE_EXCEPTION.code());
+ }
}
@Test
@@ -237,20 +259,22 @@ public class TabletServerShutdownITCase {
() -> assertThat(zkClient.getLeaderAndIsr(tb).get().leader()).isEqualTo(leader));
}
- private void writeData(
+ private ErrorMessage writeData(
TabletServerGateway tabletServerGateway, long tableId, boolean isLogTable)
throws Exception {
if (isLogTable) {
- tabletServerGateway
+ return tabletServerGateway
.produceLog(
newProduceLogRequest(tableId, 0, 1, genMemoryLogRecordsByObject(DATA1)))
- .get();
+ .get()
+ .getBucketsRespAt(0);
} else {
- tabletServerGateway
+ return tabletServerGateway
.putKv(
newPutKvRequest(
tableId, 0, 1, genKvRecordBatch(DATA_1_WITH_KEY_AND_VALUE)))
- .get();
+ .get()
+ .getBucketsRespAt(0);
}
}
}
diff --git a/fluss-server/src/test/java/org/apache/fluss/server/tablet/TabletServerShutdownTest.java b/fluss-server/src/test/java/org/apache/fluss/server/tablet/TabletServerShutdownTest.java
new file mode 100644
index 000000000..6cb07f77f
--- /dev/null
+++ b/fluss-server/src/test/java/org/apache/fluss/server/tablet/TabletServerShutdownTest.java
@@ -0,0 +1,133 @@
+/*
+ * 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.fluss.server.tablet;
+
+import org.apache.fluss.config.ConfigOptions;
+import org.apache.fluss.config.Configuration;
+import org.apache.fluss.exception.FlussRuntimeException;
+
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.fluss.record.TestData.DEFAULT_REMOTE_DATA_DIR;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+/** Test for the shutdown ordering of {@link TabletServer}. */
+final class TabletServerShutdownTest {
+
+ @Test
+ void testQuiescesTabletUsersBeforeClosingTabletManagers() throws Exception {
+ Configuration conf = new Configuration();
+ conf.set(ConfigOptions.TABLET_SERVER_ID, 0);
+ conf.setString(ConfigOptions.REMOTE_DATA_DIR, DEFAULT_REMOTE_DATA_DIR);
+ TestingTabletServer server = new TestingTabletServer(conf);
+ ExecutorService shutdownExecutor = Executors.newSingleThreadExecutor();
+ Future<CompletableFuture<Void>> stopServicesInvocation =
+ shutdownExecutor.submit(server::stopServices);
+
+ try {
+ assertThat(server.awaitRpcShutdownStarted()).isTrue();
+ assertThat(server.getShutdownEvents()).containsExactly("rpc-started");
+
+ server.completeRpcShutdown();
+ stopServicesInvocation.get(10, TimeUnit.SECONDS).get(10, TimeUnit.SECONDS);
+
+ assertThat(server.getShutdownEvents())
+ .containsExactly(
+ "rpc-started", "rpc-completed", "replica-manager", "tablet-managers");
+ } finally {
+ server.completeRpcShutdown();
+ shutdownExecutor.shutdownNow();
+ }
+ }
+
+ @Test
+ void testClosesTabletManagersWhenReplicaManagerShutdownFails() throws Exception {
+ Configuration conf = new Configuration();
+ conf.set(ConfigOptions.TABLET_SERVER_ID, 0);
+ conf.setString(ConfigOptions.REMOTE_DATA_DIR, DEFAULT_REMOTE_DATA_DIR);
+ TestingTabletServer server = new TestingTabletServer(conf);
+ server.completeRpcShutdown();
+ server.failReplicaManagerShutdown();
+
+ assertThatThrownBy(() -> server.stopServices().get(10, TimeUnit.SECONDS))
+ .isInstanceOf(ExecutionException.class)
+ .hasCauseInstanceOf(FlussRuntimeException.class);
+ assertThat(server.getShutdownEvents())
+ .containsExactly(
+ "rpc-started", "rpc-completed", "replica-manager", "tablet-managers");
+ }
+
+ private static final class TestingTabletServer extends TabletServer {
+ private final CompletableFuture<Void> rpcShutdownFuture = new CompletableFuture<>();
+ private final CountDownLatch rpcShutdownStarted = new CountDownLatch(1);
+ private final List<String> shutdownEvents = new CopyOnWriteArrayList<>();
+ private boolean failReplicaManagerShutdown;
+
+ private TestingTabletServer(Configuration conf) {
+ super(conf);
+ }
+
+ @Override
+ CompletableFuture<Void> shutdownRpcServer() {
+ shutdownEvents.add("rpc-started");
+ rpcShutdownStarted.countDown();
+ return rpcShutdownFuture.whenComplete(
+ (ignored, throwable) -> shutdownEvents.add("rpc-completed"));
+ }
+
+ @Override
+ void shutdownReplicaManager() {
+ shutdownEvents.add("replica-manager");
+ if (failReplicaManagerShutdown) {
+ throw new FlussRuntimeException("Expected replica manager shutdown failure.");
+ }
+ }
+
+ @Override
+ void shutdownTabletManagers() {
+ shutdownEvents.add("tablet-managers");
+ }
+
+ private boolean awaitRpcShutdownStarted() throws InterruptedException {
+ return rpcShutdownStarted.await(10, TimeUnit.SECONDS);
+ }
+
+ private void completeRpcShutdown() {
+ rpcShutdownFuture.complete(null);
+ }
+
+ private void failReplicaManagerShutdown() {
+ failReplicaManagerShutdown = true;
+ }
+
+ private List<String> getShutdownEvents() {
+ return shutdownEvents;
+ }
+ }
+}