/
HdfsTable.java
3118 lines (2873 loc) · 136 KB
/
HdfsTable.java
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.
package org.apache.impala.catalog;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.apache.avro.Schema;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.RemoteIterator;
import org.apache.hadoop.hive.common.ValidTxnList;
import org.apache.hadoop.hive.common.ValidWriteIdList;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.IMetaStoreClient;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.ForeignKeysRequest;
import org.apache.hadoop.hive.metastore.api.MetaException;
import org.apache.hadoop.hive.metastore.api.NoSuchObjectException;
import org.apache.hadoop.hive.metastore.api.Partition;
import org.apache.hadoop.hive.metastore.api.PrimaryKeysRequest;
import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
import org.apache.hadoop.hive.metastore.utils.FileUtils;
import org.apache.hadoop.hive.serde.serdeConstants;
import org.apache.impala.analysis.Expr;
import org.apache.impala.analysis.LiteralExpr;
import org.apache.impala.analysis.NullLiteral;
import org.apache.impala.analysis.NumericLiteral;
import org.apache.impala.analysis.PartitionKeyValue;
import org.apache.impala.catalog.HdfsPartition.FileBlock;
import org.apache.impala.catalog.HdfsPartition.FileDescriptor;
import org.apache.impala.common.FileSystemUtil;
import org.apache.impala.common.ImpalaException;
import org.apache.impala.common.Pair;
import org.apache.impala.common.PrintUtils;
import org.apache.impala.compat.MetastoreShim;
import org.apache.impala.fb.FbFileBlock;
import org.apache.impala.hive.common.MutableValidReaderWriteIdList;
import org.apache.impala.hive.common.MutableValidWriteIdList;
import org.apache.impala.service.BackendConfig;
import org.apache.impala.thrift.CatalogLookupStatus;
import org.apache.impala.thrift.CatalogObjectsConstants;
import org.apache.impala.thrift.TAccessLevel;
import org.apache.impala.thrift.TCatalogObject;
import org.apache.impala.thrift.TCatalogObjectType;
import org.apache.impala.thrift.TColumn;
import org.apache.impala.thrift.TGetPartialCatalogObjectRequest;
import org.apache.impala.thrift.TGetPartialCatalogObjectResponse;
import org.apache.impala.thrift.THdfsFileDesc;
import org.apache.impala.thrift.THdfsPartition;
import org.apache.impala.thrift.THdfsTable;
import org.apache.impala.thrift.TNetworkAddress;
import org.apache.impala.thrift.TPartialPartitionInfo;
import org.apache.impala.thrift.TPartitionKeyValue;
import org.apache.impala.thrift.TResultSet;
import org.apache.impala.thrift.TResultSetMetadata;
import org.apache.impala.thrift.TSqlConstraints;
import org.apache.impala.thrift.TTable;
import org.apache.impala.thrift.TTableDescriptor;
import org.apache.impala.thrift.TTableType;
import org.apache.impala.util.AcidUtils;
import org.apache.impala.util.AvroSchemaConverter;
import org.apache.impala.util.AvroSchemaUtils;
import org.apache.impala.util.DebugUtils;
import org.apache.impala.util.FsPermissionCache;
import org.apache.impala.util.FsPermissionChecker;
import org.apache.impala.util.HdfsCachingUtil;
import org.apache.impala.util.ListMap;
import org.apache.impala.util.MetaStoreUtil;
import org.apache.impala.util.TAccessLevelUtil;
import org.apache.impala.util.TResultRowBuilder;
import org.apache.impala.util.ThreadNameAnnotator;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.codahale.metrics.Clock;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Timer;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.base.Stopwatch;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multiset;
import com.google.common.collect.Sets;
/**
* Internal representation of table-related metadata of a file-resident table on a
* Hadoop filesystem. The table data can be accessed through libHDFS (which is more of
* an abstraction over Hadoop's FileSystem class rather than DFS specifically). A
* partitioned table can even span multiple filesystems.
*
* This class is not thread-safe. Clients of this class need to protect against
* concurrent updates using external locking (see CatalogOpExecutor class).
*
* Owned by Catalog instance.
* The partition keys constitute the clustering columns.
*
* Partition metadata are propagated to coordinators in different ways depending on the
* topic update mode.
* 1. In v1 mode (topicMode = full), we only send the partitionIds in the thrift table
* which represents the current list of the partitions. Additionally, for each newly
* added/removed partition we send a THdfsPartition in the same topic update. However,
* coordinators detect the removal of any partitions by absence of an id inside
* partitionIds in the table object.
* 2. In v2 mode (topicMode = minimal), LocalCatalog coordinators only load what they need
* and hence we only send deleted partitionIds. Updated partitions are also treated as a
* special case of deleted partitions by sending the previous partitionId for such
* partitions so that LocalCatalog coordinators invalidate them proactively.
*
* In DDL/REFRESH responses, we are still sending the full thrift tables instead of
* sending incremental updates as in the topic updates. Because catalogd is not aware of
* the table states (partitionIds) of each coordinators. Generating incremental table
* updates requires a base status. This will be improved in IMPALA-9936 and IMPALA-9937.
*/
public class HdfsTable extends Table implements FeFsTable {
// Name of default partition for unpartitioned tables
public static final String DEFAULT_PARTITION_NAME = "";
// Number of times to retry fetching the partitions from the HMS should an error occur.
private final static int NUM_PARTITION_FETCH_RETRIES = 5;
// Table property key for overriding the Impalad-wide --enable_stats_extrapolation
// setting for a specific table. By default, tables do not have the property set and
// rely on the Impalad-wide --enable_stats_extrapolation flag.
public static final String TBL_PROP_ENABLE_STATS_EXTRAPOLATION =
"impala.enable.stats.extrapolation";
// Similar to above: a table property that overwrites --recursively_list_partitions
// for a specific table. This is an escape hatch in case it turns out that someone
// was relying on the previous non-recursive behavior, even though it's known to
// be inconsistent with modern versions of Spark, Hive, etc.
public static final String TBL_PROP_DISABLE_RECURSIVE_LISTING =
"impala.disable.recursive.listing";
// Average memory requirements (in bytes) for storing the metadata of a partition.
private static final long PER_PARTITION_MEM_USAGE_BYTES = 2048;
// Average memory requirements (in bytes) for storing a file descriptor.
private static final long PER_FD_MEM_USAGE_BYTES = 500;
// Average memory requirements (in bytes) for storing a block.
private static final long PER_BLOCK_MEM_USAGE_BYTES = 150;
// Hdfs table specific metrics
public static final String CATALOG_UPDATE_DURATION_METRIC = "catalog-update-duration";
public static final String NUM_PARTITIONS_METRIC = "num-partitions";
public static final String NUM_FILES_METRIC = "num-files";
public static final String NUM_BLOCKS_METRIC = "num-blocks";
public static final String TOTAL_FILE_BYTES_METRIC = "total-file-size-bytes";
public static final String MEMORY_ESTIMATE_METRIC = "memory-estimate-bytes";
public static final String HAS_INCREMENTAL_STATS_METRIC = "has-incremental-stats";
// metrics used to find out the cache hit rate when file-metadata is requested
// for a given ValidWriteIdList
public static final String FILEMETADATA_CACHE_MISS_METRIC = "filemetadata-cache-miss";
public static final String FILEMETADATA_CACHE_HIT_METRIC = "filemetadata-cache-hit";
// metric used to monitor the number of times method loadFileMetadata is called
public static final String NUM_LOAD_FILEMETADATA_METRIC = "num-load-filemetadata";
// Load all partitions time, including fetching all partitions
// from HMS and loading all partitions. The code path is
// MetaStoreUtil.fetchAllPartitions() and HdfsTable.loadAllPartitions()
public static final String LOAD_DURATION_ALL_PARTITIONS =
"load-duration.all-partitions";
// The file metadata loading for all all partitions. This is part of
// LOAD_DURATION_ALL_PARTITIONS
// Code path: loadFileMetadataForPartitions() inside loadAllPartitions()
public static final String LOAD_DURATION_FILE_METADATA_ALL_PARTITIONS =
"load-duration.all-partitions.file-metadata";
// string to indicate NULL. set in load() from table properties
private String nullColumnValue_;
// hive uses this string for NULL partition keys. Set in load().
private String nullPartitionKeyValue_;
// Avro schema of this table if this is an Avro table, otherwise null. Set in load().
private String avroSchema_ = null;
// Set to true if any of the partitions have Avro data.
private boolean hasAvroData_ = false;
// True if this table's metadata is marked as cached. Does not necessarily mean the
// data is cached or that all/any partitions are cached.
private boolean isMarkedCached_ = false;
// Array of sorted maps storing the association between partition values and
// partition ids. There is one sorted map per partition key. It is only populated if
// this table object is stored in ImpaladCatalog.
// Declared as protected to allow third party extension visibility.
protected final List<TreeMap<LiteralExpr, Set<Long>>> partitionValuesMap_ =
new ArrayList<>();
// Array of partition id sets that correspond to partitions with null values
// in the partition keys; one set per partition key. It is not populated if the table is
// stored in the catalog server.
// Declared as protected to allow third party extension visibility.
protected final List<Set<Long>> nullPartitionIds_ = new ArrayList<>();
// Map of partition ids to HdfsPartitions.
// Declared as protected to allow third party extension visibility.
protected final Map<Long, HdfsPartition> partitionMap_ = new HashMap<>();
// Map of partition name to HdfsPartition object. Used for speeding up
// table metadata loading. It is only populated if this table object is stored in
// catalog server.
// Declared as protected to allow third party extension visibility.
protected final Map<String, HdfsPartition> nameToPartitionMap_ = new HashMap<>();
// The partition used as a prototype when creating new partitions during
// insertion. New partitions inherit file format and other settings from
// the prototype.
@VisibleForTesting
HdfsPartition prototypePartition_;
// Empirical estimate (in bytes) of the incremental stats size per column per
// partition.
public static final long STATS_SIZE_PER_COLUMN_BYTES = 200;
// Bi-directional map between an integer index and a unique datanode
// TNetworkAddresses, each of which contains blocks of 1 or more
// files in this table. The network addresses are stored using IP
// address as the host name. Each FileBlock specifies a list of
// indices within this hostIndex_ to specify which nodes contain
// replicas of the block.
private final ListMap<TNetworkAddress> hostIndex_ = new ListMap<TNetworkAddress>();
// True iff this table has incremental stats in any of its partitions.
private boolean hasIncrementalStats_ = false;
// Declared as protected to allow third party extension visibility.
protected HdfsPartitionLocationCompressor partitionLocationCompressor_;
// Base Hdfs directory where files of this table are stored.
// For unpartitioned tables it is simply the path where all files live.
// For partitioned tables it is the root directory
// under which partition dirs are placed.
protected String hdfsBaseDir_;
// List of FieldSchemas that correspond to the non-partition columns. Used when
// describing this table and its partitions to the HMS (e.g. as part of an alter table
// operation), when only non-partition columns are required.
private final List<FieldSchema> nonPartFieldSchemas_ = new ArrayList<>();
// Flag to check if the table schema has been loaded. Used as a precondition
// for setAvroSchema().
private boolean isSchemaLoaded_ = false;
// SQL constraints information for the table. Set in load() method.
private SqlConstraints sqlConstraints_ = new SqlConstraints(new ArrayList<>(),
new ArrayList<>());
// Valid write id list for this table.
// null in the case that this table is not transactional.
protected MutableValidWriteIdList validWriteIds_ = null;
// The last committed compaction id in the table level. It will be sent as a filter to
// retrieve only the latest compaction that is not seen by this instance. This value is
// updated whenever a partition is added to the table so that it is guaranteed to be
// up-to-date.
// -1 means there is no previous compaction event or compaction is not supported.
private long lastCompactionId_ = -1;
// Partitions are marked as "dirty" indicating there are in-progress modifications on
// their metadata. The corresponding partition builder contains the new version of the
// metadata so represents the in-progress modifications. The modifications will be
// finalized in the coming incremental metadata refresh (see updatePartitionsFromHms()
// for more details). This map is only maintained in the catalogd.
private final Map<Long, HdfsPartition.Builder> dirtyPartitions_ = new HashMap<>();
// The max id of all partitions of this table sent to coordinators. Partitions with ids
// larger than this are not known in coordinators.
private long maxSentPartitionId_ = HdfsPartition.INITIAL_PARTITION_ID - 1;
// Dropped partitions since last catalog update. These partitions need to be removed
// in coordinator's cache if there are no updates on them.
private final Set<HdfsPartition> droppedPartitions_ = new HashSet<>();
// pendingVersionNumber indicates a version number allocated to this HdfsTable for a
// ongoing DDL operation. This is mainly used by the topic update thread to skip a
// table from the topic updates if it cannot acquire lock on this table. The topic
// update thread bumps up this to a higher value outside the topic window so that
// the table is considered in the next update. The setCatalogVersion() makes use of this
// to eventually assign the catalogVersion to the table.
private long pendingVersionNumber_ = -1;
// lock protecting access to pendingVersionNumber
private final Object pendingVersionLock_ = new Object();
// this field is used to keep track of the last table version which is seen by the
// topic update thread. It is primarily used to identify distinct locking operations
// to determine if we can skip the table from the topic update.
private long lastVersionSeenByTopicUpdate_ = -1;
// Represents a set of storage-related statistics aggregated at the table or partition
// level.
public final static class FileMetadataStats {
// Nuber of files in a table/partition.
public long numFiles;
// Number of blocks in a table/partition.
public long numBlocks;
// Total size (in bytes) of all files in a table/partition.
public long totalFileBytes;
// Unsets the storage stats to indicate that their values are unknown.
public void unset() {
numFiles = -1;
numBlocks = -1;
totalFileBytes = -1;
}
// Initializes the values of the storage stats.
public void init() {
numFiles = 0;
numBlocks = 0;
totalFileBytes = 0;
}
public void set(FileMetadataStats stats) {
numFiles = stats.numFiles;
numBlocks = stats.numBlocks;
totalFileBytes = stats.totalFileBytes;
}
}
// Table level storage-related statistics. Depending on whether the table is stored in
// the catalog server or the impalad catalog cache, these statistics serve different
// purposes and, hence, are managed differently.
// Table stored in impalad catalog cache:
// - Used in planning.
// - Stats are modified real-time by the operations that modify table metadata
// (e.g. add partition).
// Table stored in the the catalog server:
// - Used for reporting through catalog web UI.
// - Stats are reset whenever the table is loaded (due to a metadata operation) and
// are set when the table is serialized to Thrift.
private final FileMetadataStats fileMetadataStats_ = new FileMetadataStats();
private final static Logger LOG = LoggerFactory.getLogger(HdfsTable.class);
public final static long LOADING_WARNING_TIME_NS = 5000000000L;
public HdfsTable(org.apache.hadoop.hive.metastore.api.Table msTbl,
Db db, String name, String owner) {
super(msTbl, db, name, owner);
partitionLocationCompressor_ =
new HdfsPartitionLocationCompressor(numClusteringCols_);
}
@Override // FeFsTable
public boolean isLocationCacheable() {
return FileSystemUtil.isPathCacheable(new Path(getLocation()));
}
@Override // FeFsTable
public boolean isCacheable() {
if (!isLocationCacheable()) return false;
if (!isMarkedCached() && numClusteringCols_ > 0) {
for (FeFsPartition partition: partitionMap_.values()) {
if (!partition.isCacheable()) {
return false;
}
}
}
return true;
}
/**
* Updates the storage stats of this table based on the partition information.
* This is used only for the frontend tests that do not spawn a separate Catalog
* instance.
*/
public void computeHdfsStatsForTesting() {
Preconditions.checkState(fileMetadataStats_.numFiles == -1
&& fileMetadataStats_.totalFileBytes == -1);
fileMetadataStats_.init();
for (HdfsPartition partition: partitionMap_.values()) {
fileMetadataStats_.numFiles += partition.getNumFileDescriptors();
fileMetadataStats_.totalFileBytes += partition.getSize();
}
}
@Override
public TCatalogObjectType getCatalogObjectType() {
return TCatalogObjectType.TABLE;
}
@Override // FeFsTable
public boolean isMarkedCached() { return isMarkedCached_; }
@Override // FeFsTable
public Collection<? extends PrunablePartition> getPartitions() {
return partitionMap_.values();
}
@Override // FeFsTable
public Map<Long, ? extends PrunablePartition> getPartitionMap() {
return partitionMap_;
}
@Override // FeFsTable
public List<FeFsPartition> loadPartitions(Collection<Long> ids) {
List<FeFsPartition> partitions = Lists.newArrayListWithCapacity(ids.size());
for (Long id : ids) {
HdfsPartition partition = partitionMap_.get(id);
if (partition == null) {
throw new IllegalArgumentException("no such partition id " + id);
}
partitions.add(partition);
}
return partitions;
}
@Override // FeFsTable
public Set<Long> getNullPartitionIds(int i) { return nullPartitionIds_.get(i); }
public HdfsPartitionLocationCompressor getPartitionLocationCompressor() {
return partitionLocationCompressor_;
}
// Returns an unmodifiable set of the partition IDs from partitionMap_.
@Override // FeFsTable
public Set<Long> getPartitionIds() {
return Collections.unmodifiableSet(partitionMap_.keySet());
}
@Override // FeFsTable
public TreeMap<LiteralExpr, Set<Long>> getPartitionValueMap(int i) {
return partitionValuesMap_.get(i);
}
@Override // FeFsTable
public String getNullPartitionKeyValue() {
return nullPartitionKeyValue_; // Set during load.
}
@Override // FeFsTable
public String getLocation() {
return super.getMetaStoreTable().getSd().getLocation();
}
List<FieldSchema> getNonPartitionFieldSchemas() { return nonPartFieldSchemas_; }
// True if Impala has HDFS write permissions on the hdfsBaseDir
@Override
public boolean hasWriteAccessToBaseDir() {
return TAccessLevelUtil.impliesWriteAccess(accessLevel_);
}
/**
* Returns the first location (HDFS path) that Impala does not have WRITE access
* to, or an null if none is found. For an unpartitioned table, this just
* checks the hdfsBaseDir. For a partitioned table it checks the base directory
* as well as all partition directories.
*/
@Override
public String getFirstLocationWithoutWriteAccess() {
if (!hasWriteAccessToBaseDir()) {
return hdfsBaseDir_;
}
for (HdfsPartition partition: partitionMap_.values()) {
if (!TAccessLevelUtil.impliesWriteAccess(partition.getAccessLevel())) {
return partition.getLocation();
}
}
return null;
}
/**
* Marks a partition dirty by registering the partition builder for its new instance.
*/
public void markDirtyPartition(HdfsPartition.Builder partBuilder) {
dirtyPartitions_.put(partBuilder.getOldId(), partBuilder);
}
/**
* Marks partitions dirty by registering the partition builder for its new instance.
*/
public void markDirtyPartitions(Collection<HdfsPartition.Builder> partBuilders) {
for (HdfsPartition.Builder b : partBuilders) {
markDirtyPartition(b);
}
}
/**
* Pick up the partition builder to continue the in-progress modifications.
* The builder is then unregistered so the callers should guarantee that the in-progress
* modifications are finalized (by calling Builder.build() and use the new instance to
* replace the old one).
* @return the builder for given partition's new instance.
*/
public HdfsPartition.Builder pickInprogressPartitionBuilder(HdfsPartition partition) {
return dirtyPartitions_.remove(partition.getId());
}
/**
* @return true if any partitions are dirty.
*/
@Override
public boolean hasInProgressModification() { return !dirtyPartitions_.isEmpty(); }
/**
* Clears all the in-progress modifications by clearing all the partition builders.
*/
@Override
public void resetInProgressModification() { dirtyPartitions_.clear(); }
/**
* Gets the PrunablePartition matching the given partition spec. Returns null if no
* match was found.
*/
public static PrunablePartition getPartition(FeFsTable table,
List<PartitionKeyValue> partitionSpec) {
List<TPartitionKeyValue> partitionKeyValues = new ArrayList<>();
for (PartitionKeyValue kv: partitionSpec) {
Preconditions.checkArgument(kv.isStatic(), "unexpected dynamic partition: %s",
kv);
String value = PartitionKeyValue.getPartitionKeyValueString(
kv.getLiteralValue(), table.getNullPartitionKeyValue());
partitionKeyValues.add(new TPartitionKeyValue(kv.getColName(), value));
}
return Utils.getPartitionFromThriftPartitionSpec(table, partitionKeyValues);
}
/**
* Get the partition by the given list of partValues. Returns null if none of the
* partitions match the given list of partValues.
*/
public HdfsPartition getPartition(List<LiteralExpr> partValues) {
Preconditions.checkNotNull(partValues);
for (HdfsPartition partition: partitionMap_.values()) {
if (partValues.equals(partition.getPartitionValues())) return partition;
}
return null;
}
/**
* Gets the HdfsPartition matching the Thrift version of the partition spec.
* Returns null if no match was found.
*/
public HdfsPartition getPartitionFromThriftPartitionSpec(
List<TPartitionKeyValue> partitionSpec) {
return (HdfsPartition)Utils.getPartitionFromThriftPartitionSpec(this, partitionSpec);
}
/**
* Gets hdfs partitions by the given partition set.
*/
@SuppressWarnings("unchecked")
public List<HdfsPartition> getPartitionsFromPartitionSet(
List<List<TPartitionKeyValue>> partitionSet) {
return (List<HdfsPartition>)Utils.getPartitionsFromPartitionSet(this, partitionSet);
}
/**
* Create columns corresponding to fieldSchemas. Throws a TableLoadingException if the
* metadata is incompatible with what we support.
*/
private void addColumnsFromFieldSchemas(List<FieldSchema> fieldSchemas)
throws TableLoadingException {
int pos = colsByPos_.size();
for (FieldSchema s: fieldSchemas) {
Type type = parseColumnType(s);
// Check if we support partitioning on columns of such a type.
if (pos < numClusteringCols_ && !type.supportsTablePartitioning()) {
throw new TableLoadingException(
String.format("Failed to load metadata for table '%s' because of " +
"unsupported partition-column type '%s' in partition column '%s'",
getFullName(), type.toString(), s.getName()));
}
Column col = new Column(s.getName(), type, s.getComment(), pos);
addColumn(col);
++pos;
}
}
/**
* Adds the synthetic "row__id" column to the table schema. Under "row__id" it adds
* the ACID hidden columns.
* Note that this is the exact opposite of the file schema. In an ACID file, the
* hidden columns are top-level while the user columns are embedded inside a struct
* typed column called "row". We cheat here because this way we don't need to change
* column resolution and everything will work seemlessly. We'll only need to generate
* a different schema path for the columns but that's fairly simple.
* The hidden columns can be retrieved via 'SELECT row__id.* FROM <table>' which is
* similar to Hive's 'SELECT row__id FROM <table>'.
*/
private void addColumnsForFullAcidTable(List<FieldSchema> fieldSchemas)
throws TableLoadingException {
addColumn(AcidUtils.getRowIdColumnType(colsByPos_.size()));
addColumnsFromFieldSchemas(fieldSchemas);
}
private void addVirtualColumns() {
addVirtualColumn(VirtualColumn.INPUT_FILE_NAME);
addVirtualColumn(VirtualColumn.FILE_POSITION);
}
/**
* Clear the partitions of an HdfsTable and the associated metadata.
* Declared as protected to allow third party extension visibility.
*/
protected void resetPartitions() {
partitionMap_.clear();
nameToPartitionMap_.clear();
partitionValuesMap_.clear();
nullPartitionIds_.clear();
if (isStoredInImpaladCatalogCache()) {
// Initialize partitionValuesMap_ and nullPartitionIds_. Also reset column stats.
for (int i = 0; i < numClusteringCols_; ++i) {
getColumns().get(i).getStats().setNumNulls(0);
getColumns().get(i).getStats().setNumDistinctValues(0);
partitionValuesMap_.add(new TreeMap<>());
nullPartitionIds_.add(new HashSet<>());
}
}
fileMetadataStats_.init();
}
/**
* Resets any partition metadata, creates the prototype partition and sets the base
* table directory path as well as the caching info from the HMS table.
*/
public void initializePartitionMetadata(
org.apache.hadoop.hive.metastore.api.Table msTbl) throws CatalogException {
Preconditions.checkNotNull(msTbl);
resetPartitions();
hdfsBaseDir_ = msTbl.getSd().getLocation();
setPrototypePartition(msTbl.getSd());
// We silently ignore cache directives that no longer exist in HDFS, and remove
// non-existing cache directives from the parameters.
isMarkedCached_ = HdfsCachingUtil.validateCacheParams(msTbl.getParameters());
}
/**
* Create HdfsPartition objects corresponding to 'msPartitions' and add them to this
* table's partition list. Any partition metadata will be reset and loaded from
* scratch. For each partition created, we load the block metadata for each data file
* under it. Returns time spent loading the filesystem metadata in nanoseconds.
*
* If there are no partitions in the Hive metadata, a single partition is added with no
* partition keys.
*/
private long loadAllPartitions(IMetaStoreClient client, List<Partition> msPartitions,
org.apache.hadoop.hive.metastore.api.Table msTbl) throws IOException,
CatalogException {
Preconditions.checkNotNull(msTbl);
final Clock clock = Clock.defaultClock();
long startTime = clock.getTick();
initializePartitionMetadata(msTbl);
FsPermissionCache permCache = preloadPermissionsCache(msPartitions);
Path tblLocation = FileSystemUtil.createFullyQualifiedPath(getHdfsBaseDirPath());
accessLevel_ = getAvailableAccessLevel(getFullName(), tblLocation, permCache);
List<HdfsPartition.Builder> partBuilders = new ArrayList<>();
if (msTbl.getPartitionKeysSize() == 0) {
// Legacy -> Iceberg migrated tables might have HMS partitions (HIVE-25894).
if (!IcebergTable.isIcebergTable(msTbl)) {
Preconditions.checkArgument(msPartitions == null || msPartitions.isEmpty());
}
// This table has no partition key, which means it has no declared partitions.
// We model partitions slightly differently to Hive - every file must exist in a
// partition, so add a single partition with no keys which will get all the
// files in the table's root directory.
HdfsPartition.Builder partBuilder = createPartitionBuilder(msTbl.getSd(),
/*msPartition=*/null, permCache);
partBuilder.setIsMarkedCached(isMarkedCached_);
setUnpartitionedTableStats(partBuilder);
partBuilders.add(partBuilder);
} else {
for (Partition msPartition: msPartitions) {
partBuilders.add(createPartitionBuilder(
msPartition.getSd(), msPartition, permCache));
}
}
// Load the file metadata from scratch.
Timer.Context fileMetadataLdContext = getMetrics().getTimer(
HdfsTable.LOAD_DURATION_FILE_METADATA_ALL_PARTITIONS).time();
loadFileMetadataForPartitions(client, partBuilders, /*isRefresh=*/false);
fileMetadataLdContext.stop();
for (HdfsPartition.Builder p : partBuilders) addPartition(p.build());
return clock.getTick() - startTime;
}
/**
* Loads valid txn list from HMS. Re-throws exceptions as CatalogException.
*/
private ValidTxnList loadValidTxns(IMetaStoreClient client) throws CatalogException {
try {
return MetastoreShim.getValidTxns(client);
} catch (TException exception) {
throw new CatalogException(exception.getMessage());
}
}
/**
* Similar to
* {@link #loadFileMetadataForPartitions(IMetaStoreClient, Collection, boolean)}
* but without any injecting the debug actions.
*/
public long loadFileMetadataForPartitions(IMetaStoreClient client,
Collection<HdfsPartition.Builder> partBuilders, boolean isRefresh)
throws CatalogException {
return loadFileMetadataForPartitions(client, partBuilders, isRefresh, null);
}
/**
* Helper method to load the block locations for each partition in 'parts'.
* New file descriptor lists are loaded and the partitions are updated in place.
*
* @param isRefresh whether this is a refresh operation or an initial load. This only
* affects logging.
* @return time in nanoseconds spent in loading file metadata.
*/
private long loadFileMetadataForPartitions(IMetaStoreClient client,
Collection<HdfsPartition.Builder> partBuilders, boolean isRefresh,
String debugActions) throws CatalogException {
getMetrics().getCounter(NUM_LOAD_FILEMETADATA_METRIC).inc();
final Clock clock = Clock.defaultClock();
long startTime = clock.getTick();
//TODO: maybe it'd be better to load the valid txn list in the context of a
// transaction to have consistent valid write ids and valid transaction ids.
// Currently tables are loaded when they are first referenced and stay in catalog
// until certain actions occur (refresh, invalidate, insert, etc.). However,
// Impala doesn't notice when HMS's cleaner removes old transactional directories,
// which might lead to FileNotFound exceptions.
ValidTxnList validTxnList = validWriteIds_ != null ? loadValidTxns(client) : null;
String logPrefix = String.format(
"%s file and block metadata for %s paths for table %s",
isRefresh ? "Refreshing" : "Loading", partBuilders.size(),
getFullName());
// Actually load the partitions.
// TODO(IMPALA-8406): if this fails to load files from one or more partitions, then
// we'll throw an exception here and end up bailing out of whatever catalog operation
// we're in the middle of. This could cause a partial metadata update -- eg we may
// have refreshed the top-level table properties without refreshing the files.
new ParallelFileMetadataLoader(getFileSystem(), partBuilders, validWriteIds_,
validTxnList, Utils.shouldRecursivelyListPartitions(this),
getHostIndex(), debugActions, logPrefix).load();
// TODO(todd): would be good to log a summary of the loading process:
// - how many block locations did we reuse/load individually/load via batch
// - how many partitions did we read metadata for
// - etc...
String partNames = Joiner.on(", ").join(
Iterables.limit(
Iterables.transform(partBuilders, HdfsPartition.Builder::getPartitionName),
3));
if (partBuilders.size() > 3) {
partNames += String.format(", and %s others",
Iterables.size(partBuilders) - 3);
}
long duration = clock.getTick() - startTime;
LOG.info("Loaded file and block metadata for {} partitions: {}. Time taken: {}",
getFullName(), partNames, PrintUtils.printTimeNs(duration));
return duration;
}
/**
* Gets the AccessLevel that is available for Impala for this table based on the
* permissions Impala has on the given path. If the path does not exist, recurses up
* the path until a existing parent directory is found, and inherit access permissions
* from that.
* Always returns READ_WRITE for S3, ADLS, GCS and COS files.
*/
private static TAccessLevel getAvailableAccessLevel(String tableName,
Path location, FsPermissionCache permCache) throws IOException {
Preconditions.checkNotNull(location);
FileSystem fs = location.getFileSystem(CONF);
if (assumeReadWriteAccess(fs)) return TAccessLevel.READ_WRITE;
while (location != null) {
try {
FsPermissionChecker.Permissions perms = permCache.getPermissions(location);
if (perms.canReadAndWrite()) {
return TAccessLevel.READ_WRITE;
} else if (perms.canRead()) {
return TAccessLevel.READ_ONLY;
} else if (perms.canWrite()) {
return TAccessLevel.WRITE_ONLY;
}
return TAccessLevel.NONE;
} catch (FileNotFoundException e) {
location = location.getParent();
}
}
// Should never get here.
throw new NullPointerException("Error determining access level for table " +
tableName + ": no path ancestor exists for path: " + location);
}
/**
* @return true if we assume read-write access for this filesystem for the purpose of
* {@link #getAvailableAccessLevel(String, Path, FsPermissionCache)}
*/
private static boolean assumeReadWriteAccess(FileSystem fs) {
// Avoid calling getPermissions() on file path for S3 files, as that makes a round
// trip to S3. Also, the S3A connector is currently unable to manage S3 permissions,
// so for now it is safe to assume that all files(objects) have READ_WRITE
// permissions, as that's what the S3A connector will always return too.
// TODO: Revisit if the S3A connector is updated to be able to manage S3 object
// permissions. (see HADOOP-13892)
if (FileSystemUtil.isS3AFileSystem(fs)) return true;
// The ADLS connector currently returns ACLs for files in ADLS, but can only map
// them to the ADLS client SPI and not the Hadoop users/groups, causing unexpected
// behavior. So ADLS ACLs are unsupported until the connector is able to map
// permissions to hadoop users/groups (HADOOP-14437).
if (FileSystemUtil.isADLFileSystem(fs)) return true;
if (FileSystemUtil.isABFSFileSystem(fs)) return true;
// GCS IAM permissions don't map to POSIX permissions. GCS connector presents fake
// POSIX file permissions configured by the 'fs.gs.reported.permissions' property.
// So calling getPermissions() on GCS files make no sense. Assume all GCS files have
// READ_WRITE permissions.
if (FileSystemUtil.isGCSFileSystem(fs)) return true;
// COS have different authorization models:
// - Directory permissions are reported as 777.
// - File permissions are reported as 666.
// - File owner is reported as the local current user.
// - File group is also reported as the local current user.
// So calling getPermissions() on COS files make no sense. Assume all COS files have
// READ_WRITE permissions.
if (FileSystemUtil.isCOSFileSystem(fs)) return true;
// In OSS, file owner and group are persisted, but the permissions model is not
// enforced. Authorization occurs at the level of the entire Aliyun account via Aliyun
// Resource Access Management.
// The append operation is not supported.
if (FileSystemUtil.isOSSFileSystem(fs)) return true;
return false;
}
/**
* Creates new HdfsPartition objects to be added to HdfsTable's partition list.
* Partitions may be empty, or may not even exist in the filesystem (a partition's
* location may have been changed to a new path that is about to be created by an
* INSERT). Also loads the file metadata for this partition. Returns new partition
* if successful or null if none was created. If the map of Partition name to eventID
* is not null, it uses it to set the {@code createEventId_} of the
* HdfsPartition.
*
* Throws CatalogException if one of the supplied storage descriptors contains metadata
* that Impala can't understand.
*/
public List<HdfsPartition> createAndLoadPartitions(IMetaStoreClient client,
List<org.apache.hadoop.hive.metastore.api.Partition> msPartitions,
@Nullable Map<String, Long> msPartitionsToEventId) throws CatalogException {
List<HdfsPartition.Builder> addedPartBuilders = new ArrayList<>();
FsPermissionCache permCache = preloadPermissionsCache(msPartitions);
for (org.apache.hadoop.hive.metastore.api.Partition partition: msPartitions) {
HdfsPartition.Builder partBuilder = createPartitionBuilder(partition.getSd(),
partition, permCache);
Preconditions.checkNotNull(partBuilder);
long eventId = -1L;
if (msPartitionsToEventId != null) {
String partName = FeCatalogUtils.getPartitionName(this, partition.getValues());
if (!msPartitionsToEventId.containsKey(partName)) {
LOG.warn("Create event id for partition {} not found. Using -1.", partName);
}
eventId = msPartitionsToEventId.getOrDefault(partName, -1L);
}
partBuilder.setCreateEventId(eventId);
addedPartBuilders.add(partBuilder);
}
loadFileMetadataForPartitions(client, addedPartBuilders, /*isRefresh=*/false);
return addedPartBuilders.stream()
.map(HdfsPartition.Builder::build)
.collect(Collectors.toList());
}
/**
* Creates a new HdfsPartition.Builder from a specified StorageDescriptor and an HMS
* partition object.
*/
private HdfsPartition.Builder createPartitionBuilder(
StorageDescriptor storageDescriptor, Partition msPartition,
FsPermissionCache permCache) throws CatalogException {
return createOrUpdatePartitionBuilder(
storageDescriptor, msPartition, permCache, null);
}
private HdfsPartition.Builder createOrUpdatePartitionBuilder(
StorageDescriptor storageDescriptor,
org.apache.hadoop.hive.metastore.api.Partition msPartition,
FsPermissionCache permCache, HdfsPartition.Builder partBuilder)
throws CatalogException {
if (partBuilder == null) partBuilder = new HdfsPartition.Builder(this);
partBuilder
.setMsPartition(msPartition)
.setFileFormatDescriptor(
HdfsStorageDescriptor.fromStorageDescriptor(this.name_, storageDescriptor));
Path partDirPath = new Path(storageDescriptor.getLocation());
try {
if (msPartition != null) {
// Update the parameters based on validations with hdfs.
boolean isCached = HdfsCachingUtil.validateCacheParams(
partBuilder.getParameters());
partBuilder.setIsMarkedCached(isCached);
}
TAccessLevel accessLevel = getAvailableAccessLevel(getFullName(), partDirPath,
permCache);
partBuilder.setAccessLevel(accessLevel);
partBuilder.checkWellFormed();
if (!TAccessLevelUtil.impliesWriteAccess(accessLevel)) {
// TODO: READ_ONLY isn't exactly correct because the it's possible the
// partition does not have READ permissions either. When we start checking
// whether we can READ from a table, this should be updated to set the
// table's access level to the "lowest" effective level across all
// partitions. That is, if one partition has READ_ONLY and another has
// WRITE_ONLY the table's access level should be NONE.
accessLevel_ = TAccessLevel.READ_ONLY;
}
return partBuilder;
} catch (IOException e) {
throw new CatalogException("Error initializing partition", e);
}
}
/**
* Adds the partition to the HdfsTable. Throws a CatalogException if the partition
* already exists in this table.
*/
public void addPartition(HdfsPartition partition) throws CatalogException {
if (partitionMap_.containsKey(partition.getId())) {
throw new CatalogException(String.format("Partition %s already exists in table %s",
partition.getPartitionName(), getFullName()));
}
addPartitionNoThrow(partition);
}
/**
* Adds the partition to the HdfsTable. Returns false if a partition with the same
* partition id already exists.
*/
public boolean addPartitionNoThrow(HdfsPartition partition) {
if (partitionMap_.containsKey(partition.getId())) return false;
if (partition.getFileFormat() == HdfsFileFormat.AVRO) hasAvroData_ = true;
partitionMap_.put(partition.getId(), partition);
fileMetadataStats_.totalFileBytes += partition.getSize();
fileMetadataStats_.numFiles += partition.getNumFileDescriptors();
updatePartitionMdAndColStats(partition);
lastCompactionId_ = Math.max(lastCompactionId_, partition.getLastCompactionId());
return true;
}
/**
* Updates the HdfsTable's partition metadata, i.e. adds the id to the HdfsTable and
* populates structures used for speeding up partition pruning/lookup. Also updates
* column stats.
* Declared as protected to allow third party extension visibility.
*/
protected void updatePartitionMdAndColStats(HdfsPartition partition) {
if (partition.getPartitionValues().size() != numClusteringCols_) return;
nameToPartitionMap_.put(partition.getPartitionName(), partition);