You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@ozone.apache.org by "chungen0126 (via GitHub)" <gi...@apache.org> on 2024/04/30 15:21:02 UTC

[PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

chungen0126 opened a new pull request, #6613:
URL: https://github.com/apache/ozone/pull/6613

   ## What changes were proposed in this pull request?
   To reduce round trips between the Client and Datanode for reading a block, we nee a new API to read.
   
   ```
   Client -> block(offset, length) -> Datanode
   Client <- chunkN <- Datanode
   Client <- chunkN+1 <- Datanode
   ..
   Client <-chunkLast <- Datanode
   ```
   This is using the ability of gRPC to send bidirectional traffic such that the server can pipeline the chunks to the client without waiting for ReadChunk API calls. This also avoids the client from creating multiple Chunk Stream Clients and should simplify the read path on the client side by a bit.
   
   ## What is the link to the Apache JIRA
   https://issues.apache.org/jira/browse/HDDS-10338
   
   ## How was this patch tested?
   
   There are existed test for reading data.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "ChenSammi (via GitHub)" <gi...@apache.org>.
ChenSammi commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1866988748


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -618,6 +624,69 @@ private void decreasePendingMetricsAndReleaseSemaphore() {
     return new XceiverClientReply(replyFuture);
   }
 
+  public XceiverClientReply sendCommandReadBlock(
+      ContainerCommandRequestProto request, DatanodeDetails dn)
+      throws IOException, InterruptedException {
+
+    CompletableFuture<ContainerCommandResponseProto> future =
+        new CompletableFuture<>();
+    ContainerCommandResponseProto.Builder response =
+        ContainerCommandResponseProto.newBuilder();
+    ContainerProtos.ReadBlockResponseProto.Builder readBlock =
+        ContainerProtos.ReadBlockResponseProto.newBuilder();
+    checkOpen(dn);
+    UUID dnID = dn.getUuid();
+    Type cmdType = request.getCmdType();
+    semaphore.acquire();
+    long requestTime = System.currentTimeMillis();
+    metrics.incrPendingContainerOpsMetrics(cmdType);
+
+    final StreamObserver<ContainerCommandRequestProto> requestObserver =
+        asyncStubs.get(dnID).withDeadlineAfter(timeout, TimeUnit.SECONDS)
+            .send(new StreamObserver<ContainerCommandResponseProto>() {
+              @Override
+              public void onNext(
+                  ContainerCommandResponseProto responseProto) {
+                if (responseProto.getResult() == Result.SUCCESS) {
+                  readBlock.addReadChunk(responseProto.getReadChunk());
+                } else {
+                  future.complete(

Review Comment:
   Can directly use future.complete(responseProto) here? 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "chungen0126 (via GitHub)" <gi...@apache.org>.
chungen0126 commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1867485183


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/BlockInputStream.java:
##########
@@ -124,6 +124,7 @@ public BlockInputStream(
       OzoneClientConfig config) throws IOException {
     this.blockInfo = blockInfo;
     this.blockID = blockInfo.getBlockID();
+    LOG.debug("Initializing BlockInputStream for block {}", blockID);

Review Comment:
   removed



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "peterxcli (via GitHub)" <gi...@apache.org>.
peterxcli commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1998355206


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -615,6 +622,69 @@ private void decreasePendingMetricsAndReleaseSemaphore() {
     return new XceiverClientReply(replyFuture);
   }
 
+  public XceiverClientReply sendCommandReadBlock(

Review Comment:
   This function seems quite similar as `sendCommandAsync(ContainerCommandRequestProto request, DatanodeDetails dn) throws IOException, InterruptedException` 
   How about create a `StreamObserverFactory` for them?
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "chungen0126 (via GitHub)" <gi...@apache.org>.
chungen0126 commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-2222850796

   Sure, I'll update it shortly.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "sodonnel (via GitHub)" <gi...@apache.org>.
sodonnel commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-3324735795

   The reason for the checksum error above, is this line in `StreamBlockInputStream`:
   
   ```
         if (verifyChecksum) {
           ChecksumData checksumData = ChecksumData.getFromProtoBuf(
               chunkInfo.getChecksumData());
           int startIndex = (int) readChunk.getChunkData().getOffset() / checksumData.getBytesPerChecksum();
   ```
   
   The startIndex calculated needs to be hashed into the checksum position per block. Eg, for a 16kb checksum, there are 256 checksums per 4MB chunk. So the actual checksum index is `startIndex % 256`.
   
   However, the problem is that we don't know the chunkSize in the client, and different blocks could have different chunk sizes if the cluster setting was changed at some point. Each readBlock response carries all the checksums for that chunk and the block offset for the data it contains, but without knowing the chunkSize I don't think there is a way to divide the overall block offset down to the chunk level offset to index into the checksum array for that chunk.
   
   ChunkInputStream works this out by comparing the requested offset with the offset returned, its not clear to me why that works in the general case.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-3481886385

   > That is not how it works in the current production code.  ...
   
   Sure, aren't we changing the current production code to make it more efficient?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "chungen0126 (via GitHub)" <gi...@apache.org>.
chungen0126 commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1792377886


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/StreamBlockInput.java:
##########
@@ -0,0 +1,777 @@
+/*
+ * 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 com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
+import org.apache.commons.lang3.NotImplementedException;
+import org.apache.hadoop.fs.ByteBufferReadable;
+import org.apache.hadoop.fs.CanUnbuffer;
+import org.apache.hadoop.fs.Seekable;
+import org.apache.hadoop.hdds.client.BlockID;
+import org.apache.hadoop.hdds.client.StandaloneReplicationConfig;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadChunkResponseProto;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadBlockResponseProto;
+import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
+import org.apache.hadoop.hdds.scm.OzoneClientConfig;
+import org.apache.hadoop.hdds.scm.XceiverClientFactory;
+import org.apache.hadoop.hdds.scm.XceiverClientSpi;
+import org.apache.hadoop.hdds.scm.client.HddsClientUtils;
+import org.apache.hadoop.hdds.scm.container.common.helpers.StorageContainerException;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.hdds.security.exception.SCMSecurityException;
+import org.apache.hadoop.hdds.security.token.OzoneBlockTokenIdentifier;
+import org.apache.hadoop.io.retry.RetryPolicy;
+import org.apache.hadoop.ozone.common.Checksum;
+import org.apache.hadoop.ozone.common.ChecksumData;
+import org.apache.hadoop.ozone.common.OzoneChecksumException;
+import org.apache.hadoop.ozone.common.utils.BufferUtils;
+import org.apache.hadoop.security.token.Token;
+import org.apache.ratis.thirdparty.com.google.protobuf.ByteString;
+import org.apache.ratis.thirdparty.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.EOFException;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+
+import static org.apache.hadoop.hdds.client.ReplicationConfig.getLegacyFactor;
+
+/**
+ * An {@link java.io.InputStream} called from KeyInputStream to read a block from the
+ * container.
+ */
+public class StreamBlockInput extends BlockExtendedInputStream
+    implements Seekable, CanUnbuffer, ByteBufferReadable {
+  private static final Logger LOG =
+      LoggerFactory.getLogger(StreamBlockInput.class);
+  private final BlockID blockID;
+  private final long length;
+  private final AtomicReference<Pipeline> pipelineRef =
+      new AtomicReference<>();
+  private final AtomicReference<Token<OzoneBlockTokenIdentifier>> tokenRef =
+      new AtomicReference<>();
+  private XceiverClientFactory xceiverClientFactory;
+  private XceiverClientSpi xceiverClient;
+
+  private List<Long> bufferoffsets;
+  private int bufferIndex;
+  private long blockPosition = -1;
+  private List<ByteBuffer> buffers;
+  private boolean allocated = false;
+  private long bufferOffsetWrtBlockDataData;
+  private long buffersSize;
+  private static final int EOF = -1;
+  private final List<XceiverClientSpi.Validator> validators;
+  private final boolean verifyChecksum;
+  private final Function<BlockID, BlockLocationInfo> refreshFunction;
+  private final RetryPolicy retryPolicy;
+  private int retries;
+
+
+  public StreamBlockInput(
+      BlockID blockID, long length, Pipeline pipeline,
+      Token<OzoneBlockTokenIdentifier> token,
+      XceiverClientFactory xceiverClientFactory,
+      Function<BlockID, BlockLocationInfo> refreshFunction,
+      OzoneClientConfig config) throws IOException {
+    this.blockID = blockID;
+    LOG.debug("Initializing StreamBlockInput for block {}", blockID);
+    this.length = length;
+    setPipeline(pipeline);
+    tokenRef.set(token);
+    this.xceiverClientFactory = xceiverClientFactory;
+    this.validators = ContainerProtocolCalls.toValidatorList(
+        (request, response) -> validateBlock(response));
+    this.verifyChecksum = config.isChecksumVerify();
+    this.refreshFunction = refreshFunction;
+    this.retryPolicy =
+        HddsClientUtils.createRetryPolicy(config.getMaxReadRetryCount(),
+            TimeUnit.SECONDS.toMillis(config.getReadRetryInterval()));
+
+  }
+
+
+  public BlockID getBlockID() {
+    return blockID;
+  }
+
+  public long getLength() {
+    return length;
+  }
+
+  @Override
+  public synchronized long getPos() {
+    if (length == 0) {
+      return 0;
+    }
+    if (blockPosition >= 0) {
+      return blockPosition;
+    }
+
+    if (allocated && !buffersHaveData() && !dataRemainingInBlock()) {
+      Preconditions.checkState(
+          bufferOffsetWrtBlockDataData + buffersSize == length,
+          "EOF detected but not at the last byte of the chunk");
+      return length;
+    }
+    if (buffersHaveData()) {
+      // BufferOffset w.r.t to BlockData + BufferOffset w.r.t buffers +
+      // Position of current Buffer
+      return bufferOffsetWrtBlockDataData + bufferoffsets.get(bufferIndex) +
+          buffers.get(bufferIndex).position();
+    }
+    if (buffersAllocated()) {
+      return bufferOffsetWrtBlockDataData + buffersSize;
+    }
+    return 0;
+  }
+
+  @Override
+  public synchronized int read() throws IOException {
+    checkOpen();
+
+    int dataout = EOF;
+    int len = 1;
+    int available;
+    while (len > 0) {
+      try {
+        acquireClient();
+        available = prepareRead(1);
+        retries = 0;
+      } catch (SCMSecurityException ex) {
+        throw ex;
+      } catch (StorageContainerException e) {
+        if (shouldRetryRead(e)) {
+          releaseClient();
+          refreshBlockInfo(e);
+          continue;
+        } else {
+          throw e;
+        }
+      } catch (IOException ioe) {
+        if (shouldRetryRead(ioe)) {
+          if (isConnectivityIssue(ioe)) {
+            releaseClient();
+            refreshBlockInfo(ioe);
+          } else {
+            releaseClient();
+          }
+          continue;
+        } else {
+          throw ioe;
+        }
+      }
+      if (available == EOF) {
+        // There is no more data in the chunk stream. The buffers should have
+        // been released by now
+        Preconditions.checkState(buffers == null);
+      } else {
+        dataout = Byte.toUnsignedInt(buffers.get(bufferIndex).get());
+      }
+
+      len -= available;
+      if (bufferEOF()) {
+        releaseBuffers(bufferIndex);
+      }
+    }
+
+
+    return dataout;
+
+
+  }
+
+  @Override
+  public synchronized int read(byte[] b, int off, int len) throws IOException {
+    // According to the JavaDocs for InputStream, it is recommended that
+    // subclasses provide an override of bulk read if possible for performance
+    // reasons.  In addition to performance, we need to do it for correctness
+    // reasons.  The Ozone REST service uses PipedInputStream and
+    // PipedOutputStream to relay HTTP response data between a Jersey thread and
+    // a Netty thread.  It turns out that PipedInputStream/PipedOutputStream
+    // have a subtle dependency (bug?) on the wrapped stream providing separate
+    // implementations of single-byte read and bulk read.  Without this, get key
+    // responses might close the connection before writing all of the bytes
+    // advertised in the Content-Length.
+    if (b == null) {
+      throw new NullPointerException();
+    }
+    if (off < 0 || len < 0 || len > b.length - off) {
+      throw new IndexOutOfBoundsException();
+    }
+    if (len == 0) {
+      return 0;
+    }
+    int total = 0;
+    int available;
+    while (len > 0) {
+      try {
+        acquireClient();
+        available = prepareRead(len);
+        retries = 0;
+      } catch (SCMSecurityException ex) {
+        throw ex;
+      } catch (StorageContainerException e) {
+        if (shouldRetryRead(e)) {
+          releaseClient();
+          refreshBlockInfo(e);
+          continue;
+        } else {
+          throw e;
+        }
+      } catch (IOException ioe) {
+        if (shouldRetryRead(ioe)) {
+          if (isConnectivityIssue(ioe)) {
+            releaseClient();
+            refreshBlockInfo(ioe);
+          } else {
+            releaseClient();
+          }
+          continue;
+        } else {
+          throw ioe;
+        }
+      }
+      if (available == EOF) {
+        // There is no more data in the block stream. The buffers should have
+        // been released by now
+        Preconditions.checkState(buffers == null);
+        return total != 0 ? total : EOF;
+      }
+      buffers.get(bufferIndex).get(b, off + total, available);
+      len -= available;
+      total += available;
+
+      if (bufferEOF()) {
+        releaseBuffers(bufferIndex);
+      }
+    }
+    return total;
+
+  }
+
+  @Override
+  public synchronized void close() throws IOException {
+    releaseClient();
+    releaseBuffers();
+    xceiverClientFactory = null;
+  }
+
+  @Override
+  public synchronized int read(ByteBuffer byteBuffer) throws IOException {
+    if (byteBuffer == null) {
+      throw new NullPointerException();
+    }
+    int len = byteBuffer.remaining();
+    if (len == 0) {
+      return 0;
+    }
+    int total = 0;
+    int available;
+    while (len > 0) {
+      try {
+        acquireClient();
+        available = prepareRead(len);
+        retries = 0;
+      } catch (SCMSecurityException ex) {
+        throw ex;
+      } catch (StorageContainerException e) {
+        if (shouldRetryRead(e)) {
+          releaseClient();
+          refreshBlockInfo(e);
+          continue;
+        } else {
+          throw e;
+        }
+      } catch (IOException ioe) {
+        if (shouldRetryRead(ioe)) {
+          if (isConnectivityIssue(ioe)) {
+            releaseClient();
+            refreshBlockInfo(ioe);
+          } else {
+            releaseClient();
+          }
+          continue;
+        } else {
+          throw ioe;
+        }
+      }
+      if (available == EOF) {
+        // There is no more data in the block stream. The buffers should have
+        // been released by now
+        Preconditions.checkState(buffers == null);
+        return total != 0 ? total : EOF;
+      }
+      ByteBuffer readBuf = buffers.get(bufferIndex);
+      ByteBuffer tmpBuf = readBuf.duplicate();
+      tmpBuf.limit(tmpBuf.position() + available);
+      byteBuffer.put(tmpBuf);
+      readBuf.position(tmpBuf.position());
+
+      len -= available;
+      total += available;
+
+      if (bufferEOF()) {
+        releaseBuffers(bufferIndex);
+      }
+    }
+    return total;
+  }
+
+  @Override
+  protected int readWithStrategy(ByteReaderStrategy strategy) throws IOException {
+    throw new NotImplementedException("readWithStrategy is not implemented.");
+  }
+
+  @Override
+  public synchronized void seek(long pos) throws IOException {
+    if (pos < 0 || pos > length) {
+      if (pos == 0) {
+        // It is possible for length and pos to be zero in which case
+        // seek should return instead of throwing exception
+        return;
+      }
+      throw new EOFException("EOF encountered at pos: " + pos + " for block: " + blockID);
+    }
+
+    if (buffersHavePosition(pos)) {
+      // The bufferPosition is w.r.t the current block.
+      // Adjust the bufferIndex and position to the seeked position.
+      adjustBufferPosition(pos - bufferOffsetWrtBlockDataData);
+    } else {
+      blockPosition = pos;
+    }
+  }
+
+  @Override
+  public synchronized boolean seekToNewSource(long l) throws IOException {
+    return false;
+  }
+
+  @Override
+  public synchronized void unbuffer() {
+    blockPosition = getPos();
+    releaseClient();
+    releaseBuffers();
+  }
+
+  private void setPipeline(Pipeline pipeline) throws IOException {
+    if (pipeline == null) {
+      return;
+    }
+    long replicaIndexes = pipeline.getNodes().stream().mapToInt(pipeline::getReplicaIndex).distinct().count();
+
+    if (replicaIndexes > 1) {
+      throw new IOException(String.format("Pipeline: %s has nodes containing different replica indexes.",
+          pipeline));
+    }
+
+    // irrespective of the container state, we will always read via Standalone
+    // protocol.
+    boolean okForRead =
+        pipeline.getType() == HddsProtos.ReplicationType.STAND_ALONE
+            || pipeline.getType() == HddsProtos.ReplicationType.EC;
+    Pipeline readPipeline = okForRead ? pipeline : Pipeline.newBuilder(pipeline)
+        .setReplicationConfig(StandaloneReplicationConfig.getInstance(
+            getLegacyFactor(pipeline.getReplicationConfig())))
+        .build();
+    pipelineRef.set(readPipeline);
+  }
+
+  protected synchronized void checkOpen() throws IOException {
+    if (xceiverClientFactory == null) {
+      throw new IOException("BlockInputStream has been closed.");
+    }
+  }
+
+  protected synchronized void acquireClient() throws IOException {
+    if (xceiverClientFactory != null && xceiverClient == null) {
+      final Pipeline pipeline = pipelineRef.get();
+      try {
+        xceiverClient = xceiverClientFactory.acquireClientForReadData(pipeline);
+      } catch (IOException ioe) {
+        LOG.warn("Failed to acquire client for pipeline {}, block {}",
+            pipeline, blockID);
+        throw ioe;
+      }
+    }
+  }
+
+  private synchronized int prepareRead(int len) throws IOException {
+    for (;;) {
+      if (blockPosition >= 0) {
+        if (buffersHavePosition(blockPosition)) {
+          // The current buffers have the seeked position. Adjust the buffer
+          // index and position to point to the buffer position.
+          adjustBufferPosition(blockPosition - bufferOffsetWrtBlockDataData);
+        } else {
+          // Read a required block data to fill the buffers with seeked
+          // position data
+          readDataFromContainer(len);
+        }
+      }
+      if (buffersHaveData()) {
+        // Data is available from buffers
+        ByteBuffer bb = buffers.get(bufferIndex);
+        return Math.min(len, bb.remaining());
+      } else if (dataRemainingInBlock()) {
+        // There is more data in the block stream which has not
+        // been read into the buffers yet.
+        readDataFromContainer(len);
+      } else {
+        // All available input from this block stream has been consumed.
+        return EOF;
+      }
+    }
+
+
+  }
+
+  private boolean buffersHavePosition(long pos) {
+    // Check if buffers have been allocated
+    if (buffersAllocated()) {
+      // Check if the current buffers cover the input position
+      // Released buffers should not be considered when checking if position
+      // is available
+      return pos >= bufferOffsetWrtBlockDataData +
+          bufferoffsets.get(0) &&
+          pos < bufferOffsetWrtBlockDataData + buffersSize;
+    }
+    return false;
+  }
+
+  /**
+   * Check if the buffers have been allocated data and false otherwise.
+   */
+  @VisibleForTesting
+  protected boolean buffersAllocated() {
+    return buffers != null && !buffers.isEmpty();
+  }
+
+  /**
+   * Adjust the buffers position to account for seeked position and/ or checksum
+   * boundary reads.
+   * @param bufferPosition the position to which the buffers must be advanced
+   */
+  private void adjustBufferPosition(long bufferPosition) {
+    // The bufferPosition is w.r.t the current buffers.
+    // Adjust the bufferIndex and position to the seeked bufferPosition.
+    if (bufferIndex >= buffers.size()) {
+      bufferIndex = Collections.binarySearch(bufferoffsets, bufferPosition);
+    } else if (bufferPosition < bufferoffsets.get(bufferIndex)) {
+      bufferIndex = Collections.binarySearch(
+          bufferoffsets.subList(0, bufferIndex), bufferPosition);
+    } else if (bufferPosition >= bufferoffsets.get(bufferIndex) +
+        buffers.get(bufferIndex).capacity()) {
+      bufferIndex = Collections.binarySearch(bufferoffsets.subList(
+          bufferIndex + 1, buffers.size()), bufferPosition);
+    }
+    if (bufferIndex < 0) {
+      bufferIndex = -bufferIndex - 2;
+    }
+
+    buffers.get(bufferIndex).position(
+        (int) (bufferPosition - bufferoffsets.get(bufferIndex)));
+
+    // Reset buffers > bufferIndex to position 0. We do this to reset any
+    // previous reads/ seeks which might have updated any buffer position.
+    // For buffers < bufferIndex, we do not need to reset the position as it
+    // not required for this read. If a seek was done to a position in the
+    // previous indices, the buffer position reset would be performed in the
+    // seek call.
+    for (int i = bufferIndex + 1; i < buffers.size(); i++) {
+      buffers.get(i).position(0);
+    }
+
+    // Reset the blockPosition as chunk stream has been initialized i.e. the
+    // buffers have been allocated.
+    blockPosition = -1;
+  }
+
+  /**
+   * Reads full or partial Chunk from DN Container based on the current
+   * position of the ChunkInputStream, the number of bytes of data to read
+   * and the checksum boundaries.
+   * If successful, then the read data in saved in the buffers so that
+   * subsequent read calls can utilize it.
+   * @param len number of bytes of data to be read
+   * @throws IOException if there is an I/O error while performing the call
+   * to Datanode
+   */
+  private synchronized void readDataFromContainer(int len) throws IOException {
+    // index of first byte to be read from the block
+    long startByteIndex;
+    if (blockPosition >= 0) {
+      // If seek operation was called to advance the buffer position, the
+      // chunk should be read from that position onwards.
+      startByteIndex = blockPosition;
+    } else {
+      // Start reading the block from the last blockPosition onwards.
+      startByteIndex = bufferOffsetWrtBlockDataData + buffersSize;
+    }
+
+    // bufferOffsetWrtChunkData and buffersSize are updated after the data
+    // is read from Container and put into the buffers, but if read fails
+    // and is retried, we need the previous position.  Position is reset after
+    // successful read in adjustBufferPosition()
+    blockPosition = getPos();
+    bufferOffsetWrtBlockDataData = readData(startByteIndex, len);
+    long tempOffset = 0L;
+    buffersSize = 0L;
+    bufferoffsets = new ArrayList<>(buffers.size());
+    for (ByteBuffer buffer : buffers) {
+      bufferoffsets.add(tempOffset);
+      tempOffset += buffer.limit();
+      buffersSize += buffer.limit();
+
+    }
+    bufferIndex = 0;
+    allocated = true;
+    adjustBufferPosition(startByteIndex - bufferOffsetWrtBlockDataData);
+
+  }
+
+  @VisibleForTesting
+  protected long readData(long startByteIndex, long len)
+      throws IOException {
+    Pipeline pipeline = pipelineRef.get();
+    buffers = new ArrayList<>();
+    ReadBlockResponseProto response =
+        ContainerProtocolCalls.readBlock(xceiverClient, startByteIndex,
+        len, blockID, validators, tokenRef.get(), pipeline.getReplicaIndexes(), verifyChecksum);
+    List<ReadChunkResponseProto> readBlocks = response.getReadChunkList();
+
+    for (ReadChunkResponseProto readBlock : readBlocks) {
+      if (readBlock.hasDataBuffers()) {
+        buffers.addAll(BufferUtils.getReadOnlyByteBuffers(
+            readBlock.getDataBuffers().getBuffersList()));
+      } else {
+        throw new IOException("Unexpected error while reading chunk data " +
+            "from container. No data returned.");
+      }
+    }
+    return response.getReadChunk(0)
+        .getChunkData().getOffset();
+  }
+
+  /**
+   * Check if the buffers have any data remaining between the current
+   * position and the limit.
+   */
+  private boolean buffersHaveData() {
+    boolean hasData = false;
+    if (buffersAllocated()) {
+      int buffersLen = buffers.size();
+      while (bufferIndex < buffersLen) {
+        ByteBuffer buffer = buffers.get(bufferIndex);
+        if (buffer != null && buffer.hasRemaining()) {
+          // current buffer has data
+          hasData = true;
+          break;
+        } else {
+          if (bufferIndex < buffersLen - 1) {
+            // move to next available buffer
+            ++bufferIndex;
+            Preconditions.checkState(bufferIndex < buffers.size());
+          } else {
+            // no more buffers remaining
+            break;
+          }
+        }
+      }
+    }
+
+    return hasData;
+  }
+
+  /**
+   * Check if there is more data in the chunk which has not yet been read
+   * into the buffers.
+   */
+  private boolean dataRemainingInBlock() {
+    long bufferPos;
+    if (blockPosition >= 0) {
+      bufferPos = blockPosition;
+    } else {
+      bufferPos = bufferOffsetWrtBlockDataData + buffersSize;
+    }
+
+    return bufferPos < length;
+  }
+
+  /**
+   * Check if current buffer had been read till the end.
+   */
+  private boolean bufferEOF() {
+    return allocated && !buffers.get(bufferIndex).hasRemaining();
+  }
+
+  /**
+   * Release the buffers upto the given index.
+   * @param releaseUptoBufferIndex bufferIndex (inclusive) upto which the
+   *                               buffers must be released
+   */
+  private void releaseBuffers(int releaseUptoBufferIndex) {
+    int buffersLen = buffers.size();
+    if (releaseUptoBufferIndex == buffersLen - 1) {
+      // Before releasing all the buffers, if block EOF is not reached, then
+      // blockPosition should be set to point to the last position of the
+      // buffers. This should be done so that getPos() can return the current
+      // block position
+      blockPosition = bufferOffsetWrtBlockDataData +
+          bufferoffsets.get(releaseUptoBufferIndex) +
+          buffers.get(releaseUptoBufferIndex).capacity();
+      // Release all the buffers
+      releaseBuffers();
+    } else {
+      buffers = buffers.subList(releaseUptoBufferIndex + 1, buffersLen);
+      bufferoffsets = bufferoffsets.subList(
+          releaseUptoBufferIndex + 1, buffersLen);
+    }
+  }
+
+  /**
+   * If EOF is reached, release the buffers.
+   */
+  private void releaseBuffers() {
+    buffers = null;
+    bufferIndex = 0;
+    // We should not reset bufferOffsetWrtChunkData and buffersSize here
+    // because when getPos() is called we use these
+    // values and determine whether chunk is read completely or not.
+  }
+
+  protected synchronized void releaseClient() {
+    if (xceiverClientFactory != null && xceiverClient != null) {
+      xceiverClientFactory.releaseClientForReadData(xceiverClient, false);
+      xceiverClient = null;
+    }
+  }
+
+  private void validateBlock(
+      ContainerProtos.ContainerCommandResponseProto response
+  ) throws IOException {
+
+    ReadBlockResponseProto readBlock = response.getReadBlock();
+    for (ReadChunkResponseProto readChunk : readBlock.getReadChunkList()) {
+      List<ByteString> byteStrings;
+
+      ContainerProtos.ChunkInfo chunkInfo =
+          readChunk.getChunkData();
+      if (chunkInfo.getLen() <= 0) {
+        throw new IOException("Failed to get chunk: chunkName == "
+            + chunkInfo.getChunkName() + "len == " + chunkInfo.getLen());
+      }
+      byteStrings = readChunk.getDataBuffers().getBuffersList();
+      long buffersLen = BufferUtils.getBuffersLen(byteStrings);
+      if (buffersLen != chunkInfo.getLen()) {
+        // Bytes read from chunk should be equal to chunk size.
+        throw new OzoneChecksumException(String.format(
+            "Inconsistent read for chunk=%s len=%d bytesRead=%d",
+            chunkInfo.getChunkName(), chunkInfo.getLen(),
+            buffersLen));
+      }
+
+
+      if (verifyChecksum) {
+        ChecksumData checksumData = ChecksumData.getFromProtoBuf(
+            chunkInfo.getChecksumData());
+        int startIndex = (int) readChunk.getChunkData().getOffset() / checksumData.getBytesPerChecksum();
+
+        // ChecksumData stores checksum for each 'numBytesPerChecksum'
+        // number of bytes in a list. Compute the index of the first
+        // checksum to match with the read data
+
+        Checksum.verifyChecksum(byteStrings, checksumData, startIndex,
+            false);
+      }
+    }
+  }
+
+  @VisibleForTesting
+  protected synchronized void setBuffers(List<ByteBuffer> buffers) {
+    this.buffers = buffers;
+  }
+
+  private boolean shouldRetryRead(IOException cause) throws IOException {
+    RetryPolicy.RetryAction retryAction;
+    try {
+      retryAction = retryPolicy.shouldRetry(cause, ++retries, 0, true);
+    } catch (IOException e) {
+      throw e;
+    } catch (Exception e) {
+      throw new IOException(e);
+    }
+    return retryAction.action == RetryPolicy.RetryAction.RetryDecision.RETRY;
+  }
+
+  @VisibleForTesting
+  public boolean isVerifyChecksum() {
+    return verifyChecksum;
+  }
+
+  private void refreshBlockInfo(IOException cause) throws IOException {
+    LOG.info("Attempting to update pipeline and block token for block {} from pipeline {}: {}",
+        blockID, pipelineRef.get().getId(), cause.getMessage());
+    if (refreshFunction != null) {
+      LOG.debug("Re-fetching pipeline and block token for block {}", blockID);
+      BlockLocationInfo blockLocationInfo = refreshFunction.apply(blockID);
+      if (blockLocationInfo == null) {
+        LOG.warn("No new block location info for block {}", blockID);
+      } else {
+        setPipeline(blockLocationInfo.getPipeline());
+        LOG.info("New pipeline for block {}: {}", blockID,
+            blockLocationInfo.getPipeline());
+
+        tokenRef.set(blockLocationInfo.getToken());

Review Comment:
   Yes, it will be checked in `ContainerProtocalCalls.readBlock()`. I think we don't need worry about it. 



##########
hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/DatanodeVersion.java:
##########
@@ -33,6 +33,8 @@ public enum DatanodeVersion implements ComponentVersion {
   SEPARATE_RATIS_PORTS_AVAILABLE(1, "Version with separated Ratis port."),
   COMBINED_PUTBLOCK_WRITECHUNK_RPC(2, "WriteChunk can optionally support " +
           "a PutBlock request"),
+  STEAM_BLOCK_SUPPORT(3,

Review Comment:
   done



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "chungen0126 (via GitHub)" <gi...@apache.org>.
chungen0126 commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1792383749


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/StreamBlockInput.java:
##########
@@ -0,0 +1,777 @@
+/*
+ * 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 com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
+import org.apache.commons.lang3.NotImplementedException;
+import org.apache.hadoop.fs.ByteBufferReadable;
+import org.apache.hadoop.fs.CanUnbuffer;
+import org.apache.hadoop.fs.Seekable;
+import org.apache.hadoop.hdds.client.BlockID;
+import org.apache.hadoop.hdds.client.StandaloneReplicationConfig;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadChunkResponseProto;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadBlockResponseProto;
+import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
+import org.apache.hadoop.hdds.scm.OzoneClientConfig;
+import org.apache.hadoop.hdds.scm.XceiverClientFactory;
+import org.apache.hadoop.hdds.scm.XceiverClientSpi;
+import org.apache.hadoop.hdds.scm.client.HddsClientUtils;
+import org.apache.hadoop.hdds.scm.container.common.helpers.StorageContainerException;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.hdds.security.exception.SCMSecurityException;
+import org.apache.hadoop.hdds.security.token.OzoneBlockTokenIdentifier;
+import org.apache.hadoop.io.retry.RetryPolicy;
+import org.apache.hadoop.ozone.common.Checksum;
+import org.apache.hadoop.ozone.common.ChecksumData;
+import org.apache.hadoop.ozone.common.OzoneChecksumException;
+import org.apache.hadoop.ozone.common.utils.BufferUtils;
+import org.apache.hadoop.security.token.Token;
+import org.apache.ratis.thirdparty.com.google.protobuf.ByteString;
+import org.apache.ratis.thirdparty.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.EOFException;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+
+import static org.apache.hadoop.hdds.client.ReplicationConfig.getLegacyFactor;
+
+/**
+ * An {@link java.io.InputStream} called from KeyInputStream to read a block from the
+ * container.
+ */
+public class StreamBlockInput extends BlockExtendedInputStream
+    implements Seekable, CanUnbuffer, ByteBufferReadable {
+  private static final Logger LOG =
+      LoggerFactory.getLogger(StreamBlockInput.class);
+  private final BlockID blockID;
+  private final long length;
+  private final AtomicReference<Pipeline> pipelineRef =
+      new AtomicReference<>();
+  private final AtomicReference<Token<OzoneBlockTokenIdentifier>> tokenRef =
+      new AtomicReference<>();
+  private XceiverClientFactory xceiverClientFactory;
+  private XceiverClientSpi xceiverClient;
+
+  private List<Long> bufferoffsets;
+  private int bufferIndex;
+  private long blockPosition = -1;
+  private List<ByteBuffer> buffers;
+  private boolean allocated = false;
+  private long bufferOffsetWrtBlockDataData;
+  private long buffersSize;
+  private static final int EOF = -1;
+  private final List<XceiverClientSpi.Validator> validators;
+  private final boolean verifyChecksum;
+  private final Function<BlockID, BlockLocationInfo> refreshFunction;
+  private final RetryPolicy retryPolicy;
+  private int retries;
+
+
+  public StreamBlockInput(
+      BlockID blockID, long length, Pipeline pipeline,
+      Token<OzoneBlockTokenIdentifier> token,
+      XceiverClientFactory xceiverClientFactory,
+      Function<BlockID, BlockLocationInfo> refreshFunction,
+      OzoneClientConfig config) throws IOException {
+    this.blockID = blockID;
+    LOG.debug("Initializing StreamBlockInput for block {}", blockID);
+    this.length = length;
+    setPipeline(pipeline);
+    tokenRef.set(token);
+    this.xceiverClientFactory = xceiverClientFactory;
+    this.validators = ContainerProtocolCalls.toValidatorList(
+        (request, response) -> validateBlock(response));
+    this.verifyChecksum = config.isChecksumVerify();
+    this.refreshFunction = refreshFunction;
+    this.retryPolicy =
+        HddsClientUtils.createRetryPolicy(config.getMaxReadRetryCount(),
+            TimeUnit.SECONDS.toMillis(config.getReadRetryInterval()));
+
+  }
+
+
+  public BlockID getBlockID() {
+    return blockID;
+  }
+
+  public long getLength() {
+    return length;
+  }
+
+  @Override
+  public synchronized long getPos() {
+    if (length == 0) {
+      return 0;
+    }
+    if (blockPosition >= 0) {
+      return blockPosition;
+    }
+
+    if (allocated && !buffersHaveData() && !dataRemainingInBlock()) {
+      Preconditions.checkState(
+          bufferOffsetWrtBlockDataData + buffersSize == length,
+          "EOF detected but not at the last byte of the chunk");
+      return length;
+    }
+    if (buffersHaveData()) {
+      // BufferOffset w.r.t to BlockData + BufferOffset w.r.t buffers +
+      // Position of current Buffer
+      return bufferOffsetWrtBlockDataData + bufferoffsets.get(bufferIndex) +
+          buffers.get(bufferIndex).position();
+    }
+    if (buffersAllocated()) {
+      return bufferOffsetWrtBlockDataData + buffersSize;
+    }
+    return 0;
+  }
+
+  @Override
+  public synchronized int read() throws IOException {
+    checkOpen();
+
+    int dataout = EOF;
+    int len = 1;
+    int available;
+    while (len > 0) {
+      try {
+        acquireClient();
+        available = prepareRead(1);
+        retries = 0;
+      } catch (SCMSecurityException ex) {
+        throw ex;
+      } catch (StorageContainerException e) {
+        if (shouldRetryRead(e)) {
+          releaseClient();
+          refreshBlockInfo(e);
+          continue;
+        } else {
+          throw e;
+        }
+      } catch (IOException ioe) {
+        if (shouldRetryRead(ioe)) {
+          if (isConnectivityIssue(ioe)) {
+            releaseClient();
+            refreshBlockInfo(ioe);
+          } else {
+            releaseClient();
+          }
+          continue;
+        } else {
+          throw ioe;
+        }
+      }
+      if (available == EOF) {
+        // There is no more data in the chunk stream. The buffers should have
+        // been released by now
+        Preconditions.checkState(buffers == null);
+      } else {
+        dataout = Byte.toUnsignedInt(buffers.get(bufferIndex).get());
+      }
+
+      len -= available;
+      if (bufferEOF()) {
+        releaseBuffers(bufferIndex);
+      }
+    }
+
+
+    return dataout;
+
+
+  }
+
+  @Override
+  public synchronized int read(byte[] b, int off, int len) throws IOException {
+    // According to the JavaDocs for InputStream, it is recommended that
+    // subclasses provide an override of bulk read if possible for performance
+    // reasons.  In addition to performance, we need to do it for correctness
+    // reasons.  The Ozone REST service uses PipedInputStream and
+    // PipedOutputStream to relay HTTP response data between a Jersey thread and
+    // a Netty thread.  It turns out that PipedInputStream/PipedOutputStream
+    // have a subtle dependency (bug?) on the wrapped stream providing separate
+    // implementations of single-byte read and bulk read.  Without this, get key
+    // responses might close the connection before writing all of the bytes
+    // advertised in the Content-Length.
+    if (b == null) {
+      throw new NullPointerException();
+    }
+    if (off < 0 || len < 0 || len > b.length - off) {
+      throw new IndexOutOfBoundsException();
+    }
+    if (len == 0) {
+      return 0;
+    }
+    int total = 0;
+    int available;
+    while (len > 0) {
+      try {
+        acquireClient();
+        available = prepareRead(len);
+        retries = 0;
+      } catch (SCMSecurityException ex) {
+        throw ex;
+      } catch (StorageContainerException e) {
+        if (shouldRetryRead(e)) {
+          releaseClient();
+          refreshBlockInfo(e);
+          continue;
+        } else {
+          throw e;
+        }
+      } catch (IOException ioe) {
+        if (shouldRetryRead(ioe)) {
+          if (isConnectivityIssue(ioe)) {
+            releaseClient();
+            refreshBlockInfo(ioe);
+          } else {
+            releaseClient();
+          }
+          continue;
+        } else {
+          throw ioe;
+        }
+      }
+      if (available == EOF) {
+        // There is no more data in the block stream. The buffers should have
+        // been released by now
+        Preconditions.checkState(buffers == null);
+        return total != 0 ? total : EOF;
+      }
+      buffers.get(bufferIndex).get(b, off + total, available);
+      len -= available;
+      total += available;
+
+      if (bufferEOF()) {
+        releaseBuffers(bufferIndex);
+      }
+    }
+    return total;
+
+  }
+
+  @Override
+  public synchronized void close() throws IOException {
+    releaseClient();
+    releaseBuffers();
+    xceiverClientFactory = null;
+  }
+
+  @Override
+  public synchronized int read(ByteBuffer byteBuffer) throws IOException {
+    if (byteBuffer == null) {
+      throw new NullPointerException();
+    }
+    int len = byteBuffer.remaining();
+    if (len == 0) {
+      return 0;
+    }
+    int total = 0;
+    int available;
+    while (len > 0) {
+      try {
+        acquireClient();
+        available = prepareRead(len);
+        retries = 0;
+      } catch (SCMSecurityException ex) {
+        throw ex;
+      } catch (StorageContainerException e) {
+        if (shouldRetryRead(e)) {
+          releaseClient();
+          refreshBlockInfo(e);
+          continue;
+        } else {
+          throw e;
+        }
+      } catch (IOException ioe) {
+        if (shouldRetryRead(ioe)) {
+          if (isConnectivityIssue(ioe)) {
+            releaseClient();
+            refreshBlockInfo(ioe);
+          } else {
+            releaseClient();
+          }
+          continue;
+        } else {
+          throw ioe;
+        }
+      }
+      if (available == EOF) {
+        // There is no more data in the block stream. The buffers should have
+        // been released by now
+        Preconditions.checkState(buffers == null);
+        return total != 0 ? total : EOF;
+      }
+      ByteBuffer readBuf = buffers.get(bufferIndex);
+      ByteBuffer tmpBuf = readBuf.duplicate();
+      tmpBuf.limit(tmpBuf.position() + available);
+      byteBuffer.put(tmpBuf);
+      readBuf.position(tmpBuf.position());
+
+      len -= available;
+      total += available;
+
+      if (bufferEOF()) {
+        releaseBuffers(bufferIndex);
+      }
+    }
+    return total;
+  }
+
+  @Override
+  protected int readWithStrategy(ByteReaderStrategy strategy) throws IOException {
+    throw new NotImplementedException("readWithStrategy is not implemented.");
+  }
+
+  @Override
+  public synchronized void seek(long pos) throws IOException {
+    if (pos < 0 || pos > length) {
+      if (pos == 0) {
+        // It is possible for length and pos to be zero in which case
+        // seek should return instead of throwing exception
+        return;
+      }
+      throw new EOFException("EOF encountered at pos: " + pos + " for block: " + blockID);
+    }
+
+    if (buffersHavePosition(pos)) {
+      // The bufferPosition is w.r.t the current block.
+      // Adjust the bufferIndex and position to the seeked position.
+      adjustBufferPosition(pos - bufferOffsetWrtBlockDataData);
+    } else {
+      blockPosition = pos;
+    }
+  }
+
+  @Override
+  public synchronized boolean seekToNewSource(long l) throws IOException {
+    return false;
+  }
+
+  @Override
+  public synchronized void unbuffer() {
+    blockPosition = getPos();
+    releaseClient();
+    releaseBuffers();
+  }
+
+  private void setPipeline(Pipeline pipeline) throws IOException {
+    if (pipeline == null) {
+      return;
+    }
+    long replicaIndexes = pipeline.getNodes().stream().mapToInt(pipeline::getReplicaIndex).distinct().count();
+
+    if (replicaIndexes > 1) {
+      throw new IOException(String.format("Pipeline: %s has nodes containing different replica indexes.",
+          pipeline));
+    }
+
+    // irrespective of the container state, we will always read via Standalone
+    // protocol.
+    boolean okForRead =
+        pipeline.getType() == HddsProtos.ReplicationType.STAND_ALONE
+            || pipeline.getType() == HddsProtos.ReplicationType.EC;
+    Pipeline readPipeline = okForRead ? pipeline : Pipeline.newBuilder(pipeline)
+        .setReplicationConfig(StandaloneReplicationConfig.getInstance(
+            getLegacyFactor(pipeline.getReplicationConfig())))
+        .build();
+    pipelineRef.set(readPipeline);
+  }
+
+  protected synchronized void checkOpen() throws IOException {
+    if (xceiverClientFactory == null) {
+      throw new IOException("BlockInputStream has been closed.");
+    }
+  }
+
+  protected synchronized void acquireClient() throws IOException {
+    if (xceiverClientFactory != null && xceiverClient == null) {
+      final Pipeline pipeline = pipelineRef.get();
+      try {
+        xceiverClient = xceiverClientFactory.acquireClientForReadData(pipeline);
+      } catch (IOException ioe) {
+        LOG.warn("Failed to acquire client for pipeline {}, block {}",
+            pipeline, blockID);
+        throw ioe;
+      }
+    }
+  }
+
+  private synchronized int prepareRead(int len) throws IOException {
+    for (;;) {
+      if (blockPosition >= 0) {
+        if (buffersHavePosition(blockPosition)) {
+          // The current buffers have the seeked position. Adjust the buffer
+          // index and position to point to the buffer position.
+          adjustBufferPosition(blockPosition - bufferOffsetWrtBlockDataData);
+        } else {
+          // Read a required block data to fill the buffers with seeked
+          // position data
+          readDataFromContainer(len);
+        }
+      }
+      if (buffersHaveData()) {
+        // Data is available from buffers
+        ByteBuffer bb = buffers.get(bufferIndex);
+        return Math.min(len, bb.remaining());
+      } else if (dataRemainingInBlock()) {
+        // There is more data in the block stream which has not
+        // been read into the buffers yet.
+        readDataFromContainer(len);
+      } else {
+        // All available input from this block stream has been consumed.
+        return EOF;
+      }
+    }
+
+
+  }
+
+  private boolean buffersHavePosition(long pos) {
+    // Check if buffers have been allocated
+    if (buffersAllocated()) {
+      // Check if the current buffers cover the input position
+      // Released buffers should not be considered when checking if position
+      // is available
+      return pos >= bufferOffsetWrtBlockDataData +
+          bufferoffsets.get(0) &&
+          pos < bufferOffsetWrtBlockDataData + buffersSize;
+    }
+    return false;
+  }
+
+  /**
+   * Check if the buffers have been allocated data and false otherwise.
+   */
+  @VisibleForTesting
+  protected boolean buffersAllocated() {
+    return buffers != null && !buffers.isEmpty();
+  }
+
+  /**
+   * Adjust the buffers position to account for seeked position and/ or checksum
+   * boundary reads.
+   * @param bufferPosition the position to which the buffers must be advanced
+   */
+  private void adjustBufferPosition(long bufferPosition) {
+    // The bufferPosition is w.r.t the current buffers.
+    // Adjust the bufferIndex and position to the seeked bufferPosition.
+    if (bufferIndex >= buffers.size()) {
+      bufferIndex = Collections.binarySearch(bufferoffsets, bufferPosition);
+    } else if (bufferPosition < bufferoffsets.get(bufferIndex)) {
+      bufferIndex = Collections.binarySearch(
+          bufferoffsets.subList(0, bufferIndex), bufferPosition);
+    } else if (bufferPosition >= bufferoffsets.get(bufferIndex) +
+        buffers.get(bufferIndex).capacity()) {
+      bufferIndex = Collections.binarySearch(bufferoffsets.subList(
+          bufferIndex + 1, buffers.size()), bufferPosition);
+    }
+    if (bufferIndex < 0) {
+      bufferIndex = -bufferIndex - 2;
+    }
+
+    buffers.get(bufferIndex).position(
+        (int) (bufferPosition - bufferoffsets.get(bufferIndex)));
+
+    // Reset buffers > bufferIndex to position 0. We do this to reset any
+    // previous reads/ seeks which might have updated any buffer position.
+    // For buffers < bufferIndex, we do not need to reset the position as it
+    // not required for this read. If a seek was done to a position in the
+    // previous indices, the buffer position reset would be performed in the
+    // seek call.
+    for (int i = bufferIndex + 1; i < buffers.size(); i++) {
+      buffers.get(i).position(0);
+    }
+
+    // Reset the blockPosition as chunk stream has been initialized i.e. the
+    // buffers have been allocated.
+    blockPosition = -1;
+  }
+
+  /**
+   * Reads full or partial Chunk from DN Container based on the current
+   * position of the ChunkInputStream, the number of bytes of data to read
+   * and the checksum boundaries.
+   * If successful, then the read data in saved in the buffers so that
+   * subsequent read calls can utilize it.
+   * @param len number of bytes of data to be read
+   * @throws IOException if there is an I/O error while performing the call
+   * to Datanode
+   */
+  private synchronized void readDataFromContainer(int len) throws IOException {
+    // index of first byte to be read from the block
+    long startByteIndex;
+    if (blockPosition >= 0) {
+      // If seek operation was called to advance the buffer position, the
+      // chunk should be read from that position onwards.
+      startByteIndex = blockPosition;
+    } else {
+      // Start reading the block from the last blockPosition onwards.
+      startByteIndex = bufferOffsetWrtBlockDataData + buffersSize;
+    }
+
+    // bufferOffsetWrtChunkData and buffersSize are updated after the data
+    // is read from Container and put into the buffers, but if read fails
+    // and is retried, we need the previous position.  Position is reset after
+    // successful read in adjustBufferPosition()
+    blockPosition = getPos();
+    bufferOffsetWrtBlockDataData = readData(startByteIndex, len);
+    long tempOffset = 0L;
+    buffersSize = 0L;
+    bufferoffsets = new ArrayList<>(buffers.size());
+    for (ByteBuffer buffer : buffers) {
+      bufferoffsets.add(tempOffset);
+      tempOffset += buffer.limit();
+      buffersSize += buffer.limit();
+
+    }
+    bufferIndex = 0;
+    allocated = true;
+    adjustBufferPosition(startByteIndex - bufferOffsetWrtBlockDataData);
+
+  }
+
+  @VisibleForTesting
+  protected long readData(long startByteIndex, long len)
+      throws IOException {
+    Pipeline pipeline = pipelineRef.get();
+    buffers = new ArrayList<>();
+    ReadBlockResponseProto response =
+        ContainerProtocolCalls.readBlock(xceiverClient, startByteIndex,
+        len, blockID, validators, tokenRef.get(), pipeline.getReplicaIndexes(), verifyChecksum);
+    List<ReadChunkResponseProto> readBlocks = response.getReadChunkList();
+
+    for (ReadChunkResponseProto readBlock : readBlocks) {
+      if (readBlock.hasDataBuffers()) {
+        buffers.addAll(BufferUtils.getReadOnlyByteBuffers(
+            readBlock.getDataBuffers().getBuffersList()));
+      } else {
+        throw new IOException("Unexpected error while reading chunk data " +
+            "from container. No data returned.");
+      }
+    }
+    return response.getReadChunk(0)
+        .getChunkData().getOffset();
+  }
+
+  /**
+   * Check if the buffers have any data remaining between the current
+   * position and the limit.
+   */
+  private boolean buffersHaveData() {
+    boolean hasData = false;
+    if (buffersAllocated()) {
+      int buffersLen = buffers.size();
+      while (bufferIndex < buffersLen) {
+        ByteBuffer buffer = buffers.get(bufferIndex);
+        if (buffer != null && buffer.hasRemaining()) {
+          // current buffer has data
+          hasData = true;
+          break;
+        } else {
+          if (bufferIndex < buffersLen - 1) {
+            // move to next available buffer
+            ++bufferIndex;
+            Preconditions.checkState(bufferIndex < buffers.size());
+          } else {
+            // no more buffers remaining
+            break;
+          }
+        }
+      }
+    }
+
+    return hasData;
+  }
+
+  /**
+   * Check if there is more data in the chunk which has not yet been read
+   * into the buffers.
+   */
+  private boolean dataRemainingInBlock() {
+    long bufferPos;
+    if (blockPosition >= 0) {
+      bufferPos = blockPosition;
+    } else {
+      bufferPos = bufferOffsetWrtBlockDataData + buffersSize;
+    }
+
+    return bufferPos < length;
+  }
+
+  /**
+   * Check if current buffer had been read till the end.
+   */
+  private boolean bufferEOF() {
+    return allocated && !buffers.get(bufferIndex).hasRemaining();

Review Comment:
   done



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "chungen0126 (via GitHub)" <gi...@apache.org>.
chungen0126 commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1792313617


##########
hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/keyvalue/KeyValueHandler.java:
##########
@@ -1329,6 +1333,126 @@ public void deleteUnreferenced(Container container, long localID)
     }
   }
 
+  @Override
+  public ContainerCommandResponseProto streamDataReadOnly(
+      ContainerCommandRequestProto request, KeyValueContainer kvContainer,
+      DispatcherContext dispatcherContext,
+      StreamObserver<ContainerCommandResponseProto> streamObserver) {
+    ContainerCommandResponseProto responseProto = null;
+    try {
+      if (!request.hasReadBlock()) {
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("Malformed Read Block request. trace ID: {}",
+              request.getTraceID());
+        }
+        return malformedRequest(request);
+      }
+      ReadBlockRequestProto readBlock = request.getReadBlock();
+      ChunkBuffer data;
+
+      BlockID blockID = BlockID.getFromProtobuf(
+          readBlock.getBlockID());
+      if (replicaIndexCheckRequired(request)) {
+        BlockUtils.verifyReplicaIdx(kvContainer, blockID);
+      }
+      BlockData blockData = blockManager.getBlock(kvContainer, blockID);
+      List<ContainerProtos.ChunkInfo> chunkInfos = blockData.getChunks();
+      long blockOffset = 0;
+      int chunkIndex = -1;
+      for (int i = 0; i < chunkInfos.size(); i++) {
+        blockOffset += chunkInfos.get(i).getLen();
+        if (blockOffset > readBlock.getOffset()) {
+          chunkIndex = i;
+          break;
+        }
+      }
+
+      BlockUtils.verifyBCSId(kvContainer, blockID);
+      if (dispatcherContext == null) {
+        dispatcherContext = DispatcherContext.getHandleReadBlock();
+      }
+
+      boolean isReadChunkV0 = readBlock.getVersion()
+          .equals(ContainerProtos.ReadChunkVersion.V0);
+
+      long offset = readBlock.getOffset();
+      long len =  readBlock.getLen();
+      long adjustedChunkOffset, adjustedChunkLen;
+      do {
+        int startIndex = -1;
+        ContainerProtos.ChunkInfo chunk = chunkInfos.get(chunkIndex);
+        if (readBlock.getVerifyChecksum()) {
+          Pair<Long, Long> adjustedOffsetAndLength =
+              computeChecksumBoundaries(chunk, offset, len);
+          adjustedChunkOffset = adjustedOffsetAndLength.getLeft();
+          adjustedChunkLen = adjustedOffsetAndLength.getRight();
+          startIndex = (int) adjustedChunkOffset /
+              chunk.getChecksumData().getBytesPerChecksum();
+          adjustedChunkOffset += chunk.getOffset();
+        } else {
+          adjustedChunkOffset = offset;
+          adjustedChunkLen = Math.min(
+              chunk.getLen() + chunk.getOffset() - offset, len);
+        }
+
+        ChunkInfo chunkInfo = ChunkInfo.getFromProtoBuf(
+            ContainerProtos.ChunkInfo.newBuilder(chunk)
+                .setOffset(adjustedChunkOffset)
+                .setLen(adjustedChunkLen).build());
+        // For older clients, set ReadDataIntoSingleBuffer to true so that
+        // all the data read from chunk file is returned as a single
+        // ByteString. Older clients cannot process data returned as a list
+        // of ByteStrings.
+        if (isReadChunkV0) {
+          chunkInfo.setReadDataIntoSingleBuffer(isReadChunkV0);
+        }
+        data = chunkManager.readChunk(
+            kvContainer, blockID, chunkInfo, dispatcherContext);
+
+        Preconditions.checkNotNull(data, "Chunk data is null");
+        if (DispatcherContext.op(dispatcherContext).readFromTmpFile()) {
+          validateChunkChecksumData(data, chunkInfo);
+          metrics.incBytesReadStateMachine(chunkInfo.getLen());
+          metrics.incNumReadStateMachine();
+        }
+        streamObserver.onNext(
+            getReadBlockResponse(request,
+                blockData.getProtoBufMessage().getBlockID(),
+                chunkInfo.getProtoBufMessage(), isReadChunkV0,
+                data, byteBufferToByteString, startIndex));
+        len -= adjustedChunkLen + adjustedChunkOffset - offset;
+        offset = adjustedChunkOffset + adjustedChunkLen;
+        chunkIndex++;

Review Comment:
   Add a nes test in `TestKeyValueHandler`. Do you think it is enough?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "ptlrs (via GitHub)" <gi...@apache.org>.
ptlrs commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-2558009586

   > Test conducted on our cluster(3DN / HDD / 10 Gigabit network) shows this improvement can boost read speed by at least 30%.
   
   > It can be seen that for 1GB file reading, streaming reading can reduce the reading time by about 30%.
   
   Hi @chungen0126 @guohao-rosicky, do we know how much of an improvement is being seen for files smaller than 1GB?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-3373086778

   > the request lengths and the response lengths look quite random.
   
   It may be due to the test which reads 1 byte and then some more bytes.
   
   After changed the test to reads 10MB, it failed with IllegalStateException.
   
   ```
   2025-10-06 10:49:36,161 [a38e63c4-83c0-4a67-ad0d-45b74141c76b-ChunkReader-4] ERROR server.GrpcXceiverService (GrpcXceiverService.java:onNext(120)) - Got exception when processing ContainerCommandRequestProto cmdType: ReadBlock
   traceID: ""
   containerID: 1
   datanodeUuid: "a0bb7c49-0425-40d6-8347-e5f39552daf7"
   version: 3
   readBlock {
     blockID {
       containerID: 1
       localID: 115816896921600001
       blockCommitSequenceId: 16
     }
     offset: 8388608
     len: 2097152
     verifyChecksum: true
   }
   
   java.lang.IllegalStateException
   	at com.google.common.base.Preconditions.checkState(Preconditions.java:497)
   	at org.apache.hadoop.ozone.container.keyvalue.KeyValueHandler.readBlock(KeyValueHandler.java:2072)
   	at org.apache.hadoop.ozone.container.common.impl.HddsDispatcher.streamDataReadOnly(HddsDispatcher.java:864)
   	at org.apache.hadoop.ozone.container.common.transport.server.GrpcXceiverService$1.onNext(GrpcXceiverService.java:114)
   	at org.apache.hadoop.ozone.container.common.transport.server.GrpcXceiverService$1.onNext(GrpcXceiverService.java:98)
   	at org.apache.ratis.thirdparty.io.grpc.stub.ServerCalls$StreamingServerCallHandler$StreamingServerCallListener.onMessage(ServerCalls.java:262)
   	at org.apache.ratis.thirdparty.io.grpc.ForwardingServerCallListener.onMessage(ForwardingServerCallListener.java:33)
   	at org.apache.hadoop.hdds.tracing.GrpcServerInterceptor$1.onMessage(GrpcServerInterceptor.java:49)
   ```
   
   The change of `TestStreamBlockInputStream`:
   ```diff
   @@ -73,7 +74,7 @@ void testAll(ContainerLayoutVersion layout) throws Exception {
       */
      private void testBlockReadBuffers(TestBucket bucket) throws Exception {
        String keyName = getNewKeyName();
   -    int dataLength = (2 * BLOCK_SIZE) + (CHUNK_SIZE);
   +    int dataLength = 10 << 20;
        byte[] inputData = bucket.writeRandomBytes(keyName, dataLength);
    
        try (KeyInputStream keyInputStream = bucket.getKeyInputStream(keyName)) {
   @@ -82,13 +83,8 @@ private void testBlockReadBuffers(TestBucket bucket) throws Exception {
              (StreamBlockInputStream) keyInputStream.getPartStreams().get(0);
    
    
   -      // To read 1 byte of chunk data, ChunkInputStream should get one full
   -      // checksum boundary worth of data from Container and store it in buffers.
   -      IOUtils.readFully(block0Stream, new byte[1]);
   -      checkBufferSizeAndCapacity(block0Stream.getCachedBuffers());
   -
          // Read > checksum boundary of data from chunk0
   -      int readDataLen = BYTES_PER_CHECKSUM + (BYTES_PER_CHECKSUM / 2);
   +      int readDataLen = dataLength;
          byte[] readData = readDataFromBlock(block0Stream, 0, readDataLen);
          bucket.validateData(inputData, 0, readData);
   ```


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "SaketaChalamchala (via GitHub)" <gi...@apache.org>.
SaketaChalamchala commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-2214622575

   @szetszwo could you please take a look?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "swamirishi (via GitHub)" <gi...@apache.org>.
swamirishi commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1803842565


##########
hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/keyvalue/KeyValueHandler.java:
##########
@@ -1329,6 +1333,109 @@ public void deleteUnreferenced(Container container, long localID)
     }
   }
 
+  @Override
+  public ContainerCommandResponseProto streamDataReadOnly(
+      ContainerCommandRequestProto request, KeyValueContainer kvContainer,
+      DispatcherContext dispatcherContext,
+      StreamObserver<ContainerCommandResponseProto> streamObserver) {
+    ContainerCommandResponseProto responseProto = null;
+    try {
+      if (!request.hasReadBlock()) {
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("Malformed Read Block request. trace ID: {}",
+              request.getTraceID());
+        }
+        return malformedRequest(request);
+      }
+      ReadBlockRequestProto readBlock = request.getReadBlock();
+
+      BlockID blockID = BlockID.getFromProtobuf(
+          readBlock.getBlockID());
+      // This is a new api the block should always be checked.
+      BlockUtils.verifyReplicaIdx(kvContainer, blockID);

Review Comment:
   or we would need to validate the replicaIndex and bcsID is the same on every readChunk call on the file.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "chungen0126 (via GitHub)" <gi...@apache.org>.
chungen0126 commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1792381652


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/StreamBlockInput.java:
##########
@@ -0,0 +1,777 @@
+/*
+ * 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 com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
+import org.apache.commons.lang3.NotImplementedException;
+import org.apache.hadoop.fs.ByteBufferReadable;
+import org.apache.hadoop.fs.CanUnbuffer;
+import org.apache.hadoop.fs.Seekable;
+import org.apache.hadoop.hdds.client.BlockID;
+import org.apache.hadoop.hdds.client.StandaloneReplicationConfig;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadChunkResponseProto;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadBlockResponseProto;
+import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
+import org.apache.hadoop.hdds.scm.OzoneClientConfig;
+import org.apache.hadoop.hdds.scm.XceiverClientFactory;
+import org.apache.hadoop.hdds.scm.XceiverClientSpi;
+import org.apache.hadoop.hdds.scm.client.HddsClientUtils;
+import org.apache.hadoop.hdds.scm.container.common.helpers.StorageContainerException;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.hdds.security.exception.SCMSecurityException;
+import org.apache.hadoop.hdds.security.token.OzoneBlockTokenIdentifier;
+import org.apache.hadoop.io.retry.RetryPolicy;
+import org.apache.hadoop.ozone.common.Checksum;
+import org.apache.hadoop.ozone.common.ChecksumData;
+import org.apache.hadoop.ozone.common.OzoneChecksumException;
+import org.apache.hadoop.ozone.common.utils.BufferUtils;
+import org.apache.hadoop.security.token.Token;
+import org.apache.ratis.thirdparty.com.google.protobuf.ByteString;
+import org.apache.ratis.thirdparty.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.EOFException;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+
+import static org.apache.hadoop.hdds.client.ReplicationConfig.getLegacyFactor;
+
+/**
+ * An {@link java.io.InputStream} called from KeyInputStream to read a block from the
+ * container.
+ */
+public class StreamBlockInput extends BlockExtendedInputStream
+    implements Seekable, CanUnbuffer, ByteBufferReadable {
+  private static final Logger LOG =
+      LoggerFactory.getLogger(StreamBlockInput.class);
+  private final BlockID blockID;
+  private final long length;
+  private final AtomicReference<Pipeline> pipelineRef =
+      new AtomicReference<>();
+  private final AtomicReference<Token<OzoneBlockTokenIdentifier>> tokenRef =
+      new AtomicReference<>();
+  private XceiverClientFactory xceiverClientFactory;
+  private XceiverClientSpi xceiverClient;
+
+  private List<Long> bufferoffsets;
+  private int bufferIndex;
+  private long blockPosition = -1;
+  private List<ByteBuffer> buffers;
+  private boolean allocated = false;
+  private long bufferOffsetWrtBlockDataData;
+  private long buffersSize;
+  private static final int EOF = -1;
+  private final List<XceiverClientSpi.Validator> validators;
+  private final boolean verifyChecksum;
+  private final Function<BlockID, BlockLocationInfo> refreshFunction;
+  private final RetryPolicy retryPolicy;
+  private int retries;
+
+
+  public StreamBlockInput(
+      BlockID blockID, long length, Pipeline pipeline,
+      Token<OzoneBlockTokenIdentifier> token,
+      XceiverClientFactory xceiverClientFactory,
+      Function<BlockID, BlockLocationInfo> refreshFunction,
+      OzoneClientConfig config) throws IOException {
+    this.blockID = blockID;
+    LOG.debug("Initializing StreamBlockInput for block {}", blockID);
+    this.length = length;
+    setPipeline(pipeline);
+    tokenRef.set(token);
+    this.xceiverClientFactory = xceiverClientFactory;
+    this.validators = ContainerProtocolCalls.toValidatorList(
+        (request, response) -> validateBlock(response));
+    this.verifyChecksum = config.isChecksumVerify();
+    this.refreshFunction = refreshFunction;
+    this.retryPolicy =
+        HddsClientUtils.createRetryPolicy(config.getMaxReadRetryCount(),
+            TimeUnit.SECONDS.toMillis(config.getReadRetryInterval()));
+
+  }
+
+
+  public BlockID getBlockID() {
+    return blockID;
+  }
+
+  public long getLength() {
+    return length;
+  }
+
+  @Override
+  public synchronized long getPos() {
+    if (length == 0) {
+      return 0;
+    }
+    if (blockPosition >= 0) {
+      return blockPosition;
+    }
+
+    if (allocated && !buffersHaveData() && !dataRemainingInBlock()) {
+      Preconditions.checkState(
+          bufferOffsetWrtBlockDataData + buffersSize == length,
+          "EOF detected but not at the last byte of the chunk");
+      return length;
+    }
+    if (buffersHaveData()) {
+      // BufferOffset w.r.t to BlockData + BufferOffset w.r.t buffers +
+      // Position of current Buffer
+      return bufferOffsetWrtBlockDataData + bufferoffsets.get(bufferIndex) +
+          buffers.get(bufferIndex).position();
+    }
+    if (buffersAllocated()) {
+      return bufferOffsetWrtBlockDataData + buffersSize;
+    }
+    return 0;
+  }
+
+  @Override
+  public synchronized int read() throws IOException {
+    checkOpen();
+
+    int dataout = EOF;
+    int len = 1;
+    int available;
+    while (len > 0) {
+      try {
+        acquireClient();
+        available = prepareRead(1);
+        retries = 0;
+      } catch (SCMSecurityException ex) {
+        throw ex;
+      } catch (StorageContainerException e) {
+        if (shouldRetryRead(e)) {
+          releaseClient();
+          refreshBlockInfo(e);
+          continue;
+        } else {
+          throw e;
+        }
+      } catch (IOException ioe) {
+        if (shouldRetryRead(ioe)) {
+          if (isConnectivityIssue(ioe)) {
+            releaseClient();
+            refreshBlockInfo(ioe);
+          } else {
+            releaseClient();
+          }
+          continue;
+        } else {
+          throw ioe;
+        }
+      }
+      if (available == EOF) {
+        // There is no more data in the chunk stream. The buffers should have
+        // been released by now
+        Preconditions.checkState(buffers == null);
+      } else {
+        dataout = Byte.toUnsignedInt(buffers.get(bufferIndex).get());
+      }
+
+      len -= available;
+      if (bufferEOF()) {
+        releaseBuffers(bufferIndex);
+      }
+    }
+
+
+    return dataout;
+
+
+  }
+
+  @Override
+  public synchronized int read(byte[] b, int off, int len) throws IOException {
+    // According to the JavaDocs for InputStream, it is recommended that
+    // subclasses provide an override of bulk read if possible for performance
+    // reasons.  In addition to performance, we need to do it for correctness
+    // reasons.  The Ozone REST service uses PipedInputStream and
+    // PipedOutputStream to relay HTTP response data between a Jersey thread and
+    // a Netty thread.  It turns out that PipedInputStream/PipedOutputStream
+    // have a subtle dependency (bug?) on the wrapped stream providing separate
+    // implementations of single-byte read and bulk read.  Without this, get key
+    // responses might close the connection before writing all of the bytes
+    // advertised in the Content-Length.
+    if (b == null) {
+      throw new NullPointerException();
+    }
+    if (off < 0 || len < 0 || len > b.length - off) {
+      throw new IndexOutOfBoundsException();
+    }
+    if (len == 0) {
+      return 0;
+    }
+    int total = 0;
+    int available;
+    while (len > 0) {
+      try {
+        acquireClient();
+        available = prepareRead(len);
+        retries = 0;
+      } catch (SCMSecurityException ex) {
+        throw ex;
+      } catch (StorageContainerException e) {
+        if (shouldRetryRead(e)) {
+          releaseClient();
+          refreshBlockInfo(e);
+          continue;
+        } else {
+          throw e;
+        }
+      } catch (IOException ioe) {
+        if (shouldRetryRead(ioe)) {
+          if (isConnectivityIssue(ioe)) {
+            releaseClient();
+            refreshBlockInfo(ioe);
+          } else {
+            releaseClient();
+          }
+          continue;
+        } else {
+          throw ioe;
+        }
+      }
+      if (available == EOF) {
+        // There is no more data in the block stream. The buffers should have
+        // been released by now
+        Preconditions.checkState(buffers == null);
+        return total != 0 ? total : EOF;
+      }
+      buffers.get(bufferIndex).get(b, off + total, available);
+      len -= available;
+      total += available;
+
+      if (bufferEOF()) {
+        releaseBuffers(bufferIndex);
+      }
+    }
+    return total;
+
+  }
+
+  @Override
+  public synchronized void close() throws IOException {
+    releaseClient();
+    releaseBuffers();
+    xceiverClientFactory = null;
+  }
+
+  @Override
+  public synchronized int read(ByteBuffer byteBuffer) throws IOException {

Review Comment:
   done



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "chungen0126 (via GitHub)" <gi...@apache.org>.
chungen0126 commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1792380520


##########
hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/keyvalue/KeyValueHandler.java:
##########
@@ -1329,6 +1333,113 @@ public void deleteUnreferenced(Container container, long localID)
     }
   }
 
+  @Override
+  public ContainerCommandResponseProto streamDataReadOnly(
+      ContainerCommandRequestProto request, KeyValueContainer kvContainer,
+      DispatcherContext dispatcherContext,
+      StreamObserver<ContainerCommandResponseProto> streamObserver) {
+    ContainerCommandResponseProto responseProto = null;
+    try {
+      if (!request.hasReadBlock()) {
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("Malformed Read Block request. trace ID: {}",
+              request.getTraceID());
+        }
+        return malformedRequest(request);
+      }
+      ReadBlockRequestProto readBlock = request.getReadBlock();
+      ChunkBuffer data;
+
+      BlockID blockID = BlockID.getFromProtobuf(
+          readBlock.getBlockID());
+      // This is a new api the block should always be checked.
+      BlockUtils.verifyReplicaIdx(kvContainer, blockID);
+
+      BlockData blockData = blockManager.getBlock(kvContainer, blockID);
+      List<ContainerProtos.ChunkInfo> chunkInfos = blockData.getChunks();

Review Comment:
   Add a check to avoit it.
   `Preconditions.checkState(chunkIndex >= 0);`



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "ChenSammi (via GitHub)" <gi...@apache.org>.
ChenSammi commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1866999794


##########
hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/scm/storage/ContainerProtocolCalls.java:
##########
@@ -874,4 +876,57 @@ public static List<Validator> toValidatorList(Validator validator) {
     return datanodeToResponseMap;
   }
 
+  /**
+   * Calls the container protocol to read a chunk.
+   *
+   * @param xceiverClient  client to perform call
+   * @param blockID        ID of the block
+   * @param validators     functions to validate the response
+   * @param token          a token for this block (may be null)
+   * @return container protocol read chunk response
+   * @throws IOException if there is an I/O error while performing the call
+   */
+  @SuppressWarnings("checkstyle:ParameterNumber")
+  public static ContainerProtos.ReadBlockResponseProto readBlock(
+      XceiverClientSpi xceiverClient, long offset, long len, BlockID blockID,
+      List<Validator> validators, Token<? extends TokenIdentifier> token,
+      Map<DatanodeDetails, Integer> replicaIndexes, boolean verifyChecksum) throws IOException {
+    final ReadBlockRequestProto.Builder readBlockRequest =
+        ReadBlockRequestProto.newBuilder()
+            .setOffset(offset)
+            .setVerifyChecksum(verifyChecksum)
+            .setLen(len);
+    final ContainerCommandRequestProto.Builder builder =
+        ContainerCommandRequestProto.newBuilder().setCmdType(Type.ReadBlock)
+            .setContainerID(blockID.getContainerID());
+    if (token != null) {
+      builder.setEncodedToken(token.encodeToUrlString());
+    }
+
+

Review Comment:
   Please remove the extra blank line here, and other unnecessary blank lines within the patch. 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "ChenSammi (via GitHub)" <gi...@apache.org>.
ChenSammi commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1879606608


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/StreamBlockInputStream.java:
##########
@@ -0,0 +1,751 @@
+/*
+ * 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 com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
+import org.apache.commons.lang3.NotImplementedException;
+import org.apache.hadoop.fs.ByteBufferReadable;
+import org.apache.hadoop.fs.CanUnbuffer;
+import org.apache.hadoop.fs.Seekable;
+import org.apache.hadoop.hdds.client.BlockID;
+import org.apache.hadoop.hdds.client.StandaloneReplicationConfig;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadChunkResponseProto;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadBlockResponseProto;
+import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
+import org.apache.hadoop.hdds.scm.OzoneClientConfig;
+import org.apache.hadoop.hdds.scm.XceiverClientFactory;
+import org.apache.hadoop.hdds.scm.XceiverClientSpi;
+import org.apache.hadoop.hdds.scm.client.HddsClientUtils;
+import org.apache.hadoop.hdds.scm.container.common.helpers.StorageContainerException;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.hdds.security.exception.SCMSecurityException;
+import org.apache.hadoop.hdds.security.token.OzoneBlockTokenIdentifier;
+import org.apache.hadoop.io.retry.RetryPolicy;
+import org.apache.hadoop.ozone.common.Checksum;
+import org.apache.hadoop.ozone.common.ChecksumData;
+import org.apache.hadoop.ozone.common.OzoneChecksumException;
+import org.apache.hadoop.ozone.common.utils.BufferUtils;
+import org.apache.hadoop.security.token.Token;
+import org.apache.ratis.thirdparty.com.google.protobuf.ByteString;
+import org.apache.ratis.thirdparty.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.EOFException;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+
+import static org.apache.hadoop.hdds.client.ReplicationConfig.getLegacyFactor;
+
+/**
+ * An {@link java.io.InputStream} called from KeyInputStream to read a block from the
+ * container.
+ */
+public class StreamBlockInputStream extends BlockExtendedInputStream
+    implements Seekable, CanUnbuffer, ByteBufferReadable {
+  private static final Logger LOG =
+      LoggerFactory.getLogger(StreamBlockInputStream.class);
+  private final BlockID blockID;
+  private final long blockLength;
+  private final AtomicReference<Pipeline> pipelineRef =
+      new AtomicReference<>();
+  private final AtomicReference<Token<OzoneBlockTokenIdentifier>> tokenRef =
+      new AtomicReference<>();
+  private XceiverClientFactory xceiverClientFactory;
+  private XceiverClientSpi xceiverClient;
+
+  private List<Long> bufferOffsets;
+  private int bufferIndex;
+  private long blockPosition = -1;
+  private List<ByteBuffer> buffers;
+  // Checks if the StreamBlockInputStream has already read data from the container.
+  private boolean allocated = false;
+  private long bufferOffsetWrtBlockData;
+  private long buffersSize;
+  private static final int EOF = -1;
+  private final List<XceiverClientSpi.Validator> validators;
+  private final boolean verifyChecksum;
+  private final Function<BlockID, BlockLocationInfo> refreshFunction;
+  private final RetryPolicy retryPolicy;
+  private int retries;
+
+
+  public StreamBlockInputStream(
+      BlockID blockID, long length, Pipeline pipeline,
+      Token<OzoneBlockTokenIdentifier> token,
+      XceiverClientFactory xceiverClientFactory,
+      Function<BlockID, BlockLocationInfo> refreshFunction,
+      OzoneClientConfig config) throws IOException {
+    this.blockID = blockID;
+    LOG.debug("Initializing StreamBlockInputStream for block {}", blockID);
+    this.blockLength = length;
+    setPipeline(pipeline);
+    tokenRef.set(token);
+    this.xceiverClientFactory = xceiverClientFactory;
+    this.validators = ContainerProtocolCalls.toValidatorList(
+        (request, response) -> validateBlock(response));
+    this.verifyChecksum = config.isChecksumVerify();
+    this.refreshFunction = refreshFunction;
+    this.retryPolicy =
+        HddsClientUtils.createRetryPolicy(config.getMaxReadRetryCount(),
+            TimeUnit.SECONDS.toMillis(config.getReadRetryInterval()));
+
+  }
+
+
+  public BlockID getBlockID() {
+    return blockID;
+  }
+
+  public long getLength() {
+    return blockLength;
+  }
+
+  @Override
+  public synchronized long getPos() {
+    if (blockLength == 0) {
+      return 0;
+    }
+    if (blockPosition >= 0) {
+      return blockPosition;
+    }
+
+    if (buffersHaveData()) {
+      // BufferOffset w.r.t to BlockData + BufferOffset w.r.t buffers +
+      // Position of current Buffer
+      return bufferOffsetWrtBlockData + bufferOffsets.get(bufferIndex) +
+          buffers.get(bufferIndex).position();
+    }
+    if (allocated && !dataRemainingInBlock()) {
+      Preconditions.checkState(
+          bufferOffsetWrtBlockData + buffersSize == blockLength,
+          "EOF detected but not at the last byte of the chunk");
+      return blockLength;
+    }
+    if (buffersAllocated()) {
+      return bufferOffsetWrtBlockData + buffersSize;
+    }
+    return 0;
+  }
+
+  @Override
+  public synchronized int read() throws IOException {
+    int dataout = EOF;
+    int len = 1;
+    int available;
+    while (len > 0) {
+      try {
+        acquireClient();
+        available = prepareRead(1);
+        retries = 0;
+      } catch (SCMSecurityException ex) {
+        throw ex;
+      } catch (StorageContainerException e) {
+        handleStorageContainerException(e);
+        continue;
+      } catch (IOException ioe) {
+        handleIOException(ioe);
+        continue;
+      }
+      if (available == EOF) {
+        // There is no more data in the chunk stream. The buffers should have
+        // been released by now
+        Preconditions.checkState(buffers == null);
+      } else {
+        dataout = Byte.toUnsignedInt(buffers.get(bufferIndex).get());
+      }
+
+      len -= available;
+      if (bufferEOF()) {
+        releaseBuffers(bufferIndex);
+      }
+    }
+
+
+    return dataout;
+
+
+  }
+
+  @Override
+  public synchronized int read(byte[] b, int off, int len) throws IOException {
+    // According to the JavaDocs for InputStream, it is recommended that
+    // subclasses provide an override of bulk read if possible for performance
+    // reasons.  In addition to performance, we need to do it for correctness
+    // reasons.  The Ozone REST service uses PipedInputStream and
+    // PipedOutputStream to relay HTTP response data between a Jersey thread and
+    // a Netty thread.  It turns out that PipedInputStream/PipedOutputStream
+    // have a subtle dependency (bug?) on the wrapped stream providing separate
+    // implementations of single-byte read and bulk read.  Without this, get key
+    // responses might close the connection before writing all of the bytes
+    // advertised in the Content-Length.
+    if (b == null) {
+      throw new NullPointerException();
+    }
+    if (off < 0 || len < 0 || len > b.length - off) {
+      throw new IndexOutOfBoundsException();
+    }
+    if (len == 0) {
+      return 0;
+    }
+    int total = 0;
+    int available;
+    while (len > 0) {
+      try {
+        acquireClient();
+        available = prepareRead(len);
+        retries = 0;
+      } catch (SCMSecurityException ex) {
+        throw ex;
+      } catch (StorageContainerException e) {
+        handleStorageContainerException(e);
+        continue;
+      } catch (IOException ioe) {
+        handleIOException(ioe);
+        continue;
+      }
+      if (available == EOF) {
+        // There is no more data in the block stream. The buffers should have
+        // been released by now
+        Preconditions.checkState(buffers == null);
+        return total != 0 ? total : EOF;
+      }
+      buffers.get(bufferIndex).get(b, off + total, available);
+      len -= available;
+      total += available;
+
+      if (bufferEOF()) {
+        releaseBuffers(bufferIndex);
+      }
+    }
+    return total;
+
+  }
+
+  @Override
+  public synchronized int read(ByteBuffer byteBuffer) throws IOException {
+    if (byteBuffer == null) {
+      throw new NullPointerException();
+    }
+    int len = byteBuffer.remaining();
+    if (len == 0) {
+      return 0;
+    }
+    int total = 0;
+    int available;
+    while (len > 0) {
+      try {
+        acquireClient();
+        available = prepareRead(len);
+        retries = 0;
+      } catch (SCMSecurityException ex) {
+        throw ex;
+      } catch (StorageContainerException e) {
+        handleStorageContainerException(e);
+        continue;
+      } catch (IOException ioe) {
+        handleIOException(ioe);
+        continue;
+      }
+      if (available == EOF) {
+        // There is no more data in the block stream. The buffers should have
+        // been released by now
+        Preconditions.checkState(buffers == null);
+        return total != 0 ? total : EOF;
+      }
+      ByteBuffer readBuf = buffers.get(bufferIndex);
+      ByteBuffer tmpBuf = readBuf.duplicate();
+      tmpBuf.limit(tmpBuf.position() + available);
+      byteBuffer.put(tmpBuf);
+      readBuf.position(tmpBuf.position());
+
+      len -= available;
+      total += available;
+
+      if (bufferEOF()) {
+        releaseBuffers(bufferIndex);
+      }
+    }
+    return total;
+  }
+
+  @Override
+  protected int readWithStrategy(ByteReaderStrategy strategy) throws IOException {
+    throw new NotImplementedException("readWithStrategy is not implemented.");
+  }
+
+  @Override
+  public synchronized void seek(long pos) throws IOException {
+    if (pos == 0 && blockLength == 0) {
+      // It is possible for length and pos to be zero in which case
+      // seek should return instead of throwing exception
+      return;
+    }
+    if (pos < 0 || pos > blockLength) {
+      throw new EOFException("EOF encountered at pos: " + pos + " for block: " + blockID);
+    }
+
+    if (buffersHavePosition(pos)) {
+      // The bufferPosition is w.r.t the current block.
+      // Adjust the bufferIndex and position to the seeked position.
+      adjustBufferPosition(pos - bufferOffsetWrtBlockData);
+    } else {
+      blockPosition = pos;
+    }
+  }
+
+  @Override
+  public synchronized boolean seekToNewSource(long l) throws IOException {
+    return false;
+  }
+
+  @Override
+  public synchronized void unbuffer() {
+    blockPosition = getPos();
+    releaseClient();
+    releaseBuffers();
+  }
+
+  private void setPipeline(Pipeline pipeline) throws IOException {
+    if (pipeline == null) {
+      return;
+    }
+    long replicaIndexes = pipeline.getNodes().stream().mapToInt(pipeline::getReplicaIndex).distinct().count();
+
+    if (replicaIndexes > 1) {
+      throw new IOException(String.format("Pipeline: %s has nodes containing different replica indexes.",
+          pipeline));
+    }
+
+    // irrespective of the container state, we will always read via Standalone
+    // protocol.
+    boolean okForRead =
+        pipeline.getType() == HddsProtos.ReplicationType.STAND_ALONE
+            || pipeline.getType() == HddsProtos.ReplicationType.EC;
+    Pipeline readPipeline = okForRead ? pipeline : Pipeline.newBuilder(pipeline)
+        .setReplicationConfig(StandaloneReplicationConfig.getInstance(
+            getLegacyFactor(pipeline.getReplicationConfig())))
+        .build();
+    pipelineRef.set(readPipeline);
+  }
+
+  protected synchronized void checkOpen() throws IOException {
+    if (xceiverClientFactory == null) {
+      throw new IOException("BlockInputStream has been closed.");

Review Comment:
   BlockInputStream -> StreamBlockInputStream



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-3452767811

   > Suggested approach: Non-blocking API (gRPC) + Non-blocking threads
   
   More details:
   
   An application opens an input stream and calls read(L) (blocking call), where L is the requested data length:
   - Ozone client checks the buffer queue if it already has the data.
   - If not, send an onNext(L) request to a datanode.
   - Pull data from the buffer queue until L bytes and then return to the application
   
   When a datanode receives onNext(L)
   - Open the file if it is the first call.
   - Read the file at least L bytes of data.
   - It could read up to checksum/chunk boundary, or even a few chunks more for pre-read. 
   - Return the data by one or more onNext() responses.
   
   When Ozone client receive onNext() responses
   - Put the data in the buffer queue.
   
   When the application closes the input stream:
   - The Ozone client sends an onComplete() to the datanode.
   - When the datanode receives onComplete(), close the file.
   
   When the datanode hits EOF of the block file:
   - The datanode closes the file and sends onComplete() to the Ozone client.
   - Ozone client closes the gRPC stream and continue with the next block.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "yandrey321 (via GitHub)" <gi...@apache.org>.
yandrey321 commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r2505710612


##########
hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/keyvalue/KeyValueHandler.java:
##########
@@ -2046,6 +2055,86 @@ public void deleteUnreferenced(Container container, long localID)
     }
   }
 
+  @Override
+  public ContainerCommandResponseProto readBlock(
+      ContainerCommandRequestProto request, Container kvContainer,
+      DispatcherContext dispatcherContext,
+      StreamObserver<ContainerCommandResponseProto> streamObserver) {
+
+    if (kvContainer.getContainerData().getLayoutVersion() != FILE_PER_BLOCK) {
+      return ContainerUtils.logAndReturnError(LOG,
+          new StorageContainerException("Only File Per Block is supported", IO_EXCEPTION), request);
+    }
+
+    ContainerCommandResponseProto responseProto = null;
+    if (!request.hasReadBlock()) {
+      if (LOG.isDebugEnabled()) {
+        LOG.debug("Malformed Read Block request. trace ID: {}", request.getTraceID());
+      }
+      return malformedRequest(request);
+    }
+    try {
+      ReadBlockRequestProto readBlock = request.getReadBlock();
+
+      BlockID blockID = BlockID.getFromProtobuf(readBlock.getBlockID());
+      // This is a new api the block should always be checked.
+      BlockUtils.verifyReplicaIdx(kvContainer, blockID);
+      BlockUtils.verifyBCSId(kvContainer, blockID);
+
+      File blockFile = FILE_PER_BLOCK.getChunkFile(kvContainer.getContainerData(), blockID, "unused");
+
+      BlockData blockData = getBlockManager().getBlock(kvContainer, blockID);
+      List<ContainerProtos.ChunkInfo> chunkInfos = blockData.getChunks();
+      // To get the chunksize, check the first chunk. Either there is only 1 chunk and its the largest, or there are
+      // multiple chunks and they are all the same size except the last one.
+      long bytesPerChunk = chunkInfos.get(0).getLen();
+      // The bytes per checksum is stored in the checksum data of each chunk, so check the first chunk as they all
+      // must be the same.
+      ContainerProtos.ChecksumType checksumType = chunkInfos.get(0).getChecksumData().getType();
+      ChecksumData checksumData = null;
+      int bytesPerChecksum = STREAMING_BYTES_PER_CHUNK;
+      if (checksumType == ContainerProtos.ChecksumType.NONE) {
+        checksumData = new ChecksumData(checksumType, 0);
+      } else {
+        bytesPerChecksum = chunkInfos.get(0).getChecksumData().getBytesPerChecksum();
+      }
+      // We have to align the read to checksum boundaries, so whatever offset is requested, we have to move back to the
+      // previous checksum boundary.
+      // eg if bytesPerChecksum is 512, and the requested offset is 600, we have to move back to 512.
+      // If the checksum type is NONE, we don't have to do this, but using no checksums should be rare in practice and
+      // it simplifies the code to always do this.
+      long adjustedOffset = readBlock.getOffset() - readBlock.getOffset() % bytesPerChecksum;
+      try (RandomAccessFile file = new RandomAccessFile(blockFile, "r");
+           FileChannel channel = file.getChannel()) {
+        ByteBuffer buffer = ByteBuffer.allocate(bytesPerChecksum);
+        channel.position(adjustedOffset);
+        while (channel.read(buffer) != -1) {
+          buffer.flip();
+          if (checksumType != ContainerProtos.ChecksumType.NONE) {
+            // As the checksums are stored "chunk by chunk", we need to figure out which chunk we start reading from,
+            // and its offset to pull out the correct checksum bytes for each read.
+            int chunkIndex = (int) (adjustedOffset / bytesPerChunk);
+            int chunkOffset = (int) (adjustedOffset % bytesPerChunk);
+            int checksumIndex = chunkOffset / bytesPerChecksum;
+            ByteString checksum = blockData.getChunks().get(chunkIndex).getChecksumData().getChecksums(checksumIndex);
+            checksumData = new ChecksumData(checksumType, bytesPerChecksum, Collections.singletonList(checksum));
+          }
+          streamObserver.onNext(getReadBlockResponse(request, checksumData, buffer, adjustedOffset));

Review Comment:
   here we need to check if streamObserver.isReady(), and if its not ready we should use [setOnReadyHandler](https://grpc.github.io/grpc-java/javadoc/io/grpc/stub/ServerCallStreamObserver.html#setOnReadyHandler(java.lang.Runnable))​([Runnable](https://docs.oracle.com/javase/8/docs/api/java/lang/Runnable.html?is-external=true) onReadyHandler) for transferring the remaining data.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "yandrey321 (via GitHub)" <gi...@apache.org>.
yandrey321 commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r2492281859


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/StreamBlockInputStream.java:
##########
@@ -0,0 +1,443 @@
+/*
+ * 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 java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+import org.apache.commons.lang3.NotImplementedException;
+import org.apache.hadoop.fs.ByteBufferReadable;
+import org.apache.hadoop.fs.CanUnbuffer;
+import org.apache.hadoop.fs.FSExceptionMessages;
+import org.apache.hadoop.fs.Seekable;
+import org.apache.hadoop.hdds.client.BlockID;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadBlockResponseProto;
+import org.apache.hadoop.hdds.scm.OzoneClientConfig;
+import org.apache.hadoop.hdds.scm.StreamingReadResponse;
+import org.apache.hadoop.hdds.scm.StreamingReaderSpi;
+import org.apache.hadoop.hdds.scm.XceiverClientFactory;
+import org.apache.hadoop.hdds.scm.XceiverClientSpi;
+import org.apache.hadoop.hdds.scm.container.common.helpers.StorageContainerException;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.hdds.security.token.OzoneBlockTokenIdentifier;
+import org.apache.hadoop.io.retry.RetryPolicy;
+import org.apache.hadoop.ozone.common.Checksum;
+import org.apache.hadoop.ozone.common.ChecksumData;
+import org.apache.hadoop.ozone.common.OzoneChecksumException;
+import org.apache.hadoop.security.token.Token;
+import org.apache.ratis.thirdparty.io.grpc.StatusRuntimeException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * An {@link java.io.InputStream} called from KeyInputStream to read a block from the
+ * container.
+ */
+public class StreamBlockInputStream extends BlockExtendedInputStream
+    implements Seekable, CanUnbuffer, ByteBufferReadable {
+  private static final Logger LOG = LoggerFactory.getLogger(StreamBlockInputStream.class);
+  private static final int EOF = -1;
+  private static final Throwable CANCELLED_EXCEPTION = new Throwable("Cancelled by client");
+
+  private final BlockID blockID;
+  private final long blockLength;
+  private final AtomicReference<Pipeline> pipelineRef = new AtomicReference<>();
+  private final AtomicReference<Token<OzoneBlockTokenIdentifier>> tokenRef = new AtomicReference<>();
+  private XceiverClientFactory xceiverClientFactory;
+  private XceiverClientSpi xceiverClient;
+
+  private ByteBuffer buffer;
+  private long position = 0;
+  private boolean initialized = false;
+  private StreamingReader streamingReader;
+
+  private final boolean verifyChecksum;
+  private final Function<BlockID, BlockLocationInfo> refreshFunction;
+  private final RetryPolicy retryPolicy;
+  private int retries = 0;
+
+  public StreamBlockInputStream(
+      BlockID blockID, long length, Pipeline pipeline,
+      Token<OzoneBlockTokenIdentifier> token,
+      XceiverClientFactory xceiverClientFactory,
+      Function<BlockID, BlockLocationInfo> refreshFunction,
+      OzoneClientConfig config) throws IOException {
+    this.blockID = blockID;
+    this.blockLength = length;
+    pipelineRef.set(setPipeline(pipeline));
+    tokenRef.set(token);
+    this.xceiverClientFactory = xceiverClientFactory;
+    this.verifyChecksum = config.isChecksumVerify();
+    this.retryPolicy = getReadRetryPolicy(config);
+    this.refreshFunction = refreshFunction;
+  }
+
+  @Override
+  public BlockID getBlockID() {
+    return blockID;
+  }
+
+  @Override
+  public long getLength() {
+    return blockLength;
+  }
+
+  @Override
+  public synchronized long getPos() {
+    return position;
+  }
+
+  @Override
+  public synchronized int read() throws IOException {
+    checkOpen();
+    if (!dataAvailableToRead()) {
+      return EOF;
+    }
+    position++;
+    return buffer.get();
+  }
+
+  @Override
+  public synchronized int read(byte[] b, int off, int len) throws IOException {
+    ByteBuffer tmpBuffer = ByteBuffer.wrap(b, off, len);
+    return read(tmpBuffer);
+  }
+
+  @Override
+  public synchronized int read(ByteBuffer targetBuf) throws IOException {

Review Comment:
   it would be good to have open telemetry trace here.



##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/StreamBlockInputStream.java:
##########
@@ -0,0 +1,443 @@
+/*
+ * 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 java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+import org.apache.commons.lang3.NotImplementedException;
+import org.apache.hadoop.fs.ByteBufferReadable;
+import org.apache.hadoop.fs.CanUnbuffer;
+import org.apache.hadoop.fs.FSExceptionMessages;
+import org.apache.hadoop.fs.Seekable;
+import org.apache.hadoop.hdds.client.BlockID;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadBlockResponseProto;
+import org.apache.hadoop.hdds.scm.OzoneClientConfig;
+import org.apache.hadoop.hdds.scm.StreamingReadResponse;
+import org.apache.hadoop.hdds.scm.StreamingReaderSpi;
+import org.apache.hadoop.hdds.scm.XceiverClientFactory;
+import org.apache.hadoop.hdds.scm.XceiverClientSpi;
+import org.apache.hadoop.hdds.scm.container.common.helpers.StorageContainerException;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.hdds.security.token.OzoneBlockTokenIdentifier;
+import org.apache.hadoop.io.retry.RetryPolicy;
+import org.apache.hadoop.ozone.common.Checksum;
+import org.apache.hadoop.ozone.common.ChecksumData;
+import org.apache.hadoop.ozone.common.OzoneChecksumException;
+import org.apache.hadoop.security.token.Token;
+import org.apache.ratis.thirdparty.io.grpc.StatusRuntimeException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * An {@link java.io.InputStream} called from KeyInputStream to read a block from the
+ * container.
+ */
+public class StreamBlockInputStream extends BlockExtendedInputStream
+    implements Seekable, CanUnbuffer, ByteBufferReadable {
+  private static final Logger LOG = LoggerFactory.getLogger(StreamBlockInputStream.class);
+  private static final int EOF = -1;
+  private static final Throwable CANCELLED_EXCEPTION = new Throwable("Cancelled by client");
+
+  private final BlockID blockID;
+  private final long blockLength;
+  private final AtomicReference<Pipeline> pipelineRef = new AtomicReference<>();
+  private final AtomicReference<Token<OzoneBlockTokenIdentifier>> tokenRef = new AtomicReference<>();
+  private XceiverClientFactory xceiverClientFactory;
+  private XceiverClientSpi xceiverClient;
+
+  private ByteBuffer buffer;
+  private long position = 0;
+  private boolean initialized = false;
+  private StreamingReader streamingReader;
+
+  private final boolean verifyChecksum;
+  private final Function<BlockID, BlockLocationInfo> refreshFunction;
+  private final RetryPolicy retryPolicy;
+  private int retries = 0;
+
+  public StreamBlockInputStream(
+      BlockID blockID, long length, Pipeline pipeline,
+      Token<OzoneBlockTokenIdentifier> token,
+      XceiverClientFactory xceiverClientFactory,
+      Function<BlockID, BlockLocationInfo> refreshFunction,
+      OzoneClientConfig config) throws IOException {
+    this.blockID = blockID;
+    this.blockLength = length;
+    pipelineRef.set(setPipeline(pipeline));
+    tokenRef.set(token);
+    this.xceiverClientFactory = xceiverClientFactory;
+    this.verifyChecksum = config.isChecksumVerify();
+    this.retryPolicy = getReadRetryPolicy(config);
+    this.refreshFunction = refreshFunction;
+  }
+
+  @Override
+  public BlockID getBlockID() {
+    return blockID;
+  }
+
+  @Override
+  public long getLength() {
+    return blockLength;
+  }
+
+  @Override
+  public synchronized long getPos() {
+    return position;
+  }
+
+  @Override
+  public synchronized int read() throws IOException {
+    checkOpen();
+    if (!dataAvailableToRead()) {
+      return EOF;
+    }
+    position++;
+    return buffer.get();
+  }
+
+  @Override
+  public synchronized int read(byte[] b, int off, int len) throws IOException {

Review Comment:
   it would be good to have open telemetry trace here.



##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/StreamBlockInputStream.java:
##########
@@ -0,0 +1,443 @@
+/*
+ * 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 java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+import org.apache.commons.lang3.NotImplementedException;
+import org.apache.hadoop.fs.ByteBufferReadable;
+import org.apache.hadoop.fs.CanUnbuffer;
+import org.apache.hadoop.fs.FSExceptionMessages;
+import org.apache.hadoop.fs.Seekable;
+import org.apache.hadoop.hdds.client.BlockID;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadBlockResponseProto;
+import org.apache.hadoop.hdds.scm.OzoneClientConfig;
+import org.apache.hadoop.hdds.scm.StreamingReadResponse;
+import org.apache.hadoop.hdds.scm.StreamingReaderSpi;
+import org.apache.hadoop.hdds.scm.XceiverClientFactory;
+import org.apache.hadoop.hdds.scm.XceiverClientSpi;
+import org.apache.hadoop.hdds.scm.container.common.helpers.StorageContainerException;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.hdds.security.token.OzoneBlockTokenIdentifier;
+import org.apache.hadoop.io.retry.RetryPolicy;
+import org.apache.hadoop.ozone.common.Checksum;
+import org.apache.hadoop.ozone.common.ChecksumData;
+import org.apache.hadoop.ozone.common.OzoneChecksumException;
+import org.apache.hadoop.security.token.Token;
+import org.apache.ratis.thirdparty.io.grpc.StatusRuntimeException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * An {@link java.io.InputStream} called from KeyInputStream to read a block from the
+ * container.
+ */
+public class StreamBlockInputStream extends BlockExtendedInputStream
+    implements Seekable, CanUnbuffer, ByteBufferReadable {
+  private static final Logger LOG = LoggerFactory.getLogger(StreamBlockInputStream.class);
+  private static final int EOF = -1;
+  private static final Throwable CANCELLED_EXCEPTION = new Throwable("Cancelled by client");
+
+  private final BlockID blockID;
+  private final long blockLength;
+  private final AtomicReference<Pipeline> pipelineRef = new AtomicReference<>();
+  private final AtomicReference<Token<OzoneBlockTokenIdentifier>> tokenRef = new AtomicReference<>();
+  private XceiverClientFactory xceiverClientFactory;
+  private XceiverClientSpi xceiverClient;
+
+  private ByteBuffer buffer;
+  private long position = 0;
+  private boolean initialized = false;
+  private StreamingReader streamingReader;
+
+  private final boolean verifyChecksum;
+  private final Function<BlockID, BlockLocationInfo> refreshFunction;
+  private final RetryPolicy retryPolicy;
+  private int retries = 0;
+
+  public StreamBlockInputStream(
+      BlockID blockID, long length, Pipeline pipeline,
+      Token<OzoneBlockTokenIdentifier> token,
+      XceiverClientFactory xceiverClientFactory,
+      Function<BlockID, BlockLocationInfo> refreshFunction,
+      OzoneClientConfig config) throws IOException {
+    this.blockID = blockID;
+    this.blockLength = length;
+    pipelineRef.set(setPipeline(pipeline));
+    tokenRef.set(token);
+    this.xceiverClientFactory = xceiverClientFactory;
+    this.verifyChecksum = config.isChecksumVerify();
+    this.retryPolicy = getReadRetryPolicy(config);
+    this.refreshFunction = refreshFunction;
+  }
+
+  @Override
+  public BlockID getBlockID() {
+    return blockID;
+  }
+
+  @Override
+  public long getLength() {
+    return blockLength;
+  }
+
+  @Override
+  public synchronized long getPos() {
+    return position;
+  }
+
+  @Override
+  public synchronized int read() throws IOException {
+    checkOpen();
+    if (!dataAvailableToRead()) {
+      return EOF;
+    }
+    position++;
+    return buffer.get();
+  }
+
+  @Override
+  public synchronized int read(byte[] b, int off, int len) throws IOException {
+    ByteBuffer tmpBuffer = ByteBuffer.wrap(b, off, len);
+    return read(tmpBuffer);
+  }
+
+  @Override
+  public synchronized int read(ByteBuffer targetBuf) throws IOException {
+    checkOpen();
+    int read = 0;
+    while (targetBuf.hasRemaining()) {
+      if (!dataAvailableToRead()) {
+        break;
+      }
+      int toCopy = Math.min(buffer.remaining(), targetBuf.remaining());
+      ByteBuffer tmpBuf = buffer.duplicate();
+      tmpBuf.limit(tmpBuf.position() + toCopy);
+      targetBuf.put(tmpBuf);
+      buffer.position(tmpBuf.position());
+      position += toCopy;
+      read += toCopy;
+    }
+    return read > 0 ? read : EOF;
+  }
+
+  private boolean dataAvailableToRead() throws IOException {
+    if (position >= blockLength) {
+      return false;
+    }
+    initialize();
+    if (buffer == null || buffer.remaining() == 0) {
+      int loaded = fillBuffer();
+      return loaded != EOF;
+    }
+    return true;
+  }
+
+  @Override
+  protected int readWithStrategy(ByteReaderStrategy strategy) throws IOException {
+    throw new NotImplementedException("readWithStrategy is not implemented.");
+  }
+
+  @Override
+  public synchronized void seek(long pos) throws IOException {
+    checkOpen();
+    if (pos < 0) {
+      throw new IOException("Cannot seek to negative offset");
+    }
+    if (pos > blockLength) {
+      throw new IOException("Cannot seek after the end of the block");
+    }
+    if (pos == position) {
+      return;
+    }
+    closeStream();
+    position = pos;
+  }
+
+  @Override
+  // The seekable interface indicates that seekToNewSource should seek to a new source of the data,
+  // ie a different datanode. This is not supported for now.
+  public synchronized boolean seekToNewSource(long l) throws IOException {
+    return false;
+  }
+
+  @Override
+  public synchronized void unbuffer() {
+    releaseClient();
+  }
+
+  private void closeStream() {
+    if (streamingReader != null) {
+      streamingReader.cancel();
+      streamingReader = null;
+    }
+    initialized = false;
+    buffer = null;
+  }
+
+  protected synchronized void checkOpen() throws IOException {
+    if (xceiverClientFactory == null) {
+      throw new IOException(FSExceptionMessages.STREAM_IS_CLOSED + " Block: " + blockID);
+    }
+  }
+
+  protected synchronized void acquireClient() throws IOException {
+    checkOpen();
+    if (xceiverClient == null) {
+      final Pipeline pipeline = pipelineRef.get();
+      try {
+        xceiverClient = xceiverClientFactory.acquireClientForReadData(pipeline);
+      } catch (IOException ioe) {
+        LOG.warn("Failed to acquire client for pipeline {}, block {}", pipeline, blockID);
+        throw ioe;
+      }
+    }
+  }
+
+  private void initialize() throws IOException {
+    if (initialized) {
+      return;
+    }
+    while (true) {
+      try {
+        acquireClient();
+        streamingReader = new StreamingReader();
+        ContainerProtocolCalls.readBlock(xceiverClient, position, blockID, tokenRef.get(),
+            pipelineRef.get().getReplicaIndexes(), streamingReader);
+        initialized = true;
+        return;
+      } catch (InterruptedException ie) {
+        Thread.currentThread().interrupt();
+        handleExceptions(new IOException("Interrupted", ie));
+      } catch (IOException ioe) {
+        handleExceptions(ioe);
+      }
+    }
+  }
+
+  private void handleExceptions(IOException cause) throws IOException {
+    if (cause instanceof StorageContainerException || isConnectivityIssue(cause)) {
+      if (shouldRetryRead(cause, retryPolicy, retries++)) {
+        releaseClient();
+        refreshBlockInfo(cause);
+        LOG.warn("Refreshing block data to read block {} due to {}", blockID, cause.getMessage());
+      } else {
+        throw cause;
+      }
+    } else {
+      throw cause;
+    }
+  }
+
+  private int fillBuffer() throws IOException {

Review Comment:
   it would be good to have open telemetry trace here.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-3572415883

   >  ... since you have requested changes, could you review the latest changes?
   
   @devabhishekpal , could you follow up on this?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r2456572637


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -504,6 +516,65 @@ private XceiverClientReply sendCommandWithRetry(
     }
   }
 
+  /**
+   * Starts a streaming read operation, intended to read entire blocks from the datanodes. This method expects a
+   * {@link StreamObserver} to be passed in, which will be used to receive the streamed data from the datanode.
+   * Upon successfully starting the streaming read, a {@link StreamingReadResponse} is returned, which contains
+   * information about the datanode used for the read, and the request observer that can be used to manage the stream
+   * (e.g., to cancel it if needed). A semaphore is acquired to limit the number of concurrent streaming reads so upon
+   * successful return of this method, the caller must ensure to call {@link #completeStreamRead(StreamingReadResponse)}
+   * to release the semaphore once the streaming read is complete.
+   * @param request The container command request to initiate the streaming read.
+   * @param streamObserver The observer that will handle the streamed responses.
+   * @return A {@link StreamingReadResponse} containing details of the streaming read operation.
+   * @throws IOException
+   * @throws InterruptedException
+   */
+  @Override
+  public StreamingReadResponse streamRead(ContainerCommandRequestProto request,
+      StreamObserver<ContainerCommandResponseProto> streamObserver) throws IOException, InterruptedException {
+    List<DatanodeDetails> datanodeList = sortDatanodes(request);
+    IOException lastException = null;
+    for (DatanodeDetails dn : datanodeList) {
+      try {
+        checkOpen(dn);
+        semaphore.acquire();
+        XceiverClientProtocolServiceStub stub = asyncStubs.get(dn.getID());
+        if (stub == null) {
+          throw new IOException("Failed to get gRPC stub for DataNode: " + dn);
+        }
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("Executing command {} on datanode {}", processForDebug(request), dn);
+        }
+        StreamObserver<ContainerCommandRequestProto> requestObserver = stub
+            .withDeadlineAfter(timeout, TimeUnit.SECONDS)
+            .send(streamObserver);
+        requestObserver.onNext(request);
+        requestObserver.onCompleted();
+        return new StreamingReadResponse(dn, (ClientCallStreamObserver<ContainerCommandRequestProto>) requestObserver);

Review Comment:
   It should not call onCompleted() here.  Otherwise, the returned `requestObserver` is already completed and becomes useless.



##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/StreamBlockInputStream.java:
##########
@@ -0,0 +1,413 @@
+/*
+ * 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 java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+import org.apache.commons.lang3.NotImplementedException;
+import org.apache.hadoop.fs.ByteBufferReadable;
+import org.apache.hadoop.fs.CanUnbuffer;
+import org.apache.hadoop.fs.FSExceptionMessages;
+import org.apache.hadoop.fs.Seekable;
+import org.apache.hadoop.hdds.client.BlockID;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadBlockResponseProto;
+import org.apache.hadoop.hdds.scm.OzoneClientConfig;
+import org.apache.hadoop.hdds.scm.StreamingReadResponse;
+import org.apache.hadoop.hdds.scm.XceiverClientFactory;
+import org.apache.hadoop.hdds.scm.XceiverClientSpi;
+import org.apache.hadoop.hdds.scm.container.common.helpers.StorageContainerException;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.hdds.security.token.OzoneBlockTokenIdentifier;
+import org.apache.hadoop.io.retry.RetryPolicy;
+import org.apache.hadoop.ozone.common.Checksum;
+import org.apache.hadoop.ozone.common.ChecksumData;
+import org.apache.hadoop.ozone.common.OzoneChecksumException;
+import org.apache.hadoop.security.token.Token;
+import org.apache.ratis.thirdparty.io.grpc.stub.StreamObserver;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * An {@link java.io.InputStream} called from KeyInputStream to read a block from the
+ * container.
+ */
+public class StreamBlockInputStream extends BlockExtendedInputStream
+    implements Seekable, CanUnbuffer, ByteBufferReadable {
+  private static final Logger LOG = LoggerFactory.getLogger(StreamBlockInputStream.class);
+  private static final int EOF = -1;
+  private static final Throwable CANCELLED_EXCEPTION = new Throwable("Cancelled by client");
+
+  private final BlockID blockID;
+  private final long blockLength;
+  private final AtomicReference<Pipeline> pipelineRef = new AtomicReference<>();
+  private final AtomicReference<Token<OzoneBlockTokenIdentifier>> tokenRef = new AtomicReference<>();
+  private XceiverClientFactory xceiverClientFactory;
+  private XceiverClientSpi xceiverClient;
+
+  private ByteBuffer buffer;
+  private long position = 0;
+  private boolean initialized = false;
+  private StreamingReader streamingReader;
+
+  private final boolean verifyChecksum;
+  private final Function<BlockID, BlockLocationInfo> refreshFunction;
+  private final RetryPolicy retryPolicy;
+  private int retries = 0;
+
+  public StreamBlockInputStream(
+      BlockID blockID, long length, Pipeline pipeline,
+      Token<OzoneBlockTokenIdentifier> token,
+      XceiverClientFactory xceiverClientFactory,
+      Function<BlockID, BlockLocationInfo> refreshFunction,
+      OzoneClientConfig config) throws IOException {
+    this.blockID = blockID;
+    this.blockLength = length;
+    pipelineRef.set(setPipeline(pipeline));
+    tokenRef.set(token);
+    this.xceiverClientFactory = xceiverClientFactory;
+    this.verifyChecksum = config.isChecksumVerify();
+    this.retryPolicy = getReadRetryPolicy(config);
+    this.refreshFunction = refreshFunction;
+  }
+
+  @Override
+  public BlockID getBlockID() {
+    return blockID;
+  }
+
+  @Override
+  public long getLength() {
+    return blockLength;
+  }
+
+  @Override
+  public synchronized long getPos() {
+    return position;
+  }
+
+  @Override
+  public synchronized int read() throws IOException {
+    checkOpen();
+    if (!dataAvailableToRead()) {
+      return EOF;
+    }
+    position++;
+    return buffer.get();
+  }
+
+  @Override
+  public synchronized int read(byte[] b, int off, int len) throws IOException {
+    ByteBuffer tmpBuffer = ByteBuffer.wrap(b, off, len);
+    return read(tmpBuffer);
+  }
+
+  @Override
+  public synchronized int read(ByteBuffer targetBuf) throws IOException {
+    checkOpen();
+    int read = 0;
+    while (targetBuf.hasRemaining()) {
+      if (!dataAvailableToRead()) {
+        break;
+      }
+      int toCopy = Math.min(buffer.remaining(), targetBuf.remaining());
+      ByteBuffer tmpBuf = buffer.duplicate();
+      tmpBuf.limit(tmpBuf.position() + toCopy);
+      targetBuf.put(tmpBuf);
+      buffer.position(tmpBuf.position());
+      position += toCopy;
+      read += toCopy;
+    }
+    return read > 0 ? read : EOF;
+  }
+
+  private boolean dataAvailableToRead() throws IOException {
+    if (position >= blockLength) {
+      return false;
+    }
+    initialize();
+    if (buffer == null || buffer.remaining() == 0) {
+      int loaded = fillBuffer();
+      return loaded != EOF;
+    }
+    return true;
+  }
+
+  @Override
+  protected int readWithStrategy(ByteReaderStrategy strategy) throws IOException {
+    throw new NotImplementedException("readWithStrategy is not implemented.");
+  }
+
+  @Override
+  public synchronized void seek(long pos) throws IOException {
+    checkOpen();
+    if (pos < 0) {
+      throw new IOException("Cannot seek to negative offset");
+    }
+    if (pos > blockLength) {
+      throw new IOException("Cannot seek after the end of the block");
+    }
+    if (pos == position) {
+      return;
+    }
+    closeStream();
+    position = pos;
+  }
+
+  @Override
+  // The seekable interface indicates that seekToNewSource should seek to a new source of the data,
+  // ie a different datanode. This is not supported for now.
+  public synchronized boolean seekToNewSource(long l) throws IOException {
+    return false;
+  }
+
+  @Override
+  public synchronized void unbuffer() {
+    releaseClient();
+  }
+
+  private void closeStream() {
+    if (streamingReader != null) {
+      streamingReader.cancel();
+      streamingReader = null;
+    }
+    initialized = false;
+    buffer = null;
+  }
+
+  protected synchronized void checkOpen() throws IOException {
+    if (xceiverClientFactory == null) {
+      throw new IOException(FSExceptionMessages.STREAM_IS_CLOSED + " Block: " + blockID);
+    }
+  }
+
+  protected synchronized void acquireClient() throws IOException {
+    checkOpen();
+    if (xceiverClient == null) {
+      final Pipeline pipeline = pipelineRef.get();
+      try {
+        xceiverClient = xceiverClientFactory.acquireClientForReadData(pipeline);
+      } catch (IOException ioe) {
+        LOG.warn("Failed to acquire client for pipeline {}, block {}", pipeline, blockID);
+        throw ioe;
+      }
+    }
+  }
+
+  private void initialize() throws IOException {
+    if (initialized) {
+      return;
+    }
+    while (true) {
+      try {
+        acquireClient();
+        streamingReader = new StreamingReader();
+        StreamingReadResponse response =
+            ContainerProtocolCalls.readBlock(xceiverClient, position, blockID, tokenRef.get(),
+                pipelineRef.get().getReplicaIndexes(), streamingReader);
+        streamingReader.setRequestResponse(response);
+        initialized = true;
+        return;
+      } catch (InterruptedException ie) {
+        Thread.currentThread().interrupt();
+        handleExceptions(new IOException("Interrupted", ie));
+      } catch (IOException ioe) {
+        handleExceptions(ioe);
+      }
+    }
+  }
+
+  private void handleExceptions(IOException cause) throws IOException {
+    if (cause instanceof StorageContainerException || isConnectivityIssue(cause)) {
+      if (shouldRetryRead(cause, retryPolicy, retries++)) {
+        releaseClient();
+        refreshBlockInfo(cause);
+        LOG.warn("Refreshing block data to read block {} due to {}", blockID, cause.getMessage());
+      } else {
+        throw cause;
+      }
+    } else {
+      throw cause;
+    }
+  }
+
+  private int fillBuffer() throws IOException {
+    if (!streamingReader.hasNext()) {
+      return EOF;
+    }
+    buffer = streamingReader.readNext();
+    return buffer == null ? EOF : buffer.limit();
+  }
+
+  protected synchronized void releaseClient() {
+    if (xceiverClientFactory != null && xceiverClient != null) {
+      closeStream();
+      xceiverClientFactory.releaseClientForReadData(xceiverClient, false);
+      xceiverClient = null;
+    }
+  }
+
+  @Override
+  public synchronized void close() throws IOException {
+    releaseClient();
+    xceiverClientFactory = null;
+  }
+
+  private void refreshBlockInfo(IOException cause) throws IOException {
+    refreshBlockInfo(cause, blockID, pipelineRef, tokenRef, refreshFunction);
+  }
+
+  /**
+   * Implementation of a StreamObserver used to received and buffer streaming GRPC reads.
+   */
+  public class StreamingReader implements StreamObserver<ContainerProtos.ContainerCommandResponseProto> {
+
+    private final BlockingQueue<ContainerProtos.ReadBlockResponseProto> responseQueue = new LinkedBlockingQueue<>(1);
+    private final AtomicBoolean completed = new AtomicBoolean(false);
+    private final AtomicBoolean failed = new AtomicBoolean(false);
+    private final AtomicBoolean semaphoreReleased = new AtomicBoolean(false);
+    private final AtomicReference<Throwable> error = new AtomicReference<>();
+    private StreamingReadResponse response;
+
+    // TODO: Semaphore in XceiverClient which count open stream?
+    public boolean hasNext() {
+      return !responseQueue.isEmpty() || !completed.get();
+    }
+
+    public ByteBuffer readNext() throws IOException {
+      if (failed.get()) {
+        Throwable cause = error.get();
+        throw new IOException("Streaming read failed", cause);
+      }
+
+      if (completed.get() && responseQueue.isEmpty()) {
+        return null; // Stream ended
+      }
+
+      ReadBlockResponseProto readBlock;
+      try {
+        readBlock = responseQueue.poll(30, TimeUnit.SECONDS);
+      } catch (InterruptedException e) {
+        Thread.currentThread().interrupt();
+        throw new IOException("Interrupted while waiting for response", e);
+      }
+      if (readBlock == null) {
+        if (failed.get()) {
+          Throwable cause = error.get();
+          throw new IOException("Streaming read failed", cause);
+        } else if (completed.get()) {
+          return null; // Stream ended
+        } else {
+          throw new IOException("Timed out waiting for response");
+        }
+      }
+      // The server always returns data starting from the last checksum boundary. Therefore if the reader position is
+      // ahead of the position we received from the server, we need to adjust the buffer position accordingly.
+      // If the reader position is behind
+      ByteBuffer buf = readBlock.getData().asReadOnlyByteBuffer();
+      long blockOffset = readBlock.getOffset();
+      long pos = getPos();
+      if (pos < blockOffset) {
+        // This should not happen, and if it does, we have a bug.
+        throw new IOException("Received data out of order. Position is " + pos + " but received data at "
+            + blockOffset);
+      }
+      if (pos > readBlock.getOffset()) {
+        int offset = (int)(pos - readBlock.getOffset());
+        buf.position(offset);
+      }
+      return buf;
+    }
+
+    public void setRequestResponse(StreamingReadResponse streamingReadResponse) {
+      this.response = streamingReadResponse;
+    }
+
+    /**
+     * By calling cancel, the client will send a cancel signal to the server, which will stop sending more data and
+     * cause the onError() to be called in this observer with a CANCELLED exception.
+     */
+    public void cancel() {
+      if (response != null && response.getRequestObserver() != null) {
+        response.getRequestObserver().cancel("Cancelled by client", CANCELLED_EXCEPTION);
+        completed.set(true);
+        releaseResources();
+      }
+    }
+
+    private void releaseResources() {
+      boolean wasNotYetComplete = semaphoreReleased.getAndSet(true);
+      if (wasNotYetComplete) {
+        xceiverClient.completeStreamRead(response);
+      }
+    }
+
+    @Override
+    public void onNext(ContainerProtos.ContainerCommandResponseProto containerCommandResponseProto) {
+      try {
+        ReadBlockResponseProto readBlock = containerCommandResponseProto.getReadBlock();
+        ByteBuffer data = readBlock.getData().asReadOnlyByteBuffer();
+        if (verifyChecksum) {
+          ChecksumData checksumData = ChecksumData.getFromProtoBuf(readBlock.getChecksumData());
+          Checksum.verifyChecksum(data, checksumData, 0);
+        }
+        offerToQueue(readBlock);
+      } catch (OzoneChecksumException e) {
+        // Calling onError will cancel the stream on the server side and also set the failure state.
+        onError(e);

Review Comment:
   It should call requestObserver.onError(..) in order to notify the server side
   ```java
           final StatusException statusException = Status.fromCode(Status.Code.DATA_LOSS).withCause(e).asException();
           setError(statusException);
           requestObserver.onError(statusException);
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "sodonnel (via GitHub)" <gi...@apache.org>.
sodonnel commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r2456891023


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -504,6 +516,65 @@ private XceiverClientReply sendCommandWithRetry(
     }
   }
 
+  /**
+   * Starts a streaming read operation, intended to read entire blocks from the datanodes. This method expects a
+   * {@link StreamObserver} to be passed in, which will be used to receive the streamed data from the datanode.
+   * Upon successfully starting the streaming read, a {@link StreamingReadResponse} is returned, which contains
+   * information about the datanode used for the read, and the request observer that can be used to manage the stream
+   * (e.g., to cancel it if needed). A semaphore is acquired to limit the number of concurrent streaming reads so upon
+   * successful return of this method, the caller must ensure to call {@link #completeStreamRead(StreamingReadResponse)}
+   * to release the semaphore once the streaming read is complete.
+   * @param request The container command request to initiate the streaming read.
+   * @param streamObserver The observer that will handle the streamed responses.
+   * @return A {@link StreamingReadResponse} containing details of the streaming read operation.
+   * @throws IOException
+   * @throws InterruptedException
+   */
+  @Override
+  public StreamingReadResponse streamRead(ContainerCommandRequestProto request,
+      StreamObserver<ContainerCommandResponseProto> streamObserver) throws IOException, InterruptedException {
+    List<DatanodeDetails> datanodeList = sortDatanodes(request);
+    IOException lastException = null;
+    for (DatanodeDetails dn : datanodeList) {
+      try {
+        checkOpen(dn);
+        semaphore.acquire();
+        XceiverClientProtocolServiceStub stub = asyncStubs.get(dn.getID());
+        if (stub == null) {
+          throw new IOException("Failed to get gRPC stub for DataNode: " + dn);
+        }
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("Executing command {} on datanode {}", processForDebug(request), dn);
+        }
+        StreamObserver<ContainerCommandRequestProto> requestObserver = stub
+            .withDeadlineAfter(timeout, TimeUnit.SECONDS)
+            .send(streamObserver);
+        requestObserver.onNext(request);
+        requestObserver.onCompleted();
+        return new StreamingReadResponse(dn, (ClientCallStreamObserver<ContainerCommandRequestProto>) requestObserver);

Review Comment:
   I don't think that is correct. You must call onComplete after sending the last request to the server to indicate there are no more messages expected to be sent to the server. It is possible to call onNext() several times to send distinct messages to the server. You are still able to call "cancel()" on the request observer after it is completed, at least that appears to work correctly.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "sodonnel (via GitHub)" <gi...@apache.org>.
sodonnel commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r2462675777


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -504,6 +516,65 @@ private XceiverClientReply sendCommandWithRetry(
     }
   }
 
+  /**
+   * Starts a streaming read operation, intended to read entire blocks from the datanodes. This method expects a
+   * {@link StreamObserver} to be passed in, which will be used to receive the streamed data from the datanode.
+   * Upon successfully starting the streaming read, a {@link StreamingReadResponse} is returned, which contains
+   * information about the datanode used for the read, and the request observer that can be used to manage the stream
+   * (e.g., to cancel it if needed). A semaphore is acquired to limit the number of concurrent streaming reads so upon
+   * successful return of this method, the caller must ensure to call {@link #completeStreamRead(StreamingReadResponse)}
+   * to release the semaphore once the streaming read is complete.
+   * @param request The container command request to initiate the streaming read.
+   * @param streamObserver The observer that will handle the streamed responses.
+   * @return A {@link StreamingReadResponse} containing details of the streaming read operation.
+   * @throws IOException
+   * @throws InterruptedException
+   */
+  @Override
+  public StreamingReadResponse streamRead(ContainerCommandRequestProto request,
+      StreamObserver<ContainerCommandResponseProto> streamObserver) throws IOException, InterruptedException {
+    List<DatanodeDetails> datanodeList = sortDatanodes(request);
+    IOException lastException = null;
+    for (DatanodeDetails dn : datanodeList) {
+      try {
+        checkOpen(dn);
+        semaphore.acquire();
+        XceiverClientProtocolServiceStub stub = asyncStubs.get(dn.getID());
+        if (stub == null) {
+          throw new IOException("Failed to get gRPC stub for DataNode: " + dn);
+        }
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("Executing command {} on datanode {}", processForDebug(request), dn);
+        }
+        StreamObserver<ContainerCommandRequestProto> requestObserver = stub
+            .withDeadlineAfter(timeout, TimeUnit.SECONDS)
+            .send(streamObserver);
+        requestObserver.onNext(request);
+        requestObserver.onCompleted();
+        return new StreamingReadResponse(dn, (ClientCallStreamObserver<ContainerCommandRequestProto>) requestObserver);

Review Comment:
   The implementation is just streaming the whole block each time and removing the length part. The idea being that the stream blocks on the socket until more is read. This new block input stream just starts reading from whatever position you tell it to start and then blocks until the client consumes it. Then reads more. The length part of the read isn’t there. Except at the higher level streams.
   
   With a 10kb read the server will respond with a checksum sized read of 16kb or 1mb if that is the checksum size. Then from my experiments the server will keep sending consecutive chunks up to 1mb which will block on the socket until the client pulls them off. Then the server will block sending until it can get more out.  (edited) 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-3537172073

   @sodonnel , Tried to add length to ReadBlockRequestProto.  It works well.   See https://github.com/szetszwo/ozone/commits/HDDS-10338b/ (please feel free to use the code.)
   
   Tested it with various client buffer sizes (17MB, 3.5MB, 4KB).  Below is the case 3.5MB (=3565158).
   ```
   XXX ---------------------------------------------------------
   XXX read 17825792 bytes with bufferSize 3565158
   XXX ---------------------------------------------------------
   XXX initStreamRead conID: 1 locID: 115816896921600001 on datanode a85ea168-0eb0-46ed-9090-10c44ebd9c10(10.96.128.134/10.96.128.134)
   XXX position 0, length 3565158, requested 0, diff 3565158, rounded 3670016
   XXX XceiverClientGrpc-1 -> dn-10c44ebd9c10_stream, send onNext request blockID { containerID: 1 localID: 115816896921600001 blockCommitSequenceId: 16 } offset: 0 length: 3670016
   XXX server readBlock blockID { containerID: 1 localID: 115816896921600001 blockCommitSequenceId: 16 } offset: 0 length: 3670016
   XXX server onNext response 0: dataLength=262144
   XXX server onNext response 1: dataLength=262144
   XXX server onNext response 2: dataLength=262144
   XXX server onNext response 3: dataLength=262144
   XXX server onNext response 4: dataLength=262144
   XXX server onNext response 5: dataLength=262144
   XXX server onNext response 6: dataLength=262144
   XXX server onNext response 7: dataLength=262144
   XXX server onNext response 8: dataLength=262144
   XXX server onNext response 9: dataLength=262144
   XXX server onNext response 10: dataLength=262144
   XXX server onNext response 11: dataLength=262144
   XXX server onNext response 12: dataLength=262144
   XXX server onNext response 13: dataLength=262144
   XXX server response ended: totalDataLength=3670016, numResponse=14
   XXX position 3670016, length 3460300, requested 3670016, diff 3460300, rounded 3670016
   XXX XceiverClientGrpc-1 -> dn-10c44ebd9c10_stream, send onNext request blockID { containerID: 1 localID: 115816896921600001 blockCommitSequenceId: 16 } offset: 3670016 length: 3670016
   XXX server readBlock blockID { containerID: 1 localID: 115816896921600001 blockCommitSequenceId: 16 } offset: 3670016 length: 3670016
   XXX server onNext response 0: dataLength=262144
   XXX server onNext response 1: dataLength=262144
   XXX server onNext response 2: dataLength=262144
   XXX server onNext response 3: dataLength=262144
   XXX server onNext response 4: dataLength=262144
   XXX server onNext response 5: dataLength=262144
   XXX server onNext response 6: dataLength=262144
   XXX server onNext response 7: dataLength=262144
   XXX server onNext response 8: dataLength=262144
   XXX server onNext response 9: dataLength=262144
   XXX server onNext response 10: dataLength=262144
   XXX server onNext response 11: dataLength=262144
   XXX server onNext response 12: dataLength=262144
   XXX server onNext response 13: dataLength=262144
   XXX server response ended: totalDataLength=3670016, numResponse=14
   XXX position 7340032, length 1048576, requested 7340032, diff 1048576, rounded 1048576
   XXX XceiverClientGrpc-1 -> dn-10c44ebd9c10_stream, send onNext request blockID { containerID: 1 localID: 115816896921600001 blockCommitSequenceId: 16 } offset: 7340032 length: 1048576
   XXX server readBlock blockID { containerID: 1 localID: 115816896921600001 blockCommitSequenceId: 16 } offset: 7340032 length: 1048576
   XXX server onNext response 0: dataLength=262144
   XXX server onNext response 1: dataLength=262144
   XXX server onNext response 2: dataLength=262144
   XXX server onNext response 3: dataLength=262144
   XXX server response ended: totalDataLength=1048576, numResponse=4
   XXX initStreamRead conID: 2 locID: 115816896921600002 on datanode a85ea168-0eb0-46ed-9090-10c44ebd9c10(10.96.128.134/10.96.128.134)
   XXX position 0, length 2306866, requested 0, diff 2306866, rounded 2359296
   XXX XceiverClientGrpc-1 -> dn-10c44ebd9c10_stream, send onNext request blockID { containerID: 2 localID: 115816896921600002 blockCommitSequenceId: 39 } offset: 0 length: 2359296
   XXX server readBlock blockID { containerID: 2 localID: 115816896921600002 blockCommitSequenceId: 39 } offset: 0 length: 2359296
   XXX server onNext response 0: dataLength=262144
   XXX server onNext response 1: dataLength=262144
   XXX server onNext response 2: dataLength=262144
   XXX server onNext response 3: dataLength=262144
   XXX server onNext response 4: dataLength=262144
   XXX server onNext response 5: dataLength=262144
   XXX server onNext response 6: dataLength=262144
   XXX server onNext response 7: dataLength=262144
   XXX server onNext response 8: dataLength=262144
   XXX server response ended: totalDataLength=2359296, numResponse=9
   XXX position 2359296, length 3512728, requested 2359296, diff 3512728, rounded 3670016
   XXX XceiverClientGrpc-1 -> dn-10c44ebd9c10_stream, send onNext request blockID { containerID: 2 localID: 115816896921600002 blockCommitSequenceId: 39 } offset: 2359296 length: 3670016
   XXX server readBlock blockID { containerID: 2 localID: 115816896921600002 blockCommitSequenceId: 39 } offset: 2359296 length: 3670016
   XXX server onNext response 0: dataLength=262144
   XXX server onNext response 1: dataLength=262144
   XXX server onNext response 2: dataLength=262144
   XXX server onNext response 3: dataLength=262144
   XXX server onNext response 4: dataLength=262144
   XXX server onNext response 5: dataLength=262144
   XXX server onNext response 6: dataLength=262144
   XXX server onNext response 7: dataLength=262144
   XXX server onNext response 8: dataLength=262144
   XXX server onNext response 9: dataLength=262144
   XXX server onNext response 10: dataLength=262144
   XXX server onNext response 11: dataLength=262144
   XXX server onNext response 12: dataLength=262144
   XXX server onNext response 13: dataLength=262144
   XXX server response ended: totalDataLength=3670016, numResponse=14
   XXX position 6029312, length 2359296, requested 6029312, diff 2359296, rounded 2359296
   XXX XceiverClientGrpc-1 -> dn-10c44ebd9c10_stream, send onNext request blockID { containerID: 2 localID: 115816896921600002 blockCommitSequenceId: 39 } offset: 6029312 length: 2359296
   XXX server readBlock blockID { containerID: 2 localID: 115816896921600002 blockCommitSequenceId: 39 } offset: 6029312 length: 2359296
   XXX server onNext response 0: dataLength=262144
   XXX server onNext response 1: dataLength=262144
   XXX server onNext response 2: dataLength=262144
   XXX server onNext response 3: dataLength=262144
   XXX server onNext response 4: dataLength=262144
   XXX server onNext response 5: dataLength=262144
   XXX server onNext response 6: dataLength=262144
   XXX server onNext response 7: dataLength=262144
   XXX server onNext response 8: dataLength=262144
   XXX server response ended: totalDataLength=2359296, numResponse=9
   XXX initStreamRead conID: 3 locID: 115816896921600003 on datanode a85ea168-0eb0-46ed-9090-10c44ebd9c10(10.96.128.134/10.96.128.134)
   XXX position 0, length 1048574, requested 0, diff 1048574, rounded 1048576
   XXX XceiverClientGrpc-1 -> dn-10c44ebd9c10_stream, send onNext request blockID { containerID: 3 localID: 115816896921600003 blockCommitSequenceId: 47 } offset: 0 length: 1048576
   XXX server readBlock blockID { containerID: 3 localID: 115816896921600003 blockCommitSequenceId: 47 } offset: 0 length: 1048576
   XXX server onNext response 0: dataLength=262144
   XXX server onNext response 1: dataLength=262144
   XXX server onNext response 2: dataLength=262144
   XXX server onNext response 3: dataLength=262144
   XXX server response ended: totalDataLength=1048576, numResponse=4
   ```


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r2491600458


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/StreamBlockInputStream.java:
##########
@@ -0,0 +1,443 @@
+/*
+ * 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 java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+import org.apache.commons.lang3.NotImplementedException;
+import org.apache.hadoop.fs.ByteBufferReadable;
+import org.apache.hadoop.fs.CanUnbuffer;
+import org.apache.hadoop.fs.FSExceptionMessages;
+import org.apache.hadoop.fs.Seekable;
+import org.apache.hadoop.hdds.client.BlockID;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadBlockResponseProto;
+import org.apache.hadoop.hdds.scm.OzoneClientConfig;
+import org.apache.hadoop.hdds.scm.StreamingReadResponse;
+import org.apache.hadoop.hdds.scm.StreamingReaderSpi;
+import org.apache.hadoop.hdds.scm.XceiverClientFactory;
+import org.apache.hadoop.hdds.scm.XceiverClientSpi;
+import org.apache.hadoop.hdds.scm.container.common.helpers.StorageContainerException;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.hdds.security.token.OzoneBlockTokenIdentifier;
+import org.apache.hadoop.io.retry.RetryPolicy;
+import org.apache.hadoop.ozone.common.Checksum;
+import org.apache.hadoop.ozone.common.ChecksumData;
+import org.apache.hadoop.ozone.common.OzoneChecksumException;
+import org.apache.hadoop.security.token.Token;
+import org.apache.ratis.thirdparty.io.grpc.StatusRuntimeException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * An {@link java.io.InputStream} called from KeyInputStream to read a block from the
+ * container.
+ */
+public class StreamBlockInputStream extends BlockExtendedInputStream
+    implements Seekable, CanUnbuffer, ByteBufferReadable {
+  private static final Logger LOG = LoggerFactory.getLogger(StreamBlockInputStream.class);
+  private static final int EOF = -1;
+  private static final Throwable CANCELLED_EXCEPTION = new Throwable("Cancelled by client");
+
+  private final BlockID blockID;
+  private final long blockLength;
+  private final AtomicReference<Pipeline> pipelineRef = new AtomicReference<>();
+  private final AtomicReference<Token<OzoneBlockTokenIdentifier>> tokenRef = new AtomicReference<>();
+  private XceiverClientFactory xceiverClientFactory;
+  private XceiverClientSpi xceiverClient;
+
+  private ByteBuffer buffer;
+  private long position = 0;
+  private boolean initialized = false;
+  private StreamingReader streamingReader;
+
+  private final boolean verifyChecksum;
+  private final Function<BlockID, BlockLocationInfo> refreshFunction;
+  private final RetryPolicy retryPolicy;
+  private int retries = 0;
+
+  public StreamBlockInputStream(
+      BlockID blockID, long length, Pipeline pipeline,
+      Token<OzoneBlockTokenIdentifier> token,
+      XceiverClientFactory xceiverClientFactory,
+      Function<BlockID, BlockLocationInfo> refreshFunction,
+      OzoneClientConfig config) throws IOException {
+    this.blockID = blockID;
+    this.blockLength = length;
+    pipelineRef.set(setPipeline(pipeline));
+    tokenRef.set(token);
+    this.xceiverClientFactory = xceiverClientFactory;
+    this.verifyChecksum = config.isChecksumVerify();
+    this.retryPolicy = getReadRetryPolicy(config);
+    this.refreshFunction = refreshFunction;
+  }
+
+  @Override
+  public BlockID getBlockID() {
+    return blockID;
+  }
+
+  @Override
+  public long getLength() {
+    return blockLength;
+  }
+
+  @Override
+  public synchronized long getPos() {
+    return position;
+  }
+
+  @Override
+  public synchronized int read() throws IOException {
+    checkOpen();
+    if (!dataAvailableToRead()) {
+      return EOF;
+    }
+    position++;
+    return buffer.get();
+  }
+
+  @Override
+  public synchronized int read(byte[] b, int off, int len) throws IOException {
+    ByteBuffer tmpBuffer = ByteBuffer.wrap(b, off, len);
+    return read(tmpBuffer);
+  }
+
+  @Override
+  public synchronized int read(ByteBuffer targetBuf) throws IOException {
+    checkOpen();
+    int read = 0;
+    while (targetBuf.hasRemaining()) {
+      if (!dataAvailableToRead()) {
+        break;
+      }
+      int toCopy = Math.min(buffer.remaining(), targetBuf.remaining());
+      ByteBuffer tmpBuf = buffer.duplicate();
+      tmpBuf.limit(tmpBuf.position() + toCopy);
+      targetBuf.put(tmpBuf);
+      buffer.position(tmpBuf.position());
+      position += toCopy;
+      read += toCopy;
+    }
+    return read > 0 ? read : EOF;
+  }
+
+  private boolean dataAvailableToRead() throws IOException {
+    if (position >= blockLength) {
+      return false;
+    }
+    initialize();
+    if (buffer == null || buffer.remaining() == 0) {
+      int loaded = fillBuffer();
+      return loaded != EOF;
+    }
+    return true;
+  }
+
+  @Override
+  protected int readWithStrategy(ByteReaderStrategy strategy) throws IOException {
+    throw new NotImplementedException("readWithStrategy is not implemented.");
+  }
+
+  @Override
+  public synchronized void seek(long pos) throws IOException {
+    checkOpen();
+    if (pos < 0) {
+      throw new IOException("Cannot seek to negative offset");
+    }
+    if (pos > blockLength) {
+      throw new IOException("Cannot seek after the end of the block");
+    }
+    if (pos == position) {
+      return;
+    }
+    closeStream();
+    position = pos;
+  }
+
+  @Override
+  // The seekable interface indicates that seekToNewSource should seek to a new source of the data,
+  // ie a different datanode. This is not supported for now.
+  public synchronized boolean seekToNewSource(long l) throws IOException {
+    return false;
+  }
+
+  @Override
+  public synchronized void unbuffer() {
+    releaseClient();
+  }
+
+  private void closeStream() {
+    if (streamingReader != null) {
+      streamingReader.cancel();
+      streamingReader = null;
+    }
+    initialized = false;
+    buffer = null;
+  }
+
+  protected synchronized void checkOpen() throws IOException {
+    if (xceiverClientFactory == null) {
+      throw new IOException(FSExceptionMessages.STREAM_IS_CLOSED + " Block: " + blockID);
+    }
+  }
+
+  protected synchronized void acquireClient() throws IOException {
+    checkOpen();
+    if (xceiverClient == null) {
+      final Pipeline pipeline = pipelineRef.get();
+      try {
+        xceiverClient = xceiverClientFactory.acquireClientForReadData(pipeline);
+      } catch (IOException ioe) {
+        LOG.warn("Failed to acquire client for pipeline {}, block {}", pipeline, blockID);
+        throw ioe;
+      }
+    }
+  }
+
+  private void initialize() throws IOException {
+    if (initialized) {
+      return;
+    }
+    while (true) {
+      try {
+        acquireClient();
+        streamingReader = new StreamingReader();
+        ContainerProtocolCalls.readBlock(xceiverClient, position, blockID, tokenRef.get(),
+            pipelineRef.get().getReplicaIndexes(), streamingReader);
+        initialized = true;
+        return;
+      } catch (InterruptedException ie) {
+        Thread.currentThread().interrupt();
+        handleExceptions(new IOException("Interrupted", ie));
+      } catch (IOException ioe) {
+        handleExceptions(ioe);
+      }
+    }
+  }
+
+  private void handleExceptions(IOException cause) throws IOException {
+    if (cause instanceof StorageContainerException || isConnectivityIssue(cause)) {
+      if (shouldRetryRead(cause, retryPolicy, retries++)) {
+        releaseClient();
+        refreshBlockInfo(cause);
+        LOG.warn("Refreshing block data to read block {} due to {}", blockID, cause.getMessage());
+      } else {
+        throw cause;
+      }
+    } else {
+      throw cause;
+    }
+  }
+
+  private int fillBuffer() throws IOException {
+    if (!streamingReader.hasNext()) {
+      return EOF;
+    }
+    buffer = streamingReader.readNext();
+    return buffer == null ? EOF : buffer.limit();
+  }
+
+  protected synchronized void releaseClient() {
+    if (xceiverClientFactory != null && xceiverClient != null) {
+      closeStream();
+      xceiverClientFactory.releaseClientForReadData(xceiverClient, false);
+      xceiverClient = null;
+    }
+  }
+
+  @Override
+  public synchronized void close() throws IOException {
+    releaseClient();
+    xceiverClientFactory = null;
+  }
+
+  private void refreshBlockInfo(IOException cause) throws IOException {
+    refreshBlockInfo(cause, blockID, pipelineRef, tokenRef, refreshFunction);
+  }
+
+  private synchronized void releaseStreamResources(StreamingReadResponse response) {
+    if (xceiverClient != null) {
+      xceiverClient.completeStreamRead(response);
+    }
+  }
+
+  /**
+   * Implementation of a StreamObserver used to received and buffer streaming GRPC reads.
+   */
+  public class StreamingReader implements StreamingReaderSpi {
+
+    private final BlockingQueue<ContainerProtos.ReadBlockResponseProto> responseQueue = new LinkedBlockingQueue<>(1);

Review Comment:
   > The thread overhead is on the datanode side, as streaming a block to a client ties up the server handler thread.  ...
   
   @sodonnel , This `BlockingQueue<> responseQueue` is at the client side.  So, the thread blocking problem is at the client side.
   
   Server side gRPC threads won't block in the current implementation.  Since the server side onNext() implementation does not block.  We may print some debug messages to verify.
   
   It would be much better if the blocking thread problem is at the server side.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "swamirishi (via GitHub)" <gi...@apache.org>.
swamirishi commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-3572398750

   I am not able to take out time to do a complete review on this PR. I don't wanna block the PR please go ahead and merge the changes if other reviewers are good with the changes. I will review the changes offline and I will bring up bugs if at all I find any. Apologies for the delayed response.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "sodonnel (via GitHub)" <gi...@apache.org>.
sodonnel commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r2463013208


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -504,6 +516,65 @@ private XceiverClientReply sendCommandWithRetry(
     }
   }
 
+  /**
+   * Starts a streaming read operation, intended to read entire blocks from the datanodes. This method expects a
+   * {@link StreamObserver} to be passed in, which will be used to receive the streamed data from the datanode.
+   * Upon successfully starting the streaming read, a {@link StreamingReadResponse} is returned, which contains
+   * information about the datanode used for the read, and the request observer that can be used to manage the stream
+   * (e.g., to cancel it if needed). A semaphore is acquired to limit the number of concurrent streaming reads so upon
+   * successful return of this method, the caller must ensure to call {@link #completeStreamRead(StreamingReadResponse)}
+   * to release the semaphore once the streaming read is complete.
+   * @param request The container command request to initiate the streaming read.
+   * @param streamObserver The observer that will handle the streamed responses.
+   * @return A {@link StreamingReadResponse} containing details of the streaming read operation.
+   * @throws IOException
+   * @throws InterruptedException
+   */
+  @Override
+  public StreamingReadResponse streamRead(ContainerCommandRequestProto request,
+      StreamObserver<ContainerCommandResponseProto> streamObserver) throws IOException, InterruptedException {
+    List<DatanodeDetails> datanodeList = sortDatanodes(request);
+    IOException lastException = null;
+    for (DatanodeDetails dn : datanodeList) {
+      try {
+        checkOpen(dn);
+        semaphore.acquire();
+        XceiverClientProtocolServiceStub stub = asyncStubs.get(dn.getID());
+        if (stub == null) {
+          throw new IOException("Failed to get gRPC stub for DataNode: " + dn);
+        }
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("Executing command {} on datanode {}", processForDebug(request), dn);
+        }
+        StreamObserver<ContainerCommandRequestProto> requestObserver = stub
+            .withDeadlineAfter(timeout, TimeUnit.SECONDS)
+            .send(streamObserver);
+        requestObserver.onNext(request);
+        requestObserver.onCompleted();
+        return new StreamingReadResponse(dn, (ClientCallStreamObserver<ContainerCommandRequestProto>) requestObserver);

Review Comment:
   The approach used is similar to the HDFS xceiver approach, where an open file on the client ties to an open file on the server. This leads to relatively simple code on the server side, only needing to open the block file once and could allow for fadvise type things about readahead if we wanted in the future. If this approach is used, we will need to greatly increase the datanode handler pool size, but this seems to work well on HDFS where it is common to allow between 4k - 32k xceivers in extreme circumstances.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r2461180608


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -504,6 +516,65 @@ private XceiverClientReply sendCommandWithRetry(
     }
   }
 
+  /**
+   * Starts a streaming read operation, intended to read entire blocks from the datanodes. This method expects a
+   * {@link StreamObserver} to be passed in, which will be used to receive the streamed data from the datanode.
+   * Upon successfully starting the streaming read, a {@link StreamingReadResponse} is returned, which contains
+   * information about the datanode used for the read, and the request observer that can be used to manage the stream
+   * (e.g., to cancel it if needed). A semaphore is acquired to limit the number of concurrent streaming reads so upon
+   * successful return of this method, the caller must ensure to call {@link #completeStreamRead(StreamingReadResponse)}
+   * to release the semaphore once the streaming read is complete.
+   * @param request The container command request to initiate the streaming read.
+   * @param streamObserver The observer that will handle the streamed responses.
+   * @return A {@link StreamingReadResponse} containing details of the streaming read operation.
+   * @throws IOException
+   * @throws InterruptedException
+   */
+  @Override
+  public StreamingReadResponse streamRead(ContainerCommandRequestProto request,
+      StreamObserver<ContainerCommandResponseProto> streamObserver) throws IOException, InterruptedException {
+    List<DatanodeDetails> datanodeList = sortDatanodes(request);
+    IOException lastException = null;
+    for (DatanodeDetails dn : datanodeList) {
+      try {
+        checkOpen(dn);
+        semaphore.acquire();
+        XceiverClientProtocolServiceStub stub = asyncStubs.get(dn.getID());
+        if (stub == null) {
+          throw new IOException("Failed to get gRPC stub for DataNode: " + dn);
+        }
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("Executing command {} on datanode {}", processForDebug(request), dn);
+        }
+        StreamObserver<ContainerCommandRequestProto> requestObserver = stub
+            .withDeadlineAfter(timeout, TimeUnit.SECONDS)
+            .send(streamObserver);
+        requestObserver.onNext(request);
+        requestObserver.onCompleted();
+        return new StreamingReadResponse(dn, (ClientCallStreamObserver<ContainerCommandRequestProto>) requestObserver);

Review Comment:
   > However its still not clear to me if I need to call onComplete()  ...
   
   It should not be.   If we call `onComplete()` right after `onNext()`, a gRPC stream can only send one request with a fixed length.  Then, a stream won't be able to support multiple read below or it has to read the entire blocks all the time.
   
   Suppose A block has 128 MB.
   - Case 1
   1. A client application opens the file.
   2. It calls read() with 10KB initially
   3. It calls read() with 50MB more.
   4. ...  // the client could call read() any number of times with an arbitrary length.
   
   - Case 2
   1. A client application opens the file.
   2. It calls read() with 10KB.
   3. It leaves the file open for 1 minute.
   4. It closes the file.
   
   If we only have one request per stream, how to set the data length for both cases?   If we read the entire block all the time, Case 2 is inefficient. Otherwise, we don't read the entire block.  Then, it has to open multiple gRPC streams for case 1.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "fenixjin (via GitHub)" <gi...@apache.org>.
fenixjin commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-2406530881

   > Test conducted on our cluster(3DN / HDD / 10 Gigabit network) shows this improvement can boost read speed by at least 30%.
   
   In single thread read, stream read cut read time from 7.3 - 7.4s to 4.8 - 5.2s.
   In freon ozone-client-one-key-reader test, stream read increased read bandwidth from 427MB/s to 586MB/s.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "ChenSammi (via GitHub)" <gi...@apache.org>.
ChenSammi commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1866997718


##########
hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/scm/storage/ContainerProtocolCalls.java:
##########
@@ -874,4 +876,57 @@ public static List<Validator> toValidatorList(Validator validator) {
     return datanodeToResponseMap;
   }
 
+  /**
+   * Calls the container protocol to read a chunk.
+   *
+   * @param xceiverClient  client to perform call
+   * @param blockID        ID of the block
+   * @param validators     functions to validate the response
+   * @param token          a token for this block (may be null)
+   * @return container protocol read chunk response
+   * @throws IOException if there is an I/O error while performing the call
+   */
+  @SuppressWarnings("checkstyle:ParameterNumber")
+  public static ContainerProtos.ReadBlockResponseProto readBlock(
+      XceiverClientSpi xceiverClient, long offset, long len, BlockID blockID,

Review Comment:
   offset and len are missing in javadoc. 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "chungen0126 (via GitHub)" <gi...@apache.org>.
chungen0126 commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1792354197


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/StreamBlockInput.java:
##########
@@ -0,0 +1,777 @@
+/*
+ * 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 com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
+import org.apache.commons.lang3.NotImplementedException;
+import org.apache.hadoop.fs.ByteBufferReadable;
+import org.apache.hadoop.fs.CanUnbuffer;
+import org.apache.hadoop.fs.Seekable;
+import org.apache.hadoop.hdds.client.BlockID;
+import org.apache.hadoop.hdds.client.StandaloneReplicationConfig;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadChunkResponseProto;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadBlockResponseProto;
+import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
+import org.apache.hadoop.hdds.scm.OzoneClientConfig;
+import org.apache.hadoop.hdds.scm.XceiverClientFactory;
+import org.apache.hadoop.hdds.scm.XceiverClientSpi;
+import org.apache.hadoop.hdds.scm.client.HddsClientUtils;
+import org.apache.hadoop.hdds.scm.container.common.helpers.StorageContainerException;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.hdds.security.exception.SCMSecurityException;
+import org.apache.hadoop.hdds.security.token.OzoneBlockTokenIdentifier;
+import org.apache.hadoop.io.retry.RetryPolicy;
+import org.apache.hadoop.ozone.common.Checksum;
+import org.apache.hadoop.ozone.common.ChecksumData;
+import org.apache.hadoop.ozone.common.OzoneChecksumException;
+import org.apache.hadoop.ozone.common.utils.BufferUtils;
+import org.apache.hadoop.security.token.Token;
+import org.apache.ratis.thirdparty.com.google.protobuf.ByteString;
+import org.apache.ratis.thirdparty.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.EOFException;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+
+import static org.apache.hadoop.hdds.client.ReplicationConfig.getLegacyFactor;
+
+/**
+ * An {@link java.io.InputStream} called from KeyInputStream to read a block from the
+ * container.
+ */
+public class StreamBlockInput extends BlockExtendedInputStream
+    implements Seekable, CanUnbuffer, ByteBufferReadable {
+  private static final Logger LOG =
+      LoggerFactory.getLogger(StreamBlockInput.class);
+  private final BlockID blockID;
+  private final long length;
+  private final AtomicReference<Pipeline> pipelineRef =
+      new AtomicReference<>();
+  private final AtomicReference<Token<OzoneBlockTokenIdentifier>> tokenRef =
+      new AtomicReference<>();
+  private XceiverClientFactory xceiverClientFactory;
+  private XceiverClientSpi xceiverClient;
+
+  private List<Long> bufferoffsets;
+  private int bufferIndex;
+  private long blockPosition = -1;
+  private List<ByteBuffer> buffers;
+  private boolean allocated = false;
+  private long bufferOffsetWrtBlockDataData;
+  private long buffersSize;
+  private static final int EOF = -1;
+  private final List<XceiverClientSpi.Validator> validators;
+  private final boolean verifyChecksum;
+  private final Function<BlockID, BlockLocationInfo> refreshFunction;
+  private final RetryPolicy retryPolicy;
+  private int retries;
+
+
+  public StreamBlockInput(
+      BlockID blockID, long length, Pipeline pipeline,
+      Token<OzoneBlockTokenIdentifier> token,
+      XceiverClientFactory xceiverClientFactory,
+      Function<BlockID, BlockLocationInfo> refreshFunction,
+      OzoneClientConfig config) throws IOException {
+    this.blockID = blockID;
+    LOG.debug("Initializing StreamBlockInput for block {}", blockID);
+    this.length = length;
+    setPipeline(pipeline);
+    tokenRef.set(token);
+    this.xceiverClientFactory = xceiverClientFactory;
+    this.validators = ContainerProtocolCalls.toValidatorList(
+        (request, response) -> validateBlock(response));
+    this.verifyChecksum = config.isChecksumVerify();
+    this.refreshFunction = refreshFunction;
+    this.retryPolicy =
+        HddsClientUtils.createRetryPolicy(config.getMaxReadRetryCount(),
+            TimeUnit.SECONDS.toMillis(config.getReadRetryInterval()));
+
+  }
+
+
+  public BlockID getBlockID() {
+    return blockID;
+  }
+
+  public long getLength() {
+    return length;
+  }
+
+  @Override
+  public synchronized long getPos() {
+    if (length == 0) {
+      return 0;
+    }
+    if (blockPosition >= 0) {
+      return blockPosition;
+    }
+
+    if (allocated && !buffersHaveData() && !dataRemainingInBlock()) {
+      Preconditions.checkState(
+          bufferOffsetWrtBlockDataData + buffersSize == length,
+          "EOF detected but not at the last byte of the chunk");
+      return length;
+    }
+    if (buffersHaveData()) {
+      // BufferOffset w.r.t to BlockData + BufferOffset w.r.t buffers +
+      // Position of current Buffer
+      return bufferOffsetWrtBlockDataData + bufferoffsets.get(bufferIndex) +
+          buffers.get(bufferIndex).position();
+    }
+    if (buffersAllocated()) {
+      return bufferOffsetWrtBlockDataData + buffersSize;
+    }
+    return 0;
+  }
+
+  @Override
+  public synchronized int read() throws IOException {
+    checkOpen();
+
+    int dataout = EOF;
+    int len = 1;
+    int available;
+    while (len > 0) {
+      try {
+        acquireClient();
+        available = prepareRead(1);
+        retries = 0;
+      } catch (SCMSecurityException ex) {
+        throw ex;
+      } catch (StorageContainerException e) {
+        if (shouldRetryRead(e)) {
+          releaseClient();
+          refreshBlockInfo(e);
+          continue;
+        } else {
+          throw e;
+        }
+      } catch (IOException ioe) {
+        if (shouldRetryRead(ioe)) {
+          if (isConnectivityIssue(ioe)) {
+            releaseClient();
+            refreshBlockInfo(ioe);
+          } else {
+            releaseClient();
+          }
+          continue;
+        } else {
+          throw ioe;
+        }
+      }
+      if (available == EOF) {
+        // There is no more data in the chunk stream. The buffers should have
+        // been released by now
+        Preconditions.checkState(buffers == null);
+      } else {
+        dataout = Byte.toUnsignedInt(buffers.get(bufferIndex).get());
+      }
+
+      len -= available;
+      if (bufferEOF()) {
+        releaseBuffers(bufferIndex);
+      }
+    }
+
+
+    return dataout;
+
+
+  }
+
+  @Override
+  public synchronized int read(byte[] b, int off, int len) throws IOException {
+    // According to the JavaDocs for InputStream, it is recommended that
+    // subclasses provide an override of bulk read if possible for performance
+    // reasons.  In addition to performance, we need to do it for correctness
+    // reasons.  The Ozone REST service uses PipedInputStream and
+    // PipedOutputStream to relay HTTP response data between a Jersey thread and
+    // a Netty thread.  It turns out that PipedInputStream/PipedOutputStream
+    // have a subtle dependency (bug?) on the wrapped stream providing separate
+    // implementations of single-byte read and bulk read.  Without this, get key
+    // responses might close the connection before writing all of the bytes
+    // advertised in the Content-Length.
+    if (b == null) {
+      throw new NullPointerException();
+    }
+    if (off < 0 || len < 0 || len > b.length - off) {
+      throw new IndexOutOfBoundsException();
+    }
+    if (len == 0) {
+      return 0;
+    }
+    int total = 0;
+    int available;
+    while (len > 0) {
+      try {
+        acquireClient();
+        available = prepareRead(len);
+        retries = 0;
+      } catch (SCMSecurityException ex) {
+        throw ex;
+      } catch (StorageContainerException e) {
+        if (shouldRetryRead(e)) {
+          releaseClient();
+          refreshBlockInfo(e);
+          continue;
+        } else {
+          throw e;
+        }
+      } catch (IOException ioe) {
+        if (shouldRetryRead(ioe)) {
+          if (isConnectivityIssue(ioe)) {
+            releaseClient();
+            refreshBlockInfo(ioe);
+          } else {
+            releaseClient();
+          }
+          continue;
+        } else {
+          throw ioe;
+        }
+      }
+      if (available == EOF) {
+        // There is no more data in the block stream. The buffers should have
+        // been released by now
+        Preconditions.checkState(buffers == null);
+        return total != 0 ? total : EOF;
+      }
+      buffers.get(bufferIndex).get(b, off + total, available);
+      len -= available;
+      total += available;
+
+      if (bufferEOF()) {
+        releaseBuffers(bufferIndex);
+      }
+    }
+    return total;
+
+  }
+
+  @Override
+  public synchronized void close() throws IOException {
+    releaseClient();
+    releaseBuffers();
+    xceiverClientFactory = null;
+  }
+
+  @Override
+  public synchronized int read(ByteBuffer byteBuffer) throws IOException {
+    if (byteBuffer == null) {
+      throw new NullPointerException();
+    }
+    int len = byteBuffer.remaining();
+    if (len == 0) {
+      return 0;
+    }
+    int total = 0;
+    int available;
+    while (len > 0) {
+      try {
+        acquireClient();
+        available = prepareRead(len);
+        retries = 0;
+      } catch (SCMSecurityException ex) {
+        throw ex;
+      } catch (StorageContainerException e) {
+        if (shouldRetryRead(e)) {
+          releaseClient();
+          refreshBlockInfo(e);
+          continue;
+        } else {
+          throw e;
+        }
+      } catch (IOException ioe) {
+        if (shouldRetryRead(ioe)) {
+          if (isConnectivityIssue(ioe)) {
+            releaseClient();
+            refreshBlockInfo(ioe);
+          } else {
+            releaseClient();
+          }
+          continue;
+        } else {
+          throw ioe;
+        }
+      }
+      if (available == EOF) {
+        // There is no more data in the block stream. The buffers should have
+        // been released by now
+        Preconditions.checkState(buffers == null);
+        return total != 0 ? total : EOF;
+      }
+      ByteBuffer readBuf = buffers.get(bufferIndex);
+      ByteBuffer tmpBuf = readBuf.duplicate();
+      tmpBuf.limit(tmpBuf.position() + available);
+      byteBuffer.put(tmpBuf);
+      readBuf.position(tmpBuf.position());
+
+      len -= available;
+      total += available;
+
+      if (bufferEOF()) {
+        releaseBuffers(bufferIndex);
+      }
+    }
+    return total;
+  }
+
+  @Override
+  protected int readWithStrategy(ByteReaderStrategy strategy) throws IOException {
+    throw new NotImplementedException("readWithStrategy is not implemented.");
+  }
+
+  @Override
+  public synchronized void seek(long pos) throws IOException {
+    if (pos < 0 || pos > length) {
+      if (pos == 0) {
+        // It is possible for length and pos to be zero in which case
+        // seek should return instead of throwing exception
+        return;
+      }
+      throw new EOFException("EOF encountered at pos: " + pos + " for block: " + blockID);
+    }
+
+    if (buffersHavePosition(pos)) {
+      // The bufferPosition is w.r.t the current block.
+      // Adjust the bufferIndex and position to the seeked position.
+      adjustBufferPosition(pos - bufferOffsetWrtBlockDataData);
+    } else {
+      blockPosition = pos;
+    }
+  }
+
+  @Override
+  public synchronized boolean seekToNewSource(long l) throws IOException {
+    return false;
+  }
+
+  @Override
+  public synchronized void unbuffer() {
+    blockPosition = getPos();
+    releaseClient();
+    releaseBuffers();
+  }
+
+  private void setPipeline(Pipeline pipeline) throws IOException {
+    if (pipeline == null) {
+      return;
+    }
+    long replicaIndexes = pipeline.getNodes().stream().mapToInt(pipeline::getReplicaIndex).distinct().count();
+
+    if (replicaIndexes > 1) {
+      throw new IOException(String.format("Pipeline: %s has nodes containing different replica indexes.",
+          pipeline));
+    }
+
+    // irrespective of the container state, we will always read via Standalone
+    // protocol.
+    boolean okForRead =
+        pipeline.getType() == HddsProtos.ReplicationType.STAND_ALONE
+            || pipeline.getType() == HddsProtos.ReplicationType.EC;
+    Pipeline readPipeline = okForRead ? pipeline : Pipeline.newBuilder(pipeline)
+        .setReplicationConfig(StandaloneReplicationConfig.getInstance(
+            getLegacyFactor(pipeline.getReplicationConfig())))
+        .build();
+    pipelineRef.set(readPipeline);
+  }
+
+  protected synchronized void checkOpen() throws IOException {
+    if (xceiverClientFactory == null) {
+      throw new IOException("BlockInputStream has been closed.");
+    }
+  }
+
+  protected synchronized void acquireClient() throws IOException {
+    if (xceiverClientFactory != null && xceiverClient == null) {

Review Comment:
   done



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "chungen0126 (via GitHub)" <gi...@apache.org>.
chungen0126 commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1792381328


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/StreamBlockInput.java:
##########
@@ -0,0 +1,777 @@
+/*
+ * 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 com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
+import org.apache.commons.lang3.NotImplementedException;
+import org.apache.hadoop.fs.ByteBufferReadable;
+import org.apache.hadoop.fs.CanUnbuffer;
+import org.apache.hadoop.fs.Seekable;
+import org.apache.hadoop.hdds.client.BlockID;
+import org.apache.hadoop.hdds.client.StandaloneReplicationConfig;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadChunkResponseProto;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadBlockResponseProto;
+import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
+import org.apache.hadoop.hdds.scm.OzoneClientConfig;
+import org.apache.hadoop.hdds.scm.XceiverClientFactory;
+import org.apache.hadoop.hdds.scm.XceiverClientSpi;
+import org.apache.hadoop.hdds.scm.client.HddsClientUtils;
+import org.apache.hadoop.hdds.scm.container.common.helpers.StorageContainerException;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.hdds.security.exception.SCMSecurityException;
+import org.apache.hadoop.hdds.security.token.OzoneBlockTokenIdentifier;
+import org.apache.hadoop.io.retry.RetryPolicy;
+import org.apache.hadoop.ozone.common.Checksum;
+import org.apache.hadoop.ozone.common.ChecksumData;
+import org.apache.hadoop.ozone.common.OzoneChecksumException;
+import org.apache.hadoop.ozone.common.utils.BufferUtils;
+import org.apache.hadoop.security.token.Token;
+import org.apache.ratis.thirdparty.com.google.protobuf.ByteString;
+import org.apache.ratis.thirdparty.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.EOFException;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+
+import static org.apache.hadoop.hdds.client.ReplicationConfig.getLegacyFactor;
+
+/**
+ * An {@link java.io.InputStream} called from KeyInputStream to read a block from the
+ * container.
+ */
+public class StreamBlockInput extends BlockExtendedInputStream
+    implements Seekable, CanUnbuffer, ByteBufferReadable {
+  private static final Logger LOG =
+      LoggerFactory.getLogger(StreamBlockInput.class);
+  private final BlockID blockID;
+  private final long length;
+  private final AtomicReference<Pipeline> pipelineRef =
+      new AtomicReference<>();
+  private final AtomicReference<Token<OzoneBlockTokenIdentifier>> tokenRef =
+      new AtomicReference<>();
+  private XceiverClientFactory xceiverClientFactory;
+  private XceiverClientSpi xceiverClient;
+
+  private List<Long> bufferoffsets;
+  private int bufferIndex;
+  private long blockPosition = -1;
+  private List<ByteBuffer> buffers;
+  private boolean allocated = false;
+  private long bufferOffsetWrtBlockDataData;

Review Comment:
   done



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "chungen0126 (via GitHub)" <gi...@apache.org>.
chungen0126 commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1792383957


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/ozone/client/io/BlockInputStreamFactoryImpl.java:
##########
@@ -86,11 +89,27 @@ public BlockExtendedInputStream create(ReplicationConfig repConfig,
       return new ECBlockInputStreamProxy((ECReplicationConfig)repConfig,
           blockInfo, xceiverFactory, refreshFunction,
           ecBlockStreamFactory, config);
+    } else if (config.isStreamReadBlock() && allDataNodesSupportStreamBlock(pipeline)) {
+      return new StreamBlockInput(
+          blockInfo.getBlockID(), blockInfo.getLength(),
+          pipeline, token, xceiverFactory, refreshFunction, config);
     } else {
       return new BlockInputStream(blockInfo,
           pipeline, token, xceiverFactory, refreshFunction,
           config);
     }
   }
 
+  private boolean allDataNodesSupportStreamBlock(Pipeline pipeline) {
+    // return true only if all DataNodes in the pipeline are on a version
+    // that supports for reading a block by streaming chunks..
+    for (DatanodeDetails dn : pipeline.getNodes()) {
+      if (dn.getCurrentVersion() <
+          STEAM_BLOCK_SUPPORT.toProtoValue()) {

Review Comment:
   done



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "chungen0126 (via GitHub)" <gi...@apache.org>.
chungen0126 commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1792465132


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -618,6 +625,71 @@ private void decreasePendingMetricsAndReleaseSemaphore() {
     return new XceiverClientReply(replyFuture);
   }
 
+  public XceiverClientReply sendCommandAsyncReadOnly(
+      ContainerCommandRequestProto request, DatanodeDetails dn)
+      throws IOException, InterruptedException {
+
+    CompletableFuture<ContainerCommandResponseProto> future =
+        new CompletableFuture<>();
+    ContainerCommandResponseProto.Builder response =
+        ContainerCommandResponseProto.newBuilder();
+    ContainerProtos.ReadBlockResponseProto.Builder readBlock =
+        ContainerProtos.ReadBlockResponseProto.newBuilder();
+    checkOpen(dn);
+    UUID dnID = dn.getUuid();
+    Type cmdType = request.getCmdType();
+    semaphore.acquire();
+    long requestTime = System.currentTimeMillis();
+    metrics.incrPendingContainerOpsMetrics(cmdType);
+
+    final StreamObserver<ContainerCommandRequestProto> requestObserver =
+        asyncStubs.get(dnID).withDeadlineAfter(timeout, TimeUnit.SECONDS)
+            .send(new StreamObserver<ContainerCommandResponseProto>() {
+              @Override
+              public void onNext(
+                  ContainerCommandResponseProto responseProto) {
+                ReadChunkResponseProto readChunk =
+                    responseProto.getReadChunk();
+                if (responseProto.getResult() == Result.SUCCESS) {
+                  readBlock.addReadChunk(readChunk);
+                } else {
+                  future.complete(
+                      ContainerCommandResponseProto.newBuilder(responseProto)
+                          .setCmdType(Type.StreamRead).build());
+                }
+              }
+
+              @Override
+              public void onError(Throwable t) {
+                future.completeExceptionally(t);
+                metrics.decrPendingContainerOpsMetrics(cmdType);
+                metrics.addContainerOpsLatency(
+                    cmdType, System.currentTimeMillis() - requestTime);
+
+              }
+
+              @Override
+              public void onCompleted() {
+                if (readBlock.getReadChunkCount() > 0) {
+                  future.complete(response.setReadBlock(readBlock)
+                      .setCmdType(Type.StreamRead).setResult(Result.SUCCESS).build());
+                }
+                if (!future.isDone()) {
+                  future.completeExceptionally(new IOException(
+                      "Stream completed but no reply for request " +
+                          processForDebug(request)));
+                }

Review Comment:
   No, we should check the readBlock first. The `future.isDone()` depends on if there are responses and they will be collected by `readBlock`



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "chungen0126 (via GitHub)" <gi...@apache.org>.
chungen0126 commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1792314812


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -618,6 +625,71 @@ private void decreasePendingMetricsAndReleaseSemaphore() {
     return new XceiverClientReply(replyFuture);
   }
 
+  public XceiverClientReply sendCommandAsyncReadOnly(
+      ContainerCommandRequestProto request, DatanodeDetails dn)
+      throws IOException, InterruptedException {
+
+    CompletableFuture<ContainerCommandResponseProto> future =
+        new CompletableFuture<>();
+    ContainerCommandResponseProto.Builder response =
+        ContainerCommandResponseProto.newBuilder();
+    ContainerProtos.ReadBlockResponseProto.Builder readBlock =
+        ContainerProtos.ReadBlockResponseProto.newBuilder();
+    checkOpen(dn);
+    UUID dnID = dn.getUuid();
+    Type cmdType = request.getCmdType();
+    semaphore.acquire();
+    long requestTime = System.currentTimeMillis();
+    metrics.incrPendingContainerOpsMetrics(cmdType);
+
+    final StreamObserver<ContainerCommandRequestProto> requestObserver =
+        asyncStubs.get(dnID).withDeadlineAfter(timeout, TimeUnit.SECONDS)
+            .send(new StreamObserver<ContainerCommandResponseProto>() {
+              @Override
+              public void onNext(
+                  ContainerCommandResponseProto responseProto) {
+                ReadChunkResponseProto readChunk =
+                    responseProto.getReadChunk();
+                if (responseProto.getResult() == Result.SUCCESS) {
+                  readBlock.addReadChunk(readChunk);
+                } else {
+                  future.complete(
+                      ContainerCommandResponseProto.newBuilder(responseProto)
+                          .setCmdType(Type.StreamRead).build());
+                }
+              }
+
+              @Override
+              public void onError(Throwable t) {
+                future.completeExceptionally(t);
+                metrics.decrPendingContainerOpsMetrics(cmdType);
+                metrics.addContainerOpsLatency(
+                    cmdType, System.currentTimeMillis() - requestTime);
+
+              }
+
+              @Override
+              public void onCompleted() {
+                if (readBlock.getReadChunkCount() > 0) {
+                  future.complete(response.setReadBlock(readBlock)
+                      .setCmdType(Type.StreamRead).setResult(Result.SUCCESS).build());
+                }
+                if (!future.isDone()) {
+                  future.completeExceptionally(new IOException(
+                      "Stream completed but no reply for request " +
+                          processForDebug(request)));
+                }

Review Comment:
   done



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "fenixjin (via GitHub)" <gi...@apache.org>.
fenixjin commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-2343032609

   I wonder if this patch is completed, we wish to test this on our environment.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "sodonnel (via GitHub)" <gi...@apache.org>.
sodonnel commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-3330400999

   > I change this part in a commit before, mistakenly thinking that this was the correct way to write it.
   
   This was a difficult part. I am not sure I have fixed it the best way, but it was the only way I could think of to do it safely.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-3354415164

   @chungen0126 , thanks a lot for working on this!  Looked at the existing code vs this change and had the following observations:
   
   ---
   
   Current with readChunk code:
   - Server side slowness:
   ⚠️ In the ChunkUtils code, we open and close the local file for each chunk.  It will be slow for large files.
   
   - Client side slowness:
   ⚠️ readChunk(..) -> XceiverClientSpi.sendCommand(..) -> XceiverClientGrpc.sendCommandAsync(..) but XceiverClientSpi.sendCommand(..) will wait for the future for each chunk (i.e. it is NOT aysnc)
   ⚠️ In XceiverClientGrpc.sendCommandAsync(..) , we create a new gRPC stream, read a chunk and then close it.
   
   ---
   
   This pull request:
   - Server side:
   ⚠️ Still using ChunkUtils and open/close the local file for each chunk.
   
   - Client side:
   ✅ Using gRPC async stream (i.e. it is real async)
   ½✅ sendCommandReadBlock(..) only creates a gRPC stream per read(..) call (not a single stream per block)
   
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "sodonnel (via GitHub)" <gi...@apache.org>.
sodonnel commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-3329886293

   I've merged in master and added a commit which fixes the checksum issue by passing the chunk block offset back to the client in the chunkInfo proto. The code as it stands with these changes works in my above test with a 1GB file.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "sodonnel (via GitHub)" <gi...@apache.org>.
sodonnel commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-3481813143

   > Not sure about you question. Here is an example:
   > 
   >     * Client: opens the block and requests with 10KB.
   >       Client: sends an onNext() request with 10KB.
   >       Server: Since this is the first request, it opens the file.
   >       Server: invokes a readChunk call to read 1MB (rounding up the chunk boundary)
   >       Server: sends an onNext() response with 1MB data.
   
   After here, and the next 1MB read, the server will have released the handler thread and hence all the context it had including the open file. The default checksum size in Ozone is 16kb. So for a client reading into 4kb buffers, which is what I have seen happen, will result in many calls coming from the client for onNext, and the server having to re-establish context for each one. This is why I believe the performance with this suggestion will not be good.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-3481859230

   > 1. Acquire a thread
   > ...
   > 6. Release the thread back to the pool
   
   > ...  The default checksum size in Ozone is 16kb. So for a client reading into 4kb buffers, ... the server will have released the handler thread ...
    
   The server always reads at least 1MB (not 16kb, not 4kb) for each onNext() calls.  It can read more if the request length is larger as below. 
   - Server: loop 50 times below in onNext()
   (a) invokes a readChunk call to read 1MB
   (b) sends an onNext() response with 1MB data.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "sodonnel (via GitHub)" <gi...@apache.org>.
sodonnel commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-3472602945

   > When a datanode receives onNext(L)
   > 
   >     * Open the file if it is the first call.
   > 
   >     * Read the file at least L bytes of data.
   > 
   >     * It could read up to checksum/chunk boundary, or even a few chunks more for pre-read.
   > 
   >     * Return the data by one or more onNext() responses.
   
   How is this going to look on the server? If the server gives up its handler thread after sending each piece of the block to the client then for each onNext() from the client, its going to have to:
   
   1. Acquire a thread
   2. Lookup RocksDB for the checksum and block meta data
   3. Calculate various offsets etc to align the checksums.
   4. Open the block file, seek
   5. Read the desired amount and close the file
   6. Release the thread back to the pool
   
   My observations is that for most calls, these client reads are not "50MB" or anything like it. They are generally 4kb, and get rounded up to the next checksum boundary. So 16kb by default. So to read the 256MB block we are going to have to do the above 16k times. This cannot be efficient for something which is trying to read a block from start to end.
   
   While this is an async API, from the clients point of view its blocking. The client needs more data and it has to wait for it to arrive. With the streaming approach I have implemented in this PR, the data is queuing up to a reasonable limit on the socket and as the client needs it, it will be immediately available usually and avoids the rework if initializing the read each time.
   
   With the approach you are describing, compared to the approach used in Ozone today, it is just keeping the GRPC stream alive. Its still a very chatty back and forward protocol passing small pieces of data and I don't see how it is going to drastically improve things due to the amount of rework required for each tiny read.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-3559548839

   1. Changed a single response to contain multiple checksums: bytesPerChecksum only affects the performance slightly.  Even 512 bytesPerChecksum can get good performance. 
   2. Added pre-read supported: the client buffer size does not matter .
   
   - 512 bytesPerChecksum
   ```
   XXX ---------------------------------------------------------
   XXX key4 with 1G (=1073741824) bytes and 512 bytesPerChecksum
   XXX  createStreamKey:   142.14 MB/s (  7.204 s, buffer   8MB (=8388608), keySize  1024.00 MB, md5=61 17 A5 9D AD F1 E1 DD 3B 3D 37 E3 2B 6A 5A 4C)
   XXX    readStreamKey:  2622.17 MB/s (  0.391 s, buffer       4k (=4096), keySize  1024.00 MB, md5=null)
   XXX    readStreamKey:   767.54 MB/s (  1.334 s, buffer       4k (=4096), keySize  1024.00 MB, md5=61 17 A5 9D AD F1 E1 DD 3B 3D 37 E3 2B 6A 5A 4C)
   XXX    readStreamKey:  2659.68 MB/s (  0.385 s, buffer    1M (=1048576), keySize  1024.00 MB, md5=null)
   XXX    readStreamKey:   762.32 MB/s (  1.343 s, buffer    1M (=1048576), keySize  1024.00 MB, md5=61 17 A5 9D AD F1 E1 DD 3B 3D 37 E3 2B 6A 5A 4C)
   XXX    readStreamKey:  2668.96 MB/s (  0.384 s, buffer    8M (=8388608), keySize  1024.00 MB, md5=null)
   XXX    readStreamKey:   727.99 MB/s (  1.407 s, buffer    8M (=8388608), keySize  1024.00 MB, md5=61 17 A5 9D AD F1 E1 DD 3B 3D 37 E3 2B 6A 5A 4C)
   XXX    readStreamKey:  2720.65 MB/s (  0.376 s, buffer  32M (=33554432), keySize  1024.00 MB, md5=null)
   XXX    readStreamKey:   680.19 MB/s (  1.505 s, buffer  32M (=33554432), keySize  1024.00 MB, md5=61 17 A5 9D AD F1 E1 DD 3B 3D 37 E3 2B 6A 5A 4C)
   ```
   - 256k bytesPerChecksum
   ```
   XXX ---------------------------------------------------------
   XXX key3 with 1G (=1073741824) bytes and 256k (=262144) bytesPerChecksum
   XXX  createStreamKey:   145.81 MB/s (  7.023 s, buffer   8MB (=8388608), keySize  1024.00 MB, md5=5B 98 A8 2B 30 74 F2 C7 40 59 9B D9 98 8E 59 9C)
   XXX    readStreamKey:  2769.22 MB/s (  0.370 s, buffer       4k (=4096), keySize  1024.00 MB, md5=null)
   XXX    readStreamKey:   780.02 MB/s (  1.313 s, buffer       4k (=4096), keySize  1024.00 MB, md5=5B 98 A8 2B 30 74 F2 C7 40 59 9B D9 98 8E 59 9C)
   XXX    readStreamKey:  2726.07 MB/s (  0.376 s, buffer    1M (=1048576), keySize  1024.00 MB, md5=null)
   XXX    readStreamKey:   778.18 MB/s (  1.316 s, buffer    1M (=1048576), keySize  1024.00 MB, md5=5B 98 A8 2B 30 74 F2 C7 40 59 9B D9 98 8E 59 9C)
   XXX    readStreamKey:  2786.75 MB/s (  0.367 s, buffer    8M (=8388608), keySize  1024.00 MB, md5=null)
   XXX    readStreamKey:   736.60 MB/s (  1.390 s, buffer    8M (=8388608), keySize  1024.00 MB, md5=5B 98 A8 2B 30 74 F2 C7 40 59 9B D9 98 8E 59 9C)
   XXX    readStreamKey:  2810.36 MB/s (  0.364 s, buffer  32M (=33554432), keySize  1024.00 MB, md5=null)
   XXX    readStreamKey:   699.14 MB/s (  1.465 s, buffer  32M (=33554432), keySize  1024.00 MB, md5=5B 98 A8 2B 30 74 F2 C7 40 59 9B D9 98 8E 59 9C)
   ```


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r2461180608


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -504,6 +516,65 @@ private XceiverClientReply sendCommandWithRetry(
     }
   }
 
+  /**
+   * Starts a streaming read operation, intended to read entire blocks from the datanodes. This method expects a
+   * {@link StreamObserver} to be passed in, which will be used to receive the streamed data from the datanode.
+   * Upon successfully starting the streaming read, a {@link StreamingReadResponse} is returned, which contains
+   * information about the datanode used for the read, and the request observer that can be used to manage the stream
+   * (e.g., to cancel it if needed). A semaphore is acquired to limit the number of concurrent streaming reads so upon
+   * successful return of this method, the caller must ensure to call {@link #completeStreamRead(StreamingReadResponse)}
+   * to release the semaphore once the streaming read is complete.
+   * @param request The container command request to initiate the streaming read.
+   * @param streamObserver The observer that will handle the streamed responses.
+   * @return A {@link StreamingReadResponse} containing details of the streaming read operation.
+   * @throws IOException
+   * @throws InterruptedException
+   */
+  @Override
+  public StreamingReadResponse streamRead(ContainerCommandRequestProto request,
+      StreamObserver<ContainerCommandResponseProto> streamObserver) throws IOException, InterruptedException {
+    List<DatanodeDetails> datanodeList = sortDatanodes(request);
+    IOException lastException = null;
+    for (DatanodeDetails dn : datanodeList) {
+      try {
+        checkOpen(dn);
+        semaphore.acquire();
+        XceiverClientProtocolServiceStub stub = asyncStubs.get(dn.getID());
+        if (stub == null) {
+          throw new IOException("Failed to get gRPC stub for DataNode: " + dn);
+        }
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("Executing command {} on datanode {}", processForDebug(request), dn);
+        }
+        StreamObserver<ContainerCommandRequestProto> requestObserver = stub
+            .withDeadlineAfter(timeout, TimeUnit.SECONDS)
+            .send(streamObserver);
+        requestObserver.onNext(request);
+        requestObserver.onCompleted();
+        return new StreamingReadResponse(dn, (ClientCallStreamObserver<ContainerCommandRequestProto>) requestObserver);

Review Comment:
   > However its still not clear to me if I need to call onComplete()  ...
   
   It should not be.   If we call `onComplete()` right after `onNext()`, a gRPC stream can only send one request with a fixed length.  Then, a stream won't be able to support multiple read below or it has to read the entire blocks all the time.
   
   Suppose A block has 128 MB.
   - Case 1
   1. A client application opens the file.
   2. It calls read() with 10KB initially
   3. It calls read() with 50MB more.
   4. ...  // the client could call read() any number of times with an arbitrary length.
   
   - Case 2
   1. A client application opens the file.
   2. It calls read() with 10KB and then close the file.
   
   If we only have one request per stream, how to set the data length for both cases?   If we read the entire block all the time, Case 2 is inefficient. Otherwise, we don't read the entire block.  Then, it have to open multiple gRPC streams for case 1.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r2462932439


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -504,6 +516,65 @@ private XceiverClientReply sendCommandWithRetry(
     }
   }
 
+  /**
+   * Starts a streaming read operation, intended to read entire blocks from the datanodes. This method expects a
+   * {@link StreamObserver} to be passed in, which will be used to receive the streamed data from the datanode.
+   * Upon successfully starting the streaming read, a {@link StreamingReadResponse} is returned, which contains
+   * information about the datanode used for the read, and the request observer that can be used to manage the stream
+   * (e.g., to cancel it if needed). A semaphore is acquired to limit the number of concurrent streaming reads so upon
+   * successful return of this method, the caller must ensure to call {@link #completeStreamRead(StreamingReadResponse)}
+   * to release the semaphore once the streaming read is complete.
+   * @param request The container command request to initiate the streaming read.
+   * @param streamObserver The observer that will handle the streamed responses.
+   * @return A {@link StreamingReadResponse} containing details of the streaming read operation.
+   * @throws IOException
+   * @throws InterruptedException
+   */
+  @Override
+  public StreamingReadResponse streamRead(ContainerCommandRequestProto request,
+      StreamObserver<ContainerCommandResponseProto> streamObserver) throws IOException, InterruptedException {
+    List<DatanodeDetails> datanodeList = sortDatanodes(request);
+    IOException lastException = null;
+    for (DatanodeDetails dn : datanodeList) {
+      try {
+        checkOpen(dn);
+        semaphore.acquire();
+        XceiverClientProtocolServiceStub stub = asyncStubs.get(dn.getID());
+        if (stub == null) {
+          throw new IOException("Failed to get gRPC stub for DataNode: " + dn);
+        }
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("Executing command {} on datanode {}", processForDebug(request), dn);
+        }
+        StreamObserver<ContainerCommandRequestProto> requestObserver = stub
+            .withDeadlineAfter(timeout, TimeUnit.SECONDS)
+            .send(streamObserver);
+        requestObserver.onNext(request);
+        requestObserver.onCompleted();
+        return new StreamingReadResponse(dn, (ClientCallStreamObserver<ContainerCommandRequestProto>) requestObserver);

Review Comment:
   1. A client application opens the file.
   2. It calls read() with 10KB.
   3. It leaves the file open for 1 minute.  `// a gRPC thread is blocked here`
   4. It closes the file.
   
   I see how it works now -- the implementation uses a `BlockingQueue responseQueue`.  When the responses are not removed from the queue, the gRPC thread is blocked in `StreamingReader.onNext(..)` and the gRPC streaming mechanism will throttle and slow down the server side.
   
   However, the number open files will be limited by the number of gRPC threads.  Also, when all the gRPC threads are blocked, any gRPC calls will be blocked.  In an asynchronous model, threads should not blocked.  When the connection is idle at Step 3 above, it should release the thread so it can work on other calls.
   
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "chungen0126 (via GitHub)" <gi...@apache.org>.
chungen0126 commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1792383206


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/StreamBlockInput.java:
##########
@@ -0,0 +1,777 @@
+/*
+ * 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 com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
+import org.apache.commons.lang3.NotImplementedException;
+import org.apache.hadoop.fs.ByteBufferReadable;
+import org.apache.hadoop.fs.CanUnbuffer;
+import org.apache.hadoop.fs.Seekable;
+import org.apache.hadoop.hdds.client.BlockID;
+import org.apache.hadoop.hdds.client.StandaloneReplicationConfig;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadChunkResponseProto;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadBlockResponseProto;
+import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
+import org.apache.hadoop.hdds.scm.OzoneClientConfig;
+import org.apache.hadoop.hdds.scm.XceiverClientFactory;
+import org.apache.hadoop.hdds.scm.XceiverClientSpi;
+import org.apache.hadoop.hdds.scm.client.HddsClientUtils;
+import org.apache.hadoop.hdds.scm.container.common.helpers.StorageContainerException;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.hdds.security.exception.SCMSecurityException;
+import org.apache.hadoop.hdds.security.token.OzoneBlockTokenIdentifier;
+import org.apache.hadoop.io.retry.RetryPolicy;
+import org.apache.hadoop.ozone.common.Checksum;
+import org.apache.hadoop.ozone.common.ChecksumData;
+import org.apache.hadoop.ozone.common.OzoneChecksumException;
+import org.apache.hadoop.ozone.common.utils.BufferUtils;
+import org.apache.hadoop.security.token.Token;
+import org.apache.ratis.thirdparty.com.google.protobuf.ByteString;
+import org.apache.ratis.thirdparty.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.EOFException;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+
+import static org.apache.hadoop.hdds.client.ReplicationConfig.getLegacyFactor;
+
+/**
+ * An {@link java.io.InputStream} called from KeyInputStream to read a block from the
+ * container.
+ */
+public class StreamBlockInput extends BlockExtendedInputStream
+    implements Seekable, CanUnbuffer, ByteBufferReadable {
+  private static final Logger LOG =
+      LoggerFactory.getLogger(StreamBlockInput.class);
+  private final BlockID blockID;
+  private final long length;
+  private final AtomicReference<Pipeline> pipelineRef =
+      new AtomicReference<>();
+  private final AtomicReference<Token<OzoneBlockTokenIdentifier>> tokenRef =
+      new AtomicReference<>();
+  private XceiverClientFactory xceiverClientFactory;
+  private XceiverClientSpi xceiverClient;
+
+  private List<Long> bufferoffsets;
+  private int bufferIndex;
+  private long blockPosition = -1;
+  private List<ByteBuffer> buffers;
+  private boolean allocated = false;
+  private long bufferOffsetWrtBlockDataData;
+  private long buffersSize;
+  private static final int EOF = -1;
+  private final List<XceiverClientSpi.Validator> validators;
+  private final boolean verifyChecksum;
+  private final Function<BlockID, BlockLocationInfo> refreshFunction;
+  private final RetryPolicy retryPolicy;
+  private int retries;
+
+
+  public StreamBlockInput(
+      BlockID blockID, long length, Pipeline pipeline,
+      Token<OzoneBlockTokenIdentifier> token,
+      XceiverClientFactory xceiverClientFactory,
+      Function<BlockID, BlockLocationInfo> refreshFunction,
+      OzoneClientConfig config) throws IOException {
+    this.blockID = blockID;
+    LOG.debug("Initializing StreamBlockInput for block {}", blockID);
+    this.length = length;
+    setPipeline(pipeline);
+    tokenRef.set(token);
+    this.xceiverClientFactory = xceiverClientFactory;
+    this.validators = ContainerProtocolCalls.toValidatorList(
+        (request, response) -> validateBlock(response));
+    this.verifyChecksum = config.isChecksumVerify();
+    this.refreshFunction = refreshFunction;
+    this.retryPolicy =
+        HddsClientUtils.createRetryPolicy(config.getMaxReadRetryCount(),
+            TimeUnit.SECONDS.toMillis(config.getReadRetryInterval()));
+
+  }
+
+
+  public BlockID getBlockID() {
+    return blockID;
+  }
+
+  public long getLength() {
+    return length;
+  }
+
+  @Override
+  public synchronized long getPos() {
+    if (length == 0) {
+      return 0;
+    }
+    if (blockPosition >= 0) {
+      return blockPosition;
+    }
+
+    if (allocated && !buffersHaveData() && !dataRemainingInBlock()) {
+      Preconditions.checkState(
+          bufferOffsetWrtBlockDataData + buffersSize == length,
+          "EOF detected but not at the last byte of the chunk");
+      return length;
+    }
+    if (buffersHaveData()) {
+      // BufferOffset w.r.t to BlockData + BufferOffset w.r.t buffers +
+      // Position of current Buffer
+      return bufferOffsetWrtBlockDataData + bufferoffsets.get(bufferIndex) +
+          buffers.get(bufferIndex).position();
+    }
+    if (buffersAllocated()) {
+      return bufferOffsetWrtBlockDataData + buffersSize;
+    }
+    return 0;
+  }
+
+  @Override
+  public synchronized int read() throws IOException {
+    checkOpen();
+
+    int dataout = EOF;
+    int len = 1;
+    int available;
+    while (len > 0) {
+      try {
+        acquireClient();
+        available = prepareRead(1);
+        retries = 0;
+      } catch (SCMSecurityException ex) {
+        throw ex;
+      } catch (StorageContainerException e) {
+        if (shouldRetryRead(e)) {
+          releaseClient();
+          refreshBlockInfo(e);
+          continue;
+        } else {
+          throw e;
+        }
+      } catch (IOException ioe) {
+        if (shouldRetryRead(ioe)) {
+          if (isConnectivityIssue(ioe)) {
+            releaseClient();
+            refreshBlockInfo(ioe);
+          } else {
+            releaseClient();
+          }
+          continue;
+        } else {
+          throw ioe;
+        }
+      }
+      if (available == EOF) {
+        // There is no more data in the chunk stream. The buffers should have
+        // been released by now
+        Preconditions.checkState(buffers == null);
+      } else {
+        dataout = Byte.toUnsignedInt(buffers.get(bufferIndex).get());
+      }
+
+      len -= available;
+      if (bufferEOF()) {
+        releaseBuffers(bufferIndex);
+      }
+    }
+
+
+    return dataout;
+
+
+  }
+
+  @Override
+  public synchronized int read(byte[] b, int off, int len) throws IOException {
+    // According to the JavaDocs for InputStream, it is recommended that
+    // subclasses provide an override of bulk read if possible for performance
+    // reasons.  In addition to performance, we need to do it for correctness
+    // reasons.  The Ozone REST service uses PipedInputStream and
+    // PipedOutputStream to relay HTTP response data between a Jersey thread and
+    // a Netty thread.  It turns out that PipedInputStream/PipedOutputStream
+    // have a subtle dependency (bug?) on the wrapped stream providing separate
+    // implementations of single-byte read and bulk read.  Without this, get key
+    // responses might close the connection before writing all of the bytes
+    // advertised in the Content-Length.
+    if (b == null) {
+      throw new NullPointerException();
+    }
+    if (off < 0 || len < 0 || len > b.length - off) {
+      throw new IndexOutOfBoundsException();
+    }
+    if (len == 0) {
+      return 0;
+    }
+    int total = 0;
+    int available;
+    while (len > 0) {
+      try {
+        acquireClient();
+        available = prepareRead(len);
+        retries = 0;
+      } catch (SCMSecurityException ex) {
+        throw ex;
+      } catch (StorageContainerException e) {
+        if (shouldRetryRead(e)) {
+          releaseClient();
+          refreshBlockInfo(e);
+          continue;
+        } else {
+          throw e;
+        }
+      } catch (IOException ioe) {
+        if (shouldRetryRead(ioe)) {
+          if (isConnectivityIssue(ioe)) {
+            releaseClient();
+            refreshBlockInfo(ioe);
+          } else {
+            releaseClient();
+          }
+          continue;
+        } else {
+          throw ioe;
+        }
+      }
+      if (available == EOF) {
+        // There is no more data in the block stream. The buffers should have
+        // been released by now
+        Preconditions.checkState(buffers == null);
+        return total != 0 ? total : EOF;
+      }
+      buffers.get(bufferIndex).get(b, off + total, available);
+      len -= available;
+      total += available;
+
+      if (bufferEOF()) {
+        releaseBuffers(bufferIndex);
+      }
+    }
+    return total;
+
+  }
+
+  @Override
+  public synchronized void close() throws IOException {
+    releaseClient();
+    releaseBuffers();
+    xceiverClientFactory = null;
+  }
+
+  @Override
+  public synchronized int read(ByteBuffer byteBuffer) throws IOException {
+    if (byteBuffer == null) {
+      throw new NullPointerException();
+    }
+    int len = byteBuffer.remaining();
+    if (len == 0) {
+      return 0;
+    }
+    int total = 0;
+    int available;
+    while (len > 0) {
+      try {
+        acquireClient();
+        available = prepareRead(len);
+        retries = 0;
+      } catch (SCMSecurityException ex) {
+        throw ex;
+      } catch (StorageContainerException e) {
+        if (shouldRetryRead(e)) {
+          releaseClient();
+          refreshBlockInfo(e);
+          continue;
+        } else {
+          throw e;
+        }
+      } catch (IOException ioe) {
+        if (shouldRetryRead(ioe)) {
+          if (isConnectivityIssue(ioe)) {
+            releaseClient();
+            refreshBlockInfo(ioe);
+          } else {
+            releaseClient();
+          }
+          continue;
+        } else {
+          throw ioe;
+        }
+      }
+      if (available == EOF) {
+        // There is no more data in the block stream. The buffers should have
+        // been released by now
+        Preconditions.checkState(buffers == null);
+        return total != 0 ? total : EOF;
+      }
+      ByteBuffer readBuf = buffers.get(bufferIndex);
+      ByteBuffer tmpBuf = readBuf.duplicate();
+      tmpBuf.limit(tmpBuf.position() + available);
+      byteBuffer.put(tmpBuf);
+      readBuf.position(tmpBuf.position());
+
+      len -= available;
+      total += available;
+
+      if (bufferEOF()) {
+        releaseBuffers(bufferIndex);
+      }
+    }
+    return total;
+  }
+
+  @Override
+  protected int readWithStrategy(ByteReaderStrategy strategy) throws IOException {
+    throw new NotImplementedException("readWithStrategy is not implemented.");
+  }
+
+  @Override
+  public synchronized void seek(long pos) throws IOException {
+    if (pos < 0 || pos > length) {
+      if (pos == 0) {
+        // It is possible for length and pos to be zero in which case
+        // seek should return instead of throwing exception
+        return;
+      }
+      throw new EOFException("EOF encountered at pos: " + pos + " for block: " + blockID);
+    }
+
+    if (buffersHavePosition(pos)) {
+      // The bufferPosition is w.r.t the current block.
+      // Adjust the bufferIndex and position to the seeked position.
+      adjustBufferPosition(pos - bufferOffsetWrtBlockDataData);
+    } else {
+      blockPosition = pos;
+    }
+  }
+
+  @Override
+  public synchronized boolean seekToNewSource(long l) throws IOException {
+    return false;
+  }
+
+  @Override
+  public synchronized void unbuffer() {
+    blockPosition = getPos();
+    releaseClient();
+    releaseBuffers();
+  }
+
+  private void setPipeline(Pipeline pipeline) throws IOException {
+    if (pipeline == null) {
+      return;
+    }
+    long replicaIndexes = pipeline.getNodes().stream().mapToInt(pipeline::getReplicaIndex).distinct().count();
+
+    if (replicaIndexes > 1) {
+      throw new IOException(String.format("Pipeline: %s has nodes containing different replica indexes.",
+          pipeline));
+    }
+
+    // irrespective of the container state, we will always read via Standalone
+    // protocol.
+    boolean okForRead =
+        pipeline.getType() == HddsProtos.ReplicationType.STAND_ALONE
+            || pipeline.getType() == HddsProtos.ReplicationType.EC;
+    Pipeline readPipeline = okForRead ? pipeline : Pipeline.newBuilder(pipeline)
+        .setReplicationConfig(StandaloneReplicationConfig.getInstance(
+            getLegacyFactor(pipeline.getReplicationConfig())))
+        .build();
+    pipelineRef.set(readPipeline);
+  }
+
+  protected synchronized void checkOpen() throws IOException {
+    if (xceiverClientFactory == null) {
+      throw new IOException("BlockInputStream has been closed.");
+    }
+  }
+
+  protected synchronized void acquireClient() throws IOException {
+    if (xceiverClientFactory != null && xceiverClient == null) {
+      final Pipeline pipeline = pipelineRef.get();
+      try {
+        xceiverClient = xceiverClientFactory.acquireClientForReadData(pipeline);
+      } catch (IOException ioe) {
+        LOG.warn("Failed to acquire client for pipeline {}, block {}",
+            pipeline, blockID);
+        throw ioe;
+      }
+    }
+  }
+
+  private synchronized int prepareRead(int len) throws IOException {
+    for (;;) {
+      if (blockPosition >= 0) {
+        if (buffersHavePosition(blockPosition)) {
+          // The current buffers have the seeked position. Adjust the buffer
+          // index and position to point to the buffer position.
+          adjustBufferPosition(blockPosition - bufferOffsetWrtBlockDataData);
+        } else {
+          // Read a required block data to fill the buffers with seeked
+          // position data
+          readDataFromContainer(len);
+        }
+      }
+      if (buffersHaveData()) {
+        // Data is available from buffers
+        ByteBuffer bb = buffers.get(bufferIndex);
+        return Math.min(len, bb.remaining());
+      } else if (dataRemainingInBlock()) {
+        // There is more data in the block stream which has not
+        // been read into the buffers yet.
+        readDataFromContainer(len);
+      } else {
+        // All available input from this block stream has been consumed.
+        return EOF;
+      }
+    }
+
+
+  }
+
+  private boolean buffersHavePosition(long pos) {
+    // Check if buffers have been allocated
+    if (buffersAllocated()) {
+      // Check if the current buffers cover the input position
+      // Released buffers should not be considered when checking if position
+      // is available
+      return pos >= bufferOffsetWrtBlockDataData +
+          bufferoffsets.get(0) &&
+          pos < bufferOffsetWrtBlockDataData + buffersSize;
+    }
+    return false;
+  }
+
+  /**
+   * Check if the buffers have been allocated data and false otherwise.
+   */
+  @VisibleForTesting
+  protected boolean buffersAllocated() {
+    return buffers != null && !buffers.isEmpty();
+  }
+
+  /**
+   * Adjust the buffers position to account for seeked position and/ or checksum
+   * boundary reads.
+   * @param bufferPosition the position to which the buffers must be advanced
+   */
+  private void adjustBufferPosition(long bufferPosition) {
+    // The bufferPosition is w.r.t the current buffers.
+    // Adjust the bufferIndex and position to the seeked bufferPosition.
+    if (bufferIndex >= buffers.size()) {
+      bufferIndex = Collections.binarySearch(bufferoffsets, bufferPosition);
+    } else if (bufferPosition < bufferoffsets.get(bufferIndex)) {
+      bufferIndex = Collections.binarySearch(
+          bufferoffsets.subList(0, bufferIndex), bufferPosition);
+    } else if (bufferPosition >= bufferoffsets.get(bufferIndex) +
+        buffers.get(bufferIndex).capacity()) {
+      bufferIndex = Collections.binarySearch(bufferoffsets.subList(
+          bufferIndex + 1, buffers.size()), bufferPosition);
+    }
+    if (bufferIndex < 0) {
+      bufferIndex = -bufferIndex - 2;
+    }

Review Comment:
   done



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "chungen0126 (via GitHub)" <gi...@apache.org>.
chungen0126 commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1792378184


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/ozone/client/io/BlockInputStreamFactoryImpl.java:
##########
@@ -38,6 +40,8 @@
 import java.util.function.Function;
 import java.util.function.Supplier;
 
+import static org.apache.hadoop.hdds.DatanodeVersion.STEAM_BLOCK_SUPPORT;

Review Comment:
   done



##########
hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/MiniOzoneCluster.java:
##########
@@ -275,7 +275,7 @@ abstract class Builder {
     protected boolean includeRecon = false;
 
     protected int dnInitialVersion = DatanodeVersion.FUTURE_VERSION.toProtoValue();
-    protected int dnCurrentVersion = DatanodeVersion.COMBINED_PUTBLOCK_WRITECHUNK_RPC.toProtoValue();
+    protected int dnCurrentVersion = DatanodeVersion.STEAM_BLOCK_SUPPORT.toProtoValue();

Review Comment:
   done



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "chungen0126 (via GitHub)" <gi...@apache.org>.
chungen0126 commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1867504861


##########
hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/scm/storage/ContainerProtocolCalls.java:
##########
@@ -874,4 +876,57 @@ public static List<Validator> toValidatorList(Validator validator) {
     return datanodeToResponseMap;
   }
 
+  /**
+   * Calls the container protocol to read a chunk.
+   *
+   * @param xceiverClient  client to perform call
+   * @param blockID        ID of the block
+   * @param validators     functions to validate the response
+   * @param token          a token for this block (may be null)
+   * @return container protocol read chunk response
+   * @throws IOException if there is an I/O error while performing the call
+   */
+  @SuppressWarnings("checkstyle:ParameterNumber")
+  public static ContainerProtos.ReadBlockResponseProto readBlock(
+      XceiverClientSpi xceiverClient, long offset, long len, BlockID blockID,

Review Comment:
   Done



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "chungen0126 (via GitHub)" <gi...@apache.org>.
chungen0126 commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1867504422


##########
hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/common/interfaces/Handler.java:
##########
@@ -223,4 +225,9 @@ public void setClusterID(String clusterID) {
     this.clusterId = clusterID;
   }
 
+  public abstract ContainerCommandResponseProto streamDataReadOnly(

Review Comment:
   Done



##########
hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/common/interfaces/ContainerDispatcher.java:
##########
@@ -93,4 +94,15 @@ default StateMachine.DataChannel getStreamDataChannel(
     throw new UnsupportedOperationException(
         "getStreamDataChannel not supported.");
   }
+
+  /**
+   * When reading data form client using stream, get StreamDataChannel.

Review Comment:
   Done



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "chungen0126 (via GitHub)" <gi...@apache.org>.
chungen0126 commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1868098415


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -618,6 +624,69 @@ private void decreasePendingMetricsAndReleaseSemaphore() {
     return new XceiverClientReply(replyFuture);
   }
 
+  public XceiverClientReply sendCommandReadBlock(
+      ContainerCommandRequestProto request, DatanodeDetails dn)
+      throws IOException, InterruptedException {
+
+    CompletableFuture<ContainerCommandResponseProto> future =
+        new CompletableFuture<>();
+    ContainerCommandResponseProto.Builder response =
+        ContainerCommandResponseProto.newBuilder();
+    ContainerProtos.ReadBlockResponseProto.Builder readBlock =
+        ContainerProtos.ReadBlockResponseProto.newBuilder();
+    checkOpen(dn);
+    UUID dnID = dn.getUuid();
+    Type cmdType = request.getCmdType();
+    semaphore.acquire();
+    long requestTime = System.currentTimeMillis();
+    metrics.incrPendingContainerOpsMetrics(cmdType);
+
+    final StreamObserver<ContainerCommandRequestProto> requestObserver =
+        asyncStubs.get(dnID).withDeadlineAfter(timeout, TimeUnit.SECONDS)
+            .send(new StreamObserver<ContainerCommandResponseProto>() {
+              @Override
+              public void onNext(
+                  ContainerCommandResponseProto responseProto) {
+                if (responseProto.getResult() == Result.SUCCESS) {
+                  readBlock.addReadChunk(responseProto.getReadChunk());
+                } else {
+                  future.complete(
+                      ContainerCommandResponseProto.newBuilder(responseProto)
+                          .setCmdType(Type.ReadBlock).build());
+                }
+              }
+
+              @Override
+              public void onError(Throwable t) {
+                future.completeExceptionally(t);
+                metrics.decrPendingContainerOpsMetrics(cmdType);
+                metrics.addContainerOpsLatency(
+                    cmdType, System.currentTimeMillis() - requestTime);
+
+              }
+
+              @Override
+              public void onCompleted() {
+                if (readBlock.getReadChunkCount() > 0) {
+                  future.complete(response.setReadBlock(readBlock)
+                      .setCmdType(Type.ReadBlock).setResult(Result.SUCCESS).build());
+                }
+                if (!future.isDone()) {
+                  future.completeExceptionally(new IOException(
+                      "Stream completed but no reply for request " +
+                          processForDebug(request)));
+                }
+                metrics.decrPendingContainerOpsMetrics(cmdType);
+                metrics.addContainerOpsLatency(
+                    cmdType, System.currentTimeMillis() - requestTime);
+              }
+            });
+    requestObserver.onNext(request);
+    requestObserver.onCompleted();
+    semaphore.release();

Review Comment:
   Change to release semaphore at the end of `StreamObserver#onError` and `StreamObserver#onCompleted`.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "chungen0126 (via GitHub)" <gi...@apache.org>.
chungen0126 commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1873806121


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -618,6 +624,69 @@ private void decreasePendingMetricsAndReleaseSemaphore() {
     return new XceiverClientReply(replyFuture);
   }
 
+  public XceiverClientReply sendCommandReadBlock(
+      ContainerCommandRequestProto request, DatanodeDetails dn)
+      throws IOException, InterruptedException {
+
+    CompletableFuture<ContainerCommandResponseProto> future =
+        new CompletableFuture<>();
+    ContainerCommandResponseProto.Builder response =
+        ContainerCommandResponseProto.newBuilder();
+    ContainerProtos.ReadBlockResponseProto.Builder readBlock =
+        ContainerProtos.ReadBlockResponseProto.newBuilder();
+    checkOpen(dn);
+    UUID dnID = dn.getUuid();
+    Type cmdType = request.getCmdType();
+    semaphore.acquire();
+    long requestTime = System.currentTimeMillis();
+    metrics.incrPendingContainerOpsMetrics(cmdType);
+
+    final StreamObserver<ContainerCommandRequestProto> requestObserver =
+        asyncStubs.get(dnID).withDeadlineAfter(timeout, TimeUnit.SECONDS)
+            .send(new StreamObserver<ContainerCommandResponseProto>() {
+              @Override
+              public void onNext(
+                  ContainerCommandResponseProto responseProto) {
+                if (responseProto.getResult() == Result.SUCCESS) {
+                  readBlock.addReadChunk(responseProto.getReadChunk());
+                } else {
+                  future.complete(
+                      ContainerCommandResponseProto.newBuilder(responseProto)
+                          .setCmdType(Type.ReadBlock).build());
+                }
+              }
+
+              @Override
+              public void onError(Throwable t) {
+                future.completeExceptionally(t);
+                metrics.decrPendingContainerOpsMetrics(cmdType);
+                metrics.addContainerOpsLatency(
+                    cmdType, System.currentTimeMillis() - requestTime);

Review Comment:
   done



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "ChenSammi (via GitHub)" <gi...@apache.org>.
ChenSammi commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1866978592


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/OzoneClientConfig.java:
##########
@@ -128,6 +128,13 @@ public enum ChecksumCombineMode {
       tags = ConfigTag.CLIENT)
   private long streamBufferMaxSize = 32 * 1024 * 1024;
 
+  @Config(key = "stream.readblock.enable",
+      defaultValue = "false",
+      type = ConfigType.BOOLEAN,
+      description = "Allow ReadBlock to stream all the readChunk in one request.",
+      tags = ConfigTag.CLIENT)
+  private boolean streamReadBlock = true;

Review Comment:
   default is false. 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "chungen0126 (via GitHub)" <gi...@apache.org>.
chungen0126 commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-2661086750

   Thanks @adoroszlai for fixing the conflicts. I was just about to address it.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "peterxcli (via GitHub)" <gi...@apache.org>.
peterxcli commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1998355206


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -615,6 +622,69 @@ private void decreasePendingMetricsAndReleaseSemaphore() {
     return new XceiverClientReply(replyFuture);
   }
 
+  public XceiverClientReply sendCommandReadBlock(

Review Comment:
   This function seems quite similar to `sendCommandAsync(ContainerCommandRequestProto request, DatanodeDetails dn) throws IOException, InterruptedException` 
   How about create a `StreamObserverFactory` for them?
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "chungen0126 (via GitHub)" <gi...@apache.org>.
chungen0126 commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1792314812


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -618,6 +625,71 @@ private void decreasePendingMetricsAndReleaseSemaphore() {
     return new XceiverClientReply(replyFuture);
   }
 
+  public XceiverClientReply sendCommandAsyncReadOnly(
+      ContainerCommandRequestProto request, DatanodeDetails dn)
+      throws IOException, InterruptedException {
+
+    CompletableFuture<ContainerCommandResponseProto> future =
+        new CompletableFuture<>();
+    ContainerCommandResponseProto.Builder response =
+        ContainerCommandResponseProto.newBuilder();
+    ContainerProtos.ReadBlockResponseProto.Builder readBlock =
+        ContainerProtos.ReadBlockResponseProto.newBuilder();
+    checkOpen(dn);
+    UUID dnID = dn.getUuid();
+    Type cmdType = request.getCmdType();
+    semaphore.acquire();
+    long requestTime = System.currentTimeMillis();
+    metrics.incrPendingContainerOpsMetrics(cmdType);
+
+    final StreamObserver<ContainerCommandRequestProto> requestObserver =
+        asyncStubs.get(dnID).withDeadlineAfter(timeout, TimeUnit.SECONDS)
+            .send(new StreamObserver<ContainerCommandResponseProto>() {
+              @Override
+              public void onNext(
+                  ContainerCommandResponseProto responseProto) {
+                ReadChunkResponseProto readChunk =
+                    responseProto.getReadChunk();
+                if (responseProto.getResult() == Result.SUCCESS) {
+                  readBlock.addReadChunk(readChunk);
+                } else {
+                  future.complete(
+                      ContainerCommandResponseProto.newBuilder(responseProto)
+                          .setCmdType(Type.StreamRead).build());
+                }
+              }
+
+              @Override
+              public void onError(Throwable t) {
+                future.completeExceptionally(t);
+                metrics.decrPendingContainerOpsMetrics(cmdType);
+                metrics.addContainerOpsLatency(
+                    cmdType, System.currentTimeMillis() - requestTime);
+
+              }
+
+              @Override
+              public void onCompleted() {
+                if (readBlock.getReadChunkCount() > 0) {
+                  future.complete(response.setReadBlock(readBlock)
+                      .setCmdType(Type.StreamRead).setResult(Result.SUCCESS).build());
+                }
+                if (!future.isDone()) {
+                  future.completeExceptionally(new IOException(
+                      "Stream completed but no reply for request " +
+                          processForDebug(request)));
+                }

Review Comment:
   done



##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/StreamBlockInput.java:
##########
@@ -0,0 +1,777 @@
+/*
+ * 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 com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
+import org.apache.commons.lang3.NotImplementedException;
+import org.apache.hadoop.fs.ByteBufferReadable;
+import org.apache.hadoop.fs.CanUnbuffer;
+import org.apache.hadoop.fs.Seekable;
+import org.apache.hadoop.hdds.client.BlockID;
+import org.apache.hadoop.hdds.client.StandaloneReplicationConfig;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadChunkResponseProto;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadBlockResponseProto;
+import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
+import org.apache.hadoop.hdds.scm.OzoneClientConfig;
+import org.apache.hadoop.hdds.scm.XceiverClientFactory;
+import org.apache.hadoop.hdds.scm.XceiverClientSpi;
+import org.apache.hadoop.hdds.scm.client.HddsClientUtils;
+import org.apache.hadoop.hdds.scm.container.common.helpers.StorageContainerException;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.hdds.security.exception.SCMSecurityException;
+import org.apache.hadoop.hdds.security.token.OzoneBlockTokenIdentifier;
+import org.apache.hadoop.io.retry.RetryPolicy;
+import org.apache.hadoop.ozone.common.Checksum;
+import org.apache.hadoop.ozone.common.ChecksumData;
+import org.apache.hadoop.ozone.common.OzoneChecksumException;
+import org.apache.hadoop.ozone.common.utils.BufferUtils;
+import org.apache.hadoop.security.token.Token;
+import org.apache.ratis.thirdparty.com.google.protobuf.ByteString;
+import org.apache.ratis.thirdparty.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.EOFException;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+
+import static org.apache.hadoop.hdds.client.ReplicationConfig.getLegacyFactor;
+
+/**
+ * An {@link java.io.InputStream} called from KeyInputStream to read a block from the
+ * container.
+ */
+public class StreamBlockInput extends BlockExtendedInputStream
+    implements Seekable, CanUnbuffer, ByteBufferReadable {
+  private static final Logger LOG =
+      LoggerFactory.getLogger(StreamBlockInput.class);
+  private final BlockID blockID;
+  private final long length;

Review Comment:
   done



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "chungen0126 (via GitHub)" <gi...@apache.org>.
chungen0126 commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1792313617


##########
hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/keyvalue/KeyValueHandler.java:
##########
@@ -1329,6 +1333,126 @@ public void deleteUnreferenced(Container container, long localID)
     }
   }
 
+  @Override
+  public ContainerCommandResponseProto streamDataReadOnly(
+      ContainerCommandRequestProto request, KeyValueContainer kvContainer,
+      DispatcherContext dispatcherContext,
+      StreamObserver<ContainerCommandResponseProto> streamObserver) {
+    ContainerCommandResponseProto responseProto = null;
+    try {
+      if (!request.hasReadBlock()) {
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("Malformed Read Block request. trace ID: {}",
+              request.getTraceID());
+        }
+        return malformedRequest(request);
+      }
+      ReadBlockRequestProto readBlock = request.getReadBlock();
+      ChunkBuffer data;
+
+      BlockID blockID = BlockID.getFromProtobuf(
+          readBlock.getBlockID());
+      if (replicaIndexCheckRequired(request)) {
+        BlockUtils.verifyReplicaIdx(kvContainer, blockID);
+      }
+      BlockData blockData = blockManager.getBlock(kvContainer, blockID);
+      List<ContainerProtos.ChunkInfo> chunkInfos = blockData.getChunks();
+      long blockOffset = 0;
+      int chunkIndex = -1;
+      for (int i = 0; i < chunkInfos.size(); i++) {
+        blockOffset += chunkInfos.get(i).getLen();
+        if (blockOffset > readBlock.getOffset()) {
+          chunkIndex = i;
+          break;
+        }
+      }
+
+      BlockUtils.verifyBCSId(kvContainer, blockID);
+      if (dispatcherContext == null) {
+        dispatcherContext = DispatcherContext.getHandleReadBlock();
+      }
+
+      boolean isReadChunkV0 = readBlock.getVersion()
+          .equals(ContainerProtos.ReadChunkVersion.V0);
+
+      long offset = readBlock.getOffset();
+      long len =  readBlock.getLen();
+      long adjustedChunkOffset, adjustedChunkLen;
+      do {
+        int startIndex = -1;
+        ContainerProtos.ChunkInfo chunk = chunkInfos.get(chunkIndex);
+        if (readBlock.getVerifyChecksum()) {
+          Pair<Long, Long> adjustedOffsetAndLength =
+              computeChecksumBoundaries(chunk, offset, len);
+          adjustedChunkOffset = adjustedOffsetAndLength.getLeft();
+          adjustedChunkLen = adjustedOffsetAndLength.getRight();
+          startIndex = (int) adjustedChunkOffset /
+              chunk.getChecksumData().getBytesPerChecksum();
+          adjustedChunkOffset += chunk.getOffset();
+        } else {
+          adjustedChunkOffset = offset;
+          adjustedChunkLen = Math.min(
+              chunk.getLen() + chunk.getOffset() - offset, len);
+        }
+
+        ChunkInfo chunkInfo = ChunkInfo.getFromProtoBuf(
+            ContainerProtos.ChunkInfo.newBuilder(chunk)
+                .setOffset(adjustedChunkOffset)
+                .setLen(adjustedChunkLen).build());
+        // For older clients, set ReadDataIntoSingleBuffer to true so that
+        // all the data read from chunk file is returned as a single
+        // ByteString. Older clients cannot process data returned as a list
+        // of ByteStrings.
+        if (isReadChunkV0) {
+          chunkInfo.setReadDataIntoSingleBuffer(isReadChunkV0);
+        }
+        data = chunkManager.readChunk(
+            kvContainer, blockID, chunkInfo, dispatcherContext);
+
+        Preconditions.checkNotNull(data, "Chunk data is null");
+        if (DispatcherContext.op(dispatcherContext).readFromTmpFile()) {
+          validateChunkChecksumData(data, chunkInfo);
+          metrics.incBytesReadStateMachine(chunkInfo.getLen());
+          metrics.incNumReadStateMachine();
+        }
+        streamObserver.onNext(
+            getReadBlockResponse(request,
+                blockData.getProtoBufMessage().getBlockID(),
+                chunkInfo.getProtoBufMessage(), isReadChunkV0,
+                data, byteBufferToByteString, startIndex));
+        len -= adjustedChunkLen + adjustedChunkOffset - offset;
+        offset = adjustedChunkOffset + adjustedChunkLen;
+        chunkIndex++;

Review Comment:
   Add a new test in `TestKeyValueHandler`. Do you think it is enough?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "devabhishekpal (via GitHub)" <gi...@apache.org>.
devabhishekpal commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1794994446


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/StreamBlockInput.java:
##########
@@ -0,0 +1,777 @@
+/*
+ * 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 com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
+import org.apache.commons.lang3.NotImplementedException;
+import org.apache.hadoop.fs.ByteBufferReadable;
+import org.apache.hadoop.fs.CanUnbuffer;
+import org.apache.hadoop.fs.Seekable;
+import org.apache.hadoop.hdds.client.BlockID;
+import org.apache.hadoop.hdds.client.StandaloneReplicationConfig;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadChunkResponseProto;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadBlockResponseProto;
+import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
+import org.apache.hadoop.hdds.scm.OzoneClientConfig;
+import org.apache.hadoop.hdds.scm.XceiverClientFactory;
+import org.apache.hadoop.hdds.scm.XceiverClientSpi;
+import org.apache.hadoop.hdds.scm.client.HddsClientUtils;
+import org.apache.hadoop.hdds.scm.container.common.helpers.StorageContainerException;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.hdds.security.exception.SCMSecurityException;
+import org.apache.hadoop.hdds.security.token.OzoneBlockTokenIdentifier;
+import org.apache.hadoop.io.retry.RetryPolicy;
+import org.apache.hadoop.ozone.common.Checksum;
+import org.apache.hadoop.ozone.common.ChecksumData;
+import org.apache.hadoop.ozone.common.OzoneChecksumException;
+import org.apache.hadoop.ozone.common.utils.BufferUtils;
+import org.apache.hadoop.security.token.Token;
+import org.apache.ratis.thirdparty.com.google.protobuf.ByteString;
+import org.apache.ratis.thirdparty.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.EOFException;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+
+import static org.apache.hadoop.hdds.client.ReplicationConfig.getLegacyFactor;
+
+/**
+ * An {@link java.io.InputStream} called from KeyInputStream to read a block from the
+ * container.
+ */
+public class StreamBlockInput extends BlockExtendedInputStream
+    implements Seekable, CanUnbuffer, ByteBufferReadable {
+  private static final Logger LOG =
+      LoggerFactory.getLogger(StreamBlockInput.class);
+  private final BlockID blockID;
+  private final long length;
+  private final AtomicReference<Pipeline> pipelineRef =
+      new AtomicReference<>();
+  private final AtomicReference<Token<OzoneBlockTokenIdentifier>> tokenRef =
+      new AtomicReference<>();
+  private XceiverClientFactory xceiverClientFactory;
+  private XceiverClientSpi xceiverClient;
+
+  private List<Long> bufferoffsets;
+  private int bufferIndex;
+  private long blockPosition = -1;
+  private List<ByteBuffer> buffers;
+  private boolean allocated = false;

Review Comment:
   I see, thanks for the explanation.
   Can we have a short comment in the code regarding this so it's easier to get the context later?
   Mainly the different variable usages, since the code is complex and would help to understand easily.
   Just a one liner would suffice ex:
   ```
   // Checks if the StreamBlockInput is ready to read data from container
   private boolean allocated = false;
   ```
   Similar for other variables as well which are not obvious in it's usage



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "sodonnel (via GitHub)" <gi...@apache.org>.
sodonnel commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-3249780357

   @chungen0126 Could you explain more detail how this change works, and why it should perform better than the current approach? Has this code been run on any cluster to prove it works and also that its performance is better than the current approach. eg for `ozone sh key get` even on a local docker environment?
   
   As I understand the current approach, provided a client asks for chunk size reads, the logic is that we pull one chunk at a time from the server to the client. When the reader has consumed that, it will go back and make another read chunk call.
   
   With the approach in this PR, it talks about using a GRPC bi-directional feature to pipeline the chunks to the client. I don't understand how this works exactly, but I immediately wonder:
   
   1. Is there more buffering memory needed on the client?
   2. How many chunks could the client need to buffer at any time for this to be effective?
   3. What triggers new chunks to come from server to client?
   4. What if the client needs to seek and read parts of the key, such as for ORC file?
   5. Is a GRPC handler tied up on the server for the entire time the block is being read by the client? Or is a thread pulled from the thread pool only when a new chunk needs to be sent to the client?
   
   Thanks.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "sodonnel (via GitHub)" <gi...@apache.org>.
sodonnel commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-3403313238

   > While this will reduce memory usage, it may slow down seeking performance. Is this the intended trade-off?
   
   While only the current buffer and one pending buffer are stored in the reader, there is scope to configure the size of that queue. However what I found in practice is that GRPC seems to buffer about 1MB of data on the connection socket, so that when the item is consumed from the queue it immediately gets refilled.
   
   Compared to the existing implementation in Ozone with 16KB checksums, the time to read 1GB dropped from about 30 seconds to 7 seconds in local tests. 1MB checksums went from 4.5s to 2.6s.
   
   Seeks are another matter. I have not attempted to benchmark them as yet, but they would tend to be slow with any approach, as we can only cache a reasonable amount of data in the client - say at most 4MB, so there is every chance a seek takes you outside of that.
   
   The approach I have implemented simplifies the code quite a bit I think, and it reads the entire block in a single RPC call and only opens the block file on the server one time.
   
   I think it will be much better than the current code in Ozone and it can of course be refined further once we get the first version committed and more extensive testing done.
   
   I still have a bit more work to do on this PR around testing and retrying reads on failed DNs.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "fenixjin (via GitHub)" <gi...@apache.org>.
fenixjin commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-2370933760

   Test conducted on our cluster(3DN / HDD / 10 Gigabit network) shows this improvement can boost read speed by at least 30%.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "ChenSammi (via GitHub)" <gi...@apache.org>.
ChenSammi commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1867370126


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/StreamBlockInput.java:
##########
@@ -0,0 +1,760 @@
+/*
+ * 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 com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
+import org.apache.commons.lang3.NotImplementedException;
+import org.apache.hadoop.fs.ByteBufferReadable;
+import org.apache.hadoop.fs.CanUnbuffer;
+import org.apache.hadoop.fs.Seekable;
+import org.apache.hadoop.hdds.client.BlockID;
+import org.apache.hadoop.hdds.client.StandaloneReplicationConfig;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadChunkResponseProto;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadBlockResponseProto;
+import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
+import org.apache.hadoop.hdds.scm.OzoneClientConfig;
+import org.apache.hadoop.hdds.scm.XceiverClientFactory;
+import org.apache.hadoop.hdds.scm.XceiverClientSpi;
+import org.apache.hadoop.hdds.scm.client.HddsClientUtils;
+import org.apache.hadoop.hdds.scm.container.common.helpers.StorageContainerException;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.hdds.security.exception.SCMSecurityException;
+import org.apache.hadoop.hdds.security.token.OzoneBlockTokenIdentifier;
+import org.apache.hadoop.io.retry.RetryPolicy;
+import org.apache.hadoop.ozone.common.Checksum;
+import org.apache.hadoop.ozone.common.ChecksumData;
+import org.apache.hadoop.ozone.common.OzoneChecksumException;
+import org.apache.hadoop.ozone.common.utils.BufferUtils;
+import org.apache.hadoop.security.token.Token;
+import org.apache.ratis.thirdparty.com.google.protobuf.ByteString;
+import org.apache.ratis.thirdparty.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.EOFException;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+
+import static org.apache.hadoop.hdds.client.ReplicationConfig.getLegacyFactor;
+
+/**
+ * An {@link java.io.InputStream} called from KeyInputStream to read a block from the
+ * container.
+ */
+public class StreamBlockInput extends BlockExtendedInputStream

Review Comment:
   Please rename StreamBlockInput to StreamBlockInputStream.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "chungen0126 (via GitHub)" <gi...@apache.org>.
chungen0126 commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1804289156


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -108,12 +110,12 @@ public class XceiverClientGrpc extends XceiverClientSpi {
    * Constructs a client that can communicate with the Container framework on
    * data nodes via DatanodeClientProtocol.
    *
-   * @param pipeline - Pipeline that defines the machines.
-   * @param config   -- Ozone Config
+   * @param pipeline     - Pipeline that defines the machines.
+   * @param config       -- Ozone Config
    * @param trustManager - a {@link ClientTrustManager} with proper CA handling.
    */
   public XceiverClientGrpc(Pipeline pipeline, ConfigurationSource config,
-      ClientTrustManager trustManager) {
+                           ClientTrustManager trustManager) {

Review Comment:
   done



##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -618,6 +624,69 @@ private void decreasePendingMetricsAndReleaseSemaphore() {
     return new XceiverClientReply(replyFuture);
   }
 
+  public XceiverClientReply sendCommandAsyncReadOnly(

Review Comment:
   done



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "kerneltime (via GitHub)" <gi...@apache.org>.
kerneltime commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1802072873


##########
hadoop-hdds/client/dev-support/findbugsExcludeFile.xml:
##########
@@ -32,4 +32,8 @@
     <Class name="org.apache.hadoop.hdds.scm.storage.TestBlockInputStream"></Class>
     <Bug pattern="RR_NOT_CHECKED" />
   </Match>
+  <Match>
+    <Class name="org.apache.hadoop.hdds.scm.storage.TestStreamBlockInput"></Class>
+    <Bug pattern="RR_NOT_CHECKED" />
+  </Match>

Review Comment:
   This applies to all the places in the code; validate the returned number of bytes read with the expected number of bytes read, and drop the find bugs exception added. Also commented below for the test itself



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "ChenSammi (via GitHub)" <gi...@apache.org>.
ChenSammi commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1866992353


##########
hadoop-hdds/interface-client/src/main/proto/DatanodeClientProtocol.proto:
##########
@@ -108,6 +108,7 @@ enum Type {
 
   FinalizeBlock = 21;
   Echo = 22;
+  ReadBlock = 23;

Review Comment:
   Please describe the command in the above comments section.   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "guohao-rosicky (via GitHub)" <gi...@apache.org>.
guohao-rosicky commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-2510729037

   Thanks for @chungen0126 's work. We previously discovered an issue with checksum calculation and it has been resolved.
   
   Single threaded reading of 1GB files :
   
   
   times | grpc stram  |  grpc
   -- | -- | --
   1 | 5223 ms | 7435 ms
   2 | 4874 | 7446
   3 | 4953 | 7386
   4 | 4851 | 7402
   5 | 4836 | 7433
   6 | 5178 | 7393
   7 | 4949 | 7343
   8 | 5344 | 7467
   9 | 4858 | 8001
   10 | 5176 | 7300
   
   It can be seen that for 1GB file reading, streaming reading can reduce the reading time by about 30%.
   
   
   
   
   
   
   
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "swamirishi (via GitHub)" <gi...@apache.org>.
swamirishi commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1811169258


##########
hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/keyvalue/KeyValueHandler.java:
##########
@@ -1329,6 +1333,109 @@ public void deleteUnreferenced(Container container, long localID)
     }
   }
 
+  @Override
+  public ContainerCommandResponseProto streamDataReadOnly(
+      ContainerCommandRequestProto request, KeyValueContainer kvContainer,
+      DispatcherContext dispatcherContext,
+      StreamObserver<ContainerCommandResponseProto> streamObserver) {
+    ContainerCommandResponseProto responseProto = null;
+    try {
+      if (!request.hasReadBlock()) {
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("Malformed Read Block request. trace ID: {}",
+              request.getTraceID());
+        }
+        return malformedRequest(request);
+      }
+      ReadBlockRequestProto readBlock = request.getReadBlock();
+
+      BlockID blockID = BlockID.getFromProtobuf(
+          readBlock.getBlockID());
+      // This is a new api the block should always be checked.
+      BlockUtils.verifyReplicaIdx(kvContainer, blockID);

Review Comment:
   It could so happen that the container replica index could change b/w 2 read chunks. You are right about that, we need to ensure that the checksums of the chunks do match on the client side. I am still looking through the client side code, just wanted to understand if we are doing a checksum verification for each and every chunk read on the client side.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r2466555548


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -504,6 +516,65 @@ private XceiverClientReply sendCommandWithRetry(
     }
   }
 
+  /**
+   * Starts a streaming read operation, intended to read entire blocks from the datanodes. This method expects a
+   * {@link StreamObserver} to be passed in, which will be used to receive the streamed data from the datanode.
+   * Upon successfully starting the streaming read, a {@link StreamingReadResponse} is returned, which contains
+   * information about the datanode used for the read, and the request observer that can be used to manage the stream
+   * (e.g., to cancel it if needed). A semaphore is acquired to limit the number of concurrent streaming reads so upon
+   * successful return of this method, the caller must ensure to call {@link #completeStreamRead(StreamingReadResponse)}
+   * to release the semaphore once the streaming read is complete.
+   * @param request The container command request to initiate the streaming read.
+   * @param streamObserver The observer that will handle the streamed responses.
+   * @return A {@link StreamingReadResponse} containing details of the streaming read operation.
+   * @throws IOException
+   * @throws InterruptedException
+   */
+  @Override
+  public StreamingReadResponse streamRead(ContainerCommandRequestProto request,
+      StreamObserver<ContainerCommandResponseProto> streamObserver) throws IOException, InterruptedException {
+    List<DatanodeDetails> datanodeList = sortDatanodes(request);
+    IOException lastException = null;
+    for (DatanodeDetails dn : datanodeList) {
+      try {
+        checkOpen(dn);
+        semaphore.acquire();
+        XceiverClientProtocolServiceStub stub = asyncStubs.get(dn.getID());
+        if (stub == null) {
+          throw new IOException("Failed to get gRPC stub for DataNode: " + dn);
+        }
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("Executing command {} on datanode {}", processForDebug(request), dn);
+        }
+        StreamObserver<ContainerCommandRequestProto> requestObserver = stub
+            .withDeadlineAfter(timeout, TimeUnit.SECONDS)
+            .send(streamObserver);
+        requestObserver.onNext(request);
+        requestObserver.onCompleted();
+        return new StreamingReadResponse(dn, (ClientCallStreamObserver<ContainerCommandRequestProto>) requestObserver);

Review Comment:
   > ... HDFS model works well and results in relatively simple code in the approach used here ... 
   
   I agree that HDFS model works  well but the problem is that this approach is not the HDFS model:
   - HDFS: Blocking API (Socket) + Blocking threads
   - This approach: Non-blocking API (gRPC) + Blocking threads
   - Suggested approach: Non-blocking API (gRPC) + Non-blocking threads
   
   > Of course we can cache open files, ...
   
   I guess you mean the server side?  We don't have to.  The server should open the file in the first gRPC onNext() call and close it in onComplete().
   
   > ... we agreed the handler pool would need to be greatly increased. I don't see any big problem with having a very large handler pool of threads that are mostly blocked. ...
   
   Increasing handler pool for performance makes sense.  However, it is not a good solution to avoid deadlocks.
   
   BTW, how large is enough?  Would it slows down other operations for creating such a large handler pool?
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "sodonnel (via GitHub)" <gi...@apache.org>.
sodonnel commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r2465368649


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -504,6 +516,65 @@ private XceiverClientReply sendCommandWithRetry(
     }
   }
 
+  /**
+   * Starts a streaming read operation, intended to read entire blocks from the datanodes. This method expects a
+   * {@link StreamObserver} to be passed in, which will be used to receive the streamed data from the datanode.
+   * Upon successfully starting the streaming read, a {@link StreamingReadResponse} is returned, which contains
+   * information about the datanode used for the read, and the request observer that can be used to manage the stream
+   * (e.g., to cancel it if needed). A semaphore is acquired to limit the number of concurrent streaming reads so upon
+   * successful return of this method, the caller must ensure to call {@link #completeStreamRead(StreamingReadResponse)}
+   * to release the semaphore once the streaming read is complete.
+   * @param request The container command request to initiate the streaming read.
+   * @param streamObserver The observer that will handle the streamed responses.
+   * @return A {@link StreamingReadResponse} containing details of the streaming read operation.
+   * @throws IOException
+   * @throws InterruptedException
+   */
+  @Override
+  public StreamingReadResponse streamRead(ContainerCommandRequestProto request,
+      StreamObserver<ContainerCommandResponseProto> streamObserver) throws IOException, InterruptedException {
+    List<DatanodeDetails> datanodeList = sortDatanodes(request);
+    IOException lastException = null;
+    for (DatanodeDetails dn : datanodeList) {
+      try {
+        checkOpen(dn);
+        semaphore.acquire();
+        XceiverClientProtocolServiceStub stub = asyncStubs.get(dn.getID());
+        if (stub == null) {
+          throw new IOException("Failed to get gRPC stub for DataNode: " + dn);
+        }
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("Executing command {} on datanode {}", processForDebug(request), dn);
+        }
+        StreamObserver<ContainerCommandRequestProto> requestObserver = stub
+            .withDeadlineAfter(timeout, TimeUnit.SECONDS)
+            .send(streamObserver);
+        requestObserver.onNext(request);
+        requestObserver.onCompleted();
+        return new StreamingReadResponse(dn, (ClientCallStreamObserver<ContainerCommandRequestProto>) requestObserver);

Review Comment:
   My observation is that the HDFS model works well and results in relatively simple code in the approach used here which performs very well. Due to the buffer sizes used in the downstream readers, attempting to read a large block by the requested sized reads will result in many calls back and forward to the server. If we make the server truly async, then on each of these calls for often 16kb of data, it will have to queue for a thread, get a thread, context switch the thread, open the block file, seek the block file, read 16kb ... and so on.
   
   Of course we can cache open files, but we cannot have just one cached entry per file as many clients could be reading a file from different positions and of course a client can seek effectively eliminating the cache. Then we have to manage the cache and worry about too many open files, etc.
   
   HDFS had had some problems with its thread per open file, and we have seen clusters with 32k or more active xceiver threads per DN. This is usually caused by long writers, rather than long readers. A long reader would probably be a rare case.
   
   There are things we can do to mitigate holding too many handlers on the server. Eg the client can unbuffer after some small configurable window. The server could time out. We could have a separate handler pool for reads vs other operations.
   
   I already talked with and about the approach here and we agreed the handler pool would need to be greatly increased. I don't see any big problem with having a very large handler pool of threads that are mostly blocked. Yes they have some overhead in terms of memory, but we are not exactly memory constrained on Ozone datanodes, similar to HDFS DNs.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-3563927485

   @chungen0126 , @sodonnel , we should plan how to merge the code.  How about we merge it in three parts in the following order?
   
   1. @chungen0126 's change up to fc9507914180e3cbacade49bc7c8e4e6299398d8
   2. @sodonnel 's change up to 726f8e4857f42446fe34e5acdbb43a3c0469697f
   3. my change up to a45fa134166a5057c2b358f711b396506577e045 in https://github.com/szetszwo/ozone/commits/HDDS-10338b/
   
   If you agree, please submit a new pull request against the current master.  This PR is very long and hard to follow.  (We may also consider merging to a dev branch first.  However, since it is configuration and the default is disabled.  We probably don't need a dev branch.) 
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "chungen0126 (via GitHub)" <gi...@apache.org>.
chungen0126 commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1792309490


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -618,6 +625,71 @@ private void decreasePendingMetricsAndReleaseSemaphore() {
     return new XceiverClientReply(replyFuture);
   }
 
+  public XceiverClientReply sendCommandAsyncReadOnly(
+      ContainerCommandRequestProto request, DatanodeDetails dn)
+      throws IOException, InterruptedException {
+
+    CompletableFuture<ContainerCommandResponseProto> future =
+        new CompletableFuture<>();
+    ContainerCommandResponseProto.Builder response =
+        ContainerCommandResponseProto.newBuilder();
+    ContainerProtos.ReadBlockResponseProto.Builder readBlock =
+        ContainerProtos.ReadBlockResponseProto.newBuilder();
+    checkOpen(dn);
+    UUID dnID = dn.getUuid();
+    Type cmdType = request.getCmdType();
+    semaphore.acquire();
+    long requestTime = System.currentTimeMillis();
+    metrics.incrPendingContainerOpsMetrics(cmdType);
+
+    final StreamObserver<ContainerCommandRequestProto> requestObserver =
+        asyncStubs.get(dnID).withDeadlineAfter(timeout, TimeUnit.SECONDS)
+            .send(new StreamObserver<ContainerCommandResponseProto>() {
+              @Override
+              public void onNext(
+                  ContainerCommandResponseProto responseProto) {
+                ReadChunkResponseProto readChunk =
+                    responseProto.getReadChunk();
+                if (responseProto.getResult() == Result.SUCCESS) {
+                  readBlock.addReadChunk(readChunk);

Review Comment:
   done



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "chungen0126 (via GitHub)" <gi...@apache.org>.
chungen0126 commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1792329440


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/StreamBlockInput.java:
##########
@@ -0,0 +1,777 @@
+/*
+ * 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 com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
+import org.apache.commons.lang3.NotImplementedException;
+import org.apache.hadoop.fs.ByteBufferReadable;
+import org.apache.hadoop.fs.CanUnbuffer;
+import org.apache.hadoop.fs.Seekable;
+import org.apache.hadoop.hdds.client.BlockID;
+import org.apache.hadoop.hdds.client.StandaloneReplicationConfig;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadChunkResponseProto;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadBlockResponseProto;
+import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
+import org.apache.hadoop.hdds.scm.OzoneClientConfig;
+import org.apache.hadoop.hdds.scm.XceiverClientFactory;
+import org.apache.hadoop.hdds.scm.XceiverClientSpi;
+import org.apache.hadoop.hdds.scm.client.HddsClientUtils;
+import org.apache.hadoop.hdds.scm.container.common.helpers.StorageContainerException;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.hdds.security.exception.SCMSecurityException;
+import org.apache.hadoop.hdds.security.token.OzoneBlockTokenIdentifier;
+import org.apache.hadoop.io.retry.RetryPolicy;
+import org.apache.hadoop.ozone.common.Checksum;
+import org.apache.hadoop.ozone.common.ChecksumData;
+import org.apache.hadoop.ozone.common.OzoneChecksumException;
+import org.apache.hadoop.ozone.common.utils.BufferUtils;
+import org.apache.hadoop.security.token.Token;
+import org.apache.ratis.thirdparty.com.google.protobuf.ByteString;
+import org.apache.ratis.thirdparty.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.EOFException;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+
+import static org.apache.hadoop.hdds.client.ReplicationConfig.getLegacyFactor;
+
+/**
+ * An {@link java.io.InputStream} called from KeyInputStream to read a block from the
+ * container.
+ */
+public class StreamBlockInput extends BlockExtendedInputStream
+    implements Seekable, CanUnbuffer, ByteBufferReadable {
+  private static final Logger LOG =
+      LoggerFactory.getLogger(StreamBlockInput.class);
+  private final BlockID blockID;
+  private final long length;
+  private final AtomicReference<Pipeline> pipelineRef =
+      new AtomicReference<>();
+  private final AtomicReference<Token<OzoneBlockTokenIdentifier>> tokenRef =
+      new AtomicReference<>();
+  private XceiverClientFactory xceiverClientFactory;
+  private XceiverClientSpi xceiverClient;
+
+  private List<Long> bufferoffsets;
+  private int bufferIndex;
+  private long blockPosition = -1;
+  private List<ByteBuffer> buffers;
+  private boolean allocated = false;

Review Comment:
   They are different things, `allocated` means that the `StreamBlockInput` reads data from container, `buffersAllocated()` checks if the buffers are empty. The buffers may be empty not only because that the `StreamBlockInput` hasn't read data from container but also the data in buffers was read and released. 
   And, the `allocated` is a short cut fot checking the `StreamBlockInput` is ready to do other actions.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "devabhishekpal (via GitHub)" <gi...@apache.org>.
devabhishekpal commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1794988929


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -618,6 +625,71 @@ private void decreasePendingMetricsAndReleaseSemaphore() {
     return new XceiverClientReply(replyFuture);
   }
 
+  public XceiverClientReply sendCommandAsyncReadOnly(
+      ContainerCommandRequestProto request, DatanodeDetails dn)
+      throws IOException, InterruptedException {
+
+    CompletableFuture<ContainerCommandResponseProto> future =
+        new CompletableFuture<>();
+    ContainerCommandResponseProto.Builder response =
+        ContainerCommandResponseProto.newBuilder();
+    ContainerProtos.ReadBlockResponseProto.Builder readBlock =
+        ContainerProtos.ReadBlockResponseProto.newBuilder();
+    checkOpen(dn);
+    UUID dnID = dn.getUuid();
+    Type cmdType = request.getCmdType();
+    semaphore.acquire();
+    long requestTime = System.currentTimeMillis();
+    metrics.incrPendingContainerOpsMetrics(cmdType);
+
+    final StreamObserver<ContainerCommandRequestProto> requestObserver =
+        asyncStubs.get(dnID).withDeadlineAfter(timeout, TimeUnit.SECONDS)
+            .send(new StreamObserver<ContainerCommandResponseProto>() {
+              @Override
+              public void onNext(
+                  ContainerCommandResponseProto responseProto) {
+                ReadChunkResponseProto readChunk =
+                    responseProto.getReadChunk();
+                if (responseProto.getResult() == Result.SUCCESS) {
+                  readBlock.addReadChunk(readChunk);
+                } else {
+                  future.complete(
+                      ContainerCommandResponseProto.newBuilder(responseProto)
+                          .setCmdType(Type.StreamRead).build());
+                }
+              }
+
+              @Override
+              public void onError(Throwable t) {
+                future.completeExceptionally(t);
+                metrics.decrPendingContainerOpsMetrics(cmdType);
+                metrics.addContainerOpsLatency(
+                    cmdType, System.currentTimeMillis() - requestTime);
+
+              }
+
+              @Override
+              public void onCompleted() {
+                if (readBlock.getReadChunkCount() > 0) {
+                  future.complete(response.setReadBlock(readBlock)
+                      .setCmdType(Type.StreamRead).setResult(Result.SUCCESS).build());
+                }
+                if (!future.isDone()) {
+                  future.completeExceptionally(new IOException(
+                      "Stream completed but no reply for request " +
+                          processForDebug(request)));
+                }

Review Comment:
   Thanks for clearing this



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "guohao-rosicky (via GitHub)" <gi...@apache.org>.
guohao-rosicky commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-2611397881

   Can you resolve the code conflict? @chungen0126 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "chungen0126 (via GitHub)" <gi...@apache.org>.
chungen0126 commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1873764955


##########
hadoop-hdds/client/src/test/java/org/apache/hadoop/hdds/scm/storage/TestStreamBlockInputStream.java:
##########
@@ -0,0 +1,272 @@
+/*
+ * 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 java.io.EOFException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Random;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.Function;
+
+import com.google.common.primitives.Bytes;
+import org.apache.hadoop.hdds.client.BlockID;
+import org.apache.hadoop.hdds.client.ContainerBlockID;
+import org.apache.hadoop.hdds.conf.OzoneConfiguration;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ChecksumType;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ChunkInfo;
+import org.apache.hadoop.hdds.scm.OzoneClientConfig;
+import org.apache.hadoop.hdds.scm.pipeline.MockPipeline;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.ozone.common.Checksum;
+
+import org.apache.ratis.thirdparty.com.google.protobuf.ByteString;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.Mockito.mock;
+
+/**
+ * Tests for {@link TestStreamBlockInputStream}'s functionality.
+ */
+public class TestStreamBlockInputStream {
+  private int blockSize;
+  private static final int CHUNK_SIZE = 100;
+  private static final int BYTES_PER_CHECKSUM = 20;

Review Comment:
   I don't think we need to add this test case. Logically, BYTES_PER_CHECKSUM should be smaller than CHUNK_SIZE. Otherwise, a single chunk file cannot be verified.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "ChenSammi (via GitHub)" <gi...@apache.org>.
ChenSammi commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1866988748


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -618,6 +624,69 @@ private void decreasePendingMetricsAndReleaseSemaphore() {
     return new XceiverClientReply(replyFuture);
   }
 
+  public XceiverClientReply sendCommandReadBlock(
+      ContainerCommandRequestProto request, DatanodeDetails dn)
+      throws IOException, InterruptedException {
+
+    CompletableFuture<ContainerCommandResponseProto> future =
+        new CompletableFuture<>();
+    ContainerCommandResponseProto.Builder response =
+        ContainerCommandResponseProto.newBuilder();
+    ContainerProtos.ReadBlockResponseProto.Builder readBlock =
+        ContainerProtos.ReadBlockResponseProto.newBuilder();
+    checkOpen(dn);
+    UUID dnID = dn.getUuid();
+    Type cmdType = request.getCmdType();
+    semaphore.acquire();
+    long requestTime = System.currentTimeMillis();
+    metrics.incrPendingContainerOpsMetrics(cmdType);
+
+    final StreamObserver<ContainerCommandRequestProto> requestObserver =
+        asyncStubs.get(dnID).withDeadlineAfter(timeout, TimeUnit.SECONDS)
+            .send(new StreamObserver<ContainerCommandResponseProto>() {
+              @Override
+              public void onNext(
+                  ContainerCommandResponseProto responseProto) {
+                if (responseProto.getResult() == Result.SUCCESS) {
+                  readBlock.addReadChunk(responseProto.getReadChunk());
+                } else {
+                  future.complete(

Review Comment:
   Can directly use future.complete(responseProto) here, instead of the if else detection? 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "chungen0126 (via GitHub)" <gi...@apache.org>.
chungen0126 commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1867497656


##########
hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/keyvalue/KeyValueHandler.java:
##########
@@ -1345,6 +1349,114 @@ public void deleteUnreferenced(Container container, long localID)
     }
   }
 
+  @Override
+  public ContainerCommandResponseProto streamDataReadOnly(
+      ContainerCommandRequestProto request, KeyValueContainer kvContainer,
+      DispatcherContext dispatcherContext,
+      StreamObserver<ContainerCommandResponseProto> streamObserver) {
+    ContainerCommandResponseProto responseProto = null;
+    try {
+      if (!request.hasReadBlock()) {
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("Malformed Read Block request. trace ID: {}",
+              request.getTraceID());
+        }
+        return malformedRequest(request);
+      }
+      ReadBlockRequestProto readBlock = request.getReadBlock();
+
+      BlockID blockID = BlockID.getFromProtobuf(
+          readBlock.getBlockID());
+      // This is a new api the block should always be checked.
+      BlockUtils.verifyReplicaIdx(kvContainer, blockID);
+      BlockUtils.verifyBCSId(kvContainer, blockID);
+
+      BlockData blockData = getBlockManager().getBlock(kvContainer, blockID);
+      List<ContainerProtos.ChunkInfo> chunkInfos = blockData.getChunks();
+      long blockOffset = 0;
+      int chunkIndex = -1;
+      long chunkOffset = 0;
+      long offset = readBlock.getOffset();
+      for (int i = 0; i < chunkInfos.size(); i++) {
+        final long chunkLen = chunkInfos.get(i).getLen();
+        blockOffset += chunkLen;
+        if (blockOffset > offset) {
+          chunkIndex = i;
+          chunkOffset = offset - blockOffset + chunkLen;
+          break;
+        }
+      }
+      Preconditions.checkState(chunkIndex >= 0);
+
+      if (dispatcherContext == null) {
+        dispatcherContext = DispatcherContext.getHandleReadBlock();
+      }
+
+      ChunkBuffer data;
+
+      long len =  readBlock.getLen();
+      long adjustedChunkOffset, adjustedChunkLen;
+      do {
+        ContainerProtos.ChunkInfo chunk = chunkInfos.get(chunkIndex);
+        if (readBlock.getVerifyChecksum()) {

Review Comment:
   > Why not do this check and adjust on client side?
   
   If we want to adjust the offset and length on client side, we need to get block info before reading block. In the original implementation, we get block info first and then read chunks, but now we're going to read block data directly.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "adoroszlai (via GitHub)" <gi...@apache.org>.
adoroszlai commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-2658883730

   Temporarily converted to draft and assigned to myself, to resolve conflicts.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-3366949726

   ```
   2025-10-03 12:19:41,888 [ForkJoinPool-1-worker-19] INFO  scm.XceiverClientGrpc (XceiverClientGrpc.java:sendCommandReadBlock(707)) - XXX XceiverClientGrpc-1 -> ac34f208-d979-4c47-be08-1555840ad752(10.96.128.204/10.96.128.204), onNext : request 1 bytes
   2025-10-03 12:19:41,906 [grpc-default-executor-2] INFO  scm.XceiverClientGrpc (XceiverClientGrpc.java:onNext(667)) - XXX XceiverClientGrpc-1 -> ac34f208-d979-4c47-be08-1555840ad752(10.96.128.204/10.96.128.204), onNext 1: response 262144 bytes
   2025-10-03 12:19:41,906 [grpc-default-executor-2] INFO  scm.XceiverClientGrpc (XceiverClientGrpc.java:onCompleted(689)) - XXX XceiverClientGrpc-1 -> ac34f208-d979-4c47-be08-1555840ad752(10.96.128.204/10.96.128.204), onCompleted
   2025-10-03 12:19:41,911 [ForkJoinPool-1-worker-19] INFO  scm.XceiverClientGrpc (XceiverClientGrpc.java:sendCommandReadBlock(707)) - XXX XceiverClientGrpc-1 -> ac34f208-d979-4c47-be08-1555840ad752(10.96.128.204/10.96.128.204), onNext : request 131072 bytes
   2025-10-03 12:19:41,919 [grpc-default-executor-0] INFO  scm.XceiverClientGrpc (XceiverClientGrpc.java:onNext(667)) - XXX XceiverClientGrpc-1 -> ac34f208-d979-4c47-be08-1555840ad752(10.96.128.204/10.96.128.204), onNext 1: response 262144 bytes
   2025-10-03 12:19:41,919 [grpc-default-executor-0] INFO  scm.XceiverClientGrpc (XceiverClientGrpc.java:onCompleted(689)) - XXX XceiverClientGrpc-1 -> ac34f208-d979-4c47-be08-1555840ad752(10.96.128.204/10.96.128.204), onCompleted
   2025-10-03 12:19:41,923 [ForkJoinPool-1-worker-19] INFO  scm.XceiverClientGrpc (XceiverClientGrpc.java:sendCommandReadBlock(707)) - XXX XceiverClientGrpc-1 -> ac34f208-d979-4c47-be08-1555840ad752(10.96.128.204/10.96.128.204), onNext : request 393216 bytes
   2025-10-03 12:19:41,927 [grpc-default-executor-2] INFO  scm.XceiverClientGrpc (XceiverClientGrpc.java:onNext(667)) - XXX XceiverClientGrpc-1 -> ac34f208-d979-4c47-be08-1555840ad752(10.96.128.204/10.96.128.204), onNext 1: response 524288 bytes
   2025-10-03 12:19:41,927 [grpc-default-executor-2] INFO  scm.XceiverClientGrpc (XceiverClientGrpc.java:onCompleted(689)) - XXX XceiverClientGrpc-1 -> ac34f208-d979-4c47-be08-1555840ad752(10.96.128.204/10.96.128.204), onCompleted
   ...
   ```
   Added some debug messages as below.  As shown in the output above, the current change does not work as expected:
   -  the client calls onCompleted right after each onNext  (thanks @sodonnel for pointing it out), and
   - the request lengths and the response lengths look quite random.
   
   ```diff
   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 09e01593fe..dfee5b7946 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
   @@ -30,11 +30,14 @@
    import java.util.List;
    import java.util.Map;
    import java.util.Objects;
   +import java.util.Optional;
    import java.util.concurrent.CompletableFuture;
    import java.util.concurrent.ConcurrentHashMap;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.Semaphore;
    import java.util.concurrent.TimeUnit;
   +import java.util.concurrent.atomic.AtomicInteger;
   +
    import org.apache.hadoop.hdds.HddsConfigKeys;
    import org.apache.hadoop.hdds.HddsUtils;
    import org.apache.hadoop.hdds.conf.ConfigurationSource;
   @@ -102,6 +105,9 @@ public class XceiverClientGrpc extends XceiverClientSpi {
    
      private boolean closed = false;
    
   +
   +  static final AtomicInteger idGenerator = new AtomicInteger(0);
   +  private final String name = getClass().getSimpleName() + "-" + idGenerator.incrementAndGet();
      /**
       * Constructs a client that can communicate with the Container framework on
       * data nodes via DatanodeClientProtocol.
   @@ -649,11 +655,18 @@ public XceiverClientReply sendCommandReadBlock(
        final StreamObserver<ContainerCommandRequestProto> requestObserver =
            asyncStubs.get(dnId).withDeadlineAfter(timeout, TimeUnit.SECONDS)
                .send(new StreamObserver<ContainerCommandResponseProto>() {
   +              int step = 0;
                  @Override
                  public void onNext(
                      ContainerCommandResponseProto responseProto) {
   +                final ContainerProtos.ReadChunkResponseProto chunk = responseProto.getReadChunk();
   +                final Long length = Optional.ofNullable(chunk)
   +                    .map(ContainerProtos.ReadChunkResponseProto::getChunkData)
   +                    .map(ContainerProtos.ChunkInfo::getLen)
   +                    .orElse(null);
   +                LOG.info("XXX {} -> {}, onNext {}: response {} bytes", name, dn, ++step, length);
                    if (responseProto.getResult() == Result.SUCCESS) {
   -                  readBlock.addReadChunk(responseProto.getReadChunk());
   +                  readBlock.addReadChunk(chunk);
                    } else {
                      future.complete(
                          ContainerCommandResponseProto.newBuilder(responseProto)
   @@ -663,6 +676,7 @@ public void onNext(
    
                  @Override
                  public void onError(Throwable t) {
   +                LOG.info("XXX {} -> {}, onError", name, dn);
                    future.completeExceptionally(t);
                    metrics.decrPendingContainerOpsMetrics(cmdType);
                    metrics.addContainerOpsLatency(
   @@ -672,6 +686,7 @@ public void onError(Throwable t) {
    
                  @Override
                  public void onCompleted() {
   +                LOG.info("XXX {} -> {}, onCompleted", name, dn);
                    if (readBlock.getReadChunkCount() > 0) {
                      future.complete(response.setReadBlock(readBlock)
                          .setCmdType(Type.ReadBlock).setResult(Result.SUCCESS).build());
   @@ -687,6 +702,9 @@ public void onCompleted() {
                    semaphore.release();
                  }
                });
   +
   +
   +    LOG.info("XXX {} -> {}, onNext : request {} bytes", name, dn, request.getReadBlock().getLen());
        requestObserver.onNext(request);
        requestObserver.onCompleted();
        return new XceiverClientReply(future);
   diff --git a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/client/rpc/read/TestInputStreamBase.java b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/client/rpc/read/TestInputStreamBase.java
   index 79ef3f50b2..3cf5fac163 100644
   --- a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/client/rpc/read/TestInputStreamBase.java
   +++ b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/client/rpc/read/TestInputStreamBase.java
   @@ -68,7 +68,7 @@ protected static MiniOzoneCluster newCluster() throws Exception {
    
        ReplicationManagerConfiguration repConf =
            conf.getObject(ReplicationManagerConfiguration.class);
   -    repConf.setInterval(Duration.ofSeconds(1));
   +    repConf.setInterval(Duration.ofSeconds(10));
        conf.setFromObject(repConf);
    
        ClientConfigForTesting.newBuilder(StorageUnit.BYTES)
   diff --git a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/client/rpc/read/TestStreamBlockInputStream.java b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/client/rpc/read/TestStreamBlockInputStream.java
   index 80ae511846..1b97207c59 100644
   --- a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/client/rpc/read/TestStreamBlockInputStream.java
   +++ b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/client/rpc/read/TestStreamBlockInputStream.java
   @@ -36,6 +36,7 @@
    import org.apache.hadoop.ozone.container.common.impl.ContainerLayoutVersion;
    import org.apache.hadoop.ozone.container.keyvalue.ContainerLayoutTestInfo;
    import org.apache.hadoop.ozone.om.TestBucket;
   +import org.junit.jupiter.api.Test;
    
    /**
     * Tests {@link StreamBlockInputStream}.
   @@ -45,8 +46,8 @@ public class TestStreamBlockInputStream extends TestInputStreamBase {
       * Run the tests as a single test method to avoid needing a new mini-cluster
       * for each test.
       */
   -  @ContainerLayoutTestInfo.ContainerTest
   -  void testAll(ContainerLayoutVersion layout) throws Exception {
   +  @Test
   +  public void testAll() throws Exception {
        try (MiniOzoneCluster cluster = newCluster()) {
          cluster.waitForClusterToBeReady();
    
   @@ -56,7 +57,7 @@ void testAll(ContainerLayoutVersion layout) throws Exception {
          OzoneConfiguration copy = new OzoneConfiguration(conf);
          copy.setFromObject(clientConfig);
          try (OzoneClient client = OzoneClientFactory.getRpcClient(copy)) {
   ```


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-3537175016

   All three cases: [test.log](https://github.com/user-attachments/files/23564912/test.log)
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "sodonnel (via GitHub)" <gi...@apache.org>.
sodonnel commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r2547626698


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -504,6 +515,62 @@ private XceiverClientReply sendCommandWithRetry(
     }
   }
 
+  /**
+   * Starts a streaming read operation, intended to read entire blocks from the datanodes. This method expects a
+   * {@link StreamingReaderSpi} to be passed in, which will be used to receive the streamed data from the datanode.
+   * Upon successfully starting the streaming read, a {@link StreamingReadResponse} is set into the pass StreamObserver,
+   * which contains information about the datanode used for the read, and the request observer that can be used to
+   * manage the stream (e.g., to cancel it if needed). A semaphore is acquired to limit the number of concurrent
+   * streaming reads so upon successful return of this method, the caller must ensure to call
+   * {@link #completeStreamRead()} to release the semaphore once the streaming read is complete.
+   * @param request The container command request to initiate the streaming read.
+   * @param streamObserver The observer that will handle the streamed responses.=
+   * @throws IOException
+   * @throws InterruptedException
+   */
+  @Override
+  public void streamRead(ContainerCommandRequestProto request,
+      StreamingReaderSpi streamObserver) throws IOException, InterruptedException {
+    List<DatanodeDetails> datanodeList = sortDatanodes(request);
+    IOException lastException = null;
+    for (DatanodeDetails dn : datanodeList) {
+      try {
+        checkOpen(dn);
+        semaphore.acquire();
+        XceiverClientProtocolServiceStub stub = asyncStubs.get(dn.getID());
+        if (stub == null) {
+          throw new IOException("Failed to get gRPC stub for DataNode: " + dn);
+        }
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("Executing command {} on datanode {}", processForDebug(request), dn);
+        }
+        stub.withDeadlineAfter(timeout, TimeUnit.SECONDS)
+            .streamBlock(request, streamObserver);
+        streamObserver.setStreamingDatanode(dn);
+        return;

Review Comment:
   Yes, it iterates over the list of available datanodes, and uses the first one that works. If the first one fails to connect, it will try to use the next one etc.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "chungen0126 (via GitHub)" <gi...@apache.org>.
chungen0126 commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-3561670170

   Thanks @sodonnel for the update and @szetszwo for the review. After reviewing the discussion above , have we considered implementing gRPC flow control here? I think that could effectively free up the blocked threads.
   
   Please refer to: 
   https://grpc.io/docs/guides/flow-control/
   
   Additionally, since we are optimizing the read path by switching from a unary request to streaming, the size of the TCP socket buffer might impact performance. I think we should expose this configuration to allow users to tune it.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r2461180608


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -504,6 +516,65 @@ private XceiverClientReply sendCommandWithRetry(
     }
   }
 
+  /**
+   * Starts a streaming read operation, intended to read entire blocks from the datanodes. This method expects a
+   * {@link StreamObserver} to be passed in, which will be used to receive the streamed data from the datanode.
+   * Upon successfully starting the streaming read, a {@link StreamingReadResponse} is returned, which contains
+   * information about the datanode used for the read, and the request observer that can be used to manage the stream
+   * (e.g., to cancel it if needed). A semaphore is acquired to limit the number of concurrent streaming reads so upon
+   * successful return of this method, the caller must ensure to call {@link #completeStreamRead(StreamingReadResponse)}
+   * to release the semaphore once the streaming read is complete.
+   * @param request The container command request to initiate the streaming read.
+   * @param streamObserver The observer that will handle the streamed responses.
+   * @return A {@link StreamingReadResponse} containing details of the streaming read operation.
+   * @throws IOException
+   * @throws InterruptedException
+   */
+  @Override
+  public StreamingReadResponse streamRead(ContainerCommandRequestProto request,
+      StreamObserver<ContainerCommandResponseProto> streamObserver) throws IOException, InterruptedException {
+    List<DatanodeDetails> datanodeList = sortDatanodes(request);
+    IOException lastException = null;
+    for (DatanodeDetails dn : datanodeList) {
+      try {
+        checkOpen(dn);
+        semaphore.acquire();
+        XceiverClientProtocolServiceStub stub = asyncStubs.get(dn.getID());
+        if (stub == null) {
+          throw new IOException("Failed to get gRPC stub for DataNode: " + dn);
+        }
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("Executing command {} on datanode {}", processForDebug(request), dn);
+        }
+        StreamObserver<ContainerCommandRequestProto> requestObserver = stub
+            .withDeadlineAfter(timeout, TimeUnit.SECONDS)
+            .send(streamObserver);
+        requestObserver.onNext(request);
+        requestObserver.onCompleted();
+        return new StreamingReadResponse(dn, (ClientCallStreamObserver<ContainerCommandRequestProto>) requestObserver);

Review Comment:
   > However its still not clear to me if I need to call onComplete()  ...
   
   It should not be.   If we call `onComplete()` right after `onNext()`, a gRPC stream can only send one request with a fixed length.  Then, a stream won't be able to support multiple read() calls below or it has to read the entire blocks even for a small length.
   
   Suppose a block has 128 MB.
   - Case 1
   1. A client application opens the file.
   2. It calls read() with 10KB initially
   3. It calls read() with 50MB more.
   4. ...  // the client could call read() any number of times with an arbitrary length.
   
   - Case 2
   1. A client application opens the file.
   2. It calls read() with 10KB.
   3. It leaves the file open for 1 minute.
   4. It closes the file.
   
   If we only have one request per stream, how to set the data length for both cases?   If we read the entire block all the time, Case 2 is inefficient. Otherwise, we don't read the entire block.  Then, it has to open multiple gRPC streams for Case 1.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r2461180608


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -504,6 +516,65 @@ private XceiverClientReply sendCommandWithRetry(
     }
   }
 
+  /**
+   * Starts a streaming read operation, intended to read entire blocks from the datanodes. This method expects a
+   * {@link StreamObserver} to be passed in, which will be used to receive the streamed data from the datanode.
+   * Upon successfully starting the streaming read, a {@link StreamingReadResponse} is returned, which contains
+   * information about the datanode used for the read, and the request observer that can be used to manage the stream
+   * (e.g., to cancel it if needed). A semaphore is acquired to limit the number of concurrent streaming reads so upon
+   * successful return of this method, the caller must ensure to call {@link #completeStreamRead(StreamingReadResponse)}
+   * to release the semaphore once the streaming read is complete.
+   * @param request The container command request to initiate the streaming read.
+   * @param streamObserver The observer that will handle the streamed responses.
+   * @return A {@link StreamingReadResponse} containing details of the streaming read operation.
+   * @throws IOException
+   * @throws InterruptedException
+   */
+  @Override
+  public StreamingReadResponse streamRead(ContainerCommandRequestProto request,
+      StreamObserver<ContainerCommandResponseProto> streamObserver) throws IOException, InterruptedException {
+    List<DatanodeDetails> datanodeList = sortDatanodes(request);
+    IOException lastException = null;
+    for (DatanodeDetails dn : datanodeList) {
+      try {
+        checkOpen(dn);
+        semaphore.acquire();
+        XceiverClientProtocolServiceStub stub = asyncStubs.get(dn.getID());
+        if (stub == null) {
+          throw new IOException("Failed to get gRPC stub for DataNode: " + dn);
+        }
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("Executing command {} on datanode {}", processForDebug(request), dn);
+        }
+        StreamObserver<ContainerCommandRequestProto> requestObserver = stub
+            .withDeadlineAfter(timeout, TimeUnit.SECONDS)
+            .send(streamObserver);
+        requestObserver.onNext(request);
+        requestObserver.onCompleted();
+        return new StreamingReadResponse(dn, (ClientCallStreamObserver<ContainerCommandRequestProto>) requestObserver);

Review Comment:
   > However its still not clear to me if I need to call onComplete()  ...
   
   It should not be.   If we call `onComplete()` right after `onNext()`, a gRPC stream can only send one request with a fixed length.  Then, a stream won't be able to support multiple read below or it has to read the entire blocks all the time.
   
   Suppose A block has 128 MB.
   - Case 1
   1. A client application opens the file.
   2. It calls read() with 10KB initially
   3. It calls read() with 50MB more.
   4. ...  // the client could call read() any number of times with an arbitrary length.
   
   - Case 2
   1. A client application opens the file.
   2. It calls read() with 10KB.
   3. It leaves the file open for 1 minute.
   4. It closes the file.
   
   If we only have one request per stream, how to set the data length for both cases?   If we read the entire block all the time, Case 2 is inefficient. Otherwise, we don't read the entire block.  Then, it has to open multiple gRPC streams for Case 1.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "sodonnel (via GitHub)" <gi...@apache.org>.
sodonnel commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r2559615191


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/StreamBlockInputStream.java:
##########
@@ -0,0 +1,451 @@
+/*
+ * 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 java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+import org.apache.commons.lang3.NotImplementedException;
+import org.apache.hadoop.fs.ByteBufferReadable;
+import org.apache.hadoop.fs.CanUnbuffer;
+import org.apache.hadoop.fs.FSExceptionMessages;
+import org.apache.hadoop.fs.Seekable;
+import org.apache.hadoop.hdds.client.BlockID;
+import org.apache.hadoop.hdds.protocol.DatanodeDetails;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadBlockResponseProto;
+import org.apache.hadoop.hdds.scm.OzoneClientConfig;
+import org.apache.hadoop.hdds.scm.StreamingReaderSpi;
+import org.apache.hadoop.hdds.scm.XceiverClientFactory;
+import org.apache.hadoop.hdds.scm.XceiverClientSpi;
+import org.apache.hadoop.hdds.scm.container.common.helpers.StorageContainerException;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.hdds.security.token.OzoneBlockTokenIdentifier;
+import org.apache.hadoop.io.retry.RetryPolicy;
+import org.apache.hadoop.ozone.common.Checksum;
+import org.apache.hadoop.ozone.common.ChecksumData;
+import org.apache.hadoop.ozone.common.OzoneChecksumException;
+import org.apache.hadoop.security.token.Token;
+import org.apache.ratis.thirdparty.io.grpc.StatusRuntimeException;
+import org.apache.ratis.thirdparty.io.grpc.stub.ClientCallStreamObserver;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * An {@link java.io.InputStream} called from KeyInputStream to read a block from the
+ * container.
+ */
+public class StreamBlockInputStream extends BlockExtendedInputStream
+    implements Seekable, CanUnbuffer, ByteBufferReadable {
+  private static final Logger LOG = LoggerFactory.getLogger(StreamBlockInputStream.class);
+  private static final int EOF = -1;
+  private static final Throwable CANCELLED_EXCEPTION = new Throwable("Cancelled by client");
+
+  private final BlockID blockID;
+  private final long blockLength;
+  private final AtomicReference<Pipeline> pipelineRef = new AtomicReference<>();
+  private final AtomicReference<Token<OzoneBlockTokenIdentifier>> tokenRef = new AtomicReference<>();
+  private XceiverClientFactory xceiverClientFactory;
+  private XceiverClientSpi xceiverClient;
+
+  private ByteBuffer buffer;
+  private long position = 0;
+  private boolean initialized = false;
+  private StreamingReader streamingReader;
+
+  private final boolean verifyChecksum;
+  private final Function<BlockID, BlockLocationInfo> refreshFunction;
+  private final RetryPolicy retryPolicy;
+  private int retries = 0;
+
+  public StreamBlockInputStream(
+      BlockID blockID, long length, Pipeline pipeline,
+      Token<OzoneBlockTokenIdentifier> token,
+      XceiverClientFactory xceiverClientFactory,
+      Function<BlockID, BlockLocationInfo> refreshFunction,
+      OzoneClientConfig config) throws IOException {
+    this.blockID = blockID;
+    this.blockLength = length;
+    pipelineRef.set(setPipeline(pipeline));
+    tokenRef.set(token);
+    this.xceiverClientFactory = xceiverClientFactory;
+    this.verifyChecksum = config.isChecksumVerify();
+    this.retryPolicy = getReadRetryPolicy(config);
+    this.refreshFunction = refreshFunction;
+  }
+
+  @Override
+  public BlockID getBlockID() {
+    return blockID;
+  }
+
+  @Override
+  public long getLength() {
+    return blockLength;
+  }
+
+  @Override
+  public synchronized long getPos() {
+    return position;
+  }
+
+  @Override
+  public synchronized int read() throws IOException {
+    checkOpen();
+    if (!dataAvailableToRead()) {
+      return EOF;
+    }
+    position++;
+    return buffer.get();
+  }
+
+  @Override
+  public synchronized int read(byte[] b, int off, int len) throws IOException {
+    ByteBuffer tmpBuffer = ByteBuffer.wrap(b, off, len);
+    return read(tmpBuffer);
+  }
+
+  @Override
+  public synchronized int read(ByteBuffer targetBuf) throws IOException {
+    checkOpen();
+    int read = 0;
+    while (targetBuf.hasRemaining()) {
+      if (!dataAvailableToRead()) {
+        break;
+      }
+      int toCopy = Math.min(buffer.remaining(), targetBuf.remaining());
+      ByteBuffer tmpBuf = buffer.duplicate();
+      tmpBuf.limit(tmpBuf.position() + toCopy);
+      targetBuf.put(tmpBuf);
+      buffer.position(tmpBuf.position());
+      position += toCopy;
+      read += toCopy;
+    }
+    return read > 0 ? read : EOF;
+  }
+
+  private boolean dataAvailableToRead() throws IOException {
+    if (position >= blockLength) {
+      return false;
+    }
+    initialize();
+    if (buffer == null || buffer.remaining() == 0) {
+      int loaded = fillBuffer();
+      return loaded != EOF;
+    }
+    return true;
+  }
+
+  @Override
+  protected int readWithStrategy(ByteReaderStrategy strategy) throws IOException {
+    throw new NotImplementedException("readWithStrategy is not implemented.");
+  }
+
+  @Override
+  public synchronized void seek(long pos) throws IOException {
+    checkOpen();
+    if (pos < 0) {
+      throw new IOException("Cannot seek to negative offset");
+    }
+    if (pos > blockLength) {
+      throw new IOException("Cannot seek after the end of the block");
+    }
+    if (pos == position) {
+      return;
+    }
+    closeStream();
+    position = pos;
+  }
+
+  @Override
+  // The seekable interface indicates that seekToNewSource should seek to a new source of the data,
+  // ie a different datanode. This is not supported for now.
+  public synchronized boolean seekToNewSource(long l) throws IOException {
+    return false;
+  }
+
+  @Override
+  public synchronized void unbuffer() {
+    releaseClient();
+  }
+
+  private void closeStream() {
+    if (streamingReader != null) {
+      streamingReader.cancel();
+      streamingReader = null;
+    }
+    initialized = false;
+    buffer = null;
+  }
+
+  protected synchronized void checkOpen() throws IOException {
+    if (xceiverClientFactory == null) {
+      throw new IOException(FSExceptionMessages.STREAM_IS_CLOSED + " Block: " + blockID);
+    }
+  }
+
+  protected synchronized void acquireClient() throws IOException {
+    checkOpen();
+    if (xceiverClient == null) {
+      final Pipeline pipeline = pipelineRef.get();
+      try {
+        xceiverClient = xceiverClientFactory.acquireClientForReadData(pipeline);
+      } catch (IOException ioe) {
+        LOG.warn("Failed to acquire client for pipeline {}, block {}", pipeline, blockID);
+        throw ioe;
+      }
+    }
+  }
+
+  private void initialize() throws IOException {
+    if (initialized) {
+      return;
+    }
+    while (true) {
+      try {
+        acquireClient();
+        streamingReader = new StreamingReader();
+        ContainerProtocolCalls.readBlock(xceiverClient, position, blockID, tokenRef.get(),
+            pipelineRef.get().getReplicaIndexes(), streamingReader);
+        initialized = true;
+        return;
+      } catch (InterruptedException ie) {
+        Thread.currentThread().interrupt();
+        handleExceptions(new IOException("Interrupted", ie));
+      } catch (IOException ioe) {
+        handleExceptions(ioe);
+      }
+    }
+  }
+
+  private void handleExceptions(IOException cause) throws IOException {
+    if (cause instanceof StorageContainerException || isConnectivityIssue(cause)) {
+      if (shouldRetryRead(cause, retryPolicy, retries++)) {
+        releaseClient();
+        refreshBlockInfo(cause);
+        LOG.warn("Refreshing block data to read block {} due to {}", blockID, cause.getMessage());
+      } else {
+        throw cause;
+      }
+    } else {
+      throw cause;
+    }
+  }
+
+  private int fillBuffer() throws IOException {
+    if (!streamingReader.hasNext()) {
+      return EOF;
+    }
+    buffer = streamingReader.readNext();
+    return buffer == null ? EOF : buffer.limit();
+  }
+
+  protected synchronized void releaseClient() {
+    if (xceiverClientFactory != null && xceiverClient != null) {
+      closeStream();
+      xceiverClientFactory.releaseClientForReadData(xceiverClient, false);
+      xceiverClient = null;
+    }
+  }
+
+  @Override
+  public synchronized void close() throws IOException {
+    releaseClient();
+    xceiverClientFactory = null;
+  }
+
+  private void refreshBlockInfo(IOException cause) throws IOException {
+    refreshBlockInfo(cause, blockID, pipelineRef, tokenRef, refreshFunction);
+  }
+
+  private synchronized void releaseStreamResources() {
+    if (xceiverClient != null) {
+      xceiverClient.completeStreamRead();
+    }
+  }
+
+  /**
+   * Implementation of a StreamObserver used to received and buffer streaming GRPC reads.
+   */
+  public class StreamingReader implements StreamingReaderSpi {
+
+    private final BlockingQueue<ContainerProtos.ReadBlockResponseProto> responseQueue = new LinkedBlockingQueue<>(1);
+    private final AtomicBoolean completed = new AtomicBoolean(false);
+    private final AtomicBoolean failed = new AtomicBoolean(false);
+    private final AtomicBoolean semaphoreReleased = new AtomicBoolean(false);
+    private final AtomicReference<Throwable> error = new AtomicReference<>();
+    private volatile ClientCallStreamObserver<ContainerProtos.ContainerCommandRequestProto> requestObserver;
+    private volatile DatanodeDetails streamingDatanodeDetails;
+
+    public boolean hasNext() {
+      return !responseQueue.isEmpty() || !completed.get();
+    }
+
+    public ByteBuffer readNext() throws IOException {
+      if (failed.get()) {
+        Throwable cause = error.get();
+        throw new IOException("Streaming read failed", cause);
+      }
+
+      if (completed.get() && responseQueue.isEmpty()) {
+        return null; // Stream ended
+      }
+
+      ReadBlockResponseProto readBlock;
+      try {
+        readBlock = responseQueue.poll(30, TimeUnit.SECONDS);
+      } catch (InterruptedException e) {
+        Thread.currentThread().interrupt();
+        throw new IOException("Interrupted while waiting for response", e);
+      }
+      if (readBlock == null) {
+        if (failed.get()) {
+          Throwable cause = error.get();
+          throw new IOException("Streaming read failed", cause);
+        } else if (completed.get()) {
+          return null; // Stream ended
+        } else {
+          throw new IOException("Timed out waiting for response");
+        }
+      }
+      // The server always returns data starting from the last checksum boundary. Therefore if the reader position is
+      // ahead of the position we received from the server, we need to adjust the buffer position accordingly.
+      // If the reader position is behind
+      ByteBuffer buf = readBlock.getData().asReadOnlyByteBuffer();
+      long blockOffset = readBlock.getOffset();
+      long pos = getPos();
+      if (pos < blockOffset) {
+        // This should not happen, and if it does, we have a bug.
+        throw new IOException("Received data out of order. Position is " + pos + " but received data at "
+            + blockOffset);
+      }
+      if (pos > readBlock.getOffset()) {
+        int offset = (int)(pos - readBlock.getOffset());
+        buf.position(offset);
+      }
+      return buf;
+    }
+
+    private void releaseResources() {
+      boolean wasNotYetComplete = semaphoreReleased.getAndSet(true);

Review Comment:
   Yea I think you are correct.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-3598737857

   With some change in HDDS-14035 (will submit a PR soon), the performance can be further improved to 3.3 GB/s for larger buffer sizes:
   ```
   ---------------------------------------------------------
   key8 with 256M (=268435456) bytes and 16k (=16384) bytesPerChecksum
    createStreamKey:   145.00 MB/s (  1.765 s, buffer   8MB (=8388608), keySize   256.00 MB, md5=9E 4E A5 A0 51 07 0A 17 5E E2 B2 07 09 60 95 6E)
      readStreamKey:  3273.01 MB/s (  0.078 s, buffer  32M (=33554432), keySize   256.00 MB, md5=null)
      readStreamKey:   743.80 MB/s (  0.344 s, buffer  32M (=33554432), keySize   256.00 MB, md5=9E 4E A5 A0 51 07 0A 17 5E E2 B2 07 09 60 95 6E)
      readStreamKey:  3300.60 MB/s (  0.078 s, buffer    8M (=8388608), keySize   256.00 MB, md5=null)
      readStreamKey:   776.45 MB/s (  0.330 s, buffer    8M (=8388608), keySize   256.00 MB, md5=9E 4E A5 A0 51 07 0A 17 5E E2 B2 07 09 60 95 6E)
      readStreamKey:  2282.57 MB/s (  0.112 s, buffer    1M (=1048576), keySize   256.00 MB, md5=null)
      readStreamKey:   757.36 MB/s (  0.338 s, buffer    1M (=1048576), keySize   256.00 MB, md5=9E 4E A5 A0 51 07 0A 17 5E E2 B2 07 09 60 95 6E)
      readStreamKey:  2259.09 MB/s (  0.113 s, buffer       4k (=4096), keySize   256.00 MB, md5=null)
      readStreamKey:   751.97 MB/s (  0.340 s, buffer       4k (=4096), keySize   256.00 MB, md5=9E 4E A5 A0 51 07 0A 17 5E E2 B2 07 09 60 95 6E)
   ```
   
   All JIRAs in https://github.com/apache/ozone/pull/6613#issuecomment-3564010448 have been merged.  Closing this ...


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "yandrey321 (via GitHub)" <gi...@apache.org>.
yandrey321 commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r2492281391


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/StreamBlockInputStream.java:
##########
@@ -0,0 +1,443 @@
+/*
+ * 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 java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+import org.apache.commons.lang3.NotImplementedException;
+import org.apache.hadoop.fs.ByteBufferReadable;
+import org.apache.hadoop.fs.CanUnbuffer;
+import org.apache.hadoop.fs.FSExceptionMessages;
+import org.apache.hadoop.fs.Seekable;
+import org.apache.hadoop.hdds.client.BlockID;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadBlockResponseProto;
+import org.apache.hadoop.hdds.scm.OzoneClientConfig;
+import org.apache.hadoop.hdds.scm.StreamingReadResponse;
+import org.apache.hadoop.hdds.scm.StreamingReaderSpi;
+import org.apache.hadoop.hdds.scm.XceiverClientFactory;
+import org.apache.hadoop.hdds.scm.XceiverClientSpi;
+import org.apache.hadoop.hdds.scm.container.common.helpers.StorageContainerException;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.hdds.security.token.OzoneBlockTokenIdentifier;
+import org.apache.hadoop.io.retry.RetryPolicy;
+import org.apache.hadoop.ozone.common.Checksum;
+import org.apache.hadoop.ozone.common.ChecksumData;
+import org.apache.hadoop.ozone.common.OzoneChecksumException;
+import org.apache.hadoop.security.token.Token;
+import org.apache.ratis.thirdparty.io.grpc.StatusRuntimeException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * An {@link java.io.InputStream} called from KeyInputStream to read a block from the
+ * container.
+ */
+public class StreamBlockInputStream extends BlockExtendedInputStream
+    implements Seekable, CanUnbuffer, ByteBufferReadable {
+  private static final Logger LOG = LoggerFactory.getLogger(StreamBlockInputStream.class);
+  private static final int EOF = -1;
+  private static final Throwable CANCELLED_EXCEPTION = new Throwable("Cancelled by client");
+
+  private final BlockID blockID;
+  private final long blockLength;
+  private final AtomicReference<Pipeline> pipelineRef = new AtomicReference<>();
+  private final AtomicReference<Token<OzoneBlockTokenIdentifier>> tokenRef = new AtomicReference<>();
+  private XceiverClientFactory xceiverClientFactory;
+  private XceiverClientSpi xceiverClient;
+
+  private ByteBuffer buffer;
+  private long position = 0;
+  private boolean initialized = false;
+  private StreamingReader streamingReader;
+
+  private final boolean verifyChecksum;
+  private final Function<BlockID, BlockLocationInfo> refreshFunction;
+  private final RetryPolicy retryPolicy;
+  private int retries = 0;
+
+  public StreamBlockInputStream(
+      BlockID blockID, long length, Pipeline pipeline,
+      Token<OzoneBlockTokenIdentifier> token,
+      XceiverClientFactory xceiverClientFactory,
+      Function<BlockID, BlockLocationInfo> refreshFunction,
+      OzoneClientConfig config) throws IOException {
+    this.blockID = blockID;
+    this.blockLength = length;
+    pipelineRef.set(setPipeline(pipeline));
+    tokenRef.set(token);
+    this.xceiverClientFactory = xceiverClientFactory;
+    this.verifyChecksum = config.isChecksumVerify();
+    this.retryPolicy = getReadRetryPolicy(config);
+    this.refreshFunction = refreshFunction;
+  }
+
+  @Override
+  public BlockID getBlockID() {
+    return blockID;
+  }
+
+  @Override
+  public long getLength() {
+    return blockLength;
+  }
+
+  @Override
+  public synchronized long getPos() {
+    return position;
+  }
+
+  @Override
+  public synchronized int read() throws IOException {
+    checkOpen();

Review Comment:
   it would be good to have open telemetry trace here. 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-3437815847

   @swamirishi , @devabhishekpal , since you have requested changes, could you review the latest changes?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "sodonnel (via GitHub)" <gi...@apache.org>.
sodonnel commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-3485814312

   > I may have misunderstood "small read". What do you mean by small read? (1) or (2) below?
   > 
   >     1. client opens a file, reads a small amount of data (say 4KB) and then the close the file; or
   > 
   >     2. client opens a file with a small buffer (say 4KB), keep looping calling read(buffer) for many times and then the close the file.
   
   I have been primarily looking at 2, which I believe is the most common spark, Hive type workload, where blocks are largely read completely.
   
   1 is more like an HBase use case, where it will scatter positional reads all over the file based on which part of the block its index tells it to read.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "sodonnel (via GitHub)" <gi...@apache.org>.
sodonnel commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-3481875773

   > The server always reads at least 1MB (not 16kb, not 4kb) for each onNext() calls.
   
   That is not how it works in the current production code. I traced it, and attempting to read a block with `hadoop fs -get` shows Ozone attempting to read in 4kb chunks, which get rounded up to the checksum boundary and it returns 16kb at a time. The point of the checksum change from 1MB -> 16kb by default was to allow for smaller reads, so we don't want to constrain it to be required to return 1MB at a time.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r2466555548


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -504,6 +516,65 @@ private XceiverClientReply sendCommandWithRetry(
     }
   }
 
+  /**
+   * Starts a streaming read operation, intended to read entire blocks from the datanodes. This method expects a
+   * {@link StreamObserver} to be passed in, which will be used to receive the streamed data from the datanode.
+   * Upon successfully starting the streaming read, a {@link StreamingReadResponse} is returned, which contains
+   * information about the datanode used for the read, and the request observer that can be used to manage the stream
+   * (e.g., to cancel it if needed). A semaphore is acquired to limit the number of concurrent streaming reads so upon
+   * successful return of this method, the caller must ensure to call {@link #completeStreamRead(StreamingReadResponse)}
+   * to release the semaphore once the streaming read is complete.
+   * @param request The container command request to initiate the streaming read.
+   * @param streamObserver The observer that will handle the streamed responses.
+   * @return A {@link StreamingReadResponse} containing details of the streaming read operation.
+   * @throws IOException
+   * @throws InterruptedException
+   */
+  @Override
+  public StreamingReadResponse streamRead(ContainerCommandRequestProto request,
+      StreamObserver<ContainerCommandResponseProto> streamObserver) throws IOException, InterruptedException {
+    List<DatanodeDetails> datanodeList = sortDatanodes(request);
+    IOException lastException = null;
+    for (DatanodeDetails dn : datanodeList) {
+      try {
+        checkOpen(dn);
+        semaphore.acquire();
+        XceiverClientProtocolServiceStub stub = asyncStubs.get(dn.getID());
+        if (stub == null) {
+          throw new IOException("Failed to get gRPC stub for DataNode: " + dn);
+        }
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("Executing command {} on datanode {}", processForDebug(request), dn);
+        }
+        StreamObserver<ContainerCommandRequestProto> requestObserver = stub
+            .withDeadlineAfter(timeout, TimeUnit.SECONDS)
+            .send(streamObserver);
+        requestObserver.onNext(request);
+        requestObserver.onCompleted();
+        return new StreamingReadResponse(dn, (ClientCallStreamObserver<ContainerCommandRequestProto>) requestObserver);

Review Comment:
   > ... HDFS model works well and results in relatively simple code in the approach used here ... 
   
   I agree that HDFS model works  well but the problem is that this approach is not the HDFS model:
   - HDFS: Blocking API (Socket) + Blocking threads
   - This approach: Non-blocking API (gRPC) + Blocking threads
   - Suggested approach: Non-blocking API (gRPC) + Non-blocking threads
   
   > Of course we can cache open files, ...
   
   I guess you mean the server side?  We don't have to.  The server should open the file in the first gRPC onNext() call and close it in onComplete()/onError().
   
   > ... we agreed the handler pool would need to be greatly increased. I don't see any big problem with having a very large handler pool of threads that are mostly blocked. ...
   
   Increasing handler pool for performance makes sense.  However, it is not a good solution to avoid deadlocks.
   
   BTW, how large is enough?  Would it slows down other operations for creating such a large handler pool?
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "sodonnel (via GitHub)" <gi...@apache.org>.
sodonnel commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r2463018964


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -504,6 +516,65 @@ private XceiverClientReply sendCommandWithRetry(
     }
   }
 
+  /**
+   * Starts a streaming read operation, intended to read entire blocks from the datanodes. This method expects a
+   * {@link StreamObserver} to be passed in, which will be used to receive the streamed data from the datanode.
+   * Upon successfully starting the streaming read, a {@link StreamingReadResponse} is returned, which contains
+   * information about the datanode used for the read, and the request observer that can be used to manage the stream
+   * (e.g., to cancel it if needed). A semaphore is acquired to limit the number of concurrent streaming reads so upon
+   * successful return of this method, the caller must ensure to call {@link #completeStreamRead(StreamingReadResponse)}
+   * to release the semaphore once the streaming read is complete.
+   * @param request The container command request to initiate the streaming read.
+   * @param streamObserver The observer that will handle the streamed responses.
+   * @return A {@link StreamingReadResponse} containing details of the streaming read operation.
+   * @throws IOException
+   * @throws InterruptedException
+   */
+  @Override
+  public StreamingReadResponse streamRead(ContainerCommandRequestProto request,
+      StreamObserver<ContainerCommandResponseProto> streamObserver) throws IOException, InterruptedException {
+    List<DatanodeDetails> datanodeList = sortDatanodes(request);
+    IOException lastException = null;
+    for (DatanodeDetails dn : datanodeList) {
+      try {
+        checkOpen(dn);
+        semaphore.acquire();
+        XceiverClientProtocolServiceStub stub = asyncStubs.get(dn.getID());
+        if (stub == null) {
+          throw new IOException("Failed to get gRPC stub for DataNode: " + dn);
+        }
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("Executing command {} on datanode {}", processForDebug(request), dn);
+        }
+        StreamObserver<ContainerCommandRequestProto> requestObserver = stub
+            .withDeadlineAfter(timeout, TimeUnit.SECONDS)
+            .send(streamObserver);
+        requestObserver.onNext(request);
+        requestObserver.onCompleted();
+        return new StreamingReadResponse(dn, (ClientCallStreamObserver<ContainerCommandRequestProto>) requestObserver);

Review Comment:
   There is also an option for the client to "unbuffer" if it sits idle for too long to terminate the server thread, while saving its position.
   
   I feel that the common use case is that clients consume large streams of a block or even the entire block, rather than opening and holding the file open without reading for long periods of time.
   
   I also have seen that the common read case is not "50MB", but more like 4kb - 64kb and in these cases the overhead of starting the read over including opening a seeking the block file can be significant. Many downstream InputStreams operate with quite small buffers by default, including the Hadoop FS ones. So we tend to see a lot of tiny sequential reads as they consume the block from start to end.
   
   One struggle is that there are at least 2 types of readers. The HBase style which wants to read a length at an offset scattered all over the file and the Hive / Spark type workload that scans a block from start to finish. In between is the ORC / Parquet reader where it seeks a bit to read some metadata and then does relatively large sequences of reads, but quite likely into a small buffer, pulling and processing the rows piece by piece.
   
   From this, it probably makes sense to have different modes of operation, but how that fits into existing interfaces is another problem! I don't think the same code path can be optimal for such different usage patterns.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r2463035082


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -504,6 +516,65 @@ private XceiverClientReply sendCommandWithRetry(
     }
   }
 
+  /**
+   * Starts a streaming read operation, intended to read entire blocks from the datanodes. This method expects a
+   * {@link StreamObserver} to be passed in, which will be used to receive the streamed data from the datanode.
+   * Upon successfully starting the streaming read, a {@link StreamingReadResponse} is returned, which contains
+   * information about the datanode used for the read, and the request observer that can be used to manage the stream
+   * (e.g., to cancel it if needed). A semaphore is acquired to limit the number of concurrent streaming reads so upon
+   * successful return of this method, the caller must ensure to call {@link #completeStreamRead(StreamingReadResponse)}
+   * to release the semaphore once the streaming read is complete.
+   * @param request The container command request to initiate the streaming read.
+   * @param streamObserver The observer that will handle the streamed responses.
+   * @return A {@link StreamingReadResponse} containing details of the streaming read operation.
+   * @throws IOException
+   * @throws InterruptedException
+   */
+  @Override
+  public StreamingReadResponse streamRead(ContainerCommandRequestProto request,
+      StreamObserver<ContainerCommandResponseProto> streamObserver) throws IOException, InterruptedException {
+    List<DatanodeDetails> datanodeList = sortDatanodes(request);
+    IOException lastException = null;
+    for (DatanodeDetails dn : datanodeList) {
+      try {
+        checkOpen(dn);
+        semaphore.acquire();
+        XceiverClientProtocolServiceStub stub = asyncStubs.get(dn.getID());
+        if (stub == null) {
+          throw new IOException("Failed to get gRPC stub for DataNode: " + dn);
+        }
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("Executing command {} on datanode {}", processForDebug(request), dn);
+        }
+        StreamObserver<ContainerCommandRequestProto> requestObserver = stub
+            .withDeadlineAfter(timeout, TimeUnit.SECONDS)
+            .send(streamObserver);
+        requestObserver.onNext(request);
+        requestObserver.onCompleted();
+        return new StreamingReadResponse(dn, (ClientCallStreamObserver<ContainerCommandRequestProto>) requestObserver);

Review Comment:
   > The approach used is similar to the HDFS xceiver approach, ...
   
   HDFS uses blocking API from Socket but we are using gRPC async API here.  We should not bring the HDFS xceiver approach to Ozone. 
   
   - When all the gRPC threads are blocked, any gRPC calls will be blocked.  Any commands sending to that datanode will be blocked.  (HDFS does not have such problem.)
   
   Moreover, it is easy for user applications to get a deadlock due to the problem above.  
   
   1. Suppose there are $n$ gRPC threads.
   2. Open $n+1$ files to read at the same time.  
   3. Do not close the files until the all files are processed.  // deadlock here
   
   See also
   <img width="664" height="932" alt="image" src="https://github.com/user-attachments/assets/556e144b-42f1-4ff0-816c-63debc30ac2f" />
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "yandrey321 (via GitHub)" <gi...@apache.org>.
yandrey321 commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r2491838022


##########
hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/keyvalue/KeyValueHandler.java:
##########
@@ -2046,6 +2055,86 @@ public void deleteUnreferenced(Container container, long localID)
     }
   }
 
+  @Override
+  public ContainerCommandResponseProto readBlock(
+      ContainerCommandRequestProto request, Container kvContainer,
+      DispatcherContext dispatcherContext,
+      StreamObserver<ContainerCommandResponseProto> streamObserver) {
+
+    if (kvContainer.getContainerData().getLayoutVersion() != FILE_PER_BLOCK) {
+      return ContainerUtils.logAndReturnError(LOG,
+          new StorageContainerException("Only File Per Block is supported", IO_EXCEPTION), request);
+    }
+
+    ContainerCommandResponseProto responseProto = null;
+    if (!request.hasReadBlock()) {
+      if (LOG.isDebugEnabled()) {
+        LOG.debug("Malformed Read Block request. trace ID: {}", request.getTraceID());
+      }
+      return malformedRequest(request);
+    }
+    try {
+      ReadBlockRequestProto readBlock = request.getReadBlock();
+
+      BlockID blockID = BlockID.getFromProtobuf(readBlock.getBlockID());
+      // This is a new api the block should always be checked.
+      BlockUtils.verifyReplicaIdx(kvContainer, blockID);
+      BlockUtils.verifyBCSId(kvContainer, blockID);
+
+      File blockFile = FILE_PER_BLOCK.getChunkFile(kvContainer.getContainerData(), blockID, "unused");
+
+      BlockData blockData = getBlockManager().getBlock(kvContainer, blockID);
+      List<ContainerProtos.ChunkInfo> chunkInfos = blockData.getChunks();
+      // To get the chunksize, check the first chunk. Either there is only 1 chunk and its the largest, or there are
+      // multiple chunks and they are all the same size except the last one.
+      long bytesPerChunk = chunkInfos.get(0).getLen();
+      // The bytes per checksum is stored in the checksum data of each chunk, so check the first chunk as they all
+      // must be the same.
+      ContainerProtos.ChecksumType checksumType = chunkInfos.get(0).getChecksumData().getType();
+      ChecksumData checksumData = null;
+      int bytesPerChecksum = STREAMING_BYTES_PER_CHUNK;
+      if (checksumType == ContainerProtos.ChecksumType.NONE) {
+        checksumData = new ChecksumData(checksumType, 0);
+      } else {
+        bytesPerChecksum = chunkInfos.get(0).getChecksumData().getBytesPerChecksum();
+      }
+      // We have to align the read to checksum boundaries, so whatever offset is requested, we have to move back to the
+      // previous checksum boundary.
+      // eg if bytesPerChecksum is 512, and the requested offset is 600, we have to move back to 512.
+      // If the checksum type is NONE, we don't have to do this, but using no checksums should be rare in practice and
+      // it simplifies the code to always do this.
+      long adjustedOffset = readBlock.getOffset() - readBlock.getOffset() % bytesPerChecksum;
+      try (RandomAccessFile file = new RandomAccessFile(blockFile, "r");
+           FileChannel channel = file.getChannel()) {
+        ByteBuffer buffer = ByteBuffer.allocate(bytesPerChecksum);
+        channel.position(adjustedOffset);
+        while (channel.read(buffer) != -1) {
+          buffer.flip();
+          if (checksumType != ContainerProtos.ChecksumType.NONE) {
+            // As the checksums are stored "chunk by chunk", we need to figure out which chunk we start reading from,
+            // and its offset to pull out the correct checksum bytes for each read.
+            int chunkIndex = (int) (adjustedOffset / bytesPerChunk);
+            int chunkOffset = (int) (adjustedOffset % bytesPerChunk);
+            int checksumIndex = chunkOffset / bytesPerChecksum;
+            ByteString checksum = blockData.getChunks().get(chunkIndex).getChecksumData().getChecksums(checksumIndex);
+            checksumData = new ChecksumData(checksumType, bytesPerChecksum, Collections.singletonList(checksum));
+          }
+          streamObserver.onNext(getReadBlockResponse(request, checksumData, buffer, adjustedOffset));
+          buffer.clear();
+
+          adjustedOffset += bytesPerChecksum;
+        }
+      }
+      // TODO metrics.incContainerBytesStats(Type.ReadBlock, readBlock.getLen());

Review Comment:
   can we add metrics to see how it performs vs. non-streamed implementation?



##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/ozone/client/io/BlockInputStreamFactoryImpl.java:
##########
@@ -85,11 +89,25 @@ public BlockExtendedInputStream create(ReplicationConfig repConfig,
       return new ECBlockInputStreamProxy((ECReplicationConfig)repConfig,
           blockInfo, xceiverFactory, refreshFunction,
           ecBlockStreamFactory, config);
+    } else if (config.isStreamReadBlock() && allDataNodesSupportStreamBlock(pipeline)) {

Review Comment:
   Can we do streaming for EC?



##########
hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/keyvalue/KeyValueHandler.java:
##########
@@ -172,6 +180,7 @@ public class KeyValueHandler extends Handler {
 
   private static final Logger LOG = LoggerFactory.getLogger(
       KeyValueHandler.class);
+  private static final int STREAMING_BYTES_PER_CHUNK = 1024 * 64;

Review Comment:
   Can we have a configuration param for the size?



##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/StreamBlockInputStream.java:
##########
@@ -0,0 +1,443 @@
+/*
+ * 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 java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+import org.apache.commons.lang3.NotImplementedException;
+import org.apache.hadoop.fs.ByteBufferReadable;
+import org.apache.hadoop.fs.CanUnbuffer;
+import org.apache.hadoop.fs.FSExceptionMessages;
+import org.apache.hadoop.fs.Seekable;
+import org.apache.hadoop.hdds.client.BlockID;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadBlockResponseProto;
+import org.apache.hadoop.hdds.scm.OzoneClientConfig;
+import org.apache.hadoop.hdds.scm.StreamingReadResponse;
+import org.apache.hadoop.hdds.scm.StreamingReaderSpi;
+import org.apache.hadoop.hdds.scm.XceiverClientFactory;
+import org.apache.hadoop.hdds.scm.XceiverClientSpi;
+import org.apache.hadoop.hdds.scm.container.common.helpers.StorageContainerException;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.hdds.security.token.OzoneBlockTokenIdentifier;
+import org.apache.hadoop.io.retry.RetryPolicy;
+import org.apache.hadoop.ozone.common.Checksum;
+import org.apache.hadoop.ozone.common.ChecksumData;
+import org.apache.hadoop.ozone.common.OzoneChecksumException;
+import org.apache.hadoop.security.token.Token;
+import org.apache.ratis.thirdparty.io.grpc.StatusRuntimeException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * An {@link java.io.InputStream} called from KeyInputStream to read a block from the
+ * container.
+ */
+public class StreamBlockInputStream extends BlockExtendedInputStream
+    implements Seekable, CanUnbuffer, ByteBufferReadable {
+  private static final Logger LOG = LoggerFactory.getLogger(StreamBlockInputStream.class);
+  private static final int EOF = -1;
+  private static final Throwable CANCELLED_EXCEPTION = new Throwable("Cancelled by client");
+
+  private final BlockID blockID;
+  private final long blockLength;
+  private final AtomicReference<Pipeline> pipelineRef = new AtomicReference<>();
+  private final AtomicReference<Token<OzoneBlockTokenIdentifier>> tokenRef = new AtomicReference<>();
+  private XceiverClientFactory xceiverClientFactory;
+  private XceiverClientSpi xceiverClient;
+
+  private ByteBuffer buffer;
+  private long position = 0;
+  private boolean initialized = false;
+  private StreamingReader streamingReader;
+
+  private final boolean verifyChecksum;
+  private final Function<BlockID, BlockLocationInfo> refreshFunction;
+  private final RetryPolicy retryPolicy;
+  private int retries = 0;
+
+  public StreamBlockInputStream(
+      BlockID blockID, long length, Pipeline pipeline,
+      Token<OzoneBlockTokenIdentifier> token,
+      XceiverClientFactory xceiverClientFactory,
+      Function<BlockID, BlockLocationInfo> refreshFunction,
+      OzoneClientConfig config) throws IOException {
+    this.blockID = blockID;
+    this.blockLength = length;
+    pipelineRef.set(setPipeline(pipeline));
+    tokenRef.set(token);
+    this.xceiverClientFactory = xceiverClientFactory;
+    this.verifyChecksum = config.isChecksumVerify();
+    this.retryPolicy = getReadRetryPolicy(config);
+    this.refreshFunction = refreshFunction;
+  }
+
+  @Override
+  public BlockID getBlockID() {
+    return blockID;
+  }
+
+  @Override
+  public long getLength() {
+    return blockLength;
+  }
+
+  @Override
+  public synchronized long getPos() {
+    return position;
+  }
+
+  @Override
+  public synchronized int read() throws IOException {
+    checkOpen();
+    if (!dataAvailableToRead()) {
+      return EOF;
+    }
+    position++;
+    return buffer.get();
+  }
+
+  @Override
+  public synchronized int read(byte[] b, int off, int len) throws IOException {
+    ByteBuffer tmpBuffer = ByteBuffer.wrap(b, off, len);
+    return read(tmpBuffer);
+  }
+
+  @Override
+  public synchronized int read(ByteBuffer targetBuf) throws IOException {
+    checkOpen();
+    int read = 0;
+    while (targetBuf.hasRemaining()) {
+      if (!dataAvailableToRead()) {
+        break;
+      }
+      int toCopy = Math.min(buffer.remaining(), targetBuf.remaining());
+      ByteBuffer tmpBuf = buffer.duplicate();
+      tmpBuf.limit(tmpBuf.position() + toCopy);
+      targetBuf.put(tmpBuf);
+      buffer.position(tmpBuf.position());
+      position += toCopy;
+      read += toCopy;
+    }
+    return read > 0 ? read : EOF;
+  }
+
+  private boolean dataAvailableToRead() throws IOException {
+    if (position >= blockLength) {
+      return false;
+    }
+    initialize();
+    if (buffer == null || buffer.remaining() == 0) {
+      int loaded = fillBuffer();
+      return loaded != EOF;
+    }
+    return true;
+  }
+
+  @Override
+  protected int readWithStrategy(ByteReaderStrategy strategy) throws IOException {
+    throw new NotImplementedException("readWithStrategy is not implemented.");
+  }
+
+  @Override
+  public synchronized void seek(long pos) throws IOException {
+    checkOpen();
+    if (pos < 0) {
+      throw new IOException("Cannot seek to negative offset");
+    }
+    if (pos > blockLength) {
+      throw new IOException("Cannot seek after the end of the block");
+    }
+    if (pos == position) {
+      return;
+    }
+    closeStream();
+    position = pos;
+  }
+
+  @Override
+  // The seekable interface indicates that seekToNewSource should seek to a new source of the data,
+  // ie a different datanode. This is not supported for now.
+  public synchronized boolean seekToNewSource(long l) throws IOException {
+    return false;
+  }
+
+  @Override
+  public synchronized void unbuffer() {
+    releaseClient();
+  }
+
+  private void closeStream() {
+    if (streamingReader != null) {
+      streamingReader.cancel();
+      streamingReader = null;
+    }
+    initialized = false;
+    buffer = null;
+  }
+
+  protected synchronized void checkOpen() throws IOException {
+    if (xceiverClientFactory == null) {
+      throw new IOException(FSExceptionMessages.STREAM_IS_CLOSED + " Block: " + blockID);
+    }
+  }
+
+  protected synchronized void acquireClient() throws IOException {
+    checkOpen();
+    if (xceiverClient == null) {
+      final Pipeline pipeline = pipelineRef.get();
+      try {
+        xceiverClient = xceiverClientFactory.acquireClientForReadData(pipeline);
+      } catch (IOException ioe) {
+        LOG.warn("Failed to acquire client for pipeline {}, block {}", pipeline, blockID);
+        throw ioe;
+      }
+    }
+  }
+
+  private void initialize() throws IOException {
+    if (initialized) {
+      return;
+    }
+    while (true) {
+      try {
+        acquireClient();
+        streamingReader = new StreamingReader();
+        ContainerProtocolCalls.readBlock(xceiverClient, position, blockID, tokenRef.get(),
+            pipelineRef.get().getReplicaIndexes(), streamingReader);
+        initialized = true;
+        return;
+      } catch (InterruptedException ie) {
+        Thread.currentThread().interrupt();
+        handleExceptions(new IOException("Interrupted", ie));
+      } catch (IOException ioe) {
+        handleExceptions(ioe);
+      }
+    }
+  }
+
+  private void handleExceptions(IOException cause) throws IOException {
+    if (cause instanceof StorageContainerException || isConnectivityIssue(cause)) {
+      if (shouldRetryRead(cause, retryPolicy, retries++)) {
+        releaseClient();
+        refreshBlockInfo(cause);
+        LOG.warn("Refreshing block data to read block {} due to {}", blockID, cause.getMessage());
+      } else {
+        throw cause;
+      }
+    } else {
+      throw cause;
+    }
+  }
+
+  private int fillBuffer() throws IOException {
+    if (!streamingReader.hasNext()) {
+      return EOF;
+    }
+    buffer = streamingReader.readNext();
+    return buffer == null ? EOF : buffer.limit();
+  }
+
+  protected synchronized void releaseClient() {
+    if (xceiverClientFactory != null && xceiverClient != null) {
+      closeStream();
+      xceiverClientFactory.releaseClientForReadData(xceiverClient, false);
+      xceiverClient = null;
+    }
+  }
+
+  @Override
+  public synchronized void close() throws IOException {
+    releaseClient();
+    xceiverClientFactory = null;
+  }
+
+  private void refreshBlockInfo(IOException cause) throws IOException {
+    refreshBlockInfo(cause, blockID, pipelineRef, tokenRef, refreshFunction);
+  }
+
+  private synchronized void releaseStreamResources(StreamingReadResponse response) {
+    if (xceiverClient != null) {
+      xceiverClient.completeStreamRead(response);
+    }
+  }
+
+  /**
+   * Implementation of a StreamObserver used to received and buffer streaming GRPC reads.
+   */
+  public class StreamingReader implements StreamingReaderSpi {
+
+    private final BlockingQueue<ContainerProtos.ReadBlockResponseProto> responseQueue = new LinkedBlockingQueue<>(1);
+    private final AtomicBoolean completed = new AtomicBoolean(false);
+    private final AtomicBoolean failed = new AtomicBoolean(false);
+    private final AtomicBoolean semaphoreReleased = new AtomicBoolean(false);
+    private final AtomicReference<Throwable> error = new AtomicReference<>();
+    private volatile StreamingReadResponse response;
+
+    public boolean hasNext() {
+      return !responseQueue.isEmpty() || !completed.get();
+    }
+
+    public ByteBuffer readNext() throws IOException {
+      if (failed.get()) {
+        Throwable cause = error.get();
+        throw new IOException("Streaming read failed", cause);
+      }
+
+      if (completed.get() && responseQueue.isEmpty()) {
+        return null; // Stream ended
+      }
+
+      ReadBlockResponseProto readBlock;
+      try {
+        readBlock = responseQueue.poll(30, TimeUnit.SECONDS);

Review Comment:
   Can we add param for this timeout value?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "swamirishi (via GitHub)" <gi...@apache.org>.
swamirishi commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1811169258


##########
hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/keyvalue/KeyValueHandler.java:
##########
@@ -1329,6 +1333,109 @@ public void deleteUnreferenced(Container container, long localID)
     }
   }
 
+  @Override
+  public ContainerCommandResponseProto streamDataReadOnly(
+      ContainerCommandRequestProto request, KeyValueContainer kvContainer,
+      DispatcherContext dispatcherContext,
+      StreamObserver<ContainerCommandResponseProto> streamObserver) {
+    ContainerCommandResponseProto responseProto = null;
+    try {
+      if (!request.hasReadBlock()) {
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("Malformed Read Block request. trace ID: {}",
+              request.getTraceID());
+        }
+        return malformedRequest(request);
+      }
+      ReadBlockRequestProto readBlock = request.getReadBlock();
+
+      BlockID blockID = BlockID.getFromProtobuf(
+          readBlock.getBlockID());
+      // This is a new api the block should always be checked.
+      BlockUtils.verifyReplicaIdx(kvContainer, blockID);

Review Comment:
   It could so happen that the container replica index could change b/w 2 read chunks. You are right about the fact that the replica can still fail, but we can save unnecessary round trips b/w client & server side. It is about narrowing down the possibilty and minor optimization. We need to ensure that the checksums of the chunks do match on the client side. I am still looking through the client side code, just wanted to understand if we are doing a checksum verification for each and every chunk read on the client side.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "kerneltime (via GitHub)" <gi...@apache.org>.
kerneltime commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1802096576


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -618,6 +624,69 @@ private void decreasePendingMetricsAndReleaseSemaphore() {
     return new XceiverClientReply(replyFuture);
   }
 
+  public XceiverClientReply sendCommandAsyncReadOnly(

Review Comment:
   Since this is specific to ReadBlock for now, we can name it such. If later on we extend this to handle other commands in a similar manner with multiple response messages we can change the signature. 
   ```suggestion
     public XceiverClientReply sendCommandReadBlock(
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "chungen0126 (via GitHub)" <gi...@apache.org>.
chungen0126 commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1868102848


##########
hadoop-hdds/container-service/src/test/java/org/apache/hadoop/ozone/container/keyvalue/TestKeyValueHandler.java:
##########
@@ -458,4 +485,77 @@ private static ContainerCommandRequestProto createContainerRequest(
         .setContainerID(containerID).setPipelineID(UUID.randomUUID().toString())
         .build();
   }
+
+  @Test
+  public void testReadBlock() throws IOException {

Review Comment:
   Add `testReadEmptyBlock` in the `TestStreamBlockInputStream` to test read an empty block.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "ChenSammi (via GitHub)" <gi...@apache.org>.
ChenSammi commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1867353993


##########
hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/common/interfaces/ContainerDispatcher.java:
##########
@@ -93,4 +94,15 @@ default StateMachine.DataChannel getStreamDataChannel(
     throw new UnsupportedOperationException(
         "getStreamDataChannel not supported.");
   }
+
+  /**
+   * When reading data form client using stream, get StreamDataChannel.
+   */
+  default void streamDataReadOnly(
+       ContainerCommandRequestProto msg,
+       StreamObserver<ContainerCommandResponseProto> streamObserver,
+       DispatcherContext dispatcherContext) {
+    throw new UnsupportedOperationException(
+         "getStreamDataChannel not supported.");

Review Comment:
   This "getStreamDataChannel not supported."  uses the incorrect function name. 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "ChenSammi (via GitHub)" <gi...@apache.org>.
ChenSammi commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1866986402


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -618,6 +624,69 @@ private void decreasePendingMetricsAndReleaseSemaphore() {
     return new XceiverClientReply(replyFuture);
   }
 
+  public XceiverClientReply sendCommandReadBlock(
+      ContainerCommandRequestProto request, DatanodeDetails dn)
+      throws IOException, InterruptedException {
+
+    CompletableFuture<ContainerCommandResponseProto> future =
+        new CompletableFuture<>();
+    ContainerCommandResponseProto.Builder response =
+        ContainerCommandResponseProto.newBuilder();
+    ContainerProtos.ReadBlockResponseProto.Builder readBlock =
+        ContainerProtos.ReadBlockResponseProto.newBuilder();
+    checkOpen(dn);
+    UUID dnID = dn.getUuid();
+    Type cmdType = request.getCmdType();
+    semaphore.acquire();
+    long requestTime = System.currentTimeMillis();
+    metrics.incrPendingContainerOpsMetrics(cmdType);
+
+    final StreamObserver<ContainerCommandRequestProto> requestObserver =
+        asyncStubs.get(dnID).withDeadlineAfter(timeout, TimeUnit.SECONDS)
+            .send(new StreamObserver<ContainerCommandResponseProto>() {
+              @Override
+              public void onNext(
+                  ContainerCommandResponseProto responseProto) {
+                if (responseProto.getResult() == Result.SUCCESS) {
+                  readBlock.addReadChunk(responseProto.getReadChunk());
+                } else {
+                  future.complete(
+                      ContainerCommandResponseProto.newBuilder(responseProto)
+                          .setCmdType(Type.ReadBlock).build());
+                }
+              }
+
+              @Override
+              public void onError(Throwable t) {
+                future.completeExceptionally(t);
+                metrics.decrPendingContainerOpsMetrics(cmdType);
+                metrics.addContainerOpsLatency(
+                    cmdType, System.currentTimeMillis() - requestTime);
+
+              }
+
+              @Override
+              public void onCompleted() {
+                if (readBlock.getReadChunkCount() > 0) {
+                  future.complete(response.setReadBlock(readBlock)
+                      .setCmdType(Type.ReadBlock).setResult(Result.SUCCESS).build());
+                }
+                if (!future.isDone()) {
+                  future.completeExceptionally(new IOException(
+                      "Stream completed but no reply for request " +
+                          processForDebug(request)));
+                }
+                metrics.decrPendingContainerOpsMetrics(cmdType);
+                metrics.addContainerOpsLatency(
+                    cmdType, System.currentTimeMillis() - requestTime);
+              }
+            });
+    requestObserver.onNext(request);
+    requestObserver.onCompleted();
+    semaphore.release();

Review Comment:
   We cannot release the semaphore directly here.  Release the semaphore after the response is returned. 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "ChenSammi (via GitHub)" <gi...@apache.org>.
ChenSammi commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1866999794


##########
hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/scm/storage/ContainerProtocolCalls.java:
##########
@@ -874,4 +876,57 @@ public static List<Validator> toValidatorList(Validator validator) {
     return datanodeToResponseMap;
   }
 
+  /**
+   * Calls the container protocol to read a chunk.
+   *
+   * @param xceiverClient  client to perform call
+   * @param blockID        ID of the block
+   * @param validators     functions to validate the response
+   * @param token          a token for this block (may be null)
+   * @return container protocol read chunk response
+   * @throws IOException if there is an I/O error while performing the call
+   */
+  @SuppressWarnings("checkstyle:ParameterNumber")
+  public static ContainerProtos.ReadBlockResponseProto readBlock(
+      XceiverClientSpi xceiverClient, long offset, long len, BlockID blockID,
+      List<Validator> validators, Token<? extends TokenIdentifier> token,
+      Map<DatanodeDetails, Integer> replicaIndexes, boolean verifyChecksum) throws IOException {
+    final ReadBlockRequestProto.Builder readBlockRequest =
+        ReadBlockRequestProto.newBuilder()
+            .setOffset(offset)
+            .setVerifyChecksum(verifyChecksum)
+            .setLen(len);
+    final ContainerCommandRequestProto.Builder builder =
+        ContainerCommandRequestProto.newBuilder().setCmdType(Type.ReadBlock)
+            .setContainerID(blockID.getContainerID());
+    if (token != null) {
+      builder.setEncodedToken(token.encodeToUrlString());
+    }
+
+

Review Comment:
   Please remove the extra black line here. 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "ChenSammi (via GitHub)" <gi...@apache.org>.
ChenSammi commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1866988748


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -618,6 +624,69 @@ private void decreasePendingMetricsAndReleaseSemaphore() {
     return new XceiverClientReply(replyFuture);
   }
 
+  public XceiverClientReply sendCommandReadBlock(
+      ContainerCommandRequestProto request, DatanodeDetails dn)
+      throws IOException, InterruptedException {
+
+    CompletableFuture<ContainerCommandResponseProto> future =
+        new CompletableFuture<>();
+    ContainerCommandResponseProto.Builder response =
+        ContainerCommandResponseProto.newBuilder();
+    ContainerProtos.ReadBlockResponseProto.Builder readBlock =
+        ContainerProtos.ReadBlockResponseProto.newBuilder();
+    checkOpen(dn);
+    UUID dnID = dn.getUuid();
+    Type cmdType = request.getCmdType();
+    semaphore.acquire();
+    long requestTime = System.currentTimeMillis();
+    metrics.incrPendingContainerOpsMetrics(cmdType);
+
+    final StreamObserver<ContainerCommandRequestProto> requestObserver =
+        asyncStubs.get(dnID).withDeadlineAfter(timeout, TimeUnit.SECONDS)
+            .send(new StreamObserver<ContainerCommandResponseProto>() {
+              @Override
+              public void onNext(
+                  ContainerCommandResponseProto responseProto) {
+                if (responseProto.getResult() == Result.SUCCESS) {
+                  readBlock.addReadChunk(responseProto.getReadChunk());
+                } else {
+                  future.complete(

Review Comment:
   Can directly use future.complete(responseProto) here, instead of the if else detection? 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "ChenSammi (via GitHub)" <gi...@apache.org>.
ChenSammi commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1867351366


##########
hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/keyvalue/KeyValueHandler.java:
##########
@@ -1345,6 +1349,114 @@ public void deleteUnreferenced(Container container, long localID)
     }
   }
 
+  @Override
+  public ContainerCommandResponseProto streamDataReadOnly(
+      ContainerCommandRequestProto request, KeyValueContainer kvContainer,
+      DispatcherContext dispatcherContext,
+      StreamObserver<ContainerCommandResponseProto> streamObserver) {
+    ContainerCommandResponseProto responseProto = null;
+    try {
+      if (!request.hasReadBlock()) {
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("Malformed Read Block request. trace ID: {}",
+              request.getTraceID());
+        }
+        return malformedRequest(request);
+      }
+      ReadBlockRequestProto readBlock = request.getReadBlock();
+
+      BlockID blockID = BlockID.getFromProtobuf(
+          readBlock.getBlockID());
+      // This is a new api the block should always be checked.
+      BlockUtils.verifyReplicaIdx(kvContainer, blockID);
+      BlockUtils.verifyBCSId(kvContainer, blockID);
+
+      BlockData blockData = getBlockManager().getBlock(kvContainer, blockID);
+      List<ContainerProtos.ChunkInfo> chunkInfos = blockData.getChunks();
+      long blockOffset = 0;
+      int chunkIndex = -1;
+      long chunkOffset = 0;
+      long offset = readBlock.getOffset();
+      for (int i = 0; i < chunkInfos.size(); i++) {
+        final long chunkLen = chunkInfos.get(i).getLen();
+        blockOffset += chunkLen;
+        if (blockOffset > offset) {
+          chunkIndex = i;
+          chunkOffset = offset - blockOffset + chunkLen;
+          break;
+        }
+      }
+      Preconditions.checkState(chunkIndex >= 0);
+
+      if (dispatcherContext == null) {
+        dispatcherContext = DispatcherContext.getHandleReadBlock();
+      }
+
+      ChunkBuffer data;
+
+      long len =  readBlock.getLen();
+      long adjustedChunkOffset, adjustedChunkLen;
+      do {
+        ContainerProtos.ChunkInfo chunk = chunkInfos.get(chunkIndex);
+        if (readBlock.getVerifyChecksum()) {

Review Comment:
   This verifyChecksum is used to decide whether offset need be adjusted. Why not do this check and adjust on client side? 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "sodonnel (via GitHub)" <gi...@apache.org>.
sodonnel commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-3575121897

   @chungen0126 the goal is to get to the point where we commit https://github.com/szetszwo/ozone/commits/HDDS-10338b/ which @szetszwo created based on the work you and I did previously. Ideally we should just close this PR and open a new one with the change above and work to get it committed. It has changed the approach to implement the flow control by asking for the next chunks as it needs them. In some initial testing it appears to perform better than the latest commit on this PR, which also implemented flow control at the server side.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "chungen0126 (via GitHub)" <gi...@apache.org>.
chungen0126 commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1792380964


##########
hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/keyvalue/KeyValueHandler.java:
##########
@@ -1329,6 +1333,113 @@ public void deleteUnreferenced(Container container, long localID)
     }
   }
 
+  @Override
+  public ContainerCommandResponseProto streamDataReadOnly(
+      ContainerCommandRequestProto request, KeyValueContainer kvContainer,
+      DispatcherContext dispatcherContext,
+      StreamObserver<ContainerCommandResponseProto> streamObserver) {
+    ContainerCommandResponseProto responseProto = null;
+    try {
+      if (!request.hasReadBlock()) {
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("Malformed Read Block request. trace ID: {}",
+              request.getTraceID());
+        }
+        return malformedRequest(request);
+      }
+      ReadBlockRequestProto readBlock = request.getReadBlock();
+      ChunkBuffer data;
+
+      BlockID blockID = BlockID.getFromProtobuf(
+          readBlock.getBlockID());
+      // This is a new api the block should always be checked.
+      BlockUtils.verifyReplicaIdx(kvContainer, blockID);
+
+      BlockData blockData = blockManager.getBlock(kvContainer, blockID);
+      List<ContainerProtos.ChunkInfo> chunkInfos = blockData.getChunks();
+      long blockOffset = 0;
+      int chunkIndex = -1;
+      for (int i = 0; i < chunkInfos.size(); i++) {
+        blockOffset += chunkInfos.get(i).getLen();
+        if (blockOffset > readBlock.getOffset()) {
+          chunkIndex = i;
+          break;
+        }
+      }
+
+      BlockUtils.verifyBCSId(kvContainer, blockID);

Review Comment:
   done



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "swamirishi (via GitHub)" <gi...@apache.org>.
swamirishi commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1803842565


##########
hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/keyvalue/KeyValueHandler.java:
##########
@@ -1329,6 +1333,109 @@ public void deleteUnreferenced(Container container, long localID)
     }
   }
 
+  @Override
+  public ContainerCommandResponseProto streamDataReadOnly(
+      ContainerCommandRequestProto request, KeyValueContainer kvContainer,
+      DispatcherContext dispatcherContext,
+      StreamObserver<ContainerCommandResponseProto> streamObserver) {
+    ContainerCommandResponseProto responseProto = null;
+    try {
+      if (!request.hasReadBlock()) {
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("Malformed Read Block request. trace ID: {}",
+              request.getTraceID());
+        }
+        return malformedRequest(request);
+      }
+      ReadBlockRequestProto readBlock = request.getReadBlock();
+
+      BlockID blockID = BlockID.getFromProtobuf(
+          readBlock.getBlockID());
+      // This is a new api the block should always be checked.
+      BlockUtils.verifyReplicaIdx(kvContainer, blockID);

Review Comment:
   or we would need to validate the replicaIndex and bcsID is the same on every readChunk call on the file(Basically move this check inside the loop). Take a look at HDDS-10983 for context.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "chungen0126 (via GitHub)" <gi...@apache.org>.
chungen0126 commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1804289620


##########
hadoop-hdds/client/dev-support/findbugsExcludeFile.xml:
##########
@@ -32,4 +32,8 @@
     <Class name="org.apache.hadoop.hdds.scm.storage.TestBlockInputStream"></Class>
     <Bug pattern="RR_NOT_CHECKED" />
   </Match>
+  <Match>
+    <Class name="org.apache.hadoop.hdds.scm.storage.TestStreamBlockInput"></Class>
+    <Bug pattern="RR_NOT_CHECKED" />
+  </Match>

Review Comment:
   done



##########
hadoop-hdds/client/src/test/java/org/apache/hadoop/hdds/scm/storage/TestStreamBlockInput.java:
##########
@@ -0,0 +1,259 @@
+/*
+ * 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 java.io.EOFException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Random;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.Function;
+
+import com.google.common.primitives.Bytes;
+import org.apache.hadoop.hdds.client.BlockID;
+import org.apache.hadoop.hdds.client.ContainerBlockID;
+import org.apache.hadoop.hdds.conf.OzoneConfiguration;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ChecksumType;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ChunkInfo;
+import org.apache.hadoop.hdds.scm.OzoneClientConfig;
+import org.apache.hadoop.hdds.scm.pipeline.MockPipeline;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.ozone.common.Checksum;
+
+import org.apache.ratis.thirdparty.com.google.protobuf.ByteString;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.Mockito.mock;
+
+/**
+ * Tests for {@link TestStreamBlockInput}'s functionality.
+ */
+public class TestStreamBlockInput {
+  private int blockSize;
+  private static final int CHUNK_SIZE = 100;
+  private static final int BYTES_PER_CHECKSUM = 20;
+  private static final Random RANDOM = new Random();
+  private static final AtomicLong CONTAINER_ID = new AtomicLong();
+  private DummyStreamBlockInput blockStream;
+  private byte[] blockData;
+  private List<ChunkInfo> chunks;
+  private Map<String, byte[]> chunkDataMap;
+  private Checksum checksum;
+  private Function<BlockID, BlockLocationInfo> refreshFunction;
+  private BlockID blockID;
+  private static final String CHUNK_NAME = "chunk-";
+  private OzoneConfiguration conf = new OzoneConfiguration();
+
+
+  @BeforeEach
+  public void setup() throws Exception {
+    OzoneClientConfig clientConfig = conf.getObject(OzoneClientConfig.class);
+    clientConfig.setStreamReadBlock(true);
+    refreshFunction = mock(Function.class);
+    blockID = new BlockID(new ContainerBlockID(1, 1));
+    checksum = new Checksum(ChecksumType.CRC32, BYTES_PER_CHECKSUM);
+    createChunkList(5);
+
+    Pipeline pipeline = MockPipeline.createSingleNodePipeline();
+    blockStream = new DummyStreamBlockInput(blockID, blockSize, pipeline,
+        null, null, refreshFunction, clientConfig, chunks, chunkDataMap);
+  }
+
+  /**
+   * Create a mock list of chunks. The first n-1 chunks of length CHUNK_SIZE
+   * and the last chunk with length CHUNK_SIZE/2.
+   */
+  private void createChunkList(int numChunks)
+      throws Exception {
+
+    chunks = new ArrayList<>(numChunks);
+    chunkDataMap = new HashMap<>();
+    blockData = new byte[0];
+    int i, chunkLen;
+    byte[] byteData;
+    String chunkName;
+
+    for (i = 0; i < numChunks; i++) {
+      chunkName = CHUNK_NAME + i;
+      chunkLen = CHUNK_SIZE;
+      if (i == numChunks - 1) {
+        chunkLen = CHUNK_SIZE / 2;
+      }
+      byteData = generateRandomData(chunkLen);
+      ChunkInfo chunkInfo = ChunkInfo.newBuilder()
+          .setChunkName(chunkName)
+          .setOffset(0)
+          .setLen(chunkLen)
+          .setChecksumData(checksum.computeChecksum(
+              byteData, 0, chunkLen).getProtoBufMessage())
+          .build();
+
+      chunkDataMap.put(chunkName, byteData);
+      chunks.add(chunkInfo);
+
+      blockSize += chunkLen;
+      blockData = Bytes.concat(blockData, byteData);
+    }
+  }
+
+  static byte[] generateRandomData(int length) {
+    byte[] bytes = new byte[length];
+    RANDOM.nextBytes(bytes);
+    return bytes;
+  }
+
+  /**
+   * Match readData with the chunkData byte-wise.
+   * @param readData Data read through ChunkInputStream
+   * @param inputDataStartIndex first index (inclusive) in chunkData to compare
+   *                            with read data
+   * @param length the number of bytes of data to match starting from
+   *               inputDataStartIndex
+   */
+  private void matchWithInputData(byte[] readData, int inputDataStartIndex,
+                                  int length) {
+    for (int i = inputDataStartIndex; i < inputDataStartIndex + length; i++) {
+      assertEquals(blockData[i], readData[i - inputDataStartIndex], "i: " + i);
+    }
+  }
+
+  private void matchWithInputData(List<ByteString> byteStrings,
+                                  int inputDataStartIndex, int length) {
+    int offset = inputDataStartIndex;
+    int totalBufferLen = 0;
+    for (ByteString byteString : byteStrings) {
+      int bufferLen = byteString.size();
+      matchWithInputData(byteString.toByteArray(), offset, bufferLen);
+      offset += bufferLen;
+      totalBufferLen += bufferLen;
+    }
+    assertEquals(length, totalBufferLen);
+  }
+
+  /**
+   * Seek to a position and verify through getPos().
+   */
+  private void seekAndVerify(int pos) throws Exception {
+    blockStream.seek(pos);
+    assertEquals(pos, blockStream.getPos(),
+        "Current position of buffer does not match with the sought position");
+  }
+
+  @Test
+  public void testFullChunkRead() throws Exception {
+    byte[] b = new byte[blockSize];
+    blockStream.read(b, 0, blockSize);
+    matchWithInputData(b, 0, blockSize);
+  }
+
+  @Test
+  public void testPartialChunkRead() throws Exception {
+    int len = blockSize / 2;
+    byte[] b = new byte[len];
+
+    blockStream.read(b, 0, len);

Review Comment:
   done



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "chungen0126 (via GitHub)" <gi...@apache.org>.
chungen0126 commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1882628451


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/StreamBlockInputStream.java:
##########
@@ -0,0 +1,760 @@
+/*
+ * 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 com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
+import org.apache.commons.lang3.NotImplementedException;
+import org.apache.hadoop.fs.ByteBufferReadable;
+import org.apache.hadoop.fs.CanUnbuffer;
+import org.apache.hadoop.fs.Seekable;
+import org.apache.hadoop.hdds.client.BlockID;
+import org.apache.hadoop.hdds.client.StandaloneReplicationConfig;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadChunkResponseProto;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadBlockResponseProto;
+import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
+import org.apache.hadoop.hdds.scm.OzoneClientConfig;
+import org.apache.hadoop.hdds.scm.XceiverClientFactory;
+import org.apache.hadoop.hdds.scm.XceiverClientSpi;
+import org.apache.hadoop.hdds.scm.client.HddsClientUtils;
+import org.apache.hadoop.hdds.scm.container.common.helpers.StorageContainerException;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.hdds.security.exception.SCMSecurityException;
+import org.apache.hadoop.hdds.security.token.OzoneBlockTokenIdentifier;
+import org.apache.hadoop.io.retry.RetryPolicy;
+import org.apache.hadoop.ozone.common.Checksum;
+import org.apache.hadoop.ozone.common.ChecksumData;
+import org.apache.hadoop.ozone.common.OzoneChecksumException;
+import org.apache.hadoop.ozone.common.utils.BufferUtils;
+import org.apache.hadoop.security.token.Token;
+import org.apache.ratis.thirdparty.com.google.protobuf.ByteString;
+import org.apache.ratis.thirdparty.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.EOFException;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+
+import static org.apache.hadoop.hdds.client.ReplicationConfig.getLegacyFactor;
+
+/**
+ * An {@link java.io.InputStream} called from KeyInputStream to read a block from the
+ * container.
+ */
+public class StreamBlockInputStream extends BlockExtendedInputStream
+    implements Seekable, CanUnbuffer, ByteBufferReadable {
+  private static final Logger LOG =
+      LoggerFactory.getLogger(StreamBlockInputStream.class);
+  private final BlockID blockID;
+  private final long blockLength;
+  private final AtomicReference<Pipeline> pipelineRef =
+      new AtomicReference<>();
+  private final AtomicReference<Token<OzoneBlockTokenIdentifier>> tokenRef =
+      new AtomicReference<>();
+  private XceiverClientFactory xceiverClientFactory;
+  private XceiverClientSpi xceiverClient;
+
+  private List<Long> bufferOffsets;
+  private int bufferIndex;
+  private long blockPosition = -1;
+  private List<ByteBuffer> buffers;
+  // Checks if the StreamBlockInputStream has already read data from the container.
+  private boolean allocated = false;
+  private long bufferOffsetWrtBlockData;
+  private long buffersSize;
+  private static final int EOF = -1;
+  private final List<XceiverClientSpi.Validator> validators;
+  private final boolean verifyChecksum;
+  private final Function<BlockID, BlockLocationInfo> refreshFunction;
+  private final RetryPolicy retryPolicy;
+  private int retries;
+
+
+  public StreamBlockInputStream(
+      BlockID blockID, long length, Pipeline pipeline,
+      Token<OzoneBlockTokenIdentifier> token,
+      XceiverClientFactory xceiverClientFactory,
+      Function<BlockID, BlockLocationInfo> refreshFunction,
+      OzoneClientConfig config) throws IOException {
+    this.blockID = blockID;
+    LOG.debug("Initializing StreamBlockInputStream for block {}", blockID);
+    this.blockLength = length;
+    setPipeline(pipeline);
+    tokenRef.set(token);
+    this.xceiverClientFactory = xceiverClientFactory;
+    this.validators = ContainerProtocolCalls.toValidatorList(
+        (request, response) -> validateBlock(response));
+    this.verifyChecksum = config.isChecksumVerify();
+    this.refreshFunction = refreshFunction;
+    this.retryPolicy =
+        HddsClientUtils.createRetryPolicy(config.getMaxReadRetryCount(),
+            TimeUnit.SECONDS.toMillis(config.getReadRetryInterval()));
+
+  }
+
+
+  public BlockID getBlockID() {
+    return blockID;
+  }
+
+  public long getLength() {
+    return blockLength;
+  }
+
+  @Override
+  public synchronized long getPos() {
+    if (blockLength == 0) {
+      return 0;
+    }
+    if (blockPosition >= 0) {
+      return blockPosition;
+    }
+
+    if (buffersHaveData()) {
+      // BufferOffset w.r.t to BlockData + BufferOffset w.r.t buffers +
+      // Position of current Buffer
+      return bufferOffsetWrtBlockData + bufferOffsets.get(bufferIndex) +
+          buffers.get(bufferIndex).position();
+    }
+    if (allocated && !dataRemainingInBlock()) {
+      Preconditions.checkState(
+          bufferOffsetWrtBlockData + buffersSize == blockLength,
+          "EOF detected but not at the last byte of the chunk");
+      return blockLength;
+    }
+    if (buffersAllocated()) {
+      return bufferOffsetWrtBlockData + buffersSize;
+    }
+    return 0;
+  }
+
+  @Override
+  public synchronized int read() throws IOException {
+    int dataout = EOF;
+    int len = 1;
+    int available;
+    while (len > 0) {
+      try {
+        acquireClient();
+        available = prepareRead(1);
+        retries = 0;
+      } catch (SCMSecurityException ex) {
+        throw ex;
+      } catch (StorageContainerException e) {
+        handleStorageContainerException(e);
+        continue;
+      } catch (IOException ioe) {
+        handleIOException(ioe);
+        continue;
+      }
+      if (available == EOF) {
+        // There is no more data in the chunk stream. The buffers should have
+        // been released by now
+        Preconditions.checkState(buffers == null);
+      } else {
+        dataout = Byte.toUnsignedInt(buffers.get(bufferIndex).get());
+      }
+
+      len -= available;
+      if (bufferEOF()) {
+        releaseBuffers(bufferIndex);
+      }
+    }
+
+
+    return dataout;
+
+
+  }
+
+  @Override
+  public synchronized int read(byte[] b, int off, int len) throws IOException {
+    // According to the JavaDocs for InputStream, it is recommended that
+    // subclasses provide an override of bulk read if possible for performance
+    // reasons.  In addition to performance, we need to do it for correctness
+    // reasons.  The Ozone REST service uses PipedInputStream and
+    // PipedOutputStream to relay HTTP response data between a Jersey thread and
+    // a Netty thread.  It turns out that PipedInputStream/PipedOutputStream
+    // have a subtle dependency (bug?) on the wrapped stream providing separate
+    // implementations of single-byte read and bulk read.  Without this, get key
+    // responses might close the connection before writing all of the bytes
+    // advertised in the Content-Length.
+    if (b == null) {
+      throw new NullPointerException();
+    }
+    if (off < 0 || len < 0 || len > b.length - off) {
+      throw new IndexOutOfBoundsException();
+    }
+    if (len == 0) {
+      return 0;
+    }
+    int total = 0;
+    int available;
+    while (len > 0) {
+      try {
+        acquireClient();
+        available = prepareRead(len);
+        retries = 0;
+      } catch (SCMSecurityException ex) {
+        throw ex;
+      } catch (StorageContainerException e) {
+        handleStorageContainerException(e);
+        continue;
+      } catch (IOException ioe) {
+        handleIOException(ioe);
+        continue;
+      }
+      if (available == EOF) {
+        // There is no more data in the block stream. The buffers should have
+        // been released by now
+        Preconditions.checkState(buffers == null);
+        return total != 0 ? total : EOF;
+      }
+      buffers.get(bufferIndex).get(b, off + total, available);
+      len -= available;
+      total += available;
+
+      if (bufferEOF()) {
+        releaseBuffers(bufferIndex);
+      }
+    }
+    return total;
+
+  }
+
+  @Override
+  public synchronized int read(ByteBuffer byteBuffer) throws IOException {
+    if (byteBuffer == null) {
+      throw new NullPointerException();
+    }
+    int len = byteBuffer.remaining();
+    if (len == 0) {
+      return 0;
+    }
+    int total = 0;
+    int available;
+    while (len > 0) {
+      try {
+        acquireClient();
+        available = prepareRead(len);
+        retries = 0;
+      } catch (SCMSecurityException ex) {
+        throw ex;
+      } catch (StorageContainerException e) {
+        handleStorageContainerException(e);
+        continue;
+      } catch (IOException ioe) {
+        handleIOException(ioe);
+        continue;
+      }
+      if (available == EOF) {
+        // There is no more data in the block stream. The buffers should have
+        // been released by now
+        Preconditions.checkState(buffers == null);
+        return total != 0 ? total : EOF;
+      }
+      ByteBuffer readBuf = buffers.get(bufferIndex);
+      ByteBuffer tmpBuf = readBuf.duplicate();
+      tmpBuf.limit(tmpBuf.position() + available);
+      byteBuffer.put(tmpBuf);
+      readBuf.position(tmpBuf.position());
+
+      len -= available;
+      total += available;
+
+      if (bufferEOF()) {
+        releaseBuffers(bufferIndex);
+      }
+    }
+    return total;
+  }
+
+  @Override
+  protected int readWithStrategy(ByteReaderStrategy strategy) throws IOException {
+    throw new NotImplementedException("readWithStrategy is not implemented.");
+  }
+
+  @Override
+  public synchronized void seek(long pos) throws IOException {
+    if (pos == 0 && blockLength == 0) {
+      // It is possible for length and pos to be zero in which case
+      // seek should return instead of throwing exception
+      return;
+    }
+    if (pos < 0 || pos > blockLength) {
+      throw new EOFException("EOF encountered at pos: " + pos + " for block: " + blockID);
+    }
+
+    if (buffersHavePosition(pos)) {
+      // The bufferPosition is w.r.t the current block.
+      // Adjust the bufferIndex and position to the seeked position.
+      adjustBufferPosition(pos - bufferOffsetWrtBlockData);
+    } else {
+      blockPosition = pos;
+    }
+  }
+
+  @Override
+  public synchronized boolean seekToNewSource(long l) throws IOException {
+    return false;
+  }
+
+  @Override
+  public synchronized void unbuffer() {
+    blockPosition = getPos();
+    releaseClient();
+    releaseBuffers();
+  }
+
+  private void setPipeline(Pipeline pipeline) throws IOException {
+    if (pipeline == null) {
+      return;
+    }
+    long replicaIndexes = pipeline.getNodes().stream().mapToInt(pipeline::getReplicaIndex).distinct().count();
+
+    if (replicaIndexes > 1) {
+      throw new IOException(String.format("Pipeline: %s has nodes containing different replica indexes.",
+          pipeline));
+    }
+
+    // irrespective of the container state, we will always read via Standalone
+    // protocol.
+    boolean okForRead =
+        pipeline.getType() == HddsProtos.ReplicationType.STAND_ALONE
+            || pipeline.getType() == HddsProtos.ReplicationType.EC;
+    Pipeline readPipeline = okForRead ? pipeline : Pipeline.newBuilder(pipeline)
+        .setReplicationConfig(StandaloneReplicationConfig.getInstance(
+            getLegacyFactor(pipeline.getReplicationConfig())))
+        .build();
+    pipelineRef.set(readPipeline);
+  }
+
+  protected synchronized void checkOpen() throws IOException {
+    if (xceiverClientFactory == null) {
+      throw new IOException("BlockInputStream has been closed.");
+    }
+  }
+
+  protected synchronized void acquireClient() throws IOException {
+    checkOpen();
+    if (xceiverClient == null) {
+      final Pipeline pipeline = pipelineRef.get();
+      try {
+        xceiverClient = xceiverClientFactory.acquireClientForReadData(pipeline);
+      } catch (IOException ioe) {
+        LOG.warn("Failed to acquire client for pipeline {}, block {}",
+            pipeline, blockID);
+        throw ioe;
+      }
+    }
+  }
+
+  private synchronized int prepareRead(int len) throws IOException {
+    for (;;) {
+      if (blockPosition >= 0) {
+        if (buffersHavePosition(blockPosition)) {
+          // The current buffers have the seeked position. Adjust the buffer
+          // index and position to point to the buffer position.
+          adjustBufferPosition(blockPosition - bufferOffsetWrtBlockData);
+        } else {
+          // Read a required block data to fill the buffers with seeked
+          // position data
+          readDataFromContainer(len);
+        }
+      }
+      if (buffersHaveData()) {
+        // Data is available from buffers
+        ByteBuffer bb = buffers.get(bufferIndex);
+        return Math.min(len, bb.remaining());
+      } else if (dataRemainingInBlock()) {
+        // There is more data in the block stream which has not
+        // been read into the buffers yet.
+        readDataFromContainer(len);
+      } else {
+        // All available input from this block stream has been consumed.
+        return EOF;
+      }
+    }
+
+
+  }
+
+  private boolean buffersHavePosition(long pos) {
+    // Check if buffers have been allocated
+    if (buffersAllocated()) {
+      // Check if the current buffers cover the input position
+      // Released buffers should not be considered when checking if position
+      // is available
+      return pos >= bufferOffsetWrtBlockData +
+          bufferOffsets.get(0) &&
+          pos < bufferOffsetWrtBlockData + buffersSize;
+    }
+    return false;
+  }
+
+  /**
+   * Check if the buffers have been allocated data and false otherwise.
+   */
+  @VisibleForTesting
+  protected boolean buffersAllocated() {
+    return buffers != null && !buffers.isEmpty();
+  }
+
+  /**
+   * Adjust the buffers position to account for seeked position and/ or checksum
+   * boundary reads.
+   * @param bufferPosition the position to which the buffers must be advanced
+   */
+  private void adjustBufferPosition(long bufferPosition) {
+    // The bufferPosition is w.r.t the current buffers.
+    // Adjust the bufferIndex and position to the seeked bufferPosition.
+    if (bufferIndex >= buffers.size()) {
+      bufferIndex = Collections.binarySearch(bufferOffsets, bufferPosition);
+    } else if (bufferPosition < bufferOffsets.get(bufferIndex)) {
+      bufferIndex = Collections.binarySearch(
+          bufferOffsets.subList(0, bufferIndex), bufferPosition);
+    } else if (bufferPosition >= bufferOffsets.get(bufferIndex) +
+        buffers.get(bufferIndex).capacity()) {
+      bufferIndex = Collections.binarySearch(bufferOffsets.subList(
+          bufferIndex + 1, buffers.size()), bufferPosition);
+    }

Review Comment:
   done



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "ChenSammi (via GitHub)" <gi...@apache.org>.
ChenSammi commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1866987423


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/BlockInputStream.java:
##########
@@ -124,6 +124,7 @@ public BlockInputStream(
       OzoneClientConfig config) throws IOException {
     this.blockInfo = blockInfo;
     this.blockID = blockInfo.getBlockID();
+    LOG.debug("Initializing BlockInputStream for block {}", blockID);

Review Comment:
   Is this debug message still needed? 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "ChenSammi (via GitHub)" <gi...@apache.org>.
ChenSammi commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1867374697


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/StreamBlockInput.java:
##########
@@ -0,0 +1,760 @@
+/*
+ * 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 com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
+import org.apache.commons.lang3.NotImplementedException;
+import org.apache.hadoop.fs.ByteBufferReadable;
+import org.apache.hadoop.fs.CanUnbuffer;
+import org.apache.hadoop.fs.Seekable;
+import org.apache.hadoop.hdds.client.BlockID;
+import org.apache.hadoop.hdds.client.StandaloneReplicationConfig;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadChunkResponseProto;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadBlockResponseProto;
+import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
+import org.apache.hadoop.hdds.scm.OzoneClientConfig;
+import org.apache.hadoop.hdds.scm.XceiverClientFactory;
+import org.apache.hadoop.hdds.scm.XceiverClientSpi;
+import org.apache.hadoop.hdds.scm.client.HddsClientUtils;
+import org.apache.hadoop.hdds.scm.container.common.helpers.StorageContainerException;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.hdds.security.exception.SCMSecurityException;
+import org.apache.hadoop.hdds.security.token.OzoneBlockTokenIdentifier;
+import org.apache.hadoop.io.retry.RetryPolicy;
+import org.apache.hadoop.ozone.common.Checksum;
+import org.apache.hadoop.ozone.common.ChecksumData;
+import org.apache.hadoop.ozone.common.OzoneChecksumException;
+import org.apache.hadoop.ozone.common.utils.BufferUtils;
+import org.apache.hadoop.security.token.Token;
+import org.apache.ratis.thirdparty.com.google.protobuf.ByteString;
+import org.apache.ratis.thirdparty.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.EOFException;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+
+import static org.apache.hadoop.hdds.client.ReplicationConfig.getLegacyFactor;
+
+/**
+ * An {@link java.io.InputStream} called from KeyInputStream to read a block from the
+ * container.
+ */
+public class StreamBlockInput extends BlockExtendedInputStream
+    implements Seekable, CanUnbuffer, ByteBufferReadable {
+  private static final Logger LOG =
+      LoggerFactory.getLogger(StreamBlockInput.class);
+  private final BlockID blockID;
+  private final long blockLength;
+  private final AtomicReference<Pipeline> pipelineRef =
+      new AtomicReference<>();
+  private final AtomicReference<Token<OzoneBlockTokenIdentifier>> tokenRef =
+      new AtomicReference<>();
+  private XceiverClientFactory xceiverClientFactory;
+  private XceiverClientSpi xceiverClient;
+
+  private List<Long> bufferoffsets;

Review Comment:
   bufferoffsets -> bufferOffsets



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "ChenSammi (via GitHub)" <gi...@apache.org>.
ChenSammi commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1867367167


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -618,6 +624,69 @@ private void decreasePendingMetricsAndReleaseSemaphore() {
     return new XceiverClientReply(replyFuture);
   }
 
+  public XceiverClientReply sendCommandReadBlock(
+      ContainerCommandRequestProto request, DatanodeDetails dn)
+      throws IOException, InterruptedException {
+
+    CompletableFuture<ContainerCommandResponseProto> future =
+        new CompletableFuture<>();
+    ContainerCommandResponseProto.Builder response =
+        ContainerCommandResponseProto.newBuilder();
+    ContainerProtos.ReadBlockResponseProto.Builder readBlock =
+        ContainerProtos.ReadBlockResponseProto.newBuilder();
+    checkOpen(dn);
+    UUID dnID = dn.getUuid();
+    Type cmdType = request.getCmdType();
+    semaphore.acquire();
+    long requestTime = System.currentTimeMillis();
+    metrics.incrPendingContainerOpsMetrics(cmdType);
+
+    final StreamObserver<ContainerCommandRequestProto> requestObserver =
+        asyncStubs.get(dnID).withDeadlineAfter(timeout, TimeUnit.SECONDS)
+            .send(new StreamObserver<ContainerCommandResponseProto>() {
+              @Override
+              public void onNext(
+                  ContainerCommandResponseProto responseProto) {
+                if (responseProto.getResult() == Result.SUCCESS) {
+                  readBlock.addReadChunk(responseProto.getReadChunk());
+                } else {
+                  future.complete(
+                      ContainerCommandResponseProto.newBuilder(responseProto)
+                          .setCmdType(Type.ReadBlock).build());
+                }
+              }
+
+              @Override
+              public void onError(Throwable t) {
+                future.completeExceptionally(t);
+                metrics.decrPendingContainerOpsMetrics(cmdType);
+                metrics.addContainerOpsLatency(
+                    cmdType, System.currentTimeMillis() - requestTime);
+

Review Comment:
   Please remove this unnecessary blank line. 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "chungen0126 (via GitHub)" <gi...@apache.org>.
chungen0126 commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1867485456


##########
hadoop-hdds/interface-client/src/main/proto/DatanodeClientProtocol.proto:
##########
@@ -108,6 +108,7 @@ enum Type {
 
   FinalizeBlock = 21;
   Echo = 22;
+  ReadBlock = 23;

Review Comment:
   done



##########
hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/scm/storage/ContainerProtocolCalls.java:
##########
@@ -874,4 +876,57 @@ public static List<Validator> toValidatorList(Validator validator) {
     return datanodeToResponseMap;
   }
 
+  /**
+   * Calls the container protocol to read a chunk.
+   *
+   * @param xceiverClient  client to perform call
+   * @param blockID        ID of the block
+   * @param validators     functions to validate the response
+   * @param token          a token for this block (may be null)
+   * @return container protocol read chunk response
+   * @throws IOException if there is an I/O error while performing the call
+   */
+  @SuppressWarnings("checkstyle:ParameterNumber")
+  public static ContainerProtos.ReadBlockResponseProto readBlock(
+      XceiverClientSpi xceiverClient, long offset, long len, BlockID blockID,
+      List<Validator> validators, Token<? extends TokenIdentifier> token,
+      Map<DatanodeDetails, Integer> replicaIndexes, boolean verifyChecksum) throws IOException {
+    final ReadBlockRequestProto.Builder readBlockRequest =
+        ReadBlockRequestProto.newBuilder()
+            .setOffset(offset)
+            .setVerifyChecksum(verifyChecksum)
+            .setLen(len);
+    final ContainerCommandRequestProto.Builder builder =
+        ContainerCommandRequestProto.newBuilder().setCmdType(Type.ReadBlock)
+            .setContainerID(blockID.getContainerID());
+    if (token != null) {
+      builder.setEncodedToken(token.encodeToUrlString());
+    }
+
+

Review Comment:
   removed



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "chungen0126 (via GitHub)" <gi...@apache.org>.
chungen0126 commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1867485926


##########
hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/common/transport/server/GrpcXceiverService.java:
##########
@@ -120,7 +125,7 @@ public void onError(Throwable t) {
       @Override
       public void onCompleted() {
         if (isClosed.compareAndSet(false, true)) {
-          LOG.debug("ContainerCommand send completed");
+          LOG.info("ContainerCommand send completed");

Review Comment:
   done



##########
hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/keyvalue/KeyValueHandler.java:
##########
@@ -1345,6 +1349,114 @@ public void deleteUnreferenced(Container container, long localID)
     }
   }
 
+  @Override
+  public ContainerCommandResponseProto streamDataReadOnly(
+      ContainerCommandRequestProto request, KeyValueContainer kvContainer,
+      DispatcherContext dispatcherContext,
+      StreamObserver<ContainerCommandResponseProto> streamObserver) {
+    ContainerCommandResponseProto responseProto = null;
+    try {
+      if (!request.hasReadBlock()) {
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("Malformed Read Block request. trace ID: {}",
+              request.getTraceID());
+        }
+        return malformedRequest(request);
+      }

Review Comment:
   done



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "ChenSammi (via GitHub)" <gi...@apache.org>.
ChenSammi commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1867003819


##########
hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/common/transport/server/GrpcXceiverService.java:
##########
@@ -120,7 +125,7 @@ public void onError(Throwable t) {
       @Override
       public void onCompleted() {
         if (isClosed.compareAndSet(false, true)) {
-          LOG.debug("ContainerCommand send completed");
+          LOG.info("ContainerCommand send completed");

Review Comment:
   Please revert this log level change. 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "fenixjin (via GitHub)" <gi...@apache.org>.
fenixjin commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-2575932018

   > > Test conducted on our cluster(3DN / HDD / 10 Gigabit network) shows this improvement can boost read speed by at least 30%.
   > 
   > > It can be seen that for 1GB file reading, streaming reading can reduce the reading time by about 30%.
   > 
   > Hi @chungen0126 @guohao-rosicky, do we know how much of an improvement is being seen for files smaller than 1GB?
   
   @ptlrs 
   conducted test using freon on the latest version of this pr, hardware is 3DN / HDD / 10 Gigabit network, tested file sizes are 1GB 128MB 16MB 2MB 256KB. there is an index bug when verifying checksum, tests were conducted after fixing it.
   here are the redunctions in mean read time given by freon:
   - 1GB: 7%
   - 128MB: 10%
   - 16MB 8%
   - 2MB 10%
   - 256KB 8%
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "layavadi (via GitHub)" <gi...@apache.org>.
layavadi commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r2151834995


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -631,6 +637,69 @@ private void decreasePendingMetricsAndReleaseSemaphore() {
     return new XceiverClientReply(replyFuture);
   }
 
+  public XceiverClientReply sendCommandReadBlock(
+      ContainerCommandRequestProto request, DatanodeDetails dn)
+      throws IOException, InterruptedException {
+
+    CompletableFuture<ContainerCommandResponseProto> future =
+        new CompletableFuture<>();
+    ContainerCommandResponseProto.Builder response =
+        ContainerCommandResponseProto.newBuilder();
+    ContainerProtos.ReadBlockResponseProto.Builder readBlock =
+        ContainerProtos.ReadBlockResponseProto.newBuilder();
+    checkOpen(dn);
+    DatanodeID dnId = dn.getID();
+    Type cmdType = request.getCmdType();
+    semaphore.acquire();
+    long requestTime = System.currentTimeMillis();
+    metrics.incrPendingContainerOpsMetrics(cmdType);
+
+    final StreamObserver<ContainerCommandRequestProto> requestObserver =
+        asyncStubs.get(dnId).withDeadlineAfter(timeout, TimeUnit.SECONDS)
+            .send(new StreamObserver<ContainerCommandResponseProto>() {
+              @Override
+              public void onNext(
+                  ContainerCommandResponseProto responseProto) {
+                if (responseProto.getResult() == Result.SUCCESS) {
+                  readBlock.addReadChunk(responseProto.getReadChunk());
+                } else {
+                  future.complete(
+                      ContainerCommandResponseProto.newBuilder(responseProto)

Review Comment:
   Should the semaphore be released here instead of waiting for Client to call complete ?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r2491608530


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/StreamBlockInputStream.java:
##########
@@ -0,0 +1,443 @@
+/*
+ * 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 java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+import org.apache.commons.lang3.NotImplementedException;
+import org.apache.hadoop.fs.ByteBufferReadable;
+import org.apache.hadoop.fs.CanUnbuffer;
+import org.apache.hadoop.fs.FSExceptionMessages;
+import org.apache.hadoop.fs.Seekable;
+import org.apache.hadoop.hdds.client.BlockID;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadBlockResponseProto;
+import org.apache.hadoop.hdds.scm.OzoneClientConfig;
+import org.apache.hadoop.hdds.scm.StreamingReadResponse;
+import org.apache.hadoop.hdds.scm.StreamingReaderSpi;
+import org.apache.hadoop.hdds.scm.XceiverClientFactory;
+import org.apache.hadoop.hdds.scm.XceiverClientSpi;
+import org.apache.hadoop.hdds.scm.container.common.helpers.StorageContainerException;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.hdds.security.token.OzoneBlockTokenIdentifier;
+import org.apache.hadoop.io.retry.RetryPolicy;
+import org.apache.hadoop.ozone.common.Checksum;
+import org.apache.hadoop.ozone.common.ChecksumData;
+import org.apache.hadoop.ozone.common.OzoneChecksumException;
+import org.apache.hadoop.security.token.Token;
+import org.apache.ratis.thirdparty.io.grpc.StatusRuntimeException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * An {@link java.io.InputStream} called from KeyInputStream to read a block from the
+ * container.
+ */
+public class StreamBlockInputStream extends BlockExtendedInputStream
+    implements Seekable, CanUnbuffer, ByteBufferReadable {
+  private static final Logger LOG = LoggerFactory.getLogger(StreamBlockInputStream.class);
+  private static final int EOF = -1;
+  private static final Throwable CANCELLED_EXCEPTION = new Throwable("Cancelled by client");
+
+  private final BlockID blockID;
+  private final long blockLength;
+  private final AtomicReference<Pipeline> pipelineRef = new AtomicReference<>();
+  private final AtomicReference<Token<OzoneBlockTokenIdentifier>> tokenRef = new AtomicReference<>();
+  private XceiverClientFactory xceiverClientFactory;
+  private XceiverClientSpi xceiverClient;
+
+  private ByteBuffer buffer;
+  private long position = 0;
+  private boolean initialized = false;
+  private StreamingReader streamingReader;
+
+  private final boolean verifyChecksum;
+  private final Function<BlockID, BlockLocationInfo> refreshFunction;
+  private final RetryPolicy retryPolicy;
+  private int retries = 0;
+
+  public StreamBlockInputStream(
+      BlockID blockID, long length, Pipeline pipeline,
+      Token<OzoneBlockTokenIdentifier> token,
+      XceiverClientFactory xceiverClientFactory,
+      Function<BlockID, BlockLocationInfo> refreshFunction,
+      OzoneClientConfig config) throws IOException {
+    this.blockID = blockID;
+    this.blockLength = length;
+    pipelineRef.set(setPipeline(pipeline));
+    tokenRef.set(token);
+    this.xceiverClientFactory = xceiverClientFactory;
+    this.verifyChecksum = config.isChecksumVerify();
+    this.retryPolicy = getReadRetryPolicy(config);
+    this.refreshFunction = refreshFunction;
+  }
+
+  @Override
+  public BlockID getBlockID() {
+    return blockID;
+  }
+
+  @Override
+  public long getLength() {
+    return blockLength;
+  }
+
+  @Override
+  public synchronized long getPos() {
+    return position;
+  }
+
+  @Override
+  public synchronized int read() throws IOException {
+    checkOpen();
+    if (!dataAvailableToRead()) {
+      return EOF;
+    }
+    position++;
+    return buffer.get();
+  }
+
+  @Override
+  public synchronized int read(byte[] b, int off, int len) throws IOException {
+    ByteBuffer tmpBuffer = ByteBuffer.wrap(b, off, len);
+    return read(tmpBuffer);
+  }
+
+  @Override
+  public synchronized int read(ByteBuffer targetBuf) throws IOException {
+    checkOpen();
+    int read = 0;
+    while (targetBuf.hasRemaining()) {
+      if (!dataAvailableToRead()) {
+        break;
+      }
+      int toCopy = Math.min(buffer.remaining(), targetBuf.remaining());
+      ByteBuffer tmpBuf = buffer.duplicate();
+      tmpBuf.limit(tmpBuf.position() + toCopy);
+      targetBuf.put(tmpBuf);
+      buffer.position(tmpBuf.position());
+      position += toCopy;
+      read += toCopy;
+    }
+    return read > 0 ? read : EOF;
+  }
+
+  private boolean dataAvailableToRead() throws IOException {
+    if (position >= blockLength) {
+      return false;
+    }
+    initialize();
+    if (buffer == null || buffer.remaining() == 0) {
+      int loaded = fillBuffer();
+      return loaded != EOF;
+    }
+    return true;
+  }
+
+  @Override
+  protected int readWithStrategy(ByteReaderStrategy strategy) throws IOException {
+    throw new NotImplementedException("readWithStrategy is not implemented.");
+  }
+
+  @Override
+  public synchronized void seek(long pos) throws IOException {
+    checkOpen();
+    if (pos < 0) {
+      throw new IOException("Cannot seek to negative offset");
+    }
+    if (pos > blockLength) {
+      throw new IOException("Cannot seek after the end of the block");
+    }
+    if (pos == position) {
+      return;
+    }
+    closeStream();
+    position = pos;
+  }
+
+  @Override
+  // The seekable interface indicates that seekToNewSource should seek to a new source of the data,
+  // ie a different datanode. This is not supported for now.
+  public synchronized boolean seekToNewSource(long l) throws IOException {
+    return false;
+  }
+
+  @Override
+  public synchronized void unbuffer() {
+    releaseClient();
+  }
+
+  private void closeStream() {
+    if (streamingReader != null) {
+      streamingReader.cancel();
+      streamingReader = null;
+    }
+    initialized = false;
+    buffer = null;
+  }
+
+  protected synchronized void checkOpen() throws IOException {
+    if (xceiverClientFactory == null) {
+      throw new IOException(FSExceptionMessages.STREAM_IS_CLOSED + " Block: " + blockID);
+    }
+  }
+
+  protected synchronized void acquireClient() throws IOException {
+    checkOpen();
+    if (xceiverClient == null) {
+      final Pipeline pipeline = pipelineRef.get();
+      try {
+        xceiverClient = xceiverClientFactory.acquireClientForReadData(pipeline);
+      } catch (IOException ioe) {
+        LOG.warn("Failed to acquire client for pipeline {}, block {}", pipeline, blockID);
+        throw ioe;
+      }
+    }
+  }
+
+  private void initialize() throws IOException {
+    if (initialized) {
+      return;
+    }
+    while (true) {
+      try {
+        acquireClient();
+        streamingReader = new StreamingReader();
+        ContainerProtocolCalls.readBlock(xceiverClient, position, blockID, tokenRef.get(),
+            pipelineRef.get().getReplicaIndexes(), streamingReader);
+        initialized = true;
+        return;
+      } catch (InterruptedException ie) {
+        Thread.currentThread().interrupt();
+        handleExceptions(new IOException("Interrupted", ie));
+      } catch (IOException ioe) {
+        handleExceptions(ioe);
+      }
+    }
+  }
+
+  private void handleExceptions(IOException cause) throws IOException {
+    if (cause instanceof StorageContainerException || isConnectivityIssue(cause)) {
+      if (shouldRetryRead(cause, retryPolicy, retries++)) {
+        releaseClient();
+        refreshBlockInfo(cause);
+        LOG.warn("Refreshing block data to read block {} due to {}", blockID, cause.getMessage());
+      } else {
+        throw cause;
+      }
+    } else {
+      throw cause;
+    }
+  }
+
+  private int fillBuffer() throws IOException {
+    if (!streamingReader.hasNext()) {
+      return EOF;
+    }
+    buffer = streamingReader.readNext();
+    return buffer == null ? EOF : buffer.limit();
+  }
+
+  protected synchronized void releaseClient() {
+    if (xceiverClientFactory != null && xceiverClient != null) {
+      closeStream();
+      xceiverClientFactory.releaseClientForReadData(xceiverClient, false);
+      xceiverClient = null;
+    }
+  }
+
+  @Override
+  public synchronized void close() throws IOException {
+    releaseClient();
+    xceiverClientFactory = null;
+  }
+
+  private void refreshBlockInfo(IOException cause) throws IOException {
+    refreshBlockInfo(cause, blockID, pipelineRef, tokenRef, refreshFunction);
+  }
+
+  private synchronized void releaseStreamResources(StreamingReadResponse response) {
+    if (xceiverClient != null) {
+      xceiverClient.completeStreamRead(response);
+    }
+  }
+
+  /**
+   * Implementation of a StreamObserver used to received and buffer streaming GRPC reads.
+   */
+  public class StreamingReader implements StreamingReaderSpi {
+
+    private final BlockingQueue<ContainerProtos.ReadBlockResponseProto> responseQueue = new LinkedBlockingQueue<>(1);

Review Comment:
   Added `client side`  to https://github.com/apache/ozone/pull/6613#discussion_r2462932439
   
   > ...  the implementation uses a BlockingQueue responseQueue. When the responses are not removed from the queue, the `client side` gRPC thread is blocked in StreamingReader.onNext(..) and the gRPC streaming mechanism will throttle and slow down the `server side`.
   
   



##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -504,6 +516,65 @@ private XceiverClientReply sendCommandWithRetry(
     }
   }
 
+  /**
+   * Starts a streaming read operation, intended to read entire blocks from the datanodes. This method expects a
+   * {@link StreamObserver} to be passed in, which will be used to receive the streamed data from the datanode.
+   * Upon successfully starting the streaming read, a {@link StreamingReadResponse} is returned, which contains
+   * information about the datanode used for the read, and the request observer that can be used to manage the stream
+   * (e.g., to cancel it if needed). A semaphore is acquired to limit the number of concurrent streaming reads so upon
+   * successful return of this method, the caller must ensure to call {@link #completeStreamRead(StreamingReadResponse)}
+   * to release the semaphore once the streaming read is complete.
+   * @param request The container command request to initiate the streaming read.
+   * @param streamObserver The observer that will handle the streamed responses.
+   * @return A {@link StreamingReadResponse} containing details of the streaming read operation.
+   * @throws IOException
+   * @throws InterruptedException
+   */
+  @Override
+  public StreamingReadResponse streamRead(ContainerCommandRequestProto request,
+      StreamObserver<ContainerCommandResponseProto> streamObserver) throws IOException, InterruptedException {
+    List<DatanodeDetails> datanodeList = sortDatanodes(request);
+    IOException lastException = null;
+    for (DatanodeDetails dn : datanodeList) {
+      try {
+        checkOpen(dn);
+        semaphore.acquire();
+        XceiverClientProtocolServiceStub stub = asyncStubs.get(dn.getID());
+        if (stub == null) {
+          throw new IOException("Failed to get gRPC stub for DataNode: " + dn);
+        }
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("Executing command {} on datanode {}", processForDebug(request), dn);
+        }
+        StreamObserver<ContainerCommandRequestProto> requestObserver = stub
+            .withDeadlineAfter(timeout, TimeUnit.SECONDS)
+            .send(streamObserver);
+        requestObserver.onNext(request);
+        requestObserver.onCompleted();
+        return new StreamingReadResponse(dn, (ClientCallStreamObserver<ContainerCommandRequestProto>) requestObserver);

Review Comment:
   1. A client application opens the file.
   2. It calls read() with 10KB.
   3. It leaves the file open for 1 minute.  `// a gRPC thread is blocked here`
   4. It closes the file.
   
   I see how it works now -- the implementation uses a `BlockingQueue responseQueue`.  When the responses are not removed from the queue, the `client side` gRPC thread is blocked in `StreamingReader.onNext(..)` and the gRPC streaming mechanism will throttle and slow down the `server side`.
   
   However, the number open files will be limited by the number of gRPC threads.  Also, when all the gRPC threads are blocked, any gRPC calls will be blocked.  In an asynchronous model, threads should not blocked.  When the connection is idle at Step 3 above, it should release the thread so it can work on other calls.
   
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r2491600458


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/StreamBlockInputStream.java:
##########
@@ -0,0 +1,443 @@
+/*
+ * 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 java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+import org.apache.commons.lang3.NotImplementedException;
+import org.apache.hadoop.fs.ByteBufferReadable;
+import org.apache.hadoop.fs.CanUnbuffer;
+import org.apache.hadoop.fs.FSExceptionMessages;
+import org.apache.hadoop.fs.Seekable;
+import org.apache.hadoop.hdds.client.BlockID;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadBlockResponseProto;
+import org.apache.hadoop.hdds.scm.OzoneClientConfig;
+import org.apache.hadoop.hdds.scm.StreamingReadResponse;
+import org.apache.hadoop.hdds.scm.StreamingReaderSpi;
+import org.apache.hadoop.hdds.scm.XceiverClientFactory;
+import org.apache.hadoop.hdds.scm.XceiverClientSpi;
+import org.apache.hadoop.hdds.scm.container.common.helpers.StorageContainerException;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.hdds.security.token.OzoneBlockTokenIdentifier;
+import org.apache.hadoop.io.retry.RetryPolicy;
+import org.apache.hadoop.ozone.common.Checksum;
+import org.apache.hadoop.ozone.common.ChecksumData;
+import org.apache.hadoop.ozone.common.OzoneChecksumException;
+import org.apache.hadoop.security.token.Token;
+import org.apache.ratis.thirdparty.io.grpc.StatusRuntimeException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * An {@link java.io.InputStream} called from KeyInputStream to read a block from the
+ * container.
+ */
+public class StreamBlockInputStream extends BlockExtendedInputStream
+    implements Seekable, CanUnbuffer, ByteBufferReadable {
+  private static final Logger LOG = LoggerFactory.getLogger(StreamBlockInputStream.class);
+  private static final int EOF = -1;
+  private static final Throwable CANCELLED_EXCEPTION = new Throwable("Cancelled by client");
+
+  private final BlockID blockID;
+  private final long blockLength;
+  private final AtomicReference<Pipeline> pipelineRef = new AtomicReference<>();
+  private final AtomicReference<Token<OzoneBlockTokenIdentifier>> tokenRef = new AtomicReference<>();
+  private XceiverClientFactory xceiverClientFactory;
+  private XceiverClientSpi xceiverClient;
+
+  private ByteBuffer buffer;
+  private long position = 0;
+  private boolean initialized = false;
+  private StreamingReader streamingReader;
+
+  private final boolean verifyChecksum;
+  private final Function<BlockID, BlockLocationInfo> refreshFunction;
+  private final RetryPolicy retryPolicy;
+  private int retries = 0;
+
+  public StreamBlockInputStream(
+      BlockID blockID, long length, Pipeline pipeline,
+      Token<OzoneBlockTokenIdentifier> token,
+      XceiverClientFactory xceiverClientFactory,
+      Function<BlockID, BlockLocationInfo> refreshFunction,
+      OzoneClientConfig config) throws IOException {
+    this.blockID = blockID;
+    this.blockLength = length;
+    pipelineRef.set(setPipeline(pipeline));
+    tokenRef.set(token);
+    this.xceiverClientFactory = xceiverClientFactory;
+    this.verifyChecksum = config.isChecksumVerify();
+    this.retryPolicy = getReadRetryPolicy(config);
+    this.refreshFunction = refreshFunction;
+  }
+
+  @Override
+  public BlockID getBlockID() {
+    return blockID;
+  }
+
+  @Override
+  public long getLength() {
+    return blockLength;
+  }
+
+  @Override
+  public synchronized long getPos() {
+    return position;
+  }
+
+  @Override
+  public synchronized int read() throws IOException {
+    checkOpen();
+    if (!dataAvailableToRead()) {
+      return EOF;
+    }
+    position++;
+    return buffer.get();
+  }
+
+  @Override
+  public synchronized int read(byte[] b, int off, int len) throws IOException {
+    ByteBuffer tmpBuffer = ByteBuffer.wrap(b, off, len);
+    return read(tmpBuffer);
+  }
+
+  @Override
+  public synchronized int read(ByteBuffer targetBuf) throws IOException {
+    checkOpen();
+    int read = 0;
+    while (targetBuf.hasRemaining()) {
+      if (!dataAvailableToRead()) {
+        break;
+      }
+      int toCopy = Math.min(buffer.remaining(), targetBuf.remaining());
+      ByteBuffer tmpBuf = buffer.duplicate();
+      tmpBuf.limit(tmpBuf.position() + toCopy);
+      targetBuf.put(tmpBuf);
+      buffer.position(tmpBuf.position());
+      position += toCopy;
+      read += toCopy;
+    }
+    return read > 0 ? read : EOF;
+  }
+
+  private boolean dataAvailableToRead() throws IOException {
+    if (position >= blockLength) {
+      return false;
+    }
+    initialize();
+    if (buffer == null || buffer.remaining() == 0) {
+      int loaded = fillBuffer();
+      return loaded != EOF;
+    }
+    return true;
+  }
+
+  @Override
+  protected int readWithStrategy(ByteReaderStrategy strategy) throws IOException {
+    throw new NotImplementedException("readWithStrategy is not implemented.");
+  }
+
+  @Override
+  public synchronized void seek(long pos) throws IOException {
+    checkOpen();
+    if (pos < 0) {
+      throw new IOException("Cannot seek to negative offset");
+    }
+    if (pos > blockLength) {
+      throw new IOException("Cannot seek after the end of the block");
+    }
+    if (pos == position) {
+      return;
+    }
+    closeStream();
+    position = pos;
+  }
+
+  @Override
+  // The seekable interface indicates that seekToNewSource should seek to a new source of the data,
+  // ie a different datanode. This is not supported for now.
+  public synchronized boolean seekToNewSource(long l) throws IOException {
+    return false;
+  }
+
+  @Override
+  public synchronized void unbuffer() {
+    releaseClient();
+  }
+
+  private void closeStream() {
+    if (streamingReader != null) {
+      streamingReader.cancel();
+      streamingReader = null;
+    }
+    initialized = false;
+    buffer = null;
+  }
+
+  protected synchronized void checkOpen() throws IOException {
+    if (xceiverClientFactory == null) {
+      throw new IOException(FSExceptionMessages.STREAM_IS_CLOSED + " Block: " + blockID);
+    }
+  }
+
+  protected synchronized void acquireClient() throws IOException {
+    checkOpen();
+    if (xceiverClient == null) {
+      final Pipeline pipeline = pipelineRef.get();
+      try {
+        xceiverClient = xceiverClientFactory.acquireClientForReadData(pipeline);
+      } catch (IOException ioe) {
+        LOG.warn("Failed to acquire client for pipeline {}, block {}", pipeline, blockID);
+        throw ioe;
+      }
+    }
+  }
+
+  private void initialize() throws IOException {
+    if (initialized) {
+      return;
+    }
+    while (true) {
+      try {
+        acquireClient();
+        streamingReader = new StreamingReader();
+        ContainerProtocolCalls.readBlock(xceiverClient, position, blockID, tokenRef.get(),
+            pipelineRef.get().getReplicaIndexes(), streamingReader);
+        initialized = true;
+        return;
+      } catch (InterruptedException ie) {
+        Thread.currentThread().interrupt();
+        handleExceptions(new IOException("Interrupted", ie));
+      } catch (IOException ioe) {
+        handleExceptions(ioe);
+      }
+    }
+  }
+
+  private void handleExceptions(IOException cause) throws IOException {
+    if (cause instanceof StorageContainerException || isConnectivityIssue(cause)) {
+      if (shouldRetryRead(cause, retryPolicy, retries++)) {
+        releaseClient();
+        refreshBlockInfo(cause);
+        LOG.warn("Refreshing block data to read block {} due to {}", blockID, cause.getMessage());
+      } else {
+        throw cause;
+      }
+    } else {
+      throw cause;
+    }
+  }
+
+  private int fillBuffer() throws IOException {
+    if (!streamingReader.hasNext()) {
+      return EOF;
+    }
+    buffer = streamingReader.readNext();
+    return buffer == null ? EOF : buffer.limit();
+  }
+
+  protected synchronized void releaseClient() {
+    if (xceiverClientFactory != null && xceiverClient != null) {
+      closeStream();
+      xceiverClientFactory.releaseClientForReadData(xceiverClient, false);
+      xceiverClient = null;
+    }
+  }
+
+  @Override
+  public synchronized void close() throws IOException {
+    releaseClient();
+    xceiverClientFactory = null;
+  }
+
+  private void refreshBlockInfo(IOException cause) throws IOException {
+    refreshBlockInfo(cause, blockID, pipelineRef, tokenRef, refreshFunction);
+  }
+
+  private synchronized void releaseStreamResources(StreamingReadResponse response) {
+    if (xceiverClient != null) {
+      xceiverClient.completeStreamRead(response);
+    }
+  }
+
+  /**
+   * Implementation of a StreamObserver used to received and buffer streaming GRPC reads.
+   */
+  public class StreamingReader implements StreamingReaderSpi {
+
+    private final BlockingQueue<ContainerProtos.ReadBlockResponseProto> responseQueue = new LinkedBlockingQueue<>(1);

Review Comment:
   > The thread overhead is on the datanode side, as streaming a block to a client ties up the server handler thread.  ...
   
   @sodonnel , This `BlockingQueue<> responseQueue` is at the client side.  So, the thread blocking problem is at the client side.
   
   Server side gRPC threads won't block in the current implementation.  Since the server side onNext() implementation does not block.  We may print some debug messages to verify.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-3563904554

   > ... have we considered implementing gRPC flow control here? ...
   
   @chungen0126 , Let's merge the current code first and then work on the further improvements.  It is already a lot of code.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "sodonnel (via GitHub)" <gi...@apache.org>.
sodonnel commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-3564686370

   I am happy for @szetszwo to simply pushed his latest changes onto this branch and just commit this one as a single PR. Its just more work and more confusing for future people to see the change split into 3, and if we want to cherry pick the change to other places for testing etc, its harder with 3 commits than 1.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "sodonnel (via GitHub)" <gi...@apache.org>.
sodonnel commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r2457427422


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/StreamBlockInputStream.java:
##########
@@ -0,0 +1,413 @@
+/*
+ * 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 java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+import org.apache.commons.lang3.NotImplementedException;
+import org.apache.hadoop.fs.ByteBufferReadable;
+import org.apache.hadoop.fs.CanUnbuffer;
+import org.apache.hadoop.fs.FSExceptionMessages;
+import org.apache.hadoop.fs.Seekable;
+import org.apache.hadoop.hdds.client.BlockID;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadBlockResponseProto;
+import org.apache.hadoop.hdds.scm.OzoneClientConfig;
+import org.apache.hadoop.hdds.scm.StreamingReadResponse;
+import org.apache.hadoop.hdds.scm.XceiverClientFactory;
+import org.apache.hadoop.hdds.scm.XceiverClientSpi;
+import org.apache.hadoop.hdds.scm.container.common.helpers.StorageContainerException;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.hdds.security.token.OzoneBlockTokenIdentifier;
+import org.apache.hadoop.io.retry.RetryPolicy;
+import org.apache.hadoop.ozone.common.Checksum;
+import org.apache.hadoop.ozone.common.ChecksumData;
+import org.apache.hadoop.ozone.common.OzoneChecksumException;
+import org.apache.hadoop.security.token.Token;
+import org.apache.ratis.thirdparty.io.grpc.stub.StreamObserver;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * An {@link java.io.InputStream} called from KeyInputStream to read a block from the
+ * container.
+ */
+public class StreamBlockInputStream extends BlockExtendedInputStream
+    implements Seekable, CanUnbuffer, ByteBufferReadable {
+  private static final Logger LOG = LoggerFactory.getLogger(StreamBlockInputStream.class);
+  private static final int EOF = -1;
+  private static final Throwable CANCELLED_EXCEPTION = new Throwable("Cancelled by client");
+
+  private final BlockID blockID;
+  private final long blockLength;
+  private final AtomicReference<Pipeline> pipelineRef = new AtomicReference<>();
+  private final AtomicReference<Token<OzoneBlockTokenIdentifier>> tokenRef = new AtomicReference<>();
+  private XceiverClientFactory xceiverClientFactory;
+  private XceiverClientSpi xceiverClient;
+
+  private ByteBuffer buffer;
+  private long position = 0;
+  private boolean initialized = false;
+  private StreamingReader streamingReader;
+
+  private final boolean verifyChecksum;
+  private final Function<BlockID, BlockLocationInfo> refreshFunction;
+  private final RetryPolicy retryPolicy;
+  private int retries = 0;
+
+  public StreamBlockInputStream(
+      BlockID blockID, long length, Pipeline pipeline,
+      Token<OzoneBlockTokenIdentifier> token,
+      XceiverClientFactory xceiverClientFactory,
+      Function<BlockID, BlockLocationInfo> refreshFunction,
+      OzoneClientConfig config) throws IOException {
+    this.blockID = blockID;
+    this.blockLength = length;
+    pipelineRef.set(setPipeline(pipeline));
+    tokenRef.set(token);
+    this.xceiverClientFactory = xceiverClientFactory;
+    this.verifyChecksum = config.isChecksumVerify();
+    this.retryPolicy = getReadRetryPolicy(config);
+    this.refreshFunction = refreshFunction;
+  }
+
+  @Override
+  public BlockID getBlockID() {
+    return blockID;
+  }
+
+  @Override
+  public long getLength() {
+    return blockLength;
+  }
+
+  @Override
+  public synchronized long getPos() {
+    return position;
+  }
+
+  @Override
+  public synchronized int read() throws IOException {
+    checkOpen();
+    if (!dataAvailableToRead()) {
+      return EOF;
+    }
+    position++;
+    return buffer.get();
+  }
+
+  @Override
+  public synchronized int read(byte[] b, int off, int len) throws IOException {
+    ByteBuffer tmpBuffer = ByteBuffer.wrap(b, off, len);
+    return read(tmpBuffer);
+  }
+
+  @Override
+  public synchronized int read(ByteBuffer targetBuf) throws IOException {
+    checkOpen();
+    int read = 0;
+    while (targetBuf.hasRemaining()) {
+      if (!dataAvailableToRead()) {
+        break;
+      }
+      int toCopy = Math.min(buffer.remaining(), targetBuf.remaining());
+      ByteBuffer tmpBuf = buffer.duplicate();
+      tmpBuf.limit(tmpBuf.position() + toCopy);
+      targetBuf.put(tmpBuf);
+      buffer.position(tmpBuf.position());
+      position += toCopy;
+      read += toCopy;
+    }
+    return read > 0 ? read : EOF;
+  }
+
+  private boolean dataAvailableToRead() throws IOException {
+    if (position >= blockLength) {
+      return false;
+    }
+    initialize();
+    if (buffer == null || buffer.remaining() == 0) {
+      int loaded = fillBuffer();
+      return loaded != EOF;
+    }
+    return true;
+  }
+
+  @Override
+  protected int readWithStrategy(ByteReaderStrategy strategy) throws IOException {
+    throw new NotImplementedException("readWithStrategy is not implemented.");
+  }
+
+  @Override
+  public synchronized void seek(long pos) throws IOException {
+    checkOpen();
+    if (pos < 0) {
+      throw new IOException("Cannot seek to negative offset");
+    }
+    if (pos > blockLength) {
+      throw new IOException("Cannot seek after the end of the block");
+    }
+    if (pos == position) {
+      return;
+    }
+    closeStream();
+    position = pos;
+  }
+
+  @Override
+  // The seekable interface indicates that seekToNewSource should seek to a new source of the data,
+  // ie a different datanode. This is not supported for now.
+  public synchronized boolean seekToNewSource(long l) throws IOException {
+    return false;
+  }
+
+  @Override
+  public synchronized void unbuffer() {
+    releaseClient();
+  }
+
+  private void closeStream() {
+    if (streamingReader != null) {
+      streamingReader.cancel();
+      streamingReader = null;
+    }
+    initialized = false;
+    buffer = null;
+  }
+
+  protected synchronized void checkOpen() throws IOException {
+    if (xceiverClientFactory == null) {
+      throw new IOException(FSExceptionMessages.STREAM_IS_CLOSED + " Block: " + blockID);
+    }
+  }
+
+  protected synchronized void acquireClient() throws IOException {
+    checkOpen();
+    if (xceiverClient == null) {
+      final Pipeline pipeline = pipelineRef.get();
+      try {
+        xceiverClient = xceiverClientFactory.acquireClientForReadData(pipeline);
+      } catch (IOException ioe) {
+        LOG.warn("Failed to acquire client for pipeline {}, block {}", pipeline, blockID);
+        throw ioe;
+      }
+    }
+  }
+
+  private void initialize() throws IOException {
+    if (initialized) {
+      return;
+    }
+    while (true) {
+      try {
+        acquireClient();
+        streamingReader = new StreamingReader();
+        StreamingReadResponse response =
+            ContainerProtocolCalls.readBlock(xceiverClient, position, blockID, tokenRef.get(),
+                pipelineRef.get().getReplicaIndexes(), streamingReader);
+        streamingReader.setRequestResponse(response);
+        initialized = true;
+        return;
+      } catch (InterruptedException ie) {
+        Thread.currentThread().interrupt();
+        handleExceptions(new IOException("Interrupted", ie));
+      } catch (IOException ioe) {
+        handleExceptions(ioe);
+      }
+    }
+  }
+
+  private void handleExceptions(IOException cause) throws IOException {
+    if (cause instanceof StorageContainerException || isConnectivityIssue(cause)) {
+      if (shouldRetryRead(cause, retryPolicy, retries++)) {
+        releaseClient();
+        refreshBlockInfo(cause);
+        LOG.warn("Refreshing block data to read block {} due to {}", blockID, cause.getMessage());
+      } else {
+        throw cause;
+      }
+    } else {
+      throw cause;
+    }
+  }
+
+  private int fillBuffer() throws IOException {
+    if (!streamingReader.hasNext()) {
+      return EOF;
+    }
+    buffer = streamingReader.readNext();
+    return buffer == null ? EOF : buffer.limit();
+  }
+
+  protected synchronized void releaseClient() {
+    if (xceiverClientFactory != null && xceiverClient != null) {
+      closeStream();
+      xceiverClientFactory.releaseClientForReadData(xceiverClient, false);
+      xceiverClient = null;
+    }
+  }
+
+  @Override
+  public synchronized void close() throws IOException {
+    releaseClient();
+    xceiverClientFactory = null;
+  }
+
+  private void refreshBlockInfo(IOException cause) throws IOException {
+    refreshBlockInfo(cause, blockID, pipelineRef, tokenRef, refreshFunction);
+  }
+
+  /**
+   * Implementation of a StreamObserver used to received and buffer streaming GRPC reads.
+   */
+  public class StreamingReader implements StreamObserver<ContainerProtos.ContainerCommandResponseProto> {
+
+    private final BlockingQueue<ContainerProtos.ReadBlockResponseProto> responseQueue = new LinkedBlockingQueue<>(1);
+    private final AtomicBoolean completed = new AtomicBoolean(false);
+    private final AtomicBoolean failed = new AtomicBoolean(false);
+    private final AtomicBoolean semaphoreReleased = new AtomicBoolean(false);
+    private final AtomicReference<Throwable> error = new AtomicReference<>();
+    private StreamingReadResponse response;
+
+    // TODO: Semaphore in XceiverClient which count open stream?
+    public boolean hasNext() {
+      return !responseQueue.isEmpty() || !completed.get();
+    }
+
+    public ByteBuffer readNext() throws IOException {
+      if (failed.get()) {
+        Throwable cause = error.get();
+        throw new IOException("Streaming read failed", cause);
+      }
+
+      if (completed.get() && responseQueue.isEmpty()) {
+        return null; // Stream ended
+      }
+
+      ReadBlockResponseProto readBlock;
+      try {
+        readBlock = responseQueue.poll(30, TimeUnit.SECONDS);
+      } catch (InterruptedException e) {
+        Thread.currentThread().interrupt();
+        throw new IOException("Interrupted while waiting for response", e);
+      }
+      if (readBlock == null) {
+        if (failed.get()) {
+          Throwable cause = error.get();
+          throw new IOException("Streaming read failed", cause);
+        } else if (completed.get()) {
+          return null; // Stream ended
+        } else {
+          throw new IOException("Timed out waiting for response");
+        }
+      }
+      // The server always returns data starting from the last checksum boundary. Therefore if the reader position is
+      // ahead of the position we received from the server, we need to adjust the buffer position accordingly.
+      // If the reader position is behind
+      ByteBuffer buf = readBlock.getData().asReadOnlyByteBuffer();
+      long blockOffset = readBlock.getOffset();
+      long pos = getPos();
+      if (pos < blockOffset) {
+        // This should not happen, and if it does, we have a bug.
+        throw new IOException("Received data out of order. Position is " + pos + " but received data at "
+            + blockOffset);
+      }
+      if (pos > readBlock.getOffset()) {
+        int offset = (int)(pos - readBlock.getOffset());
+        buf.position(offset);
+      }
+      return buf;
+    }
+
+    public void setRequestResponse(StreamingReadResponse streamingReadResponse) {
+      this.response = streamingReadResponse;
+    }
+
+    /**
+     * By calling cancel, the client will send a cancel signal to the server, which will stop sending more data and
+     * cause the onError() to be called in this observer with a CANCELLED exception.
+     */
+    public void cancel() {
+      if (response != null && response.getRequestObserver() != null) {
+        response.getRequestObserver().cancel("Cancelled by client", CANCELLED_EXCEPTION);
+        completed.set(true);
+        releaseResources();
+      }
+    }
+
+    private void releaseResources() {
+      boolean wasNotYetComplete = semaphoreReleased.getAndSet(true);
+      if (wasNotYetComplete) {
+        xceiverClient.completeStreamRead(response);
+      }
+    }
+
+    @Override
+    public void onNext(ContainerProtos.ContainerCommandResponseProto containerCommandResponseProto) {
+      try {
+        ReadBlockResponseProto readBlock = containerCommandResponseProto.getReadBlock();
+        ByteBuffer data = readBlock.getData().asReadOnlyByteBuffer();
+        if (verifyChecksum) {
+          ChecksumData checksumData = ChecksumData.getFromProtoBuf(readBlock.getChecksumData());
+          Checksum.verifyChecksum(data, checksumData, 0);
+        }
+        offerToQueue(readBlock);
+      } catch (OzoneChecksumException e) {
+        // Calling onError will cancel the stream on the server side and also set the failure state.
+        onError(e);

Review Comment:
   I think you are correct. We should call requestObserver.cancel() or error() to cancel the stream from the server. Trying a unit test for this, there is some problem with the error handling flow. I will look at it more tomorrow.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r2461180608


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -504,6 +516,65 @@ private XceiverClientReply sendCommandWithRetry(
     }
   }
 
+  /**
+   * Starts a streaming read operation, intended to read entire blocks from the datanodes. This method expects a
+   * {@link StreamObserver} to be passed in, which will be used to receive the streamed data from the datanode.
+   * Upon successfully starting the streaming read, a {@link StreamingReadResponse} is returned, which contains
+   * information about the datanode used for the read, and the request observer that can be used to manage the stream
+   * (e.g., to cancel it if needed). A semaphore is acquired to limit the number of concurrent streaming reads so upon
+   * successful return of this method, the caller must ensure to call {@link #completeStreamRead(StreamingReadResponse)}
+   * to release the semaphore once the streaming read is complete.
+   * @param request The container command request to initiate the streaming read.
+   * @param streamObserver The observer that will handle the streamed responses.
+   * @return A {@link StreamingReadResponse} containing details of the streaming read operation.
+   * @throws IOException
+   * @throws InterruptedException
+   */
+  @Override
+  public StreamingReadResponse streamRead(ContainerCommandRequestProto request,
+      StreamObserver<ContainerCommandResponseProto> streamObserver) throws IOException, InterruptedException {
+    List<DatanodeDetails> datanodeList = sortDatanodes(request);
+    IOException lastException = null;
+    for (DatanodeDetails dn : datanodeList) {
+      try {
+        checkOpen(dn);
+        semaphore.acquire();
+        XceiverClientProtocolServiceStub stub = asyncStubs.get(dn.getID());
+        if (stub == null) {
+          throw new IOException("Failed to get gRPC stub for DataNode: " + dn);
+        }
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("Executing command {} on datanode {}", processForDebug(request), dn);
+        }
+        StreamObserver<ContainerCommandRequestProto> requestObserver = stub
+            .withDeadlineAfter(timeout, TimeUnit.SECONDS)
+            .send(streamObserver);
+        requestObserver.onNext(request);
+        requestObserver.onCompleted();
+        return new StreamingReadResponse(dn, (ClientCallStreamObserver<ContainerCommandRequestProto>) requestObserver);

Review Comment:
   > However its still not clear to me if I need to call onComplete()  ...
   
   It should not be.   If we call `onComplete()` right after `onNext()`, a gRPC stream can only send one request with a fixed length.  Then, a stream won't be able to support multiple read() calls below or it has to read the entire blocks all the time.
   
   Suppose a block has 128 MB.
   - Case 1
   1. A client application opens the file.
   2. It calls read() with 10KB initially
   3. It calls read() with 50MB more.
   4. ...  // the client could call read() any number of times with an arbitrary length.
   
   - Case 2
   1. A client application opens the file.
   2. It calls read() with 10KB.
   3. It leaves the file open for 1 minute.
   4. It closes the file.
   
   If we only have one request per stream, how to set the data length for both cases?   If we read the entire block all the time, Case 2 is inefficient. Otherwise, we don't read the entire block.  Then, it has to open multiple gRPC streams for Case 1.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r2461180608


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -504,6 +516,65 @@ private XceiverClientReply sendCommandWithRetry(
     }
   }
 
+  /**
+   * Starts a streaming read operation, intended to read entire blocks from the datanodes. This method expects a
+   * {@link StreamObserver} to be passed in, which will be used to receive the streamed data from the datanode.
+   * Upon successfully starting the streaming read, a {@link StreamingReadResponse} is returned, which contains
+   * information about the datanode used for the read, and the request observer that can be used to manage the stream
+   * (e.g., to cancel it if needed). A semaphore is acquired to limit the number of concurrent streaming reads so upon
+   * successful return of this method, the caller must ensure to call {@link #completeStreamRead(StreamingReadResponse)}
+   * to release the semaphore once the streaming read is complete.
+   * @param request The container command request to initiate the streaming read.
+   * @param streamObserver The observer that will handle the streamed responses.
+   * @return A {@link StreamingReadResponse} containing details of the streaming read operation.
+   * @throws IOException
+   * @throws InterruptedException
+   */
+  @Override
+  public StreamingReadResponse streamRead(ContainerCommandRequestProto request,
+      StreamObserver<ContainerCommandResponseProto> streamObserver) throws IOException, InterruptedException {
+    List<DatanodeDetails> datanodeList = sortDatanodes(request);
+    IOException lastException = null;
+    for (DatanodeDetails dn : datanodeList) {
+      try {
+        checkOpen(dn);
+        semaphore.acquire();
+        XceiverClientProtocolServiceStub stub = asyncStubs.get(dn.getID());
+        if (stub == null) {
+          throw new IOException("Failed to get gRPC stub for DataNode: " + dn);
+        }
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("Executing command {} on datanode {}", processForDebug(request), dn);
+        }
+        StreamObserver<ContainerCommandRequestProto> requestObserver = stub
+            .withDeadlineAfter(timeout, TimeUnit.SECONDS)
+            .send(streamObserver);
+        requestObserver.onNext(request);
+        requestObserver.onCompleted();
+        return new StreamingReadResponse(dn, (ClientCallStreamObserver<ContainerCommandRequestProto>) requestObserver);

Review Comment:
   > However its still not clear to me if I need to call onComplete()  ...
   
   It should not be.   If we call `onComplete()` right after `onNext()`, a gRPC stream can only send one request with a fixed length.  Then, a stream won't be able to support multiple read below or it has to read the entire blocks all the time.
   
   Suppose A block has 128 MB.
   - Case 1
   1. A client application opens the file.
   2. It calls read() with 10KB initially
   3. It calls read() with 50MB more.
   4. ...  // the client could call read() any number of times with an arbitrary length.
   
   - Case 2
   1. A client application opens the file.
   2. It calls read() with 10KB.
   3. It leaves the file open for 1 minute.
   4. It closes the file.
   
   If we only have one request per stream, how to set the data length for both cases?   If we read the entire block all the time, Case 2 is inefficient. Otherwise, we don't read the entire block.  Then, it have to open multiple gRPC streams for case 1.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "chungen0126 (via GitHub)" <gi...@apache.org>.
chungen0126 commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1792375480


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/StreamBlockInput.java:
##########
@@ -0,0 +1,777 @@
+/*
+ * 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 com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
+import org.apache.commons.lang3.NotImplementedException;
+import org.apache.hadoop.fs.ByteBufferReadable;
+import org.apache.hadoop.fs.CanUnbuffer;
+import org.apache.hadoop.fs.Seekable;
+import org.apache.hadoop.hdds.client.BlockID;
+import org.apache.hadoop.hdds.client.StandaloneReplicationConfig;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadChunkResponseProto;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadBlockResponseProto;
+import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
+import org.apache.hadoop.hdds.scm.OzoneClientConfig;
+import org.apache.hadoop.hdds.scm.XceiverClientFactory;
+import org.apache.hadoop.hdds.scm.XceiverClientSpi;
+import org.apache.hadoop.hdds.scm.client.HddsClientUtils;
+import org.apache.hadoop.hdds.scm.container.common.helpers.StorageContainerException;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.hdds.security.exception.SCMSecurityException;
+import org.apache.hadoop.hdds.security.token.OzoneBlockTokenIdentifier;
+import org.apache.hadoop.io.retry.RetryPolicy;
+import org.apache.hadoop.ozone.common.Checksum;
+import org.apache.hadoop.ozone.common.ChecksumData;
+import org.apache.hadoop.ozone.common.OzoneChecksumException;
+import org.apache.hadoop.ozone.common.utils.BufferUtils;
+import org.apache.hadoop.security.token.Token;
+import org.apache.ratis.thirdparty.com.google.protobuf.ByteString;
+import org.apache.ratis.thirdparty.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.EOFException;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+
+import static org.apache.hadoop.hdds.client.ReplicationConfig.getLegacyFactor;
+
+/**
+ * An {@link java.io.InputStream} called from KeyInputStream to read a block from the
+ * container.
+ */
+public class StreamBlockInput extends BlockExtendedInputStream
+    implements Seekable, CanUnbuffer, ByteBufferReadable {
+  private static final Logger LOG =
+      LoggerFactory.getLogger(StreamBlockInput.class);
+  private final BlockID blockID;
+  private final long length;
+  private final AtomicReference<Pipeline> pipelineRef =
+      new AtomicReference<>();
+  private final AtomicReference<Token<OzoneBlockTokenIdentifier>> tokenRef =
+      new AtomicReference<>();
+  private XceiverClientFactory xceiverClientFactory;
+  private XceiverClientSpi xceiverClient;
+
+  private List<Long> bufferoffsets;
+  private int bufferIndex;
+  private long blockPosition = -1;
+  private List<ByteBuffer> buffers;
+  private boolean allocated = false;
+  private long bufferOffsetWrtBlockDataData;
+  private long buffersSize;
+  private static final int EOF = -1;
+  private final List<XceiverClientSpi.Validator> validators;
+  private final boolean verifyChecksum;
+  private final Function<BlockID, BlockLocationInfo> refreshFunction;
+  private final RetryPolicy retryPolicy;
+  private int retries;
+
+
+  public StreamBlockInput(
+      BlockID blockID, long length, Pipeline pipeline,
+      Token<OzoneBlockTokenIdentifier> token,
+      XceiverClientFactory xceiverClientFactory,
+      Function<BlockID, BlockLocationInfo> refreshFunction,
+      OzoneClientConfig config) throws IOException {
+    this.blockID = blockID;
+    LOG.debug("Initializing StreamBlockInput for block {}", blockID);
+    this.length = length;
+    setPipeline(pipeline);
+    tokenRef.set(token);
+    this.xceiverClientFactory = xceiverClientFactory;
+    this.validators = ContainerProtocolCalls.toValidatorList(
+        (request, response) -> validateBlock(response));
+    this.verifyChecksum = config.isChecksumVerify();
+    this.refreshFunction = refreshFunction;
+    this.retryPolicy =
+        HddsClientUtils.createRetryPolicy(config.getMaxReadRetryCount(),
+            TimeUnit.SECONDS.toMillis(config.getReadRetryInterval()));
+
+  }
+
+
+  public BlockID getBlockID() {
+    return blockID;
+  }
+
+  public long getLength() {
+    return length;
+  }
+
+  @Override
+  public synchronized long getPos() {
+    if (length == 0) {
+      return 0;
+    }
+    if (blockPosition >= 0) {
+      return blockPosition;
+    }
+
+    if (allocated && !buffersHaveData() && !dataRemainingInBlock()) {
+      Preconditions.checkState(
+          bufferOffsetWrtBlockDataData + buffersSize == length,
+          "EOF detected but not at the last byte of the chunk");
+      return length;
+    }
+    if (buffersHaveData()) {
+      // BufferOffset w.r.t to BlockData + BufferOffset w.r.t buffers +
+      // Position of current Buffer
+      return bufferOffsetWrtBlockDataData + bufferoffsets.get(bufferIndex) +
+          buffers.get(bufferIndex).position();
+    }
+    if (buffersAllocated()) {
+      return bufferOffsetWrtBlockDataData + buffersSize;
+    }
+    return 0;
+  }
+
+  @Override
+  public synchronized int read() throws IOException {
+    checkOpen();
+
+    int dataout = EOF;
+    int len = 1;
+    int available;
+    while (len > 0) {
+      try {
+        acquireClient();
+        available = prepareRead(1);
+        retries = 0;
+      } catch (SCMSecurityException ex) {
+        throw ex;
+      } catch (StorageContainerException e) {
+        if (shouldRetryRead(e)) {
+          releaseClient();
+          refreshBlockInfo(e);
+          continue;
+        } else {
+          throw e;
+        }
+      } catch (IOException ioe) {
+        if (shouldRetryRead(ioe)) {
+          if (isConnectivityIssue(ioe)) {
+            releaseClient();
+            refreshBlockInfo(ioe);
+          } else {
+            releaseClient();
+          }
+          continue;
+        } else {
+          throw ioe;
+        }
+      }
+      if (available == EOF) {
+        // There is no more data in the chunk stream. The buffers should have
+        // been released by now
+        Preconditions.checkState(buffers == null);
+      } else {
+        dataout = Byte.toUnsignedInt(buffers.get(bufferIndex).get());
+      }
+
+      len -= available;
+      if (bufferEOF()) {
+        releaseBuffers(bufferIndex);
+      }
+    }
+
+
+    return dataout;
+
+
+  }
+
+  @Override
+  public synchronized int read(byte[] b, int off, int len) throws IOException {
+    // According to the JavaDocs for InputStream, it is recommended that
+    // subclasses provide an override of bulk read if possible for performance
+    // reasons.  In addition to performance, we need to do it for correctness
+    // reasons.  The Ozone REST service uses PipedInputStream and
+    // PipedOutputStream to relay HTTP response data between a Jersey thread and
+    // a Netty thread.  It turns out that PipedInputStream/PipedOutputStream
+    // have a subtle dependency (bug?) on the wrapped stream providing separate
+    // implementations of single-byte read and bulk read.  Without this, get key
+    // responses might close the connection before writing all of the bytes
+    // advertised in the Content-Length.
+    if (b == null) {
+      throw new NullPointerException();
+    }
+    if (off < 0 || len < 0 || len > b.length - off) {
+      throw new IndexOutOfBoundsException();
+    }
+    if (len == 0) {
+      return 0;
+    }
+    int total = 0;
+    int available;
+    while (len > 0) {
+      try {
+        acquireClient();
+        available = prepareRead(len);
+        retries = 0;
+      } catch (SCMSecurityException ex) {
+        throw ex;
+      } catch (StorageContainerException e) {
+        if (shouldRetryRead(e)) {
+          releaseClient();
+          refreshBlockInfo(e);
+          continue;
+        } else {
+          throw e;
+        }
+      } catch (IOException ioe) {
+        if (shouldRetryRead(ioe)) {
+          if (isConnectivityIssue(ioe)) {
+            releaseClient();
+            refreshBlockInfo(ioe);
+          } else {
+            releaseClient();
+          }
+          continue;
+        } else {
+          throw ioe;
+        }
+      }
+      if (available == EOF) {
+        // There is no more data in the block stream. The buffers should have
+        // been released by now
+        Preconditions.checkState(buffers == null);
+        return total != 0 ? total : EOF;
+      }
+      buffers.get(bufferIndex).get(b, off + total, available);
+      len -= available;
+      total += available;
+
+      if (bufferEOF()) {
+        releaseBuffers(bufferIndex);
+      }
+    }
+    return total;
+
+  }
+
+  @Override
+  public synchronized void close() throws IOException {
+    releaseClient();
+    releaseBuffers();
+    xceiverClientFactory = null;
+  }
+
+  @Override
+  public synchronized int read(ByteBuffer byteBuffer) throws IOException {
+    if (byteBuffer == null) {
+      throw new NullPointerException();
+    }
+    int len = byteBuffer.remaining();
+    if (len == 0) {
+      return 0;
+    }
+    int total = 0;
+    int available;
+    while (len > 0) {
+      try {
+        acquireClient();
+        available = prepareRead(len);
+        retries = 0;
+      } catch (SCMSecurityException ex) {
+        throw ex;
+      } catch (StorageContainerException e) {
+        if (shouldRetryRead(e)) {
+          releaseClient();
+          refreshBlockInfo(e);
+          continue;
+        } else {
+          throw e;
+        }
+      } catch (IOException ioe) {
+        if (shouldRetryRead(ioe)) {
+          if (isConnectivityIssue(ioe)) {
+            releaseClient();
+            refreshBlockInfo(ioe);
+          } else {
+            releaseClient();
+          }
+          continue;
+        } else {
+          throw ioe;
+        }
+      }
+      if (available == EOF) {
+        // There is no more data in the block stream. The buffers should have
+        // been released by now
+        Preconditions.checkState(buffers == null);
+        return total != 0 ? total : EOF;
+      }
+      ByteBuffer readBuf = buffers.get(bufferIndex);
+      ByteBuffer tmpBuf = readBuf.duplicate();
+      tmpBuf.limit(tmpBuf.position() + available);
+      byteBuffer.put(tmpBuf);
+      readBuf.position(tmpBuf.position());
+
+      len -= available;
+      total += available;
+
+      if (bufferEOF()) {
+        releaseBuffers(bufferIndex);
+      }
+    }
+    return total;
+  }
+
+  @Override
+  protected int readWithStrategy(ByteReaderStrategy strategy) throws IOException {
+    throw new NotImplementedException("readWithStrategy is not implemented.");
+  }
+
+  @Override
+  public synchronized void seek(long pos) throws IOException {
+    if (pos < 0 || pos > length) {
+      if (pos == 0) {
+        // It is possible for length and pos to be zero in which case
+        // seek should return instead of throwing exception
+        return;
+      }
+      throw new EOFException("EOF encountered at pos: " + pos + " for block: " + blockID);
+    }
+
+    if (buffersHavePosition(pos)) {
+      // The bufferPosition is w.r.t the current block.
+      // Adjust the bufferIndex and position to the seeked position.
+      adjustBufferPosition(pos - bufferOffsetWrtBlockDataData);
+    } else {
+      blockPosition = pos;
+    }
+  }
+
+  @Override
+  public synchronized boolean seekToNewSource(long l) throws IOException {
+    return false;
+  }
+
+  @Override
+  public synchronized void unbuffer() {
+    blockPosition = getPos();
+    releaseClient();
+    releaseBuffers();
+  }
+
+  private void setPipeline(Pipeline pipeline) throws IOException {
+    if (pipeline == null) {
+      return;
+    }
+    long replicaIndexes = pipeline.getNodes().stream().mapToInt(pipeline::getReplicaIndex).distinct().count();
+
+    if (replicaIndexes > 1) {
+      throw new IOException(String.format("Pipeline: %s has nodes containing different replica indexes.",
+          pipeline));
+    }
+
+    // irrespective of the container state, we will always read via Standalone
+    // protocol.
+    boolean okForRead =
+        pipeline.getType() == HddsProtos.ReplicationType.STAND_ALONE
+            || pipeline.getType() == HddsProtos.ReplicationType.EC;
+    Pipeline readPipeline = okForRead ? pipeline : Pipeline.newBuilder(pipeline)
+        .setReplicationConfig(StandaloneReplicationConfig.getInstance(
+            getLegacyFactor(pipeline.getReplicationConfig())))
+        .build();
+    pipelineRef.set(readPipeline);
+  }
+
+  protected synchronized void checkOpen() throws IOException {
+    if (xceiverClientFactory == null) {
+      throw new IOException("BlockInputStream has been closed.");
+    }
+  }
+
+  protected synchronized void acquireClient() throws IOException {
+    if (xceiverClientFactory != null && xceiverClient == null) {
+      final Pipeline pipeline = pipelineRef.get();
+      try {
+        xceiverClient = xceiverClientFactory.acquireClientForReadData(pipeline);
+      } catch (IOException ioe) {
+        LOG.warn("Failed to acquire client for pipeline {}, block {}",
+            pipeline, blockID);
+        throw ioe;
+      }
+    }
+  }
+
+  private synchronized int prepareRead(int len) throws IOException {
+    for (;;) {
+      if (blockPosition >= 0) {
+        if (buffersHavePosition(blockPosition)) {
+          // The current buffers have the seeked position. Adjust the buffer
+          // index and position to point to the buffer position.
+          adjustBufferPosition(blockPosition - bufferOffsetWrtBlockDataData);
+        } else {
+          // Read a required block data to fill the buffers with seeked
+          // position data
+          readDataFromContainer(len);
+        }
+      }
+      if (buffersHaveData()) {
+        // Data is available from buffers
+        ByteBuffer bb = buffers.get(bufferIndex);
+        return Math.min(len, bb.remaining());
+      } else if (dataRemainingInBlock()) {
+        // There is more data in the block stream which has not
+        // been read into the buffers yet.
+        readDataFromContainer(len);
+      } else {
+        // All available input from this block stream has been consumed.
+        return EOF;
+      }
+    }
+
+
+  }
+
+  private boolean buffersHavePosition(long pos) {
+    // Check if buffers have been allocated
+    if (buffersAllocated()) {
+      // Check if the current buffers cover the input position
+      // Released buffers should not be considered when checking if position
+      // is available
+      return pos >= bufferOffsetWrtBlockDataData +
+          bufferoffsets.get(0) &&
+          pos < bufferOffsetWrtBlockDataData + buffersSize;
+    }
+    return false;
+  }
+
+  /**
+   * Check if the buffers have been allocated data and false otherwise.
+   */
+  @VisibleForTesting
+  protected boolean buffersAllocated() {
+    return buffers != null && !buffers.isEmpty();
+  }
+
+  /**
+   * Adjust the buffers position to account for seeked position and/ or checksum
+   * boundary reads.
+   * @param bufferPosition the position to which the buffers must be advanced
+   */
+  private void adjustBufferPosition(long bufferPosition) {
+    // The bufferPosition is w.r.t the current buffers.
+    // Adjust the bufferIndex and position to the seeked bufferPosition.
+    if (bufferIndex >= buffers.size()) {
+      bufferIndex = Collections.binarySearch(bufferoffsets, bufferPosition);
+    } else if (bufferPosition < bufferoffsets.get(bufferIndex)) {
+      bufferIndex = Collections.binarySearch(
+          bufferoffsets.subList(0, bufferIndex), bufferPosition);
+    } else if (bufferPosition >= bufferoffsets.get(bufferIndex) +
+        buffers.get(bufferIndex).capacity()) {
+      bufferIndex = Collections.binarySearch(bufferoffsets.subList(
+          bufferIndex + 1, buffers.size()), bufferPosition);
+    }
+    if (bufferIndex < 0) {
+      bufferIndex = -bufferIndex - 2;
+    }
+
+    buffers.get(bufferIndex).position(
+        (int) (bufferPosition - bufferoffsets.get(bufferIndex)));
+
+    // Reset buffers > bufferIndex to position 0. We do this to reset any
+    // previous reads/ seeks which might have updated any buffer position.
+    // For buffers < bufferIndex, we do not need to reset the position as it
+    // not required for this read. If a seek was done to a position in the
+    // previous indices, the buffer position reset would be performed in the
+    // seek call.
+    for (int i = bufferIndex + 1; i < buffers.size(); i++) {
+      buffers.get(i).position(0);
+    }
+
+    // Reset the blockPosition as chunk stream has been initialized i.e. the
+    // buffers have been allocated.
+    blockPosition = -1;
+  }
+
+  /**
+   * Reads full or partial Chunk from DN Container based on the current
+   * position of the ChunkInputStream, the number of bytes of data to read
+   * and the checksum boundaries.
+   * If successful, then the read data in saved in the buffers so that
+   * subsequent read calls can utilize it.
+   * @param len number of bytes of data to be read
+   * @throws IOException if there is an I/O error while performing the call
+   * to Datanode
+   */
+  private synchronized void readDataFromContainer(int len) throws IOException {
+    // index of first byte to be read from the block
+    long startByteIndex;
+    if (blockPosition >= 0) {
+      // If seek operation was called to advance the buffer position, the
+      // chunk should be read from that position onwards.
+      startByteIndex = blockPosition;
+    } else {
+      // Start reading the block from the last blockPosition onwards.
+      startByteIndex = bufferOffsetWrtBlockDataData + buffersSize;
+    }
+
+    // bufferOffsetWrtChunkData and buffersSize are updated after the data
+    // is read from Container and put into the buffers, but if read fails
+    // and is retried, we need the previous position.  Position is reset after
+    // successful read in adjustBufferPosition()
+    blockPosition = getPos();
+    bufferOffsetWrtBlockDataData = readData(startByteIndex, len);
+    long tempOffset = 0L;
+    buffersSize = 0L;
+    bufferoffsets = new ArrayList<>(buffers.size());
+    for (ByteBuffer buffer : buffers) {
+      bufferoffsets.add(tempOffset);
+      tempOffset += buffer.limit();
+      buffersSize += buffer.limit();
+
+    }
+    bufferIndex = 0;
+    allocated = true;
+    adjustBufferPosition(startByteIndex - bufferOffsetWrtBlockDataData);
+
+  }
+
+  @VisibleForTesting
+  protected long readData(long startByteIndex, long len)
+      throws IOException {
+    Pipeline pipeline = pipelineRef.get();
+    buffers = new ArrayList<>();
+    ReadBlockResponseProto response =
+        ContainerProtocolCalls.readBlock(xceiverClient, startByteIndex,
+        len, blockID, validators, tokenRef.get(), pipeline.getReplicaIndexes(), verifyChecksum);
+    List<ReadChunkResponseProto> readBlocks = response.getReadChunkList();
+
+    for (ReadChunkResponseProto readBlock : readBlocks) {
+      if (readBlock.hasDataBuffers()) {
+        buffers.addAll(BufferUtils.getReadOnlyByteBuffers(
+            readBlock.getDataBuffers().getBuffersList()));
+      } else {
+        throw new IOException("Unexpected error while reading chunk data " +
+            "from container. No data returned.");
+      }
+    }
+    return response.getReadChunk(0)
+        .getChunkData().getOffset();
+  }
+
+  /**
+   * Check if the buffers have any data remaining between the current
+   * position and the limit.
+   */
+  private boolean buffersHaveData() {
+    boolean hasData = false;
+    if (buffersAllocated()) {
+      int buffersLen = buffers.size();
+      while (bufferIndex < buffersLen) {
+        ByteBuffer buffer = buffers.get(bufferIndex);
+        if (buffer != null && buffer.hasRemaining()) {
+          // current buffer has data
+          hasData = true;
+          break;
+        } else {
+          if (bufferIndex < buffersLen - 1) {
+            // move to next available buffer
+            ++bufferIndex;
+            Preconditions.checkState(bufferIndex < buffers.size());
+          } else {
+            // no more buffers remaining
+            break;
+          }
+        }
+      }
+    }
+
+    return hasData;
+  }
+
+  /**
+   * Check if there is more data in the chunk which has not yet been read
+   * into the buffers.
+   */
+  private boolean dataRemainingInBlock() {
+    long bufferPos;
+    if (blockPosition >= 0) {
+      bufferPos = blockPosition;
+    } else {
+      bufferPos = bufferOffsetWrtBlockDataData + buffersSize;
+    }
+
+    return bufferPos < length;
+  }
+
+  /**
+   * Check if current buffer had been read till the end.
+   */
+  private boolean bufferEOF() {
+    return allocated && !buffers.get(bufferIndex).hasRemaining();
+  }
+
+  /**
+   * Release the buffers upto the given index.
+   * @param releaseUptoBufferIndex bufferIndex (inclusive) upto which the
+   *                               buffers must be released
+   */
+  private void releaseBuffers(int releaseUptoBufferIndex) {
+    int buffersLen = buffers.size();
+    if (releaseUptoBufferIndex == buffersLen - 1) {
+      // Before releasing all the buffers, if block EOF is not reached, then
+      // blockPosition should be set to point to the last position of the
+      // buffers. This should be done so that getPos() can return the current
+      // block position
+      blockPosition = bufferOffsetWrtBlockDataData +
+          bufferoffsets.get(releaseUptoBufferIndex) +
+          buffers.get(releaseUptoBufferIndex).capacity();
+      // Release all the buffers
+      releaseBuffers();
+    } else {
+      buffers = buffers.subList(releaseUptoBufferIndex + 1, buffersLen);
+      bufferoffsets = bufferoffsets.subList(
+          releaseUptoBufferIndex + 1, buffersLen);
+    }
+  }
+
+  /**
+   * If EOF is reached, release the buffers.
+   */
+  private void releaseBuffers() {
+    buffers = null;

Review Comment:
   I think `buffers = null` is good. While reading new data, we use new buffer list from container. We don't reuse the buffer list, so I just let it clean up by GC.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "kerneltime (via GitHub)" <gi...@apache.org>.
kerneltime commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-2214715823

   @chungen0126 can you please address the merge conflicts?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "chungen0126 (via GitHub)" <gi...@apache.org>.
chungen0126 commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1882632818


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/StreamBlockInputStream.java:
##########
@@ -0,0 +1,751 @@
+/*
+ * 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 com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
+import org.apache.commons.lang3.NotImplementedException;
+import org.apache.hadoop.fs.ByteBufferReadable;
+import org.apache.hadoop.fs.CanUnbuffer;
+import org.apache.hadoop.fs.Seekable;
+import org.apache.hadoop.hdds.client.BlockID;
+import org.apache.hadoop.hdds.client.StandaloneReplicationConfig;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadChunkResponseProto;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadBlockResponseProto;
+import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
+import org.apache.hadoop.hdds.scm.OzoneClientConfig;
+import org.apache.hadoop.hdds.scm.XceiverClientFactory;
+import org.apache.hadoop.hdds.scm.XceiverClientSpi;
+import org.apache.hadoop.hdds.scm.client.HddsClientUtils;
+import org.apache.hadoop.hdds.scm.container.common.helpers.StorageContainerException;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.hdds.security.exception.SCMSecurityException;
+import org.apache.hadoop.hdds.security.token.OzoneBlockTokenIdentifier;
+import org.apache.hadoop.io.retry.RetryPolicy;
+import org.apache.hadoop.ozone.common.Checksum;
+import org.apache.hadoop.ozone.common.ChecksumData;
+import org.apache.hadoop.ozone.common.OzoneChecksumException;
+import org.apache.hadoop.ozone.common.utils.BufferUtils;
+import org.apache.hadoop.security.token.Token;
+import org.apache.ratis.thirdparty.com.google.protobuf.ByteString;
+import org.apache.ratis.thirdparty.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.EOFException;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+
+import static org.apache.hadoop.hdds.client.ReplicationConfig.getLegacyFactor;
+
+/**
+ * An {@link java.io.InputStream} called from KeyInputStream to read a block from the
+ * container.
+ */
+public class StreamBlockInputStream extends BlockExtendedInputStream
+    implements Seekable, CanUnbuffer, ByteBufferReadable {
+  private static final Logger LOG =
+      LoggerFactory.getLogger(StreamBlockInputStream.class);
+  private final BlockID blockID;
+  private final long blockLength;
+  private final AtomicReference<Pipeline> pipelineRef =
+      new AtomicReference<>();
+  private final AtomicReference<Token<OzoneBlockTokenIdentifier>> tokenRef =
+      new AtomicReference<>();
+  private XceiverClientFactory xceiverClientFactory;
+  private XceiverClientSpi xceiverClient;
+
+  private List<Long> bufferOffsets;
+  private int bufferIndex;
+  private long blockPosition = -1;
+  private List<ByteBuffer> buffers;
+  // Checks if the StreamBlockInputStream has already read data from the container.
+  private boolean allocated = false;
+  private long bufferOffsetWrtBlockData;
+  private long buffersSize;
+  private static final int EOF = -1;
+  private final List<XceiverClientSpi.Validator> validators;
+  private final boolean verifyChecksum;
+  private final Function<BlockID, BlockLocationInfo> refreshFunction;
+  private final RetryPolicy retryPolicy;
+  private int retries;
+
+
+  public StreamBlockInputStream(
+      BlockID blockID, long length, Pipeline pipeline,
+      Token<OzoneBlockTokenIdentifier> token,
+      XceiverClientFactory xceiverClientFactory,
+      Function<BlockID, BlockLocationInfo> refreshFunction,
+      OzoneClientConfig config) throws IOException {
+    this.blockID = blockID;
+    LOG.debug("Initializing StreamBlockInputStream for block {}", blockID);
+    this.blockLength = length;
+    setPipeline(pipeline);
+    tokenRef.set(token);
+    this.xceiverClientFactory = xceiverClientFactory;
+    this.validators = ContainerProtocolCalls.toValidatorList(
+        (request, response) -> validateBlock(response));
+    this.verifyChecksum = config.isChecksumVerify();
+    this.refreshFunction = refreshFunction;
+    this.retryPolicy =
+        HddsClientUtils.createRetryPolicy(config.getMaxReadRetryCount(),
+            TimeUnit.SECONDS.toMillis(config.getReadRetryInterval()));
+
+  }
+
+
+  public BlockID getBlockID() {
+    return blockID;
+  }
+
+  public long getLength() {
+    return blockLength;
+  }
+
+  @Override
+  public synchronized long getPos() {
+    if (blockLength == 0) {
+      return 0;
+    }
+    if (blockPosition >= 0) {
+      return blockPosition;
+    }
+
+    if (buffersHaveData()) {
+      // BufferOffset w.r.t to BlockData + BufferOffset w.r.t buffers +
+      // Position of current Buffer
+      return bufferOffsetWrtBlockData + bufferOffsets.get(bufferIndex) +
+          buffers.get(bufferIndex).position();
+    }
+    if (allocated && !dataRemainingInBlock()) {
+      Preconditions.checkState(
+          bufferOffsetWrtBlockData + buffersSize == blockLength,
+          "EOF detected but not at the last byte of the chunk");
+      return blockLength;
+    }
+    if (buffersAllocated()) {
+      return bufferOffsetWrtBlockData + buffersSize;
+    }
+    return 0;
+  }
+
+  @Override
+  public synchronized int read() throws IOException {
+    int dataout = EOF;
+    int len = 1;
+    int available;
+    while (len > 0) {
+      try {
+        acquireClient();
+        available = prepareRead(1);
+        retries = 0;
+      } catch (SCMSecurityException ex) {
+        throw ex;
+      } catch (StorageContainerException e) {
+        handleStorageContainerException(e);
+        continue;
+      } catch (IOException ioe) {
+        handleIOException(ioe);
+        continue;
+      }
+      if (available == EOF) {
+        // There is no more data in the chunk stream. The buffers should have
+        // been released by now
+        Preconditions.checkState(buffers == null);
+      } else {
+        dataout = Byte.toUnsignedInt(buffers.get(bufferIndex).get());
+      }
+
+      len -= available;
+      if (bufferEOF()) {
+        releaseBuffers(bufferIndex);
+      }
+    }
+
+
+    return dataout;
+
+
+  }
+
+  @Override
+  public synchronized int read(byte[] b, int off, int len) throws IOException {
+    // According to the JavaDocs for InputStream, it is recommended that
+    // subclasses provide an override of bulk read if possible for performance
+    // reasons.  In addition to performance, we need to do it for correctness
+    // reasons.  The Ozone REST service uses PipedInputStream and
+    // PipedOutputStream to relay HTTP response data between a Jersey thread and
+    // a Netty thread.  It turns out that PipedInputStream/PipedOutputStream
+    // have a subtle dependency (bug?) on the wrapped stream providing separate
+    // implementations of single-byte read and bulk read.  Without this, get key
+    // responses might close the connection before writing all of the bytes
+    // advertised in the Content-Length.
+    if (b == null) {
+      throw new NullPointerException();
+    }
+    if (off < 0 || len < 0 || len > b.length - off) {
+      throw new IndexOutOfBoundsException();
+    }
+    if (len == 0) {
+      return 0;
+    }
+    int total = 0;
+    int available;
+    while (len > 0) {
+      try {
+        acquireClient();
+        available = prepareRead(len);
+        retries = 0;
+      } catch (SCMSecurityException ex) {
+        throw ex;
+      } catch (StorageContainerException e) {
+        handleStorageContainerException(e);
+        continue;
+      } catch (IOException ioe) {
+        handleIOException(ioe);
+        continue;
+      }
+      if (available == EOF) {
+        // There is no more data in the block stream. The buffers should have
+        // been released by now
+        Preconditions.checkState(buffers == null);
+        return total != 0 ? total : EOF;
+      }
+      buffers.get(bufferIndex).get(b, off + total, available);
+      len -= available;
+      total += available;
+
+      if (bufferEOF()) {
+        releaseBuffers(bufferIndex);
+      }
+    }
+    return total;
+
+  }
+
+  @Override
+  public synchronized int read(ByteBuffer byteBuffer) throws IOException {
+    if (byteBuffer == null) {
+      throw new NullPointerException();
+    }
+    int len = byteBuffer.remaining();
+    if (len == 0) {
+      return 0;
+    }
+    int total = 0;
+    int available;
+    while (len > 0) {
+      try {
+        acquireClient();
+        available = prepareRead(len);
+        retries = 0;
+      } catch (SCMSecurityException ex) {
+        throw ex;
+      } catch (StorageContainerException e) {
+        handleStorageContainerException(e);
+        continue;
+      } catch (IOException ioe) {
+        handleIOException(ioe);
+        continue;
+      }
+      if (available == EOF) {
+        // There is no more data in the block stream. The buffers should have
+        // been released by now
+        Preconditions.checkState(buffers == null);
+        return total != 0 ? total : EOF;
+      }
+      ByteBuffer readBuf = buffers.get(bufferIndex);
+      ByteBuffer tmpBuf = readBuf.duplicate();
+      tmpBuf.limit(tmpBuf.position() + available);
+      byteBuffer.put(tmpBuf);
+      readBuf.position(tmpBuf.position());
+
+      len -= available;
+      total += available;
+
+      if (bufferEOF()) {
+        releaseBuffers(bufferIndex);
+      }
+    }
+    return total;
+  }
+
+  @Override
+  protected int readWithStrategy(ByteReaderStrategy strategy) throws IOException {
+    throw new NotImplementedException("readWithStrategy is not implemented.");
+  }
+
+  @Override
+  public synchronized void seek(long pos) throws IOException {
+    if (pos == 0 && blockLength == 0) {
+      // It is possible for length and pos to be zero in which case
+      // seek should return instead of throwing exception
+      return;
+    }
+    if (pos < 0 || pos > blockLength) {
+      throw new EOFException("EOF encountered at pos: " + pos + " for block: " + blockID);
+    }
+
+    if (buffersHavePosition(pos)) {
+      // The bufferPosition is w.r.t the current block.
+      // Adjust the bufferIndex and position to the seeked position.
+      adjustBufferPosition(pos - bufferOffsetWrtBlockData);
+    } else {
+      blockPosition = pos;
+    }
+  }
+
+  @Override
+  public synchronized boolean seekToNewSource(long l) throws IOException {
+    return false;
+  }
+
+  @Override
+  public synchronized void unbuffer() {
+    blockPosition = getPos();
+    releaseClient();
+    releaseBuffers();
+  }
+
+  private void setPipeline(Pipeline pipeline) throws IOException {
+    if (pipeline == null) {
+      return;
+    }
+    long replicaIndexes = pipeline.getNodes().stream().mapToInt(pipeline::getReplicaIndex).distinct().count();
+
+    if (replicaIndexes > 1) {
+      throw new IOException(String.format("Pipeline: %s has nodes containing different replica indexes.",
+          pipeline));
+    }
+
+    // irrespective of the container state, we will always read via Standalone
+    // protocol.
+    boolean okForRead =
+        pipeline.getType() == HddsProtos.ReplicationType.STAND_ALONE
+            || pipeline.getType() == HddsProtos.ReplicationType.EC;
+    Pipeline readPipeline = okForRead ? pipeline : Pipeline.newBuilder(pipeline)
+        .setReplicationConfig(StandaloneReplicationConfig.getInstance(
+            getLegacyFactor(pipeline.getReplicationConfig())))
+        .build();
+    pipelineRef.set(readPipeline);
+  }
+
+  protected synchronized void checkOpen() throws IOException {
+    if (xceiverClientFactory == null) {
+      throw new IOException("BlockInputStream has been closed.");

Review Comment:
   done



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "chungen0126 (via GitHub)" <gi...@apache.org>.
chungen0126 commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1867484541


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/OzoneClientConfig.java:
##########
@@ -128,6 +128,13 @@ public enum ChecksumCombineMode {
       tags = ConfigTag.CLIENT)
   private long streamBufferMaxSize = 32 * 1024 * 1024;
 
+  @Config(key = "stream.readblock.enable",
+      defaultValue = "false",
+      type = ConfigType.BOOLEAN,
+      description = "Allow ReadBlock to stream all the readChunk in one request.",
+      tags = ConfigTag.CLIENT)
+  private boolean streamReadBlock = true;

Review Comment:
   done



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "ChenSammi (via GitHub)" <gi...@apache.org>.
ChenSammi commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-2516045713

   @chungen0126 , thanks for the quick patch updating.  I will finish the review today or tomorrow. 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "ChenSammi (via GitHub)" <gi...@apache.org>.
ChenSammi commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1867340399


##########
hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/common/interfaces/Handler.java:
##########
@@ -223,4 +225,9 @@ public void setClusterID(String clusterID) {
     this.clusterId = clusterID;
   }
 
+  public abstract ContainerCommandResponseProto streamDataReadOnly(

Review Comment:
   I would suggest change the function name from streamDataReadOnly to readBlock(). 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "chungen0126 (via GitHub)" <gi...@apache.org>.
chungen0126 commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1867504010


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -618,6 +624,69 @@ private void decreasePendingMetricsAndReleaseSemaphore() {
     return new XceiverClientReply(replyFuture);
   }
 
+  public XceiverClientReply sendCommandReadBlock(
+      ContainerCommandRequestProto request, DatanodeDetails dn)
+      throws IOException, InterruptedException {
+
+    CompletableFuture<ContainerCommandResponseProto> future =
+        new CompletableFuture<>();
+    ContainerCommandResponseProto.Builder response =
+        ContainerCommandResponseProto.newBuilder();
+    ContainerProtos.ReadBlockResponseProto.Builder readBlock =
+        ContainerProtos.ReadBlockResponseProto.newBuilder();
+    checkOpen(dn);
+    UUID dnID = dn.getUuid();
+    Type cmdType = request.getCmdType();
+    semaphore.acquire();
+    long requestTime = System.currentTimeMillis();
+    metrics.incrPendingContainerOpsMetrics(cmdType);
+
+    final StreamObserver<ContainerCommandRequestProto> requestObserver =
+        asyncStubs.get(dnID).withDeadlineAfter(timeout, TimeUnit.SECONDS)
+            .send(new StreamObserver<ContainerCommandResponseProto>() {
+              @Override
+              public void onNext(
+                  ContainerCommandResponseProto responseProto) {
+                if (responseProto.getResult() == Result.SUCCESS) {
+                  readBlock.addReadChunk(responseProto.getReadChunk());
+                } else {
+                  future.complete(
+                      ContainerCommandResponseProto.newBuilder(responseProto)
+                          .setCmdType(Type.ReadBlock).build());
+                }
+              }
+
+              @Override
+              public void onError(Throwable t) {
+                future.completeExceptionally(t);
+                metrics.decrPendingContainerOpsMetrics(cmdType);
+                metrics.addContainerOpsLatency(
+                    cmdType, System.currentTimeMillis() - requestTime);
+

Review Comment:
   Done



##########
hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/common/interfaces/ContainerDispatcher.java:
##########
@@ -93,4 +94,15 @@ default StateMachine.DataChannel getStreamDataChannel(
     throw new UnsupportedOperationException(
         "getStreamDataChannel not supported.");
   }
+
+  /**
+   * When reading data form client using stream, get StreamDataChannel.
+   */
+  default void streamDataReadOnly(
+       ContainerCommandRequestProto msg,
+       StreamObserver<ContainerCommandResponseProto> streamObserver,
+       DispatcherContext dispatcherContext) {
+    throw new UnsupportedOperationException(
+         "getStreamDataChannel not supported.");

Review Comment:
   Done



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r2487366995


##########
hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/common/transport/server/GrpcXceiverService.java:
##########


Review Comment:
   We probably should add a field for the block file here 
   - It is opened when constructing this StreamObserver object
   - It will be closed when setting isClosed to true.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-3481837517

   > ... and the server having to re-establish context for each one. ...
   
   No.  The context (such as the block file) should be saved with the  StreamObserver object; see https://github.com/apache/ozone/pull/6613#discussion_r2487366995


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r2487366995


##########
hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/common/transport/server/GrpcXceiverService.java:
##########


Review Comment:
   We probably should add a field for the block file here 
   - It will be opened at the first onNext() of this StreamObserver object
   - It will be closed when setting isClosed to true.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r2487366995


##########
hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/common/transport/server/GrpcXceiverService.java:
##########


Review Comment:
   We probably should a field for the block file here 
   - It is opened when constructing this StreamObserver object
   - It will be closed when setting isClosed to true.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-3482119540

   > I still have reservations that the chatty nature of the client having to request each piece of the block will add latency and overhead we don't need limiting any potential performance gains, especially with the size of reads I have seen when testing from the haoop shell and spark.
   
   This is for avoiding the deadlock but not the performance.
   
   > >  BTW, how large is enough? Would it slows down other operations for creating such a large handler pool?
   
   > I don't know, but I have seen HDFS work just fine with 32k threads active, provided the open file limits are high enough.
   
   So, we have to start 32k threads for each client?  It does not sound right. (Sorry that I missed your reply previously.)


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "chungen0126 (via GitHub)" <gi...@apache.org>.
chungen0126 commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r2202931907


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -631,6 +637,69 @@ private void decreasePendingMetricsAndReleaseSemaphore() {
     return new XceiverClientReply(replyFuture);
   }
 
+  public XceiverClientReply sendCommandReadBlock(
+      ContainerCommandRequestProto request, DatanodeDetails dn)
+      throws IOException, InterruptedException {
+
+    CompletableFuture<ContainerCommandResponseProto> future =
+        new CompletableFuture<>();
+    ContainerCommandResponseProto.Builder response =
+        ContainerCommandResponseProto.newBuilder();
+    ContainerProtos.ReadBlockResponseProto.Builder readBlock =
+        ContainerProtos.ReadBlockResponseProto.newBuilder();
+    checkOpen(dn);
+    DatanodeID dnId = dn.getID();
+    Type cmdType = request.getCmdType();
+    semaphore.acquire();
+    long requestTime = System.currentTimeMillis();
+    metrics.incrPendingContainerOpsMetrics(cmdType);
+
+    final StreamObserver<ContainerCommandRequestProto> requestObserver =
+        asyncStubs.get(dnId).withDeadlineAfter(timeout, TimeUnit.SECONDS)
+            .send(new StreamObserver<ContainerCommandResponseProto>() {
+              @Override
+              public void onNext(
+                  ContainerCommandResponseProto responseProto) {
+                if (responseProto.getResult() == Result.SUCCESS) {
+                  readBlock.addReadChunk(responseProto.getReadChunk());
+                } else {
+                  future.complete(
+                      ContainerCommandResponseProto.newBuilder(responseProto)

Review Comment:
   This is the place only for requests that are not success. We need to release semaphore at `onCompleted` method which would be called while the server side is completed.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "sodonnel (via GitHub)" <gi...@apache.org>.
sodonnel commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-3360724384

   Looking at this some more, I added in some debug messages to see what was getting called. The client does make a new call to the server for each "read", which is at the checksum boundary.
   
   On the server side, there is a some GRPC stuff getting setup with `onNext()` etc, which makes it look like a single call from the client will receive many chunks over the single call, but that isn't happening. Each 16kb read is a new call to the server.
   
   On the client side, in XceiverClientGrpc, we have a new sendReadBlock() method, and it uses a StreamObserver with `onNext` too, but that doesn't seem to get used.
   
   Surely what we need to do, is create some sort of GRPC stream which is returned to the StreamBlockInputStream, and it calls `onNext()` on it somehow until there is no more to return.
   
   However then what happens with a seek, if I read some of the block and then seek and then read some more. How is that supposed to work?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "chungen0126 (via GitHub)" <gi...@apache.org>.
chungen0126 commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r2558921152


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/StreamBlockInputStream.java:
##########
@@ -0,0 +1,451 @@
+/*
+ * 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 java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+import org.apache.commons.lang3.NotImplementedException;
+import org.apache.hadoop.fs.ByteBufferReadable;
+import org.apache.hadoop.fs.CanUnbuffer;
+import org.apache.hadoop.fs.FSExceptionMessages;
+import org.apache.hadoop.fs.Seekable;
+import org.apache.hadoop.hdds.client.BlockID;
+import org.apache.hadoop.hdds.protocol.DatanodeDetails;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadBlockResponseProto;
+import org.apache.hadoop.hdds.scm.OzoneClientConfig;
+import org.apache.hadoop.hdds.scm.StreamingReaderSpi;
+import org.apache.hadoop.hdds.scm.XceiverClientFactory;
+import org.apache.hadoop.hdds.scm.XceiverClientSpi;
+import org.apache.hadoop.hdds.scm.container.common.helpers.StorageContainerException;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.hdds.security.token.OzoneBlockTokenIdentifier;
+import org.apache.hadoop.io.retry.RetryPolicy;
+import org.apache.hadoop.ozone.common.Checksum;
+import org.apache.hadoop.ozone.common.ChecksumData;
+import org.apache.hadoop.ozone.common.OzoneChecksumException;
+import org.apache.hadoop.security.token.Token;
+import org.apache.ratis.thirdparty.io.grpc.StatusRuntimeException;
+import org.apache.ratis.thirdparty.io.grpc.stub.ClientCallStreamObserver;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * An {@link java.io.InputStream} called from KeyInputStream to read a block from the
+ * container.
+ */
+public class StreamBlockInputStream extends BlockExtendedInputStream
+    implements Seekable, CanUnbuffer, ByteBufferReadable {
+  private static final Logger LOG = LoggerFactory.getLogger(StreamBlockInputStream.class);
+  private static final int EOF = -1;
+  private static final Throwable CANCELLED_EXCEPTION = new Throwable("Cancelled by client");
+
+  private final BlockID blockID;
+  private final long blockLength;
+  private final AtomicReference<Pipeline> pipelineRef = new AtomicReference<>();
+  private final AtomicReference<Token<OzoneBlockTokenIdentifier>> tokenRef = new AtomicReference<>();
+  private XceiverClientFactory xceiverClientFactory;
+  private XceiverClientSpi xceiverClient;
+
+  private ByteBuffer buffer;
+  private long position = 0;
+  private boolean initialized = false;
+  private StreamingReader streamingReader;
+
+  private final boolean verifyChecksum;
+  private final Function<BlockID, BlockLocationInfo> refreshFunction;
+  private final RetryPolicy retryPolicy;
+  private int retries = 0;
+
+  public StreamBlockInputStream(
+      BlockID blockID, long length, Pipeline pipeline,
+      Token<OzoneBlockTokenIdentifier> token,
+      XceiverClientFactory xceiverClientFactory,
+      Function<BlockID, BlockLocationInfo> refreshFunction,
+      OzoneClientConfig config) throws IOException {
+    this.blockID = blockID;
+    this.blockLength = length;
+    pipelineRef.set(setPipeline(pipeline));
+    tokenRef.set(token);
+    this.xceiverClientFactory = xceiverClientFactory;
+    this.verifyChecksum = config.isChecksumVerify();
+    this.retryPolicy = getReadRetryPolicy(config);
+    this.refreshFunction = refreshFunction;
+  }
+
+  @Override
+  public BlockID getBlockID() {
+    return blockID;
+  }
+
+  @Override
+  public long getLength() {
+    return blockLength;
+  }
+
+  @Override
+  public synchronized long getPos() {
+    return position;
+  }
+
+  @Override
+  public synchronized int read() throws IOException {
+    checkOpen();
+    if (!dataAvailableToRead()) {
+      return EOF;
+    }
+    position++;
+    return buffer.get();
+  }
+
+  @Override
+  public synchronized int read(byte[] b, int off, int len) throws IOException {
+    ByteBuffer tmpBuffer = ByteBuffer.wrap(b, off, len);
+    return read(tmpBuffer);
+  }
+
+  @Override
+  public synchronized int read(ByteBuffer targetBuf) throws IOException {
+    checkOpen();
+    int read = 0;
+    while (targetBuf.hasRemaining()) {
+      if (!dataAvailableToRead()) {
+        break;
+      }
+      int toCopy = Math.min(buffer.remaining(), targetBuf.remaining());
+      ByteBuffer tmpBuf = buffer.duplicate();
+      tmpBuf.limit(tmpBuf.position() + toCopy);
+      targetBuf.put(tmpBuf);
+      buffer.position(tmpBuf.position());
+      position += toCopy;
+      read += toCopy;
+    }
+    return read > 0 ? read : EOF;
+  }
+
+  private boolean dataAvailableToRead() throws IOException {
+    if (position >= blockLength) {
+      return false;
+    }
+    initialize();
+    if (buffer == null || buffer.remaining() == 0) {
+      int loaded = fillBuffer();
+      return loaded != EOF;
+    }
+    return true;
+  }
+
+  @Override
+  protected int readWithStrategy(ByteReaderStrategy strategy) throws IOException {
+    throw new NotImplementedException("readWithStrategy is not implemented.");
+  }
+
+  @Override
+  public synchronized void seek(long pos) throws IOException {
+    checkOpen();
+    if (pos < 0) {
+      throw new IOException("Cannot seek to negative offset");
+    }
+    if (pos > blockLength) {
+      throw new IOException("Cannot seek after the end of the block");
+    }
+    if (pos == position) {
+      return;
+    }
+    closeStream();
+    position = pos;
+  }
+
+  @Override
+  // The seekable interface indicates that seekToNewSource should seek to a new source of the data,
+  // ie a different datanode. This is not supported for now.
+  public synchronized boolean seekToNewSource(long l) throws IOException {
+    return false;
+  }
+
+  @Override
+  public synchronized void unbuffer() {
+    releaseClient();
+  }
+
+  private void closeStream() {
+    if (streamingReader != null) {
+      streamingReader.cancel();
+      streamingReader = null;
+    }
+    initialized = false;
+    buffer = null;
+  }
+
+  protected synchronized void checkOpen() throws IOException {
+    if (xceiverClientFactory == null) {
+      throw new IOException(FSExceptionMessages.STREAM_IS_CLOSED + " Block: " + blockID);
+    }
+  }
+
+  protected synchronized void acquireClient() throws IOException {
+    checkOpen();
+    if (xceiverClient == null) {
+      final Pipeline pipeline = pipelineRef.get();
+      try {
+        xceiverClient = xceiverClientFactory.acquireClientForReadData(pipeline);
+      } catch (IOException ioe) {
+        LOG.warn("Failed to acquire client for pipeline {}, block {}", pipeline, blockID);
+        throw ioe;
+      }
+    }
+  }
+
+  private void initialize() throws IOException {
+    if (initialized) {
+      return;
+    }
+    while (true) {
+      try {
+        acquireClient();
+        streamingReader = new StreamingReader();
+        ContainerProtocolCalls.readBlock(xceiverClient, position, blockID, tokenRef.get(),
+            pipelineRef.get().getReplicaIndexes(), streamingReader);
+        initialized = true;
+        return;
+      } catch (InterruptedException ie) {
+        Thread.currentThread().interrupt();
+        handleExceptions(new IOException("Interrupted", ie));
+      } catch (IOException ioe) {
+        handleExceptions(ioe);
+      }
+    }
+  }
+
+  private void handleExceptions(IOException cause) throws IOException {
+    if (cause instanceof StorageContainerException || isConnectivityIssue(cause)) {
+      if (shouldRetryRead(cause, retryPolicy, retries++)) {
+        releaseClient();
+        refreshBlockInfo(cause);
+        LOG.warn("Refreshing block data to read block {} due to {}", blockID, cause.getMessage());
+      } else {
+        throw cause;
+      }
+    } else {
+      throw cause;
+    }
+  }
+
+  private int fillBuffer() throws IOException {
+    if (!streamingReader.hasNext()) {
+      return EOF;
+    }
+    buffer = streamingReader.readNext();
+    return buffer == null ? EOF : buffer.limit();
+  }
+
+  protected synchronized void releaseClient() {
+    if (xceiverClientFactory != null && xceiverClient != null) {
+      closeStream();
+      xceiverClientFactory.releaseClientForReadData(xceiverClient, false);
+      xceiverClient = null;
+    }
+  }
+
+  @Override
+  public synchronized void close() throws IOException {
+    releaseClient();
+    xceiverClientFactory = null;
+  }
+
+  private void refreshBlockInfo(IOException cause) throws IOException {
+    refreshBlockInfo(cause, blockID, pipelineRef, tokenRef, refreshFunction);
+  }
+
+  private synchronized void releaseStreamResources() {
+    if (xceiverClient != null) {
+      xceiverClient.completeStreamRead();
+    }
+  }
+
+  /**
+   * Implementation of a StreamObserver used to received and buffer streaming GRPC reads.
+   */
+  public class StreamingReader implements StreamingReaderSpi {
+
+    private final BlockingQueue<ContainerProtos.ReadBlockResponseProto> responseQueue = new LinkedBlockingQueue<>(1);
+    private final AtomicBoolean completed = new AtomicBoolean(false);
+    private final AtomicBoolean failed = new AtomicBoolean(false);
+    private final AtomicBoolean semaphoreReleased = new AtomicBoolean(false);
+    private final AtomicReference<Throwable> error = new AtomicReference<>();
+    private volatile ClientCallStreamObserver<ContainerProtos.ContainerCommandRequestProto> requestObserver;
+    private volatile DatanodeDetails streamingDatanodeDetails;
+
+    public boolean hasNext() {
+      return !responseQueue.isEmpty() || !completed.get();
+    }
+
+    public ByteBuffer readNext() throws IOException {
+      if (failed.get()) {
+        Throwable cause = error.get();
+        throw new IOException("Streaming read failed", cause);
+      }
+
+      if (completed.get() && responseQueue.isEmpty()) {
+        return null; // Stream ended
+      }
+
+      ReadBlockResponseProto readBlock;
+      try {
+        readBlock = responseQueue.poll(30, TimeUnit.SECONDS);
+      } catch (InterruptedException e) {
+        Thread.currentThread().interrupt();
+        throw new IOException("Interrupted while waiting for response", e);
+      }
+      if (readBlock == null) {
+        if (failed.get()) {
+          Throwable cause = error.get();
+          throw new IOException("Streaming read failed", cause);
+        } else if (completed.get()) {
+          return null; // Stream ended
+        } else {
+          throw new IOException("Timed out waiting for response");
+        }
+      }
+      // The server always returns data starting from the last checksum boundary. Therefore if the reader position is
+      // ahead of the position we received from the server, we need to adjust the buffer position accordingly.
+      // If the reader position is behind
+      ByteBuffer buf = readBlock.getData().asReadOnlyByteBuffer();
+      long blockOffset = readBlock.getOffset();
+      long pos = getPos();
+      if (pos < blockOffset) {
+        // This should not happen, and if it does, we have a bug.
+        throw new IOException("Received data out of order. Position is " + pos + " but received data at "
+            + blockOffset);
+      }
+      if (pos > readBlock.getOffset()) {
+        int offset = (int)(pos - readBlock.getOffset());
+        buf.position(offset);
+      }
+      return buf;
+    }
+
+    private void releaseResources() {
+      boolean wasNotYetComplete = semaphoreReleased.getAndSet(true);

Review Comment:
   I may have misunderstood, but since `getAndSet(true)` returns the previous value, wouldn't wasNotYetComplete be false the first time it's called? This could cause releaseStreamResources() to be skipped the first time it's called.
   ```suggestion
         boolean wasNotYetComplete = !semaphoreReleased.getAndSet(true);
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "chungen0126 (via GitHub)" <gi...@apache.org>.
chungen0126 commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-3574307152

   @sodonnel @szetszwo Here's a commit that implements client-side gRPC flow control: https://github.com/chungen0126/ozone/commit/73de01ac69a43ea7ab4b1c35451f5872b25f71a8
   
   This effectively prevents blocking the gRPC event loop thread. Since it's just a few lines of code, could you please take a look? If you agree with the change, I think it would be better to include it in this PR.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "yandrey321 (via GitHub)" <gi...@apache.org>.
yandrey321 commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r2547380335


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -504,6 +515,62 @@ private XceiverClientReply sendCommandWithRetry(
     }
   }
 
+  /**
+   * Starts a streaming read operation, intended to read entire blocks from the datanodes. This method expects a
+   * {@link StreamingReaderSpi} to be passed in, which will be used to receive the streamed data from the datanode.
+   * Upon successfully starting the streaming read, a {@link StreamingReadResponse} is set into the pass StreamObserver,
+   * which contains information about the datanode used for the read, and the request observer that can be used to
+   * manage the stream (e.g., to cancel it if needed). A semaphore is acquired to limit the number of concurrent
+   * streaming reads so upon successful return of this method, the caller must ensure to call
+   * {@link #completeStreamRead()} to release the semaphore once the streaming read is complete.
+   * @param request The container command request to initiate the streaming read.
+   * @param streamObserver The observer that will handle the streamed responses.=
+   * @throws IOException
+   * @throws InterruptedException
+   */
+  @Override
+  public void streamRead(ContainerCommandRequestProto request,
+      StreamingReaderSpi streamObserver) throws IOException, InterruptedException {
+    List<DatanodeDetails> datanodeList = sortDatanodes(request);
+    IOException lastException = null;
+    for (DatanodeDetails dn : datanodeList) {
+      try {
+        checkOpen(dn);
+        semaphore.acquire();
+        XceiverClientProtocolServiceStub stub = asyncStubs.get(dn.getID());
+        if (stub == null) {
+          throw new IOException("Failed to get gRPC stub for DataNode: " + dn);
+        }
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("Executing command {} on datanode {}", processForDebug(request), dn);
+        }
+        stub.withDeadlineAfter(timeout, TimeUnit.SECONDS)
+            .streamBlock(request, streamObserver);
+        streamObserver.setStreamingDatanode(dn);
+        return;

Review Comment:
   do we do that only for one node?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo closed pull request #6613: HDDS-10338. Implement a Client Datanode API to stream a block
URL: https://github.com/apache/ozone/pull/6613


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "sodonnel (via GitHub)" <gi...@apache.org>.
sodonnel commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r2481109699


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -504,6 +516,65 @@ private XceiverClientReply sendCommandWithRetry(
     }
   }
 
+  /**
+   * Starts a streaming read operation, intended to read entire blocks from the datanodes. This method expects a
+   * {@link StreamObserver} to be passed in, which will be used to receive the streamed data from the datanode.
+   * Upon successfully starting the streaming read, a {@link StreamingReadResponse} is returned, which contains
+   * information about the datanode used for the read, and the request observer that can be used to manage the stream
+   * (e.g., to cancel it if needed). A semaphore is acquired to limit the number of concurrent streaming reads so upon
+   * successful return of this method, the caller must ensure to call {@link #completeStreamRead(StreamingReadResponse)}
+   * to release the semaphore once the streaming read is complete.
+   * @param request The container command request to initiate the streaming read.
+   * @param streamObserver The observer that will handle the streamed responses.
+   * @return A {@link StreamingReadResponse} containing details of the streaming read operation.
+   * @throws IOException
+   * @throws InterruptedException
+   */
+  @Override
+  public StreamingReadResponse streamRead(ContainerCommandRequestProto request,
+      StreamObserver<ContainerCommandResponseProto> streamObserver) throws IOException, InterruptedException {
+    List<DatanodeDetails> datanodeList = sortDatanodes(request);
+    IOException lastException = null;
+    for (DatanodeDetails dn : datanodeList) {
+      try {
+        checkOpen(dn);
+        semaphore.acquire();
+        XceiverClientProtocolServiceStub stub = asyncStubs.get(dn.getID());
+        if (stub == null) {
+          throw new IOException("Failed to get gRPC stub for DataNode: " + dn);
+        }
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("Executing command {} on datanode {}", processForDebug(request), dn);
+        }
+        StreamObserver<ContainerCommandRequestProto> requestObserver = stub
+            .withDeadlineAfter(timeout, TimeUnit.SECONDS)
+            .send(streamObserver);
+        requestObserver.onNext(request);
+        requestObserver.onCompleted();
+        return new StreamingReadResponse(dn, (ClientCallStreamObserver<ContainerCommandRequestProto>) requestObserver);

Review Comment:
   >  The server should open the file in the first gRPC onNext() call and close it in onComplete()/onError().
   
   How is this supposed to work? The server opens the file in the context of the handler thread, which is has to release after onNext() and hence close the open file down, along with all its offset information and checksum object is deserialized from rocksDB.
   
   > Increasing handler pool for performance makes sense. However, it is not a good solution to avoid deadlocks.
   
   The handler pool needs to be sized for the typical workload the server is supposed to handle. If our workload is large reads, by context switching and chunking things up, the re-initialization of the thread each time is going to require net more work as it has to repeat the setup for each call.
   
   > BTW, how large is enough? Would it slows down other operations for creating such a large handler pool?
   
   I don't know, but I have seen HDFS work just fine with 32k threads active, provided the open file limits are high enough.
   
   The only way to know for sure is to try it and see, and iterate on the approach as problems are identified.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r2457061051


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -504,6 +516,65 @@ private XceiverClientReply sendCommandWithRetry(
     }
   }
 
+  /**
+   * Starts a streaming read operation, intended to read entire blocks from the datanodes. This method expects a
+   * {@link StreamObserver} to be passed in, which will be used to receive the streamed data from the datanode.
+   * Upon successfully starting the streaming read, a {@link StreamingReadResponse} is returned, which contains
+   * information about the datanode used for the read, and the request observer that can be used to manage the stream
+   * (e.g., to cancel it if needed). A semaphore is acquired to limit the number of concurrent streaming reads so upon
+   * successful return of this method, the caller must ensure to call {@link #completeStreamRead(StreamingReadResponse)}
+   * to release the semaphore once the streaming read is complete.
+   * @param request The container command request to initiate the streaming read.
+   * @param streamObserver The observer that will handle the streamed responses.
+   * @return A {@link StreamingReadResponse} containing details of the streaming read operation.
+   * @throws IOException
+   * @throws InterruptedException
+   */
+  @Override
+  public StreamingReadResponse streamRead(ContainerCommandRequestProto request,
+      StreamObserver<ContainerCommandResponseProto> streamObserver) throws IOException, InterruptedException {
+    List<DatanodeDetails> datanodeList = sortDatanodes(request);
+    IOException lastException = null;
+    for (DatanodeDetails dn : datanodeList) {
+      try {
+        checkOpen(dn);
+        semaphore.acquire();
+        XceiverClientProtocolServiceStub stub = asyncStubs.get(dn.getID());
+        if (stub == null) {
+          throw new IOException("Failed to get gRPC stub for DataNode: " + dn);
+        }
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("Executing command {} on datanode {}", processForDebug(request), dn);
+        }
+        StreamObserver<ContainerCommandRequestProto> requestObserver = stub
+            .withDeadlineAfter(timeout, TimeUnit.SECONDS)
+            .send(streamObserver);
+        requestObserver.onNext(request);
+        requestObserver.onCompleted();
+        return new StreamingReadResponse(dn, (ClientCallStreamObserver<ContainerCommandRequestProto>) requestObserver);

Review Comment:
   After `onCompleted()` here, it is useless to call `onError()` later on if there is an error.
   
   BTW, using `cancel()` to handle error seems inappropriate; see below:
   <img width="556" height="969" alt="image" src="https://github.com/user-attachments/assets/ce32814b-9b67-41a4-b692-24deef8b7d6d" />
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-3564031787

   @sodonnel , filed [HDDS-13974](https://issues.apache.org/jira/browse/HDDS-13974)
   "Use the same RPC steam for reading the same block".


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "swamirishi (via GitHub)" <gi...@apache.org>.
swamirishi commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1803840274


##########
hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/keyvalue/KeyValueHandler.java:
##########
@@ -1329,6 +1333,109 @@ public void deleteUnreferenced(Container container, long localID)
     }
   }
 
+  @Override
+  public ContainerCommandResponseProto streamDataReadOnly(
+      ContainerCommandRequestProto request, KeyValueContainer kvContainer,
+      DispatcherContext dispatcherContext,
+      StreamObserver<ContainerCommandResponseProto> streamObserver) {
+    ContainerCommandResponseProto responseProto = null;
+    try {
+      if (!request.hasReadBlock()) {
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("Malformed Read Block request. trace ID: {}",
+              request.getTraceID());
+        }
+        return malformedRequest(request);
+      }
+      ReadBlockRequestProto readBlock = request.getReadBlock();
+
+      BlockID blockID = BlockID.getFromProtobuf(
+          readBlock.getBlockID());
+      // This is a new api the block should always be checked.
+      BlockUtils.verifyReplicaIdx(kvContainer, blockID);

Review Comment:
   What would happen if the replicaIndex of the block changes because of containerBalancer running on the background. We would need to take some kind of a lock here to ensure the block data does change after this point.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "kerneltime (via GitHub)" <gi...@apache.org>.
kerneltime commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1802072637


##########
hadoop-hdds/client/src/test/java/org/apache/hadoop/hdds/scm/storage/TestStreamBlockInput.java:
##########
@@ -0,0 +1,259 @@
+/*
+ * 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 java.io.EOFException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Random;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.Function;
+
+import com.google.common.primitives.Bytes;
+import org.apache.hadoop.hdds.client.BlockID;
+import org.apache.hadoop.hdds.client.ContainerBlockID;
+import org.apache.hadoop.hdds.conf.OzoneConfiguration;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ChecksumType;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ChunkInfo;
+import org.apache.hadoop.hdds.scm.OzoneClientConfig;
+import org.apache.hadoop.hdds.scm.pipeline.MockPipeline;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.ozone.common.Checksum;
+
+import org.apache.ratis.thirdparty.com.google.protobuf.ByteString;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.Mockito.mock;
+
+/**
+ * Tests for {@link TestStreamBlockInput}'s functionality.
+ */
+public class TestStreamBlockInput {
+  private int blockSize;
+  private static final int CHUNK_SIZE = 100;
+  private static final int BYTES_PER_CHECKSUM = 20;
+  private static final Random RANDOM = new Random();
+  private static final AtomicLong CONTAINER_ID = new AtomicLong();
+  private DummyStreamBlockInput blockStream;
+  private byte[] blockData;
+  private List<ChunkInfo> chunks;
+  private Map<String, byte[]> chunkDataMap;
+  private Checksum checksum;
+  private Function<BlockID, BlockLocationInfo> refreshFunction;
+  private BlockID blockID;
+  private static final String CHUNK_NAME = "chunk-";
+  private OzoneConfiguration conf = new OzoneConfiguration();
+
+
+  @BeforeEach
+  public void setup() throws Exception {
+    OzoneClientConfig clientConfig = conf.getObject(OzoneClientConfig.class);
+    clientConfig.setStreamReadBlock(true);
+    refreshFunction = mock(Function.class);
+    blockID = new BlockID(new ContainerBlockID(1, 1));
+    checksum = new Checksum(ChecksumType.CRC32, BYTES_PER_CHECKSUM);
+    createChunkList(5);
+
+    Pipeline pipeline = MockPipeline.createSingleNodePipeline();
+    blockStream = new DummyStreamBlockInput(blockID, blockSize, pipeline,
+        null, null, refreshFunction, clientConfig, chunks, chunkDataMap);
+  }
+
+  /**
+   * Create a mock list of chunks. The first n-1 chunks of length CHUNK_SIZE
+   * and the last chunk with length CHUNK_SIZE/2.
+   */
+  private void createChunkList(int numChunks)
+      throws Exception {
+
+    chunks = new ArrayList<>(numChunks);
+    chunkDataMap = new HashMap<>();
+    blockData = new byte[0];
+    int i, chunkLen;
+    byte[] byteData;
+    String chunkName;
+
+    for (i = 0; i < numChunks; i++) {
+      chunkName = CHUNK_NAME + i;
+      chunkLen = CHUNK_SIZE;
+      if (i == numChunks - 1) {
+        chunkLen = CHUNK_SIZE / 2;
+      }
+      byteData = generateRandomData(chunkLen);
+      ChunkInfo chunkInfo = ChunkInfo.newBuilder()
+          .setChunkName(chunkName)
+          .setOffset(0)
+          .setLen(chunkLen)
+          .setChecksumData(checksum.computeChecksum(
+              byteData, 0, chunkLen).getProtoBufMessage())
+          .build();
+
+      chunkDataMap.put(chunkName, byteData);
+      chunks.add(chunkInfo);
+
+      blockSize += chunkLen;
+      blockData = Bytes.concat(blockData, byteData);
+    }
+  }
+
+  static byte[] generateRandomData(int length) {
+    byte[] bytes = new byte[length];
+    RANDOM.nextBytes(bytes);
+    return bytes;
+  }
+
+  /**
+   * Match readData with the chunkData byte-wise.
+   * @param readData Data read through ChunkInputStream
+   * @param inputDataStartIndex first index (inclusive) in chunkData to compare
+   *                            with read data
+   * @param length the number of bytes of data to match starting from
+   *               inputDataStartIndex
+   */
+  private void matchWithInputData(byte[] readData, int inputDataStartIndex,
+                                  int length) {
+    for (int i = inputDataStartIndex; i < inputDataStartIndex + length; i++) {
+      assertEquals(blockData[i], readData[i - inputDataStartIndex], "i: " + i);
+    }
+  }
+
+  private void matchWithInputData(List<ByteString> byteStrings,
+                                  int inputDataStartIndex, int length) {
+    int offset = inputDataStartIndex;
+    int totalBufferLen = 0;
+    for (ByteString byteString : byteStrings) {
+      int bufferLen = byteString.size();
+      matchWithInputData(byteString.toByteArray(), offset, bufferLen);
+      offset += bufferLen;
+      totalBufferLen += bufferLen;
+    }
+    assertEquals(length, totalBufferLen);
+  }
+
+  /**
+   * Seek to a position and verify through getPos().
+   */
+  private void seekAndVerify(int pos) throws Exception {
+    blockStream.seek(pos);
+    assertEquals(pos, blockStream.getPos(),
+        "Current position of buffer does not match with the sought position");
+  }
+
+  @Test
+  public void testFullChunkRead() throws Exception {
+    byte[] b = new byte[blockSize];
+    blockStream.read(b, 0, blockSize);
+    matchWithInputData(b, 0, blockSize);
+  }
+
+  @Test
+  public void testPartialChunkRead() throws Exception {
+    int len = blockSize / 2;
+    byte[] b = new byte[len];
+
+    blockStream.read(b, 0, len);

Review Comment:
   This applies to all the places in the code; validate the returned number of bytes read with the expected number of bytes read, and drop the find bugs exception added. 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "kerneltime (via GitHub)" <gi...@apache.org>.
kerneltime commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1802076166


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -108,12 +110,12 @@ public class XceiverClientGrpc extends XceiverClientSpi {
    * Constructs a client that can communicate with the Container framework on
    * data nodes via DatanodeClientProtocol.
    *
-   * @param pipeline - Pipeline that defines the machines.
-   * @param config   -- Ozone Config
+   * @param pipeline     - Pipeline that defines the machines.
+   * @param config       -- Ozone Config
    * @param trustManager - a {@link ClientTrustManager} with proper CA handling.
    */
   public XceiverClientGrpc(Pipeline pipeline, ConfigurationSource config,
-      ClientTrustManager trustManager) {
+                           ClientTrustManager trustManager) {

Review Comment:
   Please update your editor so that formatting changes are not made for lines you are not updating. 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "chungen0126 (via GitHub)" <gi...@apache.org>.
chungen0126 commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1806537264


##########
hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/keyvalue/KeyValueHandler.java:
##########
@@ -1329,6 +1333,109 @@ public void deleteUnreferenced(Container container, long localID)
     }
   }
 
+  @Override
+  public ContainerCommandResponseProto streamDataReadOnly(
+      ContainerCommandRequestProto request, KeyValueContainer kvContainer,
+      DispatcherContext dispatcherContext,
+      StreamObserver<ContainerCommandResponseProto> streamObserver) {
+    ContainerCommandResponseProto responseProto = null;
+    try {
+      if (!request.hasReadBlock()) {
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("Malformed Read Block request. trace ID: {}",
+              request.getTraceID());
+        }
+        return malformedRequest(request);
+      }
+      ReadBlockRequestProto readBlock = request.getReadBlock();
+
+      BlockID blockID = BlockID.getFromProtobuf(
+          readBlock.getBlockID());
+      // This is a new api the block should always be checked.
+      BlockUtils.verifyReplicaIdx(kvContainer, blockID);

Review Comment:
   > or we would need to validate the replicaIndex and bcsID is the same on every readChunk call on the file(Basically move this check inside the loop). Take a look at [HDDS-10983](https://issues.apache.org/jira/browse/HDDS-10983) for context.
   
   @swamirishi thanks for your review.
   I'm still confused of the problem. We validate the replicaIndex and bcsID at the start of the readBlock, and all the readChunks belong to the same block. Why do we need to validate again fot every readChunk. If the replicaIndex of the block changes during the readBlock, a mismatch can still happen after the validation and before readChunk.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "ChenSammi (via GitHub)" <gi...@apache.org>.
ChenSammi commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1867007170


##########
hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/keyvalue/KeyValueHandler.java:
##########
@@ -1345,6 +1349,114 @@ public void deleteUnreferenced(Container container, long localID)
     }
   }
 
+  @Override
+  public ContainerCommandResponseProto streamDataReadOnly(
+      ContainerCommandRequestProto request, KeyValueContainer kvContainer,
+      DispatcherContext dispatcherContext,
+      StreamObserver<ContainerCommandResponseProto> streamObserver) {
+    ContainerCommandResponseProto responseProto = null;
+    try {
+      if (!request.hasReadBlock()) {
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("Malformed Read Block request. trace ID: {}",
+              request.getTraceID());
+        }
+        return malformedRequest(request);
+      }

Review Comment:
   Please move the above if (!request.hasReadBlock()) logic out of try scope. 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "ChenSammi (via GitHub)" <gi...@apache.org>.
ChenSammi commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1867357659


##########
hadoop-hdds/container-service/src/test/java/org/apache/hadoop/ozone/container/keyvalue/TestKeyValueHandler.java:
##########
@@ -458,4 +485,77 @@ private static ContainerCommandRequestProto createContainerRequest(
         .setContainerID(containerID).setPipelineID(UUID.randomUUID().toString())
         .build();
   }
+
+  @Test
+  public void testReadBlock() throws IOException {

Review Comment:
   Could you add add an end to end case, to test read an empty file with an empty block? 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "ChenSammi (via GitHub)" <gi...@apache.org>.
ChenSammi commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1867357659


##########
hadoop-hdds/container-service/src/test/java/org/apache/hadoop/ozone/container/keyvalue/TestKeyValueHandler.java:
##########
@@ -458,4 +485,77 @@ private static ContainerCommandRequestProto createContainerRequest(
         .setContainerID(containerID).setPipelineID(UUID.randomUUID().toString())
         .build();
   }
+
+  @Test
+  public void testReadBlock() throws IOException {

Review Comment:
   Could you add add an end to end case, to test read an empty block? 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "ChenSammi (via GitHub)" <gi...@apache.org>.
ChenSammi commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1867337666


##########
hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/common/interfaces/ContainerDispatcher.java:
##########
@@ -93,4 +94,15 @@ default StateMachine.DataChannel getStreamDataChannel(
     throw new UnsupportedOperationException(
         "getStreamDataChannel not supported.");
   }
+
+  /**
+   * When reading data form client using stream, get StreamDataChannel.

Review Comment:
   This function doesn't return StreamDataChannel.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "chungen0126 (via GitHub)" <gi...@apache.org>.
chungen0126 commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1867503553


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/StreamBlockInput.java:
##########
@@ -0,0 +1,760 @@
+/*
+ * 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 com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
+import org.apache.commons.lang3.NotImplementedException;
+import org.apache.hadoop.fs.ByteBufferReadable;
+import org.apache.hadoop.fs.CanUnbuffer;
+import org.apache.hadoop.fs.Seekable;
+import org.apache.hadoop.hdds.client.BlockID;
+import org.apache.hadoop.hdds.client.StandaloneReplicationConfig;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadChunkResponseProto;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadBlockResponseProto;
+import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
+import org.apache.hadoop.hdds.scm.OzoneClientConfig;
+import org.apache.hadoop.hdds.scm.XceiverClientFactory;
+import org.apache.hadoop.hdds.scm.XceiverClientSpi;
+import org.apache.hadoop.hdds.scm.client.HddsClientUtils;
+import org.apache.hadoop.hdds.scm.container.common.helpers.StorageContainerException;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.hdds.security.exception.SCMSecurityException;
+import org.apache.hadoop.hdds.security.token.OzoneBlockTokenIdentifier;
+import org.apache.hadoop.io.retry.RetryPolicy;
+import org.apache.hadoop.ozone.common.Checksum;
+import org.apache.hadoop.ozone.common.ChecksumData;
+import org.apache.hadoop.ozone.common.OzoneChecksumException;
+import org.apache.hadoop.ozone.common.utils.BufferUtils;
+import org.apache.hadoop.security.token.Token;
+import org.apache.ratis.thirdparty.com.google.protobuf.ByteString;
+import org.apache.ratis.thirdparty.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.EOFException;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+
+import static org.apache.hadoop.hdds.client.ReplicationConfig.getLegacyFactor;
+
+/**
+ * An {@link java.io.InputStream} called from KeyInputStream to read a block from the
+ * container.
+ */
+public class StreamBlockInput extends BlockExtendedInputStream
+    implements Seekable, CanUnbuffer, ByteBufferReadable {
+  private static final Logger LOG =
+      LoggerFactory.getLogger(StreamBlockInput.class);
+  private final BlockID blockID;
+  private final long blockLength;
+  private final AtomicReference<Pipeline> pipelineRef =
+      new AtomicReference<>();
+  private final AtomicReference<Token<OzoneBlockTokenIdentifier>> tokenRef =
+      new AtomicReference<>();
+  private XceiverClientFactory xceiverClientFactory;
+  private XceiverClientSpi xceiverClient;
+
+  private List<Long> bufferoffsets;

Review Comment:
   done



##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/StreamBlockInput.java:
##########
@@ -0,0 +1,760 @@
+/*
+ * 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 com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
+import org.apache.commons.lang3.NotImplementedException;
+import org.apache.hadoop.fs.ByteBufferReadable;
+import org.apache.hadoop.fs.CanUnbuffer;
+import org.apache.hadoop.fs.Seekable;
+import org.apache.hadoop.hdds.client.BlockID;
+import org.apache.hadoop.hdds.client.StandaloneReplicationConfig;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadChunkResponseProto;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadBlockResponseProto;
+import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
+import org.apache.hadoop.hdds.scm.OzoneClientConfig;
+import org.apache.hadoop.hdds.scm.XceiverClientFactory;
+import org.apache.hadoop.hdds.scm.XceiverClientSpi;
+import org.apache.hadoop.hdds.scm.client.HddsClientUtils;
+import org.apache.hadoop.hdds.scm.container.common.helpers.StorageContainerException;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.hdds.security.exception.SCMSecurityException;
+import org.apache.hadoop.hdds.security.token.OzoneBlockTokenIdentifier;
+import org.apache.hadoop.io.retry.RetryPolicy;
+import org.apache.hadoop.ozone.common.Checksum;
+import org.apache.hadoop.ozone.common.ChecksumData;
+import org.apache.hadoop.ozone.common.OzoneChecksumException;
+import org.apache.hadoop.ozone.common.utils.BufferUtils;
+import org.apache.hadoop.security.token.Token;
+import org.apache.ratis.thirdparty.com.google.protobuf.ByteString;
+import org.apache.ratis.thirdparty.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.EOFException;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+
+import static org.apache.hadoop.hdds.client.ReplicationConfig.getLegacyFactor;
+
+/**
+ * An {@link java.io.InputStream} called from KeyInputStream to read a block from the
+ * container.
+ */
+public class StreamBlockInput extends BlockExtendedInputStream

Review Comment:
   done



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "chungen0126 (via GitHub)" <gi...@apache.org>.
chungen0126 commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1853597392


##########
hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/keyvalue/KeyValueHandler.java:
##########
@@ -1329,6 +1333,109 @@ public void deleteUnreferenced(Container container, long localID)
     }
   }
 
+  @Override
+  public ContainerCommandResponseProto streamDataReadOnly(
+      ContainerCommandRequestProto request, KeyValueContainer kvContainer,
+      DispatcherContext dispatcherContext,
+      StreamObserver<ContainerCommandResponseProto> streamObserver) {
+    ContainerCommandResponseProto responseProto = null;
+    try {
+      if (!request.hasReadBlock()) {
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("Malformed Read Block request. trace ID: {}",
+              request.getTraceID());
+        }
+        return malformedRequest(request);
+      }
+      ReadBlockRequestProto readBlock = request.getReadBlock();
+
+      BlockID blockID = BlockID.getFromProtobuf(
+          readBlock.getBlockID());
+      // This is a new api the block should always be checked.
+      BlockUtils.verifyReplicaIdx(kvContainer, blockID);

Review Comment:
   Done for adding replica index validation.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "ptlrs (via GitHub)" <gi...@apache.org>.
ptlrs commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r1870899158


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -618,6 +624,69 @@ private void decreasePendingMetricsAndReleaseSemaphore() {
     return new XceiverClientReply(replyFuture);
   }
 
+  public XceiverClientReply sendCommandReadBlock(
+      ContainerCommandRequestProto request, DatanodeDetails dn)
+      throws IOException, InterruptedException {
+
+    CompletableFuture<ContainerCommandResponseProto> future =
+        new CompletableFuture<>();
+    ContainerCommandResponseProto.Builder response =
+        ContainerCommandResponseProto.newBuilder();
+    ContainerProtos.ReadBlockResponseProto.Builder readBlock =
+        ContainerProtos.ReadBlockResponseProto.newBuilder();
+    checkOpen(dn);
+    UUID dnID = dn.getUuid();
+    Type cmdType = request.getCmdType();
+    semaphore.acquire();
+    long requestTime = System.currentTimeMillis();
+    metrics.incrPendingContainerOpsMetrics(cmdType);
+
+    final StreamObserver<ContainerCommandRequestProto> requestObserver =
+        asyncStubs.get(dnID).withDeadlineAfter(timeout, TimeUnit.SECONDS)
+            .send(new StreamObserver<ContainerCommandResponseProto>() {
+              @Override
+              public void onNext(
+                  ContainerCommandResponseProto responseProto) {
+                if (responseProto.getResult() == Result.SUCCESS) {
+                  readBlock.addReadChunk(responseProto.getReadChunk());
+                } else {
+                  future.complete(
+                      ContainerCommandResponseProto.newBuilder(responseProto)
+                          .setCmdType(Type.ReadBlock).build());
+                }
+              }
+
+              @Override
+              public void onError(Throwable t) {
+                future.completeExceptionally(t);
+                metrics.decrPendingContainerOpsMetrics(cmdType);
+                metrics.addContainerOpsLatency(
+                    cmdType, System.currentTimeMillis() - requestTime);

Review Comment:
   Elapsed time should be calculated using [nanoTime](https://docs.oracle.com/javase/8/docs/api/java/lang/System.html#nanoTime--) or `Time.monotonicNow()` as used in `HddsDispatcher.java`.



##########
hadoop-hdds/client/src/test/java/org/apache/hadoop/hdds/scm/storage/TestStreamBlockInputStream.java:
##########
@@ -0,0 +1,272 @@
+/*
+ * 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 java.io.EOFException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Random;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.Function;
+
+import com.google.common.primitives.Bytes;
+import org.apache.hadoop.hdds.client.BlockID;
+import org.apache.hadoop.hdds.client.ContainerBlockID;
+import org.apache.hadoop.hdds.conf.OzoneConfiguration;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ChecksumType;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ChunkInfo;
+import org.apache.hadoop.hdds.scm.OzoneClientConfig;
+import org.apache.hadoop.hdds.scm.pipeline.MockPipeline;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.ozone.common.Checksum;
+
+import org.apache.ratis.thirdparty.com.google.protobuf.ByteString;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.Mockito.mock;
+
+/**
+ * Tests for {@link TestStreamBlockInputStream}'s functionality.
+ */
+public class TestStreamBlockInputStream {
+  private int blockSize;
+  private static final int CHUNK_SIZE = 100;
+  private static final int BYTES_PER_CHECKSUM = 20;

Review Comment:
   Can we add some tests which cover the conditions where `BYTES_PER_CHECKSUM` is equal-to and greater than `CHUNK_SIZE`?



##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/StreamBlockInputStream.java:
##########
@@ -0,0 +1,760 @@
+/*
+ * 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 com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
+import org.apache.commons.lang3.NotImplementedException;
+import org.apache.hadoop.fs.ByteBufferReadable;
+import org.apache.hadoop.fs.CanUnbuffer;
+import org.apache.hadoop.fs.Seekable;
+import org.apache.hadoop.hdds.client.BlockID;
+import org.apache.hadoop.hdds.client.StandaloneReplicationConfig;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadChunkResponseProto;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadBlockResponseProto;
+import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
+import org.apache.hadoop.hdds.scm.OzoneClientConfig;
+import org.apache.hadoop.hdds.scm.XceiverClientFactory;
+import org.apache.hadoop.hdds.scm.XceiverClientSpi;
+import org.apache.hadoop.hdds.scm.client.HddsClientUtils;
+import org.apache.hadoop.hdds.scm.container.common.helpers.StorageContainerException;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.hdds.security.exception.SCMSecurityException;
+import org.apache.hadoop.hdds.security.token.OzoneBlockTokenIdentifier;
+import org.apache.hadoop.io.retry.RetryPolicy;
+import org.apache.hadoop.ozone.common.Checksum;
+import org.apache.hadoop.ozone.common.ChecksumData;
+import org.apache.hadoop.ozone.common.OzoneChecksumException;
+import org.apache.hadoop.ozone.common.utils.BufferUtils;
+import org.apache.hadoop.security.token.Token;
+import org.apache.ratis.thirdparty.com.google.protobuf.ByteString;
+import org.apache.ratis.thirdparty.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.EOFException;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+
+import static org.apache.hadoop.hdds.client.ReplicationConfig.getLegacyFactor;
+
+/**
+ * An {@link java.io.InputStream} called from KeyInputStream to read a block from the
+ * container.
+ */
+public class StreamBlockInputStream extends BlockExtendedInputStream
+    implements Seekable, CanUnbuffer, ByteBufferReadable {
+  private static final Logger LOG =
+      LoggerFactory.getLogger(StreamBlockInputStream.class);
+  private final BlockID blockID;
+  private final long blockLength;
+  private final AtomicReference<Pipeline> pipelineRef =
+      new AtomicReference<>();
+  private final AtomicReference<Token<OzoneBlockTokenIdentifier>> tokenRef =
+      new AtomicReference<>();
+  private XceiverClientFactory xceiverClientFactory;
+  private XceiverClientSpi xceiverClient;
+
+  private List<Long> bufferOffsets;
+  private int bufferIndex;
+  private long blockPosition = -1;
+  private List<ByteBuffer> buffers;
+  // Checks if the StreamBlockInputStream has already read data from the container.
+  private boolean allocated = false;
+  private long bufferOffsetWrtBlockData;
+  private long buffersSize;
+  private static final int EOF = -1;
+  private final List<XceiverClientSpi.Validator> validators;
+  private final boolean verifyChecksum;
+  private final Function<BlockID, BlockLocationInfo> refreshFunction;
+  private final RetryPolicy retryPolicy;
+  private int retries;
+
+
+  public StreamBlockInputStream(
+      BlockID blockID, long length, Pipeline pipeline,
+      Token<OzoneBlockTokenIdentifier> token,
+      XceiverClientFactory xceiverClientFactory,
+      Function<BlockID, BlockLocationInfo> refreshFunction,
+      OzoneClientConfig config) throws IOException {
+    this.blockID = blockID;
+    LOG.debug("Initializing StreamBlockInputStream for block {}", blockID);
+    this.blockLength = length;
+    setPipeline(pipeline);
+    tokenRef.set(token);
+    this.xceiverClientFactory = xceiverClientFactory;
+    this.validators = ContainerProtocolCalls.toValidatorList(
+        (request, response) -> validateBlock(response));
+    this.verifyChecksum = config.isChecksumVerify();
+    this.refreshFunction = refreshFunction;
+    this.retryPolicy =
+        HddsClientUtils.createRetryPolicy(config.getMaxReadRetryCount(),
+            TimeUnit.SECONDS.toMillis(config.getReadRetryInterval()));
+
+  }
+
+
+  public BlockID getBlockID() {
+    return blockID;
+  }
+
+  public long getLength() {
+    return blockLength;
+  }
+
+  @Override
+  public synchronized long getPos() {
+    if (blockLength == 0) {
+      return 0;
+    }
+    if (blockPosition >= 0) {
+      return blockPosition;
+    }
+
+    if (buffersHaveData()) {
+      // BufferOffset w.r.t to BlockData + BufferOffset w.r.t buffers +
+      // Position of current Buffer
+      return bufferOffsetWrtBlockData + bufferOffsets.get(bufferIndex) +
+          buffers.get(bufferIndex).position();
+    }
+    if (allocated && !dataRemainingInBlock()) {
+      Preconditions.checkState(
+          bufferOffsetWrtBlockData + buffersSize == blockLength,
+          "EOF detected but not at the last byte of the chunk");
+      return blockLength;
+    }
+    if (buffersAllocated()) {
+      return bufferOffsetWrtBlockData + buffersSize;
+    }
+    return 0;
+  }
+
+  @Override
+  public synchronized int read() throws IOException {
+    int dataout = EOF;
+    int len = 1;
+    int available;
+    while (len > 0) {
+      try {
+        acquireClient();
+        available = prepareRead(1);
+        retries = 0;
+      } catch (SCMSecurityException ex) {
+        throw ex;
+      } catch (StorageContainerException e) {
+        handleStorageContainerException(e);
+        continue;
+      } catch (IOException ioe) {
+        handleIOException(ioe);
+        continue;
+      }
+      if (available == EOF) {
+        // There is no more data in the chunk stream. The buffers should have
+        // been released by now
+        Preconditions.checkState(buffers == null);
+      } else {
+        dataout = Byte.toUnsignedInt(buffers.get(bufferIndex).get());
+      }
+
+      len -= available;
+      if (bufferEOF()) {
+        releaseBuffers(bufferIndex);
+      }
+    }
+
+
+    return dataout;
+
+
+  }
+
+  @Override
+  public synchronized int read(byte[] b, int off, int len) throws IOException {
+    // According to the JavaDocs for InputStream, it is recommended that
+    // subclasses provide an override of bulk read if possible for performance
+    // reasons.  In addition to performance, we need to do it for correctness
+    // reasons.  The Ozone REST service uses PipedInputStream and
+    // PipedOutputStream to relay HTTP response data between a Jersey thread and
+    // a Netty thread.  It turns out that PipedInputStream/PipedOutputStream
+    // have a subtle dependency (bug?) on the wrapped stream providing separate
+    // implementations of single-byte read and bulk read.  Without this, get key
+    // responses might close the connection before writing all of the bytes
+    // advertised in the Content-Length.
+    if (b == null) {
+      throw new NullPointerException();
+    }
+    if (off < 0 || len < 0 || len > b.length - off) {
+      throw new IndexOutOfBoundsException();
+    }
+    if (len == 0) {
+      return 0;
+    }
+    int total = 0;
+    int available;
+    while (len > 0) {
+      try {
+        acquireClient();
+        available = prepareRead(len);
+        retries = 0;
+      } catch (SCMSecurityException ex) {
+        throw ex;
+      } catch (StorageContainerException e) {
+        handleStorageContainerException(e);
+        continue;
+      } catch (IOException ioe) {
+        handleIOException(ioe);
+        continue;
+      }
+      if (available == EOF) {
+        // There is no more data in the block stream. The buffers should have
+        // been released by now
+        Preconditions.checkState(buffers == null);
+        return total != 0 ? total : EOF;
+      }
+      buffers.get(bufferIndex).get(b, off + total, available);
+      len -= available;
+      total += available;
+
+      if (bufferEOF()) {
+        releaseBuffers(bufferIndex);
+      }
+    }
+    return total;
+
+  }
+
+  @Override
+  public synchronized int read(ByteBuffer byteBuffer) throws IOException {
+    if (byteBuffer == null) {
+      throw new NullPointerException();
+    }
+    int len = byteBuffer.remaining();
+    if (len == 0) {
+      return 0;
+    }
+    int total = 0;
+    int available;
+    while (len > 0) {
+      try {
+        acquireClient();
+        available = prepareRead(len);
+        retries = 0;
+      } catch (SCMSecurityException ex) {
+        throw ex;
+      } catch (StorageContainerException e) {
+        handleStorageContainerException(e);
+        continue;
+      } catch (IOException ioe) {
+        handleIOException(ioe);
+        continue;
+      }
+      if (available == EOF) {
+        // There is no more data in the block stream. The buffers should have
+        // been released by now
+        Preconditions.checkState(buffers == null);
+        return total != 0 ? total : EOF;
+      }
+      ByteBuffer readBuf = buffers.get(bufferIndex);
+      ByteBuffer tmpBuf = readBuf.duplicate();
+      tmpBuf.limit(tmpBuf.position() + available);
+      byteBuffer.put(tmpBuf);
+      readBuf.position(tmpBuf.position());
+
+      len -= available;
+      total += available;
+
+      if (bufferEOF()) {
+        releaseBuffers(bufferIndex);
+      }
+    }
+    return total;
+  }
+
+  @Override
+  protected int readWithStrategy(ByteReaderStrategy strategy) throws IOException {
+    throw new NotImplementedException("readWithStrategy is not implemented.");
+  }
+
+  @Override
+  public synchronized void seek(long pos) throws IOException {
+    if (pos == 0 && blockLength == 0) {
+      // It is possible for length and pos to be zero in which case
+      // seek should return instead of throwing exception
+      return;
+    }
+    if (pos < 0 || pos > blockLength) {
+      throw new EOFException("EOF encountered at pos: " + pos + " for block: " + blockID);
+    }
+
+    if (buffersHavePosition(pos)) {
+      // The bufferPosition is w.r.t the current block.
+      // Adjust the bufferIndex and position to the seeked position.
+      adjustBufferPosition(pos - bufferOffsetWrtBlockData);
+    } else {
+      blockPosition = pos;
+    }
+  }
+
+  @Override
+  public synchronized boolean seekToNewSource(long l) throws IOException {
+    return false;
+  }
+
+  @Override
+  public synchronized void unbuffer() {
+    blockPosition = getPos();
+    releaseClient();
+    releaseBuffers();
+  }
+
+  private void setPipeline(Pipeline pipeline) throws IOException {
+    if (pipeline == null) {
+      return;
+    }
+    long replicaIndexes = pipeline.getNodes().stream().mapToInt(pipeline::getReplicaIndex).distinct().count();
+
+    if (replicaIndexes > 1) {
+      throw new IOException(String.format("Pipeline: %s has nodes containing different replica indexes.",
+          pipeline));
+    }
+
+    // irrespective of the container state, we will always read via Standalone
+    // protocol.
+    boolean okForRead =
+        pipeline.getType() == HddsProtos.ReplicationType.STAND_ALONE
+            || pipeline.getType() == HddsProtos.ReplicationType.EC;
+    Pipeline readPipeline = okForRead ? pipeline : Pipeline.newBuilder(pipeline)
+        .setReplicationConfig(StandaloneReplicationConfig.getInstance(
+            getLegacyFactor(pipeline.getReplicationConfig())))
+        .build();
+    pipelineRef.set(readPipeline);
+  }
+
+  protected synchronized void checkOpen() throws IOException {
+    if (xceiverClientFactory == null) {
+      throw new IOException("BlockInputStream has been closed.");
+    }
+  }
+
+  protected synchronized void acquireClient() throws IOException {
+    checkOpen();
+    if (xceiverClient == null) {
+      final Pipeline pipeline = pipelineRef.get();
+      try {
+        xceiverClient = xceiverClientFactory.acquireClientForReadData(pipeline);
+      } catch (IOException ioe) {
+        LOG.warn("Failed to acquire client for pipeline {}, block {}",
+            pipeline, blockID);
+        throw ioe;
+      }
+    }
+  }
+
+  private synchronized int prepareRead(int len) throws IOException {
+    for (;;) {
+      if (blockPosition >= 0) {
+        if (buffersHavePosition(blockPosition)) {
+          // The current buffers have the seeked position. Adjust the buffer
+          // index and position to point to the buffer position.
+          adjustBufferPosition(blockPosition - bufferOffsetWrtBlockData);
+        } else {
+          // Read a required block data to fill the buffers with seeked
+          // position data
+          readDataFromContainer(len);
+        }
+      }
+      if (buffersHaveData()) {
+        // Data is available from buffers
+        ByteBuffer bb = buffers.get(bufferIndex);
+        return Math.min(len, bb.remaining());
+      } else if (dataRemainingInBlock()) {
+        // There is more data in the block stream which has not
+        // been read into the buffers yet.
+        readDataFromContainer(len);
+      } else {
+        // All available input from this block stream has been consumed.
+        return EOF;
+      }
+    }
+
+
+  }
+
+  private boolean buffersHavePosition(long pos) {
+    // Check if buffers have been allocated
+    if (buffersAllocated()) {
+      // Check if the current buffers cover the input position
+      // Released buffers should not be considered when checking if position
+      // is available
+      return pos >= bufferOffsetWrtBlockData +
+          bufferOffsets.get(0) &&
+          pos < bufferOffsetWrtBlockData + buffersSize;
+    }
+    return false;
+  }
+
+  /**
+   * Check if the buffers have been allocated data and false otherwise.
+   */
+  @VisibleForTesting
+  protected boolean buffersAllocated() {
+    return buffers != null && !buffers.isEmpty();
+  }
+
+  /**
+   * Adjust the buffers position to account for seeked position and/ or checksum
+   * boundary reads.
+   * @param bufferPosition the position to which the buffers must be advanced
+   */
+  private void adjustBufferPosition(long bufferPosition) {
+    // The bufferPosition is w.r.t the current buffers.
+    // Adjust the bufferIndex and position to the seeked bufferPosition.
+    if (bufferIndex >= buffers.size()) {
+      bufferIndex = Collections.binarySearch(bufferOffsets, bufferPosition);
+    } else if (bufferPosition < bufferOffsets.get(bufferIndex)) {
+      bufferIndex = Collections.binarySearch(
+          bufferOffsets.subList(0, bufferIndex), bufferPosition);
+    } else if (bufferPosition >= bufferOffsets.get(bufferIndex) +
+        buffers.get(bufferIndex).capacity()) {
+      bufferIndex = Collections.binarySearch(bufferOffsets.subList(
+          bufferIndex + 1, buffers.size()), bufferPosition);
+    }

Review Comment:
   Can the conditions be combined to run a binary search on the entire bufferOffsets to simplify the code?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "sodonnel (via GitHub)" <gi...@apache.org>.
sodonnel commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r2465368649


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -504,6 +516,65 @@ private XceiverClientReply sendCommandWithRetry(
     }
   }
 
+  /**
+   * Starts a streaming read operation, intended to read entire blocks from the datanodes. This method expects a
+   * {@link StreamObserver} to be passed in, which will be used to receive the streamed data from the datanode.
+   * Upon successfully starting the streaming read, a {@link StreamingReadResponse} is returned, which contains
+   * information about the datanode used for the read, and the request observer that can be used to manage the stream
+   * (e.g., to cancel it if needed). A semaphore is acquired to limit the number of concurrent streaming reads so upon
+   * successful return of this method, the caller must ensure to call {@link #completeStreamRead(StreamingReadResponse)}
+   * to release the semaphore once the streaming read is complete.
+   * @param request The container command request to initiate the streaming read.
+   * @param streamObserver The observer that will handle the streamed responses.
+   * @return A {@link StreamingReadResponse} containing details of the streaming read operation.
+   * @throws IOException
+   * @throws InterruptedException
+   */
+  @Override
+  public StreamingReadResponse streamRead(ContainerCommandRequestProto request,
+      StreamObserver<ContainerCommandResponseProto> streamObserver) throws IOException, InterruptedException {
+    List<DatanodeDetails> datanodeList = sortDatanodes(request);
+    IOException lastException = null;
+    for (DatanodeDetails dn : datanodeList) {
+      try {
+        checkOpen(dn);
+        semaphore.acquire();
+        XceiverClientProtocolServiceStub stub = asyncStubs.get(dn.getID());
+        if (stub == null) {
+          throw new IOException("Failed to get gRPC stub for DataNode: " + dn);
+        }
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("Executing command {} on datanode {}", processForDebug(request), dn);
+        }
+        StreamObserver<ContainerCommandRequestProto> requestObserver = stub
+            .withDeadlineAfter(timeout, TimeUnit.SECONDS)
+            .send(streamObserver);
+        requestObserver.onNext(request);
+        requestObserver.onCompleted();
+        return new StreamingReadResponse(dn, (ClientCallStreamObserver<ContainerCommandRequestProto>) requestObserver);

Review Comment:
   My observation is that the HDFS model works well and results in relatively simple code in the approach used here which performs very well. Due to the buffer sizes used in the downstream readers, attempting to read a large block by the requested sized reads will result in many calls back and forward to the server. If we make the server truly async, then on each of these calls for often 16kb of data, it will have to queue for a thread, get a thread, context switch the thread, open the block file, seek the block file, read 16kb ... and so on.
   
   Of course we can cache open files, but we cannot have just one cached entry per file as many clients could be reading a file from different positions and of course a client can seek effectively eliminating the cache. Then we have to manage the cache and worry about too many open files, etc.
   
   HDFS had had some problems with its thread per open file, and we have seen clusters with 32k or more active xceiver threads per DN. This is usually caused by long writers, rather than long readers. A long reader would probably be a rare case.
   
   There are things we can do to mitigate holding too many handlers on the server. Eg the client can unbuffer after some small configurable window. The server could time out. We could have a separate handler pool for reads vs other operations.
   
   I already talked with @umamaheswararao and @kerneltime about the approach here and we agreed the handler pool would need to be greatly increased. I don't see any big problem with having a very large handler pool of threads that are mostly blocked. Yes they have some overhead in terms of memory, but we are not exactly memory constrained on Ozone datanodes, similar to HDFS DNs.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "sodonnel (via GitHub)" <gi...@apache.org>.
sodonnel commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-3485799629

   > So, we have to start 32k threads for each client? It does not sound right. (Sorry that I missed your reply previously.)
   
   The thread overhead is on the datanode side, as streaming a block to a client ties up the server handler thread. So if you have lots of blocks being read **slowly** it will use up the handlers. I don't think there is an issue with the number of threads needed on the client side. For any given block read, it will need 1 extra thread while the block is being read.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "sodonnel (via GitHub)" <gi...@apache.org>.
sodonnel commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-3481978985

   > Sure, aren't we changing the current production code to make it more efficient?
   
   ** The point of the checksum change from 1MB -> 16kb by default was to allow for smaller reads, so we don't want to constrain it to be required to return 1MB at a time. **
   
   The approach I have used here is to remove "length" from the read block call and page the data down in checksum sized pieces.
   
   > No. The context (such as the block file) should be saved with the StreamObserver object; see https://github.com/apache/ozone/pull/6613#discussion_r2487366995
   
   I can see how that could be possible, but we may also have to cache the checksum data for the block there too, and the way the code is structured it would take a bit of refactoring to get it there.
   
   I still have reservations that the chatty nature of the client having to request each piece of the block will add latency and overhead we don't need limiting any potential performance gains, especially with the size of reads I have seen when testing from the haoop shell and spark.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-3482102886

   > ** The point of the checksum change from 1MB -> 16kb by default was to allow for smaller reads, so we don't want to constrain it to be required to return 1MB at a time. **
   
   If small is required, we could round up the checksum boundary.  Updated below:
   
   - Client: opens the block and requests with 10KB.
   Client: sends an onNext() request with 10KB.
   Server: Since this is the first request, it opens the file.
   Server: invokes a readChunk call to read 10KB 
   Server: sends an onNext() response with 16KB data (rounding up the chunk boundary).
   
   - Client: requests 20KB but the buffer only has 6KB left
   Client: sends an onNext() request with 14KB.
   Server: invokes a readChunk call to read 14KB.
   Server: sends an onNext() response with 16KB data (rounding up the chunk boundary).
   
   - The 50MB case is the same as before.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r2491608530


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/StreamBlockInputStream.java:
##########
@@ -0,0 +1,443 @@
+/*
+ * 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 java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+import org.apache.commons.lang3.NotImplementedException;
+import org.apache.hadoop.fs.ByteBufferReadable;
+import org.apache.hadoop.fs.CanUnbuffer;
+import org.apache.hadoop.fs.FSExceptionMessages;
+import org.apache.hadoop.fs.Seekable;
+import org.apache.hadoop.hdds.client.BlockID;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadBlockResponseProto;
+import org.apache.hadoop.hdds.scm.OzoneClientConfig;
+import org.apache.hadoop.hdds.scm.StreamingReadResponse;
+import org.apache.hadoop.hdds.scm.StreamingReaderSpi;
+import org.apache.hadoop.hdds.scm.XceiverClientFactory;
+import org.apache.hadoop.hdds.scm.XceiverClientSpi;
+import org.apache.hadoop.hdds.scm.container.common.helpers.StorageContainerException;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.hdds.security.token.OzoneBlockTokenIdentifier;
+import org.apache.hadoop.io.retry.RetryPolicy;
+import org.apache.hadoop.ozone.common.Checksum;
+import org.apache.hadoop.ozone.common.ChecksumData;
+import org.apache.hadoop.ozone.common.OzoneChecksumException;
+import org.apache.hadoop.security.token.Token;
+import org.apache.ratis.thirdparty.io.grpc.StatusRuntimeException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * An {@link java.io.InputStream} called from KeyInputStream to read a block from the
+ * container.
+ */
+public class StreamBlockInputStream extends BlockExtendedInputStream
+    implements Seekable, CanUnbuffer, ByteBufferReadable {
+  private static final Logger LOG = LoggerFactory.getLogger(StreamBlockInputStream.class);
+  private static final int EOF = -1;
+  private static final Throwable CANCELLED_EXCEPTION = new Throwable("Cancelled by client");
+
+  private final BlockID blockID;
+  private final long blockLength;
+  private final AtomicReference<Pipeline> pipelineRef = new AtomicReference<>();
+  private final AtomicReference<Token<OzoneBlockTokenIdentifier>> tokenRef = new AtomicReference<>();
+  private XceiverClientFactory xceiverClientFactory;
+  private XceiverClientSpi xceiverClient;
+
+  private ByteBuffer buffer;
+  private long position = 0;
+  private boolean initialized = false;
+  private StreamingReader streamingReader;
+
+  private final boolean verifyChecksum;
+  private final Function<BlockID, BlockLocationInfo> refreshFunction;
+  private final RetryPolicy retryPolicy;
+  private int retries = 0;
+
+  public StreamBlockInputStream(
+      BlockID blockID, long length, Pipeline pipeline,
+      Token<OzoneBlockTokenIdentifier> token,
+      XceiverClientFactory xceiverClientFactory,
+      Function<BlockID, BlockLocationInfo> refreshFunction,
+      OzoneClientConfig config) throws IOException {
+    this.blockID = blockID;
+    this.blockLength = length;
+    pipelineRef.set(setPipeline(pipeline));
+    tokenRef.set(token);
+    this.xceiverClientFactory = xceiverClientFactory;
+    this.verifyChecksum = config.isChecksumVerify();
+    this.retryPolicy = getReadRetryPolicy(config);
+    this.refreshFunction = refreshFunction;
+  }
+
+  @Override
+  public BlockID getBlockID() {
+    return blockID;
+  }
+
+  @Override
+  public long getLength() {
+    return blockLength;
+  }
+
+  @Override
+  public synchronized long getPos() {
+    return position;
+  }
+
+  @Override
+  public synchronized int read() throws IOException {
+    checkOpen();
+    if (!dataAvailableToRead()) {
+      return EOF;
+    }
+    position++;
+    return buffer.get();
+  }
+
+  @Override
+  public synchronized int read(byte[] b, int off, int len) throws IOException {
+    ByteBuffer tmpBuffer = ByteBuffer.wrap(b, off, len);
+    return read(tmpBuffer);
+  }
+
+  @Override
+  public synchronized int read(ByteBuffer targetBuf) throws IOException {
+    checkOpen();
+    int read = 0;
+    while (targetBuf.hasRemaining()) {
+      if (!dataAvailableToRead()) {
+        break;
+      }
+      int toCopy = Math.min(buffer.remaining(), targetBuf.remaining());
+      ByteBuffer tmpBuf = buffer.duplicate();
+      tmpBuf.limit(tmpBuf.position() + toCopy);
+      targetBuf.put(tmpBuf);
+      buffer.position(tmpBuf.position());
+      position += toCopy;
+      read += toCopy;
+    }
+    return read > 0 ? read : EOF;
+  }
+
+  private boolean dataAvailableToRead() throws IOException {
+    if (position >= blockLength) {
+      return false;
+    }
+    initialize();
+    if (buffer == null || buffer.remaining() == 0) {
+      int loaded = fillBuffer();
+      return loaded != EOF;
+    }
+    return true;
+  }
+
+  @Override
+  protected int readWithStrategy(ByteReaderStrategy strategy) throws IOException {
+    throw new NotImplementedException("readWithStrategy is not implemented.");
+  }
+
+  @Override
+  public synchronized void seek(long pos) throws IOException {
+    checkOpen();
+    if (pos < 0) {
+      throw new IOException("Cannot seek to negative offset");
+    }
+    if (pos > blockLength) {
+      throw new IOException("Cannot seek after the end of the block");
+    }
+    if (pos == position) {
+      return;
+    }
+    closeStream();
+    position = pos;
+  }
+
+  @Override
+  // The seekable interface indicates that seekToNewSource should seek to a new source of the data,
+  // ie a different datanode. This is not supported for now.
+  public synchronized boolean seekToNewSource(long l) throws IOException {
+    return false;
+  }
+
+  @Override
+  public synchronized void unbuffer() {
+    releaseClient();
+  }
+
+  private void closeStream() {
+    if (streamingReader != null) {
+      streamingReader.cancel();
+      streamingReader = null;
+    }
+    initialized = false;
+    buffer = null;
+  }
+
+  protected synchronized void checkOpen() throws IOException {
+    if (xceiverClientFactory == null) {
+      throw new IOException(FSExceptionMessages.STREAM_IS_CLOSED + " Block: " + blockID);
+    }
+  }
+
+  protected synchronized void acquireClient() throws IOException {
+    checkOpen();
+    if (xceiverClient == null) {
+      final Pipeline pipeline = pipelineRef.get();
+      try {
+        xceiverClient = xceiverClientFactory.acquireClientForReadData(pipeline);
+      } catch (IOException ioe) {
+        LOG.warn("Failed to acquire client for pipeline {}, block {}", pipeline, blockID);
+        throw ioe;
+      }
+    }
+  }
+
+  private void initialize() throws IOException {
+    if (initialized) {
+      return;
+    }
+    while (true) {
+      try {
+        acquireClient();
+        streamingReader = new StreamingReader();
+        ContainerProtocolCalls.readBlock(xceiverClient, position, blockID, tokenRef.get(),
+            pipelineRef.get().getReplicaIndexes(), streamingReader);
+        initialized = true;
+        return;
+      } catch (InterruptedException ie) {
+        Thread.currentThread().interrupt();
+        handleExceptions(new IOException("Interrupted", ie));
+      } catch (IOException ioe) {
+        handleExceptions(ioe);
+      }
+    }
+  }
+
+  private void handleExceptions(IOException cause) throws IOException {
+    if (cause instanceof StorageContainerException || isConnectivityIssue(cause)) {
+      if (shouldRetryRead(cause, retryPolicy, retries++)) {
+        releaseClient();
+        refreshBlockInfo(cause);
+        LOG.warn("Refreshing block data to read block {} due to {}", blockID, cause.getMessage());
+      } else {
+        throw cause;
+      }
+    } else {
+      throw cause;
+    }
+  }
+
+  private int fillBuffer() throws IOException {
+    if (!streamingReader.hasNext()) {
+      return EOF;
+    }
+    buffer = streamingReader.readNext();
+    return buffer == null ? EOF : buffer.limit();
+  }
+
+  protected synchronized void releaseClient() {
+    if (xceiverClientFactory != null && xceiverClient != null) {
+      closeStream();
+      xceiverClientFactory.releaseClientForReadData(xceiverClient, false);
+      xceiverClient = null;
+    }
+  }
+
+  @Override
+  public synchronized void close() throws IOException {
+    releaseClient();
+    xceiverClientFactory = null;
+  }
+
+  private void refreshBlockInfo(IOException cause) throws IOException {
+    refreshBlockInfo(cause, blockID, pipelineRef, tokenRef, refreshFunction);
+  }
+
+  private synchronized void releaseStreamResources(StreamingReadResponse response) {
+    if (xceiverClient != null) {
+      xceiverClient.completeStreamRead(response);
+    }
+  }
+
+  /**
+   * Implementation of a StreamObserver used to received and buffer streaming GRPC reads.
+   */
+  public class StreamingReader implements StreamingReaderSpi {
+
+    private final BlockingQueue<ContainerProtos.ReadBlockResponseProto> responseQueue = new LinkedBlockingQueue<>(1);

Review Comment:
   Added `client side`  to https://github.com/apache/ozone/pull/6613#discussion_r2462932439
   
   > ...  the implementation uses a BlockingQueue responseQueue. When the responses are not removed from the queue, the `client side` gRPC thread is blocked in StreamingReader.onNext(..) and the gRPC streaming mechanism will throttle and slow down the server side.
   
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r2462932439


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -504,6 +516,65 @@ private XceiverClientReply sendCommandWithRetry(
     }
   }
 
+  /**
+   * Starts a streaming read operation, intended to read entire blocks from the datanodes. This method expects a
+   * {@link StreamObserver} to be passed in, which will be used to receive the streamed data from the datanode.
+   * Upon successfully starting the streaming read, a {@link StreamingReadResponse} is returned, which contains
+   * information about the datanode used for the read, and the request observer that can be used to manage the stream
+   * (e.g., to cancel it if needed). A semaphore is acquired to limit the number of concurrent streaming reads so upon
+   * successful return of this method, the caller must ensure to call {@link #completeStreamRead(StreamingReadResponse)}
+   * to release the semaphore once the streaming read is complete.
+   * @param request The container command request to initiate the streaming read.
+   * @param streamObserver The observer that will handle the streamed responses.
+   * @return A {@link StreamingReadResponse} containing details of the streaming read operation.
+   * @throws IOException
+   * @throws InterruptedException
+   */
+  @Override
+  public StreamingReadResponse streamRead(ContainerCommandRequestProto request,
+      StreamObserver<ContainerCommandResponseProto> streamObserver) throws IOException, InterruptedException {
+    List<DatanodeDetails> datanodeList = sortDatanodes(request);
+    IOException lastException = null;
+    for (DatanodeDetails dn : datanodeList) {
+      try {
+        checkOpen(dn);
+        semaphore.acquire();
+        XceiverClientProtocolServiceStub stub = asyncStubs.get(dn.getID());
+        if (stub == null) {
+          throw new IOException("Failed to get gRPC stub for DataNode: " + dn);
+        }
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("Executing command {} on datanode {}", processForDebug(request), dn);
+        }
+        StreamObserver<ContainerCommandRequestProto> requestObserver = stub
+            .withDeadlineAfter(timeout, TimeUnit.SECONDS)
+            .send(streamObserver);
+        requestObserver.onNext(request);
+        requestObserver.onCompleted();
+        return new StreamingReadResponse(dn, (ClientCallStreamObserver<ContainerCommandRequestProto>) requestObserver);

Review Comment:
   1. A client application opens the file.
   2. It calls read() with 10KB.
   3. It leaves the file open for 1 minute.  `// a gRPC thread is blocked here`
   4. It closes the file.
   
   I see how it works now -- the implementation uses a `BlockingQueue responseQueue`.  When the responses are not removed from the queue, the `client side` gRPC thread is blocked in `StreamingReader.onNext(..)` and the gRPC streaming mechanism will throttle and slow down the server side.
   
   However, the number open files will be limited by the number of gRPC threads.  Also, when all the gRPC threads are blocked, any gRPC calls will be blocked.  In an asynchronous model, threads should not blocked.  When the connection is idle at Step 3 above, it should release the thread so it can work on other calls.
   
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "sodonnel (via GitHub)" <gi...@apache.org>.
sodonnel commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-3311663690

   These are the steps I used to test the streaming block code.
   
   1. Download this PR.
   2. Merge in master - there was one small compile error I fixed by passing a string to the container scanner
   3. Create a single node docker cluster with the build, but adjust the config to make the blocksize 128MB rather than 1MB (docker_config file in the compose/ozone folder)
   
   Then create a 1GB file:
   
   ```
   dd if=/dev/urandom of=1gb bs=1M count=1024
   ```
   
   Create a bucket, volume and the key:
   
   ```
   ozone sh volume create sodonnell
   ozone sh bucket create sodonnell/bucket
   ozone sh key put sodonnell/bucket/1bg
   
   export OZONE_ROOT_LOGGER=INFO,console
   
   ozone sh key cat sodonnell/bucket/1gb > /dev/null
   ```
   
   The cat command fails with this checksum error:
   
   ```
   2025-09-19 10:17:17,474 [main] INFO impl.MetricsConfig: Loaded properties from hadoop-metrics2.properties
   2025-09-19 10:17:17,531 [main] INFO impl.MetricsSystemImpl: Scheduled Metric snapshot period at 10 second(s).
   2025-09-19 10:17:17,531 [main] INFO impl.MetricsSystemImpl: XceiverClientMetrics metrics system started
   2025-09-19 10:17:18,249 [main] WARN scm.XceiverClientGrpc: Failed to execute command ReadBlock on the pipeline Pipeline{ Id: dbc8f351-a151-432f-83de-ece94494810e, Nodes: [ {7fb912ed-eec9-4788-8b35-15f243b514ee(ozone-datanode-1.ozone_default/172.20.0.5), ReplicaIndex: 0},], ReplicationConfig: STANDALONE/ONE, State:ALLOCATED, leaderId:, CreationTimestamp2025-09-19T10:13:08.181Z[UTC]}.
   2025-09-19 10:17:18,251 [main] WARN scm.XceiverClientGrpc: Failed to execute command ReadBlock on the pipeline Pipeline{ Id: dbc8f351-a151-432f-83de-ece94494810e, Nodes: [ {7fb912ed-eec9-4788-8b35-15f243b514ee(ozone-datanode-1.ozone_default/172.20.0.5), ReplicaIndex: 0},], ReplicationConfig: STANDALONE/ONE, State:ALLOCATED, leaderId:, CreationTimestamp2025-09-19T10:13:08.181Z[UTC]}.
   2025-09-19 10:17:18,253 [main] WARN scm.XceiverClientGrpc: Failed to execute command ReadBlock on the pipeline Pipeline{ Id: dbc8f351-a151-432f-83de-ece94494810e, Nodes: [ {7fb912ed-eec9-4788-8b35-15f243b514ee(ozone-datanode-1.ozone_default/172.20.0.5), ReplicaIndex: 0},], ReplicationConfig: STANDALONE/ONE, State:ALLOCATED, leaderId:, CreationTimestamp2025-09-19T10:13:08.181Z[UTC]}.
   Checksum count mismatched: thatChecksumsCount=1 > thisChecksumsCount (=256 ) - thisStartIndex (=256)
   ```
   
   I captured debug logs before this error occurred, and I can see it performed 259 `getBlock` calls against the same block (4kb at a time)
   
   [debug.log.gz](https://github.com/user-attachments/files/22425454/debug.log.gz)
   
   ```
   grep "Executing command cmdType: ReadBlock" debug.log | wc -l
   259
   ```
   
   So the code as it stands in this test doesn't seem to be making a single getBlock call to read the entire block. Its making a call for every 4kb, which is even more strange as the checksum size is set to 16kb here.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "chungen0126 (via GitHub)" <gi...@apache.org>.
chungen0126 commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-3329964336

   Hi @sodonnel , thanks for the fix. I didn't have time to work on this. I think it works well now. I change this part in a commit before, mistakenly thinking that this was the correct way to write it.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "sodonnel (via GitHub)" <gi...@apache.org>.
sodonnel commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r2461050997


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -504,6 +516,65 @@ private XceiverClientReply sendCommandWithRetry(
     }
   }
 
+  /**
+   * Starts a streaming read operation, intended to read entire blocks from the datanodes. This method expects a
+   * {@link StreamObserver} to be passed in, which will be used to receive the streamed data from the datanode.
+   * Upon successfully starting the streaming read, a {@link StreamingReadResponse} is returned, which contains
+   * information about the datanode used for the read, and the request observer that can be used to manage the stream
+   * (e.g., to cancel it if needed). A semaphore is acquired to limit the number of concurrent streaming reads so upon
+   * successful return of this method, the caller must ensure to call {@link #completeStreamRead(StreamingReadResponse)}
+   * to release the semaphore once the streaming read is complete.
+   * @param request The container command request to initiate the streaming read.
+   * @param streamObserver The observer that will handle the streamed responses.
+   * @return A {@link StreamingReadResponse} containing details of the streaming read operation.
+   * @throws IOException
+   * @throws InterruptedException
+   */
+  @Override
+  public StreamingReadResponse streamRead(ContainerCommandRequestProto request,
+      StreamObserver<ContainerCommandResponseProto> streamObserver) throws IOException, InterruptedException {
+    List<DatanodeDetails> datanodeList = sortDatanodes(request);
+    IOException lastException = null;
+    for (DatanodeDetails dn : datanodeList) {
+      try {
+        checkOpen(dn);
+        semaphore.acquire();
+        XceiverClientProtocolServiceStub stub = asyncStubs.get(dn.getID());
+        if (stub == null) {
+          throw new IOException("Failed to get gRPC stub for DataNode: " + dn);
+        }
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("Executing command {} on datanode {}", processForDebug(request), dn);
+        }
+        StreamObserver<ContainerCommandRequestProto> requestObserver = stub
+            .withDeadlineAfter(timeout, TimeUnit.SECONDS)
+            .send(streamObserver);
+        requestObserver.onNext(request);
+        requestObserver.onCompleted();
+        return new StreamingReadResponse(dn, (ClientCallStreamObserver<ContainerCommandRequestProto>) requestObserver);

Review Comment:
   I had to refactor things a bit to fix the failing checksum problem.
   
   However its still not clear to me if I need to call `onComplete()` on the client side stream observer at all, or if it will cause a resource leak if I don't. Finding useful GRPC docs is proving channeling and AI tools are giving inconsistent answers to me.
   
   It seems to be possible to call `cancel` after `onComplete`. But the docs (at least those that I can find, as its far from clear) suggest you should not call onError after onComplete. However I tested this out and it doesn't throw anything if you do.
   
   As it stands, if the stream is read to successful complete, onComplete will be called on the **response** observer. But onComplete is not called on the **request** observer.
   
   If it is cancelled, `cancel` will get call on the request observer and that should result in onError getting trigger on the response observer.
   
   On a checksum error, `onError` will get call on the request observer.
   
   Its all very confusing and making this quite difficult to reason about IMO. What we really want is a way of synchronously iterating the stream, but we we get with GRPC is all this complete async logic that I fear has much potential for problems.
   
   What seems safest is to call:
   
   ```
   requestObserver.onNext(readBlockRequest);
   // We are never going to send another request to say its complete
   requestObserver.onComplete()
   ```
   
   Later in the code, we might call cancel for a seek, or we could call cancel for a checksum violation rather than error, as onError is not supposed to be called after onComplete. That way we can avoid worrying about not calling onComplete on the request observer. As I said earlier, I have no idea if you must call it or not!



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-3481778455

   > How is this going to look on the server? If the server gives up its handler thread after sending each piece of the block to the client then for each onNext() from the client, ...
   
   Not sure about you question.  Here is an example:
   
   - Client: opens the block and requests with 10KB.
   Client: sends an onNext() request with 10KB.
   Server: Since this is the first request, it opens the file.
   Server: invokes a readChunk call to read 1MB (rounding up the chunk boundary)
   Server: sends an onNext() response with 1MB data.
   
   - Client: requests 20KB
   Client: returns the data since it is already in client buffer (No onNext() request)
   
   - Client: requests 50MB
   Client: sends an onNext() request with 50MB.
   Server: loop 50 times below
   (a) invokes a readChunk call to read 1MB
   (b) sends an onNext() response with 1MB data.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "chungen0126 (via GitHub)" <gi...@apache.org>.
chungen0126 commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-3403122881

   Thanks, @sodonnel, for the updates. I apologize that I don't have time to work on this right now, but I gave a rough review. I have one question regarding the updates:
   The read chunk in Ozone and previous implementation of this pr caches the entire chunks and blocks, whereas the current version only caches a single response. While this will reduce memory usage, it may slow down seeking performance. Is this the intended trade-off?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "chungen0126 (via GitHub)" <gi...@apache.org>.
chungen0126 commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-3563992611

   > @chungen0126 , Let's merge the current code first and then work on the further improvements. It is already a lot of code.
   
   Sure, I agree.
   
   > @chungen0126 , @sodonnel , we should plan how to merge the code. How about we merge it in three parts in the following order?
   
   I have no idea how to merge this pr. If it was an acceptable way, let's do it.
   
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on PR #6613:
URL: https://github.com/apache/ozone/pull/6613#issuecomment-3564010448

   @chungen0126 , filed [HDDS-13973](https://issues.apache.org/jira/browse/HDDS-13973) "The ground work to support stream block" for your changes.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-10338. Implement a Client Datanode API to stream a block [ozone]

Posted by "sodonnel (via GitHub)" <gi...@apache.org>.
sodonnel commented on code in PR #6613:
URL: https://github.com/apache/ozone/pull/6613#discussion_r2457505281


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -504,6 +516,65 @@ private XceiverClientReply sendCommandWithRetry(
     }
   }
 
+  /**
+   * Starts a streaming read operation, intended to read entire blocks from the datanodes. This method expects a
+   * {@link StreamObserver} to be passed in, which will be used to receive the streamed data from the datanode.
+   * Upon successfully starting the streaming read, a {@link StreamingReadResponse} is returned, which contains
+   * information about the datanode used for the read, and the request observer that can be used to manage the stream
+   * (e.g., to cancel it if needed). A semaphore is acquired to limit the number of concurrent streaming reads so upon
+   * successful return of this method, the caller must ensure to call {@link #completeStreamRead(StreamingReadResponse)}
+   * to release the semaphore once the streaming read is complete.
+   * @param request The container command request to initiate the streaming read.
+   * @param streamObserver The observer that will handle the streamed responses.
+   * @return A {@link StreamingReadResponse} containing details of the streaming read operation.
+   * @throws IOException
+   * @throws InterruptedException
+   */
+  @Override
+  public StreamingReadResponse streamRead(ContainerCommandRequestProto request,
+      StreamObserver<ContainerCommandResponseProto> streamObserver) throws IOException, InterruptedException {
+    List<DatanodeDetails> datanodeList = sortDatanodes(request);
+    IOException lastException = null;
+    for (DatanodeDetails dn : datanodeList) {
+      try {
+        checkOpen(dn);
+        semaphore.acquire();
+        XceiverClientProtocolServiceStub stub = asyncStubs.get(dn.getID());
+        if (stub == null) {
+          throw new IOException("Failed to get gRPC stub for DataNode: " + dn);
+        }
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("Executing command {} on datanode {}", processForDebug(request), dn);
+        }
+        StreamObserver<ContainerCommandRequestProto> requestObserver = stub
+            .withDeadlineAfter(timeout, TimeUnit.SECONDS)
+            .send(streamObserver);
+        requestObserver.onNext(request);
+        requestObserver.onCompleted();
+        return new StreamingReadResponse(dn, (ClientCallStreamObserver<ContainerCommandRequestProto>) requestObserver);

Review Comment:
   From https://github.com/grpc/grpc-java/blob/ea7444607565f9d3ba8e6fe6e9d70a828f7645de/examples/src/main/java/io/grpc/examples/cancellation/CancellationClient.java#L97 It is valid to call `cancel` after `onComplete`, but it is not valid to call `onError` after `onComplete`.
   
   From what I read, `cancel` effectively calls `onError`, but the different is the meaning of what you are trying to do but not really any difference in functionality. The signal we sent to the server doesn't actually do anything except (hopefully) terminate the flow of streaming reads.
   
   But the error flow isn't working correctly. The combination of failed / completed in the code isn't working as expected when both error and complete have been set to true. I need to look at it a bit more.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org