This is an automated email from the ASF dual-hosted git repository.
sodonnel 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 ac9c5bc2675 HDDS-17570. The ECReplicationConfig objects should be
cached (#11884)
ac9c5bc2675 is described below
commit ac9c5bc26756acb429e7774a5eeca82e5c15c9da
Author: Andrey Yarovoy <[email protected]>
AuthorDate: Thu Nov 19 11:23:07 2026 -0500
HDDS-17570. The ECReplicationConfig objects should be cached (#11884)
---
.../hdds/client/DefaultReplicationConfig.java | 2 +-
.../hadoop/hdds/client/ECReplicationConfig.java | 104 ++++++--
.../hadoop/hdds/client/ReplicationConfig.java | 4 +-
.../client/ECReplicationConfigDecodeBenchmark.java | 285 +++++++++++++++++++++
.../hdds/client/TestECReplicationConfig.java | 99 +++++++
.../commands/ReconstructECContainersCommand.java | 2 +-
...inerLocationProtocolServerSideTranslatorPB.java | 2 +-
.../org/apache/hadoop/ozone/s3/util/S3Utils.java | 2 +-
8 files changed, 479 insertions(+), 21 deletions(-)
diff --git
a/hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/client/DefaultReplicationConfig.java
b/hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/client/DefaultReplicationConfig.java
index 83fb2fe65f2..fa490002e98 100644
---
a/hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/client/DefaultReplicationConfig.java
+++
b/hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/client/DefaultReplicationConfig.java
@@ -46,7 +46,7 @@ public static DefaultReplicationConfig fromProto(
"Invalid argument: default replication config is null");
}
ReplicationConfig config = proto.hasEcReplicationConfig()
- ? new ECReplicationConfig(proto.getEcReplicationConfig())
+ ? ECReplicationConfig.getInstance(proto.getEcReplicationConfig())
: ReplicationConfig.fromProtoTypeAndFactor(
proto.getType(), proto.getFactor());
return new DefaultReplicationConfig(config);
diff --git
a/hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/client/ECReplicationConfig.java
b/hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/client/ECReplicationConfig.java
index 060939dc7ed..1122d080acf 100644
---
a/hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/client/ECReplicationConfig.java
+++
b/hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/client/ECReplicationConfig.java
@@ -18,8 +18,11 @@
package org.apache.hadoop.hdds.client;
import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.google.common.annotations.VisibleForTesting;
import java.util.EnumSet;
import java.util.Objects;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
@@ -34,12 +37,26 @@ public class ECReplicationConfig implements
ReplicationConfig {
public static final String EC_REPLICATION_PARAMS_DELIMITER = "-";
- // Acceptable patterns are like:
- // rs-3-2-1024k
- // RS-3-2-2048
- // XOR-10-4-4096K
+ // <codec>-<data>-<parity>-<chunk size>, usually as getReplication() prints
it, such as rs-6-3-1024k. The codec and
+ // the "k" suffix are case-insensitive, and without "k" the chunk size is in
bytes, so RS-6-3-1024K and
+ // rs-6-3-1048576 are accepted too.
private static final Pattern STRING_FORMAT =
Pattern.compile("([a-zA-Z]+)-(\\d+)-(\\d+)-(\\d+)([kK])?");
+ /** The maximum number of configs cached by {@link #getInstance}. */
+ @VisibleForTesting
+ static final int MAX_CACHED_CONFIGS = 64;
+ /** The maximum number of strings cached by {@link #getInstance(String)},
more than configs for other spellings. */
+ @VisibleForTesting
+ static final int MAX_CACHED_STRINGS = 256;
+ /**
+ * The shared instance of each config by value. Only a few configs are used
in practice, so they are shared instead
+ * of creating equal objects; the size is bounded since a client may send
arbitrary configs.
+ */
+ private static final ConcurrentMap<ECReplicationConfig, ECReplicationConfig>
INSTANCES = new ConcurrentHashMap<>();
+ /** The shared instances by their string form, such as rs-6-3-1024k, to look
them up without the regex. */
+ private static final ConcurrentMap<String, ECReplicationConfig> BY_STRING =
new ConcurrentHashMap<>();
+ private static final EcCodec[] CODECS = EcCodec.values();
+
private final int data;
private final int parity;
@@ -67,6 +84,61 @@ public static String allValuesAsString() {
}
}
+ /**
+ * Same as {@link #ECReplicationConfig(String)}, but returns a shared
instance for a config seen before, up to
+ * {@link #MAX_CACHED_CONFIGS} configs and {@link #MAX_CACHED_STRINGS}
strings.
+ */
+ public static ECReplicationConfig getInstance(String string) {
+ final ECReplicationConfig cached = BY_STRING.get(string);
+ if (cached != null) {
+ return cached;
+ }
+ final ECReplicationConfig config = intern(new ECReplicationConfig(string));
+ // The size check is not atomic with the put, so concurrent callers may
exceed the bound by a few entries.
+ if (BY_STRING.size() < MAX_CACHED_STRINGS) {
+ BY_STRING.putIfAbsent(string, config);
+ }
+ return config;
+ }
+
+ /**
+ * Same as {@link #ECReplicationConfig(HddsProtos.ECReplicationConfig)}, but
returns a shared instance for a config
+ * seen before, up to {@link #MAX_CACHED_CONFIGS} configs.
+ */
+ public static ECReplicationConfig getInstance(HddsProtos.ECReplicationConfig
proto) {
+ return intern(new ECReplicationConfig(proto));
+ }
+
+ /** @return the shared instance equal to the given config, or the given
config if the cache is full. */
+ private static ECReplicationConfig intern(ECReplicationConfig config) {
+ final ECReplicationConfig cached = INSTANCES.get(config);
+ if (cached != null) {
+ return cached;
+ }
+ // The size check is not atomic with the put, so concurrent callers may
exceed the bound by a few entries.
+ if (INSTANCES.size() >= MAX_CACHED_CONFIGS) {
+ return config;
+ }
+ final ECReplicationConfig previous = INSTANCES.putIfAbsent(config, config);
+ return previous != null ? previous : config;
+ }
+
+ /** Like {@code EcCodec.valueOf(name.toUpperCase())}, but without creating a
string for a valid codec. */
+ private static EcCodec getCodec(String name) {
+ for (EcCodec codec : CODECS) {
+ if (codec.name().equalsIgnoreCase(name)) {
+ return codec;
+ }
+ }
+ return EcCodec.valueOf(name.toUpperCase()); // throws the same exception
as before
+ }
+
+ @VisibleForTesting
+ static void clearCache() {
+ BY_STRING.clear();
+ INSTANCES.clear();
+ }
+
public ECReplicationConfig(int data, int parity) {
this(data, parity, EcCodec.RS, 1024 * 1024);
}
@@ -80,15 +152,16 @@ public ECReplicationConfig(int data, int parity, EcCodec
codec,
}
/**
- * Create an ECReplicationConfig object from a string representing the
- * various parameters. Acceptable patterns are like:
- * rs-3-2-1024k
- * RS-3-2-2048k
- * XOR-10-4-4096K
- * IllegalArgumentException will be thrown if the passed string does not
- * match the defined pattern.
- * @param string Parameters used to create ECReplicationConfig instances.
- * Format: <codec>-<data>-<parity>-<chunksize>
+ * Creates an ECReplicationConfig from a string in the form {@code
<codec>-<data>-<parity>-<chunk size>}, usually
+ * as {@link #getReplication()} prints it, such as rs-6-3-1024k. The codec
and the "k" suffix are case-insensitive,
+ * and without "k" the chunk size is in bytes, so RS-6-3-1024K and
rs-6-3-1048576 are the same config as
+ * rs-6-3-1024k.
+ * <p>
+ * This always creates a new object; {@link #getInstance(String)} returns a
shared one.
+ *
+ * @param string the EC replication config
+ * @throws IllegalArgumentException if the string is not in this form, or
the codec, data, parity or chunk size is
+ * invalid
*/
public ECReplicationConfig(String string) {
final Matcher matcher = STRING_FORMAT.matcher(string);
@@ -129,7 +202,7 @@ public ECReplicationConfig(
HddsProtos.ECReplicationConfig ecReplicationConfig) {
this.data = ecReplicationConfig.getData();
this.parity = ecReplicationConfig.getParity();
- this.codec = EcCodec.valueOf(ecReplicationConfig.getCodec().toUpperCase());
+ this.codec = getCodec(ecReplicationConfig.getCodec());
this.ecChunkSize = ecReplicationConfig.getEcChunkSize();
}
@@ -200,7 +273,8 @@ public boolean equals(Object o) {
@Override
public int hashCode() {
- return Objects.hash(data, parity, codec, ecChunkSize);
+ // Same value as Objects.hash(data, parity, codec, ecChunkSize), without
boxing: getInstance looks up every config
+ return ((((31 + data) * 31 + parity) * 31 + Objects.hashCode(codec)) * 31)
+ ecChunkSize;
}
@Override
diff --git
a/hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/client/ReplicationConfig.java
b/hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/client/ReplicationConfig.java
index 88ce5e3203f..2ef116b9b84 100644
---
a/hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/client/ReplicationConfig.java
+++
b/hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/client/ReplicationConfig.java
@@ -93,7 +93,7 @@ static ReplicationConfig fromProto(
HddsProtos.ECReplicationConfig ecConfig) {
switch (type) {
case EC:
- return new ECReplicationConfig(ecConfig);
+ return ECReplicationConfig.getInstance(ecConfig);
case RATIS:
case CHAINED:
case STAND_ALONE:
@@ -197,7 +197,7 @@ static ReplicationConfig
parseWithoutFallback(ReplicationType type,
replicationConfig = fromTypeAndFactor(type, factor);
break;
case EC:
- replicationConfig = new ECReplicationConfig(replication);
+ replicationConfig = ECReplicationConfig.getInstance(replication);
break;
default:
throw new IllegalArgumentException("Replication type " + type +
diff --git
a/hadoop-hdds/common/src/test/java/org/apache/hadoop/hdds/client/ECReplicationConfigDecodeBenchmark.java
b/hadoop-hdds/common/src/test/java/org/apache/hadoop/hdds/client/ECReplicationConfigDecodeBenchmark.java
new file mode 100644
index 00000000000..070c83eae9b
--- /dev/null
+++
b/hadoop-hdds/common/src/test/java/org/apache/hadoop/hdds/client/ECReplicationConfigDecodeBenchmark.java
@@ -0,0 +1,285 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.hdds.client;
+
+import java.lang.management.GarbageCollectorMXBean;
+import java.lang.management.ManagementFactory;
+import java.util.Collections;
+import java.util.IdentityHashMap;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.LongAdder;
+import java.util.function.IntFunction;
+import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
+import org.apache.hadoop.hdds.scm.container.ContainerInfo;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+
+/**
+ * Benchmark for decoding EC replication configs from protos, as done for
every container, pipeline and key that
+ * OM, SCM and clients read. It reports how much heap the decoded objects
retain, how many distinct
+ * {@link ECReplicationConfig} instances they hold, the time and allocation
per decode on one thread, and the
+ * throughput with several threads.
+ *
+ * <p>The last case decodes configs that are not allowed by default by {@code
ozone.replication.allowed-configs}, as a
+ * client sending arbitrary values could; they are shared as well, up to
+ * {@link ECReplicationConfig#MAX_CACHED_CONFIGS} configs.
+ *
+ * <p>Only public API is used, so the same class can be run before and after a
change for an A/B comparison.
+ *
+ * <p>Run with:
+ * <pre>
+ * mvn test -pl :hdds-common \
+ * -Dtest=ECReplicationConfigDecodeBenchmark \
+ * -Dgroups=benchmark -Dexcluded-test-groups= \
+ * -Dsurefire.failIfNoSpecifiedTests=false
+ * </pre>
+ */
+@Tag("benchmark")
+public class ECReplicationConfigDecodeBenchmark {
+
+ /** Number of decoded objects kept alive, like the containers in SCM's
container map. */
+ private static final int RETAINED = 1_000_000;
+ private static final int[] THREAD_COUNTS = {1, 4, 8, 16};
+ private static final int ROUNDS = 5;
+ private static final int WARMUP_MS = 2_000;
+ private static final int MEASURE_MS = 1_000;
+ /** Calls per {@code System.nanoTime()} poll to amortise the timer cost. */
+ private static final int BATCH = 1_000;
+
+ /** The EC configs a cluster typically uses. */
+ private static final String[] EC_STRINGS = {"rs-3-2-1024k", "rs-6-3-1024k",
"rs-10-4-1024k"};
+ private static final HddsProtos.ECReplicationConfig[] EC_PROTOS =
protos(EC_STRINGS);
+ private static final HddsProtos.ContainerInfoProto[] CONTAINER_PROTOS =
containerProtos(EC_PROTOS);
+
+ /** Valid configs that ozone.replication.allowed-configs does not allow by
default. */
+ private static final String[] OTHER_EC_STRINGS = {"rs-4-2-1024k",
"rs-6-3-8192k", "rs-12-4-1024k"};
+ private static final HddsProtos.ECReplicationConfig[] OTHER_EC_PROTOS =
protos(OTHER_EC_STRINGS);
+ private static final HddsProtos.ContainerInfoProto[] OTHER_CONTAINER_PROTOS
= containerProtos(OTHER_EC_PROTOS);
+
+ @Test
+ public void benchmarkRetainedHeap() {
+ printRetainedHeader("3 EC configs");
+ retained("ReplicationConfig", fromProto(EC_PROTOS));
+ retained("ContainerInfo", fromProtobuf(CONTAINER_PROTOS));
+ }
+
+ @Test
+ public void benchmarkDecode() {
+ printDecodeHeader("3 EC configs");
+ decode("ReplicationConfig", fromProto(EC_PROTOS));
+ decode("ContainerInfo", fromProtobuf(CONTAINER_PROTOS));
+ decode("ECReplicationConfig(String)", fromString(EC_STRINGS));
+ }
+
+ @Test
+ public void benchmarkThroughput() throws Exception {
+ System.out.println();
+ System.out.printf("=== Decode throughput, 3 EC configs, best of %d rounds
of %d ms ===%n", ROUNDS, MEASURE_MS);
+ System.out.printf("%-9s %22s %8s %22s %8s%n", "Threads",
"ReplicationConfig/ms", "GC %", "ContainerInfo/ms",
+ "GC %");
+ for (int threads : THREAD_COUNTS) {
+ final double[] config = bestThroughput(threads, fromProto(EC_PROTOS));
+ final double[] container = bestThroughput(threads,
fromProtobuf(CONTAINER_PROTOS));
+ System.out.printf("%-9d %22.1f %8.1f %22.1f %8.1f%n", threads,
config[0], config[1], container[0],
+ container[1]);
+ }
+ }
+
+ @Test
+ public void benchmarkOtherConfigs() {
+ printRetainedHeader("3 other EC configs");
+ retained("ReplicationConfig", fromProto(OTHER_EC_PROTOS));
+ retained("ContainerInfo", fromProtobuf(OTHER_CONTAINER_PROTOS));
+ printDecodeHeader("3 other EC configs");
+ decode("ReplicationConfig", fromProto(OTHER_EC_PROTOS));
+ decode("ContainerInfo", fromProtobuf(OTHER_CONTAINER_PROTOS));
+ decode("ECReplicationConfig(String)", fromString(OTHER_EC_STRINGS));
+ }
+
+ private static HddsProtos.ECReplicationConfig[] protos(String... configs) {
+ final HddsProtos.ECReplicationConfig[] protos = new
HddsProtos.ECReplicationConfig[configs.length];
+ for (int i = 0; i < configs.length; i++) {
+ protos[i] = new ECReplicationConfig(configs[i]).toProto();
+ }
+ return protos;
+ }
+
+ private static HddsProtos.ContainerInfoProto[]
containerProtos(HddsProtos.ECReplicationConfig[] ecProtos) {
+ final HddsProtos.ContainerInfoProto[] protos = new
HddsProtos.ContainerInfoProto[ecProtos.length];
+ for (int i = 0; i < ecProtos.length; i++) {
+ protos[i] = HddsProtos.ContainerInfoProto.newBuilder()
+ .setContainerID(i + 1)
+ .setState(HddsProtos.LifeCycleState.CLOSED)
+ .setUsedBytes(5L << 30)
+ .setNumberOfKeys(1000)
+ .setOwner("om")
+ .setReplicationType(HddsProtos.ReplicationType.EC)
+ .setEcReplicationConfig(ecProtos[i])
+ .build();
+ }
+ return protos;
+ }
+
+ private static IntFunction<Object>
fromProto(HddsProtos.ECReplicationConfig[] protos) {
+ return i -> ReplicationConfig.fromProto(HddsProtos.ReplicationType.EC,
null, protos[i % protos.length]);
+ }
+
+ private static IntFunction<Object> fromString(String[] strings) {
+ return i -> new ECReplicationConfig(strings[i % strings.length]);
+ }
+
+ private static IntFunction<Object>
fromProtobuf(HddsProtos.ContainerInfoProto[] protos) {
+ return i -> ContainerInfo.fromProtobuf(protos[i % protos.length]);
+ }
+
+ private static void printRetainedHeader(String what) {
+ System.out.println();
+ System.out.printf("=== Retained heap for %,d decoded objects, %s ===%n",
RETAINED, what);
+ System.out.printf("%-26s %14s %12s %20s%n", "Objects", "retained MB",
"bytes/object", "distinct EC configs");
+ }
+
+ private static void printDecodeHeader(String what) {
+ System.out.println();
+ System.out.printf("=== Decode, single thread, %s, best of %d rounds of %d
ms ===%n", what, ROUNDS, MEASURE_MS);
+ System.out.printf("%-26s %12s %14s%n", "Operation", "ns/call",
"bytes/call");
+ }
+
+ private static void retained(String name, IntFunction<Object> decode) {
+ final Object[] objects = new Object[RETAINED];
+ final long afterArray = usedHeapAfterGc();
+ for (int i = 0; i < RETAINED; i++) {
+ objects[i] = decode.apply(i);
+ }
+ final long after = usedHeapAfterGc();
+
+ final Set<Object> distinct = Collections.newSetFromMap(new
IdentityHashMap<>());
+ for (Object o : objects) {
+ distinct.add(o instanceof ContainerInfo ? ((ContainerInfo)
o).getReplicationConfig() : o);
+ }
+ // the array itself is not counted
+ final long bytes = after - afterArray;
+ System.out.printf("%-26s %14.1f %12.1f %,20d%n", name, bytes /
1048576.0, (double) bytes / RETAINED,
+ distinct.size());
+ }
+
+ private static long usedHeapAfterGc() {
+ long used = Long.MAX_VALUE;
+ for (int i = 0; i < 5; i++) {
+ System.gc();
+ used = Math.min(used,
ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed());
+ }
+ return used;
+ }
+
+ private static void decode(String name, IntFunction<Object> decode) {
+ com.sun.management.ThreadMXBean threadBean =
(com.sun.management.ThreadMXBean) ManagementFactory.getThreadMXBean();
+ long tid = Thread.currentThread().getId();
+ final Object[] ring = newRing();
+ runFor(decode, WARMUP_MS, ring);
+ double bestNs = Double.MAX_VALUE;
+ double bytes = 0;
+ for (int round = 0; round < ROUNDS; round++) {
+ long bytesBefore = threadBean.getThreadAllocatedBytes(tid);
+ long start = System.nanoTime();
+ long calls = runFor(decode, MEASURE_MS, ring);
+ long elapsed = System.nanoTime() - start;
+ bytes = (double) (threadBean.getThreadAllocatedBytes(tid) - bytesBefore)
/ calls;
+ bestNs = Math.min(bestNs, (double) elapsed / calls);
+ }
+ System.out.printf("%-26s %12.1f %14.0f%n", name, bestNs, bytes);
+ }
+
+ /** @return calls/ms of the best round, and the share of that round's wall
time spent in GC, in percent. */
+ private static double[] bestThroughput(int threads, IntFunction<Object>
decode) throws Exception {
+ double[] best = {0, 0};
+ for (int round = 0; round < ROUNDS; round++) {
+ final long gcBefore = gcMillis();
+ final long start = System.nanoTime();
+ final double callsPerMs = throughput(threads, decode);
+ final long wallMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()
- start);
+ final double gcPercent = 100.0 * (gcMillis() - gcBefore) / wallMillis;
+ if (callsPerMs > best[0]) {
+ best = new double[] {callsPerMs, gcPercent};
+ }
+ }
+ return best;
+ }
+
+ private static long gcMillis() {
+ long total = 0;
+ for (GarbageCollectorMXBean gc :
ManagementFactory.getGarbageCollectorMXBeans()) {
+ total += Math.max(0, gc.getCollectionTime());
+ }
+ return total;
+ }
+
+ private static double throughput(int threads, IntFunction<Object> decode)
throws Exception {
+ ExecutorService pool = Executors.newFixedThreadPool(threads);
+ LongAdder total = new LongAdder();
+ CountDownLatch start = new CountDownLatch(1);
+ CountDownLatch done = new CountDownLatch(threads);
+ try {
+ for (int t = 0; t < threads; t++) {
+ pool.submit(() -> {
+ try {
+ final Object[] ring = newRing();
+ start.await();
+ runFor(decode, WARMUP_MS / 4, ring);
+ total.add(runFor(decode, MEASURE_MS, ring));
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ } finally {
+ done.countDown();
+ }
+ });
+ }
+ start.countDown();
+ if (!done.await(60, TimeUnit.SECONDS)) {
+ throw new AssertionError("benchmark threads did not finish within 60
s");
+ }
+ } finally {
+ pool.shutdownNow();
+ }
+ return (double) total.sum() / MEASURE_MS;
+ }
+
+ /**
+ * Decoded objects escape into this array, as they do into SCM's and OM's
maps, so the JIT cannot eliminate them.
+ * Each thread has its own, so threads do not contend on it.
+ */
+ private static Object[] newRing() {
+ return new Object[1024];
+ }
+
+ /** Calls {@code decode} in batches for {@code millis} and returns the
number of calls. */
+ private static long runFor(IntFunction<Object> decode, int millis, Object[]
ring) {
+ long end = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(millis);
+ long calls = 0;
+ while (System.nanoTime() < end) {
+ for (int i = 0; i < BATCH; i++) {
+ ring[i & (ring.length - 1)] = decode.apply(i);
+ }
+ calls += BATCH;
+ }
+ return calls;
+ }
+}
diff --git
a/hadoop-hdds/common/src/test/java/org/apache/hadoop/hdds/client/TestECReplicationConfig.java
b/hadoop-hdds/common/src/test/java/org/apache/hadoop/hdds/client/TestECReplicationConfig.java
index 25a79464c77..bd75a6cd20b 100644
---
a/hadoop-hdds/common/src/test/java/org/apache/hadoop/hdds/client/TestECReplicationConfig.java
+++
b/hadoop-hdds/common/src/test/java/org/apache/hadoop/hdds/client/TestECReplicationConfig.java
@@ -20,11 +20,15 @@
import static org.apache.hadoop.hdds.client.ECReplicationConfig.EcCodec.RS;
import static org.apache.hadoop.hdds.client.ECReplicationConfig.EcCodec.XOR;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.HashMap;
import java.util.Map;
+import org.apache.hadoop.hdds.conf.OzoneConfiguration;
import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
+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;
@@ -34,6 +38,11 @@
*/
class TestECReplicationConfig {
+ @BeforeEach
+ void clearCache() {
+ ECReplicationConfig.clearCache();
+ }
+
@Test
void testSuccessfulStringParsing() {
Map<String, ECReplicationConfig> valid = new HashMap();
@@ -59,6 +68,96 @@ void testSuccessfulStringParsing() {
void testUnsuccessfulStringParsing(String invalidValue) {
assertThrows(IllegalArgumentException.class,
() -> new ECReplicationConfig(invalidValue));
+ assertThrows(IllegalArgumentException.class, () ->
ECReplicationConfig.getInstance(invalidValue));
+ }
+
+ @Test
+ void testGetInstanceReusesInstance() {
+ ECReplicationConfig config =
ECReplicationConfig.getInstance("rs-6-3-1024k");
+ assertEquals(new ECReplicationConfig(6, 3, RS, 1024 * 1024), config);
+
+ assertSame(config, ECReplicationConfig.getInstance("RS-6-3-1024K"));
+ assertSame(config, ECReplicationConfig.getInstance(config.toProto()));
+ assertSame(config,
ReplicationConfig.fromProto(HddsProtos.ReplicationType.EC, null,
config.toProto()));
+ assertSame(config, ReplicationConfig.parse(ReplicationType.EC,
"rs-6-3-1024k", new OzoneConfiguration()));
+
+ assertNotSame(config, ECReplicationConfig.getInstance("rs-6-3-2048k"));
+ }
+
+ /** Any config is shared, not only the ones allowed by default, whichever
form it is decoded from. */
+ @ParameterizedTest
+ @ValueSource(strings = {"rs-3-2-1024k", "rs-6-3-1024k", "rs-10-4-4096k",
"rs-4-2-1024k", "xor-3-1-512k"})
+ void testGetInstanceSharesAnyConfig(String string) {
+ final ECReplicationConfig config = ECReplicationConfig.getInstance(string);
+ assertEquals(new ECReplicationConfig(string), config);
+
+ assertSame(config, ECReplicationConfig.getInstance(string));
+ assertSame(config, ECReplicationConfig.getInstance(string.toUpperCase()));
+ assertSame(config, ECReplicationConfig.getInstance(config.getCodec() + "-"
+ config.getData() + "-"
+ + config.getParity() + "-" + config.getEcChunkSize()));
+ assertSame(config, ECReplicationConfig.getInstance(config.toProto()));
+ assertSame(config,
ECReplicationConfig.getInstance(config.toProto().toBuilder()
+ .setCodec(config.getCodec().name()).build()));
+ }
+
+ /** The constructor still creates a new object, also for a shared config. */
+ @ParameterizedTest
+ @ValueSource(strings = {"rs-6-3-1024k", "RS-6-3-1024K", "rs-4-2-1024k"})
+ void testConstructorCreatesNewInstance(String string) {
+ final ECReplicationConfig config = new ECReplicationConfig(string);
+ assertEquals(ECReplicationConfig.getInstance(string), config);
+ assertNotSame(ECReplicationConfig.getInstance(string), config);
+ assertNotSame(new ECReplicationConfig(string), config);
+ }
+
+ /** The cache is bounded, so a client sending arbitrary configs cannot grow
it without limit. */
+ @Test
+ void testGetInstanceIsBounded() {
+ final ECReplicationConfig cachedFromString =
ECReplicationConfig.getInstance("rs-6-3-1024k");
+ final ECReplicationConfig cachedFromProto =
ECReplicationConfig.getInstance(new ECReplicationConfig(3, 2)
+ .toProto());
+ for (int data = 1; data <= ECReplicationConfig.MAX_CACHED_STRINGS; data++)
{
+ final String string = "rs-" + data + "-1-1024k";
+ assertEquals(new ECReplicationConfig(string),
ECReplicationConfig.getInstance(string));
+ }
+
+ // a new config is still decoded, but not shared any more
+ final String string = "rs-6-1-8192k";
+ final ECReplicationConfig expected = new ECReplicationConfig(string);
+ final ECReplicationConfig fromString =
ECReplicationConfig.getInstance(string);
+ assertEquals(expected, fromString);
+ assertNotSame(fromString, ECReplicationConfig.getInstance(string));
+ final ECReplicationConfig fromProto =
ECReplicationConfig.getInstance(expected.toProto());
+ assertEquals(expected, fromProto);
+ assertNotSame(fromProto,
ECReplicationConfig.getInstance(expected.toProto()));
+
+ // the configs cached before are still shared
+ assertSame(cachedFromString,
ECReplicationConfig.getInstance("rs-6-3-1024k"));
+ assertSame(cachedFromString,
ECReplicationConfig.getInstance(cachedFromString.toProto()));
+ assertSame(cachedFromProto,
ECReplicationConfig.getInstance(cachedFromProto.toProto()));
+ assertSame(cachedFromProto,
ECReplicationConfig.getInstance("rs-3-2-1024k"));
+ }
+
+ /** Once the configs are full, a string is still cached, so the same string
returns the same instance. */
+ @Test
+ void testGetInstanceCachesStringsAfterConfigsAreFull() {
+ for (int data = 1; data <= ECReplicationConfig.MAX_CACHED_CONFIGS; data++)
{
+ ECReplicationConfig.getInstance(new ECReplicationConfig(data,
1).toProto());
+ }
+
+ final String string = "rs-6-1-8192k";
+ final ECReplicationConfig config = ECReplicationConfig.getInstance(string);
+ assertEquals(new ECReplicationConfig(string), config);
+ assertSame(config, ECReplicationConfig.getInstance(string));
+ assertNotSame(config, ECReplicationConfig.getInstance(config.toProto()));
+ }
+
+ @Test
+ void testGetInstanceRejectsUnknownCodec() {
+ final HddsProtos.ECReplicationConfig proto = new ECReplicationConfig(6,
3).toProto().toBuilder()
+ .setCodec("foo").build();
+ assertThrows(IllegalArgumentException.class, () -> new
ECReplicationConfig(proto));
+ assertThrows(IllegalArgumentException.class, () ->
ECReplicationConfig.getInstance(proto));
}
@Test
diff --git
a/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/protocol/commands/ReconstructECContainersCommand.java
b/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/protocol/commands/ReconstructECContainersCommand.java
index edcd4f132c4..e1e4c854bfa 100644
---
a/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/protocol/commands/ReconstructECContainersCommand.java
+++
b/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/protocol/commands/ReconstructECContainersCommand.java
@@ -125,7 +125,7 @@ public static ReconstructECContainersCommand
getFromProtobuf(
protoMessage.getContainerID(),
srcDatanodeDetails, targetDatanodeDetails,
protoMessage.getMissingContainerIndexes(),
- new ECReplicationConfig(protoMessage.getEcReplicationConfig()),
+ ECReplicationConfig.getInstance(protoMessage.getEcReplicationConfig()),
protoMessage.getCmdId());
if (protoMessage.hasApparentVersion()) {
cmd.apparentVersion =
HDDSVersionUtils.deserializeHDDSVersionOrLayoutVersion(
diff --git
a/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/protocol/StorageContainerLocationProtocolServerSideTranslatorPB.java
b/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/protocol/StorageContainerLocationProtocolServerSideTranslatorPB.java
index d4843511311..3be758aa726 100644
---
a/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/protocol/StorageContainerLocationProtocolServerSideTranslatorPB.java
+++
b/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/protocol/StorageContainerLocationProtocolServerSideTranslatorPB.java
@@ -938,7 +938,7 @@ public SCMListContainerResponseProto listContainer(
// passed Type. Therefore, we must check for replicationConfig.
if (replicationType == HddsProtos.ReplicationType.EC) {
if (request.hasEcReplicationConfig()) {
- repConfig = new
ECReplicationConfig(request.getEcReplicationConfig());
+ repConfig =
ECReplicationConfig.getInstance(request.getEcReplicationConfig());
}
} else {
if (request.hasFactor()) {
diff --git
a/hadoop-ozone/s3gateway/src/main/java/org/apache/hadoop/ozone/s3/util/S3Utils.java
b/hadoop-ozone/s3gateway/src/main/java/org/apache/hadoop/ozone/s3/util/S3Utils.java
index 0d873f55e30..4caf7d95f9e 100644
---
a/hadoop-ozone/s3gateway/src/main/java/org/apache/hadoop/ozone/s3/util/S3Utils.java
+++
b/hadoop-ozone/s3gateway/src/main/java/org/apache/hadoop/ozone/s3/util/S3Utils.java
@@ -135,7 +135,7 @@ public static ReplicationConfig toReplicationConfig(String
s3StorageType, String
S3StorageType storageType = S3StorageType.valueOf(s3StorageType);
if (S3StorageType.STANDARD_IA.equals(storageType) &&
!StringUtils.isEmpty(s3StorageConfig)) {
- return new ECReplicationConfig(s3StorageConfig);
+ return ECReplicationConfig.getInstance(s3StorageConfig);
}
return storageType.getReplicationConfig();
} catch (IllegalArgumentException ex) {
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]