Skip to content

World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.

[#9459] improve(catalog-hive/hudi) Refactor the Hive and Hudi catalogs to use the HiveClient (#9460)

Yuhuib93d00b6503c
diff --git a/.gitignore b/.gitignore
index 1495d0cac3..d837f81741 100644
--- a/.gitignore
+++ b/.gitignore
@@ -36,6 +36,7 @@ gen
out/**
*.iws
*.ipr
+**/keytabs/
distribution
common/src/main/resources/gravitino-build-info.properties
diff --git a/catalogs/catalog-common/src/main/java/org/apache/gravitino/catalog/hive/HiveConstants.java b/catalogs/catalog-common/src/main/java/org/apache/gravitino/catalog/hive/HiveConstants.java
index d5424141b1..e8459ba2a7 100644
--- a/catalogs/catalog-common/src/main/java/org/apache/gravitino/catalog/hive/HiveConstants.java
+++ b/catalogs/catalog-common/src/main/java/org/apache/gravitino/catalog/hive/HiveConstants.java
@@ -51,4 +51,5 @@ public class HiveConstants {
public static final String HIVE_METASTORE_URIS = "hive.metastore.uris";
public static final String HIVE_FILTER_FIELD_PARAMS = "hive_filter_field_params__";
public static final String HIVE_METASTORE_TOKEN_SIGNATURE = "hive.metastore.token.signature";
+ public static final String HIVE_DEFAULT_CATALOG = "hive";
}
diff --git a/catalogs/catalog-hive/build.gradle.kts b/catalogs/catalog-hive/build.gradle.kts
index 6a39f0924f..15be9c6f59 100644
--- a/catalogs/catalog-hive/build.gradle.kts
+++ b/catalogs/catalog-hive/build.gradle.kts
@@ -36,12 +36,16 @@ dependencies {
implementation(project(":catalogs:catalog-common")) {
exclude("*")
}
+ implementation(project(":common")) {
+ exclude("*")
+ }
implementation(project(":catalogs:hive-metastore-common"))
implementation(project(":core")) {
exclude("*")
}
implementation(libs.commons.collections3)
+ implementation(libs.commons.lang3)
implementation(libs.commons.configuration1)
implementation(libs.htrace.core4)
implementation(libs.commons.io)
@@ -49,39 +53,10 @@ dependencies {
implementation(libs.hadoop2.auth) {
exclude("*")
}
- implementation(libs.woodstox.core)
- implementation(libs.hive2.metastore) {
- exclude("ant")
- exclude("co.cask.tephra")
- exclude("com.github.joshelser")
- exclude("com.google.code.findbugs", "jsr305")
- exclude("com.google.code.findbugs", "sr305")
- exclude("com.tdunning", "json")
- exclude("com.zaxxer", "HikariCP")
- exclude("io.dropwizard.metrics")
- exclude("javax.transaction", "transaction-api")
- exclude("org.apache.ant")
- exclude("org.apache.avro")
- exclude("org.apache.curator")
- exclude("org.apache.derby")
- exclude("org.apache.hadoop", "hadoop-yarn-server-resourcemanager")
- exclude("org.apache.hbase")
- exclude("org.apache.logging.log4j")
- exclude("org.apache.parquet", "parquet-hadoop-bundle")
- exclude("org.apache.zookeeper")
- exclude("org.datanucleus")
- exclude("org.eclipse.jetty.aggregate", "jetty-all")
- exclude("org.eclipse.jetty.orbit", "javax.servlet")
- exclude("org.openjdk.jol")
- exclude("org.slf4j")
- }
-
implementation(libs.hadoop2.common) {
exclude("*")
}
- implementation(libs.hadoop2.mapreduce.client.core) {
- exclude("*")
- }
+ implementation(libs.woodstox.core)
implementation(libs.slf4j.api)
compileOnly(libs.immutables.value)
@@ -103,6 +78,9 @@ dependencies {
testImplementation(libs.bundles.jetty)
testImplementation(libs.bundles.jersey)
testImplementation(libs.bundles.log4j)
+ testImplementation(libs.hadoop2.common) {
+ exclude("*")
+ }
testImplementation(libs.hadoop2.hdfs)
testImplementation(libs.hadoop2.mapreduce.client.core) {
exclude("*")
diff --git a/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveCatalog.java b/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveCatalog.java
index 98711f98ae..afaaafd961 100644
--- a/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveCatalog.java
+++ b/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveCatalog.java
@@ -19,11 +19,9 @@
package org.apache.gravitino.catalog.hive;
import java.util.Map;
-import java.util.Optional;
import org.apache.gravitino.connector.BaseCatalog;
import org.apache.gravitino.connector.CatalogOperations;
import org.apache.gravitino.connector.PropertiesMetadata;
-import org.apache.gravitino.connector.ProxyPlugin;
import org.apache.gravitino.connector.capability.Capability;
/** Implementation of an Apache Hive catalog in Apache Gravitino. */
@@ -65,18 +63,6 @@ public class HiveCatalog extends BaseCatalog<HiveCatalog> {
return new HiveCatalogCapability();
}
- @Override
- protected Optional<ProxyPlugin> newProxyPlugin(Map<String, String> config) {
- boolean impersonationEnabled =
- (boolean)
- new HiveCatalogPropertiesMetadata()
- .getOrDefault(config, HiveCatalogPropertiesMetadata.IMPERSONATION_ENABLE);
- if (!impersonationEnabled) {
- return Optional.empty();
- }
- return Optional.of(new HiveProxyPlugin());
- }
-
@Override
public PropertiesMetadata catalogPropertiesMetadata() throws UnsupportedOperationException {
return CATALOG_PROPERTIES_METADATA;
diff --git a/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveCatalogOperations.java b/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveCatalogOperations.java
index f5f3c5bcaa..42cac99c08 100644
--- a/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveCatalogOperations.java
+++ b/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveCatalogOperations.java
@@ -18,39 +18,38 @@
*/
package org.apache.gravitino.catalog.hive;
+import static org.apache.gravitino.catalog.hive.HiveCatalogPropertiesMetadata.IMPERSONATION_ENABLE;
+import static org.apache.gravitino.catalog.hive.HiveCatalogPropertiesMetadata.KEY_TAB_URI;
import static org.apache.gravitino.catalog.hive.HiveCatalogPropertiesMetadata.LIST_ALL_TABLES;
import static org.apache.gravitino.catalog.hive.HiveCatalogPropertiesMetadata.METASTORE_URIS;
import static org.apache.gravitino.catalog.hive.HiveCatalogPropertiesMetadata.PRINCIPAL;
-import static org.apache.gravitino.catalog.hive.HiveTable.SUPPORT_TABLE_TYPES;
-import static org.apache.gravitino.catalog.hive.HiveTablePropertiesMetadata.COMMENT;
-import static org.apache.gravitino.catalog.hive.HiveTablePropertiesMetadata.TABLE_TYPE;
+import static org.apache.gravitino.catalog.hive.HiveConstants.HIVE_FILTER_FIELD_PARAMS;
+import static org.apache.gravitino.catalog.hive.HiveConstants.HIVE_METASTORE_URIS;
+import static org.apache.gravitino.catalog.hive.HiveConstants.TABLE_TYPE;
+import static org.apache.gravitino.catalog.hive.TableType.EXTERNAL_TABLE;
import static org.apache.gravitino.connector.BaseCatalog.CATALOG_BYPASS_PREFIX;
-import static org.apache.gravitino.hive.converter.HiveDataTypeConverter.CONVERTER;
-import static org.apache.hadoop.hive.metastore.TableType.EXTERNAL_TABLE;
+import static org.apache.gravitino.hive.HiveTable.SUPPORT_TABLE_TYPES;
+import static org.apache.gravitino.hive.kerberos.AuthenticationConfig.IMPERSONATION_ENABLE_KEY;
+import static org.apache.gravitino.hive.kerberos.KerberosConfig.KEY_TAB_URI_KEY;
+import static org.apache.gravitino.hive.kerberos.KerberosConfig.PRINCIPAL_KEY;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
-import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
-import java.io.IOException;
-import java.io.UncheckedIOException;
-import java.lang.reflect.Method;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
import java.time.Instant;
+import java.util.ArrayList;
import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
import java.util.List;
import java.util.Map;
+import java.util.Properties;
import java.util.Set;
-import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
-import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.apache.commons.lang3.ArrayUtils;
-import org.apache.commons.lang3.StringUtils;
import org.apache.gravitino.Catalog;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
@@ -58,21 +57,24 @@ import org.apache.gravitino.SchemaChange;
import org.apache.gravitino.connector.CatalogInfo;
import org.apache.gravitino.connector.CatalogOperations;
import org.apache.gravitino.connector.HasPropertyMetadata;
-import org.apache.gravitino.connector.ProxyPlugin;
import org.apache.gravitino.connector.SupportsSchemas;
import org.apache.gravitino.exceptions.ConnectionFailedException;
import org.apache.gravitino.exceptions.NoSuchCatalogException;
+import org.apache.gravitino.exceptions.NoSuchEntityException;
import org.apache.gravitino.exceptions.NoSuchSchemaException;
import org.apache.gravitino.exceptions.NoSuchTableException;
import org.apache.gravitino.exceptions.NonEmptySchemaException;
import org.apache.gravitino.exceptions.SchemaAlreadyExistsException;
import org.apache.gravitino.exceptions.TableAlreadyExistsException;
import org.apache.gravitino.hive.CachedClientPool;
+import org.apache.gravitino.hive.HiveSchema;
+import org.apache.gravitino.hive.HiveTable;
import org.apache.gravitino.meta.AuditInfo;
import org.apache.gravitino.rel.Column;
import org.apache.gravitino.rel.Table;
import org.apache.gravitino.rel.TableCatalog;
import org.apache.gravitino.rel.TableChange;
+import org.apache.gravitino.rel.expressions.Expression;
import org.apache.gravitino.rel.expressions.NamedReference;
import org.apache.gravitino.rel.expressions.distributions.Distribution;
import org.apache.gravitino.rel.expressions.distributions.Distributions;
@@ -80,21 +82,8 @@ import org.apache.gravitino.rel.expressions.sorts.SortOrder;
import org.apache.gravitino.rel.expressions.transforms.Transform;
import org.apache.gravitino.rel.expressions.transforms.Transforms;
import org.apache.gravitino.rel.indexes.Index;
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.hive.conf.HiveConf;
-import org.apache.hadoop.hive.conf.HiveConf.ConfVars;
-import org.apache.hadoop.hive.metastore.IMetaStoreClient;
-import org.apache.hadoop.hive.metastore.api.AlreadyExistsException;
-import org.apache.hadoop.hive.metastore.api.Database;
-import org.apache.hadoop.hive.metastore.api.FieldSchema;
-import org.apache.hadoop.hive.metastore.api.InvalidOperationException;
-import org.apache.hadoop.hive.metastore.api.NoSuchObjectException;
-import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
-import org.apache.hadoop.hive.metastore.api.UnknownDBException;
-import org.apache.hadoop.hive.metastore.api.hive_metastoreConstants;
-import org.apache.hadoop.security.SecurityUtil;
-import org.apache.hadoop.security.UserGroupInformation;
-import org.apache.thrift.TException;
+import org.apache.gravitino.rel.types.Type;
+import org.apache.gravitino.utils.PrincipalUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -102,19 +91,16 @@ import org.slf4j.LoggerFactory;
public class HiveCatalogOperations implements CatalogOperations, SupportsSchemas, TableCatalog {
public static final Logger LOG = LoggerFactory.getLogger(HiveCatalogOperations.class);
- public static final String GRAVITINO_KEYTAB_FORMAT = "keytabs/gravitino-hive-%s-keytab";
@VisibleForTesting CachedClientPool clientPool;
- @VisibleForTesting HiveConf hiveConf;
-
+ @SuppressWarnings("UnusedVariable")
private CatalogInfo info;
private HasPropertyMetadata propertiesMetadata;
- private ScheduledThreadPoolExecutor checkTgtExecutor;
- private String kerberosRealm;
- private ProxyPlugin proxyPlugin;
+ private String catalogName;
+
private boolean listAllTables = true;
// The maximum number of tables that can be returned by the listTableNamesByFilter function.
// The default value is -1, which means that all tables are returned.
@@ -124,7 +110,11 @@ public class HiveCatalogOperations implements CatalogOperations, SupportsSchemas
// will only need to set the configuration 'METASTORE_URL' in Gravitino and Gravitino will change
// it to `METASTOREURIS` automatically and pass it to Hive.
public static final Map<String, String> GRAVITINO_CONFIG_TO_HIVE =
- ImmutableMap.of(METASTORE_URIS, ConfVars.METASTOREURIS.varname);
+ ImmutableMap.of(
+ METASTORE_URIS, HIVE_METASTORE_URIS,
+ IMPERSONATION_ENABLE, IMPERSONATION_ENABLE_KEY,
+ KEY_TAB_URI, KEY_TAB_URI_KEY,
+ PRINCIPAL, PRINCIPAL_KEY);
/**
* Initializes the Hive catalog operations with the provided configuration.
@@ -141,6 +131,23 @@ public class HiveCatalogOperations implements CatalogOperations, SupportsSchemas
this.info = info;
this.propertiesMetadata = propertiesMetadata;
+ Properties prop = mergeProperties(conf);
+ String catalogKey =
+ String.format("hive-%s", info == null || info.id() == null ? "0" : info.id());
+ this.clientPool = new CachedClientPool(catalogKey, prop, conf);
+ this.listAllTables = enableListAllTables(conf);
+
+ // Initialize the HMS catalog name from catalog properties (default to DEFAULT_HMS_CATALOG)
+ String defaultCatalog =
+ (String)
+ propertiesMetadata
+ .catalogPropertiesMetadata()
+ .getOrDefault(conf, HiveCatalogPropertiesMetadata.DEFAULT_CATALOG);
+ this.catalogName = defaultCatalog;
+ }
+
+ @VisibleForTesting
+ protected Properties mergeProperties(Map<String, String> conf) {
// Key format like gravitino.bypass.a.b
Map<String, String> byPassConfig = Maps.newHashMap();
// Hold keys that lie in GRAVITINO_CONFIG_TO_HIVE
@@ -161,130 +168,10 @@ public class HiveCatalogOperations implements CatalogOperations, SupportsSchemas
}
});
- Map<String, String> mergeConfig = Maps.newHashMap(byPassConfig);
- // `gravitinoConfig` overwrite byPassConfig if possible
- mergeConfig.putAll(gravitinoConfig);
-
- Configuration hadoopConf = new Configuration();
- // Set byPass first to make Gravitino config overwrite it, only keys in byPassConfig
- // and gravitinoConfig will be passed to Hive config, and gravitinoConfig has higher priority
- mergeConfig.forEach(hadoopConf::set);
- hiveConf = new HiveConf(hadoopConf, HiveCatalogOperations.class);
-
- initKerberosIfNecessary(conf, hadoopConf);
-
- this.clientPool = new CachedClientPool(hiveConf, conf);
-
- this.listAllTables = enableListAllTables(conf);
- }
-
- private void initKerberosIfNecessary(Map<String, String> conf, Configuration hadoopConf) {
- if (UserGroupInformation.AuthenticationMethod.KERBEROS
- == SecurityUtil.getAuthenticationMethod(hadoopConf)) {
- try {
- Path keytabsPath = Paths.get("keytabs");
- if (!Files.exists(keytabsPath)) {
- // Ignore the return value, because there exists many Hive catalog operations making
- // this directory.
- Files.createDirectory(keytabsPath);
- }
-
- // The id of entity is a random unique id.
- Path keytabPath = Paths.get(String.format(GRAVITINO_KEYTAB_FORMAT, info.id()));
- keytabPath.toFile().deleteOnExit();
- if (Files.exists(keytabPath)) {
- try {
- Files.delete(keytabPath);
- } catch (IOException e) {
- throw new IllegalStateException(
- String.format("Fail to delete keytab file %s", keytabPath.toAbsolutePath()), e);
- }
- }
-
- String keytabUri =
- (String)
- propertiesMetadata
- .catalogPropertiesMetadata()
- .getOrDefault(conf, HiveCatalogPropertiesMetadata.KEY_TAB_URI);
- Preconditions.checkArgument(StringUtils.isNotBlank(keytabUri), "Keytab uri can't be blank");
- // TODO: Support to download the file from Kerberos HDFS
- Preconditions.checkArgument(
- !keytabUri.trim().startsWith("hdfs"), "Keytab uri doesn't support to use HDFS");
-
- int fetchKeytabFileTimeout =
- (int)
- propertiesMetadata
- .catalogPropertiesMetadata()
- .getOrDefault(conf, HiveCatalogPropertiesMetadata.FETCH_TIMEOUT_SEC);
-
- FetchFileUtils.fetchFileFromUri(
- keytabUri, keytabPath.toFile(), fetchKeytabFileTimeout, hadoopConf);
-
- hiveConf.setVar(
- ConfVars.METASTORE_KERBEROS_KEYTAB_FILE, keytabPath.toAbsolutePath().toString());
-
- String catalogPrincipal =
- (String) propertiesMetadata.catalogPropertiesMetadata().getOrDefault(conf, PRINCIPAL);
- Preconditions.checkArgument(
- StringUtils.isNotBlank(catalogPrincipal), "The principal can't be blank");
- @SuppressWarnings("null")
- List<String> principalComponents = Splitter.on('@').splitToList(catalogPrincipal);
- Preconditions.checkArgument(
- principalComponents.size() == 2, "The principal has the wrong format");
- this.kerberosRealm = principalComponents.get(1);
-
- checkTgtExecutor =
- new ScheduledThreadPoolExecutor(
- 1, getThreadFactory(String.format("Kerberos-check-%s", info.id())));
-
- LOG.info("krb5 path: {}", System.getProperty("java.security.krb5.conf"));
- refreshKerberosConfig();
- UserGroupInformation.setConfiguration(hadoopConf);
- UserGroupInformation.loginUserFromKeytab(
- catalogPrincipal, keytabPath.toAbsolutePath().toString());
-
- UserGroupInformation kerberosLoginUgi = UserGroupInformation.getCurrentUser();
-
- int checkInterval =
- (int)
- propertiesMetadata
- .catalogPropertiesMetadata()
- .getOrDefault(conf, HiveCatalogPropertiesMetadata.CHECK_INTERVAL_SEC);
-
- checkTgtExecutor.scheduleAtFixedRate(
- () -> {
- try {
- kerberosLoginUgi.checkTGTAndReloginFromKeytab();
- } catch (Exception e) {
- LOG.error("Fail to refresh ugi token: ", e);
- }
- },
- checkInterval,
- checkInterval,
- TimeUnit.SECONDS);
-
- } catch (IOException ioe) {
- throw new UncheckedIOException(ioe);
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- }
-
- private void refreshKerberosConfig() {
- Class<?> classRef;
- try {
- if (System.getProperty("java.vendor").contains("IBM")) {
- classRef = Class.forName("com.ibm.security.krb5.internal.Config");
- } else {
- classRef = Class.forName("sun.security.krb5.Config");
- }
-
- Method refreshMethod = classRef.getMethod("refresh");
- refreshMethod.invoke(null);
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
+ Properties prop = new Properties();
+ byPassConfig.forEach(prop::setProperty);
+ gravitinoConfig.forEach(prop::setProperty);
+ return prop;
}
boolean enableListAllTables(Map<String, String> conf) {
@@ -298,20 +185,6 @@ public class HiveCatalogOperations implements CatalogOperations, SupportsSchemas
clientPool.close();
clientPool = null;
}
-
- if (checkTgtExecutor != null) {
- checkTgtExecutor.shutdown();
- checkTgtExecutor = null;
- }
-
- Path keytabPath = Paths.get(String.format(GRAVITINO_KEYTAB_FORMAT, info.id()));
- if (Files.exists(keytabPath)) {
- try {
- Files.delete(keytabPath);
- } catch (IOException e) {
- LOG.error("Fail to delete key tab file {}", keytabPath.toAbsolutePath(), e);
- }
- }
}
/**
@@ -327,18 +200,10 @@ public class HiveCatalogOperations implements CatalogOperations, SupportsSchemas
NameIdentifier[] schemas =
clientPool.run(
c ->
- c.getAllDatabases().stream()
+ c.getAllDatabases(catalogName).stream()
.map(db -> NameIdentifier.of(namespace, db))
.toArray(NameIdentifier[]::new));
return schemas;
-
- } catch (TException e) {
- throw new RuntimeException(
- "Failed to list all schemas (database) under namespace : "
- + namespace
- + " in Hive Metastore",
- e);
-
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
@@ -363,31 +228,26 @@ public class HiveCatalogOperations implements CatalogOperations, SupportsSchemas
HiveSchema.builder()
.withName(ident.name())
.withComment(comment)
+ .withCatalogName(catalogName)
.withProperties(properties)
.withAuditInfo(
AuditInfo.builder()
- .withCreator(UserGroupInformation.getCurrentUser().getUserName())
+ .withCreator(PrincipalUtils.getCurrentUserName())
.withCreateTime(Instant.now())
.build())
.build();
clientPool.run(
client -> {
- client.createDatabase(hiveSchema.toHiveDB());
+ client.createDatabase(hiveSchema);
return null;
});
LOG.info("Created Hive schema (database) {} in Hive Metastore", ident.name());
return hiveSchema;
- } catch (AlreadyExistsException e) {
- throw new SchemaAlreadyExistsException(
- e, "Hive schema (database) '%s' already exists in Hive Metastore", ident.name());
-
- } catch (TException e) {
- throw new RuntimeException(
- "Failed to create Hive schema (database) " + ident.name() + " in Hive Metastore", e);
-
+ } catch (NoSuchCatalogException | SchemaAlreadyExistsException ne) {
+ throw ne;
} catch (Exception e) {
throw new RuntimeException(e);
}
@@ -403,20 +263,12 @@ public class HiveCatalogOperations implements CatalogOperations, SupportsSchemas
@Override
public HiveSchema loadSchema(NameIdentifier ident) throws NoSuchSchemaException {
try {
- Database database = clientPool.run(client -> client.getDatabase(ident.name()));
- HiveSchema hiveSchema = HiveSchema.fromHiveDB(database);
+ HiveSchema database = clientPool.run(client -> client.getDatabase(catalogName, ident.name()));
LOG.info("Loaded Hive schema (database) {} from Hive Metastore ", ident.name());
- return hiveSchema;
-
- } catch (NoSuchObjectException | UnknownDBException e) {
- throw new NoSuchSchemaException(
- e, "Hive schema (database) does not exist: %s in Hive Metastore", ident.name());
-
- } catch (TException e) {
- throw new RuntimeException(
- "Failed to load Hive schema (database) " + ident.name() + " from Hive Metastore", e);
-
+ return database;
+ } catch (NoSuchEntityException e) {
+ throw new NoSuchSchemaException("Schema %s does not exist", ident.name());
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
@@ -435,8 +287,8 @@ public class HiveCatalogOperations implements CatalogOperations, SupportsSchemas
throws NoSuchSchemaException {
try {
// load the database parameters
- Database database = clientPool.run(client -> client.getDatabase(ident.name()));
- Map<String, String> properties = HiveSchema.buildSchemaProperties(database);
+ HiveSchema database = clientPool.run(client -> client.getDatabase(catalogName, ident.name()));
+ Map<String, String> properties = database.properties();
if (LOG.isDebugEnabled()) {
LOG.debug(
"Loaded properties for Hive schema (database) {} found {}",
@@ -457,28 +309,16 @@ public class HiveCatalogOperations implements CatalogOperations, SupportsSchemas
}
}
- // alter the Hive database parameters
- Database alteredDatabase = database.deepCopy();
- alteredDatabase.setParameters(properties);
-
clientPool.run(
client -> {
- client.alterDatabase(ident.name(), alteredDatabase);
+ client.alterDatabase(catalogName, ident.name(), database);
return null;
});
LOG.info("Altered Hive schema (database) {} in Hive Metastore", ident.name());
- return HiveSchema.fromHiveDB(alteredDatabase);
-
- } catch (NoSuchObjectException e) {
- throw new NoSuchSchemaException(
- e, "Hive schema (database) %s does not exist in Hive Metastore", ident.name());
-
- } catch (TException | InterruptedException e) {
- throw new RuntimeException(
- "Failed to alter Hive schema (database) " + ident.name() + " in Hive metastore", e);
+ return database;
- } catch (Exception e) {
+ } catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
@@ -496,25 +336,15 @@ public class HiveCatalogOperations implements CatalogOperations, SupportsSchemas
try {
clientPool.run(
client -> {
- client.dropDatabase(ident.name(), false, false, cascade);
+ client.dropDatabase(catalogName, ident.name(), cascade);
return null;
});
LOG.info("Dropped Hive schema (database) {}", ident.name());
return true;
- } catch (InvalidOperationException e) {
- throw new NonEmptySchemaException(
- e, "Hive schema (database) %s is not empty. One or more tables exist.", ident.name());
-
- } catch (NoSuchObjectException e) {
- LOG.warn("Hive schema (database) {} does not exist in Hive Metastore", ident.name());
+ } catch (NoSuchSchemaException e) {
return false;
-
- } catch (TException e) {
- throw new RuntimeException(
- "Failed to drop Hive schema (database) " + ident.name() + " in Hive Metastore", e);
-
- } catch (Exception e) {
+ } catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
@@ -545,7 +375,7 @@ public class HiveCatalogOperations implements CatalogOperations, SupportsSchemas
// first time is to retrieve all types of table names (including the missing type tables), and
// then based on
// those names we can obtain metadata for each individual table and get the type we needed.
- List<String> allTables = clientPool.run(c -> c.getAllTables(schemaIdent.name()));
+ List<String> allTables = clientPool.run(c -> c.getAllTables(catalogName, schemaIdent.name()));
if (!listAllTables) {
// The reason for using the listTableNamesByFilter function is that the
// getTableObjectiesByName function has poor performance. Currently, we focus on the
@@ -556,42 +386,30 @@ public class HiveCatalogOperations implements CatalogOperations, SupportsSchemas
clientPool.run(
c ->
c.listTableNamesByFilter(
- schemaIdent.name(), icebergAndPaimonFilter, MAX_TABLES));
+ catalogName, schemaIdent.name(), icebergAndPaimonFilter, MAX_TABLES));
allTables.removeAll(icebergAndPaimonTables);
// filter out the Hudi tables
- String hudiFilter =
- String.format(
- "%sprovider like \"hudi\"", hive_metastoreConstants.HIVE_FILTER_FIELD_PARAMS);
+ String hudiFilter = String.format("%sprovider like \"hudi\"", HIVE_FILTER_FIELD_PARAMS);
List<String> hudiTables =
clientPool.run(
- c -> c.listTableNamesByFilter(schemaIdent.name(), hudiFilter, MAX_TABLES));
+ c ->
+ c.listTableNamesByFilter(
+ catalogName, schemaIdent.name(), hudiFilter, MAX_TABLES));
removeHudiTables(allTables, hudiTables);
}
return allTables.stream()
.map(tbName -> NameIdentifier.of(namespace, tbName))
.toArray(NameIdentifier[]::new);
- } catch (UnknownDBException e) {
- throw new NoSuchSchemaException(
- "Schema (database) does not exist %s in Hive Metastore", namespace);
-
- } catch (TException e) {
- throw new RuntimeException(
- "Failed to list all tables under the namespace : " + namespace + " in Hive Metastore", e);
-
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
private static String getIcebergAndPaimonFilter() {
- String icebergFilter =
- String.format(
- "%stable_type like \"ICEBERG\"", hive_metastoreConstants.HIVE_FILTER_FIELD_PARAMS);
- String paimonFilter =
- String.format(
- "%stable_type like \"PAIMON\"", hive_metastoreConstants.HIVE_FILTER_FIELD_PARAMS);
+ String icebergFilter = String.format("%stable_type like \"ICEBERG\"", HIVE_FILTER_FIELD_PARAMS);
+ String paimonFilter = String.format("%stable_type like \"PAIMON\"", HIVE_FILTER_FIELD_PARAMS);
return String.format("%s or %s", icebergFilter, paimonFilter);
}
@@ -614,30 +432,21 @@ public class HiveCatalogOperations implements CatalogOperations, SupportsSchemas
*/
@Override
public Table loadTable(NameIdentifier tableIdent) throws NoSuchTableException {
- org.apache.hadoop.hive.metastore.api.Table table = loadHiveTable(tableIdent);
- HiveTable hiveTable =
- HiveTable.fromHiveTable(table)
- .withProxyPlugin(proxyPlugin)
- .withClientPool(clientPool)
- .build();
+ HiveTableHandle hiveTable = loadHiveTable(tableIdent);
LOG.info("Loaded Hive table {} from Hive Metastore ", tableIdent.name());
return hiveTable;
}
- private org.apache.hadoop.hive.metastore.api.Table loadHiveTable(NameIdentifier tableIdent) {
+ private HiveTableHandle loadHiveTable(NameIdentifier tableIdent) {
NameIdentifier schemaIdent = NameIdentifier.of(tableIdent.namespace().levels());
try {
- org.apache.hadoop.hive.metastore.api.Table table =
- clientPool.run(c -> c.getTable(schemaIdent.name(), tableIdent.name()));
- return table;
+ HiveTable table =
+ clientPool.run(c -> c.getTable(catalogName, schemaIdent.name(), tableIdent.name()));
+ return new HiveTableHandle(table, clientPool);
- } catch (NoSuchObjectException e) {
- throw new NoSuchTableException(
- e, "Hive table does not exist: %s in Hive Metastore", tableIdent.name());
-
- } catch (InterruptedException | TException e) {
+ } catch (InterruptedException e) {
throw new RuntimeException(
"Failed to load Hive table " + tableIdent.name() + " from Hive metastore", e);
}
@@ -664,12 +473,10 @@ public class HiveCatalogOperations implements CatalogOperations, SupportsSchemas
}
}
- private void validateColumnChangeForAlter(
- TableChange[] changes, org.apache.hadoop.hive.metastore.api.Table hiveTable) {
- Set<String> partitionFields =
- hiveTable.getPartitionKeys().stream().map(FieldSchema::getName).collect(Collectors.toSet());
+ private void validateColumnChangeForAlter(TableChange[] changes, HiveTable hiveTable) {
+ Set<String> partitionFields = new HashSet<>(hiveTable.partitionFieldNames());
Set<String> existingFields =
- hiveTable.getSd().getCols().stream().map(FieldSchema::getName).collect(Collectors.toSet());
+ Arrays.stream(hiveTable.columns()).map(Column::name).collect(Collectors.toSet());
existingFields.addAll(partitionFields);
Arrays.stream(changes)
@@ -788,38 +595,30 @@ public class HiveCatalogOperations implements CatalogOperations, SupportsSchemas
HiveTable hiveTable =
HiveTable.builder()
.withName(tableIdent.name())
- .withSchemaName(schemaIdent.name())
- .withClientPool(clientPool)
+ .withCatalogName(catalogName)
+ .withDatabaseName(schemaIdent.name())
.withComment(comment)
.withColumns(columns)
.withProperties(properties)
.withDistribution(distribution)
.withSortOrders(sortOrders)
- .withProxyPlugin(proxyPlugin)
.withAuditInfo(
AuditInfo.builder()
- .withCreator(UserGroupInformation.getCurrentUser().getUserName())
+ .withCreator(PrincipalUtils.getCurrentUserName())
.withCreateTime(Instant.now())
.build())
.withPartitioning(partitioning)
.build();
clientPool.run(
c -> {
- c.createTable(hiveTable.toHiveTable(propertiesMetadata.tablePropertiesMetadata()));
+ c.createTable(hiveTable);
return null;
});
LOG.info("Created Hive table {} in Hive Metastore", tableIdent.name());
- return hiveTable;
+ return new HiveTableHandle(hiveTable, clientPool);
- } catch (AlreadyExistsException e) {
- throw new TableAlreadyExistsException(e, "Table already exists: %s", tableIdent.name());
- } catch (TException | InterruptedException e) {
- throw new RuntimeException(
- "Failed to create Hive table " + tableIdent.name() + " in Hive Metastore", e);
- } catch (RuntimeException e) {
- throw e;
- } catch (Exception e) {
+ } catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
@@ -845,57 +644,31 @@ public class HiveCatalogOperations implements CatalogOperations, SupportsSchemas
try {
// TODO(@Minghuang): require a table lock to avoid race condition
- HiveTable table = (HiveTable) loadTable(tableIdent);
- org.apache.hadoop.hive.metastore.api.Table alteredHiveTable =
- table.toHiveTable(propertiesMetadata.tablePropertiesMetadata());
+ HiveTableHandle tableHandle = (HiveTableHandle) loadTable(tableIdent);
+ HiveTable currentTable = tableHandle.table();
+ validateColumnChangeForAlter(changes, currentTable);
- validateColumnChangeForAlter(changes, alteredHiveTable);
+ String newTableName = currentTable.name();
+ String newComment = currentTable.comment();
+ Map<String, String> updatedProperties = new HashMap<>(currentTable.properties());
+ List<Column> updatedColumns = new ArrayList<>(Arrays.asList(currentTable.columns()));
for (TableChange change : changes) {
- // Table change
if (change instanceof TableChange.RenameTable) {
- doRenameTable(alteredHiveTable, (TableChange.RenameTable) change);
-
+ TableChange.RenameTable rename = (TableChange.RenameTable) change;
+ Preconditions.checkArgument(
+ rename.getNewSchemaName().isEmpty(), "Does not support rename schema yet");
+ newTableName = rename.getNewName();
} else if (change instanceof TableChange.UpdateComment) {
- doUpdateComment(alteredHiveTable, (TableChange.UpdateComment) change);
-
+ newComment = ((TableChange.UpdateComment) change).getNewComment();
} else if (change instanceof TableChange.SetProperty) {
- doSetProperty(alteredHiveTable, (TableChange.SetProperty) change);
-
+ TableChange.SetProperty setProperty = (TableChange.SetProperty) change;
+ updatedProperties.put(setProperty.getProperty(), setProperty.getValue());
} else if (change instanceof TableChange.RemoveProperty) {
- doRemoveProperty(alteredHiveTable, (TableChange.RemoveProperty) change);
-
+ TableChange.RemoveProperty removeProperty = (TableChange.RemoveProperty) change;
+ updatedProperties.remove(removeProperty.getProperty());
} else if (change instanceof TableChange.ColumnChange) {
- // Column change
- StorageDescriptor sd = alteredHiveTable.getSd();
- List<FieldSchema> cols = sd.getCols();
-
- if (change instanceof TableChange.AddColumn) {
- TableChange.AddColumn addColumn = (TableChange.AddColumn) change;
- doAddColumn(cols, addColumn);
-
- } else if (change instanceof TableChange.DeleteColumn) {
- doDeleteColumn(cols, (TableChange.DeleteColumn) change);
-
- } else if (change instanceof TableChange.RenameColumn) {
- doRenameColumn(cols, (TableChange.RenameColumn) change);
-
- } else if (change instanceof TableChange.UpdateColumnComment) {
- doUpdateColumnComment(cols, (TableChange.UpdateColumnComment) change);
-
- } else if (change instanceof TableChange.UpdateColumnPosition) {
- doUpdateColumnPosition(cols, (TableChange.UpdateColumnPosition) change);
-
- } else if (change instanceof TableChange.UpdateColumnType) {
- doUpdateColumnType(cols, (TableChange.UpdateColumnType) change);
-
- } else if (change instanceof TableChange.UpdateColumnAutoIncrement) {
- throw new IllegalArgumentException(
- "Hive does not support altering column auto increment");
- } else {
- throw new IllegalArgumentException(
- "Unsupported column change type: " + change.getClass().getSimpleName());
- }
+ applyColumnChange(updatedColumns, (TableChange.ColumnChange) change);
} else {
throw new IllegalArgumentException(
"Unsupported table change type: "
@@ -903,21 +676,22 @@ public class HiveCatalogOperations implements CatalogOperations, SupportsSchemas
}
}
+ HiveTable updatedTable =
+ buildAlteredHiveTable(
+ currentTable, newTableName, newComment, updatedProperties, updatedColumns);
+
+ HiveTable finalUpdatedTable = updatedTable;
clientPool.run(
c -> {
- c.alter_table(schemaIdent.name(), tableIdent.name(), alteredHiveTable);
+ c.alterTable(catalogName, schemaIdent.name(), tableIdent.name(), finalUpdatedTable);
return null;
});
LOG.info("Altered Hive table {} in Hive Metastore", tableIdent.name());
- return HiveTable.fromHiveTable(alteredHiveTable)
- .withProxyPlugin(proxyPlugin)
- .withClientPool(clientPool)
- .build();
-
- } catch (TException | InterruptedException e) {
- if (e.getMessage() != null
- && e.getMessage().contains("types incompatible with the existing columns")) {
+ return new HiveTableHandle(updatedTable, clientPool);
+
+ } catch (IllegalArgumentException e) {
+ if (e.getMessage().contains("types incompatible with the existing columns")) {
throw new IllegalArgumentException(
"Failed to alter Hive table ["
+ tableIdent.name()
@@ -927,18 +701,65 @@ public class HiveCatalogOperations implements CatalogOperations, SupportsSchemas
+ "otherwise the alter operation will fail in Hive metastore.",
e);
}
- throw new RuntimeException(
- "Failed to alter Hive table " + tableIdent.name() + " in Hive metastore", e);
- } catch (IllegalArgumentException | NoSuchTableException e) {
throw e;
- } catch (Exception e) {
+ } catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
- private int columnPosition(List<FieldSchema> columns, TableChange.ColumnPosition position) {
- Preconditions.checkArgument(position != null, "Column position cannot be null");
- if (position instanceof TableChange.After) {
+ private HiveTable buildAlteredHiveTable(
+ HiveTable original,
+ String tableName,
+ String comment,
+ Map<String, String> properties,
+ List<Column> columns) {
+ HiveTable.Builder builder =
+ HiveTable.builder()
+ .withName(tableName)
+ .withColumns(columns.toArray(new Column[0]))
+ .withProperties(properties)
+ .withAuditInfo(original.auditInfo())
+ .withDistribution(original.distribution())
+ .withSortOrders(original.sortOrder())
+ .withPartitioning(original.partitioning())
+ .withCatalogName(original.catalogName())
+ .withDatabaseName(original.databaseName());
+
+ if (comment != null) {
+ builder.withComment(comment);
+ }
+ return builder.build();
+ }
+
+ private void applyColumnChange(List<Column> columns, TableChange.ColumnChange change) {
+ if (change instanceof TableChange.AddColumn) {
+ doAddColumn(columns, (TableChange.AddColumn) change);
+ } else if (change instanceof TableChange.DeleteColumn) {
+ doDeleteColumn(columns, (TableChange.DeleteColumn) change);
+ } else if (change instanceof TableChange.RenameColumn) {
+ doRenameColumn(columns, (TableChange.RenameColumn) change);
+ } else if (change instanceof TableChange.UpdateColumnComment) {
+ doUpdateColumnComment(columns, (TableChange.UpdateColumnComment) change);
+ } else if (change instanceof TableChange.UpdateColumnPosition) {
+ doUpdateColumnPosition(columns, (TableChange.UpdateColumnPosition) change);
+ } else if (change instanceof TableChange.UpdateColumnType) {
+ doUpdateColumnType(columns, (TableChange.UpdateColumnType) change);
+ } else if (change instanceof TableChange.UpdateColumnDefaultValue) {
+ doUpdateColumnDefaultValue(columns, (TableChange.UpdateColumnDefaultValue) change);
+ } else if (change instanceof TableChange.UpdateColumnNullability) {
+ doUpdateColumnNullability(columns, (TableChange.UpdateColumnNullability) change);
+ } else if (change instanceof TableChange.UpdateColumnAutoIncrement) {
+ throw new IllegalArgumentException("Hive does not support altering column auto increment");
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported column change type: " + change.getClass().getSimpleName());
+ }
+ }
+
+ private int columnPosition(List<Column> columns, TableChange.ColumnPosition position) {
+ if (position == null || position instanceof TableChange.Default) {
+ return columns.size();
+ } else if (position instanceof TableChange.After) {
String afterColumn = ((TableChange.After) position).getColumn();
int indexOfColumn = indexOfColumn(columns, afterColumn);
Preconditions.checkArgument(indexOfColumn != -1, "Column does not exist: " + afterColumn);
@@ -951,114 +772,141 @@ public class HiveCatalogOperations implements CatalogOperations, SupportsSchemas
}
}
- /**
- * Returns the index of a column in the given list of FieldSchema objects, based on the field
- * name.
- *
- * @param columns The list of Hive columns.
- * @param fieldName The name of the field to be searched.
- * @return The index of the column if found, otherwise -1.
- */
- private int indexOfColumn(List<FieldSchema> columns, String fieldName) {
- return columns.stream()
- .map(FieldSchema::getName)
- .collect(Collectors.toList())
- .indexOf(fieldName);
- }
-
- private void doRenameTable(
- org.apache.hadoop.hive.metastore.api.Table hiveTable, TableChange.RenameTable change) {
- Preconditions.checkArgument(
- !change.getNewSchemaName().isPresent(), "Does not support rename schema yet");
- hiveTable.setTableName(change.getNewName());
- }
-
- private void doUpdateComment(
- org.apache.hadoop.hive.metastore.api.Table hiveTable, TableChange.UpdateComment change) {
- Map<String, String> parameters = hiveTable.getParameters();
- parameters.put(COMMENT, change.getNewComment());
- }
-
- private void doSetProperty(
- org.apache.hadoop.hive.metastore.api.Table hiveTable, TableChange.SetProperty change) {
- Map<String, String> parameters = hiveTable.getParameters();
- parameters.put(change.getProperty(), change.getValue());
- }
-
- private void doRemoveProperty(
- org.apache.hadoop.hive.metastore.api.Table hiveTable, TableChange.RemoveProperty change) {
- Map<String, String> parameters = hiveTable.getParameters();
- parameters.remove(change.getProperty());
+ private int indexOfColumn(List<Column> columns, String fieldName) {
+ for (int i = 0; i < columns.size(); i++) {
+ if (columns.get(i).name().equals(fieldName)) {
+ return i;
+ }
+ }
+ return -1;
}
- private void doAddColumn(List<FieldSchema> cols, TableChange.AddColumn change) {
- int targetPosition;
+ private void doAddColumn(List<Column> columns, TableChange.AddColumn change) {
+ String columnName = topLevelFieldName(change.getFieldName());
if (change.isAutoIncrement()) {
throw new IllegalArgumentException("Hive catalog does not support auto-increment column");
}
- if (change.getPosition() instanceof TableChange.Default) {
- // add to the end by default
- targetPosition = cols.size();
- LOG.info(
- "Hive catalog add column {} to the end of non-partition columns by default",
- change.fieldName()[0]);
- } else {
- targetPosition = columnPosition(cols, change.getPosition());
- }
- cols.add(
+ Preconditions.checkArgument(
+ indexOfColumn(columns, columnName) == -1, "Column already exists: " + columnName);
+ int targetPosition = columnPosition(columns, change.getPosition());
+ columns.add(
targetPosition,
- new FieldSchema(
- change.fieldName()[0],
- CONVERTER.fromGravitino(change.getDataType()).getQualifiedName(),
- change.getComment()));
- }
-
- private void doDeleteColumn(List<FieldSchema> cols, TableChange.DeleteColumn change) {
- String columnName = change.fieldName()[0];
- if (!cols.removeIf(c -> c.getName().equals(columnName)) && !change.getIfExists()) {
- throw new IllegalArgumentException("DeleteColumn does not exist: " + columnName);
+ Column.of(
+ columnName,
+ change.getDataType(),
+ change.getComment(),
+ change.isNullable(),
+ change.isAutoIncrement(),
+ defaultValueOrUnset(change.getDefaultValue())));
+ }
+
+ private void doDeleteColumn(List<Column> columns, TableChange.DeleteColumn change) {
+ String columnName = topLevelFieldName(change.fieldName());
+ int index = indexOfColumn(columns, columnName);
+ if (index == -1) {
+ if (!change.getIfExists()) {
+ throw new IllegalArgumentException("DeleteColumn does not exist: " + columnName);
+ }
+ return;
}
+ columns.remove(index);
}
- private void doRenameColumn(List<FieldSchema> cols, TableChange.RenameColumn change) {
- String columnName = change.fieldName()[0];
- if (indexOfColumn(cols, columnName) == -1) {
+ private void doRenameColumn(List<Column> columns, TableChange.RenameColumn change) {
+ String columnName = topLevelFieldName(change.fieldName());
+ int index = indexOfColumn(columns, columnName);
+ if (index == -1) {
throw new IllegalArgumentException("RenameColumn does not exist: " + columnName);
}
-
String newName = change.getNewName();
- if (indexOfColumn(cols, newName) != -1) {
- throw new IllegalArgumentException("Column already exists: " + newName);
- }
- cols.get(indexOfColumn(cols, columnName)).setName(newName);
+ Preconditions.checkArgument(
+ indexOfColumn(columns, newName) == -1, "Column already exists: " + newName);
+ Column existing = columns.get(index);
+ columns.set(index, rebuildColumn(existing, newName, null, null, null, null, null));
}
- private void doUpdateColumnComment(
- List<FieldSchema> cols, TableChange.UpdateColumnComment change) {
- cols.get(indexOfColumn(cols, change.fieldName()[0])).setComment(change.getNewComment());
+ private void doUpdateColumnComment(List<Column> columns, TableChange.UpdateColumnComment change) {
+ int index = indexOfColumn(columns, topLevelFieldName(change.fieldName()));
+ if (index == -1) {
+ throw new IllegalArgumentException(
+ "UpdateColumnComment does not exist: " + change.fieldName()[0]);
+ }
+ Column existing = columns.get(index);
+ columns.set(
+ index, rebuildColumn(existing, null, null, change.getNewComment(), null, null, null));
}
private void doUpdateColumnPosition(
- List<FieldSchema> cols, TableChange.UpdateColumnPosition change) {
- String columnName = change.fieldName()[0];
- int sourceIndex = indexOfColumn(cols, columnName);
+ List<Column> columns, TableChange.UpdateColumnPosition change) {
+ String columnName = topLevelFieldName(change.fieldName());
+ int sourceIndex = indexOfColumn(columns, columnName);
if (sourceIndex == -1) {
throw new IllegalArgumentException("UpdateColumnPosition does not exist: " + columnName);
}
-
- // update column position: remove then add to given position
- FieldSchema hiveColumn = cols.remove(sourceIndex);
- cols.add(columnPosition(cols, change.getPosition()), hiveColumn);
+ Column column = columns.remove(sourceIndex);
+ int targetIndex = columnPosition(columns, change.getPosition());
+ columns.add(targetIndex, column);
}
- private void doUpdateColumnType(List<FieldSchema> cols, TableChange.UpdateColumnType change) {
- String columnName = change.fieldName()[0];
- int indexOfColumn = indexOfColumn(cols, columnName);
- if (indexOfColumn == -1) {
+ private void doUpdateColumnType(List<Column> columns, TableChange.UpdateColumnType change) {
+ String columnName = topLevelFieldName(change.getFieldName());
+ int index = indexOfColumn(columns, columnName);
+ if (index == -1) {
throw new IllegalArgumentException("UpdateColumnType does not exist: " + columnName);
}
- cols.get(indexOfColumn)
- .setType(CONVERTER.fromGravitino(change.getNewDataType()).getQualifiedName());
+ Column existing = columns.get(index);
+ columns.set(
+ index, rebuildColumn(existing, null, change.getNewDataType(), null, null, null, null));
+ }
+
+ private void doUpdateColumnDefaultValue(
+ List<Column> columns, TableChange.UpdateColumnDefaultValue change) {
+ String columnName = topLevelFieldName(change.fieldName());
+ int index = indexOfColumn(columns, columnName);
+ if (index == -1) {
+ throw new IllegalArgumentException("UpdateColumnDefaultValue does not exist: " + columnName);
+ }
+ Column existing = columns.get(index);
+ columns.set(
+ index, rebuildColumn(existing, null, null, null, null, null, change.getNewDefaultValue()));
+ }
+
+ private void doUpdateColumnNullability(
+ List<Column> columns, TableChange.UpdateColumnNullability change) {
+ String columnName = topLevelFieldName(change.fieldName());
+ int index = indexOfColumn(columns, columnName);
+ if (index == -1) {
+ throw new IllegalArgumentException("UpdateColumnNullability does not exist: " + columnName);
+ }
+ Column existing = columns.get(index);
+ columns.set(index, rebuildColumn(existing, null, null, null, change.nullable(), null, null));
+ }
+
+ private Column rebuildColumn(
+ Column existing,
+ String name,
+ Type dataType,
+ String comment,
+ Boolean nullable,
+ Boolean autoIncrement,
+ Expression defaultValue) {
+ return Column.of(
+ name != null ? name : existing.name(),
+ dataType != null ? dataType : existing.dataType(),
+ comment != null ? comment : existing.comment(),
+ nullable != null ? nullable : existing.nullable(),
+ autoIncrement != null ? autoIncrement : existing.autoIncrement(),
+ defaultValue != null ? defaultValue : existing.defaultValue());
+ }
+
+ private Expression defaultValueOrUnset(Expression defaultValue) {
+ return defaultValue == null ? Column.DEFAULT_VALUE_NOT_SET : defaultValue;
+ }
+
+ private String topLevelFieldName(String[] fieldName) {
+ Preconditions.checkArgument(
+ fieldName.length == 1, "Hive catalog only supports top-level column operations");
+ return fieldName[0];
}
/**
@@ -1120,7 +968,9 @@ public class HiveCatalogOperations implements CatalogOperations, SupportsSchemas
String comment,
Map<String, String> properties) {
try {
- clientPool.run(IMetaStoreClient::getAllDatabases);
+ clientPool.run(c -> c.getAllDatabases(catalogName));
+ } catch (ConnectionFailedException e) {
+ throw e;
} catch (Exception e) {
throw new ConnectionFailedException(
e, "Failed to run getAllDatabases in Hive Metastore: %s", e.getMessage());
@@ -1141,20 +991,16 @@ public class HiveCatalogOperations implements CatalogOperations, SupportsSchemas
try {
clientPool.run(
c -> {
- c.dropTable(schemaIdent.name(), tableIdent.name(), deleteData, false, ifPurge);
+ c.dropTable(catalogName, schemaIdent.name(), tableIdent.name(), deleteData, ifPurge);
return null;
});
LOG.info("Dropped Hive table {}", tableIdent.name());
return true;
- } catch (NoSuchObjectException e) {
- LOG.warn("Hive table {} does not exist in Hive Metastore", tableIdent.name());
+ } catch (NoSuchTableException e) {
return false;
- } catch (TException | InterruptedException e) {
- throw new RuntimeException(
- "Failed to drop Hive table " + tableIdent.name() + " in Hive Metastore", e);
- } catch (Exception e) {
+ } catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
@@ -1163,24 +1009,12 @@ public class HiveCatalogOperations implements CatalogOperations, SupportsSchemas
return clientPool;
}
- HiveConf getHiveConf() {
- return hiveConf;
- }
-
private boolean isExternalTable(NameIdentifier tableIdent) {
- org.apache.hadoop.hive.metastore.api.Table hiveTable = loadHiveTable(tableIdent);
+ HiveTableHandle hiveTable = loadHiveTable(tableIdent);
return EXTERNAL_TABLE.name().equalsIgnoreCase(hiveTable.getTableType());
}
private static ThreadFactory getThreadFactory(String factoryName) {
return new ThreadFactoryBuilder().setDaemon(true).setNameFormat(factoryName + "-%d").build();
}
-
- public String getKerberosRealm() {
- return kerberosRealm;
- }
-
- void setProxyPlugin(HiveProxyPlugin hiveProxyPlugin) {
- this.proxyPlugin = hiveProxyPlugin;
- }
}
diff --git a/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveCatalogPropertiesMetadata.java b/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveCatalogPropertiesMetadata.java
index 8897d77051..c316b1b72e 100644
--- a/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveCatalogPropertiesMetadata.java
+++ b/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveCatalogPropertiesMetadata.java
@@ -19,6 +19,8 @@
package org.apache.gravitino.catalog.hive;
+import static org.apache.gravitino.catalog.hive.HiveConstants.HIVE_DEFAULT_CATALOG;
+
import com.google.common.collect.ImmutableMap;
import java.util.Map;
import org.apache.gravitino.connector.BaseCatalogPropertiesMetadata;
@@ -29,6 +31,7 @@ public class HiveCatalogPropertiesMetadata extends BaseCatalogPropertiesMetadata
public static final String CLIENT_POOL_SIZE = HiveConstants.CLIENT_POOL_SIZE;
public static final String METASTORE_URIS = HiveConstants.METASTORE_URIS;
+ public static final String DEFAULT_CATALOG = HiveConstants.DEFAULT_CATALOG;
public static final String CLIENT_POOL_CACHE_EVICTION_INTERVAL_MS =
HiveConstants.CLIENT_POOL_CACHE_EVICTION_INTERVAL_MS;
@@ -61,6 +64,14 @@ public class HiveCatalogPropertiesMetadata extends BaseCatalogPropertiesMetadata
"The Hive metastore URIs",
false /* immutable */,
false /* hidden */))
+ .put(
+ DEFAULT_CATALOG,
+ PropertyEntry.stringOptionalPropertyEntry(
+ DEFAULT_CATALOG,
+ "The default Hive Metastore catalog name used when talking to HMS",
+ true /* immutable */,
+ HIVE_DEFAULT_CATALOG,
+ false /* hidden */))
.put(
IMPERSONATION_ENABLE,
PropertyEntry.booleanPropertyEntry(
diff --git a/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveColumn.java b/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveColumn.java
deleted file mode 100644
index 401720f73c..0000000000
--- a/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveColumn.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.gravitino.catalog.hive;
-
-import lombok.EqualsAndHashCode;
-import org.apache.gravitino.connector.BaseColumn;
-
-/** Represents a column in an Apache Hive Metastore catalog. */
-@EqualsAndHashCode(callSuper = true)
-public class HiveColumn extends BaseColumn {
-
- private HiveColumn() {}
-
- /** A builder class for constructing HiveColumn instances. */
- public static class Builder extends BaseColumnBuilder<Builder, HiveColumn> {
-
- /** Creates a new instance of {@link Builder}. */
- private Builder() {}
-
- /**
- * Internal method to build a HiveColumn instance using the provided values.
- *
- * @return A new HiveColumn instance with the configured values.
- */
- @Override
- protected HiveColumn internalBuild() {
- HiveColumn hiveColumn = new HiveColumn();
-
- hiveColumn.name = name;
- hiveColumn.comment = comment;
- hiveColumn.dataType = dataType;
- hiveColumn.nullable = nullable;
- hiveColumn.defaultValue = defaultValue == null ? DEFAULT_VALUE_NOT_SET : defaultValue;
- return hiveColumn;
- }
- }
-
- /**
- * Creates a new instance of {@link Builder}.
- *
- * @return The new instance.
- */
- public static Builder builder() {
- return new Builder();
- }
-}
diff --git a/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveProxyPlugin.java b/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveProxyPlugin.java
deleted file mode 100644
index 760a91deb2..0000000000
--- a/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveProxyPlugin.java
+++ /dev/null
@@ -1,110 +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.gravitino.catalog.hive;
-
-import java.io.IOException;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.UndeclaredThrowableException;
-import java.security.Principal;
-import java.security.PrivilegedActionException;
-import java.security.PrivilegedExceptionAction;
-import java.util.Map;
-import org.apache.gravitino.connector.CatalogOperations;
-import org.apache.gravitino.connector.ProxyPlugin;
-import org.apache.gravitino.utils.Executable;
-import org.apache.hadoop.hive.conf.HiveConf;
-import org.apache.hadoop.hive.thrift.DelegationTokenIdentifier;
-import org.apache.hadoop.io.Text;
-import org.apache.hadoop.security.UserGroupInformation;
-import org.apache.hadoop.security.token.Token;
-
-class HiveProxyPlugin implements ProxyPlugin {
-
- private final UserGroupInformation realUser;
- private HiveCatalogOperations ops;
-
- HiveProxyPlugin() {
- try {
- realUser = UserGroupInformation.getCurrentUser();
- } catch (IOException ioe) {
- throw new IllegalStateException("Fail to init HiveCatalogProxyPlugin");
- }
- }
-
- @Override
- public Object doAs(
- Principal principal, Executable<Object, Exception> action, Map<String, String> properties)
- throws Throwable {
- try {
- UserGroupInformation proxyUser;
-
- if (UserGroupInformation.isSecurityEnabled() && ops != null) {
-
- // The Gravitino server may use multiple KDC servers.
- // The http authentication use one KDC server, the Hive catalog may use another KDC server.
- // The KerberosAuthenticator will remove realm of principal.
- // And then we add the realm of Hive catalog to the user.
- final String finalPrincipalName;
- String proxyKerberosPrincipalName = principal.getName();
- if (!proxyKerberosPrincipalName.contains("@")) {
- finalPrincipalName =
- String.format("%s@%s", proxyKerberosPrincipalName, ops.getKerberosRealm());
- } else {
- finalPrincipalName = proxyKerberosPrincipalName;
- }
-
- proxyUser = UserGroupInformation.createProxyUser(finalPrincipalName, realUser);
-
- String token =
- ops.getClientPool()
- .run(
- client -> {
- return client.getDelegationToken(finalPrincipalName, realUser.getUserName());
- });
-
- Token<DelegationTokenIdentifier> delegationToken = new Token<DelegationTokenIdentifier>();
- delegationToken.decodeFromUrlString(token);
- delegationToken.setService(
- new Text(ops.getHiveConf().getVar(HiveConf.ConfVars.METASTORE_TOKEN_SIGNATURE)));
-
- proxyUser.addToken(delegationToken);
- } else {
-
- proxyUser = UserGroupInformation.createProxyUser(principal.getName(), realUser);
- }
-
- return proxyUser.doAs((PrivilegedExceptionAction<Object>) action::execute);
- } catch (UndeclaredThrowableException e) {
- Throwable innerException = e.getCause();
- if (innerException instanceof PrivilegedActionException) {
- throw innerException.getCause();
- } else if (innerException instanceof InvocationTargetException) {
- throw innerException.getCause();
- } else {
- throw innerException;
- }
- }
- }
-
- @Override
- public void bindCatalogOperation(CatalogOperations ops) {
- this.ops = ((HiveCatalogOperations) ops);
- this.ops.setProxyPlugin(this);
- }
-}
diff --git a/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveSchema.java b/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveSchema.java
deleted file mode 100644
index 29acce0461..0000000000
--- a/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveSchema.java
+++ /dev/null
@@ -1,123 +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.gravitino.catalog.hive;
-
-import com.google.common.collect.Maps;
-import java.util.Map;
-import java.util.Optional;
-import lombok.ToString;
-import org.apache.gravitino.connector.BaseSchema;
-import org.apache.gravitino.meta.AuditInfo;
-import org.apache.hadoop.hive.metastore.api.Database;
-import org.apache.hadoop.hive.metastore.api.PrincipalType;
-
-/** Represents an Apache Hive Schema (Database) entity in the Hive Metastore catalog. */
-@ToString
-public class HiveSchema extends BaseSchema {
- private HiveSchema() {}
-
- /**
- * Creates a new HiveSchema instance from a Database and a Builder.
- *
- * @param db The Database representing the HiveSchema.
- * @return A new HiveSchema instance.
- */
- public static HiveSchema fromHiveDB(Database db) {
- Map<String, String> properties = buildSchemaProperties(db);
-
- // Get audit info from Hive's Database object. Because Hive's database doesn't store create
- // time, last modifier and last modified time, we only get creator from Hive's database.
- AuditInfo.Builder auditInfoBuilder = AuditInfo.builder();
- Optional.ofNullable(db.getOwnerName()).ifPresent(auditInfoBuilder::withCreator);
-
- return HiveSchema.builder()
- .withName(db.getName())
- .withComment(db.getDescription())
- .withProperties(properties)
- .withAuditInfo(auditInfoBuilder.build())
- .build();
- }
-
- /**
- * Build schema properties from a Hive Database object.
- *
- * @param database The Hive Database object.
- * @return A map of schema properties.
- */
- public static Map<String, String> buildSchemaProperties(Database database) {
- Map<String, String> properties = Maps.newHashMap(database.getParameters());
- properties.put(HiveSchemaPropertiesMetadata.LOCATION, database.getLocationUri());
- return properties;
- }
-
- /**
- * Converts this HiveSchema to its corresponding Database.
- *
- * @return The converted Database object.
- */
- public Database toHiveDB() {
- Database hiveDb = new Database();
-
- hiveDb.setName(name());
- Optional.ofNullable(properties().get(HiveSchemaPropertiesMetadata.LOCATION))
- .ifPresent(hiveDb::setLocationUri);
- Optional.ofNullable(comment()).ifPresent(hiveDb::setDescription);
-
- // TODO: Add more privilege info to Hive's Database object after Gravitino supports privilege.
- hiveDb.setOwnerName(auditInfo().creator());
- hiveDb.setOwnerType(PrincipalType.USER);
-
- Map<String, String> parameters = Maps.newHashMap(properties());
- parameters.remove(HiveSchemaPropertiesMetadata.LOCATION);
- hiveDb.setParameters(parameters);
-
- return hiveDb;
- }
-
- /** A builder class for constructing HiveSchema instances. */
- public static class Builder extends BaseSchemaBuilder<Builder, HiveSchema> {
-
- /** Creates a new instance of {@link Builder}. */
- private Builder() {}
-
- /**
- * Internal method to build a HiveSchema instance using the provided values.
- *
- * @return A new HiveSchema instance with the configured values.
- */
- @Override
- protected HiveSchema internalBuild() {
- HiveSchema hiveSchema = new HiveSchema();
- hiveSchema.name = name;
- hiveSchema.comment = comment;
- hiveSchema.properties = properties;
- hiveSchema.auditInfo = auditInfo;
-
- return hiveSchema;
- }
- }
- /**
- * Creates a new instance of {@link Builder}.
- *
- * @return The new instance.
- */
- public static Builder builder() {
- return new Builder();
- }
-}
diff --git a/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveSchemaPropertiesMetadata.java b/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveSchemaPropertiesMetadata.java
index 6de5e0dfd9..aaceb753b2 100644
--- a/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveSchemaPropertiesMetadata.java
+++ b/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveSchemaPropertiesMetadata.java
@@ -18,6 +18,7 @@
*/
package org.apache.gravitino.catalog.hive;
+import static org.apache.gravitino.catalog.hive.HiveConstants.LOCATION;
import static org.apache.gravitino.connector.PropertyEntry.stringOptionalPropertyEntry;
import com.google.common.collect.ImmutableList;
@@ -28,7 +29,7 @@ import org.apache.gravitino.connector.BasePropertiesMetadata;
import org.apache.gravitino.connector.PropertyEntry;
public class HiveSchemaPropertiesMetadata extends BasePropertiesMetadata {
- public static final String LOCATION = HiveConstants.LOCATION;
+
private static final Map<String, PropertyEntry<?>> propertiesMetadata;
static {
diff --git a/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveTable.java b/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveTable.java
deleted file mode 100644
index 47f97591f4..0000000000
--- a/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveTable.java
+++ /dev/null
@@ -1,387 +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.gravitino.catalog.hive;
-
-import com.google.common.collect.Maps;
-import com.google.common.collect.Sets;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-import java.util.Set;
-import java.util.stream.Collectors;
-import lombok.ToString;
-import org.apache.commons.lang3.ArrayUtils;
-import org.apache.gravitino.connector.BaseTable;
-import org.apache.gravitino.connector.PropertiesMetadata;
-import org.apache.gravitino.connector.TableOperations;
-import org.apache.gravitino.hive.CachedClientPool;
-import org.apache.gravitino.hive.converter.HiveDataTypeConverter;
-import org.apache.gravitino.hive.converter.HiveTableConverter;
-import org.apache.gravitino.meta.AuditInfo;
-import org.apache.gravitino.rel.Column;
-import org.apache.gravitino.rel.SupportsPartitions;
-import org.apache.gravitino.rel.expressions.NamedReference;
-import org.apache.gravitino.rel.expressions.distributions.Distribution;
-import org.apache.gravitino.rel.expressions.distributions.Distributions;
-import org.apache.gravitino.rel.expressions.sorts.SortDirection;
-import org.apache.gravitino.rel.expressions.sorts.SortOrder;
-import org.apache.gravitino.rel.expressions.transforms.Transform;
-import org.apache.gravitino.rel.expressions.transforms.Transforms;
-import org.apache.hadoop.hive.metastore.api.FieldSchema;
-import org.apache.hadoop.hive.metastore.api.Order;
-import org.apache.hadoop.hive.metastore.api.SerDeInfo;
-import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
-import org.apache.hadoop.hive.metastore.api.Table;
-
-/** Represents an Apache Hive Table entity in the Hive Metastore catalog. */
-@ToString
-public class HiveTable extends BaseTable {
-
- // A set of supported Hive table types.
- public static final Set<String> SUPPORT_TABLE_TYPES =
- Sets.newHashSet(TableType.MANAGED_TABLE.name(), TableType.EXTERNAL_TABLE.name());
- public static final String ICEBERG_TABLE_TYPE_VALUE = "ICEBERG";
- public static final String TABLE_TYPE_PROP = "table_type";
- private String schemaName;
- private CachedClientPool clientPool;
- private StorageDescriptor sd;
-
- private HiveTable() {}
-
- /**
- * Creates a new HiveTable instance from a Table and a Builder.
- *
- * @param table The inner Table representing the HiveTable.
- * @return A new HiveTable instance Builder.
- */
- public static HiveTable.Builder fromHiveTable(Table table) {
- AuditInfo auditInfo = HiveTableConverter.getAuditInfo(table);
-
- Distribution distribution = HiveTableConverter.getDistribution(table);
-
- SortOrder[] sortOrders = HiveTableConverter.getSortOrders(table);
-
- Column[] columns = HiveTableConverter.getColumns(table, HiveColumn.builder());
-
- Transform[] partitioning = HiveTableConverter.getPartitioning(table);
-
- return HiveTable.builder()
- .withName(table.getTableName())
- .withComment(table.getParameters().get(HiveTablePropertiesMetadata.COMMENT))
- .withProperties(buildTableProperties(table))
- .withColumns(columns)
- .withDistribution(distribution)
- .withSortOrders(sortOrders)
- .withAuditInfo(auditInfo)
- .withPartitioning(partitioning)
- .withSchemaName(table.getDbName())
- .withStorageDescriptor(table.getSd());
- }
-
- public CachedClientPool clientPool() {
- return clientPool;
- }
-
- public void close() {
- if (clientPool != null) {
- // Note: Cannot close the client pool here because the client pool is shared by catalog
- clientPool = null;
- }
- }
-
- public String schemaName() {
- return schemaName;
- }
-
- public StorageDescriptor storageDescriptor() {
- return sd;
- }
-
- private static Map<String, String> buildTableProperties(Table table) {
- Map<String, String> properties = Maps.newHashMap(table.getParameters());
-
- Optional.ofNullable(table.getTableType())
- .ifPresent(t -> properties.put(HiveTablePropertiesMetadata.TABLE_TYPE, t));
-
- StorageDescriptor sd = table.getSd();
- properties.put(HiveTablePropertiesMetadata.LOCATION, sd.getLocation());
- properties.put(HiveTablePropertiesMetadata.INPUT_FORMAT, sd.getInputFormat());
- properties.put(HiveTablePropertiesMetadata.OUTPUT_FORMAT, sd.getOutputFormat());
-
- SerDeInfo serdeInfo = sd.getSerdeInfo();
- Optional.ofNullable(serdeInfo.getName())
- .ifPresent(name -> properties.put(HiveTablePropertiesMetadata.SERDE_NAME, name));
- Optional.ofNullable(serdeInfo.getSerializationLib())
- .ifPresent(lib -> properties.put(HiveTablePropertiesMetadata.SERDE_LIB, lib));
- Optional.ofNullable(serdeInfo.getParameters())
- .ifPresent(
- p ->
- p.forEach(
- (k, v) ->
- properties.put(HiveTablePropertiesMetadata.SERDE_PARAMETER_PREFIX + k, v)));
-
- return properties;
- }
-
- /**
- * Converts this HiveTable to its corresponding Table in the Hive Metastore.
- *
- * @param tablePropertiesMetadata metadata for configuring the Hive Metastore table
- * @return The converted Table.
- */
- public Table toHiveTable(PropertiesMetadata tablePropertiesMetadata) {
- Table hiveTable = new Table();
-
- hiveTable.setTableName(name);
- hiveTable.setDbName(schemaName);
- hiveTable.setTableType(
- ((TableType)
- tablePropertiesMetadata.getOrDefault(
- properties(), HiveTablePropertiesMetadata.TABLE_TYPE))
- .name());
- List<FieldSchema> partitionFields = buildPartitionKeys();
- hiveTable.setSd(buildStorageDescriptor(tablePropertiesMetadata, partitionFields));
- hiveTable.setParameters(buildTableParameters());
- hiveTable.setPartitionKeys(partitionFields);
-
- // Set AuditInfo to Hive's Table object. Hive's Table doesn't support setting last modifier
- // and last modified time, so we only set creator and create time.
- hiveTable.setOwner(auditInfo.creator());
- hiveTable.setCreateTime(Math.toIntExact(auditInfo.createTime().getEpochSecond()));
-
- return hiveTable;
- }
-
- private Map<String, String> buildTableParameters() {
- Map<String, String> parameters = Maps.newHashMap(properties());
- Optional.ofNullable(comment)
- .ifPresent(c -> parameters.put(HiveTablePropertiesMetadata.COMMENT, c));
-
- if (TableType.EXTERNAL_TABLE
- .name()
- .equalsIgnoreCase(properties().get(HiveTablePropertiesMetadata.TABLE_TYPE))) {
- parameters.put(HiveTablePropertiesMetadata.EXTERNAL, "TRUE");
- } else {
- parameters.put(HiveTablePropertiesMetadata.EXTERNAL, "FALSE");
- }
-
- parameters.remove(HiveTablePropertiesMetadata.LOCATION);
- parameters.remove(HiveTablePropertiesMetadata.TABLE_TYPE);
- parameters.remove(HiveTablePropertiesMetadata.INPUT_FORMAT);
- parameters.remove(HiveTablePropertiesMetadata.OUTPUT_FORMAT);
- parameters.remove(HiveTablePropertiesMetadata.SERDE_NAME);
- parameters.remove(HiveTablePropertiesMetadata.SERDE_LIB);
- parameters.remove(HiveTablePropertiesMetadata.FORMAT);
- parameters
- .keySet()
- .removeIf(k -> k.startsWith(HiveTablePropertiesMetadata.SERDE_PARAMETER_PREFIX));
- return parameters;
- }
-
- public List<FieldSchema> buildPartitionKeys() {
- return Arrays.stream(partitioning)
- .map(p -> getPartitionKey(((Transforms.IdentityTransform) p).fieldName()))
- .collect(Collectors.toList());
- }
-
- private FieldSchema getPartitionKey(String[] fieldName) {
- List<Column> partitionColumns =
- Arrays.stream(columns)
- .filter(c -> c.name().equals(fieldName[0]))
- .collect(Collectors.toList());
- return new FieldSchema(
- partitionColumns.get(0).name(),
- HiveDataTypeConverter.CONVERTER
- .fromGravitino(partitionColumns.get(0).dataType())
- .getQualifiedName(),
- partitionColumns.get(0).comment());
- }
-
- private StorageDescriptor buildStorageDescriptor(
- PropertiesMetadata tablePropertiesMetadata, List<FieldSchema> partitionFields) {
- StorageDescriptor strgDesc = new StorageDescriptor();
- List<String> partitionKeys =
- partitionFields.stream().map(FieldSchema::getName).collect(Collectors.toList());
- strgDesc.setCols(
- Arrays.stream(columns)
- .filter(c -> !partitionKeys.contains(c.name()))
- .map(
- c ->
- new FieldSchema(
- c.name(),
- HiveDataTypeConverter.CONVERTER
- .fromGravitino(c.dataType())
- .getQualifiedName(),
- c.comment()))
- .collect(Collectors.toList()));
-
- // `location` must not be null, otherwise it will result in an NPE when calling HMS `alterTable`
- // interface
- Optional.ofNullable(properties().get(HiveTablePropertiesMetadata.LOCATION))
- .ifPresent(
- l -> strgDesc.setLocation(properties().get(HiveTablePropertiesMetadata.LOCATION)));
-
- strgDesc.setSerdeInfo(buildSerDeInfo(tablePropertiesMetadata));
- StorageFormat storageFormat =
- (StorageFormat)
- tablePropertiesMetadata.getOrDefault(properties(), HiveTablePropertiesMetadata.FORMAT);
- strgDesc.setInputFormat(storageFormat.getInputFormat());
- strgDesc.setOutputFormat(storageFormat.getOutputFormat());
- // Individually specified INPUT_FORMAT and OUTPUT_FORMAT can override the inputFormat and
- // outputFormat of FORMAT
- Optional.ofNullable(properties().get(HiveTablePropertiesMetadata.INPUT_FORMAT))
- .ifPresent(strgDesc::setInputFormat);
- Optional.ofNullable(properties().get(HiveTablePropertiesMetadata.OUTPUT_FORMAT))
- .ifPresent(strgDesc::setOutputFormat);
-
- if (ArrayUtils.isNotEmpty(sortOrders)) {
- for (SortOrder sortOrder : sortOrders) {
- String columnName = ((NamedReference.FieldReference) sortOrder.expression()).fieldName()[0];
- strgDesc.addToSortCols(
- new Order(columnName, sortOrder.direction() == SortDirection.ASCENDING ? 1 : 0));
- }
- }
-
- if (!Distributions.NONE.equals(distribution)) {
- strgDesc.setBucketCols(
- Arrays.stream(distribution.expressions())
- .map(t -> ((NamedReference.FieldReference) t).fieldName()[0])
- .collect(Collectors.toList()));
- strgDesc.setNumBuckets(distribution.number());
- }
-
- return strgDesc;
- }
-
- private SerDeInfo buildSerDeInfo(PropertiesMetadata tablePropertiesMetadata) {
- SerDeInfo serDeInfo = new SerDeInfo();
- serDeInfo.setName(properties().getOrDefault(HiveTablePropertiesMetadata.SERDE_NAME, name()));
-
- StorageFormat storageFormat =
- (StorageFormat)
- tablePropertiesMetadata.getOrDefault(properties(), HiveTablePropertiesMetadata.FORMAT);
- serDeInfo.setSerializationLib(storageFormat.getSerde());
- // Individually specified SERDE_LIB can override the serdeLib of FORMAT
- Optional.ofNullable(properties().get(HiveTablePropertiesMetadata.SERDE_LIB))
- .ifPresent(serDeInfo::setSerializationLib);
-
- properties().entrySet().stream()
- .filter(e -> e.getKey().startsWith(HiveTablePropertiesMetadata.SERDE_PARAMETER_PREFIX))
- .forEach(
- e ->
- serDeInfo.putToParameters(
- e.getKey()
- .substring(HiveTablePropertiesMetadata.SERDE_PARAMETER_PREFIX.length()),
- e.getValue()));
- return serDeInfo;
- }
-
- @Override
- protected TableOperations newOps() {
- return new HiveTableOperations(this);
- }
-
- @Override
- public SupportsPartitions supportPartitions() throws UnsupportedOperationException {
- return (SupportsPartitions) ops();
- }
-
- /** A builder class for constructing HiveTable instances. */
- public static class Builder extends BaseTableBuilder<Builder, HiveTable> {
-
- private String schemaName;
- private CachedClientPool clientPool;
- private StorageDescriptor sd;
-
- /**
- * Sets the Hive schema (database) name to be used for building the HiveTable.
- *
- * @param schemaName The string schema name of the HiveTable.
- * @return This Builder instance.
- */
- public Builder withSchemaName(String schemaName) {
- this.schemaName = schemaName;
- return this;
- }
-
- /**
- * Sets the StorageDescriptor to be used for adding partition.
- *
- * @param sd The StorageDescriptor instance of the HiveTable.
- * @return This Builder instance.
- */
- public Builder withStorageDescriptor(StorageDescriptor sd) {
- this.sd = sd;
- return this;
- }
-
- /**
- * Sets the HiveClientPool to be used for operate partition.
- *
- * @param clientPool The HiveClientPool instance.
- * @return This Builder instance.
- */
- public Builder withClientPool(CachedClientPool clientPool) {
- this.clientPool = clientPool;
- return this;
- }
-
- /** Creates a new instance of {@link Builder}. */
- private Builder() {}
-
- /**
- * Internal method to build a HiveTable instance using the provided values.
- *
- * @return A new HiveTable instance with the configured values.
- */
- @Override
- protected HiveTable internalBuild() {
- HiveTable hiveTable = new HiveTable();
- hiveTable.name = name;
- hiveTable.comment = comment;
- hiveTable.properties = properties != null ? Maps.newHashMap(properties) : Maps.newHashMap();
- hiveTable.auditInfo = auditInfo;
- hiveTable.columns = columns;
- hiveTable.distribution = distribution;
- hiveTable.sortOrders = sortOrders;
- hiveTable.partitioning = partitioning;
- hiveTable.schemaName = schemaName;
- hiveTable.clientPool = clientPool;
- hiveTable.sd = sd;
- hiveTable.proxyPlugin = proxyPlugin;
-
- // HMS put table comment in parameters
- if (comment != null) {
- hiveTable.properties.put(HiveTablePropertiesMetadata.COMMENT, comment);
- }
-
- return hiveTable;
- }
- }
-
- /**
- * Creates a new instance of {@link Builder}.
- *
- * @return The new instance.
- */
- public static Builder builder() {
- return new Builder();
- }
-}
diff --git a/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveTableHandle.java b/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveTableHandle.java
new file mode 100644
index 0000000000..20a78e1faf
--- /dev/null
+++ b/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveTableHandle.java
@@ -0,0 +1,76 @@
+/*
+ * 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.gravitino.catalog.hive;
+
+import static org.apache.gravitino.catalog.hive.HiveConstants.TABLE_TYPE;
+
+import lombok.ToString;
+import org.apache.gravitino.connector.BaseTable;
+import org.apache.gravitino.connector.TableOperations;
+import org.apache.gravitino.hive.CachedClientPool;
+import org.apache.gravitino.hive.HiveTable;
+import org.apache.gravitino.rel.SupportsPartitions;
+
+/** Represents an Apache Hive Table entity in the Hive Metastore catalog. */
+@ToString
+public class HiveTableHandle extends BaseTable {
+ private final HiveTable table;
+ private final CachedClientPool clientPool;
+
+ public HiveTableHandle(HiveTable hiveTable, CachedClientPool clientPool) {
+ this.table = hiveTable;
+ this.clientPool = clientPool;
+ this.name = hiveTable.name();
+ this.comment = hiveTable.comment();
+ this.properties = hiveTable.properties();
+ this.auditInfo = hiveTable.auditInfo();
+ this.columns = hiveTable.columns();
+ this.partitioning = hiveTable.partitioning();
+ this.sortOrders = hiveTable.sortOrder();
+ this.distribution = hiveTable.distribution();
+ this.indexes = hiveTable.index();
+ this.proxyPlugin = hiveTable.proxyPlugin();
+ }
+
+ public HiveTable table() {
+ return table;
+ }
+
+ public CachedClientPool clientPool() {
+ return clientPool;
+ }
+
+ @Override
+ protected TableOperations newOps() {
+ return new HiveTableOperations(this);
+ }
+
+ @Override
+ public SupportsPartitions supportPartitions() throws UnsupportedOperationException {
+ return (SupportsPartitions) ops();
+ }
+
+ public void close() {
+ clientPool.close();
+ }
+
+ public String getTableType() {
+ return properties.getOrDefault(TABLE_TYPE, "MANAGED_TABLE");
+ }
+}
diff --git a/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveTableOperations.java b/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveTableOperations.java
index a5ca0778da..5ba130a8f3 100644
--- a/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveTableOperations.java
+++ b/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveTableOperations.java
@@ -18,132 +18,79 @@
*/
package org.apache.gravitino.catalog.hive;
+import static org.apache.gravitino.hive.HivePartition.extractPartitionValues;
+
import com.google.common.base.Preconditions;
import java.io.IOException;
import java.util.Arrays;
+import java.util.HashSet;
import java.util.List;
-import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
-import java.util.stream.IntStream;
import org.apache.gravitino.MetadataObjects;
import org.apache.gravitino.connector.TableOperations;
import org.apache.gravitino.exceptions.NoSuchPartitionException;
-import org.apache.gravitino.exceptions.NoSuchTableException;
import org.apache.gravitino.exceptions.PartitionAlreadyExistsException;
+import org.apache.gravitino.hive.HivePartition;
+import org.apache.gravitino.hive.HiveTable;
import org.apache.gravitino.rel.SupportsPartitions;
-import org.apache.gravitino.rel.expressions.literals.Literal;
-import org.apache.gravitino.rel.expressions.literals.Literals;
-import org.apache.gravitino.rel.expressions.transforms.Transforms;
import org.apache.gravitino.rel.partitions.IdentityPartition;
import org.apache.gravitino.rel.partitions.Partition;
-import org.apache.gravitino.rel.partitions.Partitions;
-import org.apache.hadoop.hive.common.FileUtils;
-import org.apache.hadoop.hive.metastore.api.FieldSchema;
-import org.apache.hadoop.hive.metastore.api.NoSuchObjectException;
-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.api.UnknownTableException;
-import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HiveTableOperations implements TableOperations, SupportsPartitions {
public static final Logger LOG = LoggerFactory.getLogger(HiveTableOperations.class);
- private static final String PARTITION_NAME_DELIMITER = "/";
- private static final String PARTITION_VALUE_DELIMITER = "=";
-
- private final HiveTable table;
+ private final HiveTableHandle tableHandle;
- public HiveTableOperations(HiveTable table) {
- Preconditions.checkArgument(table != null, "table must not be null");
- this.table = table;
+ public HiveTableOperations(HiveTableHandle tableHandle) {
+ Preconditions.checkArgument(tableHandle != null, "table must not be null");
+ this.tableHandle = tableHandle;
}
@Override
public String[] listPartitionNames() {
try {
- return table
+ return tableHandle
.clientPool()
- .run(
- c ->
- c.listPartitionNames(table.schemaName(), table.name(), (short) -1)
- .toArray(new String[0]));
- } catch (TException | InterruptedException e) {
+ .run(c -> c.listPartitionNames(tableHandle.table(), (short) -1).toArray(new String[0]));
+ } catch (InterruptedException e) {
throw new RuntimeException(
- "Failed to list partition names of table " + table.name() + "from Hive Metastore", e);
+ "Failed to list partition names of table " + tableHandle.name() + "from Hive Metastore",
+ e);
}
}
@Override
public Partition[] listPartitions() {
- List<org.apache.hadoop.hive.metastore.api.Partition> partitions;
try {
- partitions =
- table
- .clientPool()
- .run(c -> c.listPartitions(table.schemaName(), table.name(), (short) -1));
- } catch (TException | InterruptedException e) {
- throw new RuntimeException(e);
+ return tableHandle
+ .clientPool()
+ .run(c -> c.listPartitions(tableHandle.table(), (short) -1))
+ .toArray(new Partition[0]);
+ } catch (InterruptedException e) {
+ throw new RuntimeException(
+ "Failed to list partitions of table " + tableHandle.name() + "from Hive Metastore", e);
}
- List<String> partCols =
- table.buildPartitionKeys().stream().map(FieldSchema::getName).collect(Collectors.toList());
-
- return partitions.stream()
- .map(
- partition ->
- fromHivePartition(
- FileUtils.makePartName(partCols, partition.getValues()), partition))
- .toArray(Partition[]::new);
}
@Override
public Partition getPartition(String partitionName) throws NoSuchPartitionException {
try {
- org.apache.hadoop.hive.metastore.api.Partition partition =
- table
- .clientPool()
- .run(c -> c.getPartition(table.schemaName(), table.name(), partitionName));
- return fromHivePartition(partitionName, partition);
+ return tableHandle.clientPool().run(c -> c.getPartition(tableHandle.table(), partitionName));
- } catch (UnknownTableException e) {
- throw new NoSuchTableException(
- e, "Hive table %s does not exist in Hive Metastore", table.name());
-
- } catch (NoSuchObjectException e) {
- throw new NoSuchPartitionException(
- e, "Hive partition %s does not exist in Hive Metastore", partitionName);
-
- } catch (TException | InterruptedException e) {
+ } catch (InterruptedException e) {
throw new RuntimeException(
"Failed to get partition "
+ partitionName
+ " of table "
- + table.name()
+ + tableHandle.name()
+ "from Hive Metastore",
e);
}
}
- private Partition fromHivePartition(
- String partitionName, org.apache.hadoop.hive.metastore.api.Partition partition) {
- String[][] fieldNames = getFieldNames(partitionName);
- Literal[] values =
- partition.getValues().stream().map(Literals::stringLiteral).toArray(Literal[]::new);
- // todo: support partition properties metadata to get more necessary information
- return Partitions.identity(partitionName, fieldNames, values, partition.getParameters());
- }
-
- private String[][] getFieldNames(String partitionName) {
- // Hive partition name is in the format of "field1=value1/field2=value2/..."
- String[] fields = partitionName.split(PARTITION_NAME_DELIMITER);
- return Arrays.stream(fields)
- .map(field -> new String[] {field.split(PARTITION_VALUE_DELIMITER)[0]})
- .toArray(String[][]::new);
- }
-
@Override
public Partition addPartition(Partition partition) throws PartitionAlreadyExistsException {
if (MetadataObjects.METADATA_OBJECT_RESERVED_NAME.equals(partition.name())) {
@@ -153,16 +100,17 @@ public class HiveTableOperations implements TableOperations, SupportsPartitions
Preconditions.checkArgument(
partition instanceof IdentityPartition, "Hive only supports identity partition");
IdentityPartition identityPartition = (IdentityPartition) partition;
+ HivePartition hivePartition =
+ HivePartition.identity(
+ identityPartition.fieldNames(),
+ identityPartition.values(),
+ identityPartition.properties());
- Set<String> transformFields =
- Arrays.stream(table.partitioning())
- .map(t -> ((Transforms.IdentityTransform) t).fieldName()[0])
- .collect(Collectors.toSet());
-
+ Set<String> partitionFieldNames = new HashSet<>(tableHandle.table().partitionFieldNames());
Preconditions.checkArgument(
- transformFields.size() == identityPartition.fieldNames().length,
+ partitionFieldNames.size() == identityPartition.fieldNames().length,
"Hive partition field names must be the same as table partitioning field names: %s, but got %s",
- String.join(",", transformFields),
+ String.join(",", partitionFieldNames),
String.join(
",",
Arrays.stream(identityPartition.fieldNames())
@@ -172,179 +120,71 @@ public class HiveTableOperations implements TableOperations, SupportsPartitions
.forEach(
f ->
Preconditions.checkArgument(
- transformFields.contains(f[0]),
+ partitionFieldNames.contains(f[0]),
"Hive partition field name must be in table partitioning field names: %s, but got %s",
- String.join(",", transformFields),
+ String.join(",", partitionFieldNames),
f[0]));
try {
- org.apache.hadoop.hive.metastore.api.Partition createdPartition =
- table.clientPool().run(c -> c.add_partition(toHivePartition(identityPartition)));
- return fromHivePartition(
- generatePartitionName((IdentityPartition) partition), createdPartition);
- } catch (TException | InterruptedException e) {
+ return tableHandle.clientPool().run(c -> c.addPartition(tableHandle.table(), hivePartition));
+ } catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
- private String generatePartitionName(IdentityPartition partition) {
- Arrays.stream(partition.fieldNames())
- .forEach(
- fieldName ->
- Preconditions.checkArgument(
- fieldName.length == 1,
- "Hive catalog does not support nested partition field names"));
-
- // Hive partition name is in the format of "field1=value1/field2=value2/..."
- return IntStream.range(0, partition.fieldNames().length)
- .mapToObj(
- i ->
- partition.fieldNames()[i][0]
- + PARTITION_VALUE_DELIMITER
- + partition.values()[i].value().toString())
- .collect(Collectors.joining(PARTITION_NAME_DELIMITER));
- }
-
- private org.apache.hadoop.hive.metastore.api.Partition toHivePartition(
- IdentityPartition partition) {
- org.apache.hadoop.hive.metastore.api.Partition hivePartition =
- new org.apache.hadoop.hive.metastore.api.Partition();
- hivePartition.setDbName(table.schemaName());
- hivePartition.setTableName(table.name());
-
- // todo: support custom serde and location if necessary
- StorageDescriptor sd;
- if (table.storageDescriptor() == null) {
- // In theory, this should not happen because the Hive table will reload after creating
- // in CatalogOperationDispatcher and the storage descriptor will be set. But in case of the
- // Hive table is created by other ways(such as UT), we need to handle this.
- sd = new StorageDescriptor();
- sd.setSerdeInfo(new SerDeInfo());
- } else {
- sd = table.storageDescriptor().deepCopy();
- // The location will be automatically generated by Hive Metastore
- sd.setLocation(null);
- }
- hivePartition.setSd(sd);
-
- hivePartition.setParameters(partition.properties());
-
- hivePartition.setValues(
- Arrays.stream(partition.values())
- .map(l -> l.value().toString())
- .collect(Collectors.toList()));
-
- return hivePartition;
- }
-
@Override
public boolean dropPartition(String partitionName) {
try {
- Table hiveTable = table.clientPool().run(c -> c.getTable(table.schemaName(), table.name()));
+ HiveTable hiveTable = tableHandle.table();
// Get partitions that need to drop
// If the partition has child partition, then drop all the child partitions
// If the partition has no subpartitions, then just drop the partition
- List<org.apache.hadoop.hive.metastore.api.Partition> partitions =
- table
+ List<HivePartition> partitions =
+ tableHandle
.clientPool()
.run(
c ->
c.listPartitions(
- table.schemaName(),
- table.name(),
- getFilterPartitionValueList(hiveTable, partitionName),
+ hiveTable,
+ extractPartitionValues(hiveTable.partitionFieldNames(), partitionName),
(short) -1));
if (partitions.isEmpty()) {
throw new NoSuchPartitionException(
"Hive partition %s does not exist in Hive Metastore", partitionName);
}
// Delete partitions iteratively
- for (org.apache.hadoop.hive.metastore.api.Partition partition : partitions) {
- table
+ for (HivePartition partition : partitions) {
+ tableHandle
.clientPool()
.run(
- c ->
- c.dropPartition(
- partition.getDbName(),
- partition.getTableName(),
- partition.getValues(),
- false));
+ cc -> {
+ cc.dropPartition(
+ hiveTable.catalogName(),
+ hiveTable.databaseName(),
+ tableHandle.name(),
+ partition.name(),
+ true);
+ return null;
+ });
}
+
} catch (NoSuchPartitionException e) {
return false;
- } catch (UnknownTableException e) {
- throw new NoSuchTableException(
- e, "Hive table %s does not exist in Hive Metastore", table.name());
-
- } catch (TException | InterruptedException e) {
+ } catch (InterruptedException e) {
throw new RuntimeException(
"Failed to get partition "
+ partitionName
+ " of table "
- + table.name()
+ + tableHandle.name()
+ "from Hive Metastore",
e);
}
return true;
}
- /**
- * Retrieve and complete partition field values from the given table and partitionSpec. The absent
- * partition values will be filled with empty string.
- *
- * <p>For example, if the table is partitioned by column "log_date", "log_hour", "log_minute", and
- * the partitionSpec is:
- *
- * <p>1) "log_date=2022-01-01/log_hour=01/log_minute=01", the return value should be
- * ["2022-01-01", "01", "01"].
- *
- * <p>2) "log_date=2022-01-01", the return value should be ["2022-01-01", "", ""].
- *
- * <p>3) "log_hour=01", the return value should be ["", "01", ""].
- *
- * @param dropTable the table to get partition fields from
- * @param partitionSpec partition in String format
- * @return the filter partition list
- * @throws IllegalArgumentException if the partitionSpec is not valid
- */
- private List<String> getFilterPartitionValueList(Table dropTable, String partitionSpec)
- throws NoSuchPartitionException, IllegalArgumentException {
- // Get all partition key names of the table
- List<String> partitionKeys =
- dropTable.getPartitionKeys().stream()
- .map(FieldSchema::getName)
- .collect(Collectors.toList());
-
- // Split and process the partition specification string
- Map<String, String> partSpecMap =
- Arrays.stream(partitionSpec.split(PARTITION_NAME_DELIMITER))
- .map(
- part -> {
- String[] keyValue = part.split(PARTITION_VALUE_DELIMITER, 2);
- if (keyValue.length != 2) {
- throw new IllegalArgumentException("Error partition format: " + partitionSpec);
- }
- if (!partitionKeys.contains(keyValue[0])) {
- throw new NoSuchPartitionException(
- "Hive partition %s does not exist in Hive Metastore", partitionSpec);
- }
- return keyValue;
- })
- .collect(Collectors.toMap(keyValue -> keyValue[0], keyValue -> keyValue[1]));
-
- // Retrieve or populate partition values from partSpecMap based on the table's partition key
- // order
- List<String> partitionValues =
- partitionKeys.stream()
- .map(key -> partSpecMap.getOrDefault(key, ""))
- .collect(Collectors.toList());
-
- return partitionValues;
- }
-
@Override
public void close() throws IOException {
- table.close();
+ tableHandle.close();
}
}
diff --git a/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveTablePropertiesMetadata.java b/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveTablePropertiesMetadata.java
index 4508e8adca..fb4bd8ea15 100644
--- a/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveTablePropertiesMetadata.java
+++ b/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveTablePropertiesMetadata.java
@@ -18,6 +18,18 @@
*/
package org.apache.gravitino.catalog.hive;
+import static org.apache.gravitino.catalog.hive.HiveConstants.COMMENT;
+import static org.apache.gravitino.catalog.hive.HiveConstants.EXTERNAL;
+import static org.apache.gravitino.catalog.hive.HiveConstants.FORMAT;
+import static org.apache.gravitino.catalog.hive.HiveConstants.INPUT_FORMAT;
+import static org.apache.gravitino.catalog.hive.HiveConstants.LOCATION;
+import static org.apache.gravitino.catalog.hive.HiveConstants.NUM_FILES;
+import static org.apache.gravitino.catalog.hive.HiveConstants.OUTPUT_FORMAT;
+import static org.apache.gravitino.catalog.hive.HiveConstants.SERDE_LIB;
+import static org.apache.gravitino.catalog.hive.HiveConstants.SERDE_NAME;
+import static org.apache.gravitino.catalog.hive.HiveConstants.TABLE_TYPE;
+import static org.apache.gravitino.catalog.hive.HiveConstants.TOTAL_SIZE;
+import static org.apache.gravitino.catalog.hive.HiveConstants.TRANSIENT_LAST_DDL_TIME;
import static org.apache.gravitino.connector.PropertyEntry.booleanReservedPropertyEntry;
import static org.apache.gravitino.connector.PropertyEntry.enumImmutablePropertyEntry;
import static org.apache.gravitino.connector.PropertyEntry.stringImmutablePropertyEntry;
@@ -31,19 +43,6 @@ import org.apache.gravitino.connector.BasePropertiesMetadata;
import org.apache.gravitino.connector.PropertyEntry;
public class HiveTablePropertiesMetadata extends BasePropertiesMetadata {
- public static final String COMMENT = HiveConstants.COMMENT;
- public static final String NUM_FILES = HiveConstants.NUM_FILES;
- public static final String TOTAL_SIZE = HiveConstants.TOTAL_SIZE;
- public static final String EXTERNAL = HiveConstants.EXTERNAL;
- public static final String LOCATION = HiveConstants.LOCATION;
- public static final String FORMAT = HiveConstants.FORMAT;
- public static final String TABLE_TYPE = HiveConstants.TABLE_TYPE;
- public static final String INPUT_FORMAT = HiveConstants.INPUT_FORMAT;
- public static final String OUTPUT_FORMAT = HiveConstants.OUTPUT_FORMAT;
- public static final String SERDE_NAME = HiveConstants.SERDE_NAME;
- public static final String SERDE_LIB = HiveConstants.SERDE_LIB;
- public static final String SERDE_PARAMETER_PREFIX = HiveConstants.SERDE_PARAMETER_PREFIX;
- public static final String TRANSIENT_LAST_DDL_TIME = HiveConstants.TRANSIENT_LAST_DDL_TIME;
private static final Map<String, PropertyEntry<?>> propertiesMetadata;
diff --git a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/TestHiveCatalog.java b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/TestHiveCatalog.java
index 9528d9b2fb..831b2e5bd7 100644
--- a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/TestHiveCatalog.java
+++ b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/TestHiveCatalog.java
@@ -34,7 +34,7 @@ import org.apache.gravitino.connector.PropertiesMetadata;
import org.apache.gravitino.hive.hms.MiniHiveMetastoreService;
import org.apache.gravitino.meta.AuditInfo;
import org.apache.gravitino.meta.CatalogEntity;
-import org.apache.hadoop.hive.metastore.IMetaStoreClient;
+import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.thrift.TException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@@ -96,10 +96,11 @@ public class TestHiveCatalog extends MiniHiveMetastoreService {
Map<String, String> conf = Maps.newHashMap();
metastore.hiveConf().forEach(e -> conf.put(e.getKey(), e.getValue()));
+ conf.put(METASTORE_URIS, hiveConf.get(HiveConf.ConfVars.METASTOREURIS.varname));
try (HiveCatalogOperations ops = new HiveCatalogOperations()) {
ops.initialize(conf, entity.toCatalogInfo(), HIVE_PROPERTIES_METADATA);
- List<String> dbs = ops.clientPool.run(IMetaStoreClient::getAllDatabases);
+ List<String> dbs = ops.clientPool.run(c -> c.getAllDatabases(""));
Assertions.assertEquals(2, dbs.size());
Assertions.assertTrue(dbs.contains("default"));
Assertions.assertTrue(dbs.contains(DB_NAME));
diff --git a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/TestHiveCatalogOperations.java b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/TestHiveCatalogOperations.java
index 27260584b4..85ae07696e 100644
--- a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/TestHiveCatalogOperations.java
+++ b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/TestHiveCatalogOperations.java
@@ -26,6 +26,7 @@ import static org.apache.gravitino.Catalog.PROPERTY_IN_USE;
import static org.apache.gravitino.catalog.hive.HiveCatalogPropertiesMetadata.CHECK_INTERVAL_SEC;
import static org.apache.gravitino.catalog.hive.HiveCatalogPropertiesMetadata.CLIENT_POOL_CACHE_EVICTION_INTERVAL_MS;
import static org.apache.gravitino.catalog.hive.HiveCatalogPropertiesMetadata.CLIENT_POOL_SIZE;
+import static org.apache.gravitino.catalog.hive.HiveCatalogPropertiesMetadata.DEFAULT_CATALOG;
import static org.apache.gravitino.catalog.hive.HiveCatalogPropertiesMetadata.FETCH_TIMEOUT_SEC;
import static org.apache.gravitino.catalog.hive.HiveCatalogPropertiesMetadata.IMPERSONATION_ENABLE;
import static org.apache.gravitino.catalog.hive.HiveCatalogPropertiesMetadata.KEY_TAB_URI;
@@ -41,6 +42,7 @@ import static org.mockito.Mockito.when;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import java.util.Map;
+import java.util.Properties;
import org.apache.gravitino.Catalog;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.connector.BaseCatalog;
@@ -53,27 +55,12 @@ import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class TestHiveCatalogOperations {
- @Test
- void testInitialize() {
- Map<String, String> properties = Maps.newHashMap();
- HiveCatalogOperations hiveCatalogOperations = new HiveCatalogOperations();
- hiveCatalogOperations.initialize(properties, null, HIVE_PROPERTIES_METADATA);
- String v = hiveCatalogOperations.hiveConf.get("mapreduce.job.reduces");
- Assertions.assertEquals("10", v);
-
- // Test If we can override the value in hive-site.xml
- properties.put(CATALOG_BYPASS_PREFIX + "mapreduce.job.reduces", "20");
- hiveCatalogOperations.initialize(properties, null, HIVE_PROPERTIES_METADATA);
- v = hiveCatalogOperations.hiveConf.get("mapreduce.job.reduces");
- Assertions.assertEquals("20", v);
- }
-
@Test
void testPropertyMeta() {
Map<String, PropertyEntry<?>> propertyEntryMap =
HIVE_PROPERTIES_METADATA.catalogPropertiesMetadata().propertyEntries();
- Assertions.assertEquals(16, propertyEntryMap.size());
+ Assertions.assertEquals(17, propertyEntryMap.size());
Assertions.assertTrue(propertyEntryMap.containsKey(METASTORE_URIS));
Assertions.assertTrue(propertyEntryMap.containsKey(Catalog.PROPERTY_PACKAGE));
Assertions.assertTrue(propertyEntryMap.containsKey(BaseCatalog.CATALOG_OPERATION_IMPL));
@@ -82,6 +69,7 @@ class TestHiveCatalogOperations {
Assertions.assertTrue(propertyEntryMap.containsKey(CLIENT_POOL_SIZE));
Assertions.assertTrue(propertyEntryMap.containsKey(IMPERSONATION_ENABLE));
Assertions.assertTrue(propertyEntryMap.containsKey(LIST_ALL_TABLES));
+ Assertions.assertTrue(propertyEntryMap.containsKey(DEFAULT_CATALOG));
Assertions.assertTrue(propertyEntryMap.get(METASTORE_URIS).isRequired());
Assertions.assertFalse(propertyEntryMap.get(Catalog.PROPERTY_PACKAGE).isRequired());
Assertions.assertFalse(propertyEntryMap.get(CLIENT_POOL_SIZE).isRequired());
@@ -114,8 +102,9 @@ class TestHiveCatalogOperations {
HiveCatalogOperations op = new HiveCatalogOperations();
op.initialize(maps, null, HIVE_PROPERTIES_METADATA);
- Assertions.assertEquals("v2", op.hiveConf.get("a.b"));
- Assertions.assertEquals("v4", op.hiveConf.get("c.d"));
+ Properties pp = op.mergeProperties(maps);
+ Assertions.assertEquals("v2", pp.get("a.b"));
+ Assertions.assertEquals("v4", pp.get("c.d"));
}
@Test
@@ -128,18 +117,19 @@ class TestHiveCatalogOperations {
HiveCatalogOperations hiveCatalogOperations = new HiveCatalogOperations();
hiveCatalogOperations.initialize(properties, null, HIVE_PROPERTIES_METADATA);
+ Properties pp = hiveCatalogOperations.mergeProperties(properties);
// Verify that the normal bypass configuration is correctly applied
- String v = hiveCatalogOperations.hiveConf.get("mapreduce.job.reduces");
+ String v = pp.getProperty("mapreduce.job.reduces");
Assertions.assertEquals("20", v);
// Verify that the empty bypass configuration is not applied
// This will fail if the empty key is incorrectly added
- Assertions.assertNull(hiveCatalogOperations.hiveConf.get(""));
+ Assertions.assertNull(pp.getProperty(""));
}
@Test
- void testTestConnection() throws TException, InterruptedException {
+ void testTestConnection() throws InterruptedException {
HiveCatalogOperations op = new HiveCatalogOperations();
op.clientPool = mock(CachedClientPool.class);
when(op.clientPool.run(any())).thenThrow(new TException("mock connection exception"));
diff --git a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/TestHiveTable.java b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/TestHiveTable.java
index 5a2f574fd7..99901eaa50 100644
--- a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/TestHiveTable.java
+++ b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/TestHiveTable.java
@@ -19,7 +19,7 @@
package org.apache.gravitino.catalog.hive;
import static org.apache.gravitino.catalog.hive.HiveCatalogPropertiesMetadata.METASTORE_URIS;
-import static org.apache.gravitino.catalog.hive.HiveTablePropertiesMetadata.TABLE_TYPE;
+import static org.apache.gravitino.catalog.hive.HiveConstants.TABLE_TYPE;
import static org.apache.gravitino.connector.BaseCatalog.CATALOG_BYPASS_PREFIX;
import static org.apache.gravitino.rel.expressions.transforms.Transforms.day;
import static org.apache.gravitino.rel.expressions.transforms.Transforms.identity;
@@ -35,6 +35,8 @@ import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
import org.apache.gravitino.exceptions.NoSuchSchemaException;
import org.apache.gravitino.exceptions.TableAlreadyExistsException;
+import org.apache.gravitino.hive.HiveColumn;
+import org.apache.gravitino.hive.HiveSchema;
import org.apache.gravitino.hive.hms.MiniHiveMetastoreService;
import org.apache.gravitino.meta.AuditInfo;
import org.apache.gravitino.meta.CatalogEntity;
@@ -217,7 +219,10 @@ public class TestHiveTable extends MiniHiveMetastoreService {
new Transform[0],
distribution,
sortOrders));
- Assertions.assertTrue(exception.getMessage().contains("Table already exists"));
+ Assertions.assertTrue(
+ exception
+ .getMessage()
+ .contains(String.format("Hive table %s already exists", hiveTableName)));
// Test struct field with comment
HiveColumn structCol =
diff --git a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/TestHiveTableOperations.java b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/TestHiveTableOperations.java
index 3ef26b557e..c97efb2876 100644
--- a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/TestHiveTableOperations.java
+++ b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/TestHiveTableOperations.java
@@ -32,6 +32,7 @@ import java.util.Arrays;
import java.util.Map;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.exceptions.NoSuchPartitionException;
+import org.apache.gravitino.hive.HiveColumn;
import org.apache.gravitino.hive.hms.MiniHiveMetastoreService;
import org.apache.gravitino.rel.Column;
import org.apache.gravitino.rel.SupportsPartitions;
@@ -51,7 +52,7 @@ public class TestHiveTableOperations extends MiniHiveMetastoreService {
NameIdentifier.of(META_LAKE_NAME, HIVE_CATALOG_NAME, HIVE_SCHEMA_NAME, genRandomName());
private static HiveCatalog hiveCatalog;
private static HiveCatalogOperations hiveCatalogOperations;
- private static HiveTable hiveTable;
+ private static HiveTableHandle hiveTable;
private static Column[] columns;
private static Partition existingPartition;
@@ -74,7 +75,7 @@ public class TestHiveTableOperations extends MiniHiveMetastoreService {
existingPartition = hiveTable.supportPartitions().addPartition(partition);
}
- private static HiveTable createPartitionedTable() {
+ private static HiveTableHandle createPartitionedTable() {
Map<String, String> properties = Maps.newHashMap();
properties.put("key1", "val1");
properties.put("key2", "val2");
@@ -88,7 +89,7 @@ public class TestHiveTableOperations extends MiniHiveMetastoreService {
Transform[] partitioning = new Transform[] {identity(col1.name()), identity(col2.name())};
- return (HiveTable)
+ return (HiveTableHandle)
hiveCatalogOperations.createTable(
tableIdentifier, columns, HIVE_COMMENT, properties, partitioning);
}
@@ -283,7 +284,7 @@ public class TestHiveTableOperations extends MiniHiveMetastoreService {
hiveTable.supportPartitions().dropPartition("does_not_exist_partition");
});
Assertions.assertEquals(
- "Error partition format: does_not_exist_partition", exception5.getMessage());
+ "Invalid partition format: does_not_exist_partition", exception5.getMessage());
Assertions.assertFalse(
hiveTable.supportPartitions().dropPartition("city=not_exist"),
diff --git a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHiveIT.java b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHive2IT.java
similarity index 77%
rename from catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHiveIT.java
rename to catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHive2IT.java
index b261f11587..c934589369 100644
--- a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHiveIT.java
+++ b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHive2IT.java
@@ -18,15 +18,17 @@
*/
package org.apache.gravitino.catalog.hive.integration.test;
-import static org.apache.gravitino.catalog.hive.HiveCatalogPropertiesMetadata.METASTORE_URIS;
-import static org.apache.gravitino.catalog.hive.HiveTablePropertiesMetadata.COMMENT;
-import static org.apache.gravitino.catalog.hive.HiveTablePropertiesMetadata.EXTERNAL;
-import static org.apache.gravitino.catalog.hive.HiveTablePropertiesMetadata.FORMAT;
-import static org.apache.gravitino.catalog.hive.HiveTablePropertiesMetadata.INPUT_FORMAT;
-import static org.apache.gravitino.catalog.hive.HiveTablePropertiesMetadata.OUTPUT_FORMAT;
-import static org.apache.gravitino.catalog.hive.HiveTablePropertiesMetadata.SERDE_LIB;
-import static org.apache.gravitino.catalog.hive.HiveTablePropertiesMetadata.TABLE_TYPE;
-import static org.apache.gravitino.catalog.hive.HiveTablePropertiesMetadata.TRANSIENT_LAST_DDL_TIME;
+import static org.apache.gravitino.catalog.hive.HiveConstants.COMMENT;
+import static org.apache.gravitino.catalog.hive.HiveConstants.EXTERNAL;
+import static org.apache.gravitino.catalog.hive.HiveConstants.FORMAT;
+import static org.apache.gravitino.catalog.hive.HiveConstants.INPUT_FORMAT;
+import static org.apache.gravitino.catalog.hive.HiveConstants.LOCATION;
+import static org.apache.gravitino.catalog.hive.HiveConstants.METASTORE_URIS;
+import static org.apache.gravitino.catalog.hive.HiveConstants.OUTPUT_FORMAT;
+import static org.apache.gravitino.catalog.hive.HiveConstants.SERDE_LIB;
+import static org.apache.gravitino.catalog.hive.HiveConstants.SERDE_NAME;
+import static org.apache.gravitino.catalog.hive.HiveConstants.TABLE_TYPE;
+import static org.apache.gravitino.catalog.hive.HiveConstants.TRANSIENT_LAST_DDL_TIME;
import static org.apache.gravitino.catalog.hive.TableType.EXTERNAL_TABLE;
import static org.apache.gravitino.catalog.hive.TableType.MANAGED_TABLE;
import static org.apache.hadoop.hive.serde.serdeConstants.DATE_TYPE_NAME;
@@ -39,13 +41,13 @@ import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import java.io.IOException;
import java.time.LocalDate;
-import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
+import java.util.Properties;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.gravitino.Catalog;
@@ -58,7 +60,6 @@ import org.apache.gravitino.SchemaChange;
import org.apache.gravitino.SupportsSchemas;
import org.apache.gravitino.auth.AuthConstants;
import org.apache.gravitino.catalog.hive.HiveCatalogOperations;
-import org.apache.gravitino.catalog.hive.HiveSchemaPropertiesMetadata;
import org.apache.gravitino.catalog.hive.HiveStorageConstants;
import org.apache.gravitino.catalog.hive.HiveTablePropertiesMetadata;
import org.apache.gravitino.catalog.hive.TableType;
@@ -66,9 +67,13 @@ import org.apache.gravitino.client.GravitinoMetalake;
import org.apache.gravitino.connector.BaseCatalog;
import org.apache.gravitino.exceptions.NoSuchCatalogException;
import org.apache.gravitino.exceptions.NoSuchMetalakeException;
+import org.apache.gravitino.exceptions.NoSuchPartitionException;
import org.apache.gravitino.exceptions.NoSuchSchemaException;
import org.apache.gravitino.exceptions.NoSuchTableException;
import org.apache.gravitino.hive.HiveClientPool;
+import org.apache.gravitino.hive.HivePartition;
+import org.apache.gravitino.hive.HiveSchema;
+import org.apache.gravitino.hive.HiveTable;
import org.apache.gravitino.integration.test.container.ContainerSuite;
import org.apache.gravitino.integration.test.container.HiveContainer;
import org.apache.gravitino.integration.test.util.BaseIT;
@@ -98,9 +103,6 @@ import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
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.NoSuchObjectException;
import org.apache.spark.sql.SparkSession;
import org.apache.thrift.TException;
import org.junit.jupiter.api.AfterAll;
@@ -113,8 +115,9 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Tag("gravitino-docker-test")
-public class CatalogHiveIT extends BaseIT {
- private static final Logger LOG = LoggerFactory.getLogger(CatalogHiveIT.class);
+public class CatalogHive2IT extends BaseIT {
+ private static final Logger LOG = LoggerFactory.getLogger(CatalogHive2IT.class);
+ private static final String HMS_CATALOG = "hive";
public static final String metalakeName =
GravitinoITUtils.genRandomName("CatalogHiveIT_metalake");
public String catalogName = GravitinoITUtils.genRandomName("CatalogHiveIT_catalog");
@@ -127,7 +130,7 @@ public class CatalogHiveIT extends BaseIT {
public static final String HIVE_COL_NAME1 = "hive_col_name1";
public static final String HIVE_COL_NAME2 = "hive_col_name2";
public static final String HIVE_COL_NAME3 = "hive_col_name3";
- protected String HIVE_METASTORE_URIS;
+ protected String hiveMetastoreUris;
protected final String provider = "hive";
protected final ContainerSuite containerSuite = ContainerSuite.getInstance();
private HiveClientPool hiveClientPool;
@@ -161,9 +164,10 @@ public class CatalogHiveIT extends BaseIT {
"'gravitino_it_test'");
protected void startNecessaryContainer() {
- containerSuite.startHiveContainer();
+ containerSuite.startHiveContainer(
+ ImmutableMap.of(HiveContainer.HIVE_RUNTIME_VERSION, HiveContainer.HIVE2));
- HIVE_METASTORE_URIS =
+ hiveMetastoreUris =
String.format(
"thrift://%s:%d",
containerSuite.getHiveContainer().getContainerIpAddress(),
@@ -175,7 +179,7 @@ public class CatalogHiveIT extends BaseIT {
SparkSession.builder()
.master("local[1]")
.appName("Hive Catalog integration test")
- .config("hive.metastore.uris", HIVE_METASTORE_URIS)
+ .config("hive.metastore.uris", hiveMetastoreUris)
.config(
"spark.sql.warehouse.dir",
String.format(
@@ -204,11 +208,14 @@ public class CatalogHiveIT extends BaseIT {
startNecessaryContainer();
HiveConf hiveConf = new HiveConf();
- hiveConf.set(HiveConf.ConfVars.METASTOREURIS.varname, HIVE_METASTORE_URIS);
+ hiveConf.set(HiveConf.ConfVars.METASTOREURIS.varname, hiveMetastoreUris);
+
+ Properties hiveClientProperties = new Properties();
+ hiveClientProperties.setProperty(HiveConf.ConfVars.METASTOREURIS.varname, hiveMetastoreUris);
// Check if Hive client can connect to Hive metastore
- hiveClientPool = new HiveClientPool(1, hiveConf);
- List<String> dbs = hiveClientPool.run(client -> client.getAllDatabases());
+ hiveClientPool = new HiveClientPool("hive", 1, hiveClientProperties);
+ List<String> dbs = hiveClientPool.run(client -> client.getAllDatabases(HMS_CATALOG));
Assertions.assertFalse(dbs.isEmpty());
initSparkSession();
@@ -251,7 +258,6 @@ public class CatalogHiveIT extends BaseIT {
} catch (Exception e) {
LOG.error("Failed to close CloseableGroup", e);
}
-
client = null;
}
@@ -259,8 +265,8 @@ public class CatalogHiveIT extends BaseIT {
public void resetSchema() throws TException, InterruptedException {
catalog.asSchemas().dropSchema(schemaName, true);
assertThrows(
- NoSuchObjectException.class,
- () -> hiveClientPool.run(client -> client.getDatabase(schemaName)));
+ NoSuchSchemaException.class,
+ () -> hiveClientPool.run(client -> client.getDatabase(HMS_CATALOG, schemaName)));
createSchema();
}
@@ -277,7 +283,7 @@ public class CatalogHiveIT extends BaseIT {
protected void createCatalog() {
Map<String, String> properties = Maps.newHashMap();
- properties.put(METASTORE_URIS, HIVE_METASTORE_URIS);
+ properties.put(METASTORE_URIS, hiveMetastoreUris);
metalake.createCatalog(catalogName, Catalog.Type.RELATIONAL, provider, "comment", properties);
@@ -293,14 +299,14 @@ public class CatalogHiveIT extends BaseIT {
Assertions.assertEquals(comment, loadSchema.comment());
Assertions.assertEquals("val1", loadSchema.properties().get("key1"));
Assertions.assertEquals("val2", loadSchema.properties().get("key2"));
- Assertions.assertNotNull(loadSchema.properties().get(HiveSchemaPropertiesMetadata.LOCATION));
+ Assertions.assertNotNull(loadSchema.properties().get(LOCATION));
// Directly get database from Hive metastore to verify the schema creation
- Database database = hiveClientPool.run(client -> client.getDatabase(schemaName));
- Assertions.assertEquals(schemaName.toLowerCase(), database.getName());
- Assertions.assertEquals(comment, database.getDescription());
- Assertions.assertEquals("val1", database.getParameters().get("key1"));
- Assertions.assertEquals("val2", database.getParameters().get("key2"));
+ HiveSchema hiveSchema = loadHiveSchema(schemaName);
+ Assertions.assertEquals(schemaName.toLowerCase(), hiveSchema.name());
+ Assertions.assertEquals(comment, hiveSchema.comment());
+ Assertions.assertEquals("val1", hiveSchema.properties().get("key1"));
+ Assertions.assertEquals("val2", hiveSchema.properties().get("key2"));
}
private Column[] createColumns() {
@@ -310,28 +316,42 @@ public class CatalogHiveIT extends BaseIT {
return new Column[] {col1, col2, col3};
}
- private void checkTableReadWrite(org.apache.hadoop.hive.metastore.api.Table table) {
- String dbName = table.getDbName();
- String tableName = table.getTableName();
+ private void checkTableReadWrite(HiveTable table) {
+ String dbName = table.databaseName();
+ String tableName = table.name();
long count = sparkSession.sql(String.format(SELECT_ALL_TEMPLATE, dbName, tableName)).count();
+
+ List<String> partitionFields = table.partitionFieldNames();
+ Map<String, Column> columnByName =
+ Arrays.stream(table.columns()).collect(Collectors.toMap(Column::name, c -> c));
+ List<Column> dataColumns =
+ Arrays.stream(table.columns())
+ .filter(c -> !partitionFields.contains(c.name()))
+ .collect(Collectors.toList());
+
String values =
- table.getSd().getCols().stream()
- .map(f -> typeConstant.get(f.getType()))
- .map(Object::toString)
- .collect(Collectors.joining(","));
- if (table.getPartitionKeys().isEmpty()) {
+ dataColumns.stream().map(this::sampleValueForColumn).collect(Collectors.joining(","));
+ if (partitionFields.isEmpty()) {
sparkSession.sql(getInsertWithoutPartitionSql(dbName, tableName, values));
} else {
String partitionExpressions =
- table.getPartitionKeys().stream()
- .map(f -> f.getName() + "=" + typeConstant.get(f.getType()))
+ partitionFields.stream()
+ .map(
+ field -> {
+ Column column = columnByName.get(field);
+ Assertions.assertNotNull(
+ column, "Partition column " + field + " is missing from definition");
+ return field + "=" + sampleValueForColumn(column);
+ })
.collect(Collectors.joining(","));
sparkSession.sql(getInsertWithPartitionSql(dbName, tableName, partitionExpressions, values));
}
Assertions.assertEquals(
count + 1, sparkSession.sql(String.format(SELECT_ALL_TEMPLATE, dbName, tableName)).count());
- // Assert HDFS owner
- Path tableDirectory = new Path(table.getSd().getLocation());
+
+ String tableLocation = table.properties().get(LOCATION);
+ Assertions.assertNotNull(tableLocation, "Table location should not be null");
+ Path tableDirectory = new Path(tableLocation);
FileStatus[] fileStatuses;
try {
fileStatuses = fileSystem.listStatus(tableDirectory);
@@ -352,6 +372,112 @@ public class CatalogHiveIT extends BaseIT {
return properties;
}
+ private String sampleValueForColumn(Column column) {
+ if (column.dataType().equals(Types.ByteType.get())) {
+ return typeConstant.get(TINYINT_TYPE_NAME);
+ } else if (column.dataType().equals(Types.IntegerType.get())) {
+ return typeConstant.get(INT_TYPE_NAME);
+ } else if (column.dataType().equals(Types.DateType.get())) {
+ return typeConstant.get(DATE_TYPE_NAME);
+ } else if (column.dataType().equals(Types.StringType.get())) {
+ return typeConstant.get(STRING_TYPE_NAME);
+ }
+ throw new IllegalArgumentException(
+ "Unsupported column type for sample value: " + column.dataType());
+ }
+
+ private HiveTable loadHiveTable(String schema, String table) throws InterruptedException {
+ return hiveClientPool.run(client -> client.getTable(HMS_CATALOG, schema, table));
+ }
+
+ private HivePartition loadHivePartition(String schema, String table, String partition)
+ throws InterruptedException {
+ return hiveClientPool.run(
+ client -> {
+ HiveTable hiveTable = client.getTable(HMS_CATALOG, schema, table);
+ return client.getPartition(hiveTable, partition);
+ });
+ }
+
+ private HiveSchema loadHiveSchema(String schema) throws InterruptedException {
+ return hiveClientPool.run(client -> client.getDatabase(HMS_CATALOG, schema));
+ }
+
+ private boolean hiveTableExists(String schema, String table) throws InterruptedException {
+ return hiveClientPool.run(
+ client -> {
+ try {
+ client.getTable(HMS_CATALOG, schema, table);
+ return true;
+ } catch (NoSuchTableException e) {
+ return false;
+ }
+ });
+ }
+
+ private void dropHiveTable(String schema, String table, boolean deleteData, boolean ifPurge)
+ throws InterruptedException {
+ hiveClientPool.run(
+ client -> {
+ client.dropTable(HMS_CATALOG, schema, table, deleteData, ifPurge);
+ return null;
+ });
+ }
+
+ private List<String> partitionValues(HivePartition partition) {
+ return Arrays.stream(partition.values())
+ .map(literal -> literal.value().toString())
+ .collect(Collectors.toList());
+ }
+
+ private void compareDistributions(Distribution expected, Distribution actual) {
+ boolean expectedEmpty = expected == null || Distributions.NONE.equals(expected);
+ boolean actualEmpty = actual == null || Distributions.NONE.equals(actual);
+ Assertions.assertEquals(expectedEmpty, actualEmpty);
+ if (expectedEmpty) {
+ return;
+ }
+
+ Assertions.assertEquals(expected.number(), actual.number());
+ List<String> expectedFields =
+ Arrays.stream(expected.expressions())
+ .map(expr -> ((NamedReference.FieldReference) expr).fieldName()[0])
+ .collect(Collectors.toList());
+ List<String> actualFields =
+ Arrays.stream(actual.expressions())
+ .map(expr -> ((NamedReference.FieldReference) expr).fieldName()[0])
+ .collect(Collectors.toList());
+ Assertions.assertEquals(expectedFields, actualFields);
+ }
+
+ private void compareSortOrders(SortOrder[] expected, SortOrder[] actual) {
+ int expectedLength = expected == null ? 0 : expected.length;
+ int actualLength = actual == null ? 0 : actual.length;
+ Assertions.assertEquals(expectedLength, actualLength);
+ for (int i = 0; i < expectedLength; i++) {
+ SortOrder expectedOrder = expected[i];
+ SortOrder actualOrder = actual[i];
+ Assertions.assertEquals(expectedOrder.direction(), actualOrder.direction());
+ Assertions.assertEquals(expectedOrder.nullOrdering(), actualOrder.nullOrdering());
+ Assertions.assertEquals(
+ ((NamedReference.FieldReference) expectedOrder.expression()).fieldName()[0],
+ ((NamedReference.FieldReference) actualOrder.expression()).fieldName()[0]);
+ }
+ }
+
+ private void comparePartitioning(Transform[] expected, List<String> actualPartitionFields) {
+ if (expected == null || expected.length == 0) {
+ Assertions.assertTrue(actualPartitionFields == null || actualPartitionFields.isEmpty());
+ return;
+ }
+
+ List<String> expectedPartitionFields =
+ Arrays.stream(expected)
+ .map(p -> ((Transform.SingleFieldTransform) p).fieldName()[0])
+ .collect(Collectors.toList());
+ Assertions.assertEquals(expectedPartitionFields, actualPartitionFields);
+ }
+
@Test
public void testCreateHiveTableWithDistributionAndSortOrder()
throws TException, InterruptedException {
@@ -365,10 +491,7 @@ public class CatalogHiveIT extends BaseIT {
final SortOrder[] sortOrders =
new SortOrder[] {
- SortOrders.of(
- NamedReference.field(HIVE_COL_NAME2),
- SortDirection.DESCENDING,
- NullOrdering.NULLS_FIRST)
+ SortOrders.of(NamedReference.field(HIVE_COL_NAME2), SortDirection.DESCENDING)
};
Map<String, String> properties = createProperties();
@@ -385,12 +508,11 @@ public class CatalogHiveIT extends BaseIT {
sortOrders);
// Directly get table from Hive metastore to check if the table is created successfully.
- org.apache.hadoop.hive.metastore.api.Table hiveTab =
- hiveClientPool.run(client -> client.getTable(schemaName, tableName));
+ HiveTable hiveTab = loadHiveTable(schemaName, tableName);
properties
.keySet()
.forEach(
- key -> Assertions.assertEquals(properties.get(key), hiveTab.getParameters().get(key)));
+ key -> Assertions.assertEquals(properties.get(key), hiveTab.properties().get(key)));
assertTableEquals(createdTable, hiveTab);
checkTableReadWrite(hiveTab);
@@ -402,13 +524,11 @@ public class CatalogHiveIT extends BaseIT {
.createTable(nameIdentifier, columns, TABLE_COMMENT, properties, (Transform[]) null);
// Directly get table from Hive metastore to check if the table is created successfully.
- org.apache.hadoop.hive.metastore.api.Table hiveTable1 =
- hiveClientPool.run(client -> client.getTable(schemaName, tableName));
+ HiveTable hiveTable1 = loadHiveTable(schemaName, tableName);
properties
.keySet()
.forEach(
- key ->
- Assertions.assertEquals(properties.get(key), hiveTable1.getParameters().get(key)));
+ key -> Assertions.assertEquals(properties.get(key), hiveTable1.properties().get(key)));
assertTableEquals(createdTable1, hiveTable1);
checkTableReadWrite(hiveTable1);
@@ -466,12 +586,11 @@ public class CatalogHiveIT extends BaseIT {
nameIdentifier, columns, TABLE_COMMENT, properties, Transforms.EMPTY_TRANSFORM);
// Directly get table from Hive metastore to check if the table is created successfully.
- org.apache.hadoop.hive.metastore.api.Table hiveTab =
- hiveClientPool.run(client -> client.getTable(schemaName, tableName));
+ HiveTable hiveTab = loadHiveTable(schemaName, tableName);
properties
.keySet()
.forEach(
- key -> Assertions.assertEquals(properties.get(key), hiveTab.getParameters().get(key)));
+ key -> Assertions.assertEquals(properties.get(key), hiveTab.properties().get(key)));
assertTableEquals(createdTable, hiveTab);
checkTableReadWrite(hiveTab);
@@ -481,10 +600,9 @@ public class CatalogHiveIT extends BaseIT {
catalog
.asTableCatalog()
.createTable(nameIdentifier, columns, null, properties, Transforms.EMPTY_TRANSFORM);
- org.apache.hadoop.hive.metastore.api.Table hiveTab2 =
- hiveClientPool.run(client -> client.getTable(schemaName, tableName));
+ HiveTable hiveTab2 = loadHiveTable(schemaName, tableName);
assertTableEquals(createdTable, hiveTab2);
- checkTableReadWrite(hiveTab);
+ checkTableReadWrite(hiveTab2);
// test null partition
resetSchema();
@@ -494,13 +612,11 @@ public class CatalogHiveIT extends BaseIT {
.createTable(nameIdentifier, columns, TABLE_COMMENT, properties, (Transform[]) null);
// Directly get table from Hive metastore to check if the table is created successfully.
- org.apache.hadoop.hive.metastore.api.Table hiveTable1 =
- hiveClientPool.run(client -> client.getTable(schemaName, tableName));
+ HiveTable hiveTable1 = loadHiveTable(schemaName, tableName);
properties
.keySet()
.forEach(
- key ->
- Assertions.assertEquals(properties.get(key), hiveTable1.getParameters().get(key)));
+ key -> Assertions.assertEquals(properties.get(key), hiveTable1.properties().get(key)));
assertTableEquals(createdTable1, hiveTable1);
checkTableReadWrite(hiveTable1);
@@ -562,8 +678,7 @@ public class CatalogHiveIT extends BaseIT {
nameIdentifier, columns, TABLE_COMMENT, createProperties(), Transforms.EMPTY_TRANSFORM);
Table loadedTable1 = catalog.asTableCatalog().loadTable(nameIdentifier);
HiveTablePropertiesMetadata tablePropertiesMetadata = new HiveTablePropertiesMetadata();
- org.apache.hadoop.hive.metastore.api.Table actualTable =
- hiveClientPool.run(client -> client.getTable(schemaName, tableName));
+ HiveTable actualTable = loadHiveTable(schemaName, tableName);
assertDefaultTableProperties(loadedTable1, actualTable);
checkTableReadWrite(actualTable);
@@ -582,23 +697,22 @@ public class CatalogHiveIT extends BaseIT {
properties,
Transforms.EMPTY_TRANSFORM);
Table loadedTable2 = catalog.asTableCatalog().loadTable(NameIdentifier.of(schemaName, table2));
- org.apache.hadoop.hive.metastore.api.Table actualTable2 =
- hiveClientPool.run(client -> client.getTable(schemaName, table2));
+ HiveTable actualTable2 = loadHiveTable(schemaName, table2);
Assertions.assertEquals(
- HiveStorageConstants.OPENCSV_SERDE_CLASS,
- actualTable2.getSd().getSerdeInfo().getSerializationLib());
+ HiveStorageConstants.OPENCSV_SERDE_CLASS, actualTable2.properties().get(SERDE_LIB));
Assertions.assertEquals(
- HiveStorageConstants.TEXT_INPUT_FORMAT_CLASS, actualTable2.getSd().getInputFormat());
+ HiveStorageConstants.TEXT_INPUT_FORMAT_CLASS, actualTable2.properties().get(INPUT_FORMAT));
Assertions.assertEquals(
HiveStorageConstants.IGNORE_KEY_OUTPUT_FORMAT_CLASS,
- actualTable2.getSd().getOutputFormat());
- Assertions.assertEquals(EXTERNAL_TABLE.name(), actualTable2.getTableType());
- Assertions.assertEquals(table2.toLowerCase(), actualTable2.getSd().getSerdeInfo().getName());
- Assertions.assertEquals(TABLE_COMMENT, actualTable2.getParameters().get(COMMENT));
+ actualTable2.properties().get(OUTPUT_FORMAT));
+ Assertions.assertEquals(
+ EXTERNAL_TABLE.name(), actualTable2.properties().get(TABLE_TYPE).toUpperCase());
+ Assertions.assertEquals(table2.toLowerCase(), actualTable2.properties().get(SERDE_NAME));
+ Assertions.assertEquals(TABLE_COMMENT, actualTable2.comment());
Assertions.assertEquals(
((Boolean) tablePropertiesMetadata.getDefaultValue(EXTERNAL)).toString().toUpperCase(),
- actualTable.getParameters().get(EXTERNAL));
+ actualTable.properties().get(EXTERNAL));
Assertions.assertNotNull(loadedTable2.properties().get(TRANSIENT_LAST_DDL_TIME));
// S3 doesn't support NUM_FILES and TOTAL_SIZE
@@ -646,12 +760,12 @@ public class CatalogHiveIT extends BaseIT {
String schemaName = GravitinoITUtils.genRandomName(SCHEMA_PREFIX);
Map<String, String> schemaProperties = createSchemaProperties();
- String expectedHDFSSchemaLocation = schemaProperties.get(HiveSchemaPropertiesMetadata.LOCATION);
+ String expectedHDFSSchemaLocation = schemaProperties.get(LOCATION);
catalog.asSchemas().createSchema(schemaName, "comment", schemaProperties);
- Database actualSchema = hiveClientPool.run(client -> client.getDatabase(schemaName));
- String actualSchemaLocation = actualSchema.getLocationUri();
+ HiveSchema actualSchema = loadHiveSchema(schemaName);
+ String actualSchemaLocation = actualSchema.properties().get(LOCATION);
Assertions.assertTrue(actualSchemaLocation.endsWith(expectedHDFSSchemaLocation));
NameIdentifier tableIdent =
@@ -659,8 +773,7 @@ public class CatalogHiveIT extends BaseIT {
Map<String, String> tableProperties = createProperties();
String expectedSchemaLocation =
- tableProperties.getOrDefault(
- HiveSchemaPropertiesMetadata.LOCATION, expectedHDFSSchemaLocation);
+ tableProperties.getOrDefault(LOCATION, expectedHDFSSchemaLocation);
catalog
.asTableCatalog()
@@ -670,13 +783,12 @@ public class CatalogHiveIT extends BaseIT {
TABLE_COMMENT,
tableProperties,
Transforms.EMPTY_TRANSFORM);
- org.apache.hadoop.hive.metastore.api.Table actualTable =
- hiveClientPool.run(client -> client.getTable(schemaName, tableIdent.name()));
- String actualTableLocation = actualTable.getSd().getLocation();
+ HiveTable actualTable = loadHiveTable(schemaName, tableIdent.name());
+ String actualTableLocation = actualTable.properties().get(LOCATION);
// use `tableIdent.name().toLowerCase()` because HMS will convert table name to lower
- // actualTable.getSd().getLocation() is null for S3
- if (!tableProperties.containsKey(HiveTablePropertiesMetadata.LOCATION)) {
+ // actualTableLocation is null for S3
+ if (!tableProperties.containsKey(LOCATION) && actualTableLocation != null) {
String expectedTableLocation = expectedSchemaLocation + "/" + tableIdent.name().toLowerCase();
Assertions.assertTrue(actualTableLocation.endsWith(expectedTableLocation));
}
@@ -703,12 +815,11 @@ public class CatalogHiveIT extends BaseIT {
});
// Directly get table from Hive metastore to check if the table is created successfully.
- org.apache.hadoop.hive.metastore.api.Table hiveTab =
- hiveClientPool.run(client -> client.getTable(schemaName, tableName));
+ HiveTable hiveTab = loadHiveTable(schemaName, tableName);
properties
.keySet()
.forEach(
- key -> Assertions.assertEquals(properties.get(key), hiveTab.getParameters().get(key)));
+ key -> Assertions.assertEquals(properties.get(key), hiveTab.properties().get(key)));
assertTableEquals(createdTable, hiveTab);
checkTableReadWrite(hiveTab);
@@ -824,15 +935,13 @@ public class CatalogHiveIT extends BaseIT {
"hive_col_name2=2023-01-01/hive_col_name3=gravitino_it_test", partition.name());
// Directly get partition from Hive metastore
- org.apache.hadoop.hive.metastore.api.Partition hivePartition =
- hiveClientPool.run(
- client -> client.getPartition(schemaName, createdTable.name(), partition.name()));
- Assertions.assertEquals(
- partition.values()[0].value().toString(), hivePartition.getValues().get(0));
- Assertions.assertEquals(
- partition.values()[1].value().toString(), hivePartition.getValues().get(1));
+ HivePartition hivePartition =
+ loadHivePartition(schemaName, createdTable.name(), partition.name());
+ List<String> hiveValues = partitionValues(hivePartition);
+ Assertions.assertEquals(partition.values()[0].value().toString(), hiveValues.get(0));
+ Assertions.assertEquals(partition.values()[1].value().toString(), hiveValues.get(1));
Assertions.assertNotNull(partition.properties());
- Assertions.assertEquals(partition.properties(), hivePartition.getParameters());
+ Assertions.assertEquals(partition.properties(), hivePartition.properties());
}
@Test
@@ -851,20 +960,18 @@ public class CatalogHiveIT extends BaseIT {
(IdentityPartition) createdTable.supportPartitions().addPartition(identity);
// Directly get partition from hive metastore to check if the partition is created successfully.
- org.apache.hadoop.hive.metastore.api.Partition partitionGot =
- hiveClientPool.run(
- client -> client.getPartition(schemaName, createdTable.name(), partitionAdded.name()));
- Assertions.assertEquals(
- partitionAdded.values()[0].value().toString(), partitionGot.getValues().get(0));
- Assertions.assertEquals(
- partitionAdded.values()[1].value().toString(), partitionGot.getValues().get(1));
- Assertions.assertEquals(partitionAdded.properties(), partitionGot.getParameters());
+ HivePartition partitionGot =
+ loadHivePartition(schemaName, createdTable.name(), partitionAdded.name());
+ List<String> partitionValues = partitionValues(partitionGot);
+ Assertions.assertEquals(partitionAdded.values()[0].value().toString(), partitionValues.get(0));
+ Assertions.assertEquals(partitionAdded.values()[1].value().toString(), partitionValues.get(1));
+ Assertions.assertEquals(partitionAdded.properties(), partitionGot.properties());
// test the new partition can be read and write successfully by dynamic partition
String selectTemplate =
"SELECT * FROM %s.%s WHERE hive_col_name2 = '2023-01-02' AND hive_col_name3 = 'gravitino_it_test2'";
- long count =
- sparkSession.sql(String.format(selectTemplate, schemaName, createdTable.name())).count();
+ String sql = String.format(selectTemplate, schemaName, createdTable.name());
+ long count = sparkSession.sql(sql).count();
Assertions.assertEquals(0, count);
String insertTemplate =
@@ -899,27 +1006,23 @@ public class CatalogHiveIT extends BaseIT {
IdentityPartition partitionAdded =
(IdentityPartition) createdTable.supportPartitions().addPartition(identity);
// Directly get partition from hive metastore to check if the partition is created successfully.
- org.apache.hadoop.hive.metastore.api.Partition partitionGot =
- hiveClientPool.run(
- client -> client.getPartition(schemaName, createdTable.name(), partitionAdded.name()));
- Assertions.assertEquals(
- partitionAdded.values()[0].value().toString(), partitionGot.getValues().get(0));
- Assertions.assertEquals(
- partitionAdded.values()[1].value().toString(), partitionGot.getValues().get(1));
- Assertions.assertEquals(partitionAdded.properties(), partitionGot.getParameters());
+ HivePartition partitionGot =
+ loadHivePartition(schemaName, createdTable.name(), partitionAdded.name());
+ List<String> partitionValues = partitionValues(partitionGot);
+ Assertions.assertEquals(partitionAdded.values()[0].value().toString(), partitionValues.get(0));
+ Assertions.assertEquals(partitionAdded.values()[1].value().toString(), partitionValues.get(1));
+ Assertions.assertEquals(partitionAdded.properties(), partitionGot.properties());
// test drop partition "hive_col_name2=2023-01-02/hive_col_name3=gravitino_it_test2"
boolean dropRes1 = createdTable.supportPartitions().dropPartition(partitionAdded.name());
Assertions.assertTrue(dropRes1);
Assertions.assertThrows(
- NoSuchObjectException.class,
- () ->
- hiveClientPool.run(
- client ->
- client.getPartition(schemaName, createdTable.name(), partitionAdded.name())));
- org.apache.hadoop.hive.metastore.api.Table hiveTab =
- hiveClientPool.run(client -> client.getTable(schemaName, createdTable.name()));
- Path partitionDirectory = new Path(hiveTab.getSd().getLocation() + identity.name());
+ NoSuchPartitionException.class,
+ () -> loadHivePartition(schemaName, createdTable.name(), partitionAdded.name()));
+ HiveTable hiveTable = loadHiveTable(schemaName, createdTable.name());
+ String tableLocation = hiveTable.properties().get(LOCATION);
+ Assertions.assertNotNull(tableLocation, "Table location should not be null");
+ Path partitionDirectory = new Path(tableLocation + identity.name());
Assertions.assertFalse(
fileSystem.exists(partitionDirectory), "The partition directory should not exist");
@@ -934,14 +1037,14 @@ public class CatalogHiveIT extends BaseIT {
(IdentityPartition) createdTable.supportPartitions().addPartition(identity1);
// Directly get partition from Hive metastore to check if the partition is created successfully.
- org.apache.hadoop.hive.metastore.api.Partition partitionGot1 =
- hiveClientPool.run(
- client -> client.getPartition(schemaName, createdTable.name(), partitionAdded1.name()));
+ HivePartition partitionGot1 =
+ loadHivePartition(schemaName, createdTable.name(), partitionAdded1.name());
+ List<String> partitionValues1 = partitionValues(partitionGot1);
Assertions.assertEquals(
- partitionAdded1.values()[0].value().toString(), partitionGot1.getValues().get(0));
+ partitionAdded1.values()[0].value().toString(), partitionValues1.get(0));
Assertions.assertEquals(
- partitionAdded1.values()[1].value().toString(), partitionGot1.getValues().get(1));
- Assertions.assertEquals(partitionAdded1.properties(), partitionGot1.getParameters());
+ partitionAdded1.values()[1].value().toString(), partitionValues1.get(1));
+ Assertions.assertEquals(partitionAdded1.properties(), partitionGot1.properties());
// add partition "hive_col_name2=2024-01-02/hive_col_name3=gravitino_it_test3"
String[] field5 = new String[] {"hive_col_name2"};
@@ -953,34 +1056,28 @@ public class CatalogHiveIT extends BaseIT {
IdentityPartition partitionAdded2 =
(IdentityPartition) createdTable.supportPartitions().addPartition(identity2);
// Directly get partition from Hive metastore to check if the partition is created successfully.
- org.apache.hadoop.hive.metastore.api.Partition partitionGot2 =
- hiveClientPool.run(
- client -> client.getPartition(schemaName, createdTable.name(), partitionAdded2.name()));
+ HivePartition partitionGot2 =
+ loadHivePartition(schemaName, createdTable.name(), partitionAdded2.name());
+ List<String> partitionValues2 = partitionValues(partitionGot2);
Assertions.assertEquals(
- partitionAdded2.values()[0].value().toString(), partitionGot2.getValues().get(0));
+ partitionAdded2.values()[0].value().toString(), partitionValues2.get(0));
Assertions.assertEquals(
- partitionAdded2.values()[1].value().toString(), partitionGot2.getValues().get(1));
- Assertions.assertEquals(partitionAdded2.properties(), partitionGot2.getParameters());
+ partitionAdded2.values()[1].value().toString(), partitionValues2.get(1));
+ Assertions.assertEquals(partitionAdded2.properties(), partitionGot2.properties());
// test drop partition "hive_col_name2=2024-01-02"
boolean dropRes2 = createdTable.supportPartitions().dropPartition("hive_col_name2=2024-01-02");
Assertions.assertTrue(dropRes2);
Assertions.assertThrows(
- NoSuchObjectException.class,
- () ->
- hiveClientPool.run(
- client ->
- client.getPartition(schemaName, createdTable.name(), partitionAdded1.name())));
- Path partitionDirectory1 = new Path(hiveTab.getSd().getLocation() + identity1.name());
+ NoSuchPartitionException.class,
+ () -> loadHivePartition(schemaName, createdTable.name(), partitionAdded1.name()));
+ Path partitionDirectory1 = new Path(tableLocation + identity1.name());
Assertions.assertFalse(
fileSystem.exists(partitionDirectory1), "The partition directory should not exist");
Assertions.assertThrows(
- NoSuchObjectException.class,
- () ->
- hiveClientPool.run(
- client ->
- client.getPartition(schemaName, createdTable.name(), partitionAdded2.name())));
- Path partitionDirectory2 = new Path(hiveTab.getSd().getLocation() + identity2.name());
+ NoSuchPartitionException.class,
+ () -> loadHivePartition(schemaName, createdTable.name(), partitionAdded2.name()));
+ Path partitionDirectory2 = new Path(tableLocation + identity2.name());
Assertions.assertFalse(
fileSystem.exists(partitionDirectory2), "The partition directory should not exist");
@@ -1014,65 +1111,30 @@ public class CatalogHiveIT extends BaseIT {
new Transform[] {
Transforms.identity(columns[1].name()), Transforms.identity(columns[2].name())
});
- org.apache.hadoop.hive.metastore.api.Table actualTable =
- hiveClientPool.run(client -> client.getTable(schemaName, table.name()));
+ HiveTable actualTable = loadHiveTable(schemaName, table.name());
checkTableReadWrite(actualTable);
return table;
}
- private void assertTableEquals(
- Table createdTable, org.apache.hadoop.hive.metastore.api.Table hiveTab) {
- Distribution distribution = createdTable.distribution();
- SortOrder[] sortOrders = createdTable.sortOrder();
-
- List<FieldSchema> actualColumns = new ArrayList<>();
- actualColumns.addAll(hiveTab.getSd().getCols());
- actualColumns.addAll(hiveTab.getPartitionKeys());
- Assertions.assertEquals(schemaName.toLowerCase(), hiveTab.getDbName());
- Assertions.assertEquals(tableName.toLowerCase(), hiveTab.getTableName());
- Assertions.assertEquals("MANAGED_TABLE", hiveTab.getTableType());
- Assertions.assertEquals(createdTable.comment(), hiveTab.getParameters().get("comment"));
-
- Assertions.assertEquals(HIVE_COL_NAME1, actualColumns.get(0).getName());
- Assertions.assertEquals("tinyint", actualColumns.get(0).getType());
- Assertions.assertEquals("col_1_comment", actualColumns.get(0).getComment());
-
- Assertions.assertEquals(HIVE_COL_NAME2, actualColumns.get(1).getName());
- Assertions.assertEquals("date", actualColumns.get(1).getType());
- Assertions.assertEquals("col_2_comment", actualColumns.get(1).getComment());
-
- Assertions.assertEquals(HIVE_COL_NAME3, actualColumns.get(2).getName());
- Assertions.assertEquals("string", actualColumns.get(2).getType());
- Assertions.assertEquals("col_3_comment", actualColumns.get(2).getComment());
-
- Assertions.assertEquals(
- distribution == null ? 0 : distribution.number(), hiveTab.getSd().getNumBuckets());
-
- List<String> resultDistributionCols =
- distribution == null
- ? Collections.emptyList()
- : Arrays.stream(distribution.expressions())
- .map(t -> ((NamedReference.FieldReference) t).fieldName()[0])
- .collect(Collectors.toList());
- Assertions.assertEquals(resultDistributionCols, hiveTab.getSd().getBucketCols());
-
- for (int i = 0; i < sortOrders.length; i++) {
- Assertions.assertEquals(
- sortOrders[i].direction() == SortDirection.ASCENDING ? 1 : 0,
- hiveTab.getSd().getSortCols().get(i).getOrder());
- Assertions.assertEquals(
- ((NamedReference.FieldReference) sortOrders[i].expression()).fieldName()[0],
- hiveTab.getSd().getSortCols().get(i).getCol());
+ private void assertTableEquals(Table createdTable, HiveTable hiveTable) {
+ Assertions.assertEquals(schemaName.toLowerCase(), hiveTable.databaseName());
+ Assertions.assertEquals(createdTable.name(), hiveTable.name());
+ Assertions.assertEquals(createdTable.comment(), hiveTable.comment());
+
+ Column[] expectedColumns = createdTable.columns();
+ Column[] actualColumns = hiveTable.columns();
+ Assertions.assertEquals(expectedColumns.length, actualColumns.length);
+ for (int i = 0; i < expectedColumns.length; i++) {
+ Column expectedColumn = expectedColumns[i];
+ Column actualColumn = actualColumns[i];
+ Assertions.assertEquals(expectedColumn.name(), actualColumn.name());
+ Assertions.assertEquals(expectedColumn.dataType(), actualColumn.dataType());
+ Assertions.assertEquals(expectedColumn.comment(), actualColumn.comment());
}
- Assertions.assertNotNull(createdTable.partitioning());
- Assertions.assertEquals(createdTable.partitioning().length, hiveTab.getPartitionKeys().size());
- List<String> partitionKeys =
- Arrays.stream(createdTable.partitioning())
- .map(p -> ((Transform.SingleFieldTransform) p).fieldName()[0])
- .collect(Collectors.toList());
- List<String> hivePartitionKeys =
- hiveTab.getPartitionKeys().stream().map(FieldSchema::getName).collect(Collectors.toList());
- Assertions.assertEquals(partitionKeys, hivePartitionKeys);
+
+ compareDistributions(createdTable.distribution(), hiveTable.distribution());
+ compareSortOrders(createdTable.sortOrder(), hiveTable.sortOrder());
+ comparePartitioning(createdTable.partitioning(), hiveTable.partitionFieldNames());
}
@Test
@@ -1123,26 +1185,26 @@ public class CatalogHiveIT extends BaseIT {
Assertions.assertEquals(AuthConstants.ANONYMOUS_USER, alteredTable.auditInfo().lastModifier());
// Direct get table from Hive metastore to check if the table is altered successfully.
- org.apache.hadoop.hive.metastore.api.Table hiveTab =
- hiveClientPool.run(client -> client.getTable(schemaName, ALTER_TABLE_NAME));
- Assertions.assertEquals(schemaName.toLowerCase(), hiveTab.getDbName());
- Assertions.assertEquals(ALTER_TABLE_NAME, hiveTab.getTableName());
- Assertions.assertEquals("val2_new", hiveTab.getParameters().get("key2"));
-
- Assertions.assertEquals(HIVE_COL_NAME1, hiveTab.getSd().getCols().get(0).getName());
- Assertions.assertEquals("int", hiveTab.getSd().getCols().get(0).getType());
- Assertions.assertEquals("comment_new", hiveTab.getSd().getCols().get(0).getComment());
-
- Assertions.assertEquals("col_2_new", hiveTab.getSd().getCols().get(1).getName());
- Assertions.assertEquals("date", hiveTab.getSd().getCols().get(1).getType());
- Assertions.assertEquals("col_2_comment", hiveTab.getSd().getCols().get(1).getComment());
-
- Assertions.assertEquals("col_4", hiveTab.getSd().getCols().get(2).getName());
- Assertions.assertEquals("string", hiveTab.getSd().getCols().get(2).getType());
- Assertions.assertNull(hiveTab.getSd().getCols().get(2).getComment());
-
- Assertions.assertEquals(1, hiveTab.getPartitionKeys().size());
- Assertions.assertEquals(columns[2].name(), hiveTab.getPartitionKeys().get(0).getName());
+ HiveTable hiveTab = loadHiveTable(schemaName, ALTER_TABLE_NAME);
+ Assertions.assertEquals(schemaName.toLowerCase(), hiveTab.databaseName());
+ Assertions.assertEquals(ALTER_TABLE_NAME, hiveTab.name());
+ Assertions.assertEquals("val2_new", hiveTab.properties().get("key2"));
+
+ Column[] hiveColumns = hiveTab.columns();
+ Assertions.assertEquals(HIVE_COL_NAME1, hiveColumns[0].name());
+ Assertions.assertEquals(Types.IntegerType.get(), hiveColumns[0].dataType());
+ Assertions.assertEquals("comment_new", hiveColumns[0].comment());
+
+ Assertions.assertEquals("col_2_new", hiveColumns[1].name());
+ Assertions.assertEquals(Types.DateType.get(), hiveColumns[1].dataType());
+ Assertions.assertEquals("col_2_comment", hiveColumns[1].comment());
+
+ Assertions.assertEquals("col_4", hiveColumns[2].name());
+ Assertions.assertEquals(Types.StringType.get(), hiveColumns[2].dataType());
+ Assertions.assertNull(hiveColumns[2].comment());
+
+ Assertions.assertEquals(1, hiveTab.partitionFieldNames().size());
+ Assertions.assertEquals(columns[2].name(), hiveTab.partitionFieldNames().get(0));
assertDefaultTableProperties(alteredTable, hiveTab);
checkTableReadWrite(hiveTab);
@@ -1235,27 +1297,26 @@ public class CatalogHiveIT extends BaseIT {
"please ensure that the type of the new column position is compatible with the old one"));
}
- private void assertDefaultTableProperties(
- Table gravitinoReturnTable, org.apache.hadoop.hive.metastore.api.Table actualTable) {
+ private void assertDefaultTableProperties(Table gravitinoReturnTable, HiveTable actualTable) {
HiveTablePropertiesMetadata tablePropertiesMetadata = new HiveTablePropertiesMetadata();
Assertions.assertEquals(
tablePropertiesMetadata.getDefaultValue(SERDE_LIB),
- actualTable.getSd().getSerdeInfo().getSerializationLib());
+ actualTable.properties().get(SERDE_LIB));
Assertions.assertEquals(
tablePropertiesMetadata.getDefaultValue(INPUT_FORMAT),
- actualTable.getSd().getInputFormat());
+ actualTable.properties().get(INPUT_FORMAT));
Assertions.assertEquals(
tablePropertiesMetadata.getDefaultValue(OUTPUT_FORMAT),
- actualTable.getSd().getOutputFormat());
+ actualTable.properties().get(OUTPUT_FORMAT));
Assertions.assertEquals(
((TableType) tablePropertiesMetadata.getDefaultValue(TABLE_TYPE)).name(),
- actualTable.getTableType());
- Assertions.assertEquals(tableName.toLowerCase(), actualTable.getSd().getSerdeInfo().getName());
+ actualTable.properties().get(TABLE_TYPE));
+ Assertions.assertEquals(tableName.toLowerCase(), actualTable.properties().get(SERDE_NAME));
Assertions.assertEquals(
((Boolean) tablePropertiesMetadata.getDefaultValue(EXTERNAL)).toString().toUpperCase(),
- actualTable.getParameters().get(EXTERNAL));
- Assertions.assertNotNull(actualTable.getParameters().get(COMMENT));
- Assertions.assertNotNull(actualTable.getSd().getLocation());
+ actualTable.properties().get(EXTERNAL));
+ Assertions.assertNotNull(actualTable.properties().get(COMMENT));
+ Assertions.assertNotNull(actualTable.properties().get(LOCATION));
Assertions.assertNotNull(gravitinoReturnTable.properties().get(TRANSIENT_LAST_DDL_TIME));
}
@@ -1272,9 +1333,7 @@ public class CatalogHiveIT extends BaseIT {
catalog.asTableCatalog().dropTable(NameIdentifier.of(schemaName, ALTER_TABLE_NAME));
// Directly get table from Hive metastore to check if the table is dropped successfully.
- assertThrows(
- NoSuchObjectException.class,
- () -> hiveClientPool.run(client -> client.getTable(schemaName, ALTER_TABLE_NAME)));
+ assertThrows(NoSuchTableException.class, () -> loadHiveTable(schemaName, ALTER_TABLE_NAME));
}
@Test
@@ -1299,8 +1358,8 @@ public class CatalogHiveIT extends BaseIT {
Assertions.assertFalse(properties2.containsKey("key1"));
Assertions.assertEquals("val2-alter", properties2.get("key2"));
- Database database = hiveClientPool.run(client -> client.getDatabase(schemaName));
- Map<String, String> properties3 = database.getParameters();
+ HiveSchema database = loadHiveSchema(schemaName);
+ Map<String, String> properties3 = database.properties();
Assertions.assertFalse(properties3.containsKey("key1"));
Assertions.assertEquals("val2-alter", properties3.get("key2"));
}
@@ -1385,7 +1444,7 @@ public class CatalogHiveIT extends BaseIT {
Catalog.Type.RELATIONAL,
provider,
"comment",
- ImmutableMap.of(METASTORE_URIS, HIVE_METASTORE_URIS));
+ ImmutableMap.of(METASTORE_URIS, hiveMetastoreUris));
Catalog catalog = metalake.loadCatalog(catalogName);
// Test rename catalog
@@ -1484,13 +1543,14 @@ public class CatalogHiveIT extends BaseIT {
new Transform[] {Transforms.identity(columns[2].name())});
// Directly get table from Hive metastore to check if the table is created successfully.
- org.apache.hadoop.hive.metastore.api.Table hiveTab =
- hiveClientPool.run(client -> client.getTable(schemaName, tableName));
+ HiveTable hiveTab = loadHiveTable(schemaName, tableName);
checkTableReadWrite(hiveTab);
- Assertions.assertEquals(MANAGED_TABLE.name(), hiveTab.getTableType());
- Path tableDirectory = new Path(hiveTab.getSd().getLocation());
+ Assertions.assertEquals(MANAGED_TABLE.name(), hiveTab.properties().get(TABLE_TYPE));
+ String tableLocation = hiveTab.properties().get(LOCATION);
+ Assertions.assertNotNull(tableLocation, "Table location should not be null");
+ Path tableDirectory = new Path(tableLocation);
catalog.asTableCatalog().dropTable(NameIdentifier.of(schemaName, tableName));
- Boolean existed = hiveClientPool.run(client -> client.tableExists(schemaName, tableName));
+ Boolean existed = hiveTableExists(schemaName, tableName);
Assertions.assertFalse(existed, "The Hive table should not exist");
Assertions.assertFalse(
fileSystem.exists(tableDirectory), "The table directory should not exist");
@@ -1511,15 +1571,16 @@ public class CatalogHiveIT extends BaseIT {
properties,
new Transform[] {Transforms.identity(columns[2].name())});
// Directly get table from Hive metastore to check if the table is created successfully.
- org.apache.hadoop.hive.metastore.api.Table hiveTab =
- hiveClientPool.run(client -> client.getTable(schemaName, tableName));
+ HiveTable hiveTab = loadHiveTable(schemaName, tableName);
checkTableReadWrite(hiveTab);
- Assertions.assertEquals(EXTERNAL_TABLE.name(), hiveTab.getTableType());
+ Assertions.assertEquals(EXTERNAL_TABLE.name(), hiveTab.properties().get(TABLE_TYPE));
catalog.asTableCatalog().dropTable(NameIdentifier.of(schemaName, tableName));
- Boolean existed = hiveClientPool.run(client -> client.tableExists(schemaName, tableName));
+ Boolean existed = hiveTableExists(schemaName, tableName);
Assertions.assertFalse(existed, "The table should be not exist");
- Path tableDirectory = new Path(hiveTab.getSd().getLocation());
+ String tableLocation = hiveTab.properties().get(LOCATION);
+ Assertions.assertNotNull(tableLocation, "Table location should not be null");
+ Path tableDirectory = new Path(tableLocation);
Assertions.assertTrue(
fileSystem.listStatus(tableDirectory).length > 0, "The table should not be empty");
}
@@ -1537,18 +1598,19 @@ public class CatalogHiveIT extends BaseIT {
new Transform[] {Transforms.identity(columns[2].name())});
// Directly get table from Hive metastore to check if the table is created successfully.
- org.apache.hadoop.hive.metastore.api.Table hiveTab =
- hiveClientPool.run(client -> client.getTable(schemaName, tableName));
+ HiveTable hiveTab = loadHiveTable(schemaName, tableName);
checkTableReadWrite(hiveTab);
- Assertions.assertEquals(MANAGED_TABLE.name(), hiveTab.getTableType());
+ Assertions.assertEquals(MANAGED_TABLE.name(), hiveTab.properties().get(TABLE_TYPE));
catalog.asTableCatalog().purgeTable(NameIdentifier.of(schemaName, tableName));
- Boolean existed = hiveClientPool.run(client -> client.tableExists(schemaName, tableName));
+ Boolean existed = hiveTableExists(schemaName, tableName);
Assertions.assertFalse(existed, "The Hive table should not exist");
// purging non-exist table should return false
Assertions.assertFalse(
catalog.asTableCatalog().purgeTable(NameIdentifier.of(schemaName, tableName)),
"The table should not be found in the catalog");
- Path tableDirectory = new Path(hiveTab.getSd().getLocation());
+ String tableLocation = hiveTab.properties().get(LOCATION);
+ Assertions.assertNotNull(tableLocation, "Table location should not be null");
+ Path tableDirectory = new Path(tableLocation);
Assertions.assertFalse(
fileSystem.exists(tableDirectory), "The table directory should not exist");
Path trashDirectory = fileSystem.getTrashRoot(tableDirectory);
@@ -1571,10 +1633,9 @@ public class CatalogHiveIT extends BaseIT {
new Transform[] {Transforms.identity(columns[2].name())});
// Directly get table from Hive metastore to check if the table is created successfully.
- org.apache.hadoop.hive.metastore.api.Table hiveTab =
- hiveClientPool.run(client -> client.getTable(schemaName, tableName));
+ HiveTable hiveTab = loadHiveTable(schemaName, tableName);
checkTableReadWrite(hiveTab);
- Assertions.assertEquals(EXTERNAL_TABLE.name(), hiveTab.getTableType());
+ Assertions.assertEquals(EXTERNAL_TABLE.name(), hiveTab.properties().get(TABLE_TYPE));
TableCatalog tableCatalog = catalog.asTableCatalog();
NameIdentifier id = NameIdentifier.of(schemaName, tableName);
Assertions.assertThrows(
@@ -1584,9 +1645,11 @@ public class CatalogHiveIT extends BaseIT {
},
"Can't purge a external Hive table");
- Boolean existed = hiveClientPool.run(client -> client.tableExists(schemaName, tableName));
+ Boolean existed = hiveTableExists(schemaName, tableName);
Assertions.assertTrue(existed, "The table should be still exist");
- Path tableDirectory = new Path(hiveTab.getSd().getLocation());
+ String tableLocation = hiveTab.properties().get(LOCATION);
+ Assertions.assertNotNull(tableLocation, "Table location should not be null");
+ Path tableDirectory = new Path(tableLocation);
Assertions.assertTrue(
fileSystem.listStatus(tableDirectory).length > 0, "The table should not be empty");
}
@@ -1604,11 +1667,7 @@ public class CatalogHiveIT extends BaseIT {
new Transform[] {Transforms.identity(columns[2].name())});
// Directly drop table from Hive metastore.
- hiveClientPool.run(
- client -> {
- client.dropTable(schemaName, tableName, true, false, false);
- return null;
- });
+ dropHiveTable(schemaName, tableName, true, false);
// Drop table from catalog, drop non-exist table should return false;
Assertions.assertFalse(
@@ -1633,11 +1692,7 @@ public class CatalogHiveIT extends BaseIT {
new Transform[] {Transforms.identity(columns[2].name())});
// Directly drop table from Hive metastore.
- hiveClientPool.run(
- client -> {
- client.dropTable(schemaName, tableName, true, false, true);
- return null;
- });
+ dropHiveTable(schemaName, tableName, true, true);
// Drop table from catalog, drop non-exist table should return false;
Assertions.assertFalse(
@@ -1666,7 +1721,7 @@ public class CatalogHiveIT extends BaseIT {
Map<String, String> properties = Maps.newHashMap();
String nameOfCatalog = GravitinoITUtils.genRandomName("catalog");
// Wrong Hive HIVE_METASTORE_URIS
- String wrongHiveMetastoreURI = HIVE_METASTORE_URIS + "_wrong";
+ String wrongHiveMetastoreURI = hiveMetastoreUris + "_wrong";
properties.put(METASTORE_URIS, wrongHiveMetastoreURI);
Catalog createdCatalog =
metalake.createCatalog(
@@ -1685,8 +1740,8 @@ public class CatalogHiveIT extends BaseIT {
Catalog newCatalog =
metalake.alterCatalog(
- nameOfCatalog, CatalogChange.setProperty(METASTORE_URIS, HIVE_METASTORE_URIS));
- Assertions.assertEquals(HIVE_METASTORE_URIS, newCatalog.properties().get(METASTORE_URIS));
+ nameOfCatalog, CatalogChange.setProperty(METASTORE_URIS, hiveMetastoreUris));
+ Assertions.assertEquals(hiveMetastoreUris, newCatalog.properties().get(METASTORE_URIS));
// The URI has restored, so it should not throw exception.
Assertions.assertDoesNotThrow(
@@ -1700,7 +1755,7 @@ public class CatalogHiveIT extends BaseIT {
private void createCatalogWithCustomOperation(String catalogName, String customImpl) {
Map<String, String> properties = Maps.newHashMap();
- properties.put(METASTORE_URIS, HIVE_METASTORE_URIS);
+ properties.put(METASTORE_URIS, hiveMetastoreUris);
properties.put(BaseCatalog.CATALOG_OPERATION_IMPL, customImpl);
Catalog catalog =
diff --git a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHive3IT.java b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHive3IT.java
new file mode 100644
index 0000000000..60e8facb4e
--- /dev/null
+++ b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHive3IT.java
@@ -0,0 +1,38 @@
+/*
+ * 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.gravitino.catalog.hive.integration.test;
+
+import com.google.common.collect.ImmutableMap;
+import org.apache.gravitino.integration.test.container.HiveContainer;
+import org.junit.jupiter.api.Tag;
+
+@Tag("gravitino-docker-test")
+public class CatalogHive3IT extends CatalogHive2IT {
+ @Override
+ protected void startNecessaryContainer() {
+ containerSuite.startHiveContainer(
+ ImmutableMap.of(HiveContainer.HIVE_RUNTIME_VERSION, HiveContainer.HIVE3));
+
+ hiveMetastoreUris =
+ String.format(
+ "thrift://%s:%d",
+ containerSuite.getHiveContainer().getContainerIpAddress(),
+ HiveContainer.HIVE_METASTORE_PORT);
+ }
+}
diff --git a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHiveABSIT.java b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHiveABSIT.java
index 4f50aeaf80..a225e0ca0d 100644
--- a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHiveABSIT.java
+++ b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHiveABSIT.java
@@ -37,7 +37,7 @@ import org.junit.jupiter.api.condition.EnabledIf;
@EnabledIf(
value = "isAzureBlobStorageConfigured",
disabledReason = "Azure Blob Storage is not prepared.")
-public class CatalogHiveABSIT extends CatalogHiveIT {
+public class CatalogHiveABSIT extends CatalogHive2IT {
private static final String ABS_BUCKET_NAME = System.getenv("ABS_CONTAINER_NAME");
private static final String ABS_USER_ACCOUNT_NAME = System.getenv("ABS_ACCOUNT_NAME");
@@ -56,7 +56,7 @@ public class CatalogHiveABSIT extends CatalogHiveIT {
containerSuite.startHiveContainerWithS3(hiveContainerEnv);
- HIVE_METASTORE_URIS =
+ hiveMetastoreUris =
String.format(
"thrift://%s:%d",
containerSuite.getHiveContainerWithS3().getContainerIpAddress(),
@@ -83,7 +83,7 @@ public class CatalogHiveABSIT extends CatalogHiveIT {
SparkSession.builder()
.master("local[1]")
.appName("Hive Catalog integration test")
- .config("hive.metastore.uris", HIVE_METASTORE_URIS)
+ .config("hive.metastore.uris", hiveMetastoreUris)
.config(
"spark.sql.warehouse.dir",
String.format(
diff --git a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHiveGCSIT.java b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHiveGCSIT.java
index 343c3fd387..d9dbc02503 100644
--- a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHiveGCSIT.java
+++ b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHiveGCSIT.java
@@ -33,7 +33,7 @@ import org.junit.jupiter.api.condition.EnabledIf;
import org.testcontainers.utility.MountableFile;
@EnabledIf(value = "isGCSConfigured", disabledReason = "Google Cloud Storage(GCS) is not prepared.")
-public class CatalogHiveGCSIT extends CatalogHiveIT {
+public class CatalogHiveGCSIT extends CatalogHive2IT {
private static final String GCS_BUCKET_NAME = System.getenv("GCS_BUCKET_NAME");
private static final String GCS_ACCOUNT_JSON_FILE =
@@ -51,7 +51,7 @@ public class CatalogHiveGCSIT extends CatalogHiveIT {
containerSuite.startHiveContainerWithS3(hiveContainerEnv);
- HIVE_METASTORE_URIS =
+ hiveMetastoreUris =
String.format(
"thrift://%s:%d",
containerSuite.getHiveContainerWithS3().getContainerIpAddress(),
@@ -81,7 +81,7 @@ public class CatalogHiveGCSIT extends CatalogHiveIT {
SparkSession.builder()
.master("local[1]")
.appName("Hive Catalog integration test")
- .config("hive.metastore.uris", HIVE_METASTORE_URIS)
+ .config("hive.metastore.uris", hiveMetastoreUris)
.config(
"spark.sql.warehouse.dir",
String.format(String.format("gs://%s/user/hive/warehouse", GCS_BUCKET_NAME)))
diff --git a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHiveS3IT.java b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHiveS3IT.java
index 20265b8135..b8cf284eca 100644
--- a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHiveS3IT.java
+++ b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHiveS3IT.java
@@ -34,7 +34,7 @@ import org.slf4j.LoggerFactory;
import org.testcontainers.containers.Container;
import org.testcontainers.shaded.org.awaitility.Awaitility;
-public class CatalogHiveS3IT extends CatalogHiveIT {
+public class CatalogHiveS3IT extends CatalogHive2IT {
private static final Logger LOGGER = LoggerFactory.getLogger(CatalogHiveS3IT.class);
@@ -110,7 +110,7 @@ public class CatalogHiveS3IT extends CatalogHiveIT {
containerSuite.startHiveContainerWithS3(hiveContainerEnv);
- HIVE_METASTORE_URIS =
+ hiveMetastoreUris =
String.format(
"thrift://%s:%d",
containerSuite.getHiveContainerWithS3().getContainerIpAddress(),
@@ -138,7 +138,7 @@ public class CatalogHiveS3IT extends CatalogHiveIT {
SparkSession.builder()
.master("local[1]")
.appName("Hive Catalog integration test")
- .config("hive.metastore.uris", HIVE_METASTORE_URIS)
+ .config("hive.metastore.uris", hiveMetastoreUris)
.config(
"spark.sql.warehouse.dir",
String.format(
diff --git a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/ProxyCatalogHiveIT.java b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/ProxyCatalogHiveIT.java
index a1194c6105..b82dba2bdb 100644
--- a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/ProxyCatalogHiveIT.java
+++ b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/ProxyCatalogHiveIT.java
@@ -20,6 +20,7 @@ package org.apache.gravitino.catalog.hive.integration.test;
import static org.apache.gravitino.catalog.hive.HiveCatalogPropertiesMetadata.IMPERSONATION_ENABLE;
import static org.apache.gravitino.catalog.hive.HiveCatalogPropertiesMetadata.METASTORE_URIS;
+import static org.apache.gravitino.catalog.hive.HiveConstants.LOCATION;
import static org.apache.gravitino.server.GravitinoServer.WEBSERVER_CONF_PREFIX;
import com.google.common.collect.ImmutableMap;
@@ -27,6 +28,7 @@ import com.google.common.collect.Maps;
import java.time.LocalDate;
import java.util.Collections;
import java.util.Map;
+import java.util.Properties;
import org.apache.gravitino.Catalog;
import org.apache.gravitino.Configs;
import org.apache.gravitino.NameIdentifier;
@@ -36,6 +38,9 @@ import org.apache.gravitino.client.GravitinoAdminClient;
import org.apache.gravitino.client.GravitinoMetalake;
import org.apache.gravitino.dto.rel.partitioning.Partitioning;
import org.apache.gravitino.hive.HiveClientPool;
+import org.apache.gravitino.hive.HivePartition;
+import org.apache.gravitino.hive.HiveSchema;
+import org.apache.gravitino.hive.HiveTable;
import org.apache.gravitino.integration.test.container.ContainerSuite;
import org.apache.gravitino.integration.test.container.HiveContainer;
import org.apache.gravitino.integration.test.util.BaseIT;
@@ -55,7 +60,6 @@ import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.conf.HiveConf;
-import org.apache.hadoop.hive.metastore.api.Database;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
@@ -73,6 +77,7 @@ public class ProxyCatalogHiveIT extends BaseIT {
private static final String PROVIDER = "hive";
private static final String EXPECT_USER = "gravitino";
private static final String HADOOP_USER_NAME = "HADOOP_USER_NAME";
+ private static final String HMS_CATALOG = "";
private static final ContainerSuite containerSuite = ContainerSuite.getInstance();
private static GravitinoMetalake metalake;
@@ -109,8 +114,11 @@ public class ProxyCatalogHiveIT extends BaseIT {
HiveConf hiveConf = new HiveConf();
hiveConf.set(HiveConf.ConfVars.METASTOREURIS.varname, HIVE_METASTORE_URIS);
+ Properties hiveClientProperties = new Properties();
+ hiveClientProperties.setProperty(HiveConf.ConfVars.METASTOREURIS.varname, HIVE_METASTORE_URIS);
+
// Check if Hive client can connect to Hive metastore
- hiveClientPool = new HiveClientPool(1, hiveConf);
+ hiveClientPool = new HiveClientPool("hive", 1, hiveClientProperties);
Configuration conf = new Configuration();
conf.set(
@@ -154,10 +162,10 @@ public class ProxyCatalogHiveIT extends BaseIT {
String comment = "comment";
createSchema(schemaName, comment);
- Database db = hiveClientPool.run(client -> client.getDatabase(schemaName));
- Assertions.assertEquals(EXPECT_USER, db.getOwnerName());
- Assertions.assertEquals(
- EXPECT_USER, hdfs.getFileStatus(new Path(db.getLocationUri())).getOwner());
+ HiveSchema hiveSchema = loadHiveSchema(schemaName);
+ Assertions.assertEquals(EXPECT_USER, hiveSchema.auditInfo().creator());
+ String schemaLocation = hiveSchema.properties().get(LOCATION);
+ Assertions.assertEquals(EXPECT_USER, hdfs.getFileStatus(new Path(schemaLocation)).getOwner());
// create schema with exception using the system user
Map<String, String> properties = Maps.newHashMap();
@@ -177,10 +185,10 @@ public class ProxyCatalogHiveIT extends BaseIT {
// Test the client using `withSimpleAuth(expectUser)`.
anotherCatalogWithUsername.asSchemas().createSchema(anotherSchemaName, comment, properties);
- db = hiveClientPool.run(client -> client.getDatabase(schemaName));
- Assertions.assertEquals(EXPECT_USER, db.getOwnerName());
- Assertions.assertEquals(
- EXPECT_USER, hdfs.getFileStatus(new Path(db.getLocationUri())).getOwner());
+ hiveSchema = loadHiveSchema(schemaName);
+ Assertions.assertEquals(EXPECT_USER, hiveSchema.auditInfo().creator());
+ schemaLocation = hiveSchema.properties().get(LOCATION);
+ Assertions.assertEquals(EXPECT_USER, hdfs.getFileStatus(new Path(schemaLocation)).getOwner());
// Test the client using `withSimpleAuth(unknownUser)`
properties.put(
@@ -221,9 +229,8 @@ public class ProxyCatalogHiveIT extends BaseIT {
Table createdTable = catalog.asTableCatalog().loadTable(nameIdentifier);
String location = createdTable.properties().get("location");
Assertions.assertEquals(EXPECT_USER, hdfs.getFileStatus(new Path(location)).getOwner());
- org.apache.hadoop.hive.metastore.api.Table hiveTab =
- hiveClientPool.run(client -> client.getTable(schemaName, tableName));
- Assertions.assertEquals(EXPECT_USER, hiveTab.getOwner());
+ HiveTable hiveTab = loadHiveTable(schemaName, tableName);
+ Assertions.assertEquals(EXPECT_USER, hiveTab.auditInfo().creator());
// create table with exception with system user
TableCatalog tableCatalog = anotherCatalog.asTableCatalog();
@@ -245,9 +252,8 @@ public class ProxyCatalogHiveIT extends BaseIT {
anotherCatalogWithUsername.asTableCatalog().loadTable(nameIdentifier);
String anotherLocation = anotherCreatedTable.properties().get("location");
Assertions.assertEquals(EXPECT_USER, hdfs.getFileStatus(new Path(anotherLocation)).getOwner());
- org.apache.hadoop.hive.metastore.api.Table anotherHiveTab =
- hiveClientPool.run(client -> client.getTable(schemaName, anotherTableName));
- Assertions.assertEquals(EXPECT_USER, anotherHiveTab.getOwner());
+ HiveTable anotherHiveTab = loadHiveTable(schemaName, anotherTableName);
+ Assertions.assertEquals(EXPECT_USER, anotherHiveTab.auditInfo().creator());
// Test the client using `withSimpleAuth(not-existing)`
NameIdentifier anotherIdentWithNotExisting = NameIdentifier.of(schemaName, "new_table");
@@ -320,11 +326,12 @@ public class ProxyCatalogHiveIT extends BaseIT {
Partition partition = table.supportPartitions().addPartition(identity);
- org.apache.hadoop.hive.metastore.api.Partition partitionGot =
- hiveClientPool.run(client -> client.getPartition(schemaName, tableName, partition.name()));
-
+ HiveTable hiveTable = loadHiveTable(schemaName, tableName);
+ HivePartition partitionGot = loadHivePartition(schemaName, tableName, partition.name());
+ String tableLocation = hiveTable.properties().get(LOCATION);
+ Assertions.assertNotNull(tableLocation, "Table location should not be null");
Assertions.assertEquals(
- EXPECT_USER, hdfs.getFileStatus(new Path(partitionGot.getSd().getLocation())).getOwner());
+ EXPECT_USER, hdfs.getFileStatus(new Path(tableLocation, partitionGot.name())).getOwner());
Literal<?> anotherSecondaryPartition = Literals.stringLiteral("gravitino_it_test3");
Partition anotherIdentity =
@@ -351,13 +358,11 @@ public class ProxyCatalogHiveIT extends BaseIT {
.loadTable(nameIdentifier)
.supportPartitions()
.addPartition(anotherIdentity);
- org.apache.hadoop.hive.metastore.api.Partition anotherPartitionGot =
- hiveClientPool.run(
- client -> client.getPartition(schemaName, tableName, anotherPartition.name()));
-
+ HivePartition anotherPartitionGot =
+ loadHivePartition(schemaName, tableName, anotherPartition.name());
Assertions.assertEquals(
EXPECT_USER,
- hdfs.getFileStatus(new Path(anotherPartitionGot.getSd().getLocation())).getOwner());
+ hdfs.getFileStatus(new Path(tableLocation, anotherPartitionGot.name())).getOwner());
// Test the client using `withSimpleAuth(not-existing)`.
Literal<?> anotherNewSecondaryPartition = Literals.stringLiteral("gravitino_it_test4");
@@ -422,4 +427,22 @@ public class ProxyCatalogHiveIT extends BaseIT {
anotherCatalogWithNotExistingName =
anotherClientWithNotExistingName.loadMetalake(METALAKE_NAME).loadCatalog(CATALOG_NAME);
}
+
+ private static HiveSchema loadHiveSchema(String schemaName) throws InterruptedException {
+ return hiveClientPool.run(client -> client.getDatabase(HMS_CATALOG, schemaName));
+ }
+
+ private static HiveTable loadHiveTable(String schemaName, String tableName)
+ throws InterruptedException {
+ return hiveClientPool.run(client -> client.getTable(HMS_CATALOG, schemaName, tableName));
+ }
+
+ private static HivePartition loadHivePartition(
+ String schemaName, String tableName, String partitionName) throws InterruptedException {
+ return hiveClientPool.run(
+ client -> {
+ HiveTable hiveTable = client.getTable(HMS_CATALOG, schemaName, tableName);
+ return client.getPartition(hiveTable, partitionName);
+ });
+ }
}
diff --git a/catalogs/catalog-lakehouse-hudi/build.gradle.kts b/catalogs/catalog-lakehouse-hudi/build.gradle.kts
index 283fe93dab..738e0b2db7 100644
--- a/catalogs/catalog-lakehouse-hudi/build.gradle.kts
+++ b/catalogs/catalog-lakehouse-hudi/build.gradle.kts
@@ -33,15 +33,19 @@ dependencies {
implementation(project(":api")) {
exclude("*")
}
- implementation(project(":common")) {
+ implementation(project(":catalogs:catalog-common")) {
exclude("*")
}
implementation(project(":catalogs:hive-metastore-common"))
implementation(project(":core")) {
exclude("*")
}
+ implementation(project(":common")) {
+ exclude("*")
+ }
implementation(libs.commons.collections3)
+ implementation(libs.commons.lang3)
implementation(libs.commons.configuration1)
implementation(libs.commons.io)
implementation(libs.htrace.core4)
@@ -50,38 +54,9 @@ dependencies {
exclude("*")
}
implementation(libs.woodstox.core)
- implementation(libs.hive2.metastore) {
- exclude("ant")
- exclude("co.cask.tephra")
- exclude("com.fasterxml.jackson.core", "jackson-core")
- exclude("com.github.joshelser")
- exclude("com.google.code.findbugs", "jsr305")
- exclude("com.google.code.findbugs", "sr305")
- exclude("com.tdunning", "json")
- exclude("com.zaxxer", "HikariCP")
- exclude("io.dropwizard.metrics")
- exclude("javax.transaction", "transaction-api")
- exclude("org.apache.ant")
- exclude("org.apache.avro")
- exclude("org.apache.curator")
- exclude("org.apache.derby")
- exclude("org.apache.hadoop", "hadoop-yarn-server-resourcemanager")
- exclude("org.apache.hbase")
- exclude("org.apache.logging.log4j")
- exclude("org.apache.parquet", "parquet-hadoop-bundle")
- exclude("org.apache.zookeeper")
- exclude("org.datanucleus")
- exclude("org.eclipse.jetty.aggregate", "jetty-all")
- exclude("org.eclipse.jetty.orbit", "javax.servlet")
- exclude("org.openjdk.jol")
- exclude("org.slf4j")
- }
implementation(libs.hadoop2.common) {
exclude("*")
}
- implementation(libs.hadoop2.mapreduce.client.core) {
- exclude("*")
- }
implementation(libs.slf4j.api)
compileOnly(libs.lombok)
@@ -154,7 +129,7 @@ dependencies {
}
tasks {
- register("runtimeJars", Copy::class) {
+ val runtimeJars by registering(Copy::class) {
from(configurations.runtimeClasspath)
into("build/libs")
}
diff --git a/catalogs/catalog-lakehouse-hudi/src/main/java/org/apache/gravitino/catalog/lakehouse/hudi/HudiCatalogPropertiesMetadata.java b/catalogs/catalog-lakehouse-hudi/src/main/java/org/apache/gravitino/catalog/lakehouse/hudi/HudiCatalogPropertiesMetadata.java
index 1f5142a286..5ced457536 100644
--- a/catalogs/catalog-lakehouse-hudi/src/main/java/org/apache/gravitino/catalog/lakehouse/hudi/HudiCatalogPropertiesMetadata.java
+++ b/catalogs/catalog-lakehouse-hudi/src/main/java/org/apache/gravitino/catalog/lakehouse/hudi/HudiCatalogPropertiesMetadata.java
@@ -18,11 +18,13 @@
*/
package org.apache.gravitino.catalog.lakehouse.hudi;
+import static org.apache.gravitino.catalog.hive.HiveConstants.HIVE_DEFAULT_CATALOG;
import static org.apache.gravitino.connector.PropertyEntry.enumImmutablePropertyEntry;
import static org.apache.gravitino.connector.PropertyEntry.stringRequiredPropertyEntry;
import com.google.common.collect.ImmutableMap;
import java.util.Map;
+import org.apache.gravitino.catalog.hive.HiveConstants;
import org.apache.gravitino.catalog.lakehouse.hudi.backend.BackendType;
import org.apache.gravitino.connector.BaseCatalogPropertiesMetadata;
import org.apache.gravitino.connector.PropertyEntry;
@@ -30,6 +32,7 @@ import org.apache.gravitino.hive.ClientPropertiesMetadata;
public class HudiCatalogPropertiesMetadata extends BaseCatalogPropertiesMetadata {
public static final String CATALOG_BACKEND = "catalog-backend";
+ public static final String DEFAULT_CATALOG = HiveConstants.DEFAULT_CATALOG;
public static final String URI = "uri";
private static final ClientPropertiesMetadata CLIENT_PROPERTIES_METADATA =
new ClientPropertiesMetadata();
@@ -46,6 +49,14 @@ public class HudiCatalogPropertiesMetadata extends BaseCatalogPropertiesMetadata
null /* defaultValue */,
false /* hidden */,
false /* reserved */))
+ .put(
+ DEFAULT_CATALOG,
+ PropertyEntry.stringOptionalPropertyEntry(
+ DEFAULT_CATALOG,
+ "The default Hive Metastore catalog name used when talking to HMS",
+ true /* immutable */,
+ HIVE_DEFAULT_CATALOG,
+ false /* hidden */))
.put(
URI,
stringRequiredPropertyEntry(
diff --git a/catalogs/catalog-lakehouse-hudi/src/main/java/org/apache/gravitino/catalog/lakehouse/hudi/backend/hms/HudiHMSBackendOps.java b/catalogs/catalog-lakehouse-hudi/src/main/java/org/apache/gravitino/catalog/lakehouse/hudi/backend/hms/HudiHMSBackendOps.java
index 37a40a8314..cae2c3c4f0 100644
--- a/catalogs/catalog-lakehouse-hudi/src/main/java/org/apache/gravitino/catalog/lakehouse/hudi/backend/hms/HudiHMSBackendOps.java
+++ b/catalogs/catalog-lakehouse-hudi/src/main/java/org/apache/gravitino/catalog/lakehouse/hudi/backend/hms/HudiHMSBackendOps.java
@@ -18,23 +18,25 @@
*/
package org.apache.gravitino.catalog.lakehouse.hudi.backend.hms;
+import static org.apache.gravitino.catalog.hive.HiveConstants.HIVE_DEFAULT_CATALOG;
+import static org.apache.gravitino.catalog.hive.HiveConstants.HIVE_METASTORE_URIS;
+import static org.apache.gravitino.catalog.hive.HiveConstants.INPUT_FORMAT;
+import static org.apache.gravitino.catalog.lakehouse.hudi.HudiCatalogPropertiesMetadata.DEFAULT_CATALOG;
import static org.apache.gravitino.catalog.lakehouse.hudi.HudiCatalogPropertiesMetadata.URI;
import static org.apache.gravitino.connector.BaseCatalog.CATALOG_BYPASS_PREFIX;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
-import java.io.File;
-import java.io.IOException;
import java.util.List;
import java.util.Map;
+import java.util.Properties;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
+import org.apache.gravitino.Schema;
import org.apache.gravitino.SchemaChange;
import org.apache.gravitino.catalog.lakehouse.hudi.HudiSchema;
import org.apache.gravitino.catalog.lakehouse.hudi.HudiTable;
-import org.apache.gravitino.catalog.lakehouse.hudi.backend.hms.kerberos.AuthenticationConfig;
-import org.apache.gravitino.catalog.lakehouse.hudi.backend.hms.kerberos.KerberosClient;
import org.apache.gravitino.catalog.lakehouse.hudi.ops.HudiCatalogBackendOps;
import org.apache.gravitino.catalog.lakehouse.hudi.utils.CatalogUtils;
import org.apache.gravitino.exceptions.NoSuchCatalogException;
@@ -45,18 +47,12 @@ import org.apache.gravitino.exceptions.SchemaAlreadyExistsException;
import org.apache.gravitino.exceptions.TableAlreadyExistsException;
import org.apache.gravitino.hive.CachedClientPool;
import org.apache.gravitino.rel.Column;
+import org.apache.gravitino.rel.Table;
import org.apache.gravitino.rel.TableChange;
import org.apache.gravitino.rel.expressions.distributions.Distribution;
import org.apache.gravitino.rel.expressions.sorts.SortOrder;
import org.apache.gravitino.rel.expressions.transforms.Transform;
import org.apache.gravitino.rel.indexes.Index;
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.hive.conf.HiveConf;
-import org.apache.hadoop.hive.metastore.api.Database;
-import org.apache.hadoop.hive.metastore.api.NoSuchObjectException;
-import org.apache.hadoop.hive.metastore.api.Table;
-import org.apache.hadoop.hive.metastore.api.UnknownDBException;
-import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -64,35 +60,45 @@ public class HudiHMSBackendOps implements HudiCatalogBackendOps {
private static final Logger LOG = LoggerFactory.getLogger(HudiHMSBackendOps.class);
// Mapping from Gravitino config to Hive config
private static final Map<String, String> CONFIG_CONVERTER =
- ImmutableMap.of(URI, HiveConf.ConfVars.METASTOREURIS.varname);
+ ImmutableMap.of(URI, HIVE_METASTORE_URIS);
private static final String HUDI_PACKAGE_PREFIX = "org.apache.hudi";
- @VisibleForTesting CachedClientPool clientPool;
+ private String catalogName;
- public static final String GRAVITINO_KEYTAB_FORMAT = "keytabs/gravitino-lakehouse-hudi-%s-keytab";
+ @VisibleForTesting CachedClientPool clientPool;
@Override
public void initialize(Map<String, String> properties) {
- HiveConf hiveConf = buildHiveConfAndInitKerberosAuth(properties);
- this.clientPool = new CachedClientPool(hiveConf, properties);
+ Properties clientProperties = new Properties();
+
+ Map<String, String> byPassConfigs = Maps.newHashMap();
+ Map<String, String> convertedConfigs = Maps.newHashMap();
+ properties.forEach(
+ (key, value) -> {
+ if (key.startsWith(CATALOG_BYPASS_PREFIX)) {
+ byPassConfigs.put(key.substring(CATALOG_BYPASS_PREFIX.length()), value);
+ } else if (CONFIG_CONVERTER.containsKey(key)) {
+ convertedConfigs.put(CONFIG_CONVERTER.get(key), value);
+ } else {
+ convertedConfigs.put(key, value);
+ }
+ });
+ byPassConfigs.forEach(clientProperties::setProperty);
+ convertedConfigs.forEach(clientProperties::setProperty);
+
+ this.catalogName = properties.getOrDefault(DEFAULT_CATALOG, HIVE_DEFAULT_CATALOG);
+ String catalogKey = "hudi-" + properties.getOrDefault(CatalogUtils.CATALOG_ID_KEY, "0");
+ this.clientPool = new CachedClientPool(catalogKey, clientProperties, properties);
+ LOG.info("Hudi HMS Backend Ops initialized with properties: {}", properties);
}
@Override
public HudiSchema loadSchema(NameIdentifier schemaIdent) throws NoSuchSchemaException {
try {
- Database database = clientPool.run(client -> client.getDatabase(schemaIdent.name()));
- return HudiHMSSchema.builder().withBackendSchema(database).build();
-
- } catch (NoSuchObjectException | UnknownDBException e) {
- throw new NoSuchSchemaException(
- e, "Hudi schema (database) does not exist: %s in Hive Metastore", schemaIdent.name());
-
- } catch (TException e) {
- throw new RuntimeException(
- "Failed to load Hudi schema (database) " + schemaIdent.name() + " from Hive Metastore",
- e);
-
+ Schema database =
+ clientPool.run(client -> client.getDatabase(catalogName, schemaIdent.name()));
+ return HudiHMSSchema.builder().buildFromSchema(database);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
@@ -103,17 +109,9 @@ public class HudiHMSBackendOps implements HudiCatalogBackendOps {
try {
return clientPool.run(
c ->
- c.getAllDatabases().stream()
+ c.getAllDatabases(catalogName).stream()
.map(db -> NameIdentifier.of(namespace, db))
.toArray(NameIdentifier[]::new));
-
- } catch (TException e) {
- throw new RuntimeException(
- "Failed to list all schemas (database) under namespace : "
- + namespace
- + " in Hive Metastore",
- e);
-
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
@@ -147,21 +145,12 @@ public class HudiHMSBackendOps implements HudiCatalogBackendOps {
try {
return clientPool.run(
c -> {
- List<String> allTables = c.getAllTables(schemaIdent.name());
- return c.getTableObjectsByName(schemaIdent.name(), allTables).stream()
+ List<String> allTables = c.getAllTables(catalogName, schemaIdent.name());
+ return c.getTableObjectsByName(catalogName, schemaIdent.name(), allTables).stream()
.filter(this::checkHudiTable)
- .map(t -> NameIdentifier.of(namespace, t.getTableName()))
+ .map(t -> NameIdentifier.of(namespace, t.name()))
.toArray(NameIdentifier[]::new);
});
-
- } catch (UnknownDBException e) {
- throw new NoSuchSchemaException(
- "Schema (database) does not exist %s in Hive Metastore", namespace);
-
- } catch (TException e) {
- throw new RuntimeException(
- "Failed to list all tables under the namespace : " + namespace + " in Hive Metastore", e);
-
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
@@ -173,21 +162,14 @@ public class HudiHMSBackendOps implements HudiCatalogBackendOps {
try {
Table table =
- clientPool.run(client -> client.getTable(schemaIdent.name(), tableIdent.name()));
+ clientPool.run(
+ client -> client.getTable(catalogName, schemaIdent.name(), tableIdent.name()));
if (!checkHudiTable(table)) {
throw new NoSuchTableException(
"Table %s is not a Hudi table in Hive Metastore", tableIdent.name());
}
return HudiHMSTable.builder().withBackendTable(table).build();
- } catch (NoSuchObjectException e) {
- throw new NoSuchTableException(
- e, "Hudi table does not exist: %s in Hive Metastore", tableIdent.name());
-
- } catch (TException e) {
- throw new RuntimeException(
- "Failed to load Hudi table " + tableIdent.name() + " from Hive metastore", e);
-
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
@@ -231,44 +213,7 @@ public class HudiHMSBackendOps implements HudiCatalogBackendOps {
// uses `org.apache.hudi.hadoop.HoodieParquetInputFormat` and MOR table
// uses `org.apache.hudi.hadoop.HoodieParquetRealtimeInputFormat`, to
// simplify the logic, we just check the prefix of the input format
- return table.getSd().getInputFormat() != null
- && table.getSd().getInputFormat().startsWith(HUDI_PACKAGE_PREFIX);
- }
-
- private HiveConf buildHiveConfAndInitKerberosAuth(Map<String, String> properties) {
- Configuration hadoopConf = new Configuration();
-
- Map<String, String> byPassConfigs = Maps.newHashMap();
- Map<String, String> convertedConfigs = Maps.newHashMap();
- properties.forEach(
- (key, value) -> {
- if (key.startsWith(CATALOG_BYPASS_PREFIX)) {
- byPassConfigs.put(key.substring(CATALOG_BYPASS_PREFIX.length()), value);
- } else if (CONFIG_CONVERTER.containsKey(key)) {
- convertedConfigs.put(CONFIG_CONVERTER.get(key), value);
- } else {
- hadoopConf.set(key, value);
- }
- });
- byPassConfigs.forEach(hadoopConf::set);
- convertedConfigs.forEach(hadoopConf::set);
- initKerberosAuth(properties, hadoopConf);
- return new HiveConf(hadoopConf, HudiHMSBackendOps.class);
- }
-
- private void initKerberosAuth(Map<String, String> properties, Configuration hadoopConf) {
- AuthenticationConfig authenticationConfig = new AuthenticationConfig(properties);
- if (authenticationConfig.isKerberosAuth()) {
- try (KerberosClient kerberosClient = new KerberosClient(properties, hadoopConf, true)) {
- String keytabPath =
- String.format(
- GRAVITINO_KEYTAB_FORMAT, properties.getOrDefault(CatalogUtils.CATALOG_ID_KEY, "0"));
- File keytabFile = kerberosClient.saveKeyTabFileFromUri(keytabPath);
- kerberosClient.login(keytabFile.getAbsolutePath());
- LOG.info("Login with kerberos success");
- } catch (IOException e) {
- throw new RuntimeException("Failed to login with kerberos", e);
- }
- }
+ String inputFormat = table.properties().get(INPUT_FORMAT);
+ return inputFormat != null && inputFormat.startsWith(HUDI_PACKAGE_PREFIX);
}
}
diff --git a/catalogs/catalog-lakehouse-hudi/src/main/java/org/apache/gravitino/catalog/lakehouse/hudi/backend/hms/HudiHMSSchema.java b/catalogs/catalog-lakehouse-hudi/src/main/java/org/apache/gravitino/catalog/lakehouse/hudi/backend/hms/HudiHMSSchema.java
index 734261f5e6..d1bcbf7c69 100644
--- a/catalogs/catalog-lakehouse-hudi/src/main/java/org/apache/gravitino/catalog/lakehouse/hudi/backend/hms/HudiHMSSchema.java
+++ b/catalogs/catalog-lakehouse-hudi/src/main/java/org/apache/gravitino/catalog/lakehouse/hudi/backend/hms/HudiHMSSchema.java
@@ -18,15 +18,12 @@
*/
package org.apache.gravitino.catalog.lakehouse.hudi.backend.hms;
-import static org.apache.gravitino.catalog.lakehouse.hudi.HudiSchemaPropertiesMetadata.LOCATION;
-
-import com.google.common.collect.Maps;
import java.util.Optional;
+import org.apache.gravitino.Schema;
import org.apache.gravitino.catalog.lakehouse.hudi.HudiSchema;
import org.apache.gravitino.meta.AuditInfo;
-import org.apache.hadoop.hive.metastore.api.Database;
-public class HudiHMSSchema extends HudiSchema<Database> {
+public class HudiHMSSchema extends HudiSchema<Schema> {
public static Builder builder() {
return new Builder();
@@ -37,11 +34,11 @@ public class HudiHMSSchema extends HudiSchema<Database> {
}
@Override
- public Database fromHudiSchema() {
+ public Schema fromHudiSchema() {
throw new UnsupportedOperationException("Not implemented yet");
}
- public static class Builder extends HudiSchema.Builder<Database> {
+ public static class Builder extends HudiSchema.Builder<Schema> {
@Override
protected HudiHMSSchema simpleBuild() {
@@ -54,15 +51,13 @@ public class HudiHMSSchema extends HudiSchema<Database> {
}
@Override
- protected HudiHMSSchema buildFromSchema(Database database) {
- name = database.getName();
- comment = database.getDescription();
-
- properties = Maps.newHashMap(database.getParameters());
- properties.put(LOCATION, database.getLocationUri());
+ protected HudiHMSSchema buildFromSchema(Schema database) {
+ name = database.name();
+ comment = database.comment();
+ properties = database.properties();
AuditInfo.Builder auditInfoBuilder = AuditInfo.builder();
- Optional.ofNullable(database.getOwnerName()).ifPresent(auditInfoBuilder::withCreator);
+ Optional.ofNullable(database.auditInfo().creator()).ifPresent(auditInfoBuilder::withCreator);
auditInfo = auditInfoBuilder.build();
return simpleBuild();
diff --git a/catalogs/catalog-lakehouse-hudi/src/main/java/org/apache/gravitino/catalog/lakehouse/hudi/backend/hms/HudiHMSTable.java b/catalogs/catalog-lakehouse-hudi/src/main/java/org/apache/gravitino/catalog/lakehouse/hudi/backend/hms/HudiHMSTable.java
index e7c10ea1c2..be8edf5661 100644
--- a/catalogs/catalog-lakehouse-hudi/src/main/java/org/apache/gravitino/catalog/lakehouse/hudi/backend/hms/HudiHMSTable.java
+++ b/catalogs/catalog-lakehouse-hudi/src/main/java/org/apache/gravitino/catalog/lakehouse/hudi/backend/hms/HudiHMSTable.java
@@ -18,15 +18,11 @@
*/
package org.apache.gravitino.catalog.lakehouse.hudi.backend.hms;
-import static org.apache.gravitino.catalog.lakehouse.hudi.HudiTablePropertiesMetadata.COMMENT;
-import static org.apache.gravitino.catalog.lakehouse.hudi.HudiTablePropertiesMetadata.INPUT_FORMAT;
-import static org.apache.gravitino.catalog.lakehouse.hudi.HudiTablePropertiesMetadata.LOCATION;
-import static org.apache.gravitino.catalog.lakehouse.hudi.HudiTablePropertiesMetadata.OUTPUT_FORMAT;
-
import org.apache.gravitino.catalog.lakehouse.hudi.HudiColumn;
import org.apache.gravitino.catalog.lakehouse.hudi.HudiTable;
-import org.apache.gravitino.hive.converter.HiveTableConverter;
-import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.rel.Column;
+import org.apache.gravitino.rel.Table;
public class HudiHMSTable extends HudiTable<Table> {
public static Builder builder() {
@@ -60,25 +56,35 @@ public class HudiHMSTable extends HudiTable<Table> {
@Override
protected HudiHMSTable buildFromTable(Table hmsTable) {
- name = hmsTable.getTableName();
- comment = hmsTable.getParameters().get(COMMENT);
- columns = HiveTableConverter.getColumns(hmsTable, HudiColumn.builder());
- partitioning = HiveTableConverter.getPartitioning(hmsTable);
+ name = hmsTable.name();
+ comment = hmsTable.comment();
+ Column[] backendColumns = hmsTable.columns();
+ HudiColumn[] hudiColumns = new HudiColumn[backendColumns.length];
+ for (int i = 0; i < backendColumns.length; i++) {
+ Column c = backendColumns[i];
+ hudiColumns[i] =
+ HudiColumn.builder()
+ .withName(c.name())
+ .withComment(c.comment())
+ .withType(c.dataType())
+ .withNullable(c.nullable())
+ .withAutoIncrement(c.autoIncrement())
+ .withDefaultValue(c.defaultValue())
+ .build();
+ }
+ columns = hudiColumns;
+ partitioning = hmsTable.partitioning();
// Should always be SortOrders.NONE since Hudi using clustering to sort data (see
// https://hudi.apache.org/docs/next/clustering/)
// but is run as a background table service
- sortOrders = HiveTableConverter.getSortOrders(hmsTable);
+ sortOrders = hmsTable.sortOrder();
// Should always be Distributions.NONE since Hudi doesn't support distribution
- distribution = HiveTableConverter.getDistribution(hmsTable);
- auditInfo = HiveTableConverter.getAuditInfo(hmsTable);
-
- properties = hmsTable.getParameters();
- properties.put(LOCATION, hmsTable.getSd().getLocation());
- properties.put(INPUT_FORMAT, hmsTable.getSd().getInputFormat());
- properties.put(OUTPUT_FORMAT, hmsTable.getSd().getOutputFormat());
+ distribution = hmsTable.distribution();
+ auditInfo = AuditInfo.builder().withCreator(hmsTable.auditInfo().creator()).build();
+ properties = hmsTable.properties();
return simpleBuild();
}
}
diff --git a/catalogs/catalog-lakehouse-hudi/src/main/java/org/apache/gravitino/catalog/lakehouse/hudi/backend/hms/kerberos/AuthenticationConfig.java b/catalogs/catalog-lakehouse-hudi/src/main/java/org/apache/gravitino/catalog/lakehouse/hudi/backend/hms/kerberos/AuthenticationConfig.java
deleted file mode 100644
index f468b30cd1..0000000000
--- a/catalogs/catalog-lakehouse-hudi/src/main/java/org/apache/gravitino/catalog/lakehouse/hudi/backend/hms/kerberos/AuthenticationConfig.java
+++ /dev/null
@@ -1,68 +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.gravitino.catalog.lakehouse.hudi.backend.hms.kerberos;
-
-import org.apache.gravitino.Config;
-import org.apache.gravitino.config.ConfigBuilder;
-import org.apache.gravitino.config.ConfigConstants;
-import org.apache.gravitino.config.ConfigEntry;
-
-public class AuthenticationConfig extends Config {
-
- // The key for the authentication type, currently we support Kerberos and simple
- public static final String AUTH_TYPE_KEY = "authentication.type";
-
- public static final String IMPERSONATION_ENABLE_KEY = "authentication.impersonation-enable";
-
- enum AuthenticationType {
- SIMPLE,
- KERBEROS;
- }
-
- public static final boolean KERBEROS_DEFAULT_IMPERSONATION_ENABLE = false;
-
- public AuthenticationConfig(java.util.Map<String, String> properties) {
- super(false);
- loadFromMap(properties, k -> true);
- }
-
- public static final ConfigEntry<String> AUTH_TYPE_ENTRY =
- new ConfigBuilder(AUTH_TYPE_KEY)
- .doc(
- "The type of authentication for Hudi catalog, currently we only support simple and Kerberos")
- .version(ConfigConstants.VERSION_1_0_0)
- .stringConf()
- .createWithDefault("simple");
-
- public static final ConfigEntry<Boolean> ENABLE_IMPERSONATION_ENTRY =
- new ConfigBuilder(IMPERSONATION_ENABLE_KEY)
- .doc("Whether to enable impersonation for the Hudi catalog")
- .version(ConfigConstants.VERSION_1_0_0)
- .booleanConf()
- .createWithDefault(KERBEROS_DEFAULT_IMPERSONATION_ENABLE);
-
- public String getAuthType() {
- return get(AUTH_TYPE_ENTRY);
- }
-
- public boolean isKerberosAuth() {
- return AuthenticationConfig.AuthenticationType.KERBEROS.name().equalsIgnoreCase(getAuthType());
- }
-}
diff --git a/catalogs/catalog-lakehouse-hudi/src/main/java/org/apache/gravitino/catalog/lakehouse/hudi/backend/hms/kerberos/FetchFileUtils.java b/catalogs/catalog-lakehouse-hudi/src/main/java/org/apache/gravitino/catalog/lakehouse/hudi/backend/hms/kerberos/FetchFileUtils.java
deleted file mode 100644
index c94a87bdf2..0000000000
--- a/catalogs/catalog-lakehouse-hudi/src/main/java/org/apache/gravitino/catalog/lakehouse/hudi/backend/hms/kerberos/FetchFileUtils.java
+++ /dev/null
@@ -1,63 +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.gravitino.catalog.lakehouse.hudi.backend.hms.kerberos;
-
-import java.io.File;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.nio.file.Files;
-import org.apache.commons.io.FileUtils;
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.fs.FileSystem;
-import org.apache.hadoop.fs.Path;
-
-public class FetchFileUtils {
-
- private FetchFileUtils() {}
-
- public static void fetchFileFromUri(
- String fileUri, File destFile, int timeout, Configuration conf) throws java.io.IOException {
- try {
- URI uri = new URI(fileUri);
- String scheme = java.util.Optional.ofNullable(uri.getScheme()).orElse("file");
-
- switch (scheme) {
- case "http":
- case "https":
- case "ftp":
- FileUtils.copyURLToFile(uri.toURL(), destFile, timeout * 1000, timeout * 1000);
- break;
-
- case "file":
- Files.createSymbolicLink(destFile.toPath(), new File(uri.getPath()).toPath());
- break;
-
- case "hdfs":
- FileSystem.get(conf).copyToLocalFile(new Path(uri), new Path(destFile.toURI()));
- break;
-
- default:
- throw new IllegalArgumentException(
- String.format("Doesn't support the scheme %s", scheme));
- }
- } catch (URISyntaxException ue) {
- throw new IllegalArgumentException("The uri of file has the wrong format", ue);
- }
- }
-}
diff --git a/catalogs/catalog-lakehouse-hudi/src/main/java/org/apache/gravitino/catalog/lakehouse/hudi/backend/hms/kerberos/KerberosClient.java b/catalogs/catalog-lakehouse-hudi/src/main/java/org/apache/gravitino/catalog/lakehouse/hudi/backend/hms/kerberos/KerberosClient.java
deleted file mode 100644
index 9bdbbc7424..0000000000
--- a/catalogs/catalog-lakehouse-hudi/src/main/java/org/apache/gravitino/catalog/lakehouse/hudi/backend/hms/kerberos/KerberosClient.java
+++ /dev/null
@@ -1,121 +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.gravitino.catalog.lakehouse.hudi.backend.hms.kerberos;
-
-import com.google.common.base.Preconditions;
-import com.google.common.base.Splitter;
-import com.google.common.util.concurrent.ThreadFactoryBuilder;
-import java.io.File;
-import java.io.IOException;
-import java.util.concurrent.ScheduledThreadPoolExecutor;
-import java.util.concurrent.ThreadFactory;
-import java.util.concurrent.TimeUnit;
-import org.apache.commons.lang3.StringUtils;
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.security.UserGroupInformation;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class KerberosClient implements java.io.Closeable {
- private static final Logger LOG = LoggerFactory.getLogger(KerberosClient.class);
-
- private ScheduledThreadPoolExecutor checkTgtExecutor;
- private final java.util.Map<String, String> conf;
- private final Configuration hadoopConf;
- private final boolean refreshCredentials;
-
- public KerberosClient(
- java.util.Map<String, String> conf, Configuration hadoopConf, boolean refreshCredentials) {
- this.conf = conf;
- this.hadoopConf = hadoopConf;
- this.refreshCredentials = refreshCredentials;
- }
-
- public String login(String keytabFilePath) throws IOException {
- KerberosConfig kerberosConfig = new KerberosConfig(conf);
-
- // Check the principal and keytab file
- String catalogPrincipal = kerberosConfig.getPrincipalName();
- Preconditions.checkArgument(
- StringUtils.isNotBlank(catalogPrincipal), "The principal can't be blank");
- @SuppressWarnings("null")
- java.util.List<String> principalComponents = Splitter.on('@').splitToList(catalogPrincipal);
- Preconditions.checkArgument(
- principalComponents.size() == 2, "The principal has the wrong format");
-
- // Login
- UserGroupInformation.setConfiguration(hadoopConf);
- UserGroupInformation.loginUserFromKeytab(catalogPrincipal, keytabFilePath);
- UserGroupInformation kerberosLoginUgi = UserGroupInformation.getLoginUser();
-
- // Refresh the cache if it's out of date.
- if (refreshCredentials) {
- this.checkTgtExecutor = new ScheduledThreadPoolExecutor(1, getThreadFactory("check-tgt"));
- int checkInterval = kerberosConfig.getCheckIntervalSec();
- checkTgtExecutor.scheduleAtFixedRate(
- () -> {
- try {
- kerberosLoginUgi.checkTGTAndReloginFromKeytab();
- } catch (Exception e) {
- LOG.error("Fail to refresh ugi token: ", e);
- }
- },
- checkInterval,
- checkInterval,
- TimeUnit.SECONDS);
- }
-
- return principalComponents.get(1);
- }
-
- public File saveKeyTabFileFromUri(String keytabPath) throws IOException {
- KerberosConfig kerberosConfig = new KerberosConfig(conf);
-
- String keyTabUri = kerberosConfig.getKeytab();
- Preconditions.checkArgument(StringUtils.isNotBlank(keyTabUri), "Keytab uri can't be blank");
- Preconditions.checkArgument(
- !keyTabUri.trim().startsWith("hdfs"), "Keytab uri doesn't support to use HDFS");
-
- File keytabsDir = new File("keytabs");
- if (!keytabsDir.exists()) {
- keytabsDir.mkdir();
- }
- File keytabFile = new File(keytabPath);
- keytabFile.deleteOnExit();
- if (keytabFile.exists() && !keytabFile.delete()) {
- throw new IllegalStateException(
- String.format("Fail to delete keytab file %s", keytabFile.getAbsolutePath()));
- }
- int fetchKeytabFileTimeout = kerberosConfig.getFetchTimeoutSec();
- FetchFileUtils.fetchFileFromUri(keyTabUri, keytabFile, fetchKeytabFileTimeout, hadoopConf);
- return keytabFile;
- }
-
- private static ThreadFactory getThreadFactory(String factoryName) {
- return new ThreadFactoryBuilder().setDaemon(true).setNameFormat(factoryName + "-%d").build();
- }
-
- @Override
- public void close() {
- if (checkTgtExecutor != null) {
- checkTgtExecutor.shutdown();
- }
- }
-}
diff --git a/catalogs/catalog-lakehouse-hudi/src/main/java/org/apache/gravitino/catalog/lakehouse/hudi/backend/hms/kerberos/KerberosConfig.java b/catalogs/catalog-lakehouse-hudi/src/main/java/org/apache/gravitino/catalog/lakehouse/hudi/backend/hms/kerberos/KerberosConfig.java
deleted file mode 100644
index 294b99b8ac..0000000000
--- a/catalogs/catalog-lakehouse-hudi/src/main/java/org/apache/gravitino/catalog/lakehouse/hudi/backend/hms/kerberos/KerberosConfig.java
+++ /dev/null
@@ -1,90 +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.gravitino.catalog.lakehouse.hudi.backend.hms.kerberos;
-
-import java.util.Map;
-import org.apache.commons.lang3.StringUtils;
-import org.apache.gravitino.config.ConfigBuilder;
-import org.apache.gravitino.config.ConfigConstants;
-import org.apache.gravitino.config.ConfigEntry;
-
-public class KerberosConfig extends AuthenticationConfig {
- public static final String KEY_TAB_URI_KEY = "authentication.kerberos.keytab-uri";
-
- public static final String PRINCIPAL_KEY = "authentication.kerberos.principal";
-
- public static final String CHECK_INTERVAL_SEC_KEY = "authentication.kerberos.check-interval-sec";
-
- public static final String FETCH_TIMEOUT_SEC_KEY =
- "authentication.kerberos.keytab-fetch-timeout-sec";
-
- public static final ConfigEntry<String> PRINCIPAL_ENTRY =
- new ConfigBuilder(PRINCIPAL_KEY)
- .doc("The principal of the Kerberos connection")
- .version(ConfigConstants.VERSION_1_0_0)
- .stringConf()
- .checkValue(StringUtils::isNotBlank, ConfigConstants.NOT_BLANK_ERROR_MSG)
- .create();
-
- public static final ConfigEntry<String> KEYTAB_ENTRY =
- new ConfigBuilder(KEY_TAB_URI_KEY)
- .doc("The keytab of the Kerberos connection")
- .version(ConfigConstants.VERSION_1_0_0)
- .stringConf()
- .checkValue(StringUtils::isNotBlank, ConfigConstants.NOT_BLANK_ERROR_MSG)
- .create();
-
- public static final ConfigEntry<Integer> CHECK_INTERVAL_SEC_ENTRY =
- new ConfigBuilder(CHECK_INTERVAL_SEC_KEY)
- .doc("The check interval of the Kerberos connection for Hudi catalog")
- .version(ConfigConstants.VERSION_1_0_0)
- .intConf()
- .checkValue(value -> value > 0, ConfigConstants.POSITIVE_NUMBER_ERROR_MSG)
- .createWithDefault(60);
-
- public static final ConfigEntry<Integer> FETCH_TIMEOUT_SEC_ENTRY =
- new ConfigBuilder(FETCH_TIMEOUT_SEC_KEY)
- .doc("The fetch timeout of the Kerberos connection")
- .version(ConfigConstants.VERSION_1_0_0)
- .intConf()
- .checkValue(value -> value > 0, ConfigConstants.POSITIVE_NUMBER_ERROR_MSG)
- .createWithDefault(60);
-
- public KerberosConfig(Map<String, String> properties) {
- super(properties);
- loadFromMap(properties, k -> true);
- }
-
- public String getPrincipalName() {
- return get(PRINCIPAL_ENTRY);
- }
-
- public String getKeytab() {
- return get(KEYTAB_ENTRY);
- }
-
- public int getCheckIntervalSec() {
- return get(CHECK_INTERVAL_SEC_ENTRY);
- }
-
- public int getFetchTimeoutSec() {
- return get(FETCH_TIMEOUT_SEC_ENTRY);
- }
-}
diff --git a/catalogs/catalog-lakehouse-hudi/src/test/java/org/apache/gravitino/catalog/lakehouse/hudi/backend/hms/TestHudiHMSBackendOps.java b/catalogs/catalog-lakehouse-hudi/src/test/java/org/apache/gravitino/catalog/lakehouse/hudi/backend/hms/TestHudiHMSBackendOps.java
index d1e531e848..0ae2752f2a 100644
--- a/catalogs/catalog-lakehouse-hudi/src/test/java/org/apache/gravitino/catalog/lakehouse/hudi/backend/hms/TestHudiHMSBackendOps.java
+++ b/catalogs/catalog-lakehouse-hudi/src/test/java/org/apache/gravitino/catalog/lakehouse/hudi/backend/hms/TestHudiHMSBackendOps.java
@@ -21,27 +21,27 @@ package org.apache.gravitino.catalog.lakehouse.hudi.backend.hms;
import static org.apache.gravitino.catalog.lakehouse.hudi.HudiCatalogPropertiesMetadata.URI;
import static org.apache.gravitino.catalog.lakehouse.hudi.HudiSchemaPropertiesMetadata.LOCATION;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
+import java.time.Instant;
import java.util.Arrays;
+import java.util.HashMap;
import java.util.Map;
+import java.util.Properties;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
import org.apache.gravitino.catalog.lakehouse.hudi.HudiColumn;
import org.apache.gravitino.catalog.lakehouse.hudi.HudiSchema;
import org.apache.gravitino.catalog.lakehouse.hudi.HudiTable;
import org.apache.gravitino.exceptions.NoSuchTableException;
+import org.apache.gravitino.hive.HiveClientPool;
+import org.apache.gravitino.hive.HiveTable;
+import org.apache.gravitino.hive.client.HiveClient;
import org.apache.gravitino.hive.hms.MiniHiveMetastoreService;
+import org.apache.gravitino.meta.AuditInfo;
import org.apache.gravitino.rel.Column;
import org.apache.gravitino.rel.types.Types;
import org.apache.hadoop.hive.conf.HiveConf;
-import org.apache.hadoop.hive.metastore.api.FieldSchema;
-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.spark.sql.SparkSession;
-import org.apache.thrift.TException;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
@@ -54,29 +54,30 @@ public class TestHudiHMSBackendOps extends MiniHiveMetastoreService {
private static final String CATALOG_NAME = "catalog";
private static final String HIVE_TABLE_NAME = "hive_table";
private static final String HUDI_TABLE_NAME = "hudi_table";
+ private static final String CATALOG = "";
+ private static HiveClientPool hiveClientPool;
@BeforeAll
- public static void prepare() throws TException {
+ public static void prepare() throws Exception {
+ String hiveMetastoreUris = hiveConf.get(HiveConf.ConfVars.METASTOREURIS.varname);
+
Map<String, String> props = Maps.newHashMap();
- props.put(URI, hiveConf.get(HiveConf.ConfVars.METASTOREURIS.varname));
+ props.put(URI, hiveMetastoreUris);
ops.initialize(props);
- // create a hive table
- Table table = new Table();
- table.setDbName(DB_NAME);
- table.setTableName(HIVE_TABLE_NAME);
- StorageDescriptor strgDesc = new StorageDescriptor();
- strgDesc.setCols(Lists.newArrayList(new FieldSchema("col1", "string", "description")));
- strgDesc.setSerdeInfo(new SerDeInfo());
- table.setSd(strgDesc);
- metastoreClient.createTable(table);
+ Properties properties = new Properties();
+ properties.setProperty(HiveConf.ConfVars.METASTOREURIS.varname, hiveMetastoreUris);
+ hiveClientPool = new HiveClientPool("hudi", 1, properties);
+
+ // create a hive table using HiveClient
+ createHiveTable();
// use Spark to create a hudi table
SparkSession sparkSession =
SparkSession.builder()
.master("local[1]")
.appName("Hudi Catalog integration test")
- .config("hive.metastore.uris", hiveConf.get(HiveConf.ConfVars.METASTOREURIS.varname))
+ .config("hive.metastore.uris", hiveMetastoreUris)
.config("spark.serializer", "org.apache.spark.serializer.KryoSerializer")
.config("spark.sql.extensions", "org.apache.spark.sql.hudi.HoodieSparkSessionExtension")
.config(
@@ -90,17 +91,49 @@ public class TestHudiHMSBackendOps extends MiniHiveMetastoreService {
// create a hudi table
sparkSession.sql(
String.format("CREATE TABLE %s.%s (ts BIGINT) USING HUDI", DB_NAME, HUDI_TABLE_NAME));
+ sparkSession.close();
+ }
+
+ private static void createHiveTable() throws Exception {
+ Column col = Column.of("col1", Types.StringType.get(), "description");
+
+ HiveTable hiveTable =
+ HiveTable.builder()
+ .withName(HIVE_TABLE_NAME)
+ .withColumns(new Column[] {col})
+ .withComment("description")
+ .withProperties(new HashMap<>())
+ .withAuditInfo(
+ AuditInfo.builder()
+ .withCreator(System.getProperty("user.name", "gravitino"))
+ .withCreateTime(Instant.now())
+ .build())
+ .withCatalogName(CATALOG)
+ .withDatabaseName(DB_NAME)
+ .build();
+
+ hiveClientPool.run(
+ (HiveClient client) -> {
+ client.createTable(hiveTable);
+ return null;
+ });
}
@AfterAll
- public static void cleanup() throws TException {
+ public static void cleanup() throws Exception {
+ if (hiveClientPool != null) {
+ hiveClientPool.close();
+ }
ops.close();
}
@Test
public void testInitialize() {
try (HudiHMSBackendOps ops = new HudiHMSBackendOps()) {
- ops.initialize(ImmutableMap.of());
+ String hiveMetastoreUris = hiveConf.get(HiveConf.ConfVars.METASTOREURIS.varname);
+ Map<String, String> props = Maps.newHashMap();
+ props.put(URI, hiveMetastoreUris);
+ ops.initialize(props);
Assertions.assertNotNull(ops.clientPool);
}
}
diff --git a/catalogs/catalog-lakehouse-hudi/src/test/java/org/apache/gravitino/catalog/lakehouse/hudi/integration/test/HudiCatalogHMSIT.java b/catalogs/catalog-lakehouse-hudi/src/test/java/org/apache/gravitino/catalog/lakehouse/hudi/integration/test/HudiCatalogHMSIT.java
index 7b2800f0f9..c893997b4c 100644
--- a/catalogs/catalog-lakehouse-hudi/src/test/java/org/apache/gravitino/catalog/lakehouse/hudi/integration/test/HudiCatalogHMSIT.java
+++ b/catalogs/catalog-lakehouse-hudi/src/test/java/org/apache/gravitino/catalog/lakehouse/hudi/integration/test/HudiCatalogHMSIT.java
@@ -52,6 +52,7 @@ import org.apache.gravitino.rel.indexes.Indexes;
import org.apache.gravitino.rel.types.Types;
import org.apache.gravitino.utils.RandomNameUtils;
import org.apache.spark.sql.SparkSession;
+import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
@@ -95,6 +96,14 @@ public class HudiCatalogHMSIT extends BaseIT {
ImmutableMap.of(CATALOG_BACKEND, "hms", URI, hmsURI));
}
+ @AfterAll
+ public void close() {
+ if (sparkSession != null) {
+ sparkSession.close();
+ sparkSession = null;
+ }
+ }
+
@Test
public void testCatalog() {
String catalogName = RandomNameUtils.genRandomName("hudi_catalog");
diff --git a/catalogs/catalog-lakehouse-hudi/src/test/java/org/apache/gravitino/catalog/lakehouse/hudi/integration/test/HudiCatalogKerberosHiveIT.java b/catalogs/catalog-lakehouse-hudi/src/test/java/org/apache/gravitino/catalog/lakehouse/hudi/integration/test/HudiCatalogKerberosHiveIT.java
index e5168729a2..a692051acb 100644
--- a/catalogs/catalog-lakehouse-hudi/src/test/java/org/apache/gravitino/catalog/lakehouse/hudi/integration/test/HudiCatalogKerberosHiveIT.java
+++ b/catalogs/catalog-lakehouse-hudi/src/test/java/org/apache/gravitino/catalog/lakehouse/hudi/integration/test/HudiCatalogKerberosHiveIT.java
@@ -31,12 +31,12 @@ import org.apache.gravitino.Configs;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Schema;
import org.apache.gravitino.catalog.lakehouse.hudi.HudiCatalogPropertiesMetadata;
-import org.apache.gravitino.catalog.lakehouse.hudi.backend.hms.kerberos.AuthenticationConfig;
-import org.apache.gravitino.catalog.lakehouse.hudi.backend.hms.kerberos.KerberosConfig;
import org.apache.gravitino.client.GravitinoAdminClient;
import org.apache.gravitino.client.GravitinoMetalake;
import org.apache.gravitino.client.KerberosTokenProvider;
import org.apache.gravitino.exceptions.NoSuchTableException;
+import org.apache.gravitino.hive.kerberos.AuthenticationConfig;
+import org.apache.gravitino.hive.kerberos.KerberosConfig;
import org.apache.gravitino.integration.test.container.ContainerSuite;
import org.apache.gravitino.integration.test.container.HiveContainer;
import org.apache.gravitino.integration.test.util.BaseIT;
@@ -235,7 +235,7 @@ public class HudiCatalogKerberosHiveIT extends BaseIT {
Assertions.assertTrue(
exception
.getMessage()
- .contains("Hudi table does not exist: " + TABLE_NAME + " in Hive Metastore"),
+ .contains("Hive table " + TABLE_NAME + " does not exist in Hive Metastore"),
"Unexpected exception message: " + exception.getMessage());
}
diff --git a/catalogs/catalog-lakehouse-hudi/src/test/java/org/apache/gravitino/catalog/lakehouse/hudi/utils/TestCatalogUtils.java b/catalogs/catalog-lakehouse-hudi/src/test/java/org/apache/gravitino/catalog/lakehouse/hudi/utils/TestCatalogUtils.java
index 86eaabde8c..5f306d7bf9 100644
--- a/catalogs/catalog-lakehouse-hudi/src/test/java/org/apache/gravitino/catalog/lakehouse/hudi/utils/TestCatalogUtils.java
+++ b/catalogs/catalog-lakehouse-hudi/src/test/java/org/apache/gravitino/catalog/lakehouse/hudi/utils/TestCatalogUtils.java
@@ -35,16 +35,4 @@ public class TestCatalogUtils {
Assertions.assertInstanceOf(HudiHMSBackend.class, catalogBackend);
Assertions.assertInstanceOf(HudiHMSBackendOps.class, catalogBackend.backendOps());
}
-
- @Test
- public void testLoadHudiCatalogBackendMissingProperty() {
- IllegalArgumentException exception =
- Assertions.assertThrows(
- IllegalArgumentException.class,
- () -> CatalogUtils.loadHudiCatalogBackend(ImmutableMap.of()));
- Assertions.assertTrue(
- exception
- .getMessage()
- .contains("Property " + CATALOG_BACKEND + " must not be null or empty"));
- }
}
diff --git a/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/CachedClientPool.java b/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/CachedClientPool.java
index 3c7b5182ba..62a38819e1 100644
--- a/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/CachedClientPool.java
+++ b/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/CachedClientPool.java
@@ -24,20 +24,18 @@ import com.github.benmanes.caffeine.cache.Scheduler;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
-import java.io.IOException;
-import java.io.UncheckedIOException;
import java.util.List;
import java.util.Map;
+import java.util.Properties;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
import org.apache.gravitino.catalog.hive.HiveConstants;
+import org.apache.gravitino.exceptions.GravitinoRuntimeException;
+import org.apache.gravitino.hive.client.HiveClient;
import org.apache.gravitino.utils.ClientPool;
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.hive.metastore.IMetaStoreClient;
-import org.apache.hadoop.security.UserGroupInformation;
-import org.apache.thrift.TException;
+import org.apache.gravitino.utils.PrincipalUtils;
import org.immutables.value.Value;
/**
@@ -50,17 +48,18 @@ import org.immutables.value.Value;
*
* <p>A ClientPool that caches the underlying HiveClientPool instances.
*/
-public class CachedClientPool implements ClientPool<IMetaStoreClient, TException> {
+public class CachedClientPool implements ClientPool<HiveClient, GravitinoRuntimeException> {
private static final ClientPropertiesMetadata PROPERTIES_METADATA =
new ClientPropertiesMetadata();
private final Cache<Key, HiveClientPool> clientPoolCache;
- private final Configuration conf;
+ private final Properties conf;
private final int clientPoolSize;
private final ScheduledThreadPoolExecutor scheduler;
+ private final String name;
- public CachedClientPool(Configuration hiveConf, Map<String, String> properties) {
+ public CachedClientPool(String name, Properties hiveConf, Map<String, String> properties) {
int clientPoolSize =
(int) PROPERTIES_METADATA.getOrDefault(properties, HiveConstants.CLIENT_POOL_SIZE);
long evictionInterval =
@@ -68,6 +67,7 @@ public class CachedClientPool implements ClientPool<IMetaStoreClient, TException
PROPERTIES_METADATA.getOrDefault(
properties, HiveConstants.CLIENT_POOL_CACHE_EVICTION_INTERVAL_MS);
+ this.name = name;
this.conf = hiveConf;
this.clientPoolSize = clientPoolSize;
// Since Caffeine does not ensure that removalListener will be involved after expiration
@@ -84,7 +84,7 @@ public class CachedClientPool implements ClientPool<IMetaStoreClient, TException
@VisibleForTesting
public HiveClientPool clientPool() {
Key key = extractKey();
- return clientPoolCache.get(key, k -> new HiveClientPool(clientPoolSize, conf));
+ return clientPoolCache.get(key, k -> new HiveClientPool(name, clientPoolSize, conf));
}
@VisibleForTesting
@@ -93,26 +93,21 @@ public class CachedClientPool implements ClientPool<IMetaStoreClient, TException
}
@Override
- public <R> R run(Action<R, IMetaStoreClient, TException> action)
- throws TException, InterruptedException {
+ public <R> R run(Action<R, HiveClient, GravitinoRuntimeException> action)
+ throws GravitinoRuntimeException, InterruptedException {
return clientPool().run(action);
}
@Override
- public <R> R run(Action<R, IMetaStoreClient, TException> action, boolean retry)
- throws TException, InterruptedException {
+ public <R> R run(Action<R, HiveClient, GravitinoRuntimeException> action, boolean retry)
+ throws GravitinoRuntimeException, InterruptedException {
return clientPool().run(action, retry);
}
@VisibleForTesting
public static Key extractKey() {
List<Object> elements = Lists.newArrayList();
- try {
- elements.add(UserGroupInformation.getCurrentUser().getUserName());
- } catch (IOException e) {
- throw new UncheckedIOException(e);
- }
-
+ elements.add(PrincipalUtils.getCurrentUserName());
return Key.of(elements);
}
diff --git a/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/HiveClientPool.java b/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/HiveClientPool.java
index 902cb05c82..7fa0098a34 100644
--- a/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/HiveClientPool.java
+++ b/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/HiveClientPool.java
@@ -18,119 +18,57 @@
*/
package org.apache.gravitino.hive;
-import com.google.common.annotations.VisibleForTesting;
-import org.apache.gravitino.hive.dyn.DynMethods;
-import org.apache.gravitino.hive.dyn.DynMethods.StaticMethod;
+import java.util.Properties;
+import org.apache.gravitino.exceptions.GravitinoRuntimeException;
+import org.apache.gravitino.hive.client.HiveClient;
+import org.apache.gravitino.hive.client.HiveClientFactory;
import org.apache.gravitino.utils.ClientPoolImpl;
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.hive.conf.HiveConf;
-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.RetryingMetaStoreClient;
-import org.apache.hadoop.hive.metastore.api.MetaException;
-import org.apache.thrift.TException;
-import org.apache.thrift.transport.TTransportException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
// hive-metastore/src/main/java/org/apache/iceberg/hive/HiveClientPool.java
/** Represents a client pool for managing connections to an Apache Hive Metastore service. */
-public class HiveClientPool extends ClientPoolImpl<IMetaStoreClient, TException> {
+public class HiveClientPool extends ClientPoolImpl<HiveClient, GravitinoRuntimeException> {
private static final Logger LOG = LoggerFactory.getLogger(HiveClientPool.class);
- private static final StaticMethod GET_CLIENT =
- DynMethods.builder("getProxy")
- .impl(
- RetryingMetaStoreClient.class,
- HiveConf.class,
- HiveMetaHookLoader.class,
- String.class) // Hive 1 and 2
- .impl(
- RetryingMetaStoreClient.class,
- Configuration.class,
- HiveMetaHookLoader.class,
- String.class) // Hive 3
- .buildStatic();
-
- private final HiveConf hiveConf;
+ private final HiveClientFactory clientFactory;
/**
* Creates a new HiveClientPool with the specified pool size and configuration.
*
* @param poolSize The number of clients in the pool.
- * @param conf The configuration used to initialize the Hive Metastore clients.
+ * @param properties The configuration used to initialize the Hive Metastore clients.
*/
- public HiveClientPool(int poolSize, Configuration conf) {
+ public HiveClientPool(String name, int poolSize, Properties properties) {
// Do not allow retry by default as we rely on RetryingHiveClient
- super(poolSize, TTransportException.class, false);
- this.hiveConf = new HiveConf(conf, HiveClientPool.class);
- this.hiveConf.addResource(conf);
+ super(poolSize, GravitinoRuntimeException.class, false);
+ this.clientFactory = new HiveClientFactory(properties, name);
}
@Override
- protected IMetaStoreClient newClient() {
+ protected HiveClient newClient() {
try {
- try {
- return GET_CLIENT.invoke(
- hiveConf, (HiveMetaHookLoader) tbl -> null, HiveMetaStoreClient.class.getName());
- } catch (RuntimeException e) {
- // any MetaException would be wrapped into RuntimeException during reflection, so let's
- // double-check type here
- if (e.getCause() instanceof MetaException) {
- throw (MetaException) e.getCause();
- }
- throw e;
- }
- } catch (MetaException e) {
- throw new RuntimeException("Failed to connect to Hive Metastore", e);
+ return clientFactory.createHiveClient();
} catch (Exception e) {
- if (e.getMessage().contains("Another instance of Derby may have already booted")) {
- throw new RuntimeException(
- "Failed to start an embedded metastore because embedded "
- + "Derby supports only one client at a time. To fix this, use a metastore that supports "
- + "multiple clients.",
- e);
- }
-
- throw new RuntimeException("Failed to connect to Hive Metastore", e);
+ LOG.error("Failed to connect to Hive Metastore", e);
+ throw new GravitinoRuntimeException(e, "Failed to connect to Hive Metastore");
}
}
@Override
- protected IMetaStoreClient reconnect(IMetaStoreClient client) {
+ protected HiveClient reconnect(HiveClient client) {
LOG.warn("Reconnecting to Hive Metastore");
- try {
- client.close();
- client.reconnect();
- } catch (MetaException e) {
- throw new RuntimeException("Failed to reconnect to Hive Metastore", e);
- }
return client;
}
@Override
protected boolean isConnectionException(Exception e) {
- return super.isConnectionException(e)
- || (e instanceof MetaException
- && e.getMessage()
- .contains("Got exception: org.apache.thrift.transport.TTransportException"));
+ return false;
}
@Override
- protected void close(IMetaStoreClient client) {
+ protected void close(HiveClient client) {
LOG.info("Closing Hive Metastore client");
- client.close();
- }
-
- /**
- * Gets the HiveConf object used in this HiveClientPool.
- *
- * @return The HiveConf object used in this HiveClientPool.
- */
- @VisibleForTesting
- HiveConf hiveConf() {
- return hiveConf;
}
}
diff --git a/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveClientFactory.java b/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveClientFactory.java
index 39ceefd240..62ff549dc1 100644
--- a/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveClientFactory.java
+++ b/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveClientFactory.java
@@ -54,18 +54,20 @@ public final class HiveClientFactory {
private final Configuration hadoopConf;
private final Properties properties;
private final String keytabPath;
+ private final String name;
/**
* Creates a {@link HiveClientFactory} boundGRAVITINO_KEYTAB_FORMAT to the given configuration
* properties.
*
* @param properties Hive client configuration, must not be null.
- * @param id An identifier for this factory instance.
+ * @param name a name identifier for this factory instance.
*/
- public HiveClientFactory(Properties properties, String id) {
+ public HiveClientFactory(Properties properties, String name) {
Preconditions.checkArgument(properties != null, "Properties cannot be null");
+ this.name = name;
this.properties = properties;
- this.keytabPath = String.format(GRAVITINO_KEYTAB_FORMAT, id);
+ this.keytabPath = String.format(GRAVITINO_KEYTAB_FORMAT, name);
try {
this.hadoopConf = new Configuration();
@@ -78,7 +80,8 @@ public final class HiveClientFactory {
kerberosClient.setHiveClient(client);
}
} catch (Exception e) {
- throw new RuntimeException("Failed to initialize HiveClientFactory", e);
+ throw new RuntimeException(
+ String.format("Failed to initialize HiveClientFactory %s", this.name), e);
}
}
diff --git a/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveExceptionConverter.java b/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveExceptionConverter.java
index 9371e9c8da..3eff0eaae4 100644
--- a/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveExceptionConverter.java
+++ b/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveExceptionConverter.java
@@ -150,7 +150,7 @@ public class HiveExceptionConverter {
String message = cause.getMessage();
String lowerMessage = message != null ? message.toLowerCase(Locale.ROOT) : "";
- String exceptionClassName = cause.getClass().getName();
+ String exceptionClassName = cause.getClass().getSimpleName();
if (exceptionClassName.contains("AlreadyExistsException")) {
return toAlreadyExistsException(cause, target, message);
diff --git a/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/kerberos/KerberosClient.java b/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/kerberos/KerberosClient.java
index a5cfa7eddf..8ba4f18559 100644
--- a/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/kerberos/KerberosClient.java
+++ b/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/kerberos/KerberosClient.java
@@ -27,6 +27,8 @@ import com.google.common.base.Splitter;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.io.File;
import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Paths;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ScheduledThreadPoolExecutor;
@@ -186,8 +188,14 @@ public class KerberosClient implements java.io.Closeable {
@Override
public void close() {
- if (checkTgtExecutor != null) {
- checkTgtExecutor.shutdown();
+ try {
+ if (checkTgtExecutor != null) {
+ checkTgtExecutor.shutdown();
+ }
+
+ Files.deleteIfExists(Paths.get(keytabFilePath));
+ } catch (IOException e) {
+ LOG.warn("Failed to delete keytab file: {}", keytabFilePath, e);
}
}
diff --git a/catalogs/hive-metastore-common/src/test/java/org/apache/gravitino/hive/TestCachedClientPool.java b/catalogs/hive-metastore-common/src/test/java/org/apache/gravitino/hive/TestCachedClientPool.java
index 822cff920f..17b443c217 100644
--- a/catalogs/hive-metastore-common/src/test/java/org/apache/gravitino/hive/TestCachedClientPool.java
+++ b/catalogs/hive-metastore-common/src/test/java/org/apache/gravitino/hive/TestCachedClientPool.java
@@ -20,12 +20,13 @@
package org.apache.gravitino.hive;
import com.google.common.collect.ImmutableMap;
-import java.security.PrivilegedAction;
import java.util.Map;
+import java.util.Properties;
import java.util.concurrent.TimeUnit;
+import org.apache.gravitino.UserPrincipal;
import org.apache.gravitino.catalog.hive.HiveConstants;
import org.apache.gravitino.hive.hms.MiniHiveMetastoreService;
-import org.apache.hadoop.security.UserGroupInformation;
+import org.apache.gravitino.utils.PrincipalUtils;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@@ -40,7 +41,7 @@ public class TestCachedClientPool extends MiniHiveMetastoreService {
"1",
HiveConstants.CLIENT_POOL_CACHE_EVICTION_INTERVAL_MS,
"5000");
- CachedClientPool clientPool = new CachedClientPool(MiniHiveMetastoreService.hiveConf, props);
+ CachedClientPool clientPool = new CachedClientPool("pool", new Properties(), props);
HiveClientPool clientPool1 = clientPool.clientPool();
HiveClientPool cachedClientPool =
clientPool.clientPoolCache().getIfPresent(CachedClientPool.extractKey());
@@ -58,16 +59,21 @@ public class TestCachedClientPool extends MiniHiveMetastoreService {
@Test
public void testCacheKey() throws Exception {
- UserGroupInformation current = UserGroupInformation.getCurrentUser();
- UserGroupInformation foo1 = UserGroupInformation.createProxyUser("foo", current);
- UserGroupInformation foo2 = UserGroupInformation.createProxyUser("foo", current);
- UserGroupInformation bar = UserGroupInformation.createProxyUser("bar", current);
CachedClientPool.Key key1 =
- foo1.doAs((PrivilegedAction<CachedClientPool.Key>) CachedClientPool::extractKey);
+ PrincipalUtils.doAs(
+ new UserPrincipal("foo"),
+ (java.security.PrivilegedExceptionAction<CachedClientPool.Key>)
+ CachedClientPool::extractKey);
CachedClientPool.Key key2 =
- foo2.doAs((PrivilegedAction<CachedClientPool.Key>) CachedClientPool::extractKey);
+ PrincipalUtils.doAs(
+ new UserPrincipal("foo"),
+ (java.security.PrivilegedExceptionAction<CachedClientPool.Key>)
+ CachedClientPool::extractKey);
CachedClientPool.Key key3 =
- bar.doAs((PrivilegedAction<CachedClientPool.Key>) CachedClientPool::extractKey);
+ PrincipalUtils.doAs(
+ new UserPrincipal("bar"),
+ (java.security.PrivilegedExceptionAction<CachedClientPool.Key>)
+ CachedClientPool::extractKey);
Assertions.assertEquals(key1, key2);
Assertions.assertNotEquals(key1, key3);
}
diff --git a/catalogs/hive-metastore-common/src/test/java/org/apache/gravitino/hive/hms/MiniHiveMetastore.java b/catalogs/hive-metastore-common/src/test/java/org/apache/gravitino/hive/hms/MiniHiveMetastore.java
index 7ff4996f0a..dfa4561178 100644
--- a/catalogs/hive-metastore-common/src/test/java/org/apache/gravitino/hive/hms/MiniHiveMetastore.java
+++ b/catalogs/hive-metastore-common/src/test/java/org/apache/gravitino/hive/hms/MiniHiveMetastore.java
@@ -31,6 +31,7 @@ import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
+import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.gravitino.hive.HiveClientPool;
@@ -189,7 +190,9 @@ public class MiniHiveMetastore {
HiveConf.ConfVars.METASTOREURIS.varname,
hiveConf.getVar(HiveConf.ConfVars.METASTOREURIS));
- this.clientPool = new HiveClientPool(1, hiveConf);
+ Properties properties = new Properties();
+ properties.put("hive.metastore.uris", "thrift://localhost:" + port);
+ this.clientPool = new HiveClientPool("min-ms", 1, properties);
} catch (Exception e) {
throw new RuntimeException("Cannot start TestHiveMetastore", e);
}
@@ -225,11 +228,11 @@ public class MiniHiveMetastore {
public void reset() throws Exception {
if (clientPool != null) {
- for (String dbName : clientPool.run(client -> client.getAllDatabases())) {
- for (String tblName : clientPool.run(client -> client.getAllTables(dbName))) {
+ for (String dbName : clientPool.run(client -> client.getAllDatabases(""))) {
+ for (String tblName : clientPool.run(client -> client.getAllTables("", dbName))) {
clientPool.run(
client -> {
- client.dropTable(dbName, tblName, true, true, true);
+ client.dropTable("", dbName, tblName, true, true);
return null;
});
}
@@ -238,7 +241,7 @@ public class MiniHiveMetastore {
// Drop cascade, functions dropped by cascade
clientPool.run(
client -> {
- client.dropDatabase(dbName, true, true, true);
+ client.dropDatabase("", dbName, true);
return null;
});
}
diff --git a/core/src/main/java/org/apache/gravitino/connector/BaseTable.java b/core/src/main/java/org/apache/gravitino/connector/BaseTable.java
index 4102a43e9e..b370d26866 100644
--- a/core/src/main/java/org/apache/gravitino/connector/BaseTable.java
+++ b/core/src/main/java/org/apache/gravitino/connector/BaseTable.java
@@ -158,13 +158,17 @@ public abstract class BaseTable implements Table {
return indexes;
}
+ public Optional<ProxyPlugin> proxyPlugin() {
+ return proxyPlugin;
+ }
+
/**
* Builder interface for creating instances of {@link BaseTable}.
*
* @param <SELF> The type of the builder.
* @param <T> The type of the table being built.
*/
- interface Builder<SELF extends Builder<SELF, T>, T extends BaseTable> {
+ public interface Builder<SELF extends Builder<SELF, T>, T extends BaseTable> {
SELF withName(String name);
diff --git a/docs/apache-hive-catalog.md b/docs/apache-hive-catalog.md
index 3ea3f10e56..14facc6760 100644
--- a/docs/apache-hive-catalog.md
+++ b/docs/apache-hive-catalog.md
@@ -16,8 +16,7 @@ Apache Gravitino offers the capability to utilize [Apache Hive](https://hive.apa
* Gravitino must have network access to the Hive metastore service using the Thrift protocol.
:::note
-Although the Hive catalog uses the Hive2 metastore client, it can be compatible with the Hive3 metastore service because the called HMS APIs are still available in Hive3.
-If there is any compatibility issue, please create an [issue](https://github.com/apache/gravitino/issues).
+The Hive catalog supports HMS versions 2.x and 3.x. it can automatically detect the HMS version.
:::
## Catalog
@@ -42,6 +41,7 @@ Besides the [common catalog properties](./gravitino-server-config.md#apache-grav
| `kerberos.check-interval-sec` | The interval to check validness of the principal | 60 | No | 0.4.0 |
| `kerberos.keytab-fetch-timeout-sec` | The timeout to fetch key tab | 60 | No | 0.4.0 |
| `list-all-tables` | Lists all tables in a database, including non-Hive tables, such as Iceberg, Hudi, etc. | false | No | 0.5.1 |
+| `default.catalog` | The default catalog name for the Hive3 metastore backend; this configuration is ignored when using a Hive2 metastore. | hive | No | 1.1.0 |
:::note
For `list-all-tables=false`, the Hive catalog will filter out:
diff --git a/docs/lakehouse-hudi-catalog.md b/docs/lakehouse-hudi-catalog.md
index 3dbf9f6643..1bf6c59116 100644
--- a/docs/lakehouse-hudi-catalog.md
+++ b/docs/lakehouse-hudi-catalog.md
@@ -38,6 +38,7 @@ Tested and verified with Apache Hudi `0.15.0`.
| `client.pool-size` | For HMS backend. The maximum number of Hive metastore clients in the pool for Gravitino. | 1 | No | 0.7.0-incubating |
| `client.pool-cache.eviction-interval-ms` | For HMS backend. The cache pool eviction interval. | 300000 | No | 0.7.0-incubating |
| `gravitino.bypass.` | Property name with this prefix passed down to the underlying backend client for use. Such as `gravitino.bypass.hive.metastore.failure.retries = 3` indicate 3 times of retries upon failure of Thrift metastore calls for HMS backend. | (none) | No | 0.7.0-incubating |
+| `default.catalog` | The default catalog name for the Hive3 metastore backend; this configuration is ignored when using a Hive2 metastore. | hive | No | 1.1.0 |
#### Catalog backend security