deniskuzZ commented on code in PR #6793: URL: https://github.com/apache/hive/pull/6793#discussion_r4156009905
########## llap-server/src/java/org/apache/hadoop/hive/llap/io/encoded/ParquetEncodedDataReader.java: ########## @@ -0,0 +1,654 @@ +/* + * 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.hive.llap.io.encoded; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.security.PrivilegedExceptionAction; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.Deque; +import java.util.IdentityHashMap; +import java.util.Map; +import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.stream.Collectors; + +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.fs.FileStatus; +import org.apache.hadoop.fs.FSDataInputStream; +import org.apache.hadoop.fs.FileRange; +import org.apache.hadoop.fs.FileSystem; +import org.apache.hadoop.fs.Path; +import org.apache.hadoop.hive.common.io.Allocator; +import org.apache.hadoop.hive.common.io.Allocator.BufferObjectFactory; +import org.apache.hadoop.hive.common.io.CacheTag; +import org.apache.hadoop.hive.common.io.DataCache.BooleanRef; +import org.apache.hadoop.hive.common.io.DiskRange; +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.conf.HiveConf; +import org.apache.hadoop.hive.conf.HiveConf.ConfVars; +import org.apache.hadoop.hive.llap.ConsumerFeedback; +import org.apache.hadoop.hive.llap.ParquetCacheLayout; +import org.apache.hadoop.hive.llap.ParquetRangeBuffers; +import org.apache.hadoop.hive.llap.LlapHiveUtils; +import org.apache.hadoop.hive.llap.cache.BufferUsageManager; +import org.apache.hadoop.hive.llap.cache.LlapDataBuffer; +import org.apache.hadoop.hive.llap.cache.LowLevelCache; +import org.apache.hadoop.hive.llap.cache.LowLevelCache.Priority; +import org.apache.hadoop.hive.llap.counters.LlapIOCounters; +import org.apache.hadoop.hive.llap.counters.QueryFragmentCounters; +import org.apache.hadoop.hive.llap.io.api.LlapProxy; +import org.apache.hadoop.hive.llap.io.decode.ParquetEncodedDataConsumer; +import org.apache.hadoop.hive.ql.io.IOConstants; +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.parquet.read.DataWritableReadSupport; +import org.apache.hadoop.hive.ql.io.parquet.vector.ParquetFooterInputFromCache; +import org.apache.hadoop.hive.ql.io.orc.encoded.StoppableAllocator; +import org.apache.hadoop.hive.ql.io.parquet.ParquetRecordReaderBase; +import org.apache.hadoop.hive.ql.io.parquet.vector.VectorizedParquetRecordReader; +import org.apache.hadoop.hive.ql.exec.Utilities; +import org.apache.hadoop.hive.ql.exec.vector.VectorizedRowBatchCtx; +import org.apache.hadoop.hive.ql.metadata.RowLineageUtils; +import org.apache.hadoop.hive.ql.metadata.VirtualColumn; +import org.apache.hadoop.mapred.FileSplit; +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.filter2.compat.FilterCompat; +import org.apache.parquet.filter2.compat.RowGroupFilter; +import org.apache.parquet.filter2.predicate.FilterPredicate; +import org.apache.parquet.hadoop.ParquetFileReader; +import org.apache.parquet.hadoop.metadata.BlockMetaData; +import org.apache.parquet.hadoop.metadata.ColumnChunkMetaData; +import org.apache.parquet.hadoop.metadata.ParquetMetadata; +import org.apache.parquet.hadoop.util.HadoopStreams; +import org.apache.parquet.io.InputFile; +import org.apache.parquet.io.SeekableInputStream; +import org.apache.parquet.column.ColumnDescriptor; +import org.apache.parquet.schema.MessageType; +import org.apache.parquet.schema.Type; +import org.apache.tez.common.CallableWithNdc; + +/** + * Reads one Parquet split through the LLAP cache on an IO thread. Row groups whose first data + * page falls in the split are selected and filtered by their statistics; for each one the + * projected column chunks are looked up in the cache, the missing ranges are requested in one + * vectored read, and the chunks are handed to the consumer to decode. The next row group's + * request is issued before the current one is decoded so its transfer overlaps the decode, as + * long as the two together stay within this thread's share of the cache. Every buffer in a + * consumed batch carries exactly one ref, owned by the batch until returnData. + */ +public class ParquetEncodedDataReader extends CallableWithNdc<Void> + implements ConsumerFeedback<ParquetEncodedColumnBatch> { + + private static final BufferObjectFactory DATA_BUFFER_FACTORY = LlapDataBuffer::new; + + private final LowLevelCache lowLevelCache; + private final BufferUsageManager bufferManager; + private final Configuration daemonConf; + private final ParquetCacheLayout layout; + private final JobConf jobConf; + private final FileSplit split; + private final ParquetEncodedDataConsumer consumer; + private final QueryFragmentCounters counters; + private final UserGroupInformation ugi; + private final Path path; + private final boolean cacheOnly; + /** Bytes of column chunks one IO thread may hold across the row group in decode and the next. */ + private final long lookaheadBudget; + + private Object fileKey; + private CacheTag cacheTag; + private ParquetMetadata footer; + private MessageType requestedSchema; + private final AtomicBoolean isStopped = new AtomicBoolean(false); + + public ParquetEncodedDataReader(LowLevelCache lowLevelCache, BufferUsageManager bufferManager, + Configuration daemonConf, Configuration jobConf, FileSplit split, + ParquetEncodedDataConsumer consumer, QueryFragmentCounters counters) throws IOException { + this.lowLevelCache = lowLevelCache; + this.bufferManager = bufferManager; + this.daemonConf = daemonConf; + this.layout = new ParquetCacheLayout(bufferManager.getAllocator(), daemonConf); + this.jobConf = (JobConf) jobConf; + this.split = split; + this.consumer = consumer; + this.counters = counters; + this.path = split.getPath(); + this.ugi = UserGroupInformation.getCurrentUser(); + this.cacheOnly = HiveConf.getBoolVar(jobConf, ConfVars.LLAP_IO_CACHE_ONLY); + this.lookaheadBudget = HiveConf.getSizeVar(daemonConf, ConfVars.LLAP_IO_MEMORY_MAX_SIZE) + / Math.max(1, HiveConf.getIntVar(daemonConf, ConfVars.LLAP_IO_THREADPOOL_SIZE)); + } + + /** Reads the footer once (through the LLAP footer cache when the file has a usable key). */ + public ParquetMetadata loadFooter() throws IOException { + fileKey = SyntheticFileId.fromJobConf(jobConf); + if (fileKey == null) { + fileKey = LlapHiveUtils.createFileIdUsingFS(path.getFileSystem(jobConf), path, daemonConf); + } + if (fileKey != null) { + cacheTag = VectorizedParquetRecordReader.cacheTagOfParquetFile(path, daemonConf, jobConf); + // Bumps METADATA_CACHE_HIT / METADATA_CACHE_MISS so the LLAP IO summary accounts for the + // Parquet footer lookup the same way it does for ORC's file tail. + BooleanRef cacheHit = new BooleanRef(); + MemoryBufferOrBuffers footerData = + LlapProxy.getIo().getParquetFooterBuffersFromCache(path, jobConf, fileKey, cacheHit); + counters.incrCounter(cacheHit.value + ? LlapIOCounters.METADATA_CACHE_HIT : LlapIOCounters.METADATA_CACHE_MISS); + footer = ParquetFileReader.readFooter( + new ParquetFooterInputFromCache(footerData), ParquetMetadataConverter.NO_FILTER); + } 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. + final FileSystem fs = path.getFileSystem(jobConf); + long hdfsStart = counters.startTimeCounter(); + final FileStatus stat = fs.getFileStatus(path); + counters.recordHdfsTime(hdfsStart); + InputFile inputFile = new InputFile() { + @Override + public SeekableInputStream newStream() throws IOException { + return HadoopStreams.wrap(fs.open(path)); + } + @Override + public long getLength() { + return stat.getLen(); + } + }; + hdfsStart = counters.startTimeCounter(); + footer = ParquetFileReader.readFooter(inputFile, ParquetMetadataConverter.NO_FILTER); + counters.recordHdfsTime(hdfsStart); + } + requestedSchema = DataWritableReadSupport.getRequestedSchema( + jobConf.getBoolean(DataWritableReadSupport.PARQUET_COLUMN_INDEX_ACCESS, false), + DataWritableReadSupport.getColumnNames(jobConf.get(IOConstants.COLUMNS)), + DataWritableReadSupport.getColumnTypes(jobConf.get(IOConstants.COLUMNS_TYPES)), + footer.getFileMetaData().getSchema(), jobConf); + return footer; + } + + @Override + protected Void callInternal() throws IOException, InterruptedException { + return ugi.doAs((PrivilegedExceptionAction<Void>) () -> { + long startTime = counters.startTimeCounter(); + try { + performDataRead(); + consumer.setDone(); + } catch (Exception e) { + // A shutdown-triggered InterruptedException must not be silently reported as an ordinary + // consumer error: preserve the interrupt on the thread so any caller sees it. + if (e instanceof InterruptedException) { + Thread.currentThread().interrupt(); + } + consumer.setError(e); + } finally { + counters.incrWallClockCounter(LlapIOCounters.TOTAL_IO_TIME_NS, startTime); + } + return null; + }); + } + + private void performDataRead() throws IOException, InterruptedException { + // The LLAP IO summary keys off TABLE / FILE / STRIPES; set them the same way ORC does so a + // native Parquet fragment shows up in the summary with the same fields populated. + if (cacheTag != null) { + counters.setDesc(QueryFragmentCounters.Desc.TABLE, cacheTag.getTableName()); + } + counters.setDesc(QueryFragmentCounters.Desc.FILE, path + + (fileKey == null ? "" : " (" + fileKey + ")")); + + MessageType fileSchema = footer.getFileMetaData().getSchema(); + int[] projected = projectedLeaves(requestedSchema, fileSchema); + consumer.setFileMetadata(footer, requestedSchema, path); + + final Allocator allocator = bufferManager.getAllocator(); + final List<BlockMetaData> blocks = footer.getBlocks(); + List<BlockMetaData> selected = selectRowGroups(blocks, fileSchema); + Map<BlockMetaData, Integer> rowGroupOf = new IdentityHashMap<>(); + for (int i = 0; i < blocks.size(); ++i) { + rowGroupOf.put(blocks.get(i), i); + } + // STRIPES is the ORC term; for Parquet the analog is row groups. Reuse the same descriptor so + // the summary layout stays common and we don't have to teach the reporter about a new field. + counters.setDesc(QueryFragmentCounters.Desc.STRIPES, "0," + selected.size()); + counters.incrCounter(LlapIOCounters.SELECTED_ROWGROUPS, selected.size()); + + FileSystem fs = path.getFileSystem(jobConf); + try (FSDataInputStream fileStream = openFile(fs)) { + ParquetRangeBuffers buffers = ParquetRangeBuffers.forStream(fileStream); + Deque<Fetch> inFlight = new ArrayDeque<>(); + try { + for (int i = 0; i < selected.size() && !isStopped.get(); ++i) { + if (inFlight.isEmpty()) { + inFlight.add(startFetch(fileStream, buffers, allocator, projected, selected.get(i), + rowGroupOf.get(selected.get(i)))); + } + // The next row group's requests go out now so its transfer overlaps this one's decode. + if (i + 1 < selected.size() && !isStopped.get() + && bytes(inFlight.peek()) + bytes(projected, selected.get(i + 1)) <= lookaheadBudget) { + inFlight.add(startFetch(fileStream, buffers, allocator, projected, selected.get(i + 1), + rowGroupOf.get(selected.get(i + 1)))); + } + finishFetch(allocator, buffers, inFlight.poll()); + } + } finally { + for (Fetch fetch : inFlight) { + abandon(allocator, fetch); + } + } + } + } + + /** + * The row groups this split has to read: the ones whose first data page falls inside the split, as + * Parquet's own input format assigns them, minus any the pushed-down predicate rules out on its + * statistics. Returned in file order, since the fetch pipeline reads them in that order. + */ + private List<BlockMetaData> selectRowGroups(List<BlockMetaData> blocks, MessageType fileSchema) + throws IOException { + long splitStart = split.getStart(); + long splitEnd = splitStart + split.getLength(); + List<BlockMetaData> selected = new ArrayList<>(); + for (BlockMetaData block : blocks) { + long firstDataPage = block.getColumns().getFirst().getFirstDataPageOffset(); + if (firstDataPage >= splitStart && firstDataPage < splitEnd) { + selected.add(block); + } + } + FilterPredicate predicate = ParquetRecordReaderBase.toFilterPredicate(jobConf, fileSchema); + if (predicate == null) { + return selected; + } + return RowGroupFilter.filterRowGroups(FilterCompat.get(predicate), selected, fileSchema); + } + + /** Whether the projection reaches into a group type, which this reader does not decode. */ + public boolean projectsNestedTypes() { + for (Type field : requestedSchema.getFields()) { + if (!field.isPrimitive()) { + return true; + } + } + return false; + } + + /** + * Whether the query needs row-lineage virtual columns ({@code ROW__LINEAGE__ID} / + * {@code LAST__UPDATED__SEQUENCE__NUMBER}) that the fallback reader augments the requested schema + * with via {@link RowLineageUtils#getRequestedSchemaWithRowLineageColumns}. The native pipeline + * doesn't propagate that augmentation through {@code Includes} yet, so we defer to the fallback + * reader instead of quietly emitting nulls in the lineage slots. + */ + public boolean needsRowLineage() { + VectorizedRowBatchCtx rbCtx = Utilities.getVectorizedRowBatchCtx(jobConf); + if (rbCtx == null) { + return false; + } + MessageType fileSchema = footer.getFileMetaData().getSchema(); + return RowLineageUtils.isRowLineageColumnPresent(rbCtx, fileSchema, VirtualColumn.ROW_LINEAGE_ID) + || RowLineageUtils.isRowLineageColumnPresent(rbCtx, fileSchema, + VirtualColumn.LAST_UPDATED_SEQUENCE_NUMBER); + } + + /** + * Leaf-column positions of the requested fields; {@code BlockMetaData.getColumns()} is a flat list + * of leaves in file-schema order, so a top-level primitive at ordinal {@code k} in the file schema + * may sit at a very different leaf index (e.g. a nested group of two leaves before it shifts it + * from {@code 1} to {@code 2}). We only reach this method when every requested field is a + * top-level primitive ({@link #projectsNestedTypes()} would have forced a fallback otherwise), so + * each requested field maps to exactly one leaf whose path is a single segment. + */ + static int[] projectedLeaves(MessageType requestedSchema, MessageType fileSchema) { + List<ColumnDescriptor> allLeaves = fileSchema.getColumns(); + List<Integer> selected = new ArrayList<>(); + for (Type field : requestedSchema.getFields()) { + if (!fileSchema.containsField(field.getName())) { + continue; + } + for (int i = 0; i < allLeaves.size(); ++i) { + String[] path = allLeaves.get(i).getPath(); + // Single-segment path == top-level primitive; skip leaves buried inside a group. + if (path.length == 1 && path[0].equals(field.getName())) { + selected.add(i); + break; + } + } + } + return selected.stream().mapToInt(Integer::intValue).toArray(); + } + + private static long bytes(int[] projected, BlockMetaData block) { + long total = 0; + for (int leaf : projected) { + total += block.getColumns().get(leaf).getTotalSize(); + } + return total; + } + + private static long bytes(Fetch fetch) { Review Comment: private static long projectedChunkBytes(Fetch fetch) -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
