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 43ee1fa09b8 HDDS-16823. Move RecoverLease OM calls out of Ratis apply
(#12038)
43ee1fa09b8 is described below
commit 43ee1fa09b8f0ede42688b3ba4c597d017c087c2
Author: fmorg-git <[email protected]>
AuthorDate: Tue Nov 24 23:03:14 2026 -0800
HDDS-16823. Move RecoverLease OM calls out of Ratis apply (#12038)
---
.../hadoop/ozone/om/execution/OMExecutionFlow.java | 65 +++++-
.../hadoop/ozone/om/request/OMClientRequest.java | 13 ++
.../om/request/file/OMRecoverLeaseRequest.java | 79 +++++--
...OzoneManagerProtocolServerSideTranslatorPB.java | 3 +
.../ozone/om/execution/TestOMExecutionFlow.java | 66 ++++++
.../ozone/om/request/OMRequestTestUtils.java | 7 +
.../om/request/file/TestOMRecoverLeaseRequest.java | 102 +++++++++
.../hadoop/ozone/om/response/TestS3DerivedKey.java | 1 +
.../protocolPB/TestRecoverLeaseBlockInfo.java | 235 +++++++++++++++++++++
9 files changed, 542 insertions(+), 29 deletions(-)
diff --git
a/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/execution/OMExecutionFlow.java
b/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/execution/OMExecutionFlow.java
index 93cb76501b9..9f563d969b5 100644
---
a/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/execution/OMExecutionFlow.java
+++
b/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/execution/OMExecutionFlow.java
@@ -46,6 +46,10 @@ public class OMExecutionFlow {
Type.SnapshotMoveTableKeys, Type.SnapshotPurge,
Type.SetSnapshotProperty, Type.SetRangerServiceVersion,
Type.QuotaRepair, Type.DeleteRevokedSTSTokens,
Type.SaveLifecycleScanState, Type.CompleteFinalizeUpgrade);
+ // Types whose OMClientRequest overrides postExecute. The retry cache hits
of other types skip creating the request.
+ // A new override must be added here, which
TestOMExecutionFlow#postExecuteCmdTypesMatchOverrides enforces.
+ private static final Set<Type> POST_EXECUTE_CMD_TYPES =
EnumSet.of(Type.RecoverLease);
+
private final OzoneManager ozoneManager;
private final OMPerformanceMetrics perfMetrics;
@@ -72,12 +76,7 @@ private OMResponse submitExecutionToRatis(OMRequest request,
boolean isWrite) th
final OMRequest requestToSubmit;
if (isWrite) {
try {
- if (INTERNAL_CMD_TYPES.contains(request.getCmdType())) {
- throw new OMException(request.getCmdType() + " requests are not
accepted from clients.",
- OMException.ResultCodes.PERMISSION_DENIED);
- }
- omClientRequest = OzoneManagerRatisUtils.createClientRequest(request,
ozoneManager);
- assert (omClientRequest != null);
+ omClientRequest = createClientRequest(request);
final OMClientRequest finalOmClientRequest = omClientRequest;
OMRequest preExecuted =
captureLatencyNs(perfMetrics.getPreExecuteLatencyNs(),
() -> finalOmClientRequest.preExecute(ozoneManager));
@@ -100,12 +99,62 @@ private OMResponse submitExecutionToRatis(OMRequest
request, boolean isWrite) th
// 2. submit request to ratis
OMResponse response =
ozoneManager.getOmRatisServer().submitRequest(requestToSubmit, isWrite);
- if (!response.getSuccess() && omClientRequest != null) {
- omClientRequest.handleRequestFailure(ozoneManager);
+ if (omClientRequest != null) {
+ if (!response.getSuccess()) {
+ omClientRequest.handleRequestFailure(ozoneManager);
+ } else {
+ return postExecute(omClientRequest, request, response);
+ }
}
return response;
}
+ /**
+ * Runs post-execute steps on a successful write response served from the
Ratis retry cache.
+ */
+ public OMResponse postExecute(OMRequest request, OMResponse response) {
+ if (!hasPostExecute(request.getCmdType())) {
+ return response;
+ }
+ final OMClientRequest omClientRequest;
+ try {
+ omClientRequest = createClientRequest(request);
+ } catch (IOException ex) {
+ // Creating the request handler may look up current metadata (such as
bucket layout) that was deleted after the
+ // request was applied. Return the cached response instead of failing an
already-applied request.
+ return response;
+ }
+ return postExecute(omClientRequest, request, response);
+ }
+
+ private OMResponse postExecute(OMClientRequest omClientRequest, OMRequest
request, OMResponse response) {
+ try {
+ return omClientRequest.postExecute(ozoneManager, response);
+ } catch (IOException ex) {
+ return createPostExecuteErrorResponse(request, response, ex);
+ }
+ }
+
+ static boolean hasPostExecute(Type cmdType) {
+ return POST_EXECUTE_CMD_TYPES.contains(cmdType);
+ }
+
+ private OMClientRequest createClientRequest(OMRequest request) throws
IOException {
+ if (INTERNAL_CMD_TYPES.contains(request.getCmdType())) {
+ throw new OMException(
+ request.getCmdType() + " requests are not accepted from clients.",
OMException.ResultCodes.PERMISSION_DENIED);
+ }
+ final OMClientRequest omClientRequest =
OzoneManagerRatisUtils.createClientRequest(request, ozoneManager);
+ assert (omClientRequest != null);
+ return omClientRequest;
+ }
+
+ private static OMResponse createPostExecuteErrorResponse(OMRequest request,
OMResponse response, IOException ex) {
+ final OMResponse errorResponse =
OzoneManagerRatisUtils.createErrorResponse(request, ex);
+ return response.hasOmLockDetails() ?
+
errorResponse.toBuilder().setOmLockDetails(response.getOmLockDetails()).build()
: errorResponse;
+ }
+
/**
* Captures authenticated request context on the RPC thread before
submitting a read request to Ratis.
*/
diff --git
a/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/request/OMClientRequest.java
b/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/request/OMClientRequest.java
index a37dd2d4007..28a14fe6410 100644
---
a/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/request/OMClientRequest.java
+++
b/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/request/OMClientRequest.java
@@ -141,6 +141,19 @@ public OMRequest preExecute(OzoneManager ozoneManager)
return omRequest;
}
+ /**
+ * Perform post-execute steps on an OMResponse.
+ *
+ * Called from the RPC context on the leader after the request has been
applied successfully. When the response is
+ * served from the Ratis retry cache, this is called on a new request
instance on which {@link #preExecute} has not
+ * run, and only if the command type is registered in {@code
OMExecutionFlow.POST_EXECUTE_CMD_TYPES}.
+ *
+ * @return OMResponse that will be returned to the client.
+ */
+ public OMResponse postExecute(OzoneManager ozoneManager, OMResponse
omResponse) throws IOException {
+ return omResponse;
+ }
+
/**
* Performs any request specific failure handling during request
* submission. An example of this would be an undo of any steps
diff --git
a/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/request/file/OMRecoverLeaseRequest.java
b/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/request/file/OMRecoverLeaseRequest.java
index ac8d7eaa1a5..06f14c28e8e 100644
---
a/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/request/file/OMRecoverLeaseRequest.java
+++
b/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/request/file/OMRecoverLeaseRequest.java
@@ -24,6 +24,7 @@
import static
org.apache.hadoop.ozone.om.exceptions.OMException.ResultCodes.KEY_ALREADY_CLOSED;
import static
org.apache.hadoop.ozone.om.exceptions.OMException.ResultCodes.KEY_NOT_FOUND;
import static
org.apache.hadoop.ozone.om.exceptions.OMException.ResultCodes.KEY_UNDER_LEASE_SOFT_LIMIT_PERIOD;
+import static
org.apache.hadoop.ozone.om.exceptions.OMException.ResultCodes.SCM_GET_PIPELINE_EXCEPTION;
import static
org.apache.hadoop.ozone.om.lock.OzoneManagerLock.LeveledResource.BUCKET_LOCK;
import static org.apache.hadoop.ozone.om.upgrade.OMLayoutFeature.HBASE_SUPPORT;
import static
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.Type.RecoverLease;
@@ -50,7 +51,6 @@
import org.apache.hadoop.ozone.om.helpers.OmFSOFile;
import org.apache.hadoop.ozone.om.helpers.OmKeyInfo;
import org.apache.hadoop.ozone.om.helpers.OmKeyLocationInfo;
-import org.apache.hadoop.ozone.om.helpers.OmKeyLocationInfoGroup;
import org.apache.hadoop.ozone.om.request.key.OMKeyRequest;
import org.apache.hadoop.ozone.om.request.util.OmResponseUtil;
import org.apache.hadoop.ozone.om.response.OMClientResponse;
@@ -253,21 +253,6 @@ private RecoverLeaseResponse doWork(OzoneManager
ozoneManager,
keyInfo.setKeyName(keyName);
openKeyInfo.setKeyName(keyName);
- OmKeyLocationInfoGroup keyLatestVersionLocations =
keyInfo.getLatestVersionLocations();
- List<OmKeyLocationInfo> keyLocationInfoList =
keyLatestVersionLocations.createLocationList();
- OmKeyLocationInfoGroup openKeyLatestVersionLocations =
openKeyInfo.getLatestVersionLocations();
- List<OmKeyLocationInfo> openKeyLocationInfoList =
openKeyLatestVersionLocations.createLocationList();
-
- if (!keyLocationInfoList.isEmpty()) {
- updateBlockInfo(ozoneManager,
keyLocationInfoList.get(keyLocationInfoList.size() - 1));
- }
- if (openKeyLocationInfoList.size() > 1) {
- updateBlockInfo(ozoneManager,
openKeyLocationInfoList.get(openKeyLocationInfoList.size() - 1));
- updateBlockInfo(ozoneManager,
openKeyLocationInfoList.get(openKeyLocationInfoList.size() - 2));
- } else if (!openKeyLocationInfoList.isEmpty()) {
- updateBlockInfo(ozoneManager, openKeyLocationInfoList.get(0));
- }
-
RecoverLeaseResponse.Builder rb = RecoverLeaseResponse.newBuilder();
ClientVersion clientVersion =
ClientVersion.deserialize(getOmRequest().getVersion());
rb.setKeyInfo(keyInfo.getNetworkProtobuf(clientVersion, true));
@@ -275,19 +260,71 @@ private RecoverLeaseResponse doWork(OzoneManager
ozoneManager,
return rb.build();
}
+ /**
+ * Adds the block token and the current pipeline to the blocks that the
recovering client has to contact:
+ * the last block of the file and the last two blocks of the open file.
+ * Only the reply to the client needs them, so this runs on the leader after
the request has been applied:
+ * applying the request must not depend on SCM.
+ */
+ @Override
+ public OMResponse postExecute(OzoneManager ozoneManager, OMResponse
omResponse) throws IOException {
+ final OMResponse response = super.postExecute(ozoneManager, omResponse);
+ if (!response.hasRecoverLeaseResponse()) {
+ return response;
+ }
+ final RecoverLeaseResponse recoverLeaseResponse =
response.getRecoverLeaseResponse();
+ if (!recoverLeaseResponse.hasKeyInfo() ||
!recoverLeaseResponse.hasOpenKeyInfo()) {
+ return response;
+ }
+ final OmKeyInfo keyInfo =
OmKeyInfo.getFromProtobuf(recoverLeaseResponse.getKeyInfo());
+ final OmKeyInfo openFileKeyInfo =
OmKeyInfo.getFromProtobuf(recoverLeaseResponse.getOpenKeyInfo());
+
+ final List<OmKeyLocationInfo> keyLocationInfoList =
keyInfo.getLatestVersionLocations().createLocationList();
+ final List<OmKeyLocationInfo> openKeyLocationInfoList =
+ openFileKeyInfo.getLatestVersionLocations().createLocationList();
+
+ try {
+ if (!keyLocationInfoList.isEmpty()) {
+ updateBlockInfo(ozoneManager,
keyLocationInfoList.get(keyLocationInfoList.size() - 1));
+ }
+ if (openKeyLocationInfoList.size() > 1) {
+ updateBlockInfo(ozoneManager,
openKeyLocationInfoList.get(openKeyLocationInfoList.size() - 1));
+ updateBlockInfo(ozoneManager,
openKeyLocationInfoList.get(openKeyLocationInfoList.size() - 2));
+ } else if (!openKeyLocationInfoList.isEmpty()) {
+ updateBlockInfo(ozoneManager, openKeyLocationInfoList.get(0));
+ }
+ } catch (IOException ex) {
+ // The request was applied successfully, so nothing else logs that the
client gets an error instead.
+ LOG.warn(
+ "Failed to add block info to the RecoverLease response. Volume:{},
Bucket:{}, Key:{}", volumeName, bucketName,
+ keyName, ex);
+ throw ex;
+ }
+
+ final ClientVersion clientVersion =
ClientVersion.deserialize(getOmRequest().getVersion());
+ return
response.toBuilder().setRecoverLeaseResponse(RecoverLeaseResponse.newBuilder()
+ .setKeyInfo(keyInfo.getNetworkProtobuf(clientVersion, true))
+ .setOpenKeyInfo(openFileKeyInfo.getNetworkProtobuf(clientVersion,
true))).build();
+ }
+
private void updateBlockInfo(OzoneManager ozoneManager, OmKeyLocationInfo
blockInfo) throws IOException {
if (blockInfo != null) {
// set token to last block if enabled
if (ozoneManager.isGrpcBlockTokenEnabled()) {
- String remoteUser = getRemoteUser().getShortUserName();
- OzoneBlockTokenSecretManager secretManager =
ozoneManager.getBlockTokenSecretManager();
+ final String remoteUser = getRemoteUser().getShortUserName();
+ final OzoneBlockTokenSecretManager secretManager =
ozoneManager.getBlockTokenSecretManager();
blockInfo.setToken(secretManager.generateToken(remoteUser,
blockInfo.getBlockID(),
EnumSet.of(READ, WRITE), blockInfo.getLength()));
}
// refresh last block pipeline
- ContainerWithPipeline containerWithPipeline =
-
ozoneManager.getScmClient().getContainerClient().getContainerWithPipeline(blockInfo.getContainerID());
- blockInfo.setPipeline(containerWithPipeline.getPipeline());
+ try {
+ final ContainerWithPipeline containerWithPipeline =
+
ozoneManager.getScmClient().getContainerClient().getContainerWithPipeline(blockInfo.getContainerID());
+ blockInfo.setPipeline(containerWithPipeline.getPipeline());
+ } catch (IOException e) {
+ // SCM fails with IOException. Map it to a retriable client error
instead of INTERNAL_ERROR
+ throw new OMException(e.getMessage(), e, SCM_GET_PIPELINE_EXCEPTION);
+ }
}
}
diff --git
a/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/protocolPB/OzoneManagerProtocolServerSideTranslatorPB.java
b/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/protocolPB/OzoneManagerProtocolServerSideTranslatorPB.java
index 32a9c7b12a9..083859f1014 100644
---
a/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/protocolPB/OzoneManagerProtocolServerSideTranslatorPB.java
+++
b/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/protocolPB/OzoneManagerProtocolServerSideTranslatorPB.java
@@ -212,6 +212,9 @@ private OMResponse internalProcessRequest(OMRequest
request) throws ServiceExcep
if (response == null) {
this.lastRequestToSubmit = request;
response = ozoneManager.getOmExecutionFlow().submit(request, true);
+ } else if (response.getSuccess()) {
+ // Cached replies come from Ratis apply, so leader-only postExecute
steps still need to run.
+ response = ozoneManager.getOmExecutionFlow().postExecute(request,
response);
}
if (derivedKey != null && response.getSuccess() &&
response.hasCreateKeyResponse()) {
return
response.toBuilder().setCreateKeyResponse(response.getCreateKeyResponse().toBuilder()
diff --git
a/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/execution/TestOMExecutionFlow.java
b/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/execution/TestOMExecutionFlow.java
index 5d63b37938e..3a2b03e0fb9 100644
---
a/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/execution/TestOMExecutionFlow.java
+++
b/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/execution/TestOMExecutionFlow.java
@@ -20,14 +20,22 @@
import static
org.apache.hadoop.security.UserGroupInformation.AuthenticationMethod.KERBEROS;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertSame;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+import java.lang.reflect.Modifier;
import java.net.InetAddress;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.ipc_.RPC;
import org.apache.hadoop.ipc_.Server;
@@ -35,6 +43,10 @@
import org.apache.hadoop.ozone.om.OzoneAclUtils;
import org.apache.hadoop.ozone.om.OzoneManager;
import org.apache.hadoop.ozone.om.ratis.OzoneManagerRatisServer;
+import org.apache.hadoop.ozone.om.request.OMClientRequest;
+import org.apache.hadoop.ozone.om.request.file.OMRecoverLeaseRequest;
+import
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.DeleteKeyRequest;
+import
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.KeyArgs;
import
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.OMRequest;
import
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.OMResponse;
import
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.S3Authentication;
@@ -49,6 +61,10 @@
import org.apache.hadoop.security.token.TokenIdentifier;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
+import org.reflections.Reflections;
+import org.reflections.scanners.Scanners;
+import org.reflections.util.ClasspathHelper;
+import org.reflections.util.ConfigurationBuilder;
class TestOMExecutionFlow {
@@ -170,6 +186,56 @@ void writeRequestClearsS3Context() throws Exception {
assertFalse(submittedRequest.get().hasAssumeS3Context());
}
+ @Test
+ void postExecuteCmdTypesMatchOverrides() {
+ final Map<Type, Class<? extends OMClientRequest>> postExecuteRequests =
Map.of(
+ Type.RecoverLease, OMRecoverLeaseRequest.class);
+ final Set<Class<? extends OMClientRequest>> overriding = new Reflections(
+ new ConfigurationBuilder()
+ .setUrls(ClasspathHelper.forClass(OMClientRequest.class))
+ .setScanners(Scanners.SubTypes))
+ .getSubTypesOf(OMClientRequest.class)
+ .stream()
+ .filter(c -> !Modifier.isAbstract(c.getModifiers()) &&
overridesPostExecute(c))
+ .collect(Collectors.toSet());
+
+ assertEquals(
+ new HashSet<>(postExecuteRequests.values()), overriding,
+ "A request overriding postExecute must have its type in
OMExecutionFlow.POST_EXECUTE_CMD_TYPES and this test");
+ for (Type cmdType : Type.values()) {
+ assertEquals(postExecuteRequests.containsKey(cmdType),
OMExecutionFlow.hasPostExecute(cmdType), cmdType::name);
+ }
+ }
+
+ @Test
+ void postExecuteSkipsRequestCreationForTypesWithoutOverride() {
+ final OzoneManager ozoneManager = mock(OzoneManager.class);
+ final OMRequest request = OMRequest.newBuilder()
+ .setCmdType(Type.DeleteKey)
+ .setClientId("client-id")
+ .setDeleteKeyRequest(
+ DeleteKeyRequest.newBuilder()
+ .setKeyArgs(
+ KeyArgs.newBuilder()
+ .setVolumeName("volume")
+ .setBucketName("bucket")
+ .setKeyName("key")))
+ .build();
+ final OMResponse cached = successResponse();
+
+ assertSame(cached, new OMExecutionFlow(ozoneManager).postExecute(request,
cached));
+ verify(ozoneManager, never()).getMetadataManager();
+ }
+
+ private static boolean overridesPostExecute(Class<? extends OMClientRequest>
requestClass) {
+ try {
+ return requestClass.getMethod(
+ "postExecute", OzoneManager.class,
OMResponse.class).getDeclaringClass() != OMClientRequest.class;
+ } catch (NoSuchMethodException e) {
+ throw new IllegalStateException(e);
+ }
+ }
+
private static Server.Call createCall(UserGroupInformation user, InetAddress
remoteAddress) {
return new Server.Call(1, 0, null, null, RPC.RpcKind.RPC_PROTOCOL_BUFFER,
new byte[0]) {
@Override
diff --git
a/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/request/OMRequestTestUtils.java
b/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/request/OMRequestTestUtils.java
index b0b50bc16f0..ca9e6f317ef 100644
---
a/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/request/OMRequestTestUtils.java
+++
b/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/request/OMRequestTestUtils.java
@@ -33,6 +33,7 @@
import java.util.List;
import java.util.Map;
import java.util.UUID;
+import java.util.function.Predicate;
import java.util.stream.Collectors;
import javax.xml.bind.DatatypeConverter;
import org.apache.commons.lang3.RandomStringUtils;
@@ -605,6 +606,12 @@ public static OmKeyInfo.Builder createOmKeyInfo(String
volumeName, String bucket
new OmKeyLocationInfoGroup(0L, new ArrayList<>(), false));
}
+ // Returns for each block of the first version of the key info whether it
has the given property.
+ public static List<Boolean> blocksWith(KeyInfo keyInfo,
Predicate<KeyLocation> property) {
+ return keyInfo.getKeyLocationList(0).getKeyLocationsList().stream()
+ .map(property::test).collect(Collectors.toList());
+ }
+
/**
* Create OmDirectoryInfo.
*/
diff --git
a/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/request/file/TestOMRecoverLeaseRequest.java
b/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/request/file/TestOMRecoverLeaseRequest.java
index 5807b414ded..c46b0ef95c4 100644
---
a/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/request/file/TestOMRecoverLeaseRequest.java
+++
b/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/request/file/TestOMRecoverLeaseRequest.java
@@ -18,12 +18,20 @@
package org.apache.hadoop.ozone.om.request.file;
import static
org.apache.hadoop.ozone.om.protocolPB.OzoneManagerProtocolClientSideTranslatorPB.setReplicationConfig;
+import static org.apache.hadoop.ozone.om.request.OMRequestTestUtils.blocksWith;
+import static org.apache.hadoop.security.UserGroupInformation.createRemoteUser;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
import jakarta.annotation.Nonnull;
import java.io.IOException;
@@ -34,6 +42,8 @@
import java.util.stream.Collectors;
import org.apache.hadoop.hdds.client.RatisReplicationConfig;
import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
+import org.apache.hadoop.ipc_.ExternalCall;
+import org.apache.hadoop.ipc_.Server;
import org.apache.hadoop.ozone.ClientVersion;
import org.apache.hadoop.ozone.OzoneConfigKeys;
import org.apache.hadoop.ozone.OzoneConsts;
@@ -66,6 +76,8 @@
import
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.RecoverLeaseResponse;
import org.apache.hadoop.ozone.security.acl.IAccessAuthorizer;
import org.apache.hadoop.ozone.security.acl.OzoneObj;
+import org.apache.hadoop.security.UserGroupInformation;
+import org.apache.hadoop.security.token.Token;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
@@ -187,6 +199,82 @@ public void testCommitStageNotIdempotent() throws
Exception {
assertEquals(OzoneManagerProtocolProtos.Status.KEY_ALREADY_CLOSED,
omResponse.getStatus());
}
+ /**
+ * Verify that applying a RecoverLease request does not ask SCM for
pipelines. The leader adds them to the
+ * reply afterward, for the last block of the file and the last two blocks
of the open file.
+ */
+ @Test
+ public void testPipelinesAreAddedAfterApply() throws Exception {
+ populateNamespace(true, true, true, true);
+
+ final OMResponse applied = validateAndUpdateCache().getOMResponse();
+ assertEquals(OzoneManagerProtocolProtos.Status.OK, applied.getStatus());
+ verify(scmContainerLocationProtocol,
never()).getContainerWithPipeline(anyLong());
+ assertThat(blocksWith(applied.getRecoverLeaseResponse().getKeyInfo(),
KeyLocation::hasPipeline))
+ .containsOnly(false);
+ assertThat(blocksWith(applied.getRecoverLeaseResponse().getOpenKeyInfo(),
KeyLocation::hasPipeline))
+ .containsOnly(false);
+
+ final OMRecoverLeaseRequest request = getOmRecoverLeaseRequest(
+ createRecoverLeaseRequest(volumeName, bucketName, keyName,
forceRecovery));
+ final RecoverLeaseResponse reply = request.postExecute(ozoneManager,
applied).getRecoverLeaseResponse();
+ assertThat(blocksWith(reply.getKeyInfo(),
KeyLocation::hasPipeline)).containsExactly(false, false, true);
+ assertThat(blocksWith(reply.getOpenKeyInfo(),
KeyLocation::hasPipeline)).containsExactly(false, true, true);
+ }
+
+ /**
+ * Verify that block tokens are not generated while applying a RecoverLease
request, and that the leader issues
+ * them to the calling user afterward, for the same blocks that get a
pipeline.
+ */
+ @Test
+ public void testBlockTokensAreAddedAfterApplyForCallingUser() throws
Exception {
+ populateNamespace(true, true, true, true);
+ when(ozoneManager.isGrpcBlockTokenEnabled()).thenReturn(true);
+ when(ozoneBlockTokenSecretManager.generateToken(any(), any(), any(),
anyLong())).thenReturn(new Token<>());
+
+ final OMResponse applied = validateAndUpdateCache().getOMResponse();
+ verify(ozoneBlockTokenSecretManager, never()).generateToken(any(), any(),
any(), anyLong());
+ assertThat(blocksWith(applied.getRecoverLeaseResponse().getKeyInfo(),
KeyLocation::hasToken))
+ .containsOnly(false);
+ assertThat(blocksWith(applied.getRecoverLeaseResponse().getOpenKeyInfo(),
KeyLocation::hasToken))
+ .containsOnly(false);
+
+ Server.getCurCall().set(new RpcCallerStub(createRemoteUser("alice")));
+ try {
+ final OMRecoverLeaseRequest request = getOmRecoverLeaseRequest(
+ createRecoverLeaseRequest(volumeName, bucketName, keyName,
forceRecovery));
+ final RecoverLeaseResponse reply = request.postExecute(ozoneManager,
applied).getRecoverLeaseResponse();
+ assertThat(blocksWith(reply.getKeyInfo(),
KeyLocation::hasToken)).containsExactly(false, false, true);
+ assertThat(blocksWith(reply.getOpenKeyInfo(),
KeyLocation::hasToken)).containsExactly(false, true, true);
+ final ArgumentCaptor<String> tokenUser =
ArgumentCaptor.forClass(String.class);
+ verify(ozoneBlockTokenSecretManager,
times(3)).generateToken(tokenUser.capture(), any(), any(), anyLong());
+ assertThat(tokenUser.getAllValues()).containsOnly("alice");
+ } finally {
+ Server.getCurCall().remove();
+ }
+ }
+
+ /**
+ * Verify that a RecoverLease request is applied when SCM cannot be reached,
and that only the reply fails.
+ */
+ @Test
+ public void testScmFailureDoesNotFailApply() throws Exception {
+ populateNamespace(true, true, true, true);
+ when(scmContainerLocationProtocol.getContainerWithPipeline(anyLong()))
+ .thenThrow(new IOException("SCM is not reachable"));
+
+ final OMResponse applied = validateAndUpdateCache().getOMResponse();
+ assertEquals(OzoneManagerProtocolProtos.Status.OK, applied.getStatus());
+
assertThat(omMetadataManager.getOpenKeyTable(getBucketLayout()).get(getOpenFileName()).getMetadata())
+ .containsKey(OzoneConsts.LEASE_RECOVERY);
+
+ final OMRecoverLeaseRequest request = getOmRecoverLeaseRequest(
+ createRecoverLeaseRequest(volumeName, bucketName, keyName,
forceRecovery));
+ final OMException e = assertThrows(OMException.class, () ->
request.postExecute(ozoneManager, applied));
+ assertEquals(OMException.ResultCodes.SCM_GET_PIPELINE_EXCEPTION,
e.getResult());
+ assertEquals("SCM is not reachable", e.getMessage());
+ }
+
/**
* Verify that RecoverLease COMMIT request has a new file length.
* @throws Exception
@@ -642,4 +730,18 @@ bucketName, keyName, replicationConfig, new
OmKeyLocationInfoGroup(version, new
omKeyInfo.getFileName());
}
+ private static final class RpcCallerStub extends ExternalCall<String> {
+ private final UserGroupInformation remoteUser;
+
+ RpcCallerStub(UserGroupInformation remoteUser) {
+ super(null);
+ this.remoteUser = remoteUser;
+ }
+
+ @Override
+ public UserGroupInformation getRemoteUser() {
+ return remoteUser;
+ }
+ }
+
}
diff --git
a/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/response/TestS3DerivedKey.java
b/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/response/TestS3DerivedKey.java
index 5d44eb47b44..ddee72359a8 100644
---
a/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/response/TestS3DerivedKey.java
+++
b/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/response/TestS3DerivedKey.java
@@ -94,6 +94,7 @@ void setup() throws Exception {
when(secrets.getSecretString(ACCESS_ID)).thenReturn(SECRET);
translator = new OzoneManagerProtocolServerSideTranslatorPB(om, ratis,
mock(ProtocolMessageMetrics.class));
when(execution.submit(any(),
anyBoolean())).thenReturn(response(Status.OK));
+ when(execution.postExecute(any(), any())).thenAnswer(i ->
i.getArgument(1));
}
@AfterEach
diff --git
a/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/protocolPB/TestRecoverLeaseBlockInfo.java
b/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/protocolPB/TestRecoverLeaseBlockInfo.java
new file mode 100644
index 00000000000..ec4fcf93f97
--- /dev/null
+++
b/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/protocolPB/TestRecoverLeaseBlockInfo.java
@@ -0,0 +1,235 @@
+/*
+ * 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.protocolPB;
+
+import static org.apache.hadoop.ozone.om.request.OMRequestTestUtils.blocksWith;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.io.IOException;
+import java.util.List;
+import org.apache.hadoop.hdds.client.RatisReplicationConfig;
+import org.apache.hadoop.hdds.conf.OzoneConfiguration;
+import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
+import org.apache.hadoop.hdds.protocol.proto.HddsProtos.ReplicationFactor;
+import
org.apache.hadoop.hdds.scm.container.common.helpers.ContainerWithPipeline;
+import org.apache.hadoop.hdds.scm.pipeline.MockPipeline;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import
org.apache.hadoop.hdds.scm.protocol.StorageContainerLocationInternalInterface;
+import org.apache.hadoop.hdds.utils.ProtocolMessageMetrics;
+import org.apache.hadoop.hdds.utils.db.InMemoryTestTable;
+import org.apache.hadoop.ozone.ClientVersion;
+import org.apache.hadoop.ozone.om.OMMetadataManager;
+import org.apache.hadoop.ozone.om.OMPerformanceMetrics;
+import org.apache.hadoop.ozone.om.OzoneManager;
+import org.apache.hadoop.ozone.om.ScmClient;
+import org.apache.hadoop.ozone.om.execution.OMExecutionFlow;
+import org.apache.hadoop.ozone.om.helpers.BucketLayout;
+import org.apache.hadoop.ozone.om.helpers.OmBucketInfo;
+import org.apache.hadoop.ozone.om.helpers.OmKeyLocationInfo;
+import org.apache.hadoop.ozone.om.helpers.OmKeyLocationInfoGroup;
+import org.apache.hadoop.ozone.om.ratis.OzoneManagerRatisServer;
+import org.apache.hadoop.ozone.om.request.OMRequestTestUtils;
+import org.apache.hadoop.ozone.om.upgrade.OMVersionManager;
+import org.apache.hadoop.ozone.om.upgrade.OMVersionManagerTestUtils;
+import
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.KeyInfo;
+import
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.KeyLocation;
+import
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.OMLockDetailsProto;
+import
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.OMRequest;
+import
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.OMResponse;
+import
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.RecoverLeaseRequest;
+import
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.RecoverLeaseResponse;
+import
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.Status;
+import org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.Type;
+import org.apache.hadoop.ozone.util.ConcurrentMutableRate;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+/**
+ * Tests that the leader adds pipelines to the RecoverLease reply after the
request has been applied.
+ */
+class TestRecoverLeaseBlockInfo {
+ private final OzoneManager om = mock(OzoneManager.class);
+ private final OzoneManagerRatisServer ratis =
mock(OzoneManagerRatisServer.class);
+ private final StorageContainerLocationInternalInterface containerClient =
+ mock(StorageContainerLocationInternalInterface.class);
+ private OzoneManagerProtocolServerSideTranslatorPB translator;
+
+ @BeforeEach
+ void setup() throws Exception {
+ final ScmClient scmClient = mock(ScmClient.class);
+ when(scmClient.getContainerClient()).thenReturn(containerClient);
+ final Pipeline pipeline = MockPipeline.createSingleNodePipeline();
+ final ContainerWithPipeline containerWithPipeline =
mock(ContainerWithPipeline.class);
+ when(containerWithPipeline.getPipeline()).thenReturn(pipeline);
+
when(containerClient.getContainerWithPipeline(anyLong())).thenReturn(containerWithPipeline);
+
+ final OMMetadataManager metadataManager = mock(OMMetadataManager.class);
+ final InMemoryTestTable<String, OmBucketInfo> bucketTable = new
InMemoryTestTable<>();
+ bucketTable.put(
+ "/volume/bucket", OmBucketInfo.newBuilder()
+ .setVolumeName("volume")
+ .setBucketName("bucket")
+ .setBucketLayout(BucketLayout.FILE_SYSTEM_OPTIMIZED)
+ .build());
+ when(metadataManager.getBucketKey(any(), any())).thenAnswer(i -> "/" +
i.getArgument(0) + "/" + i.getArgument(1));
+ when(metadataManager.getBucketTable()).thenReturn(bucketTable);
+ when(metadataManager.getVolumeKey(any())).thenAnswer(i -> "/" +
i.getArgument(0));
+ when(metadataManager.getVolumeTable()).thenReturn(new
InMemoryTestTable<>());
+
+ final OMPerformanceMetrics perfMetrics = mock(OMPerformanceMetrics.class);
+
when(perfMetrics.getPreExecuteLatencyNs()).thenReturn(mock(ConcurrentMutableRate.class));
+
+ when(om.getConfiguration()).thenReturn(new OzoneConfiguration());
+ final OMVersionManager versionManager =
OMVersionManagerTestUtils.mockFinalizedOmVersionManager();
+ when(om.getVersionManager()).thenReturn(versionManager);
+ when(om.getMetadataManager()).thenReturn(metadataManager);
+ when(om.getPerfMetrics()).thenReturn(perfMetrics);
+ when(om.getOmRatisServer()).thenReturn(ratis);
+ final OMExecutionFlow executionFlow = new OMExecutionFlow(om);
+ when(om.getOmExecutionFlow()).thenReturn(executionFlow);
+ when(om.getScmClient()).thenReturn(scmClient);
+ when(om.isGrpcBlockTokenEnabled()).thenReturn(false);
+ translator = new OzoneManagerProtocolServerSideTranslatorPB(om, ratis,
mock(ProtocolMessageMetrics.class));
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void testAddsPipelinesToSuccessfulResponse(boolean cacheHit) throws
Exception {
+ final OMResponse applied = appliedResponse();
+ when(ratis.checkRetryCache()).thenReturn(cacheHit ? applied : null);
+ when(ratis.submitRequest(any(), anyBoolean())).thenReturn(applied);
+
+ final OMResponse result = translator.processRequest(request());
+
+ assertThat(result.getStatus()).isEqualTo(Status.OK);
+ assertThat(blocksWith(result.getRecoverLeaseResponse().getKeyInfo(),
KeyLocation::hasPipeline))
+ .containsExactly(true);
+ assertThat(blocksWith(result.getRecoverLeaseResponse().getOpenKeyInfo(),
KeyLocation::hasPipeline))
+ .containsExactly(true);
+ verify(containerClient, times(2)).getContainerWithPipeline(anyLong());
+ if (cacheHit) {
+ // A retried request gets pipelines too: the reply cached by Ratis does
not contain them.
+ verify(ratis, never()).submitRequest(any(), anyBoolean());
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void testDoesNotAddPipelinesToFailedResponse(boolean cacheHit) throws
Exception {
+ final OMResponse failed =
OMResponse.newBuilder().setCmdType(Type.RecoverLease)
+ .setStatus(Status.KEY_NOT_FOUND).setSuccess(false)
+ .setRecoverLeaseResponse(RecoverLeaseResponse.newBuilder()).build();
+ when(ratis.checkRetryCache()).thenReturn(cacheHit ? failed : null);
+ when(ratis.submitRequest(any(), anyBoolean())).thenReturn(failed);
+
+ final OMResponse result = translator.processRequest(request());
+
+ assertThat(result).isEqualTo(failed);
+ verify(containerClient, never()).getContainerWithPipeline(anyLong());
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void testReturnsErrorWhenScmFails(boolean cacheHit) throws Exception {
+ final OMLockDetailsProto lockDetails =
OMLockDetailsProto.newBuilder().setWriteLockNanos(10).build();
+ final OMResponse applied =
appliedResponse().toBuilder().setOmLockDetails(lockDetails).build();
+ when(ratis.checkRetryCache()).thenReturn(cacheHit ? applied : null);
+ when(ratis.submitRequest(any(), anyBoolean())).thenReturn(applied);
+ when(containerClient.getContainerWithPipeline(anyLong())).thenThrow(new
IOException("SCM is not reachable"));
+
+ final OMResponse result = translator.processRequest(request());
+
+ assertThat(result.getSuccess()).isFalse();
+
assertThat(result.getStatus()).isEqualTo(Status.SCM_GET_PIPELINE_EXCEPTION);
+ assertThat(result.getMessage()).isEqualTo("SCM is not reachable");
+ assertThat(result.getOmLockDetails()).isEqualTo(lockDetails);
+ }
+
+ @Test
+ void testCachedWriteSucceedsAfterBucketDeleted() throws Exception {
+ final OMResponse cached = appliedResponse();
+ when(ratis.checkRetryCache()).thenReturn(cached);
+
+ final OMResponse result =
translator.processRequest(request("deleted-bucket"));
+
+ assertThat(result).isEqualTo(cached);
+ verify(ratis, never()).submitRequest(any(), anyBoolean());
+ verify(containerClient, never()).getContainerWithPipeline(anyLong());
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void testIgnoresResponseWithoutRecoverLeaseKeyInfo(boolean
hasEmptyRecoverLeaseResponse) throws Exception {
+ final OMResponse.Builder builder = OMResponse.newBuilder()
+ .setCmdType(Type.RecoverLease)
+ .setStatus(Status.OK)
+ .setSuccess(true);
+ if (hasEmptyRecoverLeaseResponse) {
+ builder.setRecoverLeaseResponse(RecoverLeaseResponse.newBuilder());
+ }
+ final OMResponse cached = builder.build();
+ when(ratis.checkRetryCache()).thenReturn(cached);
+
+ final OMResponse result = translator.processRequest(request());
+
+ assertThat(result).isEqualTo(cached);
+ verify(containerClient, never()).getContainerWithPipeline(anyLong());
+ }
+
+ private static OMRequest request() {
+ return request("bucket");
+ }
+
+ private static OMRequest request(String bucketName) {
+ return
OMRequest.newBuilder().setCmdType(Type.RecoverLease).setClientId("client")
+ .setRecoverLeaseRequest(RecoverLeaseRequest.newBuilder()
+
.setVolumeName("volume").setBucketName(bucketName).setKeyName("key"))
+ .build();
+ }
+
+ /** The reply of a successfully applied request: one block per key info,
without a pipeline. */
+ private static OMResponse appliedResponse() {
+ return
OMResponse.newBuilder().setCmdType(Type.RecoverLease).setStatus(Status.OK).setSuccess(true)
+ .setRecoverLeaseResponse(RecoverLeaseResponse.newBuilder()
+ .setKeyInfo(keyInfoWithOneBlock(1000L))
+ .setOpenKeyInfo(keyInfoWithOneBlock(1001L)))
+ .build();
+ }
+
+ private static KeyInfo keyInfoWithOneBlock(long containerID) {
+ final KeyLocation block = KeyLocation.newBuilder()
+ .setBlockID(HddsProtos.BlockID.newBuilder()
+ .setContainerBlockID(HddsProtos.ContainerBlockID.newBuilder()
+ .setContainerID(containerID).setLocalID(100L)))
+ .setOffset(0).setLength(200).setCreateVersion(0L).build();
+ return OMRequestTestUtils.createOmKeyInfo("volume", "bucket", "key",
+ RatisReplicationConfig.getInstance(ReplicationFactor.ONE),
+ new OmKeyLocationInfoGroup(0L,
List.of(OmKeyLocationInfo.getFromProtobuf(block)), false)).build()
+ .getNetworkProtobuf(ClientVersion.CURRENT, true);
+ }
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]