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 ed5eb2c19ae HDDS-16812. Close evicted clients off the caller thread in
XceiverClientManager (#11454)
ed5eb2c19ae is described below
commit ed5eb2c19ae2a5f2573e5da636f3e636d4cb6da7
Author: Siyao Meng <[email protected]>
AuthorDate: Tue Oct 27 22:12:25 2026 -0700
HDDS-16812. Close evicted clients off the caller thread in
XceiverClientManager (#11454)
Co-authored-by: Claude Opus 5.5 <[email protected]>
---
.../hadoop/hdds/scm/XceiverClientManager.java | 40 +++++++++++-
.../TestXceiverClientManagerCloseContention.java | 71 ++++++++++++++++++++--
.../apache/hadoop/hdds/scm/XceiverClientSpi.java | 16 ++---
.../hadoop/hdds/scm/TestXceiverClientManager.java | 7 ++-
4 files changed, 117 insertions(+), 17 deletions(-)
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 1b8d284db94..a47398a877a 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
@@ -29,10 +29,15 @@
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;
+import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.hadoop.hdds.HddsUtils;
import org.apache.hadoop.hdds.conf.Config;
@@ -48,6 +53,7 @@
import org.apache.hadoop.ozone.util.CacheMetrics;
import org.apache.hadoop.ozone.util.OzoneNetUtils;
import org.apache.hadoop.security.UserGroupInformation;
+import org.apache.ratis.util.ConcurrentUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -71,6 +77,7 @@ public class XceiverClientManager extends
XceiverClientCreator {
private final CacheMetrics cacheMetrics;
private static XceiverClientMetrics metrics;
private final ConcurrentHashMap<String, DatanodeDetails> localDNCache;
+ private final ExecutorService closeExecutor;
/**
* Creates a new XceiverClientManager for non secured ozone cluster.
@@ -91,6 +98,9 @@ public XceiverClientManager(ConfigurationSource conf,
Objects.requireNonNull(conf, "conf == null");
long staleThresholdMs = clientConf.getStaleThreshold(MILLISECONDS);
+ // at most one thread, which exits when idle
+ this.closeExecutor = new ThreadPoolExecutor(0, 1, 60, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(),
+ new
ThreadFactoryBuilder().setDaemon(true).setNameFormat("XceiverClientManager-close-%d").build());
this.clientCache = CacheBuilder.newBuilder()
.recordStats()
.expireAfterAccess(staleThresholdMs, MILLISECONDS)
@@ -104,7 +114,9 @@ public void onRemoval(
synchronized (clientCache) {
// Mark the entry as evicted
XceiverClientSpi info = removalNotification.getValue();
- info.setEvicted();
+ if (info.setEvicted()) {
+ closeAsync(info);
+ }
}
}
}).build();
@@ -171,7 +183,9 @@ public void releaseClient(XceiverClientSpi client, boolean
invalidateClient,
boolean topologyAware) {
Objects.requireNonNull(client, "client == null");
synchronized (clientCache) {
- client.decrementReference();
+ if (client.decrementReference()) {
+ closeAsync(client);
+ }
if (invalidateClient) {
Pipeline pipeline = client.getPipeline();
String key = getPipelineCacheKey(pipeline, topologyAware, client
instanceof XceiverClientShortCircuit);
@@ -183,6 +197,27 @@ public void releaseClient(XceiverClientSpi client, boolean
invalidateClient,
}
}
+ /**
+ * Closes the client on a background thread. Closing can wait several
seconds for channel termination,
+ * so it should not run on the caller thread, which holds the clientCache
lock.
+ */
+ private void closeAsync(XceiverClientSpi client) {
+ try {
+ closeExecutor.execute(() -> closeAndLog(client));
+ } catch (RejectedExecutionException e) {
+ // this manager is already closed
+ closeAndLog(client);
+ }
+ }
+
+ private static void closeAndLog(XceiverClientSpi client) {
+ try {
+ client.close();
+ } catch (RuntimeException e) {
+ LOG.warn("Failed to close client for pipeline {}", client.getPipeline(),
e);
+ }
+ }
+
protected XceiverClientSpi getClient(Pipeline pipeline, boolean
topologyAware, boolean allowShortCircuit)
throws IOException {
try {
@@ -279,6 +314,7 @@ public void close() {
//closing is done through RemovalListener
clientCache.invalidateAll();
clientCache.cleanUp();
+ ConcurrentUtils.shutdownAndWait(closeExecutor);
if (LOG.isDebugEnabled()) {
LOG.debug("XceiverClient cache stats: {}", clientCache.stats());
}
diff --git
a/hadoop-hdds/client/src/test/java/org/apache/hadoop/hdds/scm/TestXceiverClientManagerCloseContention.java
b/hadoop-hdds/client/src/test/java/org/apache/hadoop/hdds/scm/TestXceiverClientManagerCloseContention.java
index b817f73cb76..f8412aa856b 100644
---
a/hadoop-hdds/client/src/test/java/org/apache/hadoop/hdds/scm/TestXceiverClientManagerCloseContention.java
+++
b/hadoop-hdds/client/src/test/java/org/apache/hadoop/hdds/scm/TestXceiverClientManagerCloseContention.java
@@ -18,6 +18,10 @@
package org.apache.hadoop.hdds.scm;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.CALLS_REAL_METHODS;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.withSettings;
import java.util.List;
import java.util.concurrent.CountDownLatch;
@@ -25,10 +29,13 @@
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.apache.hadoop.hdds.conf.ConfigurationSource;
import org.apache.hadoop.hdds.conf.OzoneConfiguration;
+import org.apache.hadoop.hdds.protocol.DatanodeDetails;
import org.apache.hadoop.hdds.scm.XceiverClientManager.ScmClientConfig;
import
org.apache.hadoop.hdds.scm.XceiverClientManager.XceiverClientManagerConfigBuilder;
import org.apache.hadoop.hdds.scm.client.ClientTrustManager;
@@ -48,9 +55,9 @@
* observe channel termination. Every {@code close()} therefore costs ≥100ms
* instead of ~1ms.
*
- * <p>The damage is amplified by <em>where</em> {@code close()} runs. Clients
+ * <p>The damage was amplified by <em>where</em> {@code close()} ran. Clients
* are torn down through {@link XceiverClientManager}'s cache eviction, and the
- * whole acquire / evict / close sequence executes under the {@code
clientCache}
+ * whole acquire / evict / close sequence executed under the {@code
clientCache}
* monitor:
* <pre>
* acquireClient() // synchronized (clientCache)
@@ -60,9 +67,12 @@
* -> RemovalListener.onRemoval() // synchronized
(clientCache)
* -> XceiverClientSpi.setEvicted() -> cleanup() ->
close()
* </pre>
- * So the blocking graceful-shutdown wait runs while the {@code clientCache}
- * monitor is held, and every other thread in {@code acquireClient()} /
- * {@code releaseClient()} serializes behind it.
+ * So the blocking graceful-shutdown wait ran while the {@code clientCache}
+ * monitor was held, and every other thread in {@code acquireClient()} /
+ * {@code releaseClient()} serialized behind it.
+ *
+ * <p>The manager now closes evicted clients one at a time on a background
+ * thread, so a slow {@code close()} delays the closes queued behind it.
*
* <p>This test exercises the <b>real</b> {@code XceiverClientManager} and
* {@code XceiverClientGrpc.close()} — nothing is emulated. Real (lazily
@@ -135,6 +145,8 @@ void evictionDrivenCloseDoesNotSerializeAcquisition()
throws Exception {
} finally {
pool.shutdownNow();
}
+ // closing the manager waits for the closes still queued, so that their
cost is measured
+ manager.close();
long wallMillis =
TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - wallStartNanos);
@@ -158,4 +170,53 @@ void evictionDrivenCloseDoesNotSerializeAcquisition()
throws Exception {
.isLessThan(MAX_MILLIS_PER_CLOSE);
}
}
+
+ /**
+ * A client whose close() is slow, like XceiverClientRatis waiting for
channel termination, must be closed
+ * off the caller thread and outside the clientCache lock.
+ */
+ @Test
+ void slowCloseOfEvictedClientDoesNotBlockCaller() throws Exception {
+ ScmClientConfig clientConf = new XceiverClientManagerConfigBuilder()
+ .setMaxCacheSize(1)
+ .setStaleThresholdMs(TimeUnit.SECONDS.toMillis(30))
+ .build();
+ CountDownLatch closeStarted = new CountDownLatch(1);
+ CountDownLatch finishClose = new CountDownLatch(1);
+ AtomicReference<Thread> closeThread = new AtomicReference<>();
+ AtomicBoolean closedUnderCacheLock = new AtomicBoolean();
+ AtomicBoolean closed = new AtomicBoolean();
+
+ try (XceiverClientManager manager = new XceiverClientManager(new
OzoneConfiguration(), clientConf, null) {
+ @Override
+ protected XceiverClientSpi newClient(Pipeline pipeline, DatanodeDetails
dn) {
+ XceiverClientSpi client = mock(XceiverClientSpi.class,
+ withSettings().useConstructor().defaultAnswer(CALLS_REAL_METHODS));
+ doAnswer(invocation -> {
+ closeThread.set(Thread.currentThread());
+ closedUnderCacheLock.set(Thread.holdsLock(getClientCache()));
+ closeStarted.countDown();
+ finishClose.await(10, TimeUnit.SECONDS);
+ closed.set(true);
+ return null;
+ }).when(client).close();
+ return client;
+ }
+ }) {
+ XceiverClientSpi client1 =
manager.acquireClient(MockPipeline.createPipeline(1));
+ manager.releaseClient(client1, false);
+ // evicts client1, which has no reference left and so gets closed
+ XceiverClientSpi client2 =
manager.acquireClient(MockPipeline.createPipeline(1));
+
+ assertThat(closeStarted.await(10, TimeUnit.SECONDS)).isTrue();
+ assertThat(closeThread.get()).isNotSameAs(Thread.currentThread());
+ assertThat(closedUnderCacheLock).isFalse();
+ // the close of client1 is still in progress, yet the cache is usable
+ assertThat(closed).isFalse();
+ manager.releaseClient(client2, false);
+ finishClose.countDown();
+ }
+ // closing the manager waits for pending closes
+ assertThat(closed).isTrue();
+ }
}
diff --git
a/hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientSpi.java
b/hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientSpi.java
index 60d3a1d7b70..0c4b67ac7e9 100644
---
a/hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientSpi.java
+++
b/hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientSpi.java
@@ -69,23 +69,23 @@ void incrementReference() {
this.referenceCount.incrementAndGet();
}
- void decrementReference() {
+ /** @return true if the caller should now close this client. */
+ boolean decrementReference() {
this.referenceCount.decrementAndGet();
- cleanup();
+ return shouldClose();
}
- void setEvicted() {
+ /** @return true if the caller should now close this client. */
+ boolean setEvicted() {
isEvicted = true;
- cleanup();
+ return shouldClose();
}
// close the xceiverClient only if,
// 1) there is no refcount on the client
// 2) it has been evicted from the cache.
- private void cleanup() {
- if (referenceCount.get() == 0 && isEvicted) {
- close();
- }
+ private boolean shouldClose() {
+ return referenceCount.get() == 0 && isEvicted;
}
@VisibleForTesting
diff --git
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/hdds/scm/TestXceiverClientManager.java
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/hdds/scm/TestXceiverClientManager.java
index 391cfc96095..717c8178803 100644
---
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/hdds/scm/TestXceiverClientManager.java
+++
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/hdds/scm/TestXceiverClientManager.java
@@ -40,6 +40,7 @@
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.ozone.OzoneConsts;
import org.apache.hadoop.ozone.container.common.SCMTestUtils;
+import org.apache.ozone.test.GenericTestUtils;
import org.apache.ozone.test.NonHATests;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
@@ -115,7 +116,7 @@ public void testCaching(boolean securityEnabled, @TempDir
Path metaDir) throws I
}
@Test
- public void testFreeByReference(@TempDir Path metaDir) throws IOException {
+ public void testFreeByReference(@TempDir Path metaDir) throws Exception {
OzoneConfiguration conf = new OzoneConfiguration();
ScmClientConfig clientConfig = conf.getObject(ScmClientConfig.class);
clientConfig.setMaxSize(1);
@@ -160,6 +161,7 @@ public void testFreeByReference(@TempDir Path metaDir)
throws IOException {
clientManager.releaseClient(client1, false);
// Create container should throw exception on closed client
+ GenericTestUtils.waitFor(client1::isClosed, 100, 10000);
Throwable t = assertThrows(IOException.class,
() -> ContainerProtocolCalls.createContainer(client1,
container1.getContainerInfo().getContainerID(), null));
@@ -170,7 +172,7 @@ public void testFreeByReference(@TempDir Path metaDir)
throws IOException {
}
@Test
- public void testFreeByEviction(@TempDir Path metaDir) throws IOException {
+ public void testFreeByEviction(@TempDir Path metaDir) throws Exception {
OzoneConfiguration conf = new OzoneConfiguration();
ScmClientConfig clientConfig = conf.getObject(ScmClientConfig.class);
clientConfig.setMaxSize(1);
@@ -209,6 +211,7 @@ public void testFreeByEviction(@TempDir Path metaDir)
throws IOException {
assertNull(nonExistent);
// Any container operation should now fail
+ GenericTestUtils.waitFor(client1::isClosed, 100, 10000);
Throwable t = assertThrows(IOException.class,
() -> ContainerProtocolCalls.createContainer(client1,
container1.getContainerInfo().getContainerID(), null));
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]