This is an automated email from the ASF dual-hosted git repository.
jojochuang 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 e3c68ea4d47 HDDS-16867. ECBlockInputStream should read data cells from
datanodes in parallel (#11501)
e3c68ea4d47 is described below
commit e3c68ea4d47df81b49037dce4fc6c24105593e8d
Author: Andrey Yarovoy <[email protected]>
AuthorDate: Mon Oct 19 18:26:27 2026 -0400
HDDS-16867. ECBlockInputStream should read data cells from datanodes in
parallel (#11501)
Generated-by: Claude Opus 5.5 <[email protected]>
---
.../apache/hadoop/hdds/scm/OzoneClientConfig.java | 41 ++
.../ozone/client/io/BadDataLocationException.java | 21 +
.../client/io/BlockInputStreamFactoryImpl.java | 20 +-
.../hadoop/ozone/client/io/ECBlockInputStream.java | 238 ++++++++++-
.../client/io/ECBlockInputStreamFactoryImpl.java | 20 +-
.../hadoop/hdds/scm/TestOzoneClientConfig.java | 10 +
.../hadoop/ozone/client/io/ECStreamTestUtil.java | 25 ++
.../ozone/client/io/TestECBlockInputStream.java | 320 ++++++++++++---
.../apache/hadoop/ozone/client/rpc/RpcClient.java | 78 +++-
.../hadoop/ozone/client/MockDatanodeStorage.java | 44 ++
.../hadoop/ozone/client/MockXceiverClientSpi.java | 4 +
.../hadoop/ozone/client/TestOzoneECClient.java | 111 +++++-
.../hadoop/ozone/client/rpc/TestRpcClient.java | 52 +++
.../om/protocolPB/OzoneManagerClientProtocol.java | 7 +
...OzoneManagerProtocolClientSideTranslatorPB.java | 6 +
.../apache/hadoop/ozone/s3/S3GatewayService.java | 38 +-
.../hadoop/ozone/s3/awssdk/OzoneS3SDKTests.java | 4 +
.../ozone/s3/awssdk/v2/AbstractS3SDKV2Tests.java | 77 ++++
.../hadoop/fs/ozone/TestOzoneFSInputStream.java | 34 +-
.../ozone/client/rpc/TestSecureOzoneRpcClient.java | 83 +++-
.../rpc/read/TestEcParallelReadBenchmark.java | 442 +++++++++++++++++++++
.../ozone/client/rpc/read/TestKeyInputStream.java | 14 +
22 files changed, 1594 insertions(+), 95 deletions(-)
diff --git
a/hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/OzoneClientConfig.java
b/hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/OzoneClientConfig.java
index 6dbf2103489..6044e53efda 100644
---
a/hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/OzoneClientConfig.java
+++
b/hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/OzoneClientConfig.java
@@ -258,6 +258,25 @@ public class OzoneClientConfig {
tags = ConfigTag.CLIENT)
private int ecReconstructStripeWritePoolLimit = 10 * 3;
+ @Config(key = "ozone.client.ec.parallel.read.enabled",
+ defaultValue = "false",
+ type = ConfigType.BOOLEAN,
+ description = "When enabled, a read of an EC block that spans more than
one cell reads the cells of different" +
+ " data indexes from their datanodes in parallel, instead of one cell
at a time. Reads within a single" +
+ " cell, and reads that need reconstruction, are not affected.",
+ tags = ConfigTag.CLIENT)
+ private boolean ecParallelReadEnabled = false;
+
+ @Config(key = "ozone.client.ec.parallel.read.pool.limit",
+ defaultValue = "30",
+ description = "Thread pool max size for reading the cells of an EC block
in parallel, when" +
+ " ozone.client.ec.parallel.read.enabled is true. When the pool is
saturated, the reading thread reads" +
+ " the remaining cells itself.",
+ tags = ConfigTag.CLIENT)
+ // For the largest recommended EC policy rs-10-4-1024k, a read can span
+ // 10 data indexes, so this allows 3 such reads in parallel.
+ private int ecParallelReadPoolLimit = 10 * 3;
+
@Config(key = "ozone.client.checksum.combine.mode",
defaultValue = "COMPOSITE_CRC",
description = "The combined checksum type [MD5MD5CRC / COMPOSITE_CRC] "
@@ -387,6 +406,12 @@ public void validate() {
OzoneConfigKeys.OZONE_CLIENT_BYTES_PER_CHECKSUM_MIN_SIZE;
}
+ if (ecParallelReadPoolLimit < 1) {
+ LOG.warn("ozone.client.ec.parallel.read.pool.limit ({}) must be at least
1, resetting to 1.",
+ ecParallelReadPoolLimit);
+ ecParallelReadPoolLimit = 1;
+ }
+
// Verify client configs related to HBase enhancements
// Enforce check on ozone.client.hbase.enhancements.allowed
if (!hbaseEnhancementsAllowed) {
@@ -626,6 +651,22 @@ public int getEcReconstructStripeWritePoolLimit() {
return ecReconstructStripeWritePoolLimit;
}
+ public boolean isEcParallelReadEnabled() {
+ return ecParallelReadEnabled;
+ }
+
+ public void setEcParallelReadEnabled(boolean ecParallelReadEnabled) {
+ this.ecParallelReadEnabled = ecParallelReadEnabled;
+ }
+
+ public int getEcParallelReadPoolLimit() {
+ return ecParallelReadPoolLimit;
+ }
+
+ public void setEcParallelReadPoolLimit(int poolLimit) {
+ this.ecParallelReadPoolLimit = poolLimit;
+ }
+
public void setFsDefaultBucketLayout(String bucketLayout) {
if (!bucketLayout.isEmpty()) {
this.fsDefaultBucketLayout = bucketLayout;
diff --git
a/hadoop-hdds/client/src/main/java/org/apache/hadoop/ozone/client/io/BadDataLocationException.java
b/hadoop-hdds/client/src/main/java/org/apache/hadoop/ozone/client/io/BadDataLocationException.java
index 3fa0b2f3c45..ec53291f987 100644
---
a/hadoop-hdds/client/src/main/java/org/apache/hadoop/ozone/client/io/BadDataLocationException.java
+++
b/hadoop-hdds/client/src/main/java/org/apache/hadoop/ozone/client/io/BadDataLocationException.java
@@ -19,7 +19,9 @@
import java.io.IOException;
import java.util.ArrayList;
+import java.util.Collections;
import java.util.List;
+import java.util.Map;
import org.apache.hadoop.hdds.protocol.DatanodeDetails;
/**
@@ -30,6 +32,7 @@ public class BadDataLocationException extends IOException {
private final List<DatanodeDetails> failedLocations = new ArrayList<>();
private int failedLocationIndex;
+ private final List<Integer> failedLocationIndexes = new ArrayList<>();
/**
* Required for Unwrapping {@code RemoteException}. Used by
@@ -74,6 +77,18 @@ public BadDataLocationException(DatanodeDetails dn, int
failedIndex,
failedLocationIndex = failedIndex;
}
+ /**
+ * For a read that failed on several location indexes at once.
+ * @param failures the failed location of each failed index, in index order
+ * @param ex the cause of the first failure
+ */
+ public BadDataLocationException(Map<Integer, DatanodeDetails> failures,
Throwable ex) {
+ super(ex);
+ failedLocations.addAll(failures.values());
+ failedLocationIndexes.addAll(failures.keySet());
+ failedLocationIndex = failedLocationIndexes.get(0);
+ }
+
public List<DatanodeDetails> getFailedLocations() {
return failedLocations;
}
@@ -85,4 +100,10 @@ public void addFailedLocations(List<DatanodeDetails> dns) {
public int getFailedLocationIndex() {
return failedLocationIndex;
}
+
+ public List<Integer> getFailedLocationIndexes() {
+ return failedLocationIndexes.isEmpty()
+ ? Collections.singletonList(failedLocationIndex)
+ : Collections.unmodifiableList(failedLocationIndexes);
+ }
}
diff --git
a/hadoop-hdds/client/src/main/java/org/apache/hadoop/ozone/client/io/BlockInputStreamFactoryImpl.java
b/hadoop-hdds/client/src/main/java/org/apache/hadoop/ozone/client/io/BlockInputStreamFactoryImpl.java
index fff8fc445a6..f2af2296d92 100644
---
a/hadoop-hdds/client/src/main/java/org/apache/hadoop/ozone/client/io/BlockInputStreamFactoryImpl.java
+++
b/hadoop-hdds/client/src/main/java/org/apache/hadoop/ozone/client/io/BlockInputStreamFactoryImpl.java
@@ -55,15 +55,33 @@ public static BlockInputStreamFactory getInstance(
ecReconstructExecutorSupplier);
}
+ /**
+ * @param ecParallelReadExecutorSupplier executor for reading the cells of a
healthy EC block in parallel, or
+ * null to always read them one at a time
+ */
+ public static BlockInputStreamFactory getInstance(
+ ByteBufferPool byteBufferPool,
+ Supplier<ExecutorService> ecReconstructExecutorSupplier,
+ Supplier<ExecutorService> ecParallelReadExecutorSupplier) {
+ return new BlockInputStreamFactoryImpl(byteBufferPool,
+ ecReconstructExecutorSupplier, ecParallelReadExecutorSupplier);
+ }
+
public BlockInputStreamFactoryImpl() {
this(new ElasticByteBufferPool(), Executors::newSingleThreadExecutor);
}
public BlockInputStreamFactoryImpl(ByteBufferPool byteBufferPool,
Supplier<ExecutorService> ecReconstructExecutorSupplier) {
+ this(byteBufferPool, ecReconstructExecutorSupplier, null);
+ }
+
+ public BlockInputStreamFactoryImpl(ByteBufferPool byteBufferPool,
+ Supplier<ExecutorService> ecReconstructExecutorSupplier,
+ Supplier<ExecutorService> ecParallelReadExecutorSupplier) {
this.ecBlockStreamFactory =
ECBlockInputStreamFactoryImpl.getInstance(this, byteBufferPool,
- ecReconstructExecutorSupplier);
+ ecReconstructExecutorSupplier, ecParallelReadExecutorSupplier);
}
/**
diff --git
a/hadoop-hdds/client/src/main/java/org/apache/hadoop/ozone/client/io/ECBlockInputStream.java
b/hadoop-hdds/client/src/main/java/org/apache/hadoop/ozone/client/io/ECBlockInputStream.java
index b655e5d3a39..3423bf796bc 100644
---
a/hadoop-hdds/client/src/main/java/org/apache/hadoop/ozone/client/io/ECBlockInputStream.java
+++
b/hadoop-hdds/client/src/main/java/org/apache/hadoop/ozone/client/io/ECBlockInputStream.java
@@ -18,18 +18,26 @@
package org.apache.hadoop.ozone.client.io;
import com.google.common.base.Preconditions;
+import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableMap;
+import com.google.common.util.concurrent.Uninterruptibles;
import java.io.EOFException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
+import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.FutureTask;
+import java.util.concurrent.RejectedExecutionException;
import java.util.function.Function;
+import java.util.function.Supplier;
import org.apache.hadoop.fs.FSExceptionMessages;
import org.apache.hadoop.fs.StreamCapabilities;
import org.apache.hadoop.hdds.client.BlockID;
@@ -70,6 +78,8 @@ public class ECBlockInputStream extends
BlockExtendedInputStream {
private final List<DatanodeDetails> failedLocations = new ArrayList<>();
private final int maxLocations;
private final String string;
+ // Executor for reading the cells of a multi-cell read in parallel, or null
to read them one at a time.
+ private final Supplier<ExecutorService> parallelReadExecutor;
private long position = 0;
private boolean closed = false;
@@ -113,6 +123,21 @@ public ECBlockInputStream(ECReplicationConfig repConfig,
Function<BlockID, BlockLocationInfo> refreshFunction,
BlockInputStreamFactory streamFactory,
OzoneClientConfig config) {
+ this(repConfig, blockInfo, xceiverClientFactory, refreshFunction,
streamFactory, config, null);
+ }
+
+ /**
+ * @param parallelReadExecutor executor for reading the cells of different
data indexes in parallel when a read
+ * spans more than one cell. It is used only if {@link
OzoneClientConfig#isEcParallelReadEnabled()}; with
+ * null, cells are always read one at a time.
+ */
+ public ECBlockInputStream(ECReplicationConfig repConfig,
+ BlockLocationInfo blockInfo,
+ XceiverClientFactory xceiverClientFactory,
+ Function<BlockID, BlockLocationInfo> refreshFunction,
+ BlockInputStreamFactory streamFactory,
+ OzoneClientConfig config,
+ Supplier<ExecutorService> parallelReadExecutor) {
this.repConfig = repConfig;
this.ecChunkSize = repConfig.getEcChunkSize();
this.blockInfo = blockInfo;
@@ -124,6 +149,7 @@ public ECBlockInputStream(ECReplicationConfig repConfig,
this.blockStreams =
new BlockExtendedInputStream[repConfig.getRequiredNodes()];
this.config = config;
+ this.parallelReadExecutor = config != null &&
config.isEcParallelReadEnabled() ? parallelReadExecutor : null;
this.stripeSize = (long)ecChunkSize * repConfig.getData();
setBlockLocations(this.blockInfo.getPipeline());
@@ -323,18 +349,22 @@ public synchronized int read(ByteBuffer byteBuffer)
throws IOException {
int currentBufferPosition = byteBuffer.position();
long currentPosition = getPos();
try {
- return super.read(byteBuffer);
+ return spansMultipleCells(byteBuffer) ?
readCellsInParallel(byteBuffer) : super.read(byteBuffer);
} catch (BadDataLocationException e) {
- int failedIndex = e.getFailedLocationIndex();
- if (LOG.isDebugEnabled()) {
- String cause = e.getCause() != null
- ? " due to " + e.getCause().getMessage()
- : "";
- LOG.debug("{}: read [{}] failed from {}{}", this,
- failedIndex, dataLocations[failedIndex], cause);
+ boolean retry = true;
+ for (int failedIndex : e.getFailedLocationIndexes()) {
+ if (LOG.isDebugEnabled()) {
+ String cause = e.getCause() != null
+ ? " due to " + e.getCause().getMessage()
+ : "";
+ LOG.debug("{}: read [{}] failed from {}{}", this,
+ failedIndex, dataLocations[failedIndex], cause);
+ }
+ closeStream(failedIndex);
+ // every failed index is switched to a spare, if it has one
+ retry &= shouldRetryFailedRead(failedIndex);
}
- closeStream(failedIndex);
- if (shouldRetryFailedRead(failedIndex)) {
+ if (retry) {
byteBuffer.position(currentBufferPosition);
seek(currentPosition);
} else {
@@ -391,6 +421,194 @@ protected synchronized int
readWithStrategy(ByteReaderStrategy strategy)
return totalRead;
}
+ /**
+ * Returns true if the parallel read path is enabled and the next read into
the buffer covers more than one cell.
+ */
+ private boolean spansMultipleCells(ByteBuffer buffer) {
+ if (parallelReadExecutor == null || closed) {
+ return false;
+ }
+ long length = Math.min(buffer.remaining(), remaining());
+ return position % ecChunkSize + length > ecChunkSize;
+ }
+
+ /**
+ * Reads the cells covered by the buffer from the internal block streams of
their data indexes in parallel. The
+ * cells of one data index, which come from consecutive stripes, are read in
order by a single task, so the
+ * fan-out is at most the number of data units. The calling thread runs the
task of the first cell, and any task
+ * the executor has not started yet, and returns only after all tasks have
finished.
+ *
+ * <p>Like {@link #readWithStrategy}, the position and the buffer are
advanced past the data that was read. If a
+ * read fails, they are advanced only by the cells before the first failed
cell, and a
+ * {@link BadDataLocationException} carrying every failed index is thrown.
+ */
+ private int readCellsInParallel(ByteBuffer buffer) throws IOException {
+ final long startPosition = position;
+ final int length = (int) Math.min(buffer.remaining(), remaining());
+ final int bufferStart = buffer.position();
+
+ // Split the range into cells, grouped by data index in the order they are
first needed.
+ final List<CellRead> cells = new ArrayList<>();
+ final Map<Integer, List<CellRead>> cellsByIndex = new LinkedHashMap<>();
+ for (int offset = 0; offset < length;) {
+ long cellPosition = startPosition + offset;
+ int cellLength = (int) Math.min(ecChunkSize - cellPosition %
ecChunkSize, length - offset);
+ int index = (int) ((cellPosition / ecChunkSize) % repConfig.getData());
+ List<CellRead> indexCells = cellsByIndex.computeIfAbsent(index, k -> new
ArrayList<>());
+ CellRead cell = new CellRead(index, indexCells.size(), cellPosition,
offset, cellLength);
+ indexCells.add(cell);
+ cells.add(cell);
+ offset += cellLength;
+ }
+
+ // getOrOpenStream is not thread safe, so open every stream before reading.
+ final List<FutureTask<IndexReadResult>> tasks = new ArrayList<>();
+ for (Map.Entry<Integer, List<CellRead>> entry : cellsByIndex.entrySet()) {
+ int index = entry.getKey();
+ BlockExtendedInputStream stream;
+ try {
+ stream = getOrOpenStream(index);
+ } catch (IOException e) {
+ throw new BadDataLocationException(dataLocations[index], index, e);
+ }
+ List<CellRead> indexCells = entry.getValue();
+ boolean checkPosition = seeked;
+ tasks.add(new FutureTask<>(() -> readCells(stream, indexCells, buffer,
bufferStart, checkPosition)));
+ }
+
+ ExecutorService executor = parallelReadExecutor.get();
+ for (int i = 1; i < tasks.size(); i++) {
+ try {
+ executor.execute(tasks.get(i));
+ } catch (RejectedExecutionException e) {
+ // the task is run by this thread below
+ LOG.debug("{}: parallel read task rejected", this, e);
+ }
+ }
+ // FutureTask.run does nothing if the task has already been started by the
executor.
+ for (FutureTask<IndexReadResult> task : tasks) {
+ task.run();
+ }
+ // Wait for every task, even after an unexpected error, as they all write
into the caller's buffer.
+ Map<Integer, IndexReadResult> results = new TreeMap<>();
+ Throwable unexpected = null;
+ for (FutureTask<IndexReadResult> task : tasks) {
+ try {
+ IndexReadResult result = Uninterruptibles.getUninterruptibly(task);
+ results.put(result.index, result);
+ } catch (ExecutionException e) {
+ unexpected = unexpected == null ? e.getCause() : unexpected;
+ }
+ }
+ // After a failure, the streams of indexes read past the cells that
position advances by below, so a later read
+ // must check the position of every stream, as after a seek.
+ if (unexpected != null || results.values().stream().anyMatch(result ->
result.error != null)) {
+ seeked = true;
+ }
+ if (unexpected != null) {
+ Throwables.throwIfUnchecked(unexpected);
+ throw new IOException(unexpected);
+ }
+
+ // A failure on one index must not be hidden by the success of a later
cell, so only advance by the cells
+ // before the first failed cell.
+ int read = 0;
+ for (CellRead cell : cells) {
+ if (cell.ordinal >= results.get(cell.index).cellsRead) {
+ break;
+ }
+ read += cell.length;
+ }
+ position = startPosition + read;
+ buffer.position(bufferStart + read);
+ LOG.trace("{}: read {} bytes from {} indexes in parallel", this, read,
tasks.size());
+
+ Map<Integer, DatanodeDetails> failures = new TreeMap<>();
+ IOException cause = null;
+ for (IndexReadResult result : results.values()) {
+ if (result.error != null) {
+ failures.put(result.index, dataLocations[result.index]);
+ if (cause == null) {
+ cause = result.error;
+ } else {
+ cause.addSuppressed(result.error);
+ }
+ }
+ }
+ if (cause != null) {
+ throw new BadDataLocationException(failures, cause);
+ }
+ return read;
+ }
+
+ /**
+ * Reads the given cells of one data index, in order, each into its own
slice of the buffer. Called without the
+ * stream monitor, so it only uses the given stream and state that does not
change while the caller waits.
+ */
+ private IndexReadResult readCells(BlockExtendedInputStream stream,
List<CellRead> indexCells, ByteBuffer buffer,
+ int bufferStart, boolean checkPosition) {
+ int index = indexCells.get(0).index;
+ int cellsRead = 0;
+ try {
+ for (CellRead cell : indexCells) {
+ long streamPosition = (cell.position / stripeSize) * ecChunkSize +
cell.position % ecChunkSize;
+ // The cells of one index are contiguous in its stream, so its
position only needs to be checked once
+ // the stream has been seeked.
+ if (checkPosition && streamPosition != stream.getPos()) {
+ stream.seek(streamPosition);
+ }
+ ByteBuffer slice = buffer.duplicate();
+ slice.position(bufferStart + cell.bufferOffset);
+ slice.limit(bufferStart + cell.bufferOffset + cell.length);
+ int actualRead = stream.read(slice);
+ if (actualRead == EOF) {
+ throw new IOException("Expected to read " + cell.length + " but got
EOF"
+ + " from blockGroup " + stream.getBlockID() + " index " + (index
+ 1));
+ }
+ if (actualRead != cell.length) {
+ throw new IOException(String.format(
+ "Inconsistent read for blockID=%s index=%d expectedRead=%d
actualRead=%d",
+ stream.getBlockID(), index + 1, cell.length, actualRead));
+ }
+ cellsRead++;
+ }
+ return new IndexReadResult(index, cellsRead, null);
+ } catch (IOException e) {
+ return new IndexReadResult(index, cellsRead, e);
+ }
+ }
+
+ /** The part of a parallel read that falls in one cell. */
+ private static final class CellRead {
+ private final int index;
+ // position of this cell among the cells of the same index in the read
+ private final int ordinal;
+ private final long position;
+ private final int bufferOffset;
+ private final int length;
+
+ CellRead(int index, int ordinal, long position, int bufferOffset, int
length) {
+ this.index = index;
+ this.ordinal = ordinal;
+ this.position = position;
+ this.bufferOffset = bufferOffset;
+ this.length = length;
+ }
+ }
+
+ /** Outcome of reading the cells of one data index in a parallel read. */
+ private static final class IndexReadResult {
+ private final int index;
+ private final int cellsRead;
+ private final IOException error;
+
+ IndexReadResult(int index, int cellsRead, IOException error) {
+ this.index = index;
+ this.cellsRead = cellsRead;
+ this.error = error;
+ }
+ }
+
@Override
public synchronized long getLength() {
return blockInfo.getLength();
diff --git
a/hadoop-hdds/client/src/main/java/org/apache/hadoop/ozone/client/io/ECBlockInputStreamFactoryImpl.java
b/hadoop-hdds/client/src/main/java/org/apache/hadoop/ozone/client/io/ECBlockInputStreamFactoryImpl.java
index 968d339b252..11d44b02878 100644
---
a/hadoop-hdds/client/src/main/java/org/apache/hadoop/ozone/client/io/ECBlockInputStreamFactoryImpl.java
+++
b/hadoop-hdds/client/src/main/java/org/apache/hadoop/ozone/client/io/ECBlockInputStreamFactoryImpl.java
@@ -40,20 +40,34 @@ public final class ECBlockInputStreamFactoryImpl implements
private final BlockInputStreamFactory inputStreamFactory;
private final ByteBufferPool byteBufferPool;
private final Supplier<ExecutorService> ecReconstructExecutorSupplier;
+ private final Supplier<ExecutorService> ecParallelReadExecutorSupplier;
public static ECBlockInputStreamFactory getInstance(
BlockInputStreamFactory streamFactory, ByteBufferPool byteBufferPool,
Supplier<ExecutorService> ecReconstructExecutorSupplier) {
+ return getInstance(streamFactory, byteBufferPool,
ecReconstructExecutorSupplier, null);
+ }
+
+ /**
+ * @param ecParallelReadExecutorSupplier executor for reading the cells of a
healthy EC block in parallel, or
+ * null to always read them one at a time
+ */
+ public static ECBlockInputStreamFactory getInstance(
+ BlockInputStreamFactory streamFactory, ByteBufferPool byteBufferPool,
+ Supplier<ExecutorService> ecReconstructExecutorSupplier,
+ Supplier<ExecutorService> ecParallelReadExecutorSupplier) {
return new ECBlockInputStreamFactoryImpl(streamFactory, byteBufferPool,
- ecReconstructExecutorSupplier);
+ ecReconstructExecutorSupplier, ecParallelReadExecutorSupplier);
}
private ECBlockInputStreamFactoryImpl(BlockInputStreamFactory streamFactory,
ByteBufferPool byteBufferPool,
- Supplier<ExecutorService> ecReconstructExecutorSupplier) {
+ Supplier<ExecutorService> ecReconstructExecutorSupplier,
+ Supplier<ExecutorService> ecParallelReadExecutorSupplier) {
this.byteBufferPool = byteBufferPool;
this.inputStreamFactory = streamFactory;
this.ecReconstructExecutorSupplier = ecReconstructExecutorSupplier;
+ this.ecParallelReadExecutorSupplier = ecParallelReadExecutorSupplier;
}
/**
@@ -94,7 +108,7 @@ public BlockExtendedInputStream create(boolean
missingLocations,
// Otherwise create the more efficient non-reconstruction reader
return new ECBlockInputStream((ECReplicationConfig)repConfig, blockInfo,
xceiverFactory, refreshFunction, inputStreamFactory,
- config);
+ config, ecParallelReadExecutorSupplier);
}
}
diff --git
a/hadoop-hdds/client/src/test/java/org/apache/hadoop/hdds/scm/TestOzoneClientConfig.java
b/hadoop-hdds/client/src/test/java/org/apache/hadoop/hdds/scm/TestOzoneClientConfig.java
index c9ba90c87c8..9fed189dc88 100644
---
a/hadoop-hdds/client/src/test/java/org/apache/hadoop/hdds/scm/TestOzoneClientConfig.java
+++
b/hadoop-hdds/client/src/test/java/org/apache/hadoop/hdds/scm/TestOzoneClientConfig.java
@@ -40,6 +40,16 @@ void missingSizeSuffix() {
assertEquals(OZONE_CLIENT_BYTES_PER_CHECKSUM_MIN_SIZE,
subject.getBytesPerChecksum());
}
+ @Test
+ void nonPositiveEcParallelReadPoolLimit() {
+ OzoneConfiguration conf = new OzoneConfiguration();
+ conf.setInt("ozone.client.ec.parallel.read.pool.limit", 0);
+
+ OzoneClientConfig subject = conf.getObject(OzoneClientConfig.class);
+
+ assertEquals(1, subject.getEcParallelReadPoolLimit());
+ }
+
@Test
void testClientHBaseEnhancementsAllowedTrue() {
// When ozone.client.hbase.enhancements.allowed = true,
diff --git
a/hadoop-hdds/client/src/test/java/org/apache/hadoop/ozone/client/io/ECStreamTestUtil.java
b/hadoop-hdds/client/src/test/java/org/apache/hadoop/ozone/client/io/ECStreamTestUtil.java
index d84540ec8ac..083b689ac5b 100644
---
a/hadoop-hdds/client/src/test/java/org/apache/hadoop/ozone/client/io/ECStreamTestUtil.java
+++
b/hadoop-hdds/client/src/test/java/org/apache/hadoop/ozone/client/io/ECStreamTestUtil.java
@@ -29,6 +29,8 @@
import java.util.Map;
import java.util.Set;
import java.util.SplittableRandom;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import org.apache.hadoop.hdds.client.BlockID;
import org.apache.hadoop.hdds.client.ECReplicationConfig;
@@ -224,6 +226,7 @@ public static class TestBlockInputStreamFactory implements
private List<ByteBuffer> blockStreamData;
// List of EC indexes that should fail immediately on read
private final List<Integer> failIndexes = new ArrayList<>();
+ private CountDownLatch readBarrier;
private Pipeline currentPipeline;
@@ -254,6 +257,11 @@ public synchronized void setFailIndexes(Integer... fail) {
failIndexes.addAll(Arrays.asList(fail));
}
+ // every read of the streams created after this waits until the barrier
has been reached by count reads
+ public synchronized void setReadBarrier(CountDownLatch barrier) {
+ this.readBarrier = barrier;
+ }
+
@Override
public synchronized BlockExtendedInputStream create(
ReplicationConfig repConfig,
@@ -270,6 +278,7 @@ public synchronized BlockExtendedInputStream create(
if (failIndexes.remove(Integer.valueOf(repInd))) {
stream.setShouldError(true);
}
+ stream.setReadBarrier(readBarrier);
blockStreams.put(repInd, stream);
return stream;
}
@@ -289,6 +298,7 @@ public static class TestBlockInputStream extends
BlockExtendedInputStream {
private boolean shouldErrorOnSeek = false;
private IOException errorToThrow = null;
private int ecReplicaIndex = 0;
+ private CountDownLatch readBarrier;
private static final byte EOF = -1;
TestBlockInputStream(BlockID blockId, long blockLen, ByteBuffer data) {
@@ -320,6 +330,10 @@ public void setShouldError(boolean val, int position,
this.errorToThrow = errorThrowable;
}
+ public void setReadBarrier(CountDownLatch barrier) {
+ this.readBarrier = barrier;
+ }
+
public int getEcReplicaIndex() {
return ecReplicaIndex;
}
@@ -358,6 +372,17 @@ public int read(ByteBuffer buf) throws IOException {
if (shouldError && data.position() >= shouldErrorPosition) {
throwError();
}
+ if (readBarrier != null) {
+ readBarrier.countDown();
+ try {
+ if (!readBarrier.await(10, TimeUnit.SECONDS)) {
+ throw new IOException("Timed out waiting for " +
readBarrier.getCount() + " concurrent reads");
+ }
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new IOException(e);
+ }
+ }
if (getRemaining() == 0) {
return EOF;
}
diff --git
a/hadoop-hdds/client/src/test/java/org/apache/hadoop/ozone/client/io/TestECBlockInputStream.java
b/hadoop-hdds/client/src/test/java/org/apache/hadoop/ozone/client/io/TestECBlockInputStream.java
index e85ca219b86..3f4828d7357 100644
---
a/hadoop-hdds/client/src/test/java/org/apache/hadoop/ozone/client/io/TestECBlockInputStream.java
+++
b/hadoop-hdds/client/src/test/java/org/apache/hadoop/ozone/client/io/TestECBlockInputStream.java
@@ -17,6 +17,7 @@
package org.apache.hadoop.ozone.client.io;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
@@ -27,12 +28,19 @@
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.SynchronousQueue;
+import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
+import java.util.stream.Stream;
import org.apache.hadoop.hdds.client.BlockID;
import org.apache.hadoop.hdds.client.ECReplicationConfig;
import org.apache.hadoop.hdds.client.ReplicationConfig;
@@ -49,26 +57,55 @@
import org.apache.hadoop.hdds.scm.storage.ByteReaderStrategy;
import org.apache.hadoop.hdds.security.token.OzoneBlockTokenIdentifier;
import org.apache.hadoop.security.token.Token;
+import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
+import org.junit.jupiter.params.Parameter;
+import org.junit.jupiter.params.ParameterizedClass;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.junit.jupiter.params.provider.ValueSource;
/**
- * Tests for ECBlockInputStream.
+ * Tests for ECBlockInputStream, run with cells read one at a time and in
parallel.
*/
+@ParameterizedClass
+@ValueSource(booleans = {false, true})
public class TestECBlockInputStream {
+ @Parameter
+ private boolean parallelRead;
+
private static final int ONEMB = 1024 * 1024;
private ECReplicationConfig repConfig;
private TestBlockInputStreamFactory streamFactory;
private OzoneConfiguration conf = new OzoneConfiguration();
+ // counts the tasks handed to the parallel read executor
+ private final AtomicInteger parallelReadTasks = new AtomicInteger();
+ private ExecutorService parallelReadExecutor;
@BeforeEach
public void setup() {
repConfig = new ECReplicationConfig(3, 2,
ECReplicationConfig.EcCodec.RS, ONEMB);
streamFactory = new TestBlockInputStreamFactory();
+ // same shape as the client's pool: no queue, and the caller runs the task
when it is saturated
+ parallelReadExecutor = new ThreadPoolExecutor(0, 30, 60, TimeUnit.SECONDS,
new SynchronousQueue<>(),
+ new ThreadPoolExecutor.CallerRunsPolicy()) {
+ @Override
+ public void execute(Runnable command) {
+ parallelReadTasks.incrementAndGet();
+ super.execute(command);
+ }
+ };
+ }
+
+ @AfterEach
+ public void teardown() {
+ parallelReadExecutor.shutdownNow();
}
@Test
@@ -137,9 +174,7 @@ public void
testCorrectBlockSizePassedToBlockStreamLessThanCell()
OzoneClientConfig clientConfig = conf.getObject(OzoneClientConfig.class);
clientConfig.setChecksumVerify(true);
- try (ECBlockInputStream ecb = new ECBlockInputStream(repConfig,
- keyInfo, null, null, streamFactory,
- clientConfig)) {
+ try (ECBlockInputStream ecb = createStream(keyInfo, streamFactory,
clientConfig)) {
ecb.read(buf);
// We expect only 1 block stream and it should have a length passed of
// ONEMB - 100.
@@ -157,9 +192,7 @@ public void
testCorrectBlockSizePassedToBlockStreamTwoCells()
OzoneClientConfig clientConfig = conf.getObject(OzoneClientConfig.class);
clientConfig.setChecksumVerify(true);
- try (ECBlockInputStream ecb = new ECBlockInputStream(repConfig,
- keyInfo, null, null, streamFactory,
- clientConfig)) {
+ try (ECBlockInputStream ecb = createStream(keyInfo, streamFactory,
clientConfig)) {
ecb.read(buf);
List<TestBlockInputStream> streams = streamFactory.getBlockStreams();
assertEquals(ONEMB, streams.get(0).getLength());
@@ -176,9 +209,7 @@ public void
testCorrectBlockSizePassedToBlockStreamThreeCells()
OzoneClientConfig clientConfig = conf.getObject(OzoneClientConfig.class);
clientConfig.setChecksumVerify(true);
- try (ECBlockInputStream ecb = new ECBlockInputStream(repConfig,
- keyInfo, null, null, streamFactory,
- clientConfig)) {
+ try (ECBlockInputStream ecb = createStream(keyInfo, streamFactory,
clientConfig)) {
ecb.read(buf);
List<TestBlockInputStream> streams = streamFactory.getBlockStreams();
assertEquals(ONEMB, streams.get(0).getLength());
@@ -196,9 +227,7 @@ public void
testCorrectBlockSizePassedToBlockStreamThreeFullAndPartialStripe()
OzoneClientConfig clientConfig = conf.getObject(OzoneClientConfig.class);
clientConfig.setChecksumVerify(true);
- try (ECBlockInputStream ecb = new ECBlockInputStream(repConfig,
- keyInfo, null, null, streamFactory,
- clientConfig)) {
+ try (ECBlockInputStream ecb = createStream(keyInfo, streamFactory,
clientConfig)) {
ecb.read(buf);
List<TestBlockInputStream> streams = streamFactory.getBlockStreams();
assertEquals(4 * ONEMB, streams.get(0).getLength());
@@ -216,9 +245,7 @@ public void
testCorrectBlockSizePassedToBlockStreamSingleFullCell()
OzoneClientConfig clientConfig = conf.getObject(OzoneClientConfig.class);
clientConfig.setChecksumVerify(true);
- try (ECBlockInputStream ecb = new ECBlockInputStream(repConfig,
- keyInfo, null, null, streamFactory,
- clientConfig)) {
+ try (ECBlockInputStream ecb = createStream(keyInfo, streamFactory,
clientConfig)) {
ecb.read(buf);
List<TestBlockInputStream> streams = streamFactory.getBlockStreams();
assertEquals(ONEMB, streams.get(0).getLength());
@@ -234,9 +261,7 @@ public void
testCorrectBlockSizePassedToBlockStreamSeveralFullCells()
OzoneClientConfig clientConfig = conf.getObject(OzoneClientConfig.class);
clientConfig.setChecksumVerify(true);
- try (ECBlockInputStream ecb = new ECBlockInputStream(repConfig,
- keyInfo, null, null, streamFactory,
- clientConfig)) {
+ try (ECBlockInputStream ecb = createStream(keyInfo, streamFactory,
clientConfig)) {
ecb.read(buf);
List<TestBlockInputStream> streams = streamFactory.getBlockStreams();
assertEquals(3 * ONEMB, streams.get(0).getLength());
@@ -251,9 +276,7 @@ public void testSimpleRead() throws IOException {
ECStreamTestUtil.createKeyInfo(repConfig, 5, 5 * ONEMB);
OzoneClientConfig clientConfig = conf.getObject(OzoneClientConfig.class);
clientConfig.setChecksumVerify(true);
- try (ECBlockInputStream ecb = new ECBlockInputStream(repConfig,
- keyInfo, null, null, streamFactory,
- clientConfig)) {
+ try (ECBlockInputStream ecb = createStream(keyInfo, streamFactory,
clientConfig)) {
ByteBuffer buf = ByteBuffer.allocate(100);
@@ -277,9 +300,7 @@ public void testSimpleReadUnderOneChunk() throws
IOException {
ECStreamTestUtil.createKeyInfo(repConfig, 1, ONEMB);
OzoneClientConfig clientConfig = conf.getObject(OzoneClientConfig.class);
clientConfig.setChecksumVerify(true);
- try (ECBlockInputStream ecb = new ECBlockInputStream(repConfig,
- keyInfo, null, null, streamFactory,
- clientConfig)) {
+ try (ECBlockInputStream ecb = createStream(keyInfo, streamFactory,
clientConfig)) {
ByteBuffer buf = ByteBuffer.allocate(100);
@@ -299,9 +320,7 @@ public void testReadPastEOF() throws IOException {
ECStreamTestUtil.createKeyInfo(repConfig, 5, 50);
OzoneClientConfig clientConfig = conf.getObject(OzoneClientConfig.class);
clientConfig.setChecksumVerify(true);
- try (ECBlockInputStream ecb = new ECBlockInputStream(repConfig,
- keyInfo, null, null, streamFactory,
- clientConfig)) {
+ try (ECBlockInputStream ecb = createStream(keyInfo, streamFactory,
clientConfig)) {
ByteBuffer buf = ByteBuffer.allocate(100);
@@ -321,9 +340,7 @@ public void testReadCrossingMultipleECChunkBounds() throws
IOException {
ECStreamTestUtil.createKeyInfo(repConfig, 5, 5 * ONEMB);
OzoneClientConfig clientConfig = conf.getObject(OzoneClientConfig.class);
clientConfig.setChecksumVerify(true);
- try (ECBlockInputStream ecb = new ECBlockInputStream(repConfig,
- keyInfo, null, null, streamFactory,
- clientConfig)) {
+ try (ECBlockInputStream ecb = createStream(keyInfo, streamFactory,
clientConfig)) {
// EC Chunk size is 100 and 3-2. Create a byte buffer to read 3.5 chunks,
// so 350
@@ -346,6 +363,7 @@ public void testReadCrossingMultipleECChunkBounds() throws
IOException {
validateBufferContents(buf, 250, 350, (byte) 0);
}
+ assertEquals(parallelRead, parallelReadTasks.get() > 0);
for (TestBlockInputStream s : streamFactory.getBlockStreams()) {
assertTrue(s.isClosed());
}
@@ -359,9 +377,7 @@ public void testSeekPastBlockLength() throws IOException {
ECStreamTestUtil.createKeyInfo(repConfig, 5, 100);
OzoneClientConfig clientConfig = conf.getObject(OzoneClientConfig.class);
clientConfig.setChecksumVerify(true);
- try (ECBlockInputStream ecb = new ECBlockInputStream(repConfig,
- keyInfo, null, null, streamFactory,
- clientConfig)) {
+ try (ECBlockInputStream ecb = createStream(keyInfo, streamFactory,
clientConfig)) {
assertThrows(EOFException.class, () -> ecb.seek(1000));
}
}
@@ -374,9 +390,7 @@ public void testSeekToLength() throws IOException {
ECStreamTestUtil.createKeyInfo(repConfig, 5, 100);
OzoneClientConfig clientConfig = conf.getObject(OzoneClientConfig.class);
clientConfig.setChecksumVerify(true);
- try (ECBlockInputStream ecb = new ECBlockInputStream(repConfig,
- keyInfo, null, null, streamFactory,
- clientConfig)) {
+ try (ECBlockInputStream ecb = createStream(keyInfo, streamFactory,
clientConfig)) {
// When seek more than the length, should throw EOFException.
assertThrows(EOFException.class, () -> ecb.seek(101));
}
@@ -390,9 +404,7 @@ public void testSeekToLengthZeroLengthBlock() throws
IOException {
ECStreamTestUtil.createKeyInfo(repConfig, 5, 0);
OzoneClientConfig clientConfig = conf.getObject(OzoneClientConfig.class);
clientConfig.setChecksumVerify(true);
- try (ECBlockInputStream ecb = new ECBlockInputStream(repConfig,
- keyInfo, null, null, streamFactory,
- clientConfig)) {
+ try (ECBlockInputStream ecb = createStream(keyInfo, streamFactory,
clientConfig)) {
ecb.seek(0);
assertEquals(0, ecb.getPos());
assertEquals(0, ecb.getRemaining());
@@ -407,9 +419,7 @@ public void testSeekToValidPosition() throws IOException {
ECStreamTestUtil.createKeyInfo(repConfig, 5, 5 * ONEMB);
OzoneClientConfig clientConfig = conf.getObject(OzoneClientConfig.class);
clientConfig.setChecksumVerify(true);
- try (ECBlockInputStream ecb = new ECBlockInputStream(repConfig,
- keyInfo, null, null, streamFactory,
- clientConfig)) {
+ try (ECBlockInputStream ecb = createStream(keyInfo, streamFactory,
clientConfig)) {
ecb.seek(ONEMB - 1);
assertEquals(ONEMB - 1, ecb.getPos());
assertEquals(ONEMB * 4 + 1, ecb.getRemaining());
@@ -439,9 +449,7 @@ public void testErrorReadingBlockReportsBadLocation()
throws IOException {
ECStreamTestUtil.createKeyInfo(repConfig, 5, 5 * ONEMB);
OzoneClientConfig clientConfig = conf.getObject(OzoneClientConfig.class);
clientConfig.setChecksumVerify(true);
- try (ECBlockInputStream ecb = new ECBlockInputStream(repConfig,
- keyInfo, null, null, streamFactory,
- clientConfig)) {
+ try (ECBlockInputStream ecb = createStream(keyInfo, streamFactory,
clientConfig)) {
// Read a full stripe to ensure all streams are created in the stream
// factory
ByteBuffer buf = ByteBuffer.allocate(3 * ONEMB);
@@ -473,9 +481,7 @@ public void testNoErrorIfSpareLocationToRead() throws
IOException {
ECStreamTestUtil.createKeyInfo(repConfig, 8 * ONEMB, datanodes);
OzoneClientConfig clientConfig = conf.getObject(OzoneClientConfig.class);
clientConfig.setChecksumVerify(true);
- try (ECBlockInputStream ecb = new ECBlockInputStream(repConfig,
- keyInfo, null, null, streamFactory,
- clientConfig)) {
+ try (ECBlockInputStream ecb = createStream(keyInfo, streamFactory,
clientConfig)) {
// Read a full stripe to ensure all streams are created in the stream
// factory
ByteBuffer buf = ByteBuffer.allocate(3 * ONEMB);
@@ -540,9 +546,7 @@ public void testEcPipelineRefreshFunction() {
OzoneClientConfig clientConfig = conf.getObject(OzoneClientConfig.class);
clientConfig.setChecksumVerify(true);
- try (ECBlockInputStream ecb = new ECBlockInputStream(repConfig,
- keyInfo, null, null, streamFactory,
- clientConfig)) {
+ try (ECBlockInputStream ecb = createStream(keyInfo, streamFactory,
clientConfig)) {
Pipeline pipeline =
ecb.ecPipelineRefreshFunction(3, refreshFunction)
.apply(blockID)
@@ -569,8 +573,7 @@ public void
testZeroByteReadThrowsBadDataLocationException() throws Exception {
OzoneClientConfig clientConfig = conf.getObject(OzoneClientConfig.class);
clientConfig.setChecksumVerify(true);
- try (ECBlockInputStream ecb = new ECBlockInputStream(repConfig,
- keyInfo, null, null, streamFactory, clientConfig)) {
+ try (ECBlockInputStream ecb = createStream(keyInfo, streamFactory,
clientConfig)) {
// Read a full stripe first to initialize and create streams in the
factory
ByteBuffer buf = ByteBuffer.allocate(3 * ONEMB);
@@ -598,6 +601,215 @@ public void
testZeroByteReadThrowsBadDataLocationException() throws Exception {
}
}
+ public static Stream<Arguments> parallelReadConfigs() {
+ return Stream.of(
+ Arguments.of(new ECReplicationConfig(3, 2,
ECReplicationConfig.EcCodec.RS, 100)),
+ Arguments.of(new ECReplicationConfig(6, 3,
ECReplicationConfig.EcCodec.RS, 100)),
+ Arguments.of(new ECReplicationConfig(10, 4,
ECReplicationConfig.EcCodec.RS, 100)));
+ }
+
+ @ParameterizedTest
+ @MethodSource("parallelReadConfigs")
+ public void testParallelReadReturnsWrittenData(ECReplicationConfig ecConfig)
throws IOException {
+ repConfig = ecConfig;
+ int chunk = ecConfig.getEcChunkSize();
+ int stripe = chunk * ecConfig.getData();
+ // two full stripes and a partial last stripe ending inside its second cell
+ int blockLength = 2 * stripe + chunk + chunk / 2;
+ ECStreamTestUtil.TestBlockInputStreamFactory dataStreamFactory =
createDataStreamFactory(blockLength);
+ BlockLocationInfo keyInfo = ECStreamTestUtil.createKeyInfo(ecConfig,
ecConfig.getRequiredNodes(), blockLength);
+ dataStreamFactory.setCurrentPipeline(keyInfo.getPipeline());
+
+ int[][] ranges = {
+ {10, 50}, // within one cell
+ {50, 100}, // across two cells
+ {stripe - 30, 60}, // across a stripe boundary
+ {0, blockLength}, // the whole block
+ {2 * stripe + 10, chunk + 40}, // into the partial last stripe
+ {blockLength - 130, 500}, // past the end of the block
+ };
+ try (ECBlockInputStream ecb = createParallelStream(keyInfo,
dataStreamFactory, true)) {
+ for (int[] range : ranges) {
+ ecb.seek(range[0]);
+ ByteBuffer buf = ByteBuffer.allocate(range[1]);
+ int expected = Math.min(range[1], blockLength - range[0]);
+ assertEquals(expected, ecb.read(buf), "range " +
Arrays.toString(range));
+ assertDataMatches(buf, range[0], expected);
+ assertEquals(range[0] + expected, ecb.getPos());
+ }
+ assertEquals(-1, ecb.read(ByteBuffer.allocate(10)));
+
+ // sequential reads without a seek, through a byte array
+ ecb.seek(0);
+ byte[] all = new byte[blockLength];
+ int offset = 0;
+ int read;
+ while ((read = ecb.read(all, offset, Math.min(stripe + chunk / 2,
blockLength - offset))) > 0) {
+ offset += read;
+ }
+ assertEquals(blockLength, offset);
+ assertDataMatches(ByteBuffer.wrap(all), 0, blockLength);
+ }
+ assertThat(parallelReadTasks.get()).isPositive();
+ }
+
+ @Test
+ public void testMultiCellReadReadsIndexesConcurrently() throws IOException {
+ repConfig = new ECReplicationConfig(3, 2, ECReplicationConfig.EcCodec.RS,
100);
+ int blockLength = 3 * 300;
+ ECStreamTestUtil.TestBlockInputStreamFactory dataStreamFactory =
createDataStreamFactory(blockLength);
+ BlockLocationInfo keyInfo = ECStreamTestUtil.createKeyInfo(repConfig, 5,
blockLength);
+ dataStreamFactory.setCurrentPipeline(keyInfo.getPipeline());
+ // each read of the three data indexes blocks until all three are in
flight, so a serial read times out
+ dataStreamFactory.setReadBarrier(new CountDownLatch(3));
+
+ try (ECBlockInputStream ecb = createParallelStream(keyInfo,
dataStreamFactory, true)) {
+ ByteBuffer buf = ByteBuffer.allocate(300);
+ assertEquals(300, ecb.read(buf));
+ assertDataMatches(buf, 0, 300);
+ }
+ // the calling thread reads the first index itself
+ assertEquals(2, parallelReadTasks.get());
+ }
+
+ @Test
+ public void testSingleCellReadAndDisabledFlagDoNotUseExecutor() throws
IOException {
+ repConfig = new ECReplicationConfig(3, 2, ECReplicationConfig.EcCodec.RS,
100);
+ int blockLength = 3 * 300;
+ BlockLocationInfo keyInfo = ECStreamTestUtil.createKeyInfo(repConfig, 5,
blockLength);
+
+ ECStreamTestUtil.TestBlockInputStreamFactory dataStreamFactory =
createDataStreamFactory(blockLength);
+ dataStreamFactory.setCurrentPipeline(keyInfo.getPipeline());
+ try (ECBlockInputStream ecb = createParallelStream(keyInfo,
dataStreamFactory, true)) {
+ ecb.seek(120);
+ ByteBuffer buf = ByteBuffer.allocate(80);
+ assertEquals(80, ecb.read(buf));
+ assertDataMatches(buf, 120, 80);
+ }
+ assertEquals(0, parallelReadTasks.get());
+
+ dataStreamFactory = createDataStreamFactory(blockLength);
+ dataStreamFactory.setCurrentPipeline(keyInfo.getPipeline());
+ try (ECBlockInputStream ecb = createParallelStream(keyInfo,
dataStreamFactory, false)) {
+ ByteBuffer buf = ByteBuffer.allocate(blockLength);
+ assertEquals(blockLength, ecb.read(buf));
+ assertDataMatches(buf, 0, blockLength);
+ }
+ assertEquals(0, parallelReadTasks.get());
+ }
+
+ @Test
+ public void testParallelReadReportsAllFailedIndexes() throws IOException {
+ repConfig = new ECReplicationConfig(3, 2, ECReplicationConfig.EcCodec.RS,
100);
+ int blockLength = 3 * 300;
+ BlockLocationInfo keyInfo = ECStreamTestUtil.createKeyInfo(repConfig, 5,
blockLength);
+ ECStreamTestUtil.TestBlockInputStreamFactory dataStreamFactory =
createDataStreamFactory(blockLength);
+ dataStreamFactory.setCurrentPipeline(keyInfo.getPipeline());
+ dataStreamFactory.setFailIndexes(2, 3);
+
+ try (ECBlockInputStream ecb = createParallelStream(keyInfo,
dataStreamFactory, true)) {
+ ByteBuffer buf = ByteBuffer.allocate(300);
+ BadDataLocationException e =
assertThrows(BadDataLocationException.class, () -> ecb.read(buf));
+ assertEquals(Arrays.asList(1, 2), e.getFailedLocationIndexes());
+ assertEquals(2, e.getFailedLocations().size());
+ for (DatanodeDetails dn : e.getFailedLocations()) {
+ assertThat(keyInfo.getPipeline().getReplicaIndex(dn)).isIn(2, 3);
+ }
+ // the first cell was read, and the failure of the second must not be
hidden by the third
+ assertEquals(100, ecb.getPos());
+ assertEquals(100, buf.position());
+ }
+ }
+
+ @Test
+ public void testReadAfterFailedParallelReadReturnsCorrectData() throws
IOException {
+ repConfig = new ECReplicationConfig(3, 2, ECReplicationConfig.EcCodec.RS,
100);
+ int blockLength = 3 * 300;
+ BlockLocationInfo keyInfo = ECStreamTestUtil.createKeyInfo(repConfig, 5,
blockLength);
+ ECStreamTestUtil.TestBlockInputStreamFactory dataStreamFactory =
createDataStreamFactory(blockLength);
+ dataStreamFactory.setCurrentPipeline(keyInfo.getPipeline());
+ dataStreamFactory.setFailIndexes(2);
+
+ try (ECBlockInputStream ecb = createParallelStream(keyInfo,
dataStreamFactory, true)) {
+ assertThrows(BadDataLocationException.class, () ->
ecb.read(ByteBuffer.allocate(300)));
+ assertEquals(100, ecb.getPos());
+ // index 3 has read its cell although the position stays before it, so
the retry must seek its stream back
+ dataStreamFactory.getBlockStream(2).setShouldError(false);
+ ByteBuffer buf = ByteBuffer.allocate(200);
+ assertEquals(200, ecb.read(buf));
+ assertDataMatches(buf, 100, 200);
+ assertEquals(300, ecb.getPos());
+ }
+ }
+
+ @Test
+ public void testParallelReadRetriesFailedIndexOnSpare() throws IOException {
+ repConfig = new ECReplicationConfig(3, 2, ECReplicationConfig.EcCodec.RS,
100);
+ int blockLength = 3 * 300;
+ Map<DatanodeDetails, Integer> datanodes = new LinkedHashMap<>();
+ for (int i = 1; i <= repConfig.getRequiredNodes(); i++) {
+ datanodes.put(MockDatanodeDetails.randomDatanodeDetails(), i);
+ }
+ // a spare location for index 2
+ datanodes.put(MockDatanodeDetails.randomDatanodeDetails(), 2);
+ BlockLocationInfo keyInfo = ECStreamTestUtil.createKeyInfo(repConfig,
blockLength, datanodes);
+ ECStreamTestUtil.TestBlockInputStreamFactory dataStreamFactory =
createDataStreamFactory(blockLength);
+ dataStreamFactory.setCurrentPipeline(keyInfo.getPipeline());
+ dataStreamFactory.setFailIndexes(2);
+
+ try (ECBlockInputStream ecb = createParallelStream(keyInfo,
dataStreamFactory, true)) {
+ ecb.seek(50);
+ ByteBuffer buf = ByteBuffer.allocate(600);
+ assertEquals(600, ecb.read(buf));
+ assertDataMatches(buf, 50, 600);
+ assertEquals(650, ecb.getPos());
+ }
+ }
+
+ /** Creates the stream under test, reading the cells in parallel if the
class runs with parallelRead. */
+ private ECBlockInputStream createStream(BlockLocationInfo keyInfo,
BlockInputStreamFactory factory,
+ OzoneClientConfig clientConfig) {
+ clientConfig.setEcParallelReadEnabled(parallelRead);
+ return new ECBlockInputStream(repConfig, keyInfo, null, null, factory,
clientConfig, () -> parallelReadExecutor);
+ }
+
+ private ECBlockInputStream createParallelStream(BlockLocationInfo keyInfo,
+ BlockInputStreamFactory factory, boolean parallelReadEnabled) {
+ OzoneClientConfig clientConfig = conf.getObject(OzoneClientConfig.class);
+ clientConfig.setEcParallelReadEnabled(parallelReadEnabled);
+ return new ECBlockInputStream(repConfig, keyInfo, null, null, factory,
clientConfig,
+ () -> parallelReadExecutor);
+ }
+
+ /**
+ * Creates a stream factory whose data index streams hold the block data,
where the byte at block offset p is
+ * {@link #dataAt(long)}.
+ */
+ private ECStreamTestUtil.TestBlockInputStreamFactory
createDataStreamFactory(int blockLength) {
+ List<ByteBuffer> indexData = new ArrayList<>();
+ for (int i = 1; i <= repConfig.getRequiredNodes(); i++) {
+ indexData.add(ByteBuffer.allocate((int)
ECBlockInputStream.internalBlockLength(i, repConfig, blockLength)));
+ }
+ int chunk = repConfig.getEcChunkSize();
+ for (long p = 0; p < blockLength; p++) {
+ int index = (int) ((p / chunk) % repConfig.getData());
+ indexData.get(index).put(dataAt(p));
+ }
+ ECStreamTestUtil.TestBlockInputStreamFactory factory = new
ECStreamTestUtil.TestBlockInputStreamFactory();
+ factory.setBlockStreamData(indexData);
+ return factory;
+ }
+
+ private static byte dataAt(long blockOffset) {
+ return (byte) (blockOffset * 31 + 7);
+ }
+
+ private static void assertDataMatches(ByteBuffer buf, long blockOffset, int
length) {
+ for (int i = 0; i < length; i++) {
+ assertEquals(dataAt(blockOffset + i), buf.get(i), "byte " + i + " at
block offset " + (blockOffset + i));
+ }
+ }
+
private void validateBufferContents(ByteBuffer buf, int from, int to,
byte val) {
for (int i = from; i < to; i++) {
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 22b74226072..e85e9bc4816 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
@@ -44,6 +44,7 @@
import java.security.InvalidKeyException;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
@@ -211,6 +212,10 @@ public class RpcClient implements ClientProtocol {
// for reconstruction.
private static final int EC_RECONSTRUCT_STRIPE_READ_POOL_MIN_SIZE = 3;
+ // A parallel read of the minimal recommended EC policy rs-3-2-1024k
+ // spans at most 3 data indexes.
+ private static final int EC_PARALLEL_READ_POOL_MIN_SIZE = 3;
+
private static final int WRITE_POOL_MIN_SIZE = 1;
private final ConfigurationSource conf;
@@ -231,6 +236,7 @@ public class RpcClient implements ClientProtocol {
private final BlockInputStreamFactory blockInputStreamFactory;
private final OzoneManagerVersion omVersion;
private final MemoizedSupplier<ExecutorService> ecReconstructExecutor;
+ private final MemoizedSupplier<ExecutorService> ecParallelReadExecutor;
private final ContainerClientMetrics.Handle clientMetricsHandle;
private final ContainerClientMetrics clientMetrics;
private final MemoizedSupplier<ExecutorService> writeExecutor;
@@ -258,6 +264,11 @@ public RpcClient(ConfigurationSource conf, String
omServiceId)
this.ecReconstructExecutor = MemoizedSupplier.valueOf(() ->
createThreadPoolExecutor(
EC_RECONSTRUCT_STRIPE_READ_POOL_MIN_SIZE,
clientConfig.getEcReconstructStripeReadPoolLimit(),
"ec-reconstruct-reader-TID-%d"));
+ // Created on first use, after ozoneManagerClient, which holds the
thread-local request context.
+ // The core size must not exceed the limit, which can be configured below
EC_PARALLEL_READ_POOL_MIN_SIZE.
+ this.ecParallelReadExecutor = MemoizedSupplier.valueOf(() ->
createRequestContextPropagatingExecutor(
+ Math.min(EC_PARALLEL_READ_POOL_MIN_SIZE,
clientConfig.getEcParallelReadPoolLimit()),
+ clientConfig.getEcParallelReadPoolLimit(),
"ec-parallel-reader-TID-%d", requestContext()));
this.writeExecutor = MemoizedSupplier.valueOf(() ->
createThreadPoolExecutor(
WRITE_POOL_MIN_SIZE, Integer.MAX_VALUE, "client-write-TID-%d"));
@@ -340,7 +351,7 @@ public void onRemoval(
StorageUnit.GB);
this.byteBufferPool = new BoundedElasticByteBufferPool(maxPoolSize);
this.blockInputStreamFactory = BlockInputStreamFactoryImpl
- .getInstance(byteBufferPool, ecReconstructExecutor);
+ .getInstance(byteBufferPool, ecReconstructExecutor,
ecParallelReadExecutor);
this.clientMetricsHandle = ContainerClientMetrics.acquireHandle();
this.clientMetrics = clientMetricsHandle.metrics();
@@ -2086,6 +2097,7 @@ private OmKeyInfo getKeyInfo(OmKeyArgs keyArgs) throws
IOException {
public void close() throws IOException {
IOUtils.cleanupWithLogger(LOG,
() -> shutdownExecutor(ecReconstructExecutor),
+ () -> shutdownExecutor(ecParallelReadExecutor),
() -> shutdownExecutor(writeExecutor),
ozoneManagerClient,
xceiverClientManager,
@@ -3254,4 +3266,68 @@ private static ExecutorService createThreadPoolExecutor(
new
ThreadFactoryBuilder().setNameFormat(threadNameFormat).setDaemon(true).build(),
new ThreadPoolExecutor.CallerRunsPolicy());
}
+
+ /** The thread-locals that hold the request context sent with every OM
request. */
+ private List<ThreadLocal<?>> requestContext() {
+ return Arrays.asList(ozoneManagerClient.getS3CredentialsProvider(),
+ ozoneManagerClient.getReadConsistencyHintProvider());
+ }
+
+ /**
+ * Like {@link #createThreadPoolExecutor}, but every task runs with the
request context of the thread that submitted
+ * it: the given thread-locals, here the S3 authentication and the read
consistency hint. A task can call OM, for
+ * example to refresh the locations of a block it reads; with the S3 auth
check enabled that call fails without the
+ * request's authentication, and without the hint it uses the default read
consistency instead of the request's.
+ */
+ private static ExecutorService createRequestContextPropagatingExecutor(int
corePoolSize, int maximumPoolSize,
+ String threadNameFormat, List<ThreadLocal<?>> context) {
+ return new ThreadPoolExecutor(corePoolSize, maximumPoolSize, 60,
TimeUnit.SECONDS, new SynchronousQueue<>(),
+ new
ThreadFactoryBuilder().setNameFormat(threadNameFormat).setDaemon(true).build(),
+ new ThreadPoolExecutor.CallerRunsPolicy()) {
+ @Override
+ public void execute(Runnable command) {
+ super.execute(withSubmitterContext(command, context));
+ }
+ };
+ }
+
+ /**
+ * Wraps the task to run with the submitting thread's values of the given
thread-locals, or with none where it has
+ * none, and to restore the running thread's own values afterwards, so a
pooled thread never keeps another request's
+ * context.
+ */
+ @VisibleForTesting
+ static Runnable withSubmitterContext(Runnable task, List<ThreadLocal<?>>
context) {
+ final List<Object> submitterValues = currentValues(context);
+ return () -> {
+ final List<Object> previousValues = currentValues(context);
+ setOrRemove(context, submitterValues);
+ try {
+ task.run();
+ } finally {
+ setOrRemove(context, previousValues);
+ }
+ };
+ }
+
+ private static List<Object> currentValues(List<ThreadLocal<?>> threadLocals)
{
+ List<Object> values = new ArrayList<>(threadLocals.size());
+ for (ThreadLocal<?> threadLocal : threadLocals) {
+ values.add(threadLocal.get());
+ }
+ return values;
+ }
+
+ @SuppressWarnings("unchecked")
+ private static void setOrRemove(List<ThreadLocal<?>> threadLocals,
List<Object> values) {
+ for (int i = 0; i < threadLocals.size(); i++) {
+ ThreadLocal<Object> threadLocal = (ThreadLocal<Object>)
threadLocals.get(i);
+ Object value = values.get(i);
+ if (value == null) {
+ threadLocal.remove();
+ } else {
+ threadLocal.set(value);
+ }
+ }
+ }
}
diff --git
a/hadoop-ozone/client/src/test/java/org/apache/hadoop/ozone/client/MockDatanodeStorage.java
b/hadoop-ozone/client/src/test/java/org/apache/hadoop/ozone/client/MockDatanodeStorage.java
index 5a25eb9abdf..3cadd5bb8b2 100644
---
a/hadoop-ozone/client/src/test/java/org/apache/hadoop/ozone/client/MockDatanodeStorage.java
+++
b/hadoop-ozone/client/src/test/java/org/apache/hadoop/ozone/client/MockDatanodeStorage.java
@@ -24,6 +24,10 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.hadoop.hdds.client.BlockID;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos;
@@ -52,11 +56,51 @@ public class MockDatanodeStorage {
private final Map<String, ByteString> data = new HashMap<>();
private IOException exception = null;
+ private final AtomicInteger getBlockFailures = new AtomicInteger();
+ private final List<String> failedGetBlockThreads = new
CopyOnWriteArrayList<>();
+ private final CountDownLatch getBlockFailed = new CountDownLatch(1);
+ private volatile CountDownLatch getBlockGate;
public void setStorageFailed(IOException reason) {
this.exception = reason;
}
+ /** Makes the next {@code count} GetBlock calls fail with
CONTAINER_NOT_FOUND, as after a container move. */
+ public void failNextGetBlocks(int count) {
+ getBlockFailures.set(count);
+ }
+
+ /** Returns true, and records the calling thread, if this GetBlock call
should fail. */
+ boolean consumeGetBlockFailure() {
+ if (getBlockFailures.getAndUpdate(n -> n > 0 ? n - 1 : 0) > 0) {
+ failedGetBlockThreads.add(Thread.currentThread().getName());
+ getBlockFailed.countDown();
+ return true;
+ }
+ return false;
+ }
+
+ /** Makes GetBlock calls on this datanode wait, for at most 10 seconds,
until a GetBlock call on other has failed. */
+ public void holdGetBlocksUntilFailureOn(MockDatanodeStorage other) {
+ getBlockGate = other.getBlockFailed;
+ }
+
+ void awaitGetBlockGate() {
+ CountDownLatch gate = getBlockGate;
+ if (gate != null) {
+ try {
+ gate.await(10, TimeUnit.SECONDS);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ }
+ }
+
+ /** Names of the threads whose GetBlock call failed. */
+ public List<String> getFailedGetBlockThreads() {
+ return failedGetBlockThreads;
+ }
+
private boolean isIncrementalChunkList(BlockData blockData) {
for (ContainerProtos.KeyValue kv : blockData.getMetadataList()) {
if (kv.getKey().equals(INCREMENTAL_CHUNK_LIST)) {
diff --git
a/hadoop-ozone/client/src/test/java/org/apache/hadoop/ozone/client/MockXceiverClientSpi.java
b/hadoop-ozone/client/src/test/java/org/apache/hadoop/ozone/client/MockXceiverClientSpi.java
index 63d49a29394..90c2c145f6a 100644
---
a/hadoop-ozone/client/src/test/java/org/apache/hadoop/ozone/client/MockXceiverClientSpi.java
+++
b/hadoop-ozone/client/src/test/java/org/apache/hadoop/ozone/client/MockXceiverClientSpi.java
@@ -94,6 +94,10 @@ public XceiverClientReply sendCommandAsync(
return result(request,
r -> r.setPutBlock(putBlock(request.getPutBlock())));
case GetBlock:
+ datanodeStorage.awaitGetBlockGate();
+ if (datanodeStorage.consumeGetBlockFailure()) {
+ return result(request, r -> r.setResult(Result.CONTAINER_NOT_FOUND));
+ }
return result(request,
r -> r.setGetBlock(getBlock(request.getGetBlock())));
case ListBlock:
diff --git
a/hadoop-ozone/client/src/test/java/org/apache/hadoop/ozone/client/TestOzoneECClient.java
b/hadoop-ozone/client/src/test/java/org/apache/hadoop/ozone/client/TestOzoneECClient.java
index 502e11a3095..2afc740b473 100644
---
a/hadoop-ozone/client/src/test/java/org/apache/hadoop/ozone/client/TestOzoneECClient.java
+++
b/hadoop-ozone/client/src/test/java/org/apache/hadoop/ozone/client/TestOzoneECClient.java
@@ -18,10 +18,12 @@
package org.apache.hadoop.ozone.client;
import static java.nio.charset.StandardCharsets.UTF_8;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.spy;
@@ -36,6 +38,7 @@
import java.util.List;
import java.util.Map;
import java.util.UUID;
+import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.apache.hadoop.conf.StorageUnit;
@@ -63,7 +66,9 @@
import org.apache.hadoop.ozone.client.rpc.RpcClient;
import org.apache.hadoop.ozone.om.helpers.OmKeyLocationInfo;
import org.apache.hadoop.ozone.om.helpers.OmKeyLocationInfoGroup;
+import org.apache.hadoop.ozone.om.helpers.ReadConsistency;
import org.apache.hadoop.ozone.om.helpers.ServiceInfoEx;
+import org.apache.hadoop.ozone.om.protocol.S3Auth;
import org.apache.hadoop.ozone.om.protocolPB.OmTransport;
import org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos;
import org.apache.ozone.erasurecode.rawcoder.RSRawErasureCoderFactory;
@@ -74,14 +79,23 @@
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.Parameter;
+import org.junit.jupiter.params.ParameterizedClass;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.MockedStatic;
/**
* Real unit test for OzoneECClient.
* <p>
- * Used for testing Ozone client without external network calls.
+ * Used for testing Ozone client without external network calls. Every test
runs with EC cells read one at a time
+ * and with them read in parallel.
*/
+@ParameterizedClass
+@ValueSource(booleans = {false, true})
public class TestOzoneECClient {
+ @Parameter
+ private boolean parallelRead;
private int chunkSize = 1024;
private int dataBlocks = 3;
private int parityBlocks = 2;
@@ -112,8 +126,12 @@ private void createNewClient(ConfigurationSource config,
createNewClient(config, new MockOmTransport(blkAllocator));
}
- private void createNewClient(ConfigurationSource config,
+ private void createNewClient(ConfigurationSource source,
final MockOmTransport transport) throws IOException {
+ OzoneConfiguration config = new
OzoneConfiguration(OzoneConfiguration.of(source));
+ OzoneClientConfig clientConfig = config.getObject(OzoneClientConfig.class);
+ clientConfig.setEcParallelReadEnabled(parallelRead);
+ config.setFromObject(clientConfig);
client = new OzoneClient(config, new RpcClient(config, null) {
@Override
@@ -151,6 +169,77 @@ public void close() throws IOException {
client.close();
}
+ /**
+ * A block location refresh made while reading carries the request's S3
authentication and read consistency hint,
+ * also when the refreshing cell is read by a parallel read worker. With the
S3 auth check enabled (S3 Gateway), an
+ * OM call without the authentication fails; without the hint it would use
the default read consistency.
+ */
+ @Test
+ public void testLocationRefreshDuringReadKeepsRequestContext() throws
IOException {
+ List<OzoneManagerProtocolProtos.OMRequest> omRequests = new
CopyOnWriteArrayList<>();
+ MockOmTransport recordingTransport = new MockOmTransport(allocator) {
+ @Override
+ public OzoneManagerProtocolProtos.OMResponse
submitRequest(OzoneManagerProtocolProtos.OMRequest payload)
+ throws IOException {
+ omRequests.add(payload);
+ return super.submitRequest(payload);
+ }
+ };
+ close();
+ createNewClient(conf, recordingTransport);
+ client.getProxy().setThreadLocalS3Auth(new S3Auth("stringToSign",
"signature", "accessId", "user"));
+ try {
+
client.getProxy().setThreadLocalReadConsistency(ReadConsistency.LOCAL_LEASE,
5L, 1000L);
+ OzoneBucket bucket = writeIntoECKey(inputChunks, keyName,
+ new DefaultReplicationConfig(new ECReplicationConfig(dataBlocks,
parityBlocks,
+ ECReplicationConfig.EcCodec.RS, chunkSize)));
+
+ // The datanode of the third data cell answers the first GetBlock with
CONTAINER_NOT_FOUND, so its stream
+ // refreshes the block locations from OM. In a parallel read that cell
is read by a worker thread.
+ HddsProtos.Pipeline pipeline =
recordingTransport.getKeys().get(volumeName).get(bucketName)
+
.get(keyName).getKeyLocationListList().get(0).getKeyLocations(0).getPipeline();
+ Map<DatanodeDetails, MockDatanodeStorage> storages =
factoryStub.getStorages();
+ MockDatanodeStorage storage =
+ storages.get(getMatchingStorage(storages,
DatanodeID.fromProto(pipeline.getMembers(2).getId())));
+ storage.failNextGetBlocks(1);
+ if (parallelRead) {
+ // The reading thread reads the first cell, and any cell whose task
has not started yet. Holding it in the
+ // first cell until the third has failed makes a worker read the
third, however late the pool starts.
+ storages.get(getMatchingStorage(storages,
DatanodeID.fromProto(pipeline.getMembers(0).getId())))
+ .holdGetBlocksUntilFailureOn(storage);
+ }
+ int requestsBeforeRead = omRequests.size();
+
+ byte[] read = new byte[inputSize];
+ try (OzoneInputStream is = bucket.readKey(keyName)) {
+ assertEquals(inputSize, is.read(read));
+ }
+ for (int i = 0; i < dataBlocks; i++) {
+ assertArrayEquals(inputChunks[i], Arrays.copyOfRange(read, i *
chunkSize, (i + 1) * chunkSize));
+ }
+
+ assertEquals(1, storage.getFailedGetBlockThreads().size());
+ if (parallelRead) {
+
assertThat(storage.getFailedGetBlockThreads().get(0)).startsWith("ec-parallel-reader-");
+ }
+ // The open, and the refresh after the failed GetBlock
+ List<OzoneManagerProtocolProtos.OMRequest> readRequests =
+ omRequests.subList(requestsBeforeRead, omRequests.size());
+ assertThat(readRequests).hasSizeGreaterThanOrEqualTo(2);
+ for (OzoneManagerProtocolProtos.OMRequest request : readRequests) {
+ assertTrue(request.hasS3Authentication(), request.getCmdType() + "
sent without S3 authentication");
+ OzoneManagerProtocolProtos.ReadConsistencyHint hint =
request.getReadConsistencyHint();
+ assertEquals(ReadConsistency.LOCAL_LEASE.toProto(),
hint.getReadConsistency(),
+ request.getCmdType() + " sent without the request's read
consistency");
+ assertEquals(5L, hint.getLocalLeaseContext().getLogLimit());
+ assertEquals(1000L, hint.getLocalLeaseContext().getLeaseTimeMs());
+ }
+ } finally {
+ client.getProxy().clearThreadLocalS3Auth();
+ client.getProxy().clearThreadLocalReadConsistency();
+ }
+ }
+
@Test
public void testPutECKeyAndCheckDNStoredData() throws IOException {
OzoneBucket bucket = writeIntoECKey(inputChunks, keyName, null);
@@ -575,6 +664,24 @@ public void testPartialStripeWithPartialLastChunk()
}
}
+ /** A parallel read pool limit below the pool's default core size still
reads multi-cell ranges. */
+ @ParameterizedTest
+ @ValueSource(ints = {1, 2})
+ public void testReadWithSmallParallelReadPoolLimit(int poolLimit) throws
IOException {
+ OzoneClientConfig clientConfig = conf.getObject(OzoneClientConfig.class);
+ clientConfig.setEcParallelReadPoolLimit(poolLimit);
+ conf.setFromObject(clientConfig);
+ createNewClient(conf, transportStub);
+ OzoneBucket bucket = writeIntoECKey(inputChunks, keyName, null);
+ try (OzoneInputStream is = bucket.readKey(keyName)) {
+ byte[] fileContent = new byte[inputSize];
+ assertEquals(inputSize, is.read(fileContent));
+ for (int i = 0; i < dataBlocks; i++) {
+ assertArrayEquals(inputChunks[i], Arrays.copyOfRange(fileContent, i *
chunkSize, (i + 1) * chunkSize));
+ }
+ }
+ }
+
@Test
public void test10D4PConfigWithPartialStripe()
throws IOException {
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 1283f883827..61839ec70d9 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
@@ -23,6 +23,7 @@
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
+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.eq;
@@ -57,6 +58,7 @@
import org.apache.hadoop.ozone.om.helpers.S3VolumeContext;
import org.apache.hadoop.ozone.om.helpers.ServiceInfo;
import org.apache.hadoop.ozone.om.helpers.ServiceInfoEx;
+import org.apache.hadoop.ozone.om.protocol.S3Auth;
import org.apache.hadoop.ozone.om.protocolPB.OmTransport;
import org.apache.hadoop.ozone.om.protocolPB.OzoneManagerClientProtocol;
import org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos;
@@ -623,4 +625,54 @@ protected XceiverClientFactory createXceiverClientFactory(
}
};
}
+
+ /**
+ * A task wrapped by withSubmitterContext sees the submitting thread's
values of every given thread-local, or none
+ * where it has none, and the running thread's own values are restored
afterwards, also when the task throws.
+ */
+ @Test
+ public void testWithSubmitterContextPropagatesAndRestores() {
+ ThreadLocal<S3Auth> auth = new ThreadLocal<>();
+ ThreadLocal<String> hint = new ThreadLocal<>();
+ List<ThreadLocal<?>> context = Arrays.asList(auth, hint);
+ S3Auth submitterAuth = new S3Auth("stringToSign", "signature",
"submitter", "submitterUser");
+ S3Auth workerAuth = new S3Auth("stringToSign", "signature", "worker",
"workerUser");
+ List<List<Object>> seen = new LinkedList<>();
+ Runnable observe = () -> seen.add(Arrays.asList(auth.get(), hint.get()));
+
+ auth.set(submitterAuth);
+ hint.set("submitterHint");
+ Runnable withSubmitter = RpcClient.withSubmitterContext(observe, context);
+ hint.remove();
+ Runnable withAuthOnly = RpcClient.withSubmitterContext(observe, context);
+ auth.remove();
+ Runnable withNothing = RpcClient.withSubmitterContext(observe, context);
+
+ // the running thread (a pool worker) holds different values
+ auth.set(workerAuth);
+ hint.set("workerHint");
+ for (Runnable task : Arrays.asList(withSubmitter, withAuthOnly,
withNothing)) {
+ task.run();
+ assertSame(workerAuth, auth.get());
+ assertEquals("workerHint", hint.get());
+ }
+ assertEquals(Arrays.asList(Arrays.asList(submitterAuth, "submitterHint"),
Arrays.asList(submitterAuth, null),
+ Arrays.asList(null, null)), seen);
+
+ // a running thread without values is left without them
+ auth.remove();
+ hint.remove();
+ withSubmitter.run();
+ assertNull(auth.get());
+ assertNull(hint.get());
+
+ auth.set(workerAuth);
+ hint.set("workerHint");
+ Runnable failing = RpcClient.withSubmitterContext(() -> {
+ throw new IllegalStateException("task failed");
+ }, context);
+ assertThrows(IllegalStateException.class, failing::run);
+ assertSame(workerAuth, auth.get());
+ assertEquals("workerHint", hint.get());
+ }
}
diff --git
a/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/protocolPB/OzoneManagerClientProtocol.java
b/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/protocolPB/OzoneManagerClientProtocol.java
index 00adf4f49af..f64d1a106f7 100644
---
a/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/protocolPB/OzoneManagerClientProtocol.java
+++
b/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/protocolPB/OzoneManagerClientProtocol.java
@@ -20,6 +20,7 @@
import org.apache.hadoop.ozone.om.helpers.ReadConsistency;
import org.apache.hadoop.ozone.om.protocol.OzoneManagerProtocol;
import org.apache.hadoop.ozone.om.protocol.S3Auth;
+import
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.ReadConsistencyHint;
/**
* OzoneManagerClientProtocol defines interfaces needed on the client side
@@ -48,4 +49,10 @@ void setThreadLocalReadConsistency(ReadConsistency
readConsistency,
void clearThreadLocalReadConsistency();
ThreadLocal<S3Auth> getS3CredentialsProvider();
+
+ /**
+ * The thread-local read consistency hint sent with OM read requests, so it
can be carried to threads that make
+ * OM calls on behalf of the request.
+ */
+ ThreadLocal<ReadConsistencyHint> getReadConsistencyHintProvider();
}
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 5d5e20d0a34..e36b3a40e40 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
@@ -2371,6 +2371,12 @@ public ThreadLocal<S3Auth> getS3CredentialsProvider() {
return this.threadLocalS3Auth;
}
+ @Override
+ @SkipTracing
+ public ThreadLocal<ReadConsistencyHint> getReadConsistencyHintProvider() {
+ return this.threadLocalReadConsistencyHint;
+ }
+
@Override
@SkipTracing
public S3Auth getThreadLocalS3Auth() {
diff --git
a/hadoop-ozone/integration-test-s3/src/test/java/org/apache/hadoop/ozone/s3/S3GatewayService.java
b/hadoop-ozone/integration-test-s3/src/test/java/org/apache/hadoop/ozone/s3/S3GatewayService.java
index 44ed2f8a419..c9af4a212f6 100644
---
a/hadoop-ozone/integration-test-s3/src/test/java/org/apache/hadoop/ozone/s3/S3GatewayService.java
+++
b/hadoop-ozone/integration-test-s3/src/test/java/org/apache/hadoop/ozone/s3/S3GatewayService.java
@@ -19,23 +19,59 @@
import static
org.apache.ozone.test.GenericTestUtils.PortAllocator.localhostWithFreePort;
+import java.util.function.Consumer;
import org.apache.hadoop.hdds.conf.OzoneConfiguration;
import org.apache.hadoop.ozone.MiniOzoneCluster;
import org.apache.ratis.util.Preconditions;
+import software.amazon.awssdk.services.s3.S3Client;
/** S3 Gateway for {@link MiniOzoneCluster}. */
public class S3GatewayService implements MiniOzoneCluster.Service {
private static final String[] NO_ARGS = new String[0];
+ private final Consumer<OzoneConfiguration> configOverrides;
+ private final String httpAddressKey;
private Gateway s3g;
+ public S3GatewayService() {
+ this(conf -> { }, null);
+ }
+
+ /**
+ * @param configOverrides applied to the configuration of this gateway only
+ * @param httpAddressKey if not null, this gateway's {@code host:port} http
address is set under this key in the
+ * cluster configuration, so a test can address this gateway directly
+ */
+ public S3GatewayService(Consumer<OzoneConfiguration> configOverrides, String
httpAddressKey) {
+ this.configOverrides = configOverrides;
+ this.httpAddressKey = httpAddressKey;
+ }
+
@Override
public void start(OzoneConfiguration conf) throws Exception {
Preconditions.assertNull(s3g, "S3 Gateway already started");
- configureS3G(new OzoneConfiguration(conf));
+ OzoneConfiguration s3gConf = new OzoneConfiguration(conf);
+ configOverrides.accept(s3gConf);
+ configureS3G(s3gConf);
s3g = new Gateway();
s3g.execute(NO_ARGS);
+ createOzoneClient(s3gConf);
+ if (httpAddressKey != null) {
+ conf.set(httpAddressKey,
s3gConf.get(S3GatewayConfigKeys.OZONE_S3G_HTTP_ADDRESS_KEY));
+ }
+ }
+
+ /**
+ * The gateway creates its OzoneClient on the first request, with the
configuration in the static
+ * {@link OzoneConfigurationHolder}, which the next gateway started in this
JVM replaces. Sends a request now, so
+ * the client is created with this gateway's configuration. The
configuration injected into the endpoints is still
+ * the one of the gateway started last.
+ */
+ private static void createOzoneClient(OzoneConfiguration s3gConf) throws
Exception {
+ try (S3Client client = new S3ClientFactory(s3gConf).createS3ClientV2()) {
+ client.listBuckets();
+ }
}
@Override
diff --git
a/hadoop-ozone/integration-test-s3/src/test/java/org/apache/hadoop/ozone/s3/awssdk/OzoneS3SDKTests.java
b/hadoop-ozone/integration-test-s3/src/test/java/org/apache/hadoop/ozone/s3/awssdk/OzoneS3SDKTests.java
index c200b8b48ae..78e801ef9e0 100644
---
a/hadoop-ozone/integration-test-s3/src/test/java/org/apache/hadoop/ozone/s3/awssdk/OzoneS3SDKTests.java
+++
b/hadoop-ozone/integration-test-s3/src/test/java/org/apache/hadoop/ozone/s3/awssdk/OzoneS3SDKTests.java
@@ -22,6 +22,7 @@
import org.apache.hadoop.ozone.MiniOzoneCluster;
import org.apache.hadoop.ozone.om.OMConfigKeys;
import org.apache.hadoop.ozone.s3.MultiS3GatewayService;
+import org.apache.hadoop.ozone.s3.S3GatewayService;
import org.apache.hadoop.ozone.s3.awssdk.v1.AbstractS3SDKV1Tests;
import org.apache.hadoop.ozone.s3.awssdk.v2.AbstractS3SDKV2Tests;
import org.apache.ozone.test.ClusterForTests;
@@ -41,6 +42,9 @@ protected OzoneConfiguration createOzoneConfig() {
protected MiniOzoneCluster createCluster() throws Exception {
return newClusterBuilder()
.addService(new MultiS3GatewayService(5))
+ // Outside the proxy, so only a test that addresses it reads the cells
of EC keys in parallel.
+ .addService(new S3GatewayService(conf ->
conf.setBoolean("ozone.client.ec.parallel.read.enabled", true),
+ AbstractS3SDKV2Tests.EC_PARALLEL_READ_S3G_HTTP_ADDRESS_KEY))
.build();
}
diff --git
a/hadoop-ozone/integration-test-s3/src/test/java/org/apache/hadoop/ozone/s3/awssdk/v2/AbstractS3SDKV2Tests.java
b/hadoop-ozone/integration-test-s3/src/test/java/org/apache/hadoop/ozone/s3/awssdk/v2/AbstractS3SDKV2Tests.java
index 4e4d5334d98..c074f8f8dfc 100644
---
a/hadoop-ozone/integration-test-s3/src/test/java/org/apache/hadoop/ozone/s3/awssdk/v2/AbstractS3SDKV2Tests.java
+++
b/hadoop-ozone/integration-test-s3/src/test/java/org/apache/hadoop/ozone/s3/awssdk/v2/AbstractS3SDKV2Tests.java
@@ -27,6 +27,7 @@
import static org.apache.http.HttpStatus.SC_OK;
import static org.apache.http.HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -64,12 +65,15 @@
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
+import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.xml.bind.DatatypeConverter;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.RandomStringUtils;
+import org.apache.hadoop.hdds.client.DefaultReplicationConfig;
+import org.apache.hadoop.hdds.client.ECReplicationConfig;
import org.apache.hadoop.hdds.client.ReplicationConfig;
import org.apache.hadoop.hdds.client.ReplicationFactor;
import org.apache.hadoop.hdds.client.ReplicationType;
@@ -236,6 +240,12 @@
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public abstract class AbstractS3SDKV2Tests extends OzoneTestBase implements
NonHATests.TestCase {
+ /**
+ * Test-only key for the {@code host:port} http address of a gateway,
outside the proxy, that has
+ * {@code ozone.client.ec.parallel.read.enabled} set.
+ */
+ public static final String EC_PARALLEL_READ_S3G_HTTP_ADDRESS_KEY =
"ozone.test.s3g.ec.parallel.read.http.address";
+
private static final String READ_CONSISTENCY_HEADER =
"x-ozone-read-consistency";
private static final String LOCAL_LEASE_LOG_LIMIT_HEADER =
@@ -343,6 +353,73 @@ public void testGetObjectWithReadConsistencyHeader(String
readConsistency) {
assertEquals(content, objectBytes.asUtf8String());
}
+ /**
+ * Serial reads come first: a serial read asserts that no parallel read
thread exists, and the threads of the
+ * parallel read pool outlive the read that starts them.
+ */
+ static Stream<Arguments> multiCellEcGetArguments() {
+ Stream.Builder<Arguments> arguments = Stream.builder();
+ for (boolean parallelRead : new boolean[] {false, true}) {
+ for (String readConsistency : new String[] {"follower-stale",
"follower-linearizable", "leader-only"}) {
+ arguments.add(Arguments.of(readConsistency, parallelRead));
+ }
+ }
+ return arguments.build();
+ }
+
+ /**
+ * Gets an object of an EC bucket that spans several cells, so the gateway
reads it with the request's S3
+ * authentication and read-consistency hint on the request thread, and,
through the gateway at
+ * {@link #EC_PARALLEL_READ_S3G_HTTP_ADDRESS_KEY}, on its parallel read
threads.
+ */
+ @ParameterizedTest
+ @MethodSource("multiCellEcGetArguments")
+ public void testGetMultiCellEcObjectWithReadConsistencyHeader(String
readConsistency, boolean parallelRead)
+ throws Exception {
+ final String bucketName = getBucketName();
+ final String keyName = getKeyName();
+ ECReplicationConfig ecConfig = new ECReplicationConfig("rs-3-2-1024k");
+ try (OzoneClient ozoneClient = cluster.newClient()) {
+ ozoneClient.getObjectStore().getS3Volume().createBucket(bucketName,
BucketArgs.newBuilder()
+ .setDefaultReplicationConfig(new
DefaultReplicationConfig(ecConfig)).build());
+ }
+ // Two full stripes and a partial one.
+ final byte[] content = new byte[7 * (int) OzoneConsts.MB + 100];
+ ThreadLocalRandom.current().nextBytes(content);
+ s3Client.putObject(b -> b.bucket(bucketName).key(keyName),
RequestBody.fromBytes(content));
+ try (OzoneClient ozoneClient = cluster.newClient()) {
+ assertEquals(ecConfig,
ozoneClient.getObjectStore().getS3Bucket(bucketName).getKey(keyName)
+ .getReplicationConfig());
+ }
+
+ ResponseBytes<GetObjectResponse> objectBytes;
+ try (S3Client readClient = parallelRead ? createEcParallelReadS3Client() :
null) {
+ objectBytes = (parallelRead ? readClient : s3Client).getObjectAsBytes(
+ b -> b.bucket(bucketName)
+ .key(keyName)
+ .overrideConfiguration(c -> {
+ c.putHeader(READ_CONSISTENCY_HEADER, readConsistency);
+ if ("follower-stale".equals(readConsistency)) {
+ c.putHeader(LOCAL_LEASE_LOG_LIMIT_HEADER, "10");
+ }
+ }));
+ }
+
+ assertArrayEquals(content, objectBytes.asByteArray());
+ // Only the gateway with parallel reads enabled starts the pool.
+ assertEquals(parallelRead, Thread.getAllStackTraces().keySet().stream()
+ .anyMatch(t -> t.getName().startsWith("ec-parallel-reader-")));
+ }
+
+ /** An S3 client bound to the gateway that reads the cells of EC keys in
parallel. */
+ private S3Client createEcParallelReadS3Client() throws Exception {
+ String address =
cluster.getConf().get(EC_PARALLEL_READ_S3G_HTTP_ADDRESS_KEY);
+ assertNotNull(address, "expected the cluster to run a gateway with EC
parallel reads enabled");
+ OzoneConfiguration gatewayConf = new OzoneConfiguration(cluster.getConf());
+ gatewayConf.set(S3GatewayConfigKeys.OZONE_S3G_HTTP_ADDRESS_KEY, address);
+ return new S3ClientFactory(gatewayConf).createS3ClientV2();
+ }
+
@Test
public void testGetObjectWithInvalidReadConsistencyHeader() {
final String bucketName = getBucketName();
diff --git
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/fs/ozone/TestOzoneFSInputStream.java
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/fs/ozone/TestOzoneFSInputStream.java
index 9207fc42831..186186f510e 100644
---
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/fs/ozone/TestOzoneFSInputStream.java
+++
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/fs/ozone/TestOzoneFSInputStream.java
@@ -44,6 +44,7 @@
import org.apache.hadoop.hdds.client.ECReplicationConfig;
import org.apache.hadoop.hdds.conf.OzoneConfiguration;
import org.apache.hadoop.hdds.protocol.StorageType;
+import org.apache.hadoop.hdds.scm.OzoneClientConfig;
import org.apache.hadoop.hdds.scm.storage.PositionedReadTestHelper;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.SequenceFile;
@@ -56,7 +57,6 @@
import org.apache.ozone.test.NonHATests;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
-import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
@@ -70,7 +70,9 @@
public abstract class TestOzoneFSInputStream implements NonHATests.TestCase {
private OzoneClient client;
- private FileSystem ecFs;
+ // EC bucket filesystems reading the cells one at a time and in parallel
+ private FileSystem serialEcFs;
+ private FileSystem parallelEcFs;
private Path filePath = null;
private byte[] data = null;
private String uri = null;
@@ -108,17 +110,32 @@ void init() throws Exception {
ecBucket);
String ecUri = String.format("%s://%s.%s/",
OzoneConsts.OZONE_URI_SCHEME, ecBucket, bucket.getVolumeName());
- ecFs = FileSystem.get(URI.create(ecUri), cluster().getConf());
+ serialEcFs = newEcFileSystem(ecUri, false);
+ parallelEcFs = newEcFileSystem(ecUri, true);
+ }
+
+ private FileSystem newEcFileSystem(String ecUri, boolean parallelRead)
throws IOException {
+ OzoneConfiguration conf = new OzoneConfiguration(cluster().getConf());
+ OzoneClientConfig clientConfig = conf.getObject(OzoneClientConfig.class);
+ clientConfig.setEcParallelReadEnabled(parallelRead);
+ conf.setFromObject(clientConfig);
+ return FileSystem.newInstance(URI.create(ecUri), conf);
+ }
+
+ private FileSystem ecFs(boolean parallelRead) {
+ return parallelRead ? parallelEcFs : serialEcFs;
}
@AfterAll
void shutdown() {
- closeQuietly(client, ecFs);
+ closeQuietly(client, serialEcFs, parallelEcFs);
}
- @Test
- void testConcurrentECPositionedRead() throws Exception {
- Path path = new Path("/concurrent-ec-reads");
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void testConcurrentECPositionedRead(boolean parallelRead) throws Exception {
+ FileSystem ecFs = ecFs(parallelRead);
+ Path path = new Path("/concurrent-ec-reads-" + parallelRead);
byte[] expected = Arrays.copyOf(data, 7 * 1024 * 1024 + 103);
try (FSDataOutputStream output = ecFs.create(path)) {
output.write(expected);
@@ -384,7 +401,8 @@ public void testSequenceFileReaderSync(boolean
isStreamEnable) throws IOExceptio
@ParameterizedTest
@ValueSource(booleans = {true, false})
- public void testSequenceFileReaderSyncEC() throws IOException {
+ public void testSequenceFileReaderSyncEC(boolean parallelRead) throws
IOException {
+ FileSystem ecFs = ecFs(parallelRead);
File srcfile = new File("src/test/resources/testSequenceFile");
Path path = new Path("/" + RandomStringUtils.secure().nextAlphanumeric(5));
InputStream input = new
BufferedInputStream(Files.newInputStream(srcfile.toPath()));
diff --git
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/client/rpc/TestSecureOzoneRpcClient.java
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/client/rpc/TestSecureOzoneRpcClient.java
index cad887a2380..42dbc724867 100644
---
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/client/rpc/TestSecureOzoneRpcClient.java
+++
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/client/rpc/TestSecureOzoneRpcClient.java
@@ -28,6 +28,7 @@
import static org.apache.hadoop.ozone.om.OMConfigKeys.OZONE_OM_ADDRESS_KEY;
import static
org.apache.hadoop.ozone.om.helpers.BucketLayout.FILE_SYSTEM_OPTIMIZED;
import static org.apache.ozone.test.GenericTestUtils.getTestStartTime;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@@ -48,11 +49,13 @@
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.ozone.RootedOzoneFileSystem;
import org.apache.hadoop.hdds.HddsConfigKeys;
+import org.apache.hadoop.hdds.client.ECReplicationConfig;
import org.apache.hadoop.hdds.client.RatisReplicationConfig;
import org.apache.hadoop.hdds.client.ReplicationFactor;
import org.apache.hadoop.hdds.client.ReplicationType;
import org.apache.hadoop.hdds.conf.OzoneConfiguration;
import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
+import org.apache.hadoop.hdds.scm.OzoneClientConfig;
import org.apache.hadoop.hdds.scm.ScmConfigKeys;
import
org.apache.hadoop.hdds.security.x509.certificate.client.CertificateClientTestImpl;
import org.apache.hadoop.hdds.utils.db.Table;
@@ -62,6 +65,7 @@
import org.apache.hadoop.ozone.DataTestUtil;
import org.apache.hadoop.ozone.MiniOzoneCluster;
import org.apache.hadoop.ozone.OzoneConfigKeys;
+import org.apache.hadoop.ozone.OzoneConsts;
import org.apache.hadoop.ozone.client.BucketArgs;
import org.apache.hadoop.ozone.client.OzoneBucket;
import org.apache.hadoop.ozone.client.OzoneClient;
@@ -71,6 +75,7 @@
import org.apache.hadoop.ozone.client.SecretKeyTestClient;
import org.apache.hadoop.ozone.client.io.OzoneInputStream;
import org.apache.hadoop.ozone.client.io.OzoneOutputStream;
+import org.apache.hadoop.ozone.client.protocol.ClientProtocol;
import org.apache.hadoop.ozone.om.OMMetadataManager;
import org.apache.hadoop.ozone.om.OMMetrics;
import org.apache.hadoop.ozone.om.OzoneManager;
@@ -78,8 +83,10 @@
import org.apache.hadoop.ozone.om.exceptions.OMException;
import org.apache.hadoop.ozone.om.helpers.BucketLayout;
import org.apache.hadoop.ozone.om.helpers.OmKeyInfo;
+import org.apache.hadoop.ozone.om.helpers.ReadConsistency;
import org.apache.hadoop.ozone.om.helpers.RepeatedOmKeyInfo;
import org.apache.hadoop.ozone.om.helpers.S3SecretValue;
+import org.apache.hadoop.ozone.om.protocol.S3Auth;
import org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos;
import
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.CreateVolumeRequest;
import
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.InfoVolumeRequest;
@@ -104,6 +111,16 @@
*/
class TestSecureOzoneRpcClient extends OzoneRpcClientTests {
+ // An AWS Signature V4 string to sign, its signature and the secret that
produces it, for the S3 auth tests.
+ private static final String S3_STRING_TO_SIGN = "AWS4-HMAC-SHA256\n" +
+ "20150830T123600Z\n" +
+ "20150830/us-east-1/iam/aws4_request\n" +
+ "f536975d06c0309214f805bb90ccff089219ecd68b2" +
+ "577efef23edd43b7e1a59";
+ private static final String S3_SIGNATURE = "5d672d79c15b13162d9279b0855cfba"
+
+ "6789a8edb4c82c400e06b5924a6f2b5d7";
+ private static final String S3_SECRET =
"wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY";
+
@TempDir
private static File testDir;
private static String keyProviderUri = "kms://http@localhost:9600/kms";
@@ -353,18 +370,6 @@ public void testS3Auth() throws Exception {
String volumeName = UUID.randomUUID().toString();
- String strToSign = "AWS4-HMAC-SHA256\n" +
- "20150830T123600Z\n" +
- "20150830/us-east-1/iam/aws4_request\n" +
- "f536975d06c0309214f805bb90ccff089219ecd68b2" +
- "577efef23edd43b7e1a59";
-
- String signature = "5d672d79c15b13162d9279b0855cfba" +
- "6789a8edb4c82c400e06b5924a6f2b5d7";
-
- String secret = "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY";
-
-
String accessKey = UserGroupInformation.getCurrentUser().getUserName();
S3SecretManager s3SecretManager = getCluster().getOzoneManager()
@@ -372,7 +377,7 @@ public void testS3Auth() throws Exception {
// Add secret to S3Secret table.
s3SecretManager.storeSecret(accessKey,
- S3SecretValue.of(accessKey, secret));
+ S3SecretValue.of(accessKey, S3_SECRET));
OMRequest writeRequest = OMRequest.newBuilder()
.setCmdType(OzoneManagerProtocolProtos.Type.CreateVolume)
@@ -384,7 +389,7 @@ public void testS3Auth() throws Exception {
.build())
.setS3Authentication(S3Authentication.newBuilder()
.setAccessId(accessKey)
- .setSignature(signature).setStringToSign(strToSign))
+ .setSignature(S3_SIGNATURE).setStringToSign(S3_STRING_TO_SIGN))
.build();
GenericTestUtils.waitFor(() ->
getCluster().getOzoneManager().isLeaderReady(),
@@ -404,7 +409,7 @@ public void testS3Auth() throws Exception {
.setVolumeName(volumeName).build())
.setS3Authentication(S3Authentication.newBuilder()
.setAccessId(accessKey)
- .setSignature(signature).setStringToSign(strToSign))
+ .setSignature(S3_SIGNATURE).setStringToSign(S3_STRING_TO_SIGN))
.build();
omResponse = getCluster().getOzoneManager().getOmServerProtocol()
@@ -434,6 +439,54 @@ public void testS3Auth() throws Exception {
assertEquals(Status.INVALID_TOKEN, omResponse.getStatus());
}
+ /**
+ * Reads a multi-cell EC key with S3 authentication and a read-consistency
hint set on the request thread, with
+ * sequential and with parallel EC reads.
+ */
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void testEcReadWithS3AuthAndReadConsistency(boolean parallelRead) throws
Exception {
+ String volumeName = UUID.randomUUID().toString();
+ String bucketName = UUID.randomUUID().toString();
+ String keyName = UUID.randomUUID().toString();
+ getStore().createVolume(volumeName);
+ getStore().getVolume(volumeName).createBucket(bucketName);
+ OzoneBucket bucket =
getStore().getVolume(volumeName).getBucket(bucketName);
+
+ // Two full rs-3-2-1024k stripes and a partial one, so one read spans all
data cells.
+ byte[] data = new byte[7 * (int) OzoneConsts.MB + 100];
+ ThreadLocalRandom.current().nextBytes(data);
+ ECReplicationConfig ecConfig = new ECReplicationConfig(3, 2,
ECReplicationConfig.EcCodec.RS, (int) OzoneConsts.MB);
+ try (OzoneOutputStream out = bucket.createKey(keyName, data.length,
ecConfig, new HashMap<>())) {
+ out.write(data);
+ }
+
+ String accessKey = UserGroupInformation.getCurrentUser().getUserName();
+ getCluster().getOzoneManager().getS3SecretManager().storeSecret(accessKey,
S3SecretValue.of(accessKey, S3_SECRET));
+
+ OzoneConfiguration readConf = new
OzoneConfiguration(getCluster().getConf());
+ OzoneClientConfig clientConfig =
readConf.getObject(OzoneClientConfig.class);
+ clientConfig.setEcParallelReadEnabled(parallelRead);
+ readConf.setFromObject(clientConfig);
+ try (OzoneClient readClient = OzoneClientFactory.getRpcClient(readConf)) {
+ ClientProtocol proxy = readClient.getProxy();
+ proxy.setThreadLocalS3Auth(new S3Auth(S3_STRING_TO_SIGN, S3_SIGNATURE,
accessKey, accessKey));
+
proxy.setThreadLocalReadConsistency(ReadConsistency.LINEARIZABLE_LEADER_ONLY);
+ try (OzoneInputStream in =
readClient.getObjectStore().getVolume(volumeName).getBucket(bucketName)
+ .readKey(keyName)) {
+ byte[] read = new byte[data.length];
+ IOUtils.readFully(in, read);
+ assertArrayEquals(data, read);
+ } finally {
+ proxy.clearThreadLocalS3Auth();
+ proxy.clearThreadLocalReadConsistency();
+ }
+ // The pool is shut down with the client, so check for its threads
before closing it.
+ assertEquals(parallelRead, Thread.getAllStackTraces().keySet().stream()
+ .anyMatch(t -> t.getName().startsWith("ec-parallel-reader-")));
+ }
+ }
+
@Test
public void testRemoteException() {
UserGroupInformation realUser =
UserGroupInformation.createRemoteUser("realUser");
diff --git
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/client/rpc/read/TestEcParallelReadBenchmark.java
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/client/rpc/read/TestEcParallelReadBenchmark.java
new file mode 100644
index 00000000000..ab47d43168d
--- /dev/null
+++
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/client/rpc/read/TestEcParallelReadBenchmark.java
@@ -0,0 +1,442 @@
+/*
+ * 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.client.rpc.read;
+
+import static org.apache.hadoop.hdds.client.ECReplicationConfig.EcCodec.RS;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Random;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.zip.CRC32;
+import org.apache.hadoop.hdds.client.ECReplicationConfig;
+import org.apache.hadoop.hdds.conf.OzoneConfiguration;
+import org.apache.hadoop.hdds.scm.OzoneClientConfig;
+import org.apache.hadoop.hdds.utils.IOUtils;
+import org.apache.hadoop.ozone.MiniOzoneCluster;
+import org.apache.hadoop.ozone.client.ObjectStore;
+import org.apache.hadoop.ozone.client.OzoneBucket;
+import org.apache.hadoop.ozone.client.OzoneClient;
+import org.apache.hadoop.ozone.client.OzoneClientFactory;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Nested;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestInstance;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Benchmark for reading the cells of a healthy EC block in parallel
(HDDS-16867).
+ *
+ * <p>Every EC key is read through two sets of clients of the same cluster:
with
+ * {@code ozone.client.ec.parallel.read.enabled=false} (cells are read one at
a time) and with it set to true.
+ * Each client has its own datanode connections. Rounds alternate the order of
the two arms, after a warm-up, and
+ * the median throughput of the rounds is reported; latency percentiles are
taken over all measured rounds.
+ *
+ * <p>The benchmark runs on a 5 and on a 9 datanode cluster. rs-6-3 needs 9
datanodes, so on 5 datanodes only
+ * rs-3-2 is measured; there every datanode holds a cell of every key, while
on 9 datanodes the cells of rs-3-2
+ * keys are spread over more datanodes.
+ *
+ * <p>All datanodes run in this JVM and are reached over loopback, so a
datanode round trip costs far less than
+ * on a real network. The speed-up measured here comes from overlapping the
datanode read, the transfer and the
+ * client-side checksum verification of different cells; on a real network the
serial round trips that the
+ * parallel path removes cost more, so this is a lower bound. With several
readers, the readers and all the
+ * datanodes share the CPUs of one machine.
+ *
+ * <p>Run with:
+ * <pre>
+ * mvn -pl :ozone-integration-test test -Dtest=TestEcParallelReadBenchmark \
+ * -Dexcluded-test-groups= -DskipShade -DskipRecon
+ * </pre>
+ */
+@Tag("benchmark")
+public class TestEcParallelReadBenchmark {
+
+ private static final Logger LOG =
LoggerFactory.getLogger(TestEcParallelReadBenchmark.class);
+
+ private static final int MB = 1024 * 1024;
+ private static final int EC_CHUNK_SIZE = MB;
+ /** Size of each key: 16 stripes of rs-3-2, 8 of rs-6-3. */
+ private static final int KEY_SIZE = 48 * MB;
+ private static final int WARMUP_ROUNDS = 2;
+ private static final int ROUNDS = 7;
+ /** Concurrent readers, and the number of clients and keys per policy in the
client-per-thread benchmark. */
+ private static final int READERS = 4;
+ private static final ECReplicationConfig RS_3_2 = new ECReplicationConfig(3,
2, RS, EC_CHUNK_SIZE);
+ private static final ECReplicationConfig RS_6_3 = new ECReplicationConfig(6,
3, RS, EC_CHUNK_SIZE);
+
+ @Nested
+ class FiveDatanodes extends ClusterBenchmark {
+ FiveDatanodes() {
+ super(5, Collections.singletonList(RS_3_2));
+ }
+ }
+
+ @Nested
+ class NineDatanodes extends ClusterBenchmark {
+ NineDatanodes() {
+ super(9, Arrays.asList(RS_3_2, RS_6_3));
+ }
+ }
+
+ /**
+ * The benchmarks on one cluster.
+ */
+ @TestInstance(TestInstance.Lifecycle.PER_CLASS)
+ abstract class ClusterBenchmark {
+
+ private final int datanodes;
+ private final List<ECReplicationConfig> policies;
+ private final String volumeName = "benchvol";
+ private final String bucketName = "benchbucket";
+ private MiniOzoneCluster cluster;
+ // READERS clients per arm; the shared-client benchmark uses the first of
each
+ private final List<OzoneClient> serialClients = new ArrayList<>();
+ private final List<OzoneClient> parallelClients = new ArrayList<>();
+ // CRC32 of each key, by policy then reader
+ private final List<long[]> keyCrcs = new ArrayList<>();
+
+ ClusterBenchmark(int datanodes, List<ECReplicationConfig> policies) {
+ this.datanodes = datanodes;
+ this.policies = policies;
+ }
+
+ @BeforeAll
+ void init() throws Exception {
+ cluster = MiniOzoneCluster.newBuilder(new OzoneConfiguration())
+ .setNumDatanodes(datanodes)
+ .build();
+ cluster.waitForClusterToBeReady();
+ for (int i = 0; i < READERS; i++) {
+ serialClients.add(newClient(false));
+ parallelClients.add(newClient(true));
+ }
+
+ ObjectStore objectStore = serialClients.get(0).getObjectStore();
+ objectStore.createVolume(volumeName);
+ objectStore.getVolume(volumeName).createBucket(bucketName);
+ OzoneBucket bucket = bucket(serialClients.get(0));
+ Random random = new Random(20261012L);
+ byte[] data = new byte[KEY_SIZE];
+ for (ECReplicationConfig policy : policies) {
+ long[] crcs = new long[READERS];
+ for (int i = 0; i < READERS; i++) {
+ random.nextBytes(data);
+ try (OutputStream out = bucket.createKey(keyName(policy, i),
KEY_SIZE, policy, Collections.emptyMap())) {
+ out.write(data);
+ }
+ crcs[i] = crc(data, KEY_SIZE);
+ }
+ keyCrcs.add(crcs);
+ }
+ }
+
+ private OzoneClient newClient(boolean parallelRead) throws IOException {
+ OzoneConfiguration clientConf = new
OzoneConfiguration(cluster.getConf());
+ OzoneClientConfig clientConfig =
clientConf.getObject(OzoneClientConfig.class);
+ clientConfig.setEcParallelReadEnabled(parallelRead);
+ clientConf.setFromObject(clientConfig);
+ return OzoneClientFactory.getRpcClient(clientConf);
+ }
+
+ @AfterAll
+ void shutdown() {
+ IOUtils.closeQuietly(serialClients);
+ IOUtils.closeQuietly(parallelClients);
+ if (cluster != null) {
+ cluster.shutdown();
+ }
+ }
+
+ /**
+ * One client per arm, read by 1 and by {@link #READERS} threads that all
read the same key.
+ */
+ @Test
+ void benchmarkSharedClient() throws Exception {
+ StringBuilder report = new StringBuilder(String.format("%n"
+ + "BENCHRESULT EC healthy-read parallel cells (HDDS-16867) - shared
client, %d datanodes%n"
+ + " key size=%d MB, cell=%d KB, rounds=%d (after %d warm-up),
median MB/s%n"
+ + " %-12s %-8s %-8s %12s %12s %8s%n",
+ datanodes, KEY_SIZE / MB, EC_CHUNK_SIZE / 1024, ROUNDS,
WARMUP_ROUNDS,
+ "policy", "buffer", "readers", "serial", "parallel", "speedup"));
+ for (int p = 0; p < policies.size(); p++) {
+ ECReplicationConfig policy = policies.get(p);
+ verifyKeys(p);
+ for (int bufferSize : bufferSizes(policy)) {
+ for (int readers : new int[] {1, READERS}) {
+ Comparison c = compare(arm -> {
+ List<OzoneClient> clients = Collections.nCopies(readers,
arm.get(0));
+ List<String> keys = Collections.nCopies(readers, keyName(policy,
0));
+ return readConcurrently(clients, keys, bufferSize);
+ });
+ report.append(String.format(" %-12s %-8s %-8d %12.1f %12.1f
%7.2fx%n",
+ policy.getReplication(), bufferSize / MB + "MB", readers,
+ c.serialThroughput(), c.parallelThroughput(), c.speedup()));
+ }
+ }
+ }
+ LOG.info(report.toString());
+ assertParallelReadersStarted();
+ }
+
+ /**
+ * {@link #READERS} clients per arm, each read by its own thread and
reading its own key.
+ */
+ @Test
+ void benchmarkClientPerThread() throws Exception {
+ StringBuilder report = new StringBuilder(String.format("%n"
+ + "BENCHRESULT EC healthy-read parallel cells (HDDS-16867) - %d
clients x 1 thread, %d datanodes%n"
+ + " key size=%d MB per client, cell=%d KB, rounds=%d (after %d
warm-up)%n"
+ + " throughput = median aggregate MB/s; file = time to read one
key; call = one read() call%n"
+ + " %-12s %-6s | %8s %8s %7s | %15s %15s | %15s %15s%n",
+ READERS, datanodes, KEY_SIZE / MB, EC_CHUNK_SIZE / 1024, ROUNDS,
WARMUP_ROUNDS,
+ "policy", "buffer", "serial", "parallel", "speedup",
+ "file p50 ms s/p", "file p99 ms s/p", "call p50 ms s/p", "call p99
ms s/p"));
+ for (int p = 0; p < policies.size(); p++) {
+ ECReplicationConfig policy = policies.get(p);
+ verifyKeys(p);
+ List<String> keys = new ArrayList<>();
+ for (int i = 0; i < READERS; i++) {
+ keys.add(keyName(policy, i));
+ }
+ for (int bufferSize : bufferSizes(policy)) {
+ Comparison c = compare(arm -> readConcurrently(arm, keys,
bufferSize));
+ report.append(String.format(" %-12s %-6s | %8.1f %8.1f %6.2fx |
%7.1f/%-7.1f %7.1f/%-7.1f"
+ + " | %7.2f/%-7.2f %7.2f/%-7.2f%n",
+ policy.getReplication(), bufferSize / MB + "MB",
+ c.serialThroughput(), c.parallelThroughput(), c.speedup(),
+ millis(c.serialFiles.percentile(0.50)),
millis(c.parallelFiles.percentile(0.50)),
+ millis(c.serialFiles.percentile(0.99)),
millis(c.parallelFiles.percentile(0.99)),
+ millis(c.serialCalls.percentile(0.50)),
millis(c.parallelCalls.percentile(0.50)),
+ millis(c.serialCalls.percentile(0.99)),
millis(c.parallelCalls.percentile(0.99))));
+ }
+ }
+ if (!policies.contains(RS_6_3)) {
+ report.append(String.format(" %s needs 9 datanodes, not measured on
%d%n",
+ RS_6_3.getReplication(), datanodes));
+ }
+ LOG.info(report.toString());
+ assertParallelReadersStarted();
+ }
+
+ /** Runs the workload on both arms, alternating which goes first, and
keeps the measured rounds. */
+ private Comparison compare(Workload workload) throws Exception {
+ Comparison c = new Comparison();
+ for (int round = -WARMUP_ROUNDS; round < ROUNDS; round++) {
+ boolean serialFirst = (round & 1) == 0;
+ Run first = workload.run(serialFirst ? serialClients :
parallelClients);
+ Run second = workload.run(serialFirst ? parallelClients :
serialClients);
+ if (round >= 0) {
+ c.add(serialFirst ? first : second, serialFirst ? second : first);
+ }
+ }
+ return c;
+ }
+
+ /**
+ * Reads keys.get(i) through clients.get(i) on its own thread, all threads
starting together, and returns the
+ * aggregate throughput with the per-file and per-call latencies.
+ */
+ private Run readConcurrently(List<OzoneClient> clients, List<String> keys,
int bufferSize) throws Exception {
+ int readers = clients.size();
+ ExecutorService pool = Executors.newFixedThreadPool(readers);
+ try {
+ CountDownLatch ready = new CountDownLatch(readers);
+ CountDownLatch start = new CountDownLatch(1);
+ List<Callable<Latencies>> reads = new ArrayList<>();
+ for (int i = 0; i < readers; i++) {
+ OzoneClient client = clients.get(i);
+ String key = keys.get(i);
+ reads.add(() -> {
+ ready.countDown();
+ start.await();
+ return drain(client, key, bufferSize);
+ });
+ }
+ List<Future<Latencies>> futures = new ArrayList<>();
+ for (Callable<Latencies> read : reads) {
+ futures.add(pool.submit(read));
+ }
+ ready.await();
+ long startNanos = System.nanoTime();
+ start.countDown();
+ Run run = new Run();
+ for (Future<Latencies> f : futures) {
+ Latencies l = f.get();
+ run.files.add(l.file);
+ run.calls.addAll(l.calls);
+ }
+ long elapsed = System.nanoTime() - startNanos;
+ run.throughput = (double) readers * KEY_SIZE / MB / (elapsed /
(double) TimeUnit.SECONDS.toNanos(1));
+ return run;
+ } finally {
+ pool.shutdownNow();
+ }
+ }
+
+ private Latencies drain(OzoneClient client, String key, int bufferSize)
throws IOException {
+ byte[] buf = new byte[bufferSize];
+ Latencies latencies = new Latencies();
+ long total = 0;
+ long fileStart = System.nanoTime();
+ try (InputStream in = bucket(client).readKey(key)) {
+ while (true) {
+ long callStart = System.nanoTime();
+ int n = in.read(buf);
+ if (n <= 0) {
+ break;
+ }
+ latencies.calls.add(System.nanoTime() - callStart);
+ total += n;
+ }
+ }
+ latencies.file = System.nanoTime() - fileStart;
+ assertEquals(KEY_SIZE, total);
+ return latencies;
+ }
+
+ /** Every key of the policy returns the written data through both arms. */
+ private void verifyKeys(int policyIndex) throws IOException {
+ ECReplicationConfig policy = policies.get(policyIndex);
+ byte[] all = new byte[KEY_SIZE];
+ for (List<OzoneClient> arm : Arrays.asList(serialClients,
parallelClients)) {
+ for (int i = 0; i < READERS; i++) {
+ try (InputStream in = bucket(arm.get(i)).readKey(keyName(policy,
i))) {
+ int offset = 0;
+ int n;
+ while (offset < KEY_SIZE && (n = in.read(all, offset, Math.min(3 *
MB, KEY_SIZE - offset))) > 0) {
+ offset += n;
+ }
+ assertEquals(KEY_SIZE, offset);
+ }
+ assertEquals(keyCrcs.get(policyIndex)[i], crc(all, KEY_SIZE),
keyName(policy, i));
+ }
+ }
+ }
+
+ private OzoneBucket bucket(OzoneClient client) throws IOException {
+ return
client.getObjectStore().getVolume(volumeName).getBucket(bucketName);
+ }
+ }
+
+ /** One cell (control, never parallel), one stripe, and a large buffer
spanning several stripes. */
+ private static int[] bufferSizes(ECReplicationConfig policy) {
+ return new int[] {EC_CHUNK_SIZE, EC_CHUNK_SIZE * policy.getData(), 8 * MB};
+ }
+
+ private static void assertParallelReadersStarted() {
+ assertThat(Thread.getAllStackTraces().keySet())
+ .anyMatch(t -> t.getName().startsWith("ec-parallel-reader-"));
+ }
+
+ private static String keyName(ECReplicationConfig policy, int index) {
+ return "key-" + policy.getReplication() + "-" + index;
+ }
+
+ private static long crc(byte[] data, int length) {
+ CRC32 crc = new CRC32();
+ crc.update(data, 0, length);
+ return crc.getValue();
+ }
+
+ private static double millis(double nanos) {
+ return nanos / TimeUnit.MILLISECONDS.toNanos(1);
+ }
+
+ private static double median(List<Double> values) {
+ List<Double> sorted = new ArrayList<>(values);
+ Collections.sort(sorted);
+ return sorted.get(sorted.size() / 2);
+ }
+
+ /** A workload run on one arm, given that arm's clients. */
+ @FunctionalInterface
+ private interface Workload {
+ Run run(List<OzoneClient> clients) throws Exception;
+ }
+
+ /** The latencies of one thread reading one key. */
+ private static final class Latencies {
+ private long file;
+ private final List<Long> calls = new ArrayList<>();
+ }
+
+ /** One measured run of a workload on one arm. */
+ private static final class Run {
+ private double throughput;
+ private final List<Long> files = new ArrayList<>();
+ private final List<Long> calls = new ArrayList<>();
+ }
+
+ /** Nanosecond samples with a percentile. */
+ private static final class Samples {
+ private final List<Long> values = new ArrayList<>();
+
+ double percentile(double p) {
+ List<Long> sorted = new ArrayList<>(values);
+ Collections.sort(sorted);
+ int index = (int) Math.ceil(p * sorted.size()) - 1;
+ return sorted.get(Math.max(0, Math.min(index, sorted.size() - 1)));
+ }
+ }
+
+ /** The measured rounds of both arms. */
+ private static final class Comparison {
+ private final List<Double> serialThroughputs = new ArrayList<>();
+ private final List<Double> parallelThroughputs = new ArrayList<>();
+ private final Samples serialFiles = new Samples();
+ private final Samples parallelFiles = new Samples();
+ private final Samples serialCalls = new Samples();
+ private final Samples parallelCalls = new Samples();
+
+ void add(Run serial, Run parallel) {
+ serialThroughputs.add(serial.throughput);
+ parallelThroughputs.add(parallel.throughput);
+ serialFiles.values.addAll(serial.files);
+ parallelFiles.values.addAll(parallel.files);
+ serialCalls.values.addAll(serial.calls);
+ parallelCalls.values.addAll(parallel.calls);
+ }
+
+ double serialThroughput() {
+ return median(serialThroughputs);
+ }
+
+ double parallelThroughput() {
+ return median(parallelThroughputs);
+ }
+
+ double speedup() {
+ return parallelThroughput() / serialThroughput();
+ }
+ }
+}
diff --git
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/client/rpc/read/TestKeyInputStream.java
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/client/rpc/read/TestKeyInputStream.java
index 491d7fa802b..ad882f8bc5e 100644
---
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/client/rpc/read/TestKeyInputStream.java
+++
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/client/rpc/read/TestKeyInputStream.java
@@ -35,14 +35,17 @@
import org.apache.commons.lang3.RandomUtils;
import org.apache.hadoop.hdds.client.ECReplicationConfig;
import org.apache.hadoop.hdds.client.RatisReplicationConfig;
+import org.apache.hadoop.hdds.conf.OzoneConfiguration;
import org.apache.hadoop.hdds.protocol.DatanodeDetails;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos;
+import org.apache.hadoop.hdds.scm.OzoneClientConfig;
import org.apache.hadoop.hdds.scm.XceiverClientManager;
import org.apache.hadoop.hdds.scm.XceiverClientMetrics;
import org.apache.hadoop.hdds.scm.storage.BlockExtendedInputStream;
import org.apache.hadoop.hdds.scm.storage.BlockInputStream;
import org.apache.hadoop.hdds.scm.storage.ChunkInputStream;
import org.apache.hadoop.ozone.client.OzoneClient;
+import org.apache.hadoop.ozone.client.OzoneClientFactory;
import org.apache.hadoop.ozone.client.io.KeyInputStream;
import org.apache.hadoop.ozone.common.utils.BufferUtils;
import org.apache.hadoop.ozone.container.OzoneTestHelper;
@@ -137,6 +140,17 @@ void testNonReplicationReads(ContainerLayoutVersion
layout) throws Exception {
testSkip(bucket);
testECSeek(bucket);
}
+
+ // The same EC reads through a client that reads the cells of different
data indexes in parallel.
+ OzoneConfiguration parallelReadConf = new
OzoneConfiguration(getCluster().getConf());
+ OzoneClientConfig clientConfig =
parallelReadConf.getObject(OzoneClientConfig.class);
+ clientConfig.setEcParallelReadEnabled(true);
+ parallelReadConf.setFromObject(clientConfig);
+ try (OzoneClient client =
OzoneClientFactory.getRpcClient(parallelReadConf)) {
+ testECSeek(BucketForTesting.newBuilder(client).build());
+ assertThat(Thread.getAllStackTraces().keySet())
+ .anyMatch(t -> t.getName().startsWith("ec-parallel-reader-"));
+ }
}
private void testInputStreams(BucketForTesting bucket) throws Exception {
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]