1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
|
// 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 file
import (
"bytes"
"encoding/binary"
"fmt"
"io"
"os"
"runtime"
"sync"
"github.com/apache/arrow-go/v18/arrow/memory"
"github.com/apache/arrow-go/v18/parquet"
"github.com/apache/arrow-go/v18/parquet/internal/encryption"
"github.com/apache/arrow-go/v18/parquet/metadata"
"golang.org/x/xerrors"
)
const (
footerSize uint32 = 8
)
var (
magicBytes = []byte("PAR1")
magicEBytes = []byte("PARE")
errInconsistentFileMetadata = xerrors.New("parquet: file is smaller than indicated metadata size")
)
// Reader is the main interface for reading a parquet file
type Reader struct {
r parquet.ReaderAtSeeker
props *parquet.ReaderProperties
metadata *metadata.FileMetaData
fileDecryptor encryption.FileDecryptor
pageIndexReader *metadata.PageIndexReader
bufferPool sync.Pool
}
type ReadOption func(*Reader)
// WithReadProps specifies a specific reader properties instance to use, rather
// than using the default ReaderProperties.
func WithReadProps(props *parquet.ReaderProperties) ReadOption {
return func(r *Reader) {
r.props = props
}
}
// WithMetadata allows providing a specific FileMetaData object rather than reading
// the file metadata from the file itself.
func WithMetadata(m *metadata.FileMetaData) ReadOption {
return func(r *Reader) {
r.metadata = m
}
}
// OpenParquetFile will return a Reader for the given parquet file on the local file system.
//
// Optionally the file can be memory mapped for faster reading. If no read properties are provided
// then the default ReaderProperties will be used. The WithMetadata option can be used to provide
// a FileMetaData object rather than reading the file metadata from the file.
func OpenParquetFile(filename string, memoryMap bool, opts ...ReadOption) (*Reader, error) {
var source parquet.ReaderAtSeeker
var err error
if memoryMap {
source, err = mmapOpen(filename)
if err != nil {
return nil, err
}
} else {
source, err = os.Open(filename)
if err != nil {
return nil, err
}
}
return NewParquetReader(source, opts...)
}
// NewParquetReader returns a FileReader instance that reads a parquet file which can be read from r.
// This reader needs to support Read, ReadAt and Seeking.
//
// If no read properties are provided then the default ReaderProperties will be used. The WithMetadata
// option can be used to provide a FileMetaData object rather than reading the file metadata from the file.
func NewParquetReader(r parquet.ReaderAtSeeker, opts ...ReadOption) (*Reader, error) {
f := &Reader{r: r}
for _, o := range opts {
o(f)
}
if f.props == nil {
f.props = parquet.NewReaderProperties(memory.NewGoAllocator())
}
f.bufferPool = sync.Pool{
New: func() interface{} {
buf := memory.NewResizableBuffer(f.props.Allocator())
runtime.SetFinalizer(buf, func(obj *memory.Buffer) {
obj.Release()
})
return buf
},
}
if f.metadata == nil {
if err := f.parseMetaData(); err != nil {
return nil, err
}
}
f.pageIndexReader = &metadata.PageIndexReader{
Input: f.r,
Props: f.props,
FileMetadata: f.metadata,
Decryptor: f.fileDecryptor,
}
return f, nil
}
// BufferPool returns the internal buffer pool being utilized by this reader.
// This is primarily for use by the pqarrow.FileReader or anything that builds
// on top of the Reader and constructs their own ColumnReaders (like the
// RecordReader)
func (f *Reader) BufferPool() *sync.Pool {
return &f.bufferPool
}
// Close will close the current reader, and if the underlying reader being used
// is an `io.Closer` then Close will be called on it too.
func (f *Reader) Close() error {
if r, ok := f.r.(io.Closer); ok {
return r.Close()
}
return nil
}
// MetaData returns the underlying FileMetadata object
func (f *Reader) MetaData() *metadata.FileMetaData { return f.metadata }
// parseMetaData handles parsing the metadata from the opened file.
func (f *Reader) parseMetaData() error {
footerOffset, err := f.r.Seek(0, io.SeekEnd)
if err != nil {
return fmt.Errorf("parquet: could not retrieve footer offset: %w", err)
}
if footerOffset <= int64(footerSize) {
return fmt.Errorf("parquet: file too small (size=%d)", footerOffset)
}
buf := make([]byte, footerSize)
// backup 8 bytes to read the footer size (first four bytes) and the magic bytes (last 4 bytes)
n, err := f.r.ReadAt(buf, footerOffset-int64(footerSize))
if err != nil && err != io.EOF {
return fmt.Errorf("parquet: could not read footer: %w", err)
}
if n != len(buf) {
return fmt.Errorf("parquet: could not read %d bytes from end of file", len(buf))
}
size := int64(binary.LittleEndian.Uint32(buf[:4]))
if size < 0 || size+int64(footerSize) > footerOffset {
return errInconsistentFileMetadata
}
fileDecryptProps := f.props.FileDecryptProps
switch {
case bytes.Equal(buf[4:], magicBytes): // non-encrypted metadata
buf = make([]byte, size)
if _, err := f.r.ReadAt(buf, footerOffset-int64(footerSize)-size); err != nil {
return fmt.Errorf("parquet: could not read footer: %w", err)
}
f.metadata, err = metadata.NewFileMetaData(buf, nil)
if err != nil {
return fmt.Errorf("parquet: could not read footer: %w", err)
}
f.metadata.SetSourceFileSize(footerOffset)
if !f.metadata.IsSetEncryptionAlgorithm() {
if fileDecryptProps != nil && !fileDecryptProps.PlaintextFilesAllowed() {
return fmt.Errorf("parquet: applying decryption properties on plaintext file")
}
} else {
if err := f.parseMetaDataEncryptedFilePlaintextFooter(fileDecryptProps, buf); err != nil {
return err
}
}
case bytes.Equal(buf[4:], magicEBytes): // encrypted metadata
buf = make([]byte, size)
if _, err := f.r.ReadAt(buf, footerOffset-int64(footerSize)-size); err != nil {
return fmt.Errorf("parquet: could not read footer: %w", err)
}
if fileDecryptProps == nil {
return xerrors.New("could not read encrypted metadata, no decryption found in reader's properties")
}
fileCryptoMetadata, err := metadata.NewFileCryptoMetaData(buf)
if err != nil {
return err
}
algo := fileCryptoMetadata.EncryptionAlgorithm()
fileAad, err := f.handleAadPrefix(fileDecryptProps, &algo)
if err != nil {
return err
}
f.fileDecryptor = encryption.NewFileDecryptor(fileDecryptProps, fileAad, algo.Algo, string(fileCryptoMetadata.KeyMetadata()), f.props.Allocator())
f.metadata, err = metadata.NewFileMetaData(buf[fileCryptoMetadata.Len():], f.fileDecryptor)
if err != nil {
return fmt.Errorf("parquet: could not read footer: %w", err)
}
f.metadata.SetSourceFileSize(footerOffset)
default:
return fmt.Errorf("parquet: magic bytes not found in footer. Either the file is corrupted or this isn't a parquet file")
}
return nil
}
func (f *Reader) handleAadPrefix(fileDecrypt *parquet.FileDecryptionProperties, algo *parquet.Algorithm) (string, error) {
aadPrefixInProps := fileDecrypt.AadPrefix()
aadPrefix := []byte(aadPrefixInProps)
fileHasAadPrefix := len(algo.Aad.AadPrefix) > 0
aadPrefixInFile := algo.Aad.AadPrefix
if algo.Aad.SupplyAadPrefix && aadPrefixInProps == "" {
return "", xerrors.New("AAD Prefix used for file encryption but not stored in file and not supplied in decryption props")
}
if fileHasAadPrefix {
if aadPrefixInProps != "" {
if aadPrefixInProps != string(aadPrefixInFile) {
return "", xerrors.New("AAD prefix in file and in properties but not the same")
}
}
aadPrefix = aadPrefixInFile
if fileDecrypt.Verifier != nil {
fileDecrypt.Verifier.Verify(string(aadPrefix))
}
} else {
if !algo.Aad.SupplyAadPrefix && aadPrefixInProps != "" {
return "", xerrors.New("AAD Prefix set in decryptionproperties but was not used for file encryption")
}
if fileDecrypt.Verifier != nil {
return "", xerrors.New("AAD Prefix Verifier is set but AAD Prefix not found in file")
}
}
return string(append(aadPrefix, algo.Aad.AadFileUnique...)), nil
}
func (f *Reader) parseMetaDataEncryptedFilePlaintextFooter(decryptProps *parquet.FileDecryptionProperties, data []byte) error {
if decryptProps != nil {
algo := f.metadata.EncryptionAlgorithm()
fileAad, err := f.handleAadPrefix(decryptProps, &algo)
if err != nil {
return err
}
f.fileDecryptor = encryption.NewFileDecryptor(decryptProps, fileAad, algo.Algo, string(f.metadata.GetFooterSigningKeyMetadata()), f.props.Allocator())
// set the InternalFileDecryptor in the metadata as well, as it's used
// for signature verification and for ColumnChunkMetaData creation.
f.metadata.FileDecryptor = f.fileDecryptor
if decryptProps.PlaintextFooterIntegrity() {
if len(data)-f.metadata.Size() != encryption.GcmTagLength+encryption.NonceLength {
return xerrors.New("failed reading metadata for encryption signature")
}
if !f.metadata.VerifySignature(data[f.metadata.Size():]) {
return xerrors.New("parquet crypto signature verification failed")
}
}
}
return nil
}
// WriterVersion returns the Application Version that was written in the file
// metadata
func (f *Reader) WriterVersion() *metadata.AppVersion {
return f.metadata.WriterVersion()
}
// NumRows returns the total number of rows in this parquet file.
func (f *Reader) NumRows() int64 {
return f.metadata.GetNumRows()
}
// NumRowGroups returns the total number of row groups in this file.
func (f *Reader) NumRowGroups() int {
return len(f.metadata.GetRowGroups())
}
// RowGroup returns a reader for the desired (0-based) row group
func (f *Reader) RowGroup(i int) *RowGroupReader {
rg := f.metadata.RowGroups[i]
return &RowGroupReader{
fileMetadata: f.metadata,
rgMetadata: metadata.NewRowGroupMetaData(rg, f.metadata.Schema, f.WriterVersion(), f.fileDecryptor),
props: f.props,
r: f.r,
fileDecryptor: f.fileDecryptor,
bufferPool: &f.bufferPool,
pageIndexReader: f.pageIndexReader,
}
}
func (f *Reader) GetPageIndexReader() *metadata.PageIndexReader {
return f.pageIndexReader
}
|