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 8c705b7808f HDDS-17767. Streaming reads hold XceiverClientGrpc request 
permits for the lifetime of the block stream (#12009)
8c705b7808f is described below

commit 8c705b7808f4dac4108cd43ffc2acf851738385d
Author: Sergey Soldatov <[email protected]>
AuthorDate: Fri Nov 20 01:33:13 2026 -0800

    HDDS-17767. Streaming reads hold XceiverClientGrpc request permits for the 
lifetime of the block stream (#12009)
    
    Co-authored-by: Claude Fable 5 <[email protected]>
---
 .../apache/hadoop/hdds/scm/OzoneClientConfig.java  |  26 ++
 .../apache/hadoop/hdds/scm/XceiverClientGrpc.java  | 107 +++++---
 .../hadoop/hdds/scm/TestOzoneClientConfig.java     |   4 +
 .../hdds/scm/TestXceiverClientGrpcStreamRead.java  | 270 +++++++++++++++++++++
 .../scm/storage/TestStreamBlockInputStream.java    |  59 +++++
 5 files changed, 434 insertions(+), 32 deletions(-)

diff --git 
a/hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/OzoneClientConfig.java
 
b/hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/OzoneClientConfig.java
index 069e7b4c3d3..99617bb972e 100644
--- 
a/hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/OzoneClientConfig.java
+++ 
b/hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/OzoneClientConfig.java
@@ -382,6 +382,24 @@ public class OzoneClientConfig {
       description = "Timeout for receiving streaming read responses.")
   private Duration streamReadTimeout = Duration.ofSeconds(10);
 
+  @Config(key = "ozone.client.stream.read.max-concurrent-streams",
+      defaultValue = "-1",
+      type = ConfigType.INT,
+      tags = {ConfigTag.CLIENT},
+      description = "Maximum number of concurrently open streaming read block 
streams per pipeline client. "
+          + "Each open block input stream holds one slot until it is closed; 
opening a stream beyond the limit "
+          + "waits up to ozone.client.stream.read.timeout for a slot; a wait 
that times out is retried under the "
+          + "read retry policy (ozone.client.read.max.retries) before the read 
fails. A positioned read and every "
+          + "block a key input stream has seeked into each hold a slot, so the 
limit must exceed the number of "
+          + "block streams one reader keeps open at once. Each open stream can 
buffer up to "
+          + "ozone.client.stream.read.pre-read-size bytes, so this limit also 
bounds client memory per pipeline. "
+          + "Any non-positive value (the default) makes the limit follow "
+          + "hdds.ratis.raft.client.async.outstanding-requests.max, preserving 
the capacity streaming reads "
+          + "had when they were counted against the request limit. Streaming 
reads no longer consume permits "
+          + "from hdds.ratis.raft.client.async.outstanding-requests.max; that 
limit now applies to unary "
+          + "requests only.")
+  private int streamReadMaxConcurrentStreams = -1;
+
   @Config(key = "ozone.client.netty.warmup.enabled",
       defaultValue = "true",
       type = ConfigType.BOOLEAN,
@@ -773,6 +791,14 @@ public void setStreamReadTimeout(Duration 
streamReadTimeout) {
     this.streamReadTimeout = streamReadTimeout;
   }
 
+  public int getStreamReadMaxConcurrentStreams() {
+    return streamReadMaxConcurrentStreams;
+  }
+
+  public void setStreamReadMaxConcurrentStreams(int 
streamReadMaxConcurrentStreams) {
+    this.streamReadMaxConcurrentStreams = streamReadMaxConcurrentStreams;
+  }
+
   public boolean isDatastreamPutBlockWithoutRaftEnabled() {
     return datastreamPutBlockWithoutRaftEnabled;
   }
diff --git 
a/hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java
 
b/hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java
index a4c49db8bea..3d0fb4d716a 100644
--- 
a/hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java
+++ 
b/hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java
@@ -98,6 +98,9 @@ public class XceiverClientGrpc extends XceiverClientSpi {
   private final ConfigurationSource config;
   private final XceiverClientMetrics metrics;
   private final Semaphore semaphore;
+  // Caps long-lived read streams; separate from the request semaphore so 
streams cannot starve short RPCs.
+  private final Semaphore streamSemaphore;
+  private final int maxConcurrentStreams;
   private long timeout;
   private final long streamReadTimeoutNanos;
   private final SecurityConfig secConfig;
@@ -125,8 +128,14 @@ public XceiverClientGrpc(Pipeline pipeline, 
ConfigurationSource config,
     Objects.requireNonNull(config, "config == null");
     setTimeout(getTimeoutMillis(config, 
OzoneConfigKeys.OZONE_CLIENT_READ_TIMEOUT,
         OzoneConfigKeys.OZONE_CLIENT_READ_TIMEOUT_DEFAULT));
-    this.streamReadTimeoutNanos = config.getObject(OzoneClientConfig.class)
-        .getStreamReadTimeout().toNanos();
+    final OzoneClientConfig clientConfig = 
config.getObject(OzoneClientConfig.class);
+    this.streamReadTimeoutNanos = 
clientConfig.getStreamReadTimeout().toNanos();
+    final int configuredMaxStreams = 
clientConfig.getStreamReadMaxConcurrentStreams();
+    // Non-positive inherits the request limit, matching the capacity streams 
had when they shared its semaphore.
+    this.maxConcurrentStreams = configuredMaxStreams > 0 ? configuredMaxStreams
+        : HddsClientUtils.getMaxOutstandingRequests(config);
+    // Fair, so a waiter is not starved by streams that open and close in a 
loop while the pool is full.
+    this.streamSemaphore = new Semaphore(maxConcurrentStreams, true);
     this.pipeline = pipeline;
     this.config = config;
     this.secConfig = new SecurityConfig(config);
@@ -665,42 +674,78 @@ public void initStreamRead(BlockID blockID, 
StreamingReaderSpi streamObserver) t
    */
   public void initStreamRead(BlockID blockID, StreamingReaderSpi 
streamObserver,
       Set<DatanodeID> excludedDatanodes) throws IOException {
-    final List<DatanodeDetails> datanodeList = sortDatanodes(null, 
ContainerProtos.Type.ReadBlock);
-    IOException lastException = null;
-    for (DatanodeDetails dn : datanodeList) {
+    // Select the candidates before waiting for a permit: an open that no 
datanode can serve must not queue for one.
+    final List<DatanodeDetails> datanodeList = new ArrayList<>();
+    for (DatanodeDetails dn : sortDatanodes(null, 
ContainerProtos.Type.ReadBlock)) {
       if (excludedDatanodes.contains(dn.getID())) {
         LOG.debug("Skipping excluded datanode {} (uuid={}) for initStreamRead 
{}",
             dn, dn.getUuidString(), blockID.getContainerBlockID());
-        continue;
+      } else {
+        datanodeList.add(dn);
       }
-      try {
-        checkOpen(dn);
-        semaphore.acquire();
-        XceiverClientProtocolServiceStub stub = 
dnChannelInfoMap.get(dn.getID()).getStub();
-        if (stub == null) {
-          throw new IOException("Failed to get gRPC stub for DataNode: " + dn);
+    }
+    if (datanodeList.isEmpty()) {
+      throw new IOException("Failed to start streaming read to any available 
DataNodes");
+    }
+    acquireStreamPermit(blockID);
+    boolean started = false;
+    try {
+      IOException lastException = null;
+      for (DatanodeDetails dn : datanodeList) {
+        try {
+          checkOpen(dn);
+          XceiverClientProtocolServiceStub stub = 
dnChannelInfoMap.get(dn.getID()).getStub();
+          if (stub == null) {
+            throw new IOException("Failed to get gRPC stub for DataNode: " + 
dn);
+          }
+          LOG.debug("initStreamRead {} on datanode {}", 
blockID.getContainerBlockID(), dn);
+          // No deadline: it would bound the entire long-lived streaming call. 
Per-request timeliness is
+          // enforced by streamReadTimeout in streamRead() and 
StreamingReader.poll().
+          stub.send(new ReadyAwareResponseObserver(dn, streamObserver));
+          started = true;
+          return;
+        } catch (IOException e) {
+          LOG.error("Failed to start streaming read to DataNode {}", dn, e);
+          lastException = e;
         }
-        LOG.debug("initStreamRead {} on datanode {}", 
blockID.getContainerBlockID(), dn);
-        // No deadline: it would bound the entire long-lived streaming call. 
Per-request timeliness is
-        // enforced by streamReadTimeout in streamRead() and 
StreamingReader.poll().
-        stub.send(new ReadyAwareResponseObserver(dn, streamObserver));
-        return;
-      } catch (IOException e) {
-        LOG.error("Failed to start streaming read to DataNode {}", dn, e);
-        semaphore.release();
-        lastException = e;
-      } catch (InterruptedException e) {
-        Thread.currentThread().interrupt();
-        throw new IOException("Interrupted initStreamRead to " + dn + " for " 
+ blockID, e);
       }
-    }
-    if (lastException != null) {
       throw lastException;
-    } else {
-      throw new IOException("Failed to start streaming read to any available 
DataNodes");
+    } finally {
+      if (!started) {
+        streamSemaphore.release();
+      }
     }
   }
 
+  @VisibleForTesting
+  void acquireStreamPermit(BlockID blockID) throws IOException {
+    try {
+      // Bounded: a reader that already holds a stream on this client 
(sequential read plus pread, or seeks across
+      // blocks) would otherwise wait forever for a permit only it can release.
+      if (!streamSemaphore.tryAcquire(streamReadTimeoutNanos, 
TimeUnit.NANOSECONDS)) {
+        // Retriable for the reader: a stream of another reader may be closed 
within its read retries.
+        throw new TimeoutIOException("Failed to start streaming read for " + 
blockID.getContainerBlockID()
+            + " on pipeline " + pipeline.getId() + ": " + maxConcurrentStreams
+            + " block streams are already open on this pipeline client."
+            + " Close unused input streams or increase 
ozone.client.stream.read.max-concurrent-streams.");
+      }
+    } catch (InterruptedException e) {
+      Thread.currentThread().interrupt();
+      throw (IOException) new InterruptedIOException("Interrupted while 
waiting to start streaming read for "
+          + blockID).initCause(e);
+    }
+  }
+
+  @VisibleForTesting
+  int availableStreamPermits() {
+    return streamSemaphore.availablePermits();
+  }
+
+  @VisibleForTesting
+  int availableRequestPermits() {
+    return semaphore.availablePermits();
+  }
+
   /**
    * Registers the request stream's {@code onReadyHandler} in {@code 
beforeStart}, the only point gRPC allows it,
    * hands the {@link StreamingReadResponse} to the reader from there, and 
tells it when the call terminates so a
@@ -744,13 +789,11 @@ public void onCompleted() {
   }
 
   /**
-   * This method should be called to indicate the end of streaming read. Its 
primary purpose is to release the
-   * semaphore acquired when starting the streaming read, but is also used to 
update any metrics or debug logs as
-   * needed.
+   * Indicates the end of a streaming read: releases the stream permit 
acquired in initStreamRead.
    */
   @Override
   public void completeStreamRead() {
-    semaphore.release();
+    streamSemaphore.release();
   }
 
   private static List<DatanodeDetails> sortDatanodeByOperationalState(
diff --git 
a/hadoop-hdds/client/src/test/java/org/apache/hadoop/hdds/scm/TestOzoneClientConfig.java
 
b/hadoop-hdds/client/src/test/java/org/apache/hadoop/hdds/scm/TestOzoneClientConfig.java
index 3ba468dee77..9e114268dbf 100644
--- 
a/hadoop-hdds/client/src/test/java/org/apache/hadoop/hdds/scm/TestOzoneClientConfig.java
+++ 
b/hadoop-hdds/client/src/test/java/org/apache/hadoop/hdds/scm/TestOzoneClientConfig.java
@@ -94,12 +94,16 @@ public void testStreamReadConfigParsing() {
     conf.set("ozone.client.stream.read.pre-read-size", "67108864");
     conf.set("ozone.client.stream.read.response-data-size", "2097152");
     conf.set("ozone.client.stream.read.timeout", "5s");
+    conf.set("ozone.client.stream.read.max-concurrent-streams", "12");
 
     OzoneClientConfig clientConfig = conf.getObject(OzoneClientConfig.class);
 
     assertEquals(64L << 20, clientConfig.getStreamReadPreReadSize());
     assertEquals(2 << 20, clientConfig.getStreamReadResponseDataSize());
     assertEquals(Duration.ofSeconds(5), clientConfig.getStreamReadTimeout());
+    assertEquals(12, clientConfig.getStreamReadMaxConcurrentStreams());
+
+    assertEquals(-1, new 
OzoneConfiguration().getObject(OzoneClientConfig.class).getStreamReadMaxConcurrentStreams());
   }
 
   @Test
diff --git 
a/hadoop-hdds/client/src/test/java/org/apache/hadoop/hdds/scm/TestXceiverClientGrpcStreamRead.java
 
b/hadoop-hdds/client/src/test/java/org/apache/hadoop/hdds/scm/TestXceiverClientGrpcStreamRead.java
new file mode 100644
index 00000000000..be1a1fd5d9b
--- /dev/null
+++ 
b/hadoop-hdds/client/src/test/java/org/apache/hadoop/hdds/scm/TestXceiverClientGrpcStreamRead.java
@@ -0,0 +1,270 @@
+/*
+ * 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.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+
+import java.io.IOException;
+import java.io.InterruptedIOException;
+import java.util.Collections;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+import org.apache.hadoop.hdds.client.BlockID;
+import org.apache.hadoop.hdds.conf.OzoneConfiguration;
+import org.apache.hadoop.hdds.protocol.MockDatanodeDetails;
+import org.apache.hadoop.hdds.scm.client.HddsClientUtils;
+import org.apache.hadoop.hdds.scm.pipeline.MockPipeline;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.ozone.test.GenericTestUtils;
+import org.apache.ratis.protocol.exceptions.TimeoutIOException;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+
+/**
+ * Tests for streaming read admission control in XceiverClientGrpc: long-lived 
block streams are
+ * bounded by a dedicated semaphore, separate from the request semaphore.
+ */
+class TestXceiverClientGrpcStreamRead {
+
+  private static final String MAX_STREAMS_KEY = 
"ozone.client.stream.read.max-concurrent-streams";
+
+  private static OzoneConfiguration newConf() {
+    OzoneConfiguration conf = new OzoneConfiguration();
+    conf.setInt(MAX_STREAMS_KEY, 1);
+    // Keep the admission wait short so the exhaustion tests fail fast.
+    conf.set("ozone.client.stream.read.timeout", "100ms");
+    return conf;
+  }
+
+  /** Single slot, but a long admission wait, for tests that need a waiter 
parked in acquireStreamPermit. */
+  private static OzoneConfiguration newConfWithLongWait() {
+    OzoneConfiguration conf = new OzoneConfiguration();
+    conf.setInt(MAX_STREAMS_KEY, 1);
+    conf.set("ozone.client.stream.read.timeout", "60s");
+    return conf;
+  }
+
+  private static Pipeline newPipeline() {
+    // Loopback with a free port nothing listens on: a started call is refused 
locally instead of reaching the network.
+    return MockPipeline.createPipeline(
+        
Collections.singletonList(MockDatanodeDetails.randomLocalDatanodeDetails()));
+  }
+
+  /** Starts a thread that waits for a permit and returns it once it is parked 
in acquireStreamPermit. */
+  private static Thread startParkedWaiter(XceiverClientGrpc client, BlockID 
blockID,
+      AtomicReference<IOException> failure, AtomicBoolean interrupted) throws 
Exception {
+    Thread waiter = new Thread(() -> {
+      try {
+        client.acquireStreamPermit(blockID);
+      } catch (IOException e) {
+        failure.set(e);
+      }
+      interrupted.set(Thread.currentThread().isInterrupted());
+    }, "stream-permit-waiter");
+    waiter.start();
+    // Semaphore.tryAcquire(timeout) parks the thread, so this handshake 
proves it reached the wait.
+    GenericTestUtils.waitFor(() -> waiter.getState() == 
Thread.State.TIMED_WAITING, 10, 10_000);
+    return waiter;
+  }
+
+  @Test
+  void streamAdmissionIsBoundedAndReleasedOnCompletion() throws Exception {
+    try (XceiverClientGrpc client = new XceiverClientGrpc(newPipeline(), 
newConf())) {
+      BlockID blockID = new BlockID(1L, 1L);
+      client.acquireStreamPermit(blockID);
+      assertEquals(0, client.availableStreamPermits());
+
+      // TimeoutIOException: the block input stream retries it under the read 
retry policy.
+      IOException e = assertThrows(TimeoutIOException.class, () -> 
client.acquireStreamPermit(blockID),
+          "opening a stream beyond the limit should time out instead of 
blocking indefinitely");
+      assertThat(e.getMessage()).contains(MAX_STREAMS_KEY);
+      assertEquals(0, client.availableStreamPermits(), "a failed wait must not 
touch the held slot");
+
+      client.completeStreamRead();
+      assertEquals(1, client.availableStreamPermits());
+      client.acquireStreamPermit(blockID);
+      assertEquals(0, client.availableStreamPermits());
+      client.completeStreamRead();
+    }
+  }
+
+  /**
+   * A waiter that reaches the slot before the admission timeout gets it: the 
wait is bounded, not a fail-fast.
+   */
+  @Test
+  void waiterAcquiresSlotReleasedBeforeTimeout() throws Exception {
+    try (XceiverClientGrpc client = new XceiverClientGrpc(newPipeline(), 
newConfWithLongWait())) {
+      BlockID blockID = new BlockID(1L, 1L);
+      client.acquireStreamPermit(blockID);
+      AtomicReference<IOException> failure = new AtomicReference<>();
+      AtomicBoolean interrupted = new AtomicBoolean();
+      Thread waiter = startParkedWaiter(client, blockID, failure, interrupted);
+      assertTrue(waiter.isAlive(), "a second stream must wait while the only 
slot is held");
+
+      client.completeStreamRead();
+      waiter.join(TimeUnit.SECONDS.toMillis(10));
+      assertThat(waiter.isAlive()).as("the waiter should have taken the 
released slot").isFalse();
+      assertNull(failure.get());
+      assertEquals(0, client.availableStreamPermits(), "the waiter should hold 
the released slot");
+      client.completeStreamRead();
+      assertEquals(1, client.availableStreamPermits());
+    }
+  }
+
+  /**
+   * The interrupt exit of acquireStreamPermit holds no permit, so it must not 
release one either.
+   */
+  @Test
+  void interruptedWaiterFailsWithoutReleasingPermit() throws Exception {
+    try (XceiverClientGrpc client = new XceiverClientGrpc(newPipeline(), 
newConfWithLongWait())) {
+      BlockID blockID = new BlockID(1L, 1L);
+      client.acquireStreamPermit(blockID);
+      AtomicReference<IOException> failure = new AtomicReference<>();
+      AtomicBoolean interrupted = new AtomicBoolean();
+      Thread waiter = startParkedWaiter(client, blockID, failure, interrupted);
+
+      waiter.interrupt();
+      waiter.join(TimeUnit.SECONDS.toMillis(10));
+      assertThat(waiter.isAlive()).as("an interrupted waiter should fail 
promptly").isFalse();
+      assertThat(failure.get()).isInstanceOf(InterruptedIOException.class);
+      
assertThat(failure.get().getCause()).isInstanceOf(InterruptedException.class);
+      assertTrue(interrupted.get(), "the interrupt flag must be restored");
+      assertEquals(0, client.availableStreamPermits(), "an interrupted wait 
must not release the held slot");
+      client.completeStreamRead();
+    }
+  }
+
+  /**
+   * A started stream keeps its permit until completeStreamRead, and never 
touches the request semaphore.
+   */
+  @Test
+  void startedStreamHoldsPermitUntilCompleted() throws Exception {
+    OzoneConfiguration conf = newConf();
+    final int requestPermits = HddsClientUtils.getMaxOutstandingRequests(conf);
+    try (XceiverClientGrpc client = new XceiverClientGrpc(newPipeline(), 
conf)) {
+      StreamingReaderSpi reader = mock(StreamingReaderSpi.class);
+      // gRPC starts the call lazily, so no datanode needs to be listening for 
the stream to be started.
+      client.initStreamRead(new BlockID(1L, 3L), reader, 
Collections.emptySet());
+      verify(reader).setStreamingReadResponse(any());
+      assertEquals(0, client.availableStreamPermits(), "a started stream must 
keep its permit");
+      assertEquals(requestPermits, client.availableRequestPermits(),
+          "an open stream must not consume a request permit");
+
+      client.completeStreamRead();
+      assertEquals(1, client.availableStreamPermits(), "completeStreamRead 
must release exactly one permit");
+      assertEquals(requestPermits, client.availableRequestPermits());
+    }
+  }
+
+  /**
+   * The pread-after-sequential-read case: a reader whose open stream holds 
the last slot on this pipeline client
+   * and opens another one must fail with an actionable message rather than 
wait for a permit only it can release.
+   */
+  @Test
+  void secondStreamOnFullClientFailsInsteadOfHanging() throws Exception {
+    try (XceiverClientGrpc client = new XceiverClientGrpc(newPipeline(), 
newConf())) {
+      client.initStreamRead(new BlockID(1L, 4L), 
mock(StreamingReaderSpi.class), Collections.emptySet());
+      assertEquals(0, client.availableStreamPermits());
+
+      IOException e = assertThrows(TimeoutIOException.class,
+          () -> client.initStreamRead(new BlockID(1L, 5L), 
mock(StreamingReaderSpi.class), Collections.emptySet()));
+      assertThat(e.getMessage()).contains(MAX_STREAMS_KEY).contains("1 block 
streams are already open");
+      assertEquals(0, client.availableStreamPermits(), "the started stream 
must keep its permit");
+
+      client.completeStreamRead();
+      assertEquals(1, client.availableStreamPermits());
+    }
+  }
+
+  /**
+   * With ozone.client.stream.read.max-concurrent-streams unset or 
non-positive, the stream limit must follow
+   * hdds.ratis.raft.client.async.outstanding-requests.max so existing tuning 
is preserved.
+   */
+  @Test
+  void streamLimitInheritsRequestLimitWhenUnset() throws Exception {
+    OzoneConfiguration conf = new OzoneConfiguration();
+    conf.setInt("hdds.ratis.raft.client.async.outstanding-requests.max", 96);
+    try (XceiverClientGrpc client = new XceiverClientGrpc(newPipeline(), 
conf)) {
+      assertEquals(96, client.availableStreamPermits());
+    }
+
+    for (int nonPositive : new int[] {0, -2}) {
+      conf.setInt(MAX_STREAMS_KEY, nonPositive);
+      try (XceiverClientGrpc client = new XceiverClientGrpc(newPipeline(), 
conf)) {
+        assertEquals(96, client.availableStreamPermits(), "explicit " + 
nonPositive + " should inherit");
+      }
+    }
+
+    // An explicit stream limit takes precedence over the inherited request 
limit.
+    conf.setInt(MAX_STREAMS_KEY, 7);
+    try (XceiverClientGrpc client = new XceiverClientGrpc(newPipeline(), 
conf)) {
+      assertEquals(7, client.availableStreamPermits());
+    }
+  }
+
+  @Test
+  void failedInitStreamReadReleasesPermit() throws Exception {
+    XceiverClientGrpc client = new XceiverClientGrpc(newPipeline(), newConf());
+    client.close();
+    assertThrows(IOException.class,
+        () -> client.initStreamRead(new BlockID(1L, 2L), 
mock(StreamingReaderSpi.class), Collections.emptySet()),
+        "initStreamRead on a closed client should fail");
+    assertEquals(1, client.availableStreamPermits(),
+        "a failed initStreamRead must release the stream permit it acquired");
+  }
+
+  @Test
+  void allDatanodesExcludedReleasesPermit() throws Exception {
+    Pipeline pipeline = newPipeline();
+    try (XceiverClientGrpc client = new XceiverClientGrpc(pipeline, 
newConf())) {
+      IOException e = assertThrows(IOException.class,
+          () -> client.initStreamRead(new BlockID(1L, 6L), 
mock(StreamingReaderSpi.class),
+              Collections.singleton(pipeline.getFirstNode().getID())),
+          "initStreamRead with every datanode excluded should fail");
+      assertEquals("Failed to start streaming read to any available 
DataNodes", e.getMessage());
+      assertEquals(1, client.availableStreamPermits(),
+          "initStreamRead must release the stream permit when no datanode is 
tried");
+    }
+  }
+
+  /**
+   * An open that no datanode can serve must fail right away, without queueing 
for a slot on a full client.
+   */
+  @Test
+  @Timeout(10)
+  void allDatanodesExcludedFailsWithoutWaitingForPermit() throws Exception {
+    Pipeline pipeline = newPipeline();
+    try (XceiverClientGrpc client = new XceiverClientGrpc(pipeline, 
newConfWithLongWait())) {
+      client.acquireStreamPermit(new BlockID(1L, 7L));
+      IOException e = assertThrows(IOException.class,
+          () -> client.initStreamRead(new BlockID(1L, 8L), 
mock(StreamingReaderSpi.class),
+              Collections.singleton(pipeline.getFirstNode().getID())));
+      assertEquals("Failed to start streaming read to any available 
DataNodes", e.getMessage());
+      assertEquals(0, client.availableStreamPermits(), "the held slot must not 
be touched");
+      client.completeStreamRead();
+    }
+  }
+}
diff --git 
a/hadoop-hdds/client/src/test/java/org/apache/hadoop/hdds/scm/storage/TestStreamBlockInputStream.java
 
b/hadoop-hdds/client/src/test/java/org/apache/hadoop/hdds/scm/storage/TestStreamBlockInputStream.java
index 465af2204d2..298343ae8f1 100644
--- 
a/hadoop-hdds/client/src/test/java/org/apache/hadoop/hdds/scm/storage/TestStreamBlockInputStream.java
+++ 
b/hadoop-hdds/client/src/test/java/org/apache/hadoop/hdds/scm/storage/TestStreamBlockInputStream.java
@@ -51,6 +51,7 @@
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
 import java.util.concurrent.Future;
+import java.util.concurrent.Semaphore;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicInteger;
 import java.util.concurrent.atomic.AtomicReference;
@@ -1471,6 +1472,64 @@ public void testRetriesErrorResponseAfterRefresh() 
throws Exception {
     }
   }
 
+  /**
+   * A reader queued behind a full pipeline client is not failed by one 
admission timeout: the open is retried under
+   * the read retry policy and succeeds once a slot is free.
+   */
+  @ParameterizedTest
+  @ValueSource(booleans = {false, true})
+  public void testStreamAdmissionTimeoutIsRetried(boolean positioned) throws 
Exception {
+    OzoneClientConfig clientConfig = newStreamReadConfig();
+    clientConfig.setMaxReadRetryCount(1000);
+    clientConfig.setReadRetryInterval(0);
+    byte[] data = new byte[] {1, 2, 3, 4};
+    ClientCallStreamObserver<ContainerCommandRequestProto> requestObserver = 
mock(ClientCallStreamObserver.class);
+    StreamingReadResponse streamingReadResponse = 
mock(StreamingReadResponse.class);
+    
when(streamingReadResponse.getRequestObserver()).thenReturn(requestObserver);
+
+    // Same admission as XceiverClientGrpc: a bounded wait for the only slot, 
held here by another stream.
+    Semaphore slots = new Semaphore(0);
+    CountDownLatch timedOut = new CountDownLatch(1);
+    AtomicReference<StreamingReaderSpi> lastReader = new AtomicReference<>();
+    XceiverClientGrpc xceiverClient = mock(XceiverClientGrpc.class);
+    doAnswer(inv -> {
+      if (!slots.tryAcquire(20, TimeUnit.MILLISECONDS)) {
+        timedOut.countDown();
+        throw new TimeoutIOException("no stream slot");
+      }
+      StreamingReaderSpi reader = inv.getArgument(1);
+      reader.setStreamingReadResponse(streamingReadResponse);
+      lastReader.set(reader);
+      return null;
+    }).when(xceiverClient).initStreamRead(any(BlockID.class), any(), any());
+    doAnswer(inv -> {
+      slots.release();
+      return null;
+    }).when(xceiverClient).completeStreamRead();
+    doAnswer(inv -> {
+      lastReader.get().onNext(buildResponseProto(data, 0));
+      lastReader.get().onCompleted();
+      return null;
+    }).when(xceiverClient).streamRead(any(), any());
+    XceiverClientFactory xceiverClientFactory = 
mock(XceiverClientFactory.class);
+    
when(xceiverClientFactory.acquireClientForReadData(any(Pipeline.class))).thenReturn(xceiverClient);
+
+    ExecutorService executor = Executors.newSingleThreadExecutor();
+    try (StreamBlockInputStream sbis = new StreamBlockInputStream(
+        newBlockInfo(new BlockID(1L, 24L), data.length), 
mockStandalonePipeline(), null, xceiverClientFactory,
+        NO_REFRESH, clientConfig)) {
+      ByteBuffer buffer = ByteBuffer.allocate(data.length);
+      Future<Integer> read = executor.submit(() -> positioned ? 
sbis.readPositioned(0, buffer) : sbis.read(buffer));
+      assertTrue(timedOut.await(10, TimeUnit.SECONDS), "the open should wait 
for a slot and time out");
+      slots.release();
+      assertEquals(data.length, read.get(10, TimeUnit.SECONDS));
+      assertArrayEquals(data, buffer.array());
+    } finally {
+      executor.shutdownNow();
+    }
+    assertEquals(1, slots.availablePermits(), "the retried stream must release 
exactly the slot it took");
+  }
+
   /**
    * Mocks a streaming read client which captures the StreamingReaderSpi during
    * initStreamRead and drives the given callback when a ReadBlock request is 
sent.


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

Reply via email to