rich7420 commented on code in PR #11412:
URL: https://github.com/apache/ozone/pull/11412#discussion_r4704311807


##########
hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/common/transport/server/ratis/ClosedContainerReadResolver.java:
##########
@@ -0,0 +1,67 @@
+/*
+ * 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.transport.server.ratis;
+
+import java.io.IOException;
+import org.apache.hadoop.hdds.protocol.DatanodeDetails;
+import 
org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ContainerCommandRequestProto;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.Type;
+import org.apache.hadoop.hdds.ratis.ContainerCommandRequestMessage;
+import org.apache.hadoop.ozone.container.common.interfaces.Container;
+import org.apache.hadoop.ozone.container.common.interfaces.ContainerDispatcher;
+import org.apache.hadoop.ozone.container.ozoneimpl.ContainerController;
+import org.apache.ratis.protocol.RaftClientRequest;
+import org.apache.ratis.server.api.DataStreamApi;
+
+/**
+ * Serves ReadBlock on a Ratis read-only data stream, without a Raft group, 
for a container that is not open or closing.
+ * SCM gives the read pipeline of such a container a random ID, and no Raft 
group has this ID.
+ * The container no longer changes through Raft, so this datanode can serve 
the read from its replica.
+ */
+final class ClosedContainerReadResolver implements DataStreamApi.Resolver {
+  private final ContainerDispatcher dispatcher;
+  private final ContainerController containerController;
+  private final String datanodeUuid;
+
+  ClosedContainerReadResolver(ContainerDispatcher dispatcher, 
ContainerController containerController,
+      DatanodeDetails datanode) {
+    this.dispatcher = dispatcher;
+    this.containerController = containerController;
+    this.datanodeUuid = datanode.getUuidString();
+  }
+
+  /**
+   * @return the API to serve a ReadBlock of a container on this datanode that 
is not open or closing. Otherwise, null:
+   *     Ratis then serves the request with its Raft group.
+   */
+  @Override
+  public DataStreamApi resolve(RaftClientRequest request) throws IOException {
+    final ContainerCommandRequestProto requestProto = 
ContainerCommandRequestMessage.toProto(
+        request.getMessage().getContent(), request.getRaftGroupId());
+    if (requestProto.getCmdType() != Type.ReadBlock
+        || requestProto.hasDatanodeUuid() && 
!datanodeUuid.equals(requestProto.getDatanodeUuid())) {
+      return null;
+    }
+
+    final Container<?> container = 
containerController.getContainer(requestProto.getContainerID());
+    if (container == null || container.getContainerData().isOpen() || 
container.getContainerData().isClosing()) {

Review Comment:
   Could the resolver also serve replicas still OPEN or CLOSING? SCM returns a 
random-ID pipeline after the first CLOSED report, and I got 
`GroupMismatchException` reading an open replica that way.



##########
hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/common/transport/server/ratis/ContainerStateMachine.java:
##########
@@ -892,6 +901,97 @@ public CompletableFuture<Message> query(Message request) {
     }
   }
 
+  /** Serves a Ratis read-only data stream. Only ReadBlock is supported, see 
{@link #streamReadBlock}. */
+  @Override
+  public long transferTo(Message request, WritableByteChannel stream) throws 
IOException {
+    try {
+      metrics.incNumQueryStateMachineOps();
+      final ContainerCommandRequestProto requestProto = 
message2ContainerCommandRequestProto(request);
+      if (requestProto.getCmdType() != Type.ReadBlock) {
+        throw new IOException("Unsupported command for a read-only data 
stream: " + requestProto.getCmdType());
+      }
+      return streamReadBlock(dispatcher, requestProto, stream);
+    } catch (IOException e) {
+      metrics.incNumQueryStateMachineFails();
+      throw e;
+    }
+  }
+
+  /**
+   * Reads a block and writes each ReadBlock response to the stream as one 
reply:
+   * {@code [int: metadata length][metadata: the response without its 
data][data]}.
+   * Then closes the stream, which sends the terminal reply.
+   * If the read fails, this method throws without closing the stream. Ratis 
sends the failure as the terminal reply.
+   *
+   * @return the number of bytes written to the stream
+   */
+  static long streamReadBlock(ContainerDispatcher dispatcher, 
ContainerCommandRequestProto request,
+      WritableByteChannel stream) throws IOException {
+    final AtomicLong bytesWritten = new AtomicLong();
+    final AtomicReference<Throwable> error = new AtomicReference<>();
+    final StreamObserver<ContainerCommandResponseProto> observer = new 
StreamObserver<ContainerCommandResponseProto>() {
+      @Override
+      public void onNext(ContainerCommandResponseProto response) {
+        try {
+          bytesWritten.addAndGet(writeReadBlockReply(stream, response));
+        } catch (IOException e) {
+          error.set(e);
+          throw Status.CANCELLED.withDescription("Failed to write a ReadBlock 
reply").withCause(e).asRuntimeException();
+        }
+      }
+
+      @Override
+      public void onError(Throwable t) {
+        error.compareAndSet(null, t);
+      }
+
+      @Override
+      public void onCompleted() {
+      }
+    };
+
+    try (RandomAccessFileChannel blockFile = new RandomAccessFileChannel()) {
+      dispatcher.streamDataReadOnly(request, observer, blockFile, null);
+    } catch (StatusRuntimeException e) {
+      error.compareAndSet(null, e);
+    }
+    if (error.get() != null) {
+      throw new IOException("Failed to read block " + 
BlockID.getFromProtobuf(request.getReadBlock().getBlockID()),

Review Comment:
   Ratis can't serialize this `StatusRuntimeException` cause, so a read at EOF 
got no terminal reply and my client timed out after 10s. Could the cause be 
something serializable?



##########
hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/common/transport/server/ratis/ContainerStateMachine.java:
##########
@@ -892,6 +901,97 @@ public CompletableFuture<Message> query(Message request) {
     }
   }
 
+  /** Serves a Ratis read-only data stream. Only ReadBlock is supported, see 
{@link #streamReadBlock}. */
+  @Override
+  public long transferTo(Message request, WritableByteChannel stream) throws 
IOException {
+    try {
+      metrics.incNumQueryStateMachineOps();
+      final ContainerCommandRequestProto requestProto = 
message2ContainerCommandRequestProto(request);
+      if (requestProto.getCmdType() != Type.ReadBlock) {
+        throw new IOException("Unsupported command for a read-only data 
stream: " + requestProto.getCmdType());
+      }
+      return streamReadBlock(dispatcher, requestProto, stream);
+    } catch (IOException e) {
+      metrics.incNumQueryStateMachineFails();
+      throw e;
+    }
+  }
+
+  /**
+   * Reads a block and writes each ReadBlock response to the stream as one 
reply:
+   * {@code [int: metadata length][metadata: the response without its 
data][data]}.
+   * Then closes the stream, which sends the terminal reply.
+   * If the read fails, this method throws without closing the stream. Ratis 
sends the failure as the terminal reply.
+   *
+   * @return the number of bytes written to the stream
+   */
+  static long streamReadBlock(ContainerDispatcher dispatcher, 
ContainerCommandRequestProto request,
+      WritableByteChannel stream) throws IOException {
+    final AtomicLong bytesWritten = new AtomicLong();
+    final AtomicReference<Throwable> error = new AtomicReference<>();
+    final StreamObserver<ContainerCommandResponseProto> observer = new 
StreamObserver<ContainerCommandResponseProto>() {
+      @Override
+      public void onNext(ContainerCommandResponseProto response) {
+        try {
+          bytesWritten.addAndGet(writeReadBlockReply(stream, response));
+        } catch (IOException e) {
+          error.set(e);
+          throw Status.CANCELLED.withDescription("Failed to write a ReadBlock 
reply").withCause(e).asRuntimeException();
+        }
+      }
+
+      @Override
+      public void onError(Throwable t) {
+        error.compareAndSet(null, t);
+      }
+
+      @Override
+      public void onCompleted() {
+      }
+    };
+
+    try (RandomAccessFileChannel blockFile = new RandomAccessFileChannel()) {
+      dispatcher.streamDataReadOnly(request, observer, blockFile, null);

Review Comment:
   Could one test check this context is null? Token validation depends on it, 
and a `STREAM_COMMAND` context still passed all 37 state machine and resolver 
tests.



##########
hadoop-hdds/container-service/src/test/java/org/apache/hadoop/ozone/container/common/transport/server/ratis/ContainerStateMachineTests.java:
##########
@@ -258,6 +267,148 @@ public void testWriteTimout() throws Exception {
     assertEquals(ContainerProtos.Result.CONTAINER_INTERNAL_ERROR, 
sce.getResult());
   }
 
+  @Test
+  public void testTransferToReadBlock() throws Exception {
+    final ByteString first = ByteString.copyFromUtf8("first data");
+    final List<ContainerProtos.ContainerCommandResponseProto> responses = 
Arrays.asList(
+        readBlockResponse(0, first), readBlockResponse(first.size(), 
ByteString.copyFromUtf8("second data")));
+    setUpMockReadBlock(observer -> responses.forEach(observer::onNext));
+    final List<ByteBuffer> replies = new ArrayList<>();
+    final WritableByteChannel stream = newReadStream(replies);
+
+    final long written = 
stateMachine.transferTo(newRequest(ContainerProtos.Type.ReadBlock), stream);
+
+    // Each response is one reply: [metadata length][the response without its 
data][data]
+    assertEquals(responses.size(), replies.size());
+    long replyBytes = 0;
+    for (int i = 0; i < responses.size(); i++) {
+      final ContainerProtos.ContainerCommandResponseProto response = 
responses.get(i);
+      final ByteBuffer reply = replies.get(i);
+      replyBytes += reply.remaining();
+      assertEquals(readBlockResponse(response.getReadBlock().getOffset(), 
ByteString.EMPTY), parseMetadata(reply));
+      assertEquals(response.getReadBlock().getData(), 
ByteString.copyFrom(reply));
+    }
+    assertEquals(replyBytes, written);
+    verify(stream).close();
+  }
+
+  @Test
+  public void testTransferToReadBlockErrorResponse() throws Exception {
+    final ContainerProtos.ContainerCommandResponseProto error = 
errorResponse();
+    setUpMockReadBlock(observer -> observer.onNext(error));
+    final List<ByteBuffer> replies = new ArrayList<>();
+    final WritableByteChannel stream = newReadStream(replies);
+
+    stateMachine.transferTo(newRequest(ContainerProtos.Type.ReadBlock), 
stream);
+
+    assertEquals(1, replies.size());
+    assertEquals(error, parseMetadata(replies.get(0)));
+    assertFalse(replies.get(0).hasRemaining());
+    verify(stream).close();
+  }
+
+  /** The stream stays open, so Ratis sends the failure as the terminal reply. 
*/
+  @Test
+  public void testTransferToReadBlockReadFailure() throws Exception {
+    final StatusRuntimeException failure = 
Status.OUT_OF_RANGE.asRuntimeException();
+    setUpMockReadBlock(observer -> observer.onError(failure));
+    final WritableByteChannel stream = mock(WritableByteChannel.class);
+
+    final IOException e = assertThrows(IOException.class,
+        () -> 
stateMachine.transferTo(newRequest(ContainerProtos.Type.ReadBlock), stream));
+
+    assertSame(failure, e.getCause());
+    verify(stream, never()).write(any());
+    verify(stream, never()).close();
+  }
+
+  @Test
+  public void testTransferToReadBlockWriteFailure() throws Exception {
+    setUpMockReadBlock(observer -> {
+      final StatusRuntimeException e = 
assertThrows(StatusRuntimeException.class,
+          () -> observer.onNext(readBlockResponse(0, ByteString.EMPTY)));
+      // KeyValueHandler passes a CANCELLED status on, so the dispatcher does 
not scan the container.
+      assertEquals(Status.Code.CANCELLED, e.getStatus().getCode());
+      throw e;
+    });
+    final IOException failure = new IOException("Connection closed");
+    final WritableByteChannel stream = mock(WritableByteChannel.class);
+    when(stream.write(any())).thenThrow(failure);
+
+    final IOException e = assertThrows(IOException.class,
+        () -> 
stateMachine.transferTo(newRequest(ContainerProtos.Type.ReadBlock), stream));
+
+    assertSame(failure, e.getCause());
+    verify(stream, times(1)).write(any());
+    verify(stream, never()).close();
+  }
+
+  @Test
+  public void testTransferToUnsupportedCommand() throws Exception {
+    final WritableByteChannel stream = mock(WritableByteChannel.class);
+
+    assertThrows(IOException.class, () -> 
stateMachine.transferTo(newRequest(ContainerProtos.Type.GetBlock), stream));
+
+    verify(dispatcher, never()).streamDataReadOnly(any(), any(), any(), any());
+    verify(stream, never()).write(any());
+  }
+
+  private void 
setUpMockReadBlock(Consumer<StreamObserver<ContainerProtos.ContainerCommandResponseProto>>
 readBlock) {
+    doAnswer(invocation -> {
+      readBlock.accept(invocation.getArgument(1));
+      return null;
+    }).when(dispatcher).streamDataReadOnly(any(), any(), any(), any());
+  }
+
+  private static Message newRequest(ContainerProtos.Type type) {
+    return 
ContainerCommandRequestMessage.toMessage(ContainerProtos.ContainerCommandRequestProto.newBuilder()
+        .setCmdType(type)
+        .setContainerID(1)
+        .setDatanodeUuid(UUID.randomUUID().toString())
+        .build(), null);
+  }
+
+  private static ContainerProtos.ContainerCommandResponseProto 
readBlockResponse(long offset, ByteString data) {

Review Comment:
   Could `readBlockResponse` carry a `ChunkInfo` with checksums? Adding 
`clearChunkInfoList()` in `writeReadBlockReply` still passed all 26 tests for 
me.



##########
hadoop-hdds/container-service/src/test/java/org/apache/hadoop/ozone/container/common/impl/TestHddsDispatcher.java:
##########
@@ -639,6 +650,73 @@ public void testDuplicateWriteChunkAndPutBlockRequest() 
throws  IOException {
     }
   }
 
+  /**
+   * A ReadBlock whose stream is cancelled, for example because the client 
went away, is not a container problem, so
+   * the datanode must not scan the container. Any other failure while reading 
still makes it scan.
+   */
+  @ParameterizedTest
+  @ValueSource(booleans = {true, false})
+  public void testReadBlockScansContainerOnlyIfTheStreamIsNotCancelled(boolean 
cancelled) throws Exception {

Review Comment:
   Could this be two tests sharing the setup, one per rule? The `cancelled ? … 
: …` branches make each case's expectation harder 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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


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

Reply via email to