You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@hive.apache.org by ga...@apache.org on 2017/11/03 23:26:42 UTC
[01/12] hive git commit: HIVE-17980 Moved HiveMetaStoreClient plus a
few remaining classes.
Repository: hive
Updated Branches:
refs/heads/standalone-metastore c2bbd5f4a -> 20c86d1ff
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/TestOldSchema.java
----------------------------------------------------------------------
diff --git a/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/TestOldSchema.java b/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/TestOldSchema.java
new file mode 100644
index 0000000..bf8556d
--- /dev/null
+++ b/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/TestOldSchema.java
@@ -0,0 +1,218 @@
+/*
+ * 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 java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hive.common.ndv.hll.HyperLogLog;
+import org.apache.hadoop.hive.metastore.api.AggrStats;
+import org.apache.hadoop.hive.metastore.api.ColumnStatistics;
+import org.apache.hadoop.hive.metastore.api.ColumnStatisticsData;
+import org.apache.hadoop.hive.metastore.api.ColumnStatisticsDesc;
+import org.apache.hadoop.hive.metastore.api.ColumnStatisticsObj;
+import org.apache.hadoop.hive.metastore.api.Database;
+import org.apache.hadoop.hive.metastore.api.FieldSchema;
+import org.apache.hadoop.hive.metastore.api.FileMetadataExprType;
+import org.apache.hadoop.hive.metastore.api.InvalidInputException;
+import org.apache.hadoop.hive.metastore.api.InvalidObjectException;
+import org.apache.hadoop.hive.metastore.api.LongColumnStatsData;
+import org.apache.hadoop.hive.metastore.api.MetaException;
+import org.apache.hadoop.hive.metastore.api.NoSuchObjectException;
+import org.apache.hadoop.hive.metastore.api.Partition;
+import org.apache.hadoop.hive.metastore.api.SerDeInfo;
+import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.conf.MetastoreConf;
+import org.apache.hadoop.hive.ql.io.sarg.SearchArgument;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class TestOldSchema {
+ private ObjectStore store = null;
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestOldSchema.class.getName());
+
+ public static class MockPartitionExpressionProxy implements PartitionExpressionProxy {
+ @Override
+ public String convertExprToFilter(byte[] expr) throws MetaException {
+ return null;
+ }
+
+ @Override
+ public boolean filterPartitionsByExpr(List<FieldSchema> partColumns, byte[] expr,
+ String defaultPartitionName,
+ List<String> partitionNames) throws MetaException {
+ return false;
+ }
+
+ @Override
+ public FileMetadataExprType getMetadataType(String inputFormat) {
+ return null;
+ }
+
+ @Override
+ public SearchArgument createSarg(byte[] expr) {
+ return null;
+ }
+
+ @Override
+ public FileFormatProxy getFileFormatProxy(FileMetadataExprType type) {
+ return null;
+ }
+ }
+
+ private byte bitVectors[][] = new byte[2][];
+
+ @Before
+ public void setUp() throws Exception {
+ Configuration conf = MetastoreConf.newMetastoreConf();
+ MetastoreConf.setClass(conf, MetastoreConf.ConfVars.EXPRESSION_PROXY_CLASS,
+ MockPartitionExpressionProxy.class, PartitionExpressionProxy.class);
+ MetastoreConf.setBoolVar(conf, MetastoreConf.ConfVars.STATS_FETCH_BITVECTOR, false);
+
+ store = new ObjectStore();
+ store.setConf(conf);
+ dropAllStoreObjects(store);
+
+ HyperLogLog hll = HyperLogLog.builder().build();
+ hll.addLong(1);
+ bitVectors[1] = hll.serialize();
+ hll = HyperLogLog.builder().build();
+ hll.addLong(2);
+ hll.addLong(3);
+ hll.addLong(3);
+ hll.addLong(4);
+ bitVectors[0] = hll.serialize();
+ }
+
+ @After
+ public void tearDown() {
+ }
+
+ /**
+ * Tests partition operations
+ */
+ @Test
+ public void testPartitionOps() throws Exception {
+ String dbName = "default";
+ String tableName = "snp";
+ Database db1 = new Database(dbName, "description", "locationurl", null);
+ store.createDatabase(db1);
+ long now = System.currentTimeMillis();
+ List<FieldSchema> cols = new ArrayList<>();
+ cols.add(new FieldSchema("col1", "long", "nocomment"));
+ SerDeInfo serde = new SerDeInfo("serde", "seriallib", null);
+ StorageDescriptor sd = new StorageDescriptor(cols, "file:/tmp", "input", "output", false, 0,
+ serde, null, null, Collections.emptyMap());
+ List<FieldSchema> partCols = new ArrayList<>();
+ partCols.add(new FieldSchema("ds", "string", ""));
+ Table table = new Table(tableName, dbName, "me", (int) now, (int) now, 0, sd, partCols,
+ Collections.emptyMap(), null, null, null);
+ store.createTable(table);
+
+ Deadline.startTimer("getPartition");
+ for (int i = 0; i < 10; i++) {
+ List<String> partVal = new ArrayList<>();
+ partVal.add(String.valueOf(i));
+ StorageDescriptor psd = new StorageDescriptor(sd);
+ psd.setLocation("file:/tmp/default/hit/ds=" + partVal);
+ Partition part = new Partition(partVal, dbName, tableName, (int) now, (int) now, psd,
+ Collections.emptyMap());
+ store.addPartition(part);
+ ColumnStatistics cs = new ColumnStatistics();
+ ColumnStatisticsDesc desc = new ColumnStatisticsDesc(false, dbName, tableName);
+ desc.setLastAnalyzed(now);
+ desc.setPartName("ds=" + String.valueOf(i));
+ cs.setStatsDesc(desc);
+ ColumnStatisticsObj obj = new ColumnStatisticsObj();
+ obj.setColName("col1");
+ obj.setColType("bigint");
+ ColumnStatisticsData data = new ColumnStatisticsData();
+ LongColumnStatsData dcsd = new LongColumnStatsData();
+ dcsd.setHighValue(1000 + i);
+ dcsd.setLowValue(-1000 - i);
+ dcsd.setNumNulls(i);
+ dcsd.setNumDVs(10 * i + 1);
+ dcsd.setBitVectors(bitVectors[0]);
+ data.setLongStats(dcsd);
+ obj.setStatsData(data);
+ cs.addToStatsObj(obj);
+ store.updatePartitionColumnStatistics(cs, partVal);
+
+ }
+
+ Checker statChecker = new Checker() {
+ @Override
+ public void checkStats(AggrStats aggrStats) throws Exception {
+ Assert.assertEquals(10, aggrStats.getPartsFound());
+ Assert.assertEquals(1, aggrStats.getColStatsSize());
+ ColumnStatisticsObj cso = aggrStats.getColStats().get(0);
+ Assert.assertEquals("col1", cso.getColName());
+ Assert.assertEquals("bigint", cso.getColType());
+ LongColumnStatsData lcsd = cso.getStatsData().getLongStats();
+ Assert.assertEquals(1009, lcsd.getHighValue(), 0.01);
+ Assert.assertEquals(-1009, lcsd.getLowValue(), 0.01);
+ Assert.assertEquals(45, lcsd.getNumNulls());
+ Assert.assertEquals(91, lcsd.getNumDVs());
+ }
+ };
+ List<String> partNames = new ArrayList<>();
+ for (int i = 0; i < 10; i++) {
+ partNames.add("ds=" + i);
+ }
+ AggrStats aggrStats = store.get_aggr_stats_for(dbName, tableName, partNames,
+ Arrays.asList("col1"));
+ statChecker.checkStats(aggrStats);
+
+ }
+
+ private interface Checker {
+ void checkStats(AggrStats aggrStats) throws Exception;
+ }
+
+ private static void dropAllStoreObjects(RawStore store) throws MetaException,
+ InvalidObjectException, InvalidInputException {
+ try {
+ Deadline.registerIfNot(100000);
+ Deadline.startTimer("getPartition");
+ List<String> dbs = store.getAllDatabases();
+ for (int i = 0; i < dbs.size(); i++) {
+ String db = dbs.get(i);
+ List<String> tbls = store.getAllTables(db);
+ for (String tbl : tbls) {
+ List<Partition> parts = store.getPartitions(db, tbl, 100);
+ for (Partition part : parts) {
+ store.dropPartition(db, tbl, part.getValues());
+ }
+ store.dropTable(db, tbl);
+ }
+ store.dropDatabase(db);
+ }
+ } catch (NoSuchObjectException e) {
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/VerifyingObjectStore.java
----------------------------------------------------------------------
diff --git a/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/VerifyingObjectStore.java b/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/VerifyingObjectStore.java
new file mode 100644
index 0000000..150b6ca
--- /dev/null
+++ b/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/VerifyingObjectStore.java
@@ -0,0 +1,217 @@
+/*
+ * 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.commons.lang.StringUtils.repeat;
+
+import java.lang.reflect.AccessibleObject;
+import java.lang.reflect.Array;
+import java.lang.reflect.Field;
+import java.lang.reflect.Modifier;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.commons.lang.ClassUtils;
+import org.apache.commons.lang.builder.EqualsBuilder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.apache.hadoop.hive.metastore.api.ColumnStatistics;
+import org.apache.hadoop.hive.metastore.api.MetaException;
+import org.apache.hadoop.hive.metastore.api.NoSuchObjectException;
+import org.apache.hadoop.hive.metastore.api.Partition;
+import org.apache.thrift.TException;
+
+public class VerifyingObjectStore extends ObjectStore {
+ private static final Logger LOG = LoggerFactory.getLogger(VerifyingObjectStore.class);
+
+ public VerifyingObjectStore() {
+ super();
+ LOG.warn(getClass().getSimpleName() + " is being used - test run");
+ }
+
+ @Override
+ public List<Partition> getPartitionsByFilter(String dbName, String tblName, String filter,
+ short maxParts) throws MetaException, NoSuchObjectException {
+ List<Partition> sqlResults = getPartitionsByFilterInternal(
+ dbName, tblName, filter, maxParts, true, false);
+ List<Partition> ormResults = getPartitionsByFilterInternal(
+ dbName, tblName, filter, maxParts, false, true);
+ verifyLists(sqlResults, ormResults, Partition.class);
+ return sqlResults;
+ }
+
+ @Override
+ public List<Partition> getPartitionsByNames(String dbName, String tblName,
+ List<String> partNames) throws MetaException, NoSuchObjectException {
+ List<Partition> sqlResults = getPartitionsByNamesInternal(
+ dbName, tblName, partNames, true, false);
+ List<Partition> ormResults = getPartitionsByNamesInternal(
+ dbName, tblName, partNames, false, true);
+ verifyLists(sqlResults, ormResults, Partition.class);
+ return sqlResults;
+ }
+
+ @Override
+ public boolean getPartitionsByExpr(String dbName, String tblName, byte[] expr,
+ String defaultPartitionName, short maxParts, List<Partition> result) throws TException {
+ List<Partition> ormParts = new LinkedList<>();
+ boolean sqlResult = getPartitionsByExprInternal(
+ dbName, tblName, expr, defaultPartitionName, maxParts, result, true, false);
+ boolean ormResult = getPartitionsByExprInternal(
+ dbName, tblName, expr, defaultPartitionName, maxParts, ormParts, false, true);
+ if (sqlResult != ormResult) {
+ String msg = "The unknown flag is different - SQL " + sqlResult + ", ORM " + ormResult;
+ LOG.error(msg);
+ throw new MetaException(msg);
+ }
+ verifyLists(result, ormParts, Partition.class);
+ return sqlResult;
+ }
+
+ @Override
+ public List<Partition> getPartitions(
+ String dbName, String tableName, int maxParts) throws MetaException, NoSuchObjectException {
+ List<Partition> sqlResults = getPartitionsInternal(dbName, tableName, maxParts, true, false);
+ List<Partition> ormResults = getPartitionsInternal(dbName, tableName, maxParts, false, true);
+ verifyLists(sqlResults, ormResults, Partition.class);
+ return sqlResults;
+ }
+
+ @Override
+ public ColumnStatistics getTableColumnStatistics(String dbName,
+ String tableName, List<String> colNames) throws MetaException, NoSuchObjectException {
+ ColumnStatistics sqlResult = getTableColumnStatisticsInternal(
+ dbName, tableName, colNames, true, false);
+ ColumnStatistics jdoResult = getTableColumnStatisticsInternal(
+ dbName, tableName, colNames, false, true);
+ verifyObjects(sqlResult, jdoResult, ColumnStatistics.class);
+ return sqlResult;
+ }
+
+ @Override
+ public List<ColumnStatistics> getPartitionColumnStatistics(String dbName,
+ String tableName, List<String> partNames, List<String> colNames)
+ throws MetaException, NoSuchObjectException {
+ List<ColumnStatistics> sqlResult = getPartitionColumnStatisticsInternal(
+ dbName, tableName, partNames, colNames, true, false);
+ List<ColumnStatistics> jdoResult = getPartitionColumnStatisticsInternal(
+ dbName, tableName, partNames, colNames, false, true);
+ verifyLists(sqlResult, jdoResult, ColumnStatistics.class);
+ return sqlResult;
+ }
+
+ private void verifyObjects(
+ Object sqlResult, Object jdoResult, Class<?> clazz) throws MetaException {
+ if (EqualsBuilder.reflectionEquals(sqlResult, jdoResult)) return;
+ StringBuilder errorStr = new StringBuilder("Objects are different: \n");
+ try {
+ dumpObject(errorStr, "SQL", sqlResult, clazz, 0);
+ errorStr.append("\n");
+ dumpObject(errorStr, "ORM", jdoResult, clazz, 0);
+ } catch (Throwable t) {
+ errorStr.append("Error getting the diff: " + t);
+ }
+ LOG.error("Different results: \n" + errorStr.toString());
+ throw new MetaException("Different results from SQL and ORM, see log for details");
+ }
+
+ private <T> void verifyLists(Collection<T> sqlResults, Collection<T> ormResults,
+ Class<?> clazz) throws MetaException {
+ final int MAX_DIFFS = 5;
+ if (sqlResults.size() != ormResults.size()) {
+ String msg = "Lists are not the same size: SQL " + sqlResults.size()
+ + ", ORM " + ormResults.size();
+ LOG.error(msg);
+ throw new MetaException(msg);
+ }
+
+ Iterator<T> sqlIter = sqlResults.iterator(), ormIter = ormResults.iterator();
+ StringBuilder errorStr = new StringBuilder();
+ int errors = 0;
+ for (int partIx = 0; partIx < sqlResults.size(); ++partIx) {
+ assert sqlIter.hasNext() && ormIter.hasNext();
+ T p1 = sqlIter.next(), p2 = ormIter.next();
+ if (EqualsBuilder.reflectionEquals(p1, p2)) continue;
+ errorStr.append("Results are different at list index " + partIx + ": \n");
+ try {
+ dumpObject(errorStr, "SQL", p1, clazz, 0);
+ errorStr.append("\n");
+ dumpObject(errorStr, "ORM", p2, clazz, 0);
+ errorStr.append("\n\n");
+ } catch (Throwable t) {
+ String msg = "Error getting the diff at list index " + partIx;
+ errorStr.append("\n\n" + msg);
+ LOG.error(msg, t);
+ break;
+ }
+ if (++errors == MAX_DIFFS) {
+ errorStr.append("\n\nToo many diffs, giving up (lists might be sorted differently)");
+ break;
+ }
+ }
+ if (errorStr.length() > 0) {
+ LOG.error("Different results: \n" + errorStr.toString());
+ throw new MetaException("Different results from SQL and ORM, see log for details");
+ }
+ }
+
+ private static void dumpObject(StringBuilder errorStr, String name, Object p,
+ Class<?> c, int level) throws IllegalAccessException {
+ String offsetStr = repeat(" ", level);
+ if (p == null || c == String.class || c.isPrimitive()
+ || ClassUtils.wrapperToPrimitive(c) != null) {
+ errorStr.append(offsetStr).append(name + ": [" + p + "]\n");
+ } else if (ClassUtils.isAssignable(c, Iterable.class)) {
+ errorStr.append(offsetStr).append(name + " is an iterable\n");
+ Iterator<?> i1 = ((Iterable<?>)p).iterator();
+ int i = 0;
+ while (i1.hasNext()) {
+ Object o1 = i1.next();
+ Class<?> t = o1 == null ? Object.class : o1.getClass(); // ...
+ dumpObject(errorStr, name + "[" + (i++) + "]", o1, t, level + 1);
+ }
+ } else if (c.isArray()) {
+ int len = Array.getLength(p);
+ Class<?> t = c.getComponentType();
+ errorStr.append(offsetStr).append(name + " is an array\n");
+ for (int i = 0; i < len; ++i) {
+ dumpObject(errorStr, name + "[" + i + "]", Array.get(p, i), t, level + 1);
+ }
+ } else if (ClassUtils.isAssignable(c, Map.class)) {
+ Map<?,?> c1 = (Map<?,?>)p;
+ errorStr.append(offsetStr).append(name + " is a map\n");
+ dumpObject(errorStr, name + ".keys", c1.keySet(), Set.class, level + 1);
+ dumpObject(errorStr, name + ".vals", c1.values(), Collection.class, level + 1);
+ } else {
+ errorStr.append(offsetStr).append(name + " is of type " + c.getCanonicalName() + "\n");
+ // TODO: this doesn't include superclass.
+ Field[] fields = c.getDeclaredFields();
+ AccessibleObject.setAccessible(fields, true);
+ for (int i = 0; i < fields.length; i++) {
+ Field f = fields[i];
+ if (f.getName().indexOf('$') != -1 || Modifier.isStatic(f.getModifiers())) continue;
+ dumpObject(errorStr, name + "." + f.getName(), f.get(p), f.getType(), level + 1);
+ }
+ }
+ }
+}
[12/12] hive git commit: HIVE-17980 Moved HiveMetaStoreClient plus a
few remaining classes.
Posted by ga...@apache.org.
HIVE-17980 Moved HiveMetaStoreClient plus a few remaining classes.
Project: http://git-wip-us.apache.org/repos/asf/hive/repo
Commit: http://git-wip-us.apache.org/repos/asf/hive/commit/20c86d1f
Tree: http://git-wip-us.apache.org/repos/asf/hive/tree/20c86d1f
Diff: http://git-wip-us.apache.org/repos/asf/hive/diff/20c86d1f
Branch: refs/heads/standalone-metastore
Commit: 20c86d1ff4b114d7c6cffefe2f6bca702ede0c53
Parents: c2bbd5f
Author: Alan Gates <al...@gmail.com>
Authored: Wed Sep 6 19:00:14 2017 -0700
Committer: Alan Gates <ga...@hortonworks.com>
Committed: Fri Nov 3 16:25:52 2017 -0700
----------------------------------------------------------------------
.../hive/accumulo/AccumuloStorageHandler.java | 2 +-
.../hadoop/hive/druid/DruidStorageHandler.java | 2 +-
.../hadoop/hive/hbase/HBaseStorageHandler.java | 2 +-
hcatalog/core/pom.xml | 2 +-
.../hive/hcatalog/common/HiveClientCache.java | 2 +-
.../mapreduce/FileOutputCommitterContainer.java | 4 +-
.../mapreduce/FileOutputFormatContainer.java | 4 +-
.../hive/hcatalog/mapreduce/InternalUtil.java | 2 +-
.../apache/hive/hcatalog/cli/TestPermsGrp.java | 1 -
.../mapreduce/TestHCatPartitionPublish.java | 1 -
.../listener/DbNotificationListener.java | 2 +-
.../streaming/DelimitedInputWriter.java | 3 +-
.../hcatalog/streaming/StrictJsonWriter.java | 2 +-
.../hcatalog/streaming/StrictRegexWriter.java | 2 +-
hcatalog/webhcat/java-client/pom.xml | 2 +-
.../hive/hcatalog/api/HCatClientHMSImpl.java | 5 +-
hcatalog/webhcat/svr/pom.xml | 2 +-
itests/hcatalog-unit/pom.xml | 2 +-
.../hive/hcatalog/hbase/ManyMiniCluster.java | 4 +-
itests/hive-blobstore/pom.xml | 4 +-
itests/hive-minikdc/pom.xml | 4 +-
itests/hive-unit-hadoop2/pom.xml | 2 +-
itests/hive-unit/pom.xml | 2 +-
.../AbstractTestAuthorizationApiAuthorizer.java | 1 +
.../hadoop/hive/metastore/TestFilterHooks.java | 4 +
.../hive/metastore/TestHiveMetaStore.java | 3 +-
...TestHiveMetaStoreWithEnvironmentContext.java | 1 +
.../hive/metastore/TestMarkPartitionRemote.java | 1 +
.../metastore/TestMetaStoreAuthorization.java | 1 +
.../TestMetaStoreEndFunctionListener.java | 1 +
.../metastore/TestMetaStoreEventListener.java | 1 +
.../TestMetaStoreEventListenerOnlyOnCommit.java | 1 +
.../metastore/TestMetaStoreInitListener.java | 1 +
.../metastore/TestMetaStoreListenersError.java | 1 +
.../hive/metastore/TestMetaStoreMetrics.java | 1 +
.../hive/metastore/TestRemoteHiveMetaStore.java | 1 +
.../TestRemoteHiveMetaStoreIpAddress.java | 1 +
.../hive/metastore/TestRetryingHMSHandler.java | 1 +
.../hive/ql/parse/TestReplicationScenarios.java | 1 +
.../hive/serde2/TestSerdeWithFieldComments.java | 4 +-
.../thrift/TestThriftCliServiceMessageSize.java | 14 +-
itests/qtest-accumulo/pom.xml | 4 +-
itests/qtest-spark/pom.xml | 4 +-
itests/qtest/pom.xml | 4 +-
itests/util/pom.xml | 2 +-
llap-server/pom.xml | 2 +-
metastore/pom.xml | 22 -
.../hive/metastore/HiveMetaStoreClient.java | 2719 ------------------
.../hive/metastore/HiveMetaStoreUtils.java | 213 ++
.../hadoop/hive/metastore/IMetaStoreClient.java | 1800 ------------
.../hadoop/hive/metastore/MetaStoreUtils.java | 1092 -------
.../hive/metastore/RetryingMetaStoreClient.java | 286 --
.../metastore/SerDeStorageSchemaReader.java | 4 +-
.../hive/metastore/messaging/EventUtils.java | 202 --
.../messaging/event/filters/AndFilter.java | 39 -
.../messaging/event/filters/BasicFilter.java | 33 -
.../event/filters/DatabaseAndTableFilter.java | 52 -
.../event/filters/EventBoundaryFilter.java | 34 -
.../event/filters/MessageFormatFilter.java | 36 -
.../hive/metastore/tools/HiveMetaTool.java | 487 ----
.../metastore/AlternateFailurePreListener.java | 62 -
.../metastore/DummyEndFunctionListener.java | 47 -
.../hadoop/hive/metastore/DummyListener.java | 144 -
.../metastore/DummyMetaStoreInitListener.java | 44 -
.../hadoop/hive/metastore/DummyPreListener.java | 49 -
.../DummyRawStoreControlledCommit.java | 999 -------
.../InjectableBehaviourObjectStore.java | 104 -
.../hive/metastore/IpAddressListener.java | 103 -
.../hive/metastore/MetaStoreTestUtils.java | 164 --
.../MockPartitionExpressionForMetastore.java | 59 -
.../metastore/TestHiveMetaStoreGetMetaConf.java | 138 -
.../TestHiveMetaStorePartitionSpecs.java | 409 ---
.../metastore/TestHiveMetaStoreTimeout.java | 142 -
.../hadoop/hive/metastore/TestOldSchema.java | 220 --
.../hive/metastore/VerifyingObjectStore.java | 217 --
ql/pom.xml | 2 +-
.../java/org/apache/hadoop/hive/ql/Driver.java | 7 +-
.../org/apache/hadoop/hive/ql/QueryState.java | 6 +-
.../hadoop/hive/ql/exec/ArchiveUtils.java | 2 +-
.../org/apache/hadoop/hive/ql/exec/DDLTask.java | 5 +-
.../hadoop/hive/ql/exec/FetchOperator.java | 1 -
.../apache/hadoop/hive/ql/exec/MoveTask.java | 2 +-
.../apache/hadoop/hive/ql/exec/StatsTask.java | 4 +-
.../apache/hadoop/hive/ql/exec/Utilities.java | 2 +-
.../hadoop/hive/ql/exec/tez/DagUtils.java | 4 +-
.../org/apache/hadoop/hive/ql/io/AcidUtils.java | 1 -
.../hive/ql/io/CombineHiveInputFormat.java | 1 -
.../hadoop/hive/ql/io/HiveInputFormat.java | 1 -
.../apache/hadoop/hive/ql/metadata/Hive.java | 15 +-
.../hadoop/hive/ql/metadata/Partition.java | 11 +-
.../ql/metadata/SessionHiveMetaStoreClient.java | 11 +-
.../apache/hadoop/hive/ql/metadata/Table.java | 9 +-
.../formatting/TextMetaDataFormatter.java | 2 +-
.../ql/optimizer/AbstractBucketJoinProc.java | 1 -
.../BucketingSortingReduceSinkOptimizer.java | 1 -
.../hadoop/hive/ql/optimizer/SamplePruner.java | 1 -
.../hive/ql/optimizer/StatsOptimizer.java | 2 +-
.../optimizer/physical/SamplingOptimizer.java | 1 -
.../hive/ql/parse/DDLSemanticAnalyzer.java | 2 +-
.../hive/ql/parse/ExportSemanticAnalyzer.java | 33 -
.../hive/ql/parse/ImportSemanticAnalyzer.java | 1 -
.../hive/ql/parse/LoadSemanticAnalyzer.java | 1 -
.../hadoop/hive/ql/parse/SemanticAnalyzer.java | 21 +-
.../hadoop/hive/ql/plan/CreateTableDesc.java | 2 +-
.../hadoop/hive/ql/plan/FileSinkDesc.java | 1 -
.../hadoop/hive/ql/plan/LoadTableDesc.java | 1 -
.../hadoop/hive/ql/plan/PartitionDesc.java | 4 +-
.../apache/hadoop/hive/ql/plan/PlanUtils.java | 13 +-
.../AuthorizationPreEventListener.java | 2 +-
.../hive/ql/txn/compactor/CompactorMR.java | 1 -
.../hadoop/hive/ql/txn/compactor/Initiator.java | 1 -
.../apache/hadoop/hive/ql/TestTxnCommands.java | 3 +-
service/pom.xml | 2 +-
.../thrift/EmbeddedThriftBinaryCLIService.java | 2 +-
.../apache/hive/service/server/HiveServer2.java | 6 +-
.../thrift/ThriftCliServiceTestWithCookie.java | 1 -
standalone-metastore/pom.xml | 29 +-
.../hadoop/hive/metastore/ColumnType.java | 63 +-
.../hadoop/hive/metastore/HiveAlterHandler.java | 18 +-
.../hive/metastore/HiveMetaStoreClient.java | 2686 +++++++++++++++++
.../hadoop/hive/metastore/IMetaStoreClient.java | 1799 ++++++++++++
.../hadoop/hive/metastore/RawStoreProxy.java | 2 +-
.../hive/metastore/RetryingMetaStoreClient.java | 287 ++
.../hive/metastore/messaging/EventUtils.java | 202 ++
.../messaging/event/filters/AndFilter.java | 39 +
.../messaging/event/filters/BasicFilter.java | 33 +
.../event/filters/DatabaseAndTableFilter.java | 52 +
.../event/filters/EventBoundaryFilter.java | 34 +
.../event/filters/MessageFormatFilter.java | 36 +
.../hive/metastore/tools/HiveMetaTool.java | 484 ++++
.../hadoop/hive/metastore/utils/FileUtils.java | 29 +
.../hive/metastore/utils/MetaStoreUtils.java | 497 +++-
.../hive/metastore/utils/SecurityUtils.java | 26 +
.../metastore/AlternateFailurePreListener.java | 62 +
.../metastore/DummyEndFunctionListener.java | 47 +
.../hadoop/hive/metastore/DummyListener.java | 144 +
.../metastore/DummyMetaStoreInitListener.java | 39 +
.../hadoop/hive/metastore/DummyPreListener.java | 49 +
.../DummyRawStoreControlledCommit.java | 999 +++++++
.../InjectableBehaviourObjectStore.java | 104 +
.../hive/metastore/IpAddressListener.java | 102 +
.../hive/metastore/MetaStoreTestUtils.java | 165 ++
.../MockPartitionExpressionForMetastore.java | 58 +
.../metastore/TestHiveMetaStoreGetMetaConf.java | 136 +
.../TestHiveMetaStorePartitionSpecs.java | 406 +++
.../metastore/TestHiveMetaStoreTimeout.java | 139 +
.../hadoop/hive/metastore/TestOldSchema.java | 218 ++
.../hive/metastore/VerifyingObjectStore.java | 217 ++
148 files changed, 9543 insertions(+), 9880 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/accumulo-handler/src/java/org/apache/hadoop/hive/accumulo/AccumuloStorageHandler.java
----------------------------------------------------------------------
diff --git a/accumulo-handler/src/java/org/apache/hadoop/hive/accumulo/AccumuloStorageHandler.java b/accumulo-handler/src/java/org/apache/hadoop/hive/accumulo/AccumuloStorageHandler.java
index 5391a99..872f12b 100644
--- a/accumulo-handler/src/java/org/apache/hadoop/hive/accumulo/AccumuloStorageHandler.java
+++ b/accumulo-handler/src/java/org/apache/hadoop/hive/accumulo/AccumuloStorageHandler.java
@@ -32,10 +32,10 @@ import org.apache.hadoop.hive.accumulo.serde.AccumuloIndexParameters;
import org.apache.hadoop.hive.accumulo.serde.AccumuloSerDe;
import org.apache.hadoop.hive.accumulo.serde.AccumuloSerDeParameters;
import org.apache.hadoop.hive.metastore.HiveMetaHook;
-import org.apache.hadoop.hive.metastore.MetaStoreUtils;
import org.apache.hadoop.hive.metastore.api.MetaException;
import org.apache.hadoop.hive.metastore.api.Table;
import org.apache.hadoop.hive.metastore.api.hive_metastoreConstants;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
import org.apache.hadoop.hive.ql.metadata.DefaultStorageHandler;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.metadata.HiveStoragePredicateHandler;
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/druid-handler/src/java/org/apache/hadoop/hive/druid/DruidStorageHandler.java
----------------------------------------------------------------------
diff --git a/druid-handler/src/java/org/apache/hadoop/hive/druid/DruidStorageHandler.java b/druid-handler/src/java/org/apache/hadoop/hive/druid/DruidStorageHandler.java
index 8117633..fe66a44 100644
--- a/druid-handler/src/java/org/apache/hadoop/hive/druid/DruidStorageHandler.java
+++ b/druid-handler/src/java/org/apache/hadoop/hive/druid/DruidStorageHandler.java
@@ -42,10 +42,10 @@ import org.apache.hadoop.hive.druid.security.KerberosHttpClient;
import org.apache.hadoop.hive.druid.serde.DruidSerDe;
import org.apache.hadoop.hive.metastore.DefaultHiveMetaHook;
import org.apache.hadoop.hive.metastore.HiveMetaHook;
-import org.apache.hadoop.hive.metastore.MetaStoreUtils;
import org.apache.hadoop.hive.metastore.Warehouse;
import org.apache.hadoop.hive.metastore.api.MetaException;
import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.metadata.HiveStorageHandler;
import org.apache.hadoop.hive.ql.plan.TableDesc;
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/hbase-handler/src/java/org/apache/hadoop/hive/hbase/HBaseStorageHandler.java
----------------------------------------------------------------------
diff --git a/hbase-handler/src/java/org/apache/hadoop/hive/hbase/HBaseStorageHandler.java b/hbase-handler/src/java/org/apache/hadoop/hive/hbase/HBaseStorageHandler.java
index 9cad97a..4b00762 100644
--- a/hbase-handler/src/java/org/apache/hadoop/hive/hbase/HBaseStorageHandler.java
+++ b/hbase-handler/src/java/org/apache/hadoop/hive/hbase/HBaseStorageHandler.java
@@ -47,10 +47,10 @@ import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.hbase.ColumnMappings.ColumnMapping;
import org.apache.hadoop.hive.metastore.HiveMetaHook;
-import org.apache.hadoop.hive.metastore.MetaStoreUtils;
import org.apache.hadoop.hive.metastore.api.MetaException;
import org.apache.hadoop.hive.metastore.api.Table;
import org.apache.hadoop.hive.metastore.api.hive_metastoreConstants;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
import org.apache.hadoop.hive.ql.exec.FunctionRegistry;
import org.apache.hadoop.hive.ql.index.IndexPredicateAnalyzer;
import org.apache.hadoop.hive.ql.index.IndexSearchCondition;
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/hcatalog/core/pom.xml
----------------------------------------------------------------------
diff --git a/hcatalog/core/pom.xml b/hcatalog/core/pom.xml
index 94e9fbe..560e438 100644
--- a/hcatalog/core/pom.xml
+++ b/hcatalog/core/pom.xml
@@ -69,7 +69,7 @@
</dependency>
<dependency>
<groupId>org.apache.hive</groupId>
- <artifactId>hive-metastore</artifactId>
+ <artifactId>hive-standalone-metastore</artifactId>
<version>${project.version}</version>
<type>test-jar</type>
<scope>test</scope>
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/hcatalog/core/src/main/java/org/apache/hive/hcatalog/common/HiveClientCache.java
----------------------------------------------------------------------
diff --git a/hcatalog/core/src/main/java/org/apache/hive/hcatalog/common/HiveClientCache.java b/hcatalog/core/src/main/java/org/apache/hive/hcatalog/common/HiveClientCache.java
index c1b63d9..3569ffc 100644
--- a/hcatalog/core/src/main/java/org/apache/hive/hcatalog/common/HiveClientCache.java
+++ b/hcatalog/core/src/main/java/org/apache/hive/hcatalog/common/HiveClientCache.java
@@ -76,7 +76,7 @@ class HiveClientCache {
// Since HiveMetaStoreClient is not threadsafe, hive clients are not shared across threads.
// Thread local variable containing each thread's unique ID, is used as one of the keys for the cache
- // causing each thread to get a different client even if the hiveConf is same.
+ // causing each thread to get a different client even if the conf is same.
private static final ThreadLocal<Integer> threadId =
new ThreadLocal<Integer>() {
@Override
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/hcatalog/core/src/main/java/org/apache/hive/hcatalog/mapreduce/FileOutputCommitterContainer.java
----------------------------------------------------------------------
diff --git a/hcatalog/core/src/main/java/org/apache/hive/hcatalog/mapreduce/FileOutputCommitterContainer.java b/hcatalog/core/src/main/java/org/apache/hive/hcatalog/mapreduce/FileOutputCommitterContainer.java
index 04d78ee..39a4d2d 100644
--- a/hcatalog/core/src/main/java/org/apache/hive/hcatalog/mapreduce/FileOutputCommitterContainer.java
+++ b/hcatalog/core/src/main/java/org/apache/hive/hcatalog/mapreduce/FileOutputCommitterContainer.java
@@ -38,7 +38,6 @@ import org.apache.hadoop.hive.common.FileUtils;
import org.apache.hadoop.hive.common.StatsSetupConst;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.IMetaStoreClient;
-import org.apache.hadoop.hive.metastore.MetaStoreUtils;
import org.apache.hadoop.hive.metastore.Warehouse;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.InvalidOperationException;
@@ -610,7 +609,8 @@ class FileOutputCommitterContainer extends OutputCommitterContainer {
}
} else {
- if(immutable && fs.exists(finalOutputPath) && !MetaStoreUtils.isDirEmpty(fs, finalOutputPath)) {
+ if(immutable && fs.exists(finalOutputPath) &&
+ !org.apache.hadoop.hive.metastore.utils.FileUtils.isDirEmpty(fs, finalOutputPath)) {
throw new HCatException(ErrorType.ERROR_DUPLICATE_PARTITION, "Data already exists in " + finalOutputPath
+ ", duplicate publish not possible.");
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/hcatalog/core/src/main/java/org/apache/hive/hcatalog/mapreduce/FileOutputFormatContainer.java
----------------------------------------------------------------------
diff --git a/hcatalog/core/src/main/java/org/apache/hive/hcatalog/mapreduce/FileOutputFormatContainer.java b/hcatalog/core/src/main/java/org/apache/hive/hcatalog/mapreduce/FileOutputFormatContainer.java
index 3ecb608..10eda77 100644
--- a/hcatalog/core/src/main/java/org/apache/hive/hcatalog/mapreduce/FileOutputFormatContainer.java
+++ b/hcatalog/core/src/main/java/org/apache/hive/hcatalog/mapreduce/FileOutputFormatContainer.java
@@ -23,7 +23,7 @@ import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.IMetaStoreClient;
-import org.apache.hadoop.hive.metastore.MetaStoreUtils;
+import org.apache.hadoop.hive.metastore.utils.FileUtils;
import org.apache.hadoop.hive.ql.metadata.HiveStorageHandler;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.MetaException;
@@ -202,7 +202,7 @@ class FileOutputFormatContainer extends OutputFormatContainer {
Path tablePath = new Path(table.getTTable().getSd().getLocation());
FileSystem fs = tablePath.getFileSystem(context.getConfiguration());
- if (!MetaStoreUtils.isDirEmpty(fs,tablePath)){
+ if (!FileUtils.isDirEmpty(fs,tablePath)){
throw new HCatException(ErrorType.ERROR_NON_EMPTY_TABLE,
table.getDbName() + "." + table.getTableName());
}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/hcatalog/core/src/main/java/org/apache/hive/hcatalog/mapreduce/InternalUtil.java
----------------------------------------------------------------------
diff --git a/hcatalog/core/src/main/java/org/apache/hive/hcatalog/mapreduce/InternalUtil.java b/hcatalog/core/src/main/java/org/apache/hive/hcatalog/mapreduce/InternalUtil.java
index 8fd676f..6c4c5e1 100644
--- a/hcatalog/core/src/main/java/org/apache/hive/hcatalog/mapreduce/InternalUtil.java
+++ b/hcatalog/core/src/main/java/org/apache/hive/hcatalog/mapreduce/InternalUtil.java
@@ -20,10 +20,10 @@
package org.apache.hive.hcatalog.mapreduce;
import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.hive.metastore.MetaStoreUtils;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.Partition;
import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
import org.apache.hadoop.hive.ql.metadata.Table;
import org.apache.hadoop.hive.serde.serdeConstants;
import org.apache.hadoop.hive.serde2.Deserializer;
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/hcatalog/core/src/test/java/org/apache/hive/hcatalog/cli/TestPermsGrp.java
----------------------------------------------------------------------
diff --git a/hcatalog/core/src/test/java/org/apache/hive/hcatalog/cli/TestPermsGrp.java b/hcatalog/core/src/test/java/org/apache/hive/hcatalog/cli/TestPermsGrp.java
index 80c5d63..817a635 100644
--- a/hcatalog/core/src/test/java/org/apache/hive/hcatalog/cli/TestPermsGrp.java
+++ b/hcatalog/core/src/test/java/org/apache/hive/hcatalog/cli/TestPermsGrp.java
@@ -32,7 +32,6 @@ import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.HiveMetaStoreClient;
import org.apache.hadoop.hive.metastore.MetaStoreTestUtils;
-import org.apache.hadoop.hive.metastore.MetaStoreUtils;
import org.apache.hadoop.hive.metastore.Warehouse;
import org.apache.hadoop.hive.metastore.api.AlreadyExistsException;
import org.apache.hadoop.hive.metastore.api.Database;
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/hcatalog/core/src/test/java/org/apache/hive/hcatalog/mapreduce/TestHCatPartitionPublish.java
----------------------------------------------------------------------
diff --git a/hcatalog/core/src/test/java/org/apache/hive/hcatalog/mapreduce/TestHCatPartitionPublish.java b/hcatalog/core/src/test/java/org/apache/hive/hcatalog/mapreduce/TestHCatPartitionPublish.java
index a000642..1c1516c 100644
--- a/hcatalog/core/src/test/java/org/apache/hive/hcatalog/mapreduce/TestHCatPartitionPublish.java
+++ b/hcatalog/core/src/test/java/org/apache/hive/hcatalog/mapreduce/TestHCatPartitionPublish.java
@@ -37,7 +37,6 @@ import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.HiveMetaStoreClient;
import org.apache.hadoop.hive.metastore.MetaStoreTestUtils;
-import org.apache.hadoop.hive.metastore.MetaStoreUtils;
import org.apache.hadoop.hive.metastore.Warehouse;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.SerDeInfo;
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/hcatalog/server-extensions/src/main/java/org/apache/hive/hcatalog/listener/DbNotificationListener.java
----------------------------------------------------------------------
diff --git a/hcatalog/server-extensions/src/main/java/org/apache/hive/hcatalog/listener/DbNotificationListener.java b/hcatalog/server-extensions/src/main/java/org/apache/hive/hcatalog/listener/DbNotificationListener.java
index f807055..e5e12e4 100644
--- a/hcatalog/server-extensions/src/main/java/org/apache/hive/hcatalog/listener/DbNotificationListener.java
+++ b/hcatalog/server-extensions/src/main/java/org/apache/hive/hcatalog/listener/DbNotificationListener.java
@@ -124,7 +124,7 @@ public class DbNotificationListener extends TransactionalMetaStoreEventListener
public void onConfigChange(ConfigChangeEvent tableEvent) throws MetaException {
String key = tableEvent.getKey();
if (key.equals(HiveConf.ConfVars.METASTORE_EVENT_DB_LISTENER_TTL.toString())) {
- // This weirdness of setting it in our hiveConf and then reading back does two things.
+ // This weirdness of setting it in our conf and then reading back does two things.
// One, it handles the conversion of the TimeUnit. Two, it keeps the value around for
// later in case we need it again.
hiveConf.set(HiveConf.ConfVars.METASTORE_EVENT_DB_LISTENER_TTL.name(),
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/hcatalog/streaming/src/java/org/apache/hive/hcatalog/streaming/DelimitedInputWriter.java
----------------------------------------------------------------------
diff --git a/hcatalog/streaming/src/java/org/apache/hive/hcatalog/streaming/DelimitedInputWriter.java b/hcatalog/streaming/src/java/org/apache/hive/hcatalog/streaming/DelimitedInputWriter.java
index 58fba4f..bd73f29 100644
--- a/hcatalog/streaming/src/java/org/apache/hive/hcatalog/streaming/DelimitedInputWriter.java
+++ b/hcatalog/streaming/src/java/org/apache/hive/hcatalog/streaming/DelimitedInputWriter.java
@@ -20,11 +20,10 @@ package org.apache.hive.hcatalog.streaming;
import com.google.common.annotations.VisibleForTesting;
-import org.apache.hadoop.security.UserGroupInformation;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.hive.conf.HiveConf;
-import org.apache.hadoop.hive.metastore.MetaStoreUtils;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.Table;
import org.apache.hadoop.hive.serde2.AbstractSerDe;
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/hcatalog/streaming/src/java/org/apache/hive/hcatalog/streaming/StrictJsonWriter.java
----------------------------------------------------------------------
diff --git a/hcatalog/streaming/src/java/org/apache/hive/hcatalog/streaming/StrictJsonWriter.java b/hcatalog/streaming/src/java/org/apache/hive/hcatalog/streaming/StrictJsonWriter.java
index 13756e2..7cfddfa 100644
--- a/hcatalog/streaming/src/java/org/apache/hive/hcatalog/streaming/StrictJsonWriter.java
+++ b/hcatalog/streaming/src/java/org/apache/hive/hcatalog/streaming/StrictJsonWriter.java
@@ -19,8 +19,8 @@
package org.apache.hive.hcatalog.streaming;
import org.apache.hadoop.hive.conf.HiveConf;
-import org.apache.hadoop.hive.metastore.MetaStoreUtils;
import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
import org.apache.hadoop.hive.serde2.AbstractSerDe;
import org.apache.hadoop.hive.serde2.SerDeException;
import org.apache.hadoop.hive.serde2.SerDeUtils;
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/hcatalog/streaming/src/java/org/apache/hive/hcatalog/streaming/StrictRegexWriter.java
----------------------------------------------------------------------
diff --git a/hcatalog/streaming/src/java/org/apache/hive/hcatalog/streaming/StrictRegexWriter.java b/hcatalog/streaming/src/java/org/apache/hive/hcatalog/streaming/StrictRegexWriter.java
index 78987ab..736893b 100644
--- a/hcatalog/streaming/src/java/org/apache/hive/hcatalog/streaming/StrictRegexWriter.java
+++ b/hcatalog/streaming/src/java/org/apache/hive/hcatalog/streaming/StrictRegexWriter.java
@@ -25,9 +25,9 @@ import java.util.Properties;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.hive.conf.HiveConf;
-import org.apache.hadoop.hive.metastore.MetaStoreUtils;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
import org.apache.hadoop.hive.serde.serdeConstants;
import org.apache.hadoop.hive.serde2.AbstractSerDe;
import org.apache.hadoop.hive.serde2.RegexSerDe;
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/hcatalog/webhcat/java-client/pom.xml
----------------------------------------------------------------------
diff --git a/hcatalog/webhcat/java-client/pom.xml b/hcatalog/webhcat/java-client/pom.xml
index ea51854..5693157 100644
--- a/hcatalog/webhcat/java-client/pom.xml
+++ b/hcatalog/webhcat/java-client/pom.xml
@@ -76,7 +76,7 @@
</dependency>
<dependency>
<groupId>org.apache.hive</groupId>
- <artifactId>hive-metastore</artifactId>
+ <artifactId>hive-standalone-metastore</artifactId>
<version>${project.version}</version>
<type>test-jar</type>
<scope>test</scope>
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/hcatalog/webhcat/java-client/src/main/java/org/apache/hive/hcatalog/api/HCatClientHMSImpl.java
----------------------------------------------------------------------
diff --git a/hcatalog/webhcat/java-client/src/main/java/org/apache/hive/hcatalog/api/HCatClientHMSImpl.java b/hcatalog/webhcat/java-client/src/main/java/org/apache/hive/hcatalog/api/HCatClientHMSImpl.java
index 17b9d03..5f7128d 100644
--- a/hcatalog/webhcat/java-client/src/main/java/org/apache/hive/hcatalog/api/HCatClientHMSImpl.java
+++ b/hcatalog/webhcat/java-client/src/main/java/org/apache/hive/hcatalog/api/HCatClientHMSImpl.java
@@ -29,7 +29,6 @@ import javax.annotation.Nullable;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.hive.common.ObjectPair;
import org.apache.hadoop.hive.common.classification.InterfaceAudience;
import org.apache.hadoop.hive.common.classification.InterfaceStability;
import org.apache.hadoop.hive.conf.HiveConf;
@@ -52,6 +51,7 @@ import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
import org.apache.hadoop.hive.metastore.api.Table;
import org.apache.hadoop.hive.metastore.api.UnknownDBException;
import org.apache.hadoop.hive.metastore.api.UnknownTableException;
+import org.apache.hadoop.hive.metastore.utils.ObjectPair;
import org.apache.hadoop.hive.ql.exec.FunctionRegistry;
import org.apache.hadoop.hive.ql.exec.SerializationUtilities;
import org.apache.hadoop.hive.ql.parse.SemanticException;
@@ -584,8 +584,7 @@ public class HCatClientHMSImpl extends HCatClient {
throws SemanticException, TException {
LOG.info("HCatClient: Dropping partitions using partition-predicate Expressions.");
ExprNodeGenericFuncDesc partitionExpression = new ExpressionBuilder(table, partitionSpec).build();
- ObjectPair<Integer, byte[]> serializedPartitionExpression =
- new ObjectPair<Integer, byte[]>(partitionSpec.size(),
+ ObjectPair<Integer, byte[]> serializedPartitionExpression = new ObjectPair<>(partitionSpec.size(),
SerializationUtilities.serializeExpressionToKryo(partitionExpression));
hmsClient.dropPartitions(table.getDbName(), table.getTableName(), Arrays.asList(serializedPartitionExpression),
deleteData && !isExternal(table), // Delete data?
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/hcatalog/webhcat/svr/pom.xml
----------------------------------------------------------------------
diff --git a/hcatalog/webhcat/svr/pom.xml b/hcatalog/webhcat/svr/pom.xml
index 6bceee1..a22bc22 100644
--- a/hcatalog/webhcat/svr/pom.xml
+++ b/hcatalog/webhcat/svr/pom.xml
@@ -197,7 +197,7 @@
<!-- test inter-project -->
<dependency>
<groupId>org.apache.hive</groupId>
- <artifactId>hive-metastore</artifactId>
+ <artifactId>hive-standalone-metastore</artifactId>
<version>${project.version}</version>
<type>test-jar</type>
<scope>test</scope>
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/itests/hcatalog-unit/pom.xml
----------------------------------------------------------------------
diff --git a/itests/hcatalog-unit/pom.xml b/itests/hcatalog-unit/pom.xml
index bb6b105..33344df 100644
--- a/itests/hcatalog-unit/pom.xml
+++ b/itests/hcatalog-unit/pom.xml
@@ -98,7 +98,7 @@
</dependency>
<dependency>
<groupId>org.apache.hive</groupId>
- <artifactId>hive-metastore</artifactId>
+ <artifactId>hive-standalone-metastore</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/itests/hcatalog-unit/src/test/java/org/apache/hive/hcatalog/hbase/ManyMiniCluster.java
----------------------------------------------------------------------
diff --git a/itests/hcatalog-unit/src/test/java/org/apache/hive/hcatalog/hbase/ManyMiniCluster.java b/itests/hcatalog-unit/src/test/java/org/apache/hive/hcatalog/hbase/ManyMiniCluster.java
index 745aa99..865f238 100644
--- a/itests/hcatalog-unit/src/test/java/org/apache/hive/hcatalog/hbase/ManyMiniCluster.java
+++ b/itests/hcatalog-unit/src/test/java/org/apache/hive/hcatalog/hbase/ManyMiniCluster.java
@@ -291,8 +291,8 @@ public class ManyMiniCluster {
System.setProperty("derby.stream.error.file", derbyLogFile.getPath());
-// Driver driver = new Driver(hiveConf);
-// SessionState.start(new CliSessionState(hiveConf));
+// Driver driver = new Driver(conf);
+// SessionState.start(new CliSessionState(conf));
hiveMetaStoreClient = new HiveMetaStoreClient(hiveConf);
}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/itests/hive-blobstore/pom.xml
----------------------------------------------------------------------
diff --git a/itests/hive-blobstore/pom.xml b/itests/hive-blobstore/pom.xml
index d1c732d..fadb4f2 100644
--- a/itests/hive-blobstore/pom.xml
+++ b/itests/hive-blobstore/pom.xml
@@ -55,13 +55,13 @@
</dependency>
<dependency>
<groupId>org.apache.hive</groupId>
- <artifactId>hive-metastore</artifactId>
+ <artifactId>hive-standalone-metastore</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.hive</groupId>
- <artifactId>hive-metastore</artifactId>
+ <artifactId>hive-standalone-metastore</artifactId>
<version>${project.version}</version>
<classifier>tests</classifier>
<scope>test</scope>
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/itests/hive-minikdc/pom.xml
----------------------------------------------------------------------
diff --git a/itests/hive-minikdc/pom.xml b/itests/hive-minikdc/pom.xml
index 95d2614..abe8694 100644
--- a/itests/hive-minikdc/pom.xml
+++ b/itests/hive-minikdc/pom.xml
@@ -74,13 +74,13 @@
</dependency>
<dependency>
<groupId>org.apache.hive</groupId>
- <artifactId>hive-metastore</artifactId>
+ <artifactId>hive-standalone-metastore</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.hive</groupId>
- <artifactId>hive-metastore</artifactId>
+ <artifactId>hive-standalone-metastore</artifactId>
<version>${project.version}</version>
<scope>test</scope>
<classifier>tests</classifier>
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/itests/hive-unit-hadoop2/pom.xml
----------------------------------------------------------------------
diff --git a/itests/hive-unit-hadoop2/pom.xml b/itests/hive-unit-hadoop2/pom.xml
index 339a194..b8f5398 100644
--- a/itests/hive-unit-hadoop2/pom.xml
+++ b/itests/hive-unit-hadoop2/pom.xml
@@ -76,7 +76,7 @@
</dependency>
<dependency>
<groupId>org.apache.hive</groupId>
- <artifactId>hive-metastore</artifactId>
+ <artifactId>hive-standalone-metastore</artifactId>
<version>${project.version}</version>
<classifier>tests</classifier>
</dependency>
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/itests/hive-unit/pom.xml
----------------------------------------------------------------------
diff --git a/itests/hive-unit/pom.xml b/itests/hive-unit/pom.xml
index 1440983..f7249a0 100644
--- a/itests/hive-unit/pom.xml
+++ b/itests/hive-unit/pom.xml
@@ -149,7 +149,7 @@
</dependency>
<dependency>
<groupId>org.apache.hive</groupId>
- <artifactId>hive-metastore</artifactId>
+ <artifactId>hive-standalone-metastore</artifactId>
<version>${project.version}</version>
<classifier>tests</classifier>
</dependency>
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/AbstractTestAuthorizationApiAuthorizer.java
----------------------------------------------------------------------
diff --git a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/AbstractTestAuthorizationApiAuthorizer.java b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/AbstractTestAuthorizationApiAuthorizer.java
index ebdfab2..36e0066 100644
--- a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/AbstractTestAuthorizationApiAuthorizer.java
+++ b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/AbstractTestAuthorizationApiAuthorizer.java
@@ -32,6 +32,7 @@ import org.apache.hadoop.hive.metastore.api.PrincipalType;
import org.apache.hadoop.hive.metastore.api.PrivilegeBag;
import org.apache.hadoop.hive.metastore.api.Role;
import org.apache.hadoop.hive.metastore.security.HadoopThriftAuthBridge;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
import org.apache.hadoop.hive.ql.security.authorization.MetaStoreAuthzAPIAuthorizerEmbedOnly;
import org.apache.hadoop.hive.ql.security.authorization.AuthorizationPreEventListener;
import org.junit.Test;
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestFilterHooks.java
----------------------------------------------------------------------
diff --git a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestFilterHooks.java b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestFilterHooks.java
index 6a2bbd2..9d19ed4 100644
--- a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestFilterHooks.java
+++ b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestFilterHooks.java
@@ -37,6 +37,7 @@ import org.apache.hadoop.hive.metastore.api.Partition;
import org.apache.hadoop.hive.metastore.api.PartitionSpec;
import org.apache.hadoop.hive.metastore.api.Table;
import org.apache.hadoop.hive.metastore.security.HadoopThriftAuthBridge;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
import org.apache.hadoop.hive.ql.Driver;
import org.apache.hadoop.hive.ql.session.SessionState;
import org.junit.AfterClass;
@@ -44,8 +45,11 @@ import org.junit.BeforeClass;
import org.junit.Test;
import com.google.common.collect.Lists;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class TestFilterHooks {
+ private static final Logger LOG = LoggerFactory.getLogger(TestFilterHooks.class);
public static class DummyMetaStoreFilterHookImpl extends DefaultMetaStoreFilterHookImpl {
public static boolean blockResults = false;
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestHiveMetaStore.java
----------------------------------------------------------------------
diff --git a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestHiveMetaStore.java b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestHiveMetaStore.java
index 98dad7a..f344c47 100644
--- a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestHiveMetaStore.java
+++ b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestHiveMetaStore.java
@@ -81,6 +81,7 @@ import org.apache.hadoop.hive.metastore.api.Table;
import org.apache.hadoop.hive.metastore.api.Type;
import org.apache.hadoop.hive.metastore.api.UnknownDBException;
import org.apache.hadoop.hive.metastore.api.hive_metastoreConstants;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
import org.apache.hadoop.hive.ql.exec.Utilities;
import org.apache.hadoop.hive.ql.io.HiveInputFormat;
import org.apache.hadoop.hive.ql.io.HiveOutputFormat;
@@ -1270,7 +1271,7 @@ public abstract class TestHiveMetaStore extends TestCase {
new FieldSchema("name", serdeConstants.STRING_TYPE_NAME, ""));
fam.getFields().add(
new FieldSchema("members",
- MetaStoreUtils.getListType(typ1.getName()), ""));
+ ColumnType.getListType(typ1.getName()), ""));
ret = client.createType(fam);
assertTrue("Unable to create type " + fam.getName(), ret);
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestHiveMetaStoreWithEnvironmentContext.java
----------------------------------------------------------------------
diff --git a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestHiveMetaStoreWithEnvironmentContext.java b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestHiveMetaStoreWithEnvironmentContext.java
index 3fa4b1e..6acfce5 100644
--- a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestHiveMetaStoreWithEnvironmentContext.java
+++ b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestHiveMetaStoreWithEnvironmentContext.java
@@ -43,6 +43,7 @@ import org.apache.hadoop.hive.metastore.events.DropPartitionEvent;
import org.apache.hadoop.hive.metastore.events.DropTableEvent;
import org.apache.hadoop.hive.metastore.events.ListenerEvent;
import org.apache.hadoop.hive.metastore.security.HadoopThriftAuthBridge;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
import org.apache.hadoop.hive.ql.io.HiveInputFormat;
import org.apache.hadoop.hive.ql.io.HiveOutputFormat;
import org.apache.hadoop.hive.ql.session.SessionState;
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestMarkPartitionRemote.java
----------------------------------------------------------------------
diff --git a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestMarkPartitionRemote.java b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestMarkPartitionRemote.java
index e3c9a4e..c541193 100644
--- a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestMarkPartitionRemote.java
+++ b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestMarkPartitionRemote.java
@@ -19,6 +19,7 @@
package org.apache.hadoop.hive.metastore;
import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
public class TestMarkPartitionRemote extends TestMarkPartition {
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestMetaStoreAuthorization.java
----------------------------------------------------------------------
diff --git a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestMetaStoreAuthorization.java b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestMetaStoreAuthorization.java
index 1bf76b5..e7b899b 100644
--- a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestMetaStoreAuthorization.java
+++ b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestMetaStoreAuthorization.java
@@ -33,6 +33,7 @@ import org.apache.hadoop.hive.metastore.api.Database;
import org.apache.hadoop.hive.metastore.api.MetaException;
import org.apache.hadoop.hive.metastore.api.NoSuchObjectException;
import org.apache.hadoop.hive.metastore.security.HadoopThriftAuthBridge;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
public class TestMetaStoreAuthorization extends TestCase {
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestMetaStoreEndFunctionListener.java
----------------------------------------------------------------------
diff --git a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestMetaStoreEndFunctionListener.java b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestMetaStoreEndFunctionListener.java
index 27bc791..137529e 100644
--- a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestMetaStoreEndFunctionListener.java
+++ b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestMetaStoreEndFunctionListener.java
@@ -28,6 +28,7 @@ import org.apache.hadoop.hive.metastore.api.NoSuchObjectException;
import org.apache.hadoop.hive.metastore.security.HadoopThriftAuthBridge;
import org.apache.hadoop.hive.ql.Driver;
import org.apache.hadoop.hive.ql.session.SessionState;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
/**
* TestMetaStoreEventListener. Test case for
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestMetaStoreEventListener.java
----------------------------------------------------------------------
diff --git a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestMetaStoreEventListener.java b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestMetaStoreEventListener.java
index 4df2f86..8a6c812 100644
--- a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestMetaStoreEventListener.java
+++ b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestMetaStoreEventListener.java
@@ -64,6 +64,7 @@ import org.apache.hadoop.hive.metastore.events.PreDropTableEvent;
import org.apache.hadoop.hive.metastore.events.PreEventContext;
import org.apache.hadoop.hive.metastore.events.PreLoadPartitionDoneEvent;
import org.apache.hadoop.hive.metastore.security.HadoopThriftAuthBridge;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
import org.apache.hadoop.hive.ql.Driver;
import org.apache.hadoop.hive.ql.processors.SetProcessor;
import org.apache.hadoop.hive.ql.session.SessionState;
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestMetaStoreEventListenerOnlyOnCommit.java
----------------------------------------------------------------------
diff --git a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestMetaStoreEventListenerOnlyOnCommit.java b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestMetaStoreEventListenerOnlyOnCommit.java
index d9da422..a061f36 100644
--- a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestMetaStoreEventListenerOnlyOnCommit.java
+++ b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestMetaStoreEventListenerOnlyOnCommit.java
@@ -26,6 +26,7 @@ import org.apache.hadoop.hive.cli.CliSessionState;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.events.ListenerEvent;
import org.apache.hadoop.hive.metastore.security.HadoopThriftAuthBridge;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
import org.apache.hadoop.hive.ql.Driver;
import org.apache.hadoop.hive.ql.session.SessionState;
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestMetaStoreInitListener.java
----------------------------------------------------------------------
diff --git a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestMetaStoreInitListener.java b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestMetaStoreInitListener.java
index 9578ef9..472ff65 100644
--- a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestMetaStoreInitListener.java
+++ b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestMetaStoreInitListener.java
@@ -23,6 +23,7 @@ import junit.framework.TestCase;
import org.apache.hadoop.hive.cli.CliSessionState;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.security.HadoopThriftAuthBridge;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
import org.apache.hadoop.hive.ql.Driver;
import org.apache.hadoop.hive.ql.session.SessionState;
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestMetaStoreListenersError.java
----------------------------------------------------------------------
diff --git a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestMetaStoreListenersError.java b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestMetaStoreListenersError.java
index b4d258c..11ebf4d 100644
--- a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestMetaStoreListenersError.java
+++ b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestMetaStoreListenersError.java
@@ -23,6 +23,7 @@ import junit.framework.TestCase;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hive.metastore.api.MetaException;
import org.apache.hadoop.hive.metastore.security.HadoopThriftAuthBridge;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
/**
* Test for unwrapping InvocationTargetException, which is thrown from
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestMetaStoreMetrics.java
----------------------------------------------------------------------
diff --git a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestMetaStoreMetrics.java b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestMetaStoreMetrics.java
index a899739..80cf94c 100644
--- a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestMetaStoreMetrics.java
+++ b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestMetaStoreMetrics.java
@@ -22,6 +22,7 @@ import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.metrics.Metrics;
import org.apache.hadoop.hive.metastore.metrics.MetricsConstants;
import org.apache.hadoop.hive.metastore.security.HadoopThriftAuthBridge;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
import org.apache.hadoop.hive.ql.Driver;
import org.apache.hadoop.hive.ql.session.SessionState;
import org.junit.Assert;
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestRemoteHiveMetaStore.java
----------------------------------------------------------------------
diff --git a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestRemoteHiveMetaStore.java b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestRemoteHiveMetaStore.java
index 19bed9d..55c10b1 100644
--- a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestRemoteHiveMetaStore.java
+++ b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestRemoteHiveMetaStore.java
@@ -21,6 +21,7 @@ package org.apache.hadoop.hive.metastore;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.conf.HiveConf.ConfVars;
import org.apache.hadoop.hive.metastore.security.HadoopThriftAuthBridge;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
public class TestRemoteHiveMetaStore extends TestHiveMetaStore {
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestRemoteHiveMetaStoreIpAddress.java
----------------------------------------------------------------------
diff --git a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestRemoteHiveMetaStoreIpAddress.java b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestRemoteHiveMetaStoreIpAddress.java
index 449fe71..0f33fc2 100644
--- a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestRemoteHiveMetaStoreIpAddress.java
+++ b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestRemoteHiveMetaStoreIpAddress.java
@@ -24,6 +24,7 @@ import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.conf.HiveConf.ConfVars;
import org.apache.hadoop.hive.metastore.api.Database;
import org.apache.hadoop.hive.metastore.security.HadoopThriftAuthBridge;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
import org.apache.hadoop.util.StringUtils;
/**
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestRetryingHMSHandler.java
----------------------------------------------------------------------
diff --git a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestRetryingHMSHandler.java b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestRetryingHMSHandler.java
index 41494d1..735fed5 100644
--- a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestRetryingHMSHandler.java
+++ b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/metastore/TestRetryingHMSHandler.java
@@ -34,6 +34,7 @@ import org.apache.hadoop.hive.metastore.api.SerDeInfo;
import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
import org.apache.hadoop.hive.metastore.api.Table;
import org.apache.hadoop.hive.metastore.security.HadoopThriftAuthBridge;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
import org.apache.hadoop.hive.ql.io.HiveInputFormat;
import org.apache.hadoop.hive.ql.io.HiveOutputFormat;
import org.apache.hadoop.hive.serde.serdeConstants;
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/parse/TestReplicationScenarios.java
----------------------------------------------------------------------
diff --git a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/parse/TestReplicationScenarios.java b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/parse/TestReplicationScenarios.java
index 765fa11..6a4e2ca 100644
--- a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/parse/TestReplicationScenarios.java
+++ b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/parse/TestReplicationScenarios.java
@@ -48,6 +48,7 @@ import org.apache.hadoop.hive.metastore.messaging.event.filters.AndFilter;
import org.apache.hadoop.hive.metastore.messaging.event.filters.DatabaseAndTableFilter;
import org.apache.hadoop.hive.metastore.messaging.event.filters.EventBoundaryFilter;
import org.apache.hadoop.hive.metastore.messaging.event.filters.MessageFormatFilter;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
import org.apache.hadoop.hive.ql.CommandNeedRetryException;
import org.apache.hadoop.hive.ql.Driver;
import org.apache.hadoop.hive.ql.exec.repl.ReplDumpWork;
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/itests/hive-unit/src/test/java/org/apache/hadoop/hive/serde2/TestSerdeWithFieldComments.java
----------------------------------------------------------------------
diff --git a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/serde2/TestSerdeWithFieldComments.java b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/serde2/TestSerdeWithFieldComments.java
index bb96a89..63f48f0 100644
--- a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/serde2/TestSerdeWithFieldComments.java
+++ b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/serde2/TestSerdeWithFieldComments.java
@@ -18,7 +18,7 @@
package org.apache.hadoop.hive.serde2;
import junit.framework.TestCase;
-import org.apache.hadoop.hive.metastore.MetaStoreUtils;
+import org.apache.hadoop.hive.metastore.HiveMetaStoreUtils;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.MetaException;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
@@ -61,7 +61,7 @@ public class TestSerdeWithFieldComments extends TestCase {
Deserializer mockDe = mock(Deserializer.class);
when(mockDe.getObjectInspector()).thenReturn(mockSOI);
List<FieldSchema> result =
- MetaStoreUtils.getFieldsFromDeserializer("testTable", mockDe);
+ HiveMetaStoreUtils.getFieldsFromDeserializer("testTable", mockDe);
assertEquals(2, result.size());
assertEquals("first", result.get(0).getName());
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/itests/hive-unit/src/test/java/org/apache/hive/service/cli/thrift/TestThriftCliServiceMessageSize.java
----------------------------------------------------------------------
diff --git a/itests/hive-unit/src/test/java/org/apache/hive/service/cli/thrift/TestThriftCliServiceMessageSize.java b/itests/hive-unit/src/test/java/org/apache/hive/service/cli/thrift/TestThriftCliServiceMessageSize.java
index 0948efc..147f53b 100644
--- a/itests/hive-unit/src/test/java/org/apache/hive/service/cli/thrift/TestThriftCliServiceMessageSize.java
+++ b/itests/hive-unit/src/test/java/org/apache/hive/service/cli/thrift/TestThriftCliServiceMessageSize.java
@@ -17,6 +17,13 @@
*/
package org.apache.hive.service.cli.thrift;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.fail;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.Statement;
+
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.conf.HiveConf.ConfVars;
import org.apache.hadoop.hive.metastore.MetaStoreTestUtils;
@@ -28,13 +35,6 @@ import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
-import java.sql.Connection;
-import java.sql.DriverManager;
-import java.sql.Statement;
-
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.fail;
-
public class TestThriftCliServiceMessageSize {
protected static int port;
protected static String host = "localhost";
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/itests/qtest-accumulo/pom.xml
----------------------------------------------------------------------
diff --git a/itests/qtest-accumulo/pom.xml b/itests/qtest-accumulo/pom.xml
index 40d0a74..eec7c7a 100644
--- a/itests/qtest-accumulo/pom.xml
+++ b/itests/qtest-accumulo/pom.xml
@@ -66,13 +66,13 @@
</dependency>
<dependency>
<groupId>org.apache.hive</groupId>
- <artifactId>hive-metastore</artifactId>
+ <artifactId>hive-standalone-metastore</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.hive</groupId>
- <artifactId>hive-metastore</artifactId>
+ <artifactId>hive-standalone-metastore</artifactId>
<version>${project.version}</version>
<classifier>tests</classifier>
<scope>test</scope>
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/itests/qtest-spark/pom.xml
----------------------------------------------------------------------
diff --git a/itests/qtest-spark/pom.xml b/itests/qtest-spark/pom.xml
index a506f7f..b69c71e 100644
--- a/itests/qtest-spark/pom.xml
+++ b/itests/qtest-spark/pom.xml
@@ -116,13 +116,13 @@
</dependency>
<dependency>
<groupId>org.apache.hive</groupId>
- <artifactId>hive-metastore</artifactId>
+ <artifactId>hive-standalone-metastore</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.hive</groupId>
- <artifactId>hive-metastore</artifactId>
+ <artifactId>hive-standalone-metastore</artifactId>
<version>${project.version}</version>
<classifier>tests</classifier>
<scope>test</scope>
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/itests/qtest/pom.xml
----------------------------------------------------------------------
diff --git a/itests/qtest/pom.xml b/itests/qtest/pom.xml
index 02664f3..450f4af 100644
--- a/itests/qtest/pom.xml
+++ b/itests/qtest/pom.xml
@@ -58,13 +58,13 @@
</dependency>
<dependency>
<groupId>org.apache.hive</groupId>
- <artifactId>hive-metastore</artifactId>
+ <artifactId>hive-standalone-metastore</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.hive</groupId>
- <artifactId>hive-metastore</artifactId>
+ <artifactId>hive-standalone-metastore</artifactId>
<version>${project.version}</version>
<classifier>tests</classifier>
<scope>test</scope>
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/itests/util/pom.xml
----------------------------------------------------------------------
diff --git a/itests/util/pom.xml b/itests/util/pom.xml
index e6dc09f..e5aa15f 100644
--- a/itests/util/pom.xml
+++ b/itests/util/pom.xml
@@ -103,7 +103,7 @@
</dependency>
<dependency>
<groupId>org.apache.hive</groupId>
- <artifactId>hive-metastore</artifactId>
+ <artifactId>hive-standalone-metastore</artifactId>
<version>${project.version}</version>
<type>test-jar</type>
</dependency>
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/llap-server/pom.xml
----------------------------------------------------------------------
diff --git a/llap-server/pom.xml b/llap-server/pom.xml
index 47a04cc..f318d80 100644
--- a/llap-server/pom.xml
+++ b/llap-server/pom.xml
@@ -238,7 +238,7 @@
<!-- test intra-project -->
<dependency>
<groupId>org.apache.hive</groupId>
- <artifactId>hive-metastore</artifactId>
+ <artifactId>hive-standalone-metastore</artifactId>
<version>${project.version}</version>
<type>test-jar</type>
<scope>test</scope>
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/metastore/pom.xml
----------------------------------------------------------------------
diff --git a/metastore/pom.xml b/metastore/pom.xml
index 04c6f47..8a65e73 100644
--- a/metastore/pom.xml
+++ b/metastore/pom.xml
@@ -268,17 +268,6 @@
<plugins>
<!-- plugins are always listed in sorted order by groupId, artifectId -->
<plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-jar-plugin</artifactId>
- <executions>
- <execution>
- <goals>
- <goal>test-jar</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
- <plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<executions>
@@ -296,17 +285,6 @@
</execution>
</executions>
</plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-jar-plugin</artifactId>
- <executions>
- <execution>
- <goals>
- <goal>test-jar</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
</plugins>
</build>
[10/12] hive git commit: HIVE-17980 Moved HiveMetaStoreClient plus a
few remaining classes.
Posted by ga...@apache.org.
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/metastore/src/java/org/apache/hadoop/hive/metastore/HiveMetaStoreUtils.java
----------------------------------------------------------------------
diff --git a/metastore/src/java/org/apache/hadoop/hive/metastore/HiveMetaStoreUtils.java b/metastore/src/java/org/apache/hadoop/hive/metastore/HiveMetaStoreUtils.java
new file mode 100644
index 0000000..a66c135
--- /dev/null
+++ b/metastore/src/java/org/apache/hadoop/hive/metastore/HiveMetaStoreUtils.java
@@ -0,0 +1,213 @@
+/*
+ * 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 java.util.ArrayList;
+import java.util.List;
+
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hive.metastore.api.FieldSchema;
+import org.apache.hadoop.hive.metastore.api.MetaException;
+import org.apache.hadoop.hive.serde2.Deserializer;
+import org.apache.hadoop.hive.serde2.SerDeException;
+import org.apache.hadoop.hive.serde2.SerDeUtils;
+import org.apache.hadoop.hive.serde2.objectinspector.ListObjectInspector;
+import org.apache.hadoop.hive.serde2.objectinspector.MapObjectInspector;
+import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
+import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector.Category;
+import org.apache.hadoop.hive.serde2.objectinspector.StructField;
+import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
+import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
+import org.apache.hive.common.util.ReflectionUtil;
+
+public class HiveMetaStoreUtils {
+
+ protected static final Logger LOG = LoggerFactory.getLogger("hive.log");
+
+ /**
+ * getDeserializer
+ *
+ * Get the Deserializer for a table.
+ *
+ * @param conf
+ * - hadoop config
+ * @param table
+ * the table
+ * @return
+ * Returns instantiated deserializer by looking up class name of deserializer stored in
+ * storage descriptor of passed in table. Also, initializes the deserializer with schema
+ * of table.
+ * @exception MetaException
+ * if any problems instantiating the Deserializer
+ *
+ * todo - this should move somewhere into serde.jar
+ *
+ */
+ static public Deserializer getDeserializer(Configuration conf,
+ org.apache.hadoop.hive.metastore.api.Table table, boolean skipConfError) throws
+ MetaException {
+ String lib = table.getSd().getSerdeInfo().getSerializationLib();
+ if (lib == null) {
+ return null;
+ }
+ return getDeserializer(conf, table, skipConfError, lib);
+ }
+
+ public static Deserializer getDeserializer(Configuration conf,
+ org.apache.hadoop.hive.metastore.api.Table table, boolean skipConfError,
+ String lib) throws MetaException {
+ try {
+ Deserializer deserializer = ReflectionUtil.newInstance(conf.getClassByName(lib).
+ asSubclass(Deserializer.class), conf);
+ if (skipConfError) {
+ SerDeUtils.initializeSerDeWithoutErrorCheck(deserializer, conf,
+ MetaStoreUtils.getTableMetadata(table), null);
+ } else {
+ SerDeUtils.initializeSerDe(deserializer, conf, MetaStoreUtils.getTableMetadata(table), null);
+ }
+ return deserializer;
+ } catch (RuntimeException e) {
+ throw e;
+ } catch (Throwable e) {
+ LOG.error("error in initSerDe: " + e.getClass().getName() + " "
+ + e.getMessage(), e);
+ throw new MetaException(e.getClass().getName() + " " + e.getMessage());
+ }
+ }
+
+ public static Class<? extends Deserializer> getDeserializerClass(
+ Configuration conf, org.apache.hadoop.hive.metastore.api.Table table) throws Exception {
+ String lib = table.getSd().getSerdeInfo().getSerializationLib();
+ return lib == null ? null : conf.getClassByName(lib).asSubclass(Deserializer.class);
+ }
+
+ /**
+ * getDeserializer
+ *
+ * Get the Deserializer for a partition.
+ *
+ * @param conf
+ * - hadoop config
+ * @param part
+ * the partition
+ * @param table the table
+ * @return
+ * Returns instantiated deserializer by looking up class name of deserializer stored in
+ * storage descriptor of passed in partition. Also, initializes the deserializer with
+ * schema of partition.
+ * @exception MetaException
+ * if any problems instantiating the Deserializer
+ *
+ */
+ static public Deserializer getDeserializer(Configuration conf,
+ org.apache.hadoop.hive.metastore.api.Partition part,
+ org.apache.hadoop.hive.metastore.api.Table table) throws MetaException {
+ String lib = part.getSd().getSerdeInfo().getSerializationLib();
+ try {
+ Deserializer deserializer = ReflectionUtil.newInstance(conf.getClassByName(lib).
+ asSubclass(Deserializer.class), conf);
+ SerDeUtils.initializeSerDe(deserializer, conf, MetaStoreUtils.getTableMetadata(table),
+ MetaStoreUtils.getPartitionMetadata(part, table));
+ return deserializer;
+ } catch (RuntimeException e) {
+ throw e;
+ } catch (Throwable e) {
+ LOG.error("error in initSerDe: " + e.getClass().getName() + " "
+ + e.getMessage(), e);
+ throw new MetaException(e.getClass().getName() + " " + e.getMessage());
+ }
+ }
+
+ /**
+ * @param tableName name of the table
+ * @param deserializer deserializer to use
+ * @return the list of fields
+ * @throws SerDeException if the serde throws an exception
+ * @throws MetaException if one of the fields or types in the table is invalid
+ */
+ public static List<FieldSchema> getFieldsFromDeserializer(String tableName,
+ Deserializer deserializer) throws SerDeException, MetaException {
+ ObjectInspector oi = deserializer.getObjectInspector();
+ String[] names = tableName.split("\\.");
+ String last_name = names[names.length - 1];
+ for (int i = 1; i < names.length; i++) {
+
+ if (oi instanceof StructObjectInspector) {
+ StructObjectInspector soi = (StructObjectInspector) oi;
+ StructField sf = soi.getStructFieldRef(names[i]);
+ if (sf == null) {
+ throw new MetaException("Invalid Field " + names[i]);
+ } else {
+ oi = sf.getFieldObjectInspector();
+ }
+ } else if (oi instanceof ListObjectInspector
+ && names[i].equalsIgnoreCase("$elem$")) {
+ ListObjectInspector loi = (ListObjectInspector) oi;
+ oi = loi.getListElementObjectInspector();
+ } else if (oi instanceof MapObjectInspector
+ && names[i].equalsIgnoreCase("$key$")) {
+ MapObjectInspector moi = (MapObjectInspector) oi;
+ oi = moi.getMapKeyObjectInspector();
+ } else if (oi instanceof MapObjectInspector
+ && names[i].equalsIgnoreCase("$value$")) {
+ MapObjectInspector moi = (MapObjectInspector) oi;
+ oi = moi.getMapValueObjectInspector();
+ } else {
+ throw new MetaException("Unknown type for " + names[i]);
+ }
+ }
+
+ ArrayList<FieldSchema> str_fields = new ArrayList<>();
+ // rules on how to recurse the ObjectInspector based on its type
+ if (oi.getCategory() != Category.STRUCT) {
+ str_fields.add(new FieldSchema(last_name, oi.getTypeName(),
+ FROM_SERIALIZER));
+ } else {
+ List<? extends StructField> fields = ((StructObjectInspector) oi)
+ .getAllStructFieldRefs();
+ for (int i = 0; i < fields.size(); i++) {
+ StructField structField = fields.get(i);
+ String fieldName = structField.getFieldName();
+ String fieldTypeName = structField.getFieldObjectInspector().getTypeName();
+ String fieldComment = determineFieldComment(structField.getFieldComment());
+
+ str_fields.add(new FieldSchema(fieldName, fieldTypeName, fieldComment));
+ }
+ }
+ return str_fields;
+ }
+
+ private static final String FROM_SERIALIZER = "from deserializer";
+ private static String determineFieldComment(String comment) {
+ return (comment == null) ? FROM_SERIALIZER : comment;
+ }
+
+ /**
+ * Convert TypeInfo to FieldSchema.
+ */
+ public static FieldSchema getFieldSchemaFromTypeInfo(String fieldName,
+ TypeInfo typeInfo) {
+ return new FieldSchema(fieldName, typeInfo.getTypeName(),
+ "generated by TypeInfoUtils.getFieldSchemaFromTypeInfo");
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/metastore/src/java/org/apache/hadoop/hive/metastore/IMetaStoreClient.java
----------------------------------------------------------------------
diff --git a/metastore/src/java/org/apache/hadoop/hive/metastore/IMetaStoreClient.java b/metastore/src/java/org/apache/hadoop/hive/metastore/IMetaStoreClient.java
deleted file mode 100644
index 5aa20c5..0000000
--- a/metastore/src/java/org/apache/hadoop/hive/metastore/IMetaStoreClient.java
+++ /dev/null
@@ -1,1800 +0,0 @@
-/**
- * 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 java.io.IOException;
-import java.nio.ByteBuffer;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import org.apache.hadoop.hive.common.ObjectPair;
-import org.apache.hadoop.hive.common.ValidTxnList;
-import org.apache.hadoop.hive.common.classification.InterfaceAudience;
-import org.apache.hadoop.hive.common.classification.InterfaceAudience.Public;
-import org.apache.hadoop.hive.common.classification.InterfaceStability.Evolving;
-import org.apache.hadoop.hive.common.classification.RetrySemantics;
-import org.apache.hadoop.hive.conf.HiveConf;
-import org.apache.hadoop.hive.metastore.annotation.NoReconnect;
-import org.apache.hadoop.hive.metastore.api.AggrStats;
-import org.apache.hadoop.hive.metastore.api.AlreadyExistsException;
-import org.apache.hadoop.hive.metastore.api.CmRecycleRequest;
-import org.apache.hadoop.hive.metastore.api.CmRecycleResponse;
-import org.apache.hadoop.hive.metastore.api.ColumnStatistics;
-import org.apache.hadoop.hive.metastore.api.ColumnStatisticsObj;
-import org.apache.hadoop.hive.metastore.api.CompactionResponse;
-import org.apache.hadoop.hive.metastore.api.CompactionType;
-import org.apache.hadoop.hive.metastore.api.ConfigValSecurityException;
-import org.apache.hadoop.hive.metastore.api.CurrentNotificationEventId;
-import org.apache.hadoop.hive.metastore.api.DataOperationType;
-import org.apache.hadoop.hive.metastore.api.Database;
-import org.apache.hadoop.hive.metastore.api.EnvironmentContext;
-import org.apache.hadoop.hive.metastore.api.FieldSchema;
-import org.apache.hadoop.hive.metastore.api.FireEventRequest;
-import org.apache.hadoop.hive.metastore.api.FireEventResponse;
-import org.apache.hadoop.hive.metastore.api.ForeignKeysRequest;
-import org.apache.hadoop.hive.metastore.api.Function;
-import org.apache.hadoop.hive.metastore.api.GetAllFunctionsResponse;
-import org.apache.hadoop.hive.metastore.api.GetOpenTxnsInfoResponse;
-import org.apache.hadoop.hive.metastore.api.GetPrincipalsInRoleRequest;
-import org.apache.hadoop.hive.metastore.api.GetPrincipalsInRoleResponse;
-import org.apache.hadoop.hive.metastore.api.GetRoleGrantsForPrincipalRequest;
-import org.apache.hadoop.hive.metastore.api.GetRoleGrantsForPrincipalResponse;
-import org.apache.hadoop.hive.metastore.api.HeartbeatTxnRangeResponse;
-import org.apache.hadoop.hive.metastore.api.HiveObjectPrivilege;
-import org.apache.hadoop.hive.metastore.api.HiveObjectRef;
-import org.apache.hadoop.hive.metastore.api.Index;
-import org.apache.hadoop.hive.metastore.api.InvalidInputException;
-import org.apache.hadoop.hive.metastore.api.InvalidObjectException;
-import org.apache.hadoop.hive.metastore.api.InvalidOperationException;
-import org.apache.hadoop.hive.metastore.api.InvalidPartitionException;
-import org.apache.hadoop.hive.metastore.api.LockRequest;
-import org.apache.hadoop.hive.metastore.api.LockResponse;
-import org.apache.hadoop.hive.metastore.api.MetaException;
-import org.apache.hadoop.hive.metastore.api.MetadataPpdResult;
-import org.apache.hadoop.hive.metastore.api.NoSuchLockException;
-import org.apache.hadoop.hive.metastore.api.NoSuchObjectException;
-import org.apache.hadoop.hive.metastore.api.NoSuchTxnException;
-import org.apache.hadoop.hive.metastore.api.NotNullConstraintsRequest;
-import org.apache.hadoop.hive.metastore.api.NotificationEvent;
-import org.apache.hadoop.hive.metastore.api.NotificationEventResponse;
-import org.apache.hadoop.hive.metastore.api.NotificationEventsCountResponse;
-import org.apache.hadoop.hive.metastore.api.NotificationEventsCountRequest;
-import org.apache.hadoop.hive.metastore.api.OpenTxnsResponse;
-import org.apache.hadoop.hive.metastore.api.Partition;
-import org.apache.hadoop.hive.metastore.api.PartitionEventType;
-import org.apache.hadoop.hive.metastore.api.PartitionValuesRequest;
-import org.apache.hadoop.hive.metastore.api.PartitionValuesResponse;
-import org.apache.hadoop.hive.metastore.api.PrimaryKeysRequest;
-import org.apache.hadoop.hive.metastore.api.PrincipalPrivilegeSet;
-import org.apache.hadoop.hive.metastore.api.PrincipalType;
-import org.apache.hadoop.hive.metastore.api.PrivilegeBag;
-import org.apache.hadoop.hive.metastore.api.WMResourcePlan;
-import org.apache.hadoop.hive.metastore.api.WMTrigger;
-import org.apache.hadoop.hive.metastore.api.Role;
-import org.apache.hadoop.hive.metastore.api.SQLForeignKey;
-import org.apache.hadoop.hive.metastore.api.SQLNotNullConstraint;
-import org.apache.hadoop.hive.metastore.api.SQLPrimaryKey;
-import org.apache.hadoop.hive.metastore.api.SQLUniqueConstraint;
-import org.apache.hadoop.hive.metastore.api.SetPartitionsStatsRequest;
-import org.apache.hadoop.hive.metastore.api.ShowCompactResponse;
-import org.apache.hadoop.hive.metastore.api.ShowLocksRequest;
-import org.apache.hadoop.hive.metastore.api.ShowLocksResponse;
-import org.apache.hadoop.hive.metastore.api.Table;
-import org.apache.hadoop.hive.metastore.api.TableMeta;
-import org.apache.hadoop.hive.metastore.api.TxnAbortedException;
-import org.apache.hadoop.hive.metastore.api.TxnOpenException;
-import org.apache.hadoop.hive.metastore.api.UniqueConstraintsRequest;
-import org.apache.hadoop.hive.metastore.api.UnknownDBException;
-import org.apache.hadoop.hive.metastore.api.UnknownPartitionException;
-import org.apache.hadoop.hive.metastore.api.UnknownTableException;
-import org.apache.hadoop.hive.metastore.partition.spec.PartitionSpecProxy;
-import org.apache.thrift.TException;
-
-/**
- * Wrapper around hive metastore thrift api
- */
-@Public
-@Evolving
-public interface IMetaStoreClient {
-
- /**
- * Returns whether current client is compatible with conf argument or not
- * @return
- */
- boolean isCompatibleWith(HiveConf conf);
-
- /**
- * Set added jars path info to MetaStoreClient.
- * @param addedJars the hive.added.jars.path. It is qualified paths separated by commas.
- */
- void setHiveAddedJars(String addedJars);
-
- /**
- * Returns true if the current client is using an in process metastore (local metastore).
- *
- * @return
- */
- boolean isLocalMetaStore();
-
- /**
- * Tries to reconnect this MetaStoreClient to the MetaStore.
- */
- void reconnect() throws MetaException;
-
- /**
- * close connection to meta store
- */
- @NoReconnect
- void close();
-
- /**
- * set meta variable which is open to end users
- */
- void setMetaConf(String key, String value) throws MetaException, TException;
-
- /**
- * get current meta variable
- */
- String getMetaConf(String key) throws MetaException, TException;
-
- /**
- * Get the names of all databases in the MetaStore that match the given pattern.
- * @param databasePattern
- * @return List of database names.
- * @throws MetaException
- * @throws TException
- */
- List<String> getDatabases(String databasePattern) throws MetaException, TException;
-
- /**
- * Get the names of all databases in the MetaStore.
- * @return List of database names.
- * @throws MetaException
- * @throws TException
- */
- List<String> getAllDatabases() throws MetaException, TException;
-
- /**
- * Get the names of all tables in the specified database that satisfy the supplied
- * table name pattern.
- * @param dbName
- * @param tablePattern
- * @return List of table names.
- * @throws MetaException
- * @throws TException
- * @throws UnknownDBException
- */
- List<String> getTables(String dbName, String tablePattern)
- throws MetaException, TException, UnknownDBException;
-
- /**
- * Get the names of all tables in the specified database that satisfy the supplied
- * table name pattern and table type (MANAGED_TABLE || EXTERNAL_TABLE || VIRTUAL_VIEW)
- * @param dbName Name of the database to fetch tables in.
- * @param tablePattern pattern to match for table names.
- * @param tableType Type of the table in the HMS store. VIRTUAL_VIEW is for views.
- * @return List of table names.
- * @throws MetaException
- * @throws TException
- * @throws UnknownDBException
- */
- List<String> getTables(String dbName, String tablePattern, TableType tableType)
- throws MetaException, TException, UnknownDBException;
-
- /**
- * For quick GetTablesOperation
- */
- List<TableMeta> getTableMeta(String dbPatterns, String tablePatterns, List<String> tableTypes)
- throws MetaException, TException, UnknownDBException;
-
- /**
- * Get the names of all tables in the specified database.
- * @param dbName
- * @return List of table names.
- * @throws MetaException
- * @throws TException
- * @throws UnknownDBException
- */
- List<String> getAllTables(String dbName) throws MetaException, TException, UnknownDBException;
-
- /**
- * Get a list of table names that match a filter.
- * The filter operators are LIKE, <, <=, >, >=, =, <>
- *
- * In the filter statement, values interpreted as strings must be enclosed in quotes,
- * while values interpreted as integers should not be. Strings and integers are the only
- * supported value types.
- *
- * The currently supported key names in the filter are:
- * Constants.HIVE_FILTER_FIELD_OWNER, which filters on the tables' owner's name
- * and supports all filter operators
- * Constants.HIVE_FILTER_FIELD_LAST_ACCESS, which filters on the last access times
- * and supports all filter operators except LIKE
- * Constants.HIVE_FILTER_FIELD_PARAMS, which filters on the tables' parameter keys and values
- * and only supports the filter operators = and <>.
- * Append the parameter key name to HIVE_FILTER_FIELD_PARAMS in the filter statement.
- * For example, to filter on parameter keys called "retention", the key name in the filter
- * statement should be Constants.HIVE_FILTER_FIELD_PARAMS + "retention"
- * Also, = and <> only work for keys that exist in the tables.
- * E.g., filtering on tables where key1 <> value will only
- * return tables that have a value for the parameter key1.
- * Some example filter statements include:
- * filter = Constants.HIVE_FILTER_FIELD_OWNER + " like \".*test.*\" and " +
- * Constants.HIVE_FILTER_FIELD_LAST_ACCESS + " = 0";
- * filter = Constants.HIVE_FILTER_FIELD_OWNER + " = \"test_user\" and (" +
- * Constants.HIVE_FILTER_FIELD_PARAMS + "retention = \"30\" or " +
- * Constants.HIVE_FILTER_FIELD_PARAMS + "retention = \"90\")"
- *
- * @param dbName
- * The name of the database from which you will retrieve the table names
- * @param filter
- * The filter string
- * @param maxTables
- * The maximum number of tables returned
- * @return A list of table names that match the desired filter
- */
- List<String> listTableNamesByFilter(String dbName, String filter, short maxTables)
- throws MetaException, TException, InvalidOperationException, UnknownDBException;
-
-
- /**
- * Drop the table.
- *
- * @param dbname
- * The database for this table
- * @param tableName
- * The table to drop
- * @param deleteData
- * Should we delete the underlying data
- * @param ignoreUnknownTab
- * don't throw if the requested table doesn't exist
- * @throws MetaException
- * Could not drop table properly.
- * @throws NoSuchObjectException
- * The table wasn't found.
- * @throws TException
- * A thrift communication error occurred
- */
- void dropTable(String dbname, String tableName, boolean deleteData,
- boolean ignoreUnknownTab) throws MetaException, TException,
- NoSuchObjectException;
-
- /**
- * @param ifPurge
- * completely purge the table (skipping trash) while removing data from warehouse
- * @see #dropTable(String, String, boolean, boolean)
- */
- public void dropTable(String dbname, String tableName, boolean deleteData,
- boolean ignoreUnknownTab, boolean ifPurge) throws MetaException, TException,
- NoSuchObjectException;
-
- /**
- * Drop the table in the DEFAULT database.
- *
- * @param tableName
- * The table to drop
- * @param deleteData
- * Should we delete the underlying data
- * @throws MetaException
- * Could not drop table properly.
- * @throws UnknownTableException
- * The table wasn't found.
- * @throws TException
- * A thrift communication error occurred
- * @throws NoSuchObjectException
- * The table wasn't found.
- *
- * @deprecated As of release 0.6.0 replaced by {@link #dropTable(String, String, boolean, boolean)}.
- * This method will be removed in release 0.7.0.
- */
- @Deprecated
- void dropTable(String tableName, boolean deleteData)
- throws MetaException, UnknownTableException, TException, NoSuchObjectException;
-
- /**
- * @see #dropTable(String, String, boolean, boolean)
- */
- void dropTable(String dbname, String tableName)
- throws MetaException, TException, NoSuchObjectException;
-
- /**
- * Truncate the table/partitions in the DEFAULT database.
- * @param dbName
- * The db to which the table to be truncate belongs to
- * @param tableName
- * The table to truncate
- * @param partNames
- * List of partitions to truncate. NULL will truncate the whole table/all partitions
- * @throws MetaException
- * @throws TException
- * Could not truncate table properly.
- */
- void truncateTable(String dbName, String tableName, List<String> partNames) throws MetaException, TException;
-
- /**
- * Recycles the files recursively from the input path to the cmroot directory either by copying or moving it.
- *
- * @param request Inputs for path of the data files to be recycled to cmroot and
- * isPurge flag when set to true files which needs to be recycled are not moved to Trash
- * @return Response which is currently void
- */
- CmRecycleResponse recycleDirToCmPath(CmRecycleRequest request) throws MetaException, TException;
-
- boolean tableExists(String databaseName, String tableName) throws MetaException,
- TException, UnknownDBException;
-
- /**
- * Check to see if the specified table exists in the DEFAULT database.
- * @param tableName
- * @return TRUE if DEFAULT.tableName exists, FALSE otherwise.
- * @throws MetaException
- * @throws TException
- * @throws UnknownDBException
- * @deprecated As of release 0.6.0 replaced by {@link #tableExists(String, String)}.
- * This method will be removed in release 0.7.0.
- */
- @Deprecated
- boolean tableExists(String tableName) throws MetaException,
- TException, UnknownDBException;
-
- /**
- * Get a table object from the DEFAULT database.
- *
- * @param tableName
- * Name of the table to fetch.
- * @return An object representing the table.
- * @throws MetaException
- * Could not fetch the table
- * @throws TException
- * A thrift communication error occurred
- * @throws NoSuchObjectException
- * In case the table wasn't found.
- * @deprecated As of release 0.6.0 replaced by {@link #getTable(String, String)}.
- * This method will be removed in release 0.7.0.
- */
- @Deprecated
- Table getTable(String tableName) throws MetaException, TException, NoSuchObjectException;
-
- /**
- * Get a Database Object
- * @param databaseName name of the database to fetch
- * @return the database
- * @throws NoSuchObjectException The database does not exist
- * @throws MetaException Could not fetch the database
- * @throws TException A thrift communication error occurred
- */
- Database getDatabase(String databaseName)
- throws NoSuchObjectException, MetaException, TException;
-
-
- /**
- * Get a table object.
- *
- * @param dbName
- * The database the table is located in.
- * @param tableName
- * Name of the table to fetch.
- * @return An object representing the table.
- * @throws MetaException
- * Could not fetch the table
- * @throws TException
- * A thrift communication error occurred
- * @throws NoSuchObjectException
- * In case the table wasn't found.
- */
- Table getTable(String dbName, String tableName) throws MetaException,
- TException, NoSuchObjectException;
-
- /**
- *
- * @param dbName
- * The database the tables are located in.
- * @param tableNames
- * The names of the tables to fetch
- * @return A list of objects representing the tables.
- * Only the tables that can be retrieved from the database are returned. For example,
- * if none of the requested tables could be retrieved, an empty list is returned.
- * There is no guarantee of ordering of the returned tables.
- * @throws InvalidOperationException
- * The input to this operation is invalid (e.g., the list of tables names is null)
- * @throws UnknownDBException
- * The requested database could not be fetched.
- * @throws TException
- * A thrift communication error occurred
- * @throws MetaException
- * Any other errors
- */
- List<Table> getTableObjectsByName(String dbName, List<String> tableNames)
- throws MetaException, InvalidOperationException, UnknownDBException, TException;
-
- /**
- * @param tableName
- * @param dbName
- * @param partVals
- * @return the partition object
- * @throws InvalidObjectException
- * @throws AlreadyExistsException
- * @throws MetaException
- * @throws TException
- * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#append_partition(java.lang.String,
- * java.lang.String, java.util.List)
- */
- Partition appendPartition(String tableName, String dbName,
- List<String> partVals) throws InvalidObjectException,
- AlreadyExistsException, MetaException, TException;
-
- Partition appendPartition(String tableName, String dbName, String name)
- throws InvalidObjectException, AlreadyExistsException, MetaException, TException;
-
- /**
- * Add a partition to the table.
- *
- * @param partition
- * The partition to add
- * @return The partition added
- * @throws InvalidObjectException
- * Could not find table to add to
- * @throws AlreadyExistsException
- * Partition already exists
- * @throws MetaException
- * Could not add partition
- * @throws TException
- * Thrift exception
- */
- Partition add_partition(Partition partition)
- throws InvalidObjectException, AlreadyExistsException, MetaException, TException;
-
- /**
- * Add partitions to the table.
- *
- * @param partitions
- * The partitions to add
- * @throws InvalidObjectException
- * Could not find table to add to
- * @throws AlreadyExistsException
- * Partition already exists
- * @throws MetaException
- * Could not add partition
- * @throws TException
- * Thrift exception
- */
- int add_partitions(List<Partition> partitions)
- throws InvalidObjectException, AlreadyExistsException, MetaException, TException;
-
- int add_partitions_pspec(PartitionSpecProxy partitionSpec)
- throws InvalidObjectException, AlreadyExistsException, MetaException, TException;
-
- /**
- * Add partitions to the table.
- *
- * @param partitions The partitions to add
- * @param ifNotExists only add partitions if they don't exist
- * @param needResults Whether the results are needed
- * @return the partitions that were added, or null if !needResults
- */
- List<Partition> add_partitions(
- List<Partition> partitions, boolean ifNotExists, boolean needResults)
- throws InvalidObjectException, AlreadyExistsException, MetaException, TException;
-
- /**
- * @param dbName
- * @param tblName
- * @param partVals
- * @return the partition object
- * @throws MetaException
- * @throws TException
- * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#get_partition(java.lang.String,
- * java.lang.String, java.util.List)
- */
- Partition getPartition(String dbName, String tblName,
- List<String> partVals) throws NoSuchObjectException, MetaException, TException;
-
- /**
- * @param partitionSpecs
- * @param sourceDb
- * @param sourceTable
- * @param destdb
- * @param destTableName
- * @return partition object
- */
- Partition exchange_partition(Map<String, String> partitionSpecs,
- String sourceDb, String sourceTable, String destdb,
- String destTableName) throws MetaException, NoSuchObjectException,
- InvalidObjectException, TException;
-
- /**
- * With the one partitionSpecs to exchange, multiple partitions could be exchanged.
- * e.g., year=2015/month/day, exchanging partition year=2015 results to all the partitions
- * belonging to it exchanged. This function returns the list of affected partitions.
- * @param partitionSpecs
- * @param sourceDb
- * @param sourceTable
- * @param destdb
- * @param destTableName
- * @return the list of the new partitions
- */
- List<Partition> exchange_partitions(Map<String, String> partitionSpecs,
- String sourceDb, String sourceTable, String destdb,
- String destTableName) throws MetaException, NoSuchObjectException,
- InvalidObjectException, TException;
-
- /**
- * @param dbName
- * @param tblName
- * @param name - partition name i.e. 'ds=2010-02-03/ts=2010-02-03 18%3A16%3A01'
- * @return the partition object
- * @throws MetaException
- * @throws TException
- * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#get_partition(java.lang.String,
- * java.lang.String, java.util.List)
- */
- Partition getPartition(String dbName, String tblName,
- String name) throws MetaException, UnknownTableException, NoSuchObjectException, TException;
-
-
- /**
- * @param dbName
- * @param tableName
- * @param pvals
- * @param userName
- * @param groupNames
- * @return the partition
- * @throws MetaException
- * @throws UnknownTableException
- * @throws NoSuchObjectException
- * @throws TException
- */
- Partition getPartitionWithAuthInfo(String dbName, String tableName,
- List<String> pvals, String userName, List<String> groupNames)
- throws MetaException, UnknownTableException, NoSuchObjectException, TException;
-
- /**
- * @param tbl_name
- * @param db_name
- * @param max_parts
- * @return the list of partitions
- * @throws NoSuchObjectException
- * @throws MetaException
- * @throws TException
- */
- List<Partition> listPartitions(String db_name, String tbl_name,
- short max_parts) throws NoSuchObjectException, MetaException, TException;
-
- public PartitionSpecProxy listPartitionSpecs(String dbName, String tableName, int maxParts)
- throws TException;
- List<Partition> listPartitions(String db_name, String tbl_name,
- List<String> part_vals, short max_parts) throws NoSuchObjectException, MetaException, TException;
-
- List<String> listPartitionNames(String db_name, String tbl_name,
- short max_parts) throws NoSuchObjectException, MetaException, TException;
-
- List<String> listPartitionNames(String db_name, String tbl_name,
- List<String> part_vals, short max_parts)
- throws MetaException, TException, NoSuchObjectException;
-
- public PartitionValuesResponse listPartitionValues(PartitionValuesRequest request)
- throws MetaException, TException, NoSuchObjectException;
-
- /**
- * Get number of partitions matching specified filter
- * @param dbName the database name
- * @param tableName the table name
- * @param filter the filter string,
- * for example "part1 = \"p1_abc\" and part2 <= "\p2_test\"". Filtering can
- * be done only on string partition keys.
- * @return number of partitions
- * @throws MetaException
- * @throws NoSuchObjectException
- * @throws TException
- */
- public int getNumPartitionsByFilter(String dbName, String tableName,
- String filter) throws MetaException, NoSuchObjectException, TException;
-
-
- /**
- * Get list of partitions matching specified filter
- * @param db_name the database name
- * @param tbl_name the table name
- * @param filter the filter string,
- * for example "part1 = \"p1_abc\" and part2 <= "\p2_test\"". Filtering can
- * be done only on string partition keys.
- * @param max_parts the maximum number of partitions to return,
- * all partitions are returned if -1 is passed
- * @return list of partitions
- * @throws MetaException
- * @throws NoSuchObjectException
- * @throws TException
- */
- List<Partition> listPartitionsByFilter(String db_name, String tbl_name,
- String filter, short max_parts) throws MetaException,
- NoSuchObjectException, TException;
-
- PartitionSpecProxy listPartitionSpecsByFilter(String db_name, String tbl_name,
- String filter, int max_parts) throws MetaException,
- NoSuchObjectException, TException;
-
- /**
- * Get list of partitions matching specified serialized expression
- * @param db_name the database name
- * @param tbl_name the table name
- * @param expr expression, serialized from ExprNodeDesc
- * @param max_parts the maximum number of partitions to return,
- * all partitions are returned if -1 is passed
- * @param default_partition_name Default partition name from configuration. If blank, the
- * metastore server-side configuration is used.
- * @param result the resulting list of partitions
- * @return whether the resulting list contains partitions which may or may not match the expr
- */
- boolean listPartitionsByExpr(String db_name, String tbl_name,
- byte[] expr, String default_partition_name, short max_parts, List<Partition> result)
- throws TException;
-
- /**
- * @param dbName
- * @param tableName
- * @param s
- * @param userName
- * @param groupNames
- * @return the list of partitions
- * @throws NoSuchObjectException
- */
- List<Partition> listPartitionsWithAuthInfo(String dbName,
- String tableName, short s, String userName, List<String> groupNames)
- throws MetaException, TException, NoSuchObjectException;
-
- /**
- * Get partitions by a list of partition names.
- * @param db_name database name
- * @param tbl_name table name
- * @param part_names list of partition names
- * @return list of Partition objects
- * @throws NoSuchObjectException
- * @throws MetaException
- * @throws TException
- */
- List<Partition> getPartitionsByNames(String db_name, String tbl_name,
- List<String> part_names) throws NoSuchObjectException, MetaException, TException;
-
- /**
- * @param dbName
- * @param tableName
- * @param partialPvals
- * @param s
- * @param userName
- * @param groupNames
- * @return the list of paritions
- * @throws NoSuchObjectException
- */
- List<Partition> listPartitionsWithAuthInfo(String dbName,
- String tableName, List<String> partialPvals, short s, String userName,
- List<String> groupNames) throws MetaException, TException, NoSuchObjectException;
-
- /**
- * @param db_name
- * @param tbl_name
- * @param partKVs
- * @param eventType
- * @throws MetaException
- * @throws NoSuchObjectException
- * @throws TException
- * @throws UnknownTableException
- * @throws UnknownDBException
- * @throws UnknownPartitionException
- * @throws InvalidPartitionException
- */
- void markPartitionForEvent(String db_name, String tbl_name, Map<String,String> partKVs,
- PartitionEventType eventType) throws MetaException, NoSuchObjectException, TException,
- UnknownTableException, UnknownDBException, UnknownPartitionException, InvalidPartitionException;
-
- /**
- * @param db_name
- * @param tbl_name
- * @param partKVs
- * @param eventType
- * @throws MetaException
- * @throws NoSuchObjectException
- * @throws TException
- * @throws UnknownTableException
- * @throws UnknownDBException
- * @throws UnknownPartitionException
- * @throws InvalidPartitionException
- */
- boolean isPartitionMarkedForEvent(String db_name, String tbl_name, Map<String,String> partKVs,
- PartitionEventType eventType) throws MetaException, NoSuchObjectException, TException,
- UnknownTableException, UnknownDBException, UnknownPartitionException, InvalidPartitionException;
-
- /**
- * @param partVals
- * @throws TException
- * @throws MetaException
- */
- void validatePartitionNameCharacters(List<String> partVals) throws TException, MetaException;
-
- /**
- * @param tbl
- * @throws AlreadyExistsException
- * @throws InvalidObjectException
- * @throws MetaException
- * @throws NoSuchObjectException
- * @throws TException
- * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#create_table(org.apache.hadoop.hive.metastore.api.Table)
- */
-
- void createTable(Table tbl) throws AlreadyExistsException,
- InvalidObjectException, MetaException, NoSuchObjectException, TException;
-
- void alter_table(String defaultDatabaseName, String tblName,
- Table table) throws InvalidOperationException, MetaException, TException;
-
- /**
- * Use alter_table_with_environmentContext instead of alter_table with cascade option
- * passed in EnvironmentContext using {@code StatsSetupConst.CASCADE}
- */
- @Deprecated
- void alter_table(String defaultDatabaseName, String tblName, Table table,
- boolean cascade) throws InvalidOperationException, MetaException, TException;
-
- //wrapper of alter_table_with_cascade
- void alter_table_with_environmentContext(String defaultDatabaseName, String tblName, Table table,
- EnvironmentContext environmentContext) throws InvalidOperationException, MetaException,
- TException;
-
- void createDatabase(Database db)
- throws InvalidObjectException, AlreadyExistsException, MetaException, TException;
-
- void dropDatabase(String name)
- throws NoSuchObjectException, InvalidOperationException, MetaException, TException;
-
- void dropDatabase(String name, boolean deleteData, boolean ignoreUnknownDb)
- throws NoSuchObjectException, InvalidOperationException, MetaException, TException;
-
- void dropDatabase(String name, boolean deleteData, boolean ignoreUnknownDb, boolean cascade)
- throws NoSuchObjectException, InvalidOperationException, MetaException, TException;
-
- void alterDatabase(String name, Database db)
- throws NoSuchObjectException, MetaException, TException;
-
- /**
- * @param db_name
- * @param tbl_name
- * @param part_vals
- * @param deleteData
- * delete the underlying data or just delete the table in metadata
- * @return true or false
- * @throws NoSuchObjectException
- * @throws MetaException
- * @throws TException
- * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#drop_partition(java.lang.String,
- * java.lang.String, java.util.List, boolean)
- */
- boolean dropPartition(String db_name, String tbl_name,
- List<String> part_vals, boolean deleteData) throws NoSuchObjectException,
- MetaException, TException;
-
- /**
- * Method to dropPartitions() with the option to purge the partition data directly,
- * rather than to move data to trash.
- * @param db_name Name of the database.
- * @param tbl_name Name of the table.
- * @param part_vals Specification of the partitions being dropped.
- * @param options PartitionDropOptions for the operation.
- * @return True (if partitions are dropped), else false.
- * @throws TException
- */
- boolean dropPartition(String db_name, String tbl_name, List<String> part_vals,
- PartitionDropOptions options) throws TException;
-
- List<Partition> dropPartitions(String dbName, String tblName,
- List<ObjectPair<Integer, byte[]>> partExprs, boolean deleteData,
- boolean ifExists) throws NoSuchObjectException, MetaException, TException;
-
- List<Partition> dropPartitions(String dbName, String tblName,
- List<ObjectPair<Integer, byte[]>> partExprs, boolean deleteData,
- boolean ifExists, boolean needResults) throws NoSuchObjectException, MetaException, TException;
-
- /**
- * Generalization of dropPartitions(),
- * @param dbName Name of the database
- * @param tblName Name of the table
- * @param partExprs Partition-specification
- * @param options Boolean options for dropping partitions
- * @return List of Partitions dropped
- * @throws TException On failure
- */
- List<Partition> dropPartitions(String dbName, String tblName,
- List<ObjectPair<Integer, byte[]>> partExprs, PartitionDropOptions options) throws TException;
-
- boolean dropPartition(String db_name, String tbl_name,
- String name, boolean deleteData) throws NoSuchObjectException,
- MetaException, TException;
-
- /**
- * updates a partition to new partition
- *
- * @param dbName
- * database of the old partition
- * @param tblName
- * table name of the old partition
- * @param newPart
- * new partition
- * @throws InvalidOperationException
- * if the old partition does not exist
- * @throws MetaException
- * if error in updating metadata
- * @throws TException
- * if error in communicating with metastore server
- */
- void alter_partition(String dbName, String tblName, Partition newPart)
- throws InvalidOperationException, MetaException, TException;
-
- /**
- * updates a partition to new partition
- *
- * @param dbName
- * database of the old partition
- * @param tblName
- * table name of the old partition
- * @param newPart
- * new partition
- * @throws InvalidOperationException
- * if the old partition does not exist
- * @throws MetaException
- * if error in updating metadata
- * @throws TException
- * if error in communicating with metastore server
- */
- void alter_partition(String dbName, String tblName, Partition newPart, EnvironmentContext environmentContext)
- throws InvalidOperationException, MetaException, TException;
-
- /**
- * updates a list of partitions
- *
- * @param dbName
- * database of the old partition
- * @param tblName
- * table name of the old partition
- * @param newParts
- * list of partitions
- * @throws InvalidOperationException
- * if the old partition does not exist
- * @throws MetaException
- * if error in updating metadata
- * @throws TException
- * if error in communicating with metastore server
- */
- void alter_partitions(String dbName, String tblName, List<Partition> newParts)
- throws InvalidOperationException, MetaException, TException;
-
- /**
- * updates a list of partitions
- *
- * @param dbName
- * database of the old partition
- * @param tblName
- * table name of the old partition
- * @param newParts
- * list of partitions
- * @param environmentContext
- * @throws InvalidOperationException
- * if the old partition does not exist
- * @throws MetaException
- * if error in updating metadata
- * @throws TException
- * if error in communicating with metastore server
- */
- void alter_partitions(String dbName, String tblName, List<Partition> newParts,
- EnvironmentContext environmentContext)
- throws InvalidOperationException, MetaException, TException;
-
- /**
- * rename a partition to a new partition
- *
- * @param dbname
- * database of the old partition
- * @param name
- * table name of the old partition
- * @param part_vals
- * values of the old partition
- * @param newPart
- * new partition
- * @throws InvalidOperationException
- * if srcFs and destFs are different
- * @throws MetaException
- * if error in updating metadata
- * @throws TException
- * if error in communicating with metastore server
- */
- void renamePartition(final String dbname, final String name, final List<String> part_vals, final Partition newPart)
- throws InvalidOperationException, MetaException, TException;
-
- /**
- * @param db
- * @param tableName
- * @throws UnknownTableException
- * @throws UnknownDBException
- * @throws MetaException
- * @throws TException
- * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#get_fields(java.lang.String,
- * java.lang.String)
- */
- List<FieldSchema> getFields(String db, String tableName)
- throws MetaException, TException, UnknownTableException,
- UnknownDBException;
-
- /**
- * @param db
- * @param tableName
- * @throws UnknownTableException
- * @throws UnknownDBException
- * @throws MetaException
- * @throws TException
- * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#get_schema(java.lang.String,
- * java.lang.String)
- */
- List<FieldSchema> getSchema(String db, String tableName)
- throws MetaException, TException, UnknownTableException,
- UnknownDBException;
-
- /**
- * @param name
- * name of the configuration property to get the value of
- * @param defaultValue
- * the value to return if property with the given name doesn't exist
- * @return value of the specified configuration property
- * @throws TException
- * @throws ConfigValSecurityException
- */
- String getConfigValue(String name, String defaultValue)
- throws TException, ConfigValSecurityException;
-
- /**
- *
- * @param name
- * the partition name e.g. ("ds=2010-03-03/hr=12")
- * @return a list containing the partition col values, in the same order as the name
- * @throws MetaException
- * @throws TException
- */
- List<String> partitionNameToVals(String name)
- throws MetaException, TException;
- /**
- *
- * @param name
- * the partition name e.g. ("ds=2010-03-03/hr=12")
- * @return a map from the partition col to the value, as listed in the name
- * @throws MetaException
- * @throws TException
- */
- Map<String, String> partitionNameToSpec(String name)
- throws MetaException, TException;
-
- /**
- * create an index
- * @param index the index object
- * @throws InvalidObjectException
- * @throws MetaException
- * @throws NoSuchObjectException
- * @throws TException
- * @throws AlreadyExistsException
- */
- void createIndex(Index index, Table indexTable) throws InvalidObjectException,
- MetaException, NoSuchObjectException, TException, AlreadyExistsException;
-
- void alter_index(String dbName, String tblName, String indexName,
- Index index) throws InvalidOperationException, MetaException, TException;
-
- /**
- *
- * @param dbName
- * @param tblName
- * @param indexName
- * @return the index
- * @throws MetaException
- * @throws UnknownTableException
- * @throws NoSuchObjectException
- * @throws TException
- */
- Index getIndex(String dbName, String tblName, String indexName)
- throws MetaException, UnknownTableException, NoSuchObjectException,
- TException;
-
-
- /**
- * list indexes of the give base table
- * @param db_name
- * @param tbl_name
- * @param max
- * @return the list of indexes
- * @throws NoSuchObjectException
- * @throws MetaException
- * @throws TException
- */
- List<Index> listIndexes(String db_name, String tbl_name,
- short max) throws NoSuchObjectException, MetaException, TException;
-
- /**
- * list all the index names of the give base table.
- *
- * @param db_name
- * @param tbl_name
- * @param max
- * @return the list of names
- * @throws MetaException
- * @throws TException
- */
- List<String> listIndexNames(String db_name, String tbl_name,
- short max) throws MetaException, TException;
-
- /**
- * @param db_name
- * @param tbl_name
- * @param name index name
- * @param deleteData
- * @return true on success
- * @throws NoSuchObjectException
- * @throws MetaException
- * @throws TException
- */
- boolean dropIndex(String db_name, String tbl_name,
- String name, boolean deleteData) throws NoSuchObjectException,
- MetaException, TException;
-
- /**
- * Write table level column statistics to persistent store
- * @param statsObj
- * @return boolean indicating the status of the operation
- * @throws NoSuchObjectException
- * @throws InvalidObjectException
- * @throws MetaException
- * @throws TException
- * @throws InvalidInputException
- */
-
- boolean updateTableColumnStatistics(ColumnStatistics statsObj)
- throws NoSuchObjectException, InvalidObjectException, MetaException, TException,
- InvalidInputException;
-
- /**
- * Write partition level column statistics to persistent store
- * @param statsObj
- * @return boolean indicating the status of the operation
- * @throws NoSuchObjectException
- * @throws InvalidObjectException
- * @throws MetaException
- * @throws TException
- * @throws InvalidInputException
- */
-
- boolean updatePartitionColumnStatistics(ColumnStatistics statsObj)
- throws NoSuchObjectException, InvalidObjectException, MetaException, TException,
- InvalidInputException;
-
- /**
- * Get table column statistics given dbName, tableName and multiple colName-s
- * @return ColumnStatistics struct for a given db, table and columns
- */
- List<ColumnStatisticsObj> getTableColumnStatistics(String dbName, String tableName,
- List<String> colNames) throws NoSuchObjectException, MetaException, TException;
-
- /**
- * Get partitions column statistics given dbName, tableName, multiple partitions and colName-s
- * @return ColumnStatistics struct for a given db, table and columns
- */
- Map<String, List<ColumnStatisticsObj>> getPartitionColumnStatistics(String dbName,
- String tableName, List<String> partNames, List<String> colNames)
- throws NoSuchObjectException, MetaException, TException;
-
- /**
- * Delete partition level column statistics given dbName, tableName, partName and colName
- * @param dbName
- * @param tableName
- * @param partName
- * @param colName
- * @return boolean indicating outcome of the operation
- * @throws NoSuchObjectException
- * @throws InvalidObjectException
- * @throws MetaException
- * @throws TException
- * @throws InvalidInputException
- */
-
- boolean deletePartitionColumnStatistics(String dbName, String tableName,
- String partName, String colName) throws NoSuchObjectException, MetaException,
- InvalidObjectException, TException, InvalidInputException;
-
- /**
- * Delete table level column statistics given dbName, tableName and colName
- * @param dbName
- * @param tableName
- * @param colName
- * @return boolean indicating the outcome of the operation
- * @throws NoSuchObjectException
- * @throws MetaException
- * @throws InvalidObjectException
- * @throws TException
- * @throws InvalidInputException
- */
- boolean deleteTableColumnStatistics(String dbName, String tableName, String colName) throws
- NoSuchObjectException, MetaException, InvalidObjectException, TException, InvalidInputException;
-
- /**
- * @param role
- * role object
- * @return true on success
- * @throws MetaException
- * @throws TException
- */
- boolean create_role(Role role)
- throws MetaException, TException;
-
- /**
- * @param role_name
- * role name
- *
- * @return true on success
- * @throws MetaException
- * @throws TException
- */
- boolean drop_role(String role_name) throws MetaException, TException;
-
- /**
- * list all role names
- * @return list of names
- * @throws TException
- * @throws MetaException
- */
- List<String> listRoleNames() throws MetaException, TException;
-
- /**
- *
- * @param role_name
- * @param user_name
- * @param principalType
- * @param grantor
- * @param grantorType
- * @param grantOption
- * @return true on success
- * @throws MetaException
- * @throws TException
- */
- boolean grant_role(String role_name, String user_name,
- PrincipalType principalType, String grantor, PrincipalType grantorType,
- boolean grantOption) throws MetaException, TException;
-
- /**
- * @param role_name
- * role name
- * @param user_name
- * user name
- * @param principalType
- *
- * @return true on success
- * @throws MetaException
- * @throws TException
- */
- boolean revoke_role(String role_name, String user_name,
- PrincipalType principalType, boolean grantOption) throws MetaException, TException;
-
- /**
- *
- * @param principalName
- * @param principalType
- * @return list of roles
- * @throws MetaException
- * @throws TException
- */
- List<Role> list_roles(String principalName, PrincipalType principalType)
- throws MetaException, TException;
-
- /**
- * Return the privileges that the user, group have directly and indirectly through roles
- * on the given hiveObject
- * @param hiveObject
- * @param user_name
- * @param group_names
- * @return the privilege set
- * @throws MetaException
- * @throws TException
- */
- PrincipalPrivilegeSet get_privilege_set(HiveObjectRef hiveObject,
- String user_name, List<String> group_names) throws MetaException,
- TException;
-
- /**
- * Return the privileges that this principal has directly over the object (not through roles).
- * @param principal_name
- * @param principal_type
- * @param hiveObject
- * @return list of privileges
- * @throws MetaException
- * @throws TException
- */
- List<HiveObjectPrivilege> list_privileges(String principal_name,
- PrincipalType principal_type, HiveObjectRef hiveObject)
- throws MetaException, TException;
-
- /**
- * @param privileges
- * @return true on success
- * @throws MetaException
- * @throws TException
- */
- boolean grant_privileges(PrivilegeBag privileges)
- throws MetaException, TException;
-
- /**
- * @param privileges
- * @return true on success
- * @throws MetaException
- * @throws TException
- */
- boolean revoke_privileges(PrivilegeBag privileges, boolean grantOption)
- throws MetaException, TException;
-
- /**
- * This is expected to be a no-op when in local mode,
- * which means that the implementation will return null.
- * @param owner the intended owner for the token
- * @param renewerKerberosPrincipalName
- * @return the string of the token
- * @throws MetaException
- * @throws TException
- */
- String getDelegationToken(String owner, String renewerKerberosPrincipalName)
- throws MetaException, TException;
-
- /**
- * @param tokenStrForm
- * @return the new expiration time
- * @throws MetaException
- * @throws TException
- */
- long renewDelegationToken(String tokenStrForm) throws MetaException, TException;
-
- /**
- * @param tokenStrForm
- * @throws MetaException
- * @throws TException
- */
- void cancelDelegationToken(String tokenStrForm) throws MetaException, TException;
-
- String getTokenStrForm() throws IOException;
-
- boolean addToken(String tokenIdentifier, String delegationToken) throws TException;
-
- boolean removeToken(String tokenIdentifier) throws TException;
-
- String getToken(String tokenIdentifier) throws TException;
-
- List<String> getAllTokenIdentifiers() throws TException;
-
- int addMasterKey(String key) throws MetaException, TException;
-
- void updateMasterKey(Integer seqNo, String key)
- throws NoSuchObjectException, MetaException, TException;
-
- boolean removeMasterKey(Integer keySeq) throws TException;
-
- String[] getMasterKeys() throws TException;
-
- void createFunction(Function func)
- throws InvalidObjectException, MetaException, TException;
-
- void alterFunction(String dbName, String funcName, Function newFunction)
- throws InvalidObjectException, MetaException, TException;
-
- void dropFunction(String dbName, String funcName) throws MetaException,
- NoSuchObjectException, InvalidObjectException, InvalidInputException, TException;
-
- Function getFunction(String dbName, String funcName)
- throws MetaException, TException;
-
- List<String> getFunctions(String dbName, String pattern)
- throws MetaException, TException;
-
- GetAllFunctionsResponse getAllFunctions()
- throws MetaException, TException;
-
- /**
- * Get a structure that details valid transactions.
- * @return list of valid transactions
- * @throws TException
- */
- ValidTxnList getValidTxns() throws TException;
-
- /**
- * Get a structure that details valid transactions.
- * @param currentTxn The current transaction of the caller. This will be removed from the
- * exceptions list so that the caller sees records from his own transaction.
- * @return list of valid transactions
- * @throws TException
- */
- ValidTxnList getValidTxns(long currentTxn) throws TException;
-
- /**
- * Initiate a transaction.
- * @param user User who is opening this transaction. This is the Hive user,
- * not necessarily the OS user. It is assumed that this user has already been
- * authenticated and authorized at this point.
- * @return transaction identifier
- * @throws TException
- */
- long openTxn(String user) throws TException;
-
- /**
- * Initiate a batch of transactions. It is not guaranteed that the
- * requested number of transactions will be instantiated. The system has a
- * maximum number instantiated per request, controlled by hive.txn.max
- * .batch.open in hive-site.xml. If the user requests more than this
- * value, only the configured max will be returned.
- *
- * <p>Increasing the number of transactions requested in the batch will
- * allow applications that stream data into Hive to place more commits in a
- * single file, thus reducing load on the namenode and making reads of the
- * data more efficient. However, opening more transactions in a batch will
- * also result in readers needing to keep a larger list of open
- * transactions to ignore, potentially slowing their reads. Users will
- * need to test in their system to understand the optimal number of
- * transactions to request in a batch.
- * </p>
- * @param user User who is opening this transaction. This is the Hive user,
- * not necessarily the OS user. It is assumed that this user has already been
- * authenticated and authorized at this point.
- * @param numTxns number of requested transactions to open
- * @return list of opened txn ids. As noted above, this may be less than
- * requested, so the user should check how many were returned rather than
- * optimistically assuming that the result matches the request.
- * @throws TException
- */
- OpenTxnsResponse openTxns(String user, int numTxns) throws TException;
-
- /**
- * Rollback a transaction. This will also unlock any locks associated with
- * this transaction.
- * @param txnid id of transaction to be rolled back.
- * @throws NoSuchTxnException if the requested transaction does not exist.
- * Note that this can result from the transaction having timed out and been
- * deleted.
- * @throws TException
- */
- void rollbackTxn(long txnid) throws NoSuchTxnException, TException;
-
- /**
- * Commit a transaction. This will also unlock any locks associated with
- * this transaction.
- * @param txnid id of transaction to be committed.
- * @throws NoSuchTxnException if the requested transaction does not exist.
- * This can result fro the transaction having timed out and been deleted by
- * the compactor.
- * @throws TxnAbortedException if the requested transaction has been
- * aborted. This can result from the transaction timing out.
- * @throws TException
- */
- void commitTxn(long txnid)
- throws NoSuchTxnException, TxnAbortedException, TException;
-
- /**
- * Abort a list of transactions. This is for use by "ABORT TRANSACTIONS" in the grammar.
- * @throws TException
- */
- void abortTxns(List<Long> txnids) throws TException;
-
- /**
- * Show the list of currently open transactions. This is for use by "show transactions" in the
- * grammar, not for applications that want to find a list of current transactions to work with.
- * Those wishing the latter should call {@link #getValidTxns()}.
- * @return List of currently opened transactions, included aborted ones.
- * @throws TException
- */
- GetOpenTxnsInfoResponse showTxns() throws TException;
-
- /**
- * Request a set of locks. All locks needed for a particular query, DML,
- * or DDL operation should be batched together and requested in one lock
- * call. This avoids deadlocks. It also avoids blocking other users who
- * only require some of the locks required by this user.
- *
- * <p>If the operation requires a transaction (INSERT, UPDATE,
- * or DELETE) that transaction id must be provided as part this lock
- * request. All locks associated with a transaction will be released when
- * that transaction is committed or rolled back.</p>
- * *
- * <p>Once a lock is acquired, {@link #heartbeat(long, long)} must be called
- * on a regular basis to avoid the lock being timed out by the system.</p>
- * @param request The lock request. {@link LockRequestBuilder} can be used
- * construct this request.
- * @return a lock response, which will provide two things,
- * the id of the lock (to be used in all further calls regarding this lock)
- * as well as a state of the lock. If the state is ACQUIRED then the user
- * can proceed. If it is WAITING the user should wait and call
- * {@link #checkLock(long)} before proceeding. All components of the lock
- * will have the same state.
- * @throws NoSuchTxnException if the requested transaction does not exist.
- * This can result fro the transaction having timed out and been deleted by
- * the compactor.
- * @throws TxnAbortedException if the requested transaction has been
- * aborted. This can result from the transaction timing out.
- * @throws TException
- */
- @RetrySemantics.CannotRetry
- LockResponse lock(LockRequest request)
- throws NoSuchTxnException, TxnAbortedException, TException;
-
- /**
- * Check the status of a set of locks requested via a
- * {@link #lock(org.apache.hadoop.hive.metastore.api.LockRequest)} call.
- * Once a lock is acquired, {@link #heartbeat(long, long)} must be called
- * on a regular basis to avoid the lock being timed out by the system.
- * @param lockid lock id returned by lock().
- * @return a lock response, which will provide two things,
- * the id of the lock (to be used in all further calls regarding this lock)
- * as well as a state of the lock. If the state is ACQUIRED then the user
- * can proceed. If it is WAITING the user should wait and call
- * this method again before proceeding. All components of the lock
- * will have the same state.
- * @throws NoSuchTxnException if the requested transaction does not exist.
- * This can result fro the transaction having timed out and been deleted by
- * the compactor.
- * @throws TxnAbortedException if the requested transaction has been
- * aborted. This can result from the transaction timing out.
- * @throws NoSuchLockException if the requested lockid does not exist.
- * This can result from the lock timing out and being unlocked by the system.
- * @throws TException
- */
- LockResponse checkLock(long lockid)
- throws NoSuchTxnException, TxnAbortedException, NoSuchLockException,
- TException;
-
- /**
- * Unlock a set of locks. This can only be called when the locks are not
- * assocaited with a transaction.
- * @param lockid lock id returned by
- * {@link #lock(org.apache.hadoop.hive.metastore.api.LockRequest)}
- * @throws NoSuchLockException if the requested lockid does not exist.
- * This can result from the lock timing out and being unlocked by the system.
- * @throws TxnOpenException if the locks are are associated with a
- * transaction.
- * @throws TException
- */
- void unlock(long lockid)
- throws NoSuchLockException, TxnOpenException, TException;
-
- /**
- * Show all currently held and waiting locks.
- * @return List of currently held and waiting locks.
- * @throws TException
- */
- @Deprecated
- ShowLocksResponse showLocks() throws TException;
-
- /**
- * Show all currently held and waiting locks.
- * @param showLocksRequest SHOW LOCK request
- * @return List of currently held and waiting locks.
- * @throws TException
- */
- ShowLocksResponse showLocks(ShowLocksRequest showLocksRequest) throws TException;
-
- /**
- * Send a heartbeat to indicate that the client holding these locks (if
- * any) and that opened this transaction (if one exists) is still alive.
- * The default timeout for transactions and locks is 300 seconds,
- * though it is configurable. To determine how often to heartbeat you will
- * need to ask your system administrator how the metastore thrift service
- * has been configured.
- * @param txnid the id of the open transaction. If no transaction is open
- * (it is a DDL or query) then this can be set to 0.
- * @param lockid the id of the locks obtained. If no locks have been
- * obtained then this can be set to 0.
- * @throws NoSuchTxnException if the requested transaction does not exist.
- * This can result fro the transaction having timed out and been deleted by
- * the compactor.
- * @throws TxnAbortedException if the requested transaction has been
- * aborted. This can result from the transaction timing out.
- * @throws NoSuchLockException if the requested lockid does not exist.
- * This can result from the lock timing out and being unlocked by the system.
- * @throws TException
- */
- void heartbeat(long txnid, long lockid)
- throws NoSuchLockException, NoSuchTxnException, TxnAbortedException,
- TException;
-
- /**
- * Send heartbeats for a range of transactions. This is for the streaming ingest client that
- * will have many transactions open at once. Everyone else should use
- * {@link #heartbeat(long, long)}.
- * @param min minimum transaction id to heartbeat, inclusive
- * @param max maximum transaction id to heartbeat, inclusive
- * @return a pair of lists that tell which transactions in the list did not exist (they may
- * have already been closed) and which were aborted.
- * @throws TException
- */
- HeartbeatTxnRangeResponse heartbeatTxnRange(long min, long max) throws TException;
-
- /**
- * Send a request to compact a table or partition. This will not block until the compaction is
- * complete. It will instead put a request on the queue for that table or partition to be
- * compacted. No checking is done on the dbname, tableName, or partitionName to make sure they
- * refer to valid objects. It is assumed this has already been done by the caller.
- * @param dbname Name of the database the table is in. If null, this will be assumed to be
- * 'default'.
- * @param tableName Name of the table to be compacted. This cannot be null. If partitionName
- * is null, this must be a non-partitioned table.
- * @param partitionName Name of the partition to be compacted
- * @param type Whether this is a major or minor compaction.
- * @throws TException
- */
- @Deprecated
- void compact(String dbname, String tableName, String partitionName, CompactionType type)
- throws TException;
- @Deprecated
- void compact(String dbname, String tableName, String partitionName, CompactionType type,
- Map<String, String> tblproperties) throws TException;
- /**
- * Send a request to compact a table or partition. This will not block until the compaction is
- * complete. It will instead put a request on the queue for that table or partition to be
- * compacted. No checking is done on the dbname, tableName, or partitionName to make sure they
- * refer to valid objects. It is assumed this has already been done by the caller. At most one
- * Compaction can be scheduled/running for any given resource at a time.
- * @param dbname Name of the database the table is in. If null, this will be assumed to be
- * 'default'.
- * @param tableName Name of the table to be compacted. This cannot be null. If partitionName
- * is null, this must be a non-partitioned table.
- * @param partitionName Name of the partition to be compacted
- * @param type Whether this is a major or minor compaction.
- * @param tblproperties the list of tblproperties to override for this compact. Can be null.
- * @return id of newly scheduled compaction or id/state of one which is already scheduled/running
- * @throws TException
- */
- CompactionResponse compact2(String dbname, String tableName, String partitionName, CompactionType type,
- Map<String, String> tblproperties) throws TException;
-
- /**
- * Get a list of all compactions.
- * @return List of all current compactions. This includes compactions waiting to happen,
- * in progress, and finished but waiting to clean the existing files.
- * @throws TException
- */
- ShowCompactResponse showCompactions() throws TException;
-
- /**
- * @deprecated in Hive 1.3.0/2.1.0 - will be removed in 2 releases
- */
- @Deprecated
- void addDynamicPartitions(long txnId, String dbName, String tableName, List<String> partNames)
- throws TException;
- /**
- * Send a list of partitions to the metastore to indicate which partitions were loaded
- * dynamically.
- * @param txnId id of the transaction
- * @param dbName database name
- * @param tableName table name
- * @param partNames partition name, as constructed by Warehouse.makePartName
- * @throws TException
- */
- void addDynamicPartitions(long txnId, String dbName, String tableName, List<String> partNames,
- DataOperationType operationType)
- throws TException;
-
- /**
- * Performs the commit/rollback to the metadata storage for insert operator from external storage handler.
- * @param table table name
- * @param overwrite true if the insert is overwrite
- *
- * @throws MetaException
- */
- void insertTable(Table table, boolean overwrite) throws MetaException;
-
- /**
- * A filter provided by the client that determines if a given notification event should be
- * returned.
- */
- @InterfaceAudience.LimitedPrivate({"HCatalog"})
- interface NotificationFilter {
- /**
- * Whether a notification event should be accepted
- * @param event
- * @return if true, event will be added to list, if false it will be ignored
- */
- boolean accept(NotificationEvent event);
- }
-
- /**
- * Get the next set of notifications from the database.
- * @param lastEventId The last event id that was consumed by this reader. The returned
- * notifications will start at the next eventId available after this eventId.
- * @param maxEvents Maximum number of events to return. If < 1, then all available events will
- * be returned.
- * @param filter User provided filter to remove unwanted events. If null, all events will be
- * returned.
- * @return list of notifications, sorted by eventId. It is guaranteed that the events are in
- * the order that the operations were done on the database.
- * @throws TException
- */
- @InterfaceAudience.LimitedPrivate({"HCatalog"})
- NotificationEventResponse getNextNotification(long lastEventId, int maxEvents,
- NotificationFilter filter) throws TException;
-
- /**
- * Get the last used notification event id.
- * @return last used id
- * @throws TException
- */
- @InterfaceAudience.LimitedPrivate({"HCatalog"})
- CurrentNotificationEventId getCurrentNotificationEventId() throws TException;
-
- /**
- * Get the number of events from given eventID for the input database.
- * @return number of events
- * @throws TException
- */
- @InterfaceAudience.LimitedPrivate({"HCatalog"})
- NotificationEventsCountResponse getNotificationEventsCount(NotificationEventsCountRequest rqst)
- throws TException;
-
- /**
- * Request that the metastore fire an event. Currently this is only supported for DML
- * operations, since the metastore knows when DDL operations happen.
- * @param request
- * @return response, type depends on type of request
- * @throws TException
- */
-
- @InterfaceAudience.LimitedPrivate({"Apache Hive, HCatalog"})
- FireEventResponse fireListenerEvent(FireEventRequest request) throws TException;
-
- class IncompatibleMetastoreException extends MetaException {
- IncompatibleMetastoreException(String message) {
- super(message);
- }
- }
-
- /**
- * get all role-grants for users/roles that have been granted the given role
- * Note that in the returned list of RolePrincipalGrants, the roleName is
- * redundant as it would match the role_name argument of this function
- * @param getPrincRoleReq
- * @return
- * @throws MetaException
- * @throws TException
- */
- GetPrincipalsInRoleResponse get_principals_in_role(GetPrincipalsInRoleRequest getPrincRoleReq)
- throws MetaException, TException;
-
- /**
- * get all role-grants for roles that have been granted to given principal
- * Note that in the returned list of RolePrincipalGrants, the principal information
- * redundant as it would match the principal information in request
- * @param getRolePrincReq
- * @return
- * @throws MetaException
- * @throws TException
- */
- GetRoleGrantsForPrincipalResponse get_role_grants_for_principal(
- GetRoleGrantsForPrincipalRequest getRolePrincReq) throws MetaException, TException;
-
- public AggrStats getAggrColStatsFor(String dbName, String tblName,
- List<String> colNames, List<String> partName) throws NoSuchObjectException, MetaException, TException;
-
- boolean setPartitionColumnStatistics(SetPartitionsStatsRequest request) throws NoSuchObjectException, InvalidObjectException, MetaException, TException, InvalidInputException;
-
- /**
- * Flush any catalog objects held by the metastore implementation. Note that this does not
- * flush statistics objects. This should be called at the beginning of each query.
- */
- void flushCache();
-
- /**
- * Gets file metadata, as cached by metastore, for respective file IDs.
- * The metadata that is not cached in metastore may be missing.
- */
- Iterable<Entry<Long, ByteBuffer>> getFileMetadata(List<Long> fileIds) throws TException;
-
- Iterable<Entry<Long, MetadataPpdResult>> getFileMetadataBySarg(
- List<Long> fileIds, ByteBuffer sarg, boolean doGetFooters) throws TException;
-
- /**
- * Cleares the file metadata cache for respective file IDs.
- */
- void clearFileMetadata(List<Long> fileIds) throws TException;
-
- /**
- * Adds file metadata for respective file IDs to metadata cache in metastore.
- */
- void putFileMetadata(List<Long> fileIds, List<ByteBuffer> metadata) throws TException;
-
- boolean isSameConfObj(HiveConf c);
-
- boolean cacheFileMetadata(String dbName, String tableName, String partName,
- boolean allParts) throws TException;
-
- List<SQLPrimaryKey> getPrimaryKeys(PrimaryKeysRequest request)
- throws MetaException, NoSuchObjectException, TException;
-
- List<SQLForeignKey> getForeignKeys(ForeignKeysRequest request) throws MetaException,
- NoSuchObjectException, TException;
-
- List<SQLUniqueConstraint> getUniqueConstraints(UniqueConstraintsRequest request) throws MetaException,
- NoSuchObjectException, TException;
-
- List<SQLNotNullConstraint> getNotNullConstraints(NotNullConstraintsRequest request) throws MetaException,
- NoSuchObjectException, TException;
-
- void createTableWithConstraints(
- org.apache.hadoop.hive.metastore.api.Table tTbl,
- List<SQLPrimaryKey> primaryKeys, List<SQLForeignKey> foreignKeys,
- List<SQLUniqueConstraint> uniqueConstraints,
- List<SQLNotNullConstraint> notNullConstraints)
- throws AlreadyExistsException, InvalidObjectException, MetaException, NoSuchObjectException, TException;
-
- void dropConstraint(String dbName, String tableName, String constraintName) throws
- MetaException, NoSuchObjectException, TException;
-
- void addPrimaryKey(List<SQLPrimaryKey> primaryKeyCols) throws
- MetaException, NoSuchObjectException, TException;
-
- void addForeignKey(List<SQLForeignKey> foreignKeyCols) throws
- MetaException, NoSuchObjectException, TException;
-
- void addUniqueConstraint(List<SQLUniqueConstraint> uniqueConstraintCols) throws
- MetaException, NoSuchObjectException, TException;
-
- void addNotNullConstraint(List<SQLNotNullConstraint> notNullConstraintCols) throws
- MetaException, NoSuchObjectException, TException;
-
- /**
- * Gets the unique id of the backing database instance used for storing metadata
- * @return unique id of the backing database instance
- * @throws MetaException if HMS is not able to fetch the UUID or if there are multiple UUIDs found in the database
- * @throws TException in case of Thrift errors
- */
- String getMetastoreDbUuid() throws MetaException, TException;
-
- void createResourcePlan(WMResourcePlan resourcePlan)
- throws InvalidObjectException, MetaException, TException;
-
- WMResourcePlan getResourcePlan(String resourcePlanName)
- throws NoSuchObjectException, MetaException, TException;
-
- List<WMResourcePlan> getAllResourcePlans()
- throws NoSuchObjectException, MetaException, TException;
-
- void dropResourcePlan(String resourcePlanName)
- throws NoSuchObjectException, MetaException, TException;
-
- void alterResourcePlan(String resourcePlanName, WMResourcePlan resourcePlan)
- throws NoSuchObjectException, InvalidObjectException, MetaException, TException;
-
- boolean validateResourcePlan(String resourcePlanName)
- throws NoSuchObjectException, InvalidObjectException, MetaException, TException;
-
- void createWMTrigger(WMTrigger trigger)
- throws InvalidObjectException, MetaException, TException;
-
- void alterWMTrigger(WMTrigger trigger)
- throws NoSuchObjectException, InvalidObjectException, MetaException, TException;
-
- void dropWMTrigger(String resourcePlanName, String triggerName)
- throws NoSuchObjectException, MetaException, TException;
-
- List<WMTrigger> getTriggersForResourcePlan(String resourcePlan)
- throws NoSuchObjectException, MetaException, TException;
-}
[03/12] hive git commit: HIVE-17980 Moved HiveMetaStoreClient plus a
few remaining classes.
Posted by ga...@apache.org.
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/messaging/EventUtils.java
----------------------------------------------------------------------
diff --git a/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/messaging/EventUtils.java b/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/messaging/EventUtils.java
new file mode 100644
index 0000000..7d8c1d4
--- /dev/null
+++ b/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/messaging/EventUtils.java
@@ -0,0 +1,202 @@
+/*
+ * 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.messaging;
+
+import org.apache.hadoop.hive.metastore.IMetaStoreClient;
+import org.apache.hadoop.hive.metastore.api.NotificationEvent;
+import org.apache.hadoop.hive.metastore.api.NotificationEventsCountRequest;
+import org.apache.hadoop.hive.metastore.conf.MetastoreConf;
+import org.apache.hadoop.hive.metastore.messaging.event.filters.DatabaseAndTableFilter;
+import org.apache.thrift.TException;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+public class EventUtils {
+
+ public interface NotificationFetcher {
+ int getBatchSize() throws IOException;
+ long getCurrentNotificationEventId() throws IOException;
+ long getDbNotificationEventsCount(long fromEventId, String dbName) throws IOException;
+ List<NotificationEvent> getNextNotificationEvents(
+ long pos, IMetaStoreClient.NotificationFilter filter) throws IOException;
+ }
+
+ // MetaStoreClient-based impl of NotificationFetcher
+ public static class MSClientNotificationFetcher implements NotificationFetcher{
+
+ private IMetaStoreClient msc = null;
+ private Integer batchSize = null;
+
+ public MSClientNotificationFetcher(IMetaStoreClient msc){
+ this.msc = msc;
+ }
+
+ @Override
+ public int getBatchSize() throws IOException {
+ if (batchSize == null){
+ try {
+ batchSize = Integer.parseInt(
+ msc.getConfigValue(MetastoreConf.ConfVars.BATCH_RETRIEVE_MAX.toString(), "50"));
+ // TODO: we're asking the metastore what its configuration for this var is - we may
+ // want to revisit to pull from client side instead. The reason I have it this way
+ // is because the metastore is more likely to have a reasonable config for this than
+ // an arbitrary client.
+ } catch (TException e) {
+ throw new IOException(e);
+ }
+ }
+ return batchSize;
+ }
+
+ @Override
+ public long getCurrentNotificationEventId() throws IOException {
+ try {
+ return msc.getCurrentNotificationEventId().getEventId();
+ } catch (TException e) {
+ throw new IOException(e);
+ }
+ }
+
+ @Override
+ public long getDbNotificationEventsCount(long fromEventId, String dbName) throws IOException {
+ try {
+ NotificationEventsCountRequest rqst
+ = new NotificationEventsCountRequest(fromEventId, dbName);
+ return msc.getNotificationEventsCount(rqst).getEventsCount();
+ } catch (TException e) {
+ throw new IOException(e);
+ }
+ }
+
+ @Override
+ public List<NotificationEvent> getNextNotificationEvents(
+ long pos, IMetaStoreClient.NotificationFilter filter) throws IOException {
+ try {
+ return msc.getNextNotification(pos,getBatchSize(), filter).getEvents();
+ } catch (TException e) {
+ throw new IOException(e);
+ }
+ }
+ }
+
+ public static class NotificationEventIterator implements Iterator<NotificationEvent> {
+
+ private NotificationFetcher nfetcher;
+ private IMetaStoreClient.NotificationFilter filter;
+ private int maxEvents;
+
+ private Iterator<NotificationEvent> batchIter = null;
+ private List<NotificationEvent> batch = null;
+ private long pos;
+ private long maxPos;
+ private int eventCount;
+
+ public NotificationEventIterator(
+ NotificationFetcher nfetcher, long eventFrom, int maxEvents,
+ String dbName, String tableName) throws IOException {
+ init(nfetcher, eventFrom, maxEvents, new DatabaseAndTableFilter(dbName, tableName));
+ // using init(..) instead of this(..) because the EventUtils.getDbTblNotificationFilter
+ // is an operation that needs to run before delegating to the other ctor, and this messes up chaining
+ // ctors
+ }
+
+ public NotificationEventIterator(
+ NotificationFetcher nfetcher, long eventFrom, int maxEvents,
+ IMetaStoreClient.NotificationFilter filter) throws IOException {
+ init(nfetcher,eventFrom,maxEvents,filter);
+ }
+
+ private void init(
+ NotificationFetcher nfetcher, long eventFrom, int maxEvents,
+ IMetaStoreClient.NotificationFilter filter) throws IOException {
+ this.nfetcher = nfetcher;
+ this.filter = filter;
+ this.pos = eventFrom;
+ if (maxEvents < 1){
+ // 0 or -1 implies fetch everything
+ this.maxEvents = Integer.MAX_VALUE;
+ } else {
+ this.maxEvents = maxEvents;
+ }
+
+ this.eventCount = 0;
+ this.maxPos = nfetcher.getCurrentNotificationEventId();
+ }
+
+ private void fetchNextBatch() throws IOException {
+ batch = nfetcher.getNextNotificationEvents(pos, filter);
+ int batchSize = nfetcher.getBatchSize();
+ while ( ((batch == null) || (batch.isEmpty())) && (pos < maxPos) ){
+ // no valid events this batch, but we're still not done processing events
+ pos += batchSize;
+ batch = nfetcher.getNextNotificationEvents(pos,filter);
+ }
+
+ if (batch == null){
+ batch = new ArrayList<>();
+ // instantiate empty list so that we don't error out on iterator fetching.
+ // If we're here, then the next check of pos will show our caller that
+ // that we've exhausted our event supply
+ }
+ batchIter = batch.iterator();
+ }
+
+ @Override
+ public boolean hasNext() {
+ if (eventCount >= maxEvents){
+ // If we've already satisfied the number of events we were supposed to deliver, we end it.
+ return false;
+ }
+ if ((batchIter != null) && (batchIter.hasNext())){
+ // If we have a valid batchIter and it has more elements, return them.
+ return true;
+ }
+ // If we're here, we want more events, and either batchIter is null, or batchIter
+ // has reached the end of the current batch. Let's fetch the next batch.
+ try {
+ fetchNextBatch();
+ } catch (IOException e) {
+ // Regrettable that we have to wrap the IOException into a RuntimeException,
+ // but throwing the exception is the appropriate result here, and hasNext()
+ // signature will only allow RuntimeExceptions. Iterator.hasNext() really
+ // should have allowed IOExceptions
+ throw new RuntimeException(e);
+ }
+ // New batch has been fetched. If it's not empty, we have more elements to process.
+ return !batch.isEmpty();
+ }
+
+ @Override
+ public NotificationEvent next() {
+ eventCount++;
+ NotificationEvent ev = batchIter.next();
+ pos = ev.getEventId();
+ return ev;
+ }
+
+ @Override
+ public void remove() {
+ throw new UnsupportedOperationException("remove() not supported on NotificationEventIterator");
+ }
+
+ }
+}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/messaging/event/filters/AndFilter.java
----------------------------------------------------------------------
diff --git a/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/messaging/event/filters/AndFilter.java b/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/messaging/event/filters/AndFilter.java
new file mode 100644
index 0000000..454d2cc
--- /dev/null
+++ b/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/messaging/event/filters/AndFilter.java
@@ -0,0 +1,39 @@
+/*
+ * 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.messaging.event.filters;
+
+import org.apache.hadoop.hive.metastore.IMetaStoreClient;
+import org.apache.hadoop.hive.metastore.api.NotificationEvent;
+
+public class AndFilter implements IMetaStoreClient.NotificationFilter {
+ final IMetaStoreClient.NotificationFilter[] filters;
+
+ public AndFilter(final IMetaStoreClient.NotificationFilter... filters) {
+ this.filters = filters;
+ }
+
+ @Override
+ public boolean accept(final NotificationEvent event) {
+ for (IMetaStoreClient.NotificationFilter filter : filters) {
+ if (!filter.accept(event)) {
+ return false;
+ }
+ }
+ return true;
+ }
+}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/messaging/event/filters/BasicFilter.java
----------------------------------------------------------------------
diff --git a/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/messaging/event/filters/BasicFilter.java b/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/messaging/event/filters/BasicFilter.java
new file mode 100644
index 0000000..84302d6
--- /dev/null
+++ b/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/messaging/event/filters/BasicFilter.java
@@ -0,0 +1,33 @@
+/*
+ * 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.messaging.event.filters;
+
+import org.apache.hadoop.hive.metastore.IMetaStoreClient.NotificationFilter;
+import org.apache.hadoop.hive.metastore.api.NotificationEvent;
+
+public abstract class BasicFilter implements NotificationFilter {
+ @Override
+ public boolean accept(final NotificationEvent event) {
+ if (event == null) {
+ return false; // get rid of trivial case first, so that we can safely assume non-null
+ }
+ return shouldAccept(event);
+ }
+
+ abstract boolean shouldAccept(final NotificationEvent event);
+}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/messaging/event/filters/DatabaseAndTableFilter.java
----------------------------------------------------------------------
diff --git a/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/messaging/event/filters/DatabaseAndTableFilter.java b/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/messaging/event/filters/DatabaseAndTableFilter.java
new file mode 100644
index 0000000..0852abd
--- /dev/null
+++ b/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/messaging/event/filters/DatabaseAndTableFilter.java
@@ -0,0 +1,52 @@
+/*
+ * 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.messaging.event.filters;
+
+import org.apache.hadoop.hive.metastore.api.NotificationEvent;
+
+/**
+ * Utility function that constructs a notification filter to match a given db name and/or table name.
+ * If dbName == null, fetches all warehouse events.
+ * If dnName != null, but tableName == null, fetches all events for the db
+ * If dbName != null && tableName != null, fetches all events for the specified table
+ */
+public class DatabaseAndTableFilter extends BasicFilter {
+ private final String databaseName, tableName;
+
+ public DatabaseAndTableFilter(final String databaseName, final String tableName) {
+ this.databaseName = databaseName;
+ this.tableName = tableName;
+ }
+
+ @Override
+ boolean shouldAccept(final NotificationEvent event) {
+ if (databaseName == null) {
+ return true; // if our dbName is null, we're interested in all wh events
+ }
+ if (databaseName.equalsIgnoreCase(event.getDbName())) {
+ if ((tableName == null)
+ // if our dbName is equal, but tableName is blank, we're interested in this db-level event
+ || (tableName.equalsIgnoreCase(event.getTableName()))
+ // table level event that matches us
+ ) {
+ return true;
+ }
+ }
+ return false;
+ }
+}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/messaging/event/filters/EventBoundaryFilter.java
----------------------------------------------------------------------
diff --git a/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/messaging/event/filters/EventBoundaryFilter.java b/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/messaging/event/filters/EventBoundaryFilter.java
new file mode 100644
index 0000000..988874d
--- /dev/null
+++ b/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/messaging/event/filters/EventBoundaryFilter.java
@@ -0,0 +1,34 @@
+/*
+ * 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.messaging.event.filters;
+
+import org.apache.hadoop.hive.metastore.api.NotificationEvent;
+
+public class EventBoundaryFilter extends BasicFilter {
+ private final long eventFrom, eventTo;
+
+ public EventBoundaryFilter(final long eventFrom, final long eventTo) {
+ this.eventFrom = eventFrom;
+ this.eventTo = eventTo;
+ }
+
+ @Override
+ boolean shouldAccept(final NotificationEvent event) {
+ return eventFrom <= event.getEventId() && event.getEventId() <= eventTo;
+ }
+}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/messaging/event/filters/MessageFormatFilter.java
----------------------------------------------------------------------
diff --git a/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/messaging/event/filters/MessageFormatFilter.java b/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/messaging/event/filters/MessageFormatFilter.java
new file mode 100644
index 0000000..b0ce3b9
--- /dev/null
+++ b/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/messaging/event/filters/MessageFormatFilter.java
@@ -0,0 +1,36 @@
+/*
+ * 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.messaging.event.filters;
+
+import org.apache.hadoop.hive.metastore.api.NotificationEvent;
+
+public class MessageFormatFilter extends BasicFilter {
+ private final String format;
+
+ public MessageFormatFilter(String format) {
+ this.format = format;
+ }
+
+ @Override
+ boolean shouldAccept(final NotificationEvent event) {
+ if (format == null) {
+ return true; // let's say that passing null in will not do any filtering.
+ }
+ return format.equalsIgnoreCase(event.getMessageFormat());
+ }
+}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/tools/HiveMetaTool.java
----------------------------------------------------------------------
diff --git a/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/tools/HiveMetaTool.java b/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/tools/HiveMetaTool.java
new file mode 100644
index 0000000..f4eacd5
--- /dev/null
+++ b/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/tools/HiveMetaTool.java
@@ -0,0 +1,484 @@
+/*
+ * 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.tools;
+
+import java.net.URI;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.CommandLineParser;
+import org.apache.commons.cli.GnuParser;
+import org.apache.commons.cli.HelpFormatter;
+import org.apache.commons.cli.Option;
+import org.apache.commons.cli.OptionBuilder;
+import org.apache.commons.cli.Options;
+import org.apache.commons.cli.ParseException;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hive.metastore.conf.MetastoreConf;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.metastore.ObjectStore;
+
+/**
+ * This class provides Hive admins a tool to
+ * - execute JDOQL against the metastore using DataNucleus
+ * - perform HA name node upgrade
+ */
+
+public class HiveMetaTool {
+
+ private static final Logger LOG = LoggerFactory.getLogger(HiveMetaTool.class.getName());
+ private final Options cmdLineOptions = new Options();
+ private ObjectStore objStore;
+ private boolean isObjStoreInitialized;
+
+ public HiveMetaTool() {
+ this.isObjStoreInitialized = false;
+ }
+
+ @SuppressWarnings("static-access")
+ private void init() {
+
+ System.out.println("Initializing HiveMetaTool..");
+
+ Option help = new Option("help", "print this message");
+ Option listFSRoot = new Option("listFSRoot", "print the current FS root locations");
+ Option executeJDOQL =
+ OptionBuilder.withArgName("query-string")
+ .hasArgs()
+ .withDescription("execute the given JDOQL query")
+ .create("executeJDOQL");
+
+ /* Ideally we want to specify the different arguments to updateLocation as separate argNames.
+ * However if we did that, HelpFormatter swallows all but the last argument. Note that this is
+ * a know issue with the HelpFormatter class that has not been fixed. We specify all arguments
+ * with a single argName to workaround this HelpFormatter bug.
+ */
+ Option updateFSRootLoc =
+ OptionBuilder
+ .withArgName("new-loc> " + "<old-loc")
+ .hasArgs(2)
+ .withDescription(
+ "Update FS root location in the metastore to new location.Both new-loc and " +
+ "old-loc should be valid URIs with valid host names and schemes." +
+ "When run with the dryRun option changes are displayed but are not " +
+ "persisted. When run with the serdepropKey/tablePropKey option " +
+ "updateLocation looks for the serde-prop-key/table-prop-key that is " +
+ "specified and updates its value if found.")
+ .create("updateLocation");
+ Option dryRun = new Option("dryRun" , "Perform a dry run of updateLocation changes.When " +
+ "run with the dryRun option updateLocation changes are displayed but not persisted. " +
+ "dryRun is valid only with the updateLocation option.");
+ Option serdePropKey =
+ OptionBuilder.withArgName("serde-prop-key")
+ .hasArgs()
+ .withValueSeparator()
+ .withDescription("Specify the key for serde property to be updated. serdePropKey option " +
+ "is valid only with updateLocation option.")
+ .create("serdePropKey");
+ Option tablePropKey =
+ OptionBuilder.withArgName("table-prop-key")
+ .hasArg()
+ .withValueSeparator()
+ .withDescription("Specify the key for table property to be updated. tablePropKey option " +
+ "is valid only with updateLocation option.")
+ .create("tablePropKey");
+
+ cmdLineOptions.addOption(help);
+ cmdLineOptions.addOption(listFSRoot);
+ cmdLineOptions.addOption(executeJDOQL);
+ cmdLineOptions.addOption(updateFSRootLoc);
+ cmdLineOptions.addOption(dryRun);
+ cmdLineOptions.addOption(serdePropKey);
+ cmdLineOptions.addOption(tablePropKey);
+ }
+
+ private void initObjectStore(Configuration conf) {
+ if (!isObjStoreInitialized) {
+ objStore = new ObjectStore();
+ objStore.setConf(conf);
+ isObjStoreInitialized = true;
+ }
+ }
+
+ private void shutdownObjectStore() {
+ if (isObjStoreInitialized) {
+ objStore.shutdown();
+ isObjStoreInitialized = false;
+ }
+ }
+
+ private void listFSRoot() {
+ Configuration conf = MetastoreConf.newMetastoreConf();
+ initObjectStore(conf);
+
+ Set<String> hdfsRoots = objStore.listFSRoots();
+ if (hdfsRoots != null) {
+ System.out.println("Listing FS Roots..");
+ for (String s : hdfsRoots) {
+ System.out.println(s);
+ }
+ } else {
+ System.err.println("Encountered error during listFSRoot - " +
+ "commit of JDO transaction failed");
+ }
+ }
+
+ private void executeJDOQLSelect(String query) {
+ Configuration conf = MetastoreConf.newMetastoreConf();
+ initObjectStore(conf);
+
+ System.out.println("Executing query: " + query);
+ try (ObjectStore.QueryWrapper queryWrapper = new ObjectStore.QueryWrapper()) {
+ Collection<?> result = objStore.executeJDOQLSelect(query, queryWrapper);
+ if (result != null) {
+ Iterator<?> iter = result.iterator();
+ while (iter.hasNext()) {
+ Object o = iter.next();
+ System.out.println(o.toString());
+ }
+ } else {
+ System.err.println("Encountered error during executeJDOQLSelect -" +
+ "commit of JDO transaction failed.");
+ }
+ }
+ }
+
+ private void executeJDOQLUpdate(String query) {
+ Configuration conf = MetastoreConf.newMetastoreConf();
+ initObjectStore(conf);
+
+ System.out.println("Executing query: " + query);
+ long numUpdated = objStore.executeJDOQLUpdate(query);
+ if (numUpdated >= 0) {
+ System.out.println("Number of records updated: " + numUpdated);
+ } else {
+ System.err.println("Encountered error during executeJDOQL -" +
+ "commit of JDO transaction failed.");
+ }
+ }
+
+ private int printUpdateLocations(Map<String, String> updateLocations) {
+ int count = 0;
+ for (String key: updateLocations.keySet()) {
+ String value = updateLocations.get(key);
+ System.out.println("old location: " + key + " new location: " + value);
+ count++;
+ }
+ return count;
+ }
+
+ private void printTblURIUpdateSummary(ObjectStore.UpdateMStorageDescriptorTblURIRetVal retVal,
+ boolean isDryRun) {
+ String tblName = "SDS";
+ String fieldName = "LOCATION";
+
+ if (retVal == null) {
+ System.err.println("Encountered error while executing updateMStorageDescriptorTblURI - " +
+ "commit of JDO transaction failed. Failed to update FSRoot locations in " +
+ fieldName + "field in " + tblName + " table.");
+ } else {
+ Map<String, String> updateLocations = retVal.getUpdateLocations();
+ if (isDryRun) {
+ System.out.println("Dry Run of updateLocation on table " + tblName + "..");
+ } else {
+ System.out.println("Successfully updated the following locations..");
+ }
+ int count = printUpdateLocations(updateLocations);
+ if (isDryRun) {
+ System.out.println("Found " + count + " records in " + tblName + " table to update");
+ } else {
+ System.out.println("Updated " + count + " records in " + tblName + " table");
+ }
+ List<String> badRecords = retVal.getBadRecords();
+ if (badRecords.size() > 0) {
+ System.err.println("Warning: Found records with bad " + fieldName + " in " +
+ tblName + " table.. ");
+ for (String badRecord:badRecords) {
+ System.err.println("bad location URI: " + badRecord);
+ }
+ }
+ int numNullRecords = retVal.getNumNullRecords();
+ if (numNullRecords != 0) {
+ LOG.debug("Number of NULL location URI: " + numNullRecords +
+ ". This can happen for View or Index.");
+ }
+ }
+ }
+
+ private void printDatabaseURIUpdateSummary(ObjectStore.UpdateMDatabaseURIRetVal retVal,
+ boolean isDryRun) {
+ String tblName = "DBS";
+ String fieldName = "LOCATION_URI";
+
+ if (retVal == null) {
+ System.err.println("Encountered error while executing updateMDatabaseURI - " +
+ "commit of JDO transaction failed. Failed to update FSRoot locations in " +
+ fieldName + "field in " + tblName + " table.");
+ } else {
+ Map<String, String> updateLocations = retVal.getUpdateLocations();
+ if (isDryRun) {
+ System.out.println("Dry Run of updateLocation on table " + tblName + "..");
+ } else {
+ System.out.println("Successfully updated the following locations..");
+ }
+ int count = printUpdateLocations(updateLocations);
+ if (isDryRun) {
+ System.out.println("Found " + count + " records in " + tblName + " table to update");
+ } else {
+ System.out.println("Updated " + count + " records in " + tblName + " table");
+ }
+ List<String> badRecords = retVal.getBadRecords();
+ if (badRecords.size() > 0) {
+ System.err.println("Warning: Found records with bad " + fieldName + " in " +
+ tblName + " table.. ");
+ for (String badRecord:badRecords) {
+ System.err.println("bad location URI: " + badRecord);
+ }
+ }
+ }
+ }
+
+ private void printPropURIUpdateSummary(ObjectStore.UpdatePropURIRetVal retVal, String
+ tablePropKey, boolean isDryRun, String tblName, String methodName) {
+ if (retVal == null) {
+ System.err.println("Encountered error while executing " + methodName + " - " +
+ "commit of JDO transaction failed. Failed to update FSRoot locations in " +
+ "value field corresponding to" + tablePropKey + " in " + tblName + " table.");
+ } else {
+ Map<String, String> updateLocations = retVal.getUpdateLocations();
+ if (isDryRun) {
+ System.out.println("Dry Run of updateLocation on table " + tblName + "..");
+ } else {
+ System.out.println("Successfully updated the following locations..");
+ }
+ int count = printUpdateLocations(updateLocations);
+ if (isDryRun) {
+ System.out.println("Found " + count + " records in " + tblName + " table to update");
+ } else {
+ System.out.println("Updated " + count + " records in " + tblName + " table");
+ }
+ List<String> badRecords = retVal.getBadRecords();
+ if (badRecords.size() > 0) {
+ System.err.println("Warning: Found records with bad " + tablePropKey + " key in " +
+ tblName + " table.. ");
+ for (String badRecord:badRecords) {
+ System.err.println("bad location URI: " + badRecord);
+ }
+ }
+ }
+ }
+
+ private void printSerdePropURIUpdateSummary(ObjectStore.UpdateSerdeURIRetVal retVal,
+ String serdePropKey, boolean isDryRun) {
+ String tblName = "SERDE_PARAMS";
+
+ if (retVal == null) {
+ System.err.println("Encountered error while executing updateSerdeURI - " +
+ "commit of JDO transaction failed. Failed to update FSRoot locations in " +
+ "value field corresponding to " + serdePropKey + " in " + tblName + " table.");
+ } else {
+ Map<String, String> updateLocations = retVal.getUpdateLocations();
+ if (isDryRun) {
+ System.out.println("Dry Run of updateLocation on table " + tblName + "..");
+ } else {
+ System.out.println("Successfully updated the following locations..");
+ }
+ int count = printUpdateLocations(updateLocations);
+ if (isDryRun) {
+ System.out.println("Found " + count + " records in " + tblName + " table to update");
+ } else {
+ System.out.println("Updated " + count + " records in " + tblName + " table");
+ }
+ List<String> badRecords = retVal.getBadRecords();
+ if (badRecords.size() > 0) {
+ System.err.println("Warning: Found records with bad " + serdePropKey + " key in " +
+ tblName + " table.. ");
+ for (String badRecord:badRecords) {
+ System.err.println("bad location URI: " + badRecord);
+ }
+ }
+ }
+ }
+
+ public void updateFSRootLocation(URI oldURI, URI newURI, String serdePropKey, String
+ tablePropKey, boolean isDryRun) {
+ Configuration conf = MetastoreConf.newMetastoreConf();
+ initObjectStore(conf);
+
+ System.out.println("Looking for LOCATION_URI field in DBS table to update..");
+ ObjectStore.UpdateMDatabaseURIRetVal updateMDBURIRetVal = objStore.updateMDatabaseURI(oldURI,
+ newURI, isDryRun);
+ printDatabaseURIUpdateSummary(updateMDBURIRetVal, isDryRun);
+
+ System.out.println("Looking for LOCATION field in SDS table to update..");
+ ObjectStore.UpdateMStorageDescriptorTblURIRetVal updateTblURIRetVal =
+ objStore.updateMStorageDescriptorTblURI(oldURI, newURI, isDryRun);
+ printTblURIUpdateSummary(updateTblURIRetVal, isDryRun);
+
+ if (tablePropKey != null) {
+ System.out.println("Looking for value of " + tablePropKey + " key in TABLE_PARAMS table " +
+ "to update..");
+ ObjectStore.UpdatePropURIRetVal updateTblPropURIRetVal =
+ objStore.updateTblPropURI(oldURI, newURI,
+ tablePropKey, isDryRun);
+ printPropURIUpdateSummary(updateTblPropURIRetVal, tablePropKey, isDryRun, "TABLE_PARAMS",
+ "updateTblPropURI");
+
+ System.out.println("Looking for value of " + tablePropKey + " key in SD_PARAMS table " +
+ "to update..");
+ ObjectStore.UpdatePropURIRetVal updatePropURIRetVal = objStore
+ .updateMStorageDescriptorTblPropURI(oldURI, newURI, tablePropKey, isDryRun);
+ printPropURIUpdateSummary(updatePropURIRetVal, tablePropKey, isDryRun, "SD_PARAMS",
+ "updateMStorageDescriptorTblPropURI");
+ }
+
+ if (serdePropKey != null) {
+ System.out.println("Looking for value of " + serdePropKey + " key in SERDE_PARAMS table " +
+ "to update..");
+ ObjectStore.UpdateSerdeURIRetVal updateSerdeURIretVal = objStore.updateSerdeURI(oldURI,
+ newURI, serdePropKey, isDryRun);
+ printSerdePropURIUpdateSummary(updateSerdeURIretVal, serdePropKey, isDryRun);
+ }
+ }
+
+ private static void printAndExit(HiveMetaTool metaTool) {
+ HelpFormatter formatter = new HelpFormatter();
+ formatter.printHelp("metatool", metaTool.cmdLineOptions);
+ System.exit(1);
+ }
+
+ public static void main(String[] args) {
+ HiveMetaTool metaTool = new HiveMetaTool();
+ metaTool.init();
+ CommandLineParser parser = new GnuParser();
+ CommandLine line = null;
+
+ try {
+ try {
+ line = parser.parse(metaTool.cmdLineOptions, args);
+ } catch (ParseException e) {
+ System.err.println("HiveMetaTool:Parsing failed. Reason: " + e.getLocalizedMessage());
+ printAndExit(metaTool);
+ }
+
+ if (line.hasOption("help")) {
+ HelpFormatter formatter = new HelpFormatter();
+ formatter.printHelp("metatool", metaTool.cmdLineOptions);
+ } else if (line.hasOption("listFSRoot")) {
+ if (line.hasOption("dryRun")) {
+ System.err.println("HiveMetaTool: dryRun is not valid with listFSRoot");
+ printAndExit(metaTool);
+ } else if (line.hasOption("serdePropKey")) {
+ System.err.println("HiveMetaTool: serdePropKey is not valid with listFSRoot");
+ printAndExit(metaTool);
+ } else if (line.hasOption("tablePropKey")) {
+ System.err.println("HiveMetaTool: tablePropKey is not valid with listFSRoot");
+ printAndExit(metaTool);
+ }
+ metaTool.listFSRoot();
+ } else if (line.hasOption("executeJDOQL")) {
+ String query = line.getOptionValue("executeJDOQL");
+ if (line.hasOption("dryRun")) {
+ System.err.println("HiveMetaTool: dryRun is not valid with executeJDOQL");
+ printAndExit(metaTool);
+ } else if (line.hasOption("serdePropKey")) {
+ System.err.println("HiveMetaTool: serdePropKey is not valid with executeJDOQL");
+ printAndExit(metaTool);
+ } else if (line.hasOption("tablePropKey")) {
+ System.err.println("HiveMetaTool: tablePropKey is not valid with executeJDOQL");
+ printAndExit(metaTool);
+ }
+ if (query.toLowerCase().trim().startsWith("select")) {
+ metaTool.executeJDOQLSelect(query);
+ } else if (query.toLowerCase().trim().startsWith("update")) {
+ metaTool.executeJDOQLUpdate(query);
+ } else {
+ System.err.println("HiveMetaTool:Unsupported statement type");
+ printAndExit(metaTool);
+ }
+ } else if (line.hasOption("updateLocation")) {
+ String[] loc = line.getOptionValues("updateLocation");
+ boolean isDryRun = false;
+ String serdepropKey = null;
+ String tablePropKey = null;
+
+ if (loc.length != 2 && loc.length != 3) {
+ System.err.println("HiveMetaTool:updateLocation takes in 2 required and 1 " +
+ "optional arguments but " +
+ "was passed " + loc.length + " arguments");
+ printAndExit(metaTool);
+ }
+
+ Path newPath = new Path(loc[0]);
+ Path oldPath = new Path(loc[1]);
+
+ URI oldURI = oldPath.toUri();
+ URI newURI = newPath.toUri();
+
+ if (line.hasOption("dryRun")) {
+ isDryRun = true;
+ }
+
+ if (line.hasOption("serdePropKey")) {
+ serdepropKey = line.getOptionValue("serdePropKey");
+ }
+
+ if (line.hasOption("tablePropKey")) {
+ tablePropKey = line.getOptionValue("tablePropKey");
+ }
+
+ /*
+ * validate input - Both new and old URI should contain valid host names and valid schemes.
+ * port is optional in both the URIs since HDFS HA NN URI doesn't have a port.
+ */
+ if (oldURI.getHost() == null || newURI.getHost() == null) {
+ System.err.println("HiveMetaTool:A valid host is required in both old-loc and new-loc");
+ } else if (oldURI.getScheme() == null || newURI.getScheme() == null) {
+ System.err.println("HiveMetaTool:A valid scheme is required in both old-loc and new-loc");
+ } else {
+ metaTool.updateFSRootLocation(oldURI, newURI, serdepropKey, tablePropKey, isDryRun);
+ }
+ } else {
+ if (line.hasOption("dryRun")) {
+ System.err.println("HiveMetaTool: dryRun is not a valid standalone option");
+ } else if (line.hasOption("serdePropKey")) {
+ System.err.println("HiveMetaTool: serdePropKey is not a valid standalone option");
+ } else if (line.hasOption("tablePropKey")) {
+ System.err.println("HiveMetaTool: tablePropKey is not a valid standalone option");
+ printAndExit(metaTool);
+ } else {
+ System.err.print("HiveMetaTool:Parsing failed. Reason: Invalid arguments: " );
+ for (String s : line.getArgs()) {
+ System.err.print(s + " ");
+ }
+ System.err.println();
+ }
+ printAndExit(metaTool);
+ }
+ } finally {
+ metaTool.shutdownObjectStore();
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/utils/FileUtils.java
----------------------------------------------------------------------
diff --git a/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/utils/FileUtils.java b/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/utils/FileUtils.java
index c9deccc..f6d7b5b 100644
--- a/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/utils/FileUtils.java
+++ b/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/utils/FileUtils.java
@@ -53,6 +53,16 @@ public class FileUtils {
return !name.startsWith("_") && !name.startsWith(".");
}
};
+ /**
+ * Filter that filters out hidden files
+ */
+ private static final PathFilter hiddenFileFilter = new PathFilter() {
+ @Override
+ public boolean accept(Path p) {
+ String name = p.getName();
+ return !name.startsWith("_") && !name.startsWith(".");
+ }
+ };
/**
* Move a particular file or directory to the trash.
@@ -412,4 +422,23 @@ public class FileUtils {
throw new MetaException("Unable to : " + path);
}
}
+
+ /**
+ * Utility method that determines if a specified directory already has
+ * contents (non-hidden files) or not - useful to determine if an
+ * immutable table already has contents, for example.
+ *
+ * @param path
+ * @throws IOException
+ */
+ public static boolean isDirEmpty(FileSystem fs, Path path) throws IOException {
+
+ if (fs.exists(path)) {
+ FileStatus[] status = fs.globStatus(new Path(path, "*"), hiddenFileFilter);
+ if (status.length > 0) {
+ return false;
+ }
+ }
+ return true;
+ }
}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/utils/MetaStoreUtils.java
----------------------------------------------------------------------
diff --git a/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/utils/MetaStoreUtils.java b/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/utils/MetaStoreUtils.java
index bf25e50..c711aa8 100644
--- a/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/utils/MetaStoreUtils.java
+++ b/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/utils/MetaStoreUtils.java
@@ -30,6 +30,7 @@ import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.common.StatsSetupConst;
import org.apache.hadoop.hive.metastore.ColumnType;
+import org.apache.hadoop.hive.metastore.HiveMetaStore;
import org.apache.hadoop.hive.metastore.TableType;
import org.apache.hadoop.hive.metastore.Warehouse;
import org.apache.hadoop.hive.metastore.api.ColumnStatistics;
@@ -63,9 +64,13 @@ import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.File;
+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.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.Charset;
@@ -80,6 +85,7 @@ import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
+import java.util.Properties;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
@@ -297,8 +303,8 @@ public class MetaStoreUtils {
}
}
- public static String getPartitionValWithInvalidCharacter(List<String> partVals,
- Pattern partitionValidationPattern) {
+ private static String getPartitionValWithInvalidCharacter(List<String> partVals,
+ Pattern partitionValidationPattern) {
if (partitionValidationPattern == null) {
return null;
}
@@ -495,8 +501,9 @@ public class MetaStoreUtils {
}
// check if stats need to be (re)calculated
- public static boolean requireCalStats(Configuration hiveConf, Partition oldPart,
- Partition newPart, Table tbl, EnvironmentContext environmentContext) {
+ public static boolean requireCalStats(Partition oldPart,
+ Partition newPart, Table tbl,
+ EnvironmentContext environmentContext) {
if (environmentContext != null
&& environmentContext.isSetProperties()
@@ -1046,4 +1053,486 @@ public class MetaStoreUtils {
ipAddress = (ipAddress == null) ? StringUtils.EMPTY : ipAddress;
return machineList.includes(ipAddress);
}
+
+ /**
+ * Convert FieldSchemas to Thrift DDL.
+ */
+ public static String getDDLFromFieldSchema(String structName,
+ List<FieldSchema> fieldSchemas) {
+ StringBuilder ddl = new StringBuilder();
+ ddl.append("struct ");
+ ddl.append(structName);
+ ddl.append(" { ");
+ boolean first = true;
+ for (FieldSchema col : fieldSchemas) {
+ if (first) {
+ first = false;
+ } else {
+ ddl.append(", ");
+ }
+ ddl.append(ColumnType.typeToThriftType(col.getType()));
+ ddl.append(' ');
+ ddl.append(col.getName());
+ }
+ ddl.append("}");
+
+ LOG.trace("DDL: {}", ddl);
+ return ddl.toString();
+ }
+
+ public static Properties getTableMetadata(
+ org.apache.hadoop.hive.metastore.api.Table table) {
+ return MetaStoreUtils.getSchema(table.getSd(), table.getSd(), table
+ .getParameters(), table.getDbName(), table.getTableName(), table.getPartitionKeys());
+ }
+
+ public static Properties getPartitionMetadata(
+ org.apache.hadoop.hive.metastore.api.Partition partition,
+ org.apache.hadoop.hive.metastore.api.Table table) {
+ return MetaStoreUtils
+ .getSchema(partition.getSd(), partition.getSd(), partition
+ .getParameters(), table.getDbName(), table.getTableName(),
+ table.getPartitionKeys());
+ }
+
+ public static Properties getSchema(
+ org.apache.hadoop.hive.metastore.api.Partition part,
+ org.apache.hadoop.hive.metastore.api.Table table) {
+ return MetaStoreUtils.getSchema(part.getSd(), table.getSd(), table
+ .getParameters(), table.getDbName(), table.getTableName(), table.getPartitionKeys());
+ }
+
+ /**
+ * Get partition level schema from table level schema.
+ * This function will use the same column names, column types and partition keys for
+ * each partition Properties. Their values are copied from the table Properties. This
+ * is mainly to save CPU and memory. CPU is saved because the first time the
+ * StorageDescriptor column names are accessed, JDO needs to execute a SQL query to
+ * retrieve the data. If we know the data will be the same as the table level schema
+ * and they are immutable, we should just reuse the table level schema objects.
+ *
+ * @param sd The Partition level Storage Descriptor.
+ * @param parameters partition level parameters
+ * @param tblSchema The table level schema from which this partition should be copied.
+ * @return the properties
+ */
+ public static Properties getPartSchemaFromTableSchema(
+ StorageDescriptor sd,
+ Map<String, String> parameters,
+ Properties tblSchema) {
+
+ // Inherent most properties from table level schema and overwrite some properties
+ // in the following code.
+ // This is mainly for saving CPU and memory to reuse the column names, types and
+ // partition columns in the table level schema.
+ Properties schema = (Properties) tblSchema.clone();
+
+ // InputFormat
+ String inputFormat = sd.getInputFormat();
+ if (inputFormat == null || inputFormat.length() == 0) {
+ String tblInput =
+ schema.getProperty(org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.FILE_INPUT_FORMAT);
+ if (tblInput == null) {
+ inputFormat = org.apache.hadoop.mapred.SequenceFileInputFormat.class.getName();
+ } else {
+ inputFormat = tblInput;
+ }
+ }
+ schema.setProperty(org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.FILE_INPUT_FORMAT,
+ inputFormat);
+
+ // OutputFormat
+ String outputFormat = sd.getOutputFormat();
+ if (outputFormat == null || outputFormat.length() == 0) {
+ String tblOutput =
+ schema.getProperty(org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.FILE_OUTPUT_FORMAT);
+ if (tblOutput == null) {
+ outputFormat = org.apache.hadoop.mapred.SequenceFileOutputFormat.class.getName();
+ } else {
+ outputFormat = tblOutput;
+ }
+ }
+ schema.setProperty(org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.FILE_OUTPUT_FORMAT,
+ outputFormat);
+
+ // Location
+ if (sd.getLocation() != null) {
+ schema.setProperty(org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.META_TABLE_LOCATION,
+ sd.getLocation());
+ }
+
+ // Bucket count
+ schema.setProperty(org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.BUCKET_COUNT,
+ Integer.toString(sd.getNumBuckets()));
+
+ if (sd.getBucketCols() != null && sd.getBucketCols().size() > 0) {
+ schema.setProperty(org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.BUCKET_FIELD_NAME,
+ sd.getBucketCols().get(0));
+ }
+
+ // SerdeInfo
+ if (sd.getSerdeInfo() != null) {
+
+ // We should not update the following 3 values if SerDeInfo contains these.
+ // This is to keep backward compatible with getSchema(), where these 3 keys
+ // are updated after SerDeInfo properties got copied.
+ String cols = org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.META_TABLE_COLUMNS;
+ String colTypes = org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.META_TABLE_COLUMN_TYPES;
+ String parts = org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.META_TABLE_PARTITION_COLUMNS;
+
+ for (Map.Entry<String,String> param : sd.getSerdeInfo().getParameters().entrySet()) {
+ String key = param.getKey();
+ if (schema.get(key) != null &&
+ (key.equals(cols) || key.equals(colTypes) || key.equals(parts))) {
+ continue;
+ }
+ schema.put(key, (param.getValue() != null) ? param.getValue() : StringUtils.EMPTY);
+ }
+
+ if (sd.getSerdeInfo().getSerializationLib() != null) {
+ schema.setProperty(ColumnType.SERIALIZATION_LIB, sd.getSerdeInfo().getSerializationLib());
+ }
+ }
+
+ // skipping columns since partition level field schemas are the same as table level's
+ // skipping partition keys since it is the same as table level partition keys
+
+ if (parameters != null) {
+ for (Map.Entry<String, String> e : parameters.entrySet()) {
+ schema.setProperty(e.getKey(), e.getValue());
+ }
+ }
+
+ return schema;
+ }
+
+ private static Properties addCols(Properties schema, List<FieldSchema> cols) {
+
+ StringBuilder colNameBuf = new StringBuilder();
+ StringBuilder colTypeBuf = new StringBuilder();
+ StringBuilder colComment = new StringBuilder();
+
+ boolean first = true;
+ String columnNameDelimiter = getColumnNameDelimiter(cols);
+ for (FieldSchema col : cols) {
+ if (!first) {
+ colNameBuf.append(columnNameDelimiter);
+ colTypeBuf.append(":");
+ colComment.append('\0');
+ }
+ colNameBuf.append(col.getName());
+ colTypeBuf.append(col.getType());
+ colComment.append((null != col.getComment()) ? col.getComment() : StringUtils.EMPTY);
+ first = false;
+ }
+ schema.setProperty(
+ org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.META_TABLE_COLUMNS,
+ colNameBuf.toString());
+ schema.setProperty(ColumnType.COLUMN_NAME_DELIMITER, columnNameDelimiter);
+ String colTypes = colTypeBuf.toString();
+ schema.setProperty(
+ org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.META_TABLE_COLUMN_TYPES,
+ colTypes);
+ schema.setProperty("columns.comments", colComment.toString());
+
+ return schema;
+
+ }
+
+ public static Properties getSchemaWithoutCols(StorageDescriptor sd,
+ Map<String, String> parameters, String databaseName, String tableName,
+ List<FieldSchema> partitionKeys) {
+ Properties schema = new Properties();
+ String inputFormat = sd.getInputFormat();
+ if (inputFormat == null || inputFormat.length() == 0) {
+ inputFormat = org.apache.hadoop.mapred.SequenceFileInputFormat.class
+ .getName();
+ }
+ schema.setProperty(
+ org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.FILE_INPUT_FORMAT,
+ inputFormat);
+ String outputFormat = sd.getOutputFormat();
+ if (outputFormat == null || outputFormat.length() == 0) {
+ outputFormat = org.apache.hadoop.mapred.SequenceFileOutputFormat.class
+ .getName();
+ }
+ schema.setProperty(
+ org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.FILE_OUTPUT_FORMAT,
+ outputFormat);
+
+ schema.setProperty(
+ org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.META_TABLE_NAME,
+ databaseName + "." + tableName);
+
+ if (sd.getLocation() != null) {
+ schema.setProperty(
+ org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.META_TABLE_LOCATION,
+ sd.getLocation());
+ }
+ schema.setProperty(
+ org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.BUCKET_COUNT, Integer
+ .toString(sd.getNumBuckets()));
+ if (sd.getBucketCols() != null && sd.getBucketCols().size() > 0) {
+ schema.setProperty(
+ org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.BUCKET_FIELD_NAME, sd
+ .getBucketCols().get(0));
+ }
+ if (sd.getSerdeInfo() != null) {
+ for (Map.Entry<String,String> param : sd.getSerdeInfo().getParameters().entrySet()) {
+ schema.put(param.getKey(), (param.getValue() != null) ? param.getValue() : StringUtils.EMPTY);
+ }
+
+ if (sd.getSerdeInfo().getSerializationLib() != null) {
+ schema.setProperty(ColumnType.SERIALIZATION_LIB, sd .getSerdeInfo().getSerializationLib());
+ }
+ }
+
+ if (sd.getCols() != null) {
+ schema.setProperty(ColumnType.SERIALIZATION_DDL, getDDLFromFieldSchema(tableName, sd.getCols()));
+ }
+
+ String partString = StringUtils.EMPTY;
+ String partStringSep = StringUtils.EMPTY;
+ String partTypesString = StringUtils.EMPTY;
+ String partTypesStringSep = StringUtils.EMPTY;
+ for (FieldSchema partKey : partitionKeys) {
+ partString = partString.concat(partStringSep);
+ partString = partString.concat(partKey.getName());
+ partTypesString = partTypesString.concat(partTypesStringSep);
+ partTypesString = partTypesString.concat(partKey.getType());
+ if (partStringSep.length() == 0) {
+ partStringSep = "/";
+ partTypesStringSep = ":";
+ }
+ }
+ if (partString.length() > 0) {
+ schema
+ .setProperty(
+ org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.META_TABLE_PARTITION_COLUMNS,
+ partString);
+ schema
+ .setProperty(
+ org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.META_TABLE_PARTITION_COLUMN_TYPES,
+ partTypesString);
+ }
+
+ if (parameters != null) {
+ for (Map.Entry<String, String> e : parameters.entrySet()) {
+ // add non-null parameters to the schema
+ if ( e.getValue() != null) {
+ schema.setProperty(e.getKey(), e.getValue());
+ }
+ }
+ }
+
+ return schema;
+ }
+
+ public static Properties getSchema(
+ org.apache.hadoop.hive.metastore.api.StorageDescriptor sd,
+ org.apache.hadoop.hive.metastore.api.StorageDescriptor tblsd,
+ Map<String, String> parameters, String databaseName, String tableName,
+ List<FieldSchema> partitionKeys) {
+
+ return addCols(getSchemaWithoutCols(sd, parameters, databaseName, tableName, partitionKeys), tblsd.getCols());
+ }
+
+ public static String getColumnNameDelimiter(List<FieldSchema> fieldSchemas) {
+ // we first take a look if any fieldSchemas contain COMMA
+ for (int i = 0; i < fieldSchemas.size(); i++) {
+ if (fieldSchemas.get(i).getName().contains(",")) {
+ return String.valueOf(ColumnType.COLUMN_COMMENTS_DELIMITER);
+ }
+ }
+ return String.valueOf(',');
+ }
+
+ /**
+ * Convert FieldSchemas to columnNames.
+ */
+ public static String getColumnNamesFromFieldSchema(List<FieldSchema> fieldSchemas) {
+ String delimiter = getColumnNameDelimiter(fieldSchemas);
+ StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < fieldSchemas.size(); i++) {
+ if (i > 0) {
+ sb.append(delimiter);
+ }
+ sb.append(fieldSchemas.get(i).getName());
+ }
+ return sb.toString();
+ }
+
+ /**
+ * Convert FieldSchemas to columnTypes.
+ */
+ public static String getColumnTypesFromFieldSchema(
+ List<FieldSchema> fieldSchemas) {
+ StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < fieldSchemas.size(); i++) {
+ if (i > 0) {
+ sb.append(",");
+ }
+ sb.append(fieldSchemas.get(i).getType());
+ }
+ return sb.toString();
+ }
+
+ public static String getColumnCommentsFromFieldSchema(List<FieldSchema> fieldSchemas) {
+ StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < fieldSchemas.size(); i++) {
+ if (i > 0) {
+ sb.append(ColumnType.COLUMN_COMMENTS_DELIMITER);
+ }
+ sb.append(fieldSchemas.get(i).getComment());
+ }
+ return sb.toString();
+ }
+
+ 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 + "__";
+ }
+
+ public static boolean isMaterializedViewTable(Table table) {
+ if (table == null) {
+ return false;
+ }
+ return TableType.MATERIALIZED_VIEW.toString().equals(table.getTableType());
+ }
+
+ public static List<String> getColumnNames(List<FieldSchema> schema) {
+ List<String> cols = new ArrayList<>(schema.size());
+ for (FieldSchema fs : schema) {
+ cols.add(fs.getName());
+ }
+ return cols;
+ }
}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/utils/SecurityUtils.java
----------------------------------------------------------------------
diff --git a/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/utils/SecurityUtils.java b/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/utils/SecurityUtils.java
index 41a18cb..0b0cfbd 100644
--- a/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/utils/SecurityUtils.java
+++ b/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/utils/SecurityUtils.java
@@ -36,11 +36,15 @@ import org.apache.zookeeper.client.ZooKeeperSaslClient;
import javax.security.auth.login.AppConfigurationEntry;
import org.apache.thrift.transport.TSSLTransportFactory;
import org.apache.thrift.transport.TServerSocket;
+import org.apache.thrift.transport.TSocket;
+import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLServerSocket;
+import javax.net.ssl.SSLSocket;
import javax.security.auth.login.LoginException;
import javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag;
@@ -284,4 +288,26 @@ public class SecurityUtils {
}
return thriftServerSocket;
}
+
+ public static TTransport getSSLSocket(String host, int port, int loginTimeout,
+ String trustStorePath, String trustStorePassWord) throws TTransportException {
+ TSSLTransportFactory.TSSLTransportParameters params =
+ new TSSLTransportFactory.TSSLTransportParameters();
+ params.setTrustStore(trustStorePath, trustStorePassWord);
+ params.requireClientAuth(true);
+ // The underlying SSLSocket object is bound to host:port with the given SO_TIMEOUT and
+ // SSLContext created with the given params
+ TSocket tSSLSocket = TSSLTransportFactory.getClientSocket(host, port, loginTimeout, params);
+ return getSSLSocketWithHttps(tSSLSocket);
+ }
+
+ // Using endpoint identification algorithm as HTTPS enables us to do
+ // CNAMEs/subjectAltName verification
+ private static TSocket getSSLSocketWithHttps(TSocket tSSLSocket) throws TTransportException {
+ SSLSocket sslSocket = (SSLSocket) tSSLSocket.getSocket();
+ SSLParameters sslParams = sslSocket.getSSLParameters();
+ sslParams.setEndpointIdentificationAlgorithm("HTTPS");
+ sslSocket.setSSLParameters(sslParams);
+ return new TSocket(sslSocket);
+ }
}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/AlternateFailurePreListener.java
----------------------------------------------------------------------
diff --git a/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/AlternateFailurePreListener.java b/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/AlternateFailurePreListener.java
new file mode 100644
index 0000000..bde29a1
--- /dev/null
+++ b/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/AlternateFailurePreListener.java
@@ -0,0 +1,62 @@
+/*
+ * 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 javax.jdo.JDOException;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hive.metastore.api.InvalidOperationException;
+import org.apache.hadoop.hive.metastore.api.MetaException;
+import org.apache.hadoop.hive.metastore.api.NoSuchObjectException;
+import org.apache.hadoop.hive.metastore.events.PreEventContext;
+
+/**
+ *
+ * AlternateFailurePreListener.
+ *
+ * An implementation of MetaStorePreEventListener which fails every other time it's invoked,
+ * starting with the first time.
+ *
+ * It also records and makes available the number of times it's been invoked.
+ */
+public class AlternateFailurePreListener extends MetaStorePreEventListener {
+
+ private static int callCount = 0;
+ private static boolean throwException = true;
+
+ public AlternateFailurePreListener(Configuration config) {
+ super(config);
+ }
+
+ @Override
+ public void onEvent(PreEventContext context) throws MetaException, NoSuchObjectException,
+ InvalidOperationException {
+
+ callCount++;
+ if (throwException) {
+ throwException = false;
+ throw new JDOException();
+ }
+
+ throwException = true;
+ }
+
+ public static int getCallCount() {
+ return callCount;
+ }
+}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/DummyEndFunctionListener.java
----------------------------------------------------------------------
diff --git a/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/DummyEndFunctionListener.java b/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/DummyEndFunctionListener.java
new file mode 100644
index 0000000..ca1f10b
--- /dev/null
+++ b/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/DummyEndFunctionListener.java
@@ -0,0 +1,47 @@
+/*
+ * 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 java.util.ArrayList;
+import java.util.List;
+
+import org.apache.hadoop.conf.Configuration;
+
+
+/** A dummy implementation for
+ * {@link org.apache.hadoop.hive.metastore.MetaStoreEndFunctionListener}
+ * for testing purposes.
+ */
+public class DummyEndFunctionListener extends MetaStoreEndFunctionListener{
+
+ public static final List<String> funcNameList = new ArrayList<>();
+ public static final List<MetaStoreEndFunctionContext> contextList =
+ new ArrayList<>();
+
+ public DummyEndFunctionListener(Configuration config) {
+ super(config);
+ }
+
+ @Override
+ public void onEndFunction(String functionName, MetaStoreEndFunctionContext context) {
+ funcNameList.add(functionName);
+ contextList.add(context);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/DummyListener.java
----------------------------------------------------------------------
diff --git a/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/DummyListener.java b/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/DummyListener.java
new file mode 100644
index 0000000..baecd12
--- /dev/null
+++ b/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/DummyListener.java
@@ -0,0 +1,144 @@
+/*
+ * 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 java.util.ArrayList;
+import java.util.List;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hive.metastore.api.MetaException;
+import org.apache.hadoop.hive.metastore.events.AddIndexEvent;
+import org.apache.hadoop.hive.metastore.events.AddPartitionEvent;
+import org.apache.hadoop.hive.metastore.events.AlterIndexEvent;
+import org.apache.hadoop.hive.metastore.events.AlterPartitionEvent;
+import org.apache.hadoop.hive.metastore.events.AlterTableEvent;
+import org.apache.hadoop.hive.metastore.events.ConfigChangeEvent;
+import org.apache.hadoop.hive.metastore.events.CreateDatabaseEvent;
+import org.apache.hadoop.hive.metastore.events.CreateFunctionEvent;
+import org.apache.hadoop.hive.metastore.events.CreateTableEvent;
+import org.apache.hadoop.hive.metastore.events.DropDatabaseEvent;
+import org.apache.hadoop.hive.metastore.events.DropFunctionEvent;
+import org.apache.hadoop.hive.metastore.events.DropIndexEvent;
+import org.apache.hadoop.hive.metastore.events.DropPartitionEvent;
+import org.apache.hadoop.hive.metastore.events.DropTableEvent;
+import org.apache.hadoop.hive.metastore.events.ListenerEvent;
+import org.apache.hadoop.hive.metastore.events.LoadPartitionDoneEvent;
+
+/** A dummy implementation for
+ * {@link org.apache.hadoop.hive.metastore.MetaStoreEventListener}
+ * for testing purposes.
+ */
+public class DummyListener extends MetaStoreEventListener{
+
+ public static final List<ListenerEvent> notifyList = new ArrayList<>();
+
+ /**
+ * @return The last event received, or null if no event was received.
+ */
+ public static ListenerEvent getLastEvent() {
+ if (notifyList.isEmpty()) {
+ return null;
+ } else {
+ return notifyList.get(notifyList.size() - 1);
+ }
+ }
+
+ public DummyListener(Configuration config) {
+ super(config);
+ }
+
+ @Override
+ public void onConfigChange(ConfigChangeEvent configChange) {
+ addEvent(configChange);
+ }
+
+ @Override
+ public void onAddPartition(AddPartitionEvent partition) throws MetaException {
+ addEvent(partition);
+ }
+
+ @Override
+ public void onCreateDatabase(CreateDatabaseEvent db) throws MetaException {
+ addEvent(db);
+ }
+
+ @Override
+ public void onCreateTable(CreateTableEvent table) throws MetaException {
+ addEvent(table);
+ }
+
+ @Override
+ public void onDropDatabase(DropDatabaseEvent db) throws MetaException {
+ addEvent(db);
+ }
+
+ @Override
+ public void onDropPartition(DropPartitionEvent partition) throws MetaException {
+ addEvent(partition);
+ }
+
+ @Override
+ public void onDropTable(DropTableEvent table) throws MetaException {
+ addEvent(table);
+ }
+
+ @Override
+ public void onAlterTable(AlterTableEvent event) throws MetaException {
+ addEvent(event);
+ }
+
+ @Override
+ public void onAlterPartition(AlterPartitionEvent event) throws MetaException {
+ addEvent(event);
+ }
+
+ @Override
+ public void onLoadPartitionDone(LoadPartitionDoneEvent partEvent) throws MetaException {
+ addEvent(partEvent);
+ }
+
+ @Override
+ public void onAddIndex(AddIndexEvent indexEvent) throws MetaException {
+ addEvent(indexEvent);
+ }
+
+ @Override
+ public void onDropIndex(DropIndexEvent indexEvent) throws MetaException {
+ addEvent(indexEvent);
+ }
+
+ @Override
+ public void onAlterIndex(AlterIndexEvent indexEvent) throws MetaException {
+ addEvent(indexEvent);
+ }
+
+ @Override
+ public void onCreateFunction (CreateFunctionEvent fnEvent) throws MetaException {
+ addEvent(fnEvent);
+ }
+
+ @Override
+ public void onDropFunction (DropFunctionEvent fnEvent) throws MetaException {
+ addEvent(fnEvent);
+ }
+
+ private void addEvent(ListenerEvent event) {
+ notifyList.add(event);
+ }
+}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/DummyMetaStoreInitListener.java
----------------------------------------------------------------------
diff --git a/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/DummyMetaStoreInitListener.java b/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/DummyMetaStoreInitListener.java
new file mode 100644
index 0000000..0f2a3c7
--- /dev/null
+++ b/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/DummyMetaStoreInitListener.java
@@ -0,0 +1,39 @@
+/*
+ * 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 org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hive.metastore.api.MetaException;
+
+/*
+ * An implementation of MetaStoreInitListener to verify onInit is called when
+ * HMSHandler is initialized
+ */
+public class DummyMetaStoreInitListener extends MetaStoreInitListener{
+
+ public static boolean wasCalled = false;
+ public DummyMetaStoreInitListener(Configuration config) {
+ super(config);
+ }
+
+ @Override
+ public void onInit(MetaStoreInitContext context) throws MetaException {
+ wasCalled = true;
+ }
+}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/DummyPreListener.java
----------------------------------------------------------------------
diff --git a/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/DummyPreListener.java b/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/DummyPreListener.java
new file mode 100644
index 0000000..0a68bac
--- /dev/null
+++ b/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/DummyPreListener.java
@@ -0,0 +1,49 @@
+/*
+ * 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 java.util.ArrayList;
+import java.util.List;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hive.metastore.api.InvalidOperationException;
+import org.apache.hadoop.hive.metastore.api.MetaException;
+import org.apache.hadoop.hive.metastore.api.NoSuchObjectException;
+import org.apache.hadoop.hive.metastore.events.PreEventContext;
+
+/**
+ *
+ * DummyPreListener.
+ *
+ * An implementation of MetaStorePreEventListener which stores the Events it's seen in a list.
+ */
+public class DummyPreListener extends MetaStorePreEventListener {
+
+ public static final List<PreEventContext> notifyList = new ArrayList<>();
+
+ public DummyPreListener(Configuration config) {
+ super(config);
+ }
+
+ @Override
+ public void onEvent(PreEventContext context) throws MetaException, NoSuchObjectException,
+ InvalidOperationException {
+ notifyList.add(context);
+ }
+
+}
[08/12] hive git commit: HIVE-17980 Moved HiveMetaStoreClient plus a
few remaining classes.
Posted by ga...@apache.org.
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/metastore/src/java/org/apache/hadoop/hive/metastore/tools/HiveMetaTool.java
----------------------------------------------------------------------
diff --git a/metastore/src/java/org/apache/hadoop/hive/metastore/tools/HiveMetaTool.java b/metastore/src/java/org/apache/hadoop/hive/metastore/tools/HiveMetaTool.java
deleted file mode 100644
index 22e246f..0000000
--- a/metastore/src/java/org/apache/hadoop/hive/metastore/tools/HiveMetaTool.java
+++ /dev/null
@@ -1,487 +0,0 @@
-/**
- * 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.tools;
-
-import java.net.URI;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.apache.commons.cli.CommandLine;
-import org.apache.commons.cli.CommandLineParser;
-import org.apache.commons.cli.GnuParser;
-import org.apache.commons.cli.HelpFormatter;
-import org.apache.commons.cli.Option;
-import org.apache.commons.cli.OptionBuilder;
-import org.apache.commons.cli.Options;
-import org.apache.commons.cli.ParseException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.hadoop.fs.Path;
-import org.apache.hadoop.hive.conf.HiveConf;
-import org.apache.hadoop.hive.metastore.ObjectStore;
-
-/**
- * This class provides Hive admins a tool to
- * - execute JDOQL against the metastore using DataNucleus
- * - perform HA name node upgrade
- */
-
-public class HiveMetaTool {
-
- private static final Logger LOG = LoggerFactory.getLogger(HiveMetaTool.class.getName());
- private final Options cmdLineOptions = new Options();
- private ObjectStore objStore;
- private boolean isObjStoreInitialized;
-
- public HiveMetaTool() {
- this.isObjStoreInitialized = false;
- }
-
- @SuppressWarnings("static-access")
- private void init() {
-
- System.out.println("Initializing HiveMetaTool..");
-
- Option help = new Option("help", "print this message");
- Option listFSRoot = new Option("listFSRoot", "print the current FS root locations");
- Option executeJDOQL =
- OptionBuilder.withArgName("query-string")
- .hasArgs()
- .withDescription("execute the given JDOQL query")
- .create("executeJDOQL");
-
- /* Ideally we want to specify the different arguments to updateLocation as separate argNames.
- * However if we did that, HelpFormatter swallows all but the last argument. Note that this is
- * a know issue with the HelpFormatter class that has not been fixed. We specify all arguments
- * with a single argName to workaround this HelpFormatter bug.
- */
- Option updateFSRootLoc =
- OptionBuilder
- .withArgName("new-loc> " + "<old-loc")
- .hasArgs(2)
- .withDescription(
- "Update FS root location in the metastore to new location.Both new-loc and " +
- "old-loc should be valid URIs with valid host names and schemes." +
- "When run with the dryRun option changes are displayed but are not " +
- "persisted. When run with the serdepropKey/tablePropKey option " +
- "updateLocation looks for the serde-prop-key/table-prop-key that is " +
- "specified and updates its value if found.")
- .create("updateLocation");
- Option dryRun = new Option("dryRun" , "Perform a dry run of updateLocation changes.When " +
- "run with the dryRun option updateLocation changes are displayed but not persisted. " +
- "dryRun is valid only with the updateLocation option.");
- Option serdePropKey =
- OptionBuilder.withArgName("serde-prop-key")
- .hasArgs()
- .withValueSeparator()
- .withDescription("Specify the key for serde property to be updated. serdePropKey option " +
- "is valid only with updateLocation option.")
- .create("serdePropKey");
- Option tablePropKey =
- OptionBuilder.withArgName("table-prop-key")
- .hasArg()
- .withValueSeparator()
- .withDescription("Specify the key for table property to be updated. tablePropKey option " +
- "is valid only with updateLocation option.")
- .create("tablePropKey");
-
- cmdLineOptions.addOption(help);
- cmdLineOptions.addOption(listFSRoot);
- cmdLineOptions.addOption(executeJDOQL);
- cmdLineOptions.addOption(updateFSRootLoc);
- cmdLineOptions.addOption(dryRun);
- cmdLineOptions.addOption(serdePropKey);
- cmdLineOptions.addOption(tablePropKey);
- }
-
- private void initObjectStore(HiveConf hiveConf) {
- if (!isObjStoreInitialized) {
- objStore = new ObjectStore();
- objStore.setConf(hiveConf);
- isObjStoreInitialized = true;
- }
- }
-
- private void shutdownObjectStore() {
- if (isObjStoreInitialized) {
- objStore.shutdown();
- isObjStoreInitialized = false;
- }
- }
-
- private void listFSRoot() {
- HiveConf hiveConf = new HiveConf(HiveMetaTool.class);
- initObjectStore(hiveConf);
-
- Set<String> hdfsRoots = objStore.listFSRoots();
- if (hdfsRoots != null) {
- System.out.println("Listing FS Roots..");
- for (String s : hdfsRoots) {
- System.out.println(s);
- }
- } else {
- System.err.println("Encountered error during listFSRoot - " +
- "commit of JDO transaction failed");
- }
- }
-
- private void executeJDOQLSelect(String query) {
- HiveConf hiveConf = new HiveConf(HiveMetaTool.class);
- initObjectStore(hiveConf);
-
- System.out.println("Executing query: " + query);
- ObjectStore.QueryWrapper queryWrapper = new ObjectStore.QueryWrapper();
- try {
- Collection<?> result = objStore.executeJDOQLSelect(query, queryWrapper);
- if (result != null) {
- Iterator<?> iter = result.iterator();
- while (iter.hasNext()) {
- Object o = iter.next();
- System.out.println(o.toString());
- }
- } else {
- System.err.println("Encountered error during executeJDOQLSelect -" +
- "commit of JDO transaction failed.");
- }
- } finally {
- queryWrapper.close();
- }
- }
-
- private long executeJDOQLUpdate(String query) {
- HiveConf hiveConf = new HiveConf(HiveMetaTool.class);
- initObjectStore(hiveConf);
-
- System.out.println("Executing query: " + query);
- long numUpdated = objStore.executeJDOQLUpdate(query);
- if (numUpdated >= 0) {
- System.out.println("Number of records updated: " + numUpdated);
- } else {
- System.err.println("Encountered error during executeJDOQL -" +
- "commit of JDO transaction failed.");
- }
- return numUpdated;
- }
-
- private int printUpdateLocations(Map<String, String> updateLocations) {
- int count = 0;
- for (String key: updateLocations.keySet()) {
- String value = updateLocations.get(key);
- System.out.println("old location: " + key + " new location: " + value);
- count++;
- }
- return count;
- }
-
- private void printTblURIUpdateSummary(ObjectStore.UpdateMStorageDescriptorTblURIRetVal retVal,
- boolean isDryRun) {
- String tblName = new String("SDS");
- String fieldName = new String("LOCATION");
-
- if (retVal == null) {
- System.err.println("Encountered error while executing updateMStorageDescriptorTblURI - " +
- "commit of JDO transaction failed. Failed to update FSRoot locations in " +
- fieldName + "field in " + tblName + " table.");
- } else {
- Map<String, String> updateLocations = retVal.getUpdateLocations();
- if (isDryRun) {
- System.out.println("Dry Run of updateLocation on table " + tblName + "..");
- } else {
- System.out.println("Successfully updated the following locations..");
- }
- int count = printUpdateLocations(updateLocations);
- if (isDryRun) {
- System.out.println("Found " + count + " records in " + tblName + " table to update");
- } else {
- System.out.println("Updated " + count + " records in " + tblName + " table");
- }
- List<String> badRecords = retVal.getBadRecords();
- if (badRecords.size() > 0) {
- System.err.println("Warning: Found records with bad " + fieldName + " in " +
- tblName + " table.. ");
- for (String badRecord:badRecords) {
- System.err.println("bad location URI: " + badRecord);
- }
- }
- int numNullRecords = retVal.getNumNullRecords();
- if (numNullRecords != 0) {
- LOG.debug("Number of NULL location URI: " + numNullRecords +
- ". This can happen for View or Index.");
- }
- }
- }
-
- private void printDatabaseURIUpdateSummary(ObjectStore.UpdateMDatabaseURIRetVal retVal,
- boolean isDryRun) {
- String tblName = new String("DBS");
- String fieldName = new String("LOCATION_URI");
-
- if (retVal == null) {
- System.err.println("Encountered error while executing updateMDatabaseURI - " +
- "commit of JDO transaction failed. Failed to update FSRoot locations in " +
- fieldName + "field in " + tblName + " table.");
- } else {
- Map<String, String> updateLocations = retVal.getUpdateLocations();
- if (isDryRun) {
- System.out.println("Dry Run of updateLocation on table " + tblName + "..");
- } else {
- System.out.println("Successfully updated the following locations..");
- }
- int count = printUpdateLocations(updateLocations);
- if (isDryRun) {
- System.out.println("Found " + count + " records in " + tblName + " table to update");
- } else {
- System.out.println("Updated " + count + " records in " + tblName + " table");
- }
- List<String> badRecords = retVal.getBadRecords();
- if (badRecords.size() > 0) {
- System.err.println("Warning: Found records with bad " + fieldName + " in " +
- tblName + " table.. ");
- for (String badRecord:badRecords) {
- System.err.println("bad location URI: " + badRecord);
- }
- }
- }
- }
-
- private void printPropURIUpdateSummary(ObjectStore.UpdatePropURIRetVal retVal, String
- tablePropKey, boolean isDryRun, String tblName, String methodName) {
- if (retVal == null) {
- System.err.println("Encountered error while executing " + methodName + " - " +
- "commit of JDO transaction failed. Failed to update FSRoot locations in " +
- "value field corresponding to" + tablePropKey + " in " + tblName + " table.");
- } else {
- Map<String, String> updateLocations = retVal.getUpdateLocations();
- if (isDryRun) {
- System.out.println("Dry Run of updateLocation on table " + tblName + "..");
- } else {
- System.out.println("Successfully updated the following locations..");
- }
- int count = printUpdateLocations(updateLocations);
- if (isDryRun) {
- System.out.println("Found " + count + " records in " + tblName + " table to update");
- } else {
- System.out.println("Updated " + count + " records in " + tblName + " table");
- }
- List<String> badRecords = retVal.getBadRecords();
- if (badRecords.size() > 0) {
- System.err.println("Warning: Found records with bad " + tablePropKey + " key in " +
- tblName + " table.. ");
- for (String badRecord:badRecords) {
- System.err.println("bad location URI: " + badRecord);
- }
- }
- }
- }
-
- private void printSerdePropURIUpdateSummary(ObjectStore.UpdateSerdeURIRetVal retVal,
- String serdePropKey, boolean isDryRun) {
- String tblName = new String("SERDE_PARAMS");
-
- if (retVal == null) {
- System.err.println("Encountered error while executing updateSerdeURI - " +
- "commit of JDO transaction failed. Failed to update FSRoot locations in " +
- "value field corresponding to " + serdePropKey + " in " + tblName + " table.");
- } else {
- Map<String, String> updateLocations = retVal.getUpdateLocations();
- if (isDryRun) {
- System.out.println("Dry Run of updateLocation on table " + tblName + "..");
- } else {
- System.out.println("Successfully updated the following locations..");
- }
- int count = printUpdateLocations(updateLocations);
- if (isDryRun) {
- System.out.println("Found " + count + " records in " + tblName + " table to update");
- } else {
- System.out.println("Updated " + count + " records in " + tblName + " table");
- }
- List<String> badRecords = retVal.getBadRecords();
- if (badRecords.size() > 0) {
- System.err.println("Warning: Found records with bad " + serdePropKey + " key in " +
- tblName + " table.. ");
- for (String badRecord:badRecords) {
- System.err.println("bad location URI: " + badRecord);
- }
- }
- }
- }
-
- public void updateFSRootLocation(URI oldURI, URI newURI, String serdePropKey, String
- tablePropKey, boolean isDryRun) {
- HiveConf hiveConf = new HiveConf(HiveMetaTool.class);
- initObjectStore(hiveConf);
-
- System.out.println("Looking for LOCATION_URI field in DBS table to update..");
- ObjectStore.UpdateMDatabaseURIRetVal updateMDBURIRetVal = objStore.updateMDatabaseURI(oldURI,
- newURI, isDryRun);
- printDatabaseURIUpdateSummary(updateMDBURIRetVal, isDryRun);
-
- System.out.println("Looking for LOCATION field in SDS table to update..");
- ObjectStore.UpdateMStorageDescriptorTblURIRetVal updateTblURIRetVal =
- objStore.updateMStorageDescriptorTblURI(oldURI, newURI, isDryRun);
- printTblURIUpdateSummary(updateTblURIRetVal, isDryRun);
-
- if (tablePropKey != null) {
- System.out.println("Looking for value of " + tablePropKey + " key in TABLE_PARAMS table " +
- "to update..");
- ObjectStore.UpdatePropURIRetVal updateTblPropURIRetVal =
- objStore.updateTblPropURI(oldURI, newURI,
- tablePropKey, isDryRun);
- printPropURIUpdateSummary(updateTblPropURIRetVal, tablePropKey, isDryRun, "TABLE_PARAMS",
- "updateTblPropURI");
-
- System.out.println("Looking for value of " + tablePropKey + " key in SD_PARAMS table " +
- "to update..");
- ObjectStore.UpdatePropURIRetVal updatePropURIRetVal = objStore
- .updateMStorageDescriptorTblPropURI(oldURI, newURI, tablePropKey, isDryRun);
- printPropURIUpdateSummary(updatePropURIRetVal, tablePropKey, isDryRun, "SD_PARAMS",
- "updateMStorageDescriptorTblPropURI");
- }
-
- if (serdePropKey != null) {
- System.out.println("Looking for value of " + serdePropKey + " key in SERDE_PARAMS table " +
- "to update..");
- ObjectStore.UpdateSerdeURIRetVal updateSerdeURIretVal = objStore.updateSerdeURI(oldURI,
- newURI, serdePropKey, isDryRun);
- printSerdePropURIUpdateSummary(updateSerdeURIretVal, serdePropKey, isDryRun);
- }
- }
-
- private static void printAndExit(HiveMetaTool metaTool) {
- HelpFormatter formatter = new HelpFormatter();
- formatter.printHelp("metatool", metaTool.cmdLineOptions);
- System.exit(1);
- }
-
- public static void main(String[] args) {
- HiveMetaTool metaTool = new HiveMetaTool();
- metaTool.init();
- CommandLineParser parser = new GnuParser();
- CommandLine line = null;
-
- try {
- try {
- line = parser.parse(metaTool.cmdLineOptions, args);
- } catch (ParseException e) {
- System.err.println("HiveMetaTool:Parsing failed. Reason: " + e.getLocalizedMessage());
- printAndExit(metaTool);
- }
-
- if (line.hasOption("help")) {
- HelpFormatter formatter = new HelpFormatter();
- formatter.printHelp("metatool", metaTool.cmdLineOptions);
- } else if (line.hasOption("listFSRoot")) {
- if (line.hasOption("dryRun")) {
- System.err.println("HiveMetaTool: dryRun is not valid with listFSRoot");
- printAndExit(metaTool);
- } else if (line.hasOption("serdePropKey")) {
- System.err.println("HiveMetaTool: serdePropKey is not valid with listFSRoot");
- printAndExit(metaTool);
- } else if (line.hasOption("tablePropKey")) {
- System.err.println("HiveMetaTool: tablePropKey is not valid with listFSRoot");
- printAndExit(metaTool);
- }
- metaTool.listFSRoot();
- } else if (line.hasOption("executeJDOQL")) {
- String query = line.getOptionValue("executeJDOQL");
- if (line.hasOption("dryRun")) {
- System.err.println("HiveMetaTool: dryRun is not valid with executeJDOQL");
- printAndExit(metaTool);
- } else if (line.hasOption("serdePropKey")) {
- System.err.println("HiveMetaTool: serdePropKey is not valid with executeJDOQL");
- printAndExit(metaTool);
- } else if (line.hasOption("tablePropKey")) {
- System.err.println("HiveMetaTool: tablePropKey is not valid with executeJDOQL");
- printAndExit(metaTool);
- }
- if (query.toLowerCase().trim().startsWith("select")) {
- metaTool.executeJDOQLSelect(query);
- } else if (query.toLowerCase().trim().startsWith("update")) {
- metaTool.executeJDOQLUpdate(query);
- } else {
- System.err.println("HiveMetaTool:Unsupported statement type");
- printAndExit(metaTool);
- }
- } else if (line.hasOption("updateLocation")) {
- String[] loc = line.getOptionValues("updateLocation");
- boolean isDryRun = false;
- String serdepropKey = null;
- String tablePropKey = null;
-
- if (loc.length != 2 && loc.length != 3) {
- System.err.println("HiveMetaTool:updateLocation takes in 2 required and 1 " +
- "optional arguments but " +
- "was passed " + loc.length + " arguments");
- printAndExit(metaTool);
- }
-
- Path newPath = new Path(loc[0]);
- Path oldPath = new Path(loc[1]);
-
- URI oldURI = oldPath.toUri();
- URI newURI = newPath.toUri();
-
- if (line.hasOption("dryRun")) {
- isDryRun = true;
- }
-
- if (line.hasOption("serdePropKey")) {
- serdepropKey = line.getOptionValue("serdePropKey");
- }
-
- if (line.hasOption("tablePropKey")) {
- tablePropKey = line.getOptionValue("tablePropKey");
- }
-
- /*
- * validate input - Both new and old URI should contain valid host names and valid schemes.
- * port is optional in both the URIs since HDFS HA NN URI doesn't have a port.
- */
- if (oldURI.getHost() == null || newURI.getHost() == null) {
- System.err.println("HiveMetaTool:A valid host is required in both old-loc and new-loc");
- } else if (oldURI.getScheme() == null || newURI.getScheme() == null) {
- System.err.println("HiveMetaTool:A valid scheme is required in both old-loc and new-loc");
- } else {
- metaTool.updateFSRootLocation(oldURI, newURI, serdepropKey, tablePropKey, isDryRun);
- }
- } else {
- if (line.hasOption("dryRun")) {
- System.err.println("HiveMetaTool: dryRun is not a valid standalone option");
- } else if (line.hasOption("serdePropKey")) {
- System.err.println("HiveMetaTool: serdePropKey is not a valid standalone option");
- } else if (line.hasOption("tablePropKey")) {
- System.err.println("HiveMetaTool: tablePropKey is not a valid standalone option");
- printAndExit(metaTool);
- } else {
- System.err.print("HiveMetaTool:Parsing failed. Reason: Invalid arguments: " );
- for (String s : line.getArgs()) {
- System.err.print(s + " ");
- }
- System.err.println();
- }
- printAndExit(metaTool);
- }
- } finally {
- metaTool.shutdownObjectStore();
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/metastore/src/test/org/apache/hadoop/hive/metastore/AlternateFailurePreListener.java
----------------------------------------------------------------------
diff --git a/metastore/src/test/org/apache/hadoop/hive/metastore/AlternateFailurePreListener.java b/metastore/src/test/org/apache/hadoop/hive/metastore/AlternateFailurePreListener.java
deleted file mode 100644
index 22146ba..0000000
--- a/metastore/src/test/org/apache/hadoop/hive/metastore/AlternateFailurePreListener.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/**
- * 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 javax.jdo.JDOException;
-
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.hive.metastore.api.InvalidOperationException;
-import org.apache.hadoop.hive.metastore.api.MetaException;
-import org.apache.hadoop.hive.metastore.api.NoSuchObjectException;
-import org.apache.hadoop.hive.metastore.events.PreEventContext;
-
-/**
- *
- * AlternateFailurePreListener.
- *
- * An implementation of MetaStorePreEventListener which fails every other time it's invoked,
- * starting with the first time.
- *
- * It also records and makes available the number of times it's been invoked.
- */
-public class AlternateFailurePreListener extends MetaStorePreEventListener {
-
- private static int callCount = 0;
- private static boolean throwException = true;
-
- public AlternateFailurePreListener(Configuration config) {
- super(config);
- }
-
- @Override
- public void onEvent(PreEventContext context) throws MetaException, NoSuchObjectException,
- InvalidOperationException {
-
- callCount++;
- if (throwException) {
- throwException = false;
- throw new JDOException();
- }
-
- throwException = true;
- }
-
- public static int getCallCount() {
- return callCount;
- }
-}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/metastore/src/test/org/apache/hadoop/hive/metastore/DummyEndFunctionListener.java
----------------------------------------------------------------------
diff --git a/metastore/src/test/org/apache/hadoop/hive/metastore/DummyEndFunctionListener.java b/metastore/src/test/org/apache/hadoop/hive/metastore/DummyEndFunctionListener.java
deleted file mode 100644
index ac62cd5..0000000
--- a/metastore/src/test/org/apache/hadoop/hive/metastore/DummyEndFunctionListener.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/**
- * 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 java.util.ArrayList;
-import java.util.List;
-
-import org.apache.hadoop.conf.Configuration;
-
-
-/** A dummy implementation for
- * {@link org.apache.hadoop.hive.metastore.MetaStoreEndFunctionListener}
- * for testing purposes.
- */
-public class DummyEndFunctionListener extends MetaStoreEndFunctionListener{
-
- public static final List<String> funcNameList = new ArrayList<String>();
- public static final List<MetaStoreEndFunctionContext> contextList =
- new ArrayList<MetaStoreEndFunctionContext>();
-
- public DummyEndFunctionListener(Configuration config) {
- super(config);
- }
-
- @Override
- public void onEndFunction(String functionName, MetaStoreEndFunctionContext context) {
- funcNameList.add(functionName);
- contextList.add(context);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/metastore/src/test/org/apache/hadoop/hive/metastore/DummyListener.java
----------------------------------------------------------------------
diff --git a/metastore/src/test/org/apache/hadoop/hive/metastore/DummyListener.java b/metastore/src/test/org/apache/hadoop/hive/metastore/DummyListener.java
deleted file mode 100644
index 182e724..0000000
--- a/metastore/src/test/org/apache/hadoop/hive/metastore/DummyListener.java
+++ /dev/null
@@ -1,144 +0,0 @@
-/**
- * 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 java.util.ArrayList;
-import java.util.List;
-
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.hive.metastore.api.MetaException;
-import org.apache.hadoop.hive.metastore.events.AddIndexEvent;
-import org.apache.hadoop.hive.metastore.events.AddPartitionEvent;
-import org.apache.hadoop.hive.metastore.events.AlterIndexEvent;
-import org.apache.hadoop.hive.metastore.events.AlterPartitionEvent;
-import org.apache.hadoop.hive.metastore.events.AlterTableEvent;
-import org.apache.hadoop.hive.metastore.events.ConfigChangeEvent;
-import org.apache.hadoop.hive.metastore.events.CreateDatabaseEvent;
-import org.apache.hadoop.hive.metastore.events.CreateFunctionEvent;
-import org.apache.hadoop.hive.metastore.events.CreateTableEvent;
-import org.apache.hadoop.hive.metastore.events.DropDatabaseEvent;
-import org.apache.hadoop.hive.metastore.events.DropFunctionEvent;
-import org.apache.hadoop.hive.metastore.events.DropIndexEvent;
-import org.apache.hadoop.hive.metastore.events.DropPartitionEvent;
-import org.apache.hadoop.hive.metastore.events.DropTableEvent;
-import org.apache.hadoop.hive.metastore.events.ListenerEvent;
-import org.apache.hadoop.hive.metastore.events.LoadPartitionDoneEvent;
-
-/** A dummy implementation for
- * {@link org.apache.hadoop.hive.metastore.MetaStoreEventListener}
- * for testing purposes.
- */
-public class DummyListener extends MetaStoreEventListener{
-
- public static final List<ListenerEvent> notifyList = new ArrayList<ListenerEvent>();
-
- /**
- * @return The last event received, or null if no event was received.
- */
- public static ListenerEvent getLastEvent() {
- if (notifyList.isEmpty()) {
- return null;
- } else {
- return notifyList.get(notifyList.size() - 1);
- }
- }
-
- public DummyListener(Configuration config) {
- super(config);
- }
-
- @Override
- public void onConfigChange(ConfigChangeEvent configChange) {
- addEvent(configChange);
- }
-
- @Override
- public void onAddPartition(AddPartitionEvent partition) throws MetaException {
- addEvent(partition);
- }
-
- @Override
- public void onCreateDatabase(CreateDatabaseEvent db) throws MetaException {
- addEvent(db);
- }
-
- @Override
- public void onCreateTable(CreateTableEvent table) throws MetaException {
- addEvent(table);
- }
-
- @Override
- public void onDropDatabase(DropDatabaseEvent db) throws MetaException {
- addEvent(db);
- }
-
- @Override
- public void onDropPartition(DropPartitionEvent partition) throws MetaException {
- addEvent(partition);
- }
-
- @Override
- public void onDropTable(DropTableEvent table) throws MetaException {
- addEvent(table);
- }
-
- @Override
- public void onAlterTable(AlterTableEvent event) throws MetaException {
- addEvent(event);
- }
-
- @Override
- public void onAlterPartition(AlterPartitionEvent event) throws MetaException {
- addEvent(event);
- }
-
- @Override
- public void onLoadPartitionDone(LoadPartitionDoneEvent partEvent) throws MetaException {
- addEvent(partEvent);
- }
-
- @Override
- public void onAddIndex(AddIndexEvent indexEvent) throws MetaException {
- addEvent(indexEvent);
- }
-
- @Override
- public void onDropIndex(DropIndexEvent indexEvent) throws MetaException {
- addEvent(indexEvent);
- }
-
- @Override
- public void onAlterIndex(AlterIndexEvent indexEvent) throws MetaException {
- addEvent(indexEvent);
- }
-
- @Override
- public void onCreateFunction (CreateFunctionEvent fnEvent) throws MetaException {
- addEvent(fnEvent);
- }
-
- @Override
- public void onDropFunction (DropFunctionEvent fnEvent) throws MetaException {
- addEvent(fnEvent);
- }
-
- private void addEvent(ListenerEvent event) {
- notifyList.add(event);
- }
-}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/metastore/src/test/org/apache/hadoop/hive/metastore/DummyMetaStoreInitListener.java
----------------------------------------------------------------------
diff --git a/metastore/src/test/org/apache/hadoop/hive/metastore/DummyMetaStoreInitListener.java b/metastore/src/test/org/apache/hadoop/hive/metastore/DummyMetaStoreInitListener.java
deleted file mode 100644
index 2eb8354..0000000
--- a/metastore/src/test/org/apache/hadoop/hive/metastore/DummyMetaStoreInitListener.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/**
- * 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 org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.hive.conf.HiveConf;
-import org.apache.hadoop.hive.metastore.MetaStoreInitContext;
-import org.apache.hadoop.hive.metastore.MetaStoreInitListener;
-import org.apache.hadoop.hive.metastore.api.MetaException;
-
-/*
- * An implementation of MetaStoreInitListener to verify onInit is called when
- * HMSHandler is initialized
- */
-public class DummyMetaStoreInitListener extends MetaStoreInitListener{
-
- public static boolean wasCalled = false;
- public DummyMetaStoreInitListener(Configuration config) {
- super(config);
- }
-
- @Override
- public void onInit(MetaStoreInitContext context) throws MetaException {
- wasCalled = true;
- }
-}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/metastore/src/test/org/apache/hadoop/hive/metastore/DummyPreListener.java
----------------------------------------------------------------------
diff --git a/metastore/src/test/org/apache/hadoop/hive/metastore/DummyPreListener.java b/metastore/src/test/org/apache/hadoop/hive/metastore/DummyPreListener.java
deleted file mode 100644
index 7ff6f92..0000000
--- a/metastore/src/test/org/apache/hadoop/hive/metastore/DummyPreListener.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/**
- * 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 java.util.ArrayList;
-import java.util.List;
-
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.hive.metastore.api.InvalidOperationException;
-import org.apache.hadoop.hive.metastore.api.MetaException;
-import org.apache.hadoop.hive.metastore.api.NoSuchObjectException;
-import org.apache.hadoop.hive.metastore.events.PreEventContext;
-
-/**
- *
- * DummyPreListener.
- *
- * An implementation of MetaStorePreEventListener which stores the Events it's seen in a list.
- */
-public class DummyPreListener extends MetaStorePreEventListener {
-
- public static final List<PreEventContext> notifyList = new ArrayList<PreEventContext>();
-
- public DummyPreListener(Configuration config) {
- super(config);
- }
-
- @Override
- public void onEvent(PreEventContext context) throws MetaException, NoSuchObjectException,
- InvalidOperationException {
- notifyList.add(context);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/metastore/src/test/org/apache/hadoop/hive/metastore/DummyRawStoreControlledCommit.java
----------------------------------------------------------------------
diff --git a/metastore/src/test/org/apache/hadoop/hive/metastore/DummyRawStoreControlledCommit.java b/metastore/src/test/org/apache/hadoop/hive/metastore/DummyRawStoreControlledCommit.java
deleted file mode 100644
index 610b9fa..0000000
--- a/metastore/src/test/org/apache/hadoop/hive/metastore/DummyRawStoreControlledCommit.java
+++ /dev/null
@@ -1,999 +0,0 @@
-/**
- * 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 java.nio.ByteBuffer;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.hadoop.conf.Configurable;
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.hive.metastore.api.AggrStats;
-import org.apache.hadoop.hive.metastore.api.AlreadyExistsException;
-import org.apache.hadoop.hive.metastore.api.ColumnStatistics;
-import org.apache.hadoop.hive.metastore.api.ColumnStatisticsObj;
-import org.apache.hadoop.hive.metastore.api.CurrentNotificationEventId;
-import org.apache.hadoop.hive.metastore.api.Database;
-import org.apache.hadoop.hive.metastore.api.FieldSchema;
-import org.apache.hadoop.hive.metastore.api.FileMetadataExprType;
-import org.apache.hadoop.hive.metastore.api.Function;
-import org.apache.hadoop.hive.metastore.api.HiveObjectPrivilege;
-import org.apache.hadoop.hive.metastore.api.Index;
-import org.apache.hadoop.hive.metastore.api.InvalidInputException;
-import org.apache.hadoop.hive.metastore.api.InvalidObjectException;
-import org.apache.hadoop.hive.metastore.api.InvalidOperationException;
-import org.apache.hadoop.hive.metastore.api.InvalidPartitionException;
-import org.apache.hadoop.hive.metastore.api.MetaException;
-import org.apache.hadoop.hive.metastore.api.NoSuchObjectException;
-import org.apache.hadoop.hive.metastore.api.NotificationEvent;
-import org.apache.hadoop.hive.metastore.api.NotificationEventRequest;
-import org.apache.hadoop.hive.metastore.api.NotificationEventResponse;
-import org.apache.hadoop.hive.metastore.api.NotificationEventsCountRequest;
-import org.apache.hadoop.hive.metastore.api.NotificationEventsCountResponse;
-import org.apache.hadoop.hive.metastore.api.Partition;
-import org.apache.hadoop.hive.metastore.api.PartitionEventType;
-import org.apache.hadoop.hive.metastore.api.PartitionValuesResponse;
-import org.apache.hadoop.hive.metastore.api.PrincipalPrivilegeSet;
-import org.apache.hadoop.hive.metastore.api.PrincipalType;
-import org.apache.hadoop.hive.metastore.api.PrivilegeBag;
-import org.apache.hadoop.hive.metastore.api.WMResourcePlan;
-import org.apache.hadoop.hive.metastore.api.WMTrigger;
-import org.apache.hadoop.hive.metastore.api.Role;
-import org.apache.hadoop.hive.metastore.api.RolePrincipalGrant;
-import org.apache.hadoop.hive.metastore.api.SQLForeignKey;
-import org.apache.hadoop.hive.metastore.api.SQLNotNullConstraint;
-import org.apache.hadoop.hive.metastore.api.SQLPrimaryKey;
-import org.apache.hadoop.hive.metastore.api.SQLUniqueConstraint;
-import org.apache.hadoop.hive.metastore.api.Table;
-import org.apache.hadoop.hive.metastore.api.TableMeta;
-import org.apache.hadoop.hive.metastore.api.Type;
-import org.apache.hadoop.hive.metastore.api.UnknownDBException;
-import org.apache.hadoop.hive.metastore.api.UnknownPartitionException;
-import org.apache.hadoop.hive.metastore.api.UnknownTableException;
-import org.apache.hadoop.hive.metastore.partition.spec.PartitionSpecProxy;
-import org.apache.thrift.TException;
-
-/**
- * A wrapper around {@link org.apache.hadoop.hive.metastore.ObjectStore}
- * with the ability to control the result of commitTransaction().
- * All other functions simply delegate to an embedded ObjectStore object.
- * Ideally, we should have just extended ObjectStore instead of using
- * delegation. However, since HiveMetaStore uses a Proxy, this class must
- * not inherit from any other class.
- */
-public class DummyRawStoreControlledCommit implements RawStore, Configurable {
-
- private final ObjectStore objectStore;
- public DummyRawStoreControlledCommit() {
- objectStore = new ObjectStore();
- }
-
- /**
- * If true, shouldCommit() will simply call delegate commitTransaction() to the
- * underlying ObjectStore.
- * If false, shouldCommit() immediately returns false.
- */
- private static boolean shouldCommitSucceed = true;
- public static void setCommitSucceed(boolean flag) {
- shouldCommitSucceed = flag;
- }
-
- @Override
- public boolean commitTransaction() {
- if (shouldCommitSucceed) {
- return objectStore.commitTransaction();
- } else {
- return false;
- }
- }
-
- @Override
- public boolean isActiveTransaction() {
- return false;
- }
-
- // All remaining functions simply delegate to objectStore
-
- @Override
- public Configuration getConf() {
- return objectStore.getConf();
- }
-
- @Override
- public void setConf(Configuration conf) {
- objectStore.setConf(conf);
- }
-
- @Override
- public void shutdown() {
- objectStore.shutdown();
- }
-
- @Override
- public boolean openTransaction() {
- return objectStore.openTransaction();
- }
-
- @Override
- public void rollbackTransaction() {
- objectStore.rollbackTransaction();
- }
-
- @Override
- public void createDatabase(Database db) throws InvalidObjectException, MetaException {
- objectStore.createDatabase(db);
- }
-
- @Override
- public Database getDatabase(String dbName) throws NoSuchObjectException {
- return objectStore.getDatabase(dbName);
- }
-
- @Override
- public boolean dropDatabase(String dbName)
- throws NoSuchObjectException, MetaException {
- return objectStore.dropDatabase(dbName);
- }
-
- @Override
- public boolean alterDatabase(String dbName, Database db)
- throws NoSuchObjectException, MetaException {
-
- return objectStore.alterDatabase(dbName, db);
- }
-
- @Override
- public List<String> getDatabases(String pattern) throws MetaException {
- return objectStore.getDatabases(pattern);
- }
-
- @Override
- public List<String> getAllDatabases() throws MetaException {
- return objectStore.getAllDatabases();
- }
-
- @Override
- public boolean createType(Type type) {
- return objectStore.createType(type);
- }
-
- @Override
- public Type getType(String typeName) {
- return objectStore.getType(typeName);
- }
-
- @Override
- public boolean dropType(String typeName) {
- return objectStore.dropType(typeName);
- }
-
- @Override
- public void createTable(Table tbl) throws InvalidObjectException, MetaException {
- objectStore.createTable(tbl);
- }
-
- @Override
- public boolean dropTable(String dbName, String tableName)
- throws MetaException, NoSuchObjectException,
- InvalidObjectException, InvalidInputException {
- return objectStore.dropTable(dbName, tableName);
- }
-
- @Override
- public Table getTable(String dbName, String tableName) throws MetaException {
- return objectStore.getTable(dbName, tableName);
- }
-
- @Override
- public boolean addPartition(Partition part)
- throws InvalidObjectException, MetaException {
- return objectStore.addPartition(part);
- }
-
- @Override
- public Partition getPartition(String dbName, String tableName, List<String> partVals)
- throws MetaException, NoSuchObjectException {
- return objectStore.getPartition(dbName, tableName, partVals);
- }
-
- @Override
- public boolean dropPartition(String dbName, String tableName, List<String> partVals)
- throws MetaException, NoSuchObjectException,
- InvalidObjectException, InvalidInputException {
- return objectStore.dropPartition(dbName, tableName, partVals);
- }
-
- @Override
- public List<Partition> getPartitions(String dbName, String tableName, int max)
- throws MetaException, NoSuchObjectException {
- return objectStore.getPartitions(dbName, tableName, max);
- }
-
- @Override
- public void alterTable(String dbName, String name, Table newTable)
- throws InvalidObjectException, MetaException {
- objectStore.alterTable(dbName, name, newTable);
- }
-
- @Override
- public List<String> getTables(String dbName, String pattern) throws MetaException {
- return objectStore.getTables(dbName, pattern);
- }
-
- @Override
- public List<String> getTables(String dbName, String pattern, TableType tableType) throws MetaException {
- return objectStore.getTables(dbName, pattern, tableType);
- }
-
- @Override
- public List<TableMeta> getTableMeta(String dbNames, String tableNames, List<String> tableTypes)
- throws MetaException {
- return objectStore.getTableMeta(dbNames, tableNames, tableTypes);
- }
-
- @Override
- public List<Table> getTableObjectsByName(String dbName, List<String> tableNames)
- throws MetaException, UnknownDBException {
- return objectStore.getTableObjectsByName(dbName, tableNames);
- }
-
- @Override
- public List<String> getAllTables(String dbName) throws MetaException {
- return objectStore.getAllTables(dbName);
- }
-
- @Override
- public List<String> listTableNamesByFilter(String dbName, String filter,
- short maxTables) throws MetaException, UnknownDBException {
- return objectStore.listTableNamesByFilter(dbName, filter, maxTables);
- }
-
- @Override
- public List<String> listPartitionNames(String dbName, String tblName, short maxParts)
- throws MetaException {
- return objectStore.listPartitionNames(dbName, tblName, maxParts);
- }
-
- @Override
- public PartitionValuesResponse listPartitionValues(String db_name, String tbl_name, List<FieldSchema> cols, boolean applyDistinct, String filter, boolean ascending, List<FieldSchema> order, long maxParts) throws MetaException {
- return null;
- }
-
- @Override
- public List<String> listPartitionNamesByFilter(String dbName, String tblName,
- String filter, short maxParts) throws MetaException {
- return objectStore.listPartitionNamesByFilter(dbName, tblName, filter, maxParts);
- }
-
- @Override
- public void alterPartition(String dbName, String tblName, List<String> partVals,
- Partition newPart) throws InvalidObjectException, MetaException {
- objectStore.alterPartition(dbName, tblName, partVals, newPart);
- }
-
- @Override
- public void alterPartitions(String dbName, String tblName,
- List<List<String>> partValsList, List<Partition> newParts)
- throws InvalidObjectException, MetaException {
- objectStore.alterPartitions(dbName, tblName, partValsList, newParts);
- }
-
- @Override
- public boolean addIndex(Index index) throws InvalidObjectException, MetaException {
- return objectStore.addIndex(index);
- }
-
- @Override
- public Index getIndex(String dbName, String origTableName, String indexName)
- throws MetaException {
- return objectStore.getIndex(dbName, origTableName, indexName);
- }
-
- @Override
- public boolean dropIndex(String dbName, String origTableName, String indexName)
- throws MetaException {
- return objectStore.dropIndex(dbName, origTableName, indexName);
- }
-
- @Override
- public List<Index> getIndexes(String dbName, String origTableName, int max)
- throws MetaException {
- return objectStore.getIndexes(dbName, origTableName, max);
- }
-
- @Override
- public List<String> listIndexNames(String dbName, String origTableName, short max)
- throws MetaException {
- return objectStore.listIndexNames(dbName, origTableName, max);
- }
-
- @Override
- public void alterIndex(String dbName, String baseTblName, String name, Index newIndex)
- throws InvalidObjectException, MetaException {
- objectStore.alterIndex(dbName, baseTblName, name, newIndex);
- }
-
- @Override
- public List<Partition> getPartitionsByFilter(String dbName, String tblName,
- String filter, short maxParts) throws MetaException, NoSuchObjectException {
- return objectStore.getPartitionsByFilter(dbName, tblName, filter, maxParts);
- }
-
- @Override
- public int getNumPartitionsByFilter(String dbName, String tblName,
- String filter) throws MetaException, NoSuchObjectException {
- return objectStore.getNumPartitionsByFilter(dbName, tblName, filter);
- }
-
- @Override
- public int getNumPartitionsByExpr(String dbName, String tblName,
- byte[] expr) throws MetaException, NoSuchObjectException {
- return objectStore.getNumPartitionsByExpr(dbName, tblName, expr);
- }
-
- @Override
- public List<Partition> getPartitionsByNames(String dbName, String tblName,
- List<String> partNames) throws MetaException, NoSuchObjectException {
- return objectStore.getPartitionsByNames(dbName, tblName, partNames);
- }
-
- @Override
- public boolean getPartitionsByExpr(String dbName, String tblName, byte[] expr,
- String defaultPartitionName, short maxParts, List<Partition> result) throws TException {
- return objectStore.getPartitionsByExpr(
- dbName, tblName, expr, defaultPartitionName, maxParts, result);
- }
-
- @Override
- public Table markPartitionForEvent(String dbName, String tblName,
- Map<String, String> partVals, PartitionEventType evtType)
- throws MetaException, UnknownTableException, InvalidPartitionException,
- UnknownPartitionException {
- return objectStore.markPartitionForEvent(dbName, tblName, partVals, evtType);
- }
-
- @Override
- public boolean isPartitionMarkedForEvent(String dbName, String tblName,
- Map<String, String> partName, PartitionEventType evtType)
- throws MetaException, UnknownTableException, InvalidPartitionException,
- UnknownPartitionException {
- return objectStore.isPartitionMarkedForEvent(dbName, tblName, partName, evtType);
- }
-
- @Override
- public boolean addRole(String rowName, String ownerName) throws InvalidObjectException,
- MetaException, NoSuchObjectException {
- return objectStore.addRole(rowName, ownerName);
- }
-
- @Override
- public boolean removeRole(String roleName)
- throws MetaException, NoSuchObjectException {
- return objectStore.removeRole(roleName);
- }
-
- @Override
- public boolean grantRole(Role role, String userName, PrincipalType principalType,
- String grantor, PrincipalType grantorType, boolean grantOption)
- throws MetaException, NoSuchObjectException, InvalidObjectException {
- return objectStore.grantRole(role, userName, principalType, grantor, grantorType,
- grantOption);
- }
-
- @Override
- public boolean revokeRole(Role role, String userName, PrincipalType principalType, boolean grantOption)
- throws MetaException, NoSuchObjectException {
- return objectStore.revokeRole(role, userName, principalType, grantOption);
- }
-
- @Override
- public PrincipalPrivilegeSet getUserPrivilegeSet(String userName,
- List<String> groupNames) throws InvalidObjectException, MetaException {
- return objectStore.getUserPrivilegeSet(userName, groupNames);
- }
-
- @Override
- public PrincipalPrivilegeSet getDBPrivilegeSet(String dbName, String userName,
- List<String> groupNames) throws InvalidObjectException, MetaException {
- return objectStore.getDBPrivilegeSet(dbName, userName, groupNames);
- }
-
- @Override
- public PrincipalPrivilegeSet getTablePrivilegeSet(String dbName, String tableName,
- String userName, List<String> groupNames)
- throws InvalidObjectException, MetaException {
- return objectStore.getTablePrivilegeSet(dbName, tableName, userName, groupNames);
- }
-
- @Override
- public PrincipalPrivilegeSet getPartitionPrivilegeSet(String dbName, String tableName,
- String partition, String userName, List<String> groupNames)
- throws InvalidObjectException, MetaException {
- return objectStore.getPartitionPrivilegeSet(dbName, tableName, partition,
- userName, groupNames);
- }
-
- @Override
- public PrincipalPrivilegeSet getColumnPrivilegeSet(String dbName, String tableName,
- String partitionName, String columnName, String userName, List<String> groupNames)
- throws InvalidObjectException, MetaException {
- return objectStore.getColumnPrivilegeSet(dbName, tableName, partitionName,
- columnName, userName, groupNames);
- }
-
- @Override
- public List<HiveObjectPrivilege> listPrincipalGlobalGrants(String principalName,
- PrincipalType principalType) {
- return objectStore.listPrincipalGlobalGrants(principalName, principalType);
- }
-
- @Override
- public List<HiveObjectPrivilege> listPrincipalDBGrants(String principalName,
- PrincipalType principalType, String dbName) {
- return objectStore.listPrincipalDBGrants(principalName, principalType, dbName);
- }
-
- @Override
- public List<HiveObjectPrivilege> listAllTableGrants(String principalName,
- PrincipalType principalType, String dbName, String tableName) {
- return objectStore.listAllTableGrants(principalName, principalType,
- dbName, tableName);
- }
-
- @Override
- public List<HiveObjectPrivilege> listPrincipalPartitionGrants(String principalName,
- PrincipalType principalType, String dbName, String tableName, List<String> partValues,
- String partName) {
- return objectStore.listPrincipalPartitionGrants(principalName, principalType,
- dbName, tableName, partValues, partName);
- }
-
- @Override
- public List<HiveObjectPrivilege> listPrincipalTableColumnGrants(String principalName,
- PrincipalType principalType, String dbName, String tableName, String columnName) {
- return objectStore.listPrincipalTableColumnGrants(principalName, principalType,
- dbName, tableName, columnName);
- }
-
- @Override
- public List<HiveObjectPrivilege> listPrincipalPartitionColumnGrants(
- String principalName, PrincipalType principalType, String dbName, String tableName,
- List<String> partVals, String partName, String columnName) {
- return objectStore.listPrincipalPartitionColumnGrants(principalName, principalType,
- dbName, tableName, partVals, partName, columnName);
- }
-
- @Override
- public boolean grantPrivileges(PrivilegeBag privileges) throws InvalidObjectException,
- MetaException, NoSuchObjectException {
- return objectStore.grantPrivileges(privileges);
- }
-
- @Override
- public boolean revokePrivileges(PrivilegeBag privileges, boolean grantOption)
- throws InvalidObjectException, MetaException, NoSuchObjectException {
- return objectStore.revokePrivileges(privileges, grantOption);
- }
-
- @Override
- public Role getRole(String roleName) throws NoSuchObjectException {
- return objectStore.getRole(roleName);
- }
-
- @Override
- public List<String> listRoleNames() {
- return objectStore.listRoleNames();
- }
-
- @Override
- public List<Role> listRoles(String principalName, PrincipalType principalType) {
- return objectStore.listRoles(principalName, principalType);
- }
-
- @Override
- public List<RolePrincipalGrant> listRolesWithGrants(String principalName,
- PrincipalType principalType) {
- return objectStore.listRolesWithGrants(principalName, principalType);
- }
-
- @Override
- public List<RolePrincipalGrant> listRoleMembers(String roleName) {
- return objectStore.listRoleMembers(roleName);
- }
-
- @Override
- public Partition getPartitionWithAuth(String dbName, String tblName,
- List<String> partVals, String userName, List<String> groupNames)
- throws MetaException, NoSuchObjectException, InvalidObjectException {
- return objectStore.getPartitionWithAuth(dbName, tblName, partVals, userName,
- groupNames);
- }
-
- @Override
- public List<Partition> getPartitionsWithAuth(String dbName, String tblName,
- short maxParts, String userName, List<String> groupNames)
- throws MetaException, NoSuchObjectException, InvalidObjectException {
- return objectStore.getPartitionsWithAuth(dbName, tblName, maxParts, userName,
- groupNames);
- }
-
- @Override
- public List<String> listPartitionNamesPs(String dbName, String tblName,
- List<String> partVals, short maxParts)
- throws MetaException, NoSuchObjectException {
- return objectStore.listPartitionNamesPs(dbName, tblName, partVals, maxParts);
- }
-
- @Override
- public List<Partition> listPartitionsPsWithAuth(String dbName, String tblName,
- List<String> partVals, short maxParts, String userName, List<String> groupNames)
- throws MetaException, InvalidObjectException, NoSuchObjectException {
- return objectStore.listPartitionsPsWithAuth(dbName, tblName, partVals, maxParts,
- userName, groupNames);
- }
-
- @Override
- public long cleanupEvents() {
- return objectStore.cleanupEvents();
- }
-
- @Override
- public List<HiveObjectPrivilege> listPrincipalDBGrantsAll(
- String principalName, PrincipalType principalType) {
- return objectStore.listPrincipalDBGrantsAll(principalName, principalType);
- }
-
- @Override
- public List<HiveObjectPrivilege> listPrincipalTableGrantsAll(
- String principalName, PrincipalType principalType) {
- return objectStore.listPrincipalTableGrantsAll(principalName, principalType);
- }
-
- @Override
- public List<HiveObjectPrivilege> listPrincipalPartitionGrantsAll(
- String principalName, PrincipalType principalType) {
- return objectStore.listPrincipalPartitionGrantsAll(principalName, principalType);
- }
-
- @Override
- public List<HiveObjectPrivilege> listPrincipalTableColumnGrantsAll(
- String principalName, PrincipalType principalType) {
- return objectStore.listPrincipalTableColumnGrantsAll(principalName, principalType);
- }
-
- @Override
- public List<HiveObjectPrivilege> listPrincipalPartitionColumnGrantsAll(
- String principalName, PrincipalType principalType) {
- return objectStore.listPrincipalPartitionColumnGrantsAll(principalName, principalType);
- }
-
- @Override
- public List<HiveObjectPrivilege> listGlobalGrantsAll() {
- return objectStore.listGlobalGrantsAll();
- }
-
- @Override
- public List<HiveObjectPrivilege> listDBGrantsAll(String dbName) {
- return objectStore.listDBGrantsAll(dbName);
- }
-
- @Override
- public List<HiveObjectPrivilege> listPartitionColumnGrantsAll(String dbName, String tableName,
- String partitionName, String columnName) {
- return objectStore.listPartitionColumnGrantsAll(dbName, tableName, partitionName, columnName);
- }
-
- @Override
- public List<HiveObjectPrivilege> listTableGrantsAll(String dbName, String tableName) {
- return objectStore.listTableGrantsAll(dbName, tableName);
- }
-
- @Override
- public List<HiveObjectPrivilege> listPartitionGrantsAll(String dbName, String tableName,
- String partitionName) {
- return objectStore.listPartitionGrantsAll(dbName, tableName, partitionName);
- }
-
- @Override
- public List<HiveObjectPrivilege> listTableColumnGrantsAll(String dbName, String tableName,
- String columnName) {
- return objectStore.listTableColumnGrantsAll(dbName, tableName, columnName);
- }
-
- @Override
- public ColumnStatistics getTableColumnStatistics(String dbName, String tableName,
- List<String> colNames) throws MetaException, NoSuchObjectException {
- return objectStore.getTableColumnStatistics(dbName, tableName, colNames);
- }
-
- @Override
- public boolean deleteTableColumnStatistics(String dbName, String tableName,
- String colName)
- throws NoSuchObjectException, MetaException, InvalidObjectException,
- InvalidInputException {
- return objectStore.deleteTableColumnStatistics(dbName, tableName, colName);
- }
-
- @Override
- public boolean deletePartitionColumnStatistics(String dbName, String tableName,
- String partName, List<String> partVals, String colName)
- throws NoSuchObjectException, MetaException, InvalidObjectException,
- InvalidInputException {
- return objectStore.deletePartitionColumnStatistics(dbName, tableName, partName,
- partVals, colName);
- }
-
- @Override
- public boolean updateTableColumnStatistics(ColumnStatistics statsObj)
- throws NoSuchObjectException, MetaException, InvalidObjectException,
- InvalidInputException {
- return objectStore.updateTableColumnStatistics(statsObj);
- }
-
- @Override
- public boolean updatePartitionColumnStatistics(ColumnStatistics statsObj,
- List<String> partVals)
- throws NoSuchObjectException, MetaException, InvalidObjectException,
- InvalidInputException {
- return objectStore.updatePartitionColumnStatistics(statsObj, partVals);
- }
-
- @Override
- public boolean addToken(String tokenIdentifier, String delegationToken) {
- return false;
- }
-
- @Override
- public boolean removeToken(String tokenIdentifier) {
- return false;
- }
-
- @Override
- public String getToken(String tokenIdentifier) {
- return "";
- }
-
- @Override
- public List<String> getAllTokenIdentifiers() {
- return new ArrayList<String>();
- }
-
- @Override
- public int addMasterKey(String key) throws MetaException {
- return -1;
- }
-
- @Override
- public void updateMasterKey(Integer seqNo, String key)
- throws NoSuchObjectException, MetaException {}
-
- @Override
- public boolean removeMasterKey(Integer keySeq) {
- return false;
- }
-
- @Override
- public String[] getMasterKeys() {
- return new String[0];
- }
-
- @Override
- public void verifySchema() throws MetaException {
- }
-
- @Override
- public String getMetaStoreSchemaVersion() throws MetaException {
- return objectStore.getMetaStoreSchemaVersion();
- }
-
- @Override
- public void setMetaStoreSchemaVersion(String schemaVersion, String comment) throws MetaException {
- objectStore.setMetaStoreSchemaVersion(schemaVersion, comment);
-
- }
-
- @Override
- public List<ColumnStatistics> getPartitionColumnStatistics(String dbName,
- String tblName, List<String> colNames, List<String> partNames)
- throws MetaException, NoSuchObjectException {
- return objectStore.getPartitionColumnStatistics(dbName, tblName , colNames, partNames);
- }
-
- @Override
- public boolean doesPartitionExist(String dbName, String tableName,
- List<String> partVals) throws MetaException, NoSuchObjectException {
- return objectStore.doesPartitionExist(dbName, tableName, partVals);
- }
-
- @Override
- public boolean addPartitions(String dbName, String tblName, List<Partition> parts)
- throws InvalidObjectException, MetaException {
- return objectStore.addPartitions(dbName, tblName, parts);
- }
-
- @Override
- public boolean addPartitions(String dbName, String tblName, PartitionSpecProxy partitionSpec, boolean ifNotExists) throws InvalidObjectException, MetaException {
- return false;
- }
-
- @Override
- public void dropPartitions(String dbName, String tblName, List<String> partNames)
- throws MetaException, NoSuchObjectException {
- objectStore.dropPartitions(dbName, tblName, partNames);
- }
-
- @Override
- public void createFunction(Function func) throws InvalidObjectException,
- MetaException {
- objectStore.createFunction(func);
- }
-
- @Override
- public void alterFunction(String dbName, String funcName, Function newFunction)
- throws InvalidObjectException, MetaException {
- objectStore.alterFunction(dbName, funcName, newFunction);
- }
-
- @Override
- public void dropFunction(String dbName, String funcName)
- throws MetaException, NoSuchObjectException, InvalidObjectException,
- InvalidInputException {
- objectStore.dropFunction(dbName, funcName);
- }
-
- @Override
- public Function getFunction(String dbName, String funcName)
- throws MetaException {
- return objectStore.getFunction(dbName, funcName);
- }
-
- @Override
- public List<Function> getAllFunctions()
- throws MetaException {
- return Collections.emptyList();
- }
-
- @Override
- public List<String> getFunctions(String dbName, String pattern)
- throws MetaException {
- return objectStore.getFunctions(dbName, pattern);
- }
-
- @Override
- public AggrStats get_aggr_stats_for(String dbName,
- String tblName, List<String> partNames, List<String> colNames)
- throws MetaException {
- return null;
- }
-
- @Override
- public NotificationEventResponse getNextNotification(NotificationEventRequest rqst) {
- return objectStore.getNextNotification(rqst);
- }
-
- @Override
- public void addNotificationEvent(NotificationEvent event) {
- objectStore.addNotificationEvent(event);
- }
-
- @Override
- public void cleanNotificationEvents(int olderThan) {
- objectStore.cleanNotificationEvents(olderThan);
- }
-
- @Override
- public CurrentNotificationEventId getCurrentNotificationEventId() {
- return objectStore.getCurrentNotificationEventId();
- }
-
- @Override
- public NotificationEventsCountResponse getNotificationEventsCount(NotificationEventsCountRequest rqst) {
- return objectStore.getNotificationEventsCount(rqst);
- }
-
- @Override
- public void flushCache() {
- objectStore.flushCache();
- }
-
- @Override
- public ByteBuffer[] getFileMetadata(List<Long> fileIds) {
- return null;
- }
-
- @Override
- public void putFileMetadata(
- List<Long> fileIds, List<ByteBuffer> metadata, FileMetadataExprType type) {
- }
-
- @Override
- public boolean isFileMetadataSupported() {
- return false;
- }
-
-
- @Override
- public void getFileMetadataByExpr(List<Long> fileIds, FileMetadataExprType type, byte[] expr,
- ByteBuffer[] metadatas, ByteBuffer[] stripeBitsets, boolean[] eliminated) {
- }
-
- @Override
- public int getTableCount() throws MetaException {
- return objectStore.getTableCount();
- }
-
- @Override
- public int getPartitionCount() throws MetaException {
- return objectStore.getPartitionCount();
- }
-
- @Override
- public int getDatabaseCount() throws MetaException {
- return objectStore.getDatabaseCount();
- }
-
- @Override
- public FileMetadataHandler getFileMetadataHandler(FileMetadataExprType type) {
- return null;
- }
-
- @Override
- public List<SQLPrimaryKey> getPrimaryKeys(String db_name, String tbl_name)
- throws MetaException {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public List<SQLForeignKey> getForeignKeys(String parent_db_name,
- String parent_tbl_name, String foreign_db_name, String foreign_tbl_name)
- throws MetaException {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public List<SQLUniqueConstraint> getUniqueConstraints(String db_name, String tbl_name)
- throws MetaException {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public List<SQLNotNullConstraint> getNotNullConstraints(String db_name, String tbl_name)
- throws MetaException {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public List<String> createTableWithConstraints(Table tbl,
- List<SQLPrimaryKey> primaryKeys, List<SQLForeignKey> foreignKeys,
- List<SQLUniqueConstraint> uniqueConstraints,
- List<SQLNotNullConstraint> notNullConstraints)
- throws InvalidObjectException, MetaException {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public void dropConstraint(String dbName, String tableName,
- String constraintName) throws NoSuchObjectException {
- // TODO Auto-generated method stub
- }
-
- @Override
- public List<String> addPrimaryKeys(List<SQLPrimaryKey> pks)
- throws InvalidObjectException, MetaException {
- return null;
- }
-
- @Override
- public List<String> addForeignKeys(List<SQLForeignKey> fks)
- throws InvalidObjectException, MetaException {
- return null;
- }
-
- @Override
- public List<String> addUniqueConstraints(List<SQLUniqueConstraint> uks)
- throws InvalidObjectException, MetaException {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public List<String> addNotNullConstraints(List<SQLNotNullConstraint> nns)
- throws InvalidObjectException, MetaException {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Map<String, List<ColumnStatisticsObj>> getColStatsForTablePartitions(String dbName,
- String tableName) throws MetaException, NoSuchObjectException {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public String getMetastoreDbUuid() throws MetaException {
- throw new MetaException("Get metastore uuid is not implemented");
- }
-
- @Override
- public void createResourcePlan(WMResourcePlan resourcePlan)
- throws AlreadyExistsException, MetaException {
- objectStore.createResourcePlan(resourcePlan);
- }
-
- @Override
- public WMResourcePlan getResourcePlan(String name) throws NoSuchObjectException {
- return objectStore.getResourcePlan(name);
- }
-
- @Override
- public List<WMResourcePlan> getAllResourcePlans() throws MetaException {
- return objectStore.getAllResourcePlans();
- }
-
- @Override
- public void alterResourcePlan(String name, WMResourcePlan resourcePlan)
- throws AlreadyExistsException, NoSuchObjectException, InvalidOperationException,
- MetaException {
- objectStore.alterResourcePlan(name, resourcePlan);
- }
-
- @Override
- public boolean validateResourcePlan(String name)
- throws NoSuchObjectException, InvalidObjectException, MetaException {
- return objectStore.validateResourcePlan(name);
- }
-
- @Override
- public void dropResourcePlan(String name) throws NoSuchObjectException, MetaException {
- objectStore.dropResourcePlan(name);
- }
-
- @Override
- public void createWMTrigger(WMTrigger trigger)
- throws AlreadyExistsException, MetaException, NoSuchObjectException,
- InvalidOperationException {
- objectStore.createWMTrigger(trigger);
- }
-
- @Override
- public void alterWMTrigger(WMTrigger trigger)
- throws NoSuchObjectException, InvalidOperationException, MetaException {
- objectStore.alterWMTrigger(trigger);
- }
-
- @Override
- public void dropWMTrigger(String resourcePlanName, String triggerName)
- throws NoSuchObjectException, InvalidOperationException, MetaException {
- objectStore.dropWMTrigger(resourcePlanName, triggerName);
- }
-
- @Override
- public List<WMTrigger> getTriggersForResourcePlan(String resourcePlanName)
- throws NoSuchObjectException, MetaException {
- return objectStore.getTriggersForResourcePlan(resourcePlanName);
- }
-}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/metastore/src/test/org/apache/hadoop/hive/metastore/InjectableBehaviourObjectStore.java
----------------------------------------------------------------------
diff --git a/metastore/src/test/org/apache/hadoop/hive/metastore/InjectableBehaviourObjectStore.java b/metastore/src/test/org/apache/hadoop/hive/metastore/InjectableBehaviourObjectStore.java
deleted file mode 100644
index d89c54c..0000000
--- a/metastore/src/test/org/apache/hadoop/hive/metastore/InjectableBehaviourObjectStore.java
+++ /dev/null
@@ -1,104 +0,0 @@
-/**
- * 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 java.util.List;
-import org.apache.hadoop.hive.metastore.api.MetaException;
-import org.apache.hadoop.hive.metastore.api.NotificationEventRequest;
-import org.apache.hadoop.hive.metastore.api.NotificationEventResponse;
-import org.apache.hadoop.hive.metastore.api.Table;
-
-import static org.junit.Assert.assertEquals;
-
-
-/**
- * A wrapper around {@link ObjectStore} that allows us to inject custom behaviour
- * on to some of the methods for testing.
- */
-public class InjectableBehaviourObjectStore extends ObjectStore {
- public InjectableBehaviourObjectStore() {
- super();
- }
-
- /**
- * A utility class that allows people injecting behaviour to determine if their injections occurred.
- */
- public static abstract class BehaviourInjection<T,F>
- implements com.google.common.base.Function<T,F>{
- protected boolean injectionPathCalled = false;
- protected boolean nonInjectedPathCalled = false;
-
- public void assertInjectionsPerformed(
- boolean expectedInjectionCalled, boolean expectedNonInjectedPathCalled){
- assertEquals(expectedInjectionCalled, injectionPathCalled);
- assertEquals(expectedNonInjectedPathCalled, nonInjectedPathCalled);
- }
- };
-
- private static com.google.common.base.Function<Table,Table> getTableModifier =
- com.google.common.base.Functions.identity();
- private static com.google.common.base.Function<List<String>, List<String>> listPartitionNamesModifier =
- com.google.common.base.Functions.identity();
- private static com.google.common.base.Function<NotificationEventResponse, NotificationEventResponse>
- getNextNotificationModifier = com.google.common.base.Functions.identity();
-
- // Methods to set/reset getTable modifier
- public static void setGetTableBehaviour(com.google.common.base.Function<Table,Table> modifier){
- getTableModifier = (modifier == null)? com.google.common.base.Functions.identity() : modifier;
- }
-
- public static void resetGetTableBehaviour(){
- setGetTableBehaviour(null);
- }
-
- // Methods to set/reset listPartitionNames modifier
- public static void setListPartitionNamesBehaviour(com.google.common.base.Function<List<String>, List<String>> modifier){
- listPartitionNamesModifier = (modifier == null)? com.google.common.base.Functions.identity() : modifier;
- }
-
- public static void resetListPartitionNamesBehaviour(){
- setListPartitionNamesBehaviour(null);
- }
-
- // Methods to set/reset getNextNotification modifier
- public static void setGetNextNotificationBehaviour(
- com.google.common.base.Function<NotificationEventResponse,NotificationEventResponse> modifier){
- getNextNotificationModifier = (modifier == null)? com.google.common.base.Functions.identity() : modifier;
- }
-
- public static void resetGetNextNotificationBehaviour(){
- setGetNextNotificationBehaviour(null);
- }
-
- // ObjectStore methods to be overridden with injected behavior
- @Override
- public Table getTable(String dbName, String tableName) throws MetaException {
- return getTableModifier.apply(super.getTable(dbName, tableName));
- }
-
- @Override
- public List<String> listPartitionNames(String dbName, String tableName, short max) throws MetaException {
- return listPartitionNamesModifier.apply(super.listPartitionNames(dbName, tableName, max));
- }
-
- @Override
- public NotificationEventResponse getNextNotification(NotificationEventRequest rqst) {
- return getNextNotificationModifier.apply(super.getNextNotification(rqst));
- }
-}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/metastore/src/test/org/apache/hadoop/hive/metastore/IpAddressListener.java
----------------------------------------------------------------------
diff --git a/metastore/src/test/org/apache/hadoop/hive/metastore/IpAddressListener.java b/metastore/src/test/org/apache/hadoop/hive/metastore/IpAddressListener.java
deleted file mode 100644
index e40edca..0000000
--- a/metastore/src/test/org/apache/hadoop/hive/metastore/IpAddressListener.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/**
- * 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 java.net.InetAddress;
-import java.net.UnknownHostException;
-
-import junit.framework.Assert;
-
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.hive.metastore.HiveMetaStore.HMSHandler;
-import org.apache.hadoop.hive.metastore.api.MetaException;
-import org.apache.hadoop.hive.metastore.events.AddPartitionEvent;
-import org.apache.hadoop.hive.metastore.events.AlterPartitionEvent;
-import org.apache.hadoop.hive.metastore.events.AlterTableEvent;
-import org.apache.hadoop.hive.metastore.events.CreateDatabaseEvent;
-import org.apache.hadoop.hive.metastore.events.CreateTableEvent;
-import org.apache.hadoop.hive.metastore.events.DropDatabaseEvent;
-import org.apache.hadoop.hive.metastore.events.DropPartitionEvent;
-import org.apache.hadoop.hive.metastore.events.DropTableEvent;
-import org.apache.hadoop.hive.metastore.events.LoadPartitionDoneEvent;
-
-/** An implementation for MetaStoreEventListener which checks that the IP Address stored in
- * HMSHandler matches that of local host, for testing purposes.
- */
-public class IpAddressListener extends MetaStoreEventListener{
-
- private static final String LOCAL_HOST = "localhost";
-
- public IpAddressListener(Configuration config) {
- super(config);
- }
-
- private void checkIpAddress() {
- try {
- String localhostIp = InetAddress.getByName(LOCAL_HOST).getHostAddress();
- Assert.assertEquals(localhostIp, HMSHandler.getThreadLocalIpAddress());
- } catch (UnknownHostException e) {
- Assert.assertTrue("InetAddress.getLocalHost threw an exception: " + e.getMessage(), false);
- }
- }
-
- @Override
- public void onAddPartition(AddPartitionEvent partition) throws MetaException {
- checkIpAddress();
- }
-
- @Override
- public void onCreateDatabase(CreateDatabaseEvent db) throws MetaException {
- checkIpAddress();
- }
-
- @Override
- public void onCreateTable(CreateTableEvent table) throws MetaException {
- checkIpAddress();
- }
-
- @Override
- public void onDropDatabase(DropDatabaseEvent db) throws MetaException {
- checkIpAddress();
- }
-
- @Override
- public void onDropPartition(DropPartitionEvent partition) throws MetaException {
- checkIpAddress();
- }
-
- @Override
- public void onDropTable(DropTableEvent table) throws MetaException {
- checkIpAddress();
- }
-
- @Override
- public void onAlterTable(AlterTableEvent event) throws MetaException {
- checkIpAddress();
- }
-
- @Override
- public void onAlterPartition(AlterPartitionEvent event) throws MetaException {
- checkIpAddress();
- }
-
- @Override
- public void onLoadPartitionDone(LoadPartitionDoneEvent partEvent) throws MetaException {
- checkIpAddress();
- }
-}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/metastore/src/test/org/apache/hadoop/hive/metastore/MetaStoreTestUtils.java
----------------------------------------------------------------------
diff --git a/metastore/src/test/org/apache/hadoop/hive/metastore/MetaStoreTestUtils.java b/metastore/src/test/org/apache/hadoop/hive/metastore/MetaStoreTestUtils.java
deleted file mode 100644
index 78ccf9f..0000000
--- a/metastore/src/test/org/apache/hadoop/hive/metastore/MetaStoreTestUtils.java
+++ /dev/null
@@ -1,164 +0,0 @@
-/**
- * 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 java.io.IOException;
-import java.net.InetSocketAddress;
-import java.net.ServerSocket;
-import java.net.Socket;
-import java.util.Map;
-
-import org.apache.hadoop.hive.conf.HiveConf;
-import org.apache.hadoop.hive.metastore.HiveMetaStore.HMSHandler;
-import org.apache.hadoop.hive.metastore.security.HadoopThriftAuthBridge;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class MetaStoreTestUtils {
-
- private static final Logger LOG = LoggerFactory.getLogger("hive.log");
-
- public static int startMetaStore() throws Exception {
- return MetaStoreTestUtils.startMetaStore(HadoopThriftAuthBridge.getBridge(), null);
- }
-
- public static int startMetaStore(final HadoopThriftAuthBridge bridge, HiveConf conf) throws Exception {
- int port = MetaStoreTestUtils.findFreePort();
- MetaStoreTestUtils.startMetaStore(port, bridge, conf);
- return port;
- }
-
- public static int startMetaStore(HiveConf conf) throws Exception {
- return startMetaStore(HadoopThriftAuthBridge.getBridge(), conf);
- }
-
- public static void startMetaStore(final int port, final HadoopThriftAuthBridge bridge) throws Exception {
- MetaStoreTestUtils.startMetaStore(port, bridge, null);
- }
-
- public static void startMetaStore(final int port,
- final HadoopThriftAuthBridge bridge, HiveConf hiveConf)
- throws Exception{
- if (hiveConf == null) {
- hiveConf = new HiveConf(HMSHandler.class);
- }
- final HiveConf 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();
- MetaStoreTestUtils.loopUntilHMSReady(port);
- }
-
- /**
- * A simple connect test to make sure that the metastore is up
- * @throws Exception
- */
- public static void loopUntilHMSReady(int port) throws Exception {
- int retries = 0;
- Exception exc = null;
- 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(MetaStoreTestUtils.getAllThreadStacksAsString());
- throw exc;
- }
-
- public 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());
- MetaStoreTestUtils.addStackString(entry.getValue(), sb);
- }
- return sb.toString();
- }
-
- public 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();
- }
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/metastore/src/test/org/apache/hadoop/hive/metastore/MockPartitionExpressionForMetastore.java
----------------------------------------------------------------------
diff --git a/metastore/src/test/org/apache/hadoop/hive/metastore/MockPartitionExpressionForMetastore.java b/metastore/src/test/org/apache/hadoop/hive/metastore/MockPartitionExpressionForMetastore.java
deleted file mode 100644
index 12a862d..0000000
--- a/metastore/src/test/org/apache/hadoop/hive/metastore/MockPartitionExpressionForMetastore.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/**
- * 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 org.apache.hadoop.hive.metastore.api.FieldSchema;
-import org.apache.hadoop.hive.metastore.api.FileMetadataExprType;
-import org.apache.hadoop.hive.metastore.api.MetaException;
-import org.apache.hadoop.hive.ql.io.sarg.SearchArgument;
-import org.apache.hadoop.hive.serde2.typeinfo.PrimitiveTypeInfo;
-
-import java.util.List;
-
-/**
- * Test Mock-out for PartitionExpressionForMetastore.
- */
-public class MockPartitionExpressionForMetastore implements PartitionExpressionProxy {
- @Override
- public String convertExprToFilter(byte[] expr) throws MetaException {
- return null;
- }
-
- @Override
- public boolean filterPartitionsByExpr(List<FieldSchema> partColumns,
- byte[] expr, String defaultPartitionName,
- List<String> partitionNames) throws MetaException {
- return false;
- }
-
- @Override
- public FileMetadataExprType getMetadataType(String inputFormat) {
- return null;
- }
-
- @Override
- public SearchArgument createSarg(byte[] expr) {
- return null;
- }
-
- @Override
- public FileFormatProxy getFileFormatProxy(FileMetadataExprType type) {
- return null;
- }
-}
[09/12] hive git commit: HIVE-17980 Moved HiveMetaStoreClient plus a
few remaining classes.
Posted by ga...@apache.org.
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/metastore/src/java/org/apache/hadoop/hive/metastore/MetaStoreUtils.java
----------------------------------------------------------------------
diff --git a/metastore/src/java/org/apache/hadoop/hive/metastore/MetaStoreUtils.java b/metastore/src/java/org/apache/hadoop/hive/metastore/MetaStoreUtils.java
deleted file mode 100644
index 939ae21..0000000
--- a/metastore/src/java/org/apache/hadoop/hive/metastore/MetaStoreUtils.java
+++ /dev/null
@@ -1,1092 +0,0 @@
-/**
- * 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 java.io.IOException;
-import java.lang.reflect.Constructor;
-import java.net.InetSocketAddress;
-import java.net.ServerSocket;
-import java.net.Socket;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Properties;
-import java.util.Set;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import org.apache.commons.lang.StringUtils;
-import org.apache.hadoop.hive.metastore.security.HadoopThriftAuthBridge;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
-import org.apache.hadoop.fs.FileStatus;
-import org.apache.hadoop.fs.FileSystem;
-import org.apache.hadoop.fs.Path;
-import org.apache.hadoop.fs.PathFilter;
-import org.apache.hadoop.hive.common.JavaUtils;
-import org.apache.hadoop.hive.conf.HiveConf;
-import org.apache.hadoop.hive.metastore.HiveMetaStore.HMSHandler;
-import org.apache.hadoop.hive.metastore.api.EnvironmentContext;
-import org.apache.hadoop.hive.metastore.api.FieldSchema;
-import org.apache.hadoop.hive.metastore.api.MetaException;
-import org.apache.hadoop.hive.metastore.api.Partition;
-import org.apache.hadoop.hive.metastore.api.Table;
-import org.apache.hadoop.hive.metastore.api.hive_metastoreConstants;
-import org.apache.hadoop.hive.serde.serdeConstants;
-import org.apache.hadoop.hive.serde2.Deserializer;
-import org.apache.hadoop.hive.serde2.SerDeException;
-import org.apache.hadoop.hive.serde2.SerDeUtils;
-import org.apache.hadoop.hive.serde2.objectinspector.ListObjectInspector;
-import org.apache.hadoop.hive.serde2.objectinspector.MapObjectInspector;
-import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
-import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector.Category;
-import org.apache.hadoop.hive.serde2.objectinspector.StructField;
-import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
-import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
-import org.apache.hadoop.security.SaslRpcServer;
-import org.apache.hive.common.util.ReflectionUtil;
-
-public class MetaStoreUtils {
-
- private static final Logger LOG = LoggerFactory.getLogger("hive.log");
-
- // Right now we only support one special character '/'.
- // More special characters can be added accordingly in the future.
- // NOTE:
- // If the following array is updated, please also be sure to update the
- // configuration parameter documentation
- // HIVE_SUPPORT_SPECICAL_CHARACTERS_IN_TABLE_NAMES in HiveConf as well.
- public static final char[] specialCharactersInTableNames = new char[] { '/' };
-
- public static void populateQuickStats(FileStatus[] fileStatus, Map<String, String> params) {
- org.apache.hadoop.hive.metastore.utils.MetaStoreUtils.populateQuickStats(fileStatus, params);
- }
-
- public static boolean updateTableStatsFast(Table tbl, FileStatus[] fileStatus, boolean newDir,
- boolean forceRecompute, EnvironmentContext environmentContext) throws MetaException {
- return org.apache.hadoop.hive.metastore.utils.MetaStoreUtils.updateTableStatsFast(
- tbl, fileStatus, newDir, forceRecompute, environmentContext);
- }
-
- public static boolean updatePartitionStatsFast(Partition part, Warehouse wh, EnvironmentContext environmentContext)
- throws MetaException {
- return org.apache.hadoop.hive.metastore.utils.MetaStoreUtils.updatePartitionStatsFast(
- part, wh, environmentContext);
- }
-
- /**
- * getDeserializer
- *
- * Get the Deserializer for a table.
- *
- * @param conf
- * - hadoop config
- * @param table
- * the table
- * @return
- * Returns instantiated deserializer by looking up class name of deserializer stored in
- * storage descriptor of passed in table. Also, initializes the deserializer with schema
- * of table.
- * @exception MetaException
- * if any problems instantiating the Deserializer
- *
- * todo - this should move somewhere into serde.jar
- *
- */
- static public Deserializer getDeserializer(Configuration conf,
- org.apache.hadoop.hive.metastore.api.Table table, boolean skipConfError) throws
- MetaException {
- String lib = table.getSd().getSerdeInfo().getSerializationLib();
- if (lib == null) {
- return null;
- }
- return getDeserializer(conf, table, skipConfError, lib);
- }
-
- public static Deserializer getDeserializer(Configuration conf,
- org.apache.hadoop.hive.metastore.api.Table table, boolean skipConfError,
- String lib) throws MetaException {
- try {
- Deserializer deserializer = ReflectionUtil.newInstance(conf.getClassByName(lib).
- asSubclass(Deserializer.class), conf);
- if (skipConfError) {
- SerDeUtils.initializeSerDeWithoutErrorCheck(deserializer, conf,
- MetaStoreUtils.getTableMetadata(table), null);
- } else {
- SerDeUtils.initializeSerDe(deserializer, conf, MetaStoreUtils.getTableMetadata(table), null);
- }
- return deserializer;
- } catch (RuntimeException e) {
- throw e;
- } catch (Throwable e) {
- LOG.error("error in initSerDe: " + e.getClass().getName() + " "
- + e.getMessage(), e);
- throw new MetaException(e.getClass().getName() + " " + e.getMessage());
- }
- }
-
- public static Class<? extends Deserializer> getDeserializerClass(
- Configuration conf, org.apache.hadoop.hive.metastore.api.Table table) throws Exception {
- String lib = table.getSd().getSerdeInfo().getSerializationLib();
- return lib == null ? null : conf.getClassByName(lib).asSubclass(Deserializer.class);
- }
-
- /**
- * getDeserializer
- *
- * Get the Deserializer for a partition.
- *
- * @param conf
- * - hadoop config
- * @param part
- * the partition
- * @param table the table
- * @return
- * Returns instantiated deserializer by looking up class name of deserializer stored in
- * storage descriptor of passed in partition. Also, initializes the deserializer with
- * schema of partition.
- * @exception MetaException
- * if any problems instantiating the Deserializer
- *
- */
- static public Deserializer getDeserializer(Configuration conf,
- org.apache.hadoop.hive.metastore.api.Partition part,
- org.apache.hadoop.hive.metastore.api.Table table) throws MetaException {
- String lib = part.getSd().getSerdeInfo().getSerializationLib();
- try {
- Deserializer deserializer = ReflectionUtil.newInstance(conf.getClassByName(lib).
- asSubclass(Deserializer.class), conf);
- SerDeUtils.initializeSerDe(deserializer, conf, MetaStoreUtils.getTableMetadata(table),
- MetaStoreUtils.getPartitionMetadata(part, table));
- return deserializer;
- } catch (RuntimeException e) {
- throw e;
- } catch (Throwable e) {
- LOG.error("error in initSerDe: " + e.getClass().getName() + " "
- + e.getMessage(), e);
- throw new MetaException(e.getClass().getName() + " " + e.getMessage());
- }
- }
-
- /**
- * Given a list of partition columns and a partial mapping from
- * some partition columns to values the function returns the values
- * for the column.
- * @param partCols the list of table partition columns
- * @param partSpec the partial mapping from partition column to values
- * @return list of values of for given partition columns, any missing
- * values in partSpec is replaced by an empty string
- */
- public static List<String> getPvals(List<FieldSchema> partCols,
- Map<String, String> partSpec) {
- List<String> pvals = new ArrayList<String>(partCols.size());
- for (FieldSchema field : partCols) {
- String val = StringUtils.defaultString(partSpec.get(field.getName()));
- pvals.add(val);
- }
- return pvals;
- }
-
- /**
- * validateName
- *
- * Checks the name conforms to our standars which are: "[a-zA-z_0-9]+". checks
- * this is just characters and numbers and _
- *
- * @param name
- * the name to validate
- * @param conf
- * hive configuration
- * @return true or false depending on conformance
- * if it doesn't match the pattern.
- */
- static public boolean validateName(String name, Configuration conf) {
- Pattern tpat = null;
- String allowedCharacters = "\\w_";
- if (conf != null
- && HiveConf.getBoolVar(conf,
- HiveConf.ConfVars.HIVE_SUPPORT_SPECICAL_CHARACTERS_IN_TABLE_NAMES)) {
- for (Character c : specialCharactersInTableNames) {
- allowedCharacters += c;
- }
- }
- tpat = Pattern.compile("[" + allowedCharacters + "]+");
- Matcher m = tpat.matcher(name);
- return m.matches();
- }
-
- /*
- * At the Metadata level there are no restrictions on Column Names.
- */
- public static boolean validateColumnName(String name) {
- return true;
- }
-
- public static final String TYPE_FROM_DESERIALIZER = "<derived from deserializer>";
-
- public static String getListType(String t) {
- return "array<" + t + ">";
- }
-
- static HashMap<String, String> typeToThriftTypeMap;
- static {
- typeToThriftTypeMap = new HashMap<String, String>();
- typeToThriftTypeMap.put(
- org.apache.hadoop.hive.serde.serdeConstants.BOOLEAN_TYPE_NAME, "bool");
- typeToThriftTypeMap.put(
- org.apache.hadoop.hive.serde.serdeConstants.TINYINT_TYPE_NAME, "byte");
- typeToThriftTypeMap.put(
- org.apache.hadoop.hive.serde.serdeConstants.SMALLINT_TYPE_NAME, "i16");
- typeToThriftTypeMap.put(
- org.apache.hadoop.hive.serde.serdeConstants.INT_TYPE_NAME, "i32");
- typeToThriftTypeMap.put(
- org.apache.hadoop.hive.serde.serdeConstants.BIGINT_TYPE_NAME, "i64");
- typeToThriftTypeMap.put(
- org.apache.hadoop.hive.serde.serdeConstants.DOUBLE_TYPE_NAME, "double");
- typeToThriftTypeMap.put(
- org.apache.hadoop.hive.serde.serdeConstants.FLOAT_TYPE_NAME, "float");
- typeToThriftTypeMap.put(
- org.apache.hadoop.hive.serde.serdeConstants.LIST_TYPE_NAME, "list");
- typeToThriftTypeMap.put(
- org.apache.hadoop.hive.serde.serdeConstants.MAP_TYPE_NAME, "map");
- typeToThriftTypeMap.put(
- org.apache.hadoop.hive.serde.serdeConstants.STRING_TYPE_NAME, "string");
- typeToThriftTypeMap.put(
- org.apache.hadoop.hive.serde.serdeConstants.BINARY_TYPE_NAME, "binary");
- // These 4 types are not supported yet.
- // We should define a complex type date in thrift that contains a single int
- // member, and DynamicSerDe
- // should convert it to date type at runtime.
- typeToThriftTypeMap.put(
- org.apache.hadoop.hive.serde.serdeConstants.DATE_TYPE_NAME, "date");
- typeToThriftTypeMap.put(
- org.apache.hadoop.hive.serde.serdeConstants.DATETIME_TYPE_NAME, "datetime");
- typeToThriftTypeMap
- .put(org.apache.hadoop.hive.serde.serdeConstants.TIMESTAMP_TYPE_NAME,
- "timestamp");
- typeToThriftTypeMap.put(
- org.apache.hadoop.hive.serde.serdeConstants.DECIMAL_TYPE_NAME, "decimal");
- typeToThriftTypeMap.put(
- org.apache.hadoop.hive.serde.serdeConstants.INTERVAL_YEAR_MONTH_TYPE_NAME,
- org.apache.hadoop.hive.serde.serdeConstants.INTERVAL_YEAR_MONTH_TYPE_NAME);
- typeToThriftTypeMap.put(
- org.apache.hadoop.hive.serde.serdeConstants.INTERVAL_DAY_TIME_TYPE_NAME,
- org.apache.hadoop.hive.serde.serdeConstants.INTERVAL_DAY_TIME_TYPE_NAME);
- }
-
- private static Set<String> hiveThriftTypeMap; //for validation
- static {
- hiveThriftTypeMap = new HashSet<String>();
- hiveThriftTypeMap.addAll(serdeConstants.PrimitiveTypes);
- hiveThriftTypeMap.addAll(org.apache.hadoop.hive.serde.serdeConstants.CollectionTypes);
- hiveThriftTypeMap.add(org.apache.hadoop.hive.serde.serdeConstants.UNION_TYPE_NAME);
- hiveThriftTypeMap.add(org.apache.hadoop.hive.serde.serdeConstants.STRUCT_TYPE_NAME);
- }
-
- /**
- * Convert type to ThriftType. We do that by tokenizing the type and convert
- * each token.
- */
- public static String typeToThriftType(String type) {
- StringBuilder thriftType = new StringBuilder();
- int last = 0;
- boolean lastAlphaDigit = Character.isLetterOrDigit(type.charAt(last));
- for (int i = 1; i <= type.length(); i++) {
- if (i == type.length()
- || Character.isLetterOrDigit(type.charAt(i)) != lastAlphaDigit) {
- String token = type.substring(last, i);
- last = i;
- String thriftToken = typeToThriftTypeMap.get(token);
- thriftType.append(thriftToken == null ? token : thriftToken);
- lastAlphaDigit = !lastAlphaDigit;
- }
- }
- return thriftType.toString();
- }
-
- /**
- * Convert FieldSchemas to Thrift DDL.
- */
- public static String getDDLFromFieldSchema(String structName,
- List<FieldSchema> fieldSchemas) {
- StringBuilder ddl = new StringBuilder();
- ddl.append("struct ");
- ddl.append(structName);
- ddl.append(" { ");
- boolean first = true;
- for (FieldSchema col : fieldSchemas) {
- if (first) {
- first = false;
- } else {
- ddl.append(", ");
- }
- ddl.append(typeToThriftType(col.getType()));
- ddl.append(' ');
- ddl.append(col.getName());
- }
- ddl.append("}");
-
- LOG.trace("DDL: {}", ddl);
- return ddl.toString();
- }
-
- public static Properties getTableMetadata(
- org.apache.hadoop.hive.metastore.api.Table table) {
- return MetaStoreUtils.getSchema(table.getSd(), table.getSd(), table
- .getParameters(), table.getDbName(), table.getTableName(), table.getPartitionKeys());
- }
-
- public static Properties getPartitionMetadata(
- org.apache.hadoop.hive.metastore.api.Partition partition,
- org.apache.hadoop.hive.metastore.api.Table table) {
- return MetaStoreUtils
- .getSchema(partition.getSd(), partition.getSd(), partition
- .getParameters(), table.getDbName(), table.getTableName(),
- table.getPartitionKeys());
- }
-
- public static Properties getSchema(
- org.apache.hadoop.hive.metastore.api.Partition part,
- org.apache.hadoop.hive.metastore.api.Table table) {
- return MetaStoreUtils.getSchema(part.getSd(), table.getSd(), table
- .getParameters(), table.getDbName(), table.getTableName(), table.getPartitionKeys());
- }
-
- /**
- * Get partition level schema from table level schema.
- * This function will use the same column names, column types and partition keys for
- * each partition Properties. Their values are copied from the table Properties. This
- * is mainly to save CPU and memory. CPU is saved because the first time the
- * StorageDescriptor column names are accessed, JDO needs to execute a SQL query to
- * retrieve the data. If we know the data will be the same as the table level schema
- * and they are immutable, we should just reuse the table level schema objects.
- *
- * @param sd The Partition level Storage Descriptor.
- * @param tblsd The Table level Storage Descriptor.
- * @param parameters partition level parameters
- * @param databaseName DB name
- * @param tableName table name
- * @param partitionKeys partition columns
- * @param tblSchema The table level schema from which this partition should be copied.
- * @return the properties
- */
- public static Properties getPartSchemaFromTableSchema(
- org.apache.hadoop.hive.metastore.api.StorageDescriptor sd,
- org.apache.hadoop.hive.metastore.api.StorageDescriptor tblsd,
- Map<String, String> parameters, String databaseName, String tableName,
- List<FieldSchema> partitionKeys,
- Properties tblSchema) {
-
- // Inherent most properties from table level schema and overwrite some properties
- // in the following code.
- // This is mainly for saving CPU and memory to reuse the column names, types and
- // partition columns in the table level schema.
- Properties schema = (Properties) tblSchema.clone();
-
- // InputFormat
- String inputFormat = sd.getInputFormat();
- if (inputFormat == null || inputFormat.length() == 0) {
- String tblInput =
- schema.getProperty(org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.FILE_INPUT_FORMAT);
- if (tblInput == null) {
- inputFormat = org.apache.hadoop.mapred.SequenceFileInputFormat.class.getName();
- } else {
- inputFormat = tblInput;
- }
- }
- schema.setProperty(org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.FILE_INPUT_FORMAT,
- inputFormat);
-
- // OutputFormat
- String outputFormat = sd.getOutputFormat();
- if (outputFormat == null || outputFormat.length() == 0) {
- String tblOutput =
- schema.getProperty(org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.FILE_OUTPUT_FORMAT);
- if (tblOutput == null) {
- outputFormat = org.apache.hadoop.mapred.SequenceFileOutputFormat.class.getName();
- } else {
- outputFormat = tblOutput;
- }
- }
- schema.setProperty(org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.FILE_OUTPUT_FORMAT,
- outputFormat);
-
- // Location
- if (sd.getLocation() != null) {
- schema.setProperty(org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.META_TABLE_LOCATION,
- sd.getLocation());
- }
-
- // Bucket count
- schema.setProperty(org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.BUCKET_COUNT,
- Integer.toString(sd.getNumBuckets()));
-
- if (sd.getBucketCols() != null && sd.getBucketCols().size() > 0) {
- schema.setProperty(org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.BUCKET_FIELD_NAME,
- sd.getBucketCols().get(0));
- }
-
- // SerdeInfo
- if (sd.getSerdeInfo() != null) {
-
- // We should not update the following 3 values if SerDeInfo contains these.
- // This is to keep backward compatible with getSchema(), where these 3 keys
- // are updated after SerDeInfo properties got copied.
- String cols = org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.META_TABLE_COLUMNS;
- String colTypes = org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.META_TABLE_COLUMN_TYPES;
- String parts = org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.META_TABLE_PARTITION_COLUMNS;
-
- for (Map.Entry<String,String> param : sd.getSerdeInfo().getParameters().entrySet()) {
- String key = param.getKey();
- if (schema.get(key) != null &&
- (key.equals(cols) || key.equals(colTypes) || key.equals(parts))) {
- continue;
- }
- schema.put(key, (param.getValue() != null) ? param.getValue() : StringUtils.EMPTY);
- }
-
- if (sd.getSerdeInfo().getSerializationLib() != null) {
- schema.setProperty(org.apache.hadoop.hive.serde.serdeConstants.SERIALIZATION_LIB,
- sd.getSerdeInfo().getSerializationLib());
- }
- }
-
- // skipping columns since partition level field schemas are the same as table level's
- // skipping partition keys since it is the same as table level partition keys
-
- if (parameters != null) {
- for (Entry<String, String> e : parameters.entrySet()) {
- schema.setProperty(e.getKey(), e.getValue());
- }
- }
-
- return schema;
- }
-
- public static Properties addCols(Properties schema, List<FieldSchema> cols) {
-
- StringBuilder colNameBuf = new StringBuilder();
- StringBuilder colTypeBuf = new StringBuilder();
- StringBuilder colComment = new StringBuilder();
-
- boolean first = true;
- String columnNameDelimiter = getColumnNameDelimiter(cols);
- for (FieldSchema col : cols) {
- if (!first) {
- colNameBuf.append(columnNameDelimiter);
- colTypeBuf.append(":");
- colComment.append('\0');
- }
- colNameBuf.append(col.getName());
- colTypeBuf.append(col.getType());
- colComment.append((null != col.getComment()) ? col.getComment() : StringUtils.EMPTY);
- first = false;
- }
- schema.setProperty(
- org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.META_TABLE_COLUMNS,
- colNameBuf.toString());
- schema.setProperty(serdeConstants.COLUMN_NAME_DELIMITER, columnNameDelimiter);
- String colTypes = colTypeBuf.toString();
- schema.setProperty(
- org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.META_TABLE_COLUMN_TYPES,
- colTypes);
- schema.setProperty("columns.comments", colComment.toString());
-
- return schema;
-
- }
-
- public static Properties getSchemaWithoutCols(org.apache.hadoop.hive.metastore.api.StorageDescriptor sd,
- org.apache.hadoop.hive.metastore.api.StorageDescriptor tblsd,
- Map<String, String> parameters, String databaseName, String tableName,
- List<FieldSchema> partitionKeys) {
- Properties schema = new Properties();
- String inputFormat = sd.getInputFormat();
- if (inputFormat == null || inputFormat.length() == 0) {
- inputFormat = org.apache.hadoop.mapred.SequenceFileInputFormat.class
- .getName();
- }
- schema.setProperty(
- org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.FILE_INPUT_FORMAT,
- inputFormat);
- String outputFormat = sd.getOutputFormat();
- if (outputFormat == null || outputFormat.length() == 0) {
- outputFormat = org.apache.hadoop.mapred.SequenceFileOutputFormat.class
- .getName();
- }
- schema.setProperty(
- org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.FILE_OUTPUT_FORMAT,
- outputFormat);
-
- schema.setProperty(
- org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.META_TABLE_NAME,
- databaseName + "." + tableName);
-
- if (sd.getLocation() != null) {
- schema.setProperty(
- org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.META_TABLE_LOCATION,
- sd.getLocation());
- }
- schema.setProperty(
- org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.BUCKET_COUNT, Integer
- .toString(sd.getNumBuckets()));
- if (sd.getBucketCols() != null && sd.getBucketCols().size() > 0) {
- schema.setProperty(
- org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.BUCKET_FIELD_NAME, sd
- .getBucketCols().get(0));
- }
- if (sd.getSerdeInfo() != null) {
- for (Map.Entry<String,String> param : sd.getSerdeInfo().getParameters().entrySet()) {
- schema.put(param.getKey(), (param.getValue() != null) ? param.getValue() : StringUtils.EMPTY);
- }
-
- if (sd.getSerdeInfo().getSerializationLib() != null) {
- schema.setProperty(
- org.apache.hadoop.hive.serde.serdeConstants.SERIALIZATION_LIB, sd
- .getSerdeInfo().getSerializationLib());
- }
- }
-
- if (sd.getCols() != null) {
- schema.setProperty(
- org.apache.hadoop.hive.serde.serdeConstants.SERIALIZATION_DDL,
- getDDLFromFieldSchema(tableName, sd.getCols()));
- }
-
- String partString = StringUtils.EMPTY;
- String partStringSep = StringUtils.EMPTY;
- String partTypesString = StringUtils.EMPTY;
- String partTypesStringSep = StringUtils.EMPTY;
- for (FieldSchema partKey : partitionKeys) {
- partString = partString.concat(partStringSep);
- partString = partString.concat(partKey.getName());
- partTypesString = partTypesString.concat(partTypesStringSep);
- partTypesString = partTypesString.concat(partKey.getType());
- if (partStringSep.length() == 0) {
- partStringSep = "/";
- partTypesStringSep = ":";
- }
- }
- if (partString.length() > 0) {
- schema
- .setProperty(
- org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.META_TABLE_PARTITION_COLUMNS,
- partString);
- schema
- .setProperty(
- org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.META_TABLE_PARTITION_COLUMN_TYPES,
- partTypesString);
- }
-
- if (parameters != null) {
- for (Entry<String, String> e : parameters.entrySet()) {
- // add non-null parameters to the schema
- if ( e.getValue() != null) {
- schema.setProperty(e.getKey(), e.getValue());
- }
- }
- }
-
- return schema;
- }
-
- public static Properties getSchema(
- org.apache.hadoop.hive.metastore.api.StorageDescriptor sd,
- org.apache.hadoop.hive.metastore.api.StorageDescriptor tblsd,
- Map<String, String> parameters, String databaseName, String tableName,
- List<FieldSchema> partitionKeys) {
-
- return addCols(getSchemaWithoutCols(sd, tblsd, parameters, databaseName, tableName, partitionKeys), tblsd.getCols());
- }
-
- public static String getColumnNameDelimiter(List<FieldSchema> fieldSchemas) {
- // we first take a look if any fieldSchemas contain COMMA
- for (int i = 0; i < fieldSchemas.size(); i++) {
- if (fieldSchemas.get(i).getName().contains(",")) {
- return String.valueOf(SerDeUtils.COLUMN_COMMENTS_DELIMITER);
- }
- }
- return String.valueOf(SerDeUtils.COMMA);
- }
-
- /**
- * Convert FieldSchemas to columnNames.
- */
- public static String getColumnNamesFromFieldSchema(List<FieldSchema> fieldSchemas) {
- String delimiter = getColumnNameDelimiter(fieldSchemas);
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < fieldSchemas.size(); i++) {
- if (i > 0) {
- sb.append(delimiter);
- }
- sb.append(fieldSchemas.get(i).getName());
- }
- return sb.toString();
- }
-
- /**
- * Convert FieldSchemas to columnTypes.
- */
- public static String getColumnTypesFromFieldSchema(
- List<FieldSchema> fieldSchemas) {
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < fieldSchemas.size(); i++) {
- if (i > 0) {
- sb.append(",");
- }
- sb.append(fieldSchemas.get(i).getType());
- }
- return sb.toString();
- }
-
- public static String getColumnCommentsFromFieldSchema(List<FieldSchema> fieldSchemas) {
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < fieldSchemas.size(); i++) {
- if (i > 0) {
- sb.append(SerDeUtils.COLUMN_COMMENTS_DELIMITER);
- }
- sb.append(fieldSchemas.get(i).getComment());
- }
- return sb.toString();
- }
-
- public static int startMetaStore() throws Exception {
- return startMetaStore(HadoopThriftAuthBridge.getBridge(), null);
- }
-
- public static int startMetaStore(final HadoopThriftAuthBridge bridge, HiveConf conf) throws Exception {
- int port = findFreePort();
- startMetaStore(port, bridge, conf);
- return port;
- }
-
- public static int startMetaStore(HiveConf 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, HiveConf hiveConf)
- throws Exception{
- if (hiveConf == null) {
- hiveConf = new HiveConf(HMSHandler.class);
- }
- final HiveConf 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 = null;
- 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();
- }
- }
- }
-
- /**
- * Catches exceptions that can't be handled and bundles them to MetaException
- *
- * @param e
- * @throws MetaException
- */
- static void logAndThrowMetaException(Exception e) throws MetaException {
- String exInfo = "Got exception: " + e.getClass().getName() + " "
- + e.getMessage();
- LOG.error(exInfo, e);
- LOG.error("Converting exception to MetaException");
- throw new MetaException(exInfo);
- }
-
- /**
- * @param tableName
- * @param deserializer
- * @return the list of fields
- * @throws SerDeException
- * @throws MetaException
- */
- public static List<FieldSchema> getFieldsFromDeserializer(String tableName,
- Deserializer deserializer) throws SerDeException, MetaException {
- ObjectInspector oi = deserializer.getObjectInspector();
- String[] names = tableName.split("\\.");
- String last_name = names[names.length - 1];
- for (int i = 1; i < names.length; i++) {
-
- if (oi instanceof StructObjectInspector) {
- StructObjectInspector soi = (StructObjectInspector) oi;
- StructField sf = soi.getStructFieldRef(names[i]);
- if (sf == null) {
- throw new MetaException("Invalid Field " + names[i]);
- } else {
- oi = sf.getFieldObjectInspector();
- }
- } else if (oi instanceof ListObjectInspector
- && names[i].equalsIgnoreCase("$elem$")) {
- ListObjectInspector loi = (ListObjectInspector) oi;
- oi = loi.getListElementObjectInspector();
- } else if (oi instanceof MapObjectInspector
- && names[i].equalsIgnoreCase("$key$")) {
- MapObjectInspector moi = (MapObjectInspector) oi;
- oi = moi.getMapKeyObjectInspector();
- } else if (oi instanceof MapObjectInspector
- && names[i].equalsIgnoreCase("$value$")) {
- MapObjectInspector moi = (MapObjectInspector) oi;
- oi = moi.getMapValueObjectInspector();
- } else {
- throw new MetaException("Unknown type for " + names[i]);
- }
- }
-
- ArrayList<FieldSchema> str_fields = new ArrayList<FieldSchema>();
- // rules on how to recurse the ObjectInspector based on its type
- if (oi.getCategory() != Category.STRUCT) {
- str_fields.add(new FieldSchema(last_name, oi.getTypeName(),
- FROM_SERIALIZER));
- } else {
- List<? extends StructField> fields = ((StructObjectInspector) oi)
- .getAllStructFieldRefs();
- for (int i = 0; i < fields.size(); i++) {
- StructField structField = fields.get(i);
- String fieldName = structField.getFieldName();
- String fieldTypeName = structField.getFieldObjectInspector().getTypeName();
- String fieldComment = determineFieldComment(structField.getFieldComment());
-
- str_fields.add(new FieldSchema(fieldName, fieldTypeName, fieldComment));
- }
- }
- return str_fields;
- }
-
- private static final String FROM_SERIALIZER = "from deserializer";
- private static String determineFieldComment(String comment) {
- return (comment == null) ? FROM_SERIALIZER : comment;
- }
-
- /**
- * Convert TypeInfo to FieldSchema.
- */
- public static FieldSchema getFieldSchemaFromTypeInfo(String fieldName,
- TypeInfo typeInfo) {
- return new FieldSchema(fieldName, typeInfo.getTypeName(),
- "generated by TypeInfoUtils.getFieldSchemaFromTypeInfo");
- }
-
- /**
- * Determines whether a table is an external table.
- *
- * @param table table of interest
- *
- * @return true if external
- */
- public static boolean isExternalTable(Table table) {
- if (table == null) {
- return false;
- }
- Map<String, String> params = table.getParameters();
- if (params == null) {
- return false;
- }
-
- return "TRUE".equalsIgnoreCase(params.get("EXTERNAL"));
- }
-
- public static boolean isArchived(
- org.apache.hadoop.hive.metastore.api.Partition part) {
- Map<String, String> params = part.getParameters();
- return "TRUE".equalsIgnoreCase(params.get(hive_metastoreConstants.IS_ARCHIVED));
- }
-
- /**
- * Filter that filters out hidden files
- */
- private static final PathFilter hiddenFileFilter = new PathFilter() {
- @Override
- public boolean accept(Path p) {
- String name = p.getName();
- return !name.startsWith("_") && !name.startsWith(".");
- }
- };
-
- /**
- * Utility method that determines if a specified directory already has
- * contents (non-hidden files) or not - useful to determine if an
- * immutable table already has contents, for example.
- *
- * @param path
- * @throws IOException
- */
- public static boolean isDirEmpty(FileSystem fs, Path path) throws IOException {
-
- if (fs.exists(path)) {
- FileStatus[] status = fs.globStatus(new Path(path, "*"), hiddenFileFilter);
- if (status.length > 0) {
- return false;
- }
- }
- return true;
- }
-
- public static String getIndexTableName(String dbName, String baseTblName, String indexName) {
- return dbName + "__" + baseTblName + "_" + indexName + "__";
- }
-
- public static boolean isIndexTable(Table table) {
- if (table == null) {
- return false;
- }
- return TableType.INDEX_TABLE.toString().equals(table.getTableType());
- }
-
- public static boolean isMaterializedViewTable(Table table) {
- if (table == null) {
- return false;
- }
- return TableType.MATERIALIZED_VIEW.toString().equals(table.getTableType());
- }
-
- public static boolean isView(Table table) {
- if (table == null) {
- return false;
- }
- return TableType.VIRTUAL_VIEW.toString().equals(table.getTableType());
- }
-
- @SuppressWarnings("unchecked")
- public static Class<? extends RawStore> getClass(String rawStoreClassName)
- throws MetaException {
- try {
- return (Class<? extends RawStore>)
- Class.forName(rawStoreClassName, true, JavaUtils.getClassLoader());
- } catch (ClassNotFoundException e) {
- throw new MetaException(rawStoreClassName + " class not found");
- }
- }
-
- /**
- * Create an object of the given class.
- * @param theClass
- * @param parameterTypes
- * an array of parameterTypes for the constructor
- * @param initargs
- * the list of arguments for the constructor
- */
- public static <T> T newInstance(Class<T> theClass, Class<?>[] parameterTypes,
- Object[] initargs) {
- // Perform some sanity checks on the arguments.
- if (parameterTypes.length != initargs.length) {
- throw new IllegalArgumentException(
- "Number of constructor parameter types doesn't match number of arguments");
- }
- for (int i = 0; i < parameterTypes.length; i++) {
- Class<?> clazz = parameterTypes[i];
- if (initargs[i] != null && !(clazz.isInstance(initargs[i]))) {
- throw new IllegalArgumentException("Object : " + initargs[i]
- + " is not an instance of " + clazz);
- }
- }
-
- try {
- Constructor<T> meth = theClass.getDeclaredConstructor(parameterTypes);
- meth.setAccessible(true);
- return meth.newInstance(initargs);
- } catch (Exception e) {
- throw new RuntimeException("Unable to instantiate " + theClass.getName(), e);
- }
- }
-
- /**
- * @param schema1: The first schema to be compared
- * @param schema2: The second schema to be compared
- * @return true if the two schemas are the same else false
- * for comparing a field we ignore the comment it has
- */
- public static boolean compareFieldColumns(List<FieldSchema> schema1, List<FieldSchema> schema2) {
- if (schema1.size() != schema2.size()) {
- return false;
- }
- Iterator<FieldSchema> its1 = schema1.iterator();
- Iterator<FieldSchema> its2 = schema2.iterator();
- while (its1.hasNext()) {
- FieldSchema f1 = its1.next();
- FieldSchema f2 = its2.next();
- // The default equals provided by thrift compares the comments too for
- // equality, thus we need to compare the relevant fields here.
- if (!StringUtils.equals(f1.getName(), f2.getName()) ||
- !StringUtils.equals(f1.getType(), f2.getType())) {
- return false;
- }
- }
- return true;
- }
-
- /**
- * Read and return the meta store Sasl configuration. Currently it uses the default
- * Hadoop SASL configuration and can be configured using "hadoop.rpc.protection"
- * HADOOP-10211, made a backward incompatible change due to which this call doesn't
- * work with Hadoop 2.4.0 and later.
- * @param conf
- * @return The SASL configuration
- */
- public static Map<String, String> getMetaStoreSaslProperties(HiveConf conf, boolean useSSL) {
- // As of now Hive Meta Store uses the same configuration as Hadoop SASL configuration
-
- // If SSL is enabled, override the given value of "hadoop.rpc.protection" and set it to "authentication"
- // This disables any encryption provided by SASL, since SSL already provides it
- String hadoopRpcProtectionVal = conf.get(CommonConfigurationKeysPublic.HADOOP_RPC_PROTECTION);
- String hadoopRpcProtectionAuth = SaslRpcServer.QualityOfProtection.AUTHENTICATION.toString();
-
- if (useSSL && hadoopRpcProtectionVal != null && !hadoopRpcProtectionVal.equals(hadoopRpcProtectionAuth)) {
- LOG.warn("Overriding value of " + CommonConfigurationKeysPublic.HADOOP_RPC_PROTECTION + " setting it from "
- + hadoopRpcProtectionVal + " to " + hadoopRpcProtectionAuth + " because SSL is enabled");
- conf.set(CommonConfigurationKeysPublic.HADOOP_RPC_PROTECTION, hadoopRpcProtectionAuth);
- }
- return HadoopThriftAuthBridge.getBridge().getHadoopSaslProperties(conf);
- }
-
-
- public static String ARCHIVING_LEVEL = "archiving_level";
- public static int getArchivingLevel(Partition part) throws MetaException {
- if (!isArchived(part)) {
- throw new MetaException("Getting level of unarchived partition");
- }
-
- String lv = part.getParameters().get(ARCHIVING_LEVEL);
- if (lv != null) {
- return Integer.parseInt(lv);
- }
- // partitions archived before introducing multiple archiving
- return part.getValues().size();
- }
-
- public static String[] getQualifiedName(String defaultDbName, String tableName) {
- String[] names = tableName.split("\\.");
- if (names.length == 1) {
- return new String[] { defaultDbName, tableName};
- }
- return names;
- }
-
- public static List<String> getColumnNames(List<FieldSchema> schema) {
- List<String> cols = new ArrayList<>(schema.size());
- for (FieldSchema fs : schema) {
- cols.add(fs.getName());
- }
- return cols;
- }
-}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/metastore/src/java/org/apache/hadoop/hive/metastore/RetryingMetaStoreClient.java
----------------------------------------------------------------------
diff --git a/metastore/src/java/org/apache/hadoop/hive/metastore/RetryingMetaStoreClient.java b/metastore/src/java/org/apache/hadoop/hive/metastore/RetryingMetaStoreClient.java
deleted file mode 100644
index d3e5f7e..0000000
--- a/metastore/src/java/org/apache/hadoop/hive/metastore/RetryingMetaStoreClient.java
+++ /dev/null
@@ -1,286 +0,0 @@
-/**
- * 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 java.io.IOException;
-import java.lang.annotation.Annotation;
-import java.lang.reflect.InvocationHandler;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.lang.reflect.Proxy;
-import java.lang.reflect.UndeclaredThrowableException;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.TimeUnit;
-
-import org.apache.hadoop.hive.common.classification.RetrySemantics;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.hadoop.hive.common.classification.InterfaceAudience.Public;
-import org.apache.hadoop.hive.conf.HiveConf;
-import org.apache.hadoop.hive.metastore.annotation.NoReconnect;
-import org.apache.hadoop.hive.metastore.api.MetaException;
-import org.apache.hadoop.security.UserGroupInformation;
-import org.apache.thrift.TApplicationException;
-import org.apache.thrift.TException;
-import org.apache.thrift.protocol.TProtocolException;
-import org.apache.thrift.transport.TTransportException;
-
-import com.google.common.annotations.VisibleForTesting;
-
-/**
- * RetryingMetaStoreClient. Creates a proxy for a IMetaStoreClient
- * implementation and retries calls to it on failure.
- * If the login user is authenticated using keytab, it relogins user before
- * each call.
- *
- */
-@Public
-public class RetryingMetaStoreClient implements InvocationHandler {
-
- private static final Logger LOG = LoggerFactory.getLogger(RetryingMetaStoreClient.class.getName());
-
- private final IMetaStoreClient base;
- private final int retryLimit;
- private final long retryDelaySeconds;
- private final ConcurrentHashMap<String, Long> metaCallTimeMap;
- private final long connectionLifeTimeInMillis;
- private long lastConnectionTime;
- private boolean localMetaStore;
-
-
- protected RetryingMetaStoreClient(HiveConf hiveConf, Class<?>[] constructorArgTypes,
- Object[] constructorArgs, ConcurrentHashMap<String, Long> metaCallTimeMap,
- Class<? extends IMetaStoreClient> msClientClass) throws MetaException {
-
- this.retryLimit = hiveConf.getIntVar(HiveConf.ConfVars.METASTORETHRIFTFAILURERETRIES);
- this.retryDelaySeconds = hiveConf.getTimeVar(
- HiveConf.ConfVars.METASTORE_CLIENT_CONNECT_RETRY_DELAY, TimeUnit.SECONDS);
- this.metaCallTimeMap = metaCallTimeMap;
- this.connectionLifeTimeInMillis = hiveConf.getTimeVar(
- HiveConf.ConfVars.METASTORE_CLIENT_SOCKET_LIFETIME, TimeUnit.MILLISECONDS);
- this.lastConnectionTime = System.currentTimeMillis();
- String msUri = hiveConf.getVar(HiveConf.ConfVars.METASTOREURIS);
- localMetaStore = (msUri == null) || msUri.trim().isEmpty();
-
- reloginExpiringKeytabUser();
- this.base = (IMetaStoreClient) MetaStoreUtils.newInstance(
- msClientClass, constructorArgTypes, constructorArgs);
- }
-
- public static IMetaStoreClient getProxy(
- HiveConf hiveConf, boolean allowEmbedded) throws MetaException {
- return getProxy(hiveConf, new Class[]{HiveConf.class, HiveMetaHookLoader.class, Boolean.class},
- new Object[]{hiveConf, null, allowEmbedded}, null, HiveMetaStoreClient.class.getName()
- );
- }
-
- @VisibleForTesting
- public static IMetaStoreClient getProxy(HiveConf hiveConf, HiveMetaHookLoader hookLoader,
- String mscClassName) throws MetaException {
- return getProxy(hiveConf, hookLoader, null, mscClassName, true);
- }
-
- public static IMetaStoreClient getProxy(HiveConf hiveConf, HiveMetaHookLoader hookLoader,
- ConcurrentHashMap<String, Long> metaCallTimeMap, String mscClassName, boolean allowEmbedded)
- throws MetaException {
-
- return getProxy(hiveConf,
- new Class[] {HiveConf.class, HiveMetaHookLoader.class, Boolean.class},
- new Object[] {hiveConf, hookLoader, allowEmbedded},
- metaCallTimeMap,
- mscClassName
- );
- }
-
- /**
- * This constructor is meant for Hive internal use only.
- * Please use getProxy(HiveConf hiveConf, HiveMetaHookLoader hookLoader) for external purpose.
- */
- public static IMetaStoreClient getProxy(HiveConf hiveConf, Class<?>[] constructorArgTypes,
- Object[] constructorArgs, String mscClassName) throws MetaException {
- return getProxy(hiveConf, constructorArgTypes, constructorArgs, null, mscClassName);
- }
-
- /**
- * This constructor is meant for Hive internal use only.
- * Please use getProxy(HiveConf hiveConf, HiveMetaHookLoader hookLoader) for external purpose.
- */
- public static IMetaStoreClient getProxy(HiveConf hiveConf, Class<?>[] constructorArgTypes,
- Object[] constructorArgs, ConcurrentHashMap<String, Long> metaCallTimeMap,
- String mscClassName) throws MetaException {
-
- @SuppressWarnings("unchecked")
- Class<? extends IMetaStoreClient> baseClass =
- (Class<? extends IMetaStoreClient>)MetaStoreUtils.getClass(mscClassName);
-
- RetryingMetaStoreClient handler =
- new RetryingMetaStoreClient(hiveConf, constructorArgTypes, constructorArgs,
- metaCallTimeMap, baseClass);
- return (IMetaStoreClient) Proxy.newProxyInstance(
- RetryingMetaStoreClient.class.getClassLoader(), baseClass.getInterfaces(), handler);
- }
-
- @Override
- public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
- Object ret = null;
- int retriesMade = 0;
- TException caughtException = null;
-
- boolean allowReconnect = ! method.isAnnotationPresent(NoReconnect.class);
- boolean allowRetry = true;
- Annotation[] directives = method.getDeclaredAnnotations();
- if(directives != null) {
- for(Annotation a : directives) {
- if(a instanceof RetrySemantics.CannotRetry) {
- allowRetry = false;
- }
- }
- }
-
- while (true) {
- try {
- reloginExpiringKeytabUser();
-
- if (allowReconnect) {
- if (retriesMade > 0 || hasConnectionLifeTimeReached(method)) {
- base.reconnect();
- lastConnectionTime = System.currentTimeMillis();
- }
- }
-
- if (metaCallTimeMap == null) {
- ret = method.invoke(base, args);
- } else {
- // need to capture the timing
- long startTime = System.currentTimeMillis();
- ret = method.invoke(base, args);
- long timeTaken = System.currentTimeMillis() - startTime;
- addMethodTime(method, timeTaken);
- }
- break;
- } catch (UndeclaredThrowableException e) {
- throw e.getCause();
- } catch (InvocationTargetException e) {
- Throwable t = e.getCause();
- if (t instanceof TApplicationException) {
- TApplicationException tae = (TApplicationException)t;
- switch (tae.getType()) {
- case TApplicationException.UNSUPPORTED_CLIENT_TYPE:
- case TApplicationException.UNKNOWN_METHOD:
- case TApplicationException.WRONG_METHOD_NAME:
- case TApplicationException.INVALID_PROTOCOL:
- throw t;
- default:
- // TODO: most other options are probably unrecoverable... throw?
- caughtException = tae;
- }
- } else if ((t instanceof TProtocolException) || (t instanceof TTransportException)) {
- // TODO: most protocol exceptions are probably unrecoverable... throw?
- caughtException = (TException)t;
- } else if ((t instanceof MetaException) && t.getMessage().matches(
- "(?s).*(JDO[a-zA-Z]*|TProtocol|TTransport)Exception.*") &&
- !t.getMessage().contains("java.sql.SQLIntegrityConstraintViolationException")) {
- caughtException = (MetaException)t;
- } else {
- throw t;
- }
- } catch (MetaException e) {
- if (e.getMessage().matches("(?s).*(IO|TTransport)Exception.*") &&
- !e.getMessage().contains("java.sql.SQLIntegrityConstraintViolationException")) {
- caughtException = e;
- } else {
- throw e;
- }
- }
-
-
- if (retriesMade >= retryLimit || base.isLocalMetaStore() || !allowRetry) {
- throw caughtException;
- }
- retriesMade++;
- LOG.warn("MetaStoreClient lost connection. Attempting to reconnect (" + retriesMade + " of " +
- retryLimit + ") after " + retryDelaySeconds + "s. " + method.getName(), caughtException);
- Thread.sleep(retryDelaySeconds * 1000);
- }
- return ret;
- }
-
- private void addMethodTime(Method method, long timeTaken) {
- String methodStr = getMethodString(method);
- while (true) {
- Long curTime = metaCallTimeMap.get(methodStr), newTime = timeTaken;
- if (curTime != null && metaCallTimeMap.replace(methodStr, curTime, newTime + curTime)) break;
- if (curTime == null && (null == metaCallTimeMap.putIfAbsent(methodStr, newTime))) break;
- }
- }
-
- /**
- * @param method
- * @return String representation with arg types. eg getDatabase_(String, )
- */
- private String getMethodString(Method method) {
- StringBuilder methodSb = new StringBuilder(method.getName());
- methodSb.append("_(");
- for (Class<?> paramClass : method.getParameterTypes()) {
- methodSb.append(paramClass.getSimpleName());
- methodSb.append(", ");
- }
- methodSb.append(")");
- return methodSb.toString();
- }
-
- private boolean hasConnectionLifeTimeReached(Method method) {
- if (connectionLifeTimeInMillis <= 0 || localMetaStore) {
- return false;
- }
-
- boolean shouldReconnect =
- (System.currentTimeMillis() - lastConnectionTime) >= connectionLifeTimeInMillis;
- if (LOG.isDebugEnabled()) {
- LOG.debug("Reconnection status for Method: " + method.getName() + " is " + shouldReconnect);
- }
- return shouldReconnect;
- }
-
- /**
- * Relogin if login user is logged in using keytab
- * Relogin is actually done by ugi code only if sufficient time has passed
- * A no-op if kerberos security is not enabled
- * @throws MetaException
- */
- private void reloginExpiringKeytabUser() throws MetaException {
- if(!UserGroupInformation.isSecurityEnabled()){
- return;
- }
- try {
- UserGroupInformation ugi = UserGroupInformation.getLoginUser();
- //checkTGT calls ugi.relogin only after checking if it is close to tgt expiry
- //hadoop relogin is actually done only every x minutes (x=10 in hadoop 1.x)
- if(ugi.isFromKeytab()){
- ugi.checkTGTAndReloginFromKeytab();
- }
- } catch (IOException e) {
- String msg = "Error doing relogin using keytab " + e.getMessage();
- LOG.error(msg, e);
- throw new MetaException(msg);
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/metastore/src/java/org/apache/hadoop/hive/metastore/SerDeStorageSchemaReader.java
----------------------------------------------------------------------
diff --git a/metastore/src/java/org/apache/hadoop/hive/metastore/SerDeStorageSchemaReader.java b/metastore/src/java/org/apache/hadoop/hive/metastore/SerDeStorageSchemaReader.java
index 80fae28..59bcd5c 100644
--- a/metastore/src/java/org/apache/hadoop/hive/metastore/SerDeStorageSchemaReader.java
+++ b/metastore/src/java/org/apache/hadoop/hive/metastore/SerDeStorageSchemaReader.java
@@ -44,8 +44,8 @@ public class SerDeStorageSchemaReader implements StorageSchemaReader {
}
}
- Deserializer s = MetaStoreUtils.getDeserializer(conf, tbl, false);
- return MetaStoreUtils.getFieldsFromDeserializer(tbl.getTableName(), s);
+ Deserializer s = HiveMetaStoreUtils.getDeserializer(conf, tbl, false);
+ return HiveMetaStoreUtils.getFieldsFromDeserializer(tbl.getTableName(), s);
} catch (Exception e) {
StringUtils.stringifyException(e);
throw new MetaException(e.getMessage());
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/metastore/src/java/org/apache/hadoop/hive/metastore/messaging/EventUtils.java
----------------------------------------------------------------------
diff --git a/metastore/src/java/org/apache/hadoop/hive/metastore/messaging/EventUtils.java b/metastore/src/java/org/apache/hadoop/hive/metastore/messaging/EventUtils.java
deleted file mode 100644
index 8f90c7a..0000000
--- a/metastore/src/java/org/apache/hadoop/hive/metastore/messaging/EventUtils.java
+++ /dev/null
@@ -1,202 +0,0 @@
-/**
- * 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.messaging;
-
-import org.apache.hadoop.hive.conf.HiveConf;
-import org.apache.hadoop.hive.metastore.IMetaStoreClient;
-import org.apache.hadoop.hive.metastore.api.NotificationEvent;
-import org.apache.hadoop.hive.metastore.api.NotificationEventsCountRequest;
-import org.apache.hadoop.hive.metastore.messaging.event.filters.DatabaseAndTableFilter;
-import org.apache.thrift.TException;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-public class EventUtils {
-
- public interface NotificationFetcher {
- int getBatchSize() throws IOException;
- long getCurrentNotificationEventId() throws IOException;
- long getDbNotificationEventsCount(long fromEventId, String dbName) throws IOException;
- List<NotificationEvent> getNextNotificationEvents(
- long pos, IMetaStoreClient.NotificationFilter filter) throws IOException;
- }
-
- // MetaStoreClient-based impl of NotificationFetcher
- public static class MSClientNotificationFetcher implements NotificationFetcher{
-
- private IMetaStoreClient msc = null;
- private Integer batchSize = null;
-
- public MSClientNotificationFetcher(IMetaStoreClient msc){
- this.msc = msc;
- }
-
- @Override
- public int getBatchSize() throws IOException {
- if (batchSize == null){
- try {
- batchSize = Integer.parseInt(
- msc.getConfigValue(HiveConf.ConfVars.METASTORE_BATCH_RETRIEVE_MAX.varname, "50"));
- // TODO: we're asking the metastore what its configuration for this var is - we may
- // want to revisit to pull from client side instead. The reason I have it this way
- // is because the metastore is more likely to have a reasonable config for this than
- // an arbitrary client.
- } catch (TException e) {
- throw new IOException(e);
- }
- }
- return batchSize;
- }
-
- @Override
- public long getCurrentNotificationEventId() throws IOException {
- try {
- return msc.getCurrentNotificationEventId().getEventId();
- } catch (TException e) {
- throw new IOException(e);
- }
- }
-
- @Override
- public long getDbNotificationEventsCount(long fromEventId, String dbName) throws IOException {
- try {
- NotificationEventsCountRequest rqst
- = new NotificationEventsCountRequest(fromEventId, dbName);
- return msc.getNotificationEventsCount(rqst).getEventsCount();
- } catch (TException e) {
- throw new IOException(e);
- }
- }
-
- @Override
- public List<NotificationEvent> getNextNotificationEvents(
- long pos, IMetaStoreClient.NotificationFilter filter) throws IOException {
- try {
- return msc.getNextNotification(pos,getBatchSize(), filter).getEvents();
- } catch (TException e) {
- throw new IOException(e);
- }
- }
- }
-
- public static class NotificationEventIterator implements Iterator<NotificationEvent> {
-
- private NotificationFetcher nfetcher;
- private IMetaStoreClient.NotificationFilter filter;
- private int maxEvents;
-
- private Iterator<NotificationEvent> batchIter = null;
- private List<NotificationEvent> batch = null;
- private long pos;
- private long maxPos;
- private int eventCount;
-
- public NotificationEventIterator(
- NotificationFetcher nfetcher, long eventFrom, int maxEvents,
- String dbName, String tableName) throws IOException {
- init(nfetcher, eventFrom, maxEvents, new DatabaseAndTableFilter(dbName, tableName));
- // using init(..) instead of this(..) because the EventUtils.getDbTblNotificationFilter
- // is an operation that needs to run before delegating to the other ctor, and this messes up chaining
- // ctors
- }
-
- public NotificationEventIterator(
- NotificationFetcher nfetcher, long eventFrom, int maxEvents,
- IMetaStoreClient.NotificationFilter filter) throws IOException {
- init(nfetcher,eventFrom,maxEvents,filter);
- }
-
- private void init(
- NotificationFetcher nfetcher, long eventFrom, int maxEvents,
- IMetaStoreClient.NotificationFilter filter) throws IOException {
- this.nfetcher = nfetcher;
- this.filter = filter;
- this.pos = eventFrom;
- if (maxEvents < 1){
- // 0 or -1 implies fetch everything
- this.maxEvents = Integer.MAX_VALUE;
- } else {
- this.maxEvents = maxEvents;
- }
-
- this.eventCount = 0;
- this.maxPos = nfetcher.getCurrentNotificationEventId();
- }
-
- private void fetchNextBatch() throws IOException {
- batch = nfetcher.getNextNotificationEvents(pos, filter);
- int batchSize = nfetcher.getBatchSize();
- while ( ((batch == null) || (batch.isEmpty())) && (pos < maxPos) ){
- // no valid events this batch, but we're still not done processing events
- pos += batchSize;
- batch = nfetcher.getNextNotificationEvents(pos,filter);
- }
-
- if (batch == null){
- batch = new ArrayList<NotificationEvent>();
- // instantiate empty list so that we don't error out on iterator fetching.
- // If we're here, then the next check of pos will show our caller that
- // that we've exhausted our event supply
- }
- batchIter = batch.iterator();
- }
-
- @Override
- public boolean hasNext() {
- if (eventCount >= maxEvents){
- // If we've already satisfied the number of events we were supposed to deliver, we end it.
- return false;
- }
- if ((batchIter != null) && (batchIter.hasNext())){
- // If we have a valid batchIter and it has more elements, return them.
- return true;
- }
- // If we're here, we want more events, and either batchIter is null, or batchIter
- // has reached the end of the current batch. Let's fetch the next batch.
- try {
- fetchNextBatch();
- } catch (IOException e) {
- // Regrettable that we have to wrap the IOException into a RuntimeException,
- // but throwing the exception is the appropriate result here, and hasNext()
- // signature will only allow RuntimeExceptions. Iterator.hasNext() really
- // should have allowed IOExceptions
- throw new RuntimeException(e);
- }
- // New batch has been fetched. If it's not empty, we have more elements to process.
- return !batch.isEmpty();
- }
-
- @Override
- public NotificationEvent next() {
- eventCount++;
- NotificationEvent ev = batchIter.next();
- pos = ev.getEventId();
- return ev;
- }
-
- @Override
- public void remove() {
- throw new UnsupportedOperationException("remove() not supported on NotificationEventIterator");
- }
-
- }
-}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/metastore/src/java/org/apache/hadoop/hive/metastore/messaging/event/filters/AndFilter.java
----------------------------------------------------------------------
diff --git a/metastore/src/java/org/apache/hadoop/hive/metastore/messaging/event/filters/AndFilter.java b/metastore/src/java/org/apache/hadoop/hive/metastore/messaging/event/filters/AndFilter.java
deleted file mode 100644
index d6429f6..0000000
--- a/metastore/src/java/org/apache/hadoop/hive/metastore/messaging/event/filters/AndFilter.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/**
- * 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.messaging.event.filters;
-
-import org.apache.hadoop.hive.metastore.IMetaStoreClient;
-import org.apache.hadoop.hive.metastore.api.NotificationEvent;
-
-public class AndFilter implements IMetaStoreClient.NotificationFilter {
- final IMetaStoreClient.NotificationFilter[] filters;
-
- public AndFilter(final IMetaStoreClient.NotificationFilter... filters) {
- this.filters = filters;
- }
-
- @Override
- public boolean accept(final NotificationEvent event) {
- for (IMetaStoreClient.NotificationFilter filter : filters) {
- if (!filter.accept(event)) {
- return false;
- }
- }
- return true;
- }
-}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/metastore/src/java/org/apache/hadoop/hive/metastore/messaging/event/filters/BasicFilter.java
----------------------------------------------------------------------
diff --git a/metastore/src/java/org/apache/hadoop/hive/metastore/messaging/event/filters/BasicFilter.java b/metastore/src/java/org/apache/hadoop/hive/metastore/messaging/event/filters/BasicFilter.java
deleted file mode 100644
index 5294063..0000000
--- a/metastore/src/java/org/apache/hadoop/hive/metastore/messaging/event/filters/BasicFilter.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/**
- * 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.messaging.event.filters;
-
-import org.apache.hadoop.hive.metastore.IMetaStoreClient.NotificationFilter;
-import org.apache.hadoop.hive.metastore.api.NotificationEvent;
-
-public abstract class BasicFilter implements NotificationFilter {
- @Override
- public boolean accept(final NotificationEvent event) {
- if (event == null) {
- return false; // get rid of trivial case first, so that we can safely assume non-null
- }
- return shouldAccept(event);
- }
-
- abstract boolean shouldAccept(final NotificationEvent event);
-}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/metastore/src/java/org/apache/hadoop/hive/metastore/messaging/event/filters/DatabaseAndTableFilter.java
----------------------------------------------------------------------
diff --git a/metastore/src/java/org/apache/hadoop/hive/metastore/messaging/event/filters/DatabaseAndTableFilter.java b/metastore/src/java/org/apache/hadoop/hive/metastore/messaging/event/filters/DatabaseAndTableFilter.java
deleted file mode 100644
index 490d3b4..0000000
--- a/metastore/src/java/org/apache/hadoop/hive/metastore/messaging/event/filters/DatabaseAndTableFilter.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/**
- * 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.messaging.event.filters;
-
-import org.apache.hadoop.hive.metastore.api.NotificationEvent;
-
-/**
- * Utility function that constructs a notification filter to match a given db name and/or table name.
- * If dbName == null, fetches all warehouse events.
- * If dnName != null, but tableName == null, fetches all events for the db
- * If dbName != null && tableName != null, fetches all events for the specified table
- */
-public class DatabaseAndTableFilter extends BasicFilter {
- private final String databaseName, tableName;
-
- public DatabaseAndTableFilter(final String databaseName, final String tableName) {
- this.databaseName = databaseName;
- this.tableName = tableName;
- }
-
- @Override
- boolean shouldAccept(final NotificationEvent event) {
- if (databaseName == null) {
- return true; // if our dbName is null, we're interested in all wh events
- }
- if (databaseName.equalsIgnoreCase(event.getDbName())) {
- if ((tableName == null)
- // if our dbName is equal, but tableName is blank, we're interested in this db-level event
- || (tableName.equalsIgnoreCase(event.getTableName()))
- // table level event that matches us
- ) {
- return true;
- }
- }
- return false;
- }
-}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/metastore/src/java/org/apache/hadoop/hive/metastore/messaging/event/filters/EventBoundaryFilter.java
----------------------------------------------------------------------
diff --git a/metastore/src/java/org/apache/hadoop/hive/metastore/messaging/event/filters/EventBoundaryFilter.java b/metastore/src/java/org/apache/hadoop/hive/metastore/messaging/event/filters/EventBoundaryFilter.java
deleted file mode 100644
index 137b4ce..0000000
--- a/metastore/src/java/org/apache/hadoop/hive/metastore/messaging/event/filters/EventBoundaryFilter.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/**
- * 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.messaging.event.filters;
-
-import org.apache.hadoop.hive.metastore.api.NotificationEvent;
-
-public class EventBoundaryFilter extends BasicFilter {
- private final long eventFrom, eventTo;
-
- public EventBoundaryFilter(final long eventFrom, final long eventTo) {
- this.eventFrom = eventFrom;
- this.eventTo = eventTo;
- }
-
- @Override
- boolean shouldAccept(final NotificationEvent event) {
- return eventFrom <= event.getEventId() && event.getEventId() <= eventTo;
- }
-}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/metastore/src/java/org/apache/hadoop/hive/metastore/messaging/event/filters/MessageFormatFilter.java
----------------------------------------------------------------------
diff --git a/metastore/src/java/org/apache/hadoop/hive/metastore/messaging/event/filters/MessageFormatFilter.java b/metastore/src/java/org/apache/hadoop/hive/metastore/messaging/event/filters/MessageFormatFilter.java
deleted file mode 100644
index 4e91ee6..0000000
--- a/metastore/src/java/org/apache/hadoop/hive/metastore/messaging/event/filters/MessageFormatFilter.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/**
- * 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.messaging.event.filters;
-
-import org.apache.hadoop.hive.metastore.api.NotificationEvent;
-
-public class MessageFormatFilter extends BasicFilter {
- private final String format;
-
- public MessageFormatFilter(String format) {
- this.format = format;
- }
-
- @Override
- boolean shouldAccept(final NotificationEvent event) {
- if (format == null) {
- return true; // let's say that passing null in will not do any filtering.
- }
- return format.equalsIgnoreCase(event.getMessageFormat());
- }
-}
[06/12] hive git commit: HIVE-17980 Moved HiveMetaStoreClient plus a
few remaining classes.
Posted by ga...@apache.org.
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/ql/src/java/org/apache/hadoop/hive/ql/parse/LoadSemanticAnalyzer.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/parse/LoadSemanticAnalyzer.java b/ql/src/java/org/apache/hadoop/hive/ql/parse/LoadSemanticAnalyzer.java
index 5f2a34e..cd5581f 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/parse/LoadSemanticAnalyzer.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/parse/LoadSemanticAnalyzer.java
@@ -36,7 +36,6 @@ import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.PathFilter;
import org.apache.hadoop.hive.conf.HiveConf;
-import org.apache.hadoop.hive.metastore.MetaStoreUtils;
import org.apache.hadoop.hive.metastore.TableType;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.ql.ErrorMsg;
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/ql/src/java/org/apache/hadoop/hive/ql/parse/SemanticAnalyzer.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/parse/SemanticAnalyzer.java b/ql/src/java/org/apache/hadoop/hive/ql/parse/SemanticAnalyzer.java
index 549b38d..2ded4b3 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/parse/SemanticAnalyzer.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/parse/SemanticAnalyzer.java
@@ -65,7 +65,6 @@ import org.apache.hadoop.hive.common.StatsSetupConst.StatDB;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.conf.HiveConf.ConfVars;
import org.apache.hadoop.hive.conf.HiveConf.StrictChecks;
-import org.apache.hadoop.hive.metastore.MetaStoreUtils;
import org.apache.hadoop.hive.metastore.TableType;
import org.apache.hadoop.hive.metastore.TransactionalValidationListener;
import org.apache.hadoop.hive.metastore.Warehouse;
@@ -6814,6 +6813,24 @@ public class SemanticAnalyzer extends BaseSemanticAnalyzer {
checkImmutableTable(qb, dest_tab, dest_path, false);
+ // check for partition
+ List<FieldSchema> parts = dest_tab.getPartitionKeys();
+ if (parts != null && parts.size() > 0) { // table is partitioned
+ if (partSpec == null || partSpec.size() == 0) { // user did NOT specify partition
+ throw new SemanticException(generateErrorMessage(
+ qb.getParseInfo().getDestForClause(dest),
+ ErrorMsg.NEED_PARTITION_ERROR.getMsg()));
+ }
+ dpCtx = qbm.getDPCtx(dest);
+ if (dpCtx == null) {
+ dest_tab.validatePartColumnNames(partSpec, false);
+ dpCtx = new DynamicPartitionCtx(dest_tab, partSpec,
+ conf.getVar(HiveConf.ConfVars.DEFAULTPARTITIONNAME),
+ conf.getIntVar(HiveConf.ConfVars.DYNAMICPARTITIONMAXPARTSPERNODE));
+ qbm.setDPCtx(dest, dpCtx);
+ }
+ }
+
// Check for dynamic partitions.
dpCtx = checkDynPart(qb, qbm, dest_tab, partSpec, dest);
if (dpCtx != null && dpCtx.getSPPath() != null) {
@@ -7395,7 +7412,7 @@ public class SemanticAnalyzer extends BaseSemanticAnalyzer {
}
try {
FileSystem fs = dest_path.getFileSystem(conf);
- if (! MetaStoreUtils.isDirEmpty(fs,dest_path)){
+ if (! org.apache.hadoop.hive.metastore.utils.FileUtils.isDirEmpty(fs,dest_path)){
LOG.warn("Attempted write into an immutable table : "
+ dest_tab.getTableName() + " : " + dest_path);
throw new SemanticException(
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/ql/src/java/org/apache/hadoop/hive/ql/plan/CreateTableDesc.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/plan/CreateTableDesc.java b/ql/src/java/org/apache/hadoop/hive/ql/plan/CreateTableDesc.java
index 9e130dc..f6fb42c 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/plan/CreateTableDesc.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/plan/CreateTableDesc.java
@@ -28,7 +28,6 @@ import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.common.StatsSetupConst;
import org.apache.hadoop.hive.conf.HiveConf;
-import org.apache.hadoop.hive.metastore.MetaStoreUtils;
import org.apache.hadoop.hive.metastore.TableType;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.Order;
@@ -36,6 +35,7 @@ import org.apache.hadoop.hive.metastore.api.SQLForeignKey;
import org.apache.hadoop.hive.metastore.api.SQLNotNullConstraint;
import org.apache.hadoop.hive.metastore.api.SQLPrimaryKey;
import org.apache.hadoop.hive.metastore.api.SQLUniqueConstraint;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
import org.apache.hadoop.hive.ql.ErrorMsg;
import org.apache.hadoop.hive.ql.exec.DDLTask;
import org.apache.hadoop.hive.ql.exec.Utilities;
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/ql/src/java/org/apache/hadoop/hive/ql/plan/FileSinkDesc.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/plan/FileSinkDesc.java b/ql/src/java/org/apache/hadoop/hive/ql/plan/FileSinkDesc.java
index 550e6f8..84476d8 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/plan/FileSinkDesc.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/plan/FileSinkDesc.java
@@ -23,7 +23,6 @@ import java.util.List;
import java.util.Objects;
import org.apache.hadoop.fs.Path;
-import org.apache.hadoop.hive.metastore.MetaStoreUtils;
import org.apache.hadoop.hive.ql.io.AcidUtils;
import org.apache.hadoop.hive.ql.metadata.Table;
import org.apache.hadoop.hive.ql.plan.Explain.Level;
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/ql/src/java/org/apache/hadoop/hive/ql/plan/LoadTableDesc.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/plan/LoadTableDesc.java b/ql/src/java/org/apache/hadoop/hive/ql/plan/LoadTableDesc.java
index 1fa7b40..4108b73 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/plan/LoadTableDesc.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/plan/LoadTableDesc.java
@@ -19,7 +19,6 @@
package org.apache.hadoop.hive.ql.plan;
import org.apache.hadoop.fs.Path;
-import org.apache.hadoop.hive.metastore.MetaStoreUtils;
import org.apache.hadoop.hive.ql.exec.Utilities;
import org.apache.hadoop.hive.ql.io.AcidUtils;
import org.apache.hadoop.hive.ql.plan.Explain.Level;
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/ql/src/java/org/apache/hadoop/hive/ql/plan/PartitionDesc.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/plan/PartitionDesc.java b/ql/src/java/org/apache/hadoop/hive/ql/plan/PartitionDesc.java
index bf8ee75..47f20b5 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/plan/PartitionDesc.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/plan/PartitionDesc.java
@@ -31,8 +31,8 @@ import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.common.CopyOnFirstWriteProperties;
import org.apache.hadoop.hive.common.StringInternUtils;
-import org.apache.hadoop.hive.metastore.MetaStoreUtils;
import org.apache.hadoop.hive.metastore.api.hive_metastoreConstants;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
import org.apache.hadoop.hive.ql.exec.Utilities;
import org.apache.hadoop.hive.ql.io.HiveFileFormatUtils;
import org.apache.hadoop.hive.ql.io.HiveOutputFormat;
@@ -87,7 +87,7 @@ public class PartitionDesc implements Serializable, Cloneable {
if (Utilities.isInputFileFormatSelfDescribing(this)) {
// if IF is self describing no need to send column info per partition, since its not used anyway.
Table tbl = part.getTable();
- setProperties(MetaStoreUtils.getSchemaWithoutCols(part.getTPartition().getSd(), part.getTPartition().getSd(),
+ setProperties(MetaStoreUtils.getSchemaWithoutCols(part.getTPartition().getSd(),
part.getParameters(), tbl.getDbName(), tbl.getTableName(), tbl.getPartitionKeys()));
} else {
setProperties(part.getMetadataFromPartitionSchema());
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/ql/src/java/org/apache/hadoop/hive/ql/plan/PlanUtils.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/plan/PlanUtils.java b/ql/src/java/org/apache/hadoop/hive/ql/plan/PlanUtils.java
index 3c1e92a..d9f0bd6 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/plan/PlanUtils.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/plan/PlanUtils.java
@@ -34,9 +34,10 @@ import org.apache.hadoop.hive.common.JavaUtils;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.conf.HiveConf.ConfVars;
import org.apache.hadoop.hive.llap.LlapOutputFormat;
-import org.apache.hadoop.hive.metastore.MetaStoreUtils;
+import org.apache.hadoop.hive.metastore.HiveMetaStoreUtils;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.hive_metastoreConstants;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
import org.apache.hadoop.hive.ql.exec.ColumnInfo;
import org.apache.hadoop.hive.ql.exec.RowSchema;
import org.apache.hadoop.hive.ql.exec.TableScanOperator;
@@ -586,7 +587,7 @@ public final class PlanUtils {
// last one for union column.
List<FieldSchema> schemas = new ArrayList<FieldSchema>(length + 1);
for (int i = 0; i < length; i++) {
- schemas.add(MetaStoreUtils.getFieldSchemaFromTypeInfo(
+ schemas.add(HiveMetaStoreUtils.getFieldSchemaFromTypeInfo(
fieldPrefix + outputColumnNames.get(i), cols.get(i).getTypeInfo()));
}
@@ -603,7 +604,7 @@ public final class PlanUtils {
unionTypes.add(TypeInfoFactory.getStructTypeInfo(names, types));
}
if (outputColumnNames.size() - length > 0) {
- schemas.add(MetaStoreUtils.getFieldSchemaFromTypeInfo(
+ schemas.add(HiveMetaStoreUtils.getFieldSchemaFromTypeInfo(
fieldPrefix + outputColumnNames.get(length),
TypeInfoFactory.getUnionTypeInfo(unionTypes)));
}
@@ -619,7 +620,7 @@ public final class PlanUtils {
String fieldPrefix) {
List<FieldSchema> schemas = new ArrayList<FieldSchema>(cols.size());
for (int i = 0; i < cols.size(); i++) {
- schemas.add(MetaStoreUtils.getFieldSchemaFromTypeInfo(fieldPrefix
+ schemas.add(HiveMetaStoreUtils.getFieldSchemaFromTypeInfo(fieldPrefix
+ outputColumnNames.get(i + start), cols.get(i).getTypeInfo()));
}
return schemas;
@@ -632,7 +633,7 @@ public final class PlanUtils {
List<ExprNodeDesc> cols, String fieldPrefix) {
List<FieldSchema> schemas = new ArrayList<FieldSchema>(cols.size());
for (int i = 0; i < cols.size(); i++) {
- schemas.add(MetaStoreUtils.getFieldSchemaFromTypeInfo(fieldPrefix + i,
+ schemas.add(HiveMetaStoreUtils.getFieldSchemaFromTypeInfo(fieldPrefix + i,
cols.get(i).getTypeInfo()));
}
return schemas;
@@ -662,7 +663,7 @@ public final class PlanUtils {
if (name.equals(String.valueOf(i))) {
name = fieldPrefix + name;
}
- schemas.add(MetaStoreUtils.getFieldSchemaFromTypeInfo(name, cols.get(i)
+ schemas.add(HiveMetaStoreUtils.getFieldSchemaFromTypeInfo(name, cols.get(i)
.getType()));
}
return schemas;
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/ql/src/java/org/apache/hadoop/hive/ql/security/authorization/AuthorizationPreEventListener.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/security/authorization/AuthorizationPreEventListener.java b/ql/src/java/org/apache/hadoop/hive/ql/security/authorization/AuthorizationPreEventListener.java
index 5202571..8569ffb 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/security/authorization/AuthorizationPreEventListener.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/security/authorization/AuthorizationPreEventListener.java
@@ -23,6 +23,7 @@ import java.util.List;
import com.google.common.base.Function;
import com.google.common.collect.Iterators;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.conf.Configuration;
@@ -30,7 +31,6 @@ import org.apache.hadoop.hive.common.classification.InterfaceAudience.Private;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.conf.HiveConf.ConfVars;
import org.apache.hadoop.hive.metastore.MetaStorePreEventListener;
-import org.apache.hadoop.hive.metastore.MetaStoreUtils;
import org.apache.hadoop.hive.metastore.TableType;
import org.apache.hadoop.hive.metastore.api.Database;
import org.apache.hadoop.hive.metastore.api.InvalidOperationException;
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/CompactorMR.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/CompactorMR.java b/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/CompactorMR.java
index 7d4d379..b94e47b 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/CompactorMR.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/CompactorMR.java
@@ -37,7 +37,6 @@ import org.apache.hadoop.hive.common.StringableMap;
import org.apache.hadoop.hive.common.ValidCompactorTxnList;
import org.apache.hadoop.hive.common.ValidTxnList;
import org.apache.hadoop.hive.conf.HiveConf;
-import org.apache.hadoop.hive.metastore.MetaStoreUtils;
import org.apache.hadoop.hive.metastore.api.CompactionType;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/Initiator.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/Initiator.java b/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/Initiator.java
index 8daa5c0..ab3cfc8 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/Initiator.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/Initiator.java
@@ -23,7 +23,6 @@ import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.common.FileUtils;
import org.apache.hadoop.hive.common.ValidTxnList;
import org.apache.hadoop.hive.conf.HiveConf;
-import org.apache.hadoop.hive.metastore.MetaStoreUtils;
import org.apache.hadoop.hive.metastore.api.CompactionRequest;
import org.apache.hadoop.hive.metastore.api.CompactionResponse;
import org.apache.hadoop.hive.metastore.api.CompactionType;
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/ql/src/test/org/apache/hadoop/hive/ql/TestTxnCommands.java
----------------------------------------------------------------------
diff --git a/ql/src/test/org/apache/hadoop/hive/ql/TestTxnCommands.java b/ql/src/test/org/apache/hadoop/hive/ql/TestTxnCommands.java
index 662462c..6d3e156 100644
--- a/ql/src/test/org/apache/hadoop/hive/ql/TestTxnCommands.java
+++ b/ql/src/test/org/apache/hadoop/hive/ql/TestTxnCommands.java
@@ -96,7 +96,7 @@ public class TestTxnCommands extends TxnCommandsBaseForTests {
Path bucket = AcidUtils.createBucketFile(new Path(new Path(getWarehouseDir(), table.toString().toLowerCase()), AcidUtils.deltaSubdir(txnId, txnId, stmtId)), bucketNum);
FileOutputStream delta = new FileOutputStream(testName.getMethodName() + "_" + bucket.getParent().getName() + "_" + bucket.getName());
// try {
-// FileDump.printJsonData(hiveConf, bucket.toString(), delta);
+// FileDump.printJsonData(conf, bucket.toString(), delta);
// }
// catch(FileNotFoundException ex) {
;//this happens if you change BUCKET_COUNT
@@ -351,7 +351,6 @@ public class TestTxnCommands extends TxnCommandsBaseForTests {
hiveConf.setTimeVar(HiveConf.ConfVars.HIVE_TXN_TIMEOUT, 1, TimeUnit.SECONDS);
// Have to reset the conf when we change it so that the change takes affect
houseKeeperService.setConf(hiveConf);
- //hiveConf.setBoolVar(HiveConf.ConfVars.HIVETESTMODEFAILHEARTBEATER, true);
runStatementOnDriver("start transaction");
runStatementOnDriver("select count(*) from " + Table.ACIDTBL + " where a = 17");
pause(750);
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/service/pom.xml
----------------------------------------------------------------------
diff --git a/service/pom.xml b/service/pom.xml
index 412bde5..484230f 100644
--- a/service/pom.xml
+++ b/service/pom.xml
@@ -252,7 +252,7 @@
</dependency>
<dependency>
<groupId>org.apache.hive</groupId>
- <artifactId>hive-metastore</artifactId>
+ <artifactId>hive-standalone-metastore</artifactId>
<version>${project.version}</version>
<type>test-jar</type>
<scope>test</scope>
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/service/src/java/org/apache/hive/service/cli/thrift/EmbeddedThriftBinaryCLIService.java
----------------------------------------------------------------------
diff --git a/service/src/java/org/apache/hive/service/cli/thrift/EmbeddedThriftBinaryCLIService.java b/service/src/java/org/apache/hive/service/cli/thrift/EmbeddedThriftBinaryCLIService.java
index e9a5830..fbfd57a 100644
--- a/service/src/java/org/apache/hive/service/cli/thrift/EmbeddedThriftBinaryCLIService.java
+++ b/service/src/java/org/apache/hive/service/cli/thrift/EmbeddedThriftBinaryCLIService.java
@@ -38,7 +38,7 @@ public class EmbeddedThriftBinaryCLIService extends ThriftBinaryCLIService {
@Override
public synchronized void init(HiveConf hiveConf) {
// Null HiveConf is passed in jdbc driver side code since driver side is supposed to be
- // independent of hiveConf object. Create new HiveConf object here in this case.
+ // independent of conf object. Create new HiveConf object here in this case.
if (hiveConf == null) {
hiveConf = new HiveConf();
}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/service/src/java/org/apache/hive/service/server/HiveServer2.java
----------------------------------------------------------------------
diff --git a/service/src/java/org/apache/hive/service/server/HiveServer2.java b/service/src/java/org/apache/hive/service/server/HiveServer2.java
index 2c4fe7f..285ab02 100644
--- a/service/src/java/org/apache/hive/service/server/HiveServer2.java
+++ b/service/src/java/org/apache/hive/service/server/HiveServer2.java
@@ -63,11 +63,7 @@ import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.conf.HiveConf.ConfVars;
import org.apache.hadoop.hive.llap.coordinator.LlapCoordinator;
import org.apache.hadoop.hive.llap.registry.impl.LlapRegistryService;
-import org.apache.hadoop.hive.metastore.MetaStoreUtils;
-import org.apache.hadoop.hive.metastore.RawStore;
-import org.apache.hadoop.hive.metastore.api.MetaException;
import org.apache.hadoop.hive.metastore.cache.CachedStore;
-import org.apache.hadoop.hive.metastore.conf.MetastoreConf;
import org.apache.hadoop.hive.ql.exec.spark.session.SparkSessionManagerImpl;
import org.apache.hadoop.hive.ql.exec.tez.TezSessionPoolManager;
import org.apache.hadoop.hive.ql.exec.tez.WorkloadManager;
@@ -162,7 +158,7 @@ public class HiveServer2 extends CompositeService {
}
addService(thriftCLIService);
super.init(hiveConf);
- // Set host name in hiveConf
+ // Set host name in conf
try {
hiveConf.set(HiveConf.ConfVars.HIVE_SERVER2_THRIFT_BIND_HOST.varname, getServerHost());
} catch (Throwable t) {
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/service/src/test/org/apache/hive/service/cli/thrift/ThriftCliServiceTestWithCookie.java
----------------------------------------------------------------------
diff --git a/service/src/test/org/apache/hive/service/cli/thrift/ThriftCliServiceTestWithCookie.java b/service/src/test/org/apache/hive/service/cli/thrift/ThriftCliServiceTestWithCookie.java
index 6660097..3aa475f 100644
--- a/service/src/test/org/apache/hive/service/cli/thrift/ThriftCliServiceTestWithCookie.java
+++ b/service/src/test/org/apache/hive/service/cli/thrift/ThriftCliServiceTestWithCookie.java
@@ -32,7 +32,6 @@ import org.apache.hadoop.hive.conf.HiveConf.ConfVars;
import org.apache.hadoop.hive.metastore.MetaStoreTestUtils;
import org.apache.hive.service.Service;
import org.apache.hive.service.auth.HiveAuthConstants;
-import org.apache.hive.service.auth.HiveAuthConstants.AuthTypes;
import org.apache.hive.service.cli.OperationHandle;
import org.apache.hive.service.cli.OperationState;
import org.apache.hive.service.cli.OperationStatus;
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/standalone-metastore/pom.xml
----------------------------------------------------------------------
diff --git a/standalone-metastore/pom.xml b/standalone-metastore/pom.xml
index eee6528..fd834fa 100644
--- a/standalone-metastore/pom.xml
+++ b/standalone-metastore/pom.xml
@@ -190,6 +190,22 @@
</exclusion>
</exclusions>
</dependency>
+ <dependency>
+ <groupId>org.apache.hadoop</groupId>
+ <artifactId>hadoop-mapreduce-client-core</artifactId>
+ <version>${hadoop.version}</version>
+ <optional>true</optional>
+ <exclusions>
+ <exclusion>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-log4j12</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>commmons-logging</groupId>
+ <artifactId>commons-logging</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
<!-- This is our one and only Hive dependency.-->
<dependency>
<groupId>org.apache.hive</groupId>
@@ -472,7 +488,7 @@
<javax.jdo.option.ConnectionURL>jdbc:derby:memory:${test.tmp.dir}/junit_metastore_db;create=true</javax.jdo.option.ConnectionURL>
<metastore.schema.verification>false</metastore.schema.verification>
<test.tmp.dir>${test.tmp.dir}</test.tmp.dir>
- <test.warehouse.dir>${test.warehouse.scheme}${test.warehouse.dir}</test.warehouse.dir>
+ <metastore.warehouse.dir>${test.warehouse.scheme}${test.warehouse.dir}</metastore.warehouse.dir>
</systemPropertyVariables>
<additionalClasspathElements>
<additionalClasspathElement>${log4j.conf.dir}</additionalClasspathElement>
@@ -480,6 +496,17 @@
</configuration>
</plugin>
<plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-jar-plugin</artifactId>
+ <executions>
+ <execution>
+ <goals>
+ <goal>test-jar</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>3.0.0</version>
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/ColumnType.java
----------------------------------------------------------------------
diff --git a/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/ColumnType.java b/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/ColumnType.java
index a41b5ee..d5dea4d 100644
--- a/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/ColumnType.java
+++ b/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/ColumnType.java
@@ -86,8 +86,6 @@ public class ColumnType {
public static final String COLUMN_NAME_DELIMITER = "column.name.delimiter";
- public static final String SERIALIZATION_FORMAT = "serialization.format";
-
public static final Set<String> PrimitiveTypes = StringUtils.asSet(
VOID_TYPE_NAME,
BOOLEAN_TYPE_NAME,
@@ -239,4 +237,65 @@ public class ColumnType {
}
return false;
}
+
+ // These aren't column types, they are info for how things are stored in thrift.
+ // It didn't seem useful to create another Constants class just for these though.
+ public static final String SERIALIZATION_FORMAT = "serialization.format";
+
+ public static final String SERIALIZATION_LIB = "serialization.lib";
+
+ public static final String SERIALIZATION_DDL = "serialization.ddl";
+
+ public static final char COLUMN_COMMENTS_DELIMITER = '\0';
+
+ private static HashMap<String, String> typeToThriftTypeMap;
+ static {
+ typeToThriftTypeMap = new HashMap<>();
+ typeToThriftTypeMap.put(BOOLEAN_TYPE_NAME, "bool");
+ typeToThriftTypeMap.put(TINYINT_TYPE_NAME, "byte");
+ typeToThriftTypeMap.put(SMALLINT_TYPE_NAME, "i16");
+ typeToThriftTypeMap.put(INT_TYPE_NAME, "i32");
+ typeToThriftTypeMap.put(BIGINT_TYPE_NAME, "i64");
+ typeToThriftTypeMap.put(DOUBLE_TYPE_NAME, "double");
+ typeToThriftTypeMap.put(FLOAT_TYPE_NAME, "float");
+ typeToThriftTypeMap.put(LIST_TYPE_NAME, "list");
+ typeToThriftTypeMap.put(MAP_TYPE_NAME, "map");
+ typeToThriftTypeMap.put(STRING_TYPE_NAME, "string");
+ typeToThriftTypeMap.put(BINARY_TYPE_NAME, "binary");
+ // These 4 types are not supported yet.
+ // We should define a complex type date in thrift that contains a single int
+ // member, and DynamicSerDe
+ // should convert it to date type at runtime.
+ typeToThriftTypeMap.put(DATE_TYPE_NAME, "date");
+ typeToThriftTypeMap.put(DATETIME_TYPE_NAME, "datetime");
+ typeToThriftTypeMap.put(TIMESTAMP_TYPE_NAME, "timestamp");
+ typeToThriftTypeMap.put(DECIMAL_TYPE_NAME, "decimal");
+ typeToThriftTypeMap.put(INTERVAL_YEAR_MONTH_TYPE_NAME, INTERVAL_YEAR_MONTH_TYPE_NAME);
+ typeToThriftTypeMap.put(INTERVAL_DAY_TIME_TYPE_NAME, INTERVAL_DAY_TIME_TYPE_NAME);
+ }
+
+ /**
+ * Convert type to ThriftType. We do that by tokenizing the type and convert
+ * each token.
+ */
+ public static String typeToThriftType(String type) {
+ StringBuilder thriftType = new StringBuilder();
+ int last = 0;
+ boolean lastAlphaDigit = Character.isLetterOrDigit(type.charAt(last));
+ for (int i = 1; i <= type.length(); i++) {
+ if (i == type.length()
+ || Character.isLetterOrDigit(type.charAt(i)) != lastAlphaDigit) {
+ String token = type.substring(last, i);
+ last = i;
+ String thriftToken = typeToThriftTypeMap.get(token);
+ thriftType.append(thriftToken == null ? token : thriftToken);
+ lastAlphaDigit = !lastAlphaDigit;
+ }
+ }
+ return thriftType.toString();
+ }
+
+ public static String getListType(String t) {
+ return "array<" + t + ">";
+ }
}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/HiveAlterHandler.java
----------------------------------------------------------------------
diff --git a/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/HiveAlterHandler.java b/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/HiveAlterHandler.java
index ccadac1..03c082c 100644
--- a/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/HiveAlterHandler.java
+++ b/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/HiveAlterHandler.java
@@ -66,19 +66,19 @@ import java.util.Map.Entry;
*/
public class HiveAlterHandler implements AlterHandler {
- protected Configuration hiveConf;
+ protected Configuration conf;
private static final Logger LOG = LoggerFactory.getLogger(HiveAlterHandler.class
.getName());
@Override
public Configuration getConf() {
- return hiveConf;
+ return conf;
}
@Override
@SuppressWarnings("nls")
public void setConf(Configuration conf) {
- hiveConf = conf;
+ this.conf = conf;
}
@Override
@@ -106,7 +106,7 @@ public class HiveAlterHandler implements AlterHandler {
String newTblName = newt.getTableName().toLowerCase();
String newDbName = newt.getDbName().toLowerCase();
- if (!MetaStoreUtils.validateName(newTblName, hiveConf)) {
+ if (!MetaStoreUtils.validateName(newTblName, conf)) {
throw new InvalidOperationException(newTblName + " is not a valid object name");
}
String validate = MetaStoreUtils.validateTblColumns(newt.getSd().getCols());
@@ -155,7 +155,7 @@ public class HiveAlterHandler implements AlterHandler {
// Views derive the column type from the base table definition. So the view definition
// can be altered to change the column types. The column type compatibility checks should
// be done only for non-views.
- if (MetastoreConf.getBoolVar(hiveConf,
+ if (MetastoreConf.getBoolVar(conf,
MetastoreConf.ConfVars.DISALLOW_INCOMPATIBLE_COL_TYPE_CHANGES) &&
!oldt.getTableType().equals(TableType.VIRTUAL_VIEW.toString())) {
// Throws InvalidOperationException if the new column types are not
@@ -276,7 +276,7 @@ public class HiveAlterHandler implements AlterHandler {
}
} else {
// operations other than table rename
- if (MetaStoreUtils.requireCalStats(hiveConf, null, null, newt, environmentContext) &&
+ if (MetaStoreUtils.requireCalStats(null, null, newt, environmentContext) &&
!isPartitionedTable) {
Database db = msdb.getDatabase(newDbName);
// Update table stats. For partitioned table, we update stats in alterPartition()
@@ -422,7 +422,7 @@ public class HiveAlterHandler implements AlterHandler {
try {
msdb.openTransaction();
oldPart = msdb.getPartition(dbname, name, new_part.getValues());
- if (MetaStoreUtils.requireCalStats(hiveConf, oldPart, new_part, tbl, environmentContext)) {
+ if (MetaStoreUtils.requireCalStats(oldPart, new_part, tbl, environmentContext)) {
// if stats are same, no need to update
if (MetaStoreUtils.isFastStatsSame(oldPart, new_part)) {
MetaStoreUtils.updateBasicState(environmentContext, new_part.getParameters());
@@ -555,7 +555,7 @@ public class HiveAlterHandler implements AlterHandler {
new_part.getSd().setLocation(oldPart.getSd().getLocation());
}
- if (MetaStoreUtils.requireCalStats(hiveConf, oldPart, new_part, tbl, environmentContext)) {
+ if (MetaStoreUtils.requireCalStats(oldPart, new_part, tbl, environmentContext)) {
MetaStoreUtils.updatePartitionStatsFast(new_part, wh, false, true, environmentContext);
}
@@ -647,7 +647,7 @@ public class HiveAlterHandler implements AlterHandler {
oldParts.add(oldTmpPart);
partValsList.add(tmpPart.getValues());
- if (MetaStoreUtils.requireCalStats(hiveConf, oldTmpPart, tmpPart, tbl, environmentContext)) {
+ if (MetaStoreUtils.requireCalStats(oldTmpPart, tmpPart, tbl, environmentContext)) {
// Check if stats are same, no need to update
if (MetaStoreUtils.isFastStatsSame(oldTmpPart, tmpPart)) {
MetaStoreUtils.updateBasicState(environmentContext, tmpPart.getParameters());
[02/12] hive git commit: HIVE-17980 Moved HiveMetaStoreClient plus a
few remaining classes.
Posted by ga...@apache.org.
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/DummyRawStoreControlledCommit.java
----------------------------------------------------------------------
diff --git a/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/DummyRawStoreControlledCommit.java b/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/DummyRawStoreControlledCommit.java
new file mode 100644
index 0000000..6c1348f
--- /dev/null
+++ b/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/DummyRawStoreControlledCommit.java
@@ -0,0 +1,999 @@
+/*
+ * 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 java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.hadoop.conf.Configurable;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hive.metastore.api.AggrStats;
+import org.apache.hadoop.hive.metastore.api.AlreadyExistsException;
+import org.apache.hadoop.hive.metastore.api.ColumnStatistics;
+import org.apache.hadoop.hive.metastore.api.ColumnStatisticsObj;
+import org.apache.hadoop.hive.metastore.api.CurrentNotificationEventId;
+import org.apache.hadoop.hive.metastore.api.Database;
+import org.apache.hadoop.hive.metastore.api.FieldSchema;
+import org.apache.hadoop.hive.metastore.api.FileMetadataExprType;
+import org.apache.hadoop.hive.metastore.api.Function;
+import org.apache.hadoop.hive.metastore.api.HiveObjectPrivilege;
+import org.apache.hadoop.hive.metastore.api.Index;
+import org.apache.hadoop.hive.metastore.api.InvalidInputException;
+import org.apache.hadoop.hive.metastore.api.InvalidObjectException;
+import org.apache.hadoop.hive.metastore.api.InvalidOperationException;
+import org.apache.hadoop.hive.metastore.api.InvalidPartitionException;
+import org.apache.hadoop.hive.metastore.api.MetaException;
+import org.apache.hadoop.hive.metastore.api.NoSuchObjectException;
+import org.apache.hadoop.hive.metastore.api.NotificationEvent;
+import org.apache.hadoop.hive.metastore.api.NotificationEventRequest;
+import org.apache.hadoop.hive.metastore.api.NotificationEventResponse;
+import org.apache.hadoop.hive.metastore.api.NotificationEventsCountRequest;
+import org.apache.hadoop.hive.metastore.api.NotificationEventsCountResponse;
+import org.apache.hadoop.hive.metastore.api.Partition;
+import org.apache.hadoop.hive.metastore.api.PartitionEventType;
+import org.apache.hadoop.hive.metastore.api.PartitionValuesResponse;
+import org.apache.hadoop.hive.metastore.api.PrincipalPrivilegeSet;
+import org.apache.hadoop.hive.metastore.api.PrincipalType;
+import org.apache.hadoop.hive.metastore.api.PrivilegeBag;
+import org.apache.hadoop.hive.metastore.api.WMResourcePlan;
+import org.apache.hadoop.hive.metastore.api.WMTrigger;
+import org.apache.hadoop.hive.metastore.api.Role;
+import org.apache.hadoop.hive.metastore.api.RolePrincipalGrant;
+import org.apache.hadoop.hive.metastore.api.SQLForeignKey;
+import org.apache.hadoop.hive.metastore.api.SQLNotNullConstraint;
+import org.apache.hadoop.hive.metastore.api.SQLPrimaryKey;
+import org.apache.hadoop.hive.metastore.api.SQLUniqueConstraint;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.api.TableMeta;
+import org.apache.hadoop.hive.metastore.api.Type;
+import org.apache.hadoop.hive.metastore.api.UnknownDBException;
+import org.apache.hadoop.hive.metastore.api.UnknownPartitionException;
+import org.apache.hadoop.hive.metastore.api.UnknownTableException;
+import org.apache.hadoop.hive.metastore.partition.spec.PartitionSpecProxy;
+import org.apache.thrift.TException;
+
+/**
+ * A wrapper around {@link org.apache.hadoop.hive.metastore.ObjectStore}
+ * with the ability to control the result of commitTransaction().
+ * All other functions simply delegate to an embedded ObjectStore object.
+ * Ideally, we should have just extended ObjectStore instead of using
+ * delegation. However, since HiveMetaStore uses a Proxy, this class must
+ * not inherit from any other class.
+ */
+public class DummyRawStoreControlledCommit implements RawStore, Configurable {
+
+ private final ObjectStore objectStore;
+ public DummyRawStoreControlledCommit() {
+ objectStore = new ObjectStore();
+ }
+
+ /**
+ * If true, shouldCommit() will simply call delegate commitTransaction() to the
+ * underlying ObjectStore.
+ * If false, shouldCommit() immediately returns false.
+ */
+ private static boolean shouldCommitSucceed = true;
+ public static void setCommitSucceed(boolean flag) {
+ shouldCommitSucceed = flag;
+ }
+
+ @Override
+ public boolean commitTransaction() {
+ if (shouldCommitSucceed) {
+ return objectStore.commitTransaction();
+ } else {
+ return false;
+ }
+ }
+
+ @Override
+ public boolean isActiveTransaction() {
+ return false;
+ }
+
+ // All remaining functions simply delegate to objectStore
+
+ @Override
+ public Configuration getConf() {
+ return objectStore.getConf();
+ }
+
+ @Override
+ public void setConf(Configuration conf) {
+ objectStore.setConf(conf);
+ }
+
+ @Override
+ public void shutdown() {
+ objectStore.shutdown();
+ }
+
+ @Override
+ public boolean openTransaction() {
+ return objectStore.openTransaction();
+ }
+
+ @Override
+ public void rollbackTransaction() {
+ objectStore.rollbackTransaction();
+ }
+
+ @Override
+ public void createDatabase(Database db) throws InvalidObjectException, MetaException {
+ objectStore.createDatabase(db);
+ }
+
+ @Override
+ public Database getDatabase(String dbName) throws NoSuchObjectException {
+ return objectStore.getDatabase(dbName);
+ }
+
+ @Override
+ public boolean dropDatabase(String dbName)
+ throws NoSuchObjectException, MetaException {
+ return objectStore.dropDatabase(dbName);
+ }
+
+ @Override
+ public boolean alterDatabase(String dbName, Database db)
+ throws NoSuchObjectException, MetaException {
+
+ return objectStore.alterDatabase(dbName, db);
+ }
+
+ @Override
+ public List<String> getDatabases(String pattern) throws MetaException {
+ return objectStore.getDatabases(pattern);
+ }
+
+ @Override
+ public List<String> getAllDatabases() throws MetaException {
+ return objectStore.getAllDatabases();
+ }
+
+ @Override
+ public boolean createType(Type type) {
+ return objectStore.createType(type);
+ }
+
+ @Override
+ public Type getType(String typeName) {
+ return objectStore.getType(typeName);
+ }
+
+ @Override
+ public boolean dropType(String typeName) {
+ return objectStore.dropType(typeName);
+ }
+
+ @Override
+ public void createTable(Table tbl) throws InvalidObjectException, MetaException {
+ objectStore.createTable(tbl);
+ }
+
+ @Override
+ public boolean dropTable(String dbName, String tableName)
+ throws MetaException, NoSuchObjectException,
+ InvalidObjectException, InvalidInputException {
+ return objectStore.dropTable(dbName, tableName);
+ }
+
+ @Override
+ public Table getTable(String dbName, String tableName) throws MetaException {
+ return objectStore.getTable(dbName, tableName);
+ }
+
+ @Override
+ public boolean addPartition(Partition part)
+ throws InvalidObjectException, MetaException {
+ return objectStore.addPartition(part);
+ }
+
+ @Override
+ public Partition getPartition(String dbName, String tableName, List<String> partVals)
+ throws MetaException, NoSuchObjectException {
+ return objectStore.getPartition(dbName, tableName, partVals);
+ }
+
+ @Override
+ public boolean dropPartition(String dbName, String tableName, List<String> partVals)
+ throws MetaException, NoSuchObjectException,
+ InvalidObjectException, InvalidInputException {
+ return objectStore.dropPartition(dbName, tableName, partVals);
+ }
+
+ @Override
+ public List<Partition> getPartitions(String dbName, String tableName, int max)
+ throws MetaException, NoSuchObjectException {
+ return objectStore.getPartitions(dbName, tableName, max);
+ }
+
+ @Override
+ public void alterTable(String dbName, String name, Table newTable)
+ throws InvalidObjectException, MetaException {
+ objectStore.alterTable(dbName, name, newTable);
+ }
+
+ @Override
+ public List<String> getTables(String dbName, String pattern) throws MetaException {
+ return objectStore.getTables(dbName, pattern);
+ }
+
+ @Override
+ public List<String> getTables(String dbName, String pattern, TableType tableType) throws MetaException {
+ return objectStore.getTables(dbName, pattern, tableType);
+ }
+
+ @Override
+ public List<TableMeta> getTableMeta(String dbNames, String tableNames, List<String> tableTypes)
+ throws MetaException {
+ return objectStore.getTableMeta(dbNames, tableNames, tableTypes);
+ }
+
+ @Override
+ public List<Table> getTableObjectsByName(String dbName, List<String> tableNames)
+ throws MetaException, UnknownDBException {
+ return objectStore.getTableObjectsByName(dbName, tableNames);
+ }
+
+ @Override
+ public List<String> getAllTables(String dbName) throws MetaException {
+ return objectStore.getAllTables(dbName);
+ }
+
+ @Override
+ public List<String> listTableNamesByFilter(String dbName, String filter,
+ short maxTables) throws MetaException, UnknownDBException {
+ return objectStore.listTableNamesByFilter(dbName, filter, maxTables);
+ }
+
+ @Override
+ public List<String> listPartitionNames(String dbName, String tblName, short maxParts)
+ throws MetaException {
+ return objectStore.listPartitionNames(dbName, tblName, maxParts);
+ }
+
+ @Override
+ public PartitionValuesResponse listPartitionValues(String db_name, String tbl_name, List<FieldSchema> cols, boolean applyDistinct, String filter, boolean ascending, List<FieldSchema> order, long maxParts) throws MetaException {
+ return null;
+ }
+
+ @Override
+ public List<String> listPartitionNamesByFilter(String dbName, String tblName,
+ String filter, short maxParts) throws MetaException {
+ return objectStore.listPartitionNamesByFilter(dbName, tblName, filter, maxParts);
+ }
+
+ @Override
+ public void alterPartition(String dbName, String tblName, List<String> partVals,
+ Partition newPart) throws InvalidObjectException, MetaException {
+ objectStore.alterPartition(dbName, tblName, partVals, newPart);
+ }
+
+ @Override
+ public void alterPartitions(String dbName, String tblName,
+ List<List<String>> partValsList, List<Partition> newParts)
+ throws InvalidObjectException, MetaException {
+ objectStore.alterPartitions(dbName, tblName, partValsList, newParts);
+ }
+
+ @Override
+ public boolean addIndex(Index index) throws InvalidObjectException, MetaException {
+ return objectStore.addIndex(index);
+ }
+
+ @Override
+ public Index getIndex(String dbName, String origTableName, String indexName)
+ throws MetaException {
+ return objectStore.getIndex(dbName, origTableName, indexName);
+ }
+
+ @Override
+ public boolean dropIndex(String dbName, String origTableName, String indexName)
+ throws MetaException {
+ return objectStore.dropIndex(dbName, origTableName, indexName);
+ }
+
+ @Override
+ public List<Index> getIndexes(String dbName, String origTableName, int max)
+ throws MetaException {
+ return objectStore.getIndexes(dbName, origTableName, max);
+ }
+
+ @Override
+ public List<String> listIndexNames(String dbName, String origTableName, short max)
+ throws MetaException {
+ return objectStore.listIndexNames(dbName, origTableName, max);
+ }
+
+ @Override
+ public void alterIndex(String dbName, String baseTblName, String name, Index newIndex)
+ throws InvalidObjectException, MetaException {
+ objectStore.alterIndex(dbName, baseTblName, name, newIndex);
+ }
+
+ @Override
+ public List<Partition> getPartitionsByFilter(String dbName, String tblName,
+ String filter, short maxParts) throws MetaException, NoSuchObjectException {
+ return objectStore.getPartitionsByFilter(dbName, tblName, filter, maxParts);
+ }
+
+ @Override
+ public int getNumPartitionsByFilter(String dbName, String tblName,
+ String filter) throws MetaException, NoSuchObjectException {
+ return objectStore.getNumPartitionsByFilter(dbName, tblName, filter);
+ }
+
+ @Override
+ public int getNumPartitionsByExpr(String dbName, String tblName,
+ byte[] expr) throws MetaException, NoSuchObjectException {
+ return objectStore.getNumPartitionsByExpr(dbName, tblName, expr);
+ }
+
+ @Override
+ public List<Partition> getPartitionsByNames(String dbName, String tblName,
+ List<String> partNames) throws MetaException, NoSuchObjectException {
+ return objectStore.getPartitionsByNames(dbName, tblName, partNames);
+ }
+
+ @Override
+ public boolean getPartitionsByExpr(String dbName, String tblName, byte[] expr,
+ String defaultPartitionName, short maxParts, List<Partition> result) throws TException {
+ return objectStore.getPartitionsByExpr(
+ dbName, tblName, expr, defaultPartitionName, maxParts, result);
+ }
+
+ @Override
+ public Table markPartitionForEvent(String dbName, String tblName,
+ Map<String, String> partVals, PartitionEventType evtType)
+ throws MetaException, UnknownTableException, InvalidPartitionException,
+ UnknownPartitionException {
+ return objectStore.markPartitionForEvent(dbName, tblName, partVals, evtType);
+ }
+
+ @Override
+ public boolean isPartitionMarkedForEvent(String dbName, String tblName,
+ Map<String, String> partName, PartitionEventType evtType)
+ throws MetaException, UnknownTableException, InvalidPartitionException,
+ UnknownPartitionException {
+ return objectStore.isPartitionMarkedForEvent(dbName, tblName, partName, evtType);
+ }
+
+ @Override
+ public boolean addRole(String rowName, String ownerName) throws InvalidObjectException,
+ MetaException, NoSuchObjectException {
+ return objectStore.addRole(rowName, ownerName);
+ }
+
+ @Override
+ public boolean removeRole(String roleName)
+ throws MetaException, NoSuchObjectException {
+ return objectStore.removeRole(roleName);
+ }
+
+ @Override
+ public boolean grantRole(Role role, String userName, PrincipalType principalType,
+ String grantor, PrincipalType grantorType, boolean grantOption)
+ throws MetaException, NoSuchObjectException, InvalidObjectException {
+ return objectStore.grantRole(role, userName, principalType, grantor, grantorType,
+ grantOption);
+ }
+
+ @Override
+ public boolean revokeRole(Role role, String userName, PrincipalType principalType, boolean grantOption)
+ throws MetaException, NoSuchObjectException {
+ return objectStore.revokeRole(role, userName, principalType, grantOption);
+ }
+
+ @Override
+ public PrincipalPrivilegeSet getUserPrivilegeSet(String userName,
+ List<String> groupNames) throws InvalidObjectException, MetaException {
+ return objectStore.getUserPrivilegeSet(userName, groupNames);
+ }
+
+ @Override
+ public PrincipalPrivilegeSet getDBPrivilegeSet(String dbName, String userName,
+ List<String> groupNames) throws InvalidObjectException, MetaException {
+ return objectStore.getDBPrivilegeSet(dbName, userName, groupNames);
+ }
+
+ @Override
+ public PrincipalPrivilegeSet getTablePrivilegeSet(String dbName, String tableName,
+ String userName, List<String> groupNames)
+ throws InvalidObjectException, MetaException {
+ return objectStore.getTablePrivilegeSet(dbName, tableName, userName, groupNames);
+ }
+
+ @Override
+ public PrincipalPrivilegeSet getPartitionPrivilegeSet(String dbName, String tableName,
+ String partition, String userName, List<String> groupNames)
+ throws InvalidObjectException, MetaException {
+ return objectStore.getPartitionPrivilegeSet(dbName, tableName, partition,
+ userName, groupNames);
+ }
+
+ @Override
+ public PrincipalPrivilegeSet getColumnPrivilegeSet(String dbName, String tableName,
+ String partitionName, String columnName, String userName, List<String> groupNames)
+ throws InvalidObjectException, MetaException {
+ return objectStore.getColumnPrivilegeSet(dbName, tableName, partitionName,
+ columnName, userName, groupNames);
+ }
+
+ @Override
+ public List<HiveObjectPrivilege> listPrincipalGlobalGrants(String principalName,
+ PrincipalType principalType) {
+ return objectStore.listPrincipalGlobalGrants(principalName, principalType);
+ }
+
+ @Override
+ public List<HiveObjectPrivilege> listPrincipalDBGrants(String principalName,
+ PrincipalType principalType, String dbName) {
+ return objectStore.listPrincipalDBGrants(principalName, principalType, dbName);
+ }
+
+ @Override
+ public List<HiveObjectPrivilege> listAllTableGrants(String principalName,
+ PrincipalType principalType, String dbName, String tableName) {
+ return objectStore.listAllTableGrants(principalName, principalType,
+ dbName, tableName);
+ }
+
+ @Override
+ public List<HiveObjectPrivilege> listPrincipalPartitionGrants(String principalName,
+ PrincipalType principalType, String dbName, String tableName, List<String> partValues,
+ String partName) {
+ return objectStore.listPrincipalPartitionGrants(principalName, principalType,
+ dbName, tableName, partValues, partName);
+ }
+
+ @Override
+ public List<HiveObjectPrivilege> listPrincipalTableColumnGrants(String principalName,
+ PrincipalType principalType, String dbName, String tableName, String columnName) {
+ return objectStore.listPrincipalTableColumnGrants(principalName, principalType,
+ dbName, tableName, columnName);
+ }
+
+ @Override
+ public List<HiveObjectPrivilege> listPrincipalPartitionColumnGrants(
+ String principalName, PrincipalType principalType, String dbName, String tableName,
+ List<String> partVals, String partName, String columnName) {
+ return objectStore.listPrincipalPartitionColumnGrants(principalName, principalType,
+ dbName, tableName, partVals, partName, columnName);
+ }
+
+ @Override
+ public boolean grantPrivileges(PrivilegeBag privileges) throws InvalidObjectException,
+ MetaException, NoSuchObjectException {
+ return objectStore.grantPrivileges(privileges);
+ }
+
+ @Override
+ public boolean revokePrivileges(PrivilegeBag privileges, boolean grantOption)
+ throws InvalidObjectException, MetaException, NoSuchObjectException {
+ return objectStore.revokePrivileges(privileges, grantOption);
+ }
+
+ @Override
+ public Role getRole(String roleName) throws NoSuchObjectException {
+ return objectStore.getRole(roleName);
+ }
+
+ @Override
+ public List<String> listRoleNames() {
+ return objectStore.listRoleNames();
+ }
+
+ @Override
+ public List<Role> listRoles(String principalName, PrincipalType principalType) {
+ return objectStore.listRoles(principalName, principalType);
+ }
+
+ @Override
+ public List<RolePrincipalGrant> listRolesWithGrants(String principalName,
+ PrincipalType principalType) {
+ return objectStore.listRolesWithGrants(principalName, principalType);
+ }
+
+ @Override
+ public List<RolePrincipalGrant> listRoleMembers(String roleName) {
+ return objectStore.listRoleMembers(roleName);
+ }
+
+ @Override
+ public Partition getPartitionWithAuth(String dbName, String tblName,
+ List<String> partVals, String userName, List<String> groupNames)
+ throws MetaException, NoSuchObjectException, InvalidObjectException {
+ return objectStore.getPartitionWithAuth(dbName, tblName, partVals, userName,
+ groupNames);
+ }
+
+ @Override
+ public List<Partition> getPartitionsWithAuth(String dbName, String tblName,
+ short maxParts, String userName, List<String> groupNames)
+ throws MetaException, NoSuchObjectException, InvalidObjectException {
+ return objectStore.getPartitionsWithAuth(dbName, tblName, maxParts, userName,
+ groupNames);
+ }
+
+ @Override
+ public List<String> listPartitionNamesPs(String dbName, String tblName,
+ List<String> partVals, short maxParts)
+ throws MetaException, NoSuchObjectException {
+ return objectStore.listPartitionNamesPs(dbName, tblName, partVals, maxParts);
+ }
+
+ @Override
+ public List<Partition> listPartitionsPsWithAuth(String dbName, String tblName,
+ List<String> partVals, short maxParts, String userName, List<String> groupNames)
+ throws MetaException, InvalidObjectException, NoSuchObjectException {
+ return objectStore.listPartitionsPsWithAuth(dbName, tblName, partVals, maxParts,
+ userName, groupNames);
+ }
+
+ @Override
+ public long cleanupEvents() {
+ return objectStore.cleanupEvents();
+ }
+
+ @Override
+ public List<HiveObjectPrivilege> listPrincipalDBGrantsAll(
+ String principalName, PrincipalType principalType) {
+ return objectStore.listPrincipalDBGrantsAll(principalName, principalType);
+ }
+
+ @Override
+ public List<HiveObjectPrivilege> listPrincipalTableGrantsAll(
+ String principalName, PrincipalType principalType) {
+ return objectStore.listPrincipalTableGrantsAll(principalName, principalType);
+ }
+
+ @Override
+ public List<HiveObjectPrivilege> listPrincipalPartitionGrantsAll(
+ String principalName, PrincipalType principalType) {
+ return objectStore.listPrincipalPartitionGrantsAll(principalName, principalType);
+ }
+
+ @Override
+ public List<HiveObjectPrivilege> listPrincipalTableColumnGrantsAll(
+ String principalName, PrincipalType principalType) {
+ return objectStore.listPrincipalTableColumnGrantsAll(principalName, principalType);
+ }
+
+ @Override
+ public List<HiveObjectPrivilege> listPrincipalPartitionColumnGrantsAll(
+ String principalName, PrincipalType principalType) {
+ return objectStore.listPrincipalPartitionColumnGrantsAll(principalName, principalType);
+ }
+
+ @Override
+ public List<HiveObjectPrivilege> listGlobalGrantsAll() {
+ return objectStore.listGlobalGrantsAll();
+ }
+
+ @Override
+ public List<HiveObjectPrivilege> listDBGrantsAll(String dbName) {
+ return objectStore.listDBGrantsAll(dbName);
+ }
+
+ @Override
+ public List<HiveObjectPrivilege> listPartitionColumnGrantsAll(String dbName, String tableName,
+ String partitionName, String columnName) {
+ return objectStore.listPartitionColumnGrantsAll(dbName, tableName, partitionName, columnName);
+ }
+
+ @Override
+ public List<HiveObjectPrivilege> listTableGrantsAll(String dbName, String tableName) {
+ return objectStore.listTableGrantsAll(dbName, tableName);
+ }
+
+ @Override
+ public List<HiveObjectPrivilege> listPartitionGrantsAll(String dbName, String tableName,
+ String partitionName) {
+ return objectStore.listPartitionGrantsAll(dbName, tableName, partitionName);
+ }
+
+ @Override
+ public List<HiveObjectPrivilege> listTableColumnGrantsAll(String dbName, String tableName,
+ String columnName) {
+ return objectStore.listTableColumnGrantsAll(dbName, tableName, columnName);
+ }
+
+ @Override
+ public ColumnStatistics getTableColumnStatistics(String dbName, String tableName,
+ List<String> colNames) throws MetaException, NoSuchObjectException {
+ return objectStore.getTableColumnStatistics(dbName, tableName, colNames);
+ }
+
+ @Override
+ public boolean deleteTableColumnStatistics(String dbName, String tableName,
+ String colName)
+ throws NoSuchObjectException, MetaException, InvalidObjectException,
+ InvalidInputException {
+ return objectStore.deleteTableColumnStatistics(dbName, tableName, colName);
+ }
+
+ @Override
+ public boolean deletePartitionColumnStatistics(String dbName, String tableName,
+ String partName, List<String> partVals, String colName)
+ throws NoSuchObjectException, MetaException, InvalidObjectException,
+ InvalidInputException {
+ return objectStore.deletePartitionColumnStatistics(dbName, tableName, partName,
+ partVals, colName);
+ }
+
+ @Override
+ public boolean updateTableColumnStatistics(ColumnStatistics statsObj)
+ throws NoSuchObjectException, MetaException, InvalidObjectException,
+ InvalidInputException {
+ return objectStore.updateTableColumnStatistics(statsObj);
+ }
+
+ @Override
+ public boolean updatePartitionColumnStatistics(ColumnStatistics statsObj,
+ List<String> partVals)
+ throws NoSuchObjectException, MetaException, InvalidObjectException,
+ InvalidInputException {
+ return objectStore.updatePartitionColumnStatistics(statsObj, partVals);
+ }
+
+ @Override
+ public boolean addToken(String tokenIdentifier, String delegationToken) {
+ return false;
+ }
+
+ @Override
+ public boolean removeToken(String tokenIdentifier) {
+ return false;
+ }
+
+ @Override
+ public String getToken(String tokenIdentifier) {
+ return "";
+ }
+
+ @Override
+ public List<String> getAllTokenIdentifiers() {
+ return new ArrayList<>();
+ }
+
+ @Override
+ public int addMasterKey(String key) throws MetaException {
+ return -1;
+ }
+
+ @Override
+ public void updateMasterKey(Integer seqNo, String key)
+ throws NoSuchObjectException, MetaException {}
+
+ @Override
+ public boolean removeMasterKey(Integer keySeq) {
+ return false;
+ }
+
+ @Override
+ public String[] getMasterKeys() {
+ return new String[0];
+ }
+
+ @Override
+ public void verifySchema() throws MetaException {
+ }
+
+ @Override
+ public String getMetaStoreSchemaVersion() throws MetaException {
+ return objectStore.getMetaStoreSchemaVersion();
+ }
+
+ @Override
+ public void setMetaStoreSchemaVersion(String schemaVersion, String comment) throws MetaException {
+ objectStore.setMetaStoreSchemaVersion(schemaVersion, comment);
+
+ }
+
+ @Override
+ public List<ColumnStatistics> getPartitionColumnStatistics(String dbName,
+ String tblName, List<String> colNames, List<String> partNames)
+ throws MetaException, NoSuchObjectException {
+ return objectStore.getPartitionColumnStatistics(dbName, tblName , colNames, partNames);
+ }
+
+ @Override
+ public boolean doesPartitionExist(String dbName, String tableName,
+ List<String> partVals) throws MetaException, NoSuchObjectException {
+ return objectStore.doesPartitionExist(dbName, tableName, partVals);
+ }
+
+ @Override
+ public boolean addPartitions(String dbName, String tblName, List<Partition> parts)
+ throws InvalidObjectException, MetaException {
+ return objectStore.addPartitions(dbName, tblName, parts);
+ }
+
+ @Override
+ public boolean addPartitions(String dbName, String tblName, PartitionSpecProxy partitionSpec, boolean ifNotExists) throws InvalidObjectException, MetaException {
+ return false;
+ }
+
+ @Override
+ public void dropPartitions(String dbName, String tblName, List<String> partNames)
+ throws MetaException, NoSuchObjectException {
+ objectStore.dropPartitions(dbName, tblName, partNames);
+ }
+
+ @Override
+ public void createFunction(Function func) throws InvalidObjectException,
+ MetaException {
+ objectStore.createFunction(func);
+ }
+
+ @Override
+ public void alterFunction(String dbName, String funcName, Function newFunction)
+ throws InvalidObjectException, MetaException {
+ objectStore.alterFunction(dbName, funcName, newFunction);
+ }
+
+ @Override
+ public void dropFunction(String dbName, String funcName)
+ throws MetaException, NoSuchObjectException, InvalidObjectException,
+ InvalidInputException {
+ objectStore.dropFunction(dbName, funcName);
+ }
+
+ @Override
+ public Function getFunction(String dbName, String funcName)
+ throws MetaException {
+ return objectStore.getFunction(dbName, funcName);
+ }
+
+ @Override
+ public List<Function> getAllFunctions()
+ throws MetaException {
+ return Collections.emptyList();
+ }
+
+ @Override
+ public List<String> getFunctions(String dbName, String pattern)
+ throws MetaException {
+ return objectStore.getFunctions(dbName, pattern);
+ }
+
+ @Override
+ public AggrStats get_aggr_stats_for(String dbName,
+ String tblName, List<String> partNames, List<String> colNames)
+ throws MetaException {
+ return null;
+ }
+
+ @Override
+ public NotificationEventResponse getNextNotification(NotificationEventRequest rqst) {
+ return objectStore.getNextNotification(rqst);
+ }
+
+ @Override
+ public void addNotificationEvent(NotificationEvent event) {
+ objectStore.addNotificationEvent(event);
+ }
+
+ @Override
+ public void cleanNotificationEvents(int olderThan) {
+ objectStore.cleanNotificationEvents(olderThan);
+ }
+
+ @Override
+ public CurrentNotificationEventId getCurrentNotificationEventId() {
+ return objectStore.getCurrentNotificationEventId();
+ }
+
+ @Override
+ public NotificationEventsCountResponse getNotificationEventsCount(NotificationEventsCountRequest rqst) {
+ return objectStore.getNotificationEventsCount(rqst);
+ }
+
+ @Override
+ public void flushCache() {
+ objectStore.flushCache();
+ }
+
+ @Override
+ public ByteBuffer[] getFileMetadata(List<Long> fileIds) {
+ return null;
+ }
+
+ @Override
+ public void putFileMetadata(
+ List<Long> fileIds, List<ByteBuffer> metadata, FileMetadataExprType type) {
+ }
+
+ @Override
+ public boolean isFileMetadataSupported() {
+ return false;
+ }
+
+
+ @Override
+ public void getFileMetadataByExpr(List<Long> fileIds, FileMetadataExprType type, byte[] expr,
+ ByteBuffer[] metadatas, ByteBuffer[] stripeBitsets, boolean[] eliminated) {
+ }
+
+ @Override
+ public int getTableCount() throws MetaException {
+ return objectStore.getTableCount();
+ }
+
+ @Override
+ public int getPartitionCount() throws MetaException {
+ return objectStore.getPartitionCount();
+ }
+
+ @Override
+ public int getDatabaseCount() throws MetaException {
+ return objectStore.getDatabaseCount();
+ }
+
+ @Override
+ public FileMetadataHandler getFileMetadataHandler(FileMetadataExprType type) {
+ return null;
+ }
+
+ @Override
+ public List<SQLPrimaryKey> getPrimaryKeys(String db_name, String tbl_name)
+ throws MetaException {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public List<SQLForeignKey> getForeignKeys(String parent_db_name,
+ String parent_tbl_name, String foreign_db_name, String foreign_tbl_name)
+ throws MetaException {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public List<SQLUniqueConstraint> getUniqueConstraints(String db_name, String tbl_name)
+ throws MetaException {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public List<SQLNotNullConstraint> getNotNullConstraints(String db_name, String tbl_name)
+ throws MetaException {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public List<String> createTableWithConstraints(Table tbl,
+ List<SQLPrimaryKey> primaryKeys, List<SQLForeignKey> foreignKeys,
+ List<SQLUniqueConstraint> uniqueConstraints,
+ List<SQLNotNullConstraint> notNullConstraints)
+ throws InvalidObjectException, MetaException {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public void dropConstraint(String dbName, String tableName,
+ String constraintName) throws NoSuchObjectException {
+ // TODO Auto-generated method stub
+ }
+
+ @Override
+ public List<String> addPrimaryKeys(List<SQLPrimaryKey> pks)
+ throws InvalidObjectException, MetaException {
+ return null;
+ }
+
+ @Override
+ public List<String> addForeignKeys(List<SQLForeignKey> fks)
+ throws InvalidObjectException, MetaException {
+ return null;
+ }
+
+ @Override
+ public List<String> addUniqueConstraints(List<SQLUniqueConstraint> uks)
+ throws InvalidObjectException, MetaException {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public List<String> addNotNullConstraints(List<SQLNotNullConstraint> nns)
+ throws InvalidObjectException, MetaException {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public Map<String, List<ColumnStatisticsObj>> getColStatsForTablePartitions(String dbName,
+ String tableName) throws MetaException, NoSuchObjectException {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String getMetastoreDbUuid() throws MetaException {
+ throw new MetaException("Get metastore uuid is not implemented");
+ }
+
+ @Override
+ public void createResourcePlan(WMResourcePlan resourcePlan)
+ throws AlreadyExistsException, MetaException {
+ objectStore.createResourcePlan(resourcePlan);
+ }
+
+ @Override
+ public WMResourcePlan getResourcePlan(String name) throws NoSuchObjectException {
+ return objectStore.getResourcePlan(name);
+ }
+
+ @Override
+ public List<WMResourcePlan> getAllResourcePlans() throws MetaException {
+ return objectStore.getAllResourcePlans();
+ }
+
+ @Override
+ public void alterResourcePlan(String name, WMResourcePlan resourcePlan)
+ throws AlreadyExistsException, NoSuchObjectException, InvalidOperationException,
+ MetaException {
+ objectStore.alterResourcePlan(name, resourcePlan);
+ }
+
+ @Override
+ public boolean validateResourcePlan(String name)
+ throws NoSuchObjectException, InvalidObjectException, MetaException {
+ return objectStore.validateResourcePlan(name);
+ }
+
+ @Override
+ public void dropResourcePlan(String name) throws NoSuchObjectException, MetaException {
+ objectStore.dropResourcePlan(name);
+ }
+
+ @Override
+ public void createWMTrigger(WMTrigger trigger)
+ throws AlreadyExistsException, MetaException, NoSuchObjectException,
+ InvalidOperationException {
+ objectStore.createWMTrigger(trigger);
+ }
+
+ @Override
+ public void alterWMTrigger(WMTrigger trigger)
+ throws NoSuchObjectException, InvalidOperationException, MetaException {
+ objectStore.alterWMTrigger(trigger);
+ }
+
+ @Override
+ public void dropWMTrigger(String resourcePlanName, String triggerName)
+ throws NoSuchObjectException, InvalidOperationException, MetaException {
+ objectStore.dropWMTrigger(resourcePlanName, triggerName);
+ }
+
+ @Override
+ public List<WMTrigger> getTriggersForResourcePlan(String resourcePlanName)
+ throws NoSuchObjectException, MetaException {
+ return objectStore.getTriggersForResourcePlan(resourcePlanName);
+ }
+}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/InjectableBehaviourObjectStore.java
----------------------------------------------------------------------
diff --git a/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/InjectableBehaviourObjectStore.java b/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/InjectableBehaviourObjectStore.java
new file mode 100644
index 0000000..d7a40b6
--- /dev/null
+++ b/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/InjectableBehaviourObjectStore.java
@@ -0,0 +1,104 @@
+/*
+ * 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 java.util.List;
+import org.apache.hadoop.hive.metastore.api.MetaException;
+import org.apache.hadoop.hive.metastore.api.NotificationEventRequest;
+import org.apache.hadoop.hive.metastore.api.NotificationEventResponse;
+import org.apache.hadoop.hive.metastore.api.Table;
+
+import static org.junit.Assert.assertEquals;
+
+
+/**
+ * A wrapper around {@link ObjectStore} that allows us to inject custom behaviour
+ * on to some of the methods for testing.
+ */
+public class InjectableBehaviourObjectStore extends ObjectStore {
+ public InjectableBehaviourObjectStore() {
+ super();
+ }
+
+ /**
+ * A utility class that allows people injecting behaviour to determine if their injections occurred.
+ */
+ public static abstract class BehaviourInjection<T,F>
+ implements com.google.common.base.Function<T,F>{
+ protected boolean injectionPathCalled = false;
+ protected boolean nonInjectedPathCalled = false;
+
+ public void assertInjectionsPerformed(
+ boolean expectedInjectionCalled, boolean expectedNonInjectedPathCalled){
+ assertEquals(expectedInjectionCalled, injectionPathCalled);
+ assertEquals(expectedNonInjectedPathCalled, nonInjectedPathCalled);
+ }
+ }
+
+ private static com.google.common.base.Function<Table,Table> getTableModifier =
+ com.google.common.base.Functions.identity();
+ private static com.google.common.base.Function<List<String>, List<String>> listPartitionNamesModifier =
+ com.google.common.base.Functions.identity();
+ private static com.google.common.base.Function<NotificationEventResponse, NotificationEventResponse>
+ getNextNotificationModifier = com.google.common.base.Functions.identity();
+
+ // Methods to set/reset getTable modifier
+ public static void setGetTableBehaviour(com.google.common.base.Function<Table,Table> modifier){
+ getTableModifier = (modifier == null)? com.google.common.base.Functions.identity() : modifier;
+ }
+
+ public static void resetGetTableBehaviour(){
+ setGetTableBehaviour(null);
+ }
+
+ // Methods to set/reset listPartitionNames modifier
+ public static void setListPartitionNamesBehaviour(com.google.common.base.Function<List<String>, List<String>> modifier){
+ listPartitionNamesModifier = (modifier == null)? com.google.common.base.Functions.identity() : modifier;
+ }
+
+ public static void resetListPartitionNamesBehaviour(){
+ setListPartitionNamesBehaviour(null);
+ }
+
+ // Methods to set/reset getNextNotification modifier
+ public static void setGetNextNotificationBehaviour(
+ com.google.common.base.Function<NotificationEventResponse,NotificationEventResponse> modifier){
+ getNextNotificationModifier = (modifier == null)? com.google.common.base.Functions.identity() : modifier;
+ }
+
+ public static void resetGetNextNotificationBehaviour(){
+ setGetNextNotificationBehaviour(null);
+ }
+
+ // ObjectStore methods to be overridden with injected behavior
+ @Override
+ public Table getTable(String dbName, String tableName) throws MetaException {
+ return getTableModifier.apply(super.getTable(dbName, tableName));
+ }
+
+ @Override
+ public List<String> listPartitionNames(String dbName, String tableName, short max) throws MetaException {
+ return listPartitionNamesModifier.apply(super.listPartitionNames(dbName, tableName, max));
+ }
+
+ @Override
+ public NotificationEventResponse getNextNotification(NotificationEventRequest rqst) {
+ return getNextNotificationModifier.apply(super.getNextNotification(rqst));
+ }
+}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/IpAddressListener.java
----------------------------------------------------------------------
diff --git a/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/IpAddressListener.java b/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/IpAddressListener.java
new file mode 100644
index 0000000..e7a0d2d
--- /dev/null
+++ b/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/IpAddressListener.java
@@ -0,0 +1,102 @@
+/*
+ * 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 java.net.InetAddress;
+import java.net.UnknownHostException;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hive.metastore.HiveMetaStore.HMSHandler;
+import org.apache.hadoop.hive.metastore.api.MetaException;
+import org.apache.hadoop.hive.metastore.events.AddPartitionEvent;
+import org.apache.hadoop.hive.metastore.events.AlterPartitionEvent;
+import org.apache.hadoop.hive.metastore.events.AlterTableEvent;
+import org.apache.hadoop.hive.metastore.events.CreateDatabaseEvent;
+import org.apache.hadoop.hive.metastore.events.CreateTableEvent;
+import org.apache.hadoop.hive.metastore.events.DropDatabaseEvent;
+import org.apache.hadoop.hive.metastore.events.DropPartitionEvent;
+import org.apache.hadoop.hive.metastore.events.DropTableEvent;
+import org.apache.hadoop.hive.metastore.events.LoadPartitionDoneEvent;
+import org.junit.Assert;
+
+/** An implementation for MetaStoreEventListener which checks that the IP Address stored in
+ * HMSHandler matches that of local host, for testing purposes.
+ */
+public class IpAddressListener extends MetaStoreEventListener{
+
+ private static final String LOCAL_HOST = "localhost";
+
+ public IpAddressListener(Configuration config) {
+ super(config);
+ }
+
+ private void checkIpAddress() {
+ try {
+ String localhostIp = InetAddress.getByName(LOCAL_HOST).getHostAddress();
+ Assert.assertEquals(localhostIp, HMSHandler.getThreadLocalIpAddress());
+ } catch (UnknownHostException e) {
+ Assert.assertTrue("InetAddress.getLocalHost threw an exception: " + e.getMessage(), false);
+ }
+ }
+
+ @Override
+ public void onAddPartition(AddPartitionEvent partition) throws MetaException {
+ checkIpAddress();
+ }
+
+ @Override
+ public void onCreateDatabase(CreateDatabaseEvent db) throws MetaException {
+ checkIpAddress();
+ }
+
+ @Override
+ public void onCreateTable(CreateTableEvent table) throws MetaException {
+ checkIpAddress();
+ }
+
+ @Override
+ public void onDropDatabase(DropDatabaseEvent db) throws MetaException {
+ checkIpAddress();
+ }
+
+ @Override
+ public void onDropPartition(DropPartitionEvent partition) throws MetaException {
+ checkIpAddress();
+ }
+
+ @Override
+ public void onDropTable(DropTableEvent table) throws MetaException {
+ checkIpAddress();
+ }
+
+ @Override
+ public void onAlterTable(AlterTableEvent event) throws MetaException {
+ checkIpAddress();
+ }
+
+ @Override
+ public void onAlterPartition(AlterPartitionEvent event) throws MetaException {
+ checkIpAddress();
+ }
+
+ @Override
+ public void onLoadPartitionDone(LoadPartitionDoneEvent partEvent) throws MetaException {
+ checkIpAddress();
+ }
+}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/MetaStoreTestUtils.java
----------------------------------------------------------------------
diff --git a/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/MetaStoreTestUtils.java b/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/MetaStoreTestUtils.java
new file mode 100644
index 0000000..2c5a8ac
--- /dev/null
+++ b/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/MetaStoreTestUtils.java
@@ -0,0 +1,165 @@
+/**
+ * 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 java.io.IOException;
+import java.net.InetSocketAddress;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.util.Map;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hive.metastore.conf.MetastoreConf;
+import org.apache.hadoop.hive.metastore.security.HadoopThriftAuthBridge;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class MetaStoreTestUtils {
+
+ private static final Logger LOG = LoggerFactory.getLogger("hive.log");
+
+ public static int startMetaStore() throws Exception {
+ return MetaStoreTestUtils.startMetaStore(HadoopThriftAuthBridge.getBridge(), null);
+ }
+
+ public static int startMetaStore(final HadoopThriftAuthBridge bridge, Configuration conf)
+ throws Exception {
+ int port = MetaStoreTestUtils.findFreePort();
+ MetaStoreTestUtils.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 {
+ MetaStoreTestUtils.startMetaStore(port, bridge, null);
+ }
+
+ public static void startMetaStore(final int port,
+ final HadoopThriftAuthBridge bridge, Configuration conf)
+ throws Exception{
+ if (conf == null) {
+ conf = MetastoreConf.newMetastoreConf();
+ }
+ final Configuration finalConf = conf;
+ Thread thread = new Thread(new Runnable() {
+ @Override
+ public void run() {
+ try {
+ HiveMetaStore.startMetaStore(port, bridge, finalConf);
+ } catch (Throwable e) {
+ LOG.error("Metastore Thrift Server threw an exception...", e);
+ }
+ }
+ });
+ thread.setDaemon(true);
+ thread.start();
+ MetaStoreTestUtils.loopUntilHMSReady(port);
+ }
+
+ /**
+ * A simple connect test to make sure that the metastore is up
+ * @throws Exception
+ */
+ public static void loopUntilHMSReady(int port) throws Exception {
+ int retries = 0;
+ Exception exc = null;
+ 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(MetaStoreTestUtils.getAllThreadStacksAsString());
+ throw exc;
+ }
+
+ public 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());
+ MetaStoreTestUtils.addStackString(entry.getValue(), sb);
+ }
+ return sb.toString();
+ }
+
+ public 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();
+ }
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/MockPartitionExpressionForMetastore.java
----------------------------------------------------------------------
diff --git a/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/MockPartitionExpressionForMetastore.java b/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/MockPartitionExpressionForMetastore.java
new file mode 100644
index 0000000..346fd98
--- /dev/null
+++ b/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/MockPartitionExpressionForMetastore.java
@@ -0,0 +1,58 @@
+/*
+ * 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 org.apache.hadoop.hive.metastore.api.FieldSchema;
+import org.apache.hadoop.hive.metastore.api.FileMetadataExprType;
+import org.apache.hadoop.hive.metastore.api.MetaException;
+import org.apache.hadoop.hive.ql.io.sarg.SearchArgument;
+
+import java.util.List;
+
+/**
+ * Test Mock-out for PartitionExpressionForMetastore.
+ */
+public class MockPartitionExpressionForMetastore implements PartitionExpressionProxy {
+ @Override
+ public String convertExprToFilter(byte[] expr) throws MetaException {
+ return null;
+ }
+
+ @Override
+ public boolean filterPartitionsByExpr(List<FieldSchema> partColumns,
+ byte[] expr, String defaultPartitionName,
+ List<String> partitionNames) throws MetaException {
+ return false;
+ }
+
+ @Override
+ public FileMetadataExprType getMetadataType(String inputFormat) {
+ return null;
+ }
+
+ @Override
+ public SearchArgument createSarg(byte[] expr) {
+ return null;
+ }
+
+ @Override
+ public FileFormatProxy getFileFormatProxy(FileMetadataExprType type) {
+ return null;
+ }
+}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/TestHiveMetaStoreGetMetaConf.java
----------------------------------------------------------------------
diff --git a/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/TestHiveMetaStoreGetMetaConf.java b/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/TestHiveMetaStoreGetMetaConf.java
new file mode 100644
index 0000000..2f69e4f
--- /dev/null
+++ b/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/TestHiveMetaStoreGetMetaConf.java
@@ -0,0 +1,136 @@
+/*
+ * 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 java.security.Permission;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hive.metastore.api.MetaException;
+import org.apache.hadoop.hive.metastore.conf.MetastoreConf;
+import org.apache.hadoop.hive.metastore.conf.MetastoreConf.ConfVars;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
+import org.apache.thrift.TException;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.Rule;
+import org.junit.rules.ExpectedException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static org.junit.Assert.*;
+import org.junit.Before;
+
+public class TestHiveMetaStoreGetMetaConf {
+
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestHiveMetaStoreGetMetaConf.class);
+ private static Configuration conf;
+ private static SecurityManager securityManager;
+
+ private HiveMetaStoreClient hmsc;
+
+ public static class NoExitSecurityManager extends SecurityManager {
+
+ @Override
+ public void checkPermission(Permission perm) {
+ // allow anything.
+ }
+
+ @Override
+ public void checkPermission(Permission perm, Object context) {
+ // allow anything.
+ }
+
+ @Override
+ public void checkExit(int status) {
+ super.checkExit(status);
+ throw new RuntimeException("System.exit() was called. Raising exception.");
+ }
+ }
+
+ @AfterClass
+ public static void tearDown() throws Exception {
+ LOG.info("Shutting down metastore.");
+ System.setSecurityManager(securityManager);
+ }
+
+ @BeforeClass
+ public static void startMetaStoreServer() throws Exception {
+
+ securityManager = System.getSecurityManager();
+ System.setSecurityManager(new NoExitSecurityManager());
+ Configuration metastoreConf = MetastoreConf.newMetastoreConf();
+ MetastoreConf.setClass(metastoreConf, ConfVars.EXPRESSION_PROXY_CLASS,
+ MockPartitionExpressionForMetastore.class, PartitionExpressionProxy.class);
+ MetastoreConf.setBoolVar(metastoreConf, ConfVars.TRY_DIRECT_SQL_DDL, false);
+ int msPort = MetaStoreUtils.startMetaStore(metastoreConf);
+ conf = MetastoreConf.newMetastoreConf();
+ MetastoreConf.setVar(conf, ConfVars.THRIFT_URIS, "thrift://localhost:" + msPort);
+ MetastoreConf.setBoolVar(conf, ConfVars.HIVE_SUPPORT_CONCURRENCY, false);
+ MetastoreConf.setLongVar(conf, ConfVars.THRIFT_CONNECTION_RETRIES, 10);
+ }
+
+ @Before
+ public void setup() throws MetaException {
+ hmsc = new HiveMetaStoreClient(conf);
+ }
+
+ @After
+ public void closeClient() {
+ if (hmsc != null) {
+ hmsc.close();
+ }
+ }
+
+ @Test
+ public void testGetMetaConfDefault() throws TException {
+ ConfVars metaConfVar = ConfVars.TRY_DIRECT_SQL;
+ String expected = metaConfVar.getDefaultVal().toString();
+ String actual = hmsc.getMetaConf(metaConfVar.toString());
+ assertEquals(expected, actual);
+ }
+
+ @Test
+ public void testGetMetaConfDefaultEmptyString() throws TException {
+ ConfVars metaConfVar = ConfVars.PARTITION_NAME_WHITELIST_PATTERN;
+ String expected = "";
+ String actual = hmsc.getMetaConf(metaConfVar.toString());
+ assertEquals(expected, actual);
+ }
+
+ @Test
+ public void testGetMetaConfOverridden() throws TException {
+ ConfVars metaConfVar = ConfVars.TRY_DIRECT_SQL_DDL;
+ String expected = "false";
+ String actual = hmsc.getMetaConf(metaConfVar.toString());
+ assertEquals(expected, actual);
+ }
+
+ @Test
+ public void testGetMetaConfUnknownPreperty() throws TException {
+ String unknownPropertyName = "hive.meta.foo.bar";
+ thrown.expect(MetaException.class);
+ thrown.expectMessage("Invalid configuration key " + unknownPropertyName);
+ hmsc.getMetaConf(unknownPropertyName);
+ }
+}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/TestHiveMetaStorePartitionSpecs.java
----------------------------------------------------------------------
diff --git a/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/TestHiveMetaStorePartitionSpecs.java b/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/TestHiveMetaStorePartitionSpecs.java
new file mode 100644
index 0000000..24e2847
--- /dev/null
+++ b/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/TestHiveMetaStorePartitionSpecs.java
@@ -0,0 +1,406 @@
+/*
+ * 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 org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hive.metastore.api.Database;
+import org.apache.hadoop.hive.metastore.api.FieldSchema;
+import org.apache.hadoop.hive.metastore.api.Partition;
+import org.apache.hadoop.hive.metastore.api.PartitionSpec;
+import org.apache.hadoop.hive.metastore.api.SerDeInfo;
+import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.conf.MetastoreConf;
+import org.apache.hadoop.hive.metastore.conf.MetastoreConf.ConfVars;
+import org.apache.hadoop.hive.metastore.partition.spec.CompositePartitionSpecProxy;
+import org.apache.hadoop.hive.metastore.partition.spec.PartitionSpecProxy;
+import org.junit.AfterClass;
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.security.Permission;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Test to check PartitionSpec support in HiveMetaStore.
+ */
+public class TestHiveMetaStorePartitionSpecs {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestHiveMetaStorePartitionSpecs.class);
+ private static int msPort;
+ private static Configuration conf;
+ private static SecurityManager securityManager;
+
+ public static class NoExitSecurityManager extends SecurityManager {
+
+ @Override
+ public void checkPermission(Permission perm) {
+ // allow anything.
+ }
+
+ @Override
+ public void checkPermission(Permission perm, Object context) {
+ // allow anything.
+ }
+
+ @Override
+ public void checkExit(int status) {
+
+ super.checkExit(status);
+ throw new RuntimeException("System.exit() was called. Raising exception. ");
+ }
+ }
+
+
+ @AfterClass
+ public static void tearDown() throws Exception {
+ LOG.info("Shutting down metastore.");
+ System.setSecurityManager(securityManager);
+
+ HiveMetaStoreClient hmsc = new HiveMetaStoreClient(conf);
+ hmsc.dropDatabase(dbName, true, true, true);
+ }
+
+ @BeforeClass
+ public static void startMetaStoreServer() throws Exception {
+
+ Configuration metastoreConf = MetastoreConf.newMetastoreConf();
+ MetastoreConf.setClass(metastoreConf, ConfVars.EXPRESSION_PROXY_CLASS,
+ MockPartitionExpressionForMetastore.class, PartitionExpressionProxy.class);
+ msPort = MetaStoreTestUtils.startMetaStore(metastoreConf);
+ securityManager = System.getSecurityManager();
+ System.setSecurityManager(new NoExitSecurityManager());
+ conf = MetastoreConf.newMetastoreConf();
+ MetastoreConf.setVar(conf, ConfVars.THRIFT_URIS, "thrift://localhost:" + msPort);
+ MetastoreConf.setLongVar(conf, ConfVars.THRIFT_CONNECTION_RETRIES, 3);
+ MetastoreConf.setBoolVar(conf, ConfVars.HIVE_SUPPORT_CONCURRENCY, false);
+ MetastoreConf.setClass(conf, ConfVars.EXPRESSION_PROXY_CLASS,
+ MockPartitionExpressionForMetastore.class, PartitionExpressionProxy.class);
+ }
+
+ private static String dbName = "testpartitionspecs_db";
+ private static String tableName = "testpartitionspecs_table";
+ private static int nDates = 10;
+ private static String datePrefix = "2014010";
+
+ private static void createTable(HiveMetaStoreClient hmsc, boolean enablePartitionGrouping) throws Exception {
+
+
+ List<FieldSchema> columns = new ArrayList<>();
+ columns.add(new FieldSchema("foo", "string", ""));
+ columns.add(new FieldSchema("bar", "string", ""));
+
+ List<FieldSchema> partColumns = new ArrayList<>();
+ partColumns.add(new FieldSchema("dt", "string", ""));
+ partColumns.add(new FieldSchema("blurb", "string", ""));
+
+ SerDeInfo serdeInfo = new SerDeInfo("LBCSerDe",
+ "org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe", new HashMap<>());
+
+ StorageDescriptor storageDescriptor
+ = new StorageDescriptor(columns, null,
+ "org.apache.hadoop.hive.ql.io.RCFileInputFormat",
+ "org.apache.hadoop.hive.ql.io.RCFileOutputFormat",
+ false, 0, serdeInfo, null, null, null);
+
+ Map<String, String> tableParameters = new HashMap<>();
+ tableParameters.put("hive.hcatalog.partition.spec.grouping.enabled", enablePartitionGrouping? "true":"false");
+ Table table = new Table(tableName, dbName, "", 0, 0, 0, storageDescriptor, partColumns, tableParameters, "", "", "");
+
+ hmsc.createTable(table);
+ Assert.assertTrue("Table " + dbName + "." + tableName + " does not exist",
+ hmsc.tableExists(dbName, tableName));
+
+ }
+
+ private static void clearAndRecreateDB(HiveMetaStoreClient hmsc) throws Exception {
+ hmsc.dropDatabase(dbName,
+ true, // Delete data.
+ true, // Ignore unknownDB.
+ true // Cascade.
+ );
+
+ hmsc.createDatabase(new Database(dbName,
+ "", // Description.
+ null, // Location.
+ null // Parameters.
+ ));
+ }
+
+ // Get partition-path. For grid='XYZ', place the partition outside the table-path.
+ private static String getPartitionPath(Table table, List<String> partValues) {
+
+ return partValues.get(1).equalsIgnoreCase("isLocatedOutsideTablePath")? // i.e. Is the partition outside the table-dir?
+ table.getSd().getLocation().replace(table.getTableName(), "location_outside_" + table.getTableName())
+ + "_" + partValues.get(0) + "_" + partValues.get(1)
+ : null ; // Use defaults... Partitions are put in the table directory.
+
+ }
+
+ private static void populatePartitions(HiveMetaStoreClient hmsc, Table table, List<String> blurbs) throws Exception {
+ for (int i=0; i< nDates; ++i) {
+ for (String blurb : blurbs) {
+ StorageDescriptor sd = new StorageDescriptor(table.getSd());
+ // Add partitions located in the table-directory (i.e. default).
+ List<String> values = Arrays.asList(datePrefix + i, blurb);
+ sd.setLocation(getPartitionPath(table, values));
+ hmsc.add_partition(new Partition(values, dbName, tableName, 0, 0, sd, null));
+ }
+ }
+ }
+
+ private void testGetPartitionSpecs(boolean enablePartitionGrouping) {
+ try {
+ HiveMetaStoreClient hmsc = new HiveMetaStoreClient(conf);
+ clearAndRecreateDB(hmsc);
+ createTable(hmsc, enablePartitionGrouping);
+ Table table = hmsc.getTable(dbName, tableName);
+ populatePartitions(hmsc, table, Arrays.asList("isLocatedInTablePath", "isLocatedOutsideTablePath"));
+
+ PartitionSpecProxy partitionSpecProxy = hmsc.listPartitionSpecs(dbName, tableName, -1);
+ Assert.assertEquals( "Unexpected number of partitions.", nDates * 2, partitionSpecProxy.size());
+
+ Map<String, List<String>> locationToDateMap = new HashMap<>();
+ locationToDateMap.put("isLocatedInTablePath", new ArrayList<>());
+ locationToDateMap.put("isLocatedOutsideTablePath", new ArrayList<>());
+ PartitionSpecProxy.PartitionIterator iterator = partitionSpecProxy.getPartitionIterator();
+
+ while (iterator.hasNext()) {
+ Partition partition = iterator.next();
+ locationToDateMap.get(partition.getValues().get(1)).add(partition.getValues().get(0));
+ }
+
+ List<String> expectedDates = new ArrayList<>(nDates);
+ for (int i=0; i<nDates; ++i) {
+ expectedDates.add(datePrefix + i);
+ }
+
+ Assert.assertArrayEquals("Unexpected date-values.", expectedDates.toArray(), locationToDateMap.get("isLocatedInTablePath").toArray());
+ Assert.assertArrayEquals("Unexpected date-values.", expectedDates.toArray(), locationToDateMap.get("isLocatedOutsideTablePath").toArray());
+
+ partitionSpecProxy = hmsc.listPartitionSpecsByFilter(dbName, tableName, "blurb = \"isLocatedOutsideTablePath\"", -1);
+ locationToDateMap.get("isLocatedInTablePath").clear();
+ locationToDateMap.get("isLocatedOutsideTablePath").clear();
+ iterator = partitionSpecProxy.getPartitionIterator();
+
+ while (iterator.hasNext()) {
+ Partition partition = iterator.next();
+ locationToDateMap.get(partition.getValues().get(1)).add(partition.getValues().get(0));
+ }
+
+ Assert.assertEquals("Unexpected date-values.", 0, locationToDateMap.get("isLocatedInTablePath").size());
+ Assert.assertArrayEquals("Unexpected date-values.", expectedDates.toArray(), locationToDateMap.get("isLocatedOutsideTablePath").toArray());
+
+
+ }
+ catch (Throwable t) {
+ LOG.error("Unexpected Exception!", t);
+ t.printStackTrace();
+ Assert.assertTrue("Unexpected Exception!", false);
+ }
+ }
+
+ /**
+ * Test for HiveMetaStoreClient.listPartitionSpecs() and HiveMetaStoreClient.listPartitionSpecsByFilter().
+ * Check behaviour with and without Partition-grouping enabled.
+ */
+ @Test
+ public void testGetPartitionSpecs_WithAndWithoutPartitionGrouping() {
+ testGetPartitionSpecs(true);
+ testGetPartitionSpecs(false);
+ }
+
+
+ /**
+ * Test to confirm that partitions can be added using PartitionSpecs.
+ */
+ @Test
+ public void testAddPartitions() {
+ try {
+ // Create source table.
+ HiveMetaStoreClient hmsc = new HiveMetaStoreClient(conf);
+ clearAndRecreateDB(hmsc);
+ createTable(hmsc, true);
+ Table table = hmsc.getTable(dbName, tableName);
+ populatePartitions(hmsc, table, Arrays.asList("isLocatedInTablePath", "isLocatedOutsideTablePath"));
+
+ // Clone the table,
+ String targetTableName = "cloned_" + tableName;
+ Table targetTable = new Table(table);
+ targetTable.setTableName(targetTableName);
+ StorageDescriptor targetTableSd = new StorageDescriptor(targetTable.getSd());
+ targetTableSd.setLocation(
+ targetTableSd.getLocation().replace( tableName, targetTableName));
+ hmsc.createTable(targetTable);
+
+ // Get partition-list from source.
+ PartitionSpecProxy partitionsForAddition
+ = hmsc.listPartitionSpecsByFilter(dbName, tableName, "blurb = \"isLocatedInTablePath\"", -1);
+ partitionsForAddition.setTableName(targetTableName);
+ partitionsForAddition.setRootLocation(targetTableSd.getLocation());
+
+ Assert.assertEquals("Unexpected number of partitions added. ",
+ partitionsForAddition.size(), hmsc.add_partitions_pspec(partitionsForAddition));
+
+ // Check that the added partitions are as expected.
+ PartitionSpecProxy clonedPartitions = hmsc.listPartitionSpecs(dbName, targetTableName, -1);
+ Assert.assertEquals("Unexpected number of partitions returned. ",
+ partitionsForAddition.size(), clonedPartitions.size());
+
+ PartitionSpecProxy.PartitionIterator sourceIterator = partitionsForAddition.getPartitionIterator(),
+ targetIterator = clonedPartitions.getPartitionIterator();
+
+ while (targetIterator.hasNext()) {
+ Partition sourcePartition = sourceIterator.next(),
+ targetPartition = targetIterator.next();
+ Assert.assertEquals("Mismatched values.",
+ sourcePartition.getValues(), targetPartition.getValues());
+ Assert.assertEquals("Mismatched locations.",
+ sourcePartition.getSd().getLocation(), targetPartition.getSd().getLocation());
+ }
+ }
+ catch (Throwable t) {
+ LOG.error("Unexpected Exception!", t);
+ t.printStackTrace();
+ Assert.assertTrue("Unexpected Exception!", false);
+ }
+ }
+
+ /**
+ * Test to confirm that Partition-grouping behaves correctly when Table-schemas evolve.
+ * Partitions must be grouped by location and schema.
+ */
+ @Test
+ public void testFetchingPartitionsWithDifferentSchemas() {
+ try {
+ // Create source table.
+ HiveMetaStoreClient hmsc = new HiveMetaStoreClient(conf);
+ clearAndRecreateDB(hmsc);
+ createTable(hmsc, true);
+ Table table = hmsc.getTable(dbName, tableName);
+ populatePartitions(hmsc,
+ table,
+ Arrays.asList("isLocatedInTablePath", "isLocatedOutsideTablePath") // Blurb list.
+ );
+
+ // Modify table schema. Add columns.
+ List<FieldSchema> fields = table.getSd().getCols();
+ fields.add(new FieldSchema("goo", "string", "Entirely new column. Doesn't apply to older partitions."));
+ table.getSd().setCols(fields);
+ hmsc.alter_table(dbName, tableName, table);
+ // Check that the change stuck.
+ table = hmsc.getTable(dbName,tableName);
+ Assert.assertEquals("Unexpected number of table columns.",
+ 3, table.getSd().getColsSize());
+
+ // Add partitions with new schema.
+ // Mark Partitions with new schema with different blurb.
+ populatePartitions(hmsc, table, Arrays.asList("hasNewColumn"));
+
+ // Retrieve *all* partitions from the table.
+ PartitionSpecProxy partitionSpecProxy = hmsc.listPartitionSpecs(dbName, tableName, -1);
+ Assert.assertEquals("Unexpected number of partitions.", nDates * 3, partitionSpecProxy.size());
+
+ // Confirm grouping.
+ Assert.assertTrue("Unexpected type of PartitionSpecProxy.", partitionSpecProxy instanceof CompositePartitionSpecProxy);
+ CompositePartitionSpecProxy compositePartitionSpecProxy = (CompositePartitionSpecProxy)partitionSpecProxy;
+ List<PartitionSpec> partitionSpecs = compositePartitionSpecProxy.toPartitionSpec();
+ Assert.assertTrue("PartitionSpec[0] should have been a SharedSDPartitionSpec.",
+ partitionSpecs.get(0).isSetSharedSDPartitionSpec());
+ Assert.assertEquals("PartitionSpec[0] should use the table-path as the common root location. ",
+ table.getSd().getLocation(), partitionSpecs.get(0).getRootPath());
+ Assert.assertTrue("PartitionSpec[1] should have been a SharedSDPartitionSpec.",
+ partitionSpecs.get(1).isSetSharedSDPartitionSpec());
+ Assert.assertEquals("PartitionSpec[1] should use the table-path as the common root location. ",
+ table.getSd().getLocation(), partitionSpecs.get(1).getRootPath());
+ Assert.assertTrue("PartitionSpec[2] should have been a ListComposingPartitionSpec.",
+ partitionSpecs.get(2).isSetPartitionList());
+
+ // Categorize the partitions returned, and confirm that all partitions are accounted for.
+ PartitionSpecProxy.PartitionIterator iterator = partitionSpecProxy.getPartitionIterator();
+ Map<String, List<Partition>> blurbToPartitionList = new HashMap<>(3);
+ while (iterator.hasNext()) {
+
+ Partition partition = iterator.next();
+ String blurb = partition.getValues().get(1);
+
+ if (!blurbToPartitionList.containsKey(blurb)) {
+ blurbToPartitionList.put(blurb, new ArrayList<>(nDates));
+ }
+
+ blurbToPartitionList.get(blurb).add(partition);
+
+ } // </Classification>
+
+ // All partitions with blurb="isLocatedOutsideTablePath" should have 2 columns,
+ // and must have locations outside the table directory.
+ for (Partition partition : blurbToPartitionList.get("isLocatedOutsideTablePath")) {
+ Assert.assertEquals("Unexpected number of columns.", 2, partition.getSd().getCols().size());
+ Assert.assertEquals("Unexpected first column.", "foo", partition.getSd().getCols().get(0).getName());
+ Assert.assertEquals("Unexpected second column.", "bar", partition.getSd().getCols().get(1).getName());
+ String partitionLocation = partition.getSd().getLocation();
+ String tableLocation = table.getSd().getLocation();
+ Assert.assertTrue("Unexpected partition location: " + partitionLocation + ". " +
+ "Partition should have been outside table location: " + tableLocation,
+ !partitionLocation.startsWith(tableLocation));
+ }
+
+ // All partitions with blurb="isLocatedInTablePath" should have 2 columns,
+ // and must have locations within the table directory.
+ for (Partition partition : blurbToPartitionList.get("isLocatedInTablePath")) {
+ Assert.assertEquals("Unexpected number of columns.", 2, partition.getSd().getCols().size());
+ Assert.assertEquals("Unexpected first column.", "foo", partition.getSd().getCols().get(0).getName());
+ Assert.assertEquals("Unexpected second column.", "bar", partition.getSd().getCols().get(1).getName());
+ String partitionLocation = partition.getSd().getLocation();
+ String tableLocation = table.getSd().getLocation();
+ Assert.assertTrue("Unexpected partition location: " + partitionLocation + ". " +
+ "Partition should have been within table location: " + tableLocation,
+ partitionLocation.startsWith(tableLocation));
+ }
+
+ // All partitions with blurb="hasNewColumn" were added after the table schema changed,
+ // and must have 3 columns. Also, the partition locations must lie within the table directory.
+ for (Partition partition : blurbToPartitionList.get("hasNewColumn")) {
+ Assert.assertEquals("Unexpected number of columns.", 3, partition.getSd().getCols().size());
+ Assert.assertEquals("Unexpected first column.", "foo", partition.getSd().getCols().get(0).getName());
+ Assert.assertEquals("Unexpected second column.", "bar", partition.getSd().getCols().get(1).getName());
+ Assert.assertEquals("Unexpected third column.", "goo", partition.getSd().getCols().get(2).getName());
+ String partitionLocation = partition.getSd().getLocation();
+ String tableLocation = table.getSd().getLocation();
+ Assert.assertTrue("Unexpected partition location: " + partitionLocation + ". " +
+ "Partition should have been within table location: " + tableLocation,
+ partitionLocation.startsWith(tableLocation));
+ }
+
+ }
+ catch (Throwable t) {
+ LOG.error("Unexpected Exception!", t);
+ t.printStackTrace();
+ Assert.assertTrue("Unexpected Exception!", false);
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/TestHiveMetaStoreTimeout.java
----------------------------------------------------------------------
diff --git a/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/TestHiveMetaStoreTimeout.java b/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/TestHiveMetaStoreTimeout.java
new file mode 100644
index 0000000..b4995e8
--- /dev/null
+++ b/standalone-metastore/src/test/java/org/apache/hadoop/hive/metastore/TestHiveMetaStoreTimeout.java
@@ -0,0 +1,139 @@
+/*
+ * 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 java.util.concurrent.TimeUnit;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hive.metastore.api.Database;
+import org.apache.hadoop.hive.metastore.api.MetaException;
+import org.apache.hadoop.hive.metastore.conf.MetastoreConf;
+import org.apache.hadoop.hive.metastore.conf.MetastoreConf.ConfVars;
+import org.apache.hadoop.util.StringUtils;
+import org.junit.AfterClass;
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+/**
+ * Test long running request timeout functionality in MetaStore Server
+ * HiveMetaStore.HMSHandler.create_database() is used to simulate a long running method.
+ */
+public class TestHiveMetaStoreTimeout {
+ protected static HiveMetaStoreClient client;
+ protected static Configuration conf;
+ protected static Warehouse warehouse;
+
+ @BeforeClass
+ public static void setUp() throws Exception {
+ HiveMetaStore.TEST_TIMEOUT_ENABLED = true;
+ conf = MetastoreConf.newMetastoreConf();
+ MetastoreConf.setClass(conf, ConfVars.EXPRESSION_PROXY_CLASS,
+ MockPartitionExpressionForMetastore.class, PartitionExpressionProxy.class);
+ MetastoreConf.setTimeVar(conf, ConfVars.CLIENT_SOCKET_TIMEOUT, 1000,
+ TimeUnit.MILLISECONDS);
+ warehouse = new Warehouse(conf);
+ client = new HiveMetaStoreClient(conf);
+ }
+
+ @AfterClass
+ public static void tearDown() throws Exception {
+ HiveMetaStore.TEST_TIMEOUT_ENABLED = false;
+ try {
+ client.close();
+ } catch (Throwable e) {
+ System.err.println("Unable to close metastore");
+ System.err.println(StringUtils.stringifyException(e));
+ throw e;
+ }
+ }
+
+ @Test
+ public void testNoTimeout() throws Exception {
+ HiveMetaStore.TEST_TIMEOUT_VALUE = 250;
+
+ String dbName = "db";
+ client.dropDatabase(dbName, true, true);
+
+ Database db = new Database();
+ db.setName(dbName);
+ try {
+ client.createDatabase(db);
+ } catch (MetaException e) {
+ Assert.fail("should not throw timeout exception: " + e.getMessage());
+ }
+
+ client.dropDatabase(dbName, true, true);
+ }
+
+ @Test
+ public void testTimeout() throws Exception {
+ HiveMetaStore.TEST_TIMEOUT_VALUE = 2 * 1000;
+
+ String dbName = "db";
+ client.dropDatabase(dbName, true, true);
+
+ Database db = new Database();
+ db.setName(dbName);
+ try {
+ client.createDatabase(db);
+ Assert.fail("should throw timeout exception.");
+ } catch (MetaException e) {
+ Assert.assertTrue("unexpected MetaException", e.getMessage().contains("Timeout when " +
+ "executing method: create_database"));
+ }
+
+ // restore
+ HiveMetaStore.TEST_TIMEOUT_VALUE = 1;
+ }
+
+ @Test
+ public void testResetTimeout() throws Exception {
+ HiveMetaStore.TEST_TIMEOUT_VALUE = 250;
+ String dbName = "db";
+
+ // no timeout before reset
+ client.dropDatabase(dbName, true, true);
+ Database db = new Database();
+ db.setName(dbName);
+ try {
+ client.createDatabase(db);
+ } catch (MetaException e) {
+ Assert.fail("should not throw timeout exception: " + e.getMessage());
+ }
+ client.dropDatabase(dbName, true, true);
+
+ // reset
+ HiveMetaStore.TEST_TIMEOUT_VALUE = 2000;
+ client.setMetaConf(ConfVars.CLIENT_SOCKET_TIMEOUT.getVarname(), "1s");
+
+ // timeout after reset
+ try {
+ client.createDatabase(db);
+ Assert.fail("should throw timeout exception.");
+ } catch (MetaException e) {
+ Assert.assertTrue("unexpected MetaException", e.getMessage().contains("Timeout when " +
+ "executing method: create_database"));
+ }
+
+ // restore
+ client.dropDatabase(dbName, true, true);
+ client.setMetaConf(ConfVars.CLIENT_SOCKET_TIMEOUT.getVarname(), "10s");
+ }
+}
\ No newline at end of file
[11/12] hive git commit: HIVE-17980 Moved HiveMetaStoreClient plus a
few remaining classes.
Posted by ga...@apache.org.
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/metastore/src/java/org/apache/hadoop/hive/metastore/HiveMetaStoreClient.java
----------------------------------------------------------------------
diff --git a/metastore/src/java/org/apache/hadoop/hive/metastore/HiveMetaStoreClient.java b/metastore/src/java/org/apache/hadoop/hive/metastore/HiveMetaStoreClient.java
deleted file mode 100644
index dfb0a6d..0000000
--- a/metastore/src/java/org/apache/hadoop/hive/metastore/HiveMetaStoreClient.java
+++ /dev/null
@@ -1,2719 +0,0 @@
-/**
- * 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.metastore.Warehouse.DEFAULT_DATABASE_NAME;
-import static org.apache.hadoop.hive.metastore.MetaStoreUtils.isIndexTable;
-
-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.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.Random;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.security.PrivilegedExceptionAction;
-
-import javax.security.auth.login.LoginException;
-
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.hive.common.ObjectPair;
-import org.apache.hadoop.hive.common.StatsSetupConst;
-import org.apache.hadoop.hive.common.ValidTxnList;
-import org.apache.hadoop.hive.common.auth.HiveAuthUtils;
-import org.apache.hadoop.hive.common.classification.InterfaceAudience;
-import org.apache.hadoop.hive.common.classification.InterfaceAudience.Public;
-import org.apache.hadoop.hive.common.classification.InterfaceStability.Unstable;
-import org.apache.hadoop.hive.conf.HiveConf;
-import org.apache.hadoop.hive.conf.HiveConf.ConfVars;
-import org.apache.hadoop.hive.conf.HiveConfUtil;
-import org.apache.hadoop.hive.metastore.api.*;
-import org.apache.hadoop.hive.metastore.TableType;
-import org.apache.hadoop.hive.metastore.conf.MetastoreConf;
-import org.apache.hadoop.hive.metastore.partition.spec.PartitionSpecProxy;
-import org.apache.hadoop.hive.metastore.security.HadoopThriftAuthBridge;
-import org.apache.hadoop.hive.metastore.txn.TxnUtils;
-import org.apache.hadoop.hive.metastore.utils.SecurityUtils;
-import org.apache.hadoop.hive.shims.Utils;
-import org.apache.hadoop.security.UserGroupInformation;
-import org.apache.hadoop.util.StringUtils;
-import org.apache.thrift.TApplicationException;
-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.TFramedTransport;
-import org.apache.thrift.transport.TSocket;
-import org.apache.thrift.transport.TTransport;
-import org.apache.thrift.transport.TTransportException;
-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.
- */
-@Public
-@Unstable
-public class HiveMetaStoreClient implements IMetaStoreClient, AutoCloseable {
- /**
- * 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));
-
- ThriftHiveMetastore.Iface client = null;
- private TTransport transport = null;
- private boolean isConnected = false;
- private URI metastoreUris[];
- private final HiveMetaHookLoader hookLoader;
- protected final HiveConf conf; // Keep a copy of HiveConf so if Session conf changes, we may need to get a new HMS client.
- protected boolean fastpath = false;
- private String tokenStrForm;
- private final boolean localMetaStore;
- private final MetaStoreFilterHook filterHook;
- 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;
-
- static final protected Logger LOG = LoggerFactory.getLogger(HiveMetaStoreClient.class);
-
- public HiveMetaStoreClient(HiveConf conf) throws MetaException {
- this(conf, null, true);
- }
-
- public HiveMetaStoreClient(HiveConf conf, HiveMetaHookLoader hookLoader) throws MetaException {
- this(conf, hookLoader, true);
- }
-
- public HiveMetaStoreClient(HiveConf conf, HiveMetaHookLoader hookLoader, Boolean allowEmbedded)
- throws MetaException {
-
- this.hookLoader = hookLoader;
- if (conf == null) {
- conf = new HiveConf(HiveMetaStoreClient.class);
- this.conf = conf;
- } else {
- this.conf = new HiveConf(conf);
- }
- version = HiveConf.getBoolVar(conf, ConfVars.HIVE_IN_TEST) ? TEST_VERSION : VERSION;
- filterHook = loadFilterHooks();
- fileMetadataBatchSize = HiveConf.getIntVar(
- conf, HiveConf.ConfVars.METASTORE_BATCH_RETRIEVE_OBJECTS_MAX);
-
- String msUri = conf.getVar(ConfVars.METASTOREURIS);
- localMetaStore = HiveConfUtil.isEmbeddedMetaStore(msUri);
- if (localMetaStore) {
- if (!allowEmbedded) {
- throw new MetaException("Embedded metastore is not allowed here. Please configure "
- + ConfVars.METASTOREURIS.varname + "; it is currently set to [" + msUri + "]");
- }
- // instantiate the metastore server handler directly instead of connecting
- // through the network
- if (conf.getBoolVar(ConfVars.METASTORE_FASTPATH)) {
- client = new HiveMetaStore.HMSHandler("hive client", this.conf, true);
- fastpath = true;
- } else {
- client = HiveMetaStore.newRetryingHMSHandler("hive client", this.conf, true);
- }
- isConnected = true;
- snapshotActiveConf();
- return;
- } else {
- if (conf.getBoolVar(ConfVars.METASTORE_FASTPATH)) {
- throw new RuntimeException("You can't set hive.metastore.fastpath to true when you're " +
- "talking to the thrift metastore service. You must run the metastore locally.");
- }
- }
-
- // get the number retries
- retries = HiveConf.getIntVar(conf, HiveConf.ConfVars.METASTORETHRIFTCONNECTIONRETRIES);
- retryDelaySeconds = conf.getTimeVar(
- ConfVars.METASTORE_CLIENT_CONNECT_RETRY_DELAY, TimeUnit.SECONDS);
-
- // user wants file store based configuration
- if (conf.getVar(HiveConf.ConfVars.METASTOREURIS) != null) {
- String metastoreUrisString[] = conf.getVar(
- HiveConf.ConfVars.METASTOREURIS).split(",");
- metastoreUris = new URI[metastoreUrisString.length];
- try {
- int i = 0;
- for (String s : metastoreUrisString) {
- URI tmpUri = new URI(s);
- if (tmpUri.getScheme() == null) {
- throw new IllegalArgumentException("URI: " + s
- + " does not have a scheme");
- }
- metastoreUris[i++] = new URI(
- tmpUri.getScheme(),
- tmpUri.getUserInfo(),
- HadoopThriftAuthBridge.getBridge().getCanonicalHostName(tmpUri.getHost()),
- tmpUri.getPort(),
- tmpUri.getPath(),
- tmpUri.getQuery(),
- tmpUri.getFragment()
- );
-
- }
- // make metastore URIS random
- List<?> uriList = Arrays.asList(metastoreUris);
- Collections.shuffle(uriList);
- metastoreUris = (URI[]) uriList.toArray();
- } catch (IllegalArgumentException e) {
- throw (e);
- } catch (Exception e) {
- MetaStoreUtils.logAndThrowMetaException(e);
- }
- } 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);
- this.conf.setVar(ConfVars.METASTORE_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();
- }
-
- private MetaStoreFilterHook loadFilterHooks() throws IllegalStateException {
- Class<? extends MetaStoreFilterHook> authProviderClass = conf.
- getClass(HiveConf.ConfVars.METASTORE_FILTER_HOOK.varname,
- 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 e) {
- throw new IllegalStateException(msg + e.getMessage(), e);
- } catch (SecurityException e) {
- throw new IllegalStateException(msg + e.getMessage(), e);
- } catch (InstantiationException e) {
- throw new IllegalStateException(msg + e.getMessage(), e);
- } catch (IllegalAccessException e) {
- throw new IllegalStateException(msg + e.getMessage(), e);
- } catch (IllegalArgumentException e) {
- throw new IllegalStateException(msg + e.getMessage(), e);
- } catch (InvocationTargetException e) {
- throw new IllegalStateException(msg + e.getMessage(), e);
- }
- }
-
- /**
- * 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(HiveConf 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 : HiveConf.metaVars) {
- // Since metaVars are all of different types, use string for comparison
- String oldVar = currentMetaVarsCopy.get(oneVar.varname);
- String newVar = conf.get(oneVar.varname, "");
- if (oldVar == null ||
- (oneVar.isCaseSensitive() ? !oldVar.equals(newVar) : !oldVar.equalsIgnoreCase(newVar))) {
- LOG.info("Mestastore configuration " + oneVar.varname +
- " changed from " + oldVar + " to " + newVar);
- compatible = false;
- }
- }
- return compatible;
- }
-
- @Override
- public void setHiveAddedJars(String addedJars) {
- HiveConf.setVar(conf, ConfVars.HIVEADDEDJARS, addedJars);
- }
-
- @Override
- public void reconnect() throws MetaException {
- if (localMetaStore) {
- // For direct DB connections we don't yet support reestablishing connections.
- throw new MetaException("For direct MetaStore DB connections, we don't support retries" +
- " at the client level.");
- } else {
- close();
- // 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();
- }
- }
-
- /**
- * @param dbname
- * @param tbl_name
- * @param new_tbl
- * @throws InvalidOperationException
- * @throws MetaException
- * @throws TException
- * @see
- * org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#alter_table(
- * java.lang.String, java.lang.String,
- * org.apache.hadoop.hive.metastore.api.Table)
- */
- @Override
- public void alter_table(String dbname, String tbl_name, Table new_tbl)
- throws InvalidOperationException, MetaException, 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 InvalidOperationException, MetaException, 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 {
- client.alter_table_with_environment_context(dbname, tbl_name, new_tbl, envContext);
- }
-
- /**
- * @param dbname
- * @param name
- * @param part_vals
- * @param newPart
- * @throws InvalidOperationException
- * @throws MetaException
- * @throws TException
- * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#rename_partition(
- * java.lang.String, java.lang.String, java.util.List, org.apache.hadoop.hive.metastore.api.Partition)
- */
- @Override
- public void renamePartition(final String dbname, final String name, final List<String> part_vals, final Partition newPart)
- throws InvalidOperationException, MetaException, TException {
- client.rename_partition(dbname, name, part_vals, newPart);
- }
-
- private void open() throws MetaException {
- isConnected = false;
- TTransportException tte = null;
- boolean useSSL = conf.getBoolVar(ConfVars.HIVE_METASTORE_USE_SSL);
- boolean useSasl = conf.getBoolVar(ConfVars.METASTORE_USE_THRIFT_SASL);
- boolean useFramedTransport = conf.getBoolVar(ConfVars.METASTORE_USE_THRIFT_FRAMED_TRANSPORT);
- boolean useCompactProtocol = conf.getBoolVar(ConfVars.METASTORE_USE_THRIFT_COMPACT_PROTOCOL);
- int clientSocketTimeout = (int) conf.getTimeVar(
- ConfVars.METASTORE_CLIENT_SOCKET_TIMEOUT, TimeUnit.MILLISECONDS);
-
- for (int attempt = 0; !isConnected && attempt < retries; ++attempt) {
- for (URI store : metastoreUris) {
- LOG.info("Trying to connect to metastore with URI " + store);
-
- try {
- if (useSSL) {
- try {
- String trustStorePath = conf.getVar(ConfVars.HIVE_METASTORE_SSL_TRUSTSTORE_PATH).trim();
- if (trustStorePath.isEmpty()) {
- throw new IllegalArgumentException(ConfVars.HIVE_METASTORE_SSL_TRUSTSTORE_PATH.varname
- + " Not configured for SSL connection");
- }
- String trustStorePassword =
- MetastoreConf.getPassword(conf, MetastoreConf.ConfVars.SSL_TRUSTSTORE_PASSWORD);
-
- // Create an SSL socket and connect
- transport = HiveAuthUtils.getSSLSocket(store.getHost(), store.getPort(), clientSocketTimeout, trustStorePath, trustStorePassword );
- LOG.info("Opened an SSL connection to metastore, current connections: " + connCount.incrementAndGet());
- } catch(IOException e) {
- throw new IllegalArgumentException(e);
- } catch(TTransportException e) {
- tte = e;
- throw new MetaException(e.toString());
- }
- } else {
- transport = new TSocket(store.getHost(), store.getPort(), clientSocketTimeout);
- }
-
- 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 = conf.getVar(ConfVars.METASTORE_TOKEN_SIGNATURE);
- // tokenSig could be null
- tokenStrForm = SecurityUtils.getTokenStrForm(tokenSig);
-
- if(tokenStrForm != null) {
- LOG.info("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, transport,
- MetaStoreUtils.getMetaStoreSaslProperties(conf, useSSL));
- } else {
- LOG.info("HMSC::open(): Could not find delegation token. Creating KERBEROS-based thrift connection.");
- String principalConfig =
- conf.getVar(HiveConf.ConfVars.METASTORE_KERBEROS_PRINCIPAL);
- transport = authBridge.createClientTransport(
- principalConfig, store.getHost(), "KERBEROS", null,
- transport, MetaStoreUtils.getMetaStoreSaslProperties(conf, useSSL));
- }
- } catch (IOException ioe) {
- LOG.error("Couldn't create client transport", ioe);
- throw new MetaException(ioe.toString());
- }
- } else {
- if (useFramedTransport) {
- transport = new TFramedTransport(transport);
- }
- }
-
- 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();
- LOG.info("Opened a connection to metastore, current connections: " + connCount.incrementAndGet());
- }
- isConnected = true;
- } catch (TTransportException e) {
- tte = e;
- if (LOG.isDebugEnabled()) {
- LOG.warn("Failed to connect to the MetaStore Server...", e);
- } else {
- // Don't print full exception trace if DEBUG is not on.
- LOG.warn("Failed to connect to the MetaStore Server...");
- }
- }
-
- if (isConnected && !useSasl && conf.getBoolVar(ConfVars.METASTORE_EXECUTE_SET_UGI)){
- // Call set_ugi, only in unsecure mode.
- try {
- UserGroupInformation ugi = Utils.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) {
- LOG.error("Unable to connect to metastore with URI " + store
- + " in attempt " + attempt, 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) {
- throw new MetaException("Could not connect to meta store using any of the URIs provided." +
- " Most recent failure: " + StringUtils.stringifyException(tte));
- }
-
- snapshotActiveConf();
-
- LOG.info("Connected to metastore.");
- }
-
- private void snapshotActiveConf() {
- currentMetaVars = new HashMap<String, String>(HiveConf.metaVars.length);
- for (ConfVars oneVar : HiveConf.metaVars) {
- currentMetaVars.put(oneVar.varname, conf.get(oneVar.varname, ""));
- }
- }
-
- @Override
- public String getTokenStrForm() throws IOException {
- return tokenStrForm;
- }
-
- @Override
- public void close() {
- isConnected = false;
- currentMetaVars = null;
- try {
- if (null != client) {
- client.shutdown();
- }
- } 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();
- LOG.info("Closed a connection to metastore, current connections: " + connCount.decrementAndGet());
- }
- }
-
- @Override
- public void setMetaConf(String key, String value) throws TException {
- client.setMetaConf(key, value);
- }
-
- @Override
- public String getMetaConf(String key) throws TException {
- return client.getMetaConf(key);
- }
-
- /**
- * @param new_part
- * @return the added partition
- * @throws InvalidObjectException
- * @throws AlreadyExistsException
- * @throws MetaException
- * @throws TException
- * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#add_partition(org.apache.hadoop.hive.metastore.api.Partition)
- */
- @Override
- public Partition add_partition(Partition new_part)
- throws InvalidObjectException, AlreadyExistsException, MetaException,
- TException {
- return add_partition(new_part, null);
- }
-
- public Partition add_partition(Partition new_part, EnvironmentContext envContext)
- throws InvalidObjectException, AlreadyExistsException, MetaException,
- TException {
- Partition p = client.add_partition_with_environment_context(new_part, envContext);
- return fastpath ? p : deepCopy(p);
- }
-
- /**
- * @param new_parts
- * @throws InvalidObjectException
- * @throws AlreadyExistsException
- * @throws MetaException
- * @throws TException
- * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#add_partitions(List)
- */
- @Override
- public int add_partitions(List<Partition> new_parts)
- throws InvalidObjectException, AlreadyExistsException, MetaException,
- TException {
- return client.add_partitions(new_parts);
- }
-
- @Override
- public List<Partition> add_partitions(
- List<Partition> parts, boolean ifNotExists, boolean needResults)
- throws InvalidObjectException, AlreadyExistsException, MetaException, TException {
- if (parts.isEmpty()) {
- return needResults ? new ArrayList<Partition>() : null;
- }
- Partition part = parts.get(0);
- AddPartitionsRequest req = new AddPartitionsRequest(
- part.getDbName(), part.getTableName(), parts, ifNotExists);
- req.setNeedResult(needResults);
- AddPartitionsResult result = client.add_partitions_req(req);
- return needResults ? filterHook.filterPartitions(result.getPartitions()) : null;
- }
-
- @Override
- public int add_partitions_pspec(PartitionSpecProxy partitionSpec) throws TException {
- return client.add_partitions_pspec(partitionSpec.toPartitionSpec());
- }
-
- /**
- * @param table_name
- * @param db_name
- * @param part_vals
- * @return the appended partition
- * @throws InvalidObjectException
- * @throws AlreadyExistsException
- * @throws MetaException
- * @throws TException
- * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#append_partition(java.lang.String,
- * java.lang.String, java.util.List)
- */
- @Override
- public Partition appendPartition(String db_name, String table_name,
- List<String> part_vals) throws InvalidObjectException,
- AlreadyExistsException, MetaException, TException {
- return appendPartition(db_name, table_name, part_vals, null);
- }
-
- public Partition appendPartition(String db_name, String table_name, List<String> part_vals,
- EnvironmentContext envContext) throws InvalidObjectException, AlreadyExistsException,
- MetaException, TException {
- Partition p = client.append_partition_with_environment_context(db_name, table_name,
- part_vals, envContext);
- return fastpath ? p : deepCopy(p);
- }
-
- @Override
- public Partition appendPartition(String dbName, String tableName, String partName)
- throws InvalidObjectException, AlreadyExistsException, MetaException, TException {
- return appendPartition(dbName, tableName, partName, null);
- }
-
- public Partition appendPartition(String dbName, String tableName, String partName,
- EnvironmentContext envContext) throws InvalidObjectException, AlreadyExistsException,
- MetaException, TException {
- Partition p = client.append_partition_by_name_with_environment_context(dbName, tableName,
- partName, envContext);
- return fastpath ? p : deepCopy(p);
- }
-
- /**
- * Exchange the partition between two tables
- * @param partitionSpecs partitions specs of the parent partition to be exchanged
- * @param destDb the db of the destination table
- * @param destinationTableName the destination table name
- * @return new partition after exchanging
- */
- @Override
- public Partition exchange_partition(Map<String, String> partitionSpecs,
- String sourceDb, String sourceTable, String destDb,
- String destinationTableName) throws MetaException,
- NoSuchObjectException, InvalidObjectException, TException {
- return client.exchange_partition(partitionSpecs, sourceDb, sourceTable,
- destDb, destinationTableName);
- }
-
- /**
- * Exchange the partitions between two tables
- * @param partitionSpecs partitions specs of the parent partition to be exchanged
- * @param destDb the db of the destination table
- * @param destinationTableName the destination table name
- * @return new partitions after exchanging
- */
- @Override
- public List<Partition> exchange_partitions(Map<String, String> partitionSpecs,
- String sourceDb, String sourceTable, String destDb,
- String destinationTableName) throws MetaException,
- NoSuchObjectException, InvalidObjectException, TException {
- return client.exchange_partitions(partitionSpecs, sourceDb, sourceTable,
- destDb, destinationTableName);
- }
-
- @Override
- public void validatePartitionNameCharacters(List<String> partVals)
- throws TException, MetaException {
- client.partition_name_has_valid_characters(partVals, true);
- }
-
- /**
- * Create a new Database
- * @param db
- * @throws AlreadyExistsException
- * @throws InvalidObjectException
- * @throws MetaException
- * @throws TException
- * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#create_database(Database)
- */
- @Override
- public void createDatabase(Database db)
- throws AlreadyExistsException, InvalidObjectException, MetaException, TException {
- client.create_database(db);
- }
-
- /**
- * @param tbl
- * @throws MetaException
- * @throws NoSuchObjectException
- * @throws TException
- * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#create_table(org.apache.hadoop.hive.metastore.api.Table)
- */
- @Override
- public void createTable(Table tbl) throws AlreadyExistsException,
- InvalidObjectException, MetaException, NoSuchObjectException, TException {
- createTable(tbl, null);
- }
-
- public void createTable(Table tbl, EnvironmentContext envContext) throws AlreadyExistsException,
- InvalidObjectException, MetaException, NoSuchObjectException, TException {
- HiveMetaHook hook = getHook(tbl);
- if (hook != null) {
- hook.preCreateTable(tbl);
- }
- boolean success = false;
- try {
- // Subclasses can override this step (for example, for temporary tables)
- create_table_with_environment_context(tbl, envContext);
- if (hook != null) {
- hook.commitCreateTable(tbl);
- }
- success = true;
- }
- finally {
- if (!success && (hook != null)) {
- try {
- hook.rollbackCreateTable(tbl);
- } catch (Exception e){
- LOG.error("Create rollback failed with", e);
- }
- }
- }
- }
-
- @Override
- public void createTableWithConstraints(Table tbl,
- List<SQLPrimaryKey> primaryKeys, List<SQLForeignKey> foreignKeys,
- List<SQLUniqueConstraint> uniqueConstraints,
- List<SQLNotNullConstraint> notNullConstraints)
- throws AlreadyExistsException, InvalidObjectException,
- MetaException, NoSuchObjectException, TException {
- HiveMetaHook hook = getHook(tbl);
- if (hook != null) {
- hook.preCreateTable(tbl);
- }
- boolean success = false;
- try {
- // Subclasses can override this step (for example, for temporary tables)
- client.create_table_with_constraints(tbl, primaryKeys, foreignKeys,
- uniqueConstraints, notNullConstraints);
- if (hook != null) {
- hook.commitCreateTable(tbl);
- }
- success = true;
- } finally {
- if (!success && (hook != null)) {
- hook.rollbackCreateTable(tbl);
- }
- }
- }
-
- @Override
- public void dropConstraint(String dbName, String tableName, String constraintName) throws
- NoSuchObjectException, MetaException, TException {
- client.drop_constraint(new DropConstraintRequest(dbName, tableName, constraintName));
- }
-
- @Override
- public void addPrimaryKey(List<SQLPrimaryKey> primaryKeyCols) throws
- NoSuchObjectException, MetaException, TException {
- client.add_primary_key(new AddPrimaryKeyRequest(primaryKeyCols));
- }
-
- @Override
- public void addForeignKey(List<SQLForeignKey> foreignKeyCols) throws
- NoSuchObjectException, MetaException, TException {
- client.add_foreign_key(new AddForeignKeyRequest(foreignKeyCols));
- }
-
- @Override
- public void addUniqueConstraint(List<SQLUniqueConstraint> uniqueConstraintCols) throws
- NoSuchObjectException, MetaException, TException {
- client.add_unique_constraint(new AddUniqueConstraintRequest(uniqueConstraintCols));
- }
-
- @Override
- public void addNotNullConstraint(List<SQLNotNullConstraint> notNullConstraintCols) throws
- NoSuchObjectException, MetaException, TException {
- client.add_not_null_constraint(new AddNotNullConstraintRequest(notNullConstraintCols));
- }
-
- /**
- * @param type
- * @return true or false
- * @throws AlreadyExistsException
- * @throws InvalidObjectException
- * @throws MetaException
- * @throws TException
- * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#create_type(org.apache.hadoop.hive.metastore.api.Type)
- */
- public boolean createType(Type type) throws AlreadyExistsException,
- InvalidObjectException, MetaException, TException {
- return client.create_type(type);
- }
-
- /**
- * @param name
- * @throws NoSuchObjectException
- * @throws InvalidOperationException
- * @throws MetaException
- * @throws TException
- * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#drop_database(java.lang.String, boolean, boolean)
- */
- @Override
- public void dropDatabase(String name)
- throws NoSuchObjectException, InvalidOperationException, MetaException, TException {
- dropDatabase(name, true, false, false);
- }
-
- @Override
- public void dropDatabase(String name, boolean deleteData, boolean ignoreUnknownDb)
- throws NoSuchObjectException, InvalidOperationException, MetaException, TException {
- dropDatabase(name, deleteData, ignoreUnknownDb, false);
- }
-
- @Override
- public void dropDatabase(String name, boolean deleteData, boolean ignoreUnknownDb, boolean cascade)
- throws NoSuchObjectException, InvalidOperationException, MetaException, TException {
- try {
- getDatabase(name);
- } catch (NoSuchObjectException e) {
- if (!ignoreUnknownDb) {
- throw e;
- }
- return;
- }
-
- if (cascade) {
- List<String> tableList = getAllTables(name);
- for (String table : tableList) {
- try {
- // Subclasses can override this step (for example, for temporary tables)
- dropTable(name, table, deleteData, true);
- } catch (UnsupportedOperationException e) {
- // Ignore Index tables, those will be dropped with parent tables
- }
- }
- }
- client.drop_database(name, deleteData, cascade);
- }
-
- /**
- * @param tbl_name
- * @param db_name
- * @param part_vals
- * @return true or false
- * @throws NoSuchObjectException
- * @throws MetaException
- * @throws TException
- * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#drop_partition(java.lang.String,
- * java.lang.String, java.util.List, boolean)
- */
- public boolean dropPartition(String db_name, String tbl_name,
- List<String> part_vals) throws NoSuchObjectException, MetaException,
- TException {
- return dropPartition(db_name, tbl_name, part_vals, true, null);
- }
-
- public boolean dropPartition(String db_name, String tbl_name, List<String> part_vals,
- EnvironmentContext env_context) throws NoSuchObjectException, MetaException, TException {
- return dropPartition(db_name, tbl_name, part_vals, true, env_context);
- }
-
- @Override
- public boolean dropPartition(String dbName, String tableName, String partName, boolean deleteData)
- throws NoSuchObjectException, MetaException, TException {
- return dropPartition(dbName, tableName, partName, deleteData, null);
- }
-
- private static EnvironmentContext getEnvironmentContextWithIfPurgeSet() {
- Map<String, String> warehouseOptions = new HashMap<String, String>();
- warehouseOptions.put("ifPurge", "TRUE");
- return new EnvironmentContext(warehouseOptions);
- }
-
- /*
- public boolean dropPartition(String dbName, String tableName, String partName, boolean deleteData, boolean ifPurge)
- throws NoSuchObjectException, MetaException, TException {
-
- return dropPartition(dbName, tableName, partName, deleteData,
- ifPurge? getEnvironmentContextWithIfPurgeSet() : null);
- }
- */
-
- public boolean dropPartition(String dbName, String tableName, String partName, boolean deleteData,
- EnvironmentContext envContext) throws NoSuchObjectException, MetaException, TException {
- return client.drop_partition_by_name_with_environment_context(dbName, tableName, partName,
- deleteData, envContext);
- }
-
- /**
- * @param db_name
- * @param tbl_name
- * @param part_vals
- * @param deleteData
- * delete the underlying data or just delete the table in metadata
- * @return true or false
- * @throws NoSuchObjectException
- * @throws MetaException
- * @throws TException
- * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#drop_partition(java.lang.String,
- * java.lang.String, java.util.List, boolean)
- */
- @Override
- public boolean dropPartition(String db_name, String tbl_name,
- List<String> part_vals, boolean deleteData) throws NoSuchObjectException,
- MetaException, TException {
- return dropPartition(db_name, tbl_name, part_vals, deleteData, null);
- }
-
- @Override
- public boolean dropPartition(String db_name, String tbl_name,
- List<String> part_vals, PartitionDropOptions options) throws TException {
- return dropPartition(db_name, tbl_name, part_vals, options.deleteData,
- options.purgeData? getEnvironmentContextWithIfPurgeSet() : null);
- }
-
- public boolean dropPartition(String db_name, String tbl_name, List<String> part_vals,
- boolean deleteData, EnvironmentContext envContext) throws NoSuchObjectException,
- MetaException, TException {
- return client.drop_partition_with_environment_context(db_name, tbl_name, part_vals, deleteData,
- envContext);
- }
-
- @Override
- public List<Partition> dropPartitions(String dbName, String tblName,
- List<ObjectPair<Integer, byte[]>> partExprs, PartitionDropOptions options)
- throws TException {
- RequestPartsSpec rps = new RequestPartsSpec();
- List<DropPartitionsExpr> exprs = new ArrayList<DropPartitionsExpr>(partExprs.size());
- for (ObjectPair<Integer, byte[]> partExpr : partExprs) {
- DropPartitionsExpr dpe = new DropPartitionsExpr();
- dpe.setExpr(partExpr.getSecond());
- dpe.setPartArchiveLevel(partExpr.getFirst());
- exprs.add(dpe);
- }
- rps.setExprs(exprs);
- DropPartitionsRequest req = new DropPartitionsRequest(dbName, tblName, rps);
- req.setDeleteData(options.deleteData);
- req.setNeedResult(options.returnResults);
- req.setIfExists(options.ifExists);
- if (options.purgeData) {
- LOG.info("Dropped partitions will be purged!");
- req.setEnvironmentContext(getEnvironmentContextWithIfPurgeSet());
- }
- return client.drop_partitions_req(req).getPartitions();
- }
-
- @Override
- public List<Partition> dropPartitions(String dbName, String tblName,
- List<ObjectPair<Integer, byte[]>> partExprs, boolean deleteData,
- boolean ifExists, boolean needResult) throws NoSuchObjectException, MetaException, TException {
-
- return dropPartitions(dbName, tblName, partExprs,
- PartitionDropOptions.instance()
- .deleteData(deleteData)
- .ifExists(ifExists)
- .returnResults(needResult));
-
- }
-
- @Override
- public List<Partition> dropPartitions(String dbName, String tblName,
- List<ObjectPair<Integer, byte[]>> partExprs, boolean deleteData,
- boolean ifExists) throws NoSuchObjectException, MetaException, TException {
- // By default, we need the results from dropPartitions();
- return dropPartitions(dbName, tblName, partExprs,
- PartitionDropOptions.instance()
- .deleteData(deleteData)
- .ifExists(ifExists));
- }
-
- /**
- * {@inheritDoc}
- * @see #dropTable(String, String, boolean, boolean, EnvironmentContext)
- */
- @Override
- public void dropTable(String dbname, String name, boolean deleteData,
- boolean ignoreUnknownTab) throws MetaException, TException,
- NoSuchObjectException, UnsupportedOperationException {
- dropTable(dbname, name, deleteData, ignoreUnknownTab, null);
- }
-
- /**
- * Drop the table and choose whether to save the data in the trash.
- * @param ifPurge completely purge the table (skipping trash) while removing
- * data from warehouse
- * @see #dropTable(String, String, boolean, boolean, EnvironmentContext)
- */
- @Override
- public void dropTable(String dbname, String name, boolean deleteData,
- boolean ignoreUnknownTab, boolean ifPurge)
- throws MetaException, TException, NoSuchObjectException, UnsupportedOperationException {
- //build new environmentContext with ifPurge;
- EnvironmentContext envContext = null;
- if(ifPurge){
- Map<String, String> warehouseOptions = null;
- warehouseOptions = new HashMap<String, String>();
- warehouseOptions.put("ifPurge", "TRUE");
- envContext = new EnvironmentContext(warehouseOptions);
- }
- dropTable(dbname, name, deleteData, ignoreUnknownTab, envContext);
- }
-
- /** {@inheritDoc} */
- @Override
- @Deprecated
- public void dropTable(String tableName, boolean deleteData)
- throws MetaException, UnknownTableException, TException, NoSuchObjectException {
- dropTable(DEFAULT_DATABASE_NAME, tableName, deleteData, false, null);
- }
-
- /**
- * @see #dropTable(String, String, boolean, boolean, EnvironmentContext)
- */
- @Override
- public void dropTable(String dbname, String name)
- throws NoSuchObjectException, MetaException, TException {
- dropTable(dbname, name, true, true, null);
- }
-
- /**
- * Drop the table and choose whether to: delete the underlying table data;
- * throw if the table doesn't exist; save the data in the trash.
- *
- * @param dbname
- * @param name
- * @param deleteData
- * delete the underlying data or just delete the table in metadata
- * @param ignoreUnknownTab
- * don't throw if the requested table doesn't exist
- * @param envContext
- * for communicating with thrift
- * @throws MetaException
- * could not drop table properly
- * @throws NoSuchObjectException
- * the table wasn't found
- * @throws TException
- * a thrift communication error occurred
- * @throws UnsupportedOperationException
- * dropping an index table is not allowed
- * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#drop_table(java.lang.String,
- * java.lang.String, boolean)
- */
- public void dropTable(String dbname, String name, boolean deleteData,
- boolean ignoreUnknownTab, EnvironmentContext envContext) throws MetaException, TException,
- NoSuchObjectException, UnsupportedOperationException {
- Table tbl;
- try {
- tbl = getTable(dbname, name);
- } catch (NoSuchObjectException e) {
- if (!ignoreUnknownTab) {
- throw e;
- }
- return;
- }
- if (isIndexTable(tbl)) {
- throw new UnsupportedOperationException("Cannot drop index tables");
- }
- HiveMetaHook hook = getHook(tbl);
- if (hook != null) {
- hook.preDropTable(tbl);
- }
- boolean success = false;
- try {
- drop_table_with_environment_context(dbname, name, deleteData, envContext);
- if (hook != null) {
- hook.commitDropTable(tbl, deleteData || (envContext != null && "TRUE".equals(envContext.getProperties().get("ifPurge"))));
- }
- success=true;
- } catch (NoSuchObjectException e) {
- if (!ignoreUnknownTab) {
- throw e;
- }
- } finally {
- if (!success && (hook != null)) {
- hook.rollbackDropTable(tbl);
- }
- }
- }
-
- /**
- * Truncate the table/partitions in the DEFAULT database.
- * @param dbName
- * The db to which the table to be truncate belongs to
- * @param tableName
- * The table to truncate
- * @param partNames
- * List of partitions to truncate. NULL will truncate the whole table/all partitions
- * @throws MetaException
- * @throws TException
- * Could not truncate table properly.
- */
- @Override
- public void truncateTable(String dbName, String tableName, List<String> partNames) throws MetaException, TException {
- client.truncate_table(dbName, tableName, partNames);
- }
-
- /**
- * Recycles the files recursively from the input path to the cmroot directory either by copying or moving it.
- *
- * @param request Inputs for path of the data files to be recycled to cmroot and
- * isPurge flag when set to true files which needs to be recycled are not moved to Trash
- * @return Response which is currently void
- */
- @Override
- public CmRecycleResponse recycleDirToCmPath(CmRecycleRequest request) throws MetaException, TException {
- return client.cm_recycle(request);
- }
-
- /**
- * @param type
- * @return true if the type is dropped
- * @throws MetaException
- * @throws TException
- * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#drop_type(java.lang.String)
- */
- public boolean dropType(String type) throws NoSuchObjectException, MetaException, TException {
- return client.drop_type(type);
- }
-
- /**
- * @param name
- * @return map of types
- * @throws MetaException
- * @throws TException
- * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#get_type_all(java.lang.String)
- */
- public Map<String, Type> getTypeAll(String name) throws MetaException,
- TException {
- Map<String, Type> result = null;
- Map<String, Type> fromClient = client.get_type_all(name);
- if (fromClient != null) {
- result = new LinkedHashMap<String, Type>();
- for (String key : fromClient.keySet()) {
- result.put(key, deepCopy(fromClient.get(key)));
- }
- }
- return result;
- }
-
- /** {@inheritDoc} */
- @Override
- public List<String> getDatabases(String databasePattern)
- throws MetaException {
- try {
- return filterHook.filterDatabases(client.get_databases(databasePattern));
- } catch (Exception e) {
- MetaStoreUtils.logAndThrowMetaException(e);
- }
- return null;
- }
-
- /** {@inheritDoc} */
- @Override
- public List<String> getAllDatabases() throws MetaException {
- try {
- return filterHook.filterDatabases(client.get_all_databases());
- } catch (Exception e) {
- MetaStoreUtils.logAndThrowMetaException(e);
- }
- return null;
- }
-
- /**
- * @param tbl_name
- * @param db_name
- * @param max_parts
- * @return list of partitions
- * @throws NoSuchObjectException
- * @throws MetaException
- * @throws TException
- */
- @Override
- public List<Partition> listPartitions(String db_name, String tbl_name,
- short max_parts) throws NoSuchObjectException, MetaException, TException {
- List<Partition> parts = client.get_partitions(db_name, tbl_name, max_parts);
- return fastpath ? parts : deepCopyPartitions(filterHook.filterPartitions(parts));
- }
-
- @Override
- public PartitionSpecProxy listPartitionSpecs(String dbName, String tableName, int maxParts) throws TException {
- return PartitionSpecProxy.Factory.get(filterHook.filterPartitionSpecs(
- client.get_partitions_pspec(dbName, tableName, maxParts)));
- }
-
- @Override
- public List<Partition> listPartitions(String db_name, String tbl_name,
- List<String> part_vals, short max_parts)
- throws NoSuchObjectException, MetaException, TException {
- List<Partition> parts = client.get_partitions_ps(db_name, tbl_name, part_vals, max_parts);
- return fastpath ? parts : deepCopyPartitions(filterHook.filterPartitions(parts));
- }
-
- @Override
- public List<Partition> listPartitionsWithAuthInfo(String db_name,
- String tbl_name, short max_parts, String user_name, List<String> group_names)
- throws NoSuchObjectException, MetaException, TException {
- List<Partition> parts = client.get_partitions_with_auth(db_name, tbl_name, max_parts,
- user_name, group_names);
- return fastpath ? parts :deepCopyPartitions(filterHook.filterPartitions(parts));
- }
-
- @Override
- public List<Partition> listPartitionsWithAuthInfo(String db_name,
- String tbl_name, List<String> part_vals, short max_parts,
- String user_name, List<String> group_names) throws NoSuchObjectException,
- MetaException, TException {
- List<Partition> parts = client.get_partitions_ps_with_auth(db_name,
- tbl_name, part_vals, max_parts, user_name, group_names);
- return fastpath ? parts : deepCopyPartitions(filterHook.filterPartitions(parts));
- }
-
- /**
- * Get list of partitions matching specified filter
- * @param db_name the database name
- * @param tbl_name the table name
- * @param filter the filter string,
- * for example "part1 = \"p1_abc\" and part2 <= "\p2_test\"". Filtering can
- * be done only on string partition keys.
- * @param max_parts the maximum number of partitions to return,
- * all partitions are returned if -1 is passed
- * @return list of partitions
- * @throws MetaException
- * @throws NoSuchObjectException
- * @throws TException
- */
- @Override
- public List<Partition> listPartitionsByFilter(String db_name, String tbl_name,
- String filter, short max_parts) throws MetaException,
- NoSuchObjectException, TException {
- List<Partition> parts = client.get_partitions_by_filter(db_name, tbl_name, filter, max_parts);
- return fastpath ? parts :deepCopyPartitions(filterHook.filterPartitions(parts));
- }
-
- @Override
- public PartitionSpecProxy listPartitionSpecsByFilter(String db_name, String tbl_name,
- String filter, int max_parts) throws MetaException,
- NoSuchObjectException, TException {
- return PartitionSpecProxy.Factory.get(filterHook.filterPartitionSpecs(
- client.get_part_specs_by_filter(db_name, tbl_name, filter, max_parts)));
- }
-
- @Override
- public boolean listPartitionsByExpr(String db_name, String tbl_name, byte[] expr,
- String default_partition_name, short max_parts, List<Partition> result)
- throws TException {
- assert result != null;
- PartitionsByExprRequest req = new PartitionsByExprRequest(
- db_name, tbl_name, ByteBuffer.wrap(expr));
- if (default_partition_name != null) {
- req.setDefaultPartitionName(default_partition_name);
- }
- if (max_parts >= 0) {
- req.setMaxParts(max_parts);
- }
- PartitionsByExprResult r = null;
- try {
- r = client.get_partitions_by_expr(req);
- } catch (TApplicationException te) {
- // TODO: backward compat for Hive <= 0.12. Can be removed later.
- if (te.getType() != TApplicationException.UNKNOWN_METHOD
- && te.getType() != TApplicationException.WRONG_METHOD_NAME) {
- throw te;
- }
- throw new IncompatibleMetastoreException(
- "Metastore doesn't support listPartitionsByExpr: " + te.getMessage());
- }
- if (fastpath) {
- result.addAll(r.getPartitions());
- } else {
- r.setPartitions(filterHook.filterPartitions(r.getPartitions()));
- // TODO: in these methods, do we really need to deepcopy?
- deepCopyPartitions(r.getPartitions(), result);
- }
- return !r.isSetHasUnknownPartitions() || r.isHasUnknownPartitions(); // Assume the worst.
- }
-
- /**
- * @param name
- * @return the database
- * @throws NoSuchObjectException
- * @throws MetaException
- * @throws TException
- * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#get_database(java.lang.String)
- */
- @Override
- public Database getDatabase(String name) throws NoSuchObjectException,
- MetaException, TException {
- Database d = client.get_database(name);
- return fastpath ? d :deepCopy(filterHook.filterDatabase(d));
- }
-
- /**
- * @param tbl_name
- * @param db_name
- * @param part_vals
- * @return the partition
- * @throws MetaException
- * @throws TException
- * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#get_partition(java.lang.String,
- * java.lang.String, java.util.List)
- */
- @Override
- public Partition getPartition(String db_name, String tbl_name,
- List<String> part_vals) throws NoSuchObjectException, MetaException, TException {
- Partition p = client.get_partition(db_name, tbl_name, part_vals);
- return fastpath ? p : deepCopy(filterHook.filterPartition(p));
- }
-
- @Override
- public List<Partition> getPartitionsByNames(String db_name, String tbl_name,
- List<String> part_names) throws NoSuchObjectException, MetaException, TException {
- List<Partition> parts = client.get_partitions_by_names(db_name, tbl_name, part_names);
- return fastpath ? parts : deepCopyPartitions(filterHook.filterPartitions(parts));
- }
-
- @Override
- public PartitionValuesResponse listPartitionValues(PartitionValuesRequest request)
- throws MetaException, TException, NoSuchObjectException {
- return client.get_partition_values(request);
- }
-
- @Override
- public Partition getPartitionWithAuthInfo(String db_name, String tbl_name,
- List<String> part_vals, String user_name, List<String> group_names)
- throws MetaException, UnknownTableException, NoSuchObjectException,
- TException {
- Partition p = client.get_partition_with_auth(db_name, tbl_name, part_vals, user_name,
- group_names);
- return fastpath ? p : deepCopy(filterHook.filterPartition(p));
- }
-
- /**
- * @param name
- * @param dbname
- * @return the table
- * @throws NoSuchObjectException
- * @throws MetaException
- * @throws TException
- * @throws NoSuchObjectException
- * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#get_table(java.lang.String,
- * java.lang.String)
- */
- @Override
- public Table getTable(String dbname, String name) throws MetaException,
- TException, NoSuchObjectException {
- GetTableRequest req = new GetTableRequest(dbname, name);
- req.setCapabilities(version);
- Table t = client.get_table_req(req).getTable();
- return fastpath ? t : deepCopy(filterHook.filterTable(t));
- }
-
- /** {@inheritDoc} */
- @Override
- @Deprecated
- public Table getTable(String tableName) throws MetaException, TException,
- NoSuchObjectException {
- Table t = getTable(DEFAULT_DATABASE_NAME, tableName);
- return fastpath ? t : filterHook.filterTable(t);
- }
-
- /** {@inheritDoc} */
- @Override
- public List<Table> getTableObjectsByName(String dbName, List<String> tableNames)
- throws MetaException, InvalidOperationException, UnknownDBException, TException {
- GetTablesRequest req = new GetTablesRequest(dbName);
- req.setTblNames(tableNames);
- req.setCapabilities(version);
- List<Table> tabs = client.get_table_objects_by_name_req(req).getTables();
- return fastpath ? tabs : deepCopyTables(filterHook.filterTables(tabs));
- }
-
- /** {@inheritDoc} */
- @Override
- public List<String> listTableNamesByFilter(String dbName, String filter, short maxTables)
- throws MetaException, TException, InvalidOperationException, UnknownDBException {
- return filterHook.filterTableNames(dbName,
- client.get_table_names_by_filter(dbName, filter, maxTables));
- }
-
- /**
- * @param name
- * @return the type
- * @throws MetaException
- * @throws TException
- * @throws NoSuchObjectException
- * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#get_type(java.lang.String)
- */
- public Type getType(String name) throws NoSuchObjectException, MetaException, TException {
- return deepCopy(client.get_type(name));
- }
-
- /** {@inheritDoc} */
- @Override
- public List<String> getTables(String dbname, String tablePattern) throws MetaException {
- try {
- return filterHook.filterTableNames(dbname, client.get_tables(dbname, tablePattern));
- } catch (Exception e) {
- MetaStoreUtils.logAndThrowMetaException(e);
- }
- return null;
- }
-
- /** {@inheritDoc} */
- @Override
- public List<String> getTables(String dbname, String tablePattern, TableType tableType) throws MetaException {
- try {
- return filterHook.filterTableNames(dbname, client.get_tables_by_type(dbname, tablePattern, tableType.toString()));
- } catch (Exception e) {
- MetaStoreUtils.logAndThrowMetaException(e);
- }
- return null;
- }
-
- @Override
- public List<TableMeta> getTableMeta(String dbPatterns, String tablePatterns, List<String> tableTypes)
- throws MetaException {
- try {
- return filterNames(client.get_table_meta(dbPatterns, tablePatterns, tableTypes));
- } catch (Exception e) {
- MetaStoreUtils.logAndThrowMetaException(e);
- }
- return null;
- }
-
- private List<TableMeta> filterNames(List<TableMeta> metas) throws MetaException {
- Map<String, TableMeta> sources = new LinkedHashMap<>();
- Map<String, List<String>> dbTables = new LinkedHashMap<>();
- for (TableMeta meta : metas) {
- sources.put(meta.getDbName() + "." + meta.getTableName(), meta);
- List<String> tables = dbTables.get(meta.getDbName());
- if (tables == null) {
- dbTables.put(meta.getDbName(), tables = new ArrayList<String>());
- }
- tables.add(meta.getTableName());
- }
- List<TableMeta> filtered = new ArrayList<>();
- for (Map.Entry<String, List<String>> entry : dbTables.entrySet()) {
- for (String table : filterHook.filterTableNames(entry.getKey(), entry.getValue())) {
- filtered.add(sources.get(entry.getKey() + "." + table));
- }
- }
- return filtered;
- }
-
- /** {@inheritDoc} */
- @Override
- public List<String> getAllTables(String dbname) throws MetaException {
- try {
- return filterHook.filterTableNames(dbname, client.get_all_tables(dbname));
- } catch (Exception e) {
- MetaStoreUtils.logAndThrowMetaException(e);
- }
- return null;
- }
-
- @Override
- public boolean tableExists(String databaseName, String tableName) throws MetaException,
- TException, UnknownDBException {
- try {
- GetTableRequest req = new GetTableRequest(databaseName, tableName);
- req.setCapabilities(version);
- return filterHook.filterTable(client.get_table_req(req).getTable()) != null;
- } catch (NoSuchObjectException e) {
- return false;
- }
- }
-
- /** {@inheritDoc} */
- @Override
- @Deprecated
- public boolean tableExists(String tableName) throws MetaException,
- TException, UnknownDBException {
- return tableExists(DEFAULT_DATABASE_NAME, tableName);
- }
-
- @Override
- public List<String> listPartitionNames(String dbName, String tblName,
- short max) throws NoSuchObjectException, MetaException, TException {
- return filterHook.filterPartitionNames(dbName, tblName,
- client.get_partition_names(dbName, tblName, max));
- }
-
- @Override
- public List<String> listPartitionNames(String db_name, String tbl_name,
- List<String> part_vals, short max_parts)
- throws MetaException, TException, NoSuchObjectException {
- return filterHook.filterPartitionNames(db_name, tbl_name,
- client.get_partition_names_ps(db_name, tbl_name, part_vals, max_parts));
- }
-
- /**
- * Get number of partitions matching specified filter
- * @param db_name the database name
- * @param tbl_name the table name
- * @param filter the filter string,
- * for example "part1 = \"p1_abc\" and part2 <= "\p2_test\"". Filtering can
- * be done only on string partition keys.
- * @return number of partitions
- * @throws MetaException
- * @throws NoSuchObjectException
- * @throws TException
- */
- @Override
- public int getNumPartitionsByFilter(String db_name, String tbl_name,
- String filter) throws MetaException,
- NoSuchObjectException, TException {
- return client.get_num_partitions_by_filter(db_name, tbl_name, filter);
- }
-
- @Override
- public void alter_partition(String dbName, String tblName, Partition newPart)
- throws InvalidOperationException, MetaException, TException {
- client.alter_partition_with_environment_context(dbName, tblName, newPart, null);
- }
-
- @Override
- public void alter_partition(String dbName, String tblName, Partition newPart, EnvironmentContext environmentContext)
- throws InvalidOperationException, MetaException, TException {
- client.alter_partition_with_environment_context(dbName, tblName, newPart, environmentContext);
- }
-
- @Override
- public void alter_partitions(String dbName, String tblName, List<Partition> newParts)
- throws InvalidOperationException, MetaException, TException {
- client.alter_partitions_with_environment_context(dbName, tblName, newParts, null);
- }
-
- @Override
- public void alter_partitions(String dbName, String tblName, List<Partition> newParts, EnvironmentContext environmentContext)
- throws InvalidOperationException, MetaException, TException {
- client.alter_partitions_with_environment_context(dbName, tblName, newParts, environmentContext);
-}
-
- @Override
- public void alterDatabase(String dbName, Database db)
- throws MetaException, NoSuchObjectException, TException {
- client.alter_database(dbName, db);
- }
- /**
- * @param db
- * @param tableName
- * @throws UnknownTableException
- * @throws UnknownDBException
- * @throws MetaException
- * @throws TException
- * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#get_fields(java.lang.String,
- * java.lang.String)
- */
- @Override
- public List<FieldSchema> getFields(String db, String tableName)
- throws MetaException, TException, UnknownTableException,
- UnknownDBException {
- List<FieldSchema> fields = client.get_fields(db, tableName);
- return fastpath ? fields : deepCopyFieldSchemas(fields);
- }
-
- /**
- * create an index
- * @param index the index object
- * @param indexTable which stores the index data
- * @throws InvalidObjectException
- * @throws MetaException
- * @throws NoSuchObjectException
- * @throws TException
- * @throws AlreadyExistsException
- */
- @Override
- public void createIndex(Index index, Table indexTable) throws AlreadyExistsException, InvalidObjectException, MetaException, NoSuchObjectException, TException {
- client.add_index(index, indexTable);
- }
-
- /**
- * @param dbname
- * @param base_tbl_name
- * @param idx_name
- * @param new_idx
- * @throws InvalidOperationException
- * @throws MetaException
- * @throws TException
- * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#alter_index(java.lang.String,
- * java.lang.String, java.lang.String, org.apache.hadoop.hive.metastore.api.Index)
- */
- @Override
- public void alter_index(String dbname, String base_tbl_name, String idx_name, Index new_idx)
- throws InvalidOperationException, MetaException, TException {
- client.alter_index(dbname, base_tbl_name, idx_name, new_idx);
- }
-
- /**
- * @param dbName
- * @param tblName
- * @param indexName
- * @return the index
- * @throws MetaException
- * @throws UnknownTableException
- * @throws NoSuchObjectException
- * @throws TException
- */
- @Override
- public Index getIndex(String dbName, String tblName, String indexName)
- throws MetaException, UnknownTableException, NoSuchObjectException,
- TException {
- return deepCopy(filterHook.filterIndex(client.get_index_by_name(dbName, tblName, indexName)));
- }
-
- /**
- * list indexes of the give base table
- * @param dbName
- * @param tblName
- * @param max
- * @return the list of indexes
- * @throws NoSuchObjectException
- * @throws MetaException
- * @throws TException
- */
- @Override
- public List<String> listIndexNames(String dbName, String tblName, short max)
- throws MetaException, TException {
- return filterHook.filterIndexNames(dbName, tblName, client.get_index_names(dbName, tblName, max));
- }
-
- /**
- * list all the index names of the give base table.
- *
- * @param dbName
- * @param tblName
- * @param max
- * @return list of indexes
- * @throws MetaException
- * @throws TException
- */
- @Override
- public List<Index> listIndexes(String dbName, String tblName, short max)
- throws NoSuchObjectException, MetaException, TException {
- return filterHook.filterIndexes(client.get_indexes(dbName, tblName, max));
- }
-
- @Override
- public List<SQLPrimaryKey> getPrimaryKeys(PrimaryKeysRequest req)
- throws MetaException, NoSuchObjectException, TException {
- return client.get_primary_keys(req).getPrimaryKeys();
- }
-
- @Override
- public List<SQLForeignKey> getForeignKeys(ForeignKeysRequest req) throws MetaException,
- NoSuchObjectException, TException {
- return client.get_foreign_keys(req).getForeignKeys();
- }
-
- @Override
- public List<SQLUniqueConstraint> getUniqueConstraints(UniqueConstraintsRequest req)
- throws MetaException, NoSuchObjectException, TException {
- return client.get_unique_constraints(req).getUniqueConstraints();
- }
-
- @Override
- public List<SQLNotNullConstraint> getNotNullConstraints(NotNullConstraintsRequest req)
- throws MetaException, NoSuchObjectException, TException {
- return client.get_not_null_constraints(req).getNotNullConstraints();
- }
-
-
- /** {@inheritDoc} */
- @Override
- @Deprecated
- //use setPartitionColumnStatistics instead
- public boolean updateTableColumnStatistics(ColumnStatistics statsObj)
- throws NoSuchObjectException, InvalidObjectException, MetaException, TException,
- InvalidInputException{
- return client.update_table_column_statistics(statsObj);
- }
-
- /** {@inheritDoc} */
- @Override
- @Deprecated
- //use setPartitionColumnStatistics instead
- public boolean updatePartitionColumnStatistics(ColumnStatistics statsObj)
- throws NoSuchObjectException, InvalidObjectException, MetaException, TException,
- InvalidInputException{
- return client.update_partition_column_statistics(statsObj);
- }
-
- /** {@inheritDoc} */
- @Override
- public boolean setPartitionColumnStatistics(SetPartitionsStatsRequest request)
- throws NoSuchObjectException, InvalidObjectException, MetaException, TException,
- InvalidInputException{
- return client.set_aggr_stats_for(request);
- }
-
- @Override
- public void flushCache() {
- try {
- client.flushCache();
- } catch (TException e) {
- // Not much we can do about it honestly
- LOG.warn("Got error flushing the cache", e);
- }
- }
-
- /** {@inheritDoc} */
- @Override
- public List<ColumnStatisticsObj> getTableColumnStatistics(String dbName, String tableName,
- List<String> colNames) throws NoSuchObjectException, MetaException, TException,
- InvalidInputException, InvalidObjectException {
- return client.get_table_statistics_req(
- new TableStatsRequest(dbName, tableName, colNames)).getTableStats();
- }
-
- /** {@inheritDoc} */
- @Override
- public Map<String, List<ColumnStatisticsObj>> getPartitionColumnStatistics(
- String dbName, String tableName, List<String> partNames, List<String> colNames)
- throws NoSuchObjectException, MetaException, TException {
- return client.get_partitions_statistics_req(
- new PartitionsStatsRequest(dbName, tableName, colNames, partNames)).getPartStats();
- }
-
- /** {@inheritDoc} */
- @Override
- public boolean deletePartitionColumnStatistics(String dbName, String tableName, String partName,
- String colName) throws NoSuchObjectException, InvalidObjectException, MetaException,
- TException, InvalidInputException
- {
- return client.delete_partition_column_statistics(dbName, tableName, partName, colName);
- }
-
- /** {@inheritDoc} */
- @Override
- public boolean deleteTableColumnStatistics(String dbName, String tableName, String colName)
- throws NoSuchObjectException, InvalidObjectException, MetaException, TException,
- InvalidInputException
- {
- return client.delete_table_column_statistics(dbName, tableName, colName);
- }
-
- /**
- * @param db
- * @param tableName
- * @throws UnknownTableException
- * @throws UnknownDBException
- * @throws MetaException
- * @throws TException
- * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#get_schema(java.lang.String,
- * java.lang.String)
- */
- @Override
- public List<FieldSchema> getSchema(String db, String tableName)
- throws MetaException, TException, UnknownTableException,
- UnknownDBException {
- EnvironmentContext envCxt = null;
- String addedJars = conf.getVar(ConfVars.HIVEADDEDJARS);
- if(org.apache.commons.lang.StringUtils.isNotBlank(addedJars)) {
- Map<String, String> props = new HashMap<String, String>();
- props.put("hive.added.jars.path", addedJars);
- envCxt = new EnvironmentContext(props);
- }
-
- List<FieldSchema> fields = client.get_schema_with_environment_context(db, tableName, envCxt);
- return fastpath ? fields : deepCopyFieldSchemas(fields);
- }
-
- @Override
- public String getConfigValue(String name, String defaultValue)
- throws TException, ConfigValSecurityException {
- return client.get_config_value(name, defaultValue);
- }
-
- @Override
- public Partition getPartition(String db, String tableName, String partName)
- throws MetaException, TException, UnknownTableException, NoSuchObjectException {
- Partition p = client.get_partition_by_name(db, tableName, partName);
- return fastpath ? p : deepCopy(filterHook.filterPartition(p));
- }
-
- public Partition appendPartitionByName(String dbName, String tableName, String partName)
- throws InvalidObjectException, AlreadyExistsException, MetaException, TException {
- return appendPartitionByName(dbName, tableName, partName, null);
- }
-
- public Partition appendPartitionByName(String dbName, String tableName, String partName,
- EnvironmentContext envContext) throws InvalidObjectException, AlreadyExistsException,
- MetaException, TException {
- Partition p = client.append_partition_by_name_with_environment_context(dbName, tableName,
- partName, envContext);
- return fastpath ? p : deepCopy(p);
- }
-
- public boolean dropPartitionByName(String dbName, String tableName, String partName,
- boolean deleteData) throws NoSuchObjectException, MetaException, TException {
- return dropPartitionByName(dbName, tableName, partName, deleteData, null);
- }
-
- public boolean dropPartitionByName(String dbName, String tableName, String partName,
- boolean deleteData, EnvironmentContext envContext) throws NoSuchObjectException,
- MetaException, TException {
- return client.drop_partition_by_name_with_environment_context(dbName, tableName, partName,
- deleteData, envContext);
- }
-
- private HiveMetaHook getHook(Table tbl) throws MetaException {
- if (hookLoader == null) {
- return null;
- }
- return hookLoader.getHook(tbl);
- }
-
- @Override
- public List<String> partitionNameToVals(String name) throws MetaException, TException {
- return client.partition_name_to_vals(name);
- }
-
- @Override
- public Map<String, String> partitionNameToSpec(String name) throws MetaException, TException{
- return client.partition_name_to_spec(name);
- }
-
- /**
- * @param partition
- * @return
- */
- private Partition deepCopy(Partition partition) {
- Partition copy = null;
- if (partition != null) {
- copy = new Partition(partition);
- }
- return copy;
- }
-
- private Database deepCopy(Database database) {
- Database copy = null;
- if (database != null) {
- copy = new Database(database);
- }
- return copy;
- }
-
- protected Table deepCopy(Table table) {
- Table copy = null;
- if (table != null) {
- copy = new Table(table);
- }
- return copy;
- }
-
- private Index deepCopy(Index index) {
- Index copy = null;
- if (index != null) {
- copy = new Index(index);
- }
- return copy;
- }
-
- private Type deepCopy(Type type) {
- Type copy = null;
- if (type != null) {
- copy = new Type(type);
- }
- return copy;
- }
-
- private FieldSchema deepCopy(FieldSchema schema) {
- FieldSchema copy = null;
- if (schema != null) {
- copy = new FieldSchema(schema);
- }
- return copy;
- }
-
- private Function deepCopy(Function func) {
- Function copy = null;
- if (func != null) {
- copy = new Function(func);
- }
- return copy;
- }
-
- protected PrincipalPrivilegeSet deepCopy(PrincipalPrivilegeSet pps) {
- PrincipalPrivilegeSet copy = null;
- if (pps != null) {
- copy = new PrincipalPrivilegeSet(pps);
- }
- return copy;
- }
-
- private List<Partition> deepCopyPartitions(List<Partition> partitions) {
- return deepCopyPartitions(partitions, null);
- }
-
- private List<Partition> deepCopyPartitions(
- Collection<Partition> src, List<Partition> dest) {
- if (src == null) {
- return dest;
- }
- if (dest == null) {
- dest = new ArrayList<Partition>(src.size());
- }
- for (Partition part : src) {
- dest.add(deepCopy(part));
- }
- return dest;
- }
-
- private List<Table> deepCopyTables(List<Table> tables) {
- List<Table> copy = null;
- if (tables != null) {
- copy = new ArrayList<Table>();
- for (Table tab : tables) {
- copy.add(deepCopy(tab));
- }
- }
- return copy;
- }
-
- protected List<FieldSchema> deepCopyFieldSchemas(List<FieldSchema> schemas) {
- List<FieldSchema> copy = null;
- if (schemas != null) {
- copy = new ArrayList<FieldSchema>();
- for (FieldSchema schema : schemas) {
- copy.add(deepCopy(schema));
- }
- }
- return copy;
- }
-
- @Override
- public boolean dropIndex(String dbName, String tblName, String name,
- boolean deleteData) throws NoSuchObjectException, MetaException,
- TException {
- return client.drop_index_by_name(dbName, tblName, name, deleteData);
- }
-
- @Override
- public boolean grant_role(String roleName, String userName,
- PrincipalType principalType, String grantor, PrincipalType grantorType,
- boolean grantOption) throws MetaException, TException {
- GrantRevokeRoleRequest req = new GrantRevokeRoleRequest();
- req.setRequestType(GrantRevokeType.GRANT);
- req.setRoleName(roleName);
- req.setPrincipalName(userName);
- req.setPrincipalType(principalType);
- req.setGrantor(grantor);
- req.setGrantorType(grantorType);
- req.setGrantOption(grantOption);
- GrantRevokeRoleResponse res = client.grant_revoke_role(req);
- if (!res.isSetSuccess()) {
- throw new MetaException("GrantRevokeResponse missing success field");
- }
- return res.isSuccess();
- }
-
- @Override
- public boolean create_role(Role role)
- throws MetaException, TException {
- return client.create_role(role);
- }
-
- @Override
- public boolean drop_role(String roleName) throws MetaException, TException {
- return client.drop_role(roleName);
- }
-
- @Override
- public List<Role> list_roles(String principalName,
- PrincipalType principalType) throws MetaException, TException {
- return client.list_roles(principalName, principalType);
- }
-
- @Override
- public List<String> listRoleNames() throws MetaException, TException {
- return client.get_role_names();
- }
-
- @Override
- public GetPrincipalsInRoleResponse get_principals_in_role(GetPrincipalsInRoleRequest req)
- throws MetaException, TException {
- return client.get_principals_in_role(req);
- }
-
- @Override
- public GetRoleGrantsForPrincipalResponse get_role_grants_for_principal(
- GetRoleGrantsForPrincipalRequest getRolePrincReq) throws MetaException, TException {
- return client.get_role_grants_for_principal(getRolePrincReq);
- }
-
- @Override
- public boolean grant_privileges(PrivilegeBag privileges)
- throws MetaException, TException {
- GrantRevokePrivilegeRequest req = new GrantRevokePrivilegeRequest();
- req.setRequestType(GrantRevokeType.GRANT);
- req.setPrivileges(privileges);
- GrantRevokePrivilegeResponse res = client.grant_revoke_privileges(req);
- if (!res.isSetSuccess()) {
- throw new MetaException("GrantRevokePrivilegeResponse missing success field");
- }
- return res.isSuccess();
- }
-
- @Override
- public boolean revoke_role(String roleName, String userName,
- PrincipalType principalType, boolean grantOption) throws MetaException, TException {
- GrantRevokeRoleRequest req = new GrantRevokeRoleRequest();
- req.setRequestType(GrantRevokeType.REVOKE);
- req.setRoleName(roleName);
- req.setPrincipalName(userName);
- req.setPrincipalType(principalType);
- req.setGrantOption(grantOption);
- GrantRevokeRoleResponse res = client.grant_revoke_role(req);
- if (!res.isSetSuccess()) {
- throw new MetaException("GrantRevokeResponse missing success field");
- }
- return res.isSuccess();
- }
-
- @Override
- public boolean revoke_privileges(PrivilegeBag privileges, boolean grantOption) throws MetaException,
- TException {
- GrantRevokePrivilegeRequest req = new GrantRevokePrivilegeRequest();
- req.setRequestType(GrantRevokeType.REVOKE);
- req.setPrivileges(privileges);
- req.setRevokeGrantOption(grantOption);
- GrantRevokePrivilegeResponse res = client.grant_revoke_privileges(req);
- if (!res.isSetSuccess()) {
- throw new MetaException("GrantRevokePrivilegeResponse missing success field");
- }
- return res.isSuccess();
- }
-
- @Override
- public PrincipalPrivilegeSet get_privilege_set(HiveObjectRef hiveObject,
- String userName, List<String> groupNames) throws MetaException,
- TException {
- return client.get_privilege_set(hiveObject, userName, groupNames);
- }
-
- @Override
- public List<HiveObjectPrivilege> list_privileges(String principalName,
- PrincipalType principalType, HiveObjectRef hiveObject)
- throws MetaException, TException {
- return client.list_privileges(principalName, principalType, hiveObject);
- }
-
- public String getDelegationToken(String renewerKerberosPrincipalName) throws
- MetaException, TException, IOException {
- //a convenience method that makes the intended owner for the delegation
- //token request the current user
- String owner = conf.getUser();
- return getDelegationToken(owner, renewerKerberosPrincipalName);
- }
-
- @Override
- public String getDelegationToken(String owner, String renewerKerberosPrincipalName) throws
- MetaException, TException {
- // This is expected to be a no-op, so we will return null when we use local metastore.
- if (localMetaStore) {
- return null;
- }
- return client.get_delegation_token(owner, renewerKerberosPrincipalName);
- }
-
- @Override
- public long renewDelegationToken(String tokenStrForm) throws MetaException, TException {
- if (localMetaStore) {
- return 0;
- }
- return client.renew_delegation_token(tokenStrForm);
-
- }
-
- @Override
- public void cancelDelegationToken(String tokenStrForm) throws MetaException, TException {
- if (localMetaStore) {
- return;
- }
- client.cancel_delegation_token(tokenStrForm);
- }
-
- @Override
- public boolean addToken(String tokenIdentifier, String delegationToken) throws TException {
- return client.add_token(tokenIdentifier, delegationToken);
- }
-
- @Override
- public boolean removeToken(String tokenIdentifier) throws TException {
- return client.remove_token(tokenIdentifier);
- }
-
- @Override
- public String getToken(String tokenIdentifier) throws TException {
- return client.get_token(tokenIdentifier);
- }
-
- @Override
- public List<String> getAllTokenIdentifiers() throws TException {
- return client.get_all_token_identifiers();
- }
-
- @Override
- public int addMasterKey(String key) throws MetaException, TException {
- return client.add_master_key(key);
- }
-
- @Override
- public void updateMasterKey(Integer seqNo, String key)
- throws NoSuchObjectException, MetaException, TException {
- client.update_master_key(seqNo, key);
- }
-
- @Override
- public boolean removeMasterKey(Integer keySeq) throws TException {
- return client.remove_master_key(keySeq);
- }
-
- @Override
- public String[] getMasterKeys() throws TException {
- List<String> keyList = client.get_master_keys();
- return keyList.toArray(new String[keyList.size()]);
- }
-
- @Override
- public ValidTxnList getValidTxns() throws TException {
- return TxnUtils.createValidReadTxnList(client.get_open_txns(), 0);
- }
-
- @Override
- public ValidTxnList getValidTxns(long currentTxn) throws TException {
- return TxnUtils.createValidReadTxnList(client.get_open_txns(), currentTxn);
- }
-
- @Override
- public long openTxn(String user) throws TException {
- OpenTxnsResponse txns = openTxns(user, 1);
- return txns.getTxn_ids().get(0);
- }
-
- @Override
- public OpenTxnsResponse openTxns(String user, int numTxns) throws TException {
- String hostname = null;
- try {
- hostname = InetAddress.getLocalHost().getHostName();
- } catch (UnknownHostException e) {
- LOG.error("Unable to resolve my host name " + e.getMessage());
- throw new RuntimeException(e);
- }
- return client.open_txns(new OpenTxnRequest(numTxns, user, hostname));
- }
-
- @Override
- public void rollbackTxn(long txnid) throws NoSuchTxnException, TException {
- client.abort_txn(new AbortTxnRequest(txnid));
- }
-
- @Override
- public void commitTxn(long txnid)
- throws NoSuchTxnException, TxnAbortedException, TException {
- client.commit_txn(new CommitTxnRequest(txnid));
- }
-
- @Override
- public GetOpenTxnsInfoResponse showTxns() throws TException {
- return client.get_open_txns_info();
- }
-
- @Override
- public void abortTxns(List<Long> txnids) throws NoSuchTxnException, TException {
- client.abort_txns(new AbortTxnsRequest(txnids));
- }
-
- @Override
- public LockResponse lock(LockRequest request)
- throws NoSuchTxnException, TxnAbortedException, TException {
- return client.lock(request);
- }
-
- @Override
- public LockResponse checkLock(long lockid)
- throws NoSuchTxnException, TxnAbortedException, NoSuchLockException,
- TException {
- return client.check_lock(new CheckLockRequest(lockid));
- }
-
- @Override
- public void unlock(long lockid)
- throws NoSuchLockException, TxnOpenException, TException {
- client.unlock(new UnlockRequest(lockid));
- }
-
- @Override
- @Deprecated
- public ShowLocksResponse showLocks() throws TException {
- return client.show_locks(new ShowLocksRequest());
- }
-
- @Override
- public ShowLocksResponse showLocks(ShowLocksRequest request) throws TException {
- return client.show_locks(request);
- }
-
- @Override
- public void heartbeat(long txnid, long lockid)
- throws NoSuchLockException, NoSuchTxnException, TxnAbortedException,
- TException {
- HeartbeatRequest hb = new HeartbeatRequest();
- hb.setLockid(lockid);
- hb.setTxnid(txnid);
- client.heartbeat(hb);
- }
-
- @Override
- public HeartbeatTxnRangeResponse heartbeatTxnRange(long min, long max)
- throws NoSuchTxnException, TxnAbortedException, TException {
- HeartbeatTxnRangeRequest rqst = new HeartbeatTxnRangeRequest(min, max);
- return client.heartbeat_txn_range(rqst);
- }
-
- @Override
- @Deprecated
- public void compact(String dbname, String tableName, String partitionName, CompactionType type)
- throws TException {
- CompactionRequest cr = new CompactionRequest();
- if (dbname == null) cr.setDbname(DEFAULT_DATABASE_NAME);
- else cr.setDbname(dbname);
- cr.setTablename(tableName);
- if (partitionName != null) cr.setPartitionname(partitionName);
- cr.setType(type);
- client.compact(cr);
- }
- @Deprecated
- @Override
- public void compact(String dbname, String tableName, String partitionName, CompactionType type,
- Map<String, String> tblproperties) throws TException {
- compact2(dbname, tableName, partitionName, type, tblproperties);
- }
-
- @Override
- public CompactionResponse compact2(String dbname, String tableName, String partitionName, CompactionType type,
- Map<String, String> tblproperties) throws TException {
- CompactionRequest cr = new CompactionRequest();
- if (dbname == null) cr.setDbname(DEFAULT_DATABASE_NAME);
- else cr.setDbname(dbname);
- cr.setTablename(tableName);
- if (partitionName != null) cr.setPartitionname(partitionName);
- cr.setType(type);
- cr.setProperties(tblproperties);
- return client.compact2(cr);
- }
- @Override
- public ShowCompactResponse showCompactions() throws TException {
- return client.show_compact(new ShowCompactRequest());
- }
-
- @Deprecated
- @Override
- public void addDynamicPartitions(long txnId, String dbName, String tableName,
- List<String> partNames) throws TException {
- client.add_dynamic_partitions(new AddDynamicPartitions(txnId, dbName, tableName, partNames));
- }
- @Override
- public void addDynamicPartitions(long txnId, String dbName, String tableName,
- List<String> partNames, DataOperationType operationType) throws TException {
- AddDynamicPartitions adp = new AddDynamicPartitions(txnId, dbName, tableName, partNames);
- adp.setOperationType(operationType);
- client.add_dynamic_partitions(adp);
- }
-
- @Override
- public void insertTable(Table table, boolean overwrite) throws MetaException {
- boolean failed = true;
- HiveMetaHook hook = getHook(table);
- if (hook == null || !(hook instanceof DefaultHiveMetaHook)) {
- return;
- }
- DefaultHiveMetaHook hiveMetaHook = (DefaultHiveMetaHook) hook;
- try {
- hiveMetaHook.commitInsertTable(table, overwrite);
- failed = false;
- }
- finally {
- if (failed) {
- hiveMetaHook.rollbackInsertTable(table, overwrite);
- }
- }
- }
-
- @InterfaceAudience.LimitedPrivate({"HCatalog"})
- @Override
- public NotificationEventResponse getNextNotification(long lastEventId, int maxEvents,
-
<TRUNCATED>
[05/12] hive git commit: HIVE-17980 Moved HiveMetaStoreClient plus a
few remaining classes.
Posted by ga...@apache.org.
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/HiveMetaStoreClient.java
----------------------------------------------------------------------
diff --git a/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/HiveMetaStoreClient.java b/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/HiveMetaStoreClient.java
new file mode 100644
index 0000000..ac58cea
--- /dev/null
+++ b/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/HiveMetaStoreClient.java
@@ -0,0 +1,2686 @@
+/*
+ * 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.metastore.Warehouse.DEFAULT_DATABASE_NAME;
+
+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.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.Random;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.security.PrivilegedExceptionAction;
+
+import javax.security.auth.login.LoginException;
+
+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.ValidTxnList;
+import org.apache.hadoop.hive.metastore.api.*;
+import org.apache.hadoop.hive.metastore.TableType;
+import org.apache.hadoop.hive.metastore.conf.MetastoreConf;
+import org.apache.hadoop.hive.metastore.conf.MetastoreConf.ConfVars;
+import org.apache.hadoop.hive.metastore.partition.spec.PartitionSpecProxy;
+import org.apache.hadoop.hive.metastore.security.HadoopThriftAuthBridge;
+import org.apache.hadoop.hive.metastore.txn.TxnUtils;
+import org.apache.hadoop.hive.metastore.utils.SecurityUtils;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
+import org.apache.hadoop.hive.metastore.utils.ObjectPair;
+import org.apache.hadoop.hive.metastore.utils.SecurityUtils;
+import org.apache.hadoop.security.UserGroupInformation;
+import org.apache.hadoop.util.StringUtils;
+import org.apache.thrift.TApplicationException;
+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.TFramedTransport;
+import org.apache.thrift.transport.TSocket;
+import org.apache.thrift.transport.TTransport;
+import org.apache.thrift.transport.TTransportException;
+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 {
+ /**
+ * 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));
+
+ 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.
+ protected boolean fastpath = false;
+ private String tokenStrForm;
+ private final boolean localMetaStore;
+ private final MetaStoreFilterHook filterHook;
+ 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;
+
+ 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();
+ fileMetadataBatchSize = MetastoreConf.getIntVar(
+ conf, ConfVars.BATCH_RETRIEVE_OBJECTS_MAX);
+
+ 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 + "]");
+ }
+ // instantiate the metastore server handler directly instead of connecting
+ // through the network
+ client = HiveMetaStore.newRetryingHMSHandler("hive client", this.conf, true);
+ 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) {
+ String metastoreUrisString[] = MetastoreConf.getVar(conf,
+ ConfVars.THRIFT_URIS).split(",");
+ metastoreUris = new URI[metastoreUrisString.length];
+ try {
+ int i = 0;
+ for (String s : metastoreUrisString) {
+ URI tmpUri = new URI(s);
+ if (tmpUri.getScheme() == null) {
+ throw new IllegalArgumentException("URI: " + s
+ + " does not have a scheme");
+ }
+ metastoreUris[i++] = new URI(
+ tmpUri.getScheme(),
+ tmpUri.getUserInfo(),
+ HadoopThriftAuthBridge.getBridge().getCanonicalHostName(tmpUri.getHost()),
+ tmpUri.getPort(),
+ tmpUri.getPath(),
+ tmpUri.getQuery(),
+ tmpUri.getFragment()
+ );
+
+ }
+ // make metastore URIS random
+ List<?> uriList = Arrays.asList(metastoreUris);
+ Collections.shuffle(uriList);
+ metastoreUris = (URI[]) uriList.toArray();
+ } catch (IllegalArgumentException e) {
+ throw (e);
+ } catch (Exception e) {
+ MetaStoreUtils.logAndThrowMetaException(e);
+ }
+ } 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();
+ }
+
+ 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);
+ }
+ }
+
+ /**
+ * 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 " + oneVar.toString() +
+ " changed from " + oldVar + " to " + 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("For direct MetaStore DB connections, we don't support retries" +
+ " at the client level.");
+ } else {
+ close();
+ // 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();
+ }
+ }
+
+ /**
+ * @param dbname
+ * @param tbl_name
+ * @param new_tbl
+ * @throws InvalidOperationException
+ * @throws MetaException
+ * @throws TException
+ * @see
+ * org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#alter_table(
+ * java.lang.String, java.lang.String,
+ * org.apache.hadoop.hive.metastore.api.Table)
+ */
+ @Override
+ public void alter_table(String dbname, String tbl_name, Table new_tbl)
+ throws InvalidOperationException, MetaException, 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 InvalidOperationException, MetaException, 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 {
+ client.alter_table_with_environment_context(dbname, tbl_name, new_tbl, envContext);
+ }
+
+ /**
+ * @param dbname
+ * @param name
+ * @param part_vals
+ * @param newPart
+ * @throws InvalidOperationException
+ * @throws MetaException
+ * @throws TException
+ * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#rename_partition(
+ * java.lang.String, java.lang.String, java.util.List, org.apache.hadoop.hive.metastore.api.Partition)
+ */
+ @Override
+ public void renamePartition(final String dbname, final String name, final List<String> part_vals, final Partition newPart)
+ throws InvalidOperationException, MetaException, TException {
+ client.rename_partition(dbname, name, part_vals, newPart);
+ }
+
+ private void open() throws MetaException {
+ isConnected = false;
+ TTransportException tte = null;
+ boolean useSSL = MetastoreConf.getBoolVar(conf, ConfVars.USE_SSL);
+ boolean useSasl = MetastoreConf.getBoolVar(conf, ConfVars.USE_THRIFT_SASL);
+ boolean useFramedTransport = MetastoreConf.getBoolVar(conf, ConfVars.USE_THRIFT_FRAMED_TRANSPORT);
+ boolean useCompactProtocol = MetastoreConf.getBoolVar(conf, ConfVars.USE_THRIFT_COMPACT_PROTOCOL);
+ int clientSocketTimeout = (int) MetastoreConf.getTimeVar(conf,
+ ConfVars.CLIENT_SOCKET_TIMEOUT, TimeUnit.MILLISECONDS);
+
+ for (int attempt = 0; !isConnected && attempt < retries; ++attempt) {
+ for (URI store : metastoreUris) {
+ LOG.info("Trying to connect to metastore with URI " + store);
+
+ try {
+ if (useSSL) {
+ try {
+ String trustStorePath = MetastoreConf.getVar(conf, ConfVars.SSL_TRUSTSTORE_PATH).trim();
+ if (trustStorePath.isEmpty()) {
+ throw new IllegalArgumentException(ConfVars.SSL_TRUSTSTORE_PATH.toString()
+ + " Not configured for SSL connection");
+ }
+ String trustStorePassword =
+ MetastoreConf.getPassword(conf, MetastoreConf.ConfVars.SSL_TRUSTSTORE_PASSWORD);
+
+ // Create an SSL socket and connect
+ transport = SecurityUtils.getSSLSocket(store.getHost(), store.getPort(), clientSocketTimeout,
+ trustStorePath, trustStorePassword );
+ LOG.info("Opened an SSL connection to metastore, current connections: " + connCount.incrementAndGet());
+ } catch(IOException e) {
+ throw new IllegalArgumentException(e);
+ } catch(TTransportException e) {
+ tte = e;
+ throw new MetaException(e.toString());
+ }
+ } else {
+ transport = new TSocket(store.getHost(), store.getPort(), clientSocketTimeout);
+ }
+
+ 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.info("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, transport,
+ MetaStoreUtils.getMetaStoreSaslProperties(conf, useSSL));
+ } else {
+ LOG.info("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,
+ transport, MetaStoreUtils.getMetaStoreSaslProperties(conf, useSSL));
+ }
+ } catch (IOException ioe) {
+ LOG.error("Couldn't create client transport", ioe);
+ throw new MetaException(ioe.toString());
+ }
+ } else {
+ if (useFramedTransport) {
+ transport = new TFramedTransport(transport);
+ }
+ }
+
+ 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();
+ LOG.info("Opened a connection to metastore, current connections: " + connCount.incrementAndGet());
+ }
+ isConnected = true;
+ } catch (TTransportException e) {
+ tte = e;
+ if (LOG.isDebugEnabled()) {
+ LOG.warn("Failed to connect to the MetaStore Server...", e);
+ } else {
+ // Don't print full exception trace if DEBUG is not on.
+ LOG.warn("Failed to connect to the MetaStore Server...");
+ }
+ }
+
+ if (isConnected && !useSasl && 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) {
+ LOG.error("Unable to connect to metastore with URI " + store
+ + " in attempt " + attempt, 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) {
+ throw new MetaException("Could not connect to meta store using any of the URIs provided." +
+ " Most recent failure: " + StringUtils.stringifyException(tte));
+ }
+
+ snapshotActiveConf();
+
+ LOG.info("Connected to metastore.");
+ }
+
+ 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();
+ }
+ } 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();
+ LOG.info("Closed a connection to metastore, current connections: " + connCount.decrementAndGet());
+ }
+ }
+
+ @Override
+ public void setMetaConf(String key, String value) throws TException {
+ client.setMetaConf(key, value);
+ }
+
+ @Override
+ public String getMetaConf(String key) throws TException {
+ return client.getMetaConf(key);
+ }
+
+ /**
+ * @param new_part
+ * @return the added partition
+ * @throws InvalidObjectException
+ * @throws AlreadyExistsException
+ * @throws MetaException
+ * @throws TException
+ * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#add_partition(org.apache.hadoop.hive.metastore.api.Partition)
+ */
+ @Override
+ public Partition add_partition(Partition new_part) throws TException {
+ return add_partition(new_part, null);
+ }
+
+ public Partition add_partition(Partition new_part, EnvironmentContext envContext)
+ throws TException {
+ Partition p = client.add_partition_with_environment_context(new_part, envContext);
+ return fastpath ? p : deepCopy(p);
+ }
+
+ /**
+ * @param new_parts
+ * @throws InvalidObjectException
+ * @throws AlreadyExistsException
+ * @throws MetaException
+ * @throws TException
+ * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#add_partitions(List)
+ */
+ @Override
+ public int add_partitions(List<Partition> new_parts) throws TException {
+ return client.add_partitions(new_parts);
+ }
+
+ @Override
+ public List<Partition> add_partitions(
+ List<Partition> parts, boolean ifNotExists, boolean needResults) throws TException {
+ if (parts.isEmpty()) {
+ return needResults ? new ArrayList<>() : null;
+ }
+ Partition part = parts.get(0);
+ AddPartitionsRequest req = new AddPartitionsRequest(
+ part.getDbName(), part.getTableName(), parts, ifNotExists);
+ req.setNeedResult(needResults);
+ AddPartitionsResult result = client.add_partitions_req(req);
+ return needResults ? filterHook.filterPartitions(result.getPartitions()) : null;
+ }
+
+ @Override
+ public int add_partitions_pspec(PartitionSpecProxy partitionSpec) throws TException {
+ return client.add_partitions_pspec(partitionSpec.toPartitionSpec());
+ }
+
+ /**
+ * @param table_name
+ * @param db_name
+ * @param part_vals
+ * @return the appended partition
+ * @throws InvalidObjectException
+ * @throws AlreadyExistsException
+ * @throws MetaException
+ * @throws TException
+ * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#append_partition(java.lang.String,
+ * java.lang.String, java.util.List)
+ */
+ @Override
+ public Partition appendPartition(String db_name, String table_name,
+ List<String> part_vals) throws TException {
+ return appendPartition(db_name, table_name, part_vals, null);
+ }
+
+ public Partition appendPartition(String db_name, String table_name, List<String> part_vals,
+ EnvironmentContext envContext) throws TException {
+ Partition p = client.append_partition_with_environment_context(db_name, table_name,
+ part_vals, envContext);
+ return fastpath ? p : deepCopy(p);
+ }
+
+ @Override
+ public Partition appendPartition(String dbName, String tableName, String partName)
+ throws TException {
+ return appendPartition(dbName, tableName, partName, null);
+ }
+
+ public Partition appendPartition(String dbName, String tableName, String partName,
+ EnvironmentContext envContext) throws TException {
+ Partition p = client.append_partition_by_name_with_environment_context(dbName, tableName,
+ partName, envContext);
+ return fastpath ? p : deepCopy(p);
+ }
+
+ /**
+ * Exchange the partition between two tables
+ * @param partitionSpecs partitions specs of the parent partition to be exchanged
+ * @param destDb the db of the destination table
+ * @param destinationTableName the destination table name
+ * @return new partition after exchanging
+ */
+ @Override
+ public Partition exchange_partition(Map<String, String> partitionSpecs,
+ String sourceDb, String sourceTable, String destDb,
+ String destinationTableName) throws MetaException,
+ NoSuchObjectException, InvalidObjectException, TException {
+ return client.exchange_partition(partitionSpecs, sourceDb, sourceTable,
+ destDb, destinationTableName);
+ }
+
+ /**
+ * Exchange the partitions between two tables
+ * @param partitionSpecs partitions specs of the parent partition to be exchanged
+ * @param destDb the db of the destination table
+ * @param destinationTableName the destination table name
+ * @return new partitions after exchanging
+ */
+ @Override
+ public List<Partition> exchange_partitions(Map<String, String> partitionSpecs,
+ String sourceDb, String sourceTable, String destDb,
+ String destinationTableName) throws MetaException,
+ NoSuchObjectException, InvalidObjectException, TException {
+ return client.exchange_partitions(partitionSpecs, sourceDb, sourceTable,
+ destDb, destinationTableName);
+ }
+
+ @Override
+ public void validatePartitionNameCharacters(List<String> partVals)
+ throws TException, MetaException {
+ client.partition_name_has_valid_characters(partVals, true);
+ }
+
+ /**
+ * Create a new Database
+ * @param db
+ * @throws AlreadyExistsException
+ * @throws InvalidObjectException
+ * @throws MetaException
+ * @throws TException
+ * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#create_database(Database)
+ */
+ @Override
+ public void createDatabase(Database db)
+ throws AlreadyExistsException, InvalidObjectException, MetaException, TException {
+ client.create_database(db);
+ }
+
+ /**
+ * @param tbl
+ * @throws MetaException
+ * @throws NoSuchObjectException
+ * @throws TException
+ * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#create_table(org.apache.hadoop.hive.metastore.api.Table)
+ */
+ @Override
+ public void createTable(Table tbl) throws AlreadyExistsException,
+ InvalidObjectException, MetaException, NoSuchObjectException, TException {
+ createTable(tbl, null);
+ }
+
+ public void createTable(Table tbl, EnvironmentContext envContext) throws AlreadyExistsException,
+ InvalidObjectException, MetaException, NoSuchObjectException, TException {
+ HiveMetaHook hook = getHook(tbl);
+ if (hook != null) {
+ hook.preCreateTable(tbl);
+ }
+ boolean success = false;
+ try {
+ // Subclasses can override this step (for example, for temporary tables)
+ create_table_with_environment_context(tbl, envContext);
+ if (hook != null) {
+ hook.commitCreateTable(tbl);
+ }
+ success = true;
+ }
+ finally {
+ if (!success && (hook != null)) {
+ try {
+ hook.rollbackCreateTable(tbl);
+ } catch (Exception e){
+ LOG.error("Create rollback failed with", e);
+ }
+ }
+ }
+ }
+
+ @Override
+ public void createTableWithConstraints(Table tbl,
+ List<SQLPrimaryKey> primaryKeys, List<SQLForeignKey> foreignKeys,
+ List<SQLUniqueConstraint> uniqueConstraints,
+ List<SQLNotNullConstraint> notNullConstraints)
+ throws AlreadyExistsException, InvalidObjectException,
+ MetaException, NoSuchObjectException, TException {
+ HiveMetaHook hook = getHook(tbl);
+ if (hook != null) {
+ hook.preCreateTable(tbl);
+ }
+ boolean success = false;
+ try {
+ // Subclasses can override this step (for example, for temporary tables)
+ client.create_table_with_constraints(tbl, primaryKeys, foreignKeys,
+ uniqueConstraints, notNullConstraints);
+ if (hook != null) {
+ hook.commitCreateTable(tbl);
+ }
+ success = true;
+ } finally {
+ if (!success && (hook != null)) {
+ hook.rollbackCreateTable(tbl);
+ }
+ }
+ }
+
+ @Override
+ public void dropConstraint(String dbName, String tableName, String constraintName) throws
+ NoSuchObjectException, MetaException, TException {
+ client.drop_constraint(new DropConstraintRequest(dbName, tableName, constraintName));
+ }
+
+ @Override
+ public void addPrimaryKey(List<SQLPrimaryKey> primaryKeyCols) throws
+ NoSuchObjectException, MetaException, TException {
+ client.add_primary_key(new AddPrimaryKeyRequest(primaryKeyCols));
+ }
+
+ @Override
+ public void addForeignKey(List<SQLForeignKey> foreignKeyCols) throws
+ NoSuchObjectException, MetaException, TException {
+ client.add_foreign_key(new AddForeignKeyRequest(foreignKeyCols));
+ }
+
+ @Override
+ public void addUniqueConstraint(List<SQLUniqueConstraint> uniqueConstraintCols) throws
+ NoSuchObjectException, MetaException, TException {
+ client.add_unique_constraint(new AddUniqueConstraintRequest(uniqueConstraintCols));
+ }
+
+ @Override
+ public void addNotNullConstraint(List<SQLNotNullConstraint> notNullConstraintCols) throws
+ NoSuchObjectException, MetaException, TException {
+ client.add_not_null_constraint(new AddNotNullConstraintRequest(notNullConstraintCols));
+ }
+
+ /**
+ * @param type
+ * @return true or false
+ * @throws AlreadyExistsException
+ * @throws InvalidObjectException
+ * @throws MetaException
+ * @throws TException
+ * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#create_type(org.apache.hadoop.hive.metastore.api.Type)
+ */
+ public boolean createType(Type type) throws AlreadyExistsException,
+ InvalidObjectException, MetaException, TException {
+ return client.create_type(type);
+ }
+
+ /**
+ * @param name
+ * @throws NoSuchObjectException
+ * @throws InvalidOperationException
+ * @throws MetaException
+ * @throws TException
+ * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#drop_database(java.lang.String, boolean, boolean)
+ */
+ @Override
+ public void dropDatabase(String name)
+ throws NoSuchObjectException, InvalidOperationException, MetaException, TException {
+ dropDatabase(name, true, false, false);
+ }
+
+ @Override
+ public void dropDatabase(String name, boolean deleteData, boolean ignoreUnknownDb)
+ throws NoSuchObjectException, InvalidOperationException, MetaException, TException {
+ dropDatabase(name, deleteData, ignoreUnknownDb, false);
+ }
+
+ @Override
+ public void dropDatabase(String name, boolean deleteData, boolean ignoreUnknownDb, boolean cascade)
+ throws NoSuchObjectException, InvalidOperationException, MetaException, TException {
+ try {
+ getDatabase(name);
+ } catch (NoSuchObjectException e) {
+ if (!ignoreUnknownDb) {
+ throw e;
+ }
+ return;
+ }
+
+ if (cascade) {
+ List<String> tableList = getAllTables(name);
+ for (String table : tableList) {
+ try {
+ // Subclasses can override this step (for example, for temporary tables)
+ dropTable(name, table, deleteData, true);
+ } catch (UnsupportedOperationException e) {
+ // Ignore Index tables, those will be dropped with parent tables
+ }
+ }
+ }
+ client.drop_database(name, deleteData, cascade);
+ }
+
+ /**
+ * @param tbl_name
+ * @param db_name
+ * @param part_vals
+ * @return true or false
+ * @throws NoSuchObjectException
+ * @throws MetaException
+ * @throws TException
+ * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#drop_partition(java.lang.String,
+ * java.lang.String, java.util.List, boolean)
+ */
+ public boolean dropPartition(String db_name, String tbl_name,
+ List<String> part_vals) throws NoSuchObjectException, MetaException,
+ TException {
+ return dropPartition(db_name, tbl_name, part_vals, true, null);
+ }
+
+ public boolean dropPartition(String db_name, String tbl_name, List<String> part_vals,
+ EnvironmentContext env_context) throws NoSuchObjectException, MetaException, TException {
+ return dropPartition(db_name, tbl_name, part_vals, true, env_context);
+ }
+
+ @Override
+ public boolean dropPartition(String dbName, String tableName, String partName, boolean deleteData)
+ throws NoSuchObjectException, MetaException, TException {
+ return dropPartition(dbName, tableName, partName, deleteData, null);
+ }
+
+ private static EnvironmentContext getEnvironmentContextWithIfPurgeSet() {
+ Map<String, String> warehouseOptions = new HashMap<>();
+ warehouseOptions.put("ifPurge", "TRUE");
+ return new EnvironmentContext(warehouseOptions);
+ }
+
+ /*
+ public boolean dropPartition(String dbName, String tableName, String partName, boolean deleteData, boolean ifPurge)
+ throws NoSuchObjectException, MetaException, TException {
+
+ return dropPartition(dbName, tableName, partName, deleteData,
+ ifPurge? getEnvironmentContextWithIfPurgeSet() : null);
+ }
+ */
+
+ public boolean dropPartition(String dbName, String tableName, String partName, boolean deleteData,
+ EnvironmentContext envContext) throws NoSuchObjectException, MetaException, TException {
+ return client.drop_partition_by_name_with_environment_context(dbName, tableName, partName,
+ deleteData, envContext);
+ }
+
+ /**
+ * @param db_name
+ * @param tbl_name
+ * @param part_vals
+ * @param deleteData
+ * delete the underlying data or just delete the table in metadata
+ * @return true or false
+ * @throws NoSuchObjectException
+ * @throws MetaException
+ * @throws TException
+ * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#drop_partition(java.lang.String,
+ * java.lang.String, java.util.List, boolean)
+ */
+ @Override
+ public boolean dropPartition(String db_name, String tbl_name,
+ List<String> part_vals, boolean deleteData) throws NoSuchObjectException,
+ MetaException, TException {
+ return dropPartition(db_name, tbl_name, part_vals, deleteData, null);
+ }
+
+ @Override
+ public boolean dropPartition(String db_name, String tbl_name,
+ List<String> part_vals, PartitionDropOptions options) throws TException {
+ return dropPartition(db_name, tbl_name, part_vals, options.deleteData,
+ options.purgeData? getEnvironmentContextWithIfPurgeSet() : null);
+ }
+
+ public boolean dropPartition(String db_name, String tbl_name, List<String> part_vals,
+ boolean deleteData, EnvironmentContext envContext) throws NoSuchObjectException,
+ MetaException, TException {
+ return client.drop_partition_with_environment_context(db_name, tbl_name, part_vals, deleteData,
+ envContext);
+ }
+
+ @Override
+ public List<Partition> dropPartitions(String dbName, String tblName,
+ List<ObjectPair<Integer, byte[]>> partExprs, PartitionDropOptions options)
+ throws TException {
+ RequestPartsSpec rps = new RequestPartsSpec();
+ List<DropPartitionsExpr> exprs = new ArrayList<>(partExprs.size());
+ for (ObjectPair<Integer, byte[]> partExpr : partExprs) {
+ DropPartitionsExpr dpe = new DropPartitionsExpr();
+ dpe.setExpr(partExpr.getSecond());
+ dpe.setPartArchiveLevel(partExpr.getFirst());
+ exprs.add(dpe);
+ }
+ rps.setExprs(exprs);
+ DropPartitionsRequest req = new DropPartitionsRequest(dbName, tblName, rps);
+ req.setDeleteData(options.deleteData);
+ req.setNeedResult(options.returnResults);
+ req.setIfExists(options.ifExists);
+ if (options.purgeData) {
+ LOG.info("Dropped partitions will be purged!");
+ req.setEnvironmentContext(getEnvironmentContextWithIfPurgeSet());
+ }
+ return client.drop_partitions_req(req).getPartitions();
+ }
+
+ @Override
+ public List<Partition> dropPartitions(String dbName, String tblName,
+ List<ObjectPair<Integer, byte[]>> partExprs, boolean deleteData,
+ boolean ifExists, boolean needResult) throws NoSuchObjectException, MetaException, TException {
+
+ return dropPartitions(dbName, tblName, partExprs,
+ PartitionDropOptions.instance()
+ .deleteData(deleteData)
+ .ifExists(ifExists)
+ .returnResults(needResult));
+
+ }
+
+ @Override
+ public List<Partition> dropPartitions(String dbName, String tblName,
+ List<ObjectPair<Integer, byte[]>> partExprs, boolean deleteData,
+ boolean ifExists) throws NoSuchObjectException, MetaException, TException {
+ // By default, we need the results from dropPartitions();
+ return dropPartitions(dbName, tblName, partExprs,
+ PartitionDropOptions.instance()
+ .deleteData(deleteData)
+ .ifExists(ifExists));
+ }
+
+ /**
+ * {@inheritDoc}
+ * @see #dropTable(String, String, boolean, boolean, EnvironmentContext)
+ */
+ @Override
+ public void dropTable(String dbname, String name, boolean deleteData,
+ boolean ignoreUnknownTab) throws MetaException, TException,
+ NoSuchObjectException, UnsupportedOperationException {
+ dropTable(dbname, name, deleteData, ignoreUnknownTab, null);
+ }
+
+ /**
+ * Drop the table and choose whether to save the data in the trash.
+ * @param ifPurge completely purge the table (skipping trash) while removing
+ * data from warehouse
+ * @see #dropTable(String, String, boolean, boolean, EnvironmentContext)
+ */
+ @Override
+ public void dropTable(String dbname, String name, boolean deleteData,
+ boolean ignoreUnknownTab, boolean ifPurge)
+ throws MetaException, TException, NoSuchObjectException, UnsupportedOperationException {
+ //build new environmentContext with ifPurge;
+ EnvironmentContext envContext = null;
+ if(ifPurge){
+ Map<String, String> warehouseOptions;
+ warehouseOptions = new HashMap<>();
+ warehouseOptions.put("ifPurge", "TRUE");
+ envContext = new EnvironmentContext(warehouseOptions);
+ }
+ dropTable(dbname, name, deleteData, ignoreUnknownTab, envContext);
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ @Deprecated
+ public void dropTable(String tableName, boolean deleteData)
+ throws MetaException, UnknownTableException, TException, NoSuchObjectException {
+ dropTable(DEFAULT_DATABASE_NAME, tableName, deleteData, false, null);
+ }
+
+ /**
+ * @see #dropTable(String, String, boolean, boolean, EnvironmentContext)
+ */
+ @Override
+ public void dropTable(String dbname, String name)
+ throws NoSuchObjectException, MetaException, TException {
+ dropTable(dbname, name, true, true, null);
+ }
+
+ /**
+ * Drop the table and choose whether to: delete the underlying table data;
+ * throw if the table doesn't exist; save the data in the trash.
+ *
+ * @param dbname
+ * @param name
+ * @param deleteData
+ * delete the underlying data or just delete the table in metadata
+ * @param ignoreUnknownTab
+ * don't throw if the requested table doesn't exist
+ * @param envContext
+ * for communicating with thrift
+ * @throws MetaException
+ * could not drop table properly
+ * @throws NoSuchObjectException
+ * the table wasn't found
+ * @throws TException
+ * a thrift communication error occurred
+ * @throws UnsupportedOperationException
+ * dropping an index table is not allowed
+ * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#drop_table(java.lang.String,
+ * java.lang.String, boolean)
+ */
+ public void dropTable(String dbname, String name, boolean deleteData,
+ boolean ignoreUnknownTab, EnvironmentContext envContext) throws MetaException, TException,
+ NoSuchObjectException, UnsupportedOperationException {
+ Table tbl;
+ try {
+ tbl = getTable(dbname, name);
+ } catch (NoSuchObjectException e) {
+ if (!ignoreUnknownTab) {
+ throw e;
+ }
+ return;
+ }
+ if (MetaStoreUtils.isIndexTable(tbl)) {
+ throw new UnsupportedOperationException("Cannot drop index tables");
+ }
+ HiveMetaHook hook = getHook(tbl);
+ if (hook != null) {
+ hook.preDropTable(tbl);
+ }
+ boolean success = false;
+ try {
+ drop_table_with_environment_context(dbname, name, deleteData, envContext);
+ if (hook != null) {
+ hook.commitDropTable(tbl, deleteData || (envContext != null && "TRUE".equals(envContext.getProperties().get("ifPurge"))));
+ }
+ success=true;
+ } catch (NoSuchObjectException e) {
+ if (!ignoreUnknownTab) {
+ throw e;
+ }
+ } finally {
+ if (!success && (hook != null)) {
+ hook.rollbackDropTable(tbl);
+ }
+ }
+ }
+
+ /**
+ * Truncate the table/partitions in the DEFAULT database.
+ * @param dbName
+ * The db to which the table to be truncate belongs to
+ * @param tableName
+ * The table to truncate
+ * @param partNames
+ * List of partitions to truncate. NULL will truncate the whole table/all partitions
+ * @throws MetaException
+ * @throws TException
+ * Could not truncate table properly.
+ */
+ @Override
+ public void truncateTable(String dbName, String tableName, List<String> partNames) throws MetaException, TException {
+ client.truncate_table(dbName, tableName, partNames);
+ }
+
+ /**
+ * Recycles the files recursively from the input path to the cmroot directory either by copying or moving it.
+ *
+ * @param request Inputs for path of the data files to be recycled to cmroot and
+ * isPurge flag when set to true files which needs to be recycled are not moved to Trash
+ * @return Response which is currently void
+ */
+ @Override
+ public CmRecycleResponse recycleDirToCmPath(CmRecycleRequest request) throws MetaException, TException {
+ return client.cm_recycle(request);
+ }
+
+ /**
+ * @param type
+ * @return true if the type is dropped
+ * @throws MetaException
+ * @throws TException
+ * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#drop_type(java.lang.String)
+ */
+ public boolean dropType(String type) throws NoSuchObjectException, MetaException, TException {
+ return client.drop_type(type);
+ }
+
+ /**
+ * @param name
+ * @return map of types
+ * @throws MetaException
+ * @throws TException
+ * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#get_type_all(java.lang.String)
+ */
+ public Map<String, Type> getTypeAll(String name) throws MetaException,
+ TException {
+ Map<String, Type> result = null;
+ Map<String, Type> fromClient = client.get_type_all(name);
+ if (fromClient != null) {
+ result = new LinkedHashMap<>();
+ for (String key : fromClient.keySet()) {
+ result.put(key, deepCopy(fromClient.get(key)));
+ }
+ }
+ return result;
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public List<String> getDatabases(String databasePattern)
+ throws MetaException {
+ try {
+ return filterHook.filterDatabases(client.get_databases(databasePattern));
+ } catch (Exception e) {
+ MetaStoreUtils.logAndThrowMetaException(e);
+ }
+ return null;
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public List<String> getAllDatabases() throws MetaException {
+ try {
+ return filterHook.filterDatabases(client.get_all_databases());
+ } catch (Exception e) {
+ MetaStoreUtils.logAndThrowMetaException(e);
+ }
+ return null;
+ }
+
+ /**
+ * @param tbl_name
+ * @param db_name
+ * @param max_parts
+ * @return list of partitions
+ * @throws NoSuchObjectException
+ * @throws MetaException
+ * @throws TException
+ */
+ @Override
+ public List<Partition> listPartitions(String db_name, String tbl_name,
+ short max_parts) throws NoSuchObjectException, MetaException, TException {
+ List<Partition> parts = client.get_partitions(db_name, tbl_name, max_parts);
+ return fastpath ? parts : deepCopyPartitions(filterHook.filterPartitions(parts));
+ }
+
+ @Override
+ public PartitionSpecProxy listPartitionSpecs(String dbName, String tableName, int maxParts) throws TException {
+ return PartitionSpecProxy.Factory.get(filterHook.filterPartitionSpecs(
+ client.get_partitions_pspec(dbName, tableName, maxParts)));
+ }
+
+ @Override
+ public List<Partition> listPartitions(String db_name, String tbl_name,
+ List<String> part_vals, short max_parts)
+ throws NoSuchObjectException, MetaException, TException {
+ List<Partition> parts = client.get_partitions_ps(db_name, tbl_name, part_vals, max_parts);
+ return fastpath ? parts : deepCopyPartitions(filterHook.filterPartitions(parts));
+ }
+
+ @Override
+ public List<Partition> listPartitionsWithAuthInfo(String db_name,
+ String tbl_name, short max_parts, String user_name, List<String> group_names)
+ throws NoSuchObjectException, MetaException, TException {
+ List<Partition> parts = client.get_partitions_with_auth(db_name, tbl_name, max_parts,
+ user_name, group_names);
+ return fastpath ? parts :deepCopyPartitions(filterHook.filterPartitions(parts));
+ }
+
+ @Override
+ public List<Partition> listPartitionsWithAuthInfo(String db_name,
+ String tbl_name, List<String> part_vals, short max_parts,
+ String user_name, List<String> group_names) throws NoSuchObjectException,
+ MetaException, TException {
+ List<Partition> parts = client.get_partitions_ps_with_auth(db_name,
+ tbl_name, part_vals, max_parts, user_name, group_names);
+ return fastpath ? parts : deepCopyPartitions(filterHook.filterPartitions(parts));
+ }
+
+ /**
+ * Get list of partitions matching specified filter
+ * @param db_name the database name
+ * @param tbl_name the table name
+ * @param filter the filter string,
+ * for example "part1 = \"p1_abc\" and part2 <= "\p2_test\"". Filtering can
+ * be done only on string partition keys.
+ * @param max_parts the maximum number of partitions to return,
+ * all partitions are returned if -1 is passed
+ * @return list of partitions
+ * @throws MetaException
+ * @throws NoSuchObjectException
+ * @throws TException
+ */
+ @Override
+ public List<Partition> listPartitionsByFilter(String db_name, String tbl_name,
+ String filter, short max_parts) throws MetaException,
+ NoSuchObjectException, TException {
+ List<Partition> parts = client.get_partitions_by_filter(db_name, tbl_name, filter, max_parts);
+ return fastpath ? parts :deepCopyPartitions(filterHook.filterPartitions(parts));
+ }
+
+ @Override
+ public PartitionSpecProxy listPartitionSpecsByFilter(String db_name, String tbl_name,
+ String filter, int max_parts) throws MetaException,
+ NoSuchObjectException, TException {
+ return PartitionSpecProxy.Factory.get(filterHook.filterPartitionSpecs(
+ client.get_part_specs_by_filter(db_name, tbl_name, filter, max_parts)));
+ }
+
+ @Override
+ public boolean listPartitionsByExpr(String db_name, String tbl_name, byte[] expr,
+ String default_partition_name, short max_parts, List<Partition> result)
+ throws TException {
+ assert result != null;
+ PartitionsByExprRequest req = new PartitionsByExprRequest(
+ db_name, tbl_name, ByteBuffer.wrap(expr));
+ if (default_partition_name != null) {
+ req.setDefaultPartitionName(default_partition_name);
+ }
+ if (max_parts >= 0) {
+ req.setMaxParts(max_parts);
+ }
+ PartitionsByExprResult r;
+ try {
+ r = client.get_partitions_by_expr(req);
+ } catch (TApplicationException te) {
+ // TODO: backward compat for Hive <= 0.12. Can be removed later.
+ if (te.getType() != TApplicationException.UNKNOWN_METHOD
+ && te.getType() != TApplicationException.WRONG_METHOD_NAME) {
+ throw te;
+ }
+ throw new IncompatibleMetastoreException(
+ "Metastore doesn't support listPartitionsByExpr: " + te.getMessage());
+ }
+ if (fastpath) {
+ result.addAll(r.getPartitions());
+ } else {
+ r.setPartitions(filterHook.filterPartitions(r.getPartitions()));
+ // TODO: in these methods, do we really need to deepcopy?
+ deepCopyPartitions(r.getPartitions(), result);
+ }
+ return !r.isSetHasUnknownPartitions() || r.isHasUnknownPartitions(); // Assume the worst.
+ }
+
+ /**
+ * @param name
+ * @return the database
+ * @throws NoSuchObjectException
+ * @throws MetaException
+ * @throws TException
+ * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#get_database(java.lang.String)
+ */
+ @Override
+ public Database getDatabase(String name) throws NoSuchObjectException,
+ MetaException, TException {
+ Database d = client.get_database(name);
+ return fastpath ? d :deepCopy(filterHook.filterDatabase(d));
+ }
+
+ /**
+ * @param tbl_name
+ * @param db_name
+ * @param part_vals
+ * @return the partition
+ * @throws MetaException
+ * @throws TException
+ * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#get_partition(java.lang.String,
+ * java.lang.String, java.util.List)
+ */
+ @Override
+ public Partition getPartition(String db_name, String tbl_name,
+ List<String> part_vals) throws NoSuchObjectException, MetaException, TException {
+ Partition p = client.get_partition(db_name, tbl_name, part_vals);
+ return fastpath ? p : deepCopy(filterHook.filterPartition(p));
+ }
+
+ @Override
+ public List<Partition> getPartitionsByNames(String db_name, String tbl_name,
+ List<String> part_names) throws NoSuchObjectException, MetaException, TException {
+ List<Partition> parts = client.get_partitions_by_names(db_name, tbl_name, part_names);
+ return fastpath ? parts : deepCopyPartitions(filterHook.filterPartitions(parts));
+ }
+
+ @Override
+ public PartitionValuesResponse listPartitionValues(PartitionValuesRequest request)
+ throws MetaException, TException, NoSuchObjectException {
+ return client.get_partition_values(request);
+ }
+
+ @Override
+ public Partition getPartitionWithAuthInfo(String db_name, String tbl_name,
+ List<String> part_vals, String user_name, List<String> group_names)
+ throws MetaException, UnknownTableException, NoSuchObjectException,
+ TException {
+ Partition p = client.get_partition_with_auth(db_name, tbl_name, part_vals, user_name,
+ group_names);
+ return fastpath ? p : deepCopy(filterHook.filterPartition(p));
+ }
+
+ /**
+ * @param name
+ * @param dbname
+ * @return the table
+ * @throws NoSuchObjectException
+ * @throws MetaException
+ * @throws TException
+ * @throws NoSuchObjectException
+ * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#get_table(java.lang.String,
+ * java.lang.String)
+ */
+ @Override
+ public Table getTable(String dbname, String name) throws MetaException,
+ TException, NoSuchObjectException {
+ GetTableRequest req = new GetTableRequest(dbname, name);
+ req.setCapabilities(version);
+ Table t = client.get_table_req(req).getTable();
+ return fastpath ? t : deepCopy(filterHook.filterTable(t));
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ @Deprecated
+ public Table getTable(String tableName) throws MetaException, TException,
+ NoSuchObjectException {
+ Table t = getTable(DEFAULT_DATABASE_NAME, tableName);
+ return fastpath ? t : filterHook.filterTable(t);
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public List<Table> getTableObjectsByName(String dbName, List<String> tableNames)
+ throws MetaException, InvalidOperationException, UnknownDBException, TException {
+ GetTablesRequest req = new GetTablesRequest(dbName);
+ req.setTblNames(tableNames);
+ req.setCapabilities(version);
+ List<Table> tabs = client.get_table_objects_by_name_req(req).getTables();
+ return fastpath ? tabs : deepCopyTables(filterHook.filterTables(tabs));
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public List<String> listTableNamesByFilter(String dbName, String filter, short maxTables)
+ throws MetaException, TException, InvalidOperationException, UnknownDBException {
+ return filterHook.filterTableNames(dbName,
+ client.get_table_names_by_filter(dbName, filter, maxTables));
+ }
+
+ /**
+ * @param name
+ * @return the type
+ * @throws MetaException
+ * @throws TException
+ * @throws NoSuchObjectException
+ * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#get_type(java.lang.String)
+ */
+ public Type getType(String name) throws NoSuchObjectException, MetaException, TException {
+ return deepCopy(client.get_type(name));
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public List<String> getTables(String dbname, String tablePattern) throws MetaException {
+ try {
+ return filterHook.filterTableNames(dbname, client.get_tables(dbname, tablePattern));
+ } catch (Exception e) {
+ MetaStoreUtils.logAndThrowMetaException(e);
+ }
+ return null;
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public List<String> getTables(String dbname, String tablePattern, TableType tableType) throws MetaException {
+ try {
+ return filterHook.filterTableNames(dbname, client.get_tables_by_type(dbname, tablePattern, tableType.toString()));
+ } catch (Exception e) {
+ MetaStoreUtils.logAndThrowMetaException(e);
+ }
+ return null;
+ }
+
+ @Override
+ public List<TableMeta> getTableMeta(String dbPatterns, String tablePatterns, List<String> tableTypes)
+ throws MetaException {
+ try {
+ return filterNames(client.get_table_meta(dbPatterns, tablePatterns, tableTypes));
+ } catch (Exception e) {
+ MetaStoreUtils.logAndThrowMetaException(e);
+ }
+ return null;
+ }
+
+ private List<TableMeta> filterNames(List<TableMeta> metas) throws MetaException {
+ Map<String, TableMeta> sources = new LinkedHashMap<>();
+ Map<String, List<String>> dbTables = new LinkedHashMap<>();
+ for (TableMeta meta : metas) {
+ sources.put(meta.getDbName() + "." + meta.getTableName(), meta);
+ List<String> tables = dbTables.get(meta.getDbName());
+ if (tables == null) {
+ dbTables.put(meta.getDbName(), tables = new ArrayList<>());
+ }
+ tables.add(meta.getTableName());
+ }
+ List<TableMeta> filtered = new ArrayList<>();
+ for (Map.Entry<String, List<String>> entry : dbTables.entrySet()) {
+ for (String table : filterHook.filterTableNames(entry.getKey(), entry.getValue())) {
+ filtered.add(sources.get(entry.getKey() + "." + table));
+ }
+ }
+ return filtered;
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public List<String> getAllTables(String dbname) throws MetaException {
+ try {
+ return filterHook.filterTableNames(dbname, client.get_all_tables(dbname));
+ } catch (Exception e) {
+ MetaStoreUtils.logAndThrowMetaException(e);
+ }
+ return null;
+ }
+
+ @Override
+ public boolean tableExists(String databaseName, String tableName) throws MetaException,
+ TException, UnknownDBException {
+ try {
+ GetTableRequest req = new GetTableRequest(databaseName, tableName);
+ req.setCapabilities(version);
+ return filterHook.filterTable(client.get_table_req(req).getTable()) != null;
+ } catch (NoSuchObjectException e) {
+ return false;
+ }
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ @Deprecated
+ public boolean tableExists(String tableName) throws MetaException,
+ TException, UnknownDBException {
+ return tableExists(DEFAULT_DATABASE_NAME, tableName);
+ }
+
+ @Override
+ public List<String> listPartitionNames(String dbName, String tblName,
+ short max) throws NoSuchObjectException, MetaException, TException {
+ return filterHook.filterPartitionNames(dbName, tblName,
+ client.get_partition_names(dbName, tblName, max));
+ }
+
+ @Override
+ public List<String> listPartitionNames(String db_name, String tbl_name,
+ List<String> part_vals, short max_parts)
+ throws MetaException, TException, NoSuchObjectException {
+ return filterHook.filterPartitionNames(db_name, tbl_name,
+ client.get_partition_names_ps(db_name, tbl_name, part_vals, max_parts));
+ }
+
+ /**
+ * Get number of partitions matching specified filter
+ * @param db_name the database name
+ * @param tbl_name the table name
+ * @param filter the filter string,
+ * for example "part1 = \"p1_abc\" and part2 <= "\p2_test\"". Filtering can
+ * be done only on string partition keys.
+ * @return number of partitions
+ * @throws MetaException
+ * @throws NoSuchObjectException
+ * @throws TException
+ */
+ @Override
+ public int getNumPartitionsByFilter(String db_name, String tbl_name,
+ String filter) throws MetaException,
+ NoSuchObjectException, TException {
+ return client.get_num_partitions_by_filter(db_name, tbl_name, filter);
+ }
+
+ @Override
+ public void alter_partition(String dbName, String tblName, Partition newPart)
+ throws InvalidOperationException, MetaException, TException {
+ client.alter_partition_with_environment_context(dbName, tblName, newPart, null);
+ }
+
+ @Override
+ public void alter_partition(String dbName, String tblName, Partition newPart, EnvironmentContext environmentContext)
+ throws InvalidOperationException, MetaException, TException {
+ client.alter_partition_with_environment_context(dbName, tblName, newPart, environmentContext);
+ }
+
+ @Override
+ public void alter_partitions(String dbName, String tblName, List<Partition> newParts)
+ throws InvalidOperationException, MetaException, TException {
+ client.alter_partitions_with_environment_context(dbName, tblName, newParts, null);
+ }
+
+ @Override
+ public void alter_partitions(String dbName, String tblName, List<Partition> newParts, EnvironmentContext environmentContext)
+ throws InvalidOperationException, MetaException, TException {
+ client.alter_partitions_with_environment_context(dbName, tblName, newParts, environmentContext);
+}
+
+ @Override
+ public void alterDatabase(String dbName, Database db)
+ throws MetaException, NoSuchObjectException, TException {
+ client.alter_database(dbName, db);
+ }
+ /**
+ * @param db
+ * @param tableName
+ * @throws UnknownTableException
+ * @throws UnknownDBException
+ * @throws MetaException
+ * @throws TException
+ * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#get_fields(java.lang.String,
+ * java.lang.String)
+ */
+ @Override
+ public List<FieldSchema> getFields(String db, String tableName)
+ throws MetaException, TException, UnknownTableException,
+ UnknownDBException {
+ List<FieldSchema> fields = client.get_fields(db, tableName);
+ return fastpath ? fields : deepCopyFieldSchemas(fields);
+ }
+
+ /**
+ * create an index
+ * @param index the index object
+ * @param indexTable which stores the index data
+ * @throws InvalidObjectException
+ * @throws MetaException
+ * @throws NoSuchObjectException
+ * @throws TException
+ * @throws AlreadyExistsException
+ */
+ @Override
+ public void createIndex(Index index, Table indexTable) throws AlreadyExistsException, InvalidObjectException, MetaException, NoSuchObjectException, TException {
+ client.add_index(index, indexTable);
+ }
+
+ /**
+ * @param dbname
+ * @param base_tbl_name
+ * @param idx_name
+ * @param new_idx
+ * @throws InvalidOperationException
+ * @throws MetaException
+ * @throws TException
+ * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#alter_index(java.lang.String,
+ * java.lang.String, java.lang.String, org.apache.hadoop.hive.metastore.api.Index)
+ */
+ @Override
+ public void alter_index(String dbname, String base_tbl_name, String idx_name, Index new_idx)
+ throws InvalidOperationException, MetaException, TException {
+ client.alter_index(dbname, base_tbl_name, idx_name, new_idx);
+ }
+
+ /**
+ * @param dbName
+ * @param tblName
+ * @param indexName
+ * @return the index
+ * @throws MetaException
+ * @throws UnknownTableException
+ * @throws NoSuchObjectException
+ * @throws TException
+ */
+ @Override
+ public Index getIndex(String dbName, String tblName, String indexName)
+ throws MetaException, UnknownTableException, NoSuchObjectException,
+ TException {
+ return deepCopy(filterHook.filterIndex(client.get_index_by_name(dbName, tblName, indexName)));
+ }
+
+ /**
+ * list indexes of the give base table
+ * @param dbName
+ * @param tblName
+ * @param max
+ * @return the list of indexes
+ * @throws NoSuchObjectException
+ * @throws MetaException
+ * @throws TException
+ */
+ @Override
+ public List<String> listIndexNames(String dbName, String tblName, short max)
+ throws MetaException, TException {
+ return filterHook.filterIndexNames(dbName, tblName, client.get_index_names(dbName, tblName, max));
+ }
+
+ /**
+ * list all the index names of the give base table.
+ *
+ * @param dbName
+ * @param tblName
+ * @param max
+ * @return list of indexes
+ * @throws MetaException
+ * @throws TException
+ */
+ @Override
+ public List<Index> listIndexes(String dbName, String tblName, short max)
+ throws NoSuchObjectException, MetaException, TException {
+ return filterHook.filterIndexes(client.get_indexes(dbName, tblName, max));
+ }
+
+ @Override
+ public List<SQLPrimaryKey> getPrimaryKeys(PrimaryKeysRequest req)
+ throws MetaException, NoSuchObjectException, TException {
+ return client.get_primary_keys(req).getPrimaryKeys();
+ }
+
+ @Override
+ public List<SQLForeignKey> getForeignKeys(ForeignKeysRequest req) throws MetaException,
+ NoSuchObjectException, TException {
+ return client.get_foreign_keys(req).getForeignKeys();
+ }
+
+ @Override
+ public List<SQLUniqueConstraint> getUniqueConstraints(UniqueConstraintsRequest req)
+ throws MetaException, NoSuchObjectException, TException {
+ return client.get_unique_constraints(req).getUniqueConstraints();
+ }
+
+ @Override
+ public List<SQLNotNullConstraint> getNotNullConstraints(NotNullConstraintsRequest req)
+ throws MetaException, NoSuchObjectException, TException {
+ return client.get_not_null_constraints(req).getNotNullConstraints();
+ }
+
+
+ /** {@inheritDoc} */
+ @Override
+ @Deprecated
+ //use setPartitionColumnStatistics instead
+ public boolean updateTableColumnStatistics(ColumnStatistics statsObj)
+ throws NoSuchObjectException, InvalidObjectException, MetaException, TException,
+ InvalidInputException{
+ return client.update_table_column_statistics(statsObj);
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ @Deprecated
+ //use setPartitionColumnStatistics instead
+ public boolean updatePartitionColumnStatistics(ColumnStatistics statsObj)
+ throws NoSuchObjectException, InvalidObjectException, MetaException, TException,
+ InvalidInputException{
+ return client.update_partition_column_statistics(statsObj);
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public boolean setPartitionColumnStatistics(SetPartitionsStatsRequest request)
+ throws NoSuchObjectException, InvalidObjectException, MetaException, TException,
+ InvalidInputException{
+ return client.set_aggr_stats_for(request);
+ }
+
+ @Override
+ public void flushCache() {
+ try {
+ client.flushCache();
+ } catch (TException e) {
+ // Not much we can do about it honestly
+ LOG.warn("Got error flushing the cache", e);
+ }
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public List<ColumnStatisticsObj> getTableColumnStatistics(String dbName, String tableName,
+ List<String> colNames) throws NoSuchObjectException, MetaException, TException,
+ InvalidInputException, InvalidObjectException {
+ return client.get_table_statistics_req(
+ new TableStatsRequest(dbName, tableName, colNames)).getTableStats();
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public Map<String, List<ColumnStatisticsObj>> getPartitionColumnStatistics(
+ String dbName, String tableName, List<String> partNames, List<String> colNames)
+ throws NoSuchObjectException, MetaException, TException {
+ return client.get_partitions_statistics_req(
+ new PartitionsStatsRequest(dbName, tableName, colNames, partNames)).getPartStats();
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public boolean deletePartitionColumnStatistics(String dbName, String tableName, String partName,
+ String colName) throws NoSuchObjectException, InvalidObjectException, MetaException,
+ TException, InvalidInputException
+ {
+ return client.delete_partition_column_statistics(dbName, tableName, partName, colName);
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public boolean deleteTableColumnStatistics(String dbName, String tableName, String colName)
+ throws NoSuchObjectException, InvalidObjectException, MetaException, TException,
+ InvalidInputException
+ {
+ return client.delete_table_column_statistics(dbName, tableName, colName);
+ }
+
+ /**
+ * @param db
+ * @param tableName
+ * @throws UnknownTableException
+ * @throws UnknownDBException
+ * @throws MetaException
+ * @throws TException
+ * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#get_schema(java.lang.String,
+ * java.lang.String)
+ */
+ @Override
+ public List<FieldSchema> getSchema(String db, String tableName)
+ throws MetaException, TException, UnknownTableException,
+ UnknownDBException {
+ EnvironmentContext envCxt = null;
+ String addedJars = MetastoreConf.getVar(conf, ConfVars.ADDED_JARS);
+ if(org.apache.commons.lang.StringUtils.isNotBlank(addedJars)) {
+ Map<String, String> props = new HashMap<String, String>();
+ props.put("hive.added.jars.path", addedJars);
+ envCxt = new EnvironmentContext(props);
+ }
+
+ List<FieldSchema> fields = client.get_schema_with_environment_context(db, tableName, envCxt);
+ return fastpath ? fields : deepCopyFieldSchemas(fields);
+ }
+
+ @Override
+ public String getConfigValue(String name, String defaultValue)
+ throws TException, ConfigValSecurityException {
+ return client.get_config_value(name, defaultValue);
+ }
+
+ @Override
+ public Partition getPartition(String db, String tableName, String partName)
+ throws MetaException, TException, UnknownTableException, NoSuchObjectException {
+ Partition p = client.get_partition_by_name(db, tableName, partName);
+ return fastpath ? p : deepCopy(filterHook.filterPartition(p));
+ }
+
+ public Partition appendPartitionByName(String dbName, String tableName, String partName)
+ throws InvalidObjectException, AlreadyExistsException, MetaException, TException {
+ return appendPartitionByName(dbName, tableName, partName, null);
+ }
+
+ public Partition appendPartitionByName(String dbName, String tableName, String partName,
+ EnvironmentContext envContext) throws InvalidObjectException, AlreadyExistsException,
+ MetaException, TException {
+ Partition p = client.append_partition_by_name_with_environment_context(dbName, tableName,
+ partName, envContext);
+ return fastpath ? p : deepCopy(p);
+ }
+
+ public boolean dropPartitionByName(String dbName, String tableName, String partName,
+ boolean deleteData) throws NoSuchObjectException, MetaException, TException {
+ return dropPartitionByName(dbName, tableName, partName, deleteData, null);
+ }
+
+ public boolean dropPartitionByName(String dbName, String tableName, String partName,
+ boolean deleteData, EnvironmentContext envContext) throws NoSuchObjectException,
+ MetaException, TException {
+ return client.drop_partition_by_name_with_environment_context(dbName, tableName, partName,
+ deleteData, envContext);
+ }
+
+ private HiveMetaHook getHook(Table tbl) throws MetaException {
+ if (hookLoader == null) {
+ return null;
+ }
+ return hookLoader.getHook(tbl);
+ }
+
+ @Override
+ public List<String> partitionNameToVals(String name) throws MetaException, TException {
+ return client.partition_name_to_vals(name);
+ }
+
+ @Override
+ public Map<String, String> partitionNameToSpec(String name) throws MetaException, TException{
+ return client.partition_name_to_spec(name);
+ }
+
+ /**
+ * @param partition
+ * @return
+ */
+ private Partition deepCopy(Partition partition) {
+ Partition copy = null;
+ if (partition != null) {
+ copy = new Partition(partition);
+ }
+ return copy;
+ }
+
+ private Database deepCopy(Database database) {
+ Database copy = null;
+ if (database != null) {
+ copy = new Database(database);
+ }
+ return copy;
+ }
+
+ protected Table deepCopy(Table table) {
+ Table copy = null;
+ if (table != null) {
+ copy = new Table(table);
+ }
+ return copy;
+ }
+
+ private Index deepCopy(Index index) {
+ Index copy = null;
+ if (index != null) {
+ copy = new Index(index);
+ }
+ return copy;
+ }
+
+ private Type deepCopy(Type type) {
+ Type copy = null;
+ if (type != null) {
+ copy = new Type(type);
+ }
+ return copy;
+ }
+
+ private FieldSchema deepCopy(FieldSchema schema) {
+ FieldSchema copy = null;
+ if (schema != null) {
+ copy = new FieldSchema(schema);
+ }
+ return copy;
+ }
+
+ private Function deepCopy(Function func) {
+ Function copy = null;
+ if (func != null) {
+ copy = new Function(func);
+ }
+ return copy;
+ }
+
+ protected PrincipalPrivilegeSet deepCopy(PrincipalPrivilegeSet pps) {
+ PrincipalPrivilegeSet copy = null;
+ if (pps != null) {
+ copy = new PrincipalPrivilegeSet(pps);
+ }
+ return copy;
+ }
+
+ private List<Partition> deepCopyPartitions(List<Partition> partitions) {
+ return deepCopyPartitions(partitions, null);
+ }
+
+ private List<Partition> deepCopyPartitions(
+ Collection<Partition> src, List<Partition> dest) {
+ if (src == null) {
+ return dest;
+ }
+ if (dest == null) {
+ dest = new ArrayList<Partition>(src.size());
+ }
+ for (Partition part : src) {
+ dest.add(deepCopy(part));
+ }
+ return dest;
+ }
+
+ private List<Table> deepCopyTables(List<Table> tables) {
+ List<Table> copy = null;
+ if (tables != null) {
+ copy = new ArrayList<Table>();
+ for (Table tab : tables) {
+ copy.add(deepCopy(tab));
+ }
+ }
+ return copy;
+ }
+
+ protected List<FieldSchema> deepCopyFieldSchemas(List<FieldSchema> schemas) {
+ List<FieldSchema> copy = null;
+ if (schemas != null) {
+ copy = new ArrayList<FieldSchema>();
+ for (FieldSchema schema : schemas) {
+ copy.add(deepCopy(schema));
+ }
+ }
+ return copy;
+ }
+
+ @Override
+ public boolean dropIndex(String dbName, String tblName, String name,
+ boolean deleteData) throws NoSuchObjectException, MetaException,
+ TException {
+ return client.drop_index_by_name(dbName, tblName, name, deleteData);
+ }
+
+ @Override
+ public boolean grant_role(String roleName, String userName,
+ PrincipalType principalType, String grantor, PrincipalType grantorType,
+ boolean grantOption) throws MetaException, TException {
+ GrantRevokeRoleRequest req = new GrantRevokeRoleRequest();
+ req.setRequestType(GrantRevokeType.GRANT);
+ req.setRoleName(roleName);
+ req.setPrincipalName(userName);
+ req.setPrincipalType(principalType);
+ req.setGrantor(grantor);
+ req.setGrantorType(grantorType);
+ req.setGrantOption(grantOption);
+ GrantRevokeRoleResponse res = client.grant_revoke_role(req);
+ if (!res.isSetSuccess()) {
+ throw new MetaException("GrantRevokeResponse missing success field");
+ }
+ return res.isSuccess();
+ }
+
+ @Override
+ public boolean create_role(Role role)
+ throws MetaException, TException {
+ return client.create_role(role);
+ }
+
+ @Override
+ public boolean drop_role(String roleName) throws MetaException, TException {
+ return client.drop_role(roleName);
+ }
+
+ @Override
+ public List<Role> list_roles(String principalName,
+ PrincipalType principalType) throws MetaException, TException {
+ return client.list_roles(principalName, principalType);
+ }
+
+ @Override
+ public List<String> listRoleNames() throws MetaException, TException {
+ return client.get_role_names();
+ }
+
+ @Override
+ public GetPrincipalsInRoleResponse get_principals_in_role(GetPrincipalsInRoleRequest req)
+ throws MetaException, TException {
+ return client.get_principals_in_role(req);
+ }
+
+ @Override
+ public GetRoleGrantsForPrincipalResponse get_role_grants_for_principal(
+ GetRoleGrantsForPrincipalRequest getRolePrincReq) throws MetaException, TException {
+ return client.get_role_grants_for_principal(getRolePrincReq);
+ }
+
+ @Override
+ public boolean grant_privileges(PrivilegeBag privileges)
+ throws MetaException, TException {
+ GrantRevokePrivilegeRequest req = new GrantRevokePrivilegeRequest();
+ req.setRequestType(GrantRevokeType.GRANT);
+ req.setPrivileges(privileges);
+ GrantRevokePrivilegeResponse res = client.grant_revoke_privileges(req);
+ if (!res.isSetSuccess()) {
+ throw new MetaException("GrantRevokePrivilegeResponse missing success field");
+ }
+ return res.isSuccess();
+ }
+
+ @Override
+ public boolean revoke_role(String roleName, String userName,
+ PrincipalType principalType, boolean grantOption) throws MetaException, TException {
+ GrantRevokeRoleRequest req = new GrantRevokeRoleRequest();
+ req.setRequestType(GrantRevokeType.REVOKE);
+ req.setRoleName(roleName);
+ req.setPrincipalName(userName);
+ req.setPrincipalType(principalType);
+ req.setGrantOption(grantOption);
+ GrantRevokeRoleResponse res = client.grant_revoke_role(req);
+ if (!res.isSetSuccess()) {
+ throw new MetaException("GrantRevokeResponse missing success field");
+ }
+ return res.isSuccess();
+ }
+
+ @Override
+ public boolean revoke_privileges(PrivilegeBag privileges, boolean grantOption) throws MetaException,
+ TException {
+ GrantRevokePrivilegeRequest req = new GrantRevokePrivilegeRequest();
+ req.setRequestType(GrantRevokeType.REVOKE);
+ req.setPrivileges(privileges);
+ req.setRevokeGrantOption(grantOption);
+ GrantRevokePrivilegeResponse res = client.grant_revoke_privileges(req);
+ if (!res.isSetSuccess()) {
+ throw new MetaException("GrantRevokePrivilegeResponse missing success field");
+ }
+ return res.isSuccess();
+ }
+
+ @Override
+ public PrincipalPrivilegeSet get_privilege_set(HiveObjectRef hiveObject,
+ String userName, List<String> groupNames) throws MetaException,
+ TException {
+ return client.get_privilege_set(hiveObject, userName, groupNames);
+ }
+
+ @Override
+ public List<HiveObjectPrivilege> list_privileges(String principalName,
+ PrincipalType principalType, HiveObjectRef hiveObject)
+ throws MetaException, TException {
+ return client.list_privileges(principalName, principalType, hiveObject);
+ }
+
+ public String getDelegationToken(String renewerKerberosPrincipalName) throws
+ MetaException, TException, IOException {
+ //a convenience method that makes the intended owner for the delegation
+ //token request the current user
+ String owner = SecurityUtils.getUser();
+ return getDelegationToken(owner, renewerKerberosPrincipalName);
+ }
+
+ @Override
+ public String getDelegationToken(String owner, String renewerKerberosPrincipalName) throws
+ MetaException, TException {
+ // This is expected to be a no-op, so we will return null when we use local metastore.
+ if (localMetaStore) {
+ return null;
+ }
+ return client.get_delegation_token(owner, renewerKerberosPrincipalName);
+ }
+
+ @Override
+ public long renewDelegationToken(String tokenStrForm) throws MetaException, TException {
+ if (localMetaStore) {
+ return 0;
+ }
+ return client.renew_delegation_token(tokenStrForm);
+
+ }
+
+ @Override
+ public void cancelDelegationToken(String tokenStrForm) throws MetaException, TException {
+ if (localMetaStore) {
+ return;
+ }
+ client.cancel_delegation_token(tokenStrForm);
+ }
+
+ @Override
+ public boolean addToken(String tokenIdentifier, String delegationToken) throws TException {
+ return client.add_token(tokenIdentifier, delegationToken);
+ }
+
+ @Override
+ public boolean removeToken(String tokenIdentifier) throws TException {
+ return client.remove_token(tokenIdentifier);
+ }
+
+ @Override
+ public String getToken(String tokenIdentifier) throws TException {
+ return client.get_token(tokenIdentifier);
+ }
+
+ @Override
+ public List<String> getAllTokenIdentifiers() throws TException {
+ return client.get_all_token_identifiers();
+ }
+
+ @Override
+ public int addMasterKey(String key) throws MetaException, TException {
+ return client.add_master_key(key);
+ }
+
+ @Override
+ public void updateMasterKey(Integer seqNo, String key)
+ throws NoSuchObjectException, MetaException, TException {
+ client.update_master_key(seqNo, key);
+ }
+
+ @Override
+ public boolean removeMasterKey(Integer keySeq) throws TException {
+ return client.remove_master_key(keySeq);
+ }
+
+ @Override
+ public String[] getMasterKeys() throws TException {
+ List<String> keyList = client.get_master_keys();
+ return keyList.toArray(new String[keyList.size()]);
+ }
+
+ @Override
+ public ValidTxnList getValidTxns() throws TException {
+ return TxnUtils.createValidReadTxnList(client.get_open_txns(), 0);
+ }
+
+ @Override
+ public ValidTxnList getValidTxns(long currentTxn) throws TException {
+ return TxnUtils.createValidReadTxnList(client.get_open_txns(), currentTxn);
+ }
+
+ @Override
+ public long openTxn(String user) throws TException {
+ OpenTxnsResponse txns = openTxns(user, 1);
+ return txns.getTxn_ids().get(0);
+ }
+
+ @Override
+ public OpenTxnsResponse openTxns(String user, int numTxns) throws TException {
+ String hostname = null;
+ try {
+ hostname = InetAddress.getLocalHost().getHostName();
+ } catch (UnknownHostException e) {
+ LOG.error("Unable to resolve my host name " + e.getMessage());
+ throw new RuntimeException(e);
+ }
+ return client.open_txns(new OpenTxnRequest(numTxns, user, hostname));
+ }
+
+ @Override
+ public void rollbackTxn(long txnid) throws NoSuchTxnException, TException {
+ client.abort_txn(new AbortTxnRequest(txnid));
+ }
+
+ @Override
+ public void commitTxn(long txnid)
+ throws NoSuchTxnException, TxnAbortedException, TException {
+ client.commit_txn(new CommitTxnRequest(txnid));
+ }
+
+ @Override
+ public GetOpenTxnsInfoResponse showTxns() throws TException {
+ return client.get_open_txns_info();
+ }
+
+ @Override
+ public void abortTxns(List<Long> txnids) throws NoSuchTxnException, TException {
+ client.abort_txns(new AbortTxnsRequest(txnids));
+ }
+
+ @Override
+ public LockResponse lock(LockRequest request)
+ throws NoSuchTxnException, TxnAbortedException, TException {
+ return client.lock(request);
+ }
+
+ @Override
+ public LockResponse checkLock(long lockid)
+ throws NoSuchTxnException, TxnAbortedException, NoSuchLockException,
+ TException {
+ return client.check_lock(new CheckLockRequest(lockid));
+ }
+
+ @Override
+ public void unlock(long lockid)
+ throws NoSuchLockException, TxnOpenException, TException {
+ client.unlock(new UnlockRequest(lockid));
+ }
+
+ @Override
+ @Deprecated
+ public ShowLocksResponse showLocks() throws TException {
+ return client.show_locks(new ShowLocksRequest());
+ }
+
+ @Override
+ public ShowLocksResponse showLocks(ShowLocksRequest request) throws TException {
+ return client.show_locks(request);
+ }
+
+ @Override
+ public void heartbeat(long txnid, long lockid)
+ throws NoSuchLockException, NoSuchTxnException, TxnAbortedException,
+ TException {
+ HeartbeatRequest hb = new HeartbeatRequest();
+ hb.setLockid(lockid);
+ hb.setTxnid(txnid);
+ client.heartbeat(hb);
+ }
+
+ @Override
+ public HeartbeatTxnRangeResponse heartbeatTxnRange(long min, long max)
+ throws NoSuchTxnException, TxnAbortedException, TException {
+ HeartbeatTxnRangeRequest rqst = new HeartbeatTxnRangeRequest(min, max);
+ return client.heartbeat_txn_range(rqst);
+ }
+
+ @Override
+ @Deprecated
+ public void compact(String dbname, String tableName, String partitionName, CompactionType type)
+ throws TException {
+ CompactionRequest cr = new CompactionRequest();
+ if (dbname == null) cr.setDbname(DEFAULT_DATABASE_NAME);
+ else cr.setDbname(dbname);
+ cr.setTablename(tableName);
+ if (partitionName != null) cr.setPartitionname(partitionName);
+ cr.setType(type);
+ client.compact(cr);
+ }
+ @Deprecated
+ @Override
+ public void compact(String dbname, String tableName, String partitionName, CompactionType type,
+ Map<String, String> tblproperties) throws TException {
+ compact2(dbname, tableName, partitionName, type, tblproperties);
+ }
+
+ @Override
+ public CompactionResponse compact2(String dbname, String tableName, String partitionName, CompactionType type,
+ Map<String, String> tblproperties) throws TException {
+ CompactionRequest cr = new CompactionRequest();
+ if (dbname == null) cr.setDbname(DEFAULT_DATABASE_NAME);
+ else cr.setDbname(dbname);
+ cr.setTablename(tableName);
+ if (partitionName != null) cr.setPartitionname(partitionName);
+ cr.setType(type);
+ cr.setProperties(tblproperties);
+ return client.compact2(cr);
+ }
+ @Override
+ public ShowCompactResponse showCompactions() throws TException {
+ return client.show_compact(new ShowCompactRequest());
+ }
+
+ @Deprecated
+ @Override
+ public void addDynamicPartitions(long txnId, String dbName, String tableName,
+ List<String> partNames) throws TException {
+ client.add_dynamic_partitions(new AddDynamicPartitions(txnId, dbName, tableName, partNames));
+ }
+ @Override
+ public void addDynamicPartitions(long txnId, String dbName, String tableName,
+ List<String> partNames, DataOperationType operationType) throws TException {
+ AddDynamicPartitions adp = new AddDynamicPartitions(txnId, dbName, tableName, partNames);
+ adp.setOperationType(operationType);
+ client.add_dynamic_partitions(adp);
+ }
+
+ @Override
+ public void insertTable(Table table, boolean overwrite) throws MetaException {
+ boolean failed = true;
+ HiveMetaHook hook = getHook(table);
+ if (hook == null || !(hook instanceof DefaultHiveMetaHook)) {
+ return;
+ }
+ DefaultHiveMetaHook hiveMetaHook = (DefaultHiveMetaHook) hook;
+ try {
+ hiveMetaHook.commitInsertTable(table, overwrite);
+ failed = false;
+ }
+ finally {
+ if (failed) {
+ hiveMetaHook.rollbackInsertTable(table, overwrite);
+ }
+ }
+ }
+
+ @InterfaceAudience.LimitedPrivate({"HCatalog"})
+ @Override
+ public NotificationEventResponse getNextNotification(long lastEventId, int maxEvents,
+ NotificationFilter filter) throws TException {
+ NotificationEventRequest rqst = new NotificationEventRequest(lastEventId);
+ rqst.setMaxEvents(maxEvents);
+ NotificationEventResponse rsp = client.get_next_notification(rqst);
+ LOG.debug("Got back " + rsp.getEventsSize() + " events");
+ if (filter == null) {
+ return rsp;
+ } else {
+ NotificationEventResponse filtered = new NotificationEventResponse();
+ if (rsp != null && rsp.getEvents() != null) {
+ for (NotificationEvent e : rsp.getEvents()) {
+ if (filter.accept(e)) filtered.addToEvents(e);
+ }
+ }
+ return filtered;
+ }
+ }
+
+ @InterfaceAudience.LimitedPrivate({"HCatalog"})
+ @Override
+ public CurrentNotificationEventId getCurrentNotificationEventId() throws TException {
+ return client.get_current_notificationEventId();
+ }
+
+ @InterfaceAudience.LimitedPrivate({"HCatalog"})
+ @Override
+ public NotificationEventsCountResponse getNotificationEventsCount(NotificationEventsCountRequest rqst)
+ throws TException {
+ return client.get_notification_events_count(rqst);
+ }
+
+ @InterfaceAudience.LimitedPrivate({"Apache Hive, HCatalog"})
+ @Override
+ public FireEventResponse fireListenerEvent(FireEventRequest rqst) throws TException {
+ return client.fire_listener_event(rqst);
+ }
+
+ /**
+ * Creates a synchronized wrapper for any {@link IMetaStoreClient}.
+ * This may be used by multi-threaded applications until we have
+ * fixed all reentra
<TRUNCATED>
[04/12] hive git commit: HIVE-17980 Moved HiveMetaStoreClient plus a
few remaining classes.
Posted by ga...@apache.org.
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/IMetaStoreClient.java
----------------------------------------------------------------------
diff --git a/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/IMetaStoreClient.java b/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/IMetaStoreClient.java
new file mode 100644
index 0000000..a6c1ddc
--- /dev/null
+++ b/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/IMetaStoreClient.java
@@ -0,0 +1,1799 @@
+/*
+ * 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 java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import org.apache.hadoop.classification.InterfaceAudience;
+import org.apache.hadoop.classification.InterfaceStability;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hive.common.ValidTxnList;
+import org.apache.hadoop.hive.common.classification.RetrySemantics;
+import org.apache.hadoop.hive.metastore.annotation.NoReconnect;
+import org.apache.hadoop.hive.metastore.api.AggrStats;
+import org.apache.hadoop.hive.metastore.api.AlreadyExistsException;
+import org.apache.hadoop.hive.metastore.api.CmRecycleRequest;
+import org.apache.hadoop.hive.metastore.api.CmRecycleResponse;
+import org.apache.hadoop.hive.metastore.api.ColumnStatistics;
+import org.apache.hadoop.hive.metastore.api.ColumnStatisticsObj;
+import org.apache.hadoop.hive.metastore.api.CompactionResponse;
+import org.apache.hadoop.hive.metastore.api.CompactionType;
+import org.apache.hadoop.hive.metastore.api.ConfigValSecurityException;
+import org.apache.hadoop.hive.metastore.api.CurrentNotificationEventId;
+import org.apache.hadoop.hive.metastore.api.DataOperationType;
+import org.apache.hadoop.hive.metastore.api.Database;
+import org.apache.hadoop.hive.metastore.api.EnvironmentContext;
+import org.apache.hadoop.hive.metastore.api.FieldSchema;
+import org.apache.hadoop.hive.metastore.api.FireEventRequest;
+import org.apache.hadoop.hive.metastore.api.FireEventResponse;
+import org.apache.hadoop.hive.metastore.api.ForeignKeysRequest;
+import org.apache.hadoop.hive.metastore.api.Function;
+import org.apache.hadoop.hive.metastore.api.GetAllFunctionsResponse;
+import org.apache.hadoop.hive.metastore.api.GetOpenTxnsInfoResponse;
+import org.apache.hadoop.hive.metastore.api.GetPrincipalsInRoleRequest;
+import org.apache.hadoop.hive.metastore.api.GetPrincipalsInRoleResponse;
+import org.apache.hadoop.hive.metastore.api.GetRoleGrantsForPrincipalRequest;
+import org.apache.hadoop.hive.metastore.api.GetRoleGrantsForPrincipalResponse;
+import org.apache.hadoop.hive.metastore.api.HeartbeatTxnRangeResponse;
+import org.apache.hadoop.hive.metastore.api.HiveObjectPrivilege;
+import org.apache.hadoop.hive.metastore.api.HiveObjectRef;
+import org.apache.hadoop.hive.metastore.api.Index;
+import org.apache.hadoop.hive.metastore.api.InvalidInputException;
+import org.apache.hadoop.hive.metastore.api.InvalidObjectException;
+import org.apache.hadoop.hive.metastore.api.InvalidOperationException;
+import org.apache.hadoop.hive.metastore.api.InvalidPartitionException;
+import org.apache.hadoop.hive.metastore.api.LockRequest;
+import org.apache.hadoop.hive.metastore.api.LockResponse;
+import org.apache.hadoop.hive.metastore.api.MetaException;
+import org.apache.hadoop.hive.metastore.api.MetadataPpdResult;
+import org.apache.hadoop.hive.metastore.api.NoSuchLockException;
+import org.apache.hadoop.hive.metastore.api.NoSuchObjectException;
+import org.apache.hadoop.hive.metastore.api.NoSuchTxnException;
+import org.apache.hadoop.hive.metastore.api.NotNullConstraintsRequest;
+import org.apache.hadoop.hive.metastore.api.NotificationEvent;
+import org.apache.hadoop.hive.metastore.api.NotificationEventResponse;
+import org.apache.hadoop.hive.metastore.api.NotificationEventsCountResponse;
+import org.apache.hadoop.hive.metastore.api.NotificationEventsCountRequest;
+import org.apache.hadoop.hive.metastore.api.OpenTxnsResponse;
+import org.apache.hadoop.hive.metastore.api.Partition;
+import org.apache.hadoop.hive.metastore.api.PartitionEventType;
+import org.apache.hadoop.hive.metastore.api.PartitionValuesRequest;
+import org.apache.hadoop.hive.metastore.api.PartitionValuesResponse;
+import org.apache.hadoop.hive.metastore.api.PrimaryKeysRequest;
+import org.apache.hadoop.hive.metastore.api.PrincipalPrivilegeSet;
+import org.apache.hadoop.hive.metastore.api.PrincipalType;
+import org.apache.hadoop.hive.metastore.api.PrivilegeBag;
+import org.apache.hadoop.hive.metastore.api.WMResourcePlan;
+import org.apache.hadoop.hive.metastore.api.WMTrigger;
+import org.apache.hadoop.hive.metastore.api.Role;
+import org.apache.hadoop.hive.metastore.api.SQLForeignKey;
+import org.apache.hadoop.hive.metastore.api.SQLNotNullConstraint;
+import org.apache.hadoop.hive.metastore.api.SQLPrimaryKey;
+import org.apache.hadoop.hive.metastore.api.SQLUniqueConstraint;
+import org.apache.hadoop.hive.metastore.api.SetPartitionsStatsRequest;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponse;
+import org.apache.hadoop.hive.metastore.api.ShowLocksRequest;
+import org.apache.hadoop.hive.metastore.api.ShowLocksResponse;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.api.TableMeta;
+import org.apache.hadoop.hive.metastore.api.TxnAbortedException;
+import org.apache.hadoop.hive.metastore.api.TxnOpenException;
+import org.apache.hadoop.hive.metastore.api.UniqueConstraintsRequest;
+import org.apache.hadoop.hive.metastore.api.UnknownDBException;
+import org.apache.hadoop.hive.metastore.api.UnknownPartitionException;
+import org.apache.hadoop.hive.metastore.api.UnknownTableException;
+import org.apache.hadoop.hive.metastore.partition.spec.PartitionSpecProxy;
+import org.apache.hadoop.hive.metastore.utils.ObjectPair;
+import org.apache.thrift.TException;
+
+/**
+ * Wrapper around hive metastore thrift api
+ */
+@InterfaceAudience.Public
+@InterfaceStability.Evolving
+public interface IMetaStoreClient {
+
+ /**
+ * Returns whether current client is compatible with conf argument or not
+ * @return
+ */
+ boolean isCompatibleWith(Configuration conf);
+
+ /**
+ * Set added jars path info to MetaStoreClient.
+ * @param addedJars the hive.added.jars.path. It is qualified paths separated by commas.
+ */
+ void setHiveAddedJars(String addedJars);
+
+ /**
+ * Returns true if the current client is using an in process metastore (local metastore).
+ *
+ * @return
+ */
+ boolean isLocalMetaStore();
+
+ /**
+ * Tries to reconnect this MetaStoreClient to the MetaStore.
+ */
+ void reconnect() throws MetaException;
+
+ /**
+ * close connection to meta store
+ */
+ @NoReconnect
+ void close();
+
+ /**
+ * set meta variable which is open to end users
+ */
+ void setMetaConf(String key, String value) throws MetaException, TException;
+
+ /**
+ * get current meta variable
+ */
+ String getMetaConf(String key) throws MetaException, TException;
+
+ /**
+ * Get the names of all databases in the MetaStore that match the given pattern.
+ * @param databasePattern
+ * @return List of database names.
+ * @throws MetaException
+ * @throws TException
+ */
+ List<String> getDatabases(String databasePattern) throws MetaException, TException;
+
+ /**
+ * Get the names of all databases in the MetaStore.
+ * @return List of database names.
+ * @throws MetaException
+ * @throws TException
+ */
+ List<String> getAllDatabases() throws MetaException, TException;
+
+ /**
+ * Get the names of all tables in the specified database that satisfy the supplied
+ * table name pattern.
+ * @param dbName
+ * @param tablePattern
+ * @return List of table names.
+ * @throws MetaException
+ * @throws TException
+ * @throws UnknownDBException
+ */
+ List<String> getTables(String dbName, String tablePattern)
+ throws MetaException, TException, UnknownDBException;
+
+ /**
+ * Get the names of all tables in the specified database that satisfy the supplied
+ * table name pattern and table type (MANAGED_TABLE || EXTERNAL_TABLE || VIRTUAL_VIEW)
+ * @param dbName Name of the database to fetch tables in.
+ * @param tablePattern pattern to match for table names.
+ * @param tableType Type of the table in the HMS store. VIRTUAL_VIEW is for views.
+ * @return List of table names.
+ * @throws MetaException
+ * @throws TException
+ * @throws UnknownDBException
+ */
+ List<String> getTables(String dbName, String tablePattern, TableType tableType)
+ throws MetaException, TException, UnknownDBException;
+
+ /**
+ * For quick GetTablesOperation
+ */
+ List<TableMeta> getTableMeta(String dbPatterns, String tablePatterns, List<String> tableTypes)
+ throws MetaException, TException, UnknownDBException;
+
+ /**
+ * Get the names of all tables in the specified database.
+ * @param dbName
+ * @return List of table names.
+ * @throws MetaException
+ * @throws TException
+ * @throws UnknownDBException
+ */
+ List<String> getAllTables(String dbName) throws MetaException, TException, UnknownDBException;
+
+ /**
+ * Get a list of table names that match a filter.
+ * The filter operators are LIKE, <, <=, >, >=, =, <>
+ *
+ * In the filter statement, values interpreted as strings must be enclosed in quotes,
+ * while values interpreted as integers should not be. Strings and integers are the only
+ * supported value types.
+ *
+ * The currently supported key names in the filter are:
+ * Constants.HIVE_FILTER_FIELD_OWNER, which filters on the tables' owner's name
+ * and supports all filter operators
+ * Constants.HIVE_FILTER_FIELD_LAST_ACCESS, which filters on the last access times
+ * and supports all filter operators except LIKE
+ * Constants.HIVE_FILTER_FIELD_PARAMS, which filters on the tables' parameter keys and values
+ * and only supports the filter operators = and <>.
+ * Append the parameter key name to HIVE_FILTER_FIELD_PARAMS in the filter statement.
+ * For example, to filter on parameter keys called "retention", the key name in the filter
+ * statement should be Constants.HIVE_FILTER_FIELD_PARAMS + "retention"
+ * Also, = and <> only work for keys that exist in the tables.
+ * E.g., filtering on tables where key1 <> value will only
+ * return tables that have a value for the parameter key1.
+ * Some example filter statements include:
+ * filter = Constants.HIVE_FILTER_FIELD_OWNER + " like \".*test.*\" and " +
+ * Constants.HIVE_FILTER_FIELD_LAST_ACCESS + " = 0";
+ * filter = Constants.HIVE_FILTER_FIELD_OWNER + " = \"test_user\" and (" +
+ * Constants.HIVE_FILTER_FIELD_PARAMS + "retention = \"30\" or " +
+ * Constants.HIVE_FILTER_FIELD_PARAMS + "retention = \"90\")"
+ *
+ * @param dbName
+ * The name of the database from which you will retrieve the table names
+ * @param filter
+ * The filter string
+ * @param maxTables
+ * The maximum number of tables returned
+ * @return A list of table names that match the desired filter
+ */
+ List<String> listTableNamesByFilter(String dbName, String filter, short maxTables)
+ throws MetaException, TException, InvalidOperationException, UnknownDBException;
+
+
+ /**
+ * Drop the table.
+ *
+ * @param dbname
+ * The database for this table
+ * @param tableName
+ * The table to drop
+ * @param deleteData
+ * Should we delete the underlying data
+ * @param ignoreUnknownTab
+ * don't throw if the requested table doesn't exist
+ * @throws MetaException
+ * Could not drop table properly.
+ * @throws NoSuchObjectException
+ * The table wasn't found.
+ * @throws TException
+ * A thrift communication error occurred
+ */
+ void dropTable(String dbname, String tableName, boolean deleteData,
+ boolean ignoreUnknownTab) throws MetaException, TException,
+ NoSuchObjectException;
+
+ /**
+ * @param ifPurge
+ * completely purge the table (skipping trash) while removing data from warehouse
+ * @see #dropTable(String, String, boolean, boolean)
+ */
+ public void dropTable(String dbname, String tableName, boolean deleteData,
+ boolean ignoreUnknownTab, boolean ifPurge) throws MetaException, TException,
+ NoSuchObjectException;
+
+ /**
+ * Drop the table in the DEFAULT database.
+ *
+ * @param tableName
+ * The table to drop
+ * @param deleteData
+ * Should we delete the underlying data
+ * @throws MetaException
+ * Could not drop table properly.
+ * @throws UnknownTableException
+ * The table wasn't found.
+ * @throws TException
+ * A thrift communication error occurred
+ * @throws NoSuchObjectException
+ * The table wasn't found.
+ *
+ * @deprecated As of release 0.6.0 replaced by {@link #dropTable(String, String, boolean, boolean)}.
+ * This method will be removed in release 0.7.0.
+ */
+ @Deprecated
+ void dropTable(String tableName, boolean deleteData)
+ throws MetaException, UnknownTableException, TException, NoSuchObjectException;
+
+ /**
+ * @see #dropTable(String, String, boolean, boolean)
+ */
+ void dropTable(String dbname, String tableName)
+ throws MetaException, TException, NoSuchObjectException;
+
+ /**
+ * Truncate the table/partitions in the DEFAULT database.
+ * @param dbName
+ * The db to which the table to be truncate belongs to
+ * @param tableName
+ * The table to truncate
+ * @param partNames
+ * List of partitions to truncate. NULL will truncate the whole table/all partitions
+ * @throws MetaException
+ * @throws TException
+ * Could not truncate table properly.
+ */
+ void truncateTable(String dbName, String tableName, List<String> partNames) throws MetaException, TException;
+
+ /**
+ * Recycles the files recursively from the input path to the cmroot directory either by copying or moving it.
+ *
+ * @param request Inputs for path of the data files to be recycled to cmroot and
+ * isPurge flag when set to true files which needs to be recycled are not moved to Trash
+ * @return Response which is currently void
+ */
+ CmRecycleResponse recycleDirToCmPath(CmRecycleRequest request) throws MetaException, TException;
+
+ boolean tableExists(String databaseName, String tableName) throws MetaException,
+ TException, UnknownDBException;
+
+ /**
+ * Check to see if the specified table exists in the DEFAULT database.
+ * @param tableName
+ * @return TRUE if DEFAULT.tableName exists, FALSE otherwise.
+ * @throws MetaException
+ * @throws TException
+ * @throws UnknownDBException
+ * @deprecated As of release 0.6.0 replaced by {@link #tableExists(String, String)}.
+ * This method will be removed in release 0.7.0.
+ */
+ @Deprecated
+ boolean tableExists(String tableName) throws MetaException,
+ TException, UnknownDBException;
+
+ /**
+ * Get a table object from the DEFAULT database.
+ *
+ * @param tableName
+ * Name of the table to fetch.
+ * @return An object representing the table.
+ * @throws MetaException
+ * Could not fetch the table
+ * @throws TException
+ * A thrift communication error occurred
+ * @throws NoSuchObjectException
+ * In case the table wasn't found.
+ * @deprecated As of release 0.6.0 replaced by {@link #getTable(String, String)}.
+ * This method will be removed in release 0.7.0.
+ */
+ @Deprecated
+ Table getTable(String tableName) throws MetaException, TException, NoSuchObjectException;
+
+ /**
+ * Get a Database Object
+ * @param databaseName name of the database to fetch
+ * @return the database
+ * @throws NoSuchObjectException The database does not exist
+ * @throws MetaException Could not fetch the database
+ * @throws TException A thrift communication error occurred
+ */
+ Database getDatabase(String databaseName)
+ throws NoSuchObjectException, MetaException, TException;
+
+
+ /**
+ * Get a table object.
+ *
+ * @param dbName
+ * The database the table is located in.
+ * @param tableName
+ * Name of the table to fetch.
+ * @return An object representing the table.
+ * @throws MetaException
+ * Could not fetch the table
+ * @throws TException
+ * A thrift communication error occurred
+ * @throws NoSuchObjectException
+ * In case the table wasn't found.
+ */
+ Table getTable(String dbName, String tableName) throws MetaException,
+ TException, NoSuchObjectException;
+
+ /**
+ *
+ * @param dbName
+ * The database the tables are located in.
+ * @param tableNames
+ * The names of the tables to fetch
+ * @return A list of objects representing the tables.
+ * Only the tables that can be retrieved from the database are returned. For example,
+ * if none of the requested tables could be retrieved, an empty list is returned.
+ * There is no guarantee of ordering of the returned tables.
+ * @throws InvalidOperationException
+ * The input to this operation is invalid (e.g., the list of tables names is null)
+ * @throws UnknownDBException
+ * The requested database could not be fetched.
+ * @throws TException
+ * A thrift communication error occurred
+ * @throws MetaException
+ * Any other errors
+ */
+ List<Table> getTableObjectsByName(String dbName, List<String> tableNames)
+ throws MetaException, InvalidOperationException, UnknownDBException, TException;
+
+ /**
+ * @param tableName
+ * @param dbName
+ * @param partVals
+ * @return the partition object
+ * @throws InvalidObjectException
+ * @throws AlreadyExistsException
+ * @throws MetaException
+ * @throws TException
+ * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#append_partition(java.lang.String,
+ * java.lang.String, java.util.List)
+ */
+ Partition appendPartition(String tableName, String dbName,
+ List<String> partVals) throws InvalidObjectException,
+ AlreadyExistsException, MetaException, TException;
+
+ Partition appendPartition(String tableName, String dbName, String name)
+ throws InvalidObjectException, AlreadyExistsException, MetaException, TException;
+
+ /**
+ * Add a partition to the table.
+ *
+ * @param partition
+ * The partition to add
+ * @return The partition added
+ * @throws InvalidObjectException
+ * Could not find table to add to
+ * @throws AlreadyExistsException
+ * Partition already exists
+ * @throws MetaException
+ * Could not add partition
+ * @throws TException
+ * Thrift exception
+ */
+ Partition add_partition(Partition partition)
+ throws InvalidObjectException, AlreadyExistsException, MetaException, TException;
+
+ /**
+ * Add partitions to the table.
+ *
+ * @param partitions
+ * The partitions to add
+ * @throws InvalidObjectException
+ * Could not find table to add to
+ * @throws AlreadyExistsException
+ * Partition already exists
+ * @throws MetaException
+ * Could not add partition
+ * @throws TException
+ * Thrift exception
+ */
+ int add_partitions(List<Partition> partitions)
+ throws InvalidObjectException, AlreadyExistsException, MetaException, TException;
+
+ int add_partitions_pspec(PartitionSpecProxy partitionSpec)
+ throws InvalidObjectException, AlreadyExistsException, MetaException, TException;
+
+ /**
+ * Add partitions to the table.
+ *
+ * @param partitions The partitions to add
+ * @param ifNotExists only add partitions if they don't exist
+ * @param needResults Whether the results are needed
+ * @return the partitions that were added, or null if !needResults
+ */
+ List<Partition> add_partitions(
+ List<Partition> partitions, boolean ifNotExists, boolean needResults)
+ throws InvalidObjectException, AlreadyExistsException, MetaException, TException;
+
+ /**
+ * @param dbName
+ * @param tblName
+ * @param partVals
+ * @return the partition object
+ * @throws MetaException
+ * @throws TException
+ * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#get_partition(java.lang.String,
+ * java.lang.String, java.util.List)
+ */
+ Partition getPartition(String dbName, String tblName,
+ List<String> partVals) throws NoSuchObjectException, MetaException, TException;
+
+ /**
+ * @param partitionSpecs
+ * @param sourceDb
+ * @param sourceTable
+ * @param destdb
+ * @param destTableName
+ * @return partition object
+ */
+ Partition exchange_partition(Map<String, String> partitionSpecs,
+ String sourceDb, String sourceTable, String destdb,
+ String destTableName) throws MetaException, NoSuchObjectException,
+ InvalidObjectException, TException;
+
+ /**
+ * With the one partitionSpecs to exchange, multiple partitions could be exchanged.
+ * e.g., year=2015/month/day, exchanging partition year=2015 results to all the partitions
+ * belonging to it exchanged. This function returns the list of affected partitions.
+ * @param partitionSpecs
+ * @param sourceDb
+ * @param sourceTable
+ * @param destdb
+ * @param destTableName
+ * @return the list of the new partitions
+ */
+ List<Partition> exchange_partitions(Map<String, String> partitionSpecs,
+ String sourceDb, String sourceTable, String destdb,
+ String destTableName) throws MetaException, NoSuchObjectException,
+ InvalidObjectException, TException;
+
+ /**
+ * @param dbName
+ * @param tblName
+ * @param name - partition name i.e. 'ds=2010-02-03/ts=2010-02-03 18%3A16%3A01'
+ * @return the partition object
+ * @throws MetaException
+ * @throws TException
+ * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#get_partition(java.lang.String,
+ * java.lang.String, java.util.List)
+ */
+ Partition getPartition(String dbName, String tblName,
+ String name) throws MetaException, UnknownTableException, NoSuchObjectException, TException;
+
+
+ /**
+ * @param dbName
+ * @param tableName
+ * @param pvals
+ * @param userName
+ * @param groupNames
+ * @return the partition
+ * @throws MetaException
+ * @throws UnknownTableException
+ * @throws NoSuchObjectException
+ * @throws TException
+ */
+ Partition getPartitionWithAuthInfo(String dbName, String tableName,
+ List<String> pvals, String userName, List<String> groupNames)
+ throws MetaException, UnknownTableException, NoSuchObjectException, TException;
+
+ /**
+ * @param tbl_name
+ * @param db_name
+ * @param max_parts
+ * @return the list of partitions
+ * @throws NoSuchObjectException
+ * @throws MetaException
+ * @throws TException
+ */
+ List<Partition> listPartitions(String db_name, String tbl_name,
+ short max_parts) throws NoSuchObjectException, MetaException, TException;
+
+ public PartitionSpecProxy listPartitionSpecs(String dbName, String tableName, int maxParts)
+ throws TException;
+ List<Partition> listPartitions(String db_name, String tbl_name,
+ List<String> part_vals, short max_parts) throws NoSuchObjectException, MetaException, TException;
+
+ List<String> listPartitionNames(String db_name, String tbl_name,
+ short max_parts) throws NoSuchObjectException, MetaException, TException;
+
+ List<String> listPartitionNames(String db_name, String tbl_name,
+ List<String> part_vals, short max_parts)
+ throws MetaException, TException, NoSuchObjectException;
+
+ public PartitionValuesResponse listPartitionValues(PartitionValuesRequest request)
+ throws MetaException, TException, NoSuchObjectException;
+
+ /**
+ * Get number of partitions matching specified filter
+ * @param dbName the database name
+ * @param tableName the table name
+ * @param filter the filter string,
+ * for example "part1 = \"p1_abc\" and part2 <= "\p2_test\"". Filtering can
+ * be done only on string partition keys.
+ * @return number of partitions
+ * @throws MetaException
+ * @throws NoSuchObjectException
+ * @throws TException
+ */
+ public int getNumPartitionsByFilter(String dbName, String tableName,
+ String filter) throws MetaException, NoSuchObjectException, TException;
+
+
+ /**
+ * Get list of partitions matching specified filter
+ * @param db_name the database name
+ * @param tbl_name the table name
+ * @param filter the filter string,
+ * for example "part1 = \"p1_abc\" and part2 <= "\p2_test\"". Filtering can
+ * be done only on string partition keys.
+ * @param max_parts the maximum number of partitions to return,
+ * all partitions are returned if -1 is passed
+ * @return list of partitions
+ * @throws MetaException
+ * @throws NoSuchObjectException
+ * @throws TException
+ */
+ List<Partition> listPartitionsByFilter(String db_name, String tbl_name,
+ String filter, short max_parts) throws MetaException,
+ NoSuchObjectException, TException;
+
+ PartitionSpecProxy listPartitionSpecsByFilter(String db_name, String tbl_name,
+ String filter, int max_parts) throws MetaException,
+ NoSuchObjectException, TException;
+
+ /**
+ * Get list of partitions matching specified serialized expression
+ * @param db_name the database name
+ * @param tbl_name the table name
+ * @param expr expression, serialized from ExprNodeDesc
+ * @param max_parts the maximum number of partitions to return,
+ * all partitions are returned if -1 is passed
+ * @param default_partition_name Default partition name from configuration. If blank, the
+ * metastore server-side configuration is used.
+ * @param result the resulting list of partitions
+ * @return whether the resulting list contains partitions which may or may not match the expr
+ */
+ boolean listPartitionsByExpr(String db_name, String tbl_name,
+ byte[] expr, String default_partition_name, short max_parts, List<Partition> result)
+ throws TException;
+
+ /**
+ * @param dbName
+ * @param tableName
+ * @param s
+ * @param userName
+ * @param groupNames
+ * @return the list of partitions
+ * @throws NoSuchObjectException
+ */
+ List<Partition> listPartitionsWithAuthInfo(String dbName,
+ String tableName, short s, String userName, List<String> groupNames)
+ throws MetaException, TException, NoSuchObjectException;
+
+ /**
+ * Get partitions by a list of partition names.
+ * @param db_name database name
+ * @param tbl_name table name
+ * @param part_names list of partition names
+ * @return list of Partition objects
+ * @throws NoSuchObjectException
+ * @throws MetaException
+ * @throws TException
+ */
+ List<Partition> getPartitionsByNames(String db_name, String tbl_name,
+ List<String> part_names) throws NoSuchObjectException, MetaException, TException;
+
+ /**
+ * @param dbName
+ * @param tableName
+ * @param partialPvals
+ * @param s
+ * @param userName
+ * @param groupNames
+ * @return the list of paritions
+ * @throws NoSuchObjectException
+ */
+ List<Partition> listPartitionsWithAuthInfo(String dbName,
+ String tableName, List<String> partialPvals, short s, String userName,
+ List<String> groupNames) throws MetaException, TException, NoSuchObjectException;
+
+ /**
+ * @param db_name
+ * @param tbl_name
+ * @param partKVs
+ * @param eventType
+ * @throws MetaException
+ * @throws NoSuchObjectException
+ * @throws TException
+ * @throws UnknownTableException
+ * @throws UnknownDBException
+ * @throws UnknownPartitionException
+ * @throws InvalidPartitionException
+ */
+ void markPartitionForEvent(String db_name, String tbl_name, Map<String,String> partKVs,
+ PartitionEventType eventType) throws MetaException, NoSuchObjectException, TException,
+ UnknownTableException, UnknownDBException, UnknownPartitionException, InvalidPartitionException;
+
+ /**
+ * @param db_name
+ * @param tbl_name
+ * @param partKVs
+ * @param eventType
+ * @throws MetaException
+ * @throws NoSuchObjectException
+ * @throws TException
+ * @throws UnknownTableException
+ * @throws UnknownDBException
+ * @throws UnknownPartitionException
+ * @throws InvalidPartitionException
+ */
+ boolean isPartitionMarkedForEvent(String db_name, String tbl_name, Map<String,String> partKVs,
+ PartitionEventType eventType) throws MetaException, NoSuchObjectException, TException,
+ UnknownTableException, UnknownDBException, UnknownPartitionException, InvalidPartitionException;
+
+ /**
+ * @param partVals
+ * @throws TException
+ * @throws MetaException
+ */
+ void validatePartitionNameCharacters(List<String> partVals) throws TException, MetaException;
+
+ /**
+ * @param tbl
+ * @throws AlreadyExistsException
+ * @throws InvalidObjectException
+ * @throws MetaException
+ * @throws NoSuchObjectException
+ * @throws TException
+ * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#create_table(org.apache.hadoop.hive.metastore.api.Table)
+ */
+
+ void createTable(Table tbl) throws AlreadyExistsException,
+ InvalidObjectException, MetaException, NoSuchObjectException, TException;
+
+ void alter_table(String defaultDatabaseName, String tblName,
+ Table table) throws InvalidOperationException, MetaException, TException;
+
+ /**
+ * Use alter_table_with_environmentContext instead of alter_table with cascade option
+ * passed in EnvironmentContext using {@code StatsSetupConst.CASCADE}
+ */
+ @Deprecated
+ void alter_table(String defaultDatabaseName, String tblName, Table table,
+ boolean cascade) throws InvalidOperationException, MetaException, TException;
+
+ //wrapper of alter_table_with_cascade
+ void alter_table_with_environmentContext(String defaultDatabaseName, String tblName, Table table,
+ EnvironmentContext environmentContext) throws InvalidOperationException, MetaException,
+ TException;
+
+ void createDatabase(Database db)
+ throws InvalidObjectException, AlreadyExistsException, MetaException, TException;
+
+ void dropDatabase(String name)
+ throws NoSuchObjectException, InvalidOperationException, MetaException, TException;
+
+ void dropDatabase(String name, boolean deleteData, boolean ignoreUnknownDb)
+ throws NoSuchObjectException, InvalidOperationException, MetaException, TException;
+
+ void dropDatabase(String name, boolean deleteData, boolean ignoreUnknownDb, boolean cascade)
+ throws NoSuchObjectException, InvalidOperationException, MetaException, TException;
+
+ void alterDatabase(String name, Database db)
+ throws NoSuchObjectException, MetaException, TException;
+
+ /**
+ * @param db_name
+ * @param tbl_name
+ * @param part_vals
+ * @param deleteData
+ * delete the underlying data or just delete the table in metadata
+ * @return true or false
+ * @throws NoSuchObjectException
+ * @throws MetaException
+ * @throws TException
+ * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#drop_partition(java.lang.String,
+ * java.lang.String, java.util.List, boolean)
+ */
+ boolean dropPartition(String db_name, String tbl_name,
+ List<String> part_vals, boolean deleteData) throws NoSuchObjectException,
+ MetaException, TException;
+
+ /**
+ * Method to dropPartitions() with the option to purge the partition data directly,
+ * rather than to move data to trash.
+ * @param db_name Name of the database.
+ * @param tbl_name Name of the table.
+ * @param part_vals Specification of the partitions being dropped.
+ * @param options PartitionDropOptions for the operation.
+ * @return True (if partitions are dropped), else false.
+ * @throws TException
+ */
+ boolean dropPartition(String db_name, String tbl_name, List<String> part_vals,
+ PartitionDropOptions options) throws TException;
+
+ List<Partition> dropPartitions(String dbName, String tblName,
+ List<ObjectPair<Integer, byte[]>> partExprs, boolean deleteData,
+ boolean ifExists) throws NoSuchObjectException, MetaException, TException;
+
+ List<Partition> dropPartitions(String dbName, String tblName,
+ List<ObjectPair<Integer, byte[]>> partExprs, boolean deleteData,
+ boolean ifExists, boolean needResults) throws NoSuchObjectException, MetaException, TException;
+
+ /**
+ * Generalization of dropPartitions(),
+ * @param dbName Name of the database
+ * @param tblName Name of the table
+ * @param partExprs Partition-specification
+ * @param options Boolean options for dropping partitions
+ * @return List of Partitions dropped
+ * @throws TException On failure
+ */
+ List<Partition> dropPartitions(String dbName, String tblName,
+ List<ObjectPair<Integer, byte[]>> partExprs, PartitionDropOptions options) throws TException;
+
+ boolean dropPartition(String db_name, String tbl_name,
+ String name, boolean deleteData) throws NoSuchObjectException,
+ MetaException, TException;
+
+ /**
+ * updates a partition to new partition
+ *
+ * @param dbName
+ * database of the old partition
+ * @param tblName
+ * table name of the old partition
+ * @param newPart
+ * new partition
+ * @throws InvalidOperationException
+ * if the old partition does not exist
+ * @throws MetaException
+ * if error in updating metadata
+ * @throws TException
+ * if error in communicating with metastore server
+ */
+ void alter_partition(String dbName, String tblName, Partition newPart)
+ throws InvalidOperationException, MetaException, TException;
+
+ /**
+ * updates a partition to new partition
+ *
+ * @param dbName
+ * database of the old partition
+ * @param tblName
+ * table name of the old partition
+ * @param newPart
+ * new partition
+ * @throws InvalidOperationException
+ * if the old partition does not exist
+ * @throws MetaException
+ * if error in updating metadata
+ * @throws TException
+ * if error in communicating with metastore server
+ */
+ void alter_partition(String dbName, String tblName, Partition newPart, EnvironmentContext environmentContext)
+ throws InvalidOperationException, MetaException, TException;
+
+ /**
+ * updates a list of partitions
+ *
+ * @param dbName
+ * database of the old partition
+ * @param tblName
+ * table name of the old partition
+ * @param newParts
+ * list of partitions
+ * @throws InvalidOperationException
+ * if the old partition does not exist
+ * @throws MetaException
+ * if error in updating metadata
+ * @throws TException
+ * if error in communicating with metastore server
+ */
+ void alter_partitions(String dbName, String tblName, List<Partition> newParts)
+ throws InvalidOperationException, MetaException, TException;
+
+ /**
+ * updates a list of partitions
+ *
+ * @param dbName
+ * database of the old partition
+ * @param tblName
+ * table name of the old partition
+ * @param newParts
+ * list of partitions
+ * @param environmentContext
+ * @throws InvalidOperationException
+ * if the old partition does not exist
+ * @throws MetaException
+ * if error in updating metadata
+ * @throws TException
+ * if error in communicating with metastore server
+ */
+ void alter_partitions(String dbName, String tblName, List<Partition> newParts,
+ EnvironmentContext environmentContext)
+ throws InvalidOperationException, MetaException, TException;
+
+ /**
+ * rename a partition to a new partition
+ *
+ * @param dbname
+ * database of the old partition
+ * @param name
+ * table name of the old partition
+ * @param part_vals
+ * values of the old partition
+ * @param newPart
+ * new partition
+ * @throws InvalidOperationException
+ * if srcFs and destFs are different
+ * @throws MetaException
+ * if error in updating metadata
+ * @throws TException
+ * if error in communicating with metastore server
+ */
+ void renamePartition(final String dbname, final String name, final List<String> part_vals, final Partition newPart)
+ throws InvalidOperationException, MetaException, TException;
+
+ /**
+ * @param db
+ * @param tableName
+ * @throws UnknownTableException
+ * @throws UnknownDBException
+ * @throws MetaException
+ * @throws TException
+ * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#get_fields(java.lang.String,
+ * java.lang.String)
+ */
+ List<FieldSchema> getFields(String db, String tableName)
+ throws MetaException, TException, UnknownTableException,
+ UnknownDBException;
+
+ /**
+ * @param db
+ * @param tableName
+ * @throws UnknownTableException
+ * @throws UnknownDBException
+ * @throws MetaException
+ * @throws TException
+ * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#get_schema(java.lang.String,
+ * java.lang.String)
+ */
+ List<FieldSchema> getSchema(String db, String tableName)
+ throws MetaException, TException, UnknownTableException,
+ UnknownDBException;
+
+ /**
+ * @param name
+ * name of the configuration property to get the value of
+ * @param defaultValue
+ * the value to return if property with the given name doesn't exist
+ * @return value of the specified configuration property
+ * @throws TException
+ * @throws ConfigValSecurityException
+ */
+ String getConfigValue(String name, String defaultValue)
+ throws TException, ConfigValSecurityException;
+
+ /**
+ *
+ * @param name
+ * the partition name e.g. ("ds=2010-03-03/hr=12")
+ * @return a list containing the partition col values, in the same order as the name
+ * @throws MetaException
+ * @throws TException
+ */
+ List<String> partitionNameToVals(String name)
+ throws MetaException, TException;
+ /**
+ *
+ * @param name
+ * the partition name e.g. ("ds=2010-03-03/hr=12")
+ * @return a map from the partition col to the value, as listed in the name
+ * @throws MetaException
+ * @throws TException
+ */
+ Map<String, String> partitionNameToSpec(String name)
+ throws MetaException, TException;
+
+ /**
+ * create an index
+ * @param index the index object
+ * @throws InvalidObjectException
+ * @throws MetaException
+ * @throws NoSuchObjectException
+ * @throws TException
+ * @throws AlreadyExistsException
+ */
+ void createIndex(Index index, Table indexTable) throws InvalidObjectException,
+ MetaException, NoSuchObjectException, TException, AlreadyExistsException;
+
+ void alter_index(String dbName, String tblName, String indexName,
+ Index index) throws InvalidOperationException, MetaException, TException;
+
+ /**
+ *
+ * @param dbName
+ * @param tblName
+ * @param indexName
+ * @return the index
+ * @throws MetaException
+ * @throws UnknownTableException
+ * @throws NoSuchObjectException
+ * @throws TException
+ */
+ Index getIndex(String dbName, String tblName, String indexName)
+ throws MetaException, UnknownTableException, NoSuchObjectException,
+ TException;
+
+
+ /**
+ * list indexes of the give base table
+ * @param db_name
+ * @param tbl_name
+ * @param max
+ * @return the list of indexes
+ * @throws NoSuchObjectException
+ * @throws MetaException
+ * @throws TException
+ */
+ List<Index> listIndexes(String db_name, String tbl_name,
+ short max) throws NoSuchObjectException, MetaException, TException;
+
+ /**
+ * list all the index names of the give base table.
+ *
+ * @param db_name
+ * @param tbl_name
+ * @param max
+ * @return the list of names
+ * @throws MetaException
+ * @throws TException
+ */
+ List<String> listIndexNames(String db_name, String tbl_name,
+ short max) throws MetaException, TException;
+
+ /**
+ * @param db_name
+ * @param tbl_name
+ * @param name index name
+ * @param deleteData
+ * @return true on success
+ * @throws NoSuchObjectException
+ * @throws MetaException
+ * @throws TException
+ */
+ boolean dropIndex(String db_name, String tbl_name,
+ String name, boolean deleteData) throws NoSuchObjectException,
+ MetaException, TException;
+
+ /**
+ * Write table level column statistics to persistent store
+ * @param statsObj
+ * @return boolean indicating the status of the operation
+ * @throws NoSuchObjectException
+ * @throws InvalidObjectException
+ * @throws MetaException
+ * @throws TException
+ * @throws InvalidInputException
+ */
+
+ boolean updateTableColumnStatistics(ColumnStatistics statsObj)
+ throws NoSuchObjectException, InvalidObjectException, MetaException, TException,
+ InvalidInputException;
+
+ /**
+ * Write partition level column statistics to persistent store
+ * @param statsObj
+ * @return boolean indicating the status of the operation
+ * @throws NoSuchObjectException
+ * @throws InvalidObjectException
+ * @throws MetaException
+ * @throws TException
+ * @throws InvalidInputException
+ */
+
+ boolean updatePartitionColumnStatistics(ColumnStatistics statsObj)
+ throws NoSuchObjectException, InvalidObjectException, MetaException, TException,
+ InvalidInputException;
+
+ /**
+ * Get table column statistics given dbName, tableName and multiple colName-s
+ * @return ColumnStatistics struct for a given db, table and columns
+ */
+ List<ColumnStatisticsObj> getTableColumnStatistics(String dbName, String tableName,
+ List<String> colNames) throws NoSuchObjectException, MetaException, TException;
+
+ /**
+ * Get partitions column statistics given dbName, tableName, multiple partitions and colName-s
+ * @return ColumnStatistics struct for a given db, table and columns
+ */
+ Map<String, List<ColumnStatisticsObj>> getPartitionColumnStatistics(String dbName,
+ String tableName, List<String> partNames, List<String> colNames)
+ throws NoSuchObjectException, MetaException, TException;
+
+ /**
+ * Delete partition level column statistics given dbName, tableName, partName and colName
+ * @param dbName
+ * @param tableName
+ * @param partName
+ * @param colName
+ * @return boolean indicating outcome of the operation
+ * @throws NoSuchObjectException
+ * @throws InvalidObjectException
+ * @throws MetaException
+ * @throws TException
+ * @throws InvalidInputException
+ */
+
+ boolean deletePartitionColumnStatistics(String dbName, String tableName,
+ String partName, String colName) throws NoSuchObjectException, MetaException,
+ InvalidObjectException, TException, InvalidInputException;
+
+ /**
+ * Delete table level column statistics given dbName, tableName and colName
+ * @param dbName
+ * @param tableName
+ * @param colName
+ * @return boolean indicating the outcome of the operation
+ * @throws NoSuchObjectException
+ * @throws MetaException
+ * @throws InvalidObjectException
+ * @throws TException
+ * @throws InvalidInputException
+ */
+ boolean deleteTableColumnStatistics(String dbName, String tableName, String colName) throws
+ NoSuchObjectException, MetaException, InvalidObjectException, TException, InvalidInputException;
+
+ /**
+ * @param role
+ * role object
+ * @return true on success
+ * @throws MetaException
+ * @throws TException
+ */
+ boolean create_role(Role role)
+ throws MetaException, TException;
+
+ /**
+ * @param role_name
+ * role name
+ *
+ * @return true on success
+ * @throws MetaException
+ * @throws TException
+ */
+ boolean drop_role(String role_name) throws MetaException, TException;
+
+ /**
+ * list all role names
+ * @return list of names
+ * @throws TException
+ * @throws MetaException
+ */
+ List<String> listRoleNames() throws MetaException, TException;
+
+ /**
+ *
+ * @param role_name
+ * @param user_name
+ * @param principalType
+ * @param grantor
+ * @param grantorType
+ * @param grantOption
+ * @return true on success
+ * @throws MetaException
+ * @throws TException
+ */
+ boolean grant_role(String role_name, String user_name,
+ PrincipalType principalType, String grantor, PrincipalType grantorType,
+ boolean grantOption) throws MetaException, TException;
+
+ /**
+ * @param role_name
+ * role name
+ * @param user_name
+ * user name
+ * @param principalType
+ *
+ * @return true on success
+ * @throws MetaException
+ * @throws TException
+ */
+ boolean revoke_role(String role_name, String user_name,
+ PrincipalType principalType, boolean grantOption) throws MetaException, TException;
+
+ /**
+ *
+ * @param principalName
+ * @param principalType
+ * @return list of roles
+ * @throws MetaException
+ * @throws TException
+ */
+ List<Role> list_roles(String principalName, PrincipalType principalType)
+ throws MetaException, TException;
+
+ /**
+ * Return the privileges that the user, group have directly and indirectly through roles
+ * on the given hiveObject
+ * @param hiveObject
+ * @param user_name
+ * @param group_names
+ * @return the privilege set
+ * @throws MetaException
+ * @throws TException
+ */
+ PrincipalPrivilegeSet get_privilege_set(HiveObjectRef hiveObject,
+ String user_name, List<String> group_names) throws MetaException,
+ TException;
+
+ /**
+ * Return the privileges that this principal has directly over the object (not through roles).
+ * @param principal_name
+ * @param principal_type
+ * @param hiveObject
+ * @return list of privileges
+ * @throws MetaException
+ * @throws TException
+ */
+ List<HiveObjectPrivilege> list_privileges(String principal_name,
+ PrincipalType principal_type, HiveObjectRef hiveObject)
+ throws MetaException, TException;
+
+ /**
+ * @param privileges
+ * @return true on success
+ * @throws MetaException
+ * @throws TException
+ */
+ boolean grant_privileges(PrivilegeBag privileges)
+ throws MetaException, TException;
+
+ /**
+ * @param privileges
+ * @return true on success
+ * @throws MetaException
+ * @throws TException
+ */
+ boolean revoke_privileges(PrivilegeBag privileges, boolean grantOption)
+ throws MetaException, TException;
+
+ /**
+ * This is expected to be a no-op when in local mode,
+ * which means that the implementation will return null.
+ * @param owner the intended owner for the token
+ * @param renewerKerberosPrincipalName
+ * @return the string of the token
+ * @throws MetaException
+ * @throws TException
+ */
+ String getDelegationToken(String owner, String renewerKerberosPrincipalName)
+ throws MetaException, TException;
+
+ /**
+ * @param tokenStrForm
+ * @return the new expiration time
+ * @throws MetaException
+ * @throws TException
+ */
+ long renewDelegationToken(String tokenStrForm) throws MetaException, TException;
+
+ /**
+ * @param tokenStrForm
+ * @throws MetaException
+ * @throws TException
+ */
+ void cancelDelegationToken(String tokenStrForm) throws MetaException, TException;
+
+ String getTokenStrForm() throws IOException;
+
+ boolean addToken(String tokenIdentifier, String delegationToken) throws TException;
+
+ boolean removeToken(String tokenIdentifier) throws TException;
+
+ String getToken(String tokenIdentifier) throws TException;
+
+ List<String> getAllTokenIdentifiers() throws TException;
+
+ int addMasterKey(String key) throws MetaException, TException;
+
+ void updateMasterKey(Integer seqNo, String key)
+ throws NoSuchObjectException, MetaException, TException;
+
+ boolean removeMasterKey(Integer keySeq) throws TException;
+
+ String[] getMasterKeys() throws TException;
+
+ void createFunction(Function func)
+ throws InvalidObjectException, MetaException, TException;
+
+ void alterFunction(String dbName, String funcName, Function newFunction)
+ throws InvalidObjectException, MetaException, TException;
+
+ void dropFunction(String dbName, String funcName) throws MetaException,
+ NoSuchObjectException, InvalidObjectException, InvalidInputException, TException;
+
+ Function getFunction(String dbName, String funcName)
+ throws MetaException, TException;
+
+ List<String> getFunctions(String dbName, String pattern)
+ throws MetaException, TException;
+
+ GetAllFunctionsResponse getAllFunctions()
+ throws MetaException, TException;
+
+ /**
+ * Get a structure that details valid transactions.
+ * @return list of valid transactions
+ * @throws TException
+ */
+ ValidTxnList getValidTxns() throws TException;
+
+ /**
+ * Get a structure that details valid transactions.
+ * @param currentTxn The current transaction of the caller. This will be removed from the
+ * exceptions list so that the caller sees records from his own transaction.
+ * @return list of valid transactions
+ * @throws TException
+ */
+ ValidTxnList getValidTxns(long currentTxn) throws TException;
+
+ /**
+ * Initiate a transaction.
+ * @param user User who is opening this transaction. This is the Hive user,
+ * not necessarily the OS user. It is assumed that this user has already been
+ * authenticated and authorized at this point.
+ * @return transaction identifier
+ * @throws TException
+ */
+ long openTxn(String user) throws TException;
+
+ /**
+ * Initiate a batch of transactions. It is not guaranteed that the
+ * requested number of transactions will be instantiated. The system has a
+ * maximum number instantiated per request, controlled by hive.txn.max
+ * .batch.open in hive-site.xml. If the user requests more than this
+ * value, only the configured max will be returned.
+ *
+ * <p>Increasing the number of transactions requested in the batch will
+ * allow applications that stream data into Hive to place more commits in a
+ * single file, thus reducing load on the namenode and making reads of the
+ * data more efficient. However, opening more transactions in a batch will
+ * also result in readers needing to keep a larger list of open
+ * transactions to ignore, potentially slowing their reads. Users will
+ * need to test in their system to understand the optimal number of
+ * transactions to request in a batch.
+ * </p>
+ * @param user User who is opening this transaction. This is the Hive user,
+ * not necessarily the OS user. It is assumed that this user has already been
+ * authenticated and authorized at this point.
+ * @param numTxns number of requested transactions to open
+ * @return list of opened txn ids. As noted above, this may be less than
+ * requested, so the user should check how many were returned rather than
+ * optimistically assuming that the result matches the request.
+ * @throws TException
+ */
+ OpenTxnsResponse openTxns(String user, int numTxns) throws TException;
+
+ /**
+ * Rollback a transaction. This will also unlock any locks associated with
+ * this transaction.
+ * @param txnid id of transaction to be rolled back.
+ * @throws NoSuchTxnException if the requested transaction does not exist.
+ * Note that this can result from the transaction having timed out and been
+ * deleted.
+ * @throws TException
+ */
+ void rollbackTxn(long txnid) throws NoSuchTxnException, TException;
+
+ /**
+ * Commit a transaction. This will also unlock any locks associated with
+ * this transaction.
+ * @param txnid id of transaction to be committed.
+ * @throws NoSuchTxnException if the requested transaction does not exist.
+ * This can result fro the transaction having timed out and been deleted by
+ * the compactor.
+ * @throws TxnAbortedException if the requested transaction has been
+ * aborted. This can result from the transaction timing out.
+ * @throws TException
+ */
+ void commitTxn(long txnid)
+ throws NoSuchTxnException, TxnAbortedException, TException;
+
+ /**
+ * Abort a list of transactions. This is for use by "ABORT TRANSACTIONS" in the grammar.
+ * @throws TException
+ */
+ void abortTxns(List<Long> txnids) throws TException;
+
+ /**
+ * Show the list of currently open transactions. This is for use by "show transactions" in the
+ * grammar, not for applications that want to find a list of current transactions to work with.
+ * Those wishing the latter should call {@link #getValidTxns()}.
+ * @return List of currently opened transactions, included aborted ones.
+ * @throws TException
+ */
+ GetOpenTxnsInfoResponse showTxns() throws TException;
+
+ /**
+ * Request a set of locks. All locks needed for a particular query, DML,
+ * or DDL operation should be batched together and requested in one lock
+ * call. This avoids deadlocks. It also avoids blocking other users who
+ * only require some of the locks required by this user.
+ *
+ * <p>If the operation requires a transaction (INSERT, UPDATE,
+ * or DELETE) that transaction id must be provided as part this lock
+ * request. All locks associated with a transaction will be released when
+ * that transaction is committed or rolled back.</p>
+ * *
+ * <p>Once a lock is acquired, {@link #heartbeat(long, long)} must be called
+ * on a regular basis to avoid the lock being timed out by the system.</p>
+ * @param request The lock request. {@link LockRequestBuilder} can be used
+ * construct this request.
+ * @return a lock response, which will provide two things,
+ * the id of the lock (to be used in all further calls regarding this lock)
+ * as well as a state of the lock. If the state is ACQUIRED then the user
+ * can proceed. If it is WAITING the user should wait and call
+ * {@link #checkLock(long)} before proceeding. All components of the lock
+ * will have the same state.
+ * @throws NoSuchTxnException if the requested transaction does not exist.
+ * This can result fro the transaction having timed out and been deleted by
+ * the compactor.
+ * @throws TxnAbortedException if the requested transaction has been
+ * aborted. This can result from the transaction timing out.
+ * @throws TException
+ */
+ @RetrySemantics.CannotRetry
+ LockResponse lock(LockRequest request)
+ throws NoSuchTxnException, TxnAbortedException, TException;
+
+ /**
+ * Check the status of a set of locks requested via a
+ * {@link #lock(org.apache.hadoop.hive.metastore.api.LockRequest)} call.
+ * Once a lock is acquired, {@link #heartbeat(long, long)} must be called
+ * on a regular basis to avoid the lock being timed out by the system.
+ * @param lockid lock id returned by lock().
+ * @return a lock response, which will provide two things,
+ * the id of the lock (to be used in all further calls regarding this lock)
+ * as well as a state of the lock. If the state is ACQUIRED then the user
+ * can proceed. If it is WAITING the user should wait and call
+ * this method again before proceeding. All components of the lock
+ * will have the same state.
+ * @throws NoSuchTxnException if the requested transaction does not exist.
+ * This can result fro the transaction having timed out and been deleted by
+ * the compactor.
+ * @throws TxnAbortedException if the requested transaction has been
+ * aborted. This can result from the transaction timing out.
+ * @throws NoSuchLockException if the requested lockid does not exist.
+ * This can result from the lock timing out and being unlocked by the system.
+ * @throws TException
+ */
+ LockResponse checkLock(long lockid)
+ throws NoSuchTxnException, TxnAbortedException, NoSuchLockException,
+ TException;
+
+ /**
+ * Unlock a set of locks. This can only be called when the locks are not
+ * assocaited with a transaction.
+ * @param lockid lock id returned by
+ * {@link #lock(org.apache.hadoop.hive.metastore.api.LockRequest)}
+ * @throws NoSuchLockException if the requested lockid does not exist.
+ * This can result from the lock timing out and being unlocked by the system.
+ * @throws TxnOpenException if the locks are are associated with a
+ * transaction.
+ * @throws TException
+ */
+ void unlock(long lockid)
+ throws NoSuchLockException, TxnOpenException, TException;
+
+ /**
+ * Show all currently held and waiting locks.
+ * @return List of currently held and waiting locks.
+ * @throws TException
+ */
+ @Deprecated
+ ShowLocksResponse showLocks() throws TException;
+
+ /**
+ * Show all currently held and waiting locks.
+ * @param showLocksRequest SHOW LOCK request
+ * @return List of currently held and waiting locks.
+ * @throws TException
+ */
+ ShowLocksResponse showLocks(ShowLocksRequest showLocksRequest) throws TException;
+
+ /**
+ * Send a heartbeat to indicate that the client holding these locks (if
+ * any) and that opened this transaction (if one exists) is still alive.
+ * The default timeout for transactions and locks is 300 seconds,
+ * though it is configurable. To determine how often to heartbeat you will
+ * need to ask your system administrator how the metastore thrift service
+ * has been configured.
+ * @param txnid the id of the open transaction. If no transaction is open
+ * (it is a DDL or query) then this can be set to 0.
+ * @param lockid the id of the locks obtained. If no locks have been
+ * obtained then this can be set to 0.
+ * @throws NoSuchTxnException if the requested transaction does not exist.
+ * This can result fro the transaction having timed out and been deleted by
+ * the compactor.
+ * @throws TxnAbortedException if the requested transaction has been
+ * aborted. This can result from the transaction timing out.
+ * @throws NoSuchLockException if the requested lockid does not exist.
+ * This can result from the lock timing out and being unlocked by the system.
+ * @throws TException
+ */
+ void heartbeat(long txnid, long lockid)
+ throws NoSuchLockException, NoSuchTxnException, TxnAbortedException,
+ TException;
+
+ /**
+ * Send heartbeats for a range of transactions. This is for the streaming ingest client that
+ * will have many transactions open at once. Everyone else should use
+ * {@link #heartbeat(long, long)}.
+ * @param min minimum transaction id to heartbeat, inclusive
+ * @param max maximum transaction id to heartbeat, inclusive
+ * @return a pair of lists that tell which transactions in the list did not exist (they may
+ * have already been closed) and which were aborted.
+ * @throws TException
+ */
+ HeartbeatTxnRangeResponse heartbeatTxnRange(long min, long max) throws TException;
+
+ /**
+ * Send a request to compact a table or partition. This will not block until the compaction is
+ * complete. It will instead put a request on the queue for that table or partition to be
+ * compacted. No checking is done on the dbname, tableName, or partitionName to make sure they
+ * refer to valid objects. It is assumed this has already been done by the caller.
+ * @param dbname Name of the database the table is in. If null, this will be assumed to be
+ * 'default'.
+ * @param tableName Name of the table to be compacted. This cannot be null. If partitionName
+ * is null, this must be a non-partitioned table.
+ * @param partitionName Name of the partition to be compacted
+ * @param type Whether this is a major or minor compaction.
+ * @throws TException
+ */
+ @Deprecated
+ void compact(String dbname, String tableName, String partitionName, CompactionType type)
+ throws TException;
+ @Deprecated
+ void compact(String dbname, String tableName, String partitionName, CompactionType type,
+ Map<String, String> tblproperties) throws TException;
+ /**
+ * Send a request to compact a table or partition. This will not block until the compaction is
+ * complete. It will instead put a request on the queue for that table or partition to be
+ * compacted. No checking is done on the dbname, tableName, or partitionName to make sure they
+ * refer to valid objects. It is assumed this has already been done by the caller. At most one
+ * Compaction can be scheduled/running for any given resource at a time.
+ * @param dbname Name of the database the table is in. If null, this will be assumed to be
+ * 'default'.
+ * @param tableName Name of the table to be compacted. This cannot be null. If partitionName
+ * is null, this must be a non-partitioned table.
+ * @param partitionName Name of the partition to be compacted
+ * @param type Whether this is a major or minor compaction.
+ * @param tblproperties the list of tblproperties to override for this compact. Can be null.
+ * @return id of newly scheduled compaction or id/state of one which is already scheduled/running
+ * @throws TException
+ */
+ CompactionResponse compact2(String dbname, String tableName, String partitionName, CompactionType type,
+ Map<String, String> tblproperties) throws TException;
+
+ /**
+ * Get a list of all compactions.
+ * @return List of all current compactions. This includes compactions waiting to happen,
+ * in progress, and finished but waiting to clean the existing files.
+ * @throws TException
+ */
+ ShowCompactResponse showCompactions() throws TException;
+
+ /**
+ * @deprecated in Hive 1.3.0/2.1.0 - will be removed in 2 releases
+ */
+ @Deprecated
+ void addDynamicPartitions(long txnId, String dbName, String tableName, List<String> partNames)
+ throws TException;
+ /**
+ * Send a list of partitions to the metastore to indicate which partitions were loaded
+ * dynamically.
+ * @param txnId id of the transaction
+ * @param dbName database name
+ * @param tableName table name
+ * @param partNames partition name, as constructed by Warehouse.makePartName
+ * @throws TException
+ */
+ void addDynamicPartitions(long txnId, String dbName, String tableName, List<String> partNames,
+ DataOperationType operationType)
+ throws TException;
+
+ /**
+ * Performs the commit/rollback to the metadata storage for insert operator from external storage handler.
+ * @param table table name
+ * @param overwrite true if the insert is overwrite
+ *
+ * @throws MetaException
+ */
+ void insertTable(Table table, boolean overwrite) throws MetaException;
+
+ /**
+ * A filter provided by the client that determines if a given notification event should be
+ * returned.
+ */
+ @InterfaceAudience.LimitedPrivate({"HCatalog"})
+ interface NotificationFilter {
+ /**
+ * Whether a notification event should be accepted
+ * @param event
+ * @return if true, event will be added to list, if false it will be ignored
+ */
+ boolean accept(NotificationEvent event);
+ }
+
+ /**
+ * Get the next set of notifications from the database.
+ * @param lastEventId The last event id that was consumed by this reader. The returned
+ * notifications will start at the next eventId available after this eventId.
+ * @param maxEvents Maximum number of events to return. If < 1, then all available events will
+ * be returned.
+ * @param filter User provided filter to remove unwanted events. If null, all events will be
+ * returned.
+ * @return list of notifications, sorted by eventId. It is guaranteed that the events are in
+ * the order that the operations were done on the database.
+ * @throws TException
+ */
+ @InterfaceAudience.LimitedPrivate({"HCatalog"})
+ NotificationEventResponse getNextNotification(long lastEventId, int maxEvents,
+ NotificationFilter filter) throws TException;
+
+ /**
+ * Get the last used notification event id.
+ * @return last used id
+ * @throws TException
+ */
+ @InterfaceAudience.LimitedPrivate({"HCatalog"})
+ CurrentNotificationEventId getCurrentNotificationEventId() throws TException;
+
+ /**
+ * Get the number of events from given eventID for the input database.
+ * @return number of events
+ * @throws TException
+ */
+ @InterfaceAudience.LimitedPrivate({"HCatalog"})
+ NotificationEventsCountResponse getNotificationEventsCount(NotificationEventsCountRequest rqst)
+ throws TException;
+
+ /**
+ * Request that the metastore fire an event. Currently this is only supported for DML
+ * operations, since the metastore knows when DDL operations happen.
+ * @param request
+ * @return response, type depends on type of request
+ * @throws TException
+ */
+
+ @InterfaceAudience.LimitedPrivate({"Apache Hive, HCatalog"})
+ FireEventResponse fireListenerEvent(FireEventRequest request) throws TException;
+
+ class IncompatibleMetastoreException extends MetaException {
+ IncompatibleMetastoreException(String message) {
+ super(message);
+ }
+ }
+
+ /**
+ * get all role-grants for users/roles that have been granted the given role
+ * Note that in the returned list of RolePrincipalGrants, the roleName is
+ * redundant as it would match the role_name argument of this function
+ * @param getPrincRoleReq
+ * @return
+ * @throws MetaException
+ * @throws TException
+ */
+ GetPrincipalsInRoleResponse get_principals_in_role(GetPrincipalsInRoleRequest getPrincRoleReq)
+ throws MetaException, TException;
+
+ /**
+ * get all role-grants for roles that have been granted to given principal
+ * Note that in the returned list of RolePrincipalGrants, the principal information
+ * redundant as it would match the principal information in request
+ * @param getRolePrincReq
+ * @return
+ * @throws MetaException
+ * @throws TException
+ */
+ GetRoleGrantsForPrincipalResponse get_role_grants_for_principal(
+ GetRoleGrantsForPrincipalRequest getRolePrincReq) throws MetaException, TException;
+
+ public AggrStats getAggrColStatsFor(String dbName, String tblName,
+ List<String> colNames, List<String> partName) throws NoSuchObjectException, MetaException, TException;
+
+ boolean setPartitionColumnStatistics(SetPartitionsStatsRequest request) throws NoSuchObjectException, InvalidObjectException, MetaException, TException, InvalidInputException;
+
+ /**
+ * Flush any catalog objects held by the metastore implementation. Note that this does not
+ * flush statistics objects. This should be called at the beginning of each query.
+ */
+ void flushCache();
+
+ /**
+ * Gets file metadata, as cached by metastore, for respective file IDs.
+ * The metadata that is not cached in metastore may be missing.
+ */
+ Iterable<Entry<Long, ByteBuffer>> getFileMetadata(List<Long> fileIds) throws TException;
+
+ Iterable<Entry<Long, MetadataPpdResult>> getFileMetadataBySarg(
+ List<Long> fileIds, ByteBuffer sarg, boolean doGetFooters) throws TException;
+
+ /**
+ * Cleares the file metadata cache for respective file IDs.
+ */
+ void clearFileMetadata(List<Long> fileIds) throws TException;
+
+ /**
+ * Adds file metadata for respective file IDs to metadata cache in metastore.
+ */
+ void putFileMetadata(List<Long> fileIds, List<ByteBuffer> metadata) throws TException;
+
+ boolean isSameConfObj(Configuration c);
+
+ boolean cacheFileMetadata(String dbName, String tableName, String partName,
+ boolean allParts) throws TException;
+
+ List<SQLPrimaryKey> getPrimaryKeys(PrimaryKeysRequest request)
+ throws MetaException, NoSuchObjectException, TException;
+
+ List<SQLForeignKey> getForeignKeys(ForeignKeysRequest request) throws MetaException,
+ NoSuchObjectException, TException;
+
+ List<SQLUniqueConstraint> getUniqueConstraints(UniqueConstraintsRequest request) throws MetaException,
+ NoSuchObjectException, TException;
+
+ List<SQLNotNullConstraint> getNotNullConstraints(NotNullConstraintsRequest request) throws MetaException,
+ NoSuchObjectException, TException;
+
+ void createTableWithConstraints(
+ org.apache.hadoop.hive.metastore.api.Table tTbl,
+ List<SQLPrimaryKey> primaryKeys, List<SQLForeignKey> foreignKeys,
+ List<SQLUniqueConstraint> uniqueConstraints,
+ List<SQLNotNullConstraint> notNullConstraints)
+ throws AlreadyExistsException, InvalidObjectException, MetaException, NoSuchObjectException, TException;
+
+ void dropConstraint(String dbName, String tableName, String constraintName) throws
+ MetaException, NoSuchObjectException, TException;
+
+ void addPrimaryKey(List<SQLPrimaryKey> primaryKeyCols) throws
+ MetaException, NoSuchObjectException, TException;
+
+ void addForeignKey(List<SQLForeignKey> foreignKeyCols) throws
+ MetaException, NoSuchObjectException, TException;
+
+ void addUniqueConstraint(List<SQLUniqueConstraint> uniqueConstraintCols) throws
+ MetaException, NoSuchObjectException, TException;
+
+ void addNotNullConstraint(List<SQLNotNullConstraint> notNullConstraintCols) throws
+ MetaException, NoSuchObjectException, TException;
+
+ /**
+ * Gets the unique id of the backing database instance used for storing metadata
+ * @return unique id of the backing database instance
+ * @throws MetaException if HMS is not able to fetch the UUID or if there are multiple UUIDs found in the database
+ * @throws TException in case of Thrift errors
+ */
+ String getMetastoreDbUuid() throws MetaException, TException;
+
+ void createResourcePlan(WMResourcePlan resourcePlan)
+ throws InvalidObjectException, MetaException, TException;
+
+ WMResourcePlan getResourcePlan(String resourcePlanName)
+ throws NoSuchObjectException, MetaException, TException;
+
+ List<WMResourcePlan> getAllResourcePlans()
+ throws NoSuchObjectException, MetaException, TException;
+
+ void dropResourcePlan(String resourcePlanName)
+ throws NoSuchObjectException, MetaException, TException;
+
+ void alterResourcePlan(String resourcePlanName, WMResourcePlan resourcePlan)
+ throws NoSuchObjectException, InvalidObjectException, MetaException, TException;
+
+ boolean validateResourcePlan(String resourcePlanName)
+ throws NoSuchObjectException, InvalidObjectException, MetaException, TException;
+
+ void createWMTrigger(WMTrigger trigger)
+ throws InvalidObjectException, MetaException, TException;
+
+ void alterWMTrigger(WMTrigger trigger)
+ throws NoSuchObjectException, InvalidObjectException, MetaException, TException;
+
+ void dropWMTrigger(String resourcePlanName, String triggerName)
+ throws NoSuchObjectException, MetaException, TException;
+
+ List<WMTrigger> getTriggersForResourcePlan(String resourcePlan)
+ throws NoSuchObjectException, MetaException, TException;
+}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/RawStoreProxy.java
----------------------------------------------------------------------
diff --git a/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/RawStoreProxy.java b/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/RawStoreProxy.java
index 2fd2268..0add003 100644
--- a/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/RawStoreProxy.java
+++ b/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/RawStoreProxy.java
@@ -84,7 +84,7 @@ public class RawStoreProxy implements InvocationHandler {
private void init() throws MetaException {
// Using the hook on startup ensures that the hook always has priority
// over settings in *.xml. The thread local conf needs to be used because at this point
- // it has already been initialized using hiveConf.
+ // it has already been initialized using conf.
MetaStoreInit.updateConnectionURL(hiveConf, getConf(), null, metaStoreInitData);
}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/RetryingMetaStoreClient.java
----------------------------------------------------------------------
diff --git a/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/RetryingMetaStoreClient.java b/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/RetryingMetaStoreClient.java
new file mode 100644
index 0000000..b170a63
--- /dev/null
+++ b/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/RetryingMetaStoreClient.java
@@ -0,0 +1,287 @@
+/*
+ * 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 java.io.IOException;
+import java.lang.annotation.Annotation;
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
+import java.lang.reflect.UndeclaredThrowableException;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.hadoop.classification.InterfaceAudience;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hive.common.classification.RetrySemantics;
+import org.apache.hadoop.hive.metastore.conf.MetastoreConf;
+import org.apache.hadoop.hive.metastore.conf.MetastoreConf.ConfVars;
+import org.apache.hadoop.hive.metastore.utils.JavaUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.apache.hadoop.hive.metastore.annotation.NoReconnect;
+import org.apache.hadoop.hive.metastore.api.MetaException;
+import org.apache.hadoop.security.UserGroupInformation;
+import org.apache.thrift.TApplicationException;
+import org.apache.thrift.TException;
+import org.apache.thrift.protocol.TProtocolException;
+import org.apache.thrift.transport.TTransportException;
+
+import com.google.common.annotations.VisibleForTesting;
+
+/**
+ * RetryingMetaStoreClient. Creates a proxy for a IMetaStoreClient
+ * implementation and retries calls to it on failure.
+ * If the login user is authenticated using keytab, it relogins user before
+ * each call.
+ *
+ */
+@InterfaceAudience.Public
+public class RetryingMetaStoreClient implements InvocationHandler {
+
+ private static final Logger LOG = LoggerFactory.getLogger(RetryingMetaStoreClient.class.getName());
+
+ private final IMetaStoreClient base;
+ private final int retryLimit;
+ private final long retryDelaySeconds;
+ private final ConcurrentHashMap<String, Long> metaCallTimeMap;
+ private final long connectionLifeTimeInMillis;
+ private long lastConnectionTime;
+ private boolean localMetaStore;
+
+
+ protected RetryingMetaStoreClient(Configuration conf, Class<?>[] constructorArgTypes,
+ Object[] constructorArgs, ConcurrentHashMap<String, Long> metaCallTimeMap,
+ Class<? extends IMetaStoreClient> msClientClass) throws MetaException {
+
+ this.retryLimit = MetastoreConf.getIntVar(conf, ConfVars.THRIFT_FAILURE_RETRIES);
+ this.retryDelaySeconds = MetastoreConf.getTimeVar(conf,
+ ConfVars.CLIENT_CONNECT_RETRY_DELAY, TimeUnit.SECONDS);
+ this.metaCallTimeMap = metaCallTimeMap;
+ this.connectionLifeTimeInMillis = MetastoreConf.getTimeVar(conf,
+ ConfVars.CLIENT_SOCKET_LIFETIME, TimeUnit.MILLISECONDS);
+ this.lastConnectionTime = System.currentTimeMillis();
+ String msUri = MetastoreConf.getVar(conf, ConfVars.THRIFT_URIS);
+ localMetaStore = (msUri == null) || msUri.trim().isEmpty();
+
+ reloginExpiringKeytabUser();
+ this.base = JavaUtils.newInstance(msClientClass, constructorArgTypes, constructorArgs);
+ }
+
+ public static IMetaStoreClient getProxy(
+ Configuration hiveConf, boolean allowEmbedded) throws MetaException {
+ return getProxy(hiveConf, new Class[]{Configuration.class, HiveMetaHookLoader.class, Boolean.class},
+ new Object[]{hiveConf, null, allowEmbedded}, null, HiveMetaStoreClient.class.getName()
+ );
+ }
+
+ @VisibleForTesting
+ public static IMetaStoreClient getProxy(Configuration hiveConf, HiveMetaHookLoader hookLoader,
+ String mscClassName) throws MetaException {
+ return getProxy(hiveConf, hookLoader, null, mscClassName, true);
+ }
+
+ public static IMetaStoreClient getProxy(Configuration hiveConf, HiveMetaHookLoader hookLoader,
+ ConcurrentHashMap<String, Long> metaCallTimeMap, String mscClassName, boolean allowEmbedded)
+ throws MetaException {
+
+ return getProxy(hiveConf,
+ new Class[] {Configuration.class, HiveMetaHookLoader.class, Boolean.class},
+ new Object[] {hiveConf, hookLoader, allowEmbedded},
+ metaCallTimeMap,
+ mscClassName
+ );
+ }
+
+ /**
+ * This constructor is meant for Hive internal use only.
+ * Please use getProxy(HiveConf conf, HiveMetaHookLoader hookLoader) for external purpose.
+ */
+ public static IMetaStoreClient getProxy(Configuration hiveConf, Class<?>[] constructorArgTypes,
+ Object[] constructorArgs, String mscClassName) throws MetaException {
+ return getProxy(hiveConf, constructorArgTypes, constructorArgs, null, mscClassName);
+ }
+
+ /**
+ * This constructor is meant for Hive internal use only.
+ * Please use getProxy(HiveConf conf, HiveMetaHookLoader hookLoader) for external purpose.
+ */
+ public static IMetaStoreClient getProxy(Configuration hiveConf, Class<?>[] constructorArgTypes,
+ Object[] constructorArgs, ConcurrentHashMap<String, Long> metaCallTimeMap,
+ String mscClassName) throws MetaException {
+
+ @SuppressWarnings("unchecked")
+ Class<? extends IMetaStoreClient> baseClass =
+ JavaUtils.getClass(mscClassName, IMetaStoreClient.class);
+
+ RetryingMetaStoreClient handler =
+ new RetryingMetaStoreClient(hiveConf, constructorArgTypes, constructorArgs,
+ metaCallTimeMap, baseClass);
+ return (IMetaStoreClient) Proxy.newProxyInstance(
+ RetryingMetaStoreClient.class.getClassLoader(), baseClass.getInterfaces(), handler);
+ }
+
+ @Override
+ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
+ Object ret;
+ int retriesMade = 0;
+ TException caughtException;
+
+ boolean allowReconnect = ! method.isAnnotationPresent(NoReconnect.class);
+ boolean allowRetry = true;
+ Annotation[] directives = method.getDeclaredAnnotations();
+ if(directives != null) {
+ for(Annotation a : directives) {
+ if(a instanceof RetrySemantics.CannotRetry) {
+ allowRetry = false;
+ }
+ }
+ }
+
+ while (true) {
+ try {
+ reloginExpiringKeytabUser();
+
+ if (allowReconnect) {
+ if (retriesMade > 0 || hasConnectionLifeTimeReached(method)) {
+ base.reconnect();
+ lastConnectionTime = System.currentTimeMillis();
+ }
+ }
+
+ if (metaCallTimeMap == null) {
+ ret = method.invoke(base, args);
+ } else {
+ // need to capture the timing
+ long startTime = System.currentTimeMillis();
+ ret = method.invoke(base, args);
+ long timeTaken = System.currentTimeMillis() - startTime;
+ addMethodTime(method, timeTaken);
+ }
+ break;
+ } catch (UndeclaredThrowableException e) {
+ throw e.getCause();
+ } catch (InvocationTargetException e) {
+ Throwable t = e.getCause();
+ if (t instanceof TApplicationException) {
+ TApplicationException tae = (TApplicationException)t;
+ switch (tae.getType()) {
+ case TApplicationException.UNSUPPORTED_CLIENT_TYPE:
+ case TApplicationException.UNKNOWN_METHOD:
+ case TApplicationException.WRONG_METHOD_NAME:
+ case TApplicationException.INVALID_PROTOCOL:
+ throw t;
+ default:
+ // TODO: most other options are probably unrecoverable... throw?
+ caughtException = tae;
+ }
+ } else if ((t instanceof TProtocolException) || (t instanceof TTransportException)) {
+ // TODO: most protocol exceptions are probably unrecoverable... throw?
+ caughtException = (TException)t;
+ } else if ((t instanceof MetaException) && t.getMessage().matches(
+ "(?s).*(JDO[a-zA-Z]*|TProtocol|TTransport)Exception.*") &&
+ !t.getMessage().contains("java.sql.SQLIntegrityConstraintViolationException")) {
+ caughtException = (MetaException)t;
+ } else {
+ throw t;
+ }
+ } catch (MetaException e) {
+ if (e.getMessage().matches("(?s).*(IO|TTransport)Exception.*") &&
+ !e.getMessage().contains("java.sql.SQLIntegrityConstraintViolationException")) {
+ caughtException = e;
+ } else {
+ throw e;
+ }
+ }
+
+
+ if (retriesMade >= retryLimit || base.isLocalMetaStore() || !allowRetry) {
+ throw caughtException;
+ }
+ retriesMade++;
+ LOG.warn("MetaStoreClient lost connection. Attempting to reconnect (" + retriesMade + " of " +
+ retryLimit + ") after " + retryDelaySeconds + "s. " + method.getName(), caughtException);
+ Thread.sleep(retryDelaySeconds * 1000);
+ }
+ return ret;
+ }
+
+ private void addMethodTime(Method method, long timeTaken) {
+ String methodStr = getMethodString(method);
+ while (true) {
+ Long curTime = metaCallTimeMap.get(methodStr), newTime = timeTaken;
+ if (curTime != null && metaCallTimeMap.replace(methodStr, curTime, newTime + curTime)) break;
+ if (curTime == null && (null == metaCallTimeMap.putIfAbsent(methodStr, newTime))) break;
+ }
+ }
+
+ /**
+ * @param method
+ * @return String representation with arg types. eg getDatabase_(String, )
+ */
+ private String getMethodString(Method method) {
+ StringBuilder methodSb = new StringBuilder(method.getName());
+ methodSb.append("_(");
+ for (Class<?> paramClass : method.getParameterTypes()) {
+ methodSb.append(paramClass.getSimpleName());
+ methodSb.append(", ");
+ }
+ methodSb.append(")");
+ return methodSb.toString();
+ }
+
+ private boolean hasConnectionLifeTimeReached(Method method) {
+ if (connectionLifeTimeInMillis <= 0 || localMetaStore) {
+ return false;
+ }
+
+ boolean shouldReconnect =
+ (System.currentTimeMillis() - lastConnectionTime) >= connectionLifeTimeInMillis;
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Reconnection status for Method: " + method.getName() + " is " + shouldReconnect);
+ }
+ return shouldReconnect;
+ }
+
+ /**
+ * Relogin if login user is logged in using keytab
+ * Relogin is actually done by ugi code only if sufficient time has passed
+ * A no-op if kerberos security is not enabled
+ * @throws MetaException
+ */
+ private void reloginExpiringKeytabUser() throws MetaException {
+ if(!UserGroupInformation.isSecurityEnabled()){
+ return;
+ }
+ try {
+ UserGroupInformation ugi = UserGroupInformation.getLoginUser();
+ //checkTGT calls ugi.relogin only after checking if it is close to tgt expiry
+ //hadoop relogin is actually done only every x minutes (x=10 in hadoop 1.x)
+ if(ugi.isFromKeytab()){
+ ugi.checkTGTAndReloginFromKeytab();
+ }
+ } catch (IOException e) {
+ String msg = "Error doing relogin using keytab " + e.getMessage();
+ LOG.error(msg, e);
+ throw new MetaException(msg);
+ }
+ }
+
+}
[07/12] hive git commit: HIVE-17980 Moved HiveMetaStoreClient plus a
few remaining classes.
Posted by ga...@apache.org.
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/metastore/src/test/org/apache/hadoop/hive/metastore/TestHiveMetaStoreGetMetaConf.java
----------------------------------------------------------------------
diff --git a/metastore/src/test/org/apache/hadoop/hive/metastore/TestHiveMetaStoreGetMetaConf.java b/metastore/src/test/org/apache/hadoop/hive/metastore/TestHiveMetaStoreGetMetaConf.java
deleted file mode 100644
index f71911e..0000000
--- a/metastore/src/test/org/apache/hadoop/hive/metastore/TestHiveMetaStoreGetMetaConf.java
+++ /dev/null
@@ -1,138 +0,0 @@
-/**
- * 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 java.security.Permission;
-import org.apache.hadoop.hive.conf.HiveConf;
-import org.apache.hadoop.hive.metastore.api.MetaException;
-import org.apache.thrift.TException;
-import org.junit.After;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.junit.Rule;
-import org.junit.rules.ExpectedException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import static org.junit.Assert.*;
-import org.junit.Before;
-
-public class TestHiveMetaStoreGetMetaConf {
-
- @Rule
- public ExpectedException thrown = ExpectedException.none();
-
- private static final Logger LOG = LoggerFactory.getLogger(TestHiveMetaStoreGetMetaConf.class);
- private static HiveConf hiveConf;
- private static SecurityManager securityManager;
-
- private HiveMetaStoreClient hmsc;
-
- public static class NoExitSecurityManager extends SecurityManager {
-
- @Override
- public void checkPermission(Permission perm) {
- // allow anything.
- }
-
- @Override
- public void checkPermission(Permission perm, Object context) {
- // allow anything.
- }
-
- @Override
- public void checkExit(int status) {
- super.checkExit(status);
- throw new RuntimeException("System.exit() was called. Raising exception.");
- }
- }
-
- @AfterClass
- public static void tearDown() throws Exception {
- LOG.info("Shutting down metastore.");
- System.setSecurityManager(securityManager);
- }
-
- @BeforeClass
- public static void startMetaStoreServer() throws Exception {
-
- securityManager = System.getSecurityManager();
- System.setSecurityManager(new NoExitSecurityManager());
- HiveConf metastoreConf = new HiveConf();
- metastoreConf.setClass(HiveConf.ConfVars.METASTORE_EXPRESSION_PROXY_CLASS.varname,
- MockPartitionExpressionForMetastore.class, PartitionExpressionProxy.class);
- metastoreConf.setBoolVar(HiveConf.ConfVars.METASTORE_TRY_DIRECT_SQL_DDL, false);
- int msPort = MetaStoreTestUtils.startMetaStore(metastoreConf);
- hiveConf = new HiveConf(TestHiveMetaStoreGetMetaConf.class);
- hiveConf.setVar(HiveConf.ConfVars.METASTOREURIS, "thrift://localhost:"
- + msPort);
- hiveConf.setVar(HiveConf.ConfVars.PREEXECHOOKS, "");
- hiveConf.setVar(HiveConf.ConfVars.POSTEXECHOOKS, "");
- hiveConf.setBoolVar(HiveConf.ConfVars.HIVE_SUPPORT_CONCURRENCY, false);
- hiveConf.setIntVar(HiveConf.ConfVars.METASTORETHRIFTCONNECTIONRETRIES, 10);
-
- System.setProperty(HiveConf.ConfVars.PREEXECHOOKS.varname, " ");
- System.setProperty(HiveConf.ConfVars.POSTEXECHOOKS.varname, " ");
- }
-
- @Before
- public void setup() throws MetaException {
- hmsc = new HiveMetaStoreClient(hiveConf);
- }
-
- @After
- public void closeClient() {
- if (hmsc != null) {
- hmsc.close();
- }
- }
-
- @Test
- public void testGetMetaConfDefault() throws MetaException, TException {
- HiveConf.ConfVars metaConfVar = HiveConf.ConfVars.METASTORE_TRY_DIRECT_SQL;
- String expected = metaConfVar.getDefaultValue();
- String actual = hmsc.getMetaConf(metaConfVar.toString());
- assertEquals(expected, actual);
- }
-
- @Test
- public void testGetMetaConfDefaultEmptyString() throws MetaException, TException {
- HiveConf.ConfVars metaConfVar = HiveConf.ConfVars.METASTORE_PARTITION_NAME_WHITELIST_PATTERN;
- String expected = "";
- String actual = hmsc.getMetaConf(metaConfVar.toString());
- assertEquals(expected, actual);
- }
-
- @Test
- public void testGetMetaConfOverridden() throws MetaException, TException {
- HiveConf.ConfVars metaConfVar = HiveConf.ConfVars.METASTORE_TRY_DIRECT_SQL_DDL;
- String expected = "false";
- String actual = hmsc.getMetaConf(metaConfVar.toString());
- assertEquals(expected, actual);
- }
-
- @Test
- public void testGetMetaConfUnknownPreperty() throws MetaException, TException {
- String unknownPropertyName = "hive.meta.foo.bar";
- thrown.expect(MetaException.class);
- thrown.expectMessage("Invalid configuration key " + unknownPropertyName);
- hmsc.getMetaConf(unknownPropertyName);
- }
-}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/metastore/src/test/org/apache/hadoop/hive/metastore/TestHiveMetaStorePartitionSpecs.java
----------------------------------------------------------------------
diff --git a/metastore/src/test/org/apache/hadoop/hive/metastore/TestHiveMetaStorePartitionSpecs.java b/metastore/src/test/org/apache/hadoop/hive/metastore/TestHiveMetaStorePartitionSpecs.java
deleted file mode 100644
index 86462ff..0000000
--- a/metastore/src/test/org/apache/hadoop/hive/metastore/TestHiveMetaStorePartitionSpecs.java
+++ /dev/null
@@ -1,409 +0,0 @@
-/**
- * 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 org.apache.hadoop.hive.conf.HiveConf;
-import org.apache.hadoop.hive.metastore.api.Database;
-import org.apache.hadoop.hive.metastore.api.FieldSchema;
-import org.apache.hadoop.hive.metastore.api.Partition;
-import org.apache.hadoop.hive.metastore.api.PartitionSpec;
-import org.apache.hadoop.hive.metastore.api.SerDeInfo;
-import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
-import org.apache.hadoop.hive.metastore.api.Table;
-import org.apache.hadoop.hive.metastore.partition.spec.CompositePartitionSpecProxy;
-import org.apache.hadoop.hive.metastore.partition.spec.PartitionSpecProxy;
-import org.apache.hadoop.hive.serde2.columnar.LazyBinaryColumnarSerDe;
-import org.junit.AfterClass;
-import org.junit.Assert;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.security.Permission;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Test to check PartitionSpec support in HiveMetaStore.
- */
-public class TestHiveMetaStorePartitionSpecs {
-
- private static final Logger LOG = LoggerFactory.getLogger(TestHiveMetaStorePartitionSpecs.class);
- private static int msPort;
- private static HiveConf hiveConf;
- private static SecurityManager securityManager;
-
- public static class NoExitSecurityManager extends SecurityManager {
-
- @Override
- public void checkPermission(Permission perm) {
- // allow anything.
- }
-
- @Override
- public void checkPermission(Permission perm, Object context) {
- // allow anything.
- }
-
- @Override
- public void checkExit(int status) {
-
- super.checkExit(status);
- throw new RuntimeException("System.exit() was called. Raising exception. ");
- }
- }
-
-
- @AfterClass
- public static void tearDown() throws Exception {
- LOG.info("Shutting down metastore.");
- System.setSecurityManager(securityManager);
-
- HiveMetaStoreClient hmsc = new HiveMetaStoreClient(hiveConf);
- hmsc.dropDatabase(dbName, true, true, true);
- }
-
- @BeforeClass
- public static void startMetaStoreServer() throws Exception {
-
- HiveConf metastoreConf = new HiveConf();
- metastoreConf.setClass(HiveConf.ConfVars.METASTORE_EXPRESSION_PROXY_CLASS.varname,
- MockPartitionExpressionForMetastore.class, PartitionExpressionProxy.class);
- msPort = MetaStoreTestUtils.startMetaStore(metastoreConf);
- securityManager = System.getSecurityManager();
- System.setSecurityManager(new NoExitSecurityManager());
- hiveConf = new HiveConf(TestHiveMetaStorePartitionSpecs.class);
- hiveConf.setVar(HiveConf.ConfVars.METASTOREURIS, "thrift://localhost:"
- + msPort);
- hiveConf.setIntVar(HiveConf.ConfVars.METASTORETHRIFTCONNECTIONRETRIES, 3);
- hiveConf.set(HiveConf.ConfVars.PREEXECHOOKS.varname, "");
- hiveConf.set(HiveConf.ConfVars.POSTEXECHOOKS.varname, "");
- hiveConf.set(HiveConf.ConfVars.HIVE_SUPPORT_CONCURRENCY.varname,
- "false");
- hiveConf.set(HiveConf.ConfVars.METASTORE_EXPRESSION_PROXY_CLASS.name(), MockPartitionExpressionForMetastore.class.getCanonicalName());
- System.setProperty(HiveConf.ConfVars.PREEXECHOOKS.varname, " ");
- System.setProperty(HiveConf.ConfVars.POSTEXECHOOKS.varname, " ");
- }
-
- private static String dbName = "testpartitionspecs_db";
- private static String tableName = "testpartitionspecs_table";
- private static int nDates = 10;
- private static String datePrefix = "2014010";
-
- private static void createTable(HiveMetaStoreClient hmsc, boolean enablePartitionGrouping) throws Exception {
-
-
- List<FieldSchema> columns = new ArrayList<FieldSchema>();
- columns.add(new FieldSchema("foo", "string", ""));
- columns.add(new FieldSchema("bar", "string", ""));
-
- List<FieldSchema> partColumns = new ArrayList<FieldSchema>();
- partColumns.add(new FieldSchema("dt", "string", ""));
- partColumns.add(new FieldSchema("blurb", "string", ""));
-
- SerDeInfo serdeInfo = new SerDeInfo("LBCSerDe", LazyBinaryColumnarSerDe.class.getCanonicalName(), new HashMap<String, String>());
-
- StorageDescriptor storageDescriptor
- = new StorageDescriptor(columns, null,
- "org.apache.hadoop.hive.ql.io.RCFileInputFormat",
- "org.apache.hadoop.hive.ql.io.RCFileOutputFormat",
- false, 0, serdeInfo, null, null, null);
-
- Map<String, String> tableParameters = new HashMap<String, String>();
- tableParameters.put("hive.hcatalog.partition.spec.grouping.enabled", enablePartitionGrouping? "true":"false");
- Table table = new Table(tableName, dbName, "", 0, 0, 0, storageDescriptor, partColumns, tableParameters, "", "", "");
-
- hmsc.createTable(table);
- Assert.assertTrue("Table " + dbName + "." + tableName + " does not exist",
- hmsc.tableExists(dbName, tableName));
-
- }
-
- private static void clearAndRecreateDB(HiveMetaStoreClient hmsc) throws Exception {
- hmsc.dropDatabase(dbName,
- true, // Delete data.
- true, // Ignore unknownDB.
- true // Cascade.
- );
-
- hmsc.createDatabase(new Database(dbName,
- "", // Description.
- null, // Location.
- null // Parameters.
- ));
- }
-
- // Get partition-path. For grid='XYZ', place the partition outside the table-path.
- private static String getPartitionPath(Table table, List<String> partValues) {
-
- return partValues.get(1).equalsIgnoreCase("isLocatedOutsideTablePath")? // i.e. Is the partition outside the table-dir?
- table.getSd().getLocation().replace(table.getTableName(), "location_outside_" + table.getTableName())
- + "_" + partValues.get(0) + "_" + partValues.get(1)
- : null ; // Use defaults... Partitions are put in the table directory.
-
- }
-
- private static void populatePartitions(HiveMetaStoreClient hmsc, Table table, List<String> blurbs) throws Exception {
- for (int i=0; i< nDates; ++i) {
- for (String blurb : blurbs) {
- StorageDescriptor sd = new StorageDescriptor(table.getSd());
- // Add partitions located in the table-directory (i.e. default).
- List<String> values = Arrays.asList(datePrefix + i, blurb);
- sd.setLocation(getPartitionPath(table, values));
- hmsc.add_partition(new Partition(values, dbName, tableName, 0, 0, sd, null));
- }
- }
- }
-
- private void testGetPartitionSpecs(boolean enablePartitionGrouping) {
- try {
- HiveMetaStoreClient hmsc = new HiveMetaStoreClient(hiveConf);
- clearAndRecreateDB(hmsc);
- createTable(hmsc, enablePartitionGrouping);
- Table table = hmsc.getTable(dbName, tableName);
- populatePartitions(hmsc, table, Arrays.asList("isLocatedInTablePath", "isLocatedOutsideTablePath"));
-
- PartitionSpecProxy partitionSpecProxy = hmsc.listPartitionSpecs(dbName, tableName, -1);
- Assert.assertEquals( "Unexpected number of partitions.", nDates * 2, partitionSpecProxy.size());
-
- Map<String, List<String>> locationToDateMap = new HashMap<String, List<String>>();
- locationToDateMap.put("isLocatedInTablePath", new ArrayList<String>());
- locationToDateMap.put("isLocatedOutsideTablePath", new ArrayList<String>());
- PartitionSpecProxy.PartitionIterator iterator = partitionSpecProxy.getPartitionIterator();
-
- while (iterator.hasNext()) {
- Partition partition = iterator.next();
- locationToDateMap.get(partition.getValues().get(1)).add(partition.getValues().get(0));
- }
-
- List<String> expectedDates = new ArrayList<String>(nDates);
- for (int i=0; i<nDates; ++i) {
- expectedDates.add(datePrefix + i);
- }
-
- Assert.assertArrayEquals("Unexpected date-values.", expectedDates.toArray(), locationToDateMap.get("isLocatedInTablePath").toArray());
- Assert.assertArrayEquals("Unexpected date-values.", expectedDates.toArray(), locationToDateMap.get("isLocatedOutsideTablePath").toArray());
-
- partitionSpecProxy = hmsc.listPartitionSpecsByFilter(dbName, tableName, "blurb = \"isLocatedOutsideTablePath\"", -1);
- locationToDateMap.get("isLocatedInTablePath").clear();
- locationToDateMap.get("isLocatedOutsideTablePath").clear();
- iterator = partitionSpecProxy.getPartitionIterator();
-
- while (iterator.hasNext()) {
- Partition partition = iterator.next();
- locationToDateMap.get(partition.getValues().get(1)).add(partition.getValues().get(0));
- }
-
- Assert.assertEquals("Unexpected date-values.", 0, locationToDateMap.get("isLocatedInTablePath").size());
- Assert.assertArrayEquals("Unexpected date-values.", expectedDates.toArray(), locationToDateMap.get("isLocatedOutsideTablePath").toArray());
-
-
- }
- catch (Throwable t) {
- LOG.error("Unexpected Exception!", t);
- t.printStackTrace();
- Assert.assertTrue("Unexpected Exception!", false);
- }
- }
-
- /**
- * Test for HiveMetaStoreClient.listPartitionSpecs() and HiveMetaStoreClient.listPartitionSpecsByFilter().
- * Check behaviour with and without Partition-grouping enabled.
- */
- @Test
- public void testGetPartitionSpecs_WithAndWithoutPartitionGrouping() {
- testGetPartitionSpecs(true);
- testGetPartitionSpecs(false);
- }
-
-
- /**
- * Test to confirm that partitions can be added using PartitionSpecs.
- */
- @Test
- public void testAddPartitions() {
- try {
- // Create source table.
- HiveMetaStoreClient hmsc = new HiveMetaStoreClient(hiveConf);
- clearAndRecreateDB(hmsc);
- createTable(hmsc, true);
- Table table = hmsc.getTable(dbName, tableName);
- populatePartitions(hmsc, table, Arrays.asList("isLocatedInTablePath", "isLocatedOutsideTablePath"));
-
- // Clone the table,
- String targetTableName = "cloned_" + tableName;
- Table targetTable = new Table(table);
- targetTable.setTableName(targetTableName);
- StorageDescriptor targetTableSd = new StorageDescriptor(targetTable.getSd());
- targetTableSd.setLocation(
- targetTableSd.getLocation().replace( tableName, targetTableName));
- hmsc.createTable(targetTable);
-
- // Get partition-list from source.
- PartitionSpecProxy partitionsForAddition
- = hmsc.listPartitionSpecsByFilter(dbName, tableName, "blurb = \"isLocatedInTablePath\"", -1);
- partitionsForAddition.setTableName(targetTableName);
- partitionsForAddition.setRootLocation(targetTableSd.getLocation());
-
- Assert.assertEquals("Unexpected number of partitions added. ",
- partitionsForAddition.size(), hmsc.add_partitions_pspec(partitionsForAddition));
-
- // Check that the added partitions are as expected.
- PartitionSpecProxy clonedPartitions = hmsc.listPartitionSpecs(dbName, targetTableName, -1);
- Assert.assertEquals("Unexpected number of partitions returned. ",
- partitionsForAddition.size(), clonedPartitions.size());
-
- PartitionSpecProxy.PartitionIterator sourceIterator = partitionsForAddition.getPartitionIterator(),
- targetIterator = clonedPartitions.getPartitionIterator();
-
- while (targetIterator.hasNext()) {
- Partition sourcePartition = sourceIterator.next(),
- targetPartition = targetIterator.next();
- Assert.assertEquals("Mismatched values.",
- sourcePartition.getValues(), targetPartition.getValues());
- Assert.assertEquals("Mismatched locations.",
- sourcePartition.getSd().getLocation(), targetPartition.getSd().getLocation());
- }
- }
- catch (Throwable t) {
- LOG.error("Unexpected Exception!", t);
- t.printStackTrace();
- Assert.assertTrue("Unexpected Exception!", false);
- }
- }
-
- /**
- * Test to confirm that Partition-grouping behaves correctly when Table-schemas evolve.
- * Partitions must be grouped by location and schema.
- */
- @Test
- public void testFetchingPartitionsWithDifferentSchemas() {
- try {
- // Create source table.
- HiveMetaStoreClient hmsc = new HiveMetaStoreClient(hiveConf);
- clearAndRecreateDB(hmsc);
- createTable(hmsc, true);
- Table table = hmsc.getTable(dbName, tableName);
- populatePartitions(hmsc,
- table,
- Arrays.asList("isLocatedInTablePath", "isLocatedOutsideTablePath") // Blurb list.
- );
-
- // Modify table schema. Add columns.
- List<FieldSchema> fields = table.getSd().getCols();
- fields.add(new FieldSchema("goo", "string", "Entirely new column. Doesn't apply to older partitions."));
- table.getSd().setCols(fields);
- hmsc.alter_table(dbName, tableName, table);
- // Check that the change stuck.
- table = hmsc.getTable(dbName,tableName);
- Assert.assertEquals("Unexpected number of table columns.",
- 3, table.getSd().getColsSize());
-
- // Add partitions with new schema.
- // Mark Partitions with new schema with different blurb.
- populatePartitions(hmsc, table, Arrays.asList("hasNewColumn"));
-
- // Retrieve *all* partitions from the table.
- PartitionSpecProxy partitionSpecProxy = hmsc.listPartitionSpecs(dbName, tableName, -1);
- Assert.assertEquals("Unexpected number of partitions.", nDates * 3, partitionSpecProxy.size());
-
- // Confirm grouping.
- Assert.assertTrue("Unexpected type of PartitionSpecProxy.", partitionSpecProxy instanceof CompositePartitionSpecProxy);
- CompositePartitionSpecProxy compositePartitionSpecProxy = (CompositePartitionSpecProxy)partitionSpecProxy;
- List<PartitionSpec> partitionSpecs = compositePartitionSpecProxy.toPartitionSpec();
- Assert.assertTrue("PartitionSpec[0] should have been a SharedSDPartitionSpec.",
- partitionSpecs.get(0).isSetSharedSDPartitionSpec());
- Assert.assertEquals("PartitionSpec[0] should use the table-path as the common root location. ",
- table.getSd().getLocation(), partitionSpecs.get(0).getRootPath());
- Assert.assertTrue("PartitionSpec[1] should have been a SharedSDPartitionSpec.",
- partitionSpecs.get(1).isSetSharedSDPartitionSpec());
- Assert.assertEquals("PartitionSpec[1] should use the table-path as the common root location. ",
- table.getSd().getLocation(), partitionSpecs.get(1).getRootPath());
- Assert.assertTrue("PartitionSpec[2] should have been a ListComposingPartitionSpec.",
- partitionSpecs.get(2).isSetPartitionList());
-
- // Categorize the partitions returned, and confirm that all partitions are accounted for.
- PartitionSpecProxy.PartitionIterator iterator = partitionSpecProxy.getPartitionIterator();
- Map<String, List<Partition>> blurbToPartitionList = new HashMap<String, List<Partition>>(3);
- while (iterator.hasNext()) {
-
- Partition partition = iterator.next();
- String blurb = partition.getValues().get(1);
-
- if (!blurbToPartitionList.containsKey(blurb)) {
- blurbToPartitionList.put(blurb, new ArrayList<Partition>(nDates));
- }
-
- blurbToPartitionList.get(blurb).add(partition);
-
- } // </Classification>
-
- // All partitions with blurb="isLocatedOutsideTablePath" should have 2 columns,
- // and must have locations outside the table directory.
- for (Partition partition : blurbToPartitionList.get("isLocatedOutsideTablePath")) {
- Assert.assertEquals("Unexpected number of columns.", 2, partition.getSd().getCols().size());
- Assert.assertEquals("Unexpected first column.", "foo", partition.getSd().getCols().get(0).getName());
- Assert.assertEquals("Unexpected second column.", "bar", partition.getSd().getCols().get(1).getName());
- String partitionLocation = partition.getSd().getLocation();
- String tableLocation = table.getSd().getLocation();
- Assert.assertTrue("Unexpected partition location: " + partitionLocation + ". " +
- "Partition should have been outside table location: " + tableLocation,
- !partitionLocation.startsWith(tableLocation));
- }
-
- // All partitions with blurb="isLocatedInTablePath" should have 2 columns,
- // and must have locations within the table directory.
- for (Partition partition : blurbToPartitionList.get("isLocatedInTablePath")) {
- Assert.assertEquals("Unexpected number of columns.", 2, partition.getSd().getCols().size());
- Assert.assertEquals("Unexpected first column.", "foo", partition.getSd().getCols().get(0).getName());
- Assert.assertEquals("Unexpected second column.", "bar", partition.getSd().getCols().get(1).getName());
- String partitionLocation = partition.getSd().getLocation();
- String tableLocation = table.getSd().getLocation();
- Assert.assertTrue("Unexpected partition location: " + partitionLocation + ". " +
- "Partition should have been within table location: " + tableLocation,
- partitionLocation.startsWith(tableLocation));
- }
-
- // All partitions with blurb="hasNewColumn" were added after the table schema changed,
- // and must have 3 columns. Also, the partition locations must lie within the table directory.
- for (Partition partition : blurbToPartitionList.get("hasNewColumn")) {
- Assert.assertEquals("Unexpected number of columns.", 3, partition.getSd().getCols().size());
- Assert.assertEquals("Unexpected first column.", "foo", partition.getSd().getCols().get(0).getName());
- Assert.assertEquals("Unexpected second column.", "bar", partition.getSd().getCols().get(1).getName());
- Assert.assertEquals("Unexpected third column.", "goo", partition.getSd().getCols().get(2).getName());
- String partitionLocation = partition.getSd().getLocation();
- String tableLocation = table.getSd().getLocation();
- Assert.assertTrue("Unexpected partition location: " + partitionLocation + ". " +
- "Partition should have been within table location: " + tableLocation,
- partitionLocation.startsWith(tableLocation));
- }
-
- }
- catch (Throwable t) {
- LOG.error("Unexpected Exception!", t);
- t.printStackTrace();
- Assert.assertTrue("Unexpected Exception!", false);
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/metastore/src/test/org/apache/hadoop/hive/metastore/TestHiveMetaStoreTimeout.java
----------------------------------------------------------------------
diff --git a/metastore/src/test/org/apache/hadoop/hive/metastore/TestHiveMetaStoreTimeout.java b/metastore/src/test/org/apache/hadoop/hive/metastore/TestHiveMetaStoreTimeout.java
deleted file mode 100644
index 2166c20..0000000
--- a/metastore/src/test/org/apache/hadoop/hive/metastore/TestHiveMetaStoreTimeout.java
+++ /dev/null
@@ -1,142 +0,0 @@
-/**
- * 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 java.util.concurrent.TimeUnit;
-
-import org.apache.hadoop.hive.conf.HiveConf;
-import org.apache.hadoop.hive.metastore.api.Database;
-import org.apache.hadoop.hive.metastore.api.MetaException;
-import org.apache.hadoop.util.StringUtils;
-import org.junit.AfterClass;
-import org.junit.Assert;
-import org.junit.BeforeClass;
-import org.junit.Test;
-
-/**
- * Test long running request timeout functionality in MetaStore Server
- * HiveMetaStore.HMSHandler.create_database() is used to simulate a long running method.
- */
-public class TestHiveMetaStoreTimeout {
- protected static HiveMetaStoreClient client;
- protected static HiveConf hiveConf;
- protected static Warehouse warehouse;
-
- @BeforeClass
- public static void setUp() throws Exception {
- HiveMetaStore.TEST_TIMEOUT_ENABLED = true;
- hiveConf = new HiveConf(TestHiveMetaStoreTimeout.class);
- hiveConf.set(HiveConf.ConfVars.METASTORE_EXPRESSION_PROXY_CLASS.varname,
- MockPartitionExpressionForMetastore.class.getCanonicalName());
- hiveConf.setTimeVar(HiveConf.ConfVars.METASTORE_CLIENT_SOCKET_TIMEOUT, 10 * 1000,
- TimeUnit.MILLISECONDS);
- warehouse = new Warehouse(hiveConf);
- try {
- client = new HiveMetaStoreClient(hiveConf);
- } catch (Throwable e) {
- System.err.println("Unable to open the metastore");
- System.err.println(StringUtils.stringifyException(e));
- throw e;
- }
- }
-
- @AfterClass
- public static void tearDown() throws Exception {
- HiveMetaStore.TEST_TIMEOUT_ENABLED = false;
- try {
- client.close();
- } catch (Throwable e) {
- System.err.println("Unable to close metastore");
- System.err.println(StringUtils.stringifyException(e));
- throw e;
- }
- }
-
- @Test
- public void testNoTimeout() throws Exception {
- HiveMetaStore.TEST_TIMEOUT_VALUE = 5 * 1000;
-
- String dbName = "db";
- client.dropDatabase(dbName, true, true);
-
- Database db = new Database();
- db.setName(dbName);
- try {
- client.createDatabase(db);
- } catch (MetaException e) {
- Assert.fail("should not throw timeout exception: " + e.getMessage());
- }
-
- client.dropDatabase(dbName, true, true);
- }
-
- @Test
- public void testTimeout() throws Exception {
- HiveMetaStore.TEST_TIMEOUT_VALUE = 15 * 1000;
-
- String dbName = "db";
- client.dropDatabase(dbName, true, true);
-
- Database db = new Database();
- db.setName(dbName);
- try {
- client.createDatabase(db);
- Assert.fail("should throw timeout exception.");
- } catch (MetaException e) {
- Assert.assertTrue("unexpected MetaException", e.getMessage().contains("Timeout when " +
- "executing method: create_database"));
- }
-
- // restore
- HiveMetaStore.TEST_TIMEOUT_VALUE = 5 * 1000;
- }
-
- @Test
- public void testResetTimeout() throws Exception {
- HiveMetaStore.TEST_TIMEOUT_VALUE = 5 * 1000;
- String dbName = "db";
-
- // no timeout before reset
- client.dropDatabase(dbName, true, true);
- Database db = new Database();
- db.setName(dbName);
- try {
- client.createDatabase(db);
- } catch (MetaException e) {
- Assert.fail("should not throw timeout exception: " + e.getMessage());
- }
- client.dropDatabase(dbName, true, true);
-
- // reset
- client.setMetaConf(HiveConf.ConfVars.METASTORE_CLIENT_SOCKET_TIMEOUT.varname, "3s");
-
- // timeout after reset
- try {
- client.createDatabase(db);
- Assert.fail("should throw timeout exception.");
- } catch (MetaException e) {
- Assert.assertTrue("unexpected MetaException", e.getMessage().contains("Timeout when " +
- "executing method: create_database"));
- }
-
- // restore
- client.dropDatabase(dbName, true, true);
- client.setMetaConf(HiveConf.ConfVars.METASTORE_CLIENT_SOCKET_TIMEOUT.varname, "10s");
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/metastore/src/test/org/apache/hadoop/hive/metastore/TestOldSchema.java
----------------------------------------------------------------------
diff --git a/metastore/src/test/org/apache/hadoop/hive/metastore/TestOldSchema.java b/metastore/src/test/org/apache/hadoop/hive/metastore/TestOldSchema.java
deleted file mode 100644
index 8409d9b..0000000
--- a/metastore/src/test/org/apache/hadoop/hive/metastore/TestOldSchema.java
+++ /dev/null
@@ -1,220 +0,0 @@
-/**
- * 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 java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-
-import org.apache.hadoop.hive.common.ndv.hll.HyperLogLog;
-import org.apache.hadoop.hive.conf.HiveConf;
-import org.apache.hadoop.hive.metastore.api.AggrStats;
-import org.apache.hadoop.hive.metastore.api.ColumnStatistics;
-import org.apache.hadoop.hive.metastore.api.ColumnStatisticsData;
-import org.apache.hadoop.hive.metastore.api.ColumnStatisticsDesc;
-import org.apache.hadoop.hive.metastore.api.ColumnStatisticsObj;
-import org.apache.hadoop.hive.metastore.api.Database;
-import org.apache.hadoop.hive.metastore.api.FieldSchema;
-import org.apache.hadoop.hive.metastore.api.FileMetadataExprType;
-import org.apache.hadoop.hive.metastore.api.InvalidInputException;
-import org.apache.hadoop.hive.metastore.api.InvalidObjectException;
-import org.apache.hadoop.hive.metastore.api.LongColumnStatsData;
-import org.apache.hadoop.hive.metastore.api.MetaException;
-import org.apache.hadoop.hive.metastore.api.NoSuchObjectException;
-import org.apache.hadoop.hive.metastore.api.Partition;
-import org.apache.hadoop.hive.metastore.api.SerDeInfo;
-import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
-import org.apache.hadoop.hive.metastore.api.Table;
-import org.apache.hadoop.hive.ql.io.sarg.SearchArgument;
-import org.apache.hadoop.hive.serde2.typeinfo.PrimitiveTypeInfo;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class TestOldSchema {
- private ObjectStore store = null;
-
- private static final Logger LOG = LoggerFactory.getLogger(TestOldSchema.class.getName());
-
- public static class MockPartitionExpressionProxy implements PartitionExpressionProxy {
- @Override
- public String convertExprToFilter(byte[] expr) throws MetaException {
- return null;
- }
-
- @Override
- public boolean filterPartitionsByExpr(List<FieldSchema> partColumns, byte[] expr,
- String defaultPartitionName,
- List<String> partitionNames) throws MetaException {
- return false;
- }
-
- @Override
- public FileMetadataExprType getMetadataType(String inputFormat) {
- return null;
- }
-
- @Override
- public SearchArgument createSarg(byte[] expr) {
- return null;
- }
-
- @Override
- public FileFormatProxy getFileFormatProxy(FileMetadataExprType type) {
- return null;
- }
- }
-
- byte bitVectors[][] = new byte[2][];
-
- @Before
- public void setUp() throws Exception {
- HiveConf conf = new HiveConf();
- conf.setVar(HiveConf.ConfVars.METASTORE_EXPRESSION_PROXY_CLASS,
- MockPartitionExpressionProxy.class.getName());
- conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_FETCH_BITVECTOR, false);
-
- store = new ObjectStore();
- store.setConf(conf);
- dropAllStoreObjects(store);
-
- HyperLogLog hll = HyperLogLog.builder().build();
- hll.addLong(1);
- bitVectors[1] = hll.serialize();
- hll = HyperLogLog.builder().build();
- hll.addLong(2);
- hll.addLong(3);
- hll.addLong(3);
- hll.addLong(4);
- bitVectors[0] = hll.serialize();
- }
-
- @After
- public void tearDown() {
- }
-
- /**
- * Tests partition operations
- *
- * @throws Exception
- */
- @Test
- public void testPartitionOps() throws Exception {
- String dbName = "default";
- String tableName = "snp";
- Database db1 = new Database(dbName, "description", "locationurl", null);
- store.createDatabase(db1);
- long now = System.currentTimeMillis();
- List<FieldSchema> cols = new ArrayList<>();
- cols.add(new FieldSchema("col1", "long", "nocomment"));
- SerDeInfo serde = new SerDeInfo("serde", "seriallib", null);
- StorageDescriptor sd = new StorageDescriptor(cols, "file:/tmp", "input", "output", false, 0,
- serde, null, null, Collections.<String, String> emptyMap());
- List<FieldSchema> partCols = new ArrayList<>();
- partCols.add(new FieldSchema("ds", "string", ""));
- Table table = new Table(tableName, dbName, "me", (int) now, (int) now, 0, sd, partCols,
- Collections.<String, String> emptyMap(), null, null, null);
- store.createTable(table);
-
- Deadline.startTimer("getPartition");
- for (int i = 0; i < 10; i++) {
- List<String> partVal = new ArrayList<>();
- partVal.add(String.valueOf(i));
- StorageDescriptor psd = new StorageDescriptor(sd);
- psd.setLocation("file:/tmp/default/hit/ds=" + partVal);
- Partition part = new Partition(partVal, dbName, tableName, (int) now, (int) now, psd,
- Collections.<String, String> emptyMap());
- store.addPartition(part);
- ColumnStatistics cs = new ColumnStatistics();
- ColumnStatisticsDesc desc = new ColumnStatisticsDesc(false, dbName, tableName);
- desc.setLastAnalyzed(now);
- desc.setPartName("ds=" + String.valueOf(i));
- cs.setStatsDesc(desc);
- ColumnStatisticsObj obj = new ColumnStatisticsObj();
- obj.setColName("col1");
- obj.setColType("bigint");
- ColumnStatisticsData data = new ColumnStatisticsData();
- LongColumnStatsData dcsd = new LongColumnStatsData();
- dcsd.setHighValue(1000 + i);
- dcsd.setLowValue(-1000 - i);
- dcsd.setNumNulls(i);
- dcsd.setNumDVs(10 * i + 1);
- dcsd.setBitVectors(bitVectors[0]);
- data.setLongStats(dcsd);
- obj.setStatsData(data);
- cs.addToStatsObj(obj);
- store.updatePartitionColumnStatistics(cs, partVal);
-
- }
-
- Checker statChecker = new Checker() {
- @Override
- public void checkStats(AggrStats aggrStats) throws Exception {
- Assert.assertEquals(10, aggrStats.getPartsFound());
- Assert.assertEquals(1, aggrStats.getColStatsSize());
- ColumnStatisticsObj cso = aggrStats.getColStats().get(0);
- Assert.assertEquals("col1", cso.getColName());
- Assert.assertEquals("bigint", cso.getColType());
- LongColumnStatsData lcsd = cso.getStatsData().getLongStats();
- Assert.assertEquals(1009, lcsd.getHighValue(), 0.01);
- Assert.assertEquals(-1009, lcsd.getLowValue(), 0.01);
- Assert.assertEquals(45, lcsd.getNumNulls());
- Assert.assertEquals(91, lcsd.getNumDVs());
- }
- };
- List<String> partNames = new ArrayList<>();
- for (int i = 0; i < 10; i++) {
- partNames.add("ds=" + i);
- }
- AggrStats aggrStats = store.get_aggr_stats_for(dbName, tableName, partNames,
- Arrays.asList("col1"));
- statChecker.checkStats(aggrStats);
-
- }
-
- private static interface Checker {
- void checkStats(AggrStats aggrStats) throws Exception;
- }
-
- public static void dropAllStoreObjects(RawStore store) throws MetaException,
- InvalidObjectException, InvalidInputException {
- try {
- Deadline.registerIfNot(100000);
- Deadline.startTimer("getPartition");
- List<String> dbs = store.getAllDatabases();
- for (int i = 0; i < dbs.size(); i++) {
- String db = dbs.get(i);
- List<String> tbls = store.getAllTables(db);
- for (String tbl : tbls) {
- List<Partition> parts = store.getPartitions(db, tbl, 100);
- for (Partition part : parts) {
- store.dropPartition(db, tbl, part.getValues());
- }
- store.dropTable(db, tbl);
- }
- store.dropDatabase(db);
- }
- } catch (NoSuchObjectException e) {
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/metastore/src/test/org/apache/hadoop/hive/metastore/VerifyingObjectStore.java
----------------------------------------------------------------------
diff --git a/metastore/src/test/org/apache/hadoop/hive/metastore/VerifyingObjectStore.java b/metastore/src/test/org/apache/hadoop/hive/metastore/VerifyingObjectStore.java
deleted file mode 100644
index a8c7ac3..0000000
--- a/metastore/src/test/org/apache/hadoop/hive/metastore/VerifyingObjectStore.java
+++ /dev/null
@@ -1,217 +0,0 @@
-/**
- * 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.commons.lang.StringUtils.repeat;
-
-import java.lang.reflect.AccessibleObject;
-import java.lang.reflect.Array;
-import java.lang.reflect.Field;
-import java.lang.reflect.Modifier;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.apache.commons.lang.ClassUtils;
-import org.apache.commons.lang.builder.EqualsBuilder;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.hadoop.hive.metastore.api.ColumnStatistics;
-import org.apache.hadoop.hive.metastore.api.MetaException;
-import org.apache.hadoop.hive.metastore.api.NoSuchObjectException;
-import org.apache.hadoop.hive.metastore.api.Partition;
-import org.apache.thrift.TException;
-
-public class VerifyingObjectStore extends ObjectStore {
- private static final Logger LOG = LoggerFactory.getLogger(VerifyingObjectStore.class);
-
- public VerifyingObjectStore() {
- super();
- LOG.warn(getClass().getSimpleName() + " is being used - test run");
- }
-
- @Override
- public List<Partition> getPartitionsByFilter(String dbName, String tblName, String filter,
- short maxParts) throws MetaException, NoSuchObjectException {
- List<Partition> sqlResults = getPartitionsByFilterInternal(
- dbName, tblName, filter, maxParts, true, false);
- List<Partition> ormResults = getPartitionsByFilterInternal(
- dbName, tblName, filter, maxParts, false, true);
- verifyLists(sqlResults, ormResults, Partition.class);
- return sqlResults;
- }
-
- @Override
- public List<Partition> getPartitionsByNames(String dbName, String tblName,
- List<String> partNames) throws MetaException, NoSuchObjectException {
- List<Partition> sqlResults = getPartitionsByNamesInternal(
- dbName, tblName, partNames, true, false);
- List<Partition> ormResults = getPartitionsByNamesInternal(
- dbName, tblName, partNames, false, true);
- verifyLists(sqlResults, ormResults, Partition.class);
- return sqlResults;
- }
-
- @Override
- public boolean getPartitionsByExpr(String dbName, String tblName, byte[] expr,
- String defaultPartitionName, short maxParts, List<Partition> result) throws TException {
- List<Partition> ormParts = new LinkedList<Partition>();
- boolean sqlResult = getPartitionsByExprInternal(
- dbName, tblName, expr, defaultPartitionName, maxParts, result, true, false);
- boolean ormResult = getPartitionsByExprInternal(
- dbName, tblName, expr, defaultPartitionName, maxParts, ormParts, false, true);
- if (sqlResult != ormResult) {
- String msg = "The unknown flag is different - SQL " + sqlResult + ", ORM " + ormResult;
- LOG.error(msg);
- throw new MetaException(msg);
- }
- verifyLists(result, ormParts, Partition.class);
- return sqlResult;
- }
-
- @Override
- public List<Partition> getPartitions(
- String dbName, String tableName, int maxParts) throws MetaException, NoSuchObjectException {
- List<Partition> sqlResults = getPartitionsInternal(dbName, tableName, maxParts, true, false);
- List<Partition> ormResults = getPartitionsInternal(dbName, tableName, maxParts, false, true);
- verifyLists(sqlResults, ormResults, Partition.class);
- return sqlResults;
- }
-
- @Override
- public ColumnStatistics getTableColumnStatistics(String dbName,
- String tableName, List<String> colNames) throws MetaException, NoSuchObjectException {
- ColumnStatistics sqlResult = getTableColumnStatisticsInternal(
- dbName, tableName, colNames, true, false);
- ColumnStatistics jdoResult = getTableColumnStatisticsInternal(
- dbName, tableName, colNames, false, true);
- verifyObjects(sqlResult, jdoResult, ColumnStatistics.class);
- return sqlResult;
- }
-
- @Override
- public List<ColumnStatistics> getPartitionColumnStatistics(String dbName,
- String tableName, List<String> partNames, List<String> colNames)
- throws MetaException, NoSuchObjectException {
- List<ColumnStatistics> sqlResult = getPartitionColumnStatisticsInternal(
- dbName, tableName, partNames, colNames, true, false);
- List<ColumnStatistics> jdoResult = getPartitionColumnStatisticsInternal(
- dbName, tableName, partNames, colNames, false, true);
- verifyLists(sqlResult, jdoResult, ColumnStatistics.class);
- return sqlResult;
- }
-
- private void verifyObjects(
- Object sqlResult, Object jdoResult, Class<?> clazz) throws MetaException {
- if (EqualsBuilder.reflectionEquals(sqlResult, jdoResult)) return;
- StringBuilder errorStr = new StringBuilder("Objects are different: \n");
- try {
- dumpObject(errorStr, "SQL", sqlResult, clazz, 0);
- errorStr.append("\n");
- dumpObject(errorStr, "ORM", jdoResult, clazz, 0);
- } catch (Throwable t) {
- errorStr.append("Error getting the diff: " + t);
- }
- LOG.error("Different results: \n" + errorStr.toString());
- throw new MetaException("Different results from SQL and ORM, see log for details");
- }
-
- private <T> void verifyLists(Collection<T> sqlResults, Collection<T> ormResults,
- Class<?> clazz) throws MetaException {
- final int MAX_DIFFS = 5;
- if (sqlResults.size() != ormResults.size()) {
- String msg = "Lists are not the same size: SQL " + sqlResults.size()
- + ", ORM " + ormResults.size();
- LOG.error(msg);
- throw new MetaException(msg);
- }
-
- Iterator<T> sqlIter = sqlResults.iterator(), ormIter = ormResults.iterator();
- StringBuilder errorStr = new StringBuilder();
- int errors = 0;
- for (int partIx = 0; partIx < sqlResults.size(); ++partIx) {
- assert sqlIter.hasNext() && ormIter.hasNext();
- T p1 = sqlIter.next(), p2 = ormIter.next();
- if (EqualsBuilder.reflectionEquals(p1, p2)) continue;
- errorStr.append("Results are different at list index " + partIx + ": \n");
- try {
- dumpObject(errorStr, "SQL", p1, clazz, 0);
- errorStr.append("\n");
- dumpObject(errorStr, "ORM", p2, clazz, 0);
- errorStr.append("\n\n");
- } catch (Throwable t) {
- String msg = "Error getting the diff at list index " + partIx;
- errorStr.append("\n\n" + msg);
- LOG.error(msg, t);
- break;
- }
- if (++errors == MAX_DIFFS) {
- errorStr.append("\n\nToo many diffs, giving up (lists might be sorted differently)");
- break;
- }
- }
- if (errorStr.length() > 0) {
- LOG.error("Different results: \n" + errorStr.toString());
- throw new MetaException("Different results from SQL and ORM, see log for details");
- }
- }
-
- private static void dumpObject(StringBuilder errorStr, String name, Object p,
- Class<?> c, int level) throws IllegalAccessException {
- String offsetStr = repeat(" ", level);
- if (p == null || c == String.class || c.isPrimitive()
- || ClassUtils.wrapperToPrimitive(c) != null) {
- errorStr.append(offsetStr).append(name + ": [" + p + "]\n");
- } else if (ClassUtils.isAssignable(c, Iterable.class)) {
- errorStr.append(offsetStr).append(name + " is an iterable\n");
- Iterator<?> i1 = ((Iterable<?>)p).iterator();
- int i = 0;
- while (i1.hasNext()) {
- Object o1 = i1.next();
- Class<?> t = o1 == null ? Object.class : o1.getClass(); // ...
- dumpObject(errorStr, name + "[" + (i++) + "]", o1, t, level + 1);
- }
- } else if (c.isArray()) {
- int len = Array.getLength(p);
- Class<?> t = c.getComponentType();
- errorStr.append(offsetStr).append(name + " is an array\n");
- for (int i = 0; i < len; ++i) {
- dumpObject(errorStr, name + "[" + i + "]", Array.get(p, i), t, level + 1);
- }
- } else if (ClassUtils.isAssignable(c, Map.class)) {
- Map<?,?> c1 = (Map<?,?>)p;
- errorStr.append(offsetStr).append(name + " is a map\n");
- dumpObject(errorStr, name + ".keys", c1.keySet(), Set.class, level + 1);
- dumpObject(errorStr, name + ".vals", c1.values(), Collection.class, level + 1);
- } else {
- errorStr.append(offsetStr).append(name + " is of type " + c.getCanonicalName() + "\n");
- // TODO: this doesn't include superclass.
- Field[] fields = c.getDeclaredFields();
- AccessibleObject.setAccessible(fields, true);
- for (int i = 0; i < fields.length; i++) {
- Field f = fields[i];
- if (f.getName().indexOf('$') != -1 || Modifier.isStatic(f.getModifiers())) continue;
- dumpObject(errorStr, name + "." + f.getName(), f.get(p), f.getType(), level + 1);
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/ql/pom.xml
----------------------------------------------------------------------
diff --git a/ql/pom.xml b/ql/pom.xml
index 7ed8f27..f35a4c8 100644
--- a/ql/pom.xml
+++ b/ql/pom.xml
@@ -470,7 +470,7 @@
</dependency>
<dependency>
<groupId>org.apache.hive</groupId>
- <artifactId>hive-metastore</artifactId>
+ <artifactId>hive-standalone-metastore</artifactId>
<version>${project.version}</version>
<type>test-jar</type>
<scope>test</scope>
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/ql/src/java/org/apache/hadoop/hive/ql/Driver.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/Driver.java b/ql/src/java/org/apache/hadoop/hive/ql/Driver.java
index 3fb7cfa..c915fd6 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/Driver.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/Driver.java
@@ -50,7 +50,8 @@ import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.conf.HiveConf.ConfVars;
import org.apache.hadoop.hive.conf.HiveVariableSource;
import org.apache.hadoop.hive.conf.VariableSubstitution;
-import org.apache.hadoop.hive.metastore.MetaStoreUtils;
+import org.apache.hadoop.hive.metastore.ColumnType;
+import org.apache.hadoop.hive.metastore.HiveMetaStoreUtils;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.Schema;
import org.apache.hadoop.hive.ql.exec.ConditionalTask;
@@ -304,7 +305,7 @@ public class Driver implements CommandProcessor {
String tableName = "result";
List<FieldSchema> lst = null;
try {
- lst = MetaStoreUtils.getFieldsFromDeserializer(tableName, td.getDeserializer(conf));
+ lst = HiveMetaStoreUtils.getFieldsFromDeserializer(tableName, td.getDeserializer(conf));
} catch (Exception e) {
LOG.warn("Error getting schema: "
+ org.apache.hadoop.util.StringUtils.stringifyException(e));
@@ -333,7 +334,7 @@ public class Driver implements CommandProcessor {
// Go over the schema and convert type to thrift type
if (lst != null) {
for (FieldSchema f : lst) {
- f.setType(MetaStoreUtils.typeToThriftType(f.getType()));
+ f.setType(ColumnType.typeToThriftType(f.getType()));
}
}
}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/ql/src/java/org/apache/hadoop/hive/ql/QueryState.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/QueryState.java b/ql/src/java/org/apache/hadoop/hive/ql/QueryState.java
index 7d5aa8b..f3a46db 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/QueryState.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/QueryState.java
@@ -138,8 +138,8 @@ public class QueryState {
/**
* The source HiveConf object used to create the QueryState. If runAsync is false, and the
- * confOverLay is empty then we will reuse the hiveConf object as a backing datastore for the
- * QueryState. We will create a clone of the hiveConf object otherwise.
+ * confOverLay is empty then we will reuse the conf object as a backing datastore for the
+ * QueryState. We will create a clone of the conf object otherwise.
* @param hiveConf The source HiveConf
* @return The builder
*/
@@ -153,7 +153,7 @@ public class QueryState {
* - runAsync false
* - confOverlay null
* - generateNewQueryId false
- * - hiveConf null
+ * - conf null
* @return The generated QueryState object
*/
public QueryState build() {
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/ql/src/java/org/apache/hadoop/hive/ql/exec/ArchiveUtils.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/exec/ArchiveUtils.java b/ql/src/java/org/apache/hadoop/hive/ql/exec/ArchiveUtils.java
index f7fad94..a5912eb 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/exec/ArchiveUtils.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/exec/ArchiveUtils.java
@@ -30,10 +30,10 @@ import java.util.Map;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.conf.HiveConf;
-import org.apache.hadoop.hive.metastore.MetaStoreUtils;
import org.apache.hadoop.hive.metastore.Warehouse;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.MetaException;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
import org.apache.hadoop.hive.ql.metadata.Hive;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.metadata.Partition;
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/ql/src/java/org/apache/hadoop/hive/ql/exec/DDLTask.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/exec/DDLTask.java b/ql/src/java/org/apache/hadoop/hive/ql/exec/DDLTask.java
index 591be49..93e1daf 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/exec/DDLTask.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/exec/DDLTask.java
@@ -65,7 +65,7 @@ import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.conf.HiveConf.ConfVars;
import org.apache.hadoop.hive.metastore.DefaultHiveMetaHook;
import org.apache.hadoop.hive.metastore.HiveMetaHook;
-import org.apache.hadoop.hive.metastore.MetaStoreUtils;
+import org.apache.hadoop.hive.metastore.HiveMetaStoreUtils;
import org.apache.hadoop.hive.metastore.PartitionDropOptions;
import org.apache.hadoop.hive.metastore.StatObjectConverter;
import org.apache.hadoop.hive.metastore.TableType;
@@ -103,6 +103,7 @@ import org.apache.hadoop.hive.metastore.api.SkewedInfo;
import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
import org.apache.hadoop.hive.metastore.api.TxnInfo;
import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
import org.apache.hadoop.hive.ql.CompilationOpContext;
import org.apache.hadoop.hive.ql.Context;
import org.apache.hadoop.hive.ql.DriverContext;
@@ -4088,7 +4089,7 @@ public class DDLTask extends Task<DDLWork> implements Serializable {
// the fields so that new SerDe could operate. Note that this may fail if some fields
// from old SerDe are too long to be stored in metastore, but there's nothing we can do.
try {
- Deserializer oldSerde = MetaStoreUtils.getDeserializer(
+ Deserializer oldSerde = HiveMetaStoreUtils.getDeserializer(
conf, tbl.getTTable(), false, oldSerdeName);
tbl.setFields(Hive.getFieldsFromDeserializer(tbl.getTableName(), oldSerde));
} catch (MetaException ex) {
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/ql/src/java/org/apache/hadoop/hive/ql/exec/FetchOperator.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/exec/FetchOperator.java b/ql/src/java/org/apache/hadoop/hive/ql/exec/FetchOperator.java
index b85a243..fb78bd8 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/exec/FetchOperator.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/exec/FetchOperator.java
@@ -39,7 +39,6 @@ import org.apache.hadoop.hive.common.FileUtils;
import org.apache.hadoop.hive.common.ValidReadTxnList;
import org.apache.hadoop.hive.common.ValidTxnList;
import org.apache.hadoop.hive.conf.HiveConf;
-import org.apache.hadoop.hive.metastore.MetaStoreUtils;
import org.apache.hadoop.hive.ql.exec.mr.ExecMapperContext;
import org.apache.hadoop.hive.ql.io.AcidUtils;
import org.apache.hadoop.hive.ql.io.HiveContextAwareRecordReader;
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/ql/src/java/org/apache/hadoop/hive/ql/exec/MoveTask.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/exec/MoveTask.java b/ql/src/java/org/apache/hadoop/hive/ql/exec/MoveTask.java
index e2f8c1f..af5a44f 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/exec/MoveTask.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/exec/MoveTask.java
@@ -24,10 +24,10 @@ import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.common.FileUtils;
import org.apache.hadoop.hive.common.HiveStatsUtils;
import org.apache.hadoop.hive.conf.HiveConf;
-import org.apache.hadoop.hive.metastore.MetaStoreUtils;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.InvalidOperationException;
import org.apache.hadoop.hive.metastore.api.Order;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
import org.apache.hadoop.hive.ql.Context;
import org.apache.hadoop.hive.ql.DriverContext;
import org.apache.hadoop.hive.ql.ErrorMsg;
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/ql/src/java/org/apache/hadoop/hive/ql/exec/StatsTask.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/exec/StatsTask.java b/ql/src/java/org/apache/hadoop/hive/ql/exec/StatsTask.java
index 682b42c..7ef293e 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/exec/StatsTask.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/exec/StatsTask.java
@@ -30,6 +30,7 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.fs.FileStatus;
@@ -37,7 +38,6 @@ import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.common.StatsSetupConst;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.conf.HiveConf.ConfVars;
-import org.apache.hadoop.hive.metastore.MetaStoreUtils;
import org.apache.hadoop.hive.metastore.Warehouse;
import org.apache.hadoop.hive.metastore.api.EnvironmentContext;
import org.apache.hadoop.hive.metastore.api.MetaException;
@@ -358,7 +358,7 @@ public class StatsTask extends Task<StatsWork> implements Serializable {
// prefix is of the form dbName.tblName
String prefix = StatsUtils.getFullyQualifiedTableName(table.getDbName(),
- org.apache.hadoop.hive.metastore.utils.MetaStoreUtils.encodeTableName(table.getTableName()));
+ MetaStoreUtils.encodeTableName(table.getTableName()));
if (partition != null) {
return Utilities.join(prefix, Warehouse.makePartPath(partition.getSpec()));
}
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/ql/src/java/org/apache/hadoop/hive/ql/exec/Utilities.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/exec/Utilities.java b/ql/src/java/org/apache/hadoop/hive/ql/exec/Utilities.java
index 1be7eab..2e3391f 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/exec/Utilities.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/exec/Utilities.java
@@ -103,11 +103,11 @@ import org.apache.hadoop.hive.common.StringInternUtils;
import org.apache.hadoop.hive.common.ValidTxnList;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.conf.HiveConf.ConfVars;
-import org.apache.hadoop.hive.metastore.MetaStoreUtils;
import org.apache.hadoop.hive.metastore.Warehouse;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.Order;
import org.apache.hadoop.hive.metastore.api.hive_metastoreConstants;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
import org.apache.hadoop.hive.ql.Context;
import org.apache.hadoop.hive.ql.Driver.DriverState;
import org.apache.hadoop.hive.ql.Driver.LockedDriverState;
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/ql/src/java/org/apache/hadoop/hive/ql/exec/tez/DagUtils.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/exec/tez/DagUtils.java b/ql/src/java/org/apache/hadoop/hive/ql/exec/tez/DagUtils.java
index 5c338b8..6c1afa6 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/exec/tez/DagUtils.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/exec/tez/DagUtils.java
@@ -1184,10 +1184,10 @@ public class DagUtils {
/**
* Creates and initializes a JobConf object that can be used to execute
* the DAG. The configuration object will contain configurations from mapred-site
- * overlaid with key/value pairs from the hiveConf object. Finally it will also
+ * overlaid with key/value pairs from the conf object. Finally it will also
* contain some hive specific configurations that do not change from DAG to DAG.
*
- * @param hiveConf Current hiveConf for the execution
+ * @param hiveConf Current conf for the execution
* @return JobConf base configuration for job execution
* @throws IOException
*/
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/ql/src/java/org/apache/hadoop/hive/ql/io/AcidUtils.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/io/AcidUtils.java b/ql/src/java/org/apache/hadoop/hive/ql/io/AcidUtils.java
index 4c0b71f..c879ecd 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/io/AcidUtils.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/io/AcidUtils.java
@@ -39,7 +39,6 @@ import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.conf.HiveConf.ConfVars;
import org.apache.hadoop.hive.metastore.api.DataOperationType;
import org.apache.hadoop.hive.metastore.api.hive_metastoreConstants;
-import org.apache.hadoop.hive.metastore.MetaStoreUtils;
import org.apache.hadoop.hive.metastore.TransactionalValidationListener;
import org.apache.hadoop.hive.ql.ErrorMsg;
import org.apache.hadoop.hive.ql.io.orc.OrcRecordUpdater;
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/ql/src/java/org/apache/hadoop/hive/ql/io/CombineHiveInputFormat.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/io/CombineHiveInputFormat.java b/ql/src/java/org/apache/hadoop/hive/ql/io/CombineHiveInputFormat.java
index 6a188ac..ff5b292 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/io/CombineHiveInputFormat.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/io/CombineHiveInputFormat.java
@@ -45,7 +45,6 @@ import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.PathFilter;
-import org.apache.hadoop.hive.metastore.MetaStoreUtils;
import org.apache.hadoop.hive.ql.Driver.DriverState;
import org.apache.hadoop.hive.ql.Driver.LockedDriverState;
import org.apache.hadoop.hive.ql.exec.Operator;
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/ql/src/java/org/apache/hadoop/hive/ql/io/HiveInputFormat.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/io/HiveInputFormat.java b/ql/src/java/org/apache/hadoop/hive/ql/io/HiveInputFormat.java
index 6a1dc72..016d152 100755
--- a/ql/src/java/org/apache/hadoop/hive/ql/io/HiveInputFormat.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/io/HiveInputFormat.java
@@ -37,7 +37,6 @@ import org.apache.hadoop.hive.common.JavaUtils;
import org.apache.hadoop.hive.common.StringInternUtils;
import org.apache.hadoop.hive.common.ValidReadTxnList;
import org.apache.hadoop.hive.common.ValidTxnList;
-import org.apache.hadoop.hive.metastore.MetaStoreUtils;
import org.apache.hadoop.hive.ql.exec.SerializationUtilities;
import org.apache.hive.common.util.Ref;
import org.slf4j.Logger;
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/ql/src/java/org/apache/hadoop/hive/ql/metadata/Hive.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/metadata/Hive.java b/ql/src/java/org/apache/hadoop/hive/ql/metadata/Hive.java
index 70656fe..1415b49 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/metadata/Hive.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/metadata/Hive.java
@@ -79,8 +79,8 @@ import org.apache.hadoop.hive.metastore.HiveMetaHook;
import org.apache.hadoop.hive.metastore.HiveMetaHookLoader;
import org.apache.hadoop.hive.metastore.HiveMetaStore;
import org.apache.hadoop.hive.metastore.HiveMetaStoreClient;
+import org.apache.hadoop.hive.metastore.HiveMetaStoreUtils;
import org.apache.hadoop.hive.metastore.IMetaStoreClient;
-import org.apache.hadoop.hive.metastore.MetaStoreUtils;
import org.apache.hadoop.hive.metastore.PartitionDropOptions;
import org.apache.hadoop.hive.metastore.RawStore;
import org.apache.hadoop.hive.metastore.RetryingMetaStoreClient;
@@ -133,6 +133,7 @@ import org.apache.hadoop.hive.metastore.api.SkewedInfo;
import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
import org.apache.hadoop.hive.metastore.api.UniqueConstraintsRequest;
import org.apache.hadoop.hive.metastore.api.hive_metastoreConstants;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
import org.apache.hadoop.hive.ql.ErrorMsg;
import org.apache.hadoop.hive.ql.exec.AbstractFileMergeOperator;
import org.apache.hadoop.hive.ql.exec.FunctionRegistry;
@@ -871,7 +872,7 @@ public class Hive {
tbl.setDbName(SessionState.get().getCurrentDatabase());
}
if (tbl.getCols().size() == 0 || tbl.getSd().getColsSize() == 0) {
- tbl.setFields(MetaStoreUtils.getFieldsFromDeserializer(tbl.getTableName(),
+ tbl.setFields(HiveMetaStoreUtils.getFieldsFromDeserializer(tbl.getTableName(),
tbl.getDeserializer()));
}
tbl.checkValidity(conf);
@@ -913,7 +914,7 @@ public class Hive {
public static List<FieldSchema> getFieldsFromDeserializerForMsStorage(
Table tbl, Deserializer deserializer) throws SerDeException, MetaException {
- List<FieldSchema> schema = MetaStoreUtils.getFieldsFromDeserializer(
+ List<FieldSchema> schema = HiveMetaStoreUtils.getFieldsFromDeserializer(
tbl.getTableName(), deserializer);
for (FieldSchema field : schema) {
field.setType(MetaStoreUtils.TYPE_FROM_DESERIALIZER);
@@ -2695,10 +2696,10 @@ private void constructOneLBLocationMap(FileStatus fSta,
List<DropTableDesc.PartSpec> partSpecs, PartitionDropOptions dropOptions) throws HiveException {
try {
Table tbl = getTable(dbName, tblName);
- List<ObjectPair<Integer, byte[]>> partExprs =
- new ArrayList<ObjectPair<Integer,byte[]>>(partSpecs.size());
+ List<org.apache.hadoop.hive.metastore.utils.ObjectPair<Integer, byte[]>> partExprs =
+ new ArrayList<>(partSpecs.size());
for (DropTableDesc.PartSpec partSpec : partSpecs) {
- partExprs.add(new ObjectPair<Integer, byte[]>(partSpec.getPrefixLength(),
+ partExprs.add(new org.apache.hadoop.hive.metastore.utils.ObjectPair<>(partSpec.getPrefixLength(),
SerializationUtilities.serializeExpressionToKryo(partSpec.getPartSpec())));
}
List<org.apache.hadoop.hive.metastore.api.Partition> tParts = getMSC().dropPartitions(
@@ -4141,7 +4142,7 @@ private void constructOneLBLocationMap(FileStatus fSta,
public static List<FieldSchema> getFieldsFromDeserializer(String name,
Deserializer serde) throws HiveException {
try {
- return MetaStoreUtils.getFieldsFromDeserializer(name, serde);
+ return HiveMetaStoreUtils.getFieldsFromDeserializer(name, serde);
} catch (SerDeException e) {
throw new HiveException("Error in getting fields from serde. "
+ e.getMessage(), e);
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/ql/src/java/org/apache/hadoop/hive/ql/metadata/Partition.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/metadata/Partition.java b/ql/src/java/org/apache/hadoop/hive/ql/metadata/Partition.java
index 44026fa..6d10c10 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/metadata/Partition.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/metadata/Partition.java
@@ -28,13 +28,14 @@ import java.util.Map;
import java.util.Properties;
import org.apache.hadoop.hive.common.StringInternUtils;
+import org.apache.hadoop.hive.metastore.HiveMetaStoreUtils;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.common.FileUtils;
-import org.apache.hadoop.hive.metastore.MetaStoreUtils;
import org.apache.hadoop.hive.metastore.Warehouse;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.MetaException;
@@ -228,7 +229,7 @@ public class Partition implements Serializable {
final public Deserializer getDeserializer() {
if (deserializer == null) {
try {
- deserializer = MetaStoreUtils.getDeserializer(SessionState.getSessionConf(),
+ deserializer = HiveMetaStoreUtils.getDeserializer(SessionState.getSessionConf(),
tPartition, table.getTTable());
} catch (MetaException e) {
throw new RuntimeException(e);
@@ -246,8 +247,8 @@ public class Partition implements Serializable {
}
public Properties getSchemaFromTableSchema(Properties tblSchema) {
- return MetaStoreUtils.getPartSchemaFromTableSchema(tPartition.getSd(), table.getTTable().getSd(),
- tPartition.getParameters(), table.getDbName(), table.getTableName(), table.getPartitionKeys(),
+ return MetaStoreUtils.getPartSchemaFromTableSchema(tPartition.getSd(),
+ tPartition.getParameters(),
tblSchema);
}
@@ -493,7 +494,7 @@ public class Partition implements Serializable {
SessionState.getSessionConf(), serializationLib, table.getParameters())) {
return Hive.getFieldsFromDeserializerForMsStorage(table, getDeserializer());
}
- return MetaStoreUtils.getFieldsFromDeserializer(table.getTableName(), getDeserializer());
+ return HiveMetaStoreUtils.getFieldsFromDeserializer(table.getTableName(), getDeserializer());
} catch (Exception e) {
LOG.error("Unable to get cols from serde: " +
tPartition.getSd().getSerdeInfo().getSerializationLib(), e);
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/ql/src/java/org/apache/hadoop/hive/ql/metadata/SessionHiveMetaStoreClient.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/metadata/SessionHiveMetaStoreClient.java b/ql/src/java/org/apache/hadoop/hive/ql/metadata/SessionHiveMetaStoreClient.java
index 78e83af..d024fc9 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/metadata/SessionHiveMetaStoreClient.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/metadata/SessionHiveMetaStoreClient.java
@@ -30,17 +30,16 @@ import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
+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.FileUtils;
import org.apache.hadoop.hive.common.StatsSetupConst;
-import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.io.HdfsUtils;
import org.apache.hadoop.hive.metastore.HiveMetaHookLoader;
import org.apache.hadoop.hive.metastore.HiveMetaStoreClient;
import org.apache.hadoop.hive.metastore.IMetaStoreClient;
-import org.apache.hadoop.hive.metastore.MetaStoreUtils;
import org.apache.hadoop.hive.metastore.Warehouse;
import org.apache.hadoop.hive.metastore.api.AlreadyExistsException;
import org.apache.hadoop.hive.metastore.api.ColumnStatistics;
@@ -60,6 +59,8 @@ import org.apache.hadoop.hive.metastore.api.SetPartitionsStatsRequest;
import org.apache.hadoop.hive.metastore.api.TableMeta;
import org.apache.hadoop.hive.metastore.api.UnknownDBException;
import org.apache.hadoop.hive.metastore.api.UnknownTableException;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
+import org.apache.hadoop.hive.metastore.utils.SecurityUtils;
import org.apache.hadoop.hive.ql.session.SessionState;
import org.apache.hadoop.hive.shims.HadoopShims;
import org.apache.hadoop.hive.shims.ShimLoader;
@@ -68,12 +69,12 @@ import org.apache.thrift.TException;
public class SessionHiveMetaStoreClient extends HiveMetaStoreClient implements IMetaStoreClient {
- SessionHiveMetaStoreClient(HiveConf conf, Boolean allowEmbedded) throws MetaException {
+ SessionHiveMetaStoreClient(Configuration conf, Boolean allowEmbedded) throws MetaException {
super(conf, null, allowEmbedded);
}
SessionHiveMetaStoreClient(
- HiveConf conf, HiveMetaHookLoader hookLoader, Boolean allowEmbedded) throws MetaException {
+ Configuration conf, HiveMetaHookLoader hookLoader, Boolean allowEmbedded) throws MetaException {
super(conf, hookLoader, allowEmbedded);
}
@@ -613,7 +614,7 @@ public class SessionHiveMetaStoreClient extends HiveMetaStoreClient implements I
tablePath = new Path(table.getSd().getLocation());
if (!getWh().isWritable(tablePath.getParent())) {
throw new MetaException("Table metadata not deleted since " + tablePath.getParent() +
- " is not writable by " + conf.getUser());
+ " is not writable by " + SecurityUtils.getUser());
}
} catch (IOException err) {
MetaException metaException =
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/ql/src/java/org/apache/hadoop/hive/ql/metadata/Table.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/metadata/Table.java b/ql/src/java/org/apache/hadoop/hive/ql/metadata/Table.java
index a1cad9e..0debff6 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/metadata/Table.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/metadata/Table.java
@@ -39,7 +39,7 @@ import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.common.FileUtils;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.conf.HiveConf.ConfVars;
-import org.apache.hadoop.hive.metastore.MetaStoreUtils;
+import org.apache.hadoop.hive.metastore.HiveMetaStoreUtils;
import org.apache.hadoop.hive.metastore.TableType;
import org.apache.hadoop.hive.metastore.Warehouse;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
@@ -49,6 +49,7 @@ 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.hive_metastoreConstants;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
import org.apache.hadoop.hive.ql.exec.Utilities;
import org.apache.hadoop.hive.ql.io.HiveFileFormatUtils;
import org.apache.hadoop.hive.ql.io.HiveSequenceFileOutputFormat;
@@ -268,7 +269,7 @@ public class Table implements Serializable {
}
final public Class<? extends Deserializer> getDeserializerClass() throws Exception {
- return MetaStoreUtils.getDeserializerClass(SessionState.getSessionConf(), tTable);
+ return HiveMetaStoreUtils.getDeserializerClass(SessionState.getSessionConf(), tTable);
}
final public Deserializer getDeserializer(boolean skipConfError) {
@@ -280,7 +281,7 @@ public class Table implements Serializable {
final public Deserializer getDeserializerFromMetaStore(boolean skipConfError) {
try {
- return MetaStoreUtils.getDeserializer(SessionState.getSessionConf(), tTable, skipConfError);
+ return HiveMetaStoreUtils.getDeserializer(SessionState.getSessionConf(), tTable, skipConfError);
} catch (MetaException e) {
throw new RuntimeException(e);
}
@@ -640,7 +641,7 @@ public class Table implements Serializable {
SessionState.getSessionConf(), serializationLib, tTable.getParameters())) {
return Hive.getFieldsFromDeserializerForMsStorage(this, getDeserializer());
} else {
- return MetaStoreUtils.getFieldsFromDeserializer(getTableName(), getDeserializer());
+ return HiveMetaStoreUtils.getFieldsFromDeserializer(getTableName(), getDeserializer());
}
} catch (Exception e) {
LOG.error("Unable to get field from serde: " + serializationLib, e);
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/ql/src/java/org/apache/hadoop/hive/ql/metadata/formatting/TextMetaDataFormatter.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/metadata/formatting/TextMetaDataFormatter.java b/ql/src/java/org/apache/hadoop/hive/ql/metadata/formatting/TextMetaDataFormatter.java
index 9df1b82..874c427 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/metadata/formatting/TextMetaDataFormatter.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/metadata/formatting/TextMetaDataFormatter.java
@@ -27,6 +27,7 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
import org.apache.hive.common.util.HiveStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -37,7 +38,6 @@ import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.common.FileUtils;
import org.apache.hadoop.hive.common.StatsSetupConst;
import org.apache.hadoop.hive.conf.HiveConf;
-import org.apache.hadoop.hive.metastore.MetaStoreUtils;
import org.apache.hadoop.hive.metastore.api.ColumnStatisticsObj;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.WMResourcePlan;
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/ql/src/java/org/apache/hadoop/hive/ql/optimizer/AbstractBucketJoinProc.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/optimizer/AbstractBucketJoinProc.java b/ql/src/java/org/apache/hadoop/hive/ql/optimizer/AbstractBucketJoinProc.java
index c62d98f..a7fc3e9 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/optimizer/AbstractBucketJoinProc.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/optimizer/AbstractBucketJoinProc.java
@@ -34,7 +34,6 @@ import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.common.FileUtils;
-import org.apache.hadoop.hive.metastore.MetaStoreUtils;
import org.apache.hadoop.hive.ql.ErrorMsg;
import org.apache.hadoop.hive.ql.exec.MapJoinOperator;
import org.apache.hadoop.hive.ql.exec.Operator;
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/ql/src/java/org/apache/hadoop/hive/ql/optimizer/BucketingSortingReduceSinkOptimizer.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/optimizer/BucketingSortingReduceSinkOptimizer.java b/ql/src/java/org/apache/hadoop/hive/ql/optimizer/BucketingSortingReduceSinkOptimizer.java
index fc1d4f9..31d2b23 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/optimizer/BucketingSortingReduceSinkOptimizer.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/optimizer/BucketingSortingReduceSinkOptimizer.java
@@ -26,7 +26,6 @@ import java.util.Map;
import java.util.Stack;
import org.apache.hadoop.fs.FileStatus;
-import org.apache.hadoop.hive.metastore.MetaStoreUtils;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.Order;
import org.apache.hadoop.hive.ql.exec.FileSinkOperator;
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/ql/src/java/org/apache/hadoop/hive/ql/optimizer/SamplePruner.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/optimizer/SamplePruner.java b/ql/src/java/org/apache/hadoop/hive/ql/optimizer/SamplePruner.java
index b5891ab..9100c92 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/optimizer/SamplePruner.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/optimizer/SamplePruner.java
@@ -32,7 +32,6 @@ import org.slf4j.LoggerFactory;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
-import org.apache.hadoop.hive.metastore.MetaStoreUtils;
import org.apache.hadoop.hive.ql.exec.FilterOperator;
import org.apache.hadoop.hive.ql.exec.TableScanOperator;
import org.apache.hadoop.hive.ql.io.AcidUtils;
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/ql/src/java/org/apache/hadoop/hive/ql/optimizer/StatsOptimizer.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/optimizer/StatsOptimizer.java b/ql/src/java/org/apache/hadoop/hive/ql/optimizer/StatsOptimizer.java
index a3a35ff..85f198b 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/optimizer/StatsOptimizer.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/optimizer/StatsOptimizer.java
@@ -31,11 +31,11 @@ import java.util.Stack;
import org.apache.hadoop.hive.common.StatsSetupConst;
import org.apache.hadoop.hive.common.type.HiveDecimal;
-import org.apache.hadoop.hive.metastore.MetaStoreUtils;
import org.apache.hadoop.hive.metastore.api.ColumnStatisticsData;
import org.apache.hadoop.hive.metastore.api.ColumnStatisticsObj;
import org.apache.hadoop.hive.metastore.api.DoubleColumnStatsData;
import org.apache.hadoop.hive.metastore.api.LongColumnStatsData;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
import org.apache.hadoop.hive.ql.exec.ColumnInfo;
import org.apache.hadoop.hive.ql.exec.FetchTask;
import org.apache.hadoop.hive.ql.exec.FileSinkOperator;
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/ql/src/java/org/apache/hadoop/hive/ql/optimizer/physical/SamplingOptimizer.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/optimizer/physical/SamplingOptimizer.java b/ql/src/java/org/apache/hadoop/hive/ql/optimizer/physical/SamplingOptimizer.java
index b28315a..6dd08d2 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/optimizer/physical/SamplingOptimizer.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/optimizer/physical/SamplingOptimizer.java
@@ -20,7 +20,6 @@
package org.apache.hadoop.hive.ql.optimizer.physical;
-import org.apache.hadoop.hive.metastore.MetaStoreUtils;
import org.apache.hadoop.hive.ql.exec.GroupByOperator;
import org.apache.hadoop.hive.ql.exec.Operator;
import org.apache.hadoop.hive.ql.exec.OperatorUtils;
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/ql/src/java/org/apache/hadoop/hive/ql/parse/DDLSemanticAnalyzer.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/parse/DDLSemanticAnalyzer.java b/ql/src/java/org/apache/hadoop/hive/ql/parse/DDLSemanticAnalyzer.java
index 6a2ff75..a4fd4df 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/parse/DDLSemanticAnalyzer.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/parse/DDLSemanticAnalyzer.java
@@ -24,6 +24,7 @@ import com.google.common.collect.Lists;
import org.antlr.runtime.tree.CommonTree;
import org.antlr.runtime.tree.Tree;
import org.apache.hadoop.hive.metastore.api.hive_metastoreConstants;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
import org.apache.hadoop.hive.ql.io.AcidUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -33,7 +34,6 @@ import org.apache.hadoop.hive.common.JavaUtils;
import org.apache.hadoop.hive.common.StatsSetupConst;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.conf.HiveConf.ConfVars;
-import org.apache.hadoop.hive.metastore.MetaStoreUtils;
import org.apache.hadoop.hive.metastore.TableType;
import org.apache.hadoop.hive.metastore.Warehouse;
import org.apache.hadoop.hive.metastore.api.Database;
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/ql/src/java/org/apache/hadoop/hive/ql/parse/ExportSemanticAnalyzer.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/parse/ExportSemanticAnalyzer.java b/ql/src/java/org/apache/hadoop/hive/ql/parse/ExportSemanticAnalyzer.java
index 2400f9c..b253236 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/parse/ExportSemanticAnalyzer.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/parse/ExportSemanticAnalyzer.java
@@ -19,46 +19,13 @@
package org.apache.hadoop.hive.ql.parse;
-import org.apache.hadoop.hive.ql.metadata.HiveException;
-
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.Serializable;
-import java.net.URI;
-import java.util.HashSet;
-import java.util.List;
-
-import org.antlr.runtime.tree.Tree;
-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.FileUtils;
-import org.apache.hadoop.hive.common.ValidReadTxnList;
-import org.apache.hadoop.hive.common.ValidTxnList;
-import org.apache.hadoop.hive.conf.HiveConf;
-import org.apache.hadoop.hive.metastore.MetaStoreUtils;
-import org.apache.hadoop.hive.ql.Context;
-import org.apache.hadoop.hive.ql.ErrorMsg;
-import org.apache.hadoop.hive.ql.QueryState;
-import org.apache.hadoop.hive.ql.exec.ReplCopyTask;
-import org.apache.hadoop.hive.ql.exec.Task;
-import org.apache.hadoop.hive.ql.exec.TaskFactory;
-import org.apache.hadoop.hive.ql.exec.Utilities;
-import org.apache.hadoop.hive.ql.hooks.ReadEntity;
-import org.apache.hadoop.hive.ql.hooks.WriteEntity;
-import org.apache.hadoop.hive.ql.metadata.Hive;
import org.antlr.runtime.tree.Tree;
import org.apache.hadoop.hive.ql.ErrorMsg;
import org.apache.hadoop.hive.ql.QueryState;
import org.apache.hadoop.hive.ql.exec.Task;
import org.apache.hadoop.hive.ql.exec.TaskFactory;
import org.apache.hadoop.hive.ql.metadata.InvalidTableException;
-import org.apache.hadoop.hive.ql.metadata.Partition;
-import org.apache.hadoop.hive.ql.metadata.PartitionIterable;
import org.apache.hadoop.hive.ql.metadata.Table;
-import org.apache.hadoop.hive.ql.plan.CopyWork;
-import org.slf4j.Logger;
import org.apache.hadoop.hive.ql.parse.repl.dump.TableExport;
import org.apache.hadoop.hive.ql.plan.ExportWork;
http://git-wip-us.apache.org/repos/asf/hive/blob/20c86d1f/ql/src/java/org/apache/hadoop/hive/ql/parse/ImportSemanticAnalyzer.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/parse/ImportSemanticAnalyzer.java b/ql/src/java/org/apache/hadoop/hive/ql/parse/ImportSemanticAnalyzer.java
index 1318c18..1387de2 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/parse/ImportSemanticAnalyzer.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/parse/ImportSemanticAnalyzer.java
@@ -26,7 +26,6 @@ import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.common.FileUtils;
import org.apache.hadoop.hive.common.StatsSetupConst;
import org.apache.hadoop.hive.conf.HiveConf;
-import org.apache.hadoop.hive.metastore.MetaStoreUtils;
import org.apache.hadoop.hive.metastore.TableType;
import org.apache.hadoop.hive.metastore.Warehouse;
import org.apache.hadoop.hive.metastore.api.Database;