This is an automated email from the ASF dual-hosted git repository.
adoroszlai pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/ozone.git
The following commit(s) were added to refs/heads/master by this push:
new 1c4ac3335fc HDDS-16870. EC positioned reads on healthy keys reuse the
open block streams (#11783)
1c4ac3335fc is described below
commit 1c4ac3335fce8c1ebc4b2a8b5eab1329f3021ee4
Author: Andrey Yarovoy <[email protected]>
AuthorDate: Sat Nov 7 09:39:09 2026 -0500
HDDS-16870. EC positioned reads on healthy keys reuse the open block
streams (#11783)
Co-authored-by: Claude Opus 5.5 <[email protected]>
---
.../hadoop/hdds/scm/storage/BlockInputStream.java | 2 +
.../hadoop/ozone/client/io/ECBlockInputStream.java | 275 +++++++++++++++------
.../ozone/client/io/ECBlockInputStreamProxy.java | 24 +-
.../io/ECBlockReconstructedStripeInputStream.java | 12 +
.../hdds/scm/storage/TestBlockInputStream.java | 14 ++
.../hadoop/ozone/client/io/ECStreamTestUtil.java | 41 ++-
.../ozone/client/io/TestECBlockInputStream.java | 221 +++++++++++++++++
.../client/io/TestECBlockInputStreamProxy.java | 28 ++-
.../io/TestECBlockReconstructedInputStream.java | 72 ++++++
.../hadoop/fs/ozone/TestOzoneFSInputStream.java | 10 +
.../rpc/read/TestEcPositionedReadBenchmark.java | 233 +++++++++++++++++
11 files changed, 842 insertions(+), 90 deletions(-)
diff --git
a/hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/BlockInputStream.java
b/hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/BlockInputStream.java
index ca980de1494..88be628673b 100644
---
a/hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/BlockInputStream.java
+++
b/hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/BlockInputStream.java
@@ -139,6 +139,8 @@ public synchronized void initialize() throws IOException {
if (initialized) {
return;
}
+ // A closed stream has no client to get the block with.
+ checkOpen();
List<ChunkInfo> chunks = null;
IOException catchEx = null;
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 cec0d8c3dca..037f930d768 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
@@ -27,6 +27,7 @@
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
+import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
@@ -37,9 +38,9 @@
import java.util.concurrent.FutureTask;
import java.util.concurrent.RejectedExecutionException;
import java.util.function.Function;
+import java.util.function.IntFunction;
import java.util.function.Supplier;
import org.apache.hadoop.fs.FSExceptionMessages;
-import org.apache.hadoop.fs.StreamCapabilities;
import org.apache.hadoop.hdds.client.BlockID;
import org.apache.hadoop.hdds.client.ContainerBlockID;
import org.apache.hadoop.hdds.client.ECReplicationConfig;
@@ -80,9 +81,11 @@ public class ECBlockInputStream extends
BlockExtendedInputStream {
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;
+ // Guards blockStreams and the switch of a location to a spare, as
positioned reads open streams without the monitor.
+ private final Object streamLock = new Object();
private long position = 0;
- private boolean closed = false;
+ private volatile boolean closed = false;
private boolean seeked = false;
private OzoneClientConfig config;
@@ -190,6 +193,12 @@ protected int currentStreamIndex() {
* @return BlockInput stream to read from.
*/
protected BlockExtendedInputStream getOrOpenStream(int locationIndex) throws
IOException {
+ synchronized (streamLock) {
+ return openStreamIfNeeded(locationIndex);
+ }
+ }
+
+ private BlockExtendedInputStream openStreamIfNeeded(int locationIndex)
throws IOException {
BlockExtendedInputStream stream = blockStreams[locationIndex];
if (stream == null) {
// To read an EC block, we create a STANDALONE pipeline that contains the
@@ -327,15 +336,71 @@ protected long remaining() {
return blockLength() - position;
}
+ /**
+ * Reads the cells covered by the buffer from the internal block streams of
their data indexes with positioned
+ * reads, so neither this stream nor its internal streams change position,
and calls may run concurrently with each
+ * other and with sequential reads. The indexes are read in parallel if the
parallel read executor is set.
+ *
+ * <p>A failed index is not switched to a spare. Instead, a {@link
BadDataLocationException} carrying every failed
+ * index is thrown, so that the caller can fall back to a reconstruction
read for this call.
+ */
@Override
- protected int readPositioned(long offset, ByteBuffer buffer) {
- throw new UnsupportedOperationException("Use ECBlockInputStreamProxy for
positioned reads");
- }
+ protected int readPositioned(long offset, ByteBuffer buffer) throws
IOException {
+ checkOpen();
+ final long available = blockLength() - offset;
+ if (available <= 0) {
+ return EOF;
+ }
+ final int length = (int) Math.min(buffer.remaining(), available);
+ final int bufferStart = buffer.position();
- @Override
- public boolean hasCapability(String capability) {
- return !StreamCapabilities.PREADBYTEBUFFER.equalsIgnoreCase(capability)
- && super.hasCapability(capability);
+ final Map<Integer, DatanodeDetails> locations = new TreeMap<>();
+ final Map<Integer, BlockExtendedInputStream> streams = new TreeMap<>();
+ final List<FutureTask<IndexReadResult>> tasks = new ArrayList<>();
+ for (Map.Entry<Integer, List<CellRead>> entry : splitCells(offset, length,
new ArrayList<>()).entrySet()) {
+ int index = entry.getKey();
+ BlockExtendedInputStream stream;
+ synchronized (streamLock) {
+ // close() sets closed before it closes the streams under streamLock,
so a read racing with close() either
+ // fails here, outside the try so that the locations are not reported
as bad, or opens a stream that close()
+ // then closes, instead of leaving one open after close().
+ checkOpen();
+ locations.put(index, dataLocations[index]);
+ try {
+ stream = getOrOpenStream(index);
+ } catch (IOException e) {
+ throw new BadDataLocationException(dataLocations[index], index, e);
+ }
+ streams.put(index, stream);
+ }
+ List<CellRead> indexCells = entry.getValue();
+ tasks.add(new FutureTask<>(() -> readCells(stream, indexCells, buffer,
bufferStart, false, true)));
+ }
+
+ Map<Integer, IndexReadResult> results = new TreeMap<>();
+ Throwable unexpected = runIndexReads(tasks, results);
+ // A concurrent close fails the reads, although the locations are not bad,
so they must not be reported.
+ checkOpen();
+ if (unexpected != null) {
+ Throwables.throwIfUnchecked(unexpected);
+ throw new IOException(unexpected);
+ }
+ // Another reader may have closed an index stream while this read used it,
for example a sequential read that
+ // switched the index to a spare. That fails the read, although the
location is not bad, so it must not be reported.
+ final IOException closedStreamFailure =
removeFailuresOfClosedStreams(results, streams);
+ BadDataLocationException failure = readFailure(results, locations::get);
+ if (failure != null) {
+ if (closedStreamFailure != null) {
+ failure.addSuppressed(closedStreamFailure);
+ }
+ throw failure;
+ }
+ if (closedStreamFailure != null) {
+ throw closedStreamFailure;
+ }
+ buffer.position(bufferStart + length);
+ LOG.trace("{}: positioned read of {} bytes at {} from {} indexes", this,
length, offset, tasks.size());
+ return length;
}
@Override
@@ -376,15 +441,19 @@ public synchronized int read(ByteBuffer byteBuffer)
throws IOException {
}
protected boolean shouldRetryFailedRead(int failedIndex) {
- Deque<DatanodeDetails> spareLocations =
spareDataLocations.get(failedIndex);
- if (spareLocations != null && !spareLocations.isEmpty()) {
- failedLocations.add(dataLocations[failedIndex]);
- DatanodeDetails spare = spareLocations.removeFirst();
- dataLocations[failedIndex] = spare;
- LOG.debug("{}: switching [{}] to spare {}", this, failedIndex, spare);
- return true;
+ synchronized (streamLock) {
+ Deque<DatanodeDetails> spareLocations =
spareDataLocations.get(failedIndex);
+ if (spareLocations != null && !spareLocations.isEmpty()) {
+ failedLocations.add(dataLocations[failedIndex]);
+ DatanodeDetails spare = spareLocations.removeFirst();
+ dataLocations[failedIndex] = spare;
+ // a positioned read may have reopened the stream on the failed
location
+ closeStream(failedIndex);
+ LOG.debug("{}: switching [{}] to spare {}", this, failedIndex, spare);
+ return true;
+ }
+ return false;
}
- return false;
}
/**
@@ -447,21 +516,10 @@ private int readCellsInParallel(ByteBuffer buffer) throws
IOException {
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;
- }
+ final Map<Integer, List<CellRead>> cellsByIndex =
splitCells(startPosition, length, cells);
- // getOrOpenStream is not thread safe, so open every stream before reading.
+ // Open every stream before reading, so that a failure to open is reported
for its index.
final List<FutureTask<IndexReadResult>> tasks = new ArrayList<>();
for (Map.Entry<Integer, List<CellRead>> entry : cellsByIndex.entrySet()) {
int index = entry.getKey();
@@ -473,33 +531,11 @@ private int readCellsInParallel(ByteBuffer buffer) throws
IOException {
}
List<CellRead> indexCells = entry.getValue();
boolean checkPosition = seeked;
- tasks.add(new FutureTask<>(() -> readCells(stream, indexCells, buffer,
bufferStart, checkPosition)));
+ tasks.add(new FutureTask<>(() -> readCells(stream, indexCells, buffer,
bufferStart, checkPosition, false)));
}
- 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;
- }
- }
+ Throwable unexpected = runIndexReads(tasks, results);
// 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)) {
@@ -523,11 +559,103 @@ private int readCellsInParallel(ByteBuffer buffer)
throws IOException {
buffer.position(bufferStart + read);
LOG.trace("{}: read {} bytes from {} indexes in parallel", this, read,
tasks.size());
+ BadDataLocationException failure = readFailure(results, index ->
dataLocations[index]);
+ if (failure != null) {
+ throw failure;
+ }
+ return read;
+ }
+
+ /**
+ * Splits the range into cells, grouped by data index in the order they are
first needed.
+ * @param cells receives every cell of the range, in order
+ */
+ private Map<Integer, List<CellRead>> splitCells(long startPosition, int
length, List<CellRead> cells) {
+ 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;
+ }
+ return cellsByIndex;
+ }
+
+ /**
+ * Runs the reads of the data indexes and waits for all of them. With the
parallel read executor, the calling
+ * thread runs the first task, and any task the executor has not started
yet; without it, the calling thread runs
+ * every task, one after another.
+ * @param results receives the result of every task that did not fail
unexpectedly
+ * @return the first unexpected error, or null
+ */
+ private Throwable runIndexReads(List<FutureTask<IndexReadResult>> tasks,
Map<Integer, IndexReadResult> results) {
+ if (parallelReadExecutor != null) {
+ 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.
+ 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;
+ }
+ }
+ return unexpected;
+ }
+
+ /**
+ * Removes the failed reads of the streams that are no longer the stream of
their index, because another reader
+ * closed them while they were read, and returns their failure, or null if
there is none.
+ * @param streams the stream that was read for each index
+ */
+ private IOException removeFailuresOfClosedStreams(Map<Integer,
IndexReadResult> results,
+ Map<Integer, BlockExtendedInputStream> streams) {
+ IOException failure = null;
+ synchronized (streamLock) {
+ for (Iterator<IndexReadResult> i = results.values().iterator();
i.hasNext();) {
+ final IndexReadResult result = i.next();
+ // a closed stream is either gone or replaced by a stream opened after
it was closed
+ if (result.error != null && blockStreams[result.index] !=
streams.get(result.index)) {
+ i.remove();
+ if (failure == null) {
+ failure = result.error;
+ } else {
+ failure.addSuppressed(result.error);
+ }
+ }
+ }
+ }
+ return failure;
+ }
+
+ /**
+ * Returns an exception carrying every failed index with the location it was
read from, or null if none failed.
+ */
+ private static BadDataLocationException readFailure(Map<Integer,
IndexReadResult> results,
+ IntFunction<DatanodeDetails> location) {
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]);
+ failures.put(result.index, location.apply(result.index));
if (cause == null) {
cause = result.error;
} else {
@@ -535,18 +663,16 @@ private int readCellsInParallel(ByteBuffer buffer) throws
IOException {
}
}
}
- if (cause != null) {
- throw new BadDataLocationException(failures, cause);
- }
- return read;
+ return cause == null ? null : new BadDataLocationException(failures,
cause);
}
/**
* 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.
+ * @param positioned read with positioned reads, which do not change the
position of the stream
*/
private IndexReadResult readCells(BlockExtendedInputStream stream,
List<CellRead> indexCells, ByteBuffer buffer,
- int bufferStart, boolean checkPosition) {
+ int bufferStart, boolean checkPosition, boolean positioned) {
int index = indexCells.get(0).index;
int cellsRead = 0;
try {
@@ -554,13 +680,13 @@ private IndexReadResult
readCells(BlockExtendedInputStream stream, List<CellRead
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()) {
+ if (!positioned && 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);
+ int actualRead = positioned ? stream.read(streamPosition, slice) :
stream.read(slice);
if (actualRead == EOF) {
throw new IOException("Expected to read " + cell.length + " but got
EOF"
+ " from blockGroup " + stream.getBlockID() + " index " + (index
+ 1));
@@ -689,8 +815,9 @@ private void checkOpen() throws IOException {
@Override
public synchronized void close() {
LOG.debug("{}: close", this);
- closeStreams();
+ // before closing the streams, so that a positioned read failing on a
closed stream sees the stream closed
closed = true;
+ closeStreams();
}
protected synchronized void closeStreams() {
@@ -704,16 +831,18 @@ protected synchronized void closeStreams() {
}
protected void closeStream(int i) {
- if (blockStreams[i] != null) {
- try {
- blockStreams[i].close();
- blockStreams[i] = null;
- // A reopened stream starts at offset 0, so it must be seeked before
the next read.
- seeked = true;
- LOG.debug("{}: closed stream [{}]", this, i);
- } catch (IOException e) {
- LOG.error("{}: failed to close stream [{}]: {}", this,
- i, blockStreams[i], e);
+ synchronized (streamLock) {
+ if (blockStreams[i] != null) {
+ try {
+ blockStreams[i].close();
+ blockStreams[i] = null;
+ // A reopened stream starts at offset 0, so it must be seeked before
the next read.
+ seeked = true;
+ LOG.debug("{}: closed stream [{}]", this, i);
+ } catch (IOException e) {
+ LOG.error("{}: failed to close stream [{}]: {}", this,
+ i, blockStreams[i], e);
+ }
}
}
}
diff --git
a/hadoop-hdds/client/src/main/java/org/apache/hadoop/ozone/client/io/ECBlockInputStreamProxy.java
b/hadoop-hdds/client/src/main/java/org/apache/hadoop/ozone/client/io/ECBlockInputStreamProxy.java
index c9d71f128b5..9eef2032cd7 100644
---
a/hadoop-hdds/client/src/main/java/org/apache/hadoop/ozone/client/io/ECBlockInputStreamProxy.java
+++
b/hadoop-hdds/client/src/main/java/org/apache/hadoop/ozone/client/io/ECBlockInputStreamProxy.java
@@ -54,8 +54,8 @@ public class ECBlockInputStreamProxy extends
BlockExtendedInputStream {
private final BlockLocationInfo blockInfo;
private final ECBlockInputStreamFactory ecBlockInputStreamFactory;
- private BlockExtendedInputStream blockReader;
- private boolean reconstructionReader = false;
+ private volatile BlockExtendedInputStream blockReader;
+ private volatile boolean reconstructionReader = false;
private final CopyOnWriteArrayList<DatanodeDetails> failedLocations;
private volatile boolean closed = false;
private OzoneClientConfig config;
@@ -216,6 +216,26 @@ protected int readPositioned(long position, ByteBuffer
buffer) throws IOExceptio
if (position >= blockInfo.getLength()) {
return EOF;
}
+ // Read blockReader before reconstructionReader: failover sets the flag
before it replaces the reader.
+ BlockExtendedInputStream healthyReader = blockReader;
+ if (!reconstructionReader && failedLocations.isEmpty()) {
+ int bufferPosition = buffer.position();
+ try {
+ return healthyReader.read(position, buffer);
+ } catch (IOException e) {
+ if (e instanceof BadDataLocationException) {
+ failedLocations.addAllAbsent(((BadDataLocationException)
e).getFailedLocations());
+ }
+ // a new reader below reconstructs the failed locations
+ String message = "Retrying positioned read with a new reader due to an
error in ECBlockReader.";
+ if (LOG.isDebugEnabled()) {
+ LOG.debug(message, e);
+ } else {
+ LOG.warn("{} Exception Class: {} , Exception Message: {}", message,
e.getClass().getName(), e.getMessage());
+ }
+ buffer.position(bufferPosition);
+ }
+ }
// Each request owns its cursor and reconstruction buffers; failed
locations are shared.
try (ECBlockInputStreamProxy reader = new
ECBlockInputStreamProxy(repConfig, blockInfo,
xceiverClientFactory, refreshFunction, ecBlockInputStreamFactory,
config, failedLocations)) {
diff --git
a/hadoop-hdds/client/src/main/java/org/apache/hadoop/ozone/client/io/ECBlockReconstructedStripeInputStream.java
b/hadoop-hdds/client/src/main/java/org/apache/hadoop/ozone/client/io/ECBlockReconstructedStripeInputStream.java
index 5540c916b4a..0f2b8f884cc 100644
---
a/hadoop-hdds/client/src/main/java/org/apache/hadoop/ozone/client/io/ECBlockReconstructedStripeInputStream.java
+++
b/hadoop-hdds/client/src/main/java/org/apache/hadoop/ozone/client/io/ECBlockReconstructedStripeInputStream.java
@@ -43,6 +43,7 @@
import java.util.concurrent.Future;
import java.util.function.Function;
import org.apache.commons.lang3.NotImplementedException;
+import org.apache.hadoop.fs.StreamCapabilities;
import org.apache.hadoop.hdds.client.BlockID;
import org.apache.hadoop.hdds.client.ECReplicationConfig;
import org.apache.hadoop.hdds.protocol.DatanodeDetails;
@@ -734,6 +735,17 @@ protected int readWithStrategy(ByteReaderStrategy
strategy) {
"Use readStripe() instead");
}
+ @Override
+ protected int readPositioned(long offset, ByteBuffer buffer) {
+ throw new UnsupportedOperationException("Use ECBlockInputStreamProxy for
positioned reads");
+ }
+
+ @Override
+ public boolean hasCapability(String capability) {
+ return !StreamCapabilities.PREADBYTEBUFFER.equalsIgnoreCase(capability)
+ && super.hasCapability(capability);
+ }
+
@Override
public synchronized void close() {
super.close();
diff --git
a/hadoop-hdds/client/src/test/java/org/apache/hadoop/hdds/scm/storage/TestBlockInputStream.java
b/hadoop-hdds/client/src/test/java/org/apache/hadoop/hdds/scm/storage/TestBlockInputStream.java
index 506d26ac1d8..c4233cd979f 100644
---
a/hadoop-hdds/client/src/test/java/org/apache/hadoop/hdds/scm/storage/TestBlockInputStream.java
+++
b/hadoop-hdds/client/src/test/java/org/apache/hadoop/hdds/scm/storage/TestBlockInputStream.java
@@ -473,6 +473,20 @@ public void testReadNotRetriedOnOtherException(IOException
ex)
}
}
+ @Test
+ public void
testPositionedReadOfClosedUninitializedStreamFailsWithIOException() throws
IOException {
+ BlockID blockID = new BlockID(new ContainerBlockID(1, 1));
+ BlockInputStream subject = new BlockInputStream(
+ new BlockLocationInfo(new
BlockLocationInfo.Builder().setBlockID(blockID).setLength(blockSize)),
+ MockPipeline.createSingleNodePipeline(), null,
mock(XceiverClientFactory.class), refreshFunction,
+ clientConfig);
+ subject.close();
+
+ // the stream has no client to initialize with, which must be reported as
an IOException
+ IOException e = assertThrows(IOException.class, () -> subject.read(0,
ByteBuffer.allocate(10)));
+ assertThat(e).hasMessageContaining("closed");
+ }
+
@ParameterizedTest
@MethodSource("exceptionsTriggersRefresh")
public void testRefreshOnReadFailureAfterUnbuffer(IOException ex)
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 083b689ac5b..948767b2c39 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
@@ -31,6 +31,7 @@
import java.util.SplittableRandom;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import org.apache.hadoop.hdds.client.BlockID;
import org.apache.hadoop.hdds.client.ECReplicationConfig;
@@ -299,6 +300,7 @@ public static class TestBlockInputStream extends
BlockExtendedInputStream {
private IOException errorToThrow = null;
private int ecReplicaIndex = 0;
private CountDownLatch readBarrier;
+ private final AtomicInteger positionedReads = new AtomicInteger();
private static final byte EOF = -1;
TestBlockInputStream(BlockID blockId, long blockLen, ByteBuffer data) {
@@ -338,14 +340,23 @@ public int getEcReplicaIndex() {
return ecReplicaIndex;
}
+ public int getPositionedReads() {
+ return positionedReads.get();
+ }
+
@Override
- protected int readPositioned(long position, ByteBuffer buffer) {
+ protected int readPositioned(long position, ByteBuffer buffer) throws
IOException {
+ positionedReads.incrementAndGet();
if (position >= length) {
return EOF;
}
+ int n = (int) Math.min(buffer.remaining(), length - position);
+ awaitReadBarrier();
+ if (shouldError && position + n > shouldErrorPosition) {
+ throwError();
+ }
ByteBuffer source = data.duplicate();
source.position((int) position);
- int n = (int) Math.min(buffer.remaining(), length - position);
source.limit(source.position() + n);
buffer.put(source);
return n;
@@ -372,17 +383,7 @@ 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);
- }
- }
+ awaitReadBarrier();
if (getRemaining() == 0) {
return EOF;
}
@@ -396,6 +397,20 @@ public int read(ByteBuffer buf) throws IOException {
return toRead;
}
+ private void awaitReadBarrier() throws IOException {
+ 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);
+ }
+ }
+ }
+
private void throwError() throws IOException {
if (errorToThrow != null) {
throw errorToThrow;
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 3f4828d7357..6dc18bdbe0f 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
@@ -33,14 +33,22 @@
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
+import java.util.SplittableRandom;
+import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.stream.Stream;
+import org.apache.hadoop.fs.FSExceptionMessages;
import org.apache.hadoop.hdds.client.BlockID;
import org.apache.hadoop.hdds.client.ECReplicationConfig;
import org.apache.hadoop.hdds.client.ReplicationConfig;
@@ -57,6 +65,7 @@
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.apache.ozone.test.GenericTestUtils;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -766,6 +775,218 @@ public void testParallelReadRetriesFailedIndexOnSpare()
throws IOException {
}
}
+ @ParameterizedTest
+ @MethodSource("parallelReadConfigs")
+ public void
testPositionedReadReturnsDataWithoutMovingPosition(ECReplicationConfig
ecConfig) throws IOException {
+ repConfig = ecConfig;
+ int chunk = ecConfig.getEcChunkSize();
+ int stripe = chunk * ecConfig.getData();
+ 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 = createStream(keyInfo, dataStreamFactory,
conf.getObject(OzoneClientConfig.class))) {
+ ecb.seek(37);
+ for (int[] range : ranges) {
+ ByteBuffer buf = ByteBuffer.allocate(range[1]);
+ int expected = Math.min(range[1], blockLength - range[0]);
+ assertEquals(expected, ecb.read(range[0], buf), "range " +
Arrays.toString(range));
+ assertEquals(expected, buf.position());
+ assertDataMatches(buf, range[0], expected);
+ assertEquals(37, ecb.getPos());
+ }
+ assertEquals(-1, ecb.read(blockLength, ByteBuffer.allocate(10)));
+ assertEquals(ecConfig.getData(),
dataStreamFactory.getBlockStreams().size());
+ for (ECStreamTestUtil.TestBlockInputStream indexStream :
dataStreamFactory.getBlockStreams()) {
+ assertEquals(0, indexStream.getPos());
+ }
+
+ // the sequential read continues where it was
+ ByteBuffer buf = ByteBuffer.allocate(stripe);
+ assertEquals(stripe, ecb.read(buf));
+ assertDataMatches(buf, 37, stripe);
+ assertEquals(37 + stripe, ecb.getPos());
+ }
+ assertEquals(parallelRead, parallelReadTasks.get() > 0);
+ }
+
+ @Test
+ public void testConcurrentPositionedAndSequentialReads() throws Exception {
+ repConfig = new ECReplicationConfig(3, 2, ECReplicationConfig.EcCodec.RS,
100);
+ int blockLength = 3 * 300 + 150;
+ ECStreamTestUtil.TestBlockInputStreamFactory dataStreamFactory =
createDataStreamFactory(blockLength);
+ BlockLocationInfo keyInfo = ECStreamTestUtil.createKeyInfo(repConfig, 5,
blockLength);
+ dataStreamFactory.setCurrentPipeline(keyInfo.getPipeline());
+
+ ExecutorService readers = Executors.newFixedThreadPool(8);
+ try (ECBlockInputStream ecb = createStream(keyInfo, dataStreamFactory,
conf.getObject(OzoneClientConfig.class))) {
+ List<Future<?>> futures = new ArrayList<>();
+ for (int t = 0; t < 8; t++) {
+ long seed = t;
+ futures.add(readers.submit((Callable<Void>) () -> {
+ SplittableRandom random = new SplittableRandom(seed);
+ for (int i = 0; i < 200; i++) {
+ int offset = random.nextInt(blockLength);
+ int length = Math.min(1 + random.nextInt(350), blockLength -
offset);
+ ByteBuffer buf = ByteBuffer.allocate(length);
+ ecb.readFully(offset, buf);
+ assertDataMatches(buf, offset, length);
+ }
+ return null;
+ }));
+ }
+ ByteBuffer buf = ByteBuffer.allocate(70);
+ for (long expectedPosition = 0; expectedPosition < blockLength;) {
+ buf.clear();
+ int read = ecb.read(buf);
+ assertDataMatches(buf, expectedPosition, read);
+ expectedPosition += read;
+ assertEquals(expectedPosition, ecb.getPos());
+ }
+ for (Future<?> future : futures) {
+ future.get(30, TimeUnit.SECONDS);
+ }
+ assertEquals(blockLength, ecb.getPos());
+ } finally {
+ readers.shutdownNow();
+ }
+ }
+
+ @Test
+ public void testFailedPositionedReadReportsIndexesWithoutChangingState()
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, which a positioned read must not switch to
+ DatanodeDetails spare = MockDatanodeDetails.randomDatanodeDetails();
+ datanodes.put(spare, 2);
+ BlockLocationInfo keyInfo = ECStreamTestUtil.createKeyInfo(repConfig,
blockLength, datanodes);
+ ECStreamTestUtil.TestBlockInputStreamFactory dataStreamFactory =
createDataStreamFactory(blockLength);
+ dataStreamFactory.setCurrentPipeline(keyInfo.getPipeline());
+ dataStreamFactory.setFailIndexes(2, 3);
+
+ try (ECBlockInputStream ecb = createStream(keyInfo, dataStreamFactory,
conf.getObject(OzoneClientConfig.class))) {
+ ecb.seek(50);
+ ByteBuffer buf = ByteBuffer.allocate(300);
+ BadDataLocationException e =
assertThrows(BadDataLocationException.class, () -> ecb.read(0, buf));
+ assertEquals(Arrays.asList(1, 2), e.getFailedLocationIndexes());
+ assertThat(e.getFailedLocations()).doesNotContain(spare).hasSize(2);
+ assertEquals(0, buf.position());
+ assertEquals(50, ecb.getPos());
+
+ // the failed streams were neither closed nor switched to the spare
+ dataStreamFactory.getBlockStream(2).setShouldError(false);
+ dataStreamFactory.getBlockStream(3).setShouldError(false);
+ assertEquals(300, ecb.read(0, buf));
+ assertDataMatches(buf, 0, 300);
+ assertEquals(3, dataStreamFactory.getBlockStreams().size());
+ assertEquals(50, ecb.getPos());
+ }
+ }
+
+ /**
+ * Another reader closes an index stream while a positioned read uses it,
for example a sequential read that switches
+ * the index to a spare, and the index may be reopened before the positioned
read checks it.
+ */
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ public void
testPositionedReadFailingOnConcurrentIndexCloseDoesNotReportLocations(boolean
reopen) throws Exception {
+ 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());
+ // the positioned read waits in the index stream until the test has closed
the stream
+ CountDownLatch barrier = new CountDownLatch(2);
+ dataStreamFactory.setReadBarrier(barrier);
+
+ ExecutorService reader = Executors.newSingleThreadExecutor();
+ try (ECBlockInputStream ecb = createStream(keyInfo, dataStreamFactory,
conf.getObject(OzoneClientConfig.class))) {
+ // the read only covers the first cell, of index 0
+ Future<Integer> pread = reader.submit(() -> ecb.read(10,
ByteBuffer.allocate(50)));
+ GenericTestUtils.waitFor(() -> barrier.getCount() == 1, 10, 10_000);
+ ECStreamTestUtil.TestBlockInputStream readStream =
dataStreamFactory.getBlockStream(1);
+ ecb.closeStream(0);
+ if (reopen) {
+ ecb.getOrOpenStream(0);
+ }
+ // the index stream was closed, so the read in progress fails
+ readStream.setShouldError(true);
+ barrier.countDown();
+
+ ExecutionException e = assertThrows(ExecutionException.class, () ->
pread.get(10, TimeUnit.SECONDS));
+ // the location is not bad, so it must not be reported as failed
+
assertThat(e.getCause()).isInstanceOf(IOException.class).isNotInstanceOf(BadDataLocationException.class);
+ } finally {
+ reader.shutdownNow();
+ }
+ }
+
+ @Test
+ public void
testPositionedReadFailingOnConcurrentCloseDoesNotReportLocations() throws
Exception {
+ 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());
+ // the positioned read waits in the index stream until the test has closed
the stream
+ CountDownLatch barrier = new CountDownLatch(2);
+ dataStreamFactory.setReadBarrier(barrier);
+
+ ExecutorService reader = Executors.newSingleThreadExecutor();
+ try (ECBlockInputStream ecb = createStream(keyInfo, dataStreamFactory,
conf.getObject(OzoneClientConfig.class))) {
+ Future<Integer> pread = reader.submit(() -> ecb.read(10,
ByteBuffer.allocate(50)));
+ GenericTestUtils.waitFor(() -> barrier.getCount() == 1, 10, 10_000);
+ ecb.close();
+ // closing the stream closed the index stream, so the read in progress
fails
+ dataStreamFactory.getBlockStream(1).setShouldError(true);
+ barrier.countDown();
+
+ ExecutionException e = assertThrows(ExecutionException.class, () ->
pread.get(10, TimeUnit.SECONDS));
+ // the location is not bad, so it must not be reported as failed
+
assertThat(e.getCause()).isInstanceOf(IOException.class).isNotInstanceOf(BadDataLocationException.class);
+ } finally {
+ reader.shutdownNow();
+ }
+ }
+
+ @Test
+ public void testPositionedReadRacingCloseOpensNoStreamAfterClose() throws
IOException {
+ BlockLocationInfo keyInfo = ECStreamTestUtil.createKeyInfo(repConfig, 5, 5
* ONEMB);
+ AtomicReference<ECBlockInputStream> stream = new AtomicReference<>();
+ AtomicBoolean closeOnOpen = new AtomicBoolean(true);
+ // close() runs while the positioned read opens its first index stream,
that is between two indexes of the read
+ BlockInputStreamFactory closingFactory = (rc, info, pipeline, token,
clients, refresh, config) -> {
+ BlockExtendedInputStream opened = streamFactory.create(rc, info,
pipeline, token, clients, refresh, config);
+ if (closeOnOpen.getAndSet(false)) {
+ stream.get().close();
+ }
+ return opened;
+ };
+ stream.set(createStream(keyInfo, closingFactory,
conf.getObject(OzoneClientConfig.class)));
+
+ // the read covers the cells of two indexes
+ ByteBuffer buf = ByteBuffer.allocate(repConfig.getEcChunkSize() + 100);
+ IOException e = assertThrows(IOException.class, () -> stream.get().read(0,
buf));
+ // the location is not bad, so it must not be reported as failed
+ assertThat(e).isNotInstanceOf(BadDataLocationException.class)
+ .hasMessageContaining(FSExceptionMessages.STREAM_IS_CLOSED);
+ // the second index stream is not opened after close(), where nothing
would close it
+ assertEquals(1, streamFactory.getBlockStreams().size());
+ }
+
/** 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) {
diff --git
a/hadoop-hdds/client/src/test/java/org/apache/hadoop/ozone/client/io/TestECBlockInputStreamProxy.java
b/hadoop-hdds/client/src/test/java/org/apache/hadoop/ozone/client/io/TestECBlockInputStreamProxy.java
index 95991a3174a..5d1c0a1bdb4 100644
---
a/hadoop-hdds/client/src/test/java/org/apache/hadoop/ozone/client/io/TestECBlockInputStreamProxy.java
+++
b/hadoop-hdds/client/src/test/java/org/apache/hadoop/ozone/client/io/TestECBlockInputStreamProxy.java
@@ -358,11 +358,21 @@ void positionedReadsRememberFailedLocations(boolean
sequentialFirst) throws Exce
return new ECStreamTestUtil.TestBlockInputStream(block.getBlockID(),
block.getLength(), ByteBuffer.wrap(data)) {
@Override
public int read(ByteBuffer destination) throws IOException {
+ failIfHealthy();
+ return super.read(destination);
+ }
+
+ @Override
+ protected int readPositioned(long position, ByteBuffer destination)
throws IOException {
+ failIfHealthy();
+ return super.readPositioned(position, destination);
+ }
+
+ private void failIfHealthy() throws IOException {
if (!missing) {
failedAttempts.incrementAndGet();
throw new BadDataLocationException(bad, "failed data replica");
}
- return super.read(destination);
}
};
};
@@ -415,6 +425,17 @@ void positionedReadsOverlapAndCloseTheirReaders(String
mode) throws Exception {
return new ECStreamTestUtil.TestBlockInputStream(block.getBlockID(),
block.getLength(), ByteBuffer.wrap(data)) {
@Override
public int read(ByteBuffer destination) throws IOException {
+ beforeRead(destination);
+ return super.read(destination);
+ }
+
+ @Override
+ protected int readPositioned(long position, ByteBuffer destination)
throws IOException {
+ beforeRead(destination);
+ return super.readPositioned(position, destination);
+ }
+
+ private void beforeRead(ByteBuffer destination) throws IOException {
if ("failover".equals(mode) && !missing) {
destination.put((byte) 0); // Retry must overwrite bytes from the
failed attempt.
throw new
BadDataLocationException(info.getPipeline().getFirstNode(), "failed data
replica");
@@ -427,7 +448,6 @@ public int read(ByteBuffer destination) throws IOException {
if ("failure".equals(mode)) {
throw new IOException("injected failure");
}
- return super.read(destination);
}
@Override
@@ -461,6 +481,10 @@ public void close() {
}
assertEquals(71, stream.getPos());
assertEquals(opened.get() - 1, closed.get());
+ if ("healthy".equals(mode)) {
+ // healthy positioned reads use the sequential reader, without
changing its position
+ assertEquals(1, opened.get());
+ }
assertEquals(-1, stream.read(data.length, ByteBuffer.allocate(1)));
} finally {
pool.shutdownNow();
diff --git
a/hadoop-hdds/client/src/test/java/org/apache/hadoop/ozone/client/io/TestECBlockReconstructedInputStream.java
b/hadoop-hdds/client/src/test/java/org/apache/hadoop/ozone/client/io/TestECBlockReconstructedInputStream.java
index 27a01f21eee..0fa6d23c085 100644
---
a/hadoop-hdds/client/src/test/java/org/apache/hadoop/ozone/client/io/TestECBlockReconstructedInputStream.java
+++
b/hadoop-hdds/client/src/test/java/org/apache/hadoop/ozone/client/io/TestECBlockReconstructedInputStream.java
@@ -18,6 +18,7 @@
package org.apache.hadoop.ozone.client.io;
import static
org.apache.hadoop.ozone.client.io.ECStreamTestUtil.generateParity;
+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.assertThrows;
@@ -46,6 +47,8 @@
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
/**
* Test for the ECBlockReconstructedInputStream class.
@@ -402,6 +405,75 @@ void
concurrentPositionedReadsReconstructIndependentStripes() throws Exception {
}
}
+ @Test
+ void healthyPositionedReadsReuseTheIndexStreams() throws Exception {
+ int chunk = repConfig.getEcChunkSize();
+ int blockLength = chunk * 7 - 101;
+ byte[] expected = setUpBlockData(blockLength);
+ BlockLocationInfo info = ECStreamTestUtil.createKeyInfo(repConfig,
blockLength,
+ ECStreamTestUtil.createIndexMap(1, 2, 3, 4, 5));
+ streamFactory.setCurrentPipeline(info.getPipeline());
+ try (ECBlockInputStreamProxy stream = createProxy(info)) {
+ stream.seek(chunk + 11);
+ byte[] actual = new byte[blockLength];
+ stream.readFully(0, actual);
+ assertArrayEquals(expected, actual);
+ List<ECStreamTestUtil.TestBlockInputStream> indexStreams =
streamFactory.getBlockStreams();
+ assertEquals(repConfig.getData(), indexStreams.size());
+
+ for (int offset : new int[] {chunk - 37, chunk * 3 - 29, blockLength -
5}) {
+ byte[] range = new byte[Math.min(chunk + 53, blockLength - offset)];
+ stream.readFully(offset, range);
+ assertArrayEquals(Arrays.copyOfRange(expected, offset, offset +
range.length), range);
+ }
+ // no new reader, so no new index streams, and only positioned reads on
them
+ assertEquals(indexStreams, streamFactory.getBlockStreams());
+ for (ECStreamTestUtil.TestBlockInputStream indexStream : indexStreams) {
+ assertEquals(0, indexStream.getPos());
+ assertThat(indexStream.getPositionedReads()).isPositive();
+ }
+ assertEquals(chunk + 11, stream.getPos());
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(ints = {1, 2})
+ void failedHealthyPositionedReadReconstructs(int failedIndexes) throws
Exception {
+ int chunk = repConfig.getEcChunkSize();
+ int blockLength = chunk * 7 - 101;
+ byte[] expected = setUpBlockData(blockLength);
+ BlockLocationInfo info = ECStreamTestUtil.createKeyInfo(repConfig,
blockLength,
+ ECStreamTestUtil.createIndexMap(1, 2, 3, 4, 5));
+ streamFactory.setCurrentPipeline(info.getPipeline());
+ // up to the parity count of data indexes fail, from the first positioned
read on
+ streamFactory.setFailIndexes(failedIndexes == 1 ? new Integer[] {2} : new
Integer[] {1, 3});
+ try (ECBlockInputStreamProxy stream = createProxy(info)) {
+ stream.seek(chunk + 11);
+ for (int offset : new int[] {chunk - 37, 0, chunk * 3 - 29}) {
+ byte[] actual = new byte[chunk * 3 + 53];
+ stream.readFully(offset, actual);
+ assertArrayEquals(Arrays.copyOfRange(expected, offset, offset +
actual.length), actual);
+ }
+ assertEquals(chunk + 11, stream.getPos());
+ }
+ }
+
+ /** Fills the data and parity streams of the factory, and returns the block
data. */
+ private byte[] setUpBlockData(int blockLength) throws IOException {
+ ByteBuffer[] data = allocateBuffers(repConfig.getData(),
repConfig.getEcChunkSize() * 3);
+ ECStreamTestUtil.randomFill(data, repConfig.getEcChunkSize(),
dataGenerator, blockLength);
+ addDataStreamsToFactory(data, generateParity(data, repConfig));
+ byte[] expected = new byte[blockLength];
+ ECStreamTestUtil.randomFill(ByteBuffer.wrap(expected), new
SplittableRandom(randomSeed));
+ return expected;
+ }
+
+ private ECBlockInputStreamProxy createProxy(BlockLocationInfo info) {
+ ECBlockInputStreamFactory factory =
ECBlockInputStreamFactoryImpl.getInstance(streamFactory, bufferPool,
+ () -> ecReconstructExecutor);
+ return new ECBlockInputStreamProxy(repConfig, info, null, null, factory,
conf.getObject(OzoneClientConfig.class));
+ }
+
private void addDataStreamsToFactory(ByteBuffer[] data, ByteBuffer[] parity)
{
List<ByteBuffer> dataStreams = new ArrayList<>(Arrays.asList(data));
dataStreams.addAll(Arrays.asList(parity));
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 540769edb5d..6536b7f4099 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,7 +44,10 @@
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.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.PositionedReadTestHelper;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.SequenceFile;
@@ -144,6 +147,13 @@ void testConcurrentECPositionedRead(boolean parallelRead)
throws Exception {
stream.seek(123);
PositionedReadTestHelper.runConcurrentPositionedReads(expected,
stream::readFully);
assertEquals(123, stream.getPos());
+
+ // the index streams of the block are open now, so further positioned
reads need no GetBlock
+ XceiverClientMetrics metrics =
XceiverClientManager.getXceiverClientMetrics();
+ long getBlockCalls =
metrics.getContainerOpCountMetrics(ContainerProtos.Type.GetBlock);
+ PositionedReadTestHelper.runConcurrentPositionedReads(expected,
stream::readFully);
+ assertEquals(getBlockCalls,
metrics.getContainerOpCountMetrics(ContainerProtos.Type.GetBlock));
+ assertEquals(123, stream.getPos());
}
}
diff --git
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/client/rpc/read/TestEcPositionedReadBenchmark.java
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/client/rpc/read/TestEcPositionedReadBenchmark.java
new file mode 100644
index 00000000000..b94fdd8d2c1
--- /dev/null
+++
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/client/rpc/read/TestEcPositionedReadBenchmark.java
@@ -0,0 +1,233 @@
+/*
+ * 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.junit.jupiter.api.Assertions.assertArrayEquals;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Random;
+import java.util.SplittableRandom;
+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 org.apache.hadoop.hdds.client.ECReplicationConfig;
+import org.apache.hadoop.hdds.conf.OzoneConfiguration;
+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.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.apache.hadoop.ozone.client.io.OzoneInputStream;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+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 of positioned reads on one open stream of a healthy EC key, by 1
and by several threads.
+ * Reports the latency of a positioned read and the GetBlock and ReadChunk
calls it needs.
+ */
+@Tag("benchmark")
+@TestInstance(TestInstance.Lifecycle.PER_CLASS)
+public class TestEcPositionedReadBenchmark {
+
+ private static final Logger LOG =
LoggerFactory.getLogger(TestEcPositionedReadBenchmark.class);
+
+ private static final int MB = 1024 * 1024;
+ private static final int KB = 1024;
+ private static final ECReplicationConfig RS_3_2 = new ECReplicationConfig(3,
2, RS, MB);
+ /** 16 stripes of rs-3-2, one block group. */
+ private static final int KEY_SIZE = 48 * MB;
+ private static final int WARMUP_ROUNDS = 1;
+ private static final int ROUNDS = 5;
+ private static final int THREADS = 8;
+ private static final String VOLUME = "benchvol";
+ private static final String BUCKET = "benchbucket";
+ private static final String KEY = "key";
+
+ private MiniOzoneCluster cluster;
+ // clients reading the cells of a multi-cell read one at a time, and in
parallel
+ private OzoneClient serialClient;
+ private OzoneClient parallelClient;
+ private byte[] data;
+
+ @BeforeAll
+ void init() throws Exception {
+ cluster = MiniOzoneCluster.newBuilder(new
OzoneConfiguration()).setNumDatanodes(5).build();
+ cluster.waitForClusterToBeReady();
+ serialClient = newClient(false);
+ parallelClient = newClient(true);
+ ObjectStore store = serialClient.getObjectStore();
+ store.createVolume(VOLUME);
+ store.getVolume(VOLUME).createBucket(BUCKET);
+ data = new byte[KEY_SIZE];
+ new Random(20261026L).nextBytes(data);
+ try (OutputStream out = bucket(serialClient).createKey(KEY, KEY_SIZE,
RS_3_2, Collections.emptyMap())) {
+ out.write(data);
+ }
+ }
+
+ @AfterAll
+ void shutdown() {
+ IOUtils.closeQuietly(serialClient, parallelClient);
+ if (cluster != null) {
+ cluster.shutdown();
+ }
+ }
+
+ 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);
+ }
+
+ private static OzoneBucket bucket(OzoneClient client) throws Exception {
+ return client.getObjectStore().getVolume(VOLUME).getBucket(BUCKET);
+ }
+
+ @Test
+ void benchmarkPositionedReads() throws Exception {
+ StringBuilder report = new StringBuilder();
+ for (boolean parallelRead : new boolean[] {false, true}) {
+ report.append(benchmark(parallelRead ? parallelClient : serialClient,
parallelRead));
+ }
+ LOG.info(report.toString());
+ }
+
+ private String benchmark(OzoneClient client, boolean parallelRead) throws
Exception {
+ StringBuilder report = new StringBuilder(String.format("%n"
+ + "BENCHRESULT EC healthy positioned reads (HDDS-16870) - parallel
cell reads %s, one open stream,"
+ + " 5 datanodes, %s%n"
+ + " key size=%d MB, rounds=%d (after %d warm-up); ops/s = median of
rounds; latency over all rounds%n"
+ + " %-6s %-7s %8s %10s %10s %10s %12s %12s%n",
+ parallelRead ? "on" : "off", RS_3_2.getReplication(), KEY_SIZE / MB,
ROUNDS, WARMUP_ROUNDS,
+ "size", "threads", "preads", "ops/s", "p50 ms", "p99 ms",
"GetBlock/op", "ReadChunk/op"));
+ for (int size : new int[] {4 * KB, 64 * KB, MB, 4 * MB}) {
+ for (int threads : new int[] {1, THREADS}) {
+ int preadsPerThread = size >= 4 * MB ? 25 : size >= MB ? 50 : 250;
+ List<Double> rates = new ArrayList<>();
+ List<Long> latencies = new ArrayList<>();
+ long getBlocks = 0;
+ long readChunks = 0;
+ for (int round = -WARMUP_ROUNDS; round < ROUNDS; round++) {
+ XceiverClientMetrics metrics =
XceiverClientManager.getXceiverClientMetrics();
+ long getBlockBefore =
metrics.getContainerOpCountMetrics(ContainerProtos.Type.GetBlock);
+ long readChunkBefore =
metrics.getContainerOpCountMetrics(ContainerProtos.Type.ReadChunk);
+ List<Long> roundLatencies = new ArrayList<>();
+ double rate = run(client, size, threads, preadsPerThread, round,
roundLatencies);
+ if (round >= 0) {
+ rates.add(rate);
+ latencies.addAll(roundLatencies);
+ getBlocks +=
metrics.getContainerOpCountMetrics(ContainerProtos.Type.GetBlock) -
getBlockBefore;
+ readChunks +=
metrics.getContainerOpCountMetrics(ContainerProtos.Type.ReadChunk) -
readChunkBefore;
+ }
+ }
+ long ops = (long) ROUNDS * threads * preadsPerThread;
+ report.append(String.format(" %-6s %-7d %8d %10.0f %10.3f %10.3f
%12.3f %12.3f%n",
+ size >= MB ? size / MB + "MB" : size / KB + "KB", threads, threads
* preadsPerThread,
+ median(rates), millis(percentile(latencies, 0.50)),
millis(percentile(latencies, 0.99)),
+ (double) getBlocks / ops, (double) readChunks / ops));
+ }
+ }
+ return report.toString();
+ }
+
+ /**
+ * Opens the key and runs preadsPerThread positioned reads of the given size
at random offsets on each thread, all
+ * on the same stream, and returns the aggregate positioned reads per second.
+ */
+ private double run(OzoneClient client, int size, int threads, int
preadsPerThread, int round, List<Long> latencies)
+ throws Exception {
+ ExecutorService pool = Executors.newFixedThreadPool(threads);
+ try (OzoneInputStream stream = bucket(client).readKey(KEY)) {
+ // a small positioned read first, so opening the key is not measured
+ stream.readFully(0, ByteBuffer.allocate(1));
+ CountDownLatch ready = new CountDownLatch(threads);
+ CountDownLatch start = new CountDownLatch(1);
+ List<Future<List<Long>>> futures = new ArrayList<>();
+ for (int t = 0; t < threads; t++) {
+ long seed = 31L * round + t;
+ futures.add(pool.submit((Callable<List<Long>>) () -> {
+ SplittableRandom random = new SplittableRandom(seed);
+ ByteBuffer buffer = ByteBuffer.allocate(size);
+ List<Long> own = new ArrayList<>(preadsPerThread);
+ ready.countDown();
+ start.await();
+ for (int i = 0; i < preadsPerThread; i++) {
+ int offset = random.nextInt(KEY_SIZE - size);
+ buffer.clear();
+ long begin = System.nanoTime();
+ stream.readFully(offset, buffer);
+ own.add(System.nanoTime() - begin);
+ if (i == 0) {
+ assertArrayEquals(Arrays.copyOfRange(data, offset, offset +
size), buffer.array());
+ }
+ }
+ return own;
+ }));
+ }
+ ready.await();
+ long begin = System.nanoTime();
+ start.countDown();
+ for (Future<List<Long>> future : futures) {
+ latencies.addAll(future.get(10, TimeUnit.MINUTES));
+ }
+ long elapsed = System.nanoTime() - begin;
+ return (double) threads * preadsPerThread / (elapsed / (double)
TimeUnit.SECONDS.toNanos(1));
+ } finally {
+ pool.shutdownNow();
+ }
+ }
+
+ private static double median(List<Double> values) {
+ List<Double> sorted = new ArrayList<>(values);
+ Collections.sort(sorted);
+ return sorted.get(sorted.size() / 2);
+ }
+
+ private static long percentile(List<Long> values, 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)));
+ }
+
+ private static double millis(long nanos) {
+ return nanos / 1e6;
+ }
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]