This is an automated email from the ASF dual-hosted git repository.
adoroszlai pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/ozone.git
The following commit(s) were added to refs/heads/master by this push:
new 43822f2249a HDDS-16377. Datanode ReadBlock streaming path allocates
and copies a fresh buffer for every request (#11873)
43822f2249a is described below
commit 43822f2249ad82f0d2083dc7af6b90009e901bd7
Author: Sergey Soldatov <[email protected]>
AuthorDate: Tue Nov 17 00:05:56 2026 -0800
HDDS-16377. Datanode ReadBlock streaming path allocates and copies a fresh
buffer for every request (#11873)
Co-authored-by: Claude Fable 5.1 <[email protected]>
---
.../ContainerCommandResponseBuilders.java | 10 +-
.../container/common/helpers/ReadBlockContext.java | 75 ++++++++++++
.../container/common/impl/HddsDispatcher.java | 6 +-
.../common/interfaces/ContainerDispatcher.java | 4 +-
.../ozone/container/common/interfaces/Handler.java | 4 +-
.../transport/server/GrpcXceiverService.java | 14 +--
.../ozone/container/keyvalue/KeyValueHandler.java | 36 ++++--
.../common/helpers/TestReadBlockContext.java | 73 ++++++++++++
.../transport/server/TestGrpcXceiverService.java | 3 +-
.../container/keyvalue/TestKeyValueHandler.java | 131 ++++++++++++++++++---
10 files changed, 308 insertions(+), 48 deletions(-)
diff --git
a/hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/scm/protocolPB/ContainerCommandResponseBuilders.java
b/hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/scm/protocolPB/ContainerCommandResponseBuilders.java
index 3989fbdca0f..36032936454 100644
---
a/hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/scm/protocolPB/ContainerCommandResponseBuilders.java
+++
b/hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/scm/protocolPB/ContainerCommandResponseBuilders.java
@@ -347,11 +347,15 @@ public static ContainerCommandResponseProto
getReadChunkResponse(
.build();
}
- public static ContainerCommandResponseProto getReadBlockResponse(
- ContainerCommandRequestProto request, List<ChunkInfo> chunks, ByteBuffer
data, long offset) {
+ /**
+ * If {@code byteBufferToByteString} wraps {@code data} instead of copying
it, the caller must not modify the buffer
+ * until the response has been serialized, i.e. until {@code
StreamObserver.onNext} has returned.
+ */
+ public static ContainerCommandResponseProto
getReadBlockResponse(ContainerCommandRequestProto request,
+ List<ChunkInfo> chunks, ByteBuffer data, long offset,
Function<ByteBuffer, ByteString> byteBufferToByteString) {
ContainerProtos.ReadBlockResponseProto.Builder response =
ContainerProtos.ReadBlockResponseProto.newBuilder()
- .setData(ByteString.copyFrom(data))
+ .setData(byteBufferToByteString.apply(data))
.setOffset(offset);
if (request.getReadBlock().getIncludeChecksums()) {
response.addAllChunkInfoList(chunks);
diff --git
a/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/common/helpers/ReadBlockContext.java
b/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/common/helpers/ReadBlockContext.java
new file mode 100644
index 00000000000..fb90eb34262
--- /dev/null
+++
b/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/common/helpers/ReadBlockContext.java
@@ -0,0 +1,75 @@
+/*
+ * 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.ozone.container.common.helpers;
+
+import java.io.Closeable;
+import java.nio.ByteBuffer;
+import java.util.concurrent.atomic.AtomicReference;
+import org.apache.hadoop.hdds.client.BlockID;
+import org.apache.hadoop.hdds.utils.io.RandomAccessFileChannel;
+
+/**
+ * State kept across the ReadBlock requests of one gRPC stream, which serves
one block: the block file, the block's
+ * {@link BlockData} and the read buffer. Unlike a per-request
DispatcherContext, it lives until {@link #close()}.
+ */
+public class ReadBlockContext implements Closeable {
+ private final RandomAccessFileChannel blockFile = new
RandomAccessFileChannel();
+ private final AtomicReference<BlockData> cachedBlockData = new
AtomicReference<>();
+ private ByteBuffer readBuffer;
+
+ public RandomAccessFileChannel getBlockFile() {
+ return blockFile;
+ }
+
+ /**
+ * @return the {@link BlockData} cached for the given block, or null if none
is cached for it or the cached one has
+ * a lower BCSID than requested.
+ */
+ public BlockData getCachedBlockData(BlockID blockID) {
+ final BlockData cached = cachedBlockData.get();
+ return cached != null &&
cached.getBlockID().getContainerBlockID().equals(blockID.getContainerBlockID())
+ && cached.getBlockCommitSequenceId() >=
blockID.getBlockCommitSequenceId() ? cached : null;
+ }
+
+ /** Cache the {@link BlockData} of the block this context serves until
{@link #close()}. */
+ public void cacheBlockData(BlockData blockData) {
+ cachedBlockData.set(blockData);
+ }
+
+ /**
+ * @return a cleared read buffer of at least the given capacity, reallocated
only when it has to grow.
+ * Not thread-safe: the buffer is shared across requests, so the caller must
serialize them (gRPC serializes a
+ * stream's requests).
+ */
+ public ByteBuffer getReadBuffer(int capacity) {
+ if (readBuffer == null || readBuffer.capacity() < capacity) {
+ readBuffer = ByteBuffer.allocate(capacity);
+ } else {
+ readBuffer.clear();
+ }
+ return readBuffer;
+ }
+
+ /** Close the block file and drop the cached {@link BlockData} and the read
buffer. */
+ @Override
+ public void close() {
+ cachedBlockData.set(null);
+ readBuffer = null;
+ blockFile.close();
+ }
+}
diff --git
a/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/common/impl/HddsDispatcher.java
b/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/common/impl/HddsDispatcher.java
index bdfd40ecccd..94ffd73bf41 100644
---
a/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/common/impl/HddsDispatcher.java
+++
b/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/common/impl/HddsDispatcher.java
@@ -57,7 +57,6 @@
import org.apache.hadoop.hdds.server.OzoneProtocolMessageDispatcher;
import org.apache.hadoop.hdds.tracing.TracingUtil;
import org.apache.hadoop.hdds.utils.ProtocolMessageMetrics;
-import org.apache.hadoop.hdds.utils.io.RandomAccessFileChannel;
import org.apache.hadoop.ozone.audit.AuditAction;
import org.apache.hadoop.ozone.audit.AuditEventStatus;
import org.apache.hadoop.ozone.audit.AuditLogger;
@@ -69,6 +68,7 @@
import org.apache.hadoop.ozone.container.common.helpers.BlockData;
import org.apache.hadoop.ozone.container.common.helpers.ContainerMetrics;
import org.apache.hadoop.ozone.container.common.helpers.ContainerUtils;
+import org.apache.hadoop.ozone.container.common.helpers.ReadBlockContext;
import org.apache.hadoop.ozone.container.common.interfaces.Container;
import org.apache.hadoop.ozone.container.common.interfaces.ContainerDispatcher;
import org.apache.hadoop.ozone.container.common.interfaces.Handler;
@@ -876,7 +876,7 @@ public StateMachine.DataChannel getStreamDataChannel(
@Override
public void streamDataReadOnly(ContainerCommandRequestProto msg,
StreamObserver<ContainerCommandResponseProto> streamObserver,
- RandomAccessFileChannel blockFile, DispatcherContext dispatcherContext) {
+ ReadBlockContext readBlockContext, DispatcherContext dispatcherContext) {
Objects.requireNonNull(msg, "msg == null");
Type cmdType = msg.getCmdType();
String traceID = msg.getTraceID();
@@ -918,7 +918,7 @@ public void streamDataReadOnly(ContainerCommandRequestProto
msg,
ContainerProtos.Result.CONTAINER_INTERNAL_ERROR);
}
perf.appendPreOpLatencyMs(Time.monotonicNow() - startTime);
- responseProto = handler.readBlock(msg, container, blockFile,
streamObserver);
+ responseProto = handler.readBlock(msg, container, readBlockContext,
streamObserver);
long oPLatencyMS = Time.monotonicNow() - startTime;
metrics.incContainerOpsLatencies(cmdType, oPLatencyMS);
if (responseProto == null) {
diff --git
a/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/common/interfaces/ContainerDispatcher.java
b/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/common/interfaces/ContainerDispatcher.java
index af6822443d8..bdf24d47b4d 100644
---
a/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/common/interfaces/ContainerDispatcher.java
+++
b/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/common/interfaces/ContainerDispatcher.java
@@ -23,7 +23,7 @@
import
org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ContainerCommandRequestProto;
import
org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ContainerCommandResponseProto;
import
org.apache.hadoop.hdds.scm.container.common.helpers.StorageContainerException;
-import org.apache.hadoop.hdds.utils.io.RandomAccessFileChannel;
+import org.apache.hadoop.ozone.container.common.helpers.ReadBlockContext;
import
org.apache.hadoop.ozone.container.common.transport.server.ratis.DispatcherContext;
import org.apache.ratis.statemachine.StateMachine;
import org.apache.ratis.thirdparty.io.grpc.stub.StreamObserver;
@@ -102,7 +102,7 @@ default StateMachine.DataChannel getStreamDataChannel(
default void streamDataReadOnly(
ContainerCommandRequestProto msg,
StreamObserver<ContainerCommandResponseProto> streamObserver,
- RandomAccessFileChannel blockFile,
+ ReadBlockContext readBlockContext,
DispatcherContext dispatcherContext) {
throw new UnsupportedOperationException("streamDataReadOnly not
supported.");
}
diff --git
a/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/common/interfaces/Handler.java
b/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/common/interfaces/Handler.java
index 5a4d84e7430..7f645c976dd 100644
---
a/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/common/interfaces/Handler.java
+++
b/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/common/interfaces/Handler.java
@@ -31,12 +31,12 @@
import
org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ContainerCommandResponseProto;
import
org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ContainerType;
import
org.apache.hadoop.hdds.scm.container.common.helpers.StorageContainerException;
-import org.apache.hadoop.hdds.utils.io.RandomAccessFileChannel;
import org.apache.hadoop.ozone.container.checksum.ContainerChecksumTreeManager;
import org.apache.hadoop.ozone.container.checksum.ContainerMerkleTreeWriter;
import org.apache.hadoop.ozone.container.checksum.DNContainerOperationClient;
import org.apache.hadoop.ozone.container.common.helpers.BlockData;
import org.apache.hadoop.ozone.container.common.helpers.ContainerMetrics;
+import org.apache.hadoop.ozone.container.common.helpers.ReadBlockContext;
import org.apache.hadoop.ozone.container.common.impl.ContainerData;
import org.apache.hadoop.ozone.container.common.impl.ContainerSet;
import org.apache.hadoop.ozone.container.common.report.IncrementalReportSender;
@@ -297,6 +297,6 @@ public abstract void copyContainer(
public abstract ContainerCommandResponseProto readBlock(
ContainerCommandRequestProto msg, Container container,
- RandomAccessFileChannel blockFile,
+ ReadBlockContext readBlockContext,
StreamObserver<ContainerCommandResponseProto> streamObserver);
}
diff --git
a/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/common/transport/server/GrpcXceiverService.java
b/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/common/transport/server/GrpcXceiverService.java
index 36e7c8b74f6..187df25af00 100644
---
a/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/common/transport/server/GrpcXceiverService.java
+++
b/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/common/transport/server/GrpcXceiverService.java
@@ -32,7 +32,7 @@
import
org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ContainerCommandResponseProto;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.Type;
import
org.apache.hadoop.hdds.protocol.datanode.proto.XceiverClientProtocolServiceGrpc;
-import org.apache.hadoop.hdds.utils.io.RandomAccessFileChannel;
+import org.apache.hadoop.ozone.container.common.helpers.ReadBlockContext;
import org.apache.hadoop.ozone.container.common.interfaces.ContainerDispatcher;
import
org.apache.hadoop.ozone.container.common.transport.server.ratis.DispatcherContext;
import org.apache.ratis.grpc.util.ZeroCopyMessageMarshaller;
@@ -118,7 +118,7 @@ public StreamObserver<ContainerCommandRequestProto> send(
StreamObserver<ContainerCommandResponseProto> responseObserver) {
return new StreamObserver<ContainerCommandRequestProto>() {
private final AtomicBoolean isClosed = new AtomicBoolean(false);
- private final RandomAccessFileChannel blockFile = new
RandomAccessFileChannel();
+ private final ReadBlockContext readBlockContext = new ReadBlockContext();
// Held while a request is served, so the idle closer never closes the
file under an in-flight read.
private final ReentrantLock requestLock = new ReentrantLock();
private volatile long lastRequestNanos;
@@ -130,7 +130,7 @@ boolean close() {
if (check != null) {
check.cancel(false);
}
- blockFile.close();
+ readBlockContext.close();
return true;
}
return false;
@@ -157,9 +157,9 @@ private void closeFileIfIdle() {
return;
}
try {
- if (blockFile.isOpen()) {
+ if (readBlockContext.getBlockFile().isOpen()) {
LOG.debug("Closing block file of streaming read idle for {}ms",
TimeUnit.NANOSECONDS.toMillis(idleNanos));
- blockFile.close();
+ readBlockContext.close();
}
// The next request reopens the file and schedules a new check.
idleFileCheck = null;
@@ -178,7 +178,7 @@ public void onNext(ContainerCommandRequestProto request) {
requestLock.lock();
try {
if (request.getCmdType() == Type.ReadBlock) {
- dispatcher.streamDataReadOnly(request, responseObserver,
blockFile, context);
+ dispatcher.streamDataReadOnly(request, responseObserver,
readBlockContext, context);
} else {
final ContainerCommandResponseProto resp =
dispatcher.dispatch(request, context);
responseObserver.onNext(resp);
@@ -194,7 +194,7 @@ public void onNext(ContainerCommandRequestProto request) {
context.release();
}
lastRequestNanos = System.nanoTime();
- if (!isClosed.get() && blockFile.isOpen() && idleFileCheck == null) {
+ if (!isClosed.get() && readBlockContext.getBlockFile().isOpen() &&
idleFileCheck == null) {
scheduleIdleFileCheck(streamReadFileIdleTimeoutNanos);
}
requestLock.unlock();
diff --git
a/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/keyvalue/KeyValueHandler.java
b/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/keyvalue/KeyValueHandler.java
index c8a2d4f72a6..1baec51331d 100644
---
a/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/keyvalue/KeyValueHandler.java
+++
b/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/keyvalue/KeyValueHandler.java
@@ -142,6 +142,7 @@
import org.apache.hadoop.ozone.container.common.helpers.ChunkInfo;
import org.apache.hadoop.ozone.container.common.helpers.ContainerMetrics;
import org.apache.hadoop.ozone.container.common.helpers.ContainerUtils;
+import org.apache.hadoop.ozone.container.common.helpers.ReadBlockContext;
import org.apache.hadoop.ozone.container.common.impl.ContainerData;
import org.apache.hadoop.ozone.container.common.impl.ContainerLayoutVersion;
import org.apache.hadoop.ozone.container.common.impl.ContainerSet;
@@ -2289,7 +2290,7 @@ boolean deleteUnreferencedFile(File file) {
@Override
public ContainerCommandResponseProto readBlock(
ContainerCommandRequestProto request, Container kvContainer,
- RandomAccessFileChannel blockFile,
+ ReadBlockContext readBlockContext,
StreamObserver<ContainerCommandResponseProto> streamObserver) {
if (kvContainer.getContainerData().getLayoutVersion() != FILE_PER_BLOCK) {
@@ -2306,7 +2307,7 @@ public ContainerCommandResponseProto readBlock(
}
try {
final long startTime = Time.monotonicNow();
- final long bytesRead = readBlockImpl(request, blockFile, kvContainer,
streamObserver);
+ final long bytesRead = readBlockImpl(request, readBlockContext,
kvContainer, streamObserver);
KeyValueContainerData containerData = (KeyValueContainerData) kvContainer
.getContainerData();
HddsVolume volume = containerData.getVolume();
@@ -2331,13 +2332,14 @@ public ContainerCommandResponseProto readBlock(
return responseProto;
}
- private long readBlockImpl(ContainerCommandRequestProto request,
RandomAccessFileChannel blockFile,
+ private long readBlockImpl(ContainerCommandRequestProto request,
ReadBlockContext readBlockContext,
Container kvContainer, StreamObserver<ContainerCommandResponseProto>
streamObserver)
throws IOException {
final ReadBlockRequestProto readBlock = request.getReadBlock();
final int responseDataSize =
boundResponseDataSize(readBlock.getResponseDataSize());
final BlockID blockID = BlockID.getFromProtobuf(readBlock.getBlockID());
+ final RandomAccessFileChannel blockFile = readBlockContext.getBlockFile();
if (!blockFile.isOpen()) {
final File file =
FILE_PER_BLOCK.getChunkFile(kvContainer.getContainerData(), blockID, "unused");
blockFile.open(file);
@@ -2347,20 +2349,31 @@ private long readBlockImpl(ContainerCommandRequestProto
request, RandomAccessFil
BlockUtils.verifyReplicaIdx(kvContainer, blockID);
BlockUtils.verifyBCSId(kvContainer, blockID);
- final BlockData blockData = getBlockManager().getBlock(kvContainer,
blockID);
+ if (readBlock.getOffset() < 0 || readBlock.getLength() < 0) {
+ return rejectReadBlock(readBlockContext, streamObserver,
Status.INVALID_ARGUMENT.withDescription(
+ "Negative offset " + readBlock.getOffset() + " or length " +
readBlock.getLength() + " for " + blockID));
+ }
+
+ // Cached per stream; re-resolve when the range reaches the cached size,
since the block may have grown.
+ BlockData blockData = readBlockContext.getCachedBlockData(blockID);
+ if (blockData == null || readBlock.getLength() >= blockData.getSize() -
readBlock.getOffset()) {
+ blockData = getBlockManager().getBlock(kvContainer, blockID);
+ readBlockContext.cacheBlockData(blockData);
+ }
if (readBlock.getOffset() >= blockData.getSize()) {
- return rejectReadBlock(blockFile, streamObserver,
Status.OUT_OF_RANGE.withDescription(
+ return rejectReadBlock(readBlockContext, streamObserver,
Status.OUT_OF_RANGE.withDescription(
"Requested offset " + readBlock.getOffset() + " is beyond the end of
block " + blockID + " with size "
+ blockData.getSize()));
}
final BlockReadCursor cursor = new BlockReadCursor(readBlock.getOffset(),
readBlock.getLength(),
responseDataSize, blockData.getChunks());
- final ByteBuffer buffer = ByteBuffer.allocate(cursor.responseDataSize());
long bytesRead = 0;
while (cursor.hasNext()) {
final BlockReadCursor.ReadRange range = cursor.next();
+ // Reused across the stream's requests: gRPC serializes the response
inside onNext, before the buffer is refilled.
+ final ByteBuffer buffer = readBlockContext.getReadBuffer(range.length());
blockFile.position(range.offset());
- buffer.clear().limit(range.length());
+ buffer.limit(range.length());
blockFile.read(buffer);
if (buffer.hasRemaining()) {
throw new EOFException("Unexpected end of block " + blockID + " at " +
range.offset());
@@ -2370,7 +2383,8 @@ private long readBlockImpl(ContainerCommandRequestProto
request, RandomAccessFil
if (validateChunkChecksumData) {
Checksum.validateChecksums(buffer, range.offset(), 0, range.chunks());
}
- streamObserver.onNext(getReadBlockResponse(request, range.chunks(),
buffer, range.offset()));
+ streamObserver.onNext(
+ getReadBlockResponse(request, range.chunks(), buffer,
range.offset(), byteBufferToByteString));
}
return bytesRead;
}
@@ -2380,14 +2394,14 @@ private long readBlockImpl(ContainerCommandRequestProto
request, RandomAccessFil
* and make the dispatcher scan the container. This ends the call from the
datanode side, so also close the stream's
* block file: GrpcXceiverService closes it only when the client ends the
stream or a request throws.
*/
- private static long rejectReadBlock(RandomAccessFileChannel blockFile,
+ private static long rejectReadBlock(ReadBlockContext readBlockContext,
StreamObserver<ContainerCommandResponseProto> streamObserver, Status
status) {
- blockFile.close();
+ readBlockContext.close();
streamObserver.onError(status.asRuntimeException());
return 0;
}
- /** The client chooses the response size, which is a uint32 and sizes the
read buffer: bound it. */
+ /** The client chooses the response size, which is a uint32 and sizes a
buffer kept for the stream: bound it. */
@VisibleForTesting
static int boundResponseDataSize(int responseDataSize) {
if (responseDataSize <= 0) {
diff --git
a/hadoop-hdds/container-service/src/test/java/org/apache/hadoop/ozone/container/common/helpers/TestReadBlockContext.java
b/hadoop-hdds/container-service/src/test/java/org/apache/hadoop/ozone/container/common/helpers/TestReadBlockContext.java
new file mode 100644
index 00000000000..305149d9839
--- /dev/null
+++
b/hadoop-hdds/container-service/src/test/java/org/apache/hadoop/ozone/container/common/helpers/TestReadBlockContext.java
@@ -0,0 +1,73 @@
+/*
+ * 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.ozone.container.common.helpers;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+
+import java.nio.ByteBuffer;
+import org.apache.hadoop.hdds.client.BlockID;
+import org.junit.jupiter.api.Test;
+
+/** Tests for {@link ReadBlockContext}. */
+class TestReadBlockContext {
+ @Test
+ void blockDataIsCachedPerBlockAndClearedOnClose() {
+ final ReadBlockContext context = new ReadBlockContext();
+
+ // the stored BlockData has the block's committed BCSID, which may be
higher than the client's
+ final BlockID blockID = new BlockID(1, 2);
+ final BlockData blockData = new BlockData(new BlockID(1, 2));
+ blockData.setBlockCommitSequenceId(7);
+ assertNull(context.getCachedBlockData(blockID));
+
+ context.cacheBlockData(blockData);
+ assertSame(blockData, context.getCachedBlockData(blockID));
+ assertNull(context.getCachedBlockData(new BlockID(1, 3)));
+ final BlockID newer = new BlockID(1, 2);
+ newer.setBlockCommitSequenceId(8);
+ assertNull(context.getCachedBlockData(newer));
+
+ context.close();
+ assertNull(context.getCachedBlockData(blockID));
+ }
+
+ @Test
+ void readBufferIsReusedGrownAndDroppedOnClose() {
+ final ReadBlockContext context = new ReadBlockContext();
+
+ final ByteBuffer first = context.getReadBuffer(64);
+ assertEquals(64, first.capacity());
+ first.position(10).limit(20);
+
+ assertSame(first, context.getReadBuffer(64), "same capacity reuses the
buffer");
+ assertEquals(0, first.position());
+ assertEquals(64, first.limit());
+ assertSame(first, context.getReadBuffer(16), "smaller capacity reuses the
buffer");
+
+ final ByteBuffer grown = context.getReadBuffer(128);
+ assertNotSame(first, grown, "larger capacity reallocates");
+ assertEquals(128, grown.capacity());
+ assertSame(grown, context.getReadBuffer(64));
+
+ context.close();
+ assertNotSame(grown, context.getReadBuffer(64), "buffer dropped on close");
+ }
+}
diff --git
a/hadoop-hdds/container-service/src/test/java/org/apache/hadoop/ozone/container/common/transport/server/TestGrpcXceiverService.java
b/hadoop-hdds/container-service/src/test/java/org/apache/hadoop/ozone/container/common/transport/server/TestGrpcXceiverService.java
index 1d6fad6f533..0e389a5e9f9 100644
---
a/hadoop-hdds/container-service/src/test/java/org/apache/hadoop/ozone/container/common/transport/server/TestGrpcXceiverService.java
+++
b/hadoop-hdds/container-service/src/test/java/org/apache/hadoop/ozone/container/common/transport/server/TestGrpcXceiverService.java
@@ -37,6 +37,7 @@
import
org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadBlockRequestProto;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.Type;
import org.apache.hadoop.hdds.utils.io.RandomAccessFileChannel;
+import org.apache.hadoop.ozone.container.common.helpers.ReadBlockContext;
import org.apache.hadoop.ozone.container.common.interfaces.ContainerDispatcher;
import org.apache.ozone.test.GenericTestUtils;
import org.apache.ratis.thirdparty.io.grpc.stub.StreamObserver;
@@ -83,7 +84,7 @@ private ContainerDispatcher mockDispatcher(File blockFile,
AtomicReference<Rando
Runnable inFlight) throws Exception {
ContainerDispatcher dispatcher = mock(ContainerDispatcher.class);
doAnswer(inv -> {
- RandomAccessFileChannel channel = inv.getArgument(2);
+ RandomAccessFileChannel channel =
inv.<ReadBlockContext>getArgument(2).getBlockFile();
channelRef.set(channel);
if (!channel.isOpen()) {
channel.open(blockFile);
diff --git
a/hadoop-hdds/container-service/src/test/java/org/apache/hadoop/ozone/container/keyvalue/TestKeyValueHandler.java
b/hadoop-hdds/container-service/src/test/java/org/apache/hadoop/ozone/container/keyvalue/TestKeyValueHandler.java
index d3356a5bb25..cbfbf6326af 100644
---
a/hadoop-hdds/container-service/src/test/java/org/apache/hadoop/ozone/container/keyvalue/TestKeyValueHandler.java
+++
b/hadoop-hdds/container-service/src/test/java/org/apache/hadoop/ozone/container/keyvalue/TestKeyValueHandler.java
@@ -52,6 +52,7 @@
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.atMostOnce;
import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
@@ -100,7 +101,6 @@
import org.apache.hadoop.hdds.scm.pipeline.MockPipeline;
import org.apache.hadoop.hdds.scm.pipeline.PipelineID;
import org.apache.hadoop.hdds.security.token.TokenVerifier;
-import org.apache.hadoop.hdds.utils.io.RandomAccessFileChannel;
import org.apache.hadoop.metrics2.MetricsRecordBuilder;
import org.apache.hadoop.ozone.OzoneConsts;
import org.apache.hadoop.ozone.common.Checksum;
@@ -114,6 +114,7 @@
import org.apache.hadoop.ozone.container.common.helpers.BlockData;
import org.apache.hadoop.ozone.container.common.helpers.ChunkInfo;
import org.apache.hadoop.ozone.container.common.helpers.ContainerMetrics;
+import org.apache.hadoop.ozone.container.common.helpers.ReadBlockContext;
import org.apache.hadoop.ozone.container.common.impl.ContainerImplTestUtils;
import org.apache.hadoop.ozone.container.common.impl.ContainerLayoutVersion;
import org.apache.hadoop.ozone.container.common.impl.ContainerSet;
@@ -131,6 +132,7 @@
import
org.apache.hadoop.ozone.container.common.volume.RoundRobinVolumeChoosingPolicy;
import org.apache.hadoop.ozone.container.common.volume.StorageVolume;
import org.apache.hadoop.ozone.container.common.volume.VolumeSet;
+import org.apache.hadoop.ozone.container.keyvalue.interfaces.BlockManager;
import org.apache.hadoop.ozone.container.keyvalue.interfaces.ChunkManager;
import org.apache.hadoop.ozone.container.ozoneimpl.ContainerController;
import
org.apache.hadoop.ozone.container.ozoneimpl.ContainerScannerConfiguration;
@@ -1446,14 +1448,14 @@ public void
testReadBlockCancellationIsNotAContainerFailure() throws Exception {
doThrow(Status.CANCELLED.asRuntimeException()).when(observer).onNext(any());
assertThrows(StatusRuntimeException.class,
- () -> fixture.kvHandler.readBlock(request, fixture.container,
fixture.blockFile, observer));
+ () -> fixture.kvHandler.readBlock(request, fixture.container,
fixture.readBlockContext, observer));
}
}
@Test
public void testReadBlockMetrics() throws Exception {
Path testDir = Files.createTempDirectory("testReadBlockMetrics");
- RandomAccessFileChannel blockFile = null;
+ ReadBlockContext readBlockContext = null;
try {
conf.set(OZONE_SCM_CONTAINER_LAYOUT_KEY,
ContainerLayoutVersion.FILE_PER_BLOCK.name());
HandlerWithVolumeSet handlerWithVolume =
createKeyValueHandlerWithVolumeSet(testDir);
@@ -1512,9 +1514,9 @@ public void onCompleted() {
}
};
- blockFile = new RandomAccessFileChannel();
+ readBlockContext = new ReadBlockContext();
ContainerCommandResponseProto response = kvHandler.readBlock(
- readBlockRequest, container, blockFile, streamObserver);
+ readBlockRequest, container, readBlockContext, streamObserver);
assertNull(response, "ReadBlock should return null on success");
assertTrue(responseCount.get() > 0, "Should receive at least one
response");
@@ -1523,8 +1525,8 @@ public void onCompleted() {
ContainerMetrics.STORAGE_CONTAINER_METRICS);
assertCounter("bytesReadBlock", 1024L, containerMetrics);
} finally {
- if (blockFile != null) {
- blockFile.close();
+ if (readBlockContext != null) {
+ readBlockContext.close();
}
FileUtils.deleteDirectory(testDir.toFile());
ContainerMetrics.remove();
@@ -1593,9 +1595,87 @@ public void
testReadBlockErrorOnTheStreamClosesTheBlockFile() throws Exception {
try (StreamFixture fixture = new StreamFixture()) {
fixture.appendChunk("chunk1", 0, BLOCK_SIZE);
assertResponses(fixture.read(0, BLOCK_SIZE), 0, BLOCK_SIZE);
- assertTrue(fixture.blockFile.isOpen(), "block file stays open on the
stream after a successful read");
+ assertTrue(fixture.readBlockContext.getBlockFile().isOpen(),
+ "block file stays open on the stream after a successful read");
assertOutOfRange(fixture.read(BLOCK_SIZE, 1024), BLOCK_SIZE);
- assertFalse(fixture.blockFile.isOpen(), "block file closed after
OUT_OF_RANGE");
+ assertFalse(fixture.readBlockContext.getBlockFile().isOpen(), "block
file closed after OUT_OF_RANGE");
+
+ assertInvalidArgument(fixture.read(-1, 1024));
+ assertFalse(fixture.readBlockContext.getBlockFile().isOpen(), "block
file closed after INVALID_ARGUMENT");
+
+ assertInvalidArgument(fixture.read(0, -1));
+ assertFalse(fixture.readBlockContext.getBlockFile().isOpen(), "block
file closed after negative length");
+ }
+ }
+
+ private static void assertInvalidArgument(ReadBlockResult result) {
+ assertNull(result.getResponse());
+ assertThat(result.getDataResponses()).isEmpty();
+ StatusRuntimeException sre =
assertInstanceOf(StatusRuntimeException.class, result.getErrors().get(0));
+ assertEquals(Status.Code.INVALID_ARGUMENT, sre.getStatus().getCode());
+ }
+
+ /** The read buffer is sized by what the request needs, not by the client's
response size. */
+ @Test
+ public void testReadBlockReadBufferIsSizedByTheRequest() throws Exception {
+ final int chunkSize = 4 * (int) BYTES_PER_CHECKSUM;
+ try (StreamFixture fixture = new StreamFixture()) {
+ fixture.appendChunk("chunk1", 0, chunkSize);
+ assertResponses(fixture.read(0, 1, Integer.MAX_VALUE), 0,
BYTES_PER_CHECKSUM);
+ verify(fixture.readBlockContext).getReadBuffer((int) BYTES_PER_CHECKSUM);
+ assertResponses(fixture.read(0, chunkSize, Integer.MAX_VALUE), 0,
chunkSize);
+ verify(fixture.readBlockContext).getReadBuffer(chunkSize);
+ }
+ }
+
+ /** A length past the end of the block is clamped before rounding, so it
cannot overflow. */
+ @Test
+ public void testReadBlockLengthBeyondTheBlockIsClamped() throws Exception {
+ try (StreamFixture fixture = new StreamFixture()) {
+ fixture.appendChunk("chunk1", 0, BLOCK_SIZE);
+ assertResponses(fixture.read(0, Long.MAX_VALUE), 0, BLOCK_SIZE);
+ // a misaligned offset adds the alignment to the length before rounding
+ assertResponses(fixture.read(1, Long.MAX_VALUE), 0, BLOCK_SIZE);
+ }
+ }
+
+ @Test
+ public void testReadBlockCachedBlockDataIsReusedWithinTheBlock() throws
Exception {
+ final int chunkSize = 4 * (int) BYTES_PER_CHECKSUM;
+ try (StreamFixture fixture = new StreamFixture()) {
+ fixture.appendChunk("chunk1", 0, chunkSize);
+ assertResponses(fixture.read(0, BYTES_PER_CHECKSUM), 0,
BYTES_PER_CHECKSUM);
+ assertResponses(fixture.read(BYTES_PER_CHECKSUM, BYTES_PER_CHECKSUM),
BYTES_PER_CHECKSUM, BYTES_PER_CHECKSUM);
+ verify(fixture.blockManager, times(1)).getBlock(any(), any());
+ }
+ }
+
+ /** A request reaching the end of the cached BlockData must see a block that
grew under the open stream. */
+ @Test
+ public void testReadBlockCachedBlockDataIsRefreshedWhenTheBlockGrows()
throws Exception {
+ final int chunkSize = 2 * (int) BYTES_PER_CHECKSUM;
+ try (StreamFixture fixture = new StreamFixture()) {
+ fixture.appendChunk("chunk1", 0, chunkSize);
+ assertResponses(fixture.read(0, chunkSize), 0, chunkSize);
+
+ fixture.appendChunk("chunk2", chunkSize, chunkSize);
+ // straddles the cached size: a stale cache would cap it at chunkSize -
BYTES_PER_CHECKSUM bytes
+ assertResponses(fixture.read(BYTES_PER_CHECKSUM, chunkSize),
BYTES_PER_CHECKSUM, chunkSize);
+ }
+ }
+
+ /** A request inside the cached size after the block grew must not read past
the cached BlockData. */
+ @Test
+ public void testReadBlockCachedBlockDataBoundsTheReadWhenTheBlockGrows()
throws Exception {
+ final int chunkSize = 3 * (int) BYTES_PER_CHECKSUM;
+ try (StreamFixture fixture = new StreamFixture()) {
+ fixture.appendChunk("chunk1", 0, chunkSize);
+ assertResponses(fixture.read(0, BYTES_PER_CHECKSUM), 0,
BYTES_PER_CHECKSUM);
+
+ fixture.appendChunk("chunk2", chunkSize, chunkSize);
+ // rounds up to the cached size and needs two responses: the second must
stop at the cached size, not fill
+ // the response buffer from the grown file
+ assertResponses(fixture.read(0, 2 * BYTES_PER_CHECKSUM + 1, 2 * (int)
BYTES_PER_CHECKSUM), 0, chunkSize);
}
}
@@ -1723,22 +1803,26 @@ private static void assertResponses(ReadBlockResult
result, long firstOffset, lo
}
/**
- * A real FILE_PER_BLOCK container with one block and one {@link
RandomAccessFileChannel} standing in for the
- * per-stream channel of GrpcXceiverService.
+ * A real FILE_PER_BLOCK container with one block and one {@link
ReadBlockContext} standing in for the
+ * per-stream state of GrpcXceiverService. The block manager is spied to
count block table lookups.
*/
private final class StreamFixture implements AutoCloseable {
private final Path testDir = Files.createTempDirectory("testReadBlock");
private final KeyValueHandler kvHandler;
+ private final BlockManager blockManager;
private final KeyValueContainer container;
private final BlockID blockID;
private final BlockData blockData;
- private final RandomAccessFileChannel blockFile = new
RandomAccessFileChannel();
+ private final ReadBlockContext readBlockContext = spy(new
ReadBlockContext());
StreamFixture() throws Exception {
try {
conf.set(OZONE_SCM_CONTAINER_LAYOUT_KEY,
ContainerLayoutVersion.FILE_PER_BLOCK.name());
HandlerWithVolumeSet handlerWithVolume =
createKeyValueHandlerWithVolumeSet(testDir);
- kvHandler = handlerWithVolume.getHandler();
+ KeyValueHandler realHandler = handlerWithVolume.getHandler();
+ blockManager = spy(realHandler.getBlockManager());
+ kvHandler = spy(realHandler);
+ doReturn(blockManager).when(kvHandler).getBlockManager();
MutableVolumeSet volumeSet = handlerWithVolume.getVolumeSet();
ContainerSet containerSet = handlerWithVolume.getContainerSet();
@@ -1791,13 +1875,13 @@ ReadBlockResult
read(ContainerProtos.ReadBlockRequestProto.Builder readBlock) {
.setReadBlock(readBlock.setBlockID(blockID.getDatanodeBlockIDProtobuf()))
.build();
ReadBlockResult result = new ReadBlockResult(blockID);
- result.setResponse(kvHandler.readBlock(request, container, blockFile,
result));
+ result.setResponse(kvHandler.readBlock(request, container,
readBlockContext, result));
return result;
}
@Override
public void close() throws IOException {
- blockFile.close();
+ readBlockContext.close();
FileUtils.deleteDirectory(testDir.toFile());
ContainerMetrics.remove();
}
@@ -1830,7 +1914,11 @@ private static final class ReadBlockResult implements
StreamObserver<ContainerCo
@Override
public void onNext(ContainerCommandResponseProto dataResponse) {
- dataResponses.add(dataResponse);
+ // The payload may wrap the stream's read buffer, so keep a copy.
+ final ContainerProtos.ReadBlockResponseProto readBlock =
dataResponse.getReadBlock();
+ dataResponses.add(dataResponse.toBuilder()
+
.setReadBlock(readBlock.toBuilder().setData(ByteString.copyFrom(readBlock.getData().asReadOnlyByteBuffer())))
+ .build());
}
@Override
@@ -2052,13 +2140,18 @@ private void readBlockAndVerify(HandlerWithVolumeSet
handlerWithVolume, KeyValue
StreamObserver<ContainerCommandResponseProto> streamObserver =
mock(StreamObserver.class);
List<ContainerCommandResponseProto> capturedResponses = new
java.util.ArrayList<>();
doAnswer(invocation -> {
- capturedResponses.add(invocation.getArgument(0));
+ // The payload may wrap the stream's read buffer, so keep a copy.
+ final ContainerCommandResponseProto dataResponse =
invocation.getArgument(0);
+ final ContainerProtos.ReadBlockResponseProto readBlock =
dataResponse.getReadBlock();
+ capturedResponses.add(dataResponse.toBuilder()
+
.setReadBlock(readBlock.toBuilder().setData(ByteString.copyFrom(readBlock.getData().asReadOnlyByteBuffer())))
+ .build());
return null;
}).when(streamObserver).onNext(any(ContainerCommandResponseProto.class));
- try (RandomAccessFileChannel blockFile = new RandomAccessFileChannel()) {
+ try (ReadBlockContext readBlockContext = new ReadBlockContext()) {
ContainerCommandResponseProto response =
handlerWithVolume.getHandler().readBlock(
- readBlockRequest, container, blockFile, streamObserver);
+ readBlockRequest, container, readBlockContext, streamObserver);
assertNull(response, "ReadBlock should return null on success");
}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]