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 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
|
// 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"
"fmt"
"math"
"sync"
"github.com/apache/arrow-go/v18/arrow/memory"
"github.com/apache/arrow-go/v18/parquet"
"github.com/apache/arrow-go/v18/parquet/compress"
"github.com/apache/arrow-go/v18/parquet/internal/encoding"
"github.com/apache/arrow-go/v18/parquet/internal/encryption"
format "github.com/apache/arrow-go/v18/parquet/internal/gen-go/parquet"
"github.com/apache/arrow-go/v18/parquet/internal/thrift"
"github.com/apache/arrow-go/v18/parquet/internal/utils"
"github.com/apache/arrow-go/v18/parquet/metadata"
libthrift "github.com/apache/thrift/lib/go/thrift"
"golang.org/x/xerrors"
)
// PageWriter is the interface for both serialized and buffered page writers
type PageWriter interface {
// Closes the current page, flushing any buffered data pages/dictionary pages
// based on the input parameters. Subsequent calls have no effect.
Close(hasDict, fallback bool) error
// Write the provided datapage out to the underlying writer
WriteDataPage(page DataPage) (int64, error)
// Write the provided dictionary page out to the underlying writer
WriteDictionaryPage(page *DictionaryPage) (int64, error)
// returns true if there is a configured compressor for the data
HasCompressor() bool
// use the configured compressor and writer properties to compress the data in src
// using the buffer buf. Returns the slice of the compressed bytes which may be
// the bytes in the provided buffer
Compress(buf *bytes.Buffer, src []byte) []byte
// Allow reuse of the pagewriter object by resetting it using these values instead
// of having to create a new object.
Reset(sink utils.WriterTell, codec compress.Compression, compressionLevel int, metadata *metadata.ColumnChunkMetaDataBuilder, rgOrdinal, columnOrdinal int16, metaEncryptor, dataEncryptor encryption.Encryptor) error
SetIndexBuilders(metadata.ColumnIndexBuilder, *metadata.OffsetIndexBuilder)
}
type serializedPageWriter struct {
mem memory.Allocator
metaData *metadata.ColumnChunkMetaDataBuilder
sink utils.WriterTell
nvalues int64
dictPageOffset int64
dataPageOffset int64
totalUncompressed int64
totalCompressed int64
pageOrdinal int16
rgOrdinal int16
columnOrdinal int16
compressLevel int
compressor compress.Codec
metaEncryptor encryption.Encryptor
dataEncryptor encryption.Encryptor
encryptionBuf bytes.Buffer
dataPageAAD []byte
dataPageHeaderAAD []byte
dictEncodingStats map[parquet.Encoding]int32
dataEncodingStats map[parquet.Encoding]int32
columnIndexBuilder metadata.ColumnIndexBuilder
offsetIndexBuilder *metadata.OffsetIndexBuilder
thriftSerializer *thrift.Serializer
}
func createSerializedPageWriter(sink utils.WriterTell, codec compress.Compression, compressionLevel int, metadata *metadata.ColumnChunkMetaDataBuilder, rowGroupOrdinal, columnChunkOrdinal int16, mem memory.Allocator, metaEncryptor, dataEncryptor encryption.Encryptor) (PageWriter, error) {
var (
compressor compress.Codec
err error
)
if codec != compress.Codecs.Uncompressed {
compressor, err = compress.GetCodec(codec)
if err != nil {
return nil, err
}
}
pgwriter := &serializedPageWriter{
sink: sink,
compressor: compressor,
compressLevel: compressionLevel,
metaData: metadata,
rgOrdinal: rowGroupOrdinal,
columnOrdinal: columnChunkOrdinal,
mem: mem,
metaEncryptor: metaEncryptor,
dataEncryptor: dataEncryptor,
dictEncodingStats: make(map[parquet.Encoding]int32),
dataEncodingStats: make(map[parquet.Encoding]int32),
thriftSerializer: thrift.NewThriftSerializer(),
}
if metaEncryptor != nil || dataEncryptor != nil {
pgwriter.initEncryption()
}
return pgwriter, nil
}
// NewPageWriter returns a page writer using either the buffered or serialized implementations
func NewPageWriter(sink utils.WriterTell, codec compress.Compression, compressionLevel int, metadata *metadata.ColumnChunkMetaDataBuilder, rowGroupOrdinal, columnChunkOrdinal int16, mem memory.Allocator, buffered bool, metaEncryptor, dataEncryptor encryption.Encryptor) (PageWriter, error) {
if buffered {
return newBufferedPageWriter(sink, codec, compressionLevel, metadata, rowGroupOrdinal, columnChunkOrdinal, mem, metaEncryptor, dataEncryptor)
}
return createSerializedPageWriter(sink, codec, compressionLevel, metadata, rowGroupOrdinal, columnChunkOrdinal, mem, metaEncryptor, dataEncryptor)
}
func (pw *serializedPageWriter) SetIndexBuilders(colIdxBldr metadata.ColumnIndexBuilder, offsetIdxBldr *metadata.OffsetIndexBuilder) {
pw.columnIndexBuilder = colIdxBldr
pw.offsetIndexBuilder = offsetIdxBldr
}
// Reset allows reusing the pagewriter object instead of creating a new one.
func (pw *serializedPageWriter) Reset(sink utils.WriterTell, codec compress.Compression, compressionLevel int, metadata *metadata.ColumnChunkMetaDataBuilder, rowGroupOrdinal, columnChunkOrdinal int16, metaEncryptor, dataEncryptor encryption.Encryptor) error {
var (
compressor compress.Codec
err error
)
if codec != compress.Codecs.Uncompressed {
compressor, err = compress.GetCodec(codec)
if err != nil {
return err
}
}
pw.sink = sink
pw.compressor = compressor
pw.compressLevel = compressionLevel
pw.metaData = metadata
pw.rgOrdinal = rowGroupOrdinal
pw.columnOrdinal = columnChunkOrdinal
pw.metaEncryptor = metaEncryptor
pw.dataEncryptor = dataEncryptor
pw.dictEncodingStats = make(map[parquet.Encoding]int32)
pw.dataEncodingStats = make(map[parquet.Encoding]int32)
pw.nvalues = 0
pw.dictPageOffset = 0
pw.dataPageOffset = 0
pw.totalUncompressed = 0
pw.totalCompressed = 0
pw.pageOrdinal = 0
if metaEncryptor != nil || dataEncryptor != nil {
pw.initEncryption()
}
pw.columnIndexBuilder, pw.offsetIndexBuilder = nil, nil
return nil
}
func (pw *serializedPageWriter) initEncryption() {
if pw.dataEncryptor != nil {
pw.dataPageAAD = []byte(encryption.CreateModuleAad(pw.dataEncryptor.FileAad(), encryption.DataPageModule, pw.rgOrdinal, pw.columnOrdinal, -1))
}
if pw.metaEncryptor != nil {
pw.dataPageHeaderAAD = []byte(encryption.CreateModuleAad(pw.metaEncryptor.FileAad(), encryption.DataPageHeaderModule, pw.rgOrdinal, pw.columnOrdinal, -1))
}
}
func (pw *serializedPageWriter) updateEncryption(moduleType int8) error {
switch moduleType {
case encryption.ColumnMetaModule:
pw.metaEncryptor.UpdateAad(encryption.CreateModuleAad(pw.metaEncryptor.FileAad(), moduleType, pw.rgOrdinal, pw.columnOrdinal, -1))
case encryption.DataPageModule:
encryption.QuickUpdatePageAad(pw.dataPageAAD, pw.pageOrdinal)
pw.dataEncryptor.UpdateAad(string(pw.dataPageAAD))
case encryption.DataPageHeaderModule:
encryption.QuickUpdatePageAad(pw.dataPageHeaderAAD, pw.pageOrdinal)
pw.metaEncryptor.UpdateAad(string(pw.dataPageHeaderAAD))
case encryption.DictPageHeaderModule:
pw.metaEncryptor.UpdateAad(encryption.CreateModuleAad(pw.metaEncryptor.FileAad(), moduleType, pw.rgOrdinal, pw.columnOrdinal, -1))
case encryption.DictPageModule:
pw.dataEncryptor.UpdateAad(encryption.CreateModuleAad(pw.dataEncryptor.FileAad(), moduleType, pw.rgOrdinal, pw.columnOrdinal, -1))
default:
return xerrors.New("unknown module type in updateencryption")
}
return nil
}
func (pw *serializedPageWriter) Close(hasDict, fallback bool) error {
if pw.metaEncryptor != nil {
pw.updateEncryption(encryption.ColumnMetaModule)
}
chunkInfo := metadata.ChunkMetaInfo{
NumValues: pw.nvalues,
DictPageOffset: pw.dictPageOffset,
IndexPageOffset: -1,
DataPageOffset: pw.dataPageOffset,
CompressedSize: pw.totalCompressed,
UncompressedSize: pw.totalUncompressed,
}
encodingStats := metadata.EncodingStats{
DictEncodingStats: pw.dictEncodingStats,
DataEncodingStats: pw.dataEncodingStats,
}
pw.FinishPageIndexes(0)
pw.metaData.Finish(chunkInfo, hasDict, fallback, encodingStats, pw.metaEncryptor)
_, err := pw.metaData.WriteTo(pw.sink)
return err
}
func (pw *serializedPageWriter) Compress(buf *bytes.Buffer, src []byte) []byte {
maxCompressed := pw.compressor.CompressBound(int64(len(src)))
buf.Grow(int(maxCompressed))
return pw.compressor.EncodeLevel(buf.Bytes(), src, pw.compressLevel)
}
var dataPageV1HeaderPool = sync.Pool{
New: func() interface{} { return format.NewDataPageHeader() },
}
func (pw *serializedPageWriter) setDataPageHeader(pageHdr *format.PageHeader, page *DataPageV1) {
pageHdr.Type = format.PageType_DATA_PAGE
hdr := dataPageV1HeaderPool.Get().(*format.DataPageHeader)
hdr.NumValues = page.nvals
hdr.Encoding = page.encoding
hdr.DefinitionLevelEncoding = page.defLvlEncoding
hdr.RepetitionLevelEncoding = page.repLvlEncoding
if pw.columnIndexBuilder == nil {
hdr.Statistics = page.statistics.ToThrift()
} else {
hdr.Statistics = nil
}
pageHdr.DataPageHeader = hdr
pageHdr.DataPageHeaderV2 = nil
pageHdr.DictionaryPageHeader = nil
}
var dataPageV2HeaderPool = sync.Pool{
New: func() interface{} { return format.NewDataPageHeaderV2() },
}
func (pw *serializedPageWriter) setDataPageV2Header(pageHdr *format.PageHeader, page *DataPageV2) {
pageHdr.Type = format.PageType_DATA_PAGE_V2
hdr := dataPageV2HeaderPool.Get().(*format.DataPageHeaderV2)
hdr.NumValues = page.nvals
hdr.NumNulls = page.nulls
hdr.NumRows = page.nrows
hdr.Encoding = page.encoding
hdr.DefinitionLevelsByteLength = page.defLvlByteLen
hdr.RepetitionLevelsByteLength = page.repLvlByteLen
hdr.IsCompressed = page.compressed
if pw.columnIndexBuilder == nil {
hdr.Statistics = page.statistics.ToThrift()
} else {
hdr.Statistics = nil
}
pageHdr.DataPageHeaderV2 = hdr
pageHdr.DataPageHeader = nil
pageHdr.DictionaryPageHeader = nil
}
func (pw *serializedPageWriter) HasCompressor() bool { return pw.compressor != nil }
func (pw *serializedPageWriter) NumValues() int64 { return pw.nvalues }
func (pw *serializedPageWriter) DictionaryPageOffset() int64 { return pw.dictPageOffset }
func (pw *serializedPageWriter) DataPageoffset() int64 { return pw.dataPageOffset }
func (pw *serializedPageWriter) TotalCompressedSize() int64 { return pw.totalCompressed }
func (pw *serializedPageWriter) TotalUncompressedSize() int64 { return pw.totalUncompressed }
func (pw *serializedPageWriter) WriteDictionaryPage(page *DictionaryPage) (int64, error) {
uncompressed := len(page.Data())
var data []byte
if pw.HasCompressor() {
var buffer bytes.Buffer
data = pw.Compress(&buffer, page.Data())
// data = buffer.Bytes()
} else {
data = page.Data()
}
dictPageHeader := &format.DictionaryPageHeader{
NumValues: page.NumValues(),
Encoding: page.Encoding(),
IsSorted: libthrift.BoolPtr(page.IsSorted()),
}
if pw.dataEncryptor != nil {
pw.updateEncryption(encryption.DictPageModule)
pw.encryptionBuf.Reset()
pw.encryptionBuf.Grow(pw.dataEncryptor.CiphertextSizeDelta() + len(data))
pw.dataEncryptor.Encrypt(&pw.encryptionBuf, data)
data = pw.encryptionBuf.Bytes()
}
pageHdr := pageHeaderPool.Get().(*format.PageHeader)
defer pageHeaderPool.Put(pageHdr)
pageHdr.Type = format.PageType_DICTIONARY_PAGE
pageHdr.UncompressedPageSize = int32(uncompressed)
pageHdr.CompressedPageSize = int32(len(data))
pageHdr.DictionaryPageHeader = dictPageHeader
pageHdr.DataPageHeader = nil
pageHdr.DataPageHeaderV2 = nil
startPos := pw.sink.Tell()
if pw.dictPageOffset == 0 {
pw.dictPageOffset = int64(startPos)
}
if pw.metaEncryptor != nil {
if err := pw.updateEncryption(encryption.DictPageHeaderModule); err != nil {
return 0, err
}
}
headerSize, err := pw.thriftSerializer.Serialize(pageHdr, pw.sink, pw.metaEncryptor)
if err != nil {
return 0, err
}
written, err := pw.sink.Write(data)
if err != nil {
return 0, err
}
written += headerSize
pw.totalUncompressed += int64(uncompressed + headerSize)
pw.totalCompressed = int64(written)
pw.dictEncodingStats[parquet.Encoding(page.encoding)]++
return int64(written), nil
}
var pageHeaderPool = sync.Pool{
New: func() interface{} {
return format.NewPageHeader()
},
}
func (pw *serializedPageWriter) WriteDataPage(page DataPage) (int64, error) {
uncompressed := page.UncompressedSize()
data := page.Data()
if pw.dataEncryptor != nil {
if err := pw.updateEncryption(encryption.DataPageModule); err != nil {
return 0, err
}
pw.encryptionBuf.Reset()
pw.encryptionBuf.Grow(pw.dataEncryptor.CiphertextSizeDelta() + len(data))
pw.dataEncryptor.Encrypt(&pw.encryptionBuf, data)
data = pw.encryptionBuf.Bytes()
}
pageHdr := pageHeaderPool.Get().(*format.PageHeader)
defer pageHeaderPool.Put(pageHdr)
pageHdr.UncompressedPageSize = uncompressed
pageHdr.CompressedPageSize = int32(len(data))
switch dpage := page.(type) {
case *DataPageV1:
pw.setDataPageHeader(pageHdr, dpage)
defer dataPageV1HeaderPool.Put(pageHdr.DataPageHeader)
case *DataPageV2:
pw.setDataPageV2Header(pageHdr, dpage)
defer dataPageV2HeaderPool.Put(pageHdr.DataPageHeaderV2)
default:
return 0, xerrors.New("parquet: unexpected page type")
}
startPos := pw.sink.Tell()
if pw.pageOrdinal == 0 {
pw.dataPageOffset = int64(startPos)
}
if pw.metaEncryptor != nil {
if err := pw.updateEncryption(encryption.DataPageHeaderModule); err != nil {
return 0, err
}
}
headerSize, err := pw.thriftSerializer.Serialize(pageHdr, pw.sink, pw.metaEncryptor)
if err != nil {
return 0, err
}
written, err := pw.sink.Write(data)
if err != nil {
return int64(written), err
}
written += headerSize
// collect page index
if pw.columnIndexBuilder != nil {
stats := page.Statistics()
pw.columnIndexBuilder.AddPage(&stats)
}
if pw.offsetIndexBuilder != nil {
if written > math.MaxInt32 {
return int64(written), fmt.Errorf("parquet: compressed page size %d overflows INT32_MAX", written)
}
if page.FirstRowIndex() == -1 {
return int64(written), fmt.Errorf("parquet: first row index is not set in data page for offset index")
}
// startPos is a relative offset in the buffered mode, it should be
// adjusted via OffsetIndexBuilder.Finish after BufferedPageWriter
// has flushed all data pages
if err = pw.offsetIndexBuilder.AddPage(startPos, page.FirstRowIndex(), int32(written)); err != nil {
return int64(written), err
}
}
pw.totalUncompressed += int64(uncompressed) + int64(headerSize)
pw.totalCompressed += int64(written)
pw.nvalues += int64(page.NumValues())
pw.dataEncodingStats[parquet.Encoding(page.Encoding())]++
pw.pageOrdinal++
return int64(written), nil
}
func (pw *serializedPageWriter) FinishPageIndexes(finalPos int64) {
if pw.columnIndexBuilder != nil {
pw.columnIndexBuilder.Finish()
}
if pw.offsetIndexBuilder != nil {
pw.offsetIndexBuilder.Finish(finalPos)
}
}
type bufferedPageWriter struct {
finalSink utils.WriterTell
inMemSink *encoding.BufferWriter
metadata *metadata.ColumnChunkMetaDataBuilder
pager *serializedPageWriter
hasDictionaryPages bool
}
func newBufferedPageWriter(sink utils.WriterTell, codec compress.Compression, compressionLevel int, metadata *metadata.ColumnChunkMetaDataBuilder, rgOrdinal, columnOrdinal int16, mem memory.Allocator, metaEncryptor, dataEncryptor encryption.Encryptor) (PageWriter, error) {
wr := &bufferedPageWriter{
finalSink: sink,
metadata: metadata,
hasDictionaryPages: false,
inMemSink: encoding.NewBufferWriter(0, mem),
}
pager, err := createSerializedPageWriter(wr.inMemSink, codec, compressionLevel, metadata, rgOrdinal, columnOrdinal, mem, metaEncryptor, dataEncryptor)
if err != nil {
return nil, err
}
wr.pager = pager.(*serializedPageWriter)
return wr, nil
}
func (bw *bufferedPageWriter) SetIndexBuilders(colIdxBldr metadata.ColumnIndexBuilder, offsetIdxBldr *metadata.OffsetIndexBuilder) {
bw.pager.SetIndexBuilders(colIdxBldr, offsetIdxBldr)
}
func (bw *bufferedPageWriter) Reset(sink utils.WriterTell, codec compress.Compression, compressionLevel int, metadata *metadata.ColumnChunkMetaDataBuilder, rgOrdinal, columnOrdinal int16, metaEncryptor, dataEncryptor encryption.Encryptor) error {
bw.finalSink = sink
bw.metadata = metadata
bw.hasDictionaryPages = false
bw.inMemSink.Reset(0)
return bw.pager.Reset(bw.inMemSink, codec, compressionLevel, metadata, rgOrdinal, columnOrdinal, metaEncryptor, dataEncryptor)
}
func (bw *bufferedPageWriter) WriteDictionaryPage(page *DictionaryPage) (int64, error) {
bw.hasDictionaryPages = true
return bw.pager.WriteDictionaryPage(page)
}
func (bw *bufferedPageWriter) Close(hasDict, fallback bool) error {
if bw.pager.metaEncryptor != nil {
bw.pager.updateEncryption(encryption.ColumnMetaModule)
}
position := bw.finalSink.Tell()
dictOffset := int64(0)
if bw.hasDictionaryPages {
dictOffset = bw.pager.DictionaryPageOffset() + position
}
chunkInfo := metadata.ChunkMetaInfo{
NumValues: bw.pager.NumValues(),
DictPageOffset: dictOffset,
IndexPageOffset: -1,
DataPageOffset: bw.pager.DataPageoffset() + position,
CompressedSize: bw.pager.TotalCompressedSize(),
UncompressedSize: bw.pager.TotalUncompressedSize(),
}
encodingStats := metadata.EncodingStats{
DictEncodingStats: bw.pager.dictEncodingStats,
DataEncodingStats: bw.pager.dataEncodingStats,
}
bw.metadata.Finish(chunkInfo, hasDict, fallback, encodingStats, bw.pager.metaEncryptor)
bw.pager.FinishPageIndexes(position)
bw.metadata.WriteTo(bw.inMemSink)
buf := bw.inMemSink.Finish()
defer buf.Release()
_, err := bw.finalSink.Write(buf.Bytes())
return err
}
func (bw *bufferedPageWriter) WriteDataPage(page DataPage) (int64, error) {
return bw.pager.WriteDataPage(page)
}
func (bw *bufferedPageWriter) HasCompressor() bool {
return bw.pager.HasCompressor()
}
func (bw *bufferedPageWriter) Compress(buf *bytes.Buffer, src []byte) []byte {
return bw.pager.Compress(buf, src)
}
|