World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#59] feat(catalog): Maintain the namespaces in the hive Using HiveCatalog (#74)
Xun Liu1c5620b593fe
diff --git a/catalog-hive/build.gradle.kts b/catalog-hive/build.gradle.ktsindex e91dcd3d34..d6ea514d56 100644--- a/catalog-hive/build.gradle.kts+++ b/catalog-hive/build.gradle.kts@@ -11,12 +11,20 @@ dependencies {implementation(project(":api"))implementation(project(":core"))+ compileOnly(libs.lombok)+ annotationProcessor(libs.lombok)+implementation(libs.hive2.metastore)implementation(libs.hive2.exec) {exclude("org.slf4j")exclude("org.pentaho", "pentaho-aggdesigner-algorithm")}implementation(libs.guava)+ implementation(libs.substrait.java.core) {+ exclude("org.slf4j")+ exclude("com.fasterxml.jackson.core")+ exclude("com.fasterxml.jackson.datatype")+ }testImplementation(libs.slf4j.jdk14)testImplementation(libs.junit.jupiter.api)diff --git a/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/HiveCatalog.java b/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/HiveCatalog.javaindex 5ca33ca764..17d280a6b5 100644--- a/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/HiveCatalog.java+++ b/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/HiveCatalog.java@@ -1,14 +1,22 @@package com.datastrato.graviton.catalog.hive;-import com.datastrato.graviton.Config;+import com.datastrato.graviton.*;+import com.datastrato.graviton.catalog.hive.json.HiveDatabase;+import com.datastrato.graviton.exceptions.NamespaceAlreadyExistsException;+import com.datastrato.graviton.exceptions.NoSuchNamespaceException;+import com.datastrato.graviton.exceptions.NonEmptyNamespaceException;import com.datastrato.graviton.meta.BaseCatalog;import com.google.common.annotations.VisibleForTesting;+import com.google.common.base.Preconditions;+import java.util.Map;import org.apache.hadoop.conf.Configuration;import org.apache.hadoop.hive.conf.HiveConf;+import org.apache.hadoop.hive.metastore.api.*;+import org.apache.thrift.TException;import org.slf4j.Logger;import org.slf4j.LoggerFactory;-public class HiveCatalog extends BaseCatalog {+public class HiveCatalog extends BaseCatalog implements SupportsNamespaces {public static final Logger LOG = LoggerFactory.getLogger(HiveCatalog.class);@VisibleForTesting HiveClientPool clientPool;@@ -28,6 +36,191 @@ public class HiveCatalog extends BaseCatalog {this.clientPool = new HiveClientPool(1, hiveConf);}+ @Override+ public Namespace[] listNamespaces() throws NoSuchNamespaceException {+ return listNamespaces(Namespace.of("metalake", this.name));+ }++ @Override+ public Namespace[] listNamespaces(Namespace namespace) throws NoSuchNamespaceException {+ // hive namespace expression is `metalake.catalog.db`+ if (namespace.levels().length != 2) {+ throw new NoSuchNamespaceException("Namespace does not exist: " + namespace);+ }++ try {+ Namespace[] namespaces =+ clientPool+ .run(+ client ->+ client.getAllDatabases().stream()+ .map(ns -> Namespace.of(namespace.level(0), namespace.level(1), ns)))+ .toArray(Namespace[]::new);++ LOG.debug("Listing namespace {} returned namespaces: {}", namespace, namespaces);+ return namespaces;+ } catch (TException e) {+ throw new RuntimeException(+ "Failed to list all namespace: " + namespace + " in Hive Metastore", e);+ } catch (InterruptedException e) {+ throw new RuntimeException(e);+ }+ }++ @Override+ public boolean namespaceExists(Namespace namespace) {+ try {+ clientPool.run(client -> client.getDatabase(getDbNameFromNamespace(namespace)));+ } catch (TException | InterruptedException e) {+ return false;+ }+ return true;+ }++ @Override+ public void createNamespace(Namespace namespace, Map<String, String> metadata)+ throws NamespaceAlreadyExistsException {+ Preconditions.checkArgument(+ !namespace.isEmpty(),+ String.format("Cannot create namespace with invalid name: %s", namespace));+ Preconditions.checkArgument(+ isValidateNamespace(namespace),+ String.format("Cannot support multi part namespace in Hive Metastore: %s", namespace));++ try {+ HiveDatabase hiveDatabase =+ new HiveDatabase.Builder()+ .withConf(hiveConf)+ .withNamespace(namespace)+ .withMetadata(metadata)+ .build();++ clientPool.run(+ client -> {+ client.createDatabase(hiveDatabase.getInnerDatabase());+ return null;+ });++ LOG.info("Created namespace: {}", namespace);+ } catch (AlreadyExistsException e) {+ throw new NamespaceAlreadyExistsException(+ String.format("Namespace '%s' already exists!", namespace));+ } catch (TException e) {+ throw new RuntimeException(+ "Failed to create namespace " + namespace + " in Hive Metastore", e);+ } catch (InterruptedException e) {+ throw new RuntimeException(e);+ }+ }++ @Override+ public Map<String, String> loadNamespaceMetadata(Namespace namespace)+ throws NoSuchNamespaceException {+ if (!isValidateNamespace(namespace)) {+ throw new NoSuchNamespaceException(String.format("Namespace does not exist: %s", namespace));+ }++ try {+ Database database =+ clientPool.run(client -> client.getDatabase(getDbNameFromNamespace(namespace)));+ HiveDatabase hiveDatabase = new HiveDatabase.Builder().withHiveDatabase(database).build();+ Map<String, String> metadata = hiveDatabase.getMetadata();++ LOG.debug("Loaded metadata for namespace {} found {}", namespace, metadata.keySet());+ return metadata;+ } catch (NoSuchObjectException | UnknownDBException e) {+ throw new NoSuchNamespaceException(+ String.format("Namespace does not exist: %s", namespace), e);+ } catch (TException e) {+ throw new RuntimeException(+ "Failed to list namespace under namespace: " + namespace + " in Hive Metastore", e);+ } catch (InterruptedException e) {+ throw new RuntimeException(e);+ }+ }++ @Override+ public void alterNamespace(Namespace namespace, NamespaceChange... changes)+ throws NoSuchNamespaceException {+ Preconditions.checkArgument(+ !namespace.isEmpty(),+ String.format("Cannot create namespace with invalid name: %s", namespace));+ Preconditions.checkArgument(+ isValidateNamespace(namespace),+ String.format("Cannot support multi part namespace in Hive Metastore: %s", namespace));++ try {+ // load the database parameters+ Database database =+ clientPool.run(client -> client.getDatabase(getDbNameFromNamespace(namespace)));+ HiveDatabase hiveDatabase = new HiveDatabase.Builder().withHiveDatabase(database).build();+ Map<String, String> metadata = hiveDatabase.getMetadata();+ LOG.debug("Loaded metadata for namespace {} found {}", namespace, metadata.keySet());++ for (NamespaceChange change : changes) {+ if (change instanceof NamespaceChange.SetProperty) {+ metadata.put(+ ((NamespaceChange.SetProperty) change).getProperty(),+ ((NamespaceChange.SetProperty) change).getValue());+ } else if (change instanceof NamespaceChange.RemoveProperty) {+ metadata.remove(((NamespaceChange.RemoveProperty) change).getProperty());+ } else {+ throw new IllegalArgumentException("Unsupported namespace change type: " + change);+ }+ }++ // alter the hive database parameters+ Database alteredDatabase = database.deepCopy();+ alteredDatabase.setParameters(metadata);++ clientPool.run(+ client -> {+ client.alterDatabase(getDbNameFromNamespace(namespace), alteredDatabase);+ return null;+ });++ LOG.info("Altered namespace: {}", alteredDatabase);+ // todo(xun): hive dose not support renaming database name directly,+ // perhaps we can use namespace to mapping the database names indirectly+ } catch (TException | InterruptedException e) {+ throw new RuntimeException(e);+ }+ }++ @Override+ public boolean dropNamespace(Namespace namespace, boolean cascade)+ throws NonEmptyNamespaceException, NoSuchNamespaceException {+ if (!isValidateNamespace(namespace)) {+ return false;+ }++ try {+ clientPool.run(+ client -> {+ client.dropDatabase(getDbNameFromNamespace(namespace), false, false, cascade);+ return null;+ });++ LOG.info("Dropped namespace: {}", namespace);+ return true;+ } catch (InvalidOperationException e) {+ throw new NonEmptyNamespaceException(+ String.format("Namespace %s is not empty. One or more tables exist.", namespace, e));+ } catch (NoSuchObjectException | InterruptedException e) {+ return false;+ } catch (TException e) {+ throw new RuntimeException("Failed to drop namespace " + namespace + " in Hive Metastore", e);+ }+ }++ public static boolean isValidateNamespace(Namespace namespace) {+ return namespace.levels().length == 3;+ }++ private String getDbNameFromNamespace(Namespace namespace) {+ return namespace.level(2);+ }+public static class Builder extends BaseCatalog.BaseCatalogBuilder<Builder, HiveCatalog> {HiveConf hiveConf;diff --git a/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/json/HiveDatabase.java b/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/json/HiveDatabase.javanew file mode 100644index 0000000000..d8bba6d01a--- /dev/null+++ b/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/json/HiveDatabase.java@@ -0,0 +1,181 @@+package com.datastrato.graviton.catalog.hive.json;++import static com.datastrato.graviton.catalog.hive.HiveCatalog.isValidateNamespace;++import com.datastrato.graviton.Entity;+import com.datastrato.graviton.Field;+import com.datastrato.graviton.Namespace;+import com.datastrato.graviton.exceptions.NoSuchNamespaceException;+import com.google.common.base.Preconditions;+import com.google.common.collect.Maps;+import java.io.IOException;+import java.util.Collections;+import java.util.HashMap;+import java.util.Map;+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.PrincipalType;+import org.apache.hadoop.security.UserGroupInformation;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++public class HiveDatabase implements Entity {+ public static final Logger LOG = LoggerFactory.getLogger(HiveDatabase.class);+ public static final Field METADATA =+ Field.optional("metadata", Map.class, "The metadata of the database");+ public static final Field NAMESPACE =+ Field.optional("namespace", Namespace.class, "The namespace of the database");+ public static final Field CONFIGURATION =+ Field.optional("conf", Configuration.class, "The configuration of the hive server");++ public static final String HMS_DB_OWNER = "hive.metastore.database.owner";+ public static final String HMS_DB_OWNER_TYPE = "hive.metastore.database.owner-type";++ private Namespace namespace;++ private Map<String, String> metadata;+ private Configuration conf;++ private Database innerDatabase;++ @Override+ public Map<Field, Object> fields() {+ Map<Field, Object> fields = new HashMap<>();+ fields.put(METADATA, metadata);+ fields.put(NAMESPACE, namespace);+ fields.put(CONFIGURATION, conf);++ return Collections.unmodifiableMap(fields);+ }++ private Database generateInnerDatabase() {+ if (!isValidateNamespace(namespace)) {+ throw new NoSuchNamespaceException("Namespace does not exist: " + namespace);+ }++ Database database = new Database();+ Map<String, String> parameter = Maps.newHashMap();+ String dbName = namespace.level(2);+ database.setName(dbName);+ database.setLocationUri(databaseLocation(namespace.level(2)));++ metadata.forEach(+ (key, value) -> {+ if (key.equals("comment")) {+ database.setDescription(value);+ } else if (key.equals("location")) {+ database.setLocationUri(value);+ } else if (key.equals(HMS_DB_OWNER)) {+ database.setOwnerName(value);+ } else if (key.equals(HMS_DB_OWNER_TYPE) && value != null) {+ database.setOwnerType(PrincipalType.valueOf(value));+ } else {+ if (value != null) {+ parameter.put(key, value);+ }+ }+ });++ if (database.getOwnerName() == null) {+ database.setOwnerName(currentUser());+ database.setOwnerType(PrincipalType.USER);+ }++ database.setParameters(parameter);++ return database;+ }++ public Map<String, String> getMetadata() {+ Map<String, String> meta = Maps.newHashMap();++ meta.putAll(innerDatabase.getParameters());+ meta.put("location", innerDatabase.getLocationUri());+ if (innerDatabase.getDescription() != null) {+ meta.put("comment", innerDatabase.getDescription());+ }+ if (innerDatabase.getOwnerName() != null) {+ meta.put(HMS_DB_OWNER, innerDatabase.getOwnerName());+ if (innerDatabase.getOwnerType() != null) {+ meta.put(HMS_DB_OWNER_TYPE, innerDatabase.getOwnerType().name());+ }+ }++ return meta;+ }++ private String databaseLocation(String databaseName) {+ String warehouseLocation = conf.get(HiveConf.ConfVars.METASTOREWAREHOUSE.varname);+ Preconditions.checkNotNull(+ warehouseLocation, "Warehouse location is not set: hive.metastore.warehouse.dir=null");+ warehouseLocation = stripTrailingSlash(warehouseLocation);+ return String.format("%s/%s.db", warehouseLocation, databaseName);+ }++ public static String stripTrailingSlash(String path) {+ Preconditions.checkArgument(+ path != null && path.length() > 0, "path must not be null or empty");++ String result = path;+ while (result.endsWith("/")) {+ result = result.substring(0, result.length() - 1);+ }+ return result;+ }++ private static String currentUser() {+ String username = null;+ try {+ username = UserGroupInformation.getCurrentUser().getShortUserName();+ } catch (IOException e) {+ LOG.warn("Failed to get Hadoop user", e);+ }++ if (username != null) {+ return username;+ } else {+ LOG.warn("Hadoop user is null, defaulting to user.name");+ return System.getProperty("user.name");+ }+ }++ public Database getInnerDatabase() {+ return innerDatabase;+ }++ public static class Builder {+ private final HiveDatabase hiveDatabase;++ public Builder() {+ this.hiveDatabase = new HiveDatabase();+ }++ public HiveDatabase.Builder withConf(Configuration conf) {+ this.hiveDatabase.conf = conf;+ return this;+ }++ public HiveDatabase.Builder withHiveDatabase(Database database) {+ this.hiveDatabase.innerDatabase = database;+ return this;+ }++ public HiveDatabase.Builder withNamespace(Namespace namespace) {+ this.hiveDatabase.namespace = namespace;+ return this;+ }++ public HiveDatabase.Builder withMetadata(Map<String, String> metadata) {+ this.hiveDatabase.metadata = metadata;+ return this;+ }++ public HiveDatabase build() {+ if (null == this.hiveDatabase.innerDatabase) {+ this.hiveDatabase.innerDatabase = hiveDatabase.generateInnerDatabase();+ }+ return hiveDatabase;+ }+ }+}diff --git a/catalog-hive/src/test/java/com/datastrato/graviton/catalog/hive/HiveNamespaceTest.java b/catalog-hive/src/test/java/com/datastrato/graviton/catalog/hive/HiveNamespaceTest.javanew file mode 100644index 0000000000..c5a05f3612--- /dev/null+++ b/catalog-hive/src/test/java/com/datastrato/graviton/catalog/hive/HiveNamespaceTest.java@@ -0,0 +1,98 @@+package com.datastrato.graviton.catalog.hive;++import com.datastrato.graviton.Namespace;+import com.datastrato.graviton.NamespaceChange;+import com.datastrato.graviton.catalog.hive.miniHMS.MiniHiveMetastoreService;+import com.datastrato.graviton.meta.AuditInfo;+import com.google.common.collect.Maps;+import java.time.Instant;+import java.util.Arrays;+import java.util.Map;+import java.util.UUID;+import org.junit.Assert;+import org.junit.jupiter.api.Test;++public class HiveNamespaceTest extends MiniHiveMetastoreService {+ HiveCatalog initHiveCatalog() {+ AuditInfo auditInfo =+ new AuditInfo.Builder().withCreator("creator").withCreateTime(Instant.now()).build();++ HiveCatalog hiveCatalog =+ new HiveCatalog.Builder()+ .withId(1L)+ .withName("catalog")+ .withNamespace(Namespace.of("metalake"))+ .withType(HiveCatalog.Type.RELATIONAL)+ .withMetalakeId(1L)+ .withAuditInfo(auditInfo)+ .withHiveConf(metastore.hiveConf())+ .build();++ hiveCatalog.initialize(null);+ return hiveCatalog;+ }++ @Test+ public void createNamespaces() {+ HiveCatalog hiveCatalog = initHiveCatalog();++ Namespace namespace = Namespace.of("metalake", hiveCatalog.name(), genRandomName());+ Map<String, String> properties = Maps.newHashMap();+ properties.put("key1", "val1");+ properties.put("key2", "val2");+ hiveCatalog.createNamespace(namespace, properties);+ Assert.assertTrue(hiveCatalog.namespaceExists(namespace));++ Namespace[] namespaces = hiveCatalog.listNamespaces();+ Arrays.asList(namespaces).contains(namespace);+ }++ @Test+ public void alterNamespaces() {+ HiveCatalog hiveCatalog = initHiveCatalog();++ Namespace namespace = Namespace.of("metalake", hiveCatalog.name(), genRandomName());+ Map<String, String> properties = Maps.newHashMap();+ properties.put("key1", "val1");+ properties.put("key2", "val2");+ hiveCatalog.createNamespace(namespace, properties);+ Assert.assertTrue(hiveCatalog.namespaceExists(namespace));++ Map<String, String> properties1 = hiveCatalog.loadNamespaceMetadata(namespace);+ Assert.assertTrue(properties1.get("key1").equals("val1"));+ Assert.assertTrue(properties1.get("key2").equals("val2"));++ hiveCatalog.alterNamespace(namespace, NamespaceChange.removeProperty("key1"));+ hiveCatalog.alterNamespace(namespace, NamespaceChange.setProperty("key2", "val2-alter"));+ Map<String, String> properties2 = hiveCatalog.loadNamespaceMetadata(namespace);+ Assert.assertFalse(properties2.containsKey("key1"));+ Assert.assertTrue(properties2.get("key2").equals("val2-alter"));++ hiveCatalog.alterNamespace(+ namespace,+ NamespaceChange.setProperty("key3", "val3"),+ NamespaceChange.setProperty("key4", "val4"));+ Map<String, String> properties3 = hiveCatalog.loadNamespaceMetadata(namespace);+ Assert.assertTrue(properties3.get("key3").equals("val3"));+ Assert.assertTrue(properties3.get("key4").equals("val4"));+ }++ @Test+ public void dropNamespaces() {+ HiveCatalog hiveCatalog = initHiveCatalog();++ Namespace namespace = Namespace.of("metalake", hiveCatalog.name(), genRandomName());+ Map<String, String> properties = Maps.newHashMap();+ properties.put("key1", "val1");+ properties.put("key2", "val2");+ hiveCatalog.createNamespace(namespace, properties);++ Assert.assertTrue(hiveCatalog.namespaceExists(namespace));+ hiveCatalog.dropNamespace(namespace, true);+ Assert.assertFalse(hiveCatalog.namespaceExists(namespace));+ }++ private static String genRandomName() {+ return UUID.randomUUID().toString().replace("-", "");+ }+}