Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -162,8 +162,8 @@ protected DeleteLoader newDeleteLoader() {
long start = task.start();
long length = task.length();

// TODO: Iceberg currently does not track the last modification time of a file. Until that's added,
// we need to set Long.MIN_VALUE as last modification time in the fileId triplet.
// Iceberg's metadata has no modification time for a data file, and a data file is never changed once written,
// so the key is the path and the size.
SyntheticFileId fileId = new SyntheticFileId(path, task.file().fileSizeInBytes(), Long.MIN_VALUE);
fileId.toJobConf(job);
RecordReader<NullWritable, VectorizedRowBatch> recordReader = null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ public interface LlapParquetIo {
* @param fileKey fileId of the Parquet file (either the Long fileId of HDFS or the SyntheticFileId).
* Optional, if it is not provided, it will be generated, see:
* org.apache.hadoop.hive.ql.io.HdfsUtils#getFileId()
* A miss takes a SyntheticFileId's length as the file's length and looks up no status.
* @param cacheHit optional out-parameter; when supplied, its {@code value} field is written
* with {@code true} on a cache hit and {@code false} on a miss, so the caller
* (which lives in llap-server and holds {@code QueryFragmentCounters}) can bump
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@

package org.apache.hadoop.hive.llap.io.api.impl;

import static org.apache.hadoop.fs.Options.OpenFileOptions.FS_OPTION_OPENFILE_LENGTH;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
Expand All @@ -31,8 +34,9 @@
import javax.annotation.Nullable;
import javax.management.ObjectName;

import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FutureDataInputStreamBuilder;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.common.io.CacheTag;
import org.apache.hadoop.hive.common.io.encoded.MemoryBufferOrBuffers;
Expand Down Expand Up @@ -88,6 +92,7 @@
import org.apache.hadoop.hive.llap.metrics.MetricsUtils;
import org.apache.hadoop.hive.ql.exec.vector.VectorizedRowBatch;
import org.apache.hadoop.hive.ql.io.LlapCacheOnlyInputFormatInterface;
import org.apache.hadoop.hive.ql.io.SyntheticFileId;
import org.apache.hadoop.hive.ql.io.orc.OrcSplit;
import org.apache.hadoop.hive.ql.io.orc.encoded.IoTrace;
import org.apache.hadoop.hive.ql.io.orc.OrcInputFormat;
Expand All @@ -101,6 +106,7 @@
import org.apache.hadoop.mapred.RecordReader;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.metrics2.util.MBeans;
import org.apache.hadoop.util.functional.FutureIO;
import org.apache.hive.common.util.FixedSizedObjectPool;
import org.apache.hive.common.util.HiveStringUtils;
import org.apache.orc.impl.OrcTail;
Expand Down Expand Up @@ -546,6 +552,13 @@ public RecordReader<NullWritable, VectorizedRowBatch> vectorizedReaderForPath(Ob
}
}

/**
* Bytes read from the end of a Parquet file when looking for its footer: S3A's default readahead,
* so the read costs no more than fetching the footer alone, and large enough to hold the footer of
* all but very wide schemas.
*/
private static final int FOOTER_READ_BYTES = 64 * 1024;

private class LlapParquetIoImpl implements LlapParquetIo, LlapFormatIo {
private final ColumnVectorProducer cvp;

Expand Down Expand Up @@ -587,21 +600,65 @@ public MemoryBufferOrBuffers getFooterBuffersFromCache(Path path, JobConf conf,
} else {
throwIfCacheOnlyRead(isReadCacheOnly);
}
return readAndCacheFooter(path, conf, tag, fileKey);
}

/**
* Reads the file's tail once and caches the footer from it. The last 8 bytes hold the footer length and the
* magic, and the footer itself is almost always inside the same range, so a miss costs one read rather than a
* 4 byte read followed by the footer.
*/
private MemoryBufferOrBuffers readAndCacheFooter(Path path, JobConf conf, @Nullable CacheTag tag,
@Nullable Object fileKey) throws IOException {
final FileSystem fs = path.getFileSystem(conf);
final FileStatus stat = fs.getFileStatus(path);
final FutureDataInputStreamBuilder builder = fs.openFile(path);
final long length;
if (fileKey instanceof SyntheticFileId syntheticKey) {
// A synthetic key holds the file's length, so the read needs no status lookup, which is a HEAD on S3A.
length = syntheticKey.getLength();
builder.optLong(FS_OPTION_OPENFILE_LENGTH, length);
} else {
// Other keys, such as an HDFS inode id, hold no length, so the status supplies it.
length = fs.getFileStatus(path).getLen();
}
final int trailerSize = ParquetFooterInputFromCache.FOOTER_LENGTH_SIZE + ParquetFileWriter.MAGIC.length;
// The checks of ParquetFileReader.readFooter, before anything is cached.
if (length < ParquetFileWriter.MAGIC.length + trailerSize) {
throw new IOException(path + " is not a Parquet file (length is too low: " + length + ")");
}

// To avoid reading the footer twice, we will cache it first and then read from cache.
// Parquet calls protobuf methods directly on the stream and we can't get bytes after the fact.
try (SeekableInputStream stream = HadoopStreams.wrap(fs.open(path))) {
long footerLengthIndex = stat.getLen()
- ParquetFooterInputFromCache.FOOTER_LENGTH_SIZE - ParquetFileWriter.MAGIC.length;
stream.seek(footerLengthIndex);
int footerLength = BytesUtils.readIntLittleEndian(stream);
stream.seek(footerLengthIndex - footerLength);
FSDataInputStream in = FutureIO.awaitFuture(builder.build());
try (SeekableInputStream stream = HadoopStreams.wrap(in)) {
int tailLength = (int) Math.min(length, FOOTER_READ_BYTES);
byte[] tail = new byte[tailLength];
stream.seek(length - tailLength);
stream.readFully(tail);
byte[] magic = Arrays.copyOfRange(tail, tailLength - ParquetFileWriter.MAGIC.length, tailLength);
if (!Arrays.equals(ParquetFileWriter.MAGIC, magic) && !Arrays.equals(ParquetFileWriter.EFMAGIC, magic)) {
throw new IOException(path + " is not a Parquet file. Expected magic number at tail, but found "
+ Arrays.toString(magic));
}
int footerLength = BytesUtils.readIntLittleEndian(tail, tailLength - trailerSize);
long footerIndex = length - trailerSize - footerLength;
if (footerIndex < ParquetFileWriter.MAGIC.length || footerIndex >= length - trailerSize) {
throw new IOException("Corrupted Parquet file " + path + ": the footer index " + footerIndex
+ " is not within the file");
}
int footerStart = tailLength - trailerSize - footerLength;

LOG.debug("Caching the footer of length {} for {}", footerLength, fileKey);
// Note: we don't pass in isStopped here - this is not on an IO thread.
footerData = fileMetadataCache.putFileMetadata(fileKey, footerLength, stream, tag, null);
MemoryBufferOrBuffers footerData;
if (footerStart >= 0) {
footerData = fileMetadataCache.putFileMetadata(fileKey, footerLength,
new ByteArrayInputStream(tail, footerStart, footerLength), tag, null);
} else {
// A footer larger than the hint; read it on its own rather than growing the tail read.
stream.seek(footerIndex);
footerData = fileMetadataCache.putFileMetadata(fileKey, footerLength, stream, tag, null);
}
try {
return footerData;
} finally {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.util.functional.FutureIO;
import org.apache.parquet.format.converter.ParquetMetadataConverter;
import org.apache.parquet.ParquetReadOptions;
import org.apache.parquet.filter2.compat.FilterCompat;
import org.apache.parquet.filter2.compat.RowGroupFilter;
import org.apache.parquet.filter2.predicate.FilterPredicate;
Expand Down Expand Up @@ -102,6 +102,9 @@ public class ParquetEncodedDataReader extends CallableWithNdc<Void>
implements ConsumerFeedback<ParquetEncodedColumnBatch>, TezCounterSource {

private static final BufferObjectFactory DATA_BUFFER_FACTORY = LlapDataBuffer::new;
// Built once: ParquetFileReader.readFooter(InputFile, filter) builds the same options on every call, and each build
// parses the Hadoop default configuration.
private static final ParquetReadOptions FOOTER_OPTIONS = ParquetReadOptions.builder().build();

private final LowLevelCache lowLevelCache;
private final BufferUsageManager bufferManager;
Expand Down Expand Up @@ -165,8 +168,7 @@ public ParquetMetadata readFooter() throws IOException {
HdfsUtils.getFileIdPath(path, fileKey, daemonConf), jobConf, cacheTag, fileKey, cacheHit);
counters.incrCounter(cacheHit.value
? LlapIOCounters.METADATA_CACHE_HIT : LlapIOCounters.METADATA_CACHE_MISS);
footer = ParquetFileReader.readFooter(
new ParquetFooterInputFromCache(footerData), ParquetMetadataConverter.NO_FILTER);
footer = readFooter(new ParquetFooterInputFromCache(footerData));
} else {
// Fallback path: no cache key, so we read status + footer straight from HDFS. Time both
// under HDFS_TIME_NS to match how ORC accounts for cache-miss footer reads.
Expand All @@ -185,7 +187,7 @@ public long getLength() {
}
};
hdfsStart = counters.startTimeCounter();
footer = ParquetFileReader.readFooter(inputFile, ParquetMetadataConverter.NO_FILTER);
footer = readFooter(inputFile);
counters.recordHdfsTime(hdfsStart);
}
requestedSchema = DataWritableReadSupport.getRequestedSchema(
Expand All @@ -196,6 +198,12 @@ public long getLength() {
return footer;
}

private static ParquetMetadata readFooter(InputFile file) throws IOException {
try (SeekableInputStream in = file.newStream()) {
return ParquetFileReader.readFooter(file, FOOTER_OPTIONS, in);
}
}

@Override
protected Void callInternal() throws IOException, InterruptedException {
return ugi.doAs((PrivilegedExceptionAction<Void>) () -> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,11 +56,13 @@
import org.apache.commons.lang3.ArrayUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.impl.OpenFileParameters;
import org.apache.hadoop.fs.RawLocalFileSystem;
import org.apache.hadoop.fs.FileRange;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.RawLocalFileSystem;

Check warning on line 65 in llap-server/src/test/org/apache/hadoop/hive/llap/io/encoded/TestParquetEncodedDataReader.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Duplicate import to line 60 - org.apache.hadoop.fs.RawLocalFileSystem.

See more on https://sonarcloud.io/project/issues?id=apache_hive&issues=AaJC2A2G9R6ojr3UkZoq&open=AaJC2A2G9R6ojr3UkZoq&pullRequest=6979

Check warning on line 65 in llap-server/src/test/org/apache/hadoop/hive/llap/io/encoded/TestParquetEncodedDataReader.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Remove this duplicated import.

See more on https://sonarcloud.io/project/issues?id=apache_hive&issues=AaJC2A2F9R6ojr3UkZop&open=AaJC2A2F9R6ojr3UkZop&pullRequest=6979
import org.apache.hadoop.fs.StreamCapabilities;
import org.apache.hadoop.hive.common.io.Allocator;
import org.apache.hadoop.hive.common.io.Allocator.BufferObjectFactory;
Expand All @@ -72,6 +74,7 @@
import org.apache.hadoop.hive.common.io.FileMetadataCache;
import org.apache.hadoop.hive.common.io.DiskRangeList;
import org.apache.hadoop.hive.common.io.encoded.MemoryBuffer;
import org.apache.hadoop.hive.common.io.encoded.MemoryBufferOrBuffers;
import org.apache.hadoop.hive.common.type.DataTypePhysicalVariation;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.conf.HiveConf.ConfVars;
Expand Down Expand Up @@ -112,10 +115,12 @@
import org.apache.hadoop.hive.ql.exec.vector.VectorizedRowBatchCtx;
import org.apache.hadoop.hive.ql.io.IOConstants;
import org.apache.hadoop.hive.ql.io.LlapCacheOnlyInputFormatInterface;
import org.apache.hadoop.hive.ql.io.SyntheticFileId;
import org.apache.hadoop.hive.ql.io.orc.encoded.CacheChunk;
import org.apache.hadoop.hive.ql.io.orc.encoded.Consumer;
import org.apache.hadoop.hive.ql.io.parquet.read.DataWritableReadSupport;
import org.apache.hadoop.hive.ql.io.parquet.serde.ArrayWritableObjectInspector;
import org.apache.hadoop.hive.ql.io.parquet.vector.ParquetFooterInputFromCache;
import org.apache.hadoop.hive.ql.io.parquet.vector.VectorizedParquetRecordReader;
import org.apache.hadoop.hive.ql.io.sarg.ConvertAstToSearchArg;
import org.apache.hadoop.hive.ql.io.sarg.PredicateLeaf;
Expand All @@ -137,10 +142,12 @@
import org.apache.hadoop.mapred.RecordReader;
import org.apache.hadoop.mapred.Reporter;
import org.apache.orc.TypeDescription;
import org.apache.parquet.bytes.BytesUtils;
import org.apache.parquet.example.data.Group;
import org.apache.parquet.example.data.simple.SimpleGroupFactory;
import org.apache.parquet.format.converter.ParquetMetadataConverter;
import org.apache.parquet.hadoop.ParquetFileReader;
import org.apache.parquet.hadoop.ParquetFileWriter;
import org.apache.parquet.hadoop.ParquetWriter;
import org.apache.parquet.hadoop.example.ExampleParquetWriter;
import org.apache.parquet.hadoop.metadata.BlockMetaData;
Expand Down Expand Up @@ -550,6 +557,120 @@
assertEquals(0, second.counter(LlapIOCounters.METADATA_CACHE_MISS));
}

/** A footer within the tail read is read with the tail, in one request. */
@Test
public void testFooterWithinTailReadIsOneRequest() throws Exception {
Path copy = new Path(tmpDir.toString(), "one-request.parquet");
FileSystem.getLocal(daemonConf).copyFromLocalFile(false, true, file, copy);
CountingFileSystem.reset();
LlapProxy.getIo().parquet().getFooterBuffersFromCache(copy, countingJob(), null, "one-request-footer", null);
assertEquals(1, CountingFileSystem.SEEKS.get());
}

/** A synthetic file key holds the file's length, so a footer read under it looks up no status for the length. */
@Test
public void testFooterUnderSyntheticKeySkipsStatusLookup() throws Exception {
Path copy = new Path(tmpDir.toString(), "synthetic-key.parquet");
FileSystem local = FileSystem.getLocal(daemonConf);
local.copyFromLocalFile(false, true, file, copy);
CountingFileSystem.reset();
LlapProxy.getIo().parquet().getFooterBuffersFromCache(copy, countingJob(), null, "status-footer", null);
int lookupsWithoutLength = CountingFileSystem.STATUS_LOOKUPS.get();

CountingFileSystem.reset();
MemoryBufferOrBuffers footerData = LlapProxy.getIo().parquet().getFooterBuffersFromCache(
copy, countingJob(), null, new SyntheticFileId(local.getFileStatus(copy)), null);
assertEquals(lookupsWithoutLength - 1, CountingFileSystem.STATUS_LOOKUPS.get());
assertEquals(1, CountingFileSystem.SEEKS.get());
ParquetMetadata cached = ParquetFileReader.readFooter(
new ParquetFooterInputFromCache(footerData), ParquetMetadataConverter.NO_FILTER);
ParquetMetadata expected = ParquetFileReader.readFooter(
HadoopInputFile.fromPath(copy, daemonConf), ParquetMetadataConverter.NO_FILTER);
assertEquals(expected.getFileMetaData().getSchema(), cached.getFileMetaData().getSchema());
assertEquals(expected.getBlocks().toString(), cached.getBlocks().toString());
}

private static JobConf countingJob() {
JobConf job = new JobConf(daemonConf);
job.set("fs.file.impl", CountingFileSystem.class.getName());
job.setBoolean("fs.file.impl.disable.cache", true);
return job;
}

/** A footer larger than the tail read is read on its own and comes back whole. */
@Test
public void testFooterLargerThanTailRead() throws Exception {
int columns = 2000;
Types.MessageTypeBuilder builder = Types.buildMessage();
for (int i = 0; i < columns; i++) {
builder.optional(PrimitiveTypeName.INT64).named("wide_column_" + i);
}
MessageType schema = builder.named("wide");
Path wide = new Path(tmpDir.toString(), "wide.parquet");
try (ParquetWriter<Group> writer = ExampleParquetWriter.builder(wide).withConf(daemonConf).withType(schema)
.build()) {
Group row = new SimpleGroupFactory(schema).newGroup();
for (int i = 0; i < columns; i++) {
row.append("wide_column_" + i, (long) i);
}
writer.write(row);
}
FileSystem fs = wide.getFileSystem(daemonConf);
long length = fs.getFileStatus(wide).getLen();
byte[] trailer = new byte[4];
try (FSDataInputStream in = fs.open(wide)) {
in.readFully(length - 8, trailer);
}
assertTrue("footer fits in the tail read", BytesUtils.readIntLittleEndian(trailer, 0) > 64 * 1024);

CountingFileSystem.reset();
MemoryBufferOrBuffers footerData =
LlapProxy.getIo().parquet().getFooterBuffersFromCache(wide, countingJob(), null, "wide-footer", null);
assertEquals("the tail, then the footer", 2, CountingFileSystem.SEEKS.get());
ParquetMetadata cached = ParquetFileReader.readFooter(
new ParquetFooterInputFromCache(footerData), ParquetMetadataConverter.NO_FILTER);
ParquetMetadata expected = ParquetFileReader.readFooter(
HadoopInputFile.fromPath(wide, daemonConf), ParquetMetadataConverter.NO_FILTER);
assertEquals(expected.getFileMetaData().getSchema(), cached.getFileMetaData().getSchema());
assertEquals(expected.getBlocks().toString(), cached.getBlocks().toString());
}

/** A file shorter than the Parquet trailer is refused as not Parquet, not read before its start. */
@Test
public void testFooterOfAFileTooShortForParquetIsRefused() throws Exception {
assertFooterRefused(tmpFile("tiny.parquet", new byte[] {1, 2, 3, 4, 5}), "not a Parquet file");
}

/**
* The footer of a file without the Parquet magic at its tail, or whose footer would start outside it, is refused,
* and nothing is cached for it.
*/
@Test
public void testFooterOfANonParquetFileIsRefusedUncached() throws Exception {
byte[] noMagic = new byte[1000];
noMagic[999] = 'X';
assertFooterRefused(tmpFile("no-magic.parquet", noMagic), "Expected magic number");
byte[] footerOutside = new byte[1000];
// a footer length of 2000 bytes before "PAR1", in a 1000-byte file
footerOutside[992] = (byte) 0xD0;
footerOutside[993] = 0x07;
System.arraycopy(ParquetFileWriter.MAGIC, 0, footerOutside, 996, 4);
assertFooterRefused(tmpFile("footer-outside.parquet", footerOutside), "not within the file");
}

private static Path tmpFile(String name, byte[] bytes) throws IOException {
return new Path(Files.write(tmpDir.resolve(name), bytes).toUri());
}

/** The footer read refuses the file, twice: a refused footer is not cached. */
private static void assertFooterRefused(Path path, String reason) {
for (int attempt = 0; attempt < 2; ++attempt) {
IOException e = assertThrows(IOException.class, () -> LlapProxy.getIo().parquet().getFooterBuffersFromCache(
path, new JobConf(daemonConf), null, path.getName(), null));
assertTrue(e.getMessage(), e.getMessage().contains(reason));
}
}

/** A Parquet fragment fills in the same counters the LLAP IO summary already shows for an ORC one. */
@Test
public void testFragmentCountersParityWithOrc() throws Exception {
Expand Down Expand Up @@ -1446,6 +1567,38 @@
return out;
}

/**
* A local file system that counts the status lookups and the positions read from Parquet files, one request each on
* an object store.
*/
public static class CountingFileSystem extends RawLocalFileSystem {
static final AtomicInteger STATUS_LOOKUPS = new AtomicInteger();
static final AtomicInteger SEEKS = new AtomicInteger();

static void reset() {
STATUS_LOOKUPS.set(0);
SEEKS.set(0);
}

@Override
public FileStatus getFileStatus(Path path) throws IOException {
STATUS_LOOKUPS.incrementAndGet();
return super.getFileStatus(path);
}

@Override
protected CompletableFuture<FSDataInputStream> openFileWithOptions(Path path, OpenFileParameters parameters)
throws IOException {
return super.openFileWithOptions(path, parameters).thenApply(stream -> new FSDataInputStream(stream) {
@Override
public void seek(long position) throws IOException {
SEEKS.incrementAndGet();
super.seek(position);
}
});
}
}

private static FileSplit wholeFile() {
return new FileSplit(file, 0, fileLength, (String[]) null);
}
Expand Down
Loading
Loading