World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#114] feat(core): implement the catalog management logic (#129)
Jerry Shao5a5471f3c6cb
diff --git a/core/src/main/java/com/datastrato/graviton/Configs.java b/core/src/main/java/com/datastrato/graviton/Configs.javaindex 7d1d51564f..4bdf178a90 100644--- a/core/src/main/java/com/datastrato/graviton/Configs.java+++ b/core/src/main/java/com/datastrato/graviton/Configs.java@@ -51,4 +51,11 @@ public interface Configs {.version("0.1.0").longConf().createWithDefault(60 * 60 * 1000L);++ ConfigEntry<Boolean> CATALOG_LOAD_ISOLATED =+ new ConfigBuilder("graviton.catalog.classloader.isolated")+ .doc("Whether to load the catalog in an isolated classloader")+ .version("0.1.0")+ .booleanConf()+ .createWithDefault(true);}diff --git a/core/src/main/java/com/datastrato/graviton/EntityStore.java b/core/src/main/java/com/datastrato/graviton/EntityStore.javaindex 306aaecafa..6e3a628e79 100644--- a/core/src/main/java/com/datastrato/graviton/EntityStore.java+++ b/core/src/main/java/com/datastrato/graviton/EntityStore.java@@ -8,6 +8,7 @@ import com.datastrato.graviton.util.Executable;import java.io.Closeable;import java.io.IOException;import java.util.List;+import java.util.function.Function;public interface EntityStore extends Closeable {@@ -86,6 +87,29 @@ public interface EntityStore extends Closeable {<E extends Entity & HasIdentifier> void put(NameIdentifier ident, E e, boolean overwritten)throws IOException, EntityAlreadyExistsException;+ /**+ * Update the entity into the underlying storage.+ *+ * <p>Note: the {@link NameIdentifier} of the updated entity may be changed. Based on the design+ * of the storage key, the implementation may have two implementations.+ *+ * <p>1) if the storage key is name relevant, it needs to delete the old entity and store the new+ * entity with the new key. 2) or if the storage key is name irrelevant, it can just store the new+ * entity with the current key.+ *+ * <p>Note: the whole update operation should be in one transaction.+ *+ * @param ident the name identifier of the entity+ * @param updater the updater function to update the entity+ * @param <E> the type of the entity+ * @return E the updated entity+ * @throws IOException if the store operation fails+ * @throws NoSuchEntityException if the entity does not exist+ */+ <E extends Entity & HasIdentifier> E update(+ NameIdentifier ident, Class<E> type, Function<E, E> updater)+ throws IOException, NoSuchEntityException;+/*** Get the entity from the underlying storage.*diff --git a/core/src/main/java/com/datastrato/graviton/GravitonEnv.java b/core/src/main/java/com/datastrato/graviton/GravitonEnv.javaindex b2478821c1..d619893162 100644--- a/core/src/main/java/com/datastrato/graviton/GravitonEnv.java+++ b/core/src/main/java/com/datastrato/graviton/GravitonEnv.java@@ -54,7 +54,7 @@ public class GravitonEnv {this.metalakesOperations = new BaseMetalakesOperations();// Create and initialize Catalog related modules- this.catalogManager = new CatalogManager(config);+ this.catalogManager = new CatalogManager(config, entityStore);this.catalogOperationDispatcher = new CatalogOperationDispatcher(catalogManager);LOG.info("Graviton Environment is initialized.");diff --git a/core/src/main/java/com/datastrato/graviton/catalog/CatalogManager.java b/core/src/main/java/com/datastrato/graviton/catalog/CatalogManager.javaindex b93bc36a62..393c2412ff 100644--- a/core/src/main/java/com/datastrato/graviton/catalog/CatalogManager.java+++ b/core/src/main/java/com/datastrato/graviton/catalog/CatalogManager.java@@ -9,12 +9,17 @@ import com.datastrato.graviton.CatalogChange;import com.datastrato.graviton.CatalogProvider;import com.datastrato.graviton.Config;import com.datastrato.graviton.Configs;+import com.datastrato.graviton.EntityAlreadyExistsException;+import com.datastrato.graviton.EntityStore;import com.datastrato.graviton.NameIdentifier;import com.datastrato.graviton.Namespace;+import com.datastrato.graviton.NoSuchEntityException;import com.datastrato.graviton.SupportsCatalogs;import com.datastrato.graviton.exceptions.CatalogAlreadyExistsException;import com.datastrato.graviton.exceptions.NoSuchCatalogException;import com.datastrato.graviton.exceptions.NoSuchMetalakeException;+import com.datastrato.graviton.meta.AuditInfo;+import com.datastrato.graviton.meta.BaseMetalake;import com.datastrato.graviton.meta.CatalogEntity;import com.datastrato.graviton.rel.SupportsSchemas;import com.datastrato.graviton.rel.TableCatalog;@@ -23,17 +28,22 @@ import com.datastrato.graviton.util.ThrowableFunction;import com.github.benmanes.caffeine.cache.Cache;import com.github.benmanes.caffeine.cache.Caffeine;import com.github.benmanes.caffeine.cache.Scheduler;+import com.google.common.annotations.VisibleForTesting;import com.google.common.base.Preconditions;import com.google.common.collect.Iterables;import com.google.common.collect.Lists;import com.google.common.collect.Maps;import com.google.common.collect.Streams;import com.google.common.util.concurrent.ThreadFactoryBuilder;+import java.io.Closeable;import java.io.File;+import java.io.IOException;import java.net.MalformedURLException;import java.net.URL;+import java.time.Instant;import java.util.Arrays;import java.util.Collections;+import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Optional;@@ -44,7 +54,7 @@ import java.util.stream.Collectors;import org.slf4j.Logger;import org.slf4j.LoggerFactory;-public class CatalogManager implements SupportsCatalogs {+public class CatalogManager implements SupportsCatalogs, Closeable {private static final Logger LOG = LoggerFactory.getLogger(CatalogManager.class);@@ -101,12 +111,15 @@ public class CatalogManager implements SupportsCatalogs {private final Config config;- private final Cache<NameIdentifier, CatalogWrapper> catalogCache;+ @VisibleForTesting final Cache<NameIdentifier, CatalogWrapper> catalogCache;- public CatalogManager(Config config) {+ private final EntityStore store;++ public CatalogManager(Config config, EntityStore store) {this.config = config;- long cacheEvictionIntervalInMs = config.get(Configs.CATALOG_CACHE_EVICTION_INTERVAL_MS);+ this.store = store;+ long cacheEvictionIntervalInMs = config.get(Configs.CATALOG_CACHE_EVICTION_INTERVAL_MS);this.catalogCache =Caffeine.newBuilder().expireAfterAccess(cacheEvictionIntervalInMs, TimeUnit.MILLISECONDS)@@ -126,98 +139,200 @@ public class CatalogManager implements SupportsCatalogs {.build();}+ @Overridepublic void close() {catalogCache.invalidateAll();}@Overridepublic NameIdentifier[] listCatalogs(Namespace namespace) throws NoSuchMetalakeException {- throw new UnsupportedOperationException("Not implemented yet");+ NameIdentifier metalakeIdent = NameIdentifier.of(namespace.levels());++ boolean metalakeExists;+ try {+ metalakeExists = store.exists(metalakeIdent);+ } catch (IOException e) {+ LOG.error("Failed to do storage operation", e);+ throw new RuntimeException(e);+ }++ if (!metalakeExists) {+ throw new NoSuchMetalakeException("Metalake " + metalakeIdent + " does not exist");+ }++ try {+ return store.list(namespace, CatalogEntity.class).stream()+ .map(entity -> NameIdentifier.of(namespace, entity.name()))+ .toArray(NameIdentifier[]::new);++ } catch (IOException ioe) {+ LOG.error("Failed to list catalogs in metalake {}", metalakeIdent, ioe);+ throw new RuntimeException(ioe);+ }}@Overridepublic Catalog loadCatalog(NameIdentifier ident) throws NoSuchCatalogException {- return loadCatalogWrapper(ident).catalog;+ return loadCatalogAndWrap(ident).catalog;}@Overridepublic Catalog createCatalog(NameIdentifier ident, Catalog.Type type, String comment, Map<String, String> properties)throws NoSuchMetalakeException, CatalogAlreadyExistsException {- // Check if the metalake is existed, throw NoSuchMetalakeException if it is not existed.-- // Build CatalogEntity-- // Check and store CatalogEntity+ try {+ CatalogEntity entity =+ store.executeInTransaction(+ () -> {+ NameIdentifier metalakeIdent = NameIdentifier.of(ident.namespace().levels());+ BaseMetalake metalake = store.get(metalakeIdent, BaseMetalake.class);++ CatalogEntity e =+ new CatalogEntity.Builder()+ .withId(1L /* TODO. use ID generator */)+ .withMetalakeId(metalake.getId())+ .withName(ident.name())+ .withNamespace(ident.namespace())+ .withType(type)+ .withComment(comment)+ .withProperties(properties)+ .withAuditInfo(+ new AuditInfo.Builder()+ .withCreator("graviton") /* TODO. Should change to real user */+ .withCreateTime(Instant.now())+ .build())+ .build();++ store.put(ident, e, false /* overwrite */);+ return e;+ });+ return catalogCache.get(ident, id -> createCatalogWrapper(entity)).catalog;- // Create CatalogWrapper and put it into catalogCache+ } catch (NoSuchEntityException ne) {+ LOG.warn("Metalake {} does not exist", ident.namespace(), ne);+ throw new NoSuchMetalakeException("Metalake " + ident.namespace() + " does not exist");- // return the created catalog+ } catch (EntityAlreadyExistsException ee) {+ LOG.warn("Catalog {} already exists", ident, ee);+ throw new CatalogAlreadyExistsException("Catalog " + ident + " already exists");- throw new UnsupportedOperationException("Not implemented yet");+ } catch (IOException ioe) {+ LOG.error("Failed to create catalog {}", ident, ioe);+ throw new RuntimeException(ioe);+ }}@Overridepublic Catalog alterCatalog(NameIdentifier ident, CatalogChange... changes)throws NoSuchCatalogException, IllegalArgumentException {- throw new UnsupportedOperationException("Not implemented yet");+ // There could be a race issue that someone is using the catalog from cache while we are+ // updating it.+ catalogCache.invalidate(ident);++ try {+ CatalogEntity updatedCatalog =+ store.update(+ ident,+ CatalogEntity.class,+ catalog -> {+ CatalogEntity.Builder newCatalogBuilder =+ new CatalogEntity.Builder()+ .withId(catalog.getId())+ .withMetalakeId(catalog.getMetalakeId())+ .withName(catalog.name())+ .withNamespace(ident.namespace())+ .withType(catalog.getType())+ .withComment(catalog.getComment());++ AuditInfo newInfo =+ new AuditInfo.Builder()+ .withCreator(catalog.auditInfo().creator())+ .withCreateTime(catalog.auditInfo().createTime())+ .withLastModifier(+ catalog.auditInfo().creator()) /* TODO. We should use real user */+ .withLastModifiedTime(Instant.now())+ .build();+ newCatalogBuilder.withAuditInfo(newInfo);++ Map<String, String> newProps =+ catalog.getProperties() == null+ ? new HashMap<>()+ : new HashMap<>(catalog.getProperties());+ newCatalogBuilder = updateEntity(newCatalogBuilder, newProps, changes);++ return newCatalogBuilder.build();+ });+ return catalogCache.get(+ updatedCatalog.nameIdentifier(), id -> createCatalogWrapper(updatedCatalog))+ .catalog;++ } catch (NoSuchEntityException ne) {+ LOG.warn("Catalog {} does not exist", ident, ne);+ throw new NoSuchCatalogException("Catalog " + ident + " does not exist");++ } catch (IllegalArgumentException iae) {+ LOG.warn("Failed to alter catalog {} with unknown change", ident, iae);+ throw iae;++ } catch (IOException ioe) {+ LOG.error("Failed to alter catalog {}", ident, ioe);+ throw new RuntimeException(ioe);+ }}@Overridepublic boolean dropCatalog(NameIdentifier ident) {- throw new UnsupportedOperationException("Not implemented yet");+ // There could be a race issue that someone is using the catalog while we are dropping it.+ catalogCache.invalidate(ident);++ try {+ return store.delete(ident);+ } catch (IOException ioe) {+ LOG.error("Failed to drop catalog {}", ident, ioe);+ throw new RuntimeException(ioe);+ }}- public CatalogWrapper loadCatalogWrapper(NameIdentifier ident) throws NoSuchCatalogException {+ public CatalogWrapper loadCatalogAndWrap(NameIdentifier ident) throws NoSuchCatalogException {return catalogCache.get(ident, this::loadCatalogInternal);}private CatalogWrapper loadCatalogInternal(NameIdentifier ident) throws NoSuchCatalogException {- // Load CatalogEntity from CatalogStore-- // Create CatalogWrapper+ try {+ CatalogEntity entity = store.get(ident, CatalogEntity.class);+ return createCatalogWrapper(entity);- // return CatalogWrapper+ } catch (NoSuchEntityException ne) {+ LOG.warn("Catalog {} does not exist", ident, ne);+ throw new NoSuchCatalogException("Catalog " + ident + " does not exist");- throw new UnsupportedOperationException("Not implemented yet");+ } catch (IOException ioe) {+ LOG.error("Failed to load catalog {}", ident, ioe);+ throw new RuntimeException(ioe);+ }}private CatalogWrapper createCatalogWrapper(CatalogEntity entity) {Map<String, String> mergedConf =mergeConf(entity.getProperties(), catalogConf(entity.name(), config));- // Building package path and class loaderString provider = mergedConf.get(Catalog.PROPERTY_PROVIDER);Preconditions.checkArgument(provider != null,"'provider' not set in catalog properties or conf via "+ "'graviton.catalog.<name>.provider'");- String pkg = mergedConf.get(Catalog.PROPERTY_PACKAGE);- String gravitonHome = System.getenv("GRAVITON_HOME");- Preconditions.checkArgument(gravitonHome != null, "GRAVITON_HOME not set");- boolean testEnv = System.getenv("GRAVITON_TEST") != null;- String pkgPath;- if (pkg != null) {- pkgPath = pkg;- } else if (!testEnv) {- pkgPath = gravitonHome + File.separator + "catalogs" + File.separator + provider;+ IsolatedClassLoader classLoader;+ if (config.get(Configs.CATALOG_LOAD_ISOLATED)) {+ String pkgPath = buildPkgPath(mergedConf, provider);+ classLoader = buildClassLoader(pkgPath);} else {- pkgPath =- new StringBuilder()- .append(gravitonHome)- .append(File.separator)- .append("catalog-")- .append(provider)- .append(File.separator)- .append("build")- .append(File.separator)- .append("libs")- .toString();+ // This will use the current class loader, it is mainly used for test.+ classLoader =+ new IsolatedClassLoader(+ Collections.emptyList(), Collections.emptyList(), Collections.emptyList());}- IsolatedClassLoader classLoader = buildClassLoader(pkgPath);-// Load Catalog class instanceBaseCatalog catalog;try {@@ -258,6 +373,35 @@ public class CatalogManager implements SupportsCatalogs {return config.getConfigsWithPrefix(confPrefix);}+ private String buildPkgPath(Map<String, String> conf, String provider) {+ String pkg = conf.get(Catalog.PROPERTY_PACKAGE);++ String gravitonHome = System.getenv("GRAVITON_HOME");+ Preconditions.checkArgument(gravitonHome != null, "GRAVITON_HOME not set");+ boolean testEnv = System.getenv("GRAVITON_TEST") != null;++ String pkgPath;+ if (pkg != null) {+ pkgPath = pkg;+ } else if (!testEnv) {+ pkgPath = gravitonHome + File.separator + "catalogs" + File.separator + provider;+ } else {+ pkgPath =+ new StringBuilder()+ .append(gravitonHome)+ .append(File.separator)+ .append("catalog-")+ .append(provider)+ .append(File.separator)+ .append("build")+ .append(File.separator)+ .append("libs")+ .toString();+ }++ return pkgPath;+ }+private IsolatedClassLoader buildClassLoader(String pkgPath) {// Listing all the jars under the package path and build the isolated class loader.File pkgFolder = new File(pkgPath);@@ -288,7 +432,7 @@ public class CatalogManager implements SupportsCatalogs {List<Class<? extends CatalogProvider>> providers =Streams.stream(loader.iterator()).filter(p -> p.shortName().equalsIgnoreCase(provider))- .map(p -> p.getClass())+ .map(CatalogProvider::getClass).collect(Collectors.toList());if (providers.size() == 0) {@@ -299,4 +443,33 @@ public class CatalogManager implements SupportsCatalogs {return Iterables.getOnlyElement(providers);}}++ private CatalogEntity.Builder updateEntity(+ CatalogEntity.Builder builder, Map<String, String> newProps, CatalogChange... changes) {+ for (CatalogChange change : changes) {+ if (change instanceof CatalogChange.RenameCatalog) {+ CatalogChange.RenameCatalog rename = (CatalogChange.RenameCatalog) change;+ builder.withName(rename.getNewName());++ } else if (change instanceof CatalogChange.UpdateCatalogComment) {+ CatalogChange.UpdateCatalogComment updateComment =+ (CatalogChange.UpdateCatalogComment) change;+ builder.withComment(updateComment.getNewComment());++ } else if (change instanceof CatalogChange.SetProperty) {+ CatalogChange.SetProperty setProperty = (CatalogChange.SetProperty) change;+ newProps.put(setProperty.getProperty(), setProperty.getValue());++ } else if (change instanceof CatalogChange.RemoveProperty) {+ CatalogChange.RemoveProperty removeProperty = (CatalogChange.RemoveProperty) change;+ newProps.remove(removeProperty.getProperty());++ } else {+ throw new IllegalArgumentException(+ "Unsupported catalog change: " + change.getClass().getSimpleName());+ }+ }++ return builder.withProperties(newProps);+ }}diff --git a/core/src/main/java/com/datastrato/graviton/catalog/CatalogOperationDispatcher.java b/core/src/main/java/com/datastrato/graviton/catalog/CatalogOperationDispatcher.javaindex 722a81f31c..c304bd8c50 100644--- a/core/src/main/java/com/datastrato/graviton/catalog/CatalogOperationDispatcher.java+++ b/core/src/main/java/com/datastrato/graviton/catalog/CatalogOperationDispatcher.java@@ -142,7 +142,7 @@ public class CatalogOperationDispatcher implements TableCatalog, SupportsSchemasprivate <R, E extends Throwable> R doWithCatalog(NameIdentifier ident, ThrowableFunction<CatalogManager.CatalogWrapper, R> fn, Class<E> ex)throws E {- CatalogManager.CatalogWrapper c = catalogManager.loadCatalogWrapper(ident);+ CatalogManager.CatalogWrapper c = catalogManager.loadCatalogAndWrap(ident);try {return fn.apply(c);@@ -160,7 +160,7 @@ public class CatalogOperationDispatcher implements TableCatalog, SupportsSchemasClass<E1> ex1,Class<E2> ex2)throws E1, E2 {- CatalogManager.CatalogWrapper c = catalogManager.loadCatalogWrapper(ident);+ CatalogManager.CatalogWrapper c = catalogManager.loadCatalogAndWrap(ident);try {return fn.apply(c);diff --git a/core/src/main/java/com/datastrato/graviton/meta/BaseCatalog.java b/core/src/main/java/com/datastrato/graviton/meta/BaseCatalog.javadeleted file mode 100644index 5b0a588866..0000000000--- a/core/src/main/java/com/datastrato/graviton/meta/BaseCatalog.java+++ /dev/null@@ -1,4 +0,0 @@-/*- * Copyright 2023 Datastrato.- * This software is licensed under the Apache License version 2.- */diff --git a/core/src/main/java/com/datastrato/graviton/proto/CatalogEntitySerDe.java b/core/src/main/java/com/datastrato/graviton/proto/CatalogEntitySerDe.javaindex 68d7de8370..ace0443bc4 100644--- a/core/src/main/java/com/datastrato/graviton/proto/CatalogEntitySerDe.java+++ b/core/src/main/java/com/datastrato/graviton/proto/CatalogEntitySerDe.java@@ -2,7 +2,6 @@* Copyright 2023 Datastrato.* This software is licensed under the Apache License version 2.*/-package com.datastrato.graviton.proto;import com.datastrato.graviton.meta.AuditInfo;@@ -14,6 +13,7 @@ public class CatalogEntitySerDe implements ProtoSerDe<CatalogEntity, Catalog> {Catalog.Builder builder =Catalog.newBuilder().setId(catalogEntity.getId())+ .setMetalakeId(catalogEntity.getMetalakeId()).setName(catalogEntity.name()).setAuditInfo(new AuditInfoSerDe().serialize((AuditInfo) catalogEntity.auditInfo()));@@ -28,7 +28,6 @@ public class CatalogEntitySerDe implements ProtoSerDe<CatalogEntity, Catalog> {com.datastrato.graviton.proto.Catalog.Type type =com.datastrato.graviton.proto.Catalog.Type.valueOf(catalogEntity.getType().name());builder.setType(type);- builder.setMetalakeId(catalogEntity.getMetalakeId());// Attention we have ignored namespace field herereturn builder.build();@@ -40,6 +39,7 @@ public class CatalogEntitySerDe implements ProtoSerDe<CatalogEntity, Catalog> {builder.withId(p.getId()).withName(p.getName())+ .withMetalakeId(p.getMetalakeId()).withAuditInfo(new AuditInfoSerDe().deserialize(p.getAuditInfo()));if (p.hasComment()) {@@ -51,7 +51,6 @@ public class CatalogEntitySerDe implements ProtoSerDe<CatalogEntity, Catalog> {}builder.withType(com.datastrato.graviton.Catalog.Type.valueOf(p.getType().name()));- builder.withMetalakeId(p.getMetalakeId());return builder.build();}}diff --git a/core/src/main/java/com/datastrato/graviton/proto/ProtoEntitySerDe.java b/core/src/main/java/com/datastrato/graviton/proto/ProtoEntitySerDe.javaindex 4a472f0e14..d530fc9235 100644--- a/core/src/main/java/com/datastrato/graviton/proto/ProtoEntitySerDe.java+++ b/core/src/main/java/com/datastrato/graviton/proto/ProtoEntitySerDe.java@@ -45,6 +45,9 @@ public class ProtoEntitySerDe implements EntitySerDe {Optional.ofNullable(Thread.currentThread().getContextClassLoader()).orElse(getClass().getClassLoader());+ // TODO. This potentially has issues in creating serde objects, because the class load here+ // may have no context for entities which are implemented in the specific catalog module. We+ // should lazily create the serde class in the classloader when serializing and deserializing.this.entityToSerDe = Maps.newHashMap();for (Map.Entry<String, String> entry : ENTITY_TO_SERDE.entrySet()) {String key = entry.getKey();diff --git a/core/src/main/java/com/datastrato/graviton/storage/kv/KvEntityStore.java b/core/src/main/java/com/datastrato/graviton/storage/kv/KvEntityStore.javaindex af307b422f..5907007bae 100644--- a/core/src/main/java/com/datastrato/graviton/storage/kv/KvEntityStore.java+++ b/core/src/main/java/com/datastrato/graviton/storage/kv/KvEntityStore.java@@ -23,6 +23,7 @@ import com.google.common.collect.Lists;import java.io.IOException;import java.util.List;import java.util.Objects;+import java.util.function.Function;import org.apache.commons.lang3.tuple.Pair;import org.slf4j.Logger;import org.slf4j.LoggerFactory;@@ -89,6 +90,29 @@ public class KvEntityStore implements EntityStore {backend.put(key, value, overwritten);}+ @Override+ public <E extends Entity & HasIdentifier> E update(+ NameIdentifier ident, Class<E> type, Function<E, E> updater)+ throws IOException, NoSuchEntityException {+ return executeInTransaction(+ () -> {+ byte[] key = entityKeyEncoder.encode(ident);+ byte[] value = backend.get(key);+ if (value == null) {+ throw new NoSuchEntityException(ident.toString());+ }++ E e = serDe.deserialize(value, type);+ E updatedE = updater.apply(e);+ if (!updatedE.nameIdentifier().equals(ident)) {+ delete(ident);+ }++ put(updatedE.nameIdentifier(), updatedE, true /* overwritten */);+ return updatedE;+ });+ }+@Overridepublic <E extends Entity & HasIdentifier> E get(NameIdentifier ident, Class<E> type)throws NoSuchEntityException, IOException {diff --git a/core/src/main/java/com/datastrato/graviton/util/IsolatedClassLoader.java b/core/src/main/java/com/datastrato/graviton/util/IsolatedClassLoader.javaindex aaa9d3ccee..faef5a0d71 100644--- a/core/src/main/java/com/datastrato/graviton/util/IsolatedClassLoader.java+++ b/core/src/main/java/com/datastrato/graviton/util/IsolatedClassLoader.java@@ -65,9 +65,9 @@ public class IsolatedClassLoader implements Closeable {return classLoader;}+ ClassLoader parent = Thread.currentThread().getContextClassLoader();this.classLoader =- new URLClassLoader(- execJars.toArray(new URL[0]), Thread.currentThread().getContextClassLoader()) {+ new URLClassLoader(execJars.toArray(new URL[0]), parent) {@Overrideprotected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {Class<?> clazz = findLoadedClass(name);diff --git a/core/src/test/java/com/datastrato/graviton/TestEntityStore.java b/core/src/test/java/com/datastrato/graviton/TestEntityStore.javaindex 59f31000d9..aa58bfca24 100644--- a/core/src/test/java/com/datastrato/graviton/TestEntityStore.java+++ b/core/src/test/java/com/datastrato/graviton/TestEntityStore.java@@ -19,6 +19,7 @@ import java.util.List;import java.util.Map;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;+import java.util.function.Function;import java.util.stream.Collectors;import org.junit.jupiter.api.Assertions;import org.junit.jupiter.api.Test;@@ -78,6 +79,27 @@ public class TestEntityStore {}}+ @Override+ public <E extends Entity & HasIdentifier> E update(+ NameIdentifier ident, Class<E> type, Function<E, E> updater)+ throws IOException, NoSuchEntityException {+ return executeInTransaction(+ () -> {+ E e = (E) entityMap.get(ident);+ if (e == null) {+ throw new NoSuchEntityException("Entity " + ident + " does not exist");+ }++ E newE = updater.apply(e);+ NameIdentifier newIdent = NameIdentifier.of(newE.namespace(), newE.name());+ if (!newIdent.equals(ident)) {+ delete(ident);+ }+ entityMap.put(newIdent, newE);+ return newE;+ });+ }+@Overridepublic <E extends Entity & HasIdentifier> E get(NameIdentifier ident, Class<E> type)throws NoSuchEntityException, IOException {diff --git a/core/src/test/java/com/datastrato/graviton/catalog/TestCatalogManager.java b/core/src/test/java/com/datastrato/graviton/catalog/TestCatalogManager.javanew file mode 100644index 0000000000..477220d247--- /dev/null+++ b/core/src/test/java/com/datastrato/graviton/catalog/TestCatalogManager.java@@ -0,0 +1,230 @@+/*+ * Copyright 2023 Datastrato.+ * This software is licensed under the Apache License version 2.+ */+package com.datastrato.graviton.catalog;++import com.datastrato.graviton.Catalog;+import com.datastrato.graviton.CatalogChange;+import com.datastrato.graviton.Config;+import com.datastrato.graviton.Configs;+import com.datastrato.graviton.EntityStore;+import com.datastrato.graviton.NameIdentifier;+import com.datastrato.graviton.TestEntityStore;+import com.datastrato.graviton.exceptions.CatalogAlreadyExistsException;+import com.datastrato.graviton.exceptions.NoSuchCatalogException;+import com.datastrato.graviton.exceptions.NoSuchMetalakeException;+import com.datastrato.graviton.meta.AuditInfo;+import com.datastrato.graviton.meta.BaseMetalake;+import com.datastrato.graviton.meta.SchemaVersion;+import com.google.common.collect.ImmutableMap;+import com.google.common.collect.Sets;+import java.io.IOException;+import java.time.Instant;+import java.util.Map;+import java.util.Set;+import org.junit.jupiter.api.AfterAll;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;++public class TestCatalogManager {++ private static CatalogManager catalogManager;++ private static EntityStore entityStore;++ private static Config config;++ private static String metalake = "metalake";++ @BeforeAll+ public static void setUp() throws IOException {+ config = new Config(false) {};+ config.set(Configs.CATALOG_LOAD_ISOLATED, false);++ entityStore = new TestEntityStore.InMemoryEntityStore();+ entityStore.initialize(config);+ entityStore.setSerDe(null);++ BaseMetalake metalakeEntity =+ new BaseMetalake.Builder()+ .withId(1L)+ .withName(metalake)+ .withAuditInfo(+ new AuditInfo.Builder().withCreator("test").withCreateTime(Instant.now()).build())+ .withVersion(SchemaVersion.V_0_1)+ .build();+ entityStore.put(metalakeEntity.nameIdentifier(), metalakeEntity, true);++ catalogManager = new CatalogManager(config, entityStore);+ }++ @AfterAll+ public static void tearDown() throws Exception {+ if (entityStore != null) {+ entityStore.close();+ entityStore = null;+ }++ if (catalogManager != null) {+ catalogManager.close();+ catalogManager = null;+ }+ }++ @Test+ public void testCreateCatalog() {+ NameIdentifier ident = NameIdentifier.of("metalake", "test1");+ Map<String, String> props = ImmutableMap.of("provider", "test");++ Catalog testCatalog =+ catalogManager.createCatalog(ident, Catalog.Type.RELATIONAL, "comment", props);+ Assertions.assertEquals("test1", testCatalog.name());+ Assertions.assertEquals("comment", testCatalog.comment());+ Assertions.assertEquals(props, testCatalog.properties());+ Assertions.assertEquals(Catalog.Type.RELATIONAL, testCatalog.type());++ // Test without setting "provider"+ Map<String, String> props1 = ImmutableMap.of();+ NameIdentifier ident1 = NameIdentifier.of("metalake", "test2");+ Throwable exception =+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> catalogManager.createCatalog(ident1, Catalog.Type.RELATIONAL, "comment", props1));+ Assertions.assertTrue(+ exception.getMessage().contains("'provider' not set in catalog properties"));++ // Test create under non-existed metalake+ NameIdentifier ident2 = NameIdentifier.of("metalake1", "test1");+ Throwable exception1 =+ Assertions.assertThrows(+ NoSuchMetalakeException.class,+ () -> catalogManager.createCatalog(ident2, Catalog.Type.RELATIONAL, "comment", props));+ Assertions.assertTrue(exception1.getMessage().contains("Metalake metalake1 does not exist"));++ // Test create with duplicated name+ Throwable exception2 =+ Assertions.assertThrows(+ CatalogAlreadyExistsException.class,+ () -> catalogManager.createCatalog(ident, Catalog.Type.RELATIONAL, "comment", props));+ Assertions.assertTrue(+ exception2.getMessage().contains("Catalog metalake.test1 already exists"));++ // Test if the catalog is already cached+ CatalogManager.CatalogWrapper cached = catalogManager.catalogCache.getIfPresent(ident);+ Assertions.assertNotNull(cached);+ }++ @Test+ public void testListCatalogs() {+ NameIdentifier ident = NameIdentifier.of("metalake", "test11");+ NameIdentifier ident1 = NameIdentifier.of("metalake", "test12");+ Map<String, String> props = ImmutableMap.of("provider", "test");++ catalogManager.createCatalog(ident, Catalog.Type.RELATIONAL, "comment", props);+ catalogManager.createCatalog(ident1, Catalog.Type.RELATIONAL, "comment", props);++ Set<NameIdentifier> idents = Sets.newHashSet(catalogManager.listCatalogs(ident.namespace()));+ Assertions.assertEquals(2, idents.size());+ Assertions.assertEquals(Sets.newHashSet(ident, ident1), idents);++ // Test list under non-existed metalake+ NameIdentifier ident2 = NameIdentifier.of("metalake1", "test1");+ Throwable exception =+ Assertions.assertThrows(+ NoSuchMetalakeException.class, () -> catalogManager.listCatalogs(ident2.namespace()));+ Assertions.assertTrue(exception.getMessage().contains("Metalake metalake1 does not exist"));+ }++ @Test+ public void testLoadCatalog() {+ NameIdentifier ident = NameIdentifier.of("metalake", "test21");+ Map<String, String> props = ImmutableMap.of("provider", "test");++ catalogManager.createCatalog(ident, Catalog.Type.RELATIONAL, "comment", props);++ Catalog catalog = catalogManager.loadCatalog(ident);+ Assertions.assertEquals("test21", catalog.name());+ Assertions.assertEquals("comment", catalog.comment());+ Assertions.assertEquals(props, catalog.properties());+ Assertions.assertEquals(Catalog.Type.RELATIONAL, catalog.type());++ // Test load non-existed catalog+ NameIdentifier ident1 = NameIdentifier.of("metalake", "test22");+ Throwable exception =+ Assertions.assertThrows(+ NoSuchCatalogException.class, () -> catalogManager.loadCatalog(ident1));+ Assertions.assertTrue(+ exception.getMessage().contains("Catalog metalake.test22 does not exist"));++ // Load operation will cache the catalog+ Assertions.assertNotNull(catalogManager.catalogCache.getIfPresent(ident));+ }++ @Test+ public void testAlterCatalog() {+ NameIdentifier ident = NameIdentifier.of("metalake", "test31");+ Map<String, String> props = ImmutableMap.of("provider", "test");+ String comment = "comment";++ catalogManager.createCatalog(ident, Catalog.Type.RELATIONAL, comment, props);++ // Test alter name;+ CatalogChange change = CatalogChange.rename("test32");+ catalogManager.alterCatalog(ident, change);+ Catalog catalog = catalogManager.loadCatalog(NameIdentifier.of(ident.namespace(), "test32"));+ Assertions.assertEquals("test32", catalog.name());++ // Test alter comment;+ NameIdentifier ident1 = NameIdentifier.of(ident.namespace(), "test32");+ CatalogChange change1 = CatalogChange.updateComment("comment1");+ catalogManager.alterCatalog(ident1, change1);+ Catalog catalog1 = catalogManager.loadCatalog(ident1);+ Assertions.assertEquals("comment1", catalog1.comment());++ // Test alter properties;+ CatalogChange change2 = CatalogChange.setProperty("key1", "value1");+ CatalogChange change3 = CatalogChange.setProperty("key2", "value2");+ CatalogChange change4 = CatalogChange.removeProperty("key2");++ catalogManager.alterCatalog(ident1, change2, change3, change4);+ Catalog catalog2 = catalogManager.loadCatalog(ident1);+ Map<String, String> expectedProps = ImmutableMap.of("provider", "test", "key1", "value1");+ Assertions.assertEquals(expectedProps, catalog2.properties());++ // Test Catalog does not exist+ NameIdentifier ident2 = NameIdentifier.of(ident.namespace(), "test33");+ CatalogChange change5 = CatalogChange.rename("test34");+ Throwable exception =+ Assertions.assertThrows(+ NoSuchCatalogException.class, () -> catalogManager.alterCatalog(ident2, change5));+ Assertions.assertTrue(+ exception.getMessage().contains("Catalog metalake.test33 does not exist"));++ // Alter operation will update the cache+ Assertions.assertNull(catalogManager.catalogCache.getIfPresent(ident));+ Assertions.assertNotNull(catalogManager.catalogCache.getIfPresent(ident1));+ }++ @Test+ public void testDropCatalog() {+ NameIdentifier ident = NameIdentifier.of("metalake", "test41");+ Map<String, String> props = ImmutableMap.of("provider", "test");+ String comment = "comment";++ catalogManager.createCatalog(ident, Catalog.Type.RELATIONAL, comment, props);++ // Test drop catalog+ boolean dropped = catalogManager.dropCatalog(ident);+ Assertions.assertTrue(dropped);++ // Test drop non-existed catalog+ NameIdentifier ident1 = NameIdentifier.of("metalake", "test42");+ boolean dropped1 = catalogManager.dropCatalog(ident1);+ Assertions.assertFalse(dropped1);++ // Drop operation will update the cache+ Assertions.assertNull(catalogManager.catalogCache.getIfPresent(ident));+ }+}diff --git a/core/src/test/java/com/datastrato/graviton/proto/TestEntityProtoSerDe.java b/core/src/test/java/com/datastrato/graviton/proto/TestEntityProtoSerDe.javaindex 59e058051c..29b5f7eaec 100644--- a/core/src/test/java/com/datastrato/graviton/proto/TestEntityProtoSerDe.java+++ b/core/src/test/java/com/datastrato/graviton/proto/TestEntityProtoSerDe.java@@ -71,7 +71,6 @@ public class TestEntityProtoSerDe {public void testEntitiesSerDe() throws IOException {Instant now = Instant.now();String creator = "creator";- Integer tenantId = 1;SchemaVersion version = SchemaVersion.V_0_1;Long metalakeId = 1L;String metalakeName = "metalake";@@ -126,5 +125,31 @@ public class TestEntityProtoSerDe {com.datastrato.graviton.meta.BaseMetalake metalakeFromBytes1 =entitySerDe.deserialize(metalakeBytes1, com.datastrato.graviton.meta.BaseMetalake.class);Assertions.assertEquals(metalake1, metalakeFromBytes1);++ // Test CatalogEntity+ Long catalogId = 1L;+ String catalogName = "catalog";+ String comment = "comment";++ com.datastrato.graviton.meta.CatalogEntity catalogEntity =+ new com.datastrato.graviton.meta.CatalogEntity.Builder()+ .withId(catalogId)+ .withMetalakeId(metalakeId)+ .withName(catalogName)+ .withComment(comment)+ .withType(com.datastrato.graviton.Catalog.Type.RELATIONAL)+ .withAuditInfo(auditInfo)+ .build();++ Catalog catalogProto = protoEntitySerDe.toProto(catalogEntity);+ com.datastrato.graviton.meta.CatalogEntity catalogEntityFromProto =+ protoEntitySerDe.fromProto(catalogProto);+ Assertions.assertEquals(catalogEntity, catalogEntityFromProto);++ byte[] catalogBytes = protoEntitySerDe.serialize(catalogEntity);+ com.datastrato.graviton.meta.CatalogEntity catalogEntityFromBytes =+ protoEntitySerDe.deserialize(+ catalogBytes, com.datastrato.graviton.meta.CatalogEntity.class);+ Assertions.assertEquals(catalogEntity, catalogEntityFromBytes);}}diff --git a/core/src/test/java/com/datastrato/graviton/storage/kv/TestEntityStorageBackend.java b/core/src/test/java/com/datastrato/graviton/storage/kv/TestEntityStorageBackend.javaindex 6d56c28f2b..4ef3f97163 100644--- a/core/src/test/java/com/datastrato/graviton/storage/kv/TestEntityStorageBackend.java+++ b/core/src/test/java/com/datastrato/graviton/storage/kv/TestEntityStorageBackend.java@@ -143,6 +143,23 @@ public class TestEntityStorageBackend {Assertions.assertThrows(NoSuchEntityException.class,() -> store.get(catalog.nameIdentifier(), CatalogEntity.class));++ // Test update+ BaseMetalake updatedMetalake =+ new BaseMetalake.Builder()+ .withId(metalake.getId())+ .withName("updatedMetalake")+ .withAuditInfo(auditInfo)+ .withVersion(SchemaVersion.V_0_1)+ .build();+ store.put(metalake.nameIdentifier(), metalake);+ store.update(metalake.nameIdentifier(), BaseMetalake.class, l -> updatedMetalake);+ Assertions.assertEquals(+ updatedMetalake, store.get(updatedMetalake.nameIdentifier(), BaseMetalake.class));+ Assertions.assertThrows(+ NoSuchEntityException.class,+ () -> store.get(metalake.nameIdentifier(), BaseMetalake.class));+} catch (Exception e) {Assertions.fail(e.getMessage());}diff --git a/core/src/test/resources/META-INF/services/com.datastrato.graviton.CatalogProvider b/core/src/test/resources/META-INF/services/com.datastrato.graviton.CatalogProvidernew file mode 100644index 0000000000..6485b5d5db--- /dev/null+++ b/core/src/test/resources/META-INF/services/com.datastrato.graviton.CatalogProvider@@ -0,0 +1,5 @@+#+# Copyright 2023 Datastrato.+# This software is licensed under the Apache License version 2.+#+com.datastrato.graviton.TestCatalog\ No newline at end of file