This is an automated email from the ASF dual-hosted git repository.
devmadhuu pushed a commit to branch HDDS-11233
in repository https://gitbox.apache.org/repos/asf/ozone.git
The following commit(s) were added to refs/heads/HDDS-11233 by this push:
new 8a18345bba8 HDDS-16991. Support Create File with Storage Policy
(#12022)
8a18345bba8 is described below
commit 8a18345bba8c023aea3eaf35250f96e13e22b778
Author: Anurag Parvatikar <[email protected]>
AuthorDate: Thu Nov 26 16:54:29 2026 +0530
HDDS-16991. Support Create File with Storage Policy (#12022)
---
.../ozone/client/protocol/CreateFileOptions.java | 19 ++-
.../apache/hadoop/ozone/client/rpc/RpcClient.java | 5 +
.../hadoop/ozone/client/rpc/TestRpcClient.java | 86 +++++++++++
...OzoneManagerProtocolClientSideTranslatorPB.java | 3 +
.../ozone/client/rpc/TestOzoneStoragePolicy.java | 148 ++++++++++++++++++-
.../ozone/om/TestOMFileStoragePolicyUpgrade.java | 164 +++++++++++++++++++++
.../ozone/om/request/file/OMFileCreateRequest.java | 29 +++-
.../om/request/file/TestOMFileCreateRequest.java | 122 +++++++++++++++
8 files changed, 566 insertions(+), 10 deletions(-)
diff --git
a/hadoop-ozone/client/src/main/java/org/apache/hadoop/ozone/client/protocol/CreateFileOptions.java
b/hadoop-ozone/client/src/main/java/org/apache/hadoop/ozone/client/protocol/CreateFileOptions.java
index aeef8709961..bcf9b1b65c8 100644
---
a/hadoop-ozone/client/src/main/java/org/apache/hadoop/ozone/client/protocol/CreateFileOptions.java
+++
b/hadoop-ozone/client/src/main/java/org/apache/hadoop/ozone/client/protocol/CreateFileOptions.java
@@ -17,7 +17,9 @@
package org.apache.hadoop.ozone.client.protocol;
+import jakarta.annotation.Nullable;
import org.apache.hadoop.hdds.client.ReplicationConfig;
+import org.apache.hadoop.hdds.client.StoragePolicy;
/**
* Options for {@link ClientProtocol#createFile(String, String, String,
CreateFileOptions)}.
@@ -29,12 +31,14 @@ public final class CreateFileOptions {
private final ReplicationConfig replicationConfig;
private final boolean overWrite;
private final boolean recursive;
+ private final StoragePolicy storagePolicy;
private CreateFileOptions(Builder b) {
this.size = b.size;
this.replicationConfig = b.replicationConfig;
this.overWrite = b.overWrite;
this.recursive = b.recursive;
+ this.storagePolicy = b.storagePolicy;
}
public static Builder builder() {
@@ -61,12 +65,19 @@ public boolean isRecursive() {
return recursive;
}
+ /** @return the storage policy of the file, or null to inherit the bucket's.
*/
+ @Nullable
+ public StoragePolicy getStoragePolicy() {
+ return storagePolicy;
+ }
+
@Override
public String toString() {
return "CreateFileOptions{size=" + size
+ ", replicationConfig=" + replicationConfig
+ ", overWrite=" + overWrite
- + ", recursive=" + recursive + "}";
+ + ", recursive=" + recursive
+ + ", storagePolicy=" + storagePolicy + "}";
}
/**
@@ -77,6 +88,7 @@ public static final class Builder {
private ReplicationConfig replicationConfig;
private boolean overWrite;
private boolean recursive;
+ private StoragePolicy storagePolicy;
public Builder setSize(long size) {
this.size = size;
@@ -98,6 +110,11 @@ public Builder setRecursive(boolean recursive) {
return this;
}
+ public Builder setStoragePolicy(@Nullable StoragePolicy storagePolicy) {
+ this.storagePolicy = storagePolicy;
+ return this;
+ }
+
public CreateFileOptions build() {
return new CreateFileOptions(this);
}
diff --git
a/hadoop-ozone/client/src/main/java/org/apache/hadoop/ozone/client/rpc/RpcClient.java
b/hadoop-ozone/client/src/main/java/org/apache/hadoop/ozone/client/rpc/RpcClient.java
index 2fe93125dc4..4cea61a4ebe 100644
---
a/hadoop-ozone/client/src/main/java/org/apache/hadoop/ozone/client/rpc/RpcClient.java
+++
b/hadoop-ozone/client/src/main/java/org/apache/hadoop/ozone/client/rpc/RpcClient.java
@@ -2721,6 +2721,7 @@ public OzoneOutputStream createFile(String volumeName,
String bucketName,
String keyName, CreateFileOptions options) throws IOException {
Objects.requireNonNull(options, "options == null");
final ReplicationConfig replicationConfig = options.getReplicationConfig();
+ final StoragePolicy storagePolicy = options.getStoragePolicy();
if
(!OzoneManagerVersion.ERASURE_CODED_STORAGE_SUPPORT.isSupportedBy(getOmVersion()))
{
if (replicationConfig != null &&
replicationConfig.getReplicationType()
@@ -2730,6 +2731,9 @@ public OzoneOutputStream createFile(String volumeName,
String bucketName,
+ " Erasure Coded replication.");
}
}
+ if (storagePolicy != null) {
+ checkStoragePolicySupported();
+ }
String ownerName = getRealUserInfo().getShortUserName();
OmKeyArgs keyArgs = new OmKeyArgs.Builder()
.setVolumeName(volumeName)
@@ -2739,6 +2743,7 @@ public OzoneOutputStream createFile(String volumeName,
String bucketName,
.setReplicationConfig(replicationConfig)
.setLatestVersionLocation(getLatestVersionLocation)
.setOwnerName(ownerName)
+ .setStoragePolicy(storagePolicy)
.build();
OpenKeySession keySession =
ozoneManagerClient.createFile(keyArgs, options.isOverWrite(),
options.isRecursive());
diff --git
a/hadoop-ozone/client/src/test/java/org/apache/hadoop/ozone/client/rpc/TestRpcClient.java
b/hadoop-ozone/client/src/test/java/org/apache/hadoop/ozone/client/rpc/TestRpcClient.java
index a8824e35477..5d8fa838b6a 100644
---
a/hadoop-ozone/client/src/test/java/org/apache/hadoop/ozone/client/rpc/TestRpcClient.java
+++
b/hadoop-ozone/client/src/test/java/org/apache/hadoop/ozone/client/rpc/TestRpcClient.java
@@ -82,6 +82,7 @@
import org.apache.hadoop.ozone.om.protocolPB.OzoneManagerClientProtocol;
import org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos;
import
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.BucketInfo;
+import
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.CreateFileRequest;
import
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.CreateKeyRequest;
import
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.KeyArgs;
import
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.OMRequest;
@@ -1253,6 +1254,37 @@ public OMResponse submitRequest(OMRequest request)
throws IOException {
}
}
+ /**
+ * A single CreateFileOptions carrying a storage policy and every other
option must send all of them to the OM.
+ */
+ @Test
+ void testCreateFileOptionsMappedToRequest() throws IOException {
+ AtomicReference<CreateFileRequest> captured = new AtomicReference<>();
+ OmTransport transport =
transportWithOmVersion(OzoneManagerVersion.STORAGE_POLICY_SUPPORT,
Type.CreateFile,
+ request -> captured.set(request.getCreateFileRequest()));
+ RpcClient client = createRpcClient(transport);
+ try {
+ CreateFileOptions options = CreateFileOptions.builder()
+ .setSize(1024L)
+
.setReplicationConfig(RatisReplicationConfig.getInstance(HddsProtos.ReplicationFactor.ONE))
+ .setOverWrite(true)
+ .setRecursive(true)
+ .setStoragePolicy(OzoneStoragePolicy.HOT)
+ .build();
+
+ assertThatThrownBy(() -> client.createFile("volume", "bucket", "key",
options))
+ .isInstanceOf(IOException.class)
+ .hasMessage("captured");
+ assertThat(captured.get()).isNotNull();
+ assertThat(captured.get().getIsOverwrite()).isTrue();
+ assertThat(captured.get().getIsRecursive()).isTrue();
+ assertThat(captured.get().getKeyArgs().getDataSize()).isEqualTo(1024L);
+
assertThat(captured.get().getKeyArgs().getStoragePolicy()).isEqualTo(HddsProtos.StoragePolicyProto.HOT);
+ } finally {
+ client.close();
+ }
+ }
+
@Test
public void testCreateKeyRejectsNullOptions() throws IOException {
RpcClient client = createRpcClient();
@@ -1406,6 +1438,40 @@ public OMResponse submitRequest(OMRequest request)
throws IOException {
});
}
+ /**
+ * A storage policy is sent only to an OM that supports it, and a request
without one is never rejected.
+ */
+ @ParameterizedTest
+ @EnumSource(value = OzoneManagerVersion.class, mode =
EnumSource.Mode.EXCLUDE, names = "UNKNOWN_VERSION")
+ public void
testCreateFileWithStoragePolicyRequiresSupportedOmVersion(OzoneManagerVersion
version)
+ throws IOException {
+ List<KeyArgs> requests = new ArrayList<>();
+ OmTransport transport = transportWithOmVersion(version, Type.CreateFile,
+ request -> requests.add(request.getCreateFileRequest().getKeyArgs()));
+ RpcClient client = createRpcClient(transport);
+ try {
+ ReplicationConfig replication =
RatisReplicationConfig.getInstance(HddsProtos.ReplicationFactor.THREE);
+ CreateFileOptions.Builder options =
CreateFileOptions.builder().setSize(1L).setReplicationConfig(replication);
+ IOException withoutPolicyError = assertThrows(IOException.class,
+ () -> client.createFile("vol", "bucket", "key",
options.setStoragePolicy(null).build()));
+ IOException withPolicyError = assertThrows(IOException.class,
+ () -> client.createFile("vol", "bucket", "key",
options.setStoragePolicy(OzoneStoragePolicy.COLD).build()));
+
+ assertThat(withoutPolicyError).hasMessage("captured");
+ assertThat(requests.get(0).hasStoragePolicy()).isFalse();
+ if (OzoneManagerVersion.STORAGE_POLICY_SUPPORT.isSupportedBy(version)) {
+ assertThat(withPolicyError).hasMessage("captured");
+ assertThat(requests).hasSize(2);
+
assertThat(requests.get(1).getStoragePolicy()).isEqualTo(OzoneStoragePolicy.toProto(OzoneStoragePolicy.COLD));
+ } else {
+ assertThat(withPolicyError).hasMessage("OzoneManager does not support
storage policy");
+ assertThat(requests).hasSize(1);
+ }
+ } finally {
+ client.close();
+ }
+ }
+
/**
* A storage policy field is sent only to an OM that supports it, and a
request without one is never rejected.
*/
@@ -1445,6 +1511,26 @@ public void
testCreateBucketWithStoragePolicyRequiresSupportedOmVersion(OzoneMan
}
}
+ /**
+ * The client never picks a storage policy for the caller: the OM resolves
it from the bucket.
+ */
+ @Test
+ public void testCreateFileWithoutStoragePolicyDoesNotSendOne() throws
IOException {
+ List<KeyArgs> requests = new ArrayList<>();
+ OmTransport transport =
transportWithOmVersion(OzoneManagerVersion.SOFTWARE_VERSION, Type.CreateFile,
+ request -> requests.add(request.getCreateFileRequest().getKeyArgs()));
+ RpcClient client = createRpcClient(transport);
+ try {
+ ReplicationConfig replication =
RatisReplicationConfig.getInstance(HddsProtos.ReplicationFactor.THREE);
+ assertThrows(IOException.class, () -> client.createFile("vol", "bucket",
"key", 1L, replication, false, false));
+
+ assertThat(requests).hasSize(1);
+ assertThat(requests.get(0).hasStoragePolicy()).isFalse();
+ } finally {
+ client.close();
+ }
+ }
+
/**
* Setting a storage policy needs an OM that supports it, whatever the
arguments are. This includes
* arguments that carry no storage policy field, since the method is a
public storage policy API.
diff --git
a/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/protocolPB/OzoneManagerProtocolClientSideTranslatorPB.java
b/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/protocolPB/OzoneManagerProtocolClientSideTranslatorPB.java
index 1f86338b724..273cfcc8b1f 100644
---
a/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/protocolPB/OzoneManagerProtocolClientSideTranslatorPB.java
+++
b/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/protocolPB/OzoneManagerProtocolClientSideTranslatorPB.java
@@ -2680,6 +2680,9 @@ public OpenKeySession createFile(OmKeyArgs args,
}
keyArgsBuilder.setType(args.getReplicationConfig().getReplicationType());
}
+ if (args.getStoragePolicy() != null) {
+
keyArgsBuilder.setStoragePolicy(OzoneStoragePolicy.toProto(args.getStoragePolicy()));
+ }
CreateFileRequest createFileRequest = CreateFileRequest.newBuilder()
.setKeyArgs(keyArgsBuilder.build())
.setIsOverwrite(overWrite)
diff --git
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/client/rpc/TestOzoneStoragePolicy.java
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/client/rpc/TestOzoneStoragePolicy.java
index 2c9c633b034..1e3de26c698 100644
---
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/client/rpc/TestOzoneStoragePolicy.java
+++
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/client/rpc/TestOzoneStoragePolicy.java
@@ -77,6 +77,7 @@
import org.apache.hadoop.ozone.client.OzoneKeyDetails;
import org.apache.hadoop.ozone.client.OzoneKeyLocation;
import org.apache.hadoop.ozone.client.io.OzoneOutputStream;
+import org.apache.hadoop.ozone.client.protocol.CreateFileOptions;
import org.apache.hadoop.ozone.client.protocol.CreateKeyOptions;
import org.apache.hadoop.ozone.client.protocol.MultipartUploadOptions;
import org.apache.hadoop.ozone.container.common.impl.ContainerData;
@@ -112,6 +113,9 @@ public class TestOzoneStoragePolicy {
private static final ReplicationConfig RATIS_THREE =
RatisReplicationConfig.getInstance(HddsProtos.ReplicationFactor.THREE);
+ private static final List<BucketLayout> FILE_BUCKET_LAYOUTS =
+ Arrays.asList(BucketLayout.FILE_SYSTEM_OPTIMIZED, BucketLayout.LEGACY);
+
private MiniOzoneCluster cluster;
private OzoneClient ozClient;
private ObjectStore store;
@@ -220,6 +224,90 @@ public void testKeyWithoutAnyPolicyUsesClusterDefault()
throws Exception {
OzoneStoragePolicy.getDefaultPolicy().getCreationTier());
}
+ /**
+ * Creating a file with a storage policy works for every file bucket layout.
All
+ * layouts share one cluster, because the scenarios differ only in the bucket
+ * they use.
+ */
+ @Test
+ public void testCreateFileWithStoragePolicy() throws Exception {
+ startCluster(allTierTopology(RATIS_THREE.getRequiredNodes()));
+
+ for (BucketLayout bucketLayout : FILE_BUCKET_LAYOUTS) {
+ assertFileStoragePolicyIsHonoured(bucketLayout);
+ assertFileInheritsBucketPolicyOrClusterDefault(bucketLayout);
+ assertMultiBlockFileAndOverwriteHonourPolicy(bucketLayout);
+ }
+ }
+
+ /**
+ * A file created with an explicit storage policy records that policy and
lands
+ * on the policy's creation tier, in SCM and on the datanodes.
+ */
+ private void assertFileStoragePolicyIsHonoured(BucketLayout bucketLayout)
+ throws IOException {
+ for (OzoneStoragePolicy storagePolicy : OzoneStoragePolicy.values()) {
+ OzoneBucket bucket = createBucket(null, bucketLayout);
+ OmKeyInfo keyInfo = createFileAndLookup(bucket, storagePolicy);
+
+ assertKeyInfo(keyInfo, storagePolicy);
+ assertScmContainerAndPipeline(keyInfo, storagePolicy.getCreationTier());
+ assertDatanodeContainerAndBlock(keyInfo,
storagePolicy.getCreationTier());
+ }
+ }
+
+ /**
+ * A file created without a storage policy inherits the bucket's policy, and
+ * without a bucket policy either it gets the cluster default.
+ */
+ private void assertFileInheritsBucketPolicyOrClusterDefault(BucketLayout
bucketLayout)
+ throws IOException {
+ OzoneStoragePolicy bucketPolicy = OzoneStoragePolicy.COLD;
+ OmKeyInfo inherited = createFileAndLookup(createBucket(bucketPolicy,
bucketLayout), null);
+ assertKeyInfo(inherited, bucketPolicy);
+ assertScmContainerAndPipeline(inherited, bucketPolicy.getCreationTier());
+ assertDatanodeContainerAndBlock(inherited, bucketPolicy.getCreationTier());
+
+ OzoneStoragePolicy defaultPolicy = OzoneStoragePolicy.getDefaultPolicy();
+ OmKeyInfo defaulted = createFileAndLookup(createBucket(null,
bucketLayout), null);
+ assertKeyInfo(defaulted, defaultPolicy);
+ assertScmContainerAndPipeline(defaulted, defaultPolicy.getCreationTier());
+ assertDatanodeContainerAndBlock(defaulted,
defaultPolicy.getCreationTier());
+ }
+
+ /**
+ * Tests two scenarios on a file that spans several blocks.
+ *
+ * <p>Multi-block write: Tests whether a file that needs more blocks than OM
pre-allocates keeps its policy on
+ * every block. Creating the file with size 0 makes OM pre-allocate one
block, so the other blocks come from
+ * allocateBlock calls. Every block, not just the first, must sit on the
COLD tier.
+ *
+ * <p>Overwrite: Overwriting a file with a different storage policy updates
the recorded
+ * policy and moves the new blocks to the new tier.
+ */
+ private void assertMultiBlockFileAndOverwriteHonourPolicy(BucketLayout
bucketLayout)
+ throws IOException {
+ OzoneBucket bucket = createBucket(OzoneStoragePolicy.WARM, bucketLayout);
+ String keyName = UUID.randomUUID().toString();
+
+ writeFile(bucket, keyName, multiBlockData(), 0, false,
OzoneStoragePolicy.COLD);
+ OmKeyInfo original = lookupKey(bucket, keyName);
+ assertThat(original.getStoragePolicy()).as("layout %s",
bucketLayout).isEqualTo(OzoneStoragePolicy.COLD);
+ int numOfBlocks =
original.getLatestVersionLocations().getBlocksLatestVersionOnly().size();
+ assertThat(numOfBlocks)
+ .withFailMessage("Expected more than one block so a later allocation
is exercised, "
+ + "but the file in a %s bucket has %d", bucketLayout, numOfBlocks)
+ .isGreaterThan(1);
+ assertAllBlocksOnTier(original, OzoneStoragePolicy.COLD.getCreationTier());
+ assertAllBlocksOnDatanodes(original,
OzoneStoragePolicy.COLD.getCreationTier());
+
+ writeFile(bucket, keyName, multiBlockData(), 0, true,
OzoneStoragePolicy.HOT);
+ OmKeyInfo overwritten = lookupKey(bucket, keyName);
+ assertThat(overwritten.getStoragePolicy()).as("layout %s",
bucketLayout).isEqualTo(OzoneStoragePolicy.HOT);
+ assertAllBlocksOnTier(overwritten,
OzoneStoragePolicy.HOT.getCreationTier());
+ assertAllBlocksOnDatanodes(overwritten,
OzoneStoragePolicy.HOT.getCreationTier());
+ }
+
/**
* The storage policy survives the round trip to the client on read.
*/
@@ -561,9 +649,8 @@ private void assertBlockOnTier(OmKeyLocationInfo block,
StorageTier expectedTier
}
/**
- * Checks every block of a key landed on a container of the expected tier.
The
- * {@code assertDatanodeContainerAndBlock} helper only inspects the first
block, which cannot
- * catch a tier that changes partway through a key.
+ * Checks every block of a key landed on a container of the expected tier.
This reads SCM's container record
+ * only; to check the datanode volumes, use {@code
assertAllBlocksOnDatanodes}.
*/
private void assertAllBlocksOnTier(OmKeyInfo keyInfo, StorageTier
expectedTier)
throws IOException {
@@ -580,6 +667,19 @@ private void assertAllBlocksOnTier(OmKeyInfo keyInfo,
StorageTier expectedTier)
}
}
+ /**
+ * Checks every block of a key on the datanodes, not just in SCM's records.
Looping is only needed for
+ * a file that spans several blocks; for the single-block files in the other
createFile scenarios, the
+ * one-argument {@code assertDatanodeContainerAndBlock} (block 0) is enough.
+ */
+ private void assertAllBlocksOnDatanodes(OmKeyInfo keyInfo, StorageTier
expectedTier)
+ throws IOException {
+ int blockCount =
keyInfo.getLatestVersionLocations().getBlocksLatestVersionOnly().size();
+ for (int i = 0; i < blockCount; i++) {
+ assertDatanodeContainerAndBlock(keyInfo, i, expectedTier);
+ }
+ }
+
/** Initiates an upload, completes it with two parts and returns the
completed key. */
private OmKeyInfo doMultipartUpload(OzoneBucket bucket, String keyName,
OzoneStoragePolicy storagePolicy) throws Exception {
@@ -682,6 +782,33 @@ private OmKeyInfo createKeyAndLookup(OzoneBucket bucket,
return lookupKey(bucket, keyName);
}
+ private void writeFile(OzoneBucket bucket, String keyName, byte[] data, long
size, boolean overWrite,
+ OzoneStoragePolicy storagePolicy) throws IOException {
+ try (OzoneOutputStream out = bucket.createFile(keyName,
CreateFileOptions.builder()
+ .setSize(size)
+ .setReplicationConfig(RATIS_THREE)
+ .setOverWrite(overWrite)
+ .setStoragePolicy(storagePolicy)
+ .build())) {
+ out.write(data);
+ }
+ }
+
+ private OmKeyInfo createFileAndLookup(OzoneBucket bucket,
+ OzoneStoragePolicy storagePolicy) throws IOException {
+ String keyName = UUID.randomUUID().toString();
+ byte[] data = UUID.randomUUID().toString().getBytes(UTF_8);
+ writeFile(bucket, keyName, data, data.length, false, storagePolicy);
+ return lookupKey(bucket, keyName);
+ }
+
+ /** Data that fills more than two blocks. */
+ private byte[] multiBlockData() {
+ byte[] data = new byte[(int) (2 * ozoneManager.getScmBlockSize() + 1024)];
+ Arrays.fill(data, (byte) 'p');
+ return data;
+ }
+
private OmKeyInfo lookupKey(OzoneBucket bucket, String keyName)
throws IOException {
OmKeyArgs keyArgs = new OmKeyArgs.Builder()
@@ -720,14 +847,21 @@ private void assertScmContainerAndPipeline(OmKeyInfo
keyInfo,
}
/**
- * Checks the block actually landed on a volume of the expected tier, and
that
- * the storage type travelled to the datanode on the block id.
+ * Checks the first block of a key on the datanodes. Meant for single-block
keys; for a key that spans
+ * several blocks, check each block with {@link
#assertDatanodeContainerAndBlock(OmKeyInfo, int, StorageTier)}.
*/
private void assertDatanodeContainerAndBlock(OmKeyInfo keyInfo,
StorageTier expectedTier) throws IOException {
+ assertDatanodeContainerAndBlock(keyInfo, 0, expectedTier);
+ }
+
+ /**
+ * Checks the block at {@code blockIndex} actually landed on a volume of the
expected tier.
+ */
+ private void assertDatanodeContainerAndBlock(OmKeyInfo keyInfo, int
blockIndex,
+ StorageTier expectedTier) throws IOException {
StorageType expectedStorageType = expectedTier.getUniformStorageType();
- OmKeyLocationInfo block =
-
keyInfo.getLatestVersionLocations().getBlocksLatestVersionOnly().get(0);
+ OmKeyLocationInfo block =
keyInfo.getLatestVersionLocations().getBlocksLatestVersionOnly().get(blockIndex);
ContainerInfo containerInfo = containerManager.getContainer(
ContainerID.valueOf(block.getContainerID()));
Pipeline pipeline =
diff --git
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/TestOMFileStoragePolicyUpgrade.java
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/TestOMFileStoragePolicyUpgrade.java
new file mode 100644
index 00000000000..cfb5e5b4043
--- /dev/null
+++
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/TestOMFileStoragePolicyUpgrade.java
@@ -0,0 +1,164 @@
+/*
+ * 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.om;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.List;
+import java.util.UUID;
+import org.apache.hadoop.hdds.client.OzoneStoragePolicy;
+import org.apache.hadoop.hdds.client.RatisReplicationConfig;
+import org.apache.hadoop.hdds.client.ReplicationConfig;
+import org.apache.hadoop.hdds.client.StoragePolicy;
+import org.apache.hadoop.hdds.protocol.proto.HddsProtos.ReplicationFactor;
+import org.apache.hadoop.ozone.OzoneManagerVersion;
+import org.apache.hadoop.ozone.client.OzoneBucket;
+import org.apache.hadoop.ozone.client.OzoneClient;
+import org.apache.hadoop.ozone.client.OzoneKeyDetails;
+import org.apache.hadoop.ozone.client.protocol.CreateFileOptions;
+import org.apache.hadoop.ozone.om.helpers.BucketLayout;
+import org.apache.hadoop.ozone.om.helpers.OmKeyArgs;
+import org.apache.hadoop.ozone.om.helpers.OpenKeySession;
+import org.junit.jupiter.api.Test;
+
+/**
+ * Upgrade testing for the storage policy of a file.
+ * <p>
+ * Expected behavior:
+ * 1. Pre-Finalize:
+ * - CreateFile requests that carry a storage policy are rejected by the OM,
+ * and no open file is created. An OM without storage policy support
+ * ignores the field, so accepting it would make OMs apply the same
+ * request differently.
+ * - The client does not send a storage policy to an OM that does not
+ * support it.
+ * - Requests that carry none, such as those sent by an older client,
+ * succeed. No policy is stamped on the request, so the open file ends up
+ * with no storage policy.
+ * <p>
+ * 2. Post-Finalize: the storage policy sent by the client is persisted. If the
+ * client sent none, the bucket's storage policy, then the cluster default,
+ * is persisted.
+ * <p>
+ * See {@link AbstractOMStoragePolicyUpgradeTest} for the cluster setup, which
+ * leaves only {@link OzoneManagerVersion#STORAGE_POLICY_SUPPORT} un-finalized.
+ * Its single datanode only has DISK volumes, so the tests use the policies
+ * that can be placed there: the default (WARM) and HOT, which falls back to
DISK.
+ */
+public class TestOMFileStoragePolicyUpgrade extends
AbstractOMStoragePolicyUpgradeTest {
+
+ private static final List<BucketLayout> FILE_BUCKET_LAYOUTS =
+ Arrays.asList(BucketLayout.FILE_SYSTEM_OPTIMIZED, BucketLayout.LEGACY);
+
+ private static final ReplicationConfig REPLICATION =
RatisReplicationConfig.getInstance(ReplicationFactor.ONE);
+
+ @Test
+ public void upgrade() throws Exception {
+ preFinalizationChecks();
+ finalizeOMUpgrade();
+ postFinalizationChecks();
+ }
+
+ private void preFinalizationChecks() throws Exception {
+ assertStoragePolicyNotFinalized();
+ OMMetadataManager metadataManager =
getCluster().getOzoneManager().getMetadataManager();
+
+ for (BucketLayout bucketLayout : FILE_BUCKET_LAYOUTS) {
+ // The bucket cannot carry a policy yet: CreateBucket rejects one while
pre-finalized.
+ String bucket = createBucket(null, null, bucketLayout);
+
+ // The client does not send the policy to the OM in the first place.
+ IOException clientError = assertThrows(IOException.class,
+ () -> createFileThroughClient(getClient(), bucket,
OzoneStoragePolicy.HOT));
+ assertThat(clientError).hasMessage("OzoneManager does not support
storage policy");
+
assertThat(metadataManager.getOpenKeyTable(bucketLayout).isEmpty()).isTrue();
+
+ // A request that carries a policy is rejected by the OM and creates no
open file.
+ assertRejected(() -> createFile(bucket, OzoneStoragePolicy.HOT));
+
assertThat(metadataManager.getOpenKeyTable(bucketLayout).isEmpty()).isTrue();
+
+ // Control: a request that carries no policy succeeds and stores none.
+ assertThat(createFile(bucket,
null).getKeyInfo().getStoragePolicy()).isNull();
+ }
+ }
+
+ private void postFinalizationChecks() throws Exception {
+ assertStoragePolicyFinalized();
+
+ // A client reads the OM version when it is created, so the one from
before finalization cannot be reused.
+ try (OzoneClient finalizedClient = getCluster().newClient()) {
+ for (BucketLayout bucketLayout : FILE_BUCKET_LAYOUTS) {
+ String bucketWithoutPolicy = createBucket(null, null, bucketLayout);
+
+ // The client no longer rejects the policy, and the policy it sent is
stored.
+ assertThat(createFileThroughClient(finalizedClient,
bucketWithoutPolicy, OzoneStoragePolicy.HOT)
+ .getStoragePolicy()).isEqualTo(OzoneStoragePolicy.HOT);
+
+ assertFileStoragePolicy(bucketWithoutPolicy, OzoneStoragePolicy.HOT,
OzoneStoragePolicy.HOT);
+ assertFileStoragePolicy(bucketWithoutPolicy, null,
OzoneStoragePolicy.getDefaultPolicy());
+
+ String bucketWithPolicy = createBucket(OzoneStoragePolicy.HOT, null,
bucketLayout);
+ assertFileStoragePolicy(bucketWithPolicy, OzoneStoragePolicy.WARM,
OzoneStoragePolicy.WARM);
+ assertFileStoragePolicy(bucketWithPolicy, null,
OzoneStoragePolicy.HOT);
+ }
+ }
+ }
+
+ /**
+ * Goes through the public client API, so the client side version check
applies.
+ * The file is closed empty and read back through the same client.
+ */
+ private OzoneKeyDetails createFileThroughClient(OzoneClient client, String
bucketName, StoragePolicy requestedPolicy)
+ throws IOException {
+ OzoneBucket bucket =
client.getObjectStore().getVolume(VOLUME_NAME).getBucket(bucketName);
+ String keyName = "file-" + UUID.randomUUID();
+ bucket.createFile(keyName, CreateFileOptions.builder()
+ .setReplicationConfig(REPLICATION)
+ .setStoragePolicy(requestedPolicy)
+ .build()).close();
+ return bucket.getKey(keyName);
+ }
+
+ /**
+ * Sent straight to the OM, bypassing RpcClient, so that the client side
version check cannot reject the request
+ * before the OM's validator sees it.
+ */
+ private OpenKeySession createFile(String bucketName, StoragePolicy
requestedPolicy) throws IOException {
+ OmKeyArgs.Builder keyArgs = new OmKeyArgs.Builder()
+ .setVolumeName(VOLUME_NAME)
+ .setBucketName(bucketName)
+ .setKeyName("file-" + UUID.randomUUID())
+ .setOwnerName("user1")
+ .setReplicationConfig(REPLICATION);
+ if (requestedPolicy != null) {
+ keyArgs.setStoragePolicy(requestedPolicy);
+ }
+ return getOmClient().createFile(keyArgs.build(), false, false);
+ }
+
+ /**
+ * Creates a file asking for {@code requestedPolicy} (none if null) and
checks that {@code expectedPolicy} is stored.
+ */
+ private void assertFileStoragePolicy(String bucketName, StoragePolicy
requestedPolicy, StoragePolicy expectedPolicy)
+ throws IOException {
+ assertThat(createFile(bucketName,
requestedPolicy).getKeyInfo().getStoragePolicy()).isEqualTo(expectedPolicy);
+ }
+}
diff --git
a/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/request/file/OMFileCreateRequest.java
b/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/request/file/OMFileCreateRequest.java
index cb6148dd826..14429f93db5 100644
---
a/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/request/file/OMFileCreateRequest.java
+++
b/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/request/file/OMFileCreateRequest.java
@@ -39,6 +39,7 @@
import org.apache.hadoop.hdds.utils.UniqueId;
import org.apache.hadoop.ozone.ClientVersion;
import org.apache.hadoop.ozone.OmUtils;
+import org.apache.hadoop.ozone.OzoneManagerVersion;
import org.apache.hadoop.ozone.audit.OMAction;
import org.apache.hadoop.ozone.om.OMMetadataManager;
import org.apache.hadoop.ozone.om.OMMetrics;
@@ -144,8 +145,12 @@ repConfig, new ExcludeList(), requestedSize,
keyArgs.getSortDatanodes(), userInf
// differently from an upgraded OM.
KeyArgs.Builder newKeyArgs = keyArgs.toBuilder()
.setModificationTime(Time.now()).setType(type).setFactor(factor)
- .setDataSize(requestedSize)
- .setStoragePolicy(OzoneStoragePolicy.toProto(storagePolicy));
+ .setDataSize(requestedSize);
+ // Before finalization the storage policy must not be persisted: an OM
without storage policy support would
+ // ignore the field and apply this request differently.
+ if
(ozoneManager.getVersionManager().isAllowed(OzoneManagerVersion.STORAGE_POLICY_SUPPORT))
{
+ newKeyArgs.setStoragePolicy(OzoneStoragePolicy.toProto(storagePolicy));
+ }
newKeyArgs.addAllKeyLocations(omKeyLocationInfoList.stream()
.map(info -> info.getProtobuf(
@@ -413,6 +418,26 @@ public static OMRequest
disallowCreateFileWithECReplicationConfig(
return req;
}
+ @RequestFeatureValidator(
+ conditions = ValidationCondition.CLUSTER_NEEDS_FINALIZATION,
+ processingPhase = RequestProcessingPhase.PRE_PROCESS,
+ requestType = CreateFile
+ )
+ public static OMRequest disallowCreateFileWithStoragePolicy(
+ OMRequest req, ValidationContext ctx) throws OMException {
+ if (!ctx.versionManager()
+ .isAllowed(OzoneManagerVersion.STORAGE_POLICY_SUPPORT)) {
+ if (req.getCreateFileRequest().getKeyArgs().hasStoragePolicy()) {
+ throw new OMException("Cluster does not have the storage policy"
+ + " feature finalized yet, but the request contains storage"
+ + " policy arguments. Rejecting the request, please finalize the"
+ + " cluster upgrade and then try again.",
+
OMException.ResultCodes.NOT_SUPPORTED_OPERATION_PRIOR_FINALIZATION);
+ }
+ }
+ return req;
+ }
+
/**
* Validates file create requests.
* Handles the cases where an older client attempts to create a file
diff --git
a/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/request/file/TestOMFileCreateRequest.java
b/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/request/file/TestOMFileCreateRequest.java
index 0d3d037bc2b..c9801f494a6 100644
---
a/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/request/file/TestOMFileCreateRequest.java
+++
b/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/request/file/TestOMFileCreateRequest.java
@@ -18,6 +18,9 @@
package org.apache.hadoop.ozone.om.request.file;
import static
org.apache.hadoop.ozone.om.request.OMRequestTestUtils.addVolumeAndBucketToDB;
+import static
org.apache.hadoop.ozone.om.request.validation.ValidationContext.of;
+import static
org.apache.hadoop.ozone.om.upgrade.OMVersionManagerTestUtils.mockFinalizedOmVersionManager;
+import static
org.apache.hadoop.ozone.om.upgrade.OMVersionManagerTestUtils.mockPreFinalizedOmVersionManager;
import static
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.Status.BUCKET_NOT_FOUND;
import static
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.Status.DIRECTORY_NOT_FOUND;
import static
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.Status.FILE_ALREADY_EXISTS;
@@ -25,6 +28,7 @@
import static
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.Status.NOT_A_FILE;
import static
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.Status.VOLUME_NOT_FOUND;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
@@ -54,6 +58,7 @@
import org.apache.hadoop.crypto.CryptoProtocolVersion;
import org.apache.hadoop.crypto.key.KeyProviderCryptoExtension;
import org.apache.hadoop.hdds.client.ContainerBlockID;
+import org.apache.hadoop.hdds.client.OzoneStoragePolicy;
import org.apache.hadoop.hdds.client.ReplicationConfig;
import org.apache.hadoop.hdds.client.StandaloneReplicationConfig;
import org.apache.hadoop.hdds.client.StoragePolicy;
@@ -72,7 +77,9 @@
import org.apache.hadoop.ozone.om.lock.OzoneLockProvider;
import org.apache.hadoop.ozone.om.request.OMRequestTestUtils;
import org.apache.hadoop.ozone.om.request.key.OMKeyRequestTests;
+import org.apache.hadoop.ozone.om.request.validation.ValidationContext;
import org.apache.hadoop.ozone.om.response.OMClientResponse;
+import org.apache.hadoop.ozone.om.upgrade.OMVersionManager;
import org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos;
import
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.CreateFileRequest;
import
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.KeyArgs;
@@ -233,6 +240,121 @@ public void testValidateAndUpdateCache() throws Exception
{
.getLocalID(), omKeyLocationInfo.getLocalID());
}
+ @Test
+ public void testStoragePolicyInRequestOverridesBucketPolicy() throws
Exception {
+ assertFileCreatedWithStoragePolicy(OzoneStoragePolicy.HOT,
OzoneStoragePolicy.COLD, OzoneStoragePolicy.COLD);
+ }
+
+ @Test
+ public void testStoragePolicyDefaultsToBucketPolicy() throws Exception {
+ assertFileCreatedWithStoragePolicy(OzoneStoragePolicy.COLD, null,
OzoneStoragePolicy.COLD);
+ }
+
+ @Test
+ public void testStoragePolicyDefaultsToClusterDefaultWithoutBucketPolicy()
throws Exception {
+ assertFileCreatedWithStoragePolicy(null, null,
OzoneStoragePolicy.getDefaultPolicy());
+ }
+
+ /**
+ * An OM without storage policy support does not persist the field, so
before finalization the request must be
+ * applied without one. A bucket cannot carry a policy before finalization
either, so the bucket has none.
+ */
+ @Test
+ public void testStoragePolicyNotStampedBeforeFinalization() throws Exception
{
+ OMVersionManager preFinalized = mockPreFinalizedOmVersionManager();
+ when(ozoneManager.getVersionManager()).thenReturn(preFinalized);
+ OMRequestTestUtils.addVolumeAndBucketToDB(volumeName, bucketName,
omMetadataManager, getBucketLayout());
+
+ OMRequest modifiedOmRequest =
getOMFileCreateRequest(createFileRequestWithStoragePolicy(null))
+ .preExecute(ozoneManager);
+
assertThat(modifiedOmRequest.getCreateFileRequest().getKeyArgs().hasStoragePolicy()).isFalse();
+
+ OMClientResponse response = getOMFileCreateRequest(modifiedOmRequest)
+ .validateAndUpdateCache(ozoneManager, 100L);
+
assertThat(response.getOMResponse().getStatus()).isEqualTo(OzoneManagerProtocolProtos.Status.OK);
+ OmKeyInfo omKeyInfo = verifyPathInOpenKeyTable(keyName,
modifiedOmRequest.getCreateFileRequest().getClientID(),
+ true);
+ assertThat(omKeyInfo.getStoragePolicy()).isNull();
+ }
+
+ @Test
+ public void testRejectStoragePolicyBeforeFinalization() {
+ OMRequest request =
createFileRequestWithStoragePolicy(OzoneStoragePolicy.COLD);
+
+ assertThatThrownBy(() ->
OMFileCreateRequest.disallowCreateFileWithStoragePolicy(request,
preFinalizedContext()))
+ .isInstanceOfSatisfying(OMException.class, ex -> {
+
assertThat(ex.getResult()).isEqualTo(OMException.ResultCodes.NOT_SUPPORTED_OPERATION_PRIOR_FINALIZATION);
+ assertThat(ex.getMessage()).contains("Cluster does not have the
storage policy feature finalized yet");
+ });
+ }
+
+ /**
+ * A request that carries no storage policy must pass through the validator
untouched, since the validator's return
+ * value is chained into the next validator by the request validation
framework.
+ */
+ @Test
+ public void testAllowCreateFileWithoutStoragePolicyBeforeFinalization()
throws Exception {
+ OMRequest request = createFileRequestWithStoragePolicy(null);
+
+
assertThat(OMFileCreateRequest.disallowCreateFileWithStoragePolicy(request,
preFinalizedContext()))
+ .isEqualTo(request);
+ }
+
+ @Test
+ public void testAllowCreateFileWithStoragePolicyAfterFinalization() throws
Exception {
+ OMRequest request =
createFileRequestWithStoragePolicy(OzoneStoragePolicy.COLD);
+
+ assertThat(OMFileCreateRequest.disallowCreateFileWithStoragePolicy(request,
+ of(mockFinalizedOmVersionManager(),
omMetadataManager))).isEqualTo(request);
+ }
+
+ private ValidationContext preFinalizedContext() {
+ return of(mockPreFinalizedOmVersionManager(), omMetadataManager);
+ }
+
+ /** The request a client sends, asking for {@code storagePolicy} (none if
null). */
+ private OMRequest createFileRequestWithStoragePolicy(StoragePolicy
storagePolicy) {
+ OMRequest request = createFileRequest(volumeName, bucketName, keyName,
+ HddsProtos.ReplicationFactor.ONE, HddsProtos.ReplicationType.RATIS,
false, true);
+ if (storagePolicy == null) {
+ return request;
+ }
+ KeyArgs keyArgs = request.getCreateFileRequest().getKeyArgs().toBuilder()
+ .setStoragePolicy(OzoneStoragePolicy.toProto(storagePolicy)).build();
+ return request.toBuilder()
+
.setCreateFileRequest(request.getCreateFileRequest().toBuilder().setKeyArgs(keyArgs)).build();
+ }
+
+ /**
+ * Creates a file in a bucket with {@code bucketPolicy} (none if null),
asking for {@code requestedPolicy}
+ * (none if null), and checks that {@code expectedPolicy} is stamped on the
request and stored on the open key.
+ */
+ private void assertFileCreatedWithStoragePolicy(StoragePolicy bucketPolicy,
StoragePolicy requestedPolicy,
+ StoragePolicy expectedPolicy) throws Exception {
+ OmBucketInfo.Builder bucketInfo = OmBucketInfo.newBuilder()
+ .setVolumeName(volumeName)
+ .setBucketName(bucketName)
+ .setBucketLayout(getBucketLayout());
+ if (bucketPolicy != null) {
+ bucketInfo.setStoragePolicy(bucketPolicy);
+ }
+ OMRequestTestUtils.addVolumeAndBucketToDB(volumeName, omMetadataManager,
bucketInfo);
+ // preExecute reads the bucket through the OzoneManager, which setup mocks
to return a bucket without a policy.
+ when(ozoneManager.getBucketInfo(volumeName,
bucketName)).thenReturn(bucketInfo.build());
+
+ OMRequest modifiedOmRequest =
getOMFileCreateRequest(createFileRequestWithStoragePolicy(requestedPolicy))
+ .preExecute(ozoneManager);
+
assertThat(modifiedOmRequest.getCreateFileRequest().getKeyArgs().getStoragePolicy())
+ .isEqualTo(OzoneStoragePolicy.toProto(expectedPolicy));
+
+ OMClientResponse response = getOMFileCreateRequest(modifiedOmRequest)
+ .validateAndUpdateCache(ozoneManager, 100L);
+
assertThat(response.getOMResponse().getStatus()).isEqualTo(OzoneManagerProtocolProtos.Status.OK);
+ OmKeyInfo omKeyInfo = verifyPathInOpenKeyTable(keyName,
modifiedOmRequest.getCreateFileRequest().getClientID(),
+ true);
+ assertThat(omKeyInfo.getStoragePolicy()).isEqualTo(expectedPolicy);
+ }
+
@Test
public void testValidateAndUpdateCacheWithNamespaceQuotaExceeded()
throws Exception {
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]