From 548050271e5869bc6a5b4c8b735927d6d0721062 Mon Sep 17 00:00:00 2001 From: Owen O'Malley Date: Mon, 15 Jul 2019 11:33:01 -0700 Subject: [PATCH] ORC-520: Fix file merging for column encryption. Fixes #423 Signed-off-by: Owen O'Malley --- .../src/java/org/apache/orc/DataReader.java | 14 +- .../java/org/apache/orc/EncryptionKey.java | 6 + .../org/apache/orc/EncryptionVariant.java | 11 +- .../src/java/org/apache/orc/FileMetadata.java | 1 + .../core/src/java/org/apache/orc/OrcFile.java | 219 +++++++-- .../src/java/org/apache/orc/OrcUtils.java | 2 +- .../java/org/apache/orc/PhysicalWriter.java | 1 - java/core/src/java/org/apache/orc/Reader.java | 36 +- .../org/apache/orc/StripeInformation.java | 8 +- .../java/org/apache/orc/StripeStatistics.java | 28 +- .../java/org/apache/orc/TypeDescription.java | 60 +-- java/core/src/java/org/apache/orc/Writer.java | 36 +- .../src/java/org/apache/orc/impl/OrcTail.java | 122 +++-- .../org/apache/orc/impl/PhysicalFsWriter.java | 15 +- .../java/org/apache/orc/impl/ReaderImpl.java | 417 ++++++++++-------- .../org/apache/orc/impl/RecordReaderImpl.java | 22 +- .../apache/orc/impl/RecordReaderUtils.java | 12 +- .../apache/orc/impl/StripeStatisticsImpl.java | 55 +++ .../java/org/apache/orc/impl/TypeUtils.java | 105 +++++ .../java/org/apache/orc/impl/WriterImpl.java | 171 ++++--- .../orc/impl/mask/SHA256MaskFactory.java | 33 +- .../orc/impl/reader/ReaderEncryption.java | 46 +- .../orc/impl/reader/ReaderEncryptionKey.java | 19 +- .../impl/reader/ReaderEncryptionVariant.java | 115 ++++- .../apache/orc/impl/reader/StripePlanner.java | 28 +- .../orc/impl/writer/EncryptionTreeWriter.java | 34 +- .../orc/impl/writer/ListTreeWriter.java | 8 +- .../apache/orc/impl/writer/MapTreeWriter.java | 10 +- .../orc/impl/writer/StructTreeWriter.java | 8 +- .../apache/orc/impl/writer/TreeWriter.java | 9 +- .../orc/impl/writer/TreeWriterBase.java | 23 +- .../orc/impl/writer/UnionTreeWriter.java | 8 +- .../orc/impl/writer/WriterEncryptionKey.java | 6 +- .../impl/writer/WriterEncryptionVariant.java | 4 - .../org/apache/orc/TestTypeDescription.java | 6 +- .../org/apache/orc/TestVectorOrcFile.java | 309 ++++++++++++- .../org/apache/orc/impl/MockDataReader.java | 11 +- .../test/org/apache/orc/impl/MockStripe.java | 5 + .../apache/orc/impl/TestRecordReaderImpl.java | 33 +- .../apache/orc/impl/TestSchemaEvolution.java | 3 +- proto/orc_proto.proto | 6 +- 41 files changed, 1477 insertions(+), 588 deletions(-) create mode 100644 java/core/src/java/org/apache/orc/impl/StripeStatisticsImpl.java create mode 100644 java/core/src/java/org/apache/orc/impl/TypeUtils.java diff --git a/java/core/src/java/org/apache/orc/DataReader.java b/java/core/src/java/org/apache/orc/DataReader.java index 7728cdcffd..4c1a551dc8 100644 --- a/java/core/src/java/org/apache/orc/DataReader.java +++ b/java/core/src/java/org/apache/orc/DataReader.java @@ -23,6 +23,7 @@ import org.apache.hadoop.hive.common.io.DiskRangeList; import org.apache.orc.impl.BufferChunkList; +import org.apache.orc.impl.InStream; import org.apache.orc.impl.OrcIndex; /** An abstract data reader that IO formats can use to read bytes from underlying storage. */ @@ -42,10 +43,10 @@ public interface DataReader extends AutoCloseable, Cloneable { * * @param range List of disk ranges to read. Ranges with data will be ignored. * @param doForceDirect Whether the data should be read into direct buffers. - * @return New or modified list of DiskRange-s, where all the ranges are filled with data. + * @return The list range with buffers filled in */ BufferChunkList readFileData(BufferChunkList range, - boolean doForceDirect) throws IOException; + boolean doForceDirect) throws IOException; /** * Whether the user should release buffers created by readFileData. See readFileData javadoc. @@ -70,9 +71,10 @@ BufferChunkList readFileData(BufferChunkList range, void close() throws IOException; /** - * Returns the compression codec used by this datareader. - * We should consider removing this from the interface. - * @return the compression codec + * Returns the compression options used by this DataReader. + * The codec if present is owned by the DataReader and should not be returned + * to the OrcCodecPool. + * @return the compression options */ - CompressionCodec getCompressionCodec(); + InStream.StreamOptions getCompressionOptions(); } diff --git a/java/core/src/java/org/apache/orc/EncryptionKey.java b/java/core/src/java/org/apache/orc/EncryptionKey.java index 24153b8ace..a468ea6f6c 100644 --- a/java/core/src/java/org/apache/orc/EncryptionKey.java +++ b/java/core/src/java/org/apache/orc/EncryptionKey.java @@ -46,4 +46,10 @@ public interface EncryptionKey extends Comparable { * @return the list of columns */ EncryptionVariant[] getEncryptionRoots(); + + /** + * Is the key available to this user? + * @return true if the key is available + */ + boolean isAvailable(); } diff --git a/java/core/src/java/org/apache/orc/EncryptionVariant.java b/java/core/src/java/org/apache/orc/EncryptionVariant.java index e0e91d8a80..4eb2e8ba58 100644 --- a/java/core/src/java/org/apache/orc/EncryptionVariant.java +++ b/java/core/src/java/org/apache/orc/EncryptionVariant.java @@ -22,7 +22,14 @@ import java.security.Key; /** - * Information about a key used for column encryption in an ORC file. + * Information about a column encryption variant. + * + * Column encryption is done by encoding multiple variants of the same column. + * Each encrypted column ends up in two variants: + *
    + *
  • Encrypted original
  • + *
  • Unencrypted masked
  • + *
*/ public interface EncryptionVariant extends Comparable { @@ -35,7 +42,7 @@ public interface EncryptionVariant extends Comparable { EncryptionKey getKeyDescription(); /** - * Get the root column for this encryption. + * Get the root column for this variant. * @return the root column type */ TypeDescription getRoot(); diff --git a/java/core/src/java/org/apache/orc/FileMetadata.java b/java/core/src/java/org/apache/orc/FileMetadata.java index 643bc1793a..e055b6b2e0 100644 --- a/java/core/src/java/org/apache/orc/FileMetadata.java +++ b/java/core/src/java/org/apache/orc/FileMetadata.java @@ -24,6 +24,7 @@ * Cached file metadata. Right now, it caches everything; we don't have to store all the * protobuf structs actually, we could just store what we need, but that would require that * ORC stop depending on them too. Luckily, they shouldn't be very big. + * @deprecated Use {@link org.apache.orc.impl.OrcTail} instead */ public interface FileMetadata { boolean isOriginalFormat(); diff --git a/java/core/src/java/org/apache/orc/OrcFile.java b/java/core/src/java/org/apache/orc/OrcFile.java index 23c4d0f32a..9b517c77e7 100644 --- a/java/core/src/java/org/apache/orc/OrcFile.java +++ b/java/core/src/java/org/apache/orc/OrcFile.java @@ -1,4 +1,4 @@ -/** +/* * 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 @@ -38,6 +38,7 @@ import org.apache.orc.impl.ReaderImpl; import org.apache.orc.impl.WriterImpl; import org.apache.orc.impl.WriterInternal; +import org.apache.orc.impl.reader.ReaderEncryptionVariant; import org.apache.orc.impl.writer.WriterImplV2; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -332,6 +333,9 @@ public KeyProvider getKeyProvider() { return keyProvider; } + /** + * @deprecated Use {@link #orcTail(OrcTail)} instead. + */ public ReaderOptions fileMetadata(final FileMetadata metadata) { fileMetadata = metadata; return this; @@ -430,6 +434,7 @@ public static class WriterOptions implements Cloneable { private String encryption; private String masks; private KeyProvider provider; + private Map keyOverrides = new HashMap<>(); protected WriterOptions(Properties tableProperties, Configuration conf) { configuration = conf; @@ -727,7 +732,16 @@ public WriterOptions directEncodingColumns(String value) { /** * Encrypt a set of columns with a key. - * For readers without access to the key, they will read nulls. + * + * Format of the string is a key-list. + *
    + *
  • key-list = key (';' key-list)?
  • + *
  • key = key-name ':' field-list
  • + *
  • field-list = field-name ( ',' field-list )?
  • + *
  • field-name = number | field-part ('.' field-name)?
  • + *
  • field-part = quoted string | simple name
  • + *
+ * * @param value a key-list of which columns to encrypt * @return this */ @@ -738,6 +752,16 @@ public WriterOptions encrypt(String value) { /** * Set the masks for the unencrypted data. + * + * Format of the string is a mask-list. + *
    + *
  • mask-list = mask (';' mask-list)?
  • + *
  • mask = mask-name (',' parameter)* ':' field-list
  • + *
  • field-list = field-name ( ',' field-list )?
  • + *
  • field-name = number | field-part ('.' field-name)?
  • + *
  • field-part = quoted string | simple name
  • + *
+ * * @param value a list of the masks and column names * @return this */ @@ -747,9 +771,29 @@ public WriterOptions masks(String value) { } /** - * Set the key provider for - * @param provider - * @return + * For users that need to override the current version of a key, this + * method allows them to define the version & algorithm for a given key. + * + * This will mostly be used for ORC file merging where the writer has to + * use the same version of the key that the original files used. + * + * @param keyName the key name + * @param version the version of the key to use + * @param algorithm the algorithm for the given key version + * @return this + */ + public WriterOptions setKeyVersion(String keyName, int version, + EncryptionAlgorithm algorithm) { + HadoopShims.KeyMetadata meta = new HadoopShims.KeyMetadata(keyName, + version, algorithm); + keyOverrides.put(keyName, meta); + return this; + } + + /** + * Set the key provider for column encryption. + * @param provider the object that holds the master secrets + * @return this */ public WriterOptions setKeyProvider(KeyProvider provider) { this.provider = provider; @@ -871,6 +915,10 @@ public String getEncryption() { public String getMasks() { return masks; } + + public Map getKeyOverrides() { + return keyOverrides; + } } /** @@ -952,47 +1000,110 @@ static boolean understandFormat(Path path, Reader reader) { return true; } + private static boolean sameKeys(EncryptionKey[] first, + EncryptionKey[] next) { + if (first.length != next.length) { + return false; + } + for(int k = 0; k < first.length && k < next.length; ++k) { + if (!first[k].getKeyName().equals(next[k].getKeyName()) || + first[k].getKeyVersion() != next[k].getKeyVersion() || + first[k].getAlgorithm() != next[k].getAlgorithm()) { + return false; + } + } + return true; + } + + private static boolean sameMasks(DataMaskDescription[] first, + DataMaskDescription[] next) { + if (first.length != next.length) { + return false; + } + for(int k = 0; k < first.length && k < next.length; ++k) { + if (!first[k].getName().equals(next[k].getName())) { + return false; + } + String[] firstParam = first[k].getParameters(); + String[] nextParam = next[k].getParameters(); + if (firstParam.length != nextParam.length) { + return false; + } + for(int p=0; p < firstParam.length && p < nextParam.length; ++p) { + if (!firstParam[p].equals(nextParam[p])) { + return false; + } + } + TypeDescription[] firstRoots = first[k].getColumns(); + TypeDescription[] nextRoots = next[k].getColumns(); + if (firstRoots.length != nextRoots.length) { + return false; + } + for(int r=0; r < firstRoots.length && r < nextRoots.length; ++r) { + if (firstRoots[r].getId() != nextRoots[r].getId()) { + return false; + } + } + } + return true; + } + + private static boolean sameVariants(EncryptionVariant[] first, + EncryptionVariant[] next) { + if (first.length != next.length) { + return false; + } + for(int k = 0; k < first.length && k < next.length; ++k) { + if ((first[k].getKeyDescription() == null) != + (next[k].getKeyDescription() == null) || + !first[k].getKeyDescription().getKeyName().equals( + next[k].getKeyDescription().getKeyName()) || + first[k].getRoot().getId() != + next[k].getRoot().getId()) { + return false; + } + } + return true; + } + /** * Is the new reader compatible with the file that is being written? - * @param schema the writer schema - * @param fileVersion the writer fileVersion - * @param writerVersion the writer writerVersion - * @param rowIndexStride the row index stride - * @param compression the compression that was used + * @param firstReader the first reader that others must match * @param userMetadata the user metadata * @param path the new path name for warning messages * @param reader the new reader * @return is the reader compatible with the previous ones? */ - static boolean readerIsCompatible(TypeDescription schema, - Version fileVersion, - WriterVersion writerVersion, - int rowIndexStride, - CompressionKind compression, + static boolean readerIsCompatible(Reader firstReader, Map userMetadata, Path path, Reader reader) { // now we have to check compatibility + TypeDescription schema = firstReader.getSchema(); if (!reader.getSchema().equals(schema)) { LOG.info("Can't merge {} because of different schemas {} vs {}", path, reader.getSchema(), schema); return false; } + CompressionKind compression = firstReader.getCompressionKind(); if (reader.getCompressionKind() != compression) { LOG.info("Can't merge {} because of different compression {} vs {}", path, reader.getCompressionKind(), compression); return false; } + OrcFile.Version fileVersion = firstReader.getFileVersion(); if (reader.getFileVersion() != fileVersion) { LOG.info("Can't merge {} because of different file versions {} vs {}", path, reader.getFileVersion(), fileVersion); return false; } + OrcFile.WriterVersion writerVersion = firstReader.getWriterVersion(); if (reader.getWriterVersion() != writerVersion) { LOG.info("Can't merge {} because of different writer versions {} vs {}", path, reader.getFileVersion(), fileVersion); return false; } + int rowIndexStride = firstReader.getRowIndexStride(); if (reader.getRowIndexStride() != rowIndexStride) { LOG.info("Can't merge {} because of different row index strides {} vs {}", path, reader.getRowIndexStride(), rowIndexStride); @@ -1009,6 +1120,20 @@ static boolean readerIsCompatible(TypeDescription schema, } } } + if (!sameKeys(firstReader.getColumnEncryptionKeys(), + reader.getColumnEncryptionKeys())) { + LOG.info("Can't merge {} because it has different encryption keys", path); + return false; + } + if (!sameMasks(firstReader.getDataMasks(), reader.getDataMasks())) { + LOG.info("Can't merge {} because it has different encryption masks", path); + return false; + } + if (!sameVariants(firstReader.getEncryptionVariants(), + reader.getEncryptionVariants())) { + LOG.info("Can't merge {} because it has different encryption variants", path); + return false; + } return true; } @@ -1040,45 +1165,45 @@ public static List mergeFiles(Path outputPath, List inputFiles) throws IOException { Writer output = null; final Configuration conf = options.getConfiguration(); + KeyProvider keyProvider = options.getKeyProvider(); try { byte[] buffer = new byte[0]; - TypeDescription schema = null; - CompressionKind compression = null; - int bufferSize = 0; - Version fileVersion = null; - WriterVersion writerVersion = null; - int rowIndexStride = 0; + Reader firstFile = null; List result = new ArrayList<>(inputFiles.size()); Map userMetadata = new HashMap<>(); + int bufferSize = 0; for (Path input : inputFiles) { FileSystem fs = input.getFileSystem(conf); Reader reader = createReader(input, - readerOptions(options.getConfiguration()).filesystem(fs)); + readerOptions(options.getConfiguration()) + .filesystem(fs) + .setKeyProvider(keyProvider)); if (!understandFormat(input, reader)) { continue; - } else if (schema == null) { + } else if (firstFile == null) { // if this is the first file that we are including, grab the values - schema = reader.getSchema(); - compression = reader.getCompressionKind(); + firstFile = reader; bufferSize = reader.getCompressionSize(); - rowIndexStride = reader.getRowIndexStride(); - fileVersion = reader.getFileVersion(); - writerVersion = reader.getWriterVersion(); + CompressionKind compression = reader.getCompressionKind(); options.bufferSize(bufferSize) - .version(fileVersion) - .writerVersion(writerVersion) + .version(reader.getFileVersion()) + .writerVersion(reader.getWriterVersion()) .compress(compression) - .rowIndexStride(rowIndexStride) - .setSchema(schema); + .rowIndexStride(reader.getRowIndexStride()) + .setSchema(reader.getSchema()); if (compression != CompressionKind.NONE) { options.enforceBufferSize().bufferSize(bufferSize); } mergeMetadata(userMetadata, reader); + // ensure that the merged file uses the same key versions + for(EncryptionKey key: reader.getColumnEncryptionKeys()) { + options.setKeyVersion(key.getKeyName(), key.getKeyVersion(), + key.getAlgorithm()); + } output = createWriter(outputPath, options); - } else if (!readerIsCompatible(schema, fileVersion, writerVersion, - rowIndexStride, compression, userMetadata, input, reader)) { + } else if (!readerIsCompatible(firstFile, userMetadata, input, reader)) { continue; } else { mergeMetadata(userMetadata, reader); @@ -1087,10 +1212,14 @@ public static List mergeFiles(Path outputPath, ((WriterInternal) output).increaseCompressionSize(bufferSize); } } - List statList = - reader.getOrcProtoStripeStatistics(); - try (FSDataInputStream inputStream = fs.open(input)) { - int stripeNum = 0; + EncryptionVariant[] variants = reader.getEncryptionVariants(); + List[] completeList = new List[variants.length + 1]; + for(int v=0; v < variants.length; ++v) { + completeList[v] = reader.getVariantStripeStatistics(variants[v]); + } + completeList[completeList.length - 1] = reader.getVariantStripeStatistics(null); + StripeStatistics[] stripeStats = new StripeStatistics[completeList.length]; + try (FSDataInputStream inputStream = ((ReaderImpl) reader).takeFile()) { result.add(input); for (StripeInformation stripe : reader.getStripes()) { @@ -1100,7 +1229,11 @@ public static List mergeFiles(Path outputPath, } long offset = stripe.getOffset(); inputStream.readFully(offset, buffer, 0, length); - output.appendStripe(buffer, 0, length, stripe, statList.get(stripeNum++)); + int stripeId = (int) stripe.getStripeId(); + for(int v=0; v < completeList.length; ++v) { + stripeStats[v] = completeList[v].get(stripeId); + } + output.appendStripe(buffer, 0, length, stripe, stripeStats); } } } @@ -1111,22 +1244,22 @@ public static List mergeFiles(Path outputPath, output.close(); } return result; - } catch (IOException ioe) { + } catch (Throwable t) { if (output != null) { try { output.close(); - } catch (Throwable t) { + } catch (Throwable ignore) { // PASS } try { FileSystem fs = options.getFileSystem() == null ? outputPath.getFileSystem(conf) : options.getFileSystem(); fs.delete(outputPath, false); - } catch (Throwable t) { + } catch (Throwable ignore) { // PASS } } - throw ioe; + throw new IOException("Problem merging files into " + outputPath, t); } } } diff --git a/java/core/src/java/org/apache/orc/OrcUtils.java b/java/core/src/java/org/apache/orc/OrcUtils.java index 85a4b831ea..e6f10a0790 100644 --- a/java/core/src/java/org/apache/orc/OrcUtils.java +++ b/java/core/src/java/org/apache/orc/OrcUtils.java @@ -374,7 +374,7 @@ TypeDescription convertTypeFromProtobuf(List types, public static List convertProtoStripesToStripes( List stripes) { List result = new ArrayList<>(stripes.size()); - long previousStripeId = -1; + long previousStripeId = 0; byte[][] previousKeys = null; long stripeId = 0; for (OrcProto.StripeInformation stripeProto: stripes) { diff --git a/java/core/src/java/org/apache/orc/PhysicalWriter.java b/java/core/src/java/org/apache/orc/PhysicalWriter.java index 872d5dcde7..98985a3e1d 100644 --- a/java/core/src/java/org/apache/orc/PhysicalWriter.java +++ b/java/core/src/java/org/apache/orc/PhysicalWriter.java @@ -91,7 +91,6 @@ void finalizeStripe(OrcProto.StripeFooter.Builder footer, * Write a stripe or file statistics to the file. * @param name the name of the stream * @param statistics the statistics to write - * @throws IOException */ void writeStatistics(StreamName name, OrcProto.ColumnStatistics.Builder statistics diff --git a/java/core/src/java/org/apache/orc/Reader.java b/java/core/src/java/org/apache/orc/Reader.java index 5d026b17c0..4fbffdbf8d 100644 --- a/java/core/src/java/org/apache/orc/Reader.java +++ b/java/core/src/java/org/apache/orc/Reader.java @@ -1,4 +1,4 @@ -/** +/* * 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 @@ -47,7 +47,7 @@ public interface Reader extends Closeable { /** * Get the deserialized data size of the specified columns - * @param colNames + * @param colNames the list of column names * @return raw data size of columns */ long getRawDataSizeOfColumns(List colNames); @@ -163,10 +163,22 @@ public interface Reader extends Closeable { */ EncryptionVariant[] getEncryptionVariants(); + /** + * Get the stripe statistics for a given variant. The StripeStatistics will + * have 1 entry for each column in the variant. This enables the user to + * get the stripe statistics for each variant regardless of which keys are + * available. + * @param variant the encryption variant or null for unencrypted + * @return a list of stripe statistics (one per a stripe) + * @throws IOException if the required key is not available + */ + List getVariantStripeStatistics(EncryptionVariant variant + ) throws IOException; + /** * Options for creating a RecordReader. */ - public static class Options implements Cloneable { + class Options implements Cloneable { private boolean[] include; private long offset = 0; private long length = Long.MAX_VALUE; @@ -289,7 +301,7 @@ public Options forcePositionalEvolution(boolean value) { * Set boolean flag to determine if the comparision of field names in schema * evolution is case sensitive * @param value the flag for schema evolution is case sensitive or not. - * @return + * @return this */ public Options isSchemaEvolutionCaseAware(boolean value) { this.isSchemaEvolutionCaseAware = value; @@ -303,6 +315,7 @@ public Options includeAcidColumns(boolean includeAcidColumns) { this.includeAcidColumns = includeAcidColumns; return this; } + public boolean[] getInclude() { return include; } @@ -430,7 +443,6 @@ public boolean getTolerateMissingSchema() { /** * Create a RecordReader that reads everything with the default options. * @return a new RecordReader - * @throws IOException */ RecordReader rows() throws IOException; @@ -440,7 +452,6 @@ public boolean getTolerateMissingSchema() { * before the rows() method was introduced. * @param options the options to read with * @return a new RecordReader - * @throws IOException */ RecordReader rows(Options options) throws IOException; @@ -456,16 +467,27 @@ public boolean getTolerateMissingSchema() { /** * @return Stripe statistics, in original protobuf form. + * @deprecated Use {@link #getStripeStatistics()} instead. */ List getOrcProtoStripeStatistics(); /** - * @return Stripe statistics. + * Get the stripe statistics for all of the columns. + * @return a list of the statistics for each stripe in the file */ List getStripeStatistics() throws IOException; + /** + * Get the stripe statistics from the file. + * @param include null for all columns or an array where the required columns + * are selected + * @return a list of the statistics for each stripe in the file + */ + List getStripeStatistics(boolean[] include) throws IOException; + /** * @return File statistics, in original protobuf form. + * @deprecated Use {@link #getStatistics()} instead. */ List getOrcProtoFileStatistics(); diff --git a/java/core/src/java/org/apache/orc/StripeInformation.java b/java/core/src/java/org/apache/orc/StripeInformation.java index 6490d6bbe5..1493a3d610 100644 --- a/java/core/src/java/org/apache/orc/StripeInformation.java +++ b/java/core/src/java/org/apache/orc/StripeInformation.java @@ -63,10 +63,16 @@ public interface StripeInformation { */ long getStripeId(); + /** + * Does this stripe have an explicit encryption stripe id set? + * @return true if this stripe was the first stripe of a merge + */ + boolean hasEncryptionStripeId(); + /** * Get the original stripe id that was used when the stripe was originally * written. This is only different that getStripeId in merged files. - * @return the original stripe id + * @return the original stripe id + 1 */ long getEncryptionStripeId(); diff --git a/java/core/src/java/org/apache/orc/StripeStatistics.java b/java/core/src/java/org/apache/orc/StripeStatistics.java index d1738ff9e4..f2f26ad4e8 100644 --- a/java/core/src/java/org/apache/orc/StripeStatistics.java +++ b/java/core/src/java/org/apache/orc/StripeStatistics.java @@ -1,4 +1,4 @@ -/** +/* * 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 @@ -22,13 +22,27 @@ import java.util.List; +/** + * The statistics for a stripe. + */ public class StripeStatistics { - private final List cs; + protected final List cs; + protected final TypeDescription schema; public StripeStatistics(List list) { + this(null, list); + } + + public StripeStatistics(TypeDescription schema, + List list) { + this.schema = schema; this.cs = list; } + private int getBase() { + return schema == null ? 0 : schema.getId(); + } + /** * Return list of column statistics * @@ -36,9 +50,15 @@ public StripeStatistics(List list) { */ public ColumnStatistics[] getColumnStatistics() { ColumnStatistics[] result = new ColumnStatistics[cs.size()]; - for (int i = 0; i < result.length; ++i) { - result[i] = ColumnStatisticsImpl.deserialize(null, cs.get(i)); + int base = getBase(); + for (int c = 0; c < result.length; ++c) { + TypeDescription column = schema == null ? null : schema.findSubtype(base + c); + result[c] = ColumnStatisticsImpl.deserialize(column, cs.get(c)); } return result; } + + public OrcProto.ColumnStatistics getColumn(int column) { + return cs.get(column); + } } diff --git a/java/core/src/java/org/apache/orc/TypeDescription.java b/java/core/src/java/org/apache/orc/TypeDescription.java index f36b1341db..1533d33aff 100644 --- a/java/core/src/java/org/apache/orc/TypeDescription.java +++ b/java/core/src/java/org/apache/orc/TypeDescription.java @@ -32,6 +32,7 @@ import org.apache.hadoop.hive.ql.exec.vector.VectorizedRowBatch; import org.apache.orc.impl.ParserUtils; import org.apache.orc.impl.SchemaEvolution; +import org.apache.orc.impl.TypeUtils; import org.jetbrains.annotations.NotNull; import java.io.Serializable; @@ -464,61 +465,6 @@ public int getMaximumId() { return maxId; } - private ColumnVector createColumn(RowBatchVersion version, int maxSize) { - switch (category) { - case BOOLEAN: - case BYTE: - case SHORT: - case INT: - case LONG: - case DATE: - return new LongColumnVector(maxSize); - case TIMESTAMP: - case TIMESTAMP_INSTANT: - return new TimestampColumnVector(maxSize); - case FLOAT: - case DOUBLE: - return new DoubleColumnVector(maxSize); - case DECIMAL: - if (version == RowBatchVersion.ORIGINAL || - precision > MAX_DECIMAL64_PRECISION) { - return new DecimalColumnVector(maxSize, precision, scale); - } else { - return new Decimal64ColumnVector(maxSize, precision, scale); - } - case STRING: - case BINARY: - case CHAR: - case VARCHAR: - return new BytesColumnVector(maxSize); - case STRUCT: { - ColumnVector[] fieldVector = new ColumnVector[children.size()]; - for(int i=0; i < fieldVector.length; ++i) { - fieldVector[i] = children.get(i).createColumn(version, maxSize); - } - return new StructColumnVector(maxSize, - fieldVector); - } - case UNION: { - ColumnVector[] fieldVector = new ColumnVector[children.size()]; - for(int i=0; i < fieldVector.length; ++i) { - fieldVector[i] = children.get(i).createColumn(version, maxSize); - } - return new UnionColumnVector(maxSize, - fieldVector); - } - case LIST: - return new ListColumnVector(maxSize, - children.get(0).createColumn(version, maxSize)); - case MAP: - return new MapColumnVector(maxSize, - children.get(0).createColumn(version, maxSize), - children.get(1).createColumn(version, maxSize)); - default: - throw new IllegalArgumentException("Unknown type " + category); - } - } - /** * Specify the version of the VectorizedRowBatch that the user desires. */ @@ -532,11 +478,11 @@ public VectorizedRowBatch createRowBatch(RowBatchVersion version, int size) { if (category == Category.STRUCT) { result = new VectorizedRowBatch(children.size(), size); for(int i=0; i < result.cols.length; ++i) { - result.cols[i] = children.get(i).createColumn(version, size); + result.cols[i] = TypeUtils.createColumn(children.get(i), version, size); } } else { result = new VectorizedRowBatch(1, size); - result.cols[0] = createColumn(version, size); + result.cols[0] = TypeUtils.createColumn(this, version, size); } result.reset(); return result; diff --git a/java/core/src/java/org/apache/orc/Writer.java b/java/core/src/java/org/apache/orc/Writer.java index c0ab7e0687..d4749fae06 100644 --- a/java/core/src/java/org/apache/orc/Writer.java +++ b/java/core/src/java/org/apache/orc/Writer.java @@ -89,25 +89,45 @@ public interface Writer extends Closeable { * stripe in binary form along with stripe information and stripe statistics. * After appending last stripe of a file, use appendUserMetadata() to append * any user metadata. + * + * This form only supports files with no column encryption. Use {@link + * #appendStripe(byte[], int, int, StripeInformation, StripeStatistics[])} + * for files with encryption. + * * @param stripe - stripe as byte array * @param offset - offset within byte array * @param length - length of stripe within byte array * @param stripeInfo - stripe information - * @param stripeStatistics - stripe statistics (Protobuf objects can be - * merged directly) - * @throws IOException + * @param stripeStatistics - unencrypted stripe statistics */ - public void appendStripe(byte[] stripe, int offset, int length, + void appendStripe(byte[] stripe, int offset, int length, StripeInformation stripeInfo, OrcProto.StripeStatistics stripeStatistics) throws IOException; /** - * When fast stripe append is used for merging ORC stripes, after appending - * the last stripe from a file, this interface must be used to merge any - * user metadata. + * Fast stripe append to ORC file. This interface is used for fast ORC file + * merge with other ORC files. When merging, the file to be merged should pass + * stripe in binary form along with stripe information and stripe statistics. + * After appending last stripe of a file, use {@link #addUserMetadata(String, + * ByteBuffer)} to append any user metadata. + * @param stripe - stripe as byte array + * @param offset - offset within byte array + * @param length - length of stripe within byte array + * @param stripeInfo - stripe information + * @param stripeStatistics - stripe statistics with the last one being + * for the unencrypted data and the others being for + * each encryption variant. + */ + void appendStripe(byte[] stripe, int offset, int length, + StripeInformation stripeInfo, + StripeStatistics[] stripeStatistics) throws IOException; + + /** + * Update the current user metadata with a list of new values. * @param userMetadata - user metadata + * @deprecated use {@link #addUserMetadata(String, ByteBuffer)} instead */ - public void appendUserMetadata(List userMetadata); + void appendUserMetadata(List userMetadata); /** * Get the statistics about the columns in the file. The output of this is diff --git a/java/core/src/java/org/apache/orc/impl/OrcTail.java b/java/core/src/java/org/apache/orc/impl/OrcTail.java index 2765473486..409d8f3022 100644 --- a/java/core/src/java/org/apache/orc/impl/OrcTail.java +++ b/java/core/src/java/org/apache/orc/impl/OrcTail.java @@ -16,44 +16,79 @@ package org.apache.orc.impl; -import static org.apache.orc.impl.ReaderImpl.extractMetadata; - import java.io.IOException; import java.nio.ByteBuffer; -import java.util.ArrayList; import java.util.List; -import org.apache.orc.CompressionCodec; import org.apache.orc.CompressionKind; import org.apache.orc.OrcFile; import org.apache.orc.OrcProto; import org.apache.orc.OrcUtils; import org.apache.orc.StripeInformation; -import org.apache.orc.StripeStatistics; +import org.apache.orc.TypeDescription; // TODO: Make OrcTail implement FileMetadata or Reader interface public final class OrcTail { // postscript + footer - Serialized in OrcSplit private final OrcProto.FileTail fileTail; // serialized representation of metadata, footer and postscript - private final ByteBuffer serializedTail; + private final BufferChunk serializedTail; + private final TypeDescription schema; // used to invalidate cache entries private final long fileModificationTime; - // lazily deserialized - private OrcProto.Metadata metadata; - public OrcTail(OrcProto.FileTail fileTail, ByteBuffer serializedTail) { + public OrcTail(OrcProto.FileTail fileTail, + ByteBuffer serializedTail) throws IOException { this(fileTail, serializedTail, -1); } - public OrcTail(OrcProto.FileTail fileTail, ByteBuffer serializedTail, long fileModificationTime) { + public OrcTail(OrcProto.FileTail fileTail, ByteBuffer serializedTail, + long fileModificationTime) throws IOException { + this(fileTail, + new BufferChunk(serializedTail, getStripeStatisticsOffset(fileTail)), + fileModificationTime); + } + + public OrcTail(OrcProto.FileTail fileTail, BufferChunk serializedTail, + long fileModificationTime) throws IOException { this.fileTail = fileTail; this.serializedTail = serializedTail; this.fileModificationTime = fileModificationTime; - this.metadata = null; + List types = getTypes(); + OrcUtils.isValidTypeTree(types, 0); + this.schema = OrcUtils.convertTypeFromProtobuf(types, 0); } public ByteBuffer getSerializedTail() { + if (serializedTail.next == null) { + return serializedTail.getData(); + } else { + // make a single buffer... + int len = 0; + for(BufferChunk chunk=serializedTail; + chunk != null; + chunk = (BufferChunk) chunk.next) { + len += chunk.getLength(); + } + ByteBuffer result = ByteBuffer.allocate(len); + for(BufferChunk chunk=serializedTail; + chunk != null; + chunk = (BufferChunk) chunk.next) { + ByteBuffer tmp = chunk.getData(); + result.put(tmp.array(), tmp.arrayOffset() + tmp.position(), + tmp.remaining()); + } + result.flip(); + return result; + } + } + + /** + * Gets the buffer chunks that correspond to the stripe statistics, + * file tail, and post script. + * @return the shared buffers with the contents of the file tail + */ + public BufferChunk getTailBuffer() { return serializedTail; } @@ -89,29 +124,6 @@ public int getCompressionBufferSize() { return (int) fileTail.getPostscript().getCompressionBlockSize(); } - public List getStripeStatistics(InStream.StreamOptions options) throws IOException { - List result = new ArrayList<>(); - List ssProto = getStripeStatisticsProto(options); - if (ssProto != null) { - for (OrcProto.StripeStatistics ss : ssProto) { - result.add(new StripeStatistics(ss.getColStatsList())); - } - } - return result; - } - - public List getStripeStatisticsProto(InStream.StreamOptions options) throws IOException { - if (serializedTail == null) return null; - if (metadata == null) { - metadata = extractMetadata(serializedTail, 0, - (int) fileTail.getPostscript().getMetadataLength(), - options); - // clear does not clear the contents but sets position to 0 and limit = capacity - serializedTail.clear(); - } - return metadata.getStripeStatsList(); - } - public int getMetadataSize() { return (int) getPostScript().getMetadataLength(); } @@ -120,10 +132,52 @@ public List getTypes() { return getFooter().getTypesList(); } + public TypeDescription getSchema() { + return schema; + } + public OrcProto.FileTail getFileTail() { return fileTail; } + static long getMetadataOffset(OrcProto.FileTail tail) { + OrcProto.PostScript ps = tail.getPostscript(); + return tail.getFileLength() + - 1 + - tail.getPostscriptLength() + - ps.getFooterLength() + - ps.getMetadataLength(); + } + + static long getStripeStatisticsOffset(OrcProto.FileTail tail) { + OrcProto.PostScript ps = tail.getPostscript(); + return getMetadataOffset(tail) - ps.getStripeStatisticsLength(); + } + + /** + * Get the file offset of the metadata section of footer. + * @return the byte offset of the start of the metadata + */ + public long getMetadataOffset() { + return getMetadataOffset(fileTail); + } + + /** + * Get the file offset of the stripe statistics. + * @return the byte offset of the start of the stripe statistics + */ + public long getStripeStatisticsOffset() { + return getStripeStatisticsOffset(fileTail); + } + + /** + * Get the position of the end of the file. + * @return the byte length of the file + */ + public long getFileLength() { + return fileTail.getFileLength(); + } + public OrcProto.FileTail getMinimalFileTail() { OrcProto.FileTail.Builder fileTailBuilder = OrcProto.FileTail.newBuilder(fileTail); OrcProto.Footer.Builder footerBuilder = OrcProto.Footer.newBuilder(fileTail.getFooter()); diff --git a/java/core/src/java/org/apache/orc/impl/PhysicalFsWriter.java b/java/core/src/java/org/apache/orc/impl/PhysicalFsWriter.java index 4736a63052..71d616c6e5 100644 --- a/java/core/src/java/org/apache/orc/impl/PhysicalFsWriter.java +++ b/java/core/src/java/org/apache/orc/impl/PhysicalFsWriter.java @@ -45,7 +45,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; - public class PhysicalFsWriter implements PhysicalWriter { private static final Logger LOG = LoggerFactory.getLogger(PhysicalFsWriter.class); @@ -342,7 +341,7 @@ static void writeEncryptedStripeStatistics(DirectStream output, for(int col = tracker.rootColumn; col < tracker.rootColumn + tracker.stripeStats.length; ++col) { options.modifyIv(CryptoUtils.modifyIvForStream(col, - OrcProto.Stream.Kind.STRIPE_STATISTICS, stripeNumber)); + OrcProto.Stream.Kind.STRIPE_STATISTICS, stripeNumber + 1)); OutStream stream = new OutStream("stripe stats for " + col, options, output); OrcProto.ColumnarStripeStatistics stats = @@ -403,7 +402,7 @@ static void setEncryptionStatistics(OrcProto.Encryption.Builder encryption, } StreamOptions options = new StreamOptions(variant.options); options.modifyIv(CryptoUtils.modifyIvForStream(variant.rootColumn, - OrcProto.Stream.Kind.FILE_STATISTICS, stripeNumber)); + OrcProto.Stream.Kind.FILE_STATISTICS, stripeNumber + 1)); BufferedStream buffer = new BufferedStream(); OutStream stream = new OutStream("stats for " + variant, options, buffer); file.build().writeTo(stream); @@ -418,7 +417,8 @@ public void writeFileMetadata(OrcProto.Metadata.Builder builder) throws IOExcept for(VariantTracker variant: variants.values()) { writeEncryptedStripeStatistics(rawStream, stripeNumber, variant); } - setUnencryptedStripeStatistics(builder, stripeNumber, unencrypted.stripeStats); + setUnencryptedStripeStatistics(builder, stripeNumber, + unencrypted.stripeStats); long metadataStart = rawWriter.getPos(); builder.build().writeTo(codedCompressStream); codedCompressStream.flush(); @@ -439,7 +439,6 @@ public void writeFileFooter(OrcProto.Footer.Builder builder) throws IOException if (variants.size() > 0) { OrcProto.Encryption.Builder encryption = builder.getEncryptionBuilder(); setEncryptionStatistics(encryption, stripeNumber, variants.values()); - builder.setStripeStatisticsLength(stripeStatisticsLength); } addUnencryptedStatistics(builder, unencrypted.fileStats); long bodyLength = rawWriter.getPos() - metadataLength - stripeStatisticsLength; @@ -457,6 +456,9 @@ public void writeFileFooter(OrcProto.Footer.Builder builder) throws IOException public long writePostScript(OrcProto.PostScript.Builder builder) throws IOException { builder.setFooterLength(footerLength); builder.setMetadataLength(metadataLength); + if (variants.size() > 0) { + builder.setStripeStatisticsLength(stripeStatisticsLength); + } OrcProto.PostScript ps = builder.build(); // need to write this uncompressed long startPosn = rawWriter.getPos(); @@ -513,6 +515,7 @@ public void appendRawStripe(ByteBuffer buffer, rawWriter.write(buffer.array(), buffer.arrayOffset() + buffer.position(), length); dirEntry.setOffset(start); + stripeNumber += 1; } @@ -722,7 +725,7 @@ protected OutputStream createIndexStream(StreamName name) { if (options == tracker.options) { options = new StreamOptions(options); } - options.modifyIv(CryptoUtils.modifyIvForStream(name, stripeNumber)); + options.modifyIv(CryptoUtils.modifyIvForStream(name, stripeNumber + 1)); } return new OutStream(name.toString(), options, buffer); } diff --git a/java/core/src/java/org/apache/orc/impl/ReaderImpl.java b/java/core/src/java/org/apache/orc/impl/ReaderImpl.java index 5daef41016..10989a316d 100644 --- a/java/core/src/java/org/apache/orc/impl/ReaderImpl.java +++ b/java/core/src/java/org/apache/orc/impl/ReaderImpl.java @@ -22,16 +22,12 @@ import java.nio.ByteBuffer; import java.security.Key; import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; import java.util.List; -import java.util.Set; import org.apache.orc.EncryptionAlgorithm; import org.apache.orc.EncryptionKey; import org.apache.orc.CompressionKind; import org.apache.orc.DataMaskDescription; -import org.apache.orc.EncryptionKey; import org.apache.orc.EncryptionVariant; import org.apache.orc.FileMetadata; import org.apache.orc.OrcFile; @@ -66,17 +62,15 @@ public class ReaderImpl implements Reader { private static final int DIRECTORY_SIZE_GUESS = 16 * 1024; - protected FileSystem fileSystem; private final long maxLength; protected final Path path; protected final OrcFile.ReaderOptions options; - protected final org.apache.orc.CompressionKind compressionKind; + private final org.apache.orc.CompressionKind compressionKind; protected FSDataInputStream file; protected int bufferSize; - protected OrcProto.Metadata metadata; - private List stripeStats; + // the unencrypted stripe statistics or null if they haven't been read yet + protected List stripeStatistics; private final int metadataSize; - protected final List types; private TypeDescription schema; private final List userMetadata; private final List fileStats; @@ -91,7 +85,7 @@ public class ReaderImpl implements Reader { private final List versionList; private final OrcFile.WriterVersion writerVersion; - protected OrcTail tail; + protected final OrcTail tail; public static class StripeInformationImpl implements StripeInformation { @@ -156,6 +150,11 @@ public long getStripeId() { return stripeId; } + @Override + public boolean hasEncryptionStripeId() { + return stripe.hasEncryptStripeId(); + } + @Override public long getEncryptionStripeId() { return originalStripeId; @@ -168,9 +167,11 @@ public byte[][] getEncryptedLocalKeys() { @Override public String toString() { - return "offset: " + getOffset() + " data: " + getDataLength() + - " rows: " + getNumberOfRows() + " tail: " + getFooterLength() + - " index: " + getIndexLength(); + return "offset: " + getOffset() + " data: " + + getDataLength() + " rows: " + getNumberOfRows() + " tail: " + + getFooterLength() + " index: " + getIndexLength() + + (!hasEncryptionStripeId() || stripeId == originalStripeId - 1 + ? "" : " encryption id: " + originalStripeId); } } @@ -229,7 +230,7 @@ public long getContentLength() { @Override public List getTypes() { - return types; + return OrcUtils.getOrcTypes(schema); } public static OrcFile.Version getFileVersion(List versionList) { @@ -275,6 +276,33 @@ public ReaderEncryptionVariant[] getEncryptionVariants() { return encryption.getVariants(); } + @Override + public List getVariantStripeStatistics(EncryptionVariant variant) throws IOException { + if (variant == null) { + if (stripeStatistics == null) { + try (CompressionCodec codec = OrcCodecPool.getCodec(compressionKind)) { + InStream.StreamOptions options = new InStream.StreamOptions(); + if (codec != null) { + options.withCodec(codec).withBufferSize(bufferSize); + } + + // deserialize the unencrypted stripe statistics + stripeStatistics = deserializeStripeStats(tail.getTailBuffer(), + tail.getMetadataOffset(), tail.getMetadataSize(), options); + } + } + return convertFromProto(stripeStatistics); + } else { + try (CompressionCodec codec = OrcCodecPool.getCodec(compressionKind)) { + InStream.StreamOptions compression = new InStream.StreamOptions(); + if (codec != null) { + compression.withCodec(codec).withBufferSize(bufferSize); + } + return ((ReaderEncryptionVariant) variant).getStripeStatistics(null, compression); + } + } + } + /** * Internal access to our view of the encryption. * @return the encryption information for this reader. @@ -291,23 +319,26 @@ public int getRowIndexStride() { @Override public ColumnStatistics[] getStatistics() { ColumnStatistics[] result = deserializeStats(schema, fileStats); - try (CompressionCodec codec = OrcCodecPool.getCodec(compressionKind)) { - InStream.StreamOptions compression = InStream.options(); - if (codec != null) { - compression.withCodec(codec).withBufferSize(bufferSize); - } - for (ReaderEncryptionVariant variant : encryption.getVariants()) { - ColumnStatistics[] overrides; - try { - overrides = decryptFileStats(variant, compression, - tail.getFooter()); - } catch (IOException e) { - throw new RuntimeException("Can't decrypt file stats for " + path + - " with " + variant.getKeyDescription()); + if (encryption.getKeys().length > 0) { + try (CompressionCodec codec = OrcCodecPool.getCodec(compressionKind)) { + InStream.StreamOptions compression = InStream.options(); + if (codec != null) { + compression.withCodec(codec).withBufferSize(bufferSize); } - if (overrides != null) { - for (int i = 0; i < overrides.length; ++i) { - result[variant.getRoot().getId() + i] = overrides[i]; + for (int c = schema.getId(); c <= schema.getMaximumId(); ++c) { + ReaderEncryptionVariant variant = encryption.getVariant(c); + if (variant != null) { + try { + int base = variant.getRoot().getId(); + ColumnStatistics[] overrides = decryptFileStats(variant, + compression, tail.getFooter()); + for(int sub=0; sub < overrides.length; ++sub) { + result[base + sub] = overrides[sub]; + } + } catch (IOException e) { + throw new RuntimeException("Can't decrypt file stats for " + path + + " with " + variant.getKeyDescription()); + } } } } @@ -315,7 +346,7 @@ public ColumnStatistics[] getStatistics() { return result; } - public static ColumnStatistics[] decryptFileStats(ReaderEncryptionVariant encryption, + private static ColumnStatistics[] decryptFileStats(ReaderEncryptionVariant encryption, InStream.StreamOptions compression, OrcProto.Footer footer ) throws IOException { @@ -330,7 +361,7 @@ public static ColumnStatistics[] decryptFileStats(ReaderEncryptionVariant encryp EncryptionAlgorithm algorithm = encryption.getKeyDescription().getAlgorithm(); byte[] iv = new byte[algorithm.getIvLength()]; CryptoUtils.modifyIvForStream(encryption.getRoot().getId(), - OrcProto.Stream.Kind.FILE_STATISTICS, footer.getStripesCount()) + OrcProto.Stream.Kind.FILE_STATISTICS, footer.getStripesCount() + 1) .accept(iv); InStream.StreamOptions options = new InStream.StreamOptions(compression) .withEncryption(algorithm, key, iv); @@ -445,24 +476,24 @@ public ReaderImpl(Path path, OrcFile.ReaderOptions options) throws IOException { this.compressionKind = fileMetadata.getCompressionKind(); this.bufferSize = fileMetadata.getCompressionBufferSize(); this.metadataSize = fileMetadata.getMetadataSize(); - this.stripeStats = fileMetadata.getStripeStats(); + this.stripeStatistics = fileMetadata.getStripeStats(); this.versionList = fileMetadata.getVersionList(); OrcFile.WriterImplementation writer = OrcFile.WriterImplementation.from(fileMetadata.getWriterImplementation()); this.writerVersion = OrcFile.WriterVersion.from(writer, fileMetadata.getWriterVersionNum()); - this.types = fileMetadata.getTypes(); - OrcUtils.isValidTypeTree(this.types, 0); - this.schema = OrcUtils.convertTypeFromProtobuf(this.types, 0); + List types = fileMetadata.getTypes(); + OrcUtils.isValidTypeTree(types, 0); + this.schema = OrcUtils.convertTypeFromProtobuf(types, 0); this.rowIndexStride = fileMetadata.getRowIndexStride(); this.contentLength = fileMetadata.getContentLength(); this.numberOfRows = fileMetadata.getNumberOfRows(); this.fileStats = fileMetadata.getFileStats(); this.stripes = fileMetadata.getStripes(); + this.tail = null; this.userMetadata = null; // not cached and not needed here // FileMetadata is obsolete and doesn't support encryption - this.encryption = new ReaderEncryption(null, schema, stripes, - options.getKeyProvider(), conf); + this.encryption = new ReaderEncryption(); } else { OrcTail orcTail = options.getOrcTail(); if (orcTail == null) { @@ -476,9 +507,7 @@ public ReaderImpl(Path path, OrcFile.ReaderOptions options) throws IOException { this.bufferSize = tail.getCompressionBufferSize(); this.metadataSize = tail.getMetadataSize(); this.versionList = tail.getPostScript().getVersionList(); - this.types = tail.getFooter().getTypesList(); - OrcUtils.isValidTypeTree(this.types, 0); - this.schema = OrcUtils.convertTypeFromProtobuf(this.types, 0); + this.schema = tail.getSchema(); this.rowIndexStride = tail.getFooter().getRowIndexStride(); this.contentLength = tail.getFooter().getContentLength(); this.numberOfRows = tail.getFooter().getNumberOfRows(); @@ -486,23 +515,19 @@ public ReaderImpl(Path path, OrcFile.ReaderOptions options) throws IOException { this.fileStats = tail.getFooter().getStatisticsList(); this.writerVersion = tail.getWriterVersion(); this.stripes = tail.getStripes(); - try (CompressionCodec codec = OrcCodecPool.getCodec(compressionKind)) { - InStream.StreamOptions compress = InStream.options().withCodec(codec) - .withBufferSize(bufferSize); - this.stripeStats = tail.getStripeStatisticsProto(compress); - } + this.stripeStatistics = null; this.encryption = new ReaderEncryption(tail.getFooter(), schema, - stripes, options.getKeyProvider(), conf); + tail.getStripeStatisticsOffset(), tail.getTailBuffer(), stripes, options.getKeyProvider(), conf); } } protected FileSystem getFileSystem() throws IOException { - this.fileSystem = options.getFilesystem(); - if (this.fileSystem == null) { - this.fileSystem = path.getFileSystem(options.getConfiguration()); + FileSystem fileSystem = options.getFilesystem(); + if (fileSystem == null) { + fileSystem = path.getFileSystem(options.getConfiguration()); options.filesystem(fileSystem); } - return this.fileSystem; + return fileSystem; } /** @@ -535,12 +560,13 @@ public static OrcProto.Metadata extractMetadata(ByteBuffer bb, int metadataAbsPo InStream.create("metadata", new BufferChunk(bb, 0), 0, metadataSize, options))); } - private static OrcProto.PostScript extractPostScript(ByteBuffer bb, Path path, - int psLen, int psAbsOffset) throws IOException { - // TODO: when PB is upgraded to 2.6, newInstance(ByteBuffer) method should be used here. - assert bb.hasArray(); - CodedInputStream in = CodedInputStream.newInstance( - bb.array(), bb.arrayOffset() + psAbsOffset, psLen); + private static OrcProto.PostScript extractPostScript(BufferChunk buffer, + Path path, + int psLen, + long psOffset + ) throws IOException { + CodedInputStream in = InStream.createCodedInputStream( + InStream.create("ps", buffer, psOffset, psLen)); OrcProto.PostScript ps = OrcProto.PostScript.parseFrom(in); checkOrcVersion(path, ps); @@ -562,7 +588,7 @@ private static OrcProto.PostScript extractPostScript(ByteBuffer bb, Path path, * Build a virtual OrcTail for empty files. * @return a new OrcTail */ - OrcTail buildEmptyTail() { + OrcTail buildEmptyTail() throws IOException { OrcProto.PostScript.Builder postscript = OrcProto.PostScript.newBuilder(); OrcFile.Version version = OrcFile.Version.CURRENT; postscript.setMagic(OrcFile.MAGIC) @@ -589,12 +615,25 @@ OrcTail buildEmptyTail() { result.setPostscript(postscript); result.setFileLength(0); result.setPostscriptLength(0); - return new OrcTail(result.build(), null); + return new OrcTail(result.build(), new BufferChunk(0, 0), -1); + } + + private static void read(FSDataInputStream file, + BufferChunk chunks) throws IOException { + while (chunks != null) { + if (!chunks.hasData()) { + int len = chunks.getLength(); + ByteBuffer bb = ByteBuffer.allocate(len); + file.readFully(chunks.getOffset(), bb.array(), bb.arrayOffset(), len); + chunks.setChunk(bb); + } + chunks = (BufferChunk) chunks.next; + } } protected OrcTail extractFileTail(FileSystem fs, Path path, long maxFileLength) throws IOException { - ByteBuffer buffer; + BufferChunk buffer; OrcProto.PostScript ps; OrcProto.FileTail.Builder fileTailBuilder = OrcProto.FileTail.newBuilder(); long modificationTime; @@ -624,58 +663,49 @@ protected OrcTail extractFileTail(FileSystem fs, Path path, //read last bytes into buffer to get PostScript int readSize = (int) Math.min(size, DIRECTORY_SIZE_GUESS); - buffer = ByteBuffer.allocate(readSize); - assert buffer.position() == 0; - file.readFully((size - readSize), - buffer.array(), buffer.arrayOffset(), readSize); - buffer.position(0); + buffer = new BufferChunk(size - readSize, readSize); + read(file, buffer); //read the PostScript //get length of PostScript - int psLen = buffer.get(readSize - 1) & 0xff; - ensureOrcFooter(file, path, psLen, buffer); - int psOffset = readSize - 1 - psLen; + ByteBuffer bb = buffer.getData(); + int psLen = bb.get(readSize - 1) & 0xff; + ensureOrcFooter(file, path, psLen, bb); + long psOffset = size - 1 - psLen; ps = extractPostScript(buffer, path, psLen, psOffset); - bufferSize = (int) ps.getCompressionBlockSize(); - CompressionKind compressionKind = CompressionKind.valueOf(ps.getCompression().name()); + CompressionKind compressionKind = + CompressionKind.valueOf(ps.getCompression().name()); fileTailBuilder.setPostscriptLength(psLen).setPostscript(ps); int footerSize = (int) ps.getFooterLength(); int metadataSize = (int) ps.getMetadataLength(); + int stripeStatSize = (int) ps.getStripeStatisticsLength(); //check if extra bytes need to be read - int extra = Math.max(0, psLen + 1 + footerSize + metadataSize - readSize); - int tailSize = 1 + psLen + footerSize + metadataSize; + int tailSize = 1 + psLen + footerSize + metadataSize + stripeStatSize; + int extra = Math.max(0, tailSize - readSize); if (extra > 0) { //more bytes need to be read, seek back to the right place and read extra bytes - ByteBuffer extraBuf = ByteBuffer.allocate(extra + readSize); - file.readFully((size - readSize - extra), extraBuf.array(), - extraBuf.arrayOffset() + extraBuf.position(), extra); - extraBuf.position(extra); - //append with already read bytes - extraBuf.put(buffer); - buffer = extraBuf; - buffer.position(0); - buffer.limit(tailSize); - readSize += extra; - psOffset = readSize - 1 - psLen; - } else { - //footer is already in the bytes in buffer, just adjust position, length - buffer.position(psOffset - footerSize - metadataSize); - buffer.limit(buffer.position() + tailSize); + BufferChunk orig = buffer; + buffer = new BufferChunk(size - tailSize, extra); + buffer.next = orig; + orig.prev = buffer; + read(file, buffer); } - buffer.mark(); - int footerOffset = psOffset - footerSize; - buffer.position(footerOffset); - ByteBuffer footerBuffer = buffer.slice(); - buffer.reset(); - OrcProto.Footer footer; - try (CompressionCodec codec = OrcCodecPool.getCodec(compressionKind)){ - footer = extractFooter(footerBuffer, 0, footerSize, - InStream.options().withCodec(codec).withBufferSize(bufferSize)); + InStream.StreamOptions compression = new InStream.StreamOptions(); + try (CompressionCodec codec = OrcCodecPool.getCodec(compressionKind)) { + if (codec != null) { + compression.withCodec(codec) + .withBufferSize((int) ps.getCompressionBlockSize()); + } + OrcProto.Footer footer = + OrcProto.Footer.parseFrom( + InStream.createCodedInputStream( + InStream.create("footer", buffer, psOffset - footerSize, + footerSize, compression))); + fileTailBuilder.setFooter(footer); } - fileTailBuilder.setFooter(footer); } catch (Throwable thr) { try { close(); @@ -686,10 +716,7 @@ protected OrcTail extractFileTail(FileSystem fs, Path path, new IOException("Problem reading file footer " + path, thr); } - ByteBuffer serializedTail = ByteBuffer.allocate(buffer.remaining()); - serializedTail.put(buffer.slice()); - serializedTail.rewind(); - return new OrcTail(fileTailBuilder.build(), serializedTail, modificationTime); + return new OrcTail(fileTailBuilder.build(), buffer, modificationTime); } @Override @@ -730,26 +757,34 @@ public long getRawDataSize() { @Override public long getRawDataSizeFromColIndices(List colIndices) { - return getRawDataSizeFromColIndices(colIndices, types, fileStats); + boolean[] include = new boolean[schema.getMaximumId() + 1]; + for(Integer rootId: colIndices) { + TypeDescription root = schema.findSubtype(rootId); + for(int c = root.getId(); c <= root.getMaximumId(); ++c) { + include[c] = true; + } + } + return getRawDataSizeFromColIndices(include, schema, fileStats); } - public static long getRawDataSizeFromColIndices( - List colIndices, List types, - List stats) { + static long getRawDataSizeFromColIndices(boolean[] include, + TypeDescription schema, + List stats) { long result = 0; - for (int colIdx : colIndices) { - result += getRawDataSizeOfColumn(colIdx, types, stats); + for (int c = schema.getId(); c <= schema.getMaximumId(); ++c) { + if (include[c]) { + result += getRawDataSizeOfColumn(schema.findSubtype(c), stats); + } } return result; } - private static long getRawDataSizeOfColumn(int colIdx, List types, + private static long getRawDataSizeOfColumn(TypeDescription column, List stats) { - OrcProto.ColumnStatistics colStat = stats.get(colIdx); + OrcProto.ColumnStatistics colStat = stats.get(column.getId()); long numVals = colStat.getNumberOfValues(); - OrcProto.Type type = types.get(colIdx); - switch (type.getKind()) { + switch (column.getCategory()) { case BINARY: // old orc format doesn't support binary statistics. checking for binary // statistics is not required as protocol buffers takes care of it. @@ -766,6 +801,7 @@ private static long getRawDataSizeOfColumn(int colIdx, List types int avgStrLen = (int) (colStat.getStringStatistics().getSum() / numVals); return numVals * JavaDataModel.get().lengthForStringOfLength(avgStrLen); case TIMESTAMP: + case TIMESTAMP_INSTANT: return numVals * JavaDataModel.get().lengthOfTimestamp(); case DATE: return numVals * JavaDataModel.get().lengthOfDate(); @@ -779,9 +815,13 @@ private static long getRawDataSizeOfColumn(int colIdx, List types case SHORT: case BOOLEAN: case BYTE: + case STRUCT: + case UNION: + case MAP: + case LIST: return numVals * JavaDataModel.get().primitive1(); default: - LOG.debug("Unknown primitive category: " + type.getKind()); + LOG.debug("Unknown primitive category: " + column.getCategory()); break; } @@ -790,71 +830,31 @@ private static long getRawDataSizeOfColumn(int colIdx, List types @Override public long getRawDataSizeOfColumns(List colNames) { - List colIndices = getColumnIndicesFromNames(colNames); - return getRawDataSizeFromColIndices(colIndices); - } - - private List getColumnIndicesFromNames(List colNames) { - // top level struct - OrcProto.Type type = types.get(0); - List colIndices = new ArrayList<>(); - List fieldNames = type.getFieldNamesList(); - int fieldIdx; - for (String colName : colNames) { - if (fieldNames.contains(colName)) { - fieldIdx = fieldNames.indexOf(colName); - } else { - StringBuilder s = new StringBuilder("Cannot find field for: "); - s.append(colName); - s.append(" in "); - for (String fn : fieldNames) { - s.append(fn); - s.append(", "); - } - LOG.warn(s.toString()); - continue; - } - - // a single field may span multiple columns. find start and end column - // index for the requested field - int idxStart = type.getSubtypes(fieldIdx); - - int idxEnd; - - // if the specified is the last field and then end index will be last - // column index - if (fieldIdx + 1 > fieldNames.size() - 1) { - idxEnd = getLastIdx() + 1; - } else { - idxEnd = type.getSubtypes(fieldIdx + 1); - } - - // if start index and end index are same then the field is a primitive - // field else complex field (like map, list, struct, union) - if (idxStart == idxEnd) { - // simple field - colIndices.add(idxStart); - } else { - // complex fields spans multiple columns - for (int i = idxStart; i < idxEnd; i++) { - colIndices.add(i); - } + boolean[] include = new boolean[schema.getMaximumId() + 1]; + for(String name: colNames) { + TypeDescription sub = schema.findSubtype(name); + for(int c = sub.getId(); c <= sub.getMaximumId(); ++c) { + include[c] = true; } } - return colIndices; - } - - private int getLastIdx() { - Set indices = new HashSet<>(); - for (OrcProto.Type type : types) { - indices.addAll(type.getSubtypesList()); - } - return Collections.max(indices); + return getRawDataSizeFromColIndices(include, schema, fileStats); } @Override public List getOrcProtoStripeStatistics() { - return stripeStats; + if (stripeStatistics == null) { + try (CompressionCodec codec = OrcCodecPool.getCodec(compressionKind)) { + InStream.StreamOptions options = new InStream.StreamOptions(); + if (codec != null) { + options.withCodec(codec).withBufferSize(bufferSize); + } + stripeStatistics = deserializeStripeStats(tail.getTailBuffer(), + tail.getMetadataOffset(), tail.getMetadataSize(), options); + } catch (IOException ioe) { + throw new RuntimeException("Can't deserialize stripe stats", ioe); + } + } + return stripeStatistics; } @Override @@ -862,21 +862,74 @@ public List getOrcProtoFileStatistics() { return fileStats; } + private static + List deserializeStripeStats(BufferChunk tailBuffer, + long offset, + int length, + InStream.StreamOptions options + ) throws IOException { + InStream stream = InStream.create("stripe stats", tailBuffer, offset, + length, options); + OrcProto.Metadata meta = OrcProto.Metadata.parseFrom( + InStream.createCodedInputStream(stream)); + return meta.getStripeStatsList(); + } + + private List convertFromProto(List list) { + if (list == null) { + return null; + } else { + List result = new ArrayList<>(list.size()); + for (OrcProto.StripeStatistics ss : stripeStatistics) { + result.add(new StripeStatisticsImpl(schema, + new ArrayList<>(ss.getColStatsList()))); + } + return result; + } + } + @Override public List getStripeStatistics() throws IOException { - if (metadata == null) { + return getStripeStatistics(null); + } + + @Override + public List getStripeStatistics(boolean[] included) throws IOException { + List result = convertFromProto(stripeStatistics); + if (result == null || encryption.getVariants().length > 0) { try (CompressionCodec codec = OrcCodecPool.getCodec(compressionKind)) { - metadata = extractMetadata(tail.getSerializedTail(), 0, metadataSize, - InStream.options().withCodec(codec).withBufferSize(bufferSize)); + InStream.StreamOptions options = new InStream.StreamOptions(); + if (codec != null) { + options.withCodec(codec).withBufferSize(bufferSize); + } + + result = getVariantStripeStatistics(null); + + if (encryption.getVariants().length > 0) { + // process any encrypted overrides that we have the key for + for (int c = schema.getId(); c <= schema.getMaximumId(); ++c) { + // only decrypt the variants that we need + if (included == null || included[c]) { + ReaderEncryptionVariant variant = encryption.getVariant(c); + if (variant != null) { + TypeDescription variantType = variant.getRoot(); + List colStats = + variant.getStripeStatistics(included, options); + for(int sub = c; sub <= variantType.getMaximumId(); ++sub) { + if (included == null || included[sub]) { + for(int s = 0; s < colStats.size(); ++s) { + StripeStatisticsImpl resultElem = (StripeStatisticsImpl) result.get(s); + resultElem.updateColumn(sub, colStats.get(s).getColumn(sub - variantType.getId())); + } + } + } + c = variantType.getMaximumId(); + } + } + } + } } } - if (stripeStats == null) { - stripeStats = metadata.getStripeStatsList(); - } - List result = new ArrayList<>(); - for (OrcProto.StripeStatistics ss : stripeStats) { - result.add(new StripeStatistics(ss.getColStatsList())); - } return result; } @@ -916,7 +969,7 @@ public void close() throws IOException { * RecordReaders will open new handles. * @return a file handle, if one is available */ - FSDataInputStream takeFile() { + public FSDataInputStream takeFile() { FSDataInputStream result = file; file = null; return result; diff --git a/java/core/src/java/org/apache/orc/impl/RecordReaderImpl.java b/java/core/src/java/org/apache/orc/impl/RecordReaderImpl.java index de5957955a..72c741890f 100644 --- a/java/core/src/java/org/apache/orc/impl/RecordReaderImpl.java +++ b/java/core/src/java/org/apache/orc/impl/RecordReaderImpl.java @@ -32,6 +32,7 @@ import org.apache.orc.CollectionColumnStatistics; import org.apache.orc.ColumnStatistics; import org.apache.orc.CompressionCodec; +import org.apache.orc.CompressionKind; import org.apache.orc.DataReader; import org.apache.orc.DateColumnStatistics; import org.apache.orc.DecimalColumnStatistics; @@ -158,10 +159,6 @@ protected RecordReaderImpl(ReaderImpl fileReader, } this.schema = evolution.getReaderSchema(); this.path = fileReader.path; - List types = fileReader.types; - InStream.StreamOptions unencryptedOptions = InStream.options() - .withCodec(OrcCodecPool.getCodec(fileReader.getCompressionKind())) - .withBufferSize(fileReader.getCompressionSize()); this.rowIndexStride = fileReader.rowIndexStride; boolean ignoreNonUtf8BloomFilter = OrcConf.IGNORE_NON_UTF8_BLOOM_FILTERS.getBoolean(fileReader.conf); ReaderEncryption encryption = fileReader.getEncryption(); @@ -198,6 +195,10 @@ protected RecordReaderImpl(ReaderImpl fileReader, if (options.getDataReader() != null) { this.dataReader = options.getDataReader().clone(); } else { + InStream.StreamOptions unencryptedOptions = + InStream.options() + .withCodec(OrcCodecPool.getCodec(fileReader.getCompressionKind())) + .withBufferSize(fileReader.getCompressionSize()); DataReaderProperties.Builder builder = DataReaderProperties.builder() .withCompression(unencryptedOptions) @@ -229,13 +230,14 @@ protected RecordReaderImpl(ReaderImpl fileReader, reader = TreeReaderFactory.createTreeReader(evolution.getReaderSchema(), readerContext); - indexes = new OrcIndex(new OrcProto.RowIndex[types.size()], - new OrcProto.Stream.Kind[types.size()], - new OrcProto.BloomFilterIndex[types.size()]); + int columns = schema.getMaximumId() + 1; + indexes = new OrcIndex(new OrcProto.RowIndex[columns], + new OrcProto.Stream.Kind[columns], + new OrcProto.BloomFilterIndex[columns]); planner = new StripePlanner(evolution.getFileSchema(), encryption, - unencryptedOptions, dataReader, writerVersion, - ignoreNonUtf8BloomFilter, maxDiskRangeChunkLimit); + dataReader, writerVersion, ignoreNonUtf8BloomFilter, + maxDiskRangeChunkLimit); try { advanceToNextRow(reader, 0L, true); @@ -1318,7 +1320,7 @@ public static int[] mapTranslatedSargColumns( } public CompressionCodec getCompressionCodec() { - return dataReader.getCompressionCodec(); + return dataReader.getCompressionOptions().getCodec(); } public int getMaxDiskRangeChunkLimit() { diff --git a/java/core/src/java/org/apache/orc/impl/RecordReaderUtils.java b/java/core/src/java/org/apache/orc/impl/RecordReaderUtils.java index 7ed62ef524..159b63efcb 100644 --- a/java/core/src/java/org/apache/orc/impl/RecordReaderUtils.java +++ b/java/core/src/java/org/apache/orc/impl/RecordReaderUtils.java @@ -150,8 +150,8 @@ public DataReader clone() { } @Override - public CompressionCodec getCompressionCodec() { - return options.getCodec(); + public InStream.StreamOptions getCompressionOptions() { + return options; } } @@ -174,7 +174,8 @@ static boolean overlap(long leftA, long rightA, long leftB, long rightB) { return rightB >= leftA; } - public static long estimateRgEndOffset(InStream.StreamOptions unencryptedOptions, + public static long estimateRgEndOffset(boolean isCompressed, + int bufferSize, boolean isLast, long nextGroupOffset, long streamLength) { @@ -182,8 +183,8 @@ public static long estimateRgEndOffset(InStream.StreamOptions unencryptedOptions // if adjacent groups have the same compressed block offset then stretch the slop // by factor of 2 to safely accommodate the next compression block. // One for the current compression block and another for the next compression block. - long slop = unencryptedOptions.isCompressed() - ? 2 * (OutStream.HEADER_SIZE + unencryptedOptions.getBufferSize()) + long slop = isCompressed + ? 2 * (OutStream.HEADER_SIZE + bufferSize) : WORST_UNCOMPRESSED_SLOP; return isLast ? streamLength : Math.min(streamLength, nextGroupOffset + slop); } @@ -247,6 +248,7 @@ public static int getIndexPosition(OrcProto.ColumnEncoding.Kind columnEncoding, } return base + BYTE_STREAM_POSITIONS + compressionValue; case TIMESTAMP: + case TIMESTAMP_INSTANT: if (streamType == OrcProto.Stream.Kind.DATA) { return base; } diff --git a/java/core/src/java/org/apache/orc/impl/StripeStatisticsImpl.java b/java/core/src/java/org/apache/orc/impl/StripeStatisticsImpl.java new file mode 100644 index 0000000000..f4a83cdfbd --- /dev/null +++ b/java/core/src/java/org/apache/orc/impl/StripeStatisticsImpl.java @@ -0,0 +1,55 @@ +/* + * 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.orc.impl; + +import org.apache.orc.OrcProto; +import org.apache.orc.StripeStatistics; +import org.apache.orc.TypeDescription; + +import java.util.ArrayList; +import java.util.List; + +public class StripeStatisticsImpl extends StripeStatistics { + public StripeStatisticsImpl(TypeDescription schema, + List list) { + super(schema, list); + } + + public StripeStatisticsImpl(TypeDescription schema) { + super(schema, createList(schema)); + } + + /** + * Create a list that will be filled in later. + * @param schema the schema for this stripe statistics + * @return a new list of nulls for each column + */ + private static List createList(TypeDescription schema) { + int len = schema.getMaximumId() - schema.getId() + 1; + List result = new ArrayList<>(len); + for(int c=0; c < len; ++c) { + result.add(null); + } + return result; + } + + public void updateColumn(int column, OrcProto.ColumnStatistics elem) { + cs.set(column, elem); + } +} diff --git a/java/core/src/java/org/apache/orc/impl/TypeUtils.java b/java/core/src/java/org/apache/orc/impl/TypeUtils.java new file mode 100644 index 0000000000..32d58ef157 --- /dev/null +++ b/java/core/src/java/org/apache/orc/impl/TypeUtils.java @@ -0,0 +1,105 @@ +/* + * 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.orc.impl; + +import org.apache.hadoop.hive.ql.exec.vector.BytesColumnVector; +import org.apache.hadoop.hive.ql.exec.vector.ColumnVector; +import org.apache.hadoop.hive.ql.exec.vector.Decimal64ColumnVector; +import org.apache.hadoop.hive.ql.exec.vector.DecimalColumnVector; +import org.apache.hadoop.hive.ql.exec.vector.DoubleColumnVector; +import org.apache.hadoop.hive.ql.exec.vector.ListColumnVector; +import org.apache.hadoop.hive.ql.exec.vector.LongColumnVector; +import org.apache.hadoop.hive.ql.exec.vector.MapColumnVector; +import org.apache.hadoop.hive.ql.exec.vector.StructColumnVector; +import org.apache.hadoop.hive.ql.exec.vector.TimestampColumnVector; +import org.apache.hadoop.hive.ql.exec.vector.UnionColumnVector; +import org.apache.orc.TypeDescription; + +import java.util.List; + +public class TypeUtils { + private TypeUtils() {} + + public static ColumnVector createColumn(TypeDescription schema, + TypeDescription.RowBatchVersion version, + int maxSize) { + switch (schema.getCategory()) { + case BOOLEAN: + case BYTE: + case SHORT: + case INT: + case LONG: + case DATE: + return new LongColumnVector(maxSize); + case TIMESTAMP: + case TIMESTAMP_INSTANT: + return new TimestampColumnVector(maxSize); + case FLOAT: + case DOUBLE: + return new DoubleColumnVector(maxSize); + case DECIMAL: { + int precision = schema.getPrecision(); + int scale = schema.getScale(); + if (version == TypeDescription.RowBatchVersion.ORIGINAL || + precision > TypeDescription.MAX_DECIMAL64_PRECISION) { + return new DecimalColumnVector(maxSize, precision, scale); + } else { + return new Decimal64ColumnVector(maxSize, precision, scale); + } + } + case STRING: + case BINARY: + case CHAR: + case VARCHAR: + return new BytesColumnVector(maxSize); + case STRUCT: { + List children = schema.getChildren(); + ColumnVector[] fieldVector = new ColumnVector[children.size()]; + for(int i=0; i < fieldVector.length; ++i) { + fieldVector[i] = createColumn(children.get(i), version, maxSize); + } + return new StructColumnVector(maxSize, + fieldVector); + } + case UNION: { + List children = schema.getChildren(); + ColumnVector[] fieldVector = new ColumnVector[children.size()]; + for(int i=0; i < fieldVector.length; ++i) { + fieldVector[i] = createColumn(children.get(i), version, maxSize); + } + return new UnionColumnVector(maxSize, + fieldVector); + } + case LIST: { + List children = schema.getChildren(); + return new ListColumnVector(maxSize, + createColumn(children.get(0), version, maxSize)); + } + case MAP: { + List children = schema.getChildren(); + return new MapColumnVector(maxSize, + createColumn(children.get(0), version, maxSize), + createColumn(children.get(1), version, maxSize)); + } + default: + throw new IllegalArgumentException("Unknown type " + schema.getCategory()); + } + } + +} diff --git a/java/core/src/java/org/apache/orc/impl/WriterImpl.java b/java/core/src/java/org/apache/orc/impl/WriterImpl.java index e556470375..a4b5b368c9 100644 --- a/java/core/src/java/org/apache/orc/impl/WriterImpl.java +++ b/java/core/src/java/org/apache/orc/impl/WriterImpl.java @@ -43,6 +43,7 @@ import org.apache.orc.OrcUtils; import org.apache.orc.PhysicalWriter; import org.apache.orc.StripeInformation; +import org.apache.orc.StripeStatistics; import org.apache.orc.TypeDescription; import org.apache.orc.impl.writer.WriterEncryptionKey; import org.apache.orc.impl.writer.WriterEncryptionVariant; @@ -80,7 +81,6 @@ public class WriterImpl implements WriterInternal, MemoryManager.Callback { private static final Logger LOG = LoggerFactory.getLogger(WriterImpl.class); - private static final HadoopShims SHIMS = HadoopShimsFactory.get(); private static final int MIN_ROW_INDEX_STRIDE = 1000; @@ -137,6 +137,8 @@ public class WriterImpl implements WriterInternal, MemoryManager.Callback { public WriterImpl(FileSystem fs, Path path, OrcFile.WriterOptions opts) throws IOException { + this.path = path; + this.conf = opts.getConfiguration(); // clone it so that we can annotate it with encryption this.schema = opts.getSchema().clone(); int numColumns = schema.getMaximumId() + 1; @@ -148,15 +150,10 @@ public WriterImpl(FileSystem fs, // Annotate the schema with the column encryption schema.annotateEncryption(opts.getEncryption(), opts.getMasks()); columnEncryption = new WriterEncryptionVariant[numColumns]; - if (opts.getEncryption() == null) { - columnMaskDescriptions = null; - encryption = new WriterEncryptionVariant[0]; - needKeyFlush = false; - } else { - columnMaskDescriptions = new MaskDescriptionImpl[numColumns]; - encryption = setupEncryption(opts.getKeyProvider(), schema); - needKeyFlush = true; - } + columnMaskDescriptions = new MaskDescriptionImpl[numColumns]; + encryption = setupEncryption(opts.getKeyProvider(), schema, + opts.getKeyOverrides()); + needKeyFlush = encryption.length > 0; // Set up the physical writer this.physicalWriter = opts.getPhysicalWriter() == null ? @@ -165,8 +162,6 @@ public WriterImpl(FileSystem fs, unencryptedOptions = physicalWriter.getStreamOptions(); OutStream.assertBufferSizeValid(unencryptedOptions.getBufferSize()); - this.path = path; - this.conf = opts.getConfiguration(); this.callback = opts.getCallback(); this.writerVersion = opts.getWriterVersion(); bloomFilterVersion = opts.getBloomFilterVersion(); @@ -421,10 +416,14 @@ public WriterEncryptionVariant getEncryption(int columnId) { @Override public DataMask getUnencryptedMask(int columnId) { - MaskDescriptionImpl descr = columnMaskDescriptions[columnId]; - return descr == null ? null : - DataMask.Factory.build(descr, schema.findSubtype(columnId), - (type) -> columnMaskDescriptions[type.getId()]); + if (columnMaskDescriptions != null) { + MaskDescriptionImpl descr = columnMaskDescriptions[columnId]; + if (descr != null) { + return DataMask.Factory.build(descr, schema.findSubtype(columnId), + (type) -> columnMaskDescriptions[type.getId()]); + } + } + return null; } @Override @@ -646,31 +645,44 @@ public void addUserMetadata(String name, ByteBuffer value) { @Override public void addRowBatch(VectorizedRowBatch batch) throws IOException { - // If this is the first set of rows in this stripe, tell the tree writers - // to prepare the stripe. - if (batch.size != 0 && rowsInStripe == 0) { - treeWriter.prepareStripe(stripes.size() + 1); - } - if (buildIndex) { - // Batch the writes up to the rowIndexStride so that we can get the - // right size indexes. - int posn = 0; - while (posn < batch.size) { - int chunkSize = Math.min(batch.size - posn, - rowIndexStride - rowsInIndex); - treeWriter.writeRootBatch(batch, posn, chunkSize); - posn += chunkSize; - rowsInIndex += chunkSize; - rowsInStripe += chunkSize; - if (rowsInIndex >= rowIndexStride) { - createRowIndexEntry(); + try { + // If this is the first set of rows in this stripe, tell the tree writers + // to prepare the stripe. + if (batch.size != 0 && rowsInStripe == 0) { + treeWriter.prepareStripe(stripes.size() + 1); + } + if (buildIndex) { + // Batch the writes up to the rowIndexStride so that we can get the + // right size indexes. + int posn = 0; + while (posn < batch.size) { + int chunkSize = Math.min(batch.size - posn, + rowIndexStride - rowsInIndex); + treeWriter.writeRootBatch(batch, posn, chunkSize); + posn += chunkSize; + rowsInIndex += chunkSize; + rowsInStripe += chunkSize; + if (rowsInIndex >= rowIndexStride) { + createRowIndexEntry(); + } } + } else { + rowsInStripe += batch.size; + treeWriter.writeRootBatch(batch, 0, batch.size); + } + memoryManager.addedRow(batch.size); + } catch (Throwable t) { + try { + close(); + } catch (Throwable ignore) { + // ignore + } + if (t instanceof IOException) { + throw (IOException) t; + } else { + throw new IOException("Problem adding row to " + path, t); } - } else { - rowsInStripe += batch.size; - treeWriter.writeRootBatch(batch, 0, batch.size); } - memoryManager.addedRow(batch.size); } @Override @@ -720,7 +732,7 @@ public long writeIntermediateFooter() throws IOException { return lastFlushOffset; } - static void checkArgument(boolean expression, String message) { + private static void checkArgument(boolean expression, String message) { if (!expression) { throw new IllegalArgumentException(message); } @@ -728,8 +740,19 @@ static void checkArgument(boolean expression, String message) { @Override public void appendStripe(byte[] stripe, int offset, int length, - StripeInformation stripeInfo, - OrcProto.StripeStatistics stripeStatistics) throws IOException { + StripeInformation stripeInfo, + OrcProto.StripeStatistics stripeStatistics + ) throws IOException { + appendStripe(stripe, offset, length, stripeInfo, + new StripeStatistics[]{ + new StripeStatisticsImpl(schema, stripeStatistics.getColStatsList())}); + } + + @Override + public void appendStripe(byte[] stripe, int offset, int length, + StripeInformation stripeInfo, + StripeStatistics[] stripeStatistics + ) throws IOException { checkArgument(stripe != null, "Stripe must not be null"); checkArgument(length <= stripe.length, "Specified length must not be greater specified array length"); @@ -744,16 +767,24 @@ public void appendStripe(byte[] stripe, int offset, int length, rowsInStripe = stripeInfo.getNumberOfRows(); // update stripe information OrcProto.StripeInformation.Builder dirEntry = OrcProto.StripeInformation - .newBuilder() - .setNumberOfRows(rowsInStripe) - .setIndexLength(stripeInfo.getIndexLength()) - .setDataLength(stripeInfo.getDataLength()) - .setFooterLength(stripeInfo.getFooterLength()); + .newBuilder() + .setNumberOfRows(rowsInStripe) + .setIndexLength(stripeInfo.getIndexLength()) + .setDataLength(stripeInfo.getDataLength()) + .setFooterLength(stripeInfo.getFooterLength()); + // If this is the first stripe of the original file, we need to copy the + // encryption information. + if (stripeInfo.hasEncryptionStripeId()) { + dirEntry.setEncryptStripeId(stripeInfo.getEncryptionStripeId()); + for(byte[] key: stripeInfo.getEncryptedLocalKeys()) { + dirEntry.addEncryptedLocalKeys(ByteString.copyFrom(key)); + } + } physicalWriter.appendRawStripe(ByteBuffer.wrap(stripe, offset, length), dirEntry); // since we have already written the stripe, just update stripe statistics - treeWriter.updateFileStatistics(stripeStatistics); + treeWriter.addStripeStatistics(stripeStatistics); stripes.add(dirEntry.build()); @@ -801,8 +832,8 @@ private static boolean hasTimestamp(TypeDescription schema) { return false; } - WriterEncryptionKey getKey(String keyName, - KeyProvider provider) throws IOException { + private WriterEncryptionKey getKey(String keyName, + KeyProvider provider) throws IOException { WriterEncryptionKey result = keys.get(keyName); if (result == null) { result = new WriterEncryptionKey(provider.getCurrentKeyVersion(keyName)); @@ -811,9 +842,9 @@ WriterEncryptionKey getKey(String keyName, return result; } - MaskDescriptionImpl getMask(String maskString) { - MaskDescriptionImpl result = maskDescriptions.get(maskString); + private MaskDescriptionImpl getMask(String maskString) { // if it is already there, get the earlier object + MaskDescriptionImpl result = maskDescriptions.get(maskString); if (result == null) { result = ParserUtils.buildMaskDescription(maskString); maskDescriptions.put(maskString, result); @@ -821,13 +852,16 @@ MaskDescriptionImpl getMask(String maskString) { return result; } - int visitTypeTree(TypeDescription schema, - boolean encrypted, - KeyProvider provider) throws IOException { + private int visitTypeTree(TypeDescription schema, + boolean encrypted, + KeyProvider provider) throws IOException { int result = 0; String keyName = schema.getAttributeValue(TypeDescription.ENCRYPT_ATTRIBUTE); String maskName = schema.getAttributeValue(TypeDescription.MASK_ATTRIBUTE); if (keyName != null) { + if (provider == null) { + throw new IllegalArgumentException("Encryption requires a KeyProvider."); + } if (encrypted) { throw new IllegalArgumentException("Nested encryption type: " + schema); } @@ -836,7 +870,7 @@ int visitTypeTree(TypeDescription schema, WriterEncryptionKey key = getKey(keyName, provider); HadoopShims.KeyMetadata metadata = key.getMetadata(); WriterEncryptionVariant variant = new WriterEncryptionVariant(key, - schema, keyProvider.createLocalKey(metadata)); + schema, provider.createLocalKey(metadata)); key.addRoot(variant); } if (encrypted && (keyName != null || maskName != null)) { @@ -856,24 +890,29 @@ int visitTypeTree(TypeDescription schema, * Iterate through the encryption options given by the user and set up * our data structures. * @param provider the KeyProvider to use to generate keys - * @param schema the a + * @param schema the type tree that we search for annotations + * @param keyOverrides user specified key overrides */ - WriterEncryptionVariant[] setupEncryption(KeyProvider provider, - TypeDescription schema - ) throws IOException { + private WriterEncryptionVariant[] setupEncryption(KeyProvider provider, + TypeDescription schema, + Map keyOverrides + ) throws IOException { keyProvider = provider != null ? provider : CryptoUtils.getKeyProvider(conf, new SecureRandom()); - if (keyProvider == null) { - throw new IllegalArgumentException("Encryption requires a KeyProvider."); + // Load the overrides into the cache so that we use the required key versions. + for(HadoopShims.KeyMetadata key: keyOverrides.values()) { + keys.put(key.getKeyName(), new WriterEncryptionKey(key)); } - int variantCount = visitTypeTree(schema, false, provider); + int variantCount = visitTypeTree(schema, false, keyProvider); // Now that we have de-duped the keys and maskDescriptions, make the arrays int nextId = 0; - for (MaskDescriptionImpl mask: maskDescriptions.values()) { - mask.setId(nextId++); - for(TypeDescription column: mask.getColumns()) { - this.columnMaskDescriptions[column.getId()] = mask; + if (variantCount > 0) { + for (MaskDescriptionImpl mask : maskDescriptions.values()) { + mask.setId(nextId++); + for (TypeDescription column : mask.getColumns()) { + this.columnMaskDescriptions[column.getId()] = mask; + } } } nextId = 0; diff --git a/java/core/src/java/org/apache/orc/impl/mask/SHA256MaskFactory.java b/java/core/src/java/org/apache/orc/impl/mask/SHA256MaskFactory.java index b3445f98f3..d6e7378205 100644 --- a/java/core/src/java/org/apache/orc/impl/mask/SHA256MaskFactory.java +++ b/java/core/src/java/org/apache/orc/impl/mask/SHA256MaskFactory.java @@ -84,21 +84,18 @@ public class SHA256MaskFactory extends MaskFactory { */ void maskString(final BytesColumnVector source, final int row, final BytesColumnVector target, final TypeDescription schema) { - final ByteBuffer sourceBytes = ByteBuffer - .wrap(source.vector[row], source.start[row], source.length[row]); // take SHA-256 Hash and convert to HEX - byte[] hash = DatatypeConverter - .printHexBinary(md.digest(sourceBytes.array())) - .getBytes(StandardCharsets.UTF_8); + md.update(source.vector[row], source.start[row], source.length[row]); + byte[] hash = DatatypeConverter.printHexBinary(md.digest()) + .getBytes(StandardCharsets.UTF_8); int targetLength = hash.length; switch (schema.getCategory()) { - /* For type varchar */ case VARCHAR: { /* truncate the hash if max length for varchar is less than hash length * on the other hand if if the max length is more than hash length (64 - * bytes) we use the hash length (64 bytes) always. + * bytes) we use the hash length (64 bytes) always. */ if (schema.getMaxLength() < hash.length) { targetLength = schema.getMaxLength(); @@ -109,28 +106,22 @@ void maskString(final BytesColumnVector source, final int row, case CHAR: { /* for char the length is always constant */ targetLength = schema.getMaxLength(); + /* pad the hash with blank char if targetlength is greater than hash */ + if (targetLength > hash.length) { + byte[] tmp = new byte[targetLength]; + System.arraycopy(hash, 0, tmp, 0, hash.length); + Arrays.fill(tmp, hash.length, tmp.length - 1, (byte) ' '); + hash = tmp; + } break; } default: { - targetLength = hash.length; break; } } - byte[] result; - - /* pad the hash with blank char if targetlength is greater than hash */ - if (targetLength > hash.length) { - result = new byte[targetLength]; - System.arraycopy(hash, 0, result, 0, hash.length); - Arrays.fill(result, hash.length, targetLength - 1, (byte) ' '); - } else { - result = new byte[targetLength]; - System.arraycopy(hash, 0, result, 0, targetLength); - } - - target.vector[row] = result; + target.vector[row] = hash; target.start[row] = 0; target.length[row] = targetLength; } diff --git a/java/core/src/java/org/apache/orc/impl/reader/ReaderEncryption.java b/java/core/src/java/org/apache/orc/impl/reader/ReaderEncryption.java index fdf7e1ceb6..ad7a969b83 100644 --- a/java/core/src/java/org/apache/orc/impl/reader/ReaderEncryption.java +++ b/java/core/src/java/org/apache/orc/impl/reader/ReaderEncryption.java @@ -22,6 +22,7 @@ import org.apache.orc.OrcProto; import org.apache.orc.StripeInformation; import org.apache.orc.TypeDescription; +import org.apache.orc.impl.BufferChunk; import org.apache.orc.impl.CryptoUtils; import org.apache.orc.impl.KeyProvider; import org.apache.orc.impl.MaskDescriptionImpl; @@ -49,6 +50,8 @@ public ReaderEncryption() { public ReaderEncryption(OrcProto.Footer footer, TypeDescription schema, + long stripeStatisticsOffset, + BufferChunk serializedTail, List stripes, KeyProvider provider, Configuration conf) throws IOException { @@ -71,17 +74,20 @@ public ReaderEncryption(OrcProto.Footer footer, keys[k] = new ReaderEncryptionKey(encrypt.getKey(k)); } variants = new ReaderEncryptionVariant[encrypt.getVariantsCount()]; + long offset = stripeStatisticsOffset; for(int v=0; v < variants.length; ++v) { OrcProto.EncryptionVariant variant = encrypt.getVariants(v); variants[v] = new ReaderEncryptionVariant(keys[variant.getKey()], v, - variant, schema, stripes, keyProvider); + variant, schema, stripes, offset, serializedTail, keyProvider); + offset += variants[v].getStripeStatisticsLength(); } columnVariants = new ReaderEncryptionVariant[schema.getMaximumId() + 1]; - for(int v = 0; v < variants.length; ++v) { - TypeDescription root = variants[v].getRoot(); - for(int c = root.getId(); c <= root.getMaximumId(); ++c) { + for (ReaderEncryptionVariant variant : variants) { + TypeDescription root = variant.getRoot(); + for (int c = root.getId(); c <= root.getMaximumId(); ++c) { + // set the variant if it is the first one that we've found if (columnVariants[c] == null) { - columnVariants[c] = variants[v]; + columnVariants[c] = variant; } } } @@ -104,7 +110,7 @@ public ReaderEncryptionVariant[] getVariants() { * Find the next possible variant in this file for the given column. * @param column the column to find a variant for * @param lastVariant the previous variant that we looked at - * @return the next variant or null if there are none + * @return the next variant or null if there isn't one */ private ReaderEncryptionVariant findNextVariant(int column, int lastVariant) { @@ -123,26 +129,20 @@ private ReaderEncryptionVariant findNextVariant(int column, * to see if the KeyProvider will give it to us. If not, continue to the * next variant. * @param column the column id - * @return null for no encryption or the encryption variant + * @return the encryption variant or null if there isn't one */ - public ReaderEncryptionVariant getVariant(int column) throws IOException { - if (keyProvider != null) { - while (columnVariants[column] != null) { - ReaderEncryptionVariant result = columnVariants[column]; - switch (result.getKeyDescription().getState()) { - case FAILURE: - break; - case SUCCESS: - return result; - case UNTRIED: - // try to get the footer key, to see if we have access - if (result.getFileFooterKey() != null) { - return result; - } + public ReaderEncryptionVariant getVariant(int column) { + if (columnVariants == null) { + return null; + } else { + while (columnVariants[column] != null && + !columnVariants[column].getKeyDescription().isAvailable()) { + if (keyProvider != null) { + columnVariants[column] = + findNextVariant(column, columnVariants[column].getVariantId()); } - columnVariants[column] = findNextVariant(column, result.getVariantId()); } + return columnVariants[column]; } - return null; } } diff --git a/java/core/src/java/org/apache/orc/impl/reader/ReaderEncryptionKey.java b/java/core/src/java/org/apache/orc/impl/reader/ReaderEncryptionKey.java index 407bebb36a..ee39afc7d1 100644 --- a/java/core/src/java/org/apache/orc/impl/reader/ReaderEncryptionKey.java +++ b/java/core/src/java/org/apache/orc/impl/reader/ReaderEncryptionKey.java @@ -24,6 +24,7 @@ import org.apache.orc.impl.HadoopShims; import org.jetbrains.annotations.NotNull; +import java.io.IOException; import java.util.ArrayList; import java.util.List; @@ -89,7 +90,7 @@ public void setFailure() { state = State.FAILURE; } - public void setSucess() { + public void setSuccess() { if (state == State.FAILURE) { throw new IllegalStateException("Key " + name + " had already failed."); } @@ -129,4 +130,20 @@ public int compareTo(@NotNull EncryptionKey other) { public String toString() { return name + "@" + version + " w/ " + algorithm; } + + @Override + public boolean isAvailable() { + if (getState() == ReaderEncryptionKey.State.SUCCESS) { + return true; + } else if (getState() == ReaderEncryptionKey.State.UNTRIED && + roots.size() > 0) { + // Check to see if we can decrypt the footer key of the first variant. + try { + return roots.get(0).getFileFooterKey() != null; + } catch (IOException ioe) { + setFailure(); + } + } + return false; + } } diff --git a/java/core/src/java/org/apache/orc/impl/reader/ReaderEncryptionVariant.java b/java/core/src/java/org/apache/orc/impl/reader/ReaderEncryptionVariant.java index c20bd8ef38..182de63bf2 100644 --- a/java/core/src/java/org/apache/orc/impl/reader/ReaderEncryptionVariant.java +++ b/java/core/src/java/org/apache/orc/impl/reader/ReaderEncryptionVariant.java @@ -20,18 +20,25 @@ import org.apache.hadoop.io.BytesWritable; import org.apache.orc.EncryptionAlgorithm; +import org.apache.orc.EncryptionKey; import org.apache.orc.EncryptionVariant; import org.apache.orc.OrcProto; import org.apache.orc.StripeInformation; +import org.apache.orc.StripeStatistics; import org.apache.orc.TypeDescription; +import org.apache.orc.impl.CryptoUtils; +import org.apache.orc.impl.InStream; import org.apache.orc.impl.KeyProvider; +import org.apache.orc.impl.BufferChunk; import org.apache.orc.impl.LocalKey; +import org.apache.orc.impl.StripeStatisticsImpl; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.security.Key; +import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -46,8 +53,12 @@ public class ReaderEncryptionVariant implements EncryptionVariant { private final ReaderEncryptionKey key; private final TypeDescription column; private final int variantId; + private final BufferChunk tailBuffer; + private final List stripeStats; private final LocalKey[] localKeys; private final LocalKey footerKey; + private final int stripeCount; + private final long stripeStatsOffset; /** * Create a reader's view of an encryption variant. @@ -56,32 +67,43 @@ public class ReaderEncryptionVariant implements EncryptionVariant { * @param proto the serialized description of the variant * @param schema the file schema * @param stripes the stripe information + * @param stripeStatsOffset the offset of the stripe statistics + * @param tailBuffer the serialized file tail * @param provider the key provider */ - public ReaderEncryptionVariant(ReaderEncryptionKey key, - int variantId, - OrcProto.EncryptionVariant proto, - TypeDescription schema, - List stripes, - KeyProvider provider) { + ReaderEncryptionVariant(ReaderEncryptionKey key, + int variantId, + OrcProto.EncryptionVariant proto, + TypeDescription schema, + List stripes, + long stripeStatsOffset, + BufferChunk tailBuffer, + KeyProvider provider) { this.key = key; this.variantId = variantId; this.provider = provider; - this.column = proto.hasRoot() ? schema.findSubtype(proto.getRoot()) : null; + this.column = proto == null || !proto.hasRoot() ? schema : + schema.findSubtype(proto.getRoot()); this.localKeys = new LocalKey[stripes.size()]; HashMap cache = new HashMap<>(); - for(int s=0; s < localKeys.length; ++s) { - StripeInformation stripe = stripes.get(s); - localKeys[s] = getCachedKey(cache, key.getAlgorithm(), - stripe.getEncryptedLocalKeys()[variantId]); - } - if (proto.hasEncryptedKey()) { + stripeCount = stripes.size(); + this.stripeStatsOffset = stripeStatsOffset; + if (proto != null && proto.hasEncryptedKey()) { + for (int s = 0; s < localKeys.length; ++s) { + StripeInformation stripe = stripes.get(s); + localKeys[s] = getCachedKey(cache, key.getAlgorithm(), + stripe.getEncryptedLocalKeys()[variantId]); + } footerKey = getCachedKey(cache, key.getAlgorithm(), proto.getEncryptedKey().toByteArray()); + key.addVariant(this); + stripeStats = proto.getStripeStatisticsList(); + this.tailBuffer = tailBuffer; } else { footerKey = null; + stripeStats = null; + this.tailBuffer = null; } - key.addVariant(this); } @Override @@ -131,7 +153,7 @@ private Key getDecryptedKey(LocalKey localKey) throws IOException { } if (result != null) { localKey.setDecryptedKey(result); - key.setSucess(); + key.setSuccess(); } else { key.setFailure(); } @@ -153,12 +175,12 @@ private Key getDecryptedKey(LocalKey localKey) throws IOException { @Override public Key getFileFooterKey() throws IOException { - return getDecryptedKey(footerKey); + return key == null ? null : getDecryptedKey(footerKey); } @Override public Key getStripeKey(long stripe) throws IOException { - return getDecryptedKey(localKeys[(int) stripe]); + return key == null ? null : getDecryptedKey(localKeys[(int) stripe]); } @Override @@ -179,12 +201,69 @@ public int hashCode() { public int compareTo(@NotNull EncryptionVariant other) { if (other == this) { return 0; - } else if (key == other.getKeyDescription()) { + } + EncryptionKey otherKey = other.getKeyDescription(); + if (key == otherKey) { return Integer.compare(column.getId(), other.getRoot().getId()); } else if (key == null) { return -1; + } else if (otherKey == null) { + return 1; } else { return key.compareTo(other.getKeyDescription()); } } + + public long getStripeStatisticsLength() { + long result = 0; + for(OrcProto.Stream stream: stripeStats) { + result += stream.getLength(); + } + return result; + } + + /** + * Decrypt the raw data and return the list of the stripe statistics for this + * variant. + * @param columns true for the columns that should be included + * @param compression the compression options + * @return the stripe statistics for this variant. + */ + public List getStripeStatistics(boolean[] columns, + InStream.StreamOptions compression + ) throws IOException { + StripeStatisticsImpl[] result = new StripeStatisticsImpl[stripeCount]; + for(int s=0; s < result.length; ++s) { + result[s] = new StripeStatisticsImpl(column); + } + // create the objects + long offset = stripeStatsOffset; + Key fileKey = getFileFooterKey(); + if (fileKey == null) { + throw new IOException("Can't get file footer key for " + key.getKeyName()); + } + int root = column.getId(); + for(OrcProto.Stream stream: stripeStats){ + long length = stream.getLength(); + int column = stream.getColumn(); + OrcProto.Stream.Kind kind = stream.getKind(); + if (kind == OrcProto.Stream.Kind.STRIPE_STATISTICS && + (columns == null || columns[column])) { + byte[] iv = new byte[key.getAlgorithm().getIvLength()]; + CryptoUtils.modifyIvForStream(column, kind, stripeCount + 1).accept(iv); + InStream.StreamOptions options = new InStream.StreamOptions(compression) + .withEncryption(key.getAlgorithm(), fileKey, iv); + OrcProto.ColumnarStripeStatistics stat = + OrcProto.ColumnarStripeStatistics.parseFrom( + InStream.createCodedInputStream( + InStream.create(stream, tailBuffer, offset, + length, options))); + for(int s=0; s < result.length; ++s) { + result[s].updateColumn(column - root, stat.getColStats(s)); + } + } + offset += length; + } + return Arrays.asList(result); + } } diff --git a/java/core/src/java/org/apache/orc/impl/reader/StripePlanner.java b/java/core/src/java/org/apache/orc/impl/reader/StripePlanner.java index b25654f0aa..41a30e618b 100644 --- a/java/core/src/java/org/apache/orc/impl/reader/StripePlanner.java +++ b/java/core/src/java/org/apache/orc/impl/reader/StripePlanner.java @@ -61,7 +61,6 @@ public class StripePlanner { private final OrcProto.ColumnEncoding[] encodings; private final ReaderEncryption encryption; private final DataReader dataReader; - private final InStream.StreamOptions compression; private final boolean ignoreNonUtf8BloomFilter; private final long maxBufferSize; @@ -74,7 +73,6 @@ public class StripePlanner { private final List indexStreams = new ArrayList<>(); // the data streams sorted by offset private final List dataStreams = new ArrayList<>(); - private final boolean[] usedVariants; private final OrcProto.Stream.Kind[] bloomFilterKinds; // does each column have a null stream? private final boolean[] hasNull; @@ -83,7 +81,6 @@ public class StripePlanner { * Create a stripe parser. * @param schema the file schema * @param encryption the encryption information - * @param compression the options to handle the compression * @param dataReader the underlying data reader * @param version the file writer version * @param ignoreNonUtf8BloomFilter ignore old non-utf8 bloom filters @@ -91,7 +88,6 @@ public class StripePlanner { */ public StripePlanner(TypeDescription schema, ReaderEncryption encryption, - InStream.StreamOptions compression, DataReader dataReader, OrcFile.WriterVersion version, boolean ignoreNonUtf8BloomFilter, @@ -99,9 +95,7 @@ public StripePlanner(TypeDescription schema, this.schema = schema; this.version = version; encodings = new OrcProto.ColumnEncoding[schema.getMaximumId()+1]; - usedVariants = new boolean[encryption.getVariants().length]; this.encryption = encryption; - this.compression = compression; this.dataReader = dataReader; this.ignoreNonUtf8BloomFilter = ignoreNonUtf8BloomFilter; bloomFilterKinds = new OrcProto.Stream.Kind[schema.getMaximumId() + 1]; @@ -110,8 +104,8 @@ public StripePlanner(TypeDescription schema, } public StripePlanner(StripePlanner old) { - this(old.schema, old.encryption, old.compression, old.dataReader, - old.version, old.ignoreNonUtf8BloomFilter, old.maxBufferSize); + this(old.schema, old.encryption, old.dataReader, old.version, + old.ignoreNonUtf8BloomFilter, old.maxBufferSize); } /** @@ -173,8 +167,8 @@ public String getWriterTimezone() { public InStream getStream(StreamName name) throws IOException { StreamInformation stream = streams.get(name); return stream == null ? null - : InStream.create(name, stream.firstChunk, stream.offset, - stream.length, getStreamOptions(stream.column, stream.kind)); + : InStream.create(name, stream.firstChunk, stream.offset, stream.length, + getStreamOptions(stream.column, stream.kind)); } /** @@ -204,6 +198,7 @@ private InStream.StreamOptions getStreamOptions(int column, OrcProto.Stream.Kind kind ) throws IOException { ReaderEncryptionVariant variant = encryption.getVariant(column); + InStream.StreamOptions compression = dataReader.getCompressionOptions(); if (variant == null) { return compression; } else { @@ -221,14 +216,13 @@ public OrcProto.ColumnEncoding getEncoding(int column) { } private void buildEncodings(OrcProto.StripeFooter footer, - boolean[] columnInclude) throws IOException { + boolean[] columnInclude) { for(int c=0; c < encodings.length; ++c) { if (columnInclude == null || columnInclude[c]) { ReaderEncryptionVariant variant = encryption.getVariant(c); if (variant == null) { encodings[c] = footer.getColumns(c); } else { - usedVariants[variant.getVariantId()] = true; int subColumn = c - variant.getRoot().getId(); encodings[c] = footer.getEncryption(variant.getVariantId()) .getEncoding(subColumn); @@ -248,7 +242,7 @@ private void buildEncodings(OrcProto.StripeFooter footer, private long handleStream(long offset, boolean[] columnInclude, OrcProto.Stream stream, - ReaderEncryptionVariant variant) throws IOException { + ReaderEncryptionVariant variant) { int column = stream.getColumn(); if (stream.hasKind()) { OrcProto.Stream.Kind kind = stream.getKind(); @@ -454,8 +448,10 @@ private BufferChunkList planPartialDataReading(OrcIndex index, @NotNull boolean[] includedRowGroups) { BufferChunkList result = new BufferChunkList(); if (hasSomeRowGroups(includedRowGroups)) { + InStream.StreamOptions compression = dataReader.getCompressionOptions(); + boolean isCompressed = compression.getCodec() != null; + int bufferSize = compression.getBufferSize(); OrcProto.RowIndex[] rowIndex = index.getRowGroupIndex(); - boolean isCompressed = compression.isCompressed(); for (StreamInformation stream : dataStreams) { if (RecordReaderUtils.isDictionary(stream.kind, encodings[stream.column])) { addChunk(result, stream, stream.offset, stream.length); @@ -482,8 +478,8 @@ private BufferChunkList planPartialDataReading(OrcIndex index, end += stream.length; } else { long nextGroupOffset = ri.getEntry(endGroup + 1).getPositions(posn); - end += RecordReaderUtils.estimateRgEndOffset( - compression, false, nextGroupOffset, stream.length); + end += RecordReaderUtils.estimateRgEndOffset(isCompressed, + bufferSize, false, nextGroupOffset, stream.length); } if (alreadyRead < end) { addChunk(result, stream, start, end - start); diff --git a/java/core/src/java/org/apache/orc/impl/writer/EncryptionTreeWriter.java b/java/core/src/java/org/apache/orc/impl/writer/EncryptionTreeWriter.java index 981f75a9c5..fc8a94046c 100644 --- a/java/core/src/java/org/apache/orc/impl/writer/EncryptionTreeWriter.java +++ b/java/core/src/java/org/apache/orc/impl/writer/EncryptionTreeWriter.java @@ -23,7 +23,9 @@ import org.apache.orc.ColumnStatistics; import org.apache.orc.DataMask; import org.apache.orc.OrcProto; +import org.apache.orc.StripeStatistics; import org.apache.orc.TypeDescription; +import org.apache.orc.impl.TypeUtils; import java.io.IOException; @@ -37,14 +39,20 @@ public class EncryptionTreeWriter implements TreeWriter { private final TreeWriter[] childrenWriters; private final DataMask[] masks; // a column vector that we use to apply the masks - private final VectorizedRowBatch scratch; + private final ColumnVector scratch; + private final VectorizedRowBatch scratchBatch; EncryptionTreeWriter(TypeDescription schema, - WriterEncryptionVariant encryption, - WriterContext context) throws IOException { - scratch = schema.createRowBatch(); + WriterEncryptionVariant encryption, + WriterContext context) throws IOException { + scratch = TypeUtils.createColumn(schema, TypeDescription.RowBatchVersion.USE_DECIMAL64, 1024); childrenWriters = new TreeWriterBase[2]; masks = new DataMask[childrenWriters.length]; + if (schema.getCategory() == TypeDescription.Category.STRUCT) { + scratchBatch = new VectorizedRowBatch(schema.getChildren().size(), 1024); + } else { + scratchBatch = new VectorizedRowBatch(1, 1024); + } // no mask, encrypted data masks[0] = null; @@ -58,15 +66,15 @@ public class EncryptionTreeWriter implements TreeWriter { @Override public void writeRootBatch(VectorizedRowBatch batch, int offset, int length) throws IOException { - scratch.ensureSize(length); + scratchBatch.ensureSize(offset + length); for(int alt=0; alt < childrenWriters.length; ++alt) { // if there is a mask, apply it to each column if (masks[alt] != null) { - for(int col=0; col < scratch.cols.length; ++col) { - masks[alt].maskData(batch.cols[col], scratch.cols[col], offset, + for(int col=0; col < scratchBatch.cols.length; ++col) { + masks[alt].maskData(batch.cols[col], scratchBatch.cols[col], offset, length); } - childrenWriters[alt].writeRootBatch(scratch, offset, length); + childrenWriters[alt].writeRootBatch(scratchBatch, offset, length); } else { childrenWriters[alt].writeRootBatch(batch, offset, length); } @@ -76,11 +84,12 @@ public void writeRootBatch(VectorizedRowBatch batch, int offset, @Override public void writeBatch(ColumnVector vector, int offset, int length) throws IOException { + scratch.ensureSize(length, false); for(int alt=0; alt < childrenWriters.length; ++alt) { // if there is a mask, apply it to each column if (masks[alt] != null) { - masks[alt].maskData(vector, scratch.cols[0], offset, length); - childrenWriters[alt].writeBatch(scratch.cols[0], offset, length); + masks[alt].maskData(vector, scratch, offset, length); + childrenWriters[alt].writeBatch(scratch, offset, length); } else { childrenWriters[alt].writeBatch(vector, offset, length); } @@ -109,9 +118,10 @@ public void writeStripe(int requiredIndexEntries) throws IOException { } @Override - public void updateFileStatistics(OrcProto.StripeStatistics stats) { + public void addStripeStatistics(StripeStatistics[] stripeStatistics + ) throws IOException { for(TreeWriter child: childrenWriters) { - child.updateFileStatistics(stats); + child.addStripeStatistics(stripeStatistics); } } diff --git a/java/core/src/java/org/apache/orc/impl/writer/ListTreeWriter.java b/java/core/src/java/org/apache/orc/impl/writer/ListTreeWriter.java index e21baceeaa..21b6d69d2c 100644 --- a/java/core/src/java/org/apache/orc/impl/writer/ListTreeWriter.java +++ b/java/core/src/java/org/apache/orc/impl/writer/ListTreeWriter.java @@ -22,6 +22,7 @@ import org.apache.hadoop.hive.ql.exec.vector.ListColumnVector; import org.apache.orc.ColumnStatistics; import org.apache.orc.OrcProto; +import org.apache.orc.StripeStatistics; import org.apache.orc.TypeDescription; import org.apache.orc.impl.CryptoUtils; import org.apache.orc.impl.IntegerWriter; @@ -140,9 +141,10 @@ void recordPosition(PositionRecorder recorder) throws IOException { } @Override - public void updateFileStatistics(OrcProto.StripeStatistics stats) { - super.updateFileStatistics(stats); - childWriter.updateFileStatistics(stats); + public void addStripeStatistics(StripeStatistics[] stats + ) throws IOException { + super.addStripeStatistics(stats); + childWriter.addStripeStatistics(stats); } @Override diff --git a/java/core/src/java/org/apache/orc/impl/writer/MapTreeWriter.java b/java/core/src/java/org/apache/orc/impl/writer/MapTreeWriter.java index 6f8ed2d192..0b58ef2ade 100644 --- a/java/core/src/java/org/apache/orc/impl/writer/MapTreeWriter.java +++ b/java/core/src/java/org/apache/orc/impl/writer/MapTreeWriter.java @@ -21,6 +21,7 @@ import org.apache.hadoop.hive.ql.exec.vector.MapColumnVector; import org.apache.orc.ColumnStatistics; import org.apache.orc.OrcProto; +import org.apache.orc.StripeStatistics; import org.apache.orc.TypeDescription; import org.apache.orc.impl.CryptoUtils; import org.apache.orc.impl.IntegerWriter; @@ -151,10 +152,11 @@ void recordPosition(PositionRecorder recorder) throws IOException { } @Override - public void updateFileStatistics(OrcProto.StripeStatistics stats) { - super.updateFileStatistics(stats); - keyWriter.updateFileStatistics(stats); - valueWriter.updateFileStatistics(stats); + public void addStripeStatistics(StripeStatistics[] stats + ) throws IOException { + super.addStripeStatistics(stats); + keyWriter.addStripeStatistics(stats); + valueWriter.addStripeStatistics(stats); } @Override diff --git a/java/core/src/java/org/apache/orc/impl/writer/StructTreeWriter.java b/java/core/src/java/org/apache/orc/impl/writer/StructTreeWriter.java index a78b387533..0ffad14231 100644 --- a/java/core/src/java/org/apache/orc/impl/writer/StructTreeWriter.java +++ b/java/core/src/java/org/apache/orc/impl/writer/StructTreeWriter.java @@ -23,6 +23,7 @@ import org.apache.hadoop.hive.ql.exec.vector.VectorizedRowBatch; import org.apache.orc.ColumnStatistics; import org.apache.orc.OrcProto; +import org.apache.orc.StripeStatistics; import org.apache.orc.TypeDescription; import java.io.IOException; @@ -119,10 +120,11 @@ public void writeStripe(int requiredIndexEntries) throws IOException { } @Override - public void updateFileStatistics(OrcProto.StripeStatistics stats) { - super.updateFileStatistics(stats); + public void addStripeStatistics(StripeStatistics[] stats + ) throws IOException { + super.addStripeStatistics(stats); for (TreeWriter child : childrenWriters) { - child.updateFileStatistics(stats); + child.addStripeStatistics(stats); } } diff --git a/java/core/src/java/org/apache/orc/impl/writer/TreeWriter.java b/java/core/src/java/org/apache/orc/impl/writer/TreeWriter.java index db81ae4f27..367dfb572e 100644 --- a/java/core/src/java/org/apache/orc/impl/writer/TreeWriter.java +++ b/java/core/src/java/org/apache/orc/impl/writer/TreeWriter.java @@ -23,6 +23,7 @@ import org.apache.orc.ColumnStatistics; import org.apache.orc.OrcFile; import org.apache.orc.OrcProto; +import org.apache.orc.StripeStatistics; import org.apache.orc.TypeDescription; import java.io.IOException; @@ -92,10 +93,12 @@ void writeBatch(ColumnVector vector, int offset, void writeStripe(int requiredIndexEntries) throws IOException; /** - * During a stripe append, we need to update the file statistics. - * @param stripeStatistics the statistics for the new stripe + * During a stripe append, we need to handle the stripe statistics. + * @param stripeStatistics the statistics for the new stripe across the + * encryption variants */ - void updateFileStatistics(OrcProto.StripeStatistics stripeStatistics); + void addStripeStatistics(StripeStatistics[] stripeStatistics + ) throws IOException; /** * Write the FileStatistics for each column in each encryption variant. diff --git a/java/core/src/java/org/apache/orc/impl/writer/TreeWriterBase.java b/java/core/src/java/org/apache/orc/impl/writer/TreeWriterBase.java index 17a2a5fbb4..b49420336e 100644 --- a/java/core/src/java/org/apache/orc/impl/writer/TreeWriterBase.java +++ b/java/core/src/java/org/apache/orc/impl/writer/TreeWriterBase.java @@ -26,6 +26,7 @@ import org.apache.orc.ColumnStatistics; import org.apache.orc.OrcFile; import org.apache.orc.OrcProto; +import org.apache.orc.StripeStatistics; import org.apache.orc.TypeDescription; import org.apache.orc.impl.BitFieldWriter; import org.apache.orc.impl.ColumnStatisticsImpl; @@ -343,9 +344,25 @@ void addBloomFilterEntry() { } @Override - public void updateFileStatistics(OrcProto.StripeStatistics stats) { - fileStatistics.merge(ColumnStatisticsImpl.deserialize(schema, - stats.getColStats(id))); + public void addStripeStatistics(StripeStatistics[] stats + ) throws IOException { + // pick out the correct statistics for this writer + int variantId; + int relativeColumn; + if (encryption == null) { + variantId = stats.length - 1; + relativeColumn = id; + } else { + variantId = encryption.getVariantId(); + relativeColumn = id - encryption.getRoot().getId(); + } + OrcProto.ColumnStatistics colStats = stats[variantId].getColumn(relativeColumn); + // update the file statistics + fileStatistics.merge(ColumnStatisticsImpl.deserialize(schema, colStats)); + // write them out to the file + context.writeStatistics( + new StreamName(id, OrcProto.Stream.Kind.STRIPE_STATISTICS, encryption), + colStats.toBuilder()); } /** diff --git a/java/core/src/java/org/apache/orc/impl/writer/UnionTreeWriter.java b/java/core/src/java/org/apache/orc/impl/writer/UnionTreeWriter.java index df4dfef123..f0d7858b25 100644 --- a/java/core/src/java/org/apache/orc/impl/writer/UnionTreeWriter.java +++ b/java/core/src/java/org/apache/orc/impl/writer/UnionTreeWriter.java @@ -22,6 +22,7 @@ import org.apache.hadoop.hive.ql.exec.vector.UnionColumnVector; import org.apache.orc.ColumnStatistics; import org.apache.orc.OrcProto; +import org.apache.orc.StripeStatistics; import org.apache.orc.TypeDescription; import org.apache.orc.impl.CryptoUtils; import org.apache.orc.impl.PositionRecorder; @@ -139,10 +140,11 @@ void recordPosition(PositionRecorder recorder) throws IOException { } @Override - public void updateFileStatistics(OrcProto.StripeStatistics stats) { - super.updateFileStatistics(stats); + public void addStripeStatistics(StripeStatistics[] stats + ) throws IOException { + super.addStripeStatistics(stats); for (TreeWriter child : childrenWriters) { - child.updateFileStatistics(stats); + child.addStripeStatistics(stats); } } diff --git a/java/core/src/java/org/apache/orc/impl/writer/WriterEncryptionKey.java b/java/core/src/java/org/apache/orc/impl/writer/WriterEncryptionKey.java index 40606aa98c..8443dc015d 100644 --- a/java/core/src/java/org/apache/orc/impl/writer/WriterEncryptionKey.java +++ b/java/core/src/java/org/apache/orc/impl/writer/WriterEncryptionKey.java @@ -20,7 +20,6 @@ import org.apache.orc.EncryptionAlgorithm; import org.apache.orc.EncryptionKey; -import org.apache.orc.EncryptionVariant; import org.apache.orc.impl.HadoopShims; import org.jetbrains.annotations.NotNull; @@ -68,6 +67,11 @@ public WriterEncryptionVariant[] getEncryptionRoots() { return roots.toArray(new WriterEncryptionVariant[roots.size()]); } + @Override + public boolean isAvailable() { + return true; + } + public int getId() { return id; } diff --git a/java/core/src/java/org/apache/orc/impl/writer/WriterEncryptionVariant.java b/java/core/src/java/org/apache/orc/impl/writer/WriterEncryptionVariant.java index ed026f7a90..786ef4338d 100644 --- a/java/core/src/java/org/apache/orc/impl/writer/WriterEncryptionVariant.java +++ b/java/core/src/java/org/apache/orc/impl/writer/WriterEncryptionVariant.java @@ -81,10 +81,6 @@ public void clearFileStatistics() { fileStats.clearColumn(); } - public void addFileStatistics(OrcProto.ColumnStatistics column) { - fileStats.addColumn(column); - } - public OrcProto.FileStatistics getFileStatistics() { return fileStats.build(); } diff --git a/java/core/src/test/org/apache/orc/TestTypeDescription.java b/java/core/src/test/org/apache/orc/TestTypeDescription.java index 7519ff2137..e2e722cf75 100644 --- a/java/core/src/test/org/apache/orc/TestTypeDescription.java +++ b/java/core/src/test/org/apache/orc/TestTypeDescription.java @@ -344,7 +344,7 @@ public void testAttributes() throws IOException { // set some attributes schema.findSubtype("name").setAttribute("iceberg.id", "12"); schema.findSubtype("address.street").setAttribute("mask", "nullify") - .setAttribute("encrypt", "pii"); + .setAttribute("context", "pii"); TypeDescription clone = schema.clone(); assertEquals("12", clone.findSubtype("name").getAttributeValue("iceberg.id")); @@ -370,9 +370,9 @@ public void testAttributes() throws IOException { nameCol.getAttributeNames().toArray()); assertEquals("12", nameCol.getAttributeValue("iceberg.id")); TypeDescription street = readerSchema.findSubtype("address.street"); - assertArrayEquals(new Object[]{"encrypt", "mask"}, + assertArrayEquals(new Object[]{"context", "mask"}, street.getAttributeNames().toArray()); - assertEquals("pii", street.getAttributeValue("encrypt")); + assertEquals("pii", street.getAttributeValue("context")); assertEquals("nullify", street.getAttributeValue("mask")); assertEquals(null, street.getAttributeValue("foobar")); } diff --git a/java/core/src/test/org/apache/orc/TestVectorOrcFile.java b/java/core/src/test/org/apache/orc/TestVectorOrcFile.java index 273203289e..e858917cfb 100644 --- a/java/core/src/test/org/apache/orc/TestVectorOrcFile.java +++ b/java/core/src/test/org/apache/orc/TestVectorOrcFile.java @@ -19,6 +19,7 @@ package org.apache.orc; import org.apache.orc.impl.InStream; +import org.apache.orc.impl.KeyProvider; import org.apache.orc.impl.OrcCodecPool; import org.apache.orc.impl.WriterImpl; @@ -66,12 +67,16 @@ import org.junit.runners.Parameterized; import org.mockito.Mockito; +import javax.xml.bind.DatatypeConverter; import java.io.File; import java.io.IOException; import java.math.BigInteger; import java.net.URL; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; +import java.security.KeyStore; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.sql.Date; import java.sql.Timestamp; import java.time.format.DateTimeFormatter; @@ -2305,7 +2310,7 @@ public void testSeek() throws Exception { .withZeroCopy(false) .build()); StripePlanner planner = new StripePlanner(schema, new ReaderEncryption(), - options, meta, reader.getWriterVersion(), true, Integer.MAX_VALUE); + meta, reader.getWriterVersion(), true, Integer.MAX_VALUE); boolean[] columns = new boolean[schema.getMaximumId() + 1]; Arrays.fill(columns, true); OrcIndex index = planner.parseStripe(reader.getStripes().get(0), columns) @@ -3413,8 +3418,8 @@ static ByteBuffer fromString(String s) { return ByteBuffer.wrap(s.getBytes(StandardCharsets.UTF_8)); } - static byte[] fromInt(int x) { - return Integer.toHexString(x).getBytes(StandardCharsets.UTF_8); + static byte[] fromLong(long x) { + return Long.toHexString(x).getBytes(StandardCharsets.UTF_8); } @Test @@ -3445,7 +3450,7 @@ public void testMerge() throws Exception { batch.size = 1024; for(int r=0; r < 1024; ++r) { ((LongColumnVector) batch.cols[0]).vector[r] = r; - ((BytesColumnVector) batch.cols[1]).setVal(r, fromInt(r)); + ((BytesColumnVector) batch.cols[1]).setVal(r, fromLong(r)); } writer.addRowBatch(batch); writer.addUserMetadata("a", fromString("foo")); @@ -3458,7 +3463,7 @@ public void testMerge() throws Exception { batch.size = 1024; for(int r=0; r < 1024; ++r) { ((LongColumnVector) batch.cols[0]).vector[r] = 2 * r; - ((BytesColumnVector) batch.cols[1]).setVal(r, fromInt(2 * r)); + ((BytesColumnVector) batch.cols[1]).setVal(r, fromLong(2 * r)); } writer.addRowBatch(batch); writer.addUserMetadata("a", fromString("foo")); @@ -3471,7 +3476,7 @@ public void testMerge() throws Exception { batch.size = 1024; for(int r=0; r < 1024; ++r) { ((LongColumnVector) batch.cols[0]).vector[r] = 3 * r; - ((BytesColumnVector) batch.cols[1]).setVal(r, fromInt(3 * r)); + ((BytesColumnVector) batch.cols[1]).setVal(r, fromLong(3 * r)); } writer.addRowBatch(batch); writer.addUserMetadata("c", fromString("baz")); @@ -3523,7 +3528,7 @@ public void testMerge() throws Exception { batch.size = 1024; for(int r=0; r < 1024; ++r) { ((LongColumnVector) batch.cols[0]).vector[r] = 4 * r; - ((BytesColumnVector) batch.cols[1]).setVal(r, fromInt(5 * r)); + ((BytesColumnVector) batch.cols[1]).setVal(r, fromLong(5 * r)); } writer.addRowBatch(batch); writer.close(); @@ -3549,11 +3554,299 @@ public void testMerge() throws Exception { assertEquals(fromString("bat"), reader.getMetadataValue("d")); } + /** + * Write a mergeable file to test merging files with column encryption. + * @param path the path to write to + * @param provider the key provider + * @param startValue the base value for the columns + * @param stripes the number of stripes to write + * @param bufferSize the buffer size to use for the compression + * @param encrypt the encryption string + * @param mask the mask string + * @return the locations of the intermediate stripes + * @throws IOException + */ + private long[] writeMergeableFile(Path path, + KeyProvider provider, + long startValue, + int stripes, + int bufferSize, + String encrypt, + String mask) throws IOException { + fs.delete(path, false); + TypeDescription schema = TypeDescription.fromString( + "struct>"); + + // change all of the options away from default to find anything we + // don't copy to the merged file + OrcFile.WriterOptions opts = OrcFile.writerOptions(conf) + .setSchema(schema) + .rowIndexStride(1000) + .version(fileFormat) + .bufferSize(bufferSize) + .enforceBufferSize() + .setKeyProvider(provider) + .encrypt(encrypt) + .masks(mask); + long[] intermediateFooters = new long[stripes]; + + Writer writer = OrcFile.createWriter(path, opts); + VectorizedRowBatch batch = schema.createRowBatch(); + LongColumnVector a = (LongColumnVector) batch.cols[0]; + StructColumnVector b = (StructColumnVector) batch.cols[1]; + BytesColumnVector c = (BytesColumnVector) b.fields[0]; + BytesColumnVector d = (BytesColumnVector) b.fields[1]; + batch.size = 1024; + for(int btch=0; btch < 3; ++btch) { + for (int r = 0; r < 1024; ++r) { + long value = startValue + btch * 1024 + r; + a.vector[r] = value; + c.setVal(r, fromLong(value)); + d.setVal(r, String.format("%010x", value * 1_000_001) + .getBytes(StandardCharsets.UTF_8)); + } + writer.addRowBatch(batch); + // write an intermediate footer to force a stripe + intermediateFooters[btch] = writer.writeIntermediateFooter(); + } + writer.close(); + return intermediateFooters; + } + + static String computeSha(String value) { + try { + MessageDigest md = MessageDigest.getInstance("SHA-256"); + byte[] digest = md.digest(value.getBytes(StandardCharsets.UTF_8)); + return DatatypeConverter.printHexBinary(digest); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException(e); + } + } + + @Test + public void testEncryptMerge() throws Exception { + Assume.assumeTrue(fileFormat != OrcFile.Version.V_0_11); + Path input1 = new Path(workDir, "TestVectorOrcFile.testEncryptMerge1-" + + fileFormat.getName() + ".orc"); + Path input2 = new Path(workDir, "TestVectorOrcFile.testEncryptMerge2-" + + fileFormat.getName() + ".orc"); + Path input3 = new Path(workDir, "TestVectorOrcFile.testEncryptMerge3-" + + fileFormat.getName() + ".orc"); + Path input4 = new Path(workDir, "TestVectorOrcFile.testEncryptMerge4-" + + fileFormat.getName() + ".orc"); + Path input5 = new Path(workDir, "TestVectorOrcFile.testEncryptMerge5-" + + fileFormat.getName() + ".orc"); + Random random = new Random(169); + InMemoryKeystore keystore = new InMemoryKeystore(random); + EncryptionAlgorithm algorithm = EncryptionAlgorithm.AES_CTR_128; + byte[] piiKey = new byte[algorithm.keyLength()]; + byte[] topSecretKey = new byte[algorithm.keyLength()]; + random.nextBytes(piiKey); + random.nextBytes(topSecretKey); + keystore.addKey("pii", algorithm, piiKey) + .addKey("top_secret", algorithm, topSecretKey); + String encryption = "pii:a;top_secret:b"; + String mask = "sha256,`don't worry`:b"; + + // write three files that should merge, each with 3 stripes of 1024 rows. + long[] cuts = writeMergeableFile(input1, keystore, 0, 3, 0x400, encryption, mask); + writeMergeableFile(input2, keystore, 3 * 1024, 3, 0x800, encryption, mask); + writeMergeableFile(input3, keystore, 6 * 1024, 3, 0xc00, encryption, mask); + // two files that aren't mergeable + writeMergeableFile(input4, keystore, 9 * 1024, 3, 0x400, encryption, null); + writeMergeableFile(input5, keystore, 12 * 1024, 3, 0x400, null, null); + + // make sure that we can read up to the intermediate footers + try (Reader reader = OrcFile.createReader(input1, OrcFile.readerOptions(conf) + .maxLength(cuts[0]))) { + assertEquals(1024, reader.getNumberOfRows()); + } + try (Reader reader = OrcFile.createReader(input1, OrcFile.readerOptions(conf) + .maxLength(cuts[1]))) { + assertEquals(2 * 1024, reader.getNumberOfRows()); + } + try (Reader reader = OrcFile.createReader(input1, OrcFile.readerOptions(conf) + .maxLength(cuts[2]))) { + assertEquals(3 * 1024, reader.getNumberOfRows()); + } + + // make a new version of the pii key + keystore.addKey("pii", 1, algorithm, new byte[algorithm.keyLength()]); + Path merge1 = new Path(workDir, "TestVectorOrcFile.testEncryptMerge.merge1-" + + fileFormat.getName() + ".orc"); + + // merge all three files together + fs.delete(merge1, false); + List paths = OrcFile.mergeFiles(merge1, + OrcFile.writerOptions(conf).setKeyProvider(keystore), + Arrays.asList(input1, input2, input3)); + assertEquals(3, paths.size()); + + // test reading with no keys + Reader reader = OrcFile.createReader(merge1, OrcFile.readerOptions(conf)); + assertEquals(9 * 1024, reader.getNumberOfRows()); + assertEquals(CompressionKind.ZLIB, reader.getCompressionKind()); + assertEquals(1000, reader.getRowIndexStride()); + assertEquals(0xc00, reader.getCompressionSize()); + assertEquals(fileFormat, reader.getFileVersion()); + assertEquals(9, reader.getStripes().size()); + EncryptionKey[] keys = reader.getColumnEncryptionKeys(); + assertEquals(2, keys.length); + assertEquals("pii", keys[0].getKeyName()); + assertEquals(0, keys[0].getKeyVersion()); + assertEquals(false, keys[0].isAvailable()); + assertEquals("top_secret", keys[1].getKeyName()); + assertEquals(0, keys[1].getKeyVersion()); + assertEquals(false, keys[1].isAvailable()); + // check the file stats + ColumnStatistics[] stats = reader.getStatistics(); + assertEquals(9 * 1024, stats[0].getNumberOfValues()); + assertEquals(0, stats[1].getNumberOfValues()); + assertEquals(9 * 1024, stats[2].getNumberOfValues()); + assertEquals(9 * 1024, stats[3].getNumberOfValues()); + assertEquals("00037F39CF870A1F49129F9C82D935665D352FFD25EA3296208F6F7B16FD654F", + ((StringColumnStatistics) stats[3]).getMinimum()); + assertEquals("FFF60CF25C8E227396BC77DD808773DA69D767D6B0417ADB1A0CAC51CC168797", + ((StringColumnStatistics) stats[3]).getMaximum()); + assertEquals(9 * 1024, stats[4].getNumberOfValues()); + assertEquals("001277C7986C02D9CDA490756055C6A81F3838D3394F18806DD3359AAD59862A", + ((StringColumnStatistics) stats[4]).getMinimum()); + assertEquals("FFFF1E62E46263E623F704AC22C2F27E5BBDED8693546A2A11F011251A53D23D", + ((StringColumnStatistics) stats[4]).getMaximum()); + // check the stripe stats + List stripeStats = reader.getStripeStatistics(); + for(int s=0; s < stripeStats.size(); ++s) { + ColumnStatistics[] cs = stripeStats.get(s).getColumnStatistics(); + assertEquals("stripe " + s, 1024, cs[0].getNumberOfValues()); + assertEquals("stripe " + s, 0, cs[1].getNumberOfValues()); + assertEquals("stripe " + s, 1024, cs[2].getNumberOfValues()); + assertEquals("stripe " + s, 1024, cs[3].getNumberOfValues()); + assertEquals("stripe " + s, 64, ((StringColumnStatistics) cs[3]).getMinimum().length()); + assertEquals("stripe " + s, 64, ((StringColumnStatistics) cs[3]).getMaximum().length()); + assertEquals("stripe " + s, 1024, cs[4].getNumberOfValues()); + assertEquals("stripe " + s, 64, ((StringColumnStatistics) cs[4]).getMinimum().length()); + assertEquals("stripe " + s, 64, ((StringColumnStatistics) cs[4]).getMaximum().length()); + } + // check the file contents + RecordReader rows = reader.rows(); + VectorizedRowBatch batch = reader.getSchema().createRowBatchV2(); + LongColumnVector a = (LongColumnVector) batch.cols[0]; + StructColumnVector b = (StructColumnVector) batch.cols[1]; + BytesColumnVector c = (BytesColumnVector) b.fields[0]; + BytesColumnVector d = (BytesColumnVector) b.fields[1]; + for(int btch=0; btch < 9; ++btch) { + assertEquals(true, rows.nextBatch(batch)); + assertEquals(1024, batch.size); + for(int r=0; r < batch.size; ++r) { + long value = btch * 1024 + r; + assertEquals("batch " + btch + " row " + r, true, a.isNull[r]); + assertEquals("batch " + btch + " row " + r, + computeSha(Long.toHexString(value)), c.toString(r)); + assertEquals("batch " + btch + " row " + r, + computeSha(String.format("%010x", value * 1_000_001)), + d.toString(r)); + } + } + assertEquals(false, rows.nextBatch(batch)); + rows.close(); + reader.close(); + + // test reading with keys + reader = OrcFile.createReader(merge1, + OrcFile.readerOptions(conf).setKeyProvider(keystore)); + assertEquals(9 * 1024, reader.getNumberOfRows()); + keys = reader.getColumnEncryptionKeys(); + assertEquals(2, keys.length); + assertEquals("pii", keys[0].getKeyName()); + assertEquals(0, keys[0].getKeyVersion()); + assertEquals(true, keys[0].isAvailable()); + assertEquals("top_secret", keys[1].getKeyName()); + assertEquals(0, keys[1].getKeyVersion()); + assertEquals(true, keys[1].isAvailable()); + // check the file stats + stats = reader.getStatistics(); + assertEquals(9 * 1024, stats[0].getNumberOfValues()); + assertEquals(9 * 1024, stats[1].getNumberOfValues()); + assertEquals(0, ((IntegerColumnStatistics) stats[1]).getMinimum()); + assertEquals(9 * 1024 - 1, ((IntegerColumnStatistics) stats[1]).getMaximum()); + assertEquals(9 * 1024, stats[2].getNumberOfValues()); + assertEquals(9 * 1024, stats[3].getNumberOfValues()); + assertEquals("0", ((StringColumnStatistics) stats[3]).getMinimum()); + assertEquals("fff", ((StringColumnStatistics) stats[3]).getMaximum()); + assertEquals(9 * 1024, stats[4].getNumberOfValues()); + assertEquals("0000000000", ((StringColumnStatistics) stats[4]).getMinimum()); + assertEquals("022541e1bf", ((StringColumnStatistics) stats[4]).getMaximum()); + // check the stripe stats + stripeStats = reader.getStripeStatistics(); + for(int s=0; s < stripeStats.size(); ++s) { + long low = s * 1024; + long high = s * 1024 + 1023; + ColumnStatistics[] cs = stripeStats.get(s).getColumnStatistics(); + assertEquals("stripe " + s, 1024, cs[0].getNumberOfValues()); + assertEquals("stripe " + s, 1024, cs[1].getNumberOfValues()); + assertEquals("stripe " + s, low, ((IntegerColumnStatistics) cs[1]).getMinimum()); + assertEquals("stripe " + s, high, ((IntegerColumnStatistics) cs[1]).getMaximum()); + assertEquals("stripe " + s, 1024, cs[2].getNumberOfValues()); + assertEquals("stripe " + s, 1024, cs[3].getNumberOfValues()); + assertEquals("stripe " + s, Long.toHexString(low), + ((StringColumnStatistics) cs[3]).getMinimum()); + assertEquals("stripe " + s, s == 0 ? "ff" : Long.toHexString(high), + ((StringColumnStatistics) cs[3]).getMaximum()); + assertEquals("stripe " + s, 1024, cs[4].getNumberOfValues()); + assertEquals("stripe " + s, String.format("%010x", 1_000_001 * low), + ((StringColumnStatistics) cs[4]).getMinimum()); + assertEquals("stripe " + s, String.format("%010x", 1_000_001 * high), + ((StringColumnStatistics) cs[4]).getMaximum()); + } + // check the file contents + rows = reader.rows(); + for(int btch=0; btch < 9; ++btch) { + assertEquals(true, rows.nextBatch(batch)); + assertEquals(1024, batch.size); + for(int r=0; r < batch.size; ++r) { + long value = btch * 1024 + r; + assertEquals("batch " + btch + " row " + r, value, a.vector[r]); + assertEquals("batch " + btch + " row " + r, Long.toHexString(value), + c.toString(r)); + assertEquals("batch " + btch + " row " + r, + String.format("%010x", value * 1_000_001), d.toString(r)); + } + } + assertEquals(false, rows.nextBatch(batch)); + rows.close(); + reader.close(); + + Path merge2 = new Path(workDir, "TestVectorOrcFile.testEncryptMerge.merge2-" + + fileFormat.getName() + ".orc"); + fs.delete(merge2, false); + paths = OrcFile.mergeFiles(merge2, + OrcFile.writerOptions(conf).setKeyProvider(keystore), + Arrays.asList(input2, input4, input1, input5)); + + // make sure only input1 & input2 were merged + assertEquals(2, paths.size()); + assertEquals(true, paths.contains(input1)); + assertEquals(true, paths.contains(input2)); + + reader = OrcFile.createReader(merge2, OrcFile.readerOptions(conf)); + assertEquals(2 * 3 * 1024, reader.getNumberOfRows()); + assertEquals(CompressionKind.ZLIB, reader.getCompressionKind()); + assertEquals(0x800, reader.getCompressionSize()); + assertEquals(1000, reader.getRowIndexStride()); + assertEquals(fileFormat, reader.getFileVersion()); + assertEquals(6, reader.getStripes().size()); + assertEquals(2, reader.getColumnEncryptionKeys().length); + assertEquals(2, reader.getDataMasks().length); + assertEquals(2, reader.getEncryptionVariants().length); + reader.close(); + } + Path exampleDir = new Path(System.getProperty("example.dir", "../../examples/")); @Test public void testZeroByteOrcFile() throws Exception { + // we only have to run this test once, since it is a 0 byte file. Assume.assumeTrue(fileFormat == OrcFile.Version.V_0_11); Path zeroFile = new Path(exampleDir, "zero.orc"); Reader reader = OrcFile.createReader(zeroFile, OrcFile.readerOptions(conf)); @@ -3744,7 +4037,7 @@ public void testColumnEncryption() throws Exception { random.nextBytes(piiKey); byte[] creditKey = new byte[32]; random.nextBytes(creditKey); - InMemoryKeystore keys = new InMemoryKeystore() + InMemoryKeystore keys = new InMemoryKeystore(random) .addKey("pii", EncryptionAlgorithm.AES_CTR_128, piiKey) .addKey("credit", EncryptionAlgorithm.AES_CTR_256, creditKey); Writer writer = OrcFile.createWriter(testFilePath, diff --git a/java/core/src/test/org/apache/orc/impl/MockDataReader.java b/java/core/src/test/org/apache/orc/impl/MockDataReader.java index ccf533d031..b3d950bacc 100644 --- a/java/core/src/test/org/apache/orc/impl/MockDataReader.java +++ b/java/core/src/test/org/apache/orc/impl/MockDataReader.java @@ -38,10 +38,17 @@ public class MockDataReader implements DataReader { private MockStripe next; private Set outBuffers = Collections.newSetFromMap(new IdentityHashMap<>()); + private final InStream.StreamOptions options; public MockDataReader(TypeDescription schema) { + this(schema, new InStream.StreamOptions()); + } + + public MockDataReader(TypeDescription schema, + InStream.StreamOptions options) { numColumns = schema.getMaximumId() + 1; next = new MockStripe(numColumns, stripes.size(), offset); + this.options = options; } public MockDataReader addStream(int column, OrcProto.Stream.Kind kind, @@ -106,8 +113,8 @@ public DataReader clone() { public void close() { } @Override - public CompressionCodec getCompressionCodec() { - return null; + public InStream.StreamOptions getCompressionOptions() { + return options; } public MockStripe getStripe(int id) { diff --git a/java/core/src/test/org/apache/orc/impl/MockStripe.java b/java/core/src/test/org/apache/orc/impl/MockStripe.java index 0e1e3f81a9..8e5cabced2 100644 --- a/java/core/src/test/org/apache/orc/impl/MockStripe.java +++ b/java/core/src/test/org/apache/orc/impl/MockStripe.java @@ -121,6 +121,11 @@ public long getStripeId() { return stripeId; } + @Override + public boolean hasEncryptionStripeId() { + return false; + } + @Override public long getEncryptionStripeId() { return stripeId; diff --git a/java/core/src/test/org/apache/orc/impl/TestRecordReaderImpl.java b/java/core/src/test/org/apache/orc/impl/TestRecordReaderImpl.java index 254ffcc4bc..3f3abdd52a 100644 --- a/java/core/src/test/org/apache/orc/impl/TestRecordReaderImpl.java +++ b/java/core/src/test/org/apache/orc/impl/TestRecordReaderImpl.java @@ -1363,8 +1363,7 @@ public void testPartialPlan() throws Exception { // filter by rows and groups StripePlanner planner = new StripePlanner(schema, new ReaderEncryption(), - new InStream.StreamOptions(), dataReader, - OrcFile.WriterVersion.ORC_14, false, Integer.MAX_VALUE); + dataReader, OrcFile.WriterVersion.ORC_14, false, Integer.MAX_VALUE); planner.parseStripe(stripe, columns); OrcIndex index = planner.readRowIndex(null, null); BufferChunkList result = planner.readData(index, rowGroups, false); @@ -1426,7 +1425,7 @@ public void testPartialPlanCompressed() throws Exception { .withCodec(OrcCodecPool.getCodec(CompressionKind.ZLIB)) .withBufferSize(1024); final int SLOP = 2 * (OutStream.HEADER_SIZE + options.getBufferSize()); - MockDataReader dataReader = new MockDataReader(schema) + MockDataReader dataReader = new MockDataReader(schema, options) .addStream(1, OrcProto.Stream.Kind.ROW_INDEX, createRowIndex(options, entry(0, -1, -1, -1, 0), @@ -1456,8 +1455,7 @@ public void testPartialPlanCompressed() throws Exception { final long START = stripe.getStream(1, OrcProto.Stream.Kind.PRESENT).offset; StripePlanner planner = new StripePlanner(schema, new ReaderEncryption(), - options, dataReader, OrcFile.WriterVersion.ORC_14, false, - Integer.MAX_VALUE); + dataReader, OrcFile.WriterVersion.ORC_14, false, Integer.MAX_VALUE); // filter by rows and groups boolean[] columns = new boolean[]{true, true, false}; @@ -1517,7 +1515,6 @@ public void testPartialPlanString() throws Exception { // filter by rows and groups StripePlanner planner = new StripePlanner(schema, new ReaderEncryption(), - new InStream.StreamOptions(), dataReader, OrcFile.WriterVersion.ORC_14, false, Integer.MAX_VALUE); // filter by rows and groups @@ -1972,8 +1969,7 @@ public void TestOldBloomFilters() throws Exception { // use old blooms ReaderEncryption encryption = new ReaderEncryption(); - StripePlanner planner = new StripePlanner(schema, encryption, - new InStream.StreamOptions(), dataReader, + StripePlanner planner = new StripePlanner(schema, encryption, dataReader, OrcFile.WriterVersion.HIVE_4243, false, Integer.MAX_VALUE); planner.parseStripe(stripe, new boolean[]{true, true, false, true}); OrcIndex index = @@ -1991,8 +1987,7 @@ public void TestOldBloomFilters() throws Exception { // ignore non-utf8 bloom filter dataReader.resetCounts(); Arrays.fill(bloomFilterKinds, null); - planner = new StripePlanner(schema, encryption, - new InStream.StreamOptions(), dataReader, + planner = new StripePlanner(schema, encryption, dataReader, OrcFile.WriterVersion.HIVE_4243, true, Integer.MAX_VALUE); planner.parseStripe(stripe, new boolean[]{true, true, true, false}); planner.readRowIndex(new boolean[]{false, true, true, false}, index); @@ -2008,8 +2003,7 @@ public void TestOldBloomFilters() throws Exception { // check that we are handling the post hive-12055 strings correctly dataReader.resetCounts(); Arrays.fill(bloomFilterKinds, null); - planner = new StripePlanner(schema, encryption, - new InStream.StreamOptions(), dataReader, + planner = new StripePlanner(schema, encryption, dataReader, OrcFile.WriterVersion.HIVE_12055, true, Integer.MAX_VALUE); planner.parseStripe(stripe, new boolean[]{true, true, true, true}); planner.readRowIndex(new boolean[]{false, true, true, true}, index); @@ -2026,8 +2020,7 @@ public void TestOldBloomFilters() throws Exception { // ignore non-utf8 bloom filter on decimal dataReader.resetCounts(); Arrays.fill(bloomFilterKinds, null); - planner = new StripePlanner(schema, encryption, - new InStream.StreamOptions(), dataReader, + planner = new StripePlanner(schema, encryption, dataReader, OrcFile.WriterVersion.HIVE_4243, true, Integer.MAX_VALUE); planner.parseStripe(stripe, new boolean[]{true, false, true, false}); planner.readRowIndex(new boolean[]{false, false, true, false}, index); @@ -2049,8 +2042,7 @@ public void TestCompatibleBloomFilters() throws Exception { // use old bloom filters ReaderEncryption encryption = new ReaderEncryption(); - StripePlanner planner = new StripePlanner(schema, encryption, - new InStream.StreamOptions(), dataReader, + StripePlanner planner = new StripePlanner(schema, encryption, dataReader, OrcFile.WriterVersion.HIVE_4243, true, Integer.MAX_VALUE); planner.parseStripe(stripe, new boolean[]{true, true, false, true}); OrcIndex index = @@ -2071,8 +2063,7 @@ public void TestCompatibleBloomFilters() throws Exception { // ignore non-utf8 bloom filter Arrays.fill(bloomFilterKinds, null); dataReader.resetCounts(); - planner = new StripePlanner(schema, encryption, - new InStream.StreamOptions(), dataReader, + planner = new StripePlanner(schema, encryption, dataReader, OrcFile.WriterVersion.HIVE_4243, true, Integer.MAX_VALUE); planner.parseStripe(stripe, new boolean[]{true, true, true, false}); planner.readRowIndex(new boolean[]{false, true, true, false}, index); @@ -2096,8 +2087,7 @@ public void TestNewBloomFilters() throws Exception { // use old bloom filters ReaderEncryption encryption = new ReaderEncryption(); - StripePlanner planner = new StripePlanner(schema, encryption, - new InStream.StreamOptions(), dataReader, + StripePlanner planner = new StripePlanner(schema, encryption, dataReader, OrcFile.WriterVersion.HIVE_4243, true, Integer.MAX_VALUE); planner.parseStripe(stripe, new boolean[]{true, true, false, true}); OrcIndex index = @@ -2116,8 +2106,7 @@ public void TestNewBloomFilters() throws Exception { // ignore non-utf8 bloom filter Arrays.fill(bloomFilterKinds, null); dataReader.resetCounts(); - planner = new StripePlanner(schema, encryption, - new InStream.StreamOptions(), dataReader, + planner = new StripePlanner(schema, encryption, dataReader, OrcFile.WriterVersion.HIVE_4243, true, Integer.MAX_VALUE); planner.parseStripe(stripe, new boolean[]{true, true, true, false}); planner.readRowIndex(new boolean[]{false, true, true, false}, index); diff --git a/java/core/src/test/org/apache/orc/impl/TestSchemaEvolution.java b/java/core/src/test/org/apache/orc/impl/TestSchemaEvolution.java index e07425d5bb..00a3383bf3 100644 --- a/java/core/src/test/org/apache/orc/impl/TestSchemaEvolution.java +++ b/java/core/src/test/org/apache/orc/impl/TestSchemaEvolution.java @@ -1620,8 +1620,7 @@ public void testTypeConversion() throws IOException { .addStream(2, OrcProto.Stream.Kind.LENGTH, createBuffer(7, 0, 1)) .addStripeFooter(100, null); StripePlanner planner = new StripePlanner(fileType, new ReaderEncryption(), - InStream.options(), dataReader, - OrcFile.WriterVersion.ORC_14, true, Integer.MAX_VALUE); + dataReader, OrcFile.WriterVersion.ORC_14, true, Integer.MAX_VALUE); boolean[] columns = new boolean[]{true, true, true}; planner.parseStripe(dataReader.getStripe(0), columns) .readData(null, null, false); diff --git a/proto/orc_proto.proto b/proto/orc_proto.proto index 337854b5e1..09d752e17c 100644 --- a/proto/orc_proto.proto +++ b/proto/orc_proto.proto @@ -359,9 +359,6 @@ message Footer { // information about the encryption in this file optional Encryption encryption = 10; - - // the number of bytes in the encrypted stripe statistics - optional uint64 stripeStatisticsLength = 11; } enum CompressionKind { @@ -416,6 +413,9 @@ message PostScript { // optional uint32 writerVersion = 6; + // the number of bytes in the encrypted stripe statistics + optional uint64 stripeStatisticsLength = 7; + // Leave this last in the record optional string magic = 8000; }