This is an automated email from the ASF dual-hosted git repository.

ShannonDing pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/rocketmq.git


The following commit(s) were added to refs/heads/develop by this push:
     new b846027d5f [ISSUE #11602] Close streams on failure paths and keep 
RocksDB shutdo… (#11606)
b846027d5f is described below

commit b846027d5f56d2743616cc106a43d714a15d3cf5
Author: RLDE26 <[email protected]>
AuthorDate: Fri Nov 27 18:09:52 2026 +0800

    [ISSUE #11602] Close streams on failure paths and keep RocksDB shutdo… 
(#11606)
    
    * [ISSUE #11602] Close streams on failure paths and keep RocksDB shutdown 
reachable
    
    The config-file streams, the RocksIterator and the Zstd stream are now 
managed by try-with-resources, so they are released when an earlier call 
throws. In shutdown(), the three calls that can fail are contained locally so 
db.closeE() is always reached; the interrupt flag is restored in the outermost 
finally so downstream joins still wait for their workers, and loaded keeps its 
original assignment site so the automatic reload retry path is unchanged.
    
    * [ISSUE #11602] Keep the interrupt flag clear until RocksDB shutdown has 
joined its workers
    
    * [ISSUE #11602] Trim comments on the shutdown interrupt handling
---
 .../v2/ConfigStorageShutdownInterruptTest.java     | 222 +++++++++++++++++++++
 .../common/compression/ZstdCompressor.java         |  11 +-
 .../common/config/AbstractRocksDBStorage.java      |  25 ++-
 .../apache/rocketmq/remoting/netty/TlsHelper.java  |  20 +-
 .../metadata/RocksDBConfigToJsonCommand.java       |   6 +-
 5 files changed, 259 insertions(+), 25 deletions(-)

diff --git 
a/broker/src/test/java/org/apache/rocketmq/broker/config/v2/ConfigStorageShutdownInterruptTest.java
 
b/broker/src/test/java/org/apache/rocketmq/broker/config/v2/ConfigStorageShutdownInterruptTest.java
new file mode 100644
index 0000000000..b15deb718c
--- /dev/null
+++ 
b/broker/src/test/java/org/apache/rocketmq/broker/config/v2/ConfigStorageShutdownInterruptTest.java
@@ -0,0 +1,222 @@
+/*
+ * 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.rocketmq.broker.config.v2;
+
+import java.lang.reflect.Field;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import org.apache.rocketmq.common.ServiceThread;
+import org.apache.rocketmq.common.config.AbstractRocksDBStorage;
+import org.apache.rocketmq.store.config.MessageStoreConfig;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+
+/**
+ * Regression test for PR #11606: the RocksDB handle must not be released 
before the threads
+ * stopped by {@code shutdown()} have exited, including when the caller is 
interrupted.
+ */
+public class ConfigStorageShutdownInterruptTest {
+
+    private static final long FLUSH_WORKER_EXIT_DELAY_MILLIS = 500L;
+
+    @Rule
+    public TemporaryFolder tf = new TemporaryFolder();
+
+    /** Holds the compaction executor busy; a monitor wait is not 
interruptible. */
+    private final Object compactionGate = new Object();
+
+    private ObservingConfigStorage storage;
+
+    @Before
+    public void setUp() throws Exception {
+        MessageStoreConfig config = new MessageStoreConfig();
+        config.setStorePathRootDir(tf.newFolder("store").getAbsolutePath());
+        storage = new ObservingConfigStorage(config);
+        Assert.assertTrue("config storage failed to start", storage.start());
+        storage.startFlushWorker();
+    }
+
+    @After
+    public void tearDown() {
+        if (storage != null) {
+            storage.shutdown();
+        }
+    }
+
+    /** The pool is idle, so awaitTermination() returns without checking the 
flag. */
+    @Test
+    public void testInterruptBeforeShutdownStillWaitsForFlushWorker() throws 
Exception {
+        AtomicBoolean shutdownResult = new AtomicBoolean(false);
+        AtomicBoolean interruptStatusAtExit = new AtomicBoolean(false);
+
+        Thread caller = shutdownCaller(shutdownResult, interruptStatusAtExit, 
true);
+        caller.start();
+
+        caller.join(TimeUnit.SECONDS.toMillis(60));
+        assertShutdownWaitedForFlushWorker(caller, shutdownResult, 
interruptStatusAtExit);
+    }
+
+    /** The caller is interrupted while blocked in awaitTermination(), as in 
the review. */
+    @Test
+    public void testInterruptDuringCompactionWaitStillWaitsForFlushWorker() 
throws Exception {
+        ThreadPoolExecutor compactionPool = compactionPoolOf(storage);
+        CountDownLatch taskStarted = new CountDownLatch(1);
+        AtomicBoolean shutdownResult = new AtomicBoolean(false);
+        AtomicBoolean interruptStatusAtExit = new AtomicBoolean(false);
+
+        Thread caller = shutdownCaller(shutdownResult, interruptStatusAtExit, 
false);
+
+        synchronized (compactionGate) {
+            // Occupy the compaction executor so that awaitTermination really 
blocks.
+            compactionPool.submit(new Runnable() {
+                @Override
+                public void run() {
+                    taskStarted.countDown();
+                    synchronized (compactionGate) {
+                        // Released when the test thread leaves the 
synchronized block.
+                    }
+                }
+            });
+            Assert.assertTrue("compaction task did not start", 
taskStarted.await(5, TimeUnit.SECONDS));
+
+            caller.start();
+            waitUntilBlocked(caller);
+
+            caller.interrupt();
+            // Let the caller leave awaitTermination and reach preShutdown().
+            Thread.sleep(200);
+        }
+
+        caller.join(TimeUnit.SECONDS.toMillis(60));
+        assertShutdownWaitedForFlushWorker(caller, shutdownResult, 
interruptStatusAtExit);
+    }
+
+    private Thread shutdownCaller(AtomicBoolean shutdownResult, AtomicBoolean 
interruptStatusAtExit,
+        boolean interruptBeforeShutdown) {
+        final Thread caller = new Thread(new Runnable() {
+            @Override
+            public void run() {
+                if (interruptBeforeShutdown) {
+                    Thread.currentThread().interrupt();
+                }
+                try {
+                    shutdownResult.set(storage.shutdown());
+                } finally {
+                    
interruptStatusAtExit.set(Thread.currentThread().isInterrupted());
+                }
+            }
+        }, "config-storage-shutdown-caller");
+        caller.setDaemon(true);
+        return caller;
+    }
+
+    private void assertShutdownWaitedForFlushWorker(Thread caller, 
AtomicBoolean shutdownResult,
+        AtomicBoolean interruptStatusAtExit) {
+        Assert.assertFalse("shutdown caller did not finish", caller.isAlive());
+        Assert.assertTrue("shutdown should still complete successfully", 
shutdownResult.get());
+        Assert.assertFalse("flush worker must have exited before the DB handle 
is released",
+            storage.flushWorkerAliveAfterJoin);
+        Assert.assertFalse("interrupt flag must not be set while cleanup is 
still running",
+            storage.interruptedSeenInPreShutdown);
+        Assert.assertTrue("interrupt status must be restored when shutdown 
returns",
+            interruptStatusAtExit.get());
+    }
+
+    private static void waitUntilBlocked(Thread thread) throws 
InterruptedException {
+        long deadline = System.currentTimeMillis() + 
TimeUnit.SECONDS.toMillis(10);
+        while (System.currentTimeMillis() < deadline) {
+            Thread.State state = thread.getState();
+            if (state == Thread.State.TIMED_WAITING || state == 
Thread.State.WAITING) {
+                return;
+            }
+            Thread.sleep(5);
+        }
+        Assert.fail("shutdown caller never blocked in awaitTermination");
+    }
+
+    private static ThreadPoolExecutor compactionPoolOf(AbstractRocksDBStorage 
target) throws Exception {
+        Field field = 
AbstractRocksDBStorage.class.getDeclaredField("manualCompactionThread");
+        field.setAccessible(true);
+        return (ThreadPoolExecutor) field.get(target);
+    }
+
+    /** A real ServiceThread that stays alive long enough for a premature 
join() to observe it. */
+    static class BlockingFlushWorker extends ServiceThread {
+
+        private final CountDownLatch entered = new CountDownLatch(1);
+        private volatile long exitAtNanos;
+
+        @Override
+        public String getServiceName() {
+            return "test-flush-worker";
+        }
+
+        @Override
+        public void run() {
+            exitAtNanos = System.nanoTime() + 
TimeUnit.MILLISECONDS.toNanos(FLUSH_WORKER_EXIT_DELAY_MILLIS);
+            entered.countDown();
+            while (System.nanoTime() < exitAtNanos) {
+                try {
+                    Thread.sleep(5);
+                } catch (InterruptedException ignored) {
+                }
+            }
+        }
+
+        boolean awaitEntered(long timeout, TimeUnit unit) throws 
InterruptedException {
+            return entered.await(timeout, unit);
+        }
+
+        boolean workerAlive() {
+            Thread workerThread = this.thread;
+            return workerThread != null && workerThread.isAlive();
+        }
+    }
+
+    /** Records what the shutdown thread sees around the flush worker join. */
+    static class ObservingConfigStorage extends ConfigStorage {
+
+        private final BlockingFlushWorker flushWorker = new 
BlockingFlushWorker();
+
+        volatile boolean interruptedSeenInPreShutdown;
+        volatile boolean flushWorkerAliveAfterJoin;
+
+        ObservingConfigStorage(MessageStoreConfig messageStoreConfig) {
+            super(messageStoreConfig);
+        }
+
+        void startFlushWorker() throws InterruptedException {
+            flushWorker.start();
+            Assert.assertTrue("flush worker did not start", 
flushWorker.awaitEntered(5, TimeUnit.SECONDS));
+        }
+
+        @Override
+        protected void preShutdown() {
+            interruptedSeenInPreShutdown = 
Thread.currentThread().isInterrupted();
+            flushWorker.shutdown();
+            flushWorkerAliveAfterJoin = flushWorker.workerAlive();
+            super.preShutdown();
+        }
+    }
+}
diff --git 
a/common/src/main/java/org/apache/rocketmq/common/compression/ZstdCompressor.java
 
b/common/src/main/java/org/apache/rocketmq/common/compression/ZstdCompressor.java
index 131035c264..ed3561debf 100644
--- 
a/common/src/main/java/org/apache/rocketmq/common/compression/ZstdCompressor.java
+++ 
b/common/src/main/java/org/apache/rocketmq/common/compression/ZstdCompressor.java
@@ -33,21 +33,14 @@ public class ZstdCompressor implements Compressor {
     public byte[] compress(byte[] src, int level) throws IOException {
         byte[] result = src;
         ByteArrayOutputStream byteArrayOutputStream = new 
ByteArrayOutputStream(src.length);
-        ZstdOutputStream outputStream = new 
ZstdOutputStream(byteArrayOutputStream, level);
-        try {
+        try (ZstdOutputStream outputStream = new 
ZstdOutputStream(byteArrayOutputStream, level)) {
             outputStream.write(src);
             outputStream.flush();
-            outputStream.close();
-            result = byteArrayOutputStream.toByteArray();
         } catch (IOException e) {
             log.error("Failed to compress data by zstd", e);
             throw e;
-        } finally {
-            try {
-                byteArrayOutputStream.close();
-            } catch (IOException ignored) {
-            }
         }
+        result = byteArrayOutputStream.toByteArray();
         return result;
     }
 
diff --git 
a/common/src/main/java/org/apache/rocketmq/common/config/AbstractRocksDBStorage.java
 
b/common/src/main/java/org/apache/rocketmq/common/config/AbstractRocksDBStorage.java
index 4875ce43e2..69dee9827f 100644
--- 
a/common/src/main/java/org/apache/rocketmq/common/config/AbstractRocksDBStorage.java
+++ 
b/common/src/main/java/org/apache/rocketmq/common/config/AbstractRocksDBStorage.java
@@ -507,6 +507,8 @@ public abstract class AbstractRocksDBStorage {
     }
 
     public synchronized boolean shutdown() {
+        // Clear the flag so the joins in the cleanup below really wait; 
restored in the finally.
+        boolean interrupted = Thread.interrupted();
         try {
             if (!this.loaded) {
                 LOGGER.info("RocksDBStorage is not loaded, shutdown OK. 
dbPath={}, readOnly={}", this.dbPath, this.readOnly);
@@ -515,7 +517,12 @@ public abstract class AbstractRocksDBStorage {
 
             manualCompactionThread.shutdownNow();
 
-            manualCompactionThread.awaitTermination(30, TimeUnit.SECONDS);
+            try {
+                manualCompactionThread.awaitTermination(30, TimeUnit.SECONDS);
+            } catch (InterruptedException e) {
+                interrupted = true;
+                LOGGER.warn("Interrupted while waiting for the compaction 
thread. dbPath={}", this.dbPath, e);
+            }
 
             final FlushOptions flushOptions = new FlushOptions();
             flushOptions.setWaitForFlush(true);
@@ -527,10 +534,18 @@ public abstract class AbstractRocksDBStorage {
                 flushOptions.close();
             }
             this.db.cancelAllBackgroundWork(true);
-            this.db.pauseBackgroundWork();
+            try {
+                this.db.pauseBackgroundWork();
+            } catch (Throwable e) {
+                LOGGER.error("rocksdb pause background work failed when 
shutdown", e);
+            }
             //The close order matters.
             //1. close column family handles
-            preShutdown();
+            try {
+                preShutdown();
+            } catch (Throwable e) {
+                LOGGER.error("rocksdb preShutdown failed when shutdown", e);
+            }
 
             if (this.defaultCFHandle.isOwningHandle()) {
                 this.defaultCFHandle.close();
@@ -594,6 +609,10 @@ public abstract class AbstractRocksDBStorage {
         } catch (Exception e) {
             LOGGER.error("RocksDB shutdown failed. {}", this.dbPath, e);
             return false;
+        } finally {
+            if (interrupted) {
+                Thread.currentThread().interrupt();
+            }
         }
         return true;
     }
diff --git 
a/remoting/src/main/java/org/apache/rocketmq/remoting/netty/TlsHelper.java 
b/remoting/src/main/java/org/apache/rocketmq/remoting/netty/TlsHelper.java
index 81a4a44978..d84595e346 100644
--- a/remoting/src/main/java/org/apache/rocketmq/remoting/netty/TlsHelper.java
+++ b/remoting/src/main/java/org/apache/rocketmq/remoting/netty/TlsHelper.java
@@ -126,10 +126,11 @@ public class TlsHelper {
                     }
                 }
 
-                sslContextBuilder = sslContextBuilder.keyManager(
-                    !isNullOrEmpty(tlsClientCertPath) ? new 
FileInputStream(tlsClientCertPath) : null,
-                    !isNullOrEmpty(tlsClientKeyPath) ? 
decryptionStrategy.decryptPrivateKey(tlsClientKeyPath, true) : null,
-                    !isNullOrEmpty(tlsClientKeyPassword) ? 
tlsClientKeyPassword : null);
+                try (InputStream certStream = 
!isNullOrEmpty(tlsClientCertPath) ? new FileInputStream(tlsClientCertPath) : 
null;
+                    InputStream keyStream = !isNullOrEmpty(tlsClientKeyPath) ? 
decryptionStrategy.decryptPrivateKey(tlsClientKeyPath, true) : null) {
+                    sslContextBuilder = 
sslContextBuilder.keyManager(certStream, keyStream,
+                        !isNullOrEmpty(tlsClientKeyPassword) ? 
tlsClientKeyPassword : null);
+                }
             }
         } else {
 
@@ -140,11 +141,12 @@ public class TlsHelper {
                     .sslProvider(provider)
                     .clientAuth(ClientAuth.OPTIONAL);
             } else {
-                sslContextBuilder = SslContextBuilder.forServer(
-                    !isNullOrEmpty(tlsServerCertPath) ? new 
FileInputStream(tlsServerCertPath) : null,
-                    !isNullOrEmpty(tlsServerKeyPath) ? 
decryptionStrategy.decryptPrivateKey(tlsServerKeyPath, false) : null,
-                    !isNullOrEmpty(tlsServerKeyPassword) ? 
tlsServerKeyPassword : null)
-                    .sslProvider(provider);
+                try (InputStream certStream = 
!isNullOrEmpty(tlsServerCertPath) ? new FileInputStream(tlsServerCertPath) : 
null;
+                    InputStream keyStream = !isNullOrEmpty(tlsServerKeyPath) ? 
decryptionStrategy.decryptPrivateKey(tlsServerKeyPath, false) : null) {
+                    sslContextBuilder = 
SslContextBuilder.forServer(certStream, keyStream,
+                        !isNullOrEmpty(tlsServerKeyPassword) ? 
tlsServerKeyPassword : null)
+                        .sslProvider(provider);
+                }
 
                 if (!tlsServerAuthClient) {
                     
sslContextBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE);
diff --git 
a/tools/src/main/java/org/apache/rocketmq/tools/command/metadata/RocksDBConfigToJsonCommand.java
 
b/tools/src/main/java/org/apache/rocketmq/tools/command/metadata/RocksDBConfigToJsonCommand.java
index 43ab46ef26..6e0379ac42 100644
--- 
a/tools/src/main/java/org/apache/rocketmq/tools/command/metadata/RocksDBConfigToJsonCommand.java
+++ 
b/tools/src/main/java/org/apache/rocketmq/tools/command/metadata/RocksDBConfigToJsonCommand.java
@@ -200,8 +200,7 @@ public class RocksDBConfigToJsonCommand implements 
SubCommand {
             return null;
         }
 
-        RocksIterator iterator = configRocksDBStorage.iterator();
-        try {
+        try (RocksIterator iterator = configRocksDBStorage.iterator()) {
             final Map<String, JSONObject> configMap = new HashMap<>();
             final JSONObject configTable = new JSONObject();
             iterator.seekToFirst();
@@ -303,8 +302,7 @@ public class RocksDBConfigToJsonCommand implements 
SubCommand {
             return null;
         }
 
-        RocksIterator iterator = configRocksDBStorage.iterator();
-        try {
+        try (RocksIterator iterator = configRocksDBStorage.iterator()) {
             final Map<String, JSONObject> configMap = new HashMap<>();
             final JSONObject configTable = new JSONObject();
             iterator.seekToFirst();

Reply via email to