/
HMSHandler.java
10769 lines (9826 loc) · 425 KB
/
HMSHandler.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.hadoop.hive.metastore;
import com.codahale.metrics.Counter;
import com.facebook.fb303.FacebookBase;
import com.facebook.fb303.fb_status;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.Striped;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.apache.commons.collections.CollectionUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.common.AcidConstants;
import org.apache.hadoop.hive.common.AcidMetaDataFile;
import org.apache.hadoop.hive.common.AcidMetaDataFile.DataFormat;
import org.apache.hadoop.hive.common.StatsSetupConst;
import org.apache.hadoop.hive.common.TableName;
import org.apache.hadoop.hive.common.ValidReaderWriteIdList;
import org.apache.hadoop.hive.common.ValidWriteIdList;
import org.apache.hadoop.hive.common.repl.ReplConst;
import org.apache.hadoop.hive.metastore.api.*;
import org.apache.hadoop.hive.metastore.api.Package;
import org.apache.hadoop.hive.metastore.conf.MetastoreConf;
import org.apache.hadoop.hive.metastore.conf.MetastoreConf.ConfVars;
import org.apache.hadoop.hive.metastore.dataconnector.DataConnectorProviderFactory;
import org.apache.hadoop.hive.metastore.events.*;
import org.apache.hadoop.hive.metastore.messaging.EventMessage;
import org.apache.hadoop.hive.metastore.messaging.EventMessage.EventType;
import org.apache.hadoop.hive.metastore.metrics.Metrics;
import org.apache.hadoop.hive.metastore.metrics.MetricsConstants;
import org.apache.hadoop.hive.metastore.metrics.PerfLogger;
import org.apache.hadoop.hive.metastore.partition.spec.PartitionSpecProxy;
import org.apache.hadoop.hive.metastore.txn.CompactionInfo;
import org.apache.hadoop.hive.metastore.txn.CompactionMetricsDataConverter;
import org.apache.hadoop.hive.metastore.txn.TxnStore;
import org.apache.hadoop.hive.metastore.txn.TxnUtils;
import org.apache.hadoop.hive.metastore.utils.FileUtils;
import org.apache.hadoop.hive.metastore.utils.FilterUtils;
import org.apache.hadoop.hive.metastore.utils.HdfsUtils;
import org.apache.hadoop.hive.metastore.utils.JavaUtils;
import org.apache.hadoop.hive.metastore.utils.MetaStoreServerUtils;
import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
import org.apache.hadoop.hive.metastore.utils.MetastoreVersionInfo;
import org.apache.hadoop.hive.metastore.utils.SecurityUtils;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.util.ReflectionUtils;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.jdo.JDOException;
import java.io.IOException;
import java.lang.reflect.UndeclaredThrowableException;
import java.nio.ByteBuffer;
import java.security.PrivilegedExceptionAction;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.PriorityQueue;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.regex.Pattern;
import static org.apache.commons.lang3.StringUtils.isBlank;
import static org.apache.commons.lang3.StringUtils.join;
import static org.apache.hadoop.hive.common.AcidConstants.SOFT_DELETE_PATH_SUFFIX;
import static org.apache.hadoop.hive.common.AcidConstants.SOFT_DELETE_TABLE;
import static org.apache.hadoop.hive.common.AcidConstants.DELTA_DIGITS;
import static org.apache.hadoop.hive.common.repl.ReplConst.REPL_TARGET_DATABASE_PROPERTY;
import static org.apache.hadoop.hive.metastore.HiveMetaStoreClient.RENAME_PARTITION_MAKE_COPY;
import static org.apache.hadoop.hive.metastore.HiveMetaStoreClient.TRUNCATE_SKIP_DATA_DELETION;
import static org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.TABLE_IS_CTAS;
import static org.apache.hadoop.hive.metastore.ExceptionHandler.handleException;
import static org.apache.hadoop.hive.metastore.ExceptionHandler.newMetaException;
import static org.apache.hadoop.hive.metastore.ExceptionHandler.rethrowException;
import static org.apache.hadoop.hive.metastore.ExceptionHandler.throwMetaException;
import static org.apache.hadoop.hive.metastore.Warehouse.DEFAULT_CATALOG_NAME;
import static org.apache.hadoop.hive.metastore.Warehouse.DEFAULT_DATABASE_COMMENT;
import static org.apache.hadoop.hive.metastore.Warehouse.DEFAULT_DATABASE_NAME;
import static org.apache.hadoop.hive.metastore.Warehouse.getCatalogQualifiedTableName;
import static org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.TABLE_IS_CTLT;
import static org.apache.hadoop.hive.metastore.utils.MetaStoreUtils.CAT_NAME;
import static org.apache.hadoop.hive.metastore.utils.MetaStoreUtils.DB_NAME;
import static org.apache.hadoop.hive.metastore.utils.MetaStoreUtils.getDefaultCatalog;
import static org.apache.hadoop.hive.metastore.utils.MetaStoreUtils.parseDbName;
import static org.apache.hadoop.hive.metastore.utils.MetaStoreUtils.prependCatalogToDbName;
import static org.apache.hadoop.hive.metastore.utils.MetaStoreUtils.prependNotNullCatToDbName;
/**
* Default handler for all Hive Metastore methods. Implements methods defined in hive_metastore.thrift.
*/
public class HMSHandler extends FacebookBase implements IHMSHandler {
public static final Logger LOG = LoggerFactory.getLogger(HMSHandler.class);
private final Configuration conf; // stores datastore (jpox) properties,
// right now they come from jpox.properties
// Flag to control that always threads are initialized only once
// instead of multiple times
private final static AtomicBoolean alwaysThreadsInitialized =
new AtomicBoolean(false);
private static String currentUrl;
private FileMetadataManager fileMetadataManager;
private PartitionExpressionProxy expressionProxy;
private StorageSchemaReader storageSchemaReader;
private IMetaStoreMetadataTransformer transformer;
private static DataConnectorProviderFactory dataconnectorFactory = null;
// Variables for metrics
// Package visible so that HMSMetricsListener can see them.
static AtomicInteger databaseCount, tableCount, partCount;
public static final String PARTITION_NUMBER_EXCEED_LIMIT_MSG =
"Number of partitions scanned (=%d) on table '%s' exceeds limit (=%d). This is controlled on the metastore server by %s.";
// Used for testing to simulate method timeout.
@VisibleForTesting
static boolean testTimeoutEnabled = false;
@VisibleForTesting
static long testTimeoutValue = -1;
public static final String ADMIN = "admin";
public static final String PUBLIC = "public";
static final String NO_FILTER_STRING = "";
static final int UNLIMITED_MAX_PARTITIONS = -1;
private Warehouse wh; // hdfs warehouse
private static Striped<Lock> tablelocks;
public static RawStore getRawStore() {
return HMSHandlerContext.getRawStore().orElse(null);
}
static void cleanupHandlerContext() {
try {
HMSHandlerContext.getRawStore().ifPresent(rs -> {
logAndAudit("Cleaning up thread local RawStore...");
rs.shutdown();
});
} finally {
HMSHandlerContext.getHMSHandler().ifPresent(handler -> {
handler.notifyMetaListenersOnShutDown();
});
HMSHandlerContext.clear();
logAndAudit("Done cleaning up thread local RawStore");
}
}
private static ExecutorService threadPool;
static final Logger auditLog = LoggerFactory.getLogger(
HiveMetaStore.class.getName() + ".audit");
private static void logAuditEvent(String cmd) {
if (cmd == null) {
return;
}
UserGroupInformation ugi;
try {
ugi = SecurityUtils.getUGI();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
String address = getIPAddress();
if (address == null) {
address = "unknown-ip-addr";
}
auditLog.info("ugi={} ip={} cmd={} ", ugi.getUserName(), address, cmd);
}
public static String getIPAddress() {
if (HiveMetaStore.useSasl) {
if (HiveMetaStore.saslServer != null && HiveMetaStore.saslServer.getRemoteAddress() != null) {
return HiveMetaStore.saslServer.getRemoteAddress().getHostAddress();
}
} else {
// if kerberos is not enabled
return getThreadLocalIpAddress();
}
return null;
}
/**
* Internal function to notify listeners for meta config change events
*/
private void notifyMetaListeners(String key, String oldValue, String newValue) throws MetaException {
for (MetaStoreEventListener listener : listeners) {
listener.onConfigChange(new ConfigChangeEvent(this, key, oldValue, newValue));
}
if (transactionalListeners.size() > 0) {
// All the fields of this event are final, so no reason to create a new one for each
// listener
ConfigChangeEvent cce = new ConfigChangeEvent(this, key, oldValue, newValue);
for (MetaStoreEventListener transactionalListener : transactionalListeners) {
transactionalListener.onConfigChange(cce);
}
}
}
/**
* Internal function to notify listeners to revert back to old values of keys
* that were modified during setMetaConf. This would get called from HiveMetaStore#cleanupHandlerContext
*/
private void notifyMetaListenersOnShutDown() {
try {
Map<String, String> modifiedConf = HMSHandlerContext.getModifiedConfig();
Configuration conf = HMSHandlerContext.getConfiguration()
.orElseThrow(() -> new MetaException("Unexpected: modifiedConf is non-null but conf is null"));
// Notify listeners of the changed value
for (Map.Entry<String, String> entry : modifiedConf.entrySet()) {
String key = entry.getKey();
// curr value becomes old and vice-versa
String currVal = entry.getValue();
String oldVal = conf.get(key);
if (!Objects.equals(oldVal, currVal)) {
notifyMetaListeners(key, oldVal, currVal);
}
}
logAndAudit("Meta listeners shutdown notification completed.");
} catch (MetaException e) {
LOG.error("Failed to notify meta listeners on shutdown: ", e);
}
}
static void setThreadLocalIpAddress(String ipAddress) {
HMSHandlerContext.setIpAddress(ipAddress);
}
// This will return null if the metastore is not being accessed from a metastore Thrift server,
// or if the TTransport being used to connect is not an instance of TSocket, or if kereberos
// is used
static String getThreadLocalIpAddress() {
return HMSHandlerContext.getIpAddress().orElse(null);
}
// Make it possible for tests to check that the right type of PartitionExpressionProxy was
// instantiated.
@VisibleForTesting
PartitionExpressionProxy getExpressionProxy() {
return expressionProxy;
}
public HMSHandler(String name, Configuration conf) {
super(name);
this.conf = conf;
isInTest = MetastoreConf.getBoolVar(this.conf, ConfVars.HIVE_IN_TEST);
if (threadPool == null) {
synchronized (HMSHandler.class) {
if (threadPool == null) {
int numThreads = MetastoreConf.getIntVar(conf, ConfVars.FS_HANDLER_THREADS_COUNT);
threadPool = Executors.newFixedThreadPool(numThreads,
new ThreadFactoryBuilder().setDaemon(true).setNameFormat("HMSHandler #%d").build());
int numTableLocks = MetastoreConf.getIntVar(conf, ConfVars.METASTORE_NUM_STRIPED_TABLE_LOCKS);
tablelocks = Striped.lock(numTableLocks);
}
}
}
}
/**
* Use {@link #getConf()} instead.
* @return Configuration object
*/
@Deprecated
public Configuration getHiveConf() {
return conf;
}
private AlterHandler alterHandler;
private List<MetaStorePreEventListener> preListeners;
private List<MetaStoreEventListener> listeners;
private List<TransactionalMetaStoreEventListener> transactionalListeners;
private List<MetaStoreEndFunctionListener> endFunctionListeners;
private List<MetaStoreInitListener> initListeners;
private MetaStoreFilterHook filterHook;
private boolean isServerFilterEnabled = false;
private Pattern partitionValidationPattern;
private final boolean isInTest;
@Override
public List<TransactionalMetaStoreEventListener> getTransactionalListeners() {
return transactionalListeners;
}
@Override
public List<MetaStoreEventListener> getListeners() {
return listeners;
}
@Override
public void init() throws MetaException {
initListeners = MetaStoreServerUtils.getMetaStoreListeners(
MetaStoreInitListener.class, conf, MetastoreConf.getVar(conf, ConfVars.INIT_HOOKS));
for (MetaStoreInitListener singleInitListener: initListeners) {
MetaStoreInitContext context = new MetaStoreInitContext();
singleInitListener.onInit(context);
}
String alterHandlerName = MetastoreConf.getVar(conf, ConfVars.ALTER_HANDLER);
alterHandler = ReflectionUtils.newInstance(JavaUtils.getClass(
alterHandlerName, AlterHandler.class), conf);
wh = new Warehouse(conf);
synchronized (HMSHandler.class) {
if (currentUrl == null || !currentUrl.equals(MetaStoreInit.getConnectionURL(conf))) {
createDefaultDB();
createDefaultRoles();
addAdminUsers();
currentUrl = MetaStoreInit.getConnectionURL(conf);
}
}
//Start Metrics
if (MetastoreConf.getBoolVar(conf, ConfVars.METRICS_ENABLED)) {
LOG.info("Begin calculating metadata count metrics.");
Metrics.initialize(conf);
databaseCount = Metrics.getOrCreateGauge(MetricsConstants.TOTAL_DATABASES);
tableCount = Metrics.getOrCreateGauge(MetricsConstants.TOTAL_TABLES);
partCount = Metrics.getOrCreateGauge(MetricsConstants.TOTAL_PARTITIONS);
updateMetrics();
}
preListeners = MetaStoreServerUtils.getMetaStoreListeners(MetaStorePreEventListener.class,
conf, MetastoreConf.getVar(conf, ConfVars.PRE_EVENT_LISTENERS));
preListeners.add(0, new TransactionalValidationListener(conf));
listeners = MetaStoreServerUtils.getMetaStoreListeners(MetaStoreEventListener.class, conf,
MetastoreConf.getVar(conf, ConfVars.EVENT_LISTENERS));
listeners.add(new SessionPropertiesListener(conf));
transactionalListeners = new ArrayList() {{
add(new AcidEventListener(conf));
}};
transactionalListeners.addAll(MetaStoreServerUtils.getMetaStoreListeners(
TransactionalMetaStoreEventListener.class, conf,
MetastoreConf.getVar(conf, ConfVars.TRANSACTIONAL_EVENT_LISTENERS)));
if (Metrics.getRegistry() != null) {
listeners.add(new HMSMetricsListener(conf));
}
boolean canCachedStoreCanUseEvent = false;
for (MetaStoreEventListener listener : transactionalListeners) {
if (listener.doesAddEventsToNotificationLogTable()) {
canCachedStoreCanUseEvent = true;
break;
}
}
if (conf.getBoolean(ConfVars.METASTORE_CACHE_CAN_USE_EVENT.getVarname(), false) &&
!canCachedStoreCanUseEvent) {
throw new MetaException("CahcedStore can not use events for invalidation as there is no " +
" TransactionalMetaStoreEventListener to add events to notification table");
}
endFunctionListeners = MetaStoreServerUtils.getMetaStoreListeners(
MetaStoreEndFunctionListener.class, conf, MetastoreConf.getVar(conf, ConfVars.END_FUNCTION_LISTENERS));
String partitionValidationRegex =
MetastoreConf.getVar(conf, ConfVars.PARTITION_NAME_WHITELIST_PATTERN);
if (partitionValidationRegex != null && !partitionValidationRegex.isEmpty()) {
partitionValidationPattern = Pattern.compile(partitionValidationRegex);
}
// We only initialize once the tasks that need to be run periodically. For remote metastore
// these threads are started along with the other housekeeping threads only in the leader
// HMS.
String leaderHost = MetastoreConf.getVar(conf,
MetastoreConf.ConfVars.METASTORE_HOUSEKEEPING_LEADER_HOSTNAME);
if (!HiveMetaStore.isMetaStoreRemote() && ((leaderHost == null) || leaderHost.trim().isEmpty())) {
startAlwaysTaskThreads(conf);
} else if (!HiveMetaStore.isMetaStoreRemote()) {
LOG.info("Not starting tasks specified by " + ConfVars.TASK_THREADS_ALWAYS.getVarname() +
" since " + leaderHost + " is configured to run these tasks.");
}
expressionProxy = PartFilterExprUtil.createExpressionProxy(conf);
fileMetadataManager = new FileMetadataManager(this.getMS(), conf);
isServerFilterEnabled = getIfServerFilterenabled();
filterHook = isServerFilterEnabled ? loadFilterHooks() : null;
String className = MetastoreConf.getVar(conf, MetastoreConf.ConfVars.METASTORE_METADATA_TRANSFORMER_CLASS);
if (className != null && !className.trim().isEmpty()) {
try {
transformer = JavaUtils.newInstance(JavaUtils.getClass(className.trim(), IMetaStoreMetadataTransformer.class),
new Class[] {IHMSHandler.class}, new Object[] {this});
} catch (Exception e) {
LOG.error("Unable to create instance of class " + className, e);
throw new IllegalArgumentException(e);
}
}
dataconnectorFactory = DataConnectorProviderFactory.getInstance(this);
}
static void startAlwaysTaskThreads(Configuration conf) throws MetaException {
if (alwaysThreadsInitialized.compareAndSet(false, true)) {
ThreadPool.initialize(conf);
Collection<String> taskNames =
MetastoreConf.getStringCollection(conf, ConfVars.TASK_THREADS_ALWAYS);
for (String taskName : taskNames) {
MetastoreTaskThread task =
JavaUtils.newInstance(JavaUtils.getClass(taskName, MetastoreTaskThread.class));
task.setConf(conf);
long freq = task.runFrequency(TimeUnit.MILLISECONDS);
LOG.info("Scheduling for " + task.getClass().getCanonicalName() + " service with " +
"frequency " + freq + "ms.");
// For backwards compatibility, since some threads used to be hard coded but only run if
// frequency was > 0
if (freq > 0) {
ThreadPool.getPool().scheduleAtFixedRate(task, freq, freq, TimeUnit.MILLISECONDS);
}
}
}
}
/**
*
* Filter is actually enabled only when the configured filter hook is configured, not default, and
* enabled in configuration
* @return
*/
private boolean getIfServerFilterenabled() throws MetaException{
boolean isEnabled = MetastoreConf.getBoolVar(conf, ConfVars.METASTORE_SERVER_FILTER_ENABLED);
if (!isEnabled) {
LOG.info("HMS server filtering is disabled by configuration");
return false;
}
String filterHookClassName = MetastoreConf.getVar(conf, ConfVars.FILTER_HOOK);
if (isBlank(filterHookClassName)) {
throw new MetaException("HMS server filtering is enabled but no filter hook is configured");
}
if (filterHookClassName.trim().equalsIgnoreCase(DefaultMetaStoreFilterHookImpl.class.getName())) {
throw new MetaException("HMS server filtering is enabled but the filter hook is DefaultMetaStoreFilterHookImpl, which does no filtering");
}
LOG.info("HMS server filtering is enabled. The filter class is " + filterHookClassName);
return true;
}
private MetaStoreFilterHook loadFilterHooks() throws IllegalStateException {
String errorMsg = "Unable to load filter hook at HMS server. ";
String filterHookClassName = MetastoreConf.getVar(conf, ConfVars.FILTER_HOOK);
Preconditions.checkState(!isBlank(filterHookClassName));
try {
return (MetaStoreFilterHook)Class.forName(
filterHookClassName.trim(), true, JavaUtils.getClassLoader()).getConstructor(
Configuration.class).newInstance(conf);
} catch (Exception e) {
LOG.error(errorMsg, e);
throw new IllegalStateException(errorMsg + e.getMessage(), e);
}
}
/**
* Check if user can access the table associated with the partition. If not, then throw exception
* so user cannot access partitions associated with this table
* We are not calling Pre event listener for authorization because it requires getting the
* table object from DB, more overhead. Instead ,we call filter hook to filter out table if user
* has no access. Filter hook only requires table name, not table object. That saves DB access for
* table object, and still achieve the same purpose: checking if user can access the specified
* table
*
* @param catName catalog name of the table
* @param dbName database name of the table
* @param tblName table name
* @throws NoSuchObjectException
* @throws MetaException
*/
private void authorizeTableForPartitionMetadata(
final String catName, final String dbName, final String tblName)
throws NoSuchObjectException, MetaException {
FilterUtils.checkDbAndTableFilters(
isServerFilterEnabled, filterHook, catName, dbName, tblName);
}
@Override
public void setConf(Configuration conf) {
HMSHandlerContext.setConfiguration(conf);
// reload if DS related configuration is changed
HMSHandlerContext.getRawStore().ifPresent(ms -> ms.setConf(conf));
}
@Override
public Configuration getConf() {
Configuration conf = HMSHandlerContext.getConfiguration()
.orElseGet(() -> {
Configuration configuration = new Configuration(this.conf);
HMSHandlerContext.setConfiguration(configuration);
return configuration;
});
return conf;
}
@Override
public Warehouse getWh() {
return wh;
}
@Override
public void setMetaConf(String key, String value) throws MetaException {
ConfVars confVar = MetastoreConf.getMetaConf(key);
if (confVar == null) {
throw new MetaException("Invalid configuration key " + key);
}
try {
confVar.validate(value);
} catch (IllegalArgumentException e) {
throw new MetaException("Invalid configuration value " + value + " for key " + key +
" by " + e.getMessage());
}
Configuration configuration = getConf();
String oldValue = MetastoreConf.get(configuration, key);
// Save prev val of the key on threadLocal
Map<String, String> modifiedConf = HMSHandlerContext.getModifiedConfig();
if (!modifiedConf.containsKey(key)) {
modifiedConf.put(key, oldValue);
}
// Set invoking HMSHandler on threadLocal, this will be used later to notify
// metaListeners in HiveMetaStore#cleanupHandlerContext
if (!HMSHandlerContext.getHMSHandler().isPresent()) {
HMSHandlerContext.setHMSHandler(this);
}
configuration.set(key, value);
notifyMetaListeners(key, oldValue, value);
if (ConfVars.TRY_DIRECT_SQL == confVar) {
HMSHandler.LOG.info("Direct SQL optimization = {}", value);
}
}
@Override
public String getMetaConf(String key) throws MetaException {
ConfVars confVar = MetastoreConf.getMetaConf(key);
if (confVar == null) {
throw new MetaException("Invalid configuration key " + key);
}
return getConf().get(key, confVar.getDefaultVal().toString());
}
/**
* Get a cached RawStore.
*
* @return the cached RawStore
* @throws MetaException
*/
@Override
public RawStore getMS() throws MetaException {
Configuration conf = getConf();
return getMSForConf(conf);
}
public static RawStore getMSForConf(Configuration conf) throws MetaException {
RawStore ms = getRawStore();
if (ms == null) {
ms = newRawStoreForConf(conf);
try {
ms.verifySchema();
} catch (MetaException e) {
ms.shutdown();
throw e;
}
HMSHandlerContext.setRawStore(ms);
LOG.info("Created RawStore: {}", ms);
}
return ms;
}
@Override
public TxnStore getTxnHandler() {
return HMSHandlerContext.getTxnStore(conf);
}
static RawStore newRawStoreForConf(Configuration conf) throws MetaException {
Configuration newConf = new Configuration(conf);
String rawStoreClassName = MetastoreConf.getVar(newConf, ConfVars.RAW_STORE_IMPL);
LOG.info("Opening raw store with implementation class: {}", rawStoreClassName);
return RawStoreProxy.getProxy(newConf, conf, rawStoreClassName);
}
@VisibleForTesting
public static void createDefaultCatalog(RawStore ms, Warehouse wh) throws MetaException,
InvalidOperationException {
try {
Catalog defaultCat = ms.getCatalog(DEFAULT_CATALOG_NAME);
// Null check because in some test cases we get a null from ms.getCatalog.
if (defaultCat !=null && defaultCat.getLocationUri().equals("TBD")) {
// One time update issue. When the new 'hive' catalog is created in an upgrade the
// script does not know the location of the warehouse. So we need to update it.
LOG.info("Setting location of default catalog, as it hasn't been done after upgrade");
defaultCat.setLocationUri(wh.getWhRoot().toString());
ms.alterCatalog(defaultCat.getName(), defaultCat);
}
} catch (NoSuchObjectException e) {
Catalog cat = new Catalog(DEFAULT_CATALOG_NAME, wh.getWhRoot().toString());
long time = System.currentTimeMillis() / 1000;
cat.setCreateTime((int) time);
cat.setDescription(Warehouse.DEFAULT_CATALOG_COMMENT);
ms.createCatalog(cat);
}
}
private void createDefaultDB_core(RawStore ms) throws MetaException, InvalidObjectException {
try {
ms.getDatabase(DEFAULT_CATALOG_NAME, DEFAULT_DATABASE_NAME);
} catch (NoSuchObjectException e) {
LOG.info("Started creating a default database with name: "+DEFAULT_DATABASE_NAME);
Database db = new Database(DEFAULT_DATABASE_NAME, DEFAULT_DATABASE_COMMENT,
wh.getDefaultDatabasePath(DEFAULT_DATABASE_NAME, true).toString(), null);
db.setOwnerName(PUBLIC);
db.setOwnerType(PrincipalType.ROLE);
db.setCatalogName(DEFAULT_CATALOG_NAME);
long time = System.currentTimeMillis() / 1000;
db.setCreateTime((int) time);
db.setType(DatabaseType.NATIVE);
ms.createDatabase(db);
LOG.info("Successfully created a default database with name: "+DEFAULT_DATABASE_NAME);
}
}
/**
* create default database if it doesn't exist.
*
* This is a potential contention when HiveServer2 using embedded metastore and Metastore
* Server try to concurrently invoke createDefaultDB. If one failed, JDOException was caught
* for one more time try, if failed again, simply ignored by warning, which meant another
* succeeds.
*
* @throws MetaException
*/
private void createDefaultDB() throws MetaException {
try {
RawStore ms = getMS();
createDefaultCatalog(ms, wh);
createDefaultDB_core(ms);
} catch (JDOException e) {
LOG.warn("Retrying creating default database after error: " + e.getMessage(), e);
try {
RawStore ms = getMS();
createDefaultCatalog(ms, wh);
createDefaultDB_core(ms);
} catch (InvalidObjectException | InvalidOperationException e1) {
throw new MetaException(e1.getMessage());
}
} catch (InvalidObjectException|InvalidOperationException e) {
throw new MetaException(e.getMessage());
}
}
/**
* create default roles if they don't exist.
*
* This is a potential contention when HiveServer2 using embedded metastore and Metastore
* Server try to concurrently invoke createDefaultRoles. If one failed, JDOException was caught
* for one more time try, if failed again, simply ignored by warning, which meant another
* succeeds.
*
* @throws MetaException
*/
private void createDefaultRoles() throws MetaException {
try {
createDefaultRoles_core();
} catch (JDOException e) {
LOG.warn("Retrying creating default roles after error: " + e.getMessage(), e);
createDefaultRoles_core();
}
}
private void createDefaultRoles_core() throws MetaException {
RawStore ms = getMS();
try {
ms.addRole(ADMIN, ADMIN);
} catch (InvalidObjectException e) {
LOG.debug(ADMIN +" role already exists",e);
} catch (NoSuchObjectException e) {
// This should never be thrown.
LOG.warn("Unexpected exception while adding " +ADMIN+" roles" , e);
}
LOG.info("Added "+ ADMIN+ " role in metastore");
try {
ms.addRole(PUBLIC, PUBLIC);
} catch (InvalidObjectException e) {
LOG.debug(PUBLIC + " role already exists",e);
} catch (NoSuchObjectException e) {
// This should never be thrown.
LOG.warn("Unexpected exception while adding "+PUBLIC +" roles" , e);
}
LOG.info("Added "+PUBLIC+ " role in metastore");
// now grant all privs to admin
PrivilegeBag privs = new PrivilegeBag();
privs.addToPrivileges(new HiveObjectPrivilege( new HiveObjectRef(HiveObjectType.GLOBAL, null,
null, null, null), ADMIN, PrincipalType.ROLE, new PrivilegeGrantInfo("All", 0, ADMIN,
PrincipalType.ROLE, true), "SQL"));
try {
ms.grantPrivileges(privs);
} catch (InvalidObjectException e) {
// Surprisingly these privs are already granted.
LOG.debug("Failed while granting global privs to admin", e);
} catch (NoSuchObjectException e) {
// Unlikely to be thrown.
LOG.warn("Failed while granting global privs to admin", e);
}
}
/**
* add admin users if they don't exist.
*
* This is a potential contention when HiveServer2 using embedded metastore and Metastore
* Server try to concurrently invoke addAdminUsers. If one failed, JDOException was caught for
* one more time try, if failed again, simply ignored by warning, which meant another succeeds.
*
* @throws MetaException
*/
private void addAdminUsers() throws MetaException {
try {
addAdminUsers_core();
} catch (JDOException e) {
LOG.warn("Retrying adding admin users after error: " + e.getMessage(), e);
addAdminUsers_core();
}
}
private void addAdminUsers_core() throws MetaException {
// now add pre-configured users to admin role
String userStr = MetastoreConf.getVar(conf,ConfVars.USERS_IN_ADMIN_ROLE,"").trim();
if (userStr.isEmpty()) {
LOG.info("No user is added in admin role, since config is empty");
return;
}
// Since user names need to be valid unix user names, per IEEE Std 1003.1-2001 they cannot
// contain comma, so we can safely split above string on comma.
Iterator<String> users = Splitter.on(",").trimResults().omitEmptyStrings().split(userStr).iterator();
if (!users.hasNext()) {
LOG.info("No user is added in admin role, since config value "+ userStr +
" is in incorrect format. We accept comma separated list of users.");
return;
}
Role adminRole;
RawStore ms = getMS();
try {
adminRole = ms.getRole(ADMIN);
} catch (NoSuchObjectException e) {
LOG.error("Failed to retrieve just added admin role",e);
return;
}
while (users.hasNext()) {
String userName = users.next();
try {
ms.grantRole(adminRole, userName, PrincipalType.USER, ADMIN, PrincipalType.ROLE, true);
LOG.info("Added " + userName + " to admin role");
} catch (NoSuchObjectException e) {
LOG.error("Failed to add "+ userName + " in admin role",e);
} catch (InvalidObjectException e) {
LOG.debug(userName + " already in admin role", e);
}
}
}
private static void logAndAudit(final String m) {
LOG.debug(m);
logAuditEvent(m);
}
private String startFunction(String function, String extraLogInfo) {
incrementCounter(function);
logAndAudit((getThreadLocalIpAddress() == null ? "" : "source:" + getThreadLocalIpAddress() + " ") +
function + extraLogInfo);
com.codahale.metrics.Timer timer =
Metrics.getOrCreateTimer(MetricsConstants.API_PREFIX + function);
if (timer != null) {
// Timer will be null we aren't using the metrics
HMSHandlerContext.getTimerContexts().put(function, timer.time());
}
Counter counter = Metrics.getOrCreateCounter(MetricsConstants.ACTIVE_CALLS + function);
if (counter != null) {
counter.inc();
}
return function;
}
private String startFunction(String function) {
return startFunction(function, "");
}
private void startTableFunction(String function, String catName, String db, String tbl) {
startFunction(function, " : tbl=" +
TableName.getQualified(catName, db, tbl));
}
private void startMultiTableFunction(String function, String db, List<String> tbls) {
String tableNames = join(tbls, ",");
startFunction(function, " : db=" + db + " tbls=" + tableNames);
}
private void startPartitionFunction(String function, String cat, String db, String tbl,
List<String> partVals) {
startFunction(function, " : tbl=" +
TableName.getQualified(cat, db, tbl) + "[" + join(partVals, ",") + "]");
}
private void startPartitionFunction(String function, String catName, String db, String tbl,
Map<String, String> partName) {
startFunction(function, " : tbl=" +
TableName.getQualified(catName, db, tbl) + "partition=" + partName);
}
private void endFunction(String function, boolean successful, Exception e) {
endFunction(function, successful, e, null);
}
private void endFunction(String function, boolean successful, Exception e,
String inputTableName) {
endFunction(function, new MetaStoreEndFunctionContext(successful, e, inputTableName));
}
private void endFunction(String function, MetaStoreEndFunctionContext context) {
com.codahale.metrics.Timer.Context timerContext = HMSHandlerContext.getTimerContexts().remove(function);
if (timerContext != null) {
long timeTaken = timerContext.stop();
LOG.debug((getThreadLocalIpAddress() == null ? "" : "source:" + getThreadLocalIpAddress() + " ") +
function + "time taken(ns): " + timeTaken);
}
Counter counter = Metrics.getOrCreateCounter(MetricsConstants.ACTIVE_CALLS + function);
if (counter != null) {
counter.dec();
}
for (MetaStoreEndFunctionListener listener : endFunctionListeners) {
listener.onEndFunction(function, context);
}
}
@Override
public fb_status getStatus() {
return fb_status.ALIVE;
}
@Override
public void shutdown() {
cleanupHandlerContext();
PerfLogger.getPerfLogger(false).cleanupPerfLogMetrics();
}
@Override
public AbstractMap<String, Long> getCounters() {
AbstractMap<String, Long> counters = super.getCounters();
// Allow endFunctionListeners to add any counters they have collected
if (endFunctionListeners != null) {
for (MetaStoreEndFunctionListener listener : endFunctionListeners) {
listener.exportCounters(counters);
}
}
return counters;
}
@Override
public void create_catalog(CreateCatalogRequest rqst)
throws AlreadyExistsException, InvalidObjectException, MetaException {
Catalog catalog = rqst.getCatalog();
startFunction("create_catalog", ": " + catalog.toString());
boolean success = false;
Exception ex = null;
try {
try {
getMS().getCatalog(catalog.getName());
throw new AlreadyExistsException("Catalog " + catalog.getName() + " already exists");
} catch (NoSuchObjectException e) {
// expected
}
if (!MetaStoreUtils.validateName(catalog.getName(), null)) {
throw new InvalidObjectException(catalog.getName() + " is not a valid catalog name");
}
if (catalog.getLocationUri() == null) {
throw new InvalidObjectException("You must specify a path for the catalog");
}
RawStore ms = getMS();
Path catPath = new Path(catalog.getLocationUri());
boolean madeDir = false;
Map<String, String> transactionalListenersResponses = Collections.emptyMap();
try {
firePreEvent(new PreCreateCatalogEvent(this, catalog));
if (!wh.isDir(catPath)) {
if (!wh.mkdirs(catPath)) {
throw new MetaException("Unable to create catalog path " + catPath +
", failed to create catalog " + catalog.getName());
}
madeDir = true;
}
// set the create time of catalog
long time = System.currentTimeMillis() / 1000;
catalog.setCreateTime((int) time);
ms.openTransaction();
ms.createCatalog(catalog);
// Create a default database inside the catalog
Database db = new Database(DEFAULT_DATABASE_NAME,
"Default database for catalog " + catalog.getName(), catalog.getLocationUri(),
Collections.emptyMap());
db.setCatalogName(catalog.getName());
create_database_core(ms, db);
if (!transactionalListeners.isEmpty()) {
transactionalListenersResponses =
MetaStoreListenerNotifier.notifyEvent(transactionalListeners,
EventType.CREATE_CATALOG,
new CreateCatalogEvent(true, this, catalog));
}
success = ms.commitTransaction();
} finally {
if (!success) {
ms.rollbackTransaction();
if (madeDir) {
wh.deleteDir(catPath, true, false, false);
}
}
if (!listeners.isEmpty()) {
MetaStoreListenerNotifier.notifyEvent(listeners,
EventType.CREATE_CATALOG,
new CreateCatalogEvent(success, this, catalog),
null,
transactionalListenersResponses, ms);
}
}
success = true;
} catch (AlreadyExistsException|InvalidObjectException|MetaException e) {
ex = e;
throw e;
} finally {
endFunction("create_catalog", success, ex);
}
}
@Override
public void alter_catalog(AlterCatalogRequest rqst) throws TException {
startFunction("alter_catalog " + rqst.getName());
boolean success = false;
Exception ex = null;