forked from apache/hive
/
HiveMetaStoreClient.java
5094 lines (4524 loc) · 194 KB
/
HiveMetaStoreClient.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 static org.apache.hadoop.hive.common.AcidConstants.SOFT_DELETE_TABLE;
import static org.apache.hadoop.hive.metastore.Warehouse.DEFAULT_DATABASE_NAME;
import static org.apache.hadoop.hive.metastore.utils.MetaStoreUtils.convertToGetPartitionsByNamesRequest;
import static org.apache.hadoop.hive.metastore.utils.MetaStoreUtils.getDefaultCatalog;
import static org.apache.hadoop.hive.metastore.utils.MetaStoreUtils.prependCatalogToDbName;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.InetAddress;
import java.net.URI;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import javax.security.auth.login.LoginException;
import com.google.common.base.Preconditions;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hive.common.StatsSetupConst;
import org.apache.hadoop.hive.common.TableName;
import org.apache.hadoop.hive.common.ValidTxnList;
import org.apache.hadoop.hive.common.ValidTxnWriteIdList;
import org.apache.hadoop.hive.common.ValidWriteIdList;
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.hooks.URIResolverHook;
import org.apache.hadoop.hive.metastore.partition.spec.PartitionSpecProxy;
import org.apache.hadoop.hive.metastore.security.HadoopThriftAuthBridge;
import org.apache.hadoop.hive.metastore.txn.TxnCommonUtils;
import org.apache.hadoop.hive.metastore.utils.FilterUtils;
import org.apache.hadoop.hive.metastore.utils.JavaUtils;
import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
import org.apache.hadoop.hive.metastore.utils.SecurityUtils;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.util.ReflectionUtils;
import org.apache.hadoop.util.StringUtils;
import org.apache.http.HttpException;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HttpContext;
import org.apache.thrift.TApplicationException;
import org.apache.thrift.TConfiguration;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.THttpClient;
import org.apache.thrift.transport.layered.TFramedTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Lists;
/**
* Hive Metastore Client.
* The public implementation of IMetaStoreClient. Methods not inherited from IMetaStoreClient
* are not public and can change. Hence this is marked as unstable.
* For users who require retry mechanism when the connection between metastore and client is
* broken, RetryingMetaStoreClient class should be used.
*/
@InterfaceAudience.Public
@InterfaceStability.Evolving
public class HiveMetaStoreClient implements IMetaStoreClient, AutoCloseable {
private final String CLASS_NAME = HiveMetaStoreClient.class.getName();
public static final String MANUALLY_INITIATED_COMPACTION = "manual";
public static final String TRUNCATE_SKIP_DATA_DELETION = "truncateSkipDataDeletion";
public static final String RENAME_PARTITION_MAKE_COPY = "renamePartitionMakeCopy";
/**
* Capabilities of the current client. If this client talks to a MetaStore server in a manner
* implying the usage of some expanded features that require client-side support that this client
* doesn't have (e.g. a getting a table of a new type), it will get back failures when the
* capability checking is enabled (the default).
*/
public final static ClientCapabilities VERSION = new ClientCapabilities(
Lists.newArrayList(ClientCapability.INSERT_ONLY_TABLES));
// Test capability for tests.
public final static ClientCapabilities TEST_VERSION = new ClientCapabilities(
Lists.newArrayList(ClientCapability.INSERT_ONLY_TABLES, ClientCapability.TEST_CAPABILITY));
// Name of the HiveMetaStore class. It is used to initialize embedded metastore
private static final String HIVE_METASTORE_CLASS =
"org.apache.hadoop.hive.metastore.HiveMetaStore";
// Method used to create Hive Metastore client. It is called as
// HiveMetaStore.newRetryingHMSHandler("hive client", this.conf, true);
private static final String HIVE_METASTORE_CREATE_HANDLER_METHOD = "newRetryingHMSHandler";
ThriftHiveMetastore.Iface client = null;
private TTransport transport = null;
private boolean isConnected = false;
private URI metastoreUris[];
private final HiveMetaHookLoader hookLoader;
protected final Configuration conf; // Keep a copy of HiveConf so if Session conf changes, we may need to get a new HMS client.
private String tokenStrForm;
private final boolean localMetaStore;
private final MetaStoreFilterHook filterHook;
private final boolean isClientFilterEnabled;
private final URIResolverHook uriResolverHook;
private final int fileMetadataBatchSize;
private Map<String, String> currentMetaVars;
private static final AtomicInteger connCount = new AtomicInteger(0);
// for thrift connects
private int retries = 5;
private long retryDelaySeconds = 0;
private final ClientCapabilities version;
private static String[] processorCapabilities;
private static String processorIdentifier;
//copied from ErrorMsg.java
private static final String REPL_EVENTS_MISSING_IN_METASTORE = "Notification events are missing in the meta store.";
private static final String REPL_EVENTS_WITH_DUPLICATE_ID_IN_METASTORE =
"Notification events with duplicate event ids in the meta store.";
static final protected Logger LOG = LoggerFactory.getLogger(HiveMetaStoreClient.class);
public HiveMetaStoreClient(Configuration conf) throws MetaException {
this(conf, null, true);
}
public HiveMetaStoreClient(Configuration conf, HiveMetaHookLoader hookLoader) throws MetaException {
this(conf, hookLoader, true);
}
public HiveMetaStoreClient(Configuration conf, HiveMetaHookLoader hookLoader, Boolean allowEmbedded)
throws MetaException {
this.hookLoader = hookLoader;
if (conf == null) {
conf = MetastoreConf.newMetastoreConf();
this.conf = conf;
} else {
this.conf = new Configuration(conf);
}
version = MetastoreConf.getBoolVar(conf, ConfVars.HIVE_IN_TEST) ? TEST_VERSION : VERSION;
filterHook = loadFilterHooks();
isClientFilterEnabled = getIfClientFilterEnabled();
uriResolverHook = loadUriResolverHook();
fileMetadataBatchSize = MetastoreConf.getIntVar(
conf, ConfVars.BATCH_RETRIEVE_OBJECTS_MAX);
if ((MetastoreConf.get(conf, "hive.metastore.client.capabilities")) != null) {
String[] capabilities = MetastoreConf.get(conf, "hive.metastore.client.capabilities").split(",");
setProcessorCapabilities(capabilities);
String hostName = "unknown";
try {
hostName = InetAddress.getLocalHost().getCanonicalHostName();
} catch (UnknownHostException ue) {
}
setProcessorIdentifier("HMSClient-" + "@" + hostName);
}
String msUri = MetastoreConf.getVar(conf, ConfVars.THRIFT_URIS);
localMetaStore = MetastoreConf.isEmbeddedMetaStore(msUri);
if (localMetaStore) {
if (!allowEmbedded) {
throw new MetaException("Embedded metastore is not allowed here. Please configure "
+ ConfVars.THRIFT_URIS.toString() + "; it is currently set to [" + msUri + "]");
}
client = callEmbeddedMetastore(this.conf);
// instantiate the metastore server handler directly instead of connecting
// through the network
isConnected = true;
snapshotActiveConf();
return;
}
// get the number retries
retries = MetastoreConf.getIntVar(conf, ConfVars.THRIFT_CONNECTION_RETRIES);
retryDelaySeconds = MetastoreConf.getTimeVar(conf,
ConfVars.CLIENT_CONNECT_RETRY_DELAY, TimeUnit.SECONDS);
// user wants file store based configuration
if (MetastoreConf.getVar(conf, ConfVars.THRIFT_URIS) != null) {
resolveUris();
} else {
LOG.error("NOT getting uris from conf");
throw new MetaException("MetaStoreURIs not found in conf file");
}
//If HADOOP_PROXY_USER is set in env or property,
//then need to create metastore client that proxies as that user.
String HADOOP_PROXY_USER = "HADOOP_PROXY_USER";
String proxyUser = System.getenv(HADOOP_PROXY_USER);
if (proxyUser == null) {
proxyUser = System.getProperty(HADOOP_PROXY_USER);
}
//if HADOOP_PROXY_USER is set, create DelegationToken using real user
if (proxyUser != null) {
LOG.info(HADOOP_PROXY_USER + " is set. Using delegation "
+ "token for HiveMetaStore connection.");
try {
UserGroupInformation.getLoginUser().getRealUser().doAs(
new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws Exception {
open();
return null;
}
});
String delegationTokenPropString = "DelegationTokenForHiveMetaStoreServer";
String delegationTokenStr = getDelegationToken(proxyUser, proxyUser);
SecurityUtils.setTokenStr(UserGroupInformation.getCurrentUser(), delegationTokenStr,
delegationTokenPropString);
MetastoreConf.setVar(this.conf, ConfVars.TOKEN_SIGNATURE, delegationTokenPropString);
close();
} catch (Exception e) {
LOG.error("Error while setting delegation token for " + proxyUser, e);
if (e instanceof MetaException) {
throw (MetaException) e;
} else {
throw new MetaException(e.getMessage());
}
}
}
// finally open the store
open();
}
/**
* Instantiate the metastore server handler directly instead of connecting
* through the network
*
* @param conf Configuration object passed to embedded metastore
* @return embedded client instance
* @throws MetaException
*/
static ThriftHiveMetastore.Iface callEmbeddedMetastore(Configuration conf) throws MetaException {
// Instantiate the metastore server handler directly instead of connecting
// through the network
//
// The code below simulates the following code
//
// client = HiveMetaStore.newRetryingHMSHandler(this.conf);
//
// using reflection API. This is done to avoid dependency of MetastoreClient on Hive Metastore.
// Note that newRetryingHMSHandler is static method, so we pass null as the object reference.
//
try {
Class<?> clazz = Class.forName(HIVE_METASTORE_CLASS);
//noinspection JavaReflectionMemberAccess
Method method = clazz.getDeclaredMethod(HIVE_METASTORE_CREATE_HANDLER_METHOD,
Configuration.class);
method.setAccessible(true);
return (ThriftHiveMetastore.Iface) method.invoke(null, conf);
} catch (InvocationTargetException e) {
if (e.getCause() != null) {
MetaStoreUtils.throwMetaException((Exception) e.getCause());
}
MetaStoreUtils.throwMetaException(e);
} catch (ClassNotFoundException
| NoSuchMethodException
| IllegalAccessException e) {
MetaStoreUtils.throwMetaException(e);
}
return null;
}
private boolean getIfClientFilterEnabled() {
boolean isEnabled = MetastoreConf.getBoolVar(conf, ConfVars.METASTORE_CLIENT_FILTER_ENABLED);
LOG.info("HMS client filtering is " + (isEnabled ? "enabled." : "disabled."));
return isEnabled;
}
private void resolveUris() throws MetaException {
String thriftUris = MetastoreConf.getVar(conf, ConfVars.THRIFT_URIS);
String serviceDiscoveryMode = MetastoreConf.getVar(conf, ConfVars.THRIFT_SERVICE_DISCOVERY_MODE);
List<String> metastoreUrisString = null;
// The metastore URIs can come from THRIFT_URIS directly or need to be fetched from the
// Zookeeper
try {
if (serviceDiscoveryMode == null || serviceDiscoveryMode.trim().isEmpty()) {
metastoreUrisString = Arrays.asList(thriftUris.split(","));
} else if (serviceDiscoveryMode.equalsIgnoreCase("zookeeper")) {
metastoreUrisString = new ArrayList<String>();
// Add scheme to the bare URI we get.
for (String s : MetastoreConf.getZKConfig(conf).getServerUris()) {
metastoreUrisString.add("thrift://" + s);
}
} else {
throw new IllegalArgumentException("Invalid metastore dynamic service discovery mode " +
serviceDiscoveryMode);
}
} catch (Exception e) {
MetaStoreUtils.throwMetaException(e);
}
if (metastoreUrisString.isEmpty() && "zookeeper".equalsIgnoreCase(serviceDiscoveryMode)) {
throw new MetaException("No metastore service discovered in ZooKeeper. "
+ "Please ensure that at least one metastore server is online");
}
LOG.info("Resolved metastore uris: {}", metastoreUrisString);
List<URI> metastoreURIArray = new ArrayList<URI>();
try {
for (String s : metastoreUrisString) {
URI tmpUri = new URI(s);
if (tmpUri.getScheme() == null) {
throw new IllegalArgumentException("URI: " + s
+ " does not have a scheme");
}
if (uriResolverHook != null) {
metastoreURIArray.addAll(uriResolverHook.resolveURI(tmpUri));
} else {
metastoreURIArray.add(tmpUri);
}
}
metastoreUris = new URI[metastoreURIArray.size()];
for (int j = 0; j < metastoreURIArray.size(); j++) {
metastoreUris[j] = metastoreURIArray.get(j);
}
if (MetastoreConf.getVar(conf, ConfVars.THRIFT_URI_SELECTION).equalsIgnoreCase("RANDOM")) {
List<URI> uriList = Arrays.asList(metastoreUris);
Collections.shuffle(uriList);
metastoreUris = uriList.toArray(new URI[uriList.size()]);
}
} catch (IllegalArgumentException e) {
throw (e);
} catch (Exception e) {
MetaStoreUtils.throwMetaException(e);
}
}
private MetaStoreFilterHook loadFilterHooks() throws IllegalStateException {
Class<? extends MetaStoreFilterHook> authProviderClass = MetastoreConf.
getClass(conf, ConfVars.FILTER_HOOK, DefaultMetaStoreFilterHookImpl.class,
MetaStoreFilterHook.class);
String msg = "Unable to create instance of " + authProviderClass.getName() + ": ";
try {
Constructor<? extends MetaStoreFilterHook> constructor =
authProviderClass.getConstructor(Configuration.class);
return constructor.newInstance(conf);
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | InstantiationException | IllegalArgumentException | InvocationTargetException e) {
throw new IllegalStateException(msg + e.getMessage(), e);
}
}
//multiple clients may initialize the hook at the same time
synchronized private URIResolverHook loadUriResolverHook() throws IllegalStateException {
String uriResolverClassName =
MetastoreConf.getAsString(conf, ConfVars.URI_RESOLVER);
if (uriResolverClassName.equals("")) {
return null;
} else {
LOG.info("Loading uri resolver : " + uriResolverClassName);
try {
Class<?> uriResolverClass = Class.forName(uriResolverClassName, true,
JavaUtils.getClassLoader());
return (URIResolverHook) ReflectionUtils.newInstance(uriResolverClass, null);
} catch (Exception e) {
LOG.error("Exception loading uri resolver hook", e);
return null;
}
}
}
/**
* Swaps the first element of the metastoreUris array with a random element from the
* remainder of the array.
*/
private void promoteRandomMetaStoreURI() {
if (metastoreUris.length <= 1) {
return;
}
Random rng = new Random();
int index = rng.nextInt(metastoreUris.length - 1) + 1;
URI tmp = metastoreUris[0];
metastoreUris[0] = metastoreUris[index];
metastoreUris[index] = tmp;
}
@VisibleForTesting
public TTransport getTTransport() {
return transport;
}
@Override
public boolean isLocalMetaStore() {
return localMetaStore;
}
@Override
public boolean isCompatibleWith(Configuration conf) {
// Make a copy of currentMetaVars, there is a race condition that
// currentMetaVars might be changed during the execution of the method
Map<String, String> currentMetaVarsCopy = currentMetaVars;
if (currentMetaVarsCopy == null) {
return false; // recreate
}
boolean compatible = true;
for (ConfVars oneVar : MetastoreConf.metaVars) {
// Since metaVars are all of different types, use string for comparison
String oldVar = currentMetaVarsCopy.get(oneVar.getVarname());
String newVar = MetastoreConf.getAsString(conf, oneVar);
if (oldVar == null ||
(oneVar.isCaseSensitive() ? !oldVar.equals(newVar) : !oldVar.equalsIgnoreCase(newVar))) {
LOG.info("Mestastore configuration {} changed from {} to {}",
oneVar, oldVar, newVar);
compatible = false;
}
}
return compatible;
}
@Override
public void setHiveAddedJars(String addedJars) {
MetastoreConf.setVar(conf, ConfVars.ADDED_JARS, addedJars);
}
@Override
public void reconnect() throws MetaException {
if (localMetaStore) {
// For direct DB connections we don't yet support reestablishing connections.
throw new MetaException("Retries for direct MetaStore DB connections "
+ "are not supported by this client");
} else {
close();
if (uriResolverHook != null) {
//for dynamic uris, re-lookup if there are new metastore locations
resolveUris();
}
if (MetastoreConf.getVar(conf, ConfVars.THRIFT_URI_SELECTION).equalsIgnoreCase("RANDOM")) {
// Swap the first element of the metastoreUris[] with a random element from the rest
// of the array. Rationale being that this method will generally be called when the default
// connection has died and the default connection is likely to be the first array element.
promoteRandomMetaStoreURI();
}
open();
}
}
@Override
public void alter_table(String dbname, String tbl_name, Table new_tbl) throws TException {
alter_table_with_environmentContext(dbname, tbl_name, new_tbl, null);
}
@Override
public void alter_table(String defaultDatabaseName, String tblName, Table table,
boolean cascade) throws TException {
EnvironmentContext environmentContext = new EnvironmentContext();
if (cascade) {
environmentContext.putToProperties(StatsSetupConst.CASCADE, StatsSetupConst.TRUE);
}
alter_table_with_environmentContext(defaultDatabaseName, tblName, table, environmentContext);
}
@Override
public void alter_table_with_environmentContext(String dbname, String tbl_name, Table new_tbl,
EnvironmentContext envContext) throws InvalidOperationException, MetaException, TException {
HiveMetaHook hook = getHook(new_tbl);
if (hook != null) {
hook.preAlterTable(new_tbl, envContext);
}
AlterTableRequest req = new AlterTableRequest(dbname, tbl_name, new_tbl);
req.setCatName(MetaStoreUtils.getDefaultCatalog(conf));
req.setEnvironmentContext(envContext);
if (processorCapabilities != null) {
req.setProcessorCapabilities(new ArrayList<String>(Arrays.asList(processorCapabilities)));
req.setProcessorIdentifier(processorIdentifier);
}
boolean success = false;
try {
client.alter_table_req(req);
if (hook != null) {
hook.commitAlterTable(new_tbl, envContext);
}
success = true;
} finally {
if (!success && (hook != null)) {
hook.rollbackAlterTable(new_tbl, envContext);
}
}
}
@Override
public void alter_table(String catName, String dbName, String tblName, Table newTable,
EnvironmentContext envContext) throws TException {
// This never used to call the hook. Why? There's overload madness in metastore...
AlterTableRequest req = new AlterTableRequest(dbName, tblName, newTable);
req.setCatName(catName);
req.setEnvironmentContext(envContext);
if (processorCapabilities != null) {
req.setProcessorCapabilities(new ArrayList<String>(Arrays.asList(processorCapabilities)));
req.setProcessorIdentifier(processorIdentifier);
}
client.alter_table_req(req);
}
@Override
public void alter_table(String catName, String dbName, String tbl_name, Table new_tbl,
EnvironmentContext envContext, String validWriteIds)
throws InvalidOperationException, MetaException, TException {
HiveMetaHook hook = getHook(new_tbl);
if (hook != null) {
hook.preAlterTable(new_tbl, envContext);
}
boolean success = false;
try {
boolean skipAlter = envContext != null && envContext.getProperties() != null &&
Boolean.valueOf(envContext.getProperties().getOrDefault(HiveMetaHook.SKIP_METASTORE_ALTER, "false"));
if (!skipAlter) {
AlterTableRequest req = new AlterTableRequest(dbName, tbl_name, new_tbl);
req.setCatName(catName);
req.setValidWriteIdList(validWriteIds);
req.setEnvironmentContext(envContext);
if (processorCapabilities != null) {
req.setProcessorCapabilities(new ArrayList<String>(Arrays.asList(processorCapabilities)));
req.setProcessorIdentifier(processorIdentifier);
}
client.alter_table_req(req);
}
if (hook != null) {
hook.commitAlterTable(new_tbl, envContext);
}
success = true;
} finally {
if (!success && (hook != null)) {
hook.rollbackAlterTable(new_tbl, envContext);
}
}
}
@Deprecated
@Override
public void renamePartition(final String dbname, final String tableName, final List<String> part_vals,
final Partition newPart) throws TException {
renamePartition(getDefaultCatalog(conf), dbname, tableName, part_vals, newPart, null);
}
@Override
public void renamePartition(String catName, String dbname, String tableName, List<String> part_vals,
Partition newPart, String validWriteIds, long txnId, boolean makeCopy) throws TException {
RenamePartitionRequest req = new RenamePartitionRequest(dbname, tableName, part_vals, newPart);
req.setCatName(catName);
req.setValidWriteIdList(validWriteIds);
req.setTxnId(txnId);
req.setClonePart(makeCopy);
client.rename_partition_req(req);
}
/*
Creates a THttpClient if HTTP mode is enabled. If Client auth mode is set to JWT,
then the method fetches JWT from environment variable: HMS_JWT and sets in auth
header in http request
*/
private THttpClient createHttpClient(URI store, boolean useSSL) throws MetaException,
TTransportException {
String path = MetaStoreUtils.getHttpPath(MetastoreConf.getVar(conf, ConfVars.THRIFT_HTTP_PATH));
String httpUrl = (useSSL ? "https://" : "http://") + store.getHost() + ":" + store.getPort() + path;
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
String authType = MetastoreConf.getVar(conf, ConfVars.METASTORE_CLIENT_AUTH_MODE);
if (authType.equalsIgnoreCase("jwt")) {
// fetch JWT token from environment and set it in Auth Header in HTTP request
String jwtToken = System.getenv("HMS_JWT");
if (jwtToken == null || jwtToken.isEmpty()) {
LOG.debug("No jwt token set in environment variable: HMS_JWT");
throw new MetaException("For auth mode JWT, valid signed jwt token must be provided in the "
+ "environment variable HMS_JWT");
}
httpClientBuilder.addInterceptorFirst(new HttpRequestInterceptor() {
@Override
public void process(HttpRequest httpRequest, HttpContext httpContext)
throws HttpException, IOException {
httpRequest.addHeader(HttpHeaders.AUTHORIZATION, "Bearer " + jwtToken);
}
});
} else {
String user = MetastoreConf.getVar(conf, ConfVars.METASTORE_CLIENT_PLAIN_USERNAME);
if (user == null || user.equals("")) {
try {
user = UserGroupInformation.getCurrentUser().getShortUserName();
} catch (IOException e) {
throw new MetaException("Failed to get client username from UGI");
}
}
final String httpUser = user;
httpClientBuilder.addInterceptorFirst(new HttpRequestInterceptor() {
@Override
public void process(HttpRequest httpRequest, HttpContext httpContext)
throws HttpException, IOException {
httpRequest.addHeader(MetaStoreUtils.USER_NAME_HTTP_HEADER, httpUser);
}
});
}
THttpClient tHttpClient;
try {
if (useSSL) {
String trustStorePath = MetastoreConf.getVar(conf, ConfVars.SSL_TRUSTSTORE_PATH).trim();
if (trustStorePath.isEmpty()) {
throw new IllegalArgumentException(ConfVars.SSL_TRUSTSTORE_PATH
+ " Not configured for SSL connection");
}
String trustStorePassword =
MetastoreConf.getPassword(conf, MetastoreConf.ConfVars.SSL_TRUSTSTORE_PASSWORD);
String trustStoreType =
MetastoreConf.getVar(conf, ConfVars.SSL_TRUSTSTORE_TYPE).trim();
String trustStoreAlgorithm =
MetastoreConf.getVar(conf, ConfVars.SSL_TRUSTMANAGERFACTORY_ALGORITHM).trim();
tHttpClient = SecurityUtils.getThriftHttpsClient(httpUrl, trustStorePath, trustStorePassword,
trustStoreAlgorithm, trustStoreType, httpClientBuilder);
} else {
tHttpClient = new THttpClient(httpUrl, httpClientBuilder.build());
}
} catch (Exception e) {
if (e instanceof TTransportException) {
throw (TTransportException)e;
} else {
throw new MetaException("Failed to create http transport client to url: " + httpUrl
+ ". Error:" + e);
}
}
LOG.debug("Created thrift http client for URL: " + httpUrl);
return tHttpClient;
}
private TTransport createBinaryClient(URI store, boolean useSSL) throws TTransportException,
MetaException {
TTransport binaryTransport = null;
try {
int clientSocketTimeout = (int) MetastoreConf.getTimeVar(conf,
ConfVars.CLIENT_SOCKET_TIMEOUT, TimeUnit.MILLISECONDS);
if (useSSL) {
String trustStorePath = MetastoreConf.getVar(conf, ConfVars.SSL_TRUSTSTORE_PATH).trim();
if (trustStorePath.isEmpty()) {
throw new IllegalArgumentException(ConfVars.SSL_TRUSTSTORE_PATH
+ " Not configured for SSL connection");
}
String trustStorePassword =
MetastoreConf.getPassword(conf, MetastoreConf.ConfVars.SSL_TRUSTSTORE_PASSWORD);
String trustStoreType =
MetastoreConf.getVar(conf, ConfVars.SSL_TRUSTSTORE_TYPE).trim();
String trustStoreAlgorithm =
MetastoreConf.getVar(conf, ConfVars.SSL_TRUSTMANAGERFACTORY_ALGORITHM).trim();
binaryTransport = SecurityUtils.getSSLSocket(store.getHost(), store.getPort(), clientSocketTimeout,
trustStorePath, trustStorePassword, trustStoreType, trustStoreAlgorithm);
} else {
binaryTransport = new TSocket(new TConfiguration(),store.getHost(), store.getPort(),
clientSocketTimeout);
}
binaryTransport = createAuthBinaryTransport(store, binaryTransport);
} catch (Exception e) {
if (e instanceof TTransportException) {
throw (TTransportException)e;
} else {
throw new MetaException("Failed to create binary transport client to url: " + store
+ ". Error: " + e);
}
}
LOG.debug("Created thrift binary client for URI: " + store);
return binaryTransport;
}
private void open() throws MetaException {
isConnected = false;
TTransportException tte = null;
MetaException recentME = null;
boolean useSSL = MetastoreConf.getBoolVar(conf, ConfVars.USE_SSL);
boolean useSasl = MetastoreConf.getBoolVar(conf, ConfVars.USE_THRIFT_SASL);
String clientAuthMode = MetastoreConf.getVar(conf, ConfVars.METASTORE_CLIENT_AUTH_MODE);
boolean usePasswordAuth = false;
boolean useCompactProtocol = MetastoreConf.getBoolVar(conf, ConfVars.USE_THRIFT_COMPACT_PROTOCOL);
String transportMode = MetastoreConf.getVar(conf, ConfVars.METASTORE_CLIENT_THRIFT_TRANSPORT_MODE);
boolean isHttpTransportMode = transportMode.equalsIgnoreCase("http");
if (clientAuthMode != null) {
usePasswordAuth = "PLAIN".equalsIgnoreCase(clientAuthMode);
}
for (int attempt = 0; !isConnected && attempt < retries; ++attempt) {
for (URI store : metastoreUris) {
LOG.info("Trying to connect to metastore with URI ({}) in {} transport mode", store,
transportMode);
try {
try {
if (isHttpTransportMode) {
transport = createHttpClient(store, useSSL);
} else {
transport = createBinaryClient(store, useSSL);
}
} catch (TTransportException te) {
tte = te;
throw new MetaException(te.toString());
}
final TProtocol protocol;
if (useCompactProtocol) {
protocol = new TCompactProtocol(transport);
} else {
protocol = new TBinaryProtocol(transport);
}
client = new ThriftHiveMetastore.Client(protocol);
try {
if (!transport.isOpen()) {
transport.open();
final int newCount = connCount.incrementAndGet();
if (useSSL) {
LOG.info(
"Opened an SSL connection to metastore, current connections: {}",
newCount);
if (LOG.isTraceEnabled()) {
LOG.trace("METASTORE SSL CONNECTION TRACE - open [{}]",
System.identityHashCode(this), new Exception());
}
} else {
LOG.info("Opened a connection to metastore, URI ({}) "
+ "current connections: {}", store, newCount);
if (LOG.isTraceEnabled()) {
LOG.trace("METASTORE CONNECTION TRACE - open [{}]",
System.identityHashCode(this), new Exception());
}
}
}
isConnected = true;
} catch (TTransportException e) {
tte = e;
String errMsg = String.format("Failed to connect to the MetaStore Server URI (%s) in %s "
+ "transport mode", store, transportMode);
LOG.warn(errMsg);
LOG.debug(errMsg, e);
}
if (isConnected && !useSasl && !usePasswordAuth && !isHttpTransportMode &&
MetastoreConf.getBoolVar(conf, ConfVars.EXECUTE_SET_UGI)) {
// Call set_ugi, only in unsecure mode.
try {
UserGroupInformation ugi = SecurityUtils.getUGI();
client.set_ugi(ugi.getUserName(), Arrays.asList(ugi.getGroupNames()));
} catch (LoginException e) {
LOG.warn("Failed to do login. set_ugi() is not successful, " +
"Continuing without it.", e);
} catch (IOException e) {
LOG.warn("Failed to find ugi of client set_ugi() is not successful, " +
"Continuing without it.", e);
} catch (TException e) {
LOG.warn("set_ugi() not successful, Likely cause: new client talking to old server. "
+ "Continuing without it.", e);
}
}
} catch (MetaException e) {
recentME = e;
String errMsg = "Failed to connect to metastore with URI (" + store
+ ") transport mode:" + transportMode + " in attempt " + attempt;
LOG.error(errMsg, e);
}
if (isConnected) {
break;
}
}
// Wait before launching the next round of connection retries.
if (!isConnected && retryDelaySeconds > 0) {
try {
LOG.info("Waiting " + retryDelaySeconds + " seconds before next connection attempt.");
Thread.sleep(retryDelaySeconds * 1000);
} catch (InterruptedException ignore) {}
}
}
if (!isConnected) {
// Either tte or recentME should be set but protect from a bug which causes both of them to
// be null. When MetaException wraps TTransportException, tte will be set so stringify that
// directly.
String exceptionString = "Unknown exception";
if (tte != null) {
exceptionString = StringUtils.stringifyException(tte);
} else if (recentME != null) {
exceptionString = StringUtils.stringifyException(recentME);
}
throw new MetaException("Could not connect to meta store using any of the URIs provided." +
" Most recent failure: " + exceptionString);
}
snapshotActiveConf();
}
// wraps the underlyingTransport in the appropriate transport based on mode of authentication
private TTransport createAuthBinaryTransport(URI store, TTransport underlyingTransport)
throws MetaException {
boolean isHttpTransportMode =
MetastoreConf.getVar(conf, ConfVars.METASTORE_CLIENT_THRIFT_TRANSPORT_MODE).
equalsIgnoreCase("http");
Preconditions.checkArgument(!isHttpTransportMode);
Preconditions.checkNotNull(underlyingTransport, "Underlying transport should not be null");
// default transport is the underlying one
TTransport transport = underlyingTransport;
boolean useFramedTransport =
MetastoreConf.getBoolVar(conf, ConfVars.USE_THRIFT_FRAMED_TRANSPORT);
boolean useSSL = MetastoreConf.getBoolVar(conf, ConfVars.USE_SSL);
boolean useSasl = MetastoreConf.getBoolVar(conf, ConfVars.USE_THRIFT_SASL);
String clientAuthMode = MetastoreConf.getVar(conf, ConfVars.METASTORE_CLIENT_AUTH_MODE);
boolean usePasswordAuth = false;
if (clientAuthMode != null) {
usePasswordAuth = "PLAIN".equalsIgnoreCase(clientAuthMode);
}
if (usePasswordAuth) {
// we are using PLAIN Sasl connection with user/password
LOG.debug("HMSC::open(): Creating plain authentication thrift connection.");
String userName = MetastoreConf.getVar(conf, ConfVars.METASTORE_CLIENT_PLAIN_USERNAME);
if (null == userName || userName.isEmpty()) {
throw new MetaException("No user specified for plain transport.");
}
// The password is not directly provided. It should be obtained from a keystore pointed
// by configuration "hadoop.security.credential.provider.path".
try {
String passwd = null;
char[] pwdCharArray = conf.getPassword(userName);
if (null != pwdCharArray) {
passwd = new String(pwdCharArray);
}
if (null == passwd) {
throw new MetaException("No password found for user " + userName);
}
// Overlay the SASL transport on top of the base socket transport (SSL or non-SSL)
transport = MetaStorePlainSaslHelper.getPlainTransport(userName, passwd, underlyingTransport);
} catch (IOException | TTransportException sasle) {
// IOException covers SaslException
LOG.error("Could not create client transport", sasle);
throw new MetaException(sasle.toString());
}
} else if (useSasl) {
// Wrap thrift connection with SASL for secure connection.
try {
HadoopThriftAuthBridge.Client authBridge =
HadoopThriftAuthBridge.getBridge().createClient();
// check if we should use delegation tokens to authenticate
// the call below gets hold of the tokens if they are set up by hadoop
// this should happen on the map/reduce tasks if the client added the
// tokens into hadoop's credential store in the front end during job
// submission.
String tokenSig = MetastoreConf.getVar(conf, ConfVars.TOKEN_SIGNATURE);
// tokenSig could be null
tokenStrForm = SecurityUtils.getTokenStrForm(tokenSig);
if (tokenStrForm != null) {
LOG.debug("HMSC::open(): Found delegation token. Creating DIGEST-based thrift connection.");
// authenticate using delegation tokens via the "DIGEST" mechanism
transport = authBridge.createClientTransport(null, store.getHost(),
"DIGEST", tokenStrForm, underlyingTransport,
MetaStoreUtils.getMetaStoreSaslProperties(conf, useSSL));
} else {
LOG.debug("HMSC::open(): Could not find delegation token. Creating KERBEROS-based thrift connection.");
String principalConfig =
MetastoreConf.getVar(conf, ConfVars.KERBEROS_PRINCIPAL);
transport = authBridge.createClientTransport(
principalConfig, store.getHost(), "KERBEROS", null,
underlyingTransport, MetaStoreUtils.getMetaStoreSaslProperties(conf, useSSL));
}
} catch (IOException ioe) {
LOG.error("Failed to create client transport", ioe);
throw new MetaException(ioe.toString());
}
} else {
if (useFramedTransport) {
try {
transport = new TFramedTransport(transport);
} catch (TTransportException e) {
LOG.error("Failed to create client transport", e);
throw new MetaException(e.toString());
}
}
}
return transport;
}
private void snapshotActiveConf() {
currentMetaVars = new HashMap<>(MetastoreConf.metaVars.length);
for (ConfVars oneVar : MetastoreConf.metaVars) {
currentMetaVars.put(oneVar.getVarname(), MetastoreConf.getAsString(conf, oneVar));
}
}
@Override
public String getTokenStrForm() throws IOException {
return tokenStrForm;
}
@Override
public void close() {
isConnected = false;
currentMetaVars = null;
try {
if (null != client) {
client.shutdown();
if ((transport == null) || !transport.isOpen()) {
final int newCount = connCount.decrementAndGet();
LOG.info("Closed a connection to metastore, current connections: {}",
newCount);
}
}
} catch (TException e) {
LOG.debug("Unable to shutdown metastore client. Will try closing transport directly.", e);
}
// Transport would have got closed via client.shutdown(), so we dont need this, but
// just in case, we make this call.
if ((transport != null) && transport.isOpen()) {
transport.close();
final int newCount = connCount.decrementAndGet();
LOG.info("Closed a connection to metastore, current connections: {}",
newCount);
if (LOG.isTraceEnabled()) {
LOG.trace("METASTORE CONNECTION TRACE - close [{}]",
System.identityHashCode(this), new Exception());
}
}
}
public static void setProcessorCapabilities(final String[] capabilities) {
processorCapabilities = capabilities != null ? Arrays.copyOf(capabilities, capabilities.length) : null;
}
public static void setProcessorIdentifier(final String id) {
processorIdentifier = id;
}
public static String[] getProcessorCapabilities() {
return processorCapabilities != null ? Arrays.copyOf(processorCapabilities, processorCapabilities.length) : null;
}
public static String getProcessorIdentifier() {
return processorIdentifier;
}
@Override
public void setMetaConf(String key, String value) throws TException {
client.setMetaConf(key, value);
}