abstractdog commented on code in PR #6793: URL: https://github.com/apache/hive/pull/6793#discussion_r4034551562
########## llap-server/src/java/org/apache/hadoop/hive/llap/io/encoded/ParquetEncodedDataReader.java: ########## @@ -0,0 +1,560 @@ +/* + * 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 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.ColumnVectorProducer.Includes; +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.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.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 Includes includes; + 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, Includes includes, + 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.includes = includes; + 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 { + final FileSystem fs = path.getFileSystem(jobConf); + final FileStatus stat = fs.getFileStatus(path); + InputFile inputFile = new InputFile() { + @Override + public SeekableInputStream newStream() throws IOException { + return HadoopStreams.wrap(fs.open(path)); + } + @Override + public long getLength() { + return stat.getLen(); + } + }; + footer = ParquetFileReader.readFooter(inputFile, ParquetMetadataConverter.NO_FILTER); + } + 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>) () -> { + try { + performDataRead(); + consumer.setDone(); + } catch (Throwable t) { + consumer.setError(t); + } + return null; + }); + } + + private void performDataRead() throws IOException, InterruptedException { + MessageType fileSchema = footer.getFileMetaData().getSchema(); + int[] projected = projectedLeaves(requestedSchema, fileSchema); + consumer.setFileMetadata(footer, requestedSchema, path); + + final Allocator allocator = bufferManager.getAllocator(); + final int maxAlloc = allocator.getMaxAllocation(); + final long splitStart = split.getStart(), splitEnd = splitStart + split.getLength(); + final List<BlockMetaData> blocks = footer.getBlocks(); + List<BlockMetaData> selected = new ArrayList<>(); + for (BlockMetaData block : blocks) { + long firstDataPage = block.getColumns().get(0).getFirstDataPageOffset(); + if (firstDataPage >= splitStart && firstDataPage < splitEnd) { + selected.add(block); + } + } + FilterPredicate predicate = ParquetRecordReaderBase.toFilterPredicate(jobConf, fileSchema); + if (predicate != null) { + selected = RowGroupFilter.filterRowGroups(FilterCompat.get(predicate), selected, fileSchema); + } + Map<BlockMetaData, Integer> rowGroupOf = new IdentityHashMap<>(); + for (int i = 0; i < blocks.size(); ++i) { + rowGroupOf.put(blocks.get(i), i); + } + 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, maxAlloc, 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, maxAlloc, projected, selected.get(i + 1), + rowGroupOf.get(selected.get(i + 1)))); + } + finishFetch(allocator, buffers, inFlight.poll()); + } + } finally { + for (Fetch fetch : inFlight) { + abandon(allocator, fetch); + } + } + } + } + + /** 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; + } + + /** File-schema positions of the requested fields; column chunks follow the schema order. */ + private static int[] projectedLeaves(MessageType requestedSchema, MessageType fileSchema) { + List<Integer> leaves = new ArrayList<>(); + for (Type field : requestedSchema.getFields()) { + if (fileSchema.containsField(field.getName())) { + leaves.add(fileSchema.getFieldIndex(field.getName())); + } + } + return leaves.stream().mapToInt(Integer::intValue).toArray(); Review Comment: good catch, this would totally mess up columns in case of schema like: ``` message hive_schema { optional group nested { optional int32 a; optional int32 b; } optional int32 x; } ``` where ` fileSchema.getFieldIndex("x")` = 1, but `fileSchema.getColumns() → [nested.a, nested.b, x] (three leaves, indices 0, 1, 2).`, so `block.getColumns().get(1)` was used for x, but it's actually `nested.b.` -- 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]
