-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
MetaStoreServerUtils.java
1620 lines (1490 loc) · 64.2 KB
/
MetaStoreServerUtils.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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.hadoop.hive.metastore.utils;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Predicates;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimaps;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.ListUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.common.StatsSetupConst;
import org.apache.hadoop.hive.common.TableName;
import org.apache.hadoop.hive.metastore.ColumnType;
import org.apache.hadoop.hive.metastore.HiveMetaStore;
import org.apache.hadoop.hive.metastore.IMetaStoreClient;
import org.apache.hadoop.hive.metastore.Warehouse;
import org.apache.hadoop.hive.metastore.api.ColumnStatistics;
import org.apache.hadoop.hive.metastore.api.ColumnStatisticsObj;
import org.apache.hadoop.hive.metastore.api.Database;
import org.apache.hadoop.hive.metastore.api.Decimal;
import org.apache.hadoop.hive.metastore.api.EnvironmentContext;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.InvalidObjectException;
import org.apache.hadoop.hive.metastore.api.MetaException;
import org.apache.hadoop.hive.metastore.api.MetastoreException;
import org.apache.hadoop.hive.metastore.api.NoSuchObjectException;
import org.apache.hadoop.hive.metastore.api.Order;
import org.apache.hadoop.hive.metastore.api.Partition;
import org.apache.hadoop.hive.metastore.api.PartitionListComposingSpec;
import org.apache.hadoop.hive.metastore.api.PartitionSpec;
import org.apache.hadoop.hive.metastore.api.PartitionSpecWithSharedSD;
import org.apache.hadoop.hive.metastore.api.PartitionWithoutSD;
import org.apache.hadoop.hive.metastore.api.SerDeInfo;
import org.apache.hadoop.hive.metastore.api.SkewedInfo;
import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
import org.apache.hadoop.hive.metastore.api.Table;
import org.apache.hadoop.hive.metastore.api.hive_metastoreConstants;
import org.apache.hadoop.hive.metastore.columnstats.aggr.ColumnStatsAggregator;
import org.apache.hadoop.hive.metastore.columnstats.aggr.ColumnStatsAggregatorFactory;
import org.apache.hadoop.hive.metastore.columnstats.merge.ColumnStatsMerger;
import org.apache.hadoop.hive.metastore.columnstats.merge.ColumnStatsMergerFactory;
import org.apache.hadoop.hive.metastore.conf.MetastoreConf;
import org.apache.hadoop.hive.metastore.partition.spec.PartitionSpecProxy;
import org.apache.hadoop.hive.metastore.security.DBTokenStore;
import org.apache.hadoop.hive.metastore.security.HadoopThriftAuthBridge;
import org.apache.hadoop.hive.metastore.security.MemoryTokenStore;
import org.apache.hadoop.hive.metastore.security.ZooKeeperTokenStore;
import org.apache.hadoop.security.authorize.DefaultImpersonationProvider;
import org.apache.hadoop.security.authorize.ProxyUsers;
import org.apache.hadoop.util.MachineList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
/**
* Utility methods used by Hive standalone metastore server.
*/
public class MetaStoreServerUtils {
private static final Charset ENCODING = StandardCharsets.UTF_8;
private static final Logger LOG = LoggerFactory.getLogger(MetaStoreServerUtils.class);
public static final String JUNIT_DATABASE_PREFIX = "junit_metastore_db";
/**
* Helper function to transform Nulls to empty strings.
*/
private static final com.google.common.base.Function<String,String> transFormNullsToEmptyString
= new com.google.common.base.Function<String, String>() {
@Override
public String apply(@Nullable String string) {
return org.apache.commons.lang3.StringUtils.defaultString(string);
}
};
private static final String DELEGATION_TOKEN_STORE_CLS = "hive.cluster.delegation.token.store.class";
private static final char DOT = '.';
/**
* We have a need to sanity-check the map before conversion from persisted objects to
* metadata thrift objects because null values in maps will cause a NPE if we send
* across thrift. Pruning is appropriate for most cases except for databases such as
* Oracle where Empty strings are stored as nulls, in which case we need to handle that.
* See HIVE-8485 for motivations for this.
*/
public static Map<String,String> trimMapNulls(
Map<String,String> dnMap, boolean retrieveMapNullsAsEmptyStrings){
if (dnMap == null){
return null;
}
// Must be deterministic order map - see HIVE-8707
// => we use Maps.newLinkedHashMap instead of Maps.newHashMap
if (retrieveMapNullsAsEmptyStrings) {
// convert any nulls present in map values to empty strings - this is done in the case
// of backing dbs like oracle which persist empty strings as nulls.
return Maps.newLinkedHashMap(Maps.transformValues(dnMap, transFormNullsToEmptyString));
} else {
// prune any nulls present in map values - this is the typical case.
return Maps.newLinkedHashMap(Maps.filterValues(dnMap, Predicates.notNull()));
}
}
// Given a list of partStats, this function will give you an aggr stats
public static List<ColumnStatisticsObj> aggrPartitionStats(List<ColumnStatistics> partStats,
String catName, String dbName, String tableName, List<String> partNames, List<String> colNames,
boolean areAllPartsFound, boolean useDensityFunctionForNDVEstimation, double ndvTuner)
throws MetaException {
Map<ColumnStatsAggregator, List<ColStatsObjWithSourceInfo>> colStatsMap =
new HashMap<ColumnStatsAggregator, List<ColStatsObjWithSourceInfo>>();
// Group stats by colName for each partition
Map<String, ColumnStatsAggregator> aliasToAggregator =
new HashMap<String, ColumnStatsAggregator>();
for (ColumnStatistics css : partStats) {
List<ColumnStatisticsObj> objs = css.getStatsObj();
for (ColumnStatisticsObj obj : objs) {
String partName = css.getStatsDesc().getPartName();
if (aliasToAggregator.get(obj.getColName()) == null) {
aliasToAggregator.put(obj.getColName(),
ColumnStatsAggregatorFactory.getColumnStatsAggregator(
obj.getStatsData().getSetField(), useDensityFunctionForNDVEstimation, ndvTuner));
colStatsMap.put(aliasToAggregator.get(obj.getColName()),
new ArrayList<ColStatsObjWithSourceInfo>());
}
colStatsMap.get(aliasToAggregator.get(obj.getColName()))
.add(new ColStatsObjWithSourceInfo(obj, catName, dbName, tableName, partName));
}
}
if (colStatsMap.size() < 1) {
LOG.debug("No stats data found for: tblName= {}, partNames= {}, colNames= {}",
TableName.getQualified(catName, dbName, tableName), partNames, colNames);
return Collections.emptyList();
}
return aggrPartitionStats(colStatsMap, partNames, areAllPartsFound,
useDensityFunctionForNDVEstimation, ndvTuner);
}
public static List<ColumnStatisticsObj> aggrPartitionStats(
Map<ColumnStatsAggregator, List<ColStatsObjWithSourceInfo>> colStatsMap,
final List<String> partNames, final boolean areAllPartsFound,
final boolean useDensityFunctionForNDVEstimation, final double ndvTuner)
throws MetaException {
List<ColumnStatisticsObj> aggrColStatObjs = new ArrayList<ColumnStatisticsObj>();
int numProcessors = Runtime.getRuntime().availableProcessors();
final ExecutorService pool =
Executors.newFixedThreadPool(Math.min(colStatsMap.size(), numProcessors),
new ThreadFactoryBuilder().setDaemon(true).setNameFormat("aggr-col-stats-%d").build());
final List<Future<ColumnStatisticsObj>> futures = Lists.newLinkedList();
LOG.debug("Aggregating column stats. Threads used: {}",
Math.min(colStatsMap.size(), numProcessors));
long start = System.currentTimeMillis();
for (final Map.Entry<ColumnStatsAggregator, List<ColStatsObjWithSourceInfo>> entry : colStatsMap
.entrySet()) {
futures.add(pool.submit(new Callable<ColumnStatisticsObj>() {
@Override
public ColumnStatisticsObj call() throws MetaException {
List<ColStatsObjWithSourceInfo> colStatWithSourceInfo = entry.getValue();
ColumnStatsAggregator aggregator = entry.getKey();
try {
ColumnStatisticsObj statsObj =
aggregator.aggregate(colStatWithSourceInfo, partNames, areAllPartsFound);
return statsObj;
} catch (MetaException e) {
LOG.debug(e.getMessage());
throw e;
}
}
}));
}
pool.shutdown();
if (!futures.isEmpty()) {
for (Future<ColumnStatisticsObj> future : futures) {
try {
if (future.get() != null) {
aggrColStatObjs.add(future.get());
}
} catch (InterruptedException | ExecutionException e) {
LOG.debug(e.getMessage());
pool.shutdownNow();
throw new MetaException(e.toString());
}
}
}
LOG.debug("Time for aggr col stats in seconds: {} Threads used: {}",
((System.currentTimeMillis() - (double) start)) / 1000,
Math.min(colStatsMap.size(), numProcessors));
return aggrColStatObjs;
}
public static double decimalToDouble(Decimal decimal) {
return new BigDecimal(new BigInteger(decimal.getUnscaled()), decimal.getScale()).doubleValue();
}
public static void validatePartitionNameCharacters(List<String> partVals,
Pattern partitionValidationPattern) throws MetaException {
String invalidPartitionVal = getPartitionValWithInvalidCharacter(partVals, partitionValidationPattern);
if (invalidPartitionVal != null) {
throw new MetaException("Partition value '" + invalidPartitionVal +
"' contains a character " + "not matched by whitelist pattern '" +
partitionValidationPattern.toString() + "'. " + "(configure with " +
MetastoreConf.ConfVars.PARTITION_NAME_WHITELIST_PATTERN.getVarname() + ")");
}
}
private static String getPartitionValWithInvalidCharacter(List<String> partVals,
Pattern partitionValidationPattern) {
if (partitionValidationPattern == null) {
return null;
}
for (String partVal : partVals) {
if (!partitionValidationPattern.matcher(partVal).matches()) {
return partVal;
}
}
return null;
}
/**
* Produce a hash for the storage descriptor
* @param sd storage descriptor to hash
* @param md message descriptor to use to generate the hash
* @return the hash as a byte array
*/
public static synchronized byte[] hashStorageDescriptor(StorageDescriptor sd, MessageDigest md) {
// Note all maps and lists have to be absolutely sorted. Otherwise we'll produce different
// results for hashes based on the OS or JVM being used.
md.reset();
// In case cols are null
if (sd.getCols() != null) {
for (FieldSchema fs : sd.getCols()) {
md.update(fs.getName().getBytes(ENCODING));
md.update(fs.getType().getBytes(ENCODING));
if (fs.getComment() != null) {
md.update(fs.getComment().getBytes(ENCODING));
}
}
}
if (sd.getInputFormat() != null) {
md.update(sd.getInputFormat().getBytes(ENCODING));
}
if (sd.getOutputFormat() != null) {
md.update(sd.getOutputFormat().getBytes(ENCODING));
}
md.update(sd.isCompressed() ? "true".getBytes(ENCODING) : "false".getBytes(ENCODING));
md.update(Integer.toString(sd.getNumBuckets()).getBytes(ENCODING));
if (sd.getSerdeInfo() != null) {
SerDeInfo serde = sd.getSerdeInfo();
if (serde.getName() != null) {
md.update(serde.getName().getBytes(ENCODING));
}
if (serde.getSerializationLib() != null) {
md.update(serde.getSerializationLib().getBytes(ENCODING));
}
if (serde.getParameters() != null) {
SortedMap<String, String> params = new TreeMap<>(serde.getParameters());
for (Map.Entry<String, String> param : params.entrySet()) {
md.update(param.getKey().getBytes(ENCODING));
md.update(param.getValue().getBytes(ENCODING));
}
}
}
if (sd.getBucketCols() != null) {
List<String> bucketCols = new ArrayList<>(sd.getBucketCols());
for (String bucket : bucketCols) {
md.update(bucket.getBytes(ENCODING));
}
}
if (sd.getSortCols() != null) {
SortedSet<Order> orders = new TreeSet<>(sd.getSortCols());
for (Order order : orders) {
md.update(order.getCol().getBytes(ENCODING));
md.update(Integer.toString(order.getOrder()).getBytes(ENCODING));
}
}
if (sd.getSkewedInfo() != null) {
SkewedInfo skewed = sd.getSkewedInfo();
if (skewed.getSkewedColNames() != null) {
SortedSet<String> colnames = new TreeSet<>(skewed.getSkewedColNames());
for (String colname : colnames) {
md.update(colname.getBytes(ENCODING));
}
}
if (skewed.getSkewedColValues() != null) {
SortedSet<String> sortedOuterList = new TreeSet<>();
for (List<String> innerList : skewed.getSkewedColValues()) {
SortedSet<String> sortedInnerList = new TreeSet<>(innerList);
sortedOuterList.add(org.apache.commons.lang3.StringUtils.join(sortedInnerList, "."));
}
for (String colval : sortedOuterList) {
md.update(colval.getBytes(ENCODING));
}
}
if (skewed.getSkewedColValueLocationMaps() != null) {
SortedMap<String, String> sortedMap = new TreeMap<>();
for (Map.Entry<List<String>, String> smap : skewed.getSkewedColValueLocationMaps().entrySet()) {
SortedSet<String> sortedKey = new TreeSet<>(smap.getKey());
sortedMap.put(org.apache.commons.lang3.StringUtils.join(sortedKey, "."), smap.getValue());
}
for (Map.Entry<String, String> e : sortedMap.entrySet()) {
md.update(e.getKey().getBytes(ENCODING));
md.update(e.getValue().getBytes(ENCODING));
}
}
md.update(sd.isStoredAsSubDirectories() ? "true".getBytes(ENCODING) : "false".getBytes(ENCODING));
}
return md.digest();
}
/*
* At the Metadata level there are no restrictions on Column Names.
*/
public static boolean validateColumnName(String name) {
return true;
}
/**
* @param partParams
* @return True if the passed Parameters Map contains values for all "Fast Stats".
*/
static boolean containsAllFastStats(Map<String, String> partParams) {
for (String stat : StatsSetupConst.FAST_STATS) {
if (!partParams.containsKey(stat)) {
return false;
}
}
return true;
}
/**
* Determines whether the "fast stats" for the passed partitions are the same.
*
* @param oldPart Old partition to compare.
* @param newPart New partition to compare.
* @return true if the partitions are not null, contain all the "fast stats" and have the same values for these stats, otherwise false.
*/
public static boolean isFastStatsSame(Partition oldPart, Partition newPart) {
// requires to calculate stats if new and old have different fast stats
if ((oldPart != null) && oldPart.isSetParameters() && newPart != null && newPart.isSetParameters()) {
for (String stat : StatsSetupConst.FAST_STATS) {
if (oldPart.getParameters().containsKey(stat) && newPart.getParameters().containsKey(stat)) {
Long oldStat = Long.parseLong(oldPart.getParameters().get(stat));
String newStat = newPart.getParameters().get(stat);
if (newStat == null || !oldStat.equals(Long.parseLong(newStat))) {
return false;
}
} else {
return false;
}
}
return true;
}
return false;
}
/**
* Updates the numFiles and totalSize parameters for the passed Table by querying
* the warehouse if the passed Table does not already have values for these parameters.
* NOTE: This function is rather expensive since it needs to traverse the file system to get all
* the information.
*
* @param newDir if true, the directory was just created and can be assumed to be empty
* @param forceRecompute Recompute stats even if the passed Table already has
* these parameters set
*/
public static void updateTableStatsSlow(Database db, Table tbl, Warehouse wh,
boolean newDir, boolean forceRecompute,
EnvironmentContext environmentContext) throws MetaException {
// DO_NOT_UPDATE_STATS is supposed to be a transient parameter that is only passed via RPC
// We want to avoid this property from being persistent.
//
// NOTE: If this property *is* set as table property we will remove it which is incorrect but
// we can't distinguish between these two cases
//
// This problem was introduced by HIVE-10228. A better approach would be to pass the property
// via the environment context.
Map<String,String> params = tbl.getParameters();
boolean updateStats = true;
if ((params != null) && params.containsKey(StatsSetupConst.DO_NOT_UPDATE_STATS)) {
updateStats = !Boolean.valueOf(params.get(StatsSetupConst.DO_NOT_UPDATE_STATS));
params.remove(StatsSetupConst.DO_NOT_UPDATE_STATS);
}
if (!updateStats || newDir || tbl.getPartitionKeysSize() != 0) {
return;
}
// If stats are already present and forceRecompute isn't set, nothing to do
if (!forceRecompute && params != null && containsAllFastStats(params)) {
return;
}
if (params == null) {
params = new HashMap<>();
tbl.setParameters(params);
}
// The table location already exists and may contain data.
// Let's try to populate those stats that don't require full scan.
boolean populateQuickStats = !((environmentContext != null)
&& environmentContext.isSetProperties()
&& StatsSetupConst.TRUE.equals(environmentContext.getProperties()
.get(StatsSetupConst.DO_NOT_POPULATE_QUICK_STATS)));
if (populateQuickStats) {
// NOTE: wh.getFileStatusesForUnpartitionedTable() can be REALLY slow
List<FileStatus> fileStatus = wh.getFileStatusesForUnpartitionedTable(db, tbl);
LOG.info("Updating table stats for {}", tbl.getTableName());
populateQuickStats(fileStatus, params);
}
LOG.info("Updated size of table {} to {}",
tbl.getTableName(), params.get(StatsSetupConst.TOTAL_SIZE));
if (environmentContext != null
&& environmentContext.isSetProperties()
&& StatsSetupConst.TASK.equals(environmentContext.getProperties().get(
StatsSetupConst.STATS_GENERATED))) {
StatsSetupConst.setBasicStatsState(params, StatsSetupConst.TRUE);
} else {
StatsSetupConst.setBasicStatsState(params, StatsSetupConst.FALSE);
}
}
/** This method is invalid for MM and ACID tables unless fileStatus comes from AcidUtils. */
public static void populateQuickStats(List<FileStatus> fileStatus, Map<String, String> params) {
// Why is this even in metastore?
LOG.trace("Populating quick stats based on {} files", fileStatus.size());
int numFiles = 0;
long tableSize = 0L;
int numErasureCodedFiles = 0;
for (FileStatus status : fileStatus) {
// don't take directories into account for quick stats TODO: wtf?
if (!status.isDir()) {
tableSize += status.getLen();
numFiles += 1;
if (status.isErasureCoded()) {
numErasureCodedFiles++;
}
}
}
params.put(StatsSetupConst.NUM_FILES, Integer.toString(numFiles));
params.put(StatsSetupConst.TOTAL_SIZE, Long.toString(tableSize));
params.put(StatsSetupConst.NUM_ERASURE_CODED_FILES, Integer.toString(numErasureCodedFiles));
}
public static void clearQuickStats(Map<String, String> params) {
params.remove(StatsSetupConst.NUM_FILES);
params.remove(StatsSetupConst.TOTAL_SIZE);
params.remove(StatsSetupConst.NUM_ERASURE_CODED_FILES);
}
/**
* Compare the names, types and comments of two lists of {@link FieldSchema}.
* <p>
* The name of {@link FieldSchema} is compared in the case-insensitive mode
* because all names in Hive are case-insensitive.
*
* @param oldCols old columns
* @param newCols new columns
* @return true if the two columns are the same, false otherwise
*/
public static boolean areSameColumns(List<FieldSchema> oldCols, List<FieldSchema> newCols) {
if (oldCols == newCols) {
return true;
}
if (oldCols == null || newCols == null || oldCols.size() != newCols.size()) {
return false;
}
// We should ignore the case of field names, because some computing engines are case-sensitive, such as Spark.
List<FieldSchema> transformedOldCols = oldCols.stream()
.map(col -> new FieldSchema(col.getName().toLowerCase(), col.getType(), col.getComment()))
.collect(Collectors.toList());
List<FieldSchema> transformedNewCols = newCols.stream()
.map(col -> new FieldSchema(col.getName().toLowerCase(), col.getType(), col.getComment()))
.collect(Collectors.toList());
return ListUtils.isEqualList(transformedOldCols, transformedNewCols);
}
/**
* Returns true if p is a prefix of s.
* <p>
* The compare of {@link FieldSchema} is the same as {@link #areSameColumns(List, List)}.
*/
public static boolean arePrefixColumns(List<FieldSchema> p, List<FieldSchema> s) {
if (p == s) {
return true;
}
if (p == null || s == null || p.size() > s.size()) {
return false;
}
return areSameColumns(p, s.subList(0, p.size()));
}
public static void updateBasicState(EnvironmentContext environmentContext, Map<String,String>
params) {
if (params == null) {
return;
}
if (environmentContext != null
&& environmentContext.isSetProperties()
&& StatsSetupConst.TASK.equals(environmentContext.getProperties().get(
StatsSetupConst.STATS_GENERATED))) {
StatsSetupConst.setBasicStatsState(params, StatsSetupConst.TRUE);
} else {
StatsSetupConst.setBasicStatsState(params, StatsSetupConst.FALSE);
}
}
/**
* Updates the numFiles and totalSize parameters for the passed Partition by querying
* the warehouse if the passed Partition does not already have values for these parameters.
* @param part
* @param wh
* @param madeDir if true, the directory was just created and can be assumed to be empty
* @param forceRecompute Recompute stats even if the passed Partition already has
* these parameters set
* @return true if the stats were updated, false otherwise
*/
public static boolean updatePartitionStatsFast(Partition part, Table tbl, Warehouse wh,
boolean madeDir, boolean forceRecompute, EnvironmentContext environmentContext,
boolean isCreate) throws MetaException {
return updatePartitionStatsFast(new PartitionSpecProxy.SimplePartitionWrapperIterator(part),
tbl, wh, madeDir, forceRecompute, environmentContext, isCreate);
}
/**
* Updates the numFiles and totalSize parameters for the passed Partition by querying
* the warehouse if the passed Partition does not already have values for these parameters.
* @param part
* @param wh
* @param madeDir if true, the directory was just created and can be assumed to be empty
* @param forceRecompute Recompute stats even if the passed Partition already has
* these parameters set
* @return true if the stats were updated, false otherwise
*/
public static boolean updatePartitionStatsFast(PartitionSpecProxy.PartitionIterator part,
Table table, Warehouse wh, boolean madeDir, boolean forceRecompute,
EnvironmentContext environmentContext, boolean isCreate) throws MetaException {
Map<String,String> params = part.getParameters();
if (!forceRecompute && params != null && containsAllFastStats(params)) return false;
if (params == null) {
params = new HashMap<>();
}
if (!isCreate && isTransactionalTable(table.getParameters())) {
// TODO: implement?
LOG.warn("Not updating fast stats for a transactional table " + table.getTableName());
part.setParameters(params);
return true;
}
if (!madeDir) {
// The partition location already existed and may contain data. Lets try to
// populate those statistics that don't require a full scan of the data.
LOG.info("Updating partition stats fast for: {}", part.getTableName());
List<FileStatus> fileStatus = wh.getFileStatusesForLocation(part.getLocation());
// TODO: this is invalid for ACID tables, and we cannot access AcidUtils here.
populateQuickStats(fileStatus, params);
LOG.info("Updated size to {}", params.get(StatsSetupConst.TOTAL_SIZE));
updateBasicState(environmentContext, params);
}
part.setParameters(params);
return true;
}
/*
* This method is to check if the new column list includes all the old columns with same name and
* type. The column comment does not count.
*/
public static boolean columnsIncludedByNameType(List<FieldSchema> oldCols,
List<FieldSchema> newCols) {
if (oldCols.size() > newCols.size()) {
return false;
}
Map<String, String> columnNameTypePairMap = new HashMap<>(newCols.size());
for (FieldSchema newCol : newCols) {
columnNameTypePairMap.put(newCol.getName().toLowerCase(), newCol.getType());
}
for (final FieldSchema oldCol : oldCols) {
if (!columnNameTypePairMap.containsKey(oldCol.getName())
|| !columnNameTypePairMap.get(oldCol.getName()).equalsIgnoreCase(oldCol.getType())) {
return false;
}
}
return true;
}
/** Duplicates AcidUtils; used in a couple places in metastore. */
public static boolean isTransactionalTable(Map<String, String> params) {
String transactionalProp = params.get(hive_metastoreConstants.TABLE_IS_TRANSACTIONAL);
return "true".equalsIgnoreCase(transactionalProp);
}
/**
* create listener instances as per the configuration.
*
* @param clazz Class of the listener
* @param conf configuration object
* @param listenerImplList Implementation class name
* @return instance of the listener
* @throws MetaException if there is any failure instantiating the class
*/
public static <T> List<T> getMetaStoreListeners(Class<T> clazz,
Configuration conf, String listenerImplList) throws MetaException {
List<T> listeners = new ArrayList<T>();
if (StringUtils.isBlank(listenerImplList)) {
return listeners;
}
String[] listenerImpls = listenerImplList.split(",");
for (String listenerImpl : listenerImpls) {
try {
T listener = (T) Class.forName(
listenerImpl.trim(), true, JavaUtils.getClassLoader()).getConstructor(
Configuration.class).newInstance(conf);
listeners.add(listener);
} catch (InvocationTargetException ie) {
LOG.error("Got InvocationTargetException", ie);
throw new MetaException("Failed to instantiate listener named: "+
listenerImpl + ", reason: " + ie.getCause());
} catch (Exception e) {
LOG.error("Got Exception", e);
throw new MetaException("Failed to instantiate listener named: "+
listenerImpl + ", reason: " + e);
}
}
return listeners;
}
public static String validateSkewedColNames(List<String> cols) {
if (CollectionUtils.isEmpty(cols)) {
return null;
}
for (String col : cols) {
if (!validateColumnName(col)) {
return col;
}
}
return null;
}
public static String validateSkewedColNamesSubsetCol(List<String> skewedColNames,
List<FieldSchema> cols) {
if (CollectionUtils.isEmpty(skewedColNames)) {
return null;
}
List<String> colNames = new ArrayList<>(cols.size());
for (FieldSchema fieldSchema : cols) {
colNames.add(fieldSchema.getName());
}
// make a copy
List<String> copySkewedColNames = new ArrayList<>(skewedColNames);
// remove valid columns
copySkewedColNames.removeAll(colNames);
if (copySkewedColNames.isEmpty()) {
return null;
}
return copySkewedColNames.toString();
}
public static boolean partitionNameHasValidCharacters(List<String> partVals,
Pattern partitionValidationPattern) {
return getPartitionValWithInvalidCharacter(partVals, partitionValidationPattern) == null;
}
public static void getMergableCols(ColumnStatistics csNew, Map<String, String> parameters) {
List<ColumnStatisticsObj> list = new ArrayList<>();
for (int index = 0; index < csNew.getStatsObj().size(); index++) {
ColumnStatisticsObj statsObjNew = csNew.getStatsObj().get(index);
// canColumnStatsMerge guarantees that it is accurate before we do merge
if (StatsSetupConst.canColumnStatsMerge(parameters, statsObjNew.getColName())) {
list.add(statsObjNew);
}
// in all the other cases, we can not merge
}
csNew.setStatsObj(list);
}
// this function will merge csOld into csNew.
public static void mergeColStats(ColumnStatistics csNew, ColumnStatistics csOld)
throws InvalidObjectException {
List<ColumnStatisticsObj> list = new ArrayList<>();
if (csNew.getStatsObj().size() != csOld.getStatsObjSize()) {
// Some of the columns' stats are missing
// This implies partition schema has changed. We will merge columns
// present in both, overwrite stats for columns absent in metastore and
// leave alone columns stats missing from stats task. This last case may
// leave stats in stale state. This will be addressed later.
LOG.debug("New ColumnStats size is {}, but old ColumnStats size is {}",
csNew.getStatsObj().size(), csOld.getStatsObjSize());
}
// In this case, we have to find out which columns can be merged.
Map<String, ColumnStatisticsObj> map = new HashMap<>();
// We build a hash map from colName to object for old ColumnStats.
for (ColumnStatisticsObj obj : csOld.getStatsObj()) {
map.put(obj.getColName(), obj);
}
for (int index = 0; index < csNew.getStatsObj().size(); index++) {
ColumnStatisticsObj statsObjNew = csNew.getStatsObj().get(index);
ColumnStatisticsObj statsObjOld = map.get(statsObjNew.getColName());
if (statsObjOld != null) {
// because we already confirm that the stats is accurate
// it is impossible that the column types have been changed while the
// column stats is still accurate.
assert (statsObjNew.getStatsData().getSetField() == statsObjOld.getStatsData()
.getSetField());
// If statsObjOld is found, we can merge.
ColumnStatsMerger merger = ColumnStatsMergerFactory.getColumnStatsMerger(statsObjNew,
statsObjOld);
merger.merge(statsObjNew, statsObjOld);
}
// If statsObjOld is not found, we just use statsObjNew as it is accurate.
list.add(statsObjNew);
}
// in all the other cases, we can not merge
csNew.setStatsObj(list);
}
/**
* Verify if the user is allowed to make DB notification related calls.
* Only the superusers defined in the Hadoop proxy user settings have the permission.
*
* @param user the short user name
* @param conf that contains the proxy user settings
* @return if the user has the permission
*/
public static boolean checkUserHasHostProxyPrivileges(String user, Configuration conf, String ipAddress) {
DefaultImpersonationProvider sip = ProxyUsers.getDefaultImpersonationProvider();
// Just need to initialize the ProxyUsers for the first time, given that the conf will not change on the fly
if (sip == null) {
ProxyUsers.refreshSuperUserGroupsConfiguration(conf);
sip = ProxyUsers.getDefaultImpersonationProvider();
}
Map<String, Collection<String>> proxyHosts = sip.getProxyHosts();
Collection<String> hostEntries = proxyHosts.get(sip.getProxySuperuserIpConfKey(user));
MachineList machineList = new MachineList(hostEntries);
ipAddress = (ipAddress == null) ? StringUtils.EMPTY : ipAddress;
return machineList.includes(ipAddress);
}
public static int startMetaStore() throws Exception {
return startMetaStore(HadoopThriftAuthBridge.getBridge(), null);
}
public static int startMetaStore(final HadoopThriftAuthBridge bridge, Configuration conf) throws
Exception {
int port = findFreePort();
startMetaStore(port, bridge, conf);
return port;
}
public static int startMetaStore(Configuration conf) throws Exception {
return startMetaStore(HadoopThriftAuthBridge.getBridge(), conf);
}
public static void startMetaStore(final int port, final HadoopThriftAuthBridge bridge) throws Exception {
startMetaStore(port, bridge, null);
}
public static void startMetaStore(final int port,
final HadoopThriftAuthBridge bridge, Configuration hiveConf)
throws Exception{
if (hiveConf == null) {
hiveConf = MetastoreConf.newMetastoreConf();
}
final Configuration finalHiveConf = hiveConf;
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
HiveMetaStore.startMetaStore(port, bridge, finalHiveConf);
} catch (Throwable e) {
LOG.error("Metastore Thrift Server threw an exception...",e);
}
}
});
thread.setDaemon(true);
thread.start();
loopUntilHMSReady(port);
}
/**
* A simple connect test to make sure that the metastore is up
* @throws Exception
*/
private static void loopUntilHMSReady(int port) throws Exception {
int retries = 0;
Exception exc;
while (true) {
try {
Socket socket = new Socket();
socket.connect(new InetSocketAddress(port), 5000);
socket.close();
return;
} catch (Exception e) {
if (retries++ > 60) { //give up
exc = e;
break;
}
Thread.sleep(1000);
}
}
// something is preventing metastore from starting
// print the stack from all threads for debugging purposes
LOG.error("Unable to connect to metastore server: " + exc.getMessage());
LOG.info("Printing all thread stack traces for debugging before throwing exception.");
LOG.info(getAllThreadStacksAsString());
throw exc;
}
private static String getAllThreadStacksAsString() {
Map<Thread, StackTraceElement[]> threadStacks = Thread.getAllStackTraces();
StringBuilder sb = new StringBuilder();
for (Map.Entry<Thread, StackTraceElement[]> entry : threadStacks.entrySet()) {
Thread t = entry.getKey();
sb.append(System.lineSeparator());
sb.append("Name: ").append(t.getName()).append(" State: ").append(t.getState());
addStackString(entry.getValue(), sb);
}
return sb.toString();
}
private static void addStackString(StackTraceElement[] stackElems, StringBuilder sb) {
sb.append(System.lineSeparator());
for (StackTraceElement stackElem : stackElems) {
sb.append(stackElem).append(System.lineSeparator());
}
}
/**
* Finds a free port on the machine.
*
* @return
* @throws IOException
*/
public static int findFreePort() throws IOException {
ServerSocket socket= new ServerSocket(0);
int port = socket.getLocalPort();
socket.close();
return port;
}
/**
* Finds a free port on the machine, but allow the
* ability to specify a port number to not use, no matter what.
*/
public static int findFreePortExcepting(int portToExclude) throws IOException {
ServerSocket socket1 = null;
ServerSocket socket2 = null;
try {
socket1 = new ServerSocket(0);
socket2 = new ServerSocket(0);
if (socket1.getLocalPort() != portToExclude) {
return socket1.getLocalPort();
}
// If we're here, then socket1.getLocalPort was the port to exclude
// Since both sockets were open together at a point in time, we're
// guaranteed that socket2.getLocalPort() is not the same.
return socket2.getLocalPort();
} finally {
if (socket1 != null){
socket1.close();
}
if (socket2 != null){
socket2.close();
}
}
}
public static String getIndexTableName(String dbName, String baseTblName, String indexName) {
return dbName + "__" + baseTblName + "_" + indexName + "__";
}
static public String validateTblColumns(List<FieldSchema> cols) {
for (FieldSchema fieldSchema : cols) {
// skip this, as validateColumnName always returns true
/*
if (!validateColumnName(fieldSchema.getName())) {
return "name: " + fieldSchema.getName();
}
*/
String typeError = validateColumnType(fieldSchema.getType());
if (typeError != null) {
return typeError;
}
}
return null;
}
private static String validateColumnType(String type) {
if (type.equals(MetaStoreUtils.TYPE_FROM_DESERIALIZER)) {
return null;
}
int last = 0;
boolean lastAlphaDigit = isValidTypeChar(type.charAt(last));
for (int i = 1; i <= type.length(); i++) {
if (i == type.length()
|| isValidTypeChar(type.charAt(i)) != lastAlphaDigit) {
String token = type.substring(last, i);
last = i;
if (!ColumnType.AllTypes.contains(token)) {
return "type: " + type;
}
break;
}
}
return null;
}
private static boolean isValidTypeChar(char c) {
return Character.isLetterOrDigit(c) || c == '_';
}
// check if stats need to be (re)calculated
public static boolean requireCalStats(Partition oldPart,
Partition newPart, Table tbl,
EnvironmentContext environmentContext) {
if (environmentContext != null
&& environmentContext.isSetProperties()
&& StatsSetupConst.TRUE.equals(environmentContext.getProperties().get(
StatsSetupConst.DO_NOT_UPDATE_STATS))) {
return false;
}
if (MetaStoreUtils.isView(tbl)) {
return false;
}
if (oldPart == null && newPart == null) {
return true;
}
// requires to calculate stats if new partition doesn't have it
if ((newPart == null) || (newPart.getParameters() == null)
|| !containsAllFastStats(newPart.getParameters())) {
return true;
}
if (environmentContext != null && environmentContext.isSetProperties()) {
String statsType = environmentContext.getProperties().get(StatsSetupConst.STATS_GENERATED);
// no matter STATS_GENERATED is USER or TASK, all need to re-calculate the stats: