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

smengcl pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/ozone.git


The following commit(s) were added to refs/heads/master by this push:
     new fa3c98f189e HDDS-17254. Prevent client background threads from 
blocking JVM shutdown (#11667)
fa3c98f189e is described below

commit fa3c98f189e208ceb1c11084861da81565bd2ef4
Author: Wei-Chiu Chuang <[email protected]>
AuthorDate: Thu Oct 22 15:26:35 2026 -0700

    HDDS-17254. Prevent client background threads from blocking JVM shutdown 
(#11667)
---
 .../hadoop/hdds/scm/XceiverClientShortCircuit.java |   2 +-
 .../hdds/scm/storage/BlockDataStreamOutput.java    |   4 +-
 .../hdds/scm/storage/DomainSocketFactory.java      |   2 +-
 .../client/io/BlockInputStreamFactoryImpl.java     |  10 +-
 .../hdds/scm/storage/TestClientThreadShutdown.java | 224 +++++++++++++++++++++
 .../hadoop/ozone/client/rpc/TestRpcClient.java     |  22 ++
 6 files changed, 259 insertions(+), 5 deletions(-)

diff --git 
a/hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientShortCircuit.java
 
b/hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientShortCircuit.java
index 70c3dc5f936..f5da98ebd63 100644
--- 
a/hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientShortCircuit.java
+++ 
b/hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientShortCircuit.java
@@ -140,7 +140,7 @@ public void connect() throws IOException {
     domainSocket = domainSocketFactory.createSocket(readTimeoutMs, 
writeTimeoutMs, dnAddr);
     isDomainSocketOpen.set(true);
     prefix = XceiverClientShortCircuit.class.getSimpleName() + "-" + 
domainSocket.toString();
-    timer = new Timer(prefix + "-Timer");
+    timer = new Timer(prefix + "-Timer", true);
     readDaemon.start();
     LOG.info("{} is started", prefix);
   }
diff --git 
a/hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/BlockDataStreamOutput.java
 
b/hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/BlockDataStreamOutput.java
index 0b5562efd03..80b2417c93b 100644
--- 
a/hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/BlockDataStreamOutput.java
+++ 
b/hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/BlockDataStreamOutput.java
@@ -21,6 +21,7 @@
 import static 
org.apache.hadoop.hdds.scm.storage.ContainerProtocolCalls.putBlockAsync;
 
 import com.google.common.base.Preconditions;
+import com.google.common.util.concurrent.ThreadFactoryBuilder;
 import java.io.IOException;
 import java.nio.ByteBuffer;
 import java.util.ArrayList;
@@ -192,7 +193,8 @@ public BlockDataStreamOutput(
                 .getStreamBufferFlushSize());
 
     // A single thread executor handle the responses of async requests
-    responseExecutor = Executors.newSingleThreadExecutor();
+    responseExecutor = Executors.newSingleThreadExecutor(new 
ThreadFactoryBuilder()
+        
.setNameFormat("BlockDataStreamOutput-response-%d").setDaemon(true).build());
     commitWatcher = new StreamCommitWatcher(xceiverClient, bufferList);
     totalDataFlushedLength = 0;
     writtenDataLength = 0;
diff --git 
a/hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/DomainSocketFactory.java
 
b/hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/DomainSocketFactory.java
index fa4ffae9631..c888225a071 100644
--- 
a/hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/DomainSocketFactory.java
+++ 
b/hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/DomainSocketFactory.java
@@ -157,7 +157,7 @@ private DomainSocketFactory(ConfigurationSource conf) {
       } else {
         pathInfo = PathInfo.VALID;
         isEnabled = true;
-        timer = new Timer(DomainSocketFactory.class.getSimpleName() + 
"-Timer");
+        timer = new Timer(DomainSocketFactory.class.getSimpleName() + 
"-Timer", true);
         LOG.info(FEATURE + " is enabled within {} ns.", System.nanoTime() - 
startTime);
       }
     }
diff --git 
a/hadoop-hdds/client/src/main/java/org/apache/hadoop/ozone/client/io/BlockInputStreamFactoryImpl.java
 
b/hadoop-hdds/client/src/main/java/org/apache/hadoop/ozone/client/io/BlockInputStreamFactoryImpl.java
index 19cafb40341..34b76ed78ca 100644
--- 
a/hadoop-hdds/client/src/main/java/org/apache/hadoop/ozone/client/io/BlockInputStreamFactoryImpl.java
+++ 
b/hadoop-hdds/client/src/main/java/org/apache/hadoop/ozone/client/io/BlockInputStreamFactoryImpl.java
@@ -19,9 +19,12 @@
 
 import static org.apache.hadoop.hdds.HDDSVersion.STREAM_BLOCK_SUPPORT;
 
+import com.google.common.util.concurrent.ThreadFactoryBuilder;
 import java.io.IOException;
 import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
 import java.util.function.Function;
 import java.util.function.Supplier;
 import org.apache.hadoop.hdds.client.BlockID;
@@ -68,7 +71,10 @@ public static BlockInputStreamFactory getInstance(
   }
 
   public BlockInputStreamFactoryImpl() {
-    this(new ElasticByteBufferPool(), Executors::newSingleThreadExecutor);
+    // These executors have no external owner. Retire idle workers as well as 
allowing JVM shutdown.
+    this(new ElasticByteBufferPool(), () -> new ThreadPoolExecutor(0, 1, 60, 
TimeUnit.SECONDS,
+        new LinkedBlockingQueue<>(), new ThreadFactoryBuilder()
+            .setNameFormat("EC-reconstruction-%d").setDaemon(true).build()));
   }
 
   public BlockInputStreamFactoryImpl(ByteBufferPool byteBufferPool,
diff --git 
a/hadoop-hdds/client/src/test/java/org/apache/hadoop/hdds/scm/storage/TestClientThreadShutdown.java
 
b/hadoop-hdds/client/src/test/java/org/apache/hadoop/hdds/scm/storage/TestClientThreadShutdown.java
new file mode 100644
index 00000000000..427553048cd
--- /dev/null
+++ 
b/hadoop-hdds/client/src/test/java/org/apache/hadoop/hdds/scm/storage/TestClientThreadShutdown.java
@@ -0,0 +1,224 @@
+/*
+ * 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.hadoop.hdds.scm.storage;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.lang.reflect.Field;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.Timer;
+import java.util.TimerTask;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Supplier;
+import org.apache.hadoop.hdds.conf.OzoneConfiguration;
+import org.apache.hadoop.hdds.protocol.DatanodeDetails;
+import org.apache.hadoop.hdds.protocol.MockDatanodeDetails;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos;
+import org.apache.hadoop.hdds.scm.ContainerClientMetrics;
+import org.apache.hadoop.hdds.scm.OzoneClientConfig;
+import org.apache.hadoop.hdds.scm.StreamBufferArgs;
+import org.apache.hadoop.hdds.scm.XceiverClientShortCircuit;
+import org.apache.hadoop.net.unix.DomainSocket;
+import org.apache.hadoop.ozone.client.io.BlockInputStreamFactoryImpl;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
+
+/** Tests that client background workers do not prevent JVM shutdown. */
+public class TestClientThreadShutdown {
+  private static final String READY = "CLIENT_WORKER_STARTED";
+  // Retain clients until JVM exit, so Timer finalization cannot hide a 
non-daemon thread.
+  private static Object retainedClient;
+
+  @TempDir
+  private Path tempDir;
+
+  enum Client {
+    STREAM_WRITE, SHORT_CIRCUIT, DOMAIN_SOCKET_FACTORY, EC_RECONSTRUCTION
+  }
+
+  @ParameterizedTest
+  @EnumSource(Client.class)
+  void exitsWithoutClosingClient(Client client) throws Exception {
+    Path output = tempDir.resolve(client + ".log");
+    assertExitsWithoutClosingClient(output, TestClientThreadShutdown.class, 
client.name());
+  }
+
+  /** Also used by higher-level client tests with their production executor 
suppliers. */
+  public static void assertExitsWithoutClosingClient(Path output, Class<?> 
mainClass, String client) throws Exception {
+    Process process = new ProcessBuilder(
+        Paths.get(System.getProperty("java.home"), "bin", "java").toString(),
+        "-cp", System.getProperty("surefire.test.class.path", 
System.getProperty("java.class.path")),
+        mainClass.getName(), client)
+        .redirectErrorStream(true).redirectOutput(output.toFile()).start();
+    try {
+      boolean exited = process.waitFor(30, TimeUnit.SECONDS);
+      String log = new String(Files.readAllBytes(output), 
StandardCharsets.UTF_8);
+      assertTrue(log.contains(READY), "Client worker did not start: " + log);
+      assertTrue(exited, "Client worker kept the JVM alive: " + client + "\n" 
+ log);
+      assertEquals(0, process.exitValue(), log);
+    } finally {
+      process.destroyForcibly();
+      assertTrue(process.waitFor(10, TimeUnit.SECONDS), "Child JVM did not 
terminate");
+    }
+  }
+
+  /** Exercises a Ratis write with the executor owned by RpcClient, without 
closing either resource. */
+  public static void writeRatisBlock(ExecutorService executor) throws 
Exception {
+    MockDatanodePipeline pipeline = new MockDatanodePipeline();
+    OzoneClientConfig config = new OzoneClientConfig();
+    config.setStreamBufferSize(100);
+    config.setStreamBufferFlushSize(400);
+    config.setStreamBufferMaxSize(800);
+    config.setIncrementalChunkList(false);
+    config.setEnablePutblockPiggybacking(false);
+    config.setChecksumType(ContainerProtos.ChecksumType.NONE);
+    StreamBufferArgs bufferArgs = StreamBufferArgs.getDefaultStreamBufferArgs(
+        pipeline.getPipeline().getReplicationConfig(), config);
+    RatisBlockOutputStream stream = new 
RatisBlockOutputStream(pipeline.getBlockID(), -1,
+        pipeline.getClientFactory(), pipeline.getPipeline(), new 
BufferPool(100, 8), config, null,
+        ContainerClientMetrics.acquire(), bufferArgs, () -> executor);
+    retainedClient = stream;
+    stream.write(new byte[100]);
+    stream.getResponseExecutor().submit(() -> { }).get(10, TimeUnit.SECONDS);
+    assertNotNull(retainedClient);
+    System.out.println(READY);
+  }
+
+  @Test
+  void defaultEcWorkerRetiresWhenIdle() throws Exception {
+    BlockInputStreamFactoryImpl factory = new BlockInputStreamFactoryImpl();
+    Object ecFactory = field(factory, "ecBlockStreamFactory").get(factory);
+    @SuppressWarnings("unchecked")
+    Supplier<ExecutorService> supplier = (Supplier<ExecutorService>)
+        field(ecFactory, "ecReconstructExecutorSupplier").get(ecFactory);
+    ExecutorService executor = supplier.get();
+    try {
+      // Shorten the idle timeout without changing whether core workers are 
allowed to retire.
+      if (executor instanceof ThreadPoolExecutor) {
+        ((ThreadPoolExecutor) executor).setKeepAliveTime(100, 
TimeUnit.MILLISECONDS);
+      }
+      Thread worker = executor.submit(Thread::currentThread).get(10, 
TimeUnit.SECONDS);
+      worker.join(10000);
+      assertFalse(worker.isAlive(), "Default EC reconstruction worker did not 
retire");
+      assertEquals(42, executor.submit(() -> 42).get(10, TimeUnit.SECONDS));
+    } finally {
+      executor.shutdownNow();
+      assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS));
+    }
+  }
+
+  /** Runs in an isolated JVM and deliberately leaves the client open. */
+  public static void main(String[] args) throws Exception {
+    OzoneConfiguration conf = new OzoneConfiguration();
+    switch (Client.valueOf(args[0])) {
+    case STREAM_WRITE:
+      MockDatanodePipeline pipeline = new MockDatanodePipeline();
+      OzoneClientConfig config = new OzoneClientConfig();
+      config.setDataStreamMinPacketSize(100);
+      config.setDataStreamBufferFlushSize(400);
+      config.setStreamWindowSize(500);
+      config.setStreamBufferSize(100);
+      config.setStreamBufferFlushSize(400);
+      config.setStreamBufferMaxSize(800);
+      config.setChecksumType(ContainerProtos.ChecksumType.NONE);
+      BlockDataStreamOutput stream = new 
BlockDataStreamOutput(pipeline.getBlockID(), pipeline.getClientFactory(),
+          pipeline.getPipeline(), config, null, new ArrayList<>());
+      retainedClient = stream;
+      stream.write(ByteBuffer.wrap(new byte[400]), 0, 400);
+      ExecutorService responseExecutor = (ExecutorService) field(stream, 
"responseExecutor").get(stream);
+      responseExecutor.submit(() -> { }).get(10, TimeUnit.SECONDS);
+      break;
+    case SHORT_CIRCUIT:
+      DomainSocketFactory socketFactory = mock(DomainSocketFactory.class);
+      DomainSocket socket = mock(DomainSocket.class);
+      DomainSocket.DomainInputStream input = 
mock(DomainSocket.DomainInputStream.class);
+      when(input.read()).thenReturn(-1);
+      when(socket.getInputStream()).thenReturn(input);
+      when(socketFactory.createSocket(anyInt(), anyInt(), 
any())).thenReturn(socket);
+      Field instance = field(DomainSocketFactory.class, "instance");
+      instance.set(null, socketFactory);
+      DatanodeDetails dn = MockDatanodeDetails.randomDatanodeDetails();
+      XceiverClientShortCircuit client = new XceiverClientShortCircuit(null, 
conf, dn);
+      retainedClient = client;
+      client.connect();
+      awaitTimer((Timer) field(client, "timer").get(client));
+      break;
+    case DOMAIN_SOCKET_FACTORY:
+      // Exercise timer initialization without requiring platform-specific 
native socket support.
+      field(DomainSocketFactory.class, "nativeLibraryLoaded").setBoolean(null, 
true);
+      OzoneClientConfig socketConfig = conf.getObject(OzoneClientConfig.class);
+      socketConfig.setShortCircuit(true);
+      conf.setFromObject(socketConfig);
+      conf.set(OzoneClientConfig.OZONE_DOMAIN_SOCKET_PATH, 
"/tmp/ozone-client-shutdown.sock");
+      DomainSocketFactory factory = DomainSocketFactory.getInstance(conf);
+      retainedClient = factory;
+      awaitTimer(factory.getTimer());
+      break;
+    case EC_RECONSTRUCTION:
+      BlockInputStreamFactoryImpl inputFactory = new 
BlockInputStreamFactoryImpl();
+      retainedClient = inputFactory;
+      Object ecFactory = field(inputFactory, 
"ecBlockStreamFactory").get(inputFactory);
+      @SuppressWarnings("unchecked")
+      Supplier<ExecutorService> supplier = (Supplier<ExecutorService>)
+          field(ecFactory, "ecReconstructExecutorSupplier").get(ecFactory);
+      ExecutorService executor = supplier.get();
+      retainedClient = executor;
+      executor.submit(() -> { }).get(10, TimeUnit.SECONDS);
+      break;
+    default:
+      throw new IllegalArgumentException(args[0]);
+    }
+    assertNotNull(retainedClient);
+    System.out.println(READY);
+  }
+
+  private static void awaitTimer(Timer timer) throws InterruptedException {
+    CountDownLatch started = new CountDownLatch(1);
+    timer.schedule(new TimerTask() {
+      @Override
+      public void run() {
+        started.countDown();
+      }
+    }, 0);
+    assertTrue(started.await(10, TimeUnit.SECONDS), "Timer did not start");
+  }
+
+  private static Field field(Object target, String name) throws 
ReflectiveOperationException {
+    Class<?> type = target instanceof Class ? (Class<?>) target : 
target.getClass();
+    Field result = type.getDeclaredField(name);
+    result.setAccessible(true);
+    return result;
+  }
+}
diff --git 
a/hadoop-ozone/client/src/test/java/org/apache/hadoop/ozone/client/rpc/TestRpcClient.java
 
b/hadoop-ozone/client/src/test/java/org/apache/hadoop/ozone/client/rpc/TestRpcClient.java
index 9cd25fb161f..79b125bc50f 100644
--- 
a/hadoop-ozone/client/src/test/java/org/apache/hadoop/ozone/client/rpc/TestRpcClient.java
+++ 
b/hadoop-ozone/client/src/test/java/org/apache/hadoop/ozone/client/rpc/TestRpcClient.java
@@ -34,13 +34,16 @@
 import static org.mockito.Mockito.verify;
 
 import java.io.IOException;
+import java.nio.file.Path;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.LinkedList;
 import java.util.List;
+import java.util.concurrent.ExecutorService;
 import java.util.concurrent.atomic.AtomicInteger;
 import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Supplier;
 import java.util.stream.Stream;
 import org.apache.commons.lang3.reflect.FieldUtils;
 import org.apache.hadoop.hdds.client.RatisReplicationConfig;
@@ -48,6 +51,7 @@
 import org.apache.hadoop.hdds.conf.OzoneConfiguration;
 import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
 import org.apache.hadoop.hdds.scm.XceiverClientFactory;
+import org.apache.hadoop.hdds.scm.storage.TestClientThreadShutdown;
 import org.apache.hadoop.ozone.OzoneConsts;
 import org.apache.hadoop.ozone.OzoneManagerVersion;
 import org.apache.hadoop.ozone.client.MockOmTransport;
@@ -74,6 +78,7 @@
 import org.apache.ozone.test.GenericTestUtils.LogCapturer;
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.api.function.Executable;
+import org.junit.jupiter.api.io.TempDir;
 import org.junit.jupiter.params.ParameterizedTest;
 import org.junit.jupiter.params.provider.Arguments;
 import org.junit.jupiter.params.provider.CsvSource;
@@ -86,6 +91,23 @@
  * Run RPC Client tests.
  */
 public class TestRpcClient {
+  @Test
+  void ratisWriteDoesNotPreventJvmShutdown(@TempDir Path tempDir) throws 
Exception {
+    TestClientThreadShutdown.assertExitsWithoutClosingClient(
+        tempDir.resolve("ratis-write.log"), RatisWriteClient.class, 
"RATIS_WRITE");
+  }
+
+  /** Child JVM for the HDDS-10564 regression test, using the actual RpcClient 
write executor. */
+  public static final class RatisWriteClient {
+    public static void main(String[] args) throws Exception {
+      RpcClient client = createRpcClient();
+      @SuppressWarnings("unchecked")
+      Supplier<ExecutorService> executor =
+          (Supplier<ExecutorService>) FieldUtils.readField(client, 
"writeExecutor", true);
+      TestClientThreadShutdown.writeRatisBlock(executor.get());
+    }
+  }
+
   private enum ValidateOmVersionTestCases {
     NULL_EXPECTED_NO_OM(
         null, // Expected version


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to