This is an automated email from the ASF dual-hosted git repository.
adoroszlai 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 20da41e535b HDDS-17491. Close idle clients in XceiverClientManager
even when its cache is not used (#11785)
20da41e535b is described below
commit 20da41e535b0d7ec923d818b988fd3ea8b36f0a3
Author: Andrey Yarovoy <[email protected]>
AuthorDate: Sun Nov 1 06:04:28 2026 -0500
HDDS-17491. Close idle clients in XceiverClientManager even when its cache
is not used (#11785)
Co-authored-by: Claude Opus 5.5 <[email protected]>
---
.../hadoop/hdds/scm/XceiverClientManager.java | 18 +++
.../scm/TestXceiverClientManagerIdleEviction.java | 131 ++++++++++++++++++
.../hadoop/fs/ozone/TestDataStreamClientExit.java | 146 +++++++++++++++++++++
3 files changed, 295 insertions(+)
diff --git
a/hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientManager.java
b/hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientManager.java
index 63fbe0ff9e9..82e036db3a2 100644
---
a/hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientManager.java
+++
b/hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientManager.java
@@ -41,6 +41,7 @@
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.hadoop.hdds.HddsUtils;
@@ -78,6 +79,8 @@ public class XceiverClientManager extends
XceiverClientCreator {
LoggerFactory.getLogger(XceiverClientManager.class);
private final Cache<String, XceiverClientSpi> clientCache;
+ // The cache expires idle clients only while it is used, so this cleans it
up periodically to close them anyway.
+ private final ScheduledExecutorService cleanupExecutor;
private final CacheMetrics cacheMetrics;
private static XceiverClientMetrics metrics;
private final ConcurrentHashMap<String, DatanodeDetails> localDNCache;
@@ -130,11 +133,25 @@ public void onRemoval(
}
}
}).build();
+ cleanupExecutor = Executors.newSingleThreadScheduledExecutor(new
ThreadFactoryBuilder()
+
.setNameFormat("XceiverClientManager-cleanup-%d").setDaemon(true).build());
+ if (staleThresholdMs > 0) {
+ cleanupExecutor.scheduleWithFixedDelay(this::cleanUpCache,
staleThresholdMs, staleThresholdMs, MILLISECONDS);
+ }
cacheMetrics = CacheMetrics.create(clientCache, this);
this.localDNCache = new ConcurrentHashMap<>();
}
+ private void cleanUpCache() {
+ try {
+ clientCache.cleanUp();
+ } catch (RuntimeException e) {
+ // keep the task scheduled
+ LOG.warn("Failed to close idle clients", e);
+ }
+ }
+
@VisibleForTesting
public Cache<String, XceiverClientSpi> getClientCache() {
return clientCache;
@@ -321,6 +338,7 @@ private String getPipelineCacheKey(Pipeline pipeline,
boolean topologyAware, boo
@Override
public void close() {
super.close();
+ cleanupExecutor.shutdown();
final List<XceiverClientSpi> unreferenced = new ArrayList<>();
synchronized (clientCache) {
// the RemovalListener collects the unreferenced clients instead of
closing them one by one
diff --git
a/hadoop-hdds/client/src/test/java/org/apache/hadoop/hdds/scm/TestXceiverClientManagerIdleEviction.java
b/hadoop-hdds/client/src/test/java/org/apache/hadoop/hdds/scm/TestXceiverClientManagerIdleEviction.java
new file mode 100644
index 00000000000..dde13db4cfe
--- /dev/null
+++
b/hadoop-hdds/client/src/test/java/org/apache/hadoop/hdds/scm/TestXceiverClientManagerIdleEviction.java
@@ -0,0 +1,131 @@
+/*
+ * 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;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Collectors;
+import org.apache.hadoop.hdds.conf.OzoneConfiguration;
+import org.apache.hadoop.hdds.scm.XceiverClientManager.ScmClientConfig;
+import
org.apache.hadoop.hdds.scm.XceiverClientManager.XceiverClientManagerConfigBuilder;
+import org.apache.hadoop.hdds.scm.client.ClientTrustManager;
+import org.apache.hadoop.hdds.scm.pipeline.MockPipeline;
+import org.apache.ozone.test.GenericTestUtils;
+import org.junit.jupiter.api.Test;
+
+/**
+ * Tests that {@link XceiverClientManager} closes clients that stay idle
longer than
+ * {@code scm.container.client.idle.threshold}, even when the cache is not
used again.
+ *
+ * <p>An idle client holds its connections, and for Ratis data streaming the
shared Netty worker group, whose
+ * non-daemon threads keep the JVM from exiting (HDDS-17278).
+ */
+class TestXceiverClientManagerIdleEviction {
+
+ private static final long IDLE_THRESHOLD_MS = 200;
+ /** Long enough for an idle client to be closed many times over. */
+ private static final int WAIT_MS = 20 * (int) IDLE_THRESHOLD_MS;
+
+ private static XceiverClientManager newManager() throws Exception {
+ ScmClientConfig clientConf = new XceiverClientManagerConfigBuilder()
+ .setMaxCacheSize(256)
+ .setStaleThresholdMs(IDLE_THRESHOLD_MS)
+ .build();
+ return new XceiverClientManager(new OzoneConfiguration(), clientConf,
(ClientTrustManager) null);
+ }
+
+ @Test
+ void idleClientIsClosedWithoutFurtherCacheAccess() throws Exception {
+ try (XceiverClientManager manager = newManager()) {
+ XceiverClientSpi client =
manager.acquireClient(MockPipeline.createPipeline(1));
+ manager.releaseClient(client, false);
+
+ // nothing uses the cache any more, like a JVM whose application has
finished writing
+ GenericTestUtils.waitFor(client::isClosed, 50, WAIT_MS);
+ }
+ }
+
+ @Test
+ void idleClientIsClosedWhenTheCacheIsCleanedUp() throws Exception {
+ try (XceiverClientManager manager = newManager()) {
+ XceiverClientSpi client =
manager.acquireClient(MockPipeline.createPipeline(1));
+ manager.releaseClient(client, false);
+ Thread.sleep(2 * IDLE_THRESHOLD_MS);
+
+ manager.getClientCache().cleanUp();
+ // evicted clients are closed in the background (HDDS-16812)
+ GenericTestUtils.waitFor(client::isClosed, 10, WAIT_MS);
+ }
+ }
+
+ @Test
+ void idleClientInUseIsNotClosed() throws Exception {
+ try (XceiverClientManager manager = newManager()) {
+ XceiverClientSpi client =
manager.acquireClient(MockPipeline.createPipeline(1));
+ Thread.sleep(2 * IDLE_THRESHOLD_MS);
+ manager.getClientCache().cleanUp();
+
+ // expired, but still referenced, so it must stay open until it is
released
+ assertFalse(client.isClosed());
+ manager.releaseClient(client, false);
+ GenericTestUtils.waitFor(client::isClosed, 10, WAIT_MS);
+ }
+ }
+
+ /**
+ * Using the cache does not reliably evict idle clients either: the cache is
split into segments, and a write cleans
+ * up only the segment of its own key.
+ */
+ @Test
+ void idleClientIsClosedWhenOtherClientsAreUsed() throws Exception {
+ try (XceiverClientManager manager = newManager()) {
+ List<XceiverClientSpi> idle = new ArrayList<>();
+ for (int i = 0; i < 16; i++) {
+ XceiverClientSpi client =
manager.acquireClient(MockPipeline.createPipeline(1));
+ manager.releaseClient(client, false);
+ idle.add(client);
+ }
+ Thread.sleep(2 * IDLE_THRESHOLD_MS);
+
+ XceiverClientSpi other =
manager.acquireClient(MockPipeline.createPipeline(1));
+ manager.releaseClient(other, false);
+ GenericTestUtils.waitFor(() ->
idle.stream().allMatch(XceiverClientSpi::isClosed), 50, WAIT_MS);
+ }
+ }
+
+ /** The cleanup thread must not keep a JVM alive itself, and must stop with
the manager. */
+ @Test
+ void cleanupThreadIsDaemonAndStopsOnClose() throws Exception {
+ XceiverClientManager manager = newManager();
+ List<Thread> threads = cleanupThreads();
+ assertFalse(threads.isEmpty());
+ assertTrue(threads.stream().allMatch(Thread::isDaemon));
+
+ manager.close();
+ GenericTestUtils.waitFor(() -> cleanupThreads().isEmpty(), 50, WAIT_MS);
+ }
+
+ private static List<Thread> cleanupThreads() {
+ return Thread.getAllStackTraces().keySet().stream()
+ .filter(t -> t.isAlive() &&
t.getName().startsWith("XceiverClientManager-cleanup-"))
+ .collect(Collectors.toList());
+ }
+}
diff --git
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/fs/ozone/TestDataStreamClientExit.java
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/fs/ozone/TestDataStreamClientExit.java
new file mode 100644
index 00000000000..d5cb731d20f
--- /dev/null
+++
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/fs/ozone/TestDataStreamClientExit.java
@@ -0,0 +1,146 @@
+/*
+ * 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.fs.ozone;
+
+import static java.nio.charset.StandardCharsets.UTF_8;
+import static
org.apache.hadoop.ozone.OzoneConfigKeys.HDDS_CONTAINER_RATIS_DATASTREAM_ENABLED;
+import static
org.apache.hadoop.ozone.OzoneConfigKeys.OZONE_FS_DATASTREAM_AUTO_THRESHOLD;
+import static
org.apache.hadoop.ozone.OzoneConfigKeys.OZONE_FS_DATASTREAM_ENABLED;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.io.File;
+import java.io.OutputStream;
+import java.net.URI;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.concurrent.TimeUnit;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import org.apache.hadoop.fs.FSDataOutputStream;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.hdds.conf.OzoneConfiguration;
+import org.apache.hadoop.ozone.DataTestUtil;
+import org.apache.hadoop.ozone.MiniOzoneCluster;
+import org.apache.hadoop.ozone.OzoneConsts;
+import org.apache.hadoop.ozone.client.OzoneBucket;
+import org.apache.hadoop.ozone.client.OzoneClient;
+import org.apache.hadoop.ozone.om.helpers.BucketLayout;
+import org.apache.ozone.test.GenericTestUtils;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+import org.junit.jupiter.api.io.TempDir;
+
+/**
+ * Tests that a JVM which wrote with Ratis data streaming exits without
closing its FileSystem, as a MapReduce task
+ * does, once its idle datanode clients are closed (HDDS-17278). The client
has to run in its own JVM, as the exit is
+ * what is tested.
+ */
+@Timeout(300)
+public class TestDataStreamClientExit {
+
+ private static final String RESULT = "DATASTREAM_CLIENT_RESULT";
+ private static final Pattern RESULT_LINE = Pattern.compile(RESULT + "
streamThreads=(\\d+)");
+ private static final long IDLE_THRESHOLD_SECONDS = 1;
+ /** The idle threshold, Netty's 2 s quiet period for shutting down the
worker group, and a margin. */
+ private static final long EXIT_SECONDS = 30;
+
+ private static MiniOzoneCluster cluster;
+ private static OzoneBucket bucket;
+
+ @TempDir
+ private Path dir;
+
+ @BeforeAll
+ public static void init() throws Exception {
+ OzoneConfiguration conf = new OzoneConfiguration();
+ conf.setBoolean(HDDS_CONTAINER_RATIS_DATASTREAM_ENABLED, true);
+ conf.setBoolean(OZONE_FS_DATASTREAM_ENABLED, true);
+ // stream every write
+ conf.set(OZONE_FS_DATASTREAM_AUTO_THRESHOLD, "1B");
+ cluster = MiniOzoneCluster.newBuilder(conf).setNumDatanodes(3).build();
+ cluster.waitForClusterToBeReady();
+ try (OzoneClient client = cluster.newClient()) {
+ bucket = DataTestUtil.createVolumeAndBucket(client,
BucketLayout.FILE_SYSTEM_OPTIMIZED);
+ }
+ }
+
+ @AfterAll
+ public static void shutdown() {
+ if (cluster != null) {
+ cluster.shutdown();
+ }
+ }
+
+ @Test
+ void clientExitsWithoutClosingFileSystem() throws Exception {
+ // the child's configuration directory, ahead of the test resources on its
classpath
+ Path confDir = Files.createDirectories(dir.resolve("conf"));
+ OzoneConfiguration conf = new OzoneConfiguration(cluster.getConf());
+ conf.set("scm.container.client.idle.threshold", IDLE_THRESHOLD_SECONDS +
"s");
+ try (OutputStream out =
Files.newOutputStream(confDir.resolve("ozone-site.xml"))) {
+ conf.writeXml(out);
+ }
+ String uri = String.format("%s://%s.%s/", OzoneConsts.OZONE_URI_SCHEME,
bucket.getName(), bucket.getVolumeName());
+
+ Path output = dir.resolve("client.log");
+ String classpath = confDir + File.pathSeparator
+ + System.getProperty("surefire.test.class.path",
System.getProperty("java.class.path"));
+ Process process = new ProcessBuilder(
+ Paths.get(System.getProperty("java.home"), "bin", "java").toString(),
+ "-cp", classpath, TestDataStreamClientExit.class.getName(), uri)
+ .redirectErrorStream(true).redirectOutput(output.toFile()).start();
+ try {
+ // the write, then the exit
+ GenericTestUtils.waitFor(() -> !process.isAlive() ||
log(output).contains(RESULT), 500, 120_000);
+ boolean exited = process.waitFor(EXIT_SECONDS, TimeUnit.SECONDS);
+ String log = log(output);
+ Matcher result = RESULT_LINE.matcher(log);
+ assertTrue(result.find(), "No result from the client:\n" + log);
+ // the client wrote through data streaming, so without closing its idle
clients it would not exit
+ assertTrue(Integer.parseInt(result.group(1)) > 0, "No non-daemon data
stream thread\n" + log);
+ assertTrue(exited, "The client did not exit within " + EXIT_SECONDS + "
s after writing:\n" + log);
+ assertEquals(0, process.exitValue(), log);
+ } finally {
+ process.destroyForcibly();
+ }
+ }
+
+ private static String log(Path output) {
+ try {
+ return new String(Files.readAllBytes(output), UTF_8);
+ } catch (Exception e) {
+ return "";
+ }
+ }
+
+ /** The client process: writes a file with data streaming and returns
without closing the FileSystem. */
+ public static void main(String[] args) throws Exception {
+ FileSystem fs = FileSystem.get(URI.create(args[0]), new
OzoneConfiguration());
+ try (FSDataOutputStream out = fs.create(new
org.apache.hadoop.fs.Path("/file"))) {
+ out.write(new byte[1 << 20]);
+ }
+ long streamThreads = Thread.getAllStackTraces().keySet().stream()
+ .filter(t -> !t.isDaemon() &&
t.getName().startsWith("NettyClientStreamRpc-workerGroup"))
+ .count();
+ System.out.println(RESULT + " streamThreads=" + streamThreads);
+ }
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]