-
Notifications
You must be signed in to change notification settings - Fork 3.7k
/
Copy pathmetadata.cc
2089 lines (1779 loc) · 76.5 KB
/
metadata.cc
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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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.
#include "parquet/metadata.h"
#include <algorithm>
#include <cinttypes>
#include <memory>
#include <ostream>
#include <random>
#include <sstream>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
#include "arrow/io/memory.h"
#include "arrow/util/key_value_metadata.h"
#include "arrow/util/logging.h"
#include "arrow/util/pcg_random.h"
#include "parquet/encryption/encryption_internal.h"
#include "parquet/encryption/internal_file_decryptor.h"
#include "parquet/exception.h"
#include "parquet/schema.h"
#include "parquet/schema_internal.h"
#include "parquet/size_statistics.h"
#include "parquet/thrift_internal.h"
namespace parquet {
const ApplicationVersion& ApplicationVersion::PARQUET_251_FIXED_VERSION() {
static ApplicationVersion version("parquet-mr", 1, 8, 0);
return version;
}
const ApplicationVersion& ApplicationVersion::PARQUET_816_FIXED_VERSION() {
static ApplicationVersion version("parquet-mr", 1, 2, 9);
return version;
}
const ApplicationVersion& ApplicationVersion::PARQUET_CPP_FIXED_STATS_VERSION() {
static ApplicationVersion version("parquet-cpp", 1, 3, 0);
return version;
}
const ApplicationVersion& ApplicationVersion::PARQUET_MR_FIXED_STATS_VERSION() {
static ApplicationVersion version("parquet-mr", 1, 10, 0);
return version;
}
const ApplicationVersion& ApplicationVersion::PARQUET_CPP_10353_FIXED_VERSION() {
// parquet-cpp versions released prior to Arrow 3.0 would write DataPageV2 pages
// with is_compressed==0 but still write compressed data. (See: ARROW-10353).
// Parquet 1.5.1 had this problem, and after that we switched to the
// application name "parquet-cpp-arrow", so this version is fake.
static ApplicationVersion version("parquet-cpp", 2, 0, 0);
return version;
}
std::string ParquetVersionToString(ParquetVersion::type ver) {
switch (ver) {
case ParquetVersion::PARQUET_1_0:
return "1.0";
ARROW_SUPPRESS_DEPRECATION_WARNING
case ParquetVersion::PARQUET_2_4:
return "2.4";
case ParquetVersion::PARQUET_2_6:
return "2.6";
}
// This should be unreachable
return "UNKNOWN";
}
template <typename DType>
static std::shared_ptr<Statistics> MakeTypedColumnStats(
const format::ColumnMetaData& metadata, const ColumnDescriptor* descr) {
// If ColumnOrder is defined, return max_value and min_value
if (descr->column_order().get_order() == ColumnOrder::TYPE_DEFINED_ORDER) {
return MakeStatistics<DType>(
descr, metadata.statistics.min_value, metadata.statistics.max_value,
metadata.num_values - metadata.statistics.null_count,
metadata.statistics.null_count, metadata.statistics.distinct_count,
metadata.statistics.__isset.max_value && metadata.statistics.__isset.min_value,
metadata.statistics.__isset.null_count,
metadata.statistics.__isset.distinct_count);
}
// Default behavior
return MakeStatistics<DType>(
descr, metadata.statistics.min, metadata.statistics.max,
metadata.num_values - metadata.statistics.null_count,
metadata.statistics.null_count, metadata.statistics.distinct_count,
metadata.statistics.__isset.max && metadata.statistics.__isset.min,
metadata.statistics.__isset.null_count, metadata.statistics.__isset.distinct_count);
}
std::shared_ptr<Statistics> MakeColumnStats(const format::ColumnMetaData& meta_data,
const ColumnDescriptor* descr) {
switch (static_cast<Type::type>(meta_data.type)) {
case Type::BOOLEAN:
return MakeTypedColumnStats<BooleanType>(meta_data, descr);
case Type::INT32:
return MakeTypedColumnStats<Int32Type>(meta_data, descr);
case Type::INT64:
return MakeTypedColumnStats<Int64Type>(meta_data, descr);
case Type::INT96:
return MakeTypedColumnStats<Int96Type>(meta_data, descr);
case Type::DOUBLE:
return MakeTypedColumnStats<DoubleType>(meta_data, descr);
case Type::FLOAT:
return MakeTypedColumnStats<FloatType>(meta_data, descr);
case Type::BYTE_ARRAY:
return MakeTypedColumnStats<ByteArrayType>(meta_data, descr);
case Type::FIXED_LEN_BYTE_ARRAY:
return MakeTypedColumnStats<FLBAType>(meta_data, descr);
case Type::UNDEFINED:
break;
}
throw ParquetException("Can't decode page statistics for selected column type");
}
// Get KeyValueMetadata from parquet Thrift RowGroup or ColumnChunk metadata.
//
// Returns nullptr if the metadata is not set.
template <typename Metadata>
std::shared_ptr<KeyValueMetadata> FromThriftKeyValueMetadata(const Metadata& source) {
std::shared_ptr<KeyValueMetadata> metadata = nullptr;
if (source.__isset.key_value_metadata) {
std::vector<std::string> keys;
std::vector<std::string> values;
keys.reserve(source.key_value_metadata.size());
values.reserve(source.key_value_metadata.size());
for (const auto& it : source.key_value_metadata) {
keys.push_back(it.key);
values.push_back(it.value);
}
metadata = std::make_shared<KeyValueMetadata>(std::move(keys), std::move(values));
}
return metadata;
}
template <typename Metadata>
void ToThriftKeyValueMetadata(const KeyValueMetadata& source, Metadata* metadata) {
std::vector<format::KeyValue> key_value_metadata;
key_value_metadata.reserve(static_cast<size_t>(source.size()));
for (int64_t i = 0; i < source.size(); ++i) {
format::KeyValue kv_pair;
kv_pair.__set_key(source.key(i));
kv_pair.__set_value(source.value(i));
key_value_metadata.emplace_back(std::move(kv_pair));
}
metadata->__set_key_value_metadata(std::move(key_value_metadata));
}
// MetaData Accessor
// ColumnCryptoMetaData
class ColumnCryptoMetaData::ColumnCryptoMetaDataImpl {
public:
explicit ColumnCryptoMetaDataImpl(const format::ColumnCryptoMetaData* crypto_metadata)
: crypto_metadata_(crypto_metadata) {}
bool encrypted_with_footer_key() const {
return crypto_metadata_->__isset.ENCRYPTION_WITH_FOOTER_KEY;
}
bool encrypted_with_column_key() const {
return crypto_metadata_->__isset.ENCRYPTION_WITH_COLUMN_KEY;
}
std::shared_ptr<schema::ColumnPath> path_in_schema() const {
return std::make_shared<schema::ColumnPath>(
crypto_metadata_->ENCRYPTION_WITH_COLUMN_KEY.path_in_schema);
}
const std::string& key_metadata() const {
return crypto_metadata_->ENCRYPTION_WITH_COLUMN_KEY.key_metadata;
}
private:
const format::ColumnCryptoMetaData* crypto_metadata_;
};
std::unique_ptr<ColumnCryptoMetaData> ColumnCryptoMetaData::Make(
const uint8_t* metadata) {
return std::unique_ptr<ColumnCryptoMetaData>(new ColumnCryptoMetaData(metadata));
}
ColumnCryptoMetaData::ColumnCryptoMetaData(const uint8_t* metadata)
: impl_(std::make_unique<ColumnCryptoMetaDataImpl>(
reinterpret_cast<const format::ColumnCryptoMetaData*>(metadata))) {}
ColumnCryptoMetaData::~ColumnCryptoMetaData() = default;
std::shared_ptr<schema::ColumnPath> ColumnCryptoMetaData::path_in_schema() const {
return impl_->path_in_schema();
}
bool ColumnCryptoMetaData::encrypted_with_footer_key() const {
return impl_->encrypted_with_footer_key();
}
const std::string& ColumnCryptoMetaData::key_metadata() const {
return impl_->key_metadata();
}
// ColumnChunk metadata
class ColumnChunkMetaData::ColumnChunkMetaDataImpl {
public:
explicit ColumnChunkMetaDataImpl(
const format::ColumnChunk* column, const ColumnDescriptor* descr,
int16_t row_group_ordinal, int16_t column_ordinal,
const ReaderProperties& properties, const ApplicationVersion* writer_version,
const std::shared_ptr<InternalFileDecryptor>& file_decryptor)
: column_(column),
descr_(descr),
properties_(properties),
writer_version_(writer_version) {
column_metadata_ = &column->meta_data;
if (column->__isset.crypto_metadata) { // column metadata is encrypted
const format::ColumnCryptoMetaData& ccmd = column->crypto_metadata;
if (ccmd.__isset.ENCRYPTION_WITH_COLUMN_KEY) {
if (file_decryptor != nullptr && file_decryptor->properties() != nullptr) {
// should decrypt metadata
std::shared_ptr<schema::ColumnPath> path = std::make_shared<schema::ColumnPath>(
ccmd.ENCRYPTION_WITH_COLUMN_KEY.path_in_schema);
const std::string& key_metadata = ccmd.ENCRYPTION_WITH_COLUMN_KEY.key_metadata;
std::string aad_column_metadata = encryption::CreateModuleAad(
file_decryptor->file_aad(), encryption::kColumnMetaData, row_group_ordinal,
column_ordinal, /*page_ordinal=*/static_cast<int16_t>(-1));
auto decryptor = file_decryptor->GetColumnMetaDecryptor(
path->ToDotString(), key_metadata, aad_column_metadata);
auto len = static_cast<uint32_t>(column->encrypted_column_metadata.size());
ThriftDeserializer deserializer(properties_);
deserializer.DeserializeMessage(
reinterpret_cast<const uint8_t*>(column->encrypted_column_metadata.c_str()),
&len, &decrypted_metadata_, decryptor.get());
column_metadata_ = &decrypted_metadata_;
} else {
throw ParquetException(
"Cannot decrypt ColumnMetadata."
" FileDecryption is not setup correctly");
}
}
}
for (const auto& encoding : column_metadata_->encodings) {
encodings_.push_back(LoadEnumSafe(&encoding));
}
for (const auto& encoding_stats : column_metadata_->encoding_stats) {
encoding_stats_.push_back({LoadEnumSafe(&encoding_stats.page_type),
LoadEnumSafe(&encoding_stats.encoding),
encoding_stats.count});
}
if (column_metadata_->__isset.size_statistics) {
size_statistics_ =
std::make_shared<SizeStatistics>(FromThrift(column_metadata_->size_statistics));
size_statistics_->Validate(descr_);
}
possible_stats_ = nullptr;
InitKeyValueMetadata();
}
bool Equals(const ColumnChunkMetaDataImpl& other) const {
return *column_metadata_ == *other.column_metadata_;
}
// column chunk
inline int64_t file_offset() const { return column_->file_offset; }
inline const std::string& file_path() const { return column_->file_path; }
inline Type::type type() const { return LoadEnumSafe(&column_metadata_->type); }
inline int64_t num_values() const { return column_metadata_->num_values; }
std::shared_ptr<schema::ColumnPath> path_in_schema() {
return std::make_shared<schema::ColumnPath>(column_metadata_->path_in_schema);
}
// Check if statistics are set and are valid
// 1) Must be set in the metadata
// 2) Statistics must not be corrupted
inline bool is_stats_set() const {
DCHECK(writer_version_ != nullptr);
// If the column statistics don't exist or column sort order is unknown
// we cannot use the column stats
if (!column_metadata_->__isset.statistics ||
descr_->sort_order() == SortOrder::UNKNOWN) {
return false;
}
if (possible_stats_ == nullptr) {
possible_stats_ = MakeColumnStats(*column_metadata_, descr_);
}
EncodedStatistics encodedStatistics = possible_stats_->Encode();
return writer_version_->HasCorrectStatistics(type(), encodedStatistics,
descr_->sort_order());
}
inline std::shared_ptr<Statistics> statistics() const {
return is_stats_set() ? possible_stats_ : nullptr;
}
inline std::shared_ptr<SizeStatistics> size_statistics() const {
return size_statistics_;
}
inline Compression::type compression() const {
return LoadEnumSafe(&column_metadata_->codec);
}
const std::vector<Encoding::type>& encodings() const { return encodings_; }
const std::vector<PageEncodingStats>& encoding_stats() const { return encoding_stats_; }
inline std::optional<int64_t> bloom_filter_offset() const {
if (column_metadata_->__isset.bloom_filter_offset) {
return column_metadata_->bloom_filter_offset;
}
return std::nullopt;
}
inline std::optional<int64_t> bloom_filter_length() const {
if (column_metadata_->__isset.bloom_filter_length) {
return column_metadata_->bloom_filter_length;
}
return std::nullopt;
}
inline bool has_dictionary_page() const {
return column_metadata_->__isset.dictionary_page_offset;
}
inline int64_t dictionary_page_offset() const {
return column_metadata_->dictionary_page_offset;
}
inline int64_t data_page_offset() const { return column_metadata_->data_page_offset; }
inline bool has_index_page() const {
return column_metadata_->__isset.index_page_offset;
}
inline int64_t index_page_offset() const { return column_metadata_->index_page_offset; }
inline int64_t total_compressed_size() const {
return column_metadata_->total_compressed_size;
}
inline int64_t total_uncompressed_size() const {
return column_metadata_->total_uncompressed_size;
}
inline std::unique_ptr<ColumnCryptoMetaData> crypto_metadata() const {
if (column_->__isset.crypto_metadata) {
return ColumnCryptoMetaData::Make(
reinterpret_cast<const uint8_t*>(&column_->crypto_metadata));
} else {
return nullptr;
}
}
std::optional<IndexLocation> GetColumnIndexLocation() const {
if (column_->__isset.column_index_offset && column_->__isset.column_index_length) {
return IndexLocation{column_->column_index_offset, column_->column_index_length};
}
return std::nullopt;
}
std::optional<IndexLocation> GetOffsetIndexLocation() const {
if (column_->__isset.offset_index_offset && column_->__isset.offset_index_length) {
return IndexLocation{column_->offset_index_offset, column_->offset_index_length};
}
return std::nullopt;
}
const std::shared_ptr<const KeyValueMetadata>& key_value_metadata() const {
return key_value_metadata_;
}
private:
void InitKeyValueMetadata() {
key_value_metadata_ = FromThriftKeyValueMetadata(*column_metadata_);
}
mutable std::shared_ptr<Statistics> possible_stats_;
std::vector<Encoding::type> encodings_;
std::vector<PageEncodingStats> encoding_stats_;
const format::ColumnChunk* column_;
const format::ColumnMetaData* column_metadata_;
format::ColumnMetaData decrypted_metadata_;
const ColumnDescriptor* descr_;
const ReaderProperties properties_;
const ApplicationVersion* writer_version_;
std::shared_ptr<const KeyValueMetadata> key_value_metadata_;
std::shared_ptr<SizeStatistics> size_statistics_;
};
std::unique_ptr<ColumnChunkMetaData> ColumnChunkMetaData::Make(
const void* metadata, const ColumnDescriptor* descr,
const ReaderProperties& properties, const ApplicationVersion* writer_version,
int16_t row_group_ordinal, int16_t column_ordinal,
std::shared_ptr<InternalFileDecryptor> file_decryptor) {
return std::unique_ptr<ColumnChunkMetaData>(
new ColumnChunkMetaData(metadata, descr, row_group_ordinal, column_ordinal,
properties, writer_version, std::move(file_decryptor)));
}
ColumnChunkMetaData::ColumnChunkMetaData(
const void* metadata, const ColumnDescriptor* descr, int16_t row_group_ordinal,
int16_t column_ordinal, const ReaderProperties& properties,
const ApplicationVersion* writer_version,
std::shared_ptr<InternalFileDecryptor> file_decryptor)
: impl_{new ColumnChunkMetaDataImpl(
reinterpret_cast<const format::ColumnChunk*>(metadata), descr,
row_group_ordinal, column_ordinal, properties, writer_version,
std::move(file_decryptor))} {}
ColumnChunkMetaData::~ColumnChunkMetaData() = default;
// column chunk
int64_t ColumnChunkMetaData::file_offset() const { return impl_->file_offset(); }
const std::string& ColumnChunkMetaData::file_path() const { return impl_->file_path(); }
Type::type ColumnChunkMetaData::type() const { return impl_->type(); }
int64_t ColumnChunkMetaData::num_values() const { return impl_->num_values(); }
std::shared_ptr<schema::ColumnPath> ColumnChunkMetaData::path_in_schema() const {
return impl_->path_in_schema();
}
std::shared_ptr<Statistics> ColumnChunkMetaData::statistics() const {
return impl_->statistics();
}
bool ColumnChunkMetaData::is_stats_set() const { return impl_->is_stats_set(); }
std::shared_ptr<SizeStatistics> ColumnChunkMetaData::size_statistics() const {
return impl_->size_statistics();
}
std::optional<int64_t> ColumnChunkMetaData::bloom_filter_offset() const {
return impl_->bloom_filter_offset();
}
std::optional<int64_t> ColumnChunkMetaData::bloom_filter_length() const {
return impl_->bloom_filter_length();
}
bool ColumnChunkMetaData::has_dictionary_page() const {
return impl_->has_dictionary_page();
}
int64_t ColumnChunkMetaData::dictionary_page_offset() const {
return impl_->dictionary_page_offset();
}
int64_t ColumnChunkMetaData::data_page_offset() const {
return impl_->data_page_offset();
}
bool ColumnChunkMetaData::has_index_page() const { return impl_->has_index_page(); }
int64_t ColumnChunkMetaData::index_page_offset() const {
return impl_->index_page_offset();
}
Compression::type ColumnChunkMetaData::compression() const {
return impl_->compression();
}
bool ColumnChunkMetaData::can_decompress() const {
return ::arrow::util::Codec::IsAvailable(compression());
}
const std::vector<Encoding::type>& ColumnChunkMetaData::encodings() const {
return impl_->encodings();
}
const std::vector<PageEncodingStats>& ColumnChunkMetaData::encoding_stats() const {
return impl_->encoding_stats();
}
int64_t ColumnChunkMetaData::total_uncompressed_size() const {
return impl_->total_uncompressed_size();
}
int64_t ColumnChunkMetaData::total_compressed_size() const {
return impl_->total_compressed_size();
}
std::unique_ptr<ColumnCryptoMetaData> ColumnChunkMetaData::crypto_metadata() const {
return impl_->crypto_metadata();
}
std::optional<IndexLocation> ColumnChunkMetaData::GetColumnIndexLocation() const {
return impl_->GetColumnIndexLocation();
}
std::optional<IndexLocation> ColumnChunkMetaData::GetOffsetIndexLocation() const {
return impl_->GetOffsetIndexLocation();
}
bool ColumnChunkMetaData::Equals(const ColumnChunkMetaData& other) const {
return impl_->Equals(*other.impl_);
}
const std::shared_ptr<const KeyValueMetadata>& ColumnChunkMetaData::key_value_metadata()
const {
return impl_->key_value_metadata();
}
// row-group metadata
class RowGroupMetaData::RowGroupMetaDataImpl {
public:
explicit RowGroupMetaDataImpl(const format::RowGroup* row_group,
const SchemaDescriptor* schema,
const ReaderProperties& properties,
const ApplicationVersion* writer_version,
std::shared_ptr<InternalFileDecryptor> file_decryptor)
: row_group_(row_group),
schema_(schema),
properties_(properties),
writer_version_(writer_version),
file_decryptor_(std::move(file_decryptor)) {
if (ARROW_PREDICT_FALSE(row_group_->columns.size() >
static_cast<size_t>(std::numeric_limits<int>::max()))) {
throw ParquetException("Row group had too many columns: ",
row_group_->columns.size());
}
}
bool Equals(const RowGroupMetaDataImpl& other) const {
return *row_group_ == *other.row_group_;
}
inline int num_columns() const { return static_cast<int>(row_group_->columns.size()); }
inline int64_t num_rows() const { return row_group_->num_rows; }
inline int64_t total_byte_size() const { return row_group_->total_byte_size; }
inline int64_t total_compressed_size() const {
return row_group_->total_compressed_size;
}
inline int64_t file_offset() const { return row_group_->file_offset; }
inline const SchemaDescriptor* schema() const { return schema_; }
std::unique_ptr<ColumnChunkMetaData> ColumnChunk(int i) {
if (i >= 0 && i < num_columns()) {
int16_t row_group_ordinal =
row_group_->__isset.ordinal ? row_group_->ordinal : static_cast<int16_t>(-1);
return ColumnChunkMetaData::Make(&row_group_->columns[i], schema_->Column(i),
properties_, writer_version_, row_group_ordinal, i,
file_decryptor_);
}
throw ParquetException("The file only has ", num_columns(),
" columns, requested metadata for column: ", i);
}
std::vector<SortingColumn> sorting_columns() const {
std::vector<SortingColumn> sorting_columns;
if (!row_group_->__isset.sorting_columns) {
return sorting_columns;
}
sorting_columns.resize(row_group_->sorting_columns.size());
for (size_t i = 0; i < sorting_columns.size(); ++i) {
sorting_columns[i] = FromThrift(row_group_->sorting_columns[i]);
}
return sorting_columns;
}
private:
const format::RowGroup* row_group_;
const SchemaDescriptor* schema_;
const ReaderProperties properties_;
const ApplicationVersion* writer_version_;
std::shared_ptr<InternalFileDecryptor> file_decryptor_;
};
std::unique_ptr<RowGroupMetaData> RowGroupMetaData::Make(
const void* metadata, const SchemaDescriptor* schema,
const ReaderProperties& properties, const ApplicationVersion* writer_version,
std::shared_ptr<InternalFileDecryptor> file_decryptor) {
return std::unique_ptr<parquet::RowGroupMetaData>(new RowGroupMetaData(
metadata, schema, properties, writer_version, std::move(file_decryptor)));
}
RowGroupMetaData::RowGroupMetaData(const void* metadata, const SchemaDescriptor* schema,
const ReaderProperties& properties,
const ApplicationVersion* writer_version,
std::shared_ptr<InternalFileDecryptor> file_decryptor)
: impl_{new RowGroupMetaDataImpl(reinterpret_cast<const format::RowGroup*>(metadata),
schema, properties, writer_version,
std::move(file_decryptor))} {}
RowGroupMetaData::~RowGroupMetaData() = default;
bool RowGroupMetaData::Equals(const RowGroupMetaData& other) const {
return impl_->Equals(*other.impl_);
}
int RowGroupMetaData::num_columns() const { return impl_->num_columns(); }
int64_t RowGroupMetaData::num_rows() const { return impl_->num_rows(); }
int64_t RowGroupMetaData::total_byte_size() const { return impl_->total_byte_size(); }
int64_t RowGroupMetaData::total_compressed_size() const {
return impl_->total_compressed_size();
}
int64_t RowGroupMetaData::file_offset() const { return impl_->file_offset(); }
const SchemaDescriptor* RowGroupMetaData::schema() const { return impl_->schema(); }
std::unique_ptr<ColumnChunkMetaData> RowGroupMetaData::ColumnChunk(int i) const {
return impl_->ColumnChunk(i);
}
bool RowGroupMetaData::can_decompress() const {
int n_columns = num_columns();
for (int i = 0; i < n_columns; i++) {
if (!ColumnChunk(i)->can_decompress()) {
return false;
}
}
return true;
}
std::vector<SortingColumn> RowGroupMetaData::sorting_columns() const {
return impl_->sorting_columns();
}
// Replace string data with random-generated uppercase characters
static void Scrub(std::string* s) {
static ::arrow::random::pcg64 rng;
std::uniform_int_distribution<> caps(65, 90);
for (auto& c : *s) c = caps(rng);
}
// Replace potentially sensitive metadata with random data
static void Scrub(format::FileMetaData* md) {
for (auto& s : md->schema) {
Scrub(&s.name);
}
for (auto& r : md->row_groups) {
for (auto& c : r.columns) {
Scrub(&c.file_path);
if (c.__isset.meta_data) {
auto& m = c.meta_data;
for (auto& p : m.path_in_schema) Scrub(&p);
for (auto& kv : m.key_value_metadata) {
Scrub(&kv.key);
Scrub(&kv.value);
}
Scrub(&m.statistics.max_value);
Scrub(&m.statistics.min_value);
Scrub(&m.statistics.min);
Scrub(&m.statistics.max);
}
if (c.crypto_metadata.__isset.ENCRYPTION_WITH_COLUMN_KEY) {
auto& m = c.crypto_metadata.ENCRYPTION_WITH_COLUMN_KEY;
for (auto& p : m.path_in_schema) Scrub(&p);
Scrub(&m.key_metadata);
}
Scrub(&c.encrypted_column_metadata);
}
}
for (auto& kv : md->key_value_metadata) {
Scrub(&kv.key);
Scrub(&kv.value);
}
Scrub(&md->footer_signing_key_metadata);
}
// file metadata
class FileMetaData::FileMetaDataImpl {
public:
FileMetaDataImpl() = default;
explicit FileMetaDataImpl(
const void* metadata, uint32_t* metadata_len, ReaderProperties properties,
std::shared_ptr<InternalFileDecryptor> file_decryptor = nullptr)
: properties_(std::move(properties)), file_decryptor_(std::move(file_decryptor)) {
metadata_ = std::make_unique<format::FileMetaData>();
auto footer_decryptor =
file_decryptor_ != nullptr ? file_decryptor_->GetFooterDecryptor() : nullptr;
ThriftDeserializer deserializer(properties_);
deserializer.DeserializeMessage(reinterpret_cast<const uint8_t*>(metadata),
metadata_len, metadata_.get(),
footer_decryptor.get());
metadata_len_ = *metadata_len;
if (metadata_->__isset.created_by) {
writer_version_ = ApplicationVersion(metadata_->created_by);
} else {
writer_version_ = ApplicationVersion("unknown 0.0.0");
}
InitSchema();
InitColumnOrders();
InitKeyValueMetadata();
}
bool VerifySignature(const void* signature) {
// verify decryption properties are set
if (file_decryptor_ == nullptr) {
throw ParquetException("Decryption not set properly. cannot verify signature");
}
// serialize the footer
uint8_t* serialized_data;
uint32_t serialized_len = metadata_len_;
ThriftSerializer serializer;
serializer.SerializeToBuffer(metadata_.get(), &serialized_len, &serialized_data);
::arrow::util::span<const uint8_t> serialized_data_span(serialized_data,
serialized_len);
// encrypt with nonce
::arrow::util::span<const uint8_t> nonce(reinterpret_cast<const uint8_t*>(signature),
encryption::kNonceLength);
auto tag = reinterpret_cast<const uint8_t*>(signature) + encryption::kNonceLength;
std::string key = file_decryptor_->GetFooterKey();
std::string aad = encryption::CreateFooterAad(file_decryptor_->file_aad());
auto aes_encryptor = encryption::AesEncryptor::Make(file_decryptor_->algorithm(),
static_cast<int>(key.size()),
true, false /*write_length*/);
std::shared_ptr<Buffer> encrypted_buffer = AllocateBuffer(
file_decryptor_->pool(), aes_encryptor->CiphertextLength(serialized_len));
int32_t encrypted_len = aes_encryptor->SignedFooterEncrypt(
serialized_data_span, str2span(key), str2span(aad), nonce,
encrypted_buffer->mutable_span_as<uint8_t>());
return 0 ==
memcmp(encrypted_buffer->data() + encrypted_len - encryption::kGcmTagLength,
tag, encryption::kGcmTagLength);
}
inline uint32_t size() const { return metadata_len_; }
inline int num_columns() const { return schema_.num_columns(); }
inline int64_t num_rows() const { return metadata_->num_rows; }
inline int num_row_groups() const {
return static_cast<int>(metadata_->row_groups.size());
}
inline int32_t version() const { return metadata_->version; }
inline const std::string& created_by() const { return metadata_->created_by; }
inline int num_schema_elements() const {
return static_cast<int>(metadata_->schema.size());
}
inline bool is_encryption_algorithm_set() const {
return metadata_->__isset.encryption_algorithm;
}
inline EncryptionAlgorithm encryption_algorithm() {
return FromThrift(metadata_->encryption_algorithm);
}
inline const std::string& footer_signing_key_metadata() {
return metadata_->footer_signing_key_metadata;
}
const ApplicationVersion& writer_version() const { return writer_version_; }
void WriteTo(::arrow::io::OutputStream* dst,
const std::shared_ptr<Encryptor>& encryptor) const {
ThriftSerializer serializer;
// Only in encrypted files with plaintext footers the
// encryption_algorithm is set in footer
if (is_encryption_algorithm_set()) {
uint8_t* serialized_data;
uint32_t serialized_len;
serializer.SerializeToBuffer(metadata_.get(), &serialized_len, &serialized_data);
::arrow::util::span<const uint8_t> serialized_data_span(serialized_data,
serialized_len);
// encrypt the footer key
std::vector<uint8_t> encrypted_data(encryptor->CiphertextLength(serialized_len));
int32_t encrypted_len = encryptor->Encrypt(serialized_data_span, encrypted_data);
// write unencrypted footer
PARQUET_THROW_NOT_OK(dst->Write(serialized_data, serialized_len));
// Write signature (nonce and tag)
PARQUET_THROW_NOT_OK(
dst->Write(encrypted_data.data() + 4, encryption::kNonceLength));
PARQUET_THROW_NOT_OK(
dst->Write(encrypted_data.data() + encrypted_len - encryption::kGcmTagLength,
encryption::kGcmTagLength));
} else { // either plaintext file (when encryptor is null)
// or encrypted file with encrypted footer
serializer.Serialize(metadata_.get(), dst, encryptor.get());
}
}
std::unique_ptr<RowGroupMetaData> RowGroup(int i) {
if (!(i >= 0 && i < num_row_groups())) {
std::stringstream ss;
ss << "The file only has " << num_row_groups()
<< " row groups, requested metadata for row group: " << i;
throw ParquetException(ss.str());
}
return RowGroupMetaData::Make(&metadata_->row_groups[i], &schema_, properties_,
&writer_version_, file_decryptor_);
}
bool Equals(const FileMetaDataImpl& other) const {
return *metadata_ == *other.metadata_;
}
const SchemaDescriptor* schema() const { return &schema_; }
const std::shared_ptr<const KeyValueMetadata>& key_value_metadata() const {
return key_value_metadata_;
}
void set_file_path(const std::string& path) {
for (format::RowGroup& row_group : metadata_->row_groups) {
for (format::ColumnChunk& chunk : row_group.columns) {
chunk.__set_file_path(path);
}
}
}
format::RowGroup& row_group(int i) {
if (!(i >= 0 && i < num_row_groups())) {
std::stringstream ss;
ss << "The file only has " << num_row_groups()
<< " row groups, requested metadata for row group: " << i;
throw ParquetException(ss.str());
}
return metadata_->row_groups[i];
}
void AppendRowGroups(FileMetaDataImpl* other) {
std::ostringstream diff_output;
if (!schema()->Equals(*other->schema(), &diff_output)) {
auto msg = "AppendRowGroups requires equal schemas.\n" + diff_output.str();
throw ParquetException(msg);
}
// ARROW-13654: `other` may point to self, be careful not to enter an infinite loop
const int n = other->num_row_groups();
// ARROW-16613: do not use reserve() as that may suppress overallocation
// and incur O(n²) behavior on repeated calls to AppendRowGroups().
// (see https://en.cppreference.com/w/cpp/container/vector/reserve
// about inappropriate uses of reserve()).
const auto start = metadata_->row_groups.size();
metadata_->row_groups.resize(start + n);
for (int i = 0; i < n; i++) {
metadata_->row_groups[start + i] = other->row_group(i);
metadata_->num_rows += metadata_->row_groups[start + i].num_rows;
}
}
std::shared_ptr<FileMetaData> Subset(const std::vector<int>& row_groups) {
for (int i : row_groups) {
if (i < num_row_groups()) continue;
throw ParquetException(
"The file only has ", num_row_groups(),
" row groups, but requested a subset including row group: ", i);
}
std::shared_ptr<FileMetaData> out(new FileMetaData());
out->impl_ = std::make_unique<FileMetaDataImpl>();
out->impl_->metadata_ = std::make_unique<format::FileMetaData>();
auto metadata = out->impl_->metadata_.get();
metadata->version = metadata_->version;
metadata->schema = metadata_->schema;
metadata->row_groups.resize(row_groups.size());
int i = 0;
for (int selected_index : row_groups) {
metadata->num_rows += row_group(selected_index).num_rows;
metadata->row_groups[i++] = row_group(selected_index);
}
metadata->key_value_metadata = metadata_->key_value_metadata;
metadata->created_by = metadata_->created_by;
metadata->column_orders = metadata_->column_orders;
metadata->encryption_algorithm = metadata_->encryption_algorithm;
metadata->footer_signing_key_metadata = metadata_->footer_signing_key_metadata;
metadata->__isset = metadata_->__isset;
out->impl_->schema_ = schema_;
out->impl_->writer_version_ = writer_version_;
out->impl_->key_value_metadata_ = key_value_metadata_;
out->impl_->file_decryptor_ = file_decryptor_;
return out;
}
std::string SerializeUnencrypted(bool scrub, bool debug) const {
auto md = *metadata_;
if (scrub) Scrub(&md);
if (debug) {
std::ostringstream ss;
md.printTo(ss);
return ss.str();
} else {
ThriftSerializer serializer;
std::string out;
serializer.SerializeToString(&md, &out);
return out;
}
}
void set_file_decryptor(std::shared_ptr<InternalFileDecryptor> file_decryptor) {
file_decryptor_ = std::move(file_decryptor);
}
const std::shared_ptr<InternalFileDecryptor>& file_decryptor() const {
return file_decryptor_;
}
private:
friend FileMetaDataBuilder;
uint32_t metadata_len_ = 0;
std::unique_ptr<format::FileMetaData> metadata_;
SchemaDescriptor schema_;
ApplicationVersion writer_version_;
std::shared_ptr<const KeyValueMetadata> key_value_metadata_;
const ReaderProperties properties_;
std::shared_ptr<InternalFileDecryptor> file_decryptor_;
void InitSchema() {
if (metadata_->schema.empty()) {
throw ParquetException("Empty file schema (no root)");
}
schema_.Init(schema::Unflatten(&metadata_->schema[0],
static_cast<int>(metadata_->schema.size())));
}
void InitColumnOrders() {
// update ColumnOrder
std::vector<parquet::ColumnOrder> column_orders;
if (metadata_->__isset.column_orders) {
column_orders.reserve(metadata_->column_orders.size());
for (auto& column_order : metadata_->column_orders) {
if (column_order.__isset.TYPE_ORDER) {
column_orders.push_back(ColumnOrder::type_defined_);
} else {
column_orders.push_back(ColumnOrder::undefined_);
}
}
} else {
column_orders.resize(schema_.num_columns(), ColumnOrder::undefined_);
}
schema_.updateColumnOrders(column_orders);
}
void InitKeyValueMetadata() {
key_value_metadata_ = FromThriftKeyValueMetadata(*metadata_);
}
};
std::shared_ptr<FileMetaData> FileMetaData::Make(
const void* metadata, uint32_t* metadata_len, const ReaderProperties& properties,
std::shared_ptr<InternalFileDecryptor> file_decryptor) {
// This FileMetaData ctor is private, not compatible with std::make_shared
return std::shared_ptr<FileMetaData>(
new FileMetaData(metadata, metadata_len, properties, std::move(file_decryptor)));
}
FileMetaData::FileMetaData(const void* metadata, uint32_t* metadata_len,
const ReaderProperties& properties,
std::shared_ptr<InternalFileDecryptor> file_decryptor)
: impl_(new FileMetaDataImpl(metadata, metadata_len, properties,
std::move(file_decryptor))) {}
FileMetaData::FileMetaData() : impl_(new FileMetaDataImpl()) {}
FileMetaData::~FileMetaData() = default;
bool FileMetaData::Equals(const FileMetaData& other) const {
return impl_->Equals(*other.impl_);
}
std::unique_ptr<RowGroupMetaData> FileMetaData::RowGroup(int i) const {
return impl_->RowGroup(i);
}