This is an automated email from the ASF dual-hosted git repository.
jojochuang 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 6b78ebd246a HDDS-15255. Close cached Ratis clients in parallel when
XceiverClientManager is closed (#11684)
6b78ebd246a is described below
commit 6b78ebd246af50acf0fecc2bb8f3e0d036b206b0
Author: Andrey Yarovoy <[email protected]>
AuthorDate: Fri Oct 30 19:24:38 2026 -0400
HDDS-15255. Close cached Ratis clients in parallel when
XceiverClientManager is closed (#11684)
Co-authored-by: Claude Code (Claude Opus 5.5)
---
.../hadoop/hdds/scm/XceiverClientManager.java | 48 +++-
.../TestXceiverClientManagerCloseContention.java | 37 +++
.../scm/TestXceiverClientManagerCloseStall.java | 252 +++++++++++++++++++++
3 files changed, 333 insertions(+), 4 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 a47398a877a..63fbe0ff9e9 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
@@ -32,9 +32,13 @@
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.io.IOException;
import java.net.InetSocketAddress;
+import java.util.ArrayList;
+import java.util.List;
import java.util.Objects;
+import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
@@ -77,6 +81,8 @@ public class XceiverClientManager extends
XceiverClientCreator {
private final CacheMetrics cacheMetrics;
private static XceiverClientMetrics metrics;
private final ConcurrentHashMap<String, DatanodeDetails> localDNCache;
+ /** Unreferenced clients evicted by {@link #close()}, to be closed by it;
guarded by {@link #clientCache}. */
+ private List<XceiverClientSpi> clientsToClose;
private final ExecutorService closeExecutor;
/**
@@ -115,7 +121,11 @@ public void onRemoval(
// Mark the entry as evicted
XceiverClientSpi info = removalNotification.getValue();
if (info.setEvicted()) {
- closeAsync(info);
+ if (clientsToClose == null) {
+ closeAsync(info);
+ } else {
+ clientsToClose.add(info);
+ }
}
}
}
@@ -311,9 +321,18 @@ private String getPipelineCacheKey(Pipeline pipeline,
boolean topologyAware, boo
@Override
public void close() {
super.close();
- //closing is done through RemovalListener
- clientCache.invalidateAll();
- clientCache.cleanUp();
+ final List<XceiverClientSpi> unreferenced = new ArrayList<>();
+ synchronized (clientCache) {
+ // the RemovalListener collects the unreferenced clients instead of
closing them one by one
+ clientsToClose = unreferenced;
+ try {
+ clientCache.invalidateAll();
+ clientCache.cleanUp();
+ } finally {
+ clientsToClose = null;
+ }
+ }
+ closeInParallel(unreferenced);
ConcurrentUtils.shutdownAndWait(closeExecutor);
if (LOG.isDebugEnabled()) {
LOG.debug("XceiverClient cache stats: {}", clientCache.stats());
@@ -326,6 +345,27 @@ public void close() {
}
}
+ /**
+ * Close the clients concurrently. Closing a Ratis client can wait seconds
for its gRPC channels to shut down
+ * gracefully, and closing the clients one after another adds those waits up
(HDDS-15255).
+ */
+ private static void closeInParallel(List<XceiverClientSpi> clients) {
+ if (clients.size() <= 1) {
+ clients.forEach(XceiverClientManager::closeAndLog);
+ return;
+ }
+ // one thread per client, so all the waits overlap; the cache size bounds
the number of clients
+ final ExecutorService executor =
Executors.newFixedThreadPool(clients.size(),
+ new
ThreadFactoryBuilder().setNameFormat("XceiverClientManager-close-%d").setDaemon(true).build());
+ try {
+ CompletableFuture.allOf(clients.stream()
+ .map(client -> CompletableFuture.runAsync(() -> closeAndLog(client),
executor))
+ .toArray(CompletableFuture[]::new)).join();
+ } finally {
+ executor.shutdown();
+ }
+ }
+
/**
* Get xceiver client metric.
*/
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 f8412aa856b..42de6365617 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
@@ -219,4 +219,41 @@ protected XceiverClientSpi newClient(Pipeline pipeline,
DatanodeDetails dn) {
// closing the manager waits for pending closes
assertThat(closed).isTrue();
}
+
+ @Test
+ void managerClosesCachedClientsInParallel() throws Exception {
+ CountDownLatch closeStarted = new CountDownLatch(3);
+ AtomicBoolean allClosesOverlapped = new AtomicBoolean(true);
+ AtomicBoolean closedUnderCacheLock = new AtomicBoolean();
+ ScmClientConfig clientConf = new XceiverClientManagerConfigBuilder()
+ .setMaxCacheSize(3)
+ .setStaleThresholdMs(TimeUnit.SECONDS.toMillis(30))
+ .build();
+ 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 -> {
+ if (Thread.holdsLock(getClientCache())) {
+ closedUnderCacheLock.set(true);
+ }
+ closeStarted.countDown();
+ if (!closeStarted.await(10, TimeUnit.SECONDS)) {
+ allClosesOverlapped.set(false);
+ }
+ return null;
+ }).when(client).close();
+ return client;
+ }
+ }) {
+ for (int i = 0; i < 3; i++) {
+ XceiverClientSpi client =
manager.acquireClient(MockPipeline.createPipeline(1));
+ manager.releaseClient(client, false);
+ }
+ }
+ assertThat(closeStarted.getCount()).isZero();
+ assertThat(allClosesOverlapped).isTrue();
+ assertThat(closedUnderCacheLock).isFalse();
+ }
}
diff --git
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/hdds/scm/TestXceiverClientManagerCloseStall.java
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/hdds/scm/TestXceiverClientManagerCloseStall.java
new file mode 100644
index 00000000000..057a842e469
--- /dev/null
+++
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/hdds/scm/TestXceiverClientManagerCloseStall.java
@@ -0,0 +1,252 @@
+/*
+ * 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.apache.hadoop.hdds.protocol.DatanodeDetails.Port.Name.RATIS;
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.hadoop.hdds.client.RatisReplicationConfig;
+import org.apache.hadoop.hdds.conf.OzoneConfiguration;
+import org.apache.hadoop.hdds.protocol.DatanodeDetails;
+import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
+import org.apache.hadoop.hdds.scm.XceiverClientManager.ScmClientConfig;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.hdds.scm.storage.ContainerProtocolCalls;
+import org.apache.hadoop.io.IOUtils;
+import org.apache.hadoop.ozone.MiniOzoneCluster;
+import org.apache.ozone.test.GenericTestUtils;
+import org.apache.ozone.test.GenericTestUtils.LogCapturer;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestInstance;
+import org.junit.jupiter.api.Timeout;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Closing an {@link XceiverClientManager} must not wait for its Ratis clients
one after another (HDDS-15255).
+ * <p>
+ * Ratis waits up to 3 s for each gRPC channel to terminate gracefully when a
client is closed. A channel
+ * doesn't terminate until the datanode completes the client's half-closed
stream, so a datanode that doesn't
+ * answer costs the full grace period. To reproduce that deterministically,
every client here talks to its
+ * datanodes through a {@link StallableForwarder}, which is then switched to
keep the connections open but
+ * drop all traffic.
+ */
+@TestInstance(TestInstance.Lifecycle.PER_CLASS)
+@Timeout(300)
+public class TestXceiverClientManagerCloseStall {
+
+ private static final Logger LOG =
LoggerFactory.getLogger(TestXceiverClientManagerCloseStall.class);
+
+ /** Hard-coded in Ratis {@code GrpcUtil.shutdownManagedChannel}. */
+ private static final long GRACEFUL_SHUTDOWN_MS = 3000;
+ private static final String GRACEFUL_SHUTDOWN_TIMED_OUT = "Timed out
gracefully shutting down connection";
+ private static final int MIN_PIPELINES = 3;
+
+ private static final AtomicLong CONTAINER_ID = new AtomicLong(1_000_000);
+
+ private MiniOzoneCluster cluster;
+ private OzoneConfiguration conf;
+ private final List<StallableForwarder> forwarders = new
CopyOnWriteArrayList<>();
+
+ @BeforeAll
+ void init() throws Exception {
+ conf = new OzoneConfiguration();
+ // several RATIS/THREE pipelines on the same three datanodes
+ conf.setInt(ScmConfigKeys.OZONE_DATANODE_PIPELINE_LIMIT, MIN_PIPELINES +
1);
+ cluster = MiniOzoneCluster.newBuilder(conf).setNumDatanodes(3).build();
+ cluster.waitForClusterToBeReady();
+ cluster.waitForPipelineTobeReady(HddsProtos.ReplicationFactor.THREE,
60000);
+ GenericTestUtils.waitFor(() -> openRatisThreePipelines().size() >=
MIN_PIPELINES, 500, 120000);
+ }
+
+ @AfterAll
+ void shutdown() {
+ if (cluster != null) {
+ cluster.shutdown();
+ }
+ }
+
+ @AfterEach
+ void closeForwarders() {
+ forwarders.forEach(f -> IOUtils.cleanupWithLogger(LOG, f));
+ forwarders.clear();
+ }
+
+ @Test
+ void closeDoesNotWaitForEachStalledClientInTurn() throws Exception {
+ final List<Pipeline> pipelines = openRatisThreePipelines();
+ final XceiverClientManager manager =
newManagerWithCachedClients(pipelines);
+ forwarders.forEach(StallableForwarder::stall);
+
+ try (LogCapturer logs =
LogCapturer.captureLogs(LoggerFactory.getLogger("org.apache.ratis.grpc.GrpcUtil")))
{
+ final long elapsedMs = timeClose(manager);
+ final int timedOut = StringUtils.countMatches(logs.getOutput(),
GRACEFUL_SHUTDOWN_TIMED_OUT);
+ LOG.info("Closed {} clients of stalled datanodes in {} ms, {} channels
timed out", pipelines.size(),
+ elapsedMs, timedOut);
+
+ // each client really waited for its stalled channel
+ assertThat(timedOut).isGreaterThanOrEqualTo(pipelines.size());
+ // ... but not one after another: closing them one at a time takes
pipelines.size() * 3 s or more
+ assertThat(elapsedMs).isLessThan(2 * GRACEFUL_SHUTDOWN_MS);
+ }
+ }
+
+ @Test
+ void closeIsFastWhenDatanodesRespond() throws Exception {
+ final List<Pipeline> pipelines = openRatisThreePipelines();
+ final XceiverClientManager manager =
newManagerWithCachedClients(pipelines);
+
+ try (LogCapturer logs =
LogCapturer.captureLogs(LoggerFactory.getLogger("org.apache.ratis.grpc.GrpcUtil")))
{
+ final long elapsedMs = timeClose(manager);
+ LOG.info("Closed {} clients of responsive datanodes in {} ms",
pipelines.size(), elapsedMs);
+
+ assertThat(logs.getOutput()).doesNotContain(GRACEFUL_SHUTDOWN_TIMED_OUT);
+ assertThat(elapsedMs).isLessThan(GRACEFUL_SHUTDOWN_MS);
+ }
+ }
+
+ private List<Pipeline> openRatisThreePipelines() {
+ return
cluster.getStorageContainerManager().getPipelineManager().getPipelines(
+
RatisReplicationConfig.getInstance(HddsProtos.ReplicationFactor.THREE),
Pipeline.PipelineState.OPEN);
+ }
+
+ /**
+ * @return a manager holding one released (refcount 0) Ratis client per
pipeline, as at the exit of a client
+ * process, each with an open stream to its datanodes through a forwarder
+ */
+ private XceiverClientManager newManagerWithCachedClients(List<Pipeline>
pipelines) throws IOException {
+ final XceiverClientManager manager = new XceiverClientManager(conf,
conf.getObject(ScmClientConfig.class), null);
+ for (Pipeline pipeline : pipelines) {
+ final XceiverClientSpi client =
manager.acquireClient(throughForwarders(pipeline));
+ assertThat(client).isInstanceOf(XceiverClientRatis.class);
+ ContainerProtocolCalls.createContainer(client,
CONTAINER_ID.incrementAndGet(), null);
+ manager.releaseClient(client, false);
+ }
+ assertThat(manager.getClientCache().size()).isEqualTo(pipelines.size());
+ return manager;
+ }
+
+ /** The same pipeline, with each datanode's client port replaced by a
forwarder to it. */
+ private Pipeline throughForwarders(Pipeline pipeline) throws IOException {
+ final List<DatanodeDetails> nodes = new ArrayList<>();
+ for (DatanodeDetails dn : pipeline.getNodes()) {
+ final InetAddress address = InetAddress.getByName(dn.getIpAddress());
+ final StallableForwarder forwarder = new StallableForwarder(address,
+ new InetSocketAddress(address, dn.getPort(RATIS).getValue()));
+ forwarders.add(forwarder);
+ nodes.add(DatanodeDetails.newBuilder().setDatanodeDetails(dn)
+ .addPort(DatanodeDetails.newPort(RATIS,
forwarder.getPort())).build());
+ }
+ final Pipeline proxied = pipeline.toBuilder().setNodes(nodes).build();
+ assertThat(proxied.getId()).isEqualTo(pipeline.getId());
+ return proxied;
+ }
+
+ private static long timeClose(XceiverClientManager manager) {
+ final long start = System.nanoTime();
+ manager.close();
+ return TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
+ }
+
+ /**
+ * Forwards TCP connections to a target. After {@link #stall()} it keeps the
connections open but drops all
+ * traffic in both directions, like a datanode that stopped responding.
+ */
+ private static final class StallableForwarder implements Closeable {
+ private final ServerSocket server;
+ private final InetSocketAddress target;
+ private final List<Socket> sockets = new CopyOnWriteArrayList<>();
+ private volatile boolean stalled;
+
+ StallableForwarder(InetAddress bindAddress, InetSocketAddress target)
throws IOException {
+ this.target = target;
+ this.server = new ServerSocket(0, 50, bindAddress);
+ startDaemon(this::accept, "forwarder-accept-" + getPort());
+ }
+
+ int getPort() {
+ return server.getLocalPort();
+ }
+
+ void stall() {
+ stalled = true;
+ }
+
+ private void accept() {
+ try {
+ while (!server.isClosed()) {
+ final Socket fromClient = server.accept();
+ final Socket toTarget = new Socket(target.getAddress(),
target.getPort());
+ sockets.add(fromClient);
+ sockets.add(toTarget);
+ startDaemon(() -> pump(fromClient, toTarget), "forwarder-c2s-" +
getPort());
+ startDaemon(() -> pump(toTarget, fromClient), "forwarder-s2c-" +
getPort());
+ }
+ } catch (IOException e) {
+ // server socket closed
+ }
+ }
+
+ private void pump(Socket from, Socket to) {
+ final byte[] buffer = new byte[64 << 10];
+ try {
+ final InputStream in = from.getInputStream();
+ final OutputStream out = to.getOutputStream();
+ for (int n; (n = in.read(buffer)) >= 0;) {
+ if (!stalled) {
+ out.write(buffer, 0, n);
+ out.flush();
+ }
+ }
+ } catch (IOException e) {
+ // connection closed
+ } finally {
+ IOUtils.cleanupWithLogger(null, from, to);
+ }
+ }
+
+ private static void startDaemon(Runnable runnable, String name) {
+ final Thread thread = new Thread(runnable, name);
+ thread.setDaemon(true);
+ thread.start();
+ }
+
+ @Override
+ public void close() throws IOException {
+ server.close();
+ sockets.forEach(s -> IOUtils.cleanupWithLogger(null, s));
+ }
+ }
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]