Skip to content

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

[#12403] fix(core): defer catalog wrapper cleanup with an operation lease (#12404)

Qi Yu157a6f650e75
diff --git a/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/integration/test/IcebergClassLoaderPoolIT.java b/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/integration/test/IcebergClassLoaderPoolIT.java
index b763087229..4d29d86e14 100644
--- a/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/integration/test/IcebergClassLoaderPoolIT.java
+++ b/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/integration/test/IcebergClassLoaderPoolIT.java
@@ -27,7 +27,6 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
-import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.gravitino.Catalog;
import org.apache.gravitino.GravitinoEnv;
import org.apache.gravitino.NameIdentifier;
@@ -151,15 +150,13 @@ public class IcebergClassLoaderPoolIT extends BaseIT {
return ITUtils.EMBEDDED_TEST_MODE.equals(testMode);
}
- private Object classLoaderOf(String metalake, String catalog) throws IllegalAccessException {
+ private Object classLoaderOf(String metalake, String catalog) {
CatalogManager catalogManager = GravitinoEnv.getInstance().catalogManager();
- // Use loadCatalogAndWrap (rather than the Caffeine cache directly) so this test module does not
- // need caffeine on its compile classpath. The catalog was already loaded server-side above, so
- // this returns the cached wrapper instance.
- CatalogManager.CatalogWrapper wrapper =
- catalogManager.loadCatalogAndWrap(NameIdentifier.of(metalake, catalog));
- Assertions.assertNotNull(wrapper, "wrapper should be cached for " + metalake + "." + catalog);
- return FieldUtils.readField(wrapper, "classLoader", true);
+ // doWithCatalog installs the pooled loader as the TCCL; the catalog class itself may be shared
+ // and therefore defined by the application ClassLoader.
+ return catalogManager.doWithCatalog(
+ NameIdentifier.of(metalake, catalog),
+ ignored -> Thread.currentThread().getContextClassLoader());
}
@Test
diff --git a/core/src/main/java/org/apache/gravitino/authorization/AuthorizationUtils.java b/core/src/main/java/org/apache/gravitino/authorization/AuthorizationUtils.java
index 34bfd3fe76..aa4875f3ff 100644
--- a/core/src/main/java/org/apache/gravitino/authorization/AuthorizationUtils.java
+++ b/core/src/main/java/org/apache/gravitino/authorization/AuthorizationUtils.java
@@ -23,7 +23,9 @@ import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.Collection;
+import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
@@ -40,7 +42,6 @@ import org.apache.gravitino.Schema;
import org.apache.gravitino.catalog.CatalogManager;
import org.apache.gravitino.catalog.FilesetDispatcher;
import org.apache.gravitino.catalog.hive.HiveConstants;
-import org.apache.gravitino.connector.BaseCatalog;
import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
import org.apache.gravitino.dto.authorization.PrivilegeDTO;
import org.apache.gravitino.dto.util.DTOConverters;
@@ -208,20 +209,16 @@ public class AuthorizationUtils {
for (SecurableObject securableObject : securableObjects) {
if (needApplyAuthorizationPluginAllCatalogs(securableObject)) {
NameIdentifier[] catalogs = catalogManager.listCatalogs(Namespace.of(metalake));
- // ListCatalogsInfo return `CatalogInfo` instead of `BaseCatalog`, we need `BaseCatalog` to
- // call authorization plugin method.
for (NameIdentifier catalog : catalogs) {
- callAuthorizationPluginImpl(consumer, catalogManager.loadCatalog(catalog));
+ callAuthorizationPluginImpl(consumer, catalogManager, catalog);
}
} else if (needApplyAuthorization(securableObject.type())) {
NameIdentifier catalogIdent =
NameIdentifierUtil.getCatalogIdentifier(
MetadataObjectUtil.toEntityIdent(metalake, securableObject));
- Catalog catalog = catalogManager.loadCatalog(catalogIdent);
- if (!catalogsAlreadySet.contains(catalog.name())) {
- catalogsAlreadySet.add(catalog.name());
- callAuthorizationPluginImpl(consumer, catalog);
+ if (catalogsAlreadySet.add(catalogIdent.name())) {
+ callAuthorizationPluginImpl(consumer, catalogManager, catalogIdent);
}
}
}
@@ -229,9 +226,10 @@ public class AuthorizationUtils {
public static void callAuthorizationPluginForMetadataObject(
String metalake, MetadataObject metadataObject, Consumer<AuthorizationPlugin> consumer) {
- List<Catalog> loadedCatalogs = loadMetadataObjectCatalog(metalake, metadataObject);
- for (Catalog catalog : loadedCatalogs) {
- callAuthorizationPluginImpl(consumer, catalog);
+ CatalogManager catalogManager = GravitinoEnv.getInstance().catalogManager();
+ List<NameIdentifier> catalogIdents = getMetadataObjectCatalogs(metalake, metadataObject);
+ for (NameIdentifier catalogIdent : catalogIdents) {
+ callAuthorizationPluginImpl(consumer, catalogManager, catalogIdent);
}
}
@@ -346,18 +344,19 @@ public class AuthorizationUtils {
}
}
- public static void removeCatalogPrivileges(Catalog catalog, List<String> locations) {
+ public static void removeCatalogPrivileges(NameIdentifier catalogIdent, List<String> locations) {
// If we enable authorization, we should remove the privileges about the entity in the
// authorization plugin.
MetadataObject metadataObject =
- MetadataObjects.of(null, catalog.name(), MetadataObject.Type.CATALOG);
+ MetadataObjects.of(null, catalogIdent.name(), MetadataObject.Type.CATALOG);
MetadataObjectChange removeObject = MetadataObjectChange.remove(metadataObject, locations);
callAuthorizationPluginImpl(
authorizationPlugin -> {
authorizationPlugin.onMetadataUpdated(removeObject);
},
- catalog);
+ GravitinoEnv.getInstance().catalogManager(),
+ catalogIdent);
}
public static void authorizationPluginRenamePrivileges(
@@ -450,35 +449,28 @@ public class AuthorizationUtils {
}
private static void callAuthorizationPluginImpl(
- BiConsumer<AuthorizationPlugin, String> consumer, Catalog catalog) {
-
- if (catalog instanceof BaseCatalog) {
- BaseCatalog baseCatalog = (BaseCatalog) catalog;
- if (baseCatalog.getAuthorizationPlugin() != null) {
- consumer.accept(baseCatalog.getAuthorizationPlugin(), catalog.name());
- }
- } else {
- throw new IllegalArgumentException(
- String.format(
- "Catalog %s is not a BaseCatalog, we don't support authorization plugin for it",
- catalog.type()));
- }
+ BiConsumer<AuthorizationPlugin, String> consumer,
+ CatalogManager catalogManager,
+ NameIdentifier catalogIdent) {
+ catalogManager.doWithCatalog(
+ catalogIdent,
+ catalog -> {
+ AuthorizationPlugin authorizationPlugin = catalog.getAuthorizationPlugin();
+ if (authorizationPlugin != null) {
+ consumer.accept(authorizationPlugin, catalog.name());
+ }
+ return null;
+ });
}
private static void callAuthorizationPluginImpl(
- Consumer<AuthorizationPlugin> consumer, Catalog catalog) {
-
- if (catalog instanceof BaseCatalog) {
- BaseCatalog baseCatalog = (BaseCatalog) catalog;
- if (baseCatalog.getAuthorizationPlugin() != null) {
- consumer.accept(baseCatalog.getAuthorizationPlugin());
- }
- } else {
- throw new IllegalArgumentException(
- String.format(
- "Catalog %s is not a BaseCatalog, we don't support authorization plugin for it",
- catalog.type()));
- }
+ Consumer<AuthorizationPlugin> consumer,
+ CatalogManager catalogManager,
+ NameIdentifier catalogIdent) {
+ callAuthorizationPluginImpl(
+ (authorizationPlugin, catalogName) -> consumer.accept(authorizationPlugin),
+ catalogManager,
+ catalogIdent);
}
private static void checkCatalogType(
@@ -492,26 +484,20 @@ public class AuthorizationUtils {
}
}
- private static List<Catalog> loadMetadataObjectCatalog(
+ private static List<NameIdentifier> getMetadataObjectCatalogs(
String metalake, MetadataObject metadataObject) {
CatalogManager catalogManager = GravitinoEnv.getInstance().catalogManager();
- List<Catalog> loadedCatalogs = Lists.newArrayList();
if (needApplyAuthorizationPluginAllCatalogs(metadataObject.type())) {
- NameIdentifier[] catalogs = catalogManager.listCatalogs(Namespace.of(metalake));
- // ListCatalogsInfo return `CatalogInfo` instead of `BaseCatalog`, we need `BaseCatalog` to
- // call authorization plugin method.
- for (NameIdentifier catalog : catalogs) {
- loadedCatalogs.add(catalogManager.loadCatalog(catalog));
- }
- } else if (needApplyAuthorization(metadataObject.type())) {
- NameIdentifier catalogIdent =
+ return Arrays.asList(catalogManager.listCatalogs(Namespace.of(metalake)));
+ }
+
+ if (needApplyAuthorization(metadataObject.type())) {
+ return Collections.singletonList(
NameIdentifierUtil.getCatalogIdentifier(
- MetadataObjectUtil.toEntityIdent(metalake, metadataObject));
- Catalog catalog = catalogManager.loadCatalog(catalogIdent);
- loadedCatalogs.add(catalog);
+ MetadataObjectUtil.toEntityIdent(metalake, metadataObject)));
}
- return loadedCatalogs;
+ return Collections.emptyList();
}
// The Hive default schema location is Hive warehouse directory
diff --git a/core/src/main/java/org/apache/gravitino/catalog/CapabilityHelpers.java b/core/src/main/java/org/apache/gravitino/catalog/CapabilityHelpers.java
index 7e5f77c777..adc39cc62a 100644
--- a/core/src/main/java/org/apache/gravitino/catalog/CapabilityHelpers.java
+++ b/core/src/main/java/org/apache/gravitino/catalog/CapabilityHelpers.java
@@ -27,6 +27,7 @@ import java.util.Arrays;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
import org.apache.gravitino.connector.capability.Capability;
+import org.apache.gravitino.exceptions.NoSuchCatalogException;
import org.apache.gravitino.file.FilesetChange;
import org.apache.gravitino.rel.Column;
import org.apache.gravitino.rel.TableChange;
@@ -52,10 +53,11 @@ public class CapabilityHelpers {
public static Capability getCapability(NameIdentifier ident, CatalogManager catalogManager) {
NameIdentifier catalogIdent = getCatalogIdentifier(ident);
- CatalogManager.CatalogWrapper c = catalogManager.loadCatalogAndWrap(catalogIdent);
try {
- return c.capabilities();
- } catch (Exception e) {
+ return catalogManager.doWithCatalog(catalogIdent, catalog -> catalog.capability());
+ } catch (NoSuchCatalogException e) {
+ throw e;
+ } catch (RuntimeException e) {
throw new RuntimeException("Failed to get capabilities for catalog: " + catalogIdent, e);
}
}
diff --git a/core/src/main/java/org/apache/gravitino/catalog/CatalogChangeLogListener.java b/core/src/main/java/org/apache/gravitino/catalog/CatalogChangeLogListener.java
index 38d9807a0e..e68e95e75c 100644
--- a/core/src/main/java/org/apache/gravitino/catalog/CatalogChangeLogListener.java
+++ b/core/src/main/java/org/apache/gravitino/catalog/CatalogChangeLogListener.java
@@ -49,14 +49,13 @@ import org.slf4j.LoggerFactory;
* local one. If the clear itself fails, the exception goes up to the poller, which logs it at
* {@code ERROR} and moves on, and the catalog stays stale until it expires.
*
- * <p><b>What clearing costs:</b> dropping a catalog from the cache closes its {@code
- * CatalogWrapper}, which shuts down its connection pool and its {@code IsolatedClassLoader}.
- * Clearing the whole cache therefore also closes catalogs this process is serving right now, and
- * requests still using classes from a closed classloader can fail with {@code NoClassDefFoundError}
- * (that is the bug in #11739). We accept this on purpose so a changed catalog is never served from
- * a stale cache; without it, this node would keep serving the old catalog for up to {@code
- * gravitino.catalog.cache.evictionIntervalMs}. The clear only happens when a normal removal failed,
- * never during normal operation.
+ * <p><b>What clearing costs:</b> dropping a catalog from the cache retires its {@code
+ * CatalogWrapper}. Idle wrappers release their connection pools and {@code IsolatedClassLoader}s
+ * immediately; wrappers with an active operation lease defer cleanup until their last lease is
+ * closed, so an operation is never torn down mid-flight. Connector-backed metadata returned by an
+ * operation is converted to a detached snapshot before the lease closes; later hooks and REST
+ * serialization therefore do not depend on the retired wrapper. The clear only happens when a
+ * normal removal failed, never during normal operation.
*/
public class CatalogChangeLogListener implements EntityChangeLogListener {
@@ -119,9 +118,9 @@ public class CatalogChangeLogListener implements EntityChangeLogListener {
for (CatalogInvalidation invalidation : remoteInvalidations) {
EntityChangeRecord change = invalidation.change;
NameIdentifier ident = invalidation.ident;
- // INFO on purpose: dropping the catalog from the cache also closes its connection pool and
- // its isolated classloader, and this is the main thing the change log does across nodes.
- // CatalogManager prints the matching "Closing catalog" line when the removal happens.
+ // INFO on purpose: dropping the catalog from the cache retires its wrapper and eventually
+ // closes the connection pool and isolated classloader, either immediately or after active
+ // leases finish. This is the main thing the change log does across nodes.
LOG.info(
"Invalidating catalog cache for {} due to a remote {} recorded in change log id {}",
ident,
@@ -132,11 +131,11 @@ public class CatalogChangeLogListener implements EntityChangeLogListener {
catalogManager.getCatalogCache().invalidate(ident);
} catch (RuntimeException e) {
// This batch will never be sent again, so giving up here would keep serving the old
- // catalog until it expires on its own. Clear the whole cache instead; see the class
- // javadoc for the classloader cost that comes with it.
+ // catalog until it expires on its own. Clear the whole cache instead; active operation
+ // leases defer resource cleanup until those operations finish.
LOG.error(
"Failed to evict catalog {} for change log id {}, clearing the whole catalog cache to "
- + "avoid serving it stale; catalogs in use by this node are closed as a result",
+ + "avoid serving it stale; resources in use are retired after their leases close",
ident,
change.getId(),
e);
diff --git a/core/src/main/java/org/apache/gravitino/catalog/CatalogLease.java b/core/src/main/java/org/apache/gravitino/catalog/CatalogLease.java
new file mode 100644
index 0000000000..ff86ec7640
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/catalog/CatalogLease.java
@@ -0,0 +1,71 @@
+/*
+ * 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;
+
+import java.util.concurrent.atomic.AtomicBoolean;
+import org.apache.gravitino.catalog.CatalogManager.CatalogWrapper;
+import org.apache.gravitino.connector.BaseCatalog;
+import org.apache.gravitino.utils.IsolatedClassLoader;
+
+/**
+ * A lease on a {@link CatalogWrapper} held for the duration of one catalog operation.
+ *
+ * <p>While the lease is held, the wrapper's catalog instance and its {@link IsolatedClassLoader}
+ * stay alive even if the catalog cache evicts the wrapper concurrently (expiry, explicit
+ * invalidation, or remote change-log invalidation). The resources are released once the wrapper is
+ * retired and its last lease is closed, so an operation can never observe a half-closed catalog.
+ *
+ * <p>Lease acquisition and release stay internal to {@link CatalogManager}. Dispatchers use the
+ * manager's callback API so connector-backed results can be detached before the lease closes.
+ */
+final class CatalogLease implements AutoCloseable {
+
+ private final CatalogWrapper wrapper;
+ private final AtomicBoolean released = new AtomicBoolean(false);
+
+ CatalogLease(CatalogWrapper wrapper) {
+ this.wrapper = wrapper;
+ }
+
+ /**
+ * Returns the leased catalog wrapper.
+ *
+ * @return the leased catalog wrapper, guaranteed to stay usable until this lease is closed.
+ */
+ CatalogWrapper wrapper() {
+ return wrapper;
+ }
+
+ /**
+ * Returns the catalog of the leased wrapper.
+ *
+ * @return the leased catalog, guaranteed to stay usable until this lease is closed.
+ */
+ BaseCatalog catalog() {
+ return wrapper.catalog();
+ }
+
+ /** Releases the lease. Closing an already closed lease is a no-op. */
+ @Override
+ public void close() {
+ if (released.compareAndSet(false, true)) {
+ wrapper.release();
+ }
+ }
+}
diff --git a/core/src/main/java/org/apache/gravitino/catalog/CatalogManager.java b/core/src/main/java/org/apache/gravitino/catalog/CatalogManager.java
index c3ca9701c9..2a23d7e0fa 100644
--- a/core/src/main/java/org/apache/gravitino/catalog/CatalogManager.java
+++ b/core/src/main/java/org/apache/gravitino/catalog/CatalogManager.java
@@ -57,7 +57,10 @@ import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Consumer;
+import java.util.function.Supplier;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import lombok.Getter;
@@ -165,18 +168,46 @@ public class CatalogManager implements CatalogDispatcher, Closeable {
"uri",
"fs.defaultFS");
- /** Wrapper class for a catalog instance and its class loader. */
+ /**
+ * Wrapper class for a catalog instance and its class loader.
+ *
+ * <p>A wrapper is shared by all threads that read it from the catalog cache, while cache eviction
+ * (expiry, explicit invalidation, or remote change-log invalidation) happens outside the tree
+ * lock. To keep an eviction from tearing down a catalog that an in-flight operation is still
+ * using, the wrapper counts active operations: {@link #tryAcquire()} takes a lease, {@link
+ * #release()} returns it, and {@link #retire()} (called from the cache removal listener) only
+ * marks the wrapper unusable for new leases. The catalog and the ClassLoader are cleaned up
+ * exactly once, when the wrapper is retired and the last lease has been released.
+ */
public static class CatalogWrapper {
- private BaseCatalog catalog;
- private IsolatedClassLoader classLoader;
- private ClassLoaderPool pool;
- private PooledClassLoaderEntry poolEntry;
- private boolean closed = false;
+ // Volatile because cleanup() nulls it outside leaseLock (holding the lock across a catalog
+ // close would stall tryAcquire), while unleased readers such as callers of
+ // loadCatalogAndWrap() may read it from another thread. Leased readers cannot race with
+ // cleanup at all: cleanup is only claimed once the wrapper is retired and no lease is held.
+ private volatile BaseCatalog catalog;
+
+ private final IsolatedClassLoader classLoader;
+ private final ClassLoaderPool pool;
+ private final PooledClassLoaderEntry poolEntry;
+
+ /** Guards {@link #activeOps}, {@link #retired} and {@link #cleanupStarted}. */
+ private final Object leaseLock = new Object();
+
+ /** Number of leases currently held by in-flight operations. */
+ private int activeOps = 0;
+
+ /** Set when the wrapper leaves the cache; no new lease can be acquired afterwards. */
+ private boolean retired = false;
+
+ /** Set by the thread that claims the (exactly-once) resource cleanup. */
+ private boolean cleanupStarted = false;
/** Non-pooled constructor: each catalog owns its ClassLoader exclusively. */
CatalogWrapper(IsolatedClassLoader classLoader) {
this.classLoader = classLoader;
+ this.pool = null;
+ this.poolEntry = null;
}
/** Pooled constructor: ClassLoader is managed by the pool with reference counting. */
@@ -191,6 +222,79 @@ public class CatalogManager implements CatalogDispatcher, Closeable {
return catalog;
}
+ /**
+ * Tries to take a lease on this wrapper, keeping its catalog and ClassLoader alive until the
+ * lease is released.
+ *
+ * @return true if the lease was taken, false if the wrapper has already been retired and the
+ * caller must load a fresh wrapper.
+ */
+ boolean tryAcquire() {
+ synchronized (leaseLock) {
+ if (retired) {
+ return false;
+ }
+ activeOps++;
+ return true;
+ }
+ }
+
+ /**
+ * Releases a lease taken by {@link #tryAcquire()}. Cleans up the catalog and the ClassLoader if
+ * this was the last lease on an already retired wrapper.
+ *
+ * <p>Note that in that case the cleanup runs on the releasing thread, which is usually a
+ * request thread, so a slow catalog close is charged to that request. This only happens when
+ * the wrapper was evicted while the operation was in flight; the common case is that eviction
+ * finds no lease and cleans up on the cache's own thread.
+ */
+ void release() {
+ boolean shouldCleanup;
+ synchronized (leaseLock) {
+ Preconditions.checkState(activeOps > 0, "Releasing a lease that was never acquired");
+ activeOps--;
+ shouldCleanup = claimCleanupIfIdle();
+ }
+
+ if (shouldCleanup) {
+ cleanup();
+ }
+ }
+
+ /**
+ * Retires this wrapper: no new lease can be taken. The catalog and the ClassLoader are cleaned
+ * up immediately if no operation is in flight, otherwise by the last {@link #release()}.
+ */
+ void retire() {
+ boolean shouldCleanup;
+ synchronized (leaseLock) {
+ retired = true;
+ shouldCleanup = claimCleanupIfIdle();
+ }
+
+ if (shouldCleanup) {
+ cleanup();
+ }
+ }
+
+ /**
+ * Returns whether this wrapper has been retired and can no longer serve new operations.
+ *
+ * @return true if the wrapper has been retired.
+ */
+ boolean isRetired() {
+ synchronized (leaseLock) {
+ return retired;
+ }
+ }
+
+ @VisibleForTesting
+ int activeOperations() {
+ synchronized (leaseLock) {
+ return activeOps;
+ }
+ }
+
public <R> R doWithSchemaOps(ThrowableFunction<SupportsSchemas, R> fn) throws Exception {
return classLoader.withClassLoader(
cl -> {
@@ -243,10 +347,34 @@ public class CatalogManager implements CatalogDispatcher, Closeable {
});
}
- public <R> R doWithCredentialOps(ThrowableFunction<BaseCatalog, R> fn) throws Exception {
+ /**
+ * Runs an operation against the catalog instance itself, with the catalog's ClassLoader in
+ * place for the duration of the call.
+ */
+ public <R> R doWithCatalog(ThrowableFunction<BaseCatalog, R> fn) throws Exception {
return classLoader.withClassLoader(cl -> fn.apply(catalog));
}
+ public <R> R doWithCredentialOps(ThrowableFunction<BaseCatalog, R> fn) throws Exception {
+ return doWithCatalog(fn);
+ }
+
+ /**
+ * Converts a connector-backed result into a snapshot that no longer depends on this catalog's
+ * ClassLoader, reading the connector object with that ClassLoader installed.
+ *
+ * <p>Scoped to the conversion alone: the caller's surrounding work is Gravitino's own code and
+ * must keep the application ClassLoader as its thread context ClassLoader.
+ *
+ * @param result the value returned by a connector operation
+ * @param <R> the result type
+ * @return a detached snapshot, or the value itself if it carries no connector state
+ * @throws Exception if reading the connector object fails
+ */
+ <R> R detachConnectorResult(R result) throws Exception {
+ return classLoader.withClassLoader(ignored -> ConnectorObjectSnapshot.detach(result));
+ }
+
public <R> R doWithTopicOps(ThrowableFunction<TopicCatalog, R> fn) throws Exception {
return classLoader.withClassLoader(
cl -> {
@@ -287,27 +415,50 @@ public class CatalogManager implements CatalogDispatcher, Closeable {
public <R> R doWithPropertiesMeta(ThrowableFunction<HasPropertyMetadata, R> fn)
throws Exception {
- return classLoader.withClassLoader(cl -> fn.apply(catalog));
+ return doWithCatalog(fn::apply);
}
public Capability capabilities() throws Exception {
return classLoader.withClassLoader(cl -> catalog.capability());
}
- public synchronized void close() {
- if (closed) {
- // Idempotent: a second close() must not re-run pool release or classloader cleanup.
- return;
+ /**
+ * Retires the wrapper and, once no operation is in flight anymore, releases its resources. Kept
+ * as an alias of {@link #retire()} so callers that own a wrapper exclusively (for example
+ * {@link CatalogManager#testConnection}) can keep using the {@link java.io.Closeable}-style
+ * API.
+ */
+ public void close() {
+ retire();
+ }
+
+ /**
+ * Claims the exactly-once resource cleanup when the wrapper is retired and idle. Must be called
+ * while holding {@link #leaseLock}; the caller runs {@link #cleanup()} outside the lock so a
+ * slow catalog close does not block {@link #tryAcquire()}.
+ */
+ private boolean claimCleanupIfIdle() {
+ if (!retired || activeOps > 0 || cleanupStarted) {
+ return false;
}
- closed = true;
+ cleanupStarted = true;
+ return true;
+ }
+
+ private void cleanup() {
+ // Drop the reference before closing so a failing close() cannot leave a half-closed catalog
+ // reachable: cleanup() runs exactly once, so a null assignment after close() would be skipped
+ // on that path. Unleased readers then see null and fail fast instead of using a closed
+ // catalog; leased readers cannot race with cleanup at all.
+ BaseCatalog toClose = catalog;
+ catalog = null;
try {
classLoader.withClassLoader(
cl -> {
- if (catalog != null) {
- catalog.close();
+ if (toClose != null) {
+ toClose.close();
}
- catalog = null;
return null;
});
} catch (Exception e) {
@@ -315,10 +466,9 @@ public class CatalogManager implements CatalogDispatcher, Closeable {
} finally {
// Release the pool reference (or clean up the dedicated ClassLoader) in a finally so a
// failure while closing the catalog cannot permanently leak the pooled ClassLoader
- // reference (close() is idempotent, so a retry would otherwise skip this).
+ // reference (cleanup() runs exactly once, so a retry would otherwise skip this).
if (poolEntry != null) {
pool.release(poolEntry);
- poolEntry = null;
} else if (pool == null) {
// Non-pooled path (e.g., sharing disabled or CATALOG_LOAD_ISOLATED=false)
ClassLoaderPool.cleanupClassLoader(classLoader);
@@ -377,6 +527,14 @@ public class CatalogManager implements CatalogDispatcher, Closeable {
private final ConcurrentHashMap<NameIdentifier, AtomicInteger> localMutationCounts =
new ConcurrentHashMap<>();
+ // Cache loads and publications take the read lock; close() takes the write lock. Operations do
+ // not hold this lock after acquiring a CatalogLease because the lease itself keeps the wrapper
+ // alive while close() retires it.
+ private final ReentrantReadWriteLock lifecycleLock = new ReentrantReadWriteLock();
+
+ /** Guarded by {@link #lifecycleLock}. */
+ private boolean closed;
+
// Set to true when a CatalogChangeLogListener is active. markLocalMutation() is a no-op
// unless this flag is set, preventing unbounded growth of localMutationCounts in deployments
// that do not use a relational entity store (where the poller never runs).
@@ -405,12 +563,19 @@ public class CatalogManager implements CatalogDispatcher, Closeable {
.removalListener(
(k, v, c) -> {
LOG.debug("Removed catalog cache entry, identifier={}, cause={}", k, c);
- for (Consumer<NameIdentifier> listener : removalListeners) {
- if (k != null) {
- listener.accept((NameIdentifier) k);
+ try {
+ for (Consumer<NameIdentifier> listener : removalListeners) {
+ if (k != null) {
+ listener.accept((NameIdentifier) k);
+ }
}
+ } finally {
+ // Retire rather than close: an operation that already leased this wrapper
+ // keeps it alive, and the actual catalog/ClassLoader cleanup runs when the
+ // last lease is released. Keep this in finally so a faulty external listener
+ // cannot skip resource cleanup.
+ ((CatalogWrapper) v).retire();
}
- ((CatalogWrapper) v).close();
})
.scheduler(
Scheduler.forScheduledExecutorService(
@@ -439,18 +604,63 @@ public class CatalogManager implements CatalogDispatcher, Closeable {
}
/**
- * Closes the CatalogManager and releases any resources associated with it. This method
- * invalidates all cached catalog instances and clears the cache.
+ * Closes the CatalogManager and invalidates all cached catalog instances. Idle resources are
+ * released immediately; resources protected by active leases are released when their last lease
+ * is closed.
*/
@Override
public void close() {
+ lifecycleLock.writeLock().lock();
+ try {
+ if (closed) {
+ return;
+ }
+
+ // Holding the write lock prevents new cache loads and publications until shutdown has
+ // finished. Existing operations only hold CatalogLeases, so retiring their wrappers here is
+ // non-blocking and their cleanup remains deferred until the last lease is released.
+ unregisterChangeLogListener();
+ retireCachedWrappers();
+ classLoaderPool.closeWhenIdle();
+ closed = true;
+ } finally {
+ lifecycleLock.writeLock().unlock();
+ }
+ }
+
+ private void unregisterChangeLogListener() {
if (catalogChangeLogListener != null) {
- ((SupportsEntityChangeLog) store).unregisterEntityChangeLogListener(catalogChangeLogListener);
- trackLocalMutations = false;
- localMutationCounts.clear();
+ try {
+ ((SupportsEntityChangeLog) store)
+ .unregisterEntityChangeLogListener(catalogChangeLogListener);
+ } catch (RuntimeException e) {
+ LOG.warn("Failed to unregister the catalog change-log listener", e);
+ } finally {
+ trackLocalMutations = false;
+ localMutationCounts.clear();
+ }
}
+ }
+
+ /**
+ * Retires every wrapper still cached, so their resources are released as soon as the operations
+ * holding them finish. The cache's removal listener is asynchronous, so the wrappers are retired
+ * here synchronously; active leases defer the cleanup and keep their pooled ClassLoader reference
+ * alive until the last operation releases it.
+ *
+ * <p>The caller holds {@link #lifecycleLock}'s write lock, so no wrapper can be loaded or
+ * published while the snapshot is taken.
+ */
+ private void retireCachedWrappers() {
+ List<CatalogWrapper> wrappers = new ArrayList<>(catalogCache.asMap().values());
catalogCache.invalidateAll();
- classLoaderPool.close();
+ for (CatalogWrapper wrapper : wrappers) {
+ try {
+ wrapper.retire();
+ } catch (RuntimeException e) {
+ LOG.warn("Failed to retire a cached catalog wrapper while closing the CatalogManager", e);
+ }
+ }
}
/**
@@ -569,7 +779,7 @@ public class CatalogManager implements CatalogDispatcher, Closeable {
* Loads the catalog with the specified identifier.
*
* @param ident The identifier of the catalog to load.
- * @return The loaded catalog.
+ * @return A metadata snapshot of the loaded catalog. Connector resources are not exposed.
* @throws NoSuchCatalogException If the specified catalog does not exist.
*/
@Override
@@ -578,12 +788,61 @@ public class CatalogManager implements CatalogDispatcher, Closeable {
ident,
LockType.READ,
() -> {
- BaseCatalog baseCatalog = loadCatalogAndWrap(ident).catalog();
- baseCatalog.checkMetalakeInUse();
- return baseCatalog;
+ try (CatalogLease lease = acquireCatalogLease(ident)) {
+ BaseCatalog baseCatalog = lease.catalog();
+ baseCatalog.checkMetalakeInUse();
+ return toCatalogInfo(lease.wrapper());
+ }
});
}
+ /**
+ * Runs an operation against a catalog while keeping its catalog instance and ClassLoader alive.
+ *
+ * <p>Callers that need connector-only state, such as the authorization plugin or raw catalog
+ * properties, must use this method instead of casting the metadata snapshot returned by {@link
+ * #loadCatalog(NameIdentifier)}.
+ *
+ * <p><b>Note:</b> The callback must not retain the live catalog. Connector-backed metadata should
+ * be converted to a detached value before the callback returns.
+ *
+ * @param ident The identifier of the catalog to use.
+ * @param operation The operation to run against the live catalog instance.
+ * @return The value returned by the operation.
+ * @param <R> The result type of the operation.
+ * @throws NoSuchCatalogException If the specified catalog does not exist.
+ */
+ public <R> R doWithCatalog(NameIdentifier ident, ThrowableFunction<BaseCatalog, R> operation)
+ throws NoSuchCatalogException {
+ try {
+ // wrapper.doWithCatalog installs the catalog ClassLoader: the operation runs against the
+ // connector's own catalog instance, for example to call its authorization plugin.
+ return doWithCatalogWrapper(ident, wrapper -> wrapper.doWithCatalog(operation));
+ } catch (RuntimeException e) {
+ throw e;
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to operate on catalog: " + ident, e);
+ }
+ }
+
+ /**
+ * Runs a callback with one leased wrapper and the catalog ClassLoader installed as the thread
+ * context ClassLoader. The lease is deliberately kept inside CatalogManager so callers cannot
+ * release it before they have detached connector-backed results.
+ */
+ <R> R doWithCatalogWrapper(NameIdentifier ident, ThrowableFunction<CatalogWrapper, R> operation)
+ throws Exception {
+ try (CatalogLease lease = acquireCatalogLease(ident)) {
+ // Deliberately no ClassLoader swap around the whole callback. The wrapper's doWithXxxOps,
+ // doWithPropertiesMeta and capabilities() already install the catalog ClassLoader for the
+ // connector calls that need it, while the rest of the callback is Gravitino's own code:
+ // entity-store reads in particular must not run with a connector ClassLoader as the thread
+ // context ClassLoader, because MyBatis resolves resources and drivers through it and a
+ // catalog that bundles its own JDBC driver would win those lookups.
+ return operation.apply(lease.wrapper());
+ }
+ }
+
/**
* Creates a new catalog with the provided details.
*
@@ -592,7 +851,7 @@ public class CatalogManager implements CatalogDispatcher, Closeable {
* @param provider The provider of the new catalog.
* @param comment The comment for the new catalog.
* @param properties The properties of the new catalog.
- * @return The created catalog.
+ * @return A metadata snapshot of the created catalog.
* @throws NoSuchMetalakeException If the specified metalake does not exist.
* @throws CatalogAlreadyExistsException If a catalog with the same identifier already exists.
*/
@@ -674,9 +933,10 @@ public class CatalogManager implements CatalogDispatcher, Closeable {
throw new CatalogAlreadyExistsException("Catalog %s already exists", ident);
}
entityStored = true;
- CatalogWrapper wrapper =
- catalogCache.get(ident, id -> createCatalogWrapper(e, mergedConfig));
- return wrapper.catalog;
+ try (CatalogLease lease =
+ createAndCacheCatalogLease(ident, () -> createCatalogWrapper(e, mergedConfig))) {
+ return toCatalogInfo(lease.wrapper());
+ }
} catch (RuntimeException re) {
rollbackFailedCatalogCreate(ident, secretMaterials, entityStored);
@@ -768,14 +1028,15 @@ public class CatalogManager implements CatalogDispatcher, Closeable {
ident,
LockType.READ,
() -> {
- CatalogWrapper wrapper = loadCatalogAndWrap(ident);
- wrapper.catalog().checkMetalakeAndCatalogInUse();
- try {
- wrapper.doWithCatalogOps(
- c -> {
- c.testConnection(ident);
- return null;
- });
+ try (CatalogLease lease = acquireCatalogLease(ident)) {
+ lease.catalog().checkMetalakeAndCatalogInUse();
+ lease
+ .wrapper()
+ .doWithCatalogOps(
+ c -> {
+ c.testConnection(ident);
+ return null;
+ });
} catch (UnsupportedOperationException e) {
throw e;
} catch (Exception e) {
@@ -807,10 +1068,10 @@ public class CatalogManager implements CatalogDispatcher, Closeable {
ident,
LockType.READ,
() -> {
- CatalogWrapper storedWrapper = loadCatalogAndWrap(ident);
- BaseCatalog<?> storedCatalog = storedWrapper.catalog();
- storedCatalog.checkMetalakeAndCatalogInUse();
- try {
+ try (CatalogLease storedLease = acquireCatalogLease(ident)) {
+ CatalogWrapper storedWrapper = storedLease.wrapper();
+ BaseCatalog<?> storedCatalog = storedLease.catalog();
+ storedCatalog.checkMetalakeAndCatalogInUse();
storedWrapper.doWithPropertiesMeta(
metadata -> {
Pair<Map<String, String>, Map<String, String>> alterProperty =
@@ -871,14 +1132,14 @@ public class CatalogManager implements CatalogDispatcher, Closeable {
metalakeIdent,
LockType.WRITE,
() -> {
- BaseCatalog baseCatalog = loadCatalogAndWrap(ident).catalog();
- baseCatalog.checkMetalakeInUse();
+ try (CatalogLease lease = acquireCatalogLease(ident)) {
+ BaseCatalog baseCatalog = lease.catalog();
+ baseCatalog.checkMetalakeInUse();
- if (baseCatalog.catalogInUse()) {
- return null;
- }
+ if (baseCatalog.catalogInUse()) {
+ return null;
+ }
- try {
store.update(
ident,
CatalogEntity.class,
@@ -912,14 +1173,14 @@ public class CatalogManager implements CatalogDispatcher, Closeable {
metalakeIdent,
LockType.WRITE,
() -> {
- BaseCatalog baseCatalog = loadCatalogAndWrap(ident).catalog();
- baseCatalog.checkMetalakeInUse();
+ try (CatalogLease lease = acquireCatalogLease(ident)) {
+ BaseCatalog baseCatalog = lease.catalog();
+ baseCatalog.checkMetalakeInUse();
- if (!baseCatalog.catalogInUse()) {
- return null;
- }
+ if (!baseCatalog.catalogInUse()) {
+ return null;
+ }
- try {
store.update(
ident,
CatalogEntity.class,
@@ -951,7 +1212,7 @@ public class CatalogManager implements CatalogDispatcher, Closeable {
*
* @param ident The identifier of the catalog to alter.
* @param changes The changes to apply to the catalog.
- * @return The altered catalog.
+ * @return A metadata snapshot of the altered catalog.
* @throws NoSuchCatalogException If the specified catalog does not exist.
* @throws IllegalArgumentException If an unsupported catalog change is provided.
*/
@@ -964,31 +1225,30 @@ public class CatalogManager implements CatalogDispatcher, Closeable {
LockType.READ,
() -> {
// There could be a race issue that someone is using the catalog from cache while we are
- // updating it.
- CatalogWrapper catalogWrapper = loadCatalogAndWrap(ident);
- if (catalogWrapper == null) {
- throw new NoSuchCatalogException(CATALOG_DOES_NOT_EXIST_MSG, ident);
- }
-
- BaseCatalog catalog = catalogWrapper.catalog();
- catalog.checkMetalakeAndCatalogInUse();
+ // updating it. The lease keeps the wrapper alive for the whole validation.
+ try (CatalogLease lease = acquireCatalogLease(ident)) {
+ BaseCatalog catalog = lease.catalog();
+ catalog.checkMetalakeAndCatalogInUse();
- try {
- catalogWrapper.doWithPropertiesMeta(
- f -> {
- Pair<Map<String, String>, Map<String, String>> alterProperty =
- getCatalogAlterProperty(changes);
- validatePropertyForAlter(
- f.catalogPropertiesMetadata(),
- alterProperty.getLeft(),
- alterProperty.getRight());
- return null;
- });
- } catch (IllegalArgumentException e1) {
- throw e1;
- } catch (Exception e) {
- LOG.error("Failed to alter catalog {}", ident, e);
- throw new RuntimeException(e);
+ try {
+ lease
+ .wrapper()
+ .doWithPropertiesMeta(
+ f -> {
+ Pair<Map<String, String>, Map<String, String>> alterProperty =
+ getCatalogAlterProperty(changes);
+ validatePropertyForAlter(
+ f.catalogPropertiesMetadata(),
+ alterProperty.getLeft(),
+ alterProperty.getRight());
+ return null;
+ });
+ } catch (IllegalArgumentException e1) {
+ throw e1;
+ } catch (Exception e) {
+ LOG.error("Failed to alter catalog {}", ident, e);
+ throw new RuntimeException(e);
+ }
}
return null;
});
@@ -1002,7 +1262,15 @@ public class CatalogManager implements CatalogDispatcher, Closeable {
nameIdentifierForLock,
LockType.WRITE,
() -> {
+ // Hold the lifecycle read lock across the whole mutation, from before the entity is
+ // persisted until the refreshed wrapper is published. Taking it only inside
+ // createAndCacheCatalogLease would leave a window in which close() grabs the write lock
+ // after the entity (and its secrets) were already updated, so checkOpen() would fail the
+ // caller's alter even though the change took effect. Same lock ordering as everywhere
+ // else: tree lock first, lifecycle lock second.
+ lifecycleLock.readLock().lock();
try {
+ checkOpen();
CatalogEntity updatedCatalog = alterCatalogUnderLock(ident, changes);
// Invalidate after store.update() so that any background thread that tries to reload
// the old catalog identifier from the store (after the invalidate) will get
@@ -1016,9 +1284,12 @@ public class CatalogManager implements CatalogDispatcher, Closeable {
CatalogEntity convertedCatalog = convertFilesetCatalogEntity(updatedCatalog);
// Use put() instead of get() to force the updated wrapper into the cache, preventing
// a background thread from overwriting it with stale data between invalidate and put.
- CatalogWrapper newWrapper = createCatalogWrapper(convertedCatalog, null);
- catalogCache.put(convertedCatalog.nameIdentifier(), newWrapper);
- return newWrapper.catalog();
+ try (CatalogLease lease =
+ createAndCacheCatalogLease(
+ convertedCatalog.nameIdentifier(),
+ () -> createCatalogWrapper(convertedCatalog, null))) {
+ return toCatalogInfo(lease.wrapper());
+ }
} catch (NoSuchCatalogException e) {
throw e;
@@ -1034,6 +1305,9 @@ public class CatalogManager implements CatalogDispatcher, Closeable {
} catch (IOException ioe) {
LOG.error("Failed to alter catalog {}", ident, ioe);
throw new RuntimeException(ioe);
+
+ } finally {
+ lifecycleLock.readLock().unlock();
}
});
}
@@ -1089,8 +1363,8 @@ public class CatalogManager implements CatalogDispatcher, Closeable {
metalakeIdent,
LockType.WRITE,
() -> {
- try {
- CatalogWrapper catalogWrapper = loadCatalogAndWrap(ident);
+ try (CatalogLease lease = acquireCatalogLease(ident)) {
+ CatalogWrapper catalogWrapper = lease.wrapper();
catalogWrapper.catalog().checkMetalakeInUse();
boolean catalogInUse = catalogWrapper.catalog().catalogInUse();
@@ -1281,27 +1555,123 @@ public class CatalogManager implements CatalogDispatcher, Closeable {
return false;
}
+ /**
+ * Loads the catalog with the specified identifier, wraps it in a CatalogWrapper, caches the
+ * wrapper for reuse, and takes a lease on it. The lease keeps the catalog and its ClassLoader
+ * alive for the duration of the operation even if the cache evicts the wrapper concurrently, so
+ * the caller must close the lease when the operation is done, ideally with try-with-resources.
+ *
+ * <p>If the cached wrapper has already been retired (by an eviction, an invalidation or a drop),
+ * the stale entry is evicted and a fresh wrapper is loaded and cached.
+ *
+ * <p>Lookup, loading, and lease acquisition are atomic per catalog identifier.
+ *
+ * @param ident The identifier of the catalog to load.
+ * @return A lease on the CatalogWrapper containing the loaded catalog.
+ * @throws NoSuchCatalogException If the specified catalog does not exist.
+ */
+ CatalogLease acquireCatalogLease(NameIdentifier ident) throws NoSuchCatalogException {
+ lifecycleLock.readLock().lock();
+ try {
+ checkOpen();
+ AtomicReference<CatalogLease> acquiredLease = new AtomicReference<>();
+ AtomicReference<CatalogWrapper> newlyLoadedWrapper = new AtomicReference<>();
+ try {
+ catalogCache
+ .asMap()
+ .compute(
+ ident,
+ (key, cachedWrapper) -> {
+ CatalogWrapper wrapper = cachedWrapper;
+ if (wrapper == null || !wrapper.tryAcquire()) {
+ wrapper = loadCatalogInternal(key);
+ newlyLoadedWrapper.set(wrapper);
+ Preconditions.checkState(
+ wrapper.tryAcquire(), "A newly loaded catalog wrapper cannot be retired");
+ }
+
+ CatalogLease lease = new CatalogLease(wrapper);
+ if (!acquiredLease.compareAndSet(null, lease)) {
+ lease.close();
+ throw new IllegalStateException(
+ "Catalog cache compute invoked its mapping function more than once");
+ }
+ return wrapper;
+ });
+ } catch (RuntimeException | Error e) {
+ CatalogWrapper newlyLoaded = newlyLoadedWrapper.get();
+ if (newlyLoaded != null) {
+ newlyLoaded.retire();
+ }
+ CatalogLease lease = acquiredLease.get();
+ if (lease != null) {
+ lease.close();
+ }
+ throw e;
+ }
+ return Preconditions.checkNotNull(acquiredLease.get(), "Catalog lease was not acquired");
+ } finally {
+ lifecycleLock.readLock().unlock();
+ }
+ }
+
/**
* Loads the catalog with the specified identifier, wraps it in a CatalogWrapper, and caches the
- * wrapper for reuse. If the cached wrapper has already been closed (its underlying catalog is
- * null), the stale entry is evicted and a fresh wrapper is loaded and cached.
+ * wrapper for reuse. If the cached wrapper has already been retired, the stale entry is evicted
+ * and a fresh wrapper is loaded and cached.
+ *
+ * <p>The returned wrapper is not leased, so a concurrent cache eviction may retire and close it
+ * while the caller is still using it. Prefer {@link #acquireCatalogLease(NameIdentifier)}, which
+ * keeps the wrapper alive for the duration of the operation.
*
* @param ident The identifier of the catalog to load.
* @return The wrapped CatalogWrapper containing the loaded catalog.
* @throws NoSuchCatalogException If the specified catalog does not exist.
*/
- public CatalogWrapper loadCatalogAndWrap(NameIdentifier ident) throws NoSuchCatalogException {
+ @VisibleForTesting
+ CatalogWrapper loadCatalogAndWrap(NameIdentifier ident) throws NoSuchCatalogException {
+ lifecycleLock.readLock().lock();
+ try {
+ checkOpen();
+ return loadCatalogAndWrapInternal(ident);
+ } finally {
+ lifecycleLock.readLock().unlock();
+ }
+ }
+
+ private CatalogWrapper loadCatalogAndWrapInternal(NameIdentifier ident)
+ throws NoSuchCatalogException {
CatalogWrapper wrapper = catalogCache.get(ident, this::loadCatalogInternal);
- if (wrapper.catalog() != null) {
- return wrapper;
+ if (wrapper.isRetired()) {
+ // The cached wrapper has already been retired, e.g. by a prior dropCatalog or cache eviction.
+ // Evict the stale entry and reload a fresh one. Use a conditional remove so we do not clobber
+ // a wrapper that another thread may have concurrently reloaded into the cache between our
+ // initial get and this remove.
+ catalogCache.asMap().remove(ident, wrapper);
+ wrapper = catalogCache.get(ident, this::loadCatalogInternal);
}
+ return wrapper;
+ }
- // The cached wrapper has already been closed (catalog() == null), e.g. by a prior
- // dropCatalog or cache eviction. Evict the stale entry and reload a fresh one.
- // Use a conditional remove so we do not clobber a wrapper that another thread may
- // have concurrently reloaded into the cache between our initial get and this remove.
- catalogCache.asMap().remove(ident, wrapper);
- return catalogCache.get(ident, this::loadCatalogInternal);
+ private CatalogLease createAndCacheCatalogLease(
+ NameIdentifier ident, Supplier<CatalogWrapper> wrapperSupplier) {
+ lifecycleLock.readLock().lock();
+ try {
+ checkOpen();
+ CatalogWrapper wrapper = wrapperSupplier.get();
+ Preconditions.checkState(wrapper.tryAcquire(), "A new catalog wrapper cannot be retired");
+ CatalogLease lease = new CatalogLease(wrapper);
+ try {
+ catalogCache.put(ident, wrapper);
+ return lease;
+ } catch (RuntimeException | Error e) {
+ wrapper.retire();
+ lease.close();
+ throw e;
+ }
+ } finally {
+ lifecycleLock.readLock().unlock();
+ }
}
private boolean isManagedStorageCatalog(CatalogWrapper catalogWrapper) {
@@ -1495,14 +1865,32 @@ public class CatalogManager implements CatalogDispatcher, Closeable {
* @return The resolved properties.
*/
private Map<String, String> getResolvedProperties(CatalogEntity entity) {
- // Resolve properties through the cached wrapper (loadCatalogAndWrap), which reuses the
+ // Resolve properties through the leased cached wrapper, which reuses the
// pooled/dedicated ClassLoader and the CatalogWrapper cache. This avoids building and tearing
// down a throwaway BaseCatalog (and leaking its authorizationPlugin) on every listCatalogsInfo
// call, and keeps the classLoaderSharingEnabled branching in a single place
// (createCatalogWrapper).
- CatalogWrapper catalogWrapper = loadCatalogAndWrap(entity.nameIdentifier());
- return catalogWrapper.classLoader.withClassLoader(
- cl -> catalogWrapper.catalog.properties(), RuntimeException.class);
+ try (CatalogLease lease = acquireCatalogLease(entity.nameIdentifier())) {
+ CatalogWrapper catalogWrapper = lease.wrapper();
+ return catalogWrapper.classLoader.withClassLoader(
+ cl -> catalogWrapper.catalog.properties(), RuntimeException.class);
+ }
+ }
+
+ private Catalog toCatalogInfo(CatalogWrapper wrapper) {
+ try {
+ return wrapper.doWithCatalog(
+ catalog ->
+ catalog.entity().toCatalogInfoWithResolvedProps(new HashMap<>(catalog.properties())));
+ } catch (RuntimeException e) {
+ throw e;
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to create catalog metadata snapshot", e);
+ }
+ }
+
+ private void checkOpen() {
+ Preconditions.checkState(!closed, "CatalogManager is already closed");
}
private BaseCatalog<?> createBaseCatalog(IsolatedClassLoader classLoader, CatalogEntity entity) {
diff --git a/core/src/main/java/org/apache/gravitino/catalog/ConnectorObjectSnapshot.java b/core/src/main/java/org/apache/gravitino/catalog/ConnectorObjectSnapshot.java
new file mode 100644
index 0000000000..087f07041f
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/catalog/ConnectorObjectSnapshot.java
@@ -0,0 +1,124 @@
+/*
+ * 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;
+
+import java.util.HashMap;
+import java.util.Map;
+import javax.annotation.Nullable;
+import org.apache.gravitino.Audit;
+import org.apache.gravitino.Schema;
+import org.apache.gravitino.dto.util.DTOConverters;
+import org.apache.gravitino.file.FileInfo;
+import org.apache.gravitino.file.Fileset;
+import org.apache.gravitino.messaging.Topic;
+import org.apache.gravitino.model.Model;
+import org.apache.gravitino.model.ModelVersion;
+import org.apache.gravitino.rel.Table;
+import org.apache.gravitino.rel.View;
+import org.apache.gravitino.rel.partitions.Partition;
+
+/** Creates parent-ClassLoader metadata snapshots from connector-backed operation results. */
+final class ConnectorObjectSnapshot {
+
+ private ConnectorObjectSnapshot() {}
+
+ @SuppressWarnings("unchecked")
+ static <R> R detach(R result) {
+ if (result instanceof Table) {
+ return (R) DTOConverters.toDTO((Table) result);
+ } else if (result instanceof View) {
+ return (R) DTOConverters.toDTO((View) result);
+ } else if (result instanceof Schema) {
+ return (R) DTOConverters.toDTO((Schema) result);
+ } else if (result instanceof Fileset) {
+ return (R) new FilesetSnapshot((Fileset) result);
+ } else if (result instanceof Topic) {
+ return (R) DTOConverters.toDTO((Topic) result);
+ } else if (result instanceof Model) {
+ return (R) DTOConverters.toDTO((Model) result);
+ } else if (result instanceof ModelVersion) {
+ return (R) DTOConverters.toDTO((ModelVersion) result);
+ } else if (result instanceof Partition) {
+ return (R) DTOConverters.toDTO((Partition) result);
+ } else if (result instanceof ModelVersion[]) {
+ return (R) DTOConverters.toDTOs((ModelVersion[]) result);
+ } else if (result instanceof Partition[]) {
+ return (R) DTOConverters.toDTOs((Partition[]) result);
+ } else if (result instanceof FileInfo[]) {
+ return (R) DTOConverters.toDTO((FileInfo[]) result);
+ }
+ return result;
+ }
+
+ private static final class FilesetSnapshot implements Fileset {
+
+ private final String name;
+ @Nullable private final String comment;
+ private final Type type;
+ private final Map<String, String> storageLocations;
+ @Nullable private final Map<String, String> properties;
+ private final Audit audit;
+
+ private FilesetSnapshot(Fileset fileset) {
+ this.name = fileset.name();
+ this.comment = fileset.comment();
+ this.type = fileset.type();
+ this.storageLocations = new HashMap<>(fileset.storageLocations());
+ this.properties = copyNullable(fileset.properties());
+ this.audit = DTOConverters.toDTO(fileset.auditInfo());
+ }
+
+ @Override
+ public String name() {
+ return name;
+ }
+
+ @Nullable
+ @Override
+ public String comment() {
+ return comment;
+ }
+
+ @Override
+ public Type type() {
+ return type;
+ }
+
+ @Override
+ public Map<String, String> storageLocations() {
+ return storageLocations;
+ }
+
+ @Nullable
+ @Override
+ public Map<String, String> properties() {
+ return properties;
+ }
+
+ @Override
+ public Audit auditInfo() {
+ return audit;
+ }
+
+ @Nullable
+ private static Map<String, String> copyNullable(@Nullable Map<String, String> source) {
+ return source == null ? null : new HashMap<>(source);
+ }
+ }
+}
diff --git a/core/src/main/java/org/apache/gravitino/catalog/EntityCombinedTable.java b/core/src/main/java/org/apache/gravitino/catalog/EntityCombinedTable.java
index 0e070eaa83..a9ee8513cb 100644
--- a/core/src/main/java/org/apache/gravitino/catalog/EntityCombinedTable.java
+++ b/core/src/main/java/org/apache/gravitino/catalog/EntityCombinedTable.java
@@ -83,6 +83,10 @@ public final class EntityCombinedTable implements Table {
return this;
}
+ MaskAndOmitKeys hiddenProperties() {
+ return MaskAndOmitKeys.of(keysToMask, keysToOmit);
+ }
+
@Override
public String name() {
return table.name();
diff --git a/core/src/main/java/org/apache/gravitino/catalog/OperationDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/OperationDispatcher.java
index 30d57ac86a..683f9d57d1 100644
--- a/core/src/main/java/org/apache/gravitino/catalog/OperationDispatcher.java
+++ b/core/src/main/java/org/apache/gravitino/catalog/OperationDispatcher.java
@@ -88,8 +88,9 @@ public abstract class OperationDispatcher {
throws E {
try {
NameIdentifier catalogIdent = getCatalogIdentifier(tableIdent);
- CatalogManager.CatalogWrapper c = catalogManager.loadCatalogAndWrap(catalogIdent);
- return c.doWithPartitionOps(tableIdent, fn);
+ return catalogManager.doWithCatalogWrapper(
+ catalogIdent,
+ wrapper -> wrapper.detachConnectorResult(wrapper.doWithPartitionOps(tableIdent, fn)));
} catch (Exception exception) {
if (ex.isInstance(exception)) {
throw ex.cast(exception);
@@ -105,8 +106,8 @@ public abstract class OperationDispatcher {
NameIdentifier ident, ThrowableFunction<CatalogManager.CatalogWrapper, R> fn, Class<E> ex)
throws E {
try {
- CatalogManager.CatalogWrapper c = catalogManager.loadCatalogAndWrap(ident);
- return fn.apply(c);
+ return catalogManager.doWithCatalogWrapper(
+ ident, wrapper -> wrapper.detachConnectorResult(fn.apply(wrapper)));
} catch (Exception exception) {
if (ex.isInstance(exception)) {
throw ex.cast(exception);
@@ -125,8 +126,8 @@ public abstract class OperationDispatcher {
Class<E2> ex2)
throws E1, E2 {
try {
- CatalogManager.CatalogWrapper c = catalogManager.loadCatalogAndWrap(ident);
- return fn.apply(c);
+ return catalogManager.doWithCatalogWrapper(
+ ident, wrapper -> wrapper.detachConnectorResult(fn.apply(wrapper)));
} catch (Exception exception) {
if (ex1.isInstance(exception)) {
throw ex1.cast(exception);
@@ -147,31 +148,65 @@ public abstract class OperationDispatcher {
Map<String, String> properties) {
return doWithCatalog(
catalogIdent,
- c ->
- c.doWithPropertiesMeta(
- p ->
- HiddenPropertyMaskUtils.classifyHiddenProperties(
- properties, provider.apply(p))),
+ c -> getMaskAndOmitKeys(c, provider, properties),
IllegalArgumentException.class);
}
+ /**
+ * Classifies hidden properties using metadata from the supplied leased catalog wrapper.
+ *
+ * @param catalog the leased catalog wrapper
+ * @param provider the metadata provider for the entity type
+ * @param properties the properties to classify
+ * @return the keys to mask and omit
+ * @throws Exception if reading the connector metadata fails
+ */
+ protected MaskAndOmitKeys getMaskAndOmitKeys(
+ CatalogManager.CatalogWrapper catalog,
+ ThrowableFunction<HasPropertyMetadata, PropertiesMetadata> provider,
+ Map<String, String> properties)
+ throws Exception {
+ return catalog.doWithPropertiesMeta(
+ metadata ->
+ HiddenPropertyMaskUtils.classifyHiddenProperties(properties, provider.apply(metadata)));
+ }
+
protected <T> void validateAlterProperties(
NameIdentifier ident,
ThrowableFunction<HasPropertyMetadata, PropertiesMetadata> provider,
T... changes) {
doWithCatalog(
getCatalogIdentifier(ident),
- c ->
- c.doWithPropertiesMeta(
- p -> {
- Map<String, String> upserts = getPropertiesForSet(changes);
- Map<String, String> deletes = getPropertiesForDelete(changes);
- validatePropertyForAlter(provider.apply(p), upserts, deletes);
- return null;
- }),
+ c -> {
+ validateAlterProperties(c, provider, changes);
+ return null;
+ },
IllegalArgumentException.class);
}
+ /**
+ * Validates property changes using metadata from the supplied leased catalog wrapper.
+ *
+ * @param catalog the leased catalog wrapper
+ * @param provider the metadata provider for the entity type
+ * @param changes the requested changes
+ * @param <T> the change type
+ * @throws Exception if reading the connector metadata fails
+ */
+ protected <T> void validateAlterProperties(
+ CatalogManager.CatalogWrapper catalog,
+ ThrowableFunction<HasPropertyMetadata, PropertiesMetadata> provider,
+ T... changes)
+ throws Exception {
+ catalog.doWithPropertiesMeta(
+ metadata -> {
+ Map<String, String> upserts = getPropertiesForSet(changes);
+ Map<String, String> deletes = getPropertiesForDelete(changes);
+ validatePropertyForAlter(provider.apply(metadata), upserts, deletes);
+ return null;
+ });
+ }
+
private <T> Map<String, String> getPropertiesForDelete(T... t) {
Map<String, String> properties = Maps.newHashMap();
for (T item : t) {
@@ -253,9 +288,14 @@ public abstract class OperationDispatcher {
boolean isManagedEntity(NameIdentifier catalogIdent, Capability.Scope scope) {
return doWithCatalog(
- catalogIdent,
- c -> c.capabilities().managedStorage(scope).supported(),
- IllegalArgumentException.class);
+ catalogIdent, c -> isManagedEntity(c, scope), IllegalArgumentException.class);
+ }
+
+ boolean isManagedEntity(CatalogManager.CatalogWrapper catalog, Capability.Scope scope)
+ throws Exception {
+ // Read the capability and interpret it in one pass under the catalog ClassLoader: a connector
+ // CapabilityResult can load classes of its own on the first call.
+ return catalog.doWithCatalog(c -> c.capability().managedStorage(scope).supported());
}
protected <E extends Entity & HasIdentifier> E getEntity(
diff --git a/core/src/main/java/org/apache/gravitino/catalog/TableOperationDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/TableOperationDispatcher.java
index bbc28e86ba..cd996cecdd 100644
--- a/core/src/main/java/org/apache/gravitino/catalog/TableOperationDispatcher.java
+++ b/core/src/main/java/org/apache/gravitino/catalog/TableOperationDispatcher.java
@@ -46,6 +46,7 @@ import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
import org.apache.gravitino.StringIdentifier;
import org.apache.gravitino.connector.HasPropertyMetadata;
+import org.apache.gravitino.connector.MaskAndOmitKeys;
import org.apache.gravitino.connector.capability.Capability;
import org.apache.gravitino.exceptions.GravitinoRuntimeException;
import org.apache.gravitino.exceptions.NoSuchEntityException;
@@ -184,11 +185,7 @@ public class TableOperationDispatcher extends OperationDispatcher implements Tab
TableEntity updatedEntity = updateColumnsIfNecessaryWhenLoad(ident, entityCombinedTable);
return EntityCombinedTable.of(entityCombinedTable.tableFromCatalog(), updatedEntity)
- .withHiddenProperties(
- getMaskAndOmitKeys(
- getCatalogIdentifier(ident),
- HasPropertyMetadata::tablePropertiesMetadata,
- entityCombinedTable.tableFromCatalog().properties()))
+ .withHiddenProperties(entityCombinedTable.hiddenProperties())
.withImported(entityCombinedTable.imported());
}
@@ -252,7 +249,6 @@ public class TableOperationDispatcher extends OperationDispatcher implements Tab
@Override
public Table alterTable(NameIdentifier ident, TableChange... changes)
throws NoSuchTableException, IllegalArgumentException {
- validateAlterProperties(ident, HasPropertyMetadata::tablePropertiesMetadata, changes);
boolean isRenameTable =
Arrays.stream(changes).anyMatch(change -> change instanceof TableChange.RenameTable);
@@ -283,43 +279,44 @@ public class TableOperationDispatcher extends OperationDispatcher implements Tab
nameIdentifierForLock.equals(ident) ? LockType.READ : LockType.WRITE,
() -> {
NameIdentifier catalogIdent = getCatalogIdentifier(ident);
- boolean isManagedTable = isManagedEntity(catalogIdent, Capability.Scope.TABLE);
- Optional<TableEntity> tableEntityBeforeRename =
- isRenameTable && !isManagedTable
- ? getTableEntityBeforeRename(ident)
- : Optional.empty();
- Table alteredTable =
+ AlterTableCatalogResult catalogResult =
doWithCatalog(
catalogIdent,
- c ->
- c.doWithTableOps(
- t -> t.alterTable(ident, applyCapabilities(c.capabilities(), changes))),
+ catalog -> {
+ validateAlterProperties(
+ catalog, HasPropertyMetadata::tablePropertiesMetadata, changes);
+ boolean managed = isManagedEntity(catalog, Capability.Scope.TABLE);
+ Optional<TableEntity> tableEntityBeforeRename =
+ isRenameTable && !managed
+ ? getTableEntityBeforeRename(ident)
+ : Optional.empty();
+ Table table =
+ catalog.doWithTableOps(
+ tableOps ->
+ tableOps.alterTable(
+ ident, applyCapabilities(catalog.capabilities(), changes)));
+ return new AlterTableCatalogResult(
+ snapshotTable(catalog, table, managed), tableEntityBeforeRename);
+ },
NoSuchTableException.class,
IllegalArgumentException.class);
+ Table alteredTable = catalogResult.table;
- if (isManagedTable) {
+ if (catalogResult.managed) {
return EntityCombinedTable.of(alteredTable)
- .withHiddenProperties(
- getMaskAndOmitKeys(
- getCatalogIdentifier(ident),
- HasPropertyMetadata::tablePropertiesMetadata,
- alteredTable.properties()));
+ .withHiddenProperties(catalogResult.hiddenProperties);
}
StringIdentifier stringId = getStringIdFromProperties(alteredTable.properties());
// Case 1: The table is not created by Gravitino and this table is never imported.
- TableEntity te = tableEntityBeforeRename.orElse(null);
+ TableEntity te = catalogResult.tableEntityBeforeRename.orElse(null);
if (stringId == null) {
if (te == null) {
te = getEntity(ident, TABLE, TableEntity.class);
}
if (te == null) {
return EntityCombinedTable.of(alteredTable)
- .withHiddenProperties(
- getMaskAndOmitKeys(
- getCatalogIdentifier(ident),
- HasPropertyMetadata::tablePropertiesMetadata,
- alteredTable.properties()));
+ .withHiddenProperties(catalogResult.hiddenProperties);
}
}
@@ -375,11 +372,7 @@ public class TableOperationDispatcher extends OperationDispatcher implements Tab
}
return EntityCombinedTable.of(alteredTable, updatedTableEntity)
- .withHiddenProperties(
- getMaskAndOmitKeys(
- getCatalogIdentifier(ident),
- HasPropertyMetadata::tablePropertiesMetadata,
- alteredTable.properties()));
+ .withHiddenProperties(catalogResult.hiddenProperties);
});
}
@@ -573,11 +566,7 @@ public class TableOperationDispatcher extends OperationDispatcher implements Tab
}
return EntityCombinedTable.of(table.tableFromCatalog(), tableEntity)
- .withHiddenProperties(
- getMaskAndOmitKeys(
- getCatalogIdentifier(identifier),
- HasPropertyMetadata::tablePropertiesMetadata,
- table.tableFromCatalog().properties()));
+ .withHiddenProperties(table.hiddenProperties());
}
private SchemaDispatcher getSchemaDispatcher() {
@@ -591,20 +580,19 @@ public class TableOperationDispatcher extends OperationDispatcher implements Tab
private EntityCombinedTable internalLoadTable(NameIdentifier ident) {
NameIdentifier catalogIdentifier = getCatalogIdentifier(ident);
- Table table =
+ TableCatalogResult catalogResult =
doWithCatalog(
catalogIdentifier,
- c -> c.doWithTableOps(t -> t.loadTable(ident)),
+ catalog -> {
+ Table table = catalog.doWithTableOps(tableOps -> tableOps.loadTable(ident));
+ return snapshotTable(catalog, table);
+ },
NoSuchTableException.class);
+ Table table = catalogResult.table;
- boolean isManagedTable = isManagedEntity(catalogIdentifier, Capability.Scope.TABLE);
- if (isManagedTable) {
+ if (catalogResult.managed) {
return EntityCombinedTable.of(table)
- .withHiddenProperties(
- getMaskAndOmitKeys(
- catalogIdentifier,
- HasPropertyMetadata::tablePropertiesMetadata,
- table.properties()))
+ .withHiddenProperties(catalogResult.hiddenProperties)
// The metadata of managed table is stored by Gravitino, so it is always imported.
.withImported(true /* imported */);
}
@@ -616,11 +604,7 @@ public class TableOperationDispatcher extends OperationDispatcher implements Tab
TableEntity tableEntity = getEntity(ident, TABLE, TableEntity.class);
if (tableEntity == null) {
return EntityCombinedTable.of(table)
- .withHiddenProperties(
- getMaskAndOmitKeys(
- catalogIdentifier,
- HasPropertyMetadata::tablePropertiesMetadata,
- table.properties()))
+ .withHiddenProperties(catalogResult.hiddenProperties)
// Some tables don't have properties or are not created by Gravitino,
// we can't use stringIdentifier to judge whether schema is ever imported or not.
// We need to check whether the entity exists.
@@ -628,11 +612,7 @@ public class TableOperationDispatcher extends OperationDispatcher implements Tab
}
return EntityCombinedTable.of(table, tableEntity)
- .withHiddenProperties(
- getMaskAndOmitKeys(
- catalogIdentifier,
- HasPropertyMetadata::tablePropertiesMetadata,
- table.properties()))
+ .withHiddenProperties(catalogResult.hiddenProperties)
// For some catalogs like PG, the identifier information is not stored in the table's
// metadata, we need to check if this table exists in the store, if so we don't
// need to import.
@@ -647,11 +627,7 @@ public class TableOperationDispatcher extends OperationDispatcher implements Tab
stringId.id());
return EntityCombinedTable.of(table, tableEntity)
- .withHiddenProperties(
- getMaskAndOmitKeys(
- catalogIdentifier,
- HasPropertyMetadata::tablePropertiesMetadata,
- table.properties()))
+ .withHiddenProperties(catalogResult.hiddenProperties)
.withImported(tableEntity != null);
}
@@ -665,51 +641,47 @@ public class TableOperationDispatcher extends OperationDispatcher implements Tab
SortOrder[] sortOrders,
Index[] indexes) {
NameIdentifier catalogIdent = getCatalogIdentifier(ident);
- doWithCatalog(
- catalogIdent,
- c ->
- c.doWithPropertiesMeta(
- p -> {
- validatePropertyForCreate(p.tablePropertiesMetadata(), properties);
- return null;
- }),
- IllegalArgumentException.class);
-
- long uid = idGenerator.nextId();
- // Add StringIdentifier to the properties, the specific catalog will handle this
- // StringIdentifier to make sure only when the operation is successful, the related
- // TableEntity will be visible.
- StringIdentifier stringId = StringIdentifier.fromId(uid);
- Map<String, String> updatedProperties =
- StringIdentifier.newPropertiesWithId(stringId, properties);
-
- // we do not retrieve the table again (to obtain some values generated by underlying catalog)
- // since some catalogs' API is async and the table may not be created immediately
- Table table =
+ CreateTableCatalogResult catalogResult =
doWithCatalog(
catalogIdent,
- c ->
- c.doWithTableOps(
- t ->
- t.createTable(
- ident,
- columns,
- comment,
- updatedProperties,
- partitions == null ? EMPTY_TRANSFORM : partitions,
- distribution == null ? Distributions.NONE : distribution,
- sortOrders == null ? new SortOrder[0] : sortOrders,
- indexes == null ? Indexes.EMPTY_INDEXES : indexes)),
+ catalog -> {
+ catalog.doWithPropertiesMeta(
+ metadata -> {
+ validatePropertyForCreate(metadata.tablePropertiesMetadata(), properties);
+ return null;
+ });
+
+ long uid = idGenerator.nextId();
+ // Add StringIdentifier to the properties, the specific catalog will handle this
+ // StringIdentifier to make sure only when the operation is successful, the related
+ // TableEntity will be visible.
+ StringIdentifier stringId = StringIdentifier.fromId(uid);
+ Map<String, String> updatedProperties =
+ StringIdentifier.newPropertiesWithId(stringId, properties);
+
+ // We do not retrieve the table again to obtain values generated by the underlying
+ // catalog because some catalog APIs are asynchronous.
+ Table table =
+ catalog.doWithTableOps(
+ tableOps ->
+ tableOps.createTable(
+ ident,
+ columns,
+ comment,
+ updatedProperties,
+ partitions == null ? EMPTY_TRANSFORM : partitions,
+ distribution == null ? Distributions.NONE : distribution,
+ sortOrders == null ? new SortOrder[0] : sortOrders,
+ indexes == null ? Indexes.EMPTY_INDEXES : indexes));
+ return new CreateTableCatalogResult(snapshotTable(catalog, table), uid);
+ },
NoSuchSchemaException.class,
TableAlreadyExistsException.class);
+ Table table = catalogResult.table;
// If the table is managed by Gravitino, we don't need to create TableEntity and store it again.
- boolean isManagedTable = isManagedEntity(catalogIdent, Capability.Scope.TABLE);
- if (isManagedTable) {
- return EntityCombinedTable.of(table)
- .withHiddenProperties(
- getMaskAndOmitKeys(
- catalogIdent, HasPropertyMetadata::tablePropertiesMetadata, table.properties()));
+ if (catalogResult.managed) {
+ return EntityCombinedTable.of(table).withHiddenProperties(catalogResult.hiddenProperties);
}
AuditInfo audit =
@@ -724,7 +696,7 @@ public class TableOperationDispatcher extends OperationDispatcher implements Tab
TableEntity tableEntity =
TableEntity.builder()
- .withId(uid)
+ .withId(catalogResult.id)
.withName(ident.name())
.withNamespace(ident.namespace())
.withColumns(columnEntityList)
@@ -735,17 +707,26 @@ public class TableOperationDispatcher extends OperationDispatcher implements Tab
store.put(tableEntity, true /* overwrite */);
} catch (Exception e) {
LOG.error(FormattedErrorMessages.STORE_OP_FAILURE, "put", ident, e);
- return EntityCombinedTable.of(table)
- .withHiddenProperties(
- getMaskAndOmitKeys(
- catalogIdent, HasPropertyMetadata::tablePropertiesMetadata, table.properties()));
+ return EntityCombinedTable.of(table).withHiddenProperties(catalogResult.hiddenProperties);
}
// Merge both the metadata from catalog operation and the metadata from entity store.
return EntityCombinedTable.of(table, tableEntity)
- .withHiddenProperties(
- getMaskAndOmitKeys(
- catalogIdent, HasPropertyMetadata::tablePropertiesMetadata, table.properties()));
+ .withHiddenProperties(catalogResult.hiddenProperties);
+ }
+
+ private TableCatalogResult snapshotTable(
+ CatalogManager.CatalogWrapper catalog, Table table, boolean managed) throws Exception {
+ Table snapshot = catalog.detachConnectorResult(table);
+ MaskAndOmitKeys hiddenProperties =
+ getMaskAndOmitKeys(
+ catalog, HasPropertyMetadata::tablePropertiesMetadata, snapshot.properties());
+ return new TableCatalogResult(snapshot, managed, hiddenProperties);
+ }
+
+ private TableCatalogResult snapshotTable(CatalogManager.CatalogWrapper catalog, Table table)
+ throws Exception {
+ return snapshotTable(catalog, table, isManagedEntity(catalog, Capability.Scope.TABLE));
}
private List<ColumnEntity> toColumnEntities(Column[] columns, AuditInfo audit) {
@@ -951,4 +932,38 @@ public class TableOperationDispatcher extends OperationDispatcher implements Tab
"UPDATE",
combinedTable.tableFromGravitino().id()));
}
+
+ private static class TableCatalogResult {
+
+ final Table table;
+ final boolean managed;
+ final MaskAndOmitKeys hiddenProperties;
+
+ private TableCatalogResult(Table table, boolean managed, MaskAndOmitKeys hiddenProperties) {
+ this.table = table;
+ this.managed = managed;
+ this.hiddenProperties = hiddenProperties;
+ }
+ }
+
+ private static final class AlterTableCatalogResult extends TableCatalogResult {
+
+ private final Optional<TableEntity> tableEntityBeforeRename;
+
+ private AlterTableCatalogResult(
+ TableCatalogResult tableResult, Optional<TableEntity> tableEntityBeforeRename) {
+ super(tableResult.table, tableResult.managed, tableResult.hiddenProperties);
+ this.tableEntityBeforeRename = tableEntityBeforeRename;
+ }
+ }
+
+ private static final class CreateTableCatalogResult extends TableCatalogResult {
+
+ private final long id;
+
+ private CreateTableCatalogResult(TableCatalogResult tableResult, long id) {
+ super(tableResult.table, tableResult.managed, tableResult.hiddenProperties);
+ this.id = id;
+ }
+ }
}
diff --git a/core/src/main/java/org/apache/gravitino/hook/CatalogHookDispatcher.java b/core/src/main/java/org/apache/gravitino/hook/CatalogHookDispatcher.java
index 3879e5450e..50ec46ef58 100644
--- a/core/src/main/java/org/apache/gravitino/hook/CatalogHookDispatcher.java
+++ b/core/src/main/java/org/apache/gravitino/hook/CatalogHookDispatcher.java
@@ -32,7 +32,6 @@ import org.apache.gravitino.authorization.FutureGrantManager;
import org.apache.gravitino.authorization.Owner;
import org.apache.gravitino.authorization.OwnerDispatcher;
import org.apache.gravitino.catalog.CatalogDispatcher;
-import org.apache.gravitino.connector.BaseCatalog;
import org.apache.gravitino.exceptions.CatalogAlreadyExistsException;
import org.apache.gravitino.exceptions.CatalogInUseException;
import org.apache.gravitino.exceptions.CatalogNotInUseException;
@@ -113,9 +112,16 @@ public class CatalogHookDispatcher implements CatalogDispatcher {
// Apply the metalake securable object privileges to authorization plugin
FutureGrantManager futureGrantManager = GravitinoEnv.getInstance().futureGrantManager();
- if (futureGrantManager != null && catalog instanceof BaseCatalog) {
- futureGrantManager.grantNewlyCreatedCatalog(
- ident.namespace().level(0), (BaseCatalog) catalog);
+ if (futureGrantManager != null) {
+ GravitinoEnv.getInstance()
+ .catalogManager()
+ .doWithCatalog(
+ ident,
+ leasedCatalog -> {
+ futureGrantManager.grantNewlyCreatedCatalog(
+ ident.namespace().level(0), leasedCatalog);
+ return null;
+ });
}
} catch (Exception postHookException) {
LOG.warn(
@@ -162,13 +168,9 @@ public class CatalogHookDispatcher implements CatalogDispatcher {
return false;
}
- Catalog catalog = dispatcher.loadCatalog(ident);
-
- if (catalog != null) {
- List<String> locations =
- AuthorizationUtils.getMetadataObjectLocation(ident, Entity.EntityType.CATALOG);
- AuthorizationUtils.removeCatalogPrivileges(catalog, locations);
- }
+ List<String> locations =
+ AuthorizationUtils.getMetadataObjectLocation(ident, Entity.EntityType.CATALOG);
+ AuthorizationUtils.removeCatalogPrivileges(ident, locations);
// We should call the authorization plugin before dropping the catalog, because the dropping
// catalog will close the authorization plugin. Child schema/fileset write-through secrets are
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/EntityChangeLogPoller.java b/core/src/main/java/org/apache/gravitino/storage/relational/EntityChangeLogPoller.java
index afc21cc5b3..8fa5f51a60 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/EntityChangeLogPoller.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/EntityChangeLogPoller.java
@@ -50,10 +50,12 @@ import org.slf4j.LoggerFactory;
* <li>{@code EntityCacheChangeLogListener} clears its whole entity cache.
* <li>{@code JcasbinChangeListener} clears its whole {@code metadataIdCache}. A stale
* name&#8594;id entry there would be used by authorization checks.
- * <li>{@code CatalogChangeLogListener} clears its whole catalog cache. Clearing it also closes
- * the {@code IsolatedClassLoader} of every cached catalog, including catalogs this process is
- * currently serving (that is the bug in #11739). We accept that cost so a changed catalog is
- * never served from a stale cache, and the clear only happens when a normal removal failed.
+ * <li>{@code CatalogChangeLogListener} clears its whole catalog cache. Clearing it retires every
+ * cached catalog while operation leases defer {@code IsolatedClassLoader} cleanup for
+ * catalogs this process is still serving, so no operation is torn down mid-flight. Connector
+ * metadata is detached before its operation lease closes, so response processing does not
+ * retain a dependency on the retired catalog. The clear only happens when a normal removal
+ * failed.
* </ul>
*
* <p>Do not register a listener here if it cannot recover on its own.
@@ -177,9 +179,9 @@ public class EntityChangeLogPoller implements AutoCloseable {
} catch (Throwable e) {
// Catch Throwable, not Exception: this method is the task handed to
// scheduleWithFixedDelay(), and anything that escapes it cancels all future runs for good,
- // silently. An Error is reachable here, for example a NoClassDefFoundError thrown by a
- // listener that touched a closed IsolatedClassLoader. Losing the poller would stop cache
- // invalidation for every listener in this process, so we log and let the next cycle run.
+ // silently. A listener or its recovery path can throw an Error as well as an Exception.
+ // Losing the poller would stop cache invalidation for every listener in this process, so we
+ // log and let the next cycle run.
if (handleInterruptIfAny(e, "Entity change poll")) {
return;
}
@@ -313,9 +315,8 @@ public class EntityChangeLogPoller implements AutoCloseable {
delivery.firstChangeId(),
delivery.lastChangeId);
} catch (Throwable e) {
- // Throwable, not Exception: a listener recovering by clearing its cache can close an
- // IsolatedClassLoader that is still in use and surface a NoClassDefFoundError, which is an
- // Error. One listener doing that must not take down the whole poller.
+ // Throwable, not Exception: one faulty listener must not take down the whole poller, even
+ // if it fails with an Error rather than an Exception.
LOG.error(
"Entity change log listener {} failed to consume batch id range [{}, {}]; the batch is "
+ "not retried, so the listener is responsible for local recovery",
diff --git a/core/src/main/java/org/apache/gravitino/utils/ClassLoaderPool.java b/core/src/main/java/org/apache/gravitino/utils/ClassLoaderPool.java
index fd376fb0e1..7ee2721a14 100644
--- a/core/src/main/java/org/apache/gravitino/utils/ClassLoaderPool.java
+++ b/core/src/main/java/org/apache/gravitino/utils/ClassLoaderPool.java
@@ -24,7 +24,7 @@ import java.sql.Driver;
import java.sql.DriverManager;
import java.util.Enumeration;
import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Supplier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -35,8 +35,8 @@ import org.slf4j.LoggerFactory;
* URIs, JDBC URL, default filesystem). Sharing ClassLoaders across same-configuration catalogs
* significantly reduces Metaspace memory usage.
*
- * <p>Thread safety is guaranteed through {@link ConcurrentHashMap#compute} for all acquire/release
- * operations.
+ * <p>Thread safety is guaranteed through {@link ConcurrentHashMap#compute} for per-key reference
+ * counting and a lifecycle read-write lock that serializes acquisitions with shutdown.
*
* <p><b>Concurrency note:</b> the classloader factory (JAR scanning in {@code acquire}) and {@link
* #doFinalCleanup} (thread interruption and reflective ThreadLocal cleanup in {@code release}) run
@@ -52,7 +52,10 @@ public class ClassLoaderPool implements Closeable {
private final ConcurrentHashMap<ClassLoaderKey, PooledClassLoaderEntry> pool =
new ConcurrentHashMap<>();
- private final AtomicBoolean closed = new AtomicBoolean(false);
+ private final ReentrantReadWriteLock lifecycleLock = new ReentrantReadWriteLock();
+
+ /** Guarded by {@link #lifecycleLock}. */
+ private boolean closed;
/**
* Acquires a ClassLoader entry for the given key. If an entry already exists, increments the
@@ -64,24 +67,29 @@ public class ClassLoaderPool implements Closeable {
* @throws IllegalStateException if the pool has been closed.
*/
public PooledClassLoaderEntry acquire(ClassLoaderKey key, Supplier<IsolatedClassLoader> factory) {
- return pool.compute(
- key,
- (k, existing) -> {
- if (closed.get()) {
- throw new IllegalStateException("ClassLoaderPool is already closed");
- }
- if (existing != null) {
- existing.incrementRefCount();
- LOG.debug("Reusing ClassLoader for key {}, refCount={}.", key, existing.refCount());
- return existing;
- }
- // If the factory throws (e.g., invalid classpath), the exception propagates to the
- // caller and ConcurrentHashMap leaves the key unmapped.
- IsolatedClassLoader classLoader = factory.get();
- PooledClassLoaderEntry newEntry = new PooledClassLoaderEntry(k, classLoader);
- LOG.info("Created new ClassLoader for key {}, refCount=1.", key);
- return newEntry;
- });
+ lifecycleLock.readLock().lock();
+ try {
+ return pool.compute(
+ key,
+ (k, existing) -> {
+ if (closed) {
+ throw new IllegalStateException("ClassLoaderPool is already closed");
+ }
+ if (existing != null) {
+ existing.incrementRefCount();
+ LOG.debug("Reusing ClassLoader for key {}, refCount={}.", key, existing.refCount());
+ return existing;
+ }
+ // If the factory throws (e.g., invalid classpath), the exception propagates to the
+ // caller and ConcurrentHashMap leaves the key unmapped.
+ IsolatedClassLoader classLoader = factory.get();
+ PooledClassLoaderEntry newEntry = new PooledClassLoaderEntry(k, classLoader);
+ LOG.info("Created new ClassLoader for key {}, refCount=1.", key);
+ return newEntry;
+ });
+ } finally {
+ lifecycleLock.readLock().unlock();
+ }
}
/**
@@ -124,12 +132,29 @@ public class ClassLoaderPool implements Closeable {
*/
@Override
public void close() {
- closed.set(true);
- // Drain with a loop to catch entries inserted by concurrent acquire() calls that were
- // already past the closed check when we set the flag. Since closed=true prevents any new
- // entries from being created, this loop is guaranteed to terminate.
- while (!pool.isEmpty()) {
+ lifecycleLock.writeLock().lock();
+ try {
+ closed = true;
pool.keySet().forEach(this::removeAndCleanup);
+ } finally {
+ lifecycleLock.writeLock().unlock();
+ }
+ }
+
+ /**
+ * Prevents new acquisitions while allowing existing owners to release their entries normally. An
+ * entry is removed immediately when its reference count reaches zero, so every entry still in the
+ * map is active and is cleaned up by {@link #release(PooledClassLoaderEntry)}.
+ *
+ * <p>This is intended for graceful owner shutdown: unlike {@link #close()}, it never closes a
+ * ClassLoader that an active owner may still be using.
+ */
+ public void closeWhenIdle() {
+ lifecycleLock.writeLock().lock();
+ try {
+ closed = true;
+ } finally {
+ lifecycleLock.writeLock().unlock();
}
}
diff --git a/core/src/test/java/org/apache/gravitino/authorization/TestAccessControlManager.java b/core/src/test/java/org/apache/gravitino/authorization/TestAccessControlManager.java
index dac80527ba..0b243c0942 100644
--- a/core/src/test/java/org/apache/gravitino/authorization/TestAccessControlManager.java
+++ b/core/src/test/java/org/apache/gravitino/authorization/TestAccessControlManager.java
@@ -68,6 +68,7 @@ import org.apache.gravitino.bulk.BulkItemResult;
import org.apache.gravitino.bulk.GroupAdd;
import org.apache.gravitino.bulk.UserAdd;
import org.apache.gravitino.catalog.CatalogManager;
+import org.apache.gravitino.catalog.CatalogTestUtils;
import org.apache.gravitino.connector.BaseCatalog;
import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
import org.apache.gravitino.exceptions.GroupAlreadyExistsException;
@@ -194,7 +195,7 @@ public class TestAccessControlManager {
GravitinoEnv.getInstance(), "accessControlDispatcher", accessControlManager, true);
FieldUtils.writeField(GravitinoEnv.getInstance(), "catalogManager", catalogManager, true);
BaseCatalog catalog = mock(BaseCatalog.class);
- when(catalogManager.loadCatalog(any())).thenReturn(catalog);
+ CatalogTestUtils.mockDoWithCatalog(catalogManager, catalog);
authorizationPlugin = mock(AuthorizationPlugin.class);
when(catalog.getAuthorizationPlugin()).thenReturn(authorizationPlugin);
}
diff --git a/core/src/test/java/org/apache/gravitino/authorization/TestAccessControlManagerForPermissions.java b/core/src/test/java/org/apache/gravitino/authorization/TestAccessControlManagerForPermissions.java
index 7a6564270b..228ae3b1ac 100644
--- a/core/src/test/java/org/apache/gravitino/authorization/TestAccessControlManagerForPermissions.java
+++ b/core/src/test/java/org/apache/gravitino/authorization/TestAccessControlManagerForPermissions.java
@@ -42,6 +42,7 @@ import org.apache.gravitino.MetadataObjects;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
import org.apache.gravitino.catalog.CatalogManager;
+import org.apache.gravitino.catalog.CatalogTestUtils;
import org.apache.gravitino.connector.BaseCatalog;
import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
import org.apache.gravitino.exceptions.IllegalRoleException;
@@ -176,7 +177,7 @@ public class TestAccessControlManagerForPermissions {
GravitinoEnv.getInstance(), "accessControlDispatcher", accessControlManager, true);
FieldUtils.writeField(GravitinoEnv.getInstance(), "catalogManager", catalogManager, true);
BaseCatalog catalog = Mockito.mock(BaseCatalog.class);
- Mockito.when(catalogManager.loadCatalog(any())).thenReturn(catalog);
+ CatalogTestUtils.mockDoWithCatalog(catalogManager, catalog);
Mockito.when(catalogManager.listCatalogs(Mockito.any()))
.thenReturn(new NameIdentifier[] {NameIdentifier.of("metalake", "catalog")});
authorizationPlugin = Mockito.mock(AuthorizationPlugin.class);
diff --git a/core/src/test/java/org/apache/gravitino/authorization/TestAuthorizationUtils.java b/core/src/test/java/org/apache/gravitino/authorization/TestAuthorizationUtils.java
index 01136cc7f7..102d4854a7 100644
--- a/core/src/test/java/org/apache/gravitino/authorization/TestAuthorizationUtils.java
+++ b/core/src/test/java/org/apache/gravitino/authorization/TestAuthorizationUtils.java
@@ -34,6 +34,7 @@ import org.apache.gravitino.Namespace;
import org.apache.gravitino.Schema;
import org.apache.gravitino.catalog.CatalogDispatcher;
import org.apache.gravitino.catalog.CatalogManager;
+import org.apache.gravitino.catalog.CatalogTestUtils;
import org.apache.gravitino.catalog.SchemaDispatcher;
import org.apache.gravitino.catalog.TableDispatcher;
import org.apache.gravitino.connector.BaseCatalog;
@@ -339,7 +340,7 @@ class TestAuthorizationUtils {
AccessControlDispatcher accessControlDispatcher = Mockito.mock(AccessControlDispatcher.class);
CatalogManager catalogManager = Mockito.mock(CatalogManager.class);
BaseCatalog<?> baseCatalog = Mockito.mock(BaseCatalog.class);
- Mockito.when(catalogManager.loadCatalog(Mockito.any())).thenReturn(baseCatalog);
+ CatalogTestUtils.mockDoWithCatalog(catalogManager, baseCatalog);
GravitinoEnv envMock = Mockito.mock(GravitinoEnv.class);
Mockito.when(envMock.gravitinoAuthorizer()).thenReturn(authorizer);
@@ -386,14 +387,13 @@ class TestAuthorizationUtils {
@Test
void testRenameTablePrivilegesNotifiesAuthorizationPluginWithExpectedChange() {
NameIdentifier ident = NameIdentifier.of("metalake", "catalog", "schema", "table");
- NameIdentifier catalogIdent = NameIdentifier.of("metalake", "catalog");
List<String> locations = Lists.newArrayList("/warehouse/schema/table");
AccessControlDispatcher accessControlDispatcher = Mockito.mock(AccessControlDispatcher.class);
CatalogManager catalogManager = Mockito.mock(CatalogManager.class);
BaseCatalog<?> baseCatalog = Mockito.mock(BaseCatalog.class);
AuthorizationPlugin authorizationPlugin = Mockito.mock(AuthorizationPlugin.class);
- Mockito.when(catalogManager.loadCatalog(catalogIdent)).thenReturn(baseCatalog);
+ CatalogTestUtils.mockDoWithCatalog(catalogManager, baseCatalog);
Mockito.when(baseCatalog.getAuthorizationPlugin()).thenReturn(authorizationPlugin);
GravitinoEnv envMock = Mockito.mock(GravitinoEnv.class);
@@ -426,14 +426,13 @@ class TestAuthorizationUtils {
@Test
void testRemoveTablePrivilegesNotifiesAuthorizationPluginWithExpectedChange() {
NameIdentifier ident = NameIdentifier.of("metalake", "catalog", "schema", "table");
- NameIdentifier catalogIdent = NameIdentifier.of("metalake", "catalog");
List<String> locations = Lists.newArrayList("/warehouse/schema/table");
AccessControlDispatcher accessControlDispatcher = Mockito.mock(AccessControlDispatcher.class);
CatalogManager catalogManager = Mockito.mock(CatalogManager.class);
BaseCatalog<?> baseCatalog = Mockito.mock(BaseCatalog.class);
AuthorizationPlugin authorizationPlugin = Mockito.mock(AuthorizationPlugin.class);
- Mockito.when(catalogManager.loadCatalog(catalogIdent)).thenReturn(baseCatalog);
+ CatalogTestUtils.mockDoWithCatalog(catalogManager, baseCatalog);
Mockito.when(baseCatalog.getAuthorizationPlugin()).thenReturn(authorizationPlugin);
GravitinoEnv envMock = Mockito.mock(GravitinoEnv.class);
diff --git a/core/src/test/java/org/apache/gravitino/authorization/TestOwnerManager.java b/core/src/test/java/org/apache/gravitino/authorization/TestOwnerManager.java
index 936d5336a7..9bdb976327 100644
--- a/core/src/test/java/org/apache/gravitino/authorization/TestOwnerManager.java
+++ b/core/src/test/java/org/apache/gravitino/authorization/TestOwnerManager.java
@@ -36,7 +36,6 @@ import static org.apache.gravitino.Configs.TREE_LOCK_CLEAN_INTERVAL;
import static org.apache.gravitino.Configs.TREE_LOCK_MAX_NODE_IN_MEMORY;
import static org.apache.gravitino.Configs.TREE_LOCK_MIN_NODE_IN_MEMORY;
import static org.apache.gravitino.Configs.VERSION_RETENTION_COUNT;
-import static org.mockito.ArgumentMatchers.any;
import com.google.common.collect.Lists;
import java.io.File;
@@ -58,6 +57,7 @@ import org.apache.gravitino.MetadataObjects;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
import org.apache.gravitino.catalog.CatalogManager;
+import org.apache.gravitino.catalog.CatalogTestUtils;
import org.apache.gravitino.connector.BaseCatalog;
import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
import org.apache.gravitino.exceptions.NoSuchMetadataObjectException;
@@ -173,7 +173,7 @@ public class TestOwnerManager {
ownerManager = new OwnerManager(entityStore);
BaseCatalog catalog = Mockito.mock(BaseCatalog.class);
- Mockito.when(catalogManager.loadCatalog(any())).thenReturn(catalog);
+ CatalogTestUtils.mockDoWithCatalog(catalogManager, catalog);
Mockito.when(catalogManager.listCatalogs(Mockito.any()))
.thenReturn(new NameIdentifier[] {NameIdentifier.of("metalake", "catalog")});
Mockito.when(catalog.getAuthorizationPlugin()).thenReturn(authorizationPlugin);
diff --git a/core/src/test/java/org/apache/gravitino/catalog/CatalogTestUtils.java b/core/src/test/java/org/apache/gravitino/catalog/CatalogTestUtils.java
new file mode 100644
index 0000000000..5e948f1707
--- /dev/null
+++ b/core/src/test/java/org/apache/gravitino/catalog/CatalogTestUtils.java
@@ -0,0 +1,69 @@
+/*
+ * 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;
+
+import org.apache.gravitino.connector.BaseCatalog;
+import org.apache.gravitino.utils.ThrowableFunction;
+import org.mockito.Mockito;
+
+/** Test-only helpers for catalog internals that are package-private in production code. */
+public final class CatalogTestUtils {
+
+ private CatalogTestUtils() {}
+
+ /**
+ * Stubs a mocked manager so {@link CatalogManager#doWithCatalog} invokes its callback with the
+ * supplied catalog.
+ *
+ * @param catalogManager the mocked catalog manager.
+ * @param catalog the live catalog to pass to callbacks.
+ */
+ /**
+ * Stubs a mocked {@link CatalogManager.CatalogWrapper} so that detaching a connector result
+ * behaves like the real one instead of returning null.
+ *
+ * <p>{@code OperationDispatcher.doWithCatalog} routes every result through the wrapper, so a
+ * mocked wrapper without this stub makes each dispatcher call under test return null.
+ *
+ * @param wrapper the mocked catalog wrapper.
+ * @return the same wrapper, for chaining.
+ */
+ public static CatalogManager.CatalogWrapper mockDetachConnectorResult(
+ CatalogManager.CatalogWrapper wrapper) {
+ try {
+ Mockito.doAnswer(invocation -> ConnectorObjectSnapshot.detach(invocation.getArgument(0)))
+ .when(wrapper)
+ .detachConnectorResult(Mockito.any());
+ } catch (Exception e) {
+ throw new IllegalStateException("Failed to stub detachConnectorResult", e);
+ }
+ return wrapper;
+ }
+
+ @SuppressWarnings("unchecked")
+ public static void mockDoWithCatalog(CatalogManager catalogManager, BaseCatalog<?> catalog) {
+ Mockito.doAnswer(
+ invocation -> {
+ ThrowableFunction<BaseCatalog, Object> operation = invocation.getArgument(1);
+ return operation.apply(catalog);
+ })
+ .when(catalogManager)
+ .doWithCatalog(Mockito.any(), Mockito.any());
+ }
+}
diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestCapabilityHelpers.java b/core/src/test/java/org/apache/gravitino/catalog/TestCapabilityHelpers.java
index f576db0099..7b16498d87 100644
--- a/core/src/test/java/org/apache/gravitino/catalog/TestCapabilityHelpers.java
+++ b/core/src/test/java/org/apache/gravitino/catalog/TestCapabilityHelpers.java
@@ -21,8 +21,10 @@ package org.apache.gravitino.catalog;
import java.util.Locale;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
+import org.apache.gravitino.connector.BaseCatalog;
import org.apache.gravitino.connector.capability.Capability;
import org.apache.gravitino.connector.capability.CapabilityResult;
+import org.apache.gravitino.exceptions.NoSuchCatalogException;
import org.apache.gravitino.rel.expressions.literals.Literal;
import org.apache.gravitino.rel.expressions.literals.Literals;
import org.apache.gravitino.rel.partitions.IdentityPartition;
@@ -30,6 +32,7 @@ import org.apache.gravitino.rel.partitions.Partition;
import org.apache.gravitino.rel.partitions.Partitions;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
public class TestCapabilityHelpers {
@@ -143,6 +146,38 @@ public class TestCapabilityHelpers {
Assertions.assertEquals("My Table", result.name());
}
+ @Test
+ void testGetCapabilityPropagatesNoSuchCatalogException() {
+ NameIdentifier tableIdent =
+ NameIdentifier.of(Namespace.of("metalake", "catalog", "schema"), "table");
+ CatalogManager catalogManager = Mockito.mock(CatalogManager.class);
+ Mockito.when(catalogManager.doWithCatalog(Mockito.any(), Mockito.any()))
+ .thenThrow(new NoSuchCatalogException("Catalog %s does not exist", tableIdent));
+
+ // A missing catalog must stay a NoSuchCatalogException (mapped to 404 by the REST layer)
+ // instead of being wrapped into a plain RuntimeException (a 500).
+ Assertions.assertThrows(
+ NoSuchCatalogException.class,
+ () -> CapabilityHelpers.getCapability(tableIdent, catalogManager));
+ }
+
+ @Test
+ void testGetCapabilityWrapsCapabilityFailure() throws Exception {
+ NameIdentifier tableIdent =
+ NameIdentifier.of(Namespace.of("metalake", "catalog", "schema"), "table");
+ CatalogManager catalogManager = Mockito.mock(CatalogManager.class);
+ BaseCatalog<?> catalog = Mockito.mock(BaseCatalog.class);
+ CatalogTestUtils.mockDoWithCatalog(catalogManager, catalog);
+ Mockito.when(catalog.capability()).thenThrow(new IllegalStateException("boom"));
+
+ RuntimeException e =
+ Assertions.assertThrows(
+ RuntimeException.class,
+ () -> CapabilityHelpers.getCapability(tableIdent, catalogManager));
+
+ Assertions.assertInstanceOf(IllegalStateException.class, e.getCause());
+ }
+
@Test
void testSemanticModelUsesSchemaNamespaceCapabilities() {
Namespace namespace = Namespace.of("metalake", "catalog", "mixedSchema");
diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestCatalogManager.java b/core/src/test/java/org/apache/gravitino/catalog/TestCatalogManager.java
index 26380a5833..90dff3e5e0 100644
--- a/core/src/test/java/org/apache/gravitino/catalog/TestCatalogManager.java
+++ b/core/src/test/java/org/apache/gravitino/catalog/TestCatalogManager.java
@@ -727,6 +727,9 @@ public class TestCatalogManager {
catalogManager.createCatalog(ident, Catalog.Type.RELATIONAL, provider, "comment", props);
Catalog catalog = catalogManager.loadCatalog(ident);
+ Assertions.assertFalse(
+ catalog instanceof BaseCatalog,
+ "loadCatalog must not expose a live catalog after its lease is released");
Assertions.assertEquals("test21", catalog.name());
Assertions.assertEquals("comment", catalog.comment());
testProperties(props, catalog.properties());
@@ -813,10 +816,8 @@ public class TestCatalogManager {
PROPERTY_KEY5_PREFIX + "1",
"value3");
- Catalog catalog =
- catalogManager.createCatalog(ident, Catalog.Type.RELATIONAL, provider, "comment", props);
- CatalogEntity originalEntity = entityStore.get(ident, EntityType.CATALOG, CatalogEntity.class);
- FieldUtils.writeField(catalog, "entity", originalEntity, true);
+ catalogManager.createCatalog(ident, Catalog.Type.RELATIONAL, provider, "comment", props);
+ BaseCatalog<?> catalog = catalogManager.loadCatalogAndWrap(ident).catalog();
CatalogManager.CatalogWrapper staleWrapper =
Mockito.mock(CatalogManager.CatalogWrapper.class, Mockito.RETURNS_DEEP_STUBS);
@@ -825,8 +826,11 @@ public class TestCatalogManager {
CatalogManager.CatalogWrapper freshWrapper =
Mockito.mock(CatalogManager.CatalogWrapper.class, Mockito.RETURNS_DEEP_STUBS);
BaseCatalog<?> freshCatalog = Mockito.mock(BaseCatalog.class);
- Mockito.doReturn("cache_race_test_renamed").when(freshCatalog).name();
+ Catalog freshCatalogInfo = Mockito.mock(Catalog.class);
+ Mockito.doReturn("cache_race_test_renamed").when(freshCatalogInfo).name();
Mockito.doReturn(freshCatalog).when(freshWrapper).catalog();
+ Mockito.doReturn(true).when(freshWrapper).tryAcquire();
+ Mockito.doReturn(freshCatalogInfo).when(freshWrapper).doWithCatalog(any());
AtomicBoolean staleInserted = new AtomicBoolean(false);
Answer<CatalogManager.CatalogWrapper> insertStaleWrapper =
@@ -967,6 +971,19 @@ public class TestCatalogManager {
Assertions.assertSame(registeredListener, store.unregisteredListener.get());
}
+ @Test
+ void testCloseCompletesWhenChangeLogUnregistrationFails() {
+ ChangeLogAwareEntityStore store = new ChangeLogAwareEntityStore();
+ store.throwOnUnregister = true;
+ CatalogManager manager =
+ new CatalogManager(config, store, new RandomIdGenerator(), new SecretManager(config));
+
+ Assertions.assertDoesNotThrow(manager::close);
+ Assertions.assertThrows(
+ IllegalStateException.class,
+ () -> manager.loadCatalogAndWrap(NameIdentifier.of("metalake", "catalog")));
+ }
+
@Test
void testDropCatalogDoesNotMarkLocalMutationWhenStoreReturnsFalse() throws Exception {
ChangeLogAwareEntityStore store = new ChangeLogAwareEntityStore();
@@ -1116,12 +1133,10 @@ public class TestCatalogManager {
"value3");
String comment = "comment";
- Catalog catalog =
- catalogManager.createCatalog(ident, Catalog.Type.RELATIONAL, provider, comment, props);
+ catalogManager.createCatalog(ident, Catalog.Type.RELATIONAL, provider, comment, props);
Mockito.doCallRealMethod().when(catalogManager).loadCatalogAndWrap(ident);
Assertions.assertDoesNotThrow(() -> catalogManager.disableCatalog(ident));
- CatalogEntity catalogEntity = entityStore.get(ident, EntityType.CATALOG, CatalogEntity.class);
- FieldUtils.writeField(catalog, "entity", catalogEntity, true);
+ BaseCatalog<?> catalog = catalogManager.loadCatalogAndWrap(ident).catalog();
SchemaEntity importedSchemaEntity =
SchemaEntity.builder()
@@ -1144,7 +1159,7 @@ public class TestCatalogManager {
CatalogManager.CatalogWrapper wrapper = Mockito.mock(CatalogManager.CatalogWrapper.class);
Capability capability = Mockito.mock(Capability.class);
CapabilityResult unsupportedResult = CapabilityResult.unsupported("Not managed");
- Mockito.doReturn(wrapper).when(catalogManager).loadCatalogAndWrap(ident);
+ Mockito.when(wrapper.tryAcquire()).thenReturn(true);
Mockito.doReturn(catalog).when(wrapper).catalog();
Mockito.doReturn(capability).when(wrapper).capabilities();
Mockito.doReturn(unsupportedResult).when(capability).managedStorage(any());
@@ -1153,6 +1168,7 @@ public class TestCatalogManager {
.doReturn(importedSchema)
.when(wrapper)
.doWithSchemaOps(any());
+ catalogManager.getCatalogCache().put(ident, wrapper);
// Imported schema (no StringIdentifier in external catalog properties) should not block drop.
Assertions.assertTrue(catalogManager.dropCatalog(ident));
@@ -1165,6 +1181,7 @@ public class TestCatalogManager {
new AtomicReference<>();
private boolean returnFalseForCatalogDelete;
private boolean throwMissingCatalogForSchemaList;
+ private boolean throwOnUnregister;
@Override
public boolean delete(NameIdentifier ident, EntityType entityType, boolean cascade)
@@ -1197,6 +1214,9 @@ public class TestCatalogManager {
@Override
public void unregisterEntityChangeLogListener(EntityChangeLogListener listener) {
this.unregisteredListener.set(listener);
+ if (throwOnUnregister) {
+ throw new RuntimeException("Failed to unregister listener");
+ }
}
}
@@ -1215,12 +1235,10 @@ public class TestCatalogManager {
"value3");
String comment = "comment";
- Catalog catalog =
- catalogManager.createCatalog(ident, Catalog.Type.RELATIONAL, provider, comment, props);
+ catalogManager.createCatalog(ident, Catalog.Type.RELATIONAL, provider, comment, props);
Mockito.doCallRealMethod().when(catalogManager).loadCatalogAndWrap(ident);
Assertions.assertDoesNotThrow(() -> catalogManager.disableCatalog(ident));
- CatalogEntity catalogEntity = entityStore.get(ident, EntityType.CATALOG, CatalogEntity.class);
- FieldUtils.writeField(catalog, "entity", catalogEntity, true);
+ BaseCatalog<?> catalog = catalogManager.loadCatalogAndWrap(ident).catalog();
SchemaEntity schemaEntity =
SchemaEntity.builder()
@@ -1238,7 +1256,7 @@ public class TestCatalogManager {
CatalogManager.CatalogWrapper wrapper = Mockito.mock(CatalogManager.CatalogWrapper.class);
Capability capability = Mockito.mock(Capability.class);
CapabilityResult unsupportedResult = CapabilityResult.unsupported("Not managed");
- Mockito.doReturn(wrapper).when(catalogManager).loadCatalogAndWrap(ident);
+ Mockito.when(wrapper.tryAcquire()).thenReturn(true);
Mockito.doReturn(catalog).when(wrapper).catalog();
Mockito.doReturn(capability).when(wrapper).capabilities();
Mockito.doReturn(unsupportedResult).when(capability).managedStorage(any());
@@ -1246,6 +1264,7 @@ public class TestCatalogManager {
.doThrow(new NoSuchSchemaException("Schema not found"))
.when(wrapper)
.doWithSchemaOps(any());
+ catalogManager.getCatalogCache().put(ident, wrapper);
// Schema disappearing between listSchemas and loadSchema should not block drop.
Assertions.assertTrue(catalogManager.dropCatalog(ident));
@@ -1266,12 +1285,10 @@ public class TestCatalogManager {
"value3");
String comment = "comment";
- Catalog catalog =
- catalogManager.createCatalog(ident, Catalog.Type.RELATIONAL, provider, comment, props);
+ catalogManager.createCatalog(ident, Catalog.Type.RELATIONAL, provider, comment, props);
Mockito.doCallRealMethod().when(catalogManager).loadCatalogAndWrap(ident);
Assertions.assertDoesNotThrow(() -> catalogManager.disableCatalog(ident));
- CatalogEntity catalogEntity = entityStore.get(ident, EntityType.CATALOG, CatalogEntity.class);
- FieldUtils.writeField(catalog, "entity", catalogEntity, true);
+ BaseCatalog<?> catalog = catalogManager.loadCatalogAndWrap(ident).catalog();
SchemaEntity schemaEntity =
SchemaEntity.builder()
@@ -1289,7 +1306,7 @@ public class TestCatalogManager {
CatalogManager.CatalogWrapper wrapper = Mockito.mock(CatalogManager.CatalogWrapper.class);
Capability capability = Mockito.mock(Capability.class);
CapabilityResult unsupportedResult = CapabilityResult.unsupported("Not managed");
- Mockito.doReturn(wrapper).when(catalogManager).loadCatalogAndWrap(ident);
+ Mockito.when(wrapper.tryAcquire()).thenReturn(true);
Mockito.doReturn(catalog).when(wrapper).catalog();
Mockito.doReturn(capability).when(wrapper).capabilities();
Mockito.doReturn(unsupportedResult).when(capability).managedStorage(any());
@@ -1297,6 +1314,7 @@ public class TestCatalogManager {
.doThrow(new RuntimeException("Failed connect"))
.when(wrapper)
.doWithSchemaOps(any());
+ catalogManager.getCatalogCache().put(ident, wrapper);
// Unexpected errors during schema classification should propagate (fail-closed).
RuntimeException ex =
@@ -1318,8 +1336,8 @@ public class TestCatalogManager {
PROPERTY_KEY5_PREFIX + "1",
"value3");
String comment = "comment";
- Catalog catalog =
- catalogManager.createCatalog(ident, Catalog.Type.RELATIONAL, provider, comment, props);
+ catalogManager.createCatalog(ident, Catalog.Type.RELATIONAL, provider, comment, props);
+ BaseCatalog<?> catalog = catalogManager.loadCatalogAndWrap(ident).catalog();
SchemaEntity schemaEntity =
SchemaEntity.builder()
.withId(RandomIdGenerator.INSTANCE.nextId())
@@ -1336,13 +1354,14 @@ public class TestCatalogManager {
Mockito.mock(CatalogManager.CatalogWrapper.class);
Capability capability = Mockito.mock(Capability.class);
CapabilityResult unsupportedResult = CapabilityResult.unsupported("Not managed");
- Mockito.doReturn(catalogWrapper).when(catalogManager).loadCatalogAndWrap(ident);
+ Mockito.when(catalogWrapper.tryAcquire()).thenReturn(true);
Mockito.doReturn(capability).when(catalogWrapper).capabilities();
Mockito.doReturn(unsupportedResult).when(capability).managedStorage(any());
Mockito.doReturn(catalog).when(catalogWrapper).catalog();
Mockito.doThrow(new RuntimeException("Failed connect"))
.when(catalogWrapper)
.doWithSchemaOps(any());
+ catalogManager.getCatalogCache().put(ident, catalogWrapper);
Assertions.assertTrue(catalogManager.dropCatalog(ident, true));
}
@@ -1360,21 +1379,19 @@ public class TestCatalogManager {
PROPERTY_KEY5_PREFIX + "1",
"value3");
- Catalog catalog =
- catalogManager.createCatalog(ident, Catalog.Type.RELATIONAL, provider, "comment", props);
+ catalogManager.createCatalog(ident, Catalog.Type.RELATIONAL, provider, "comment", props);
Assertions.assertDoesNotThrow(() -> catalogManager.disableCatalog(ident));
- CatalogEntity entity = entityStore.get(ident, EntityType.CATALOG, CatalogEntity.class);
- FieldUtils.writeField(catalog, "entity", entity, true);
+ BaseCatalog<?> catalog = catalogManager.loadCatalogAndWrap(ident).catalog();
CatalogManager.CatalogWrapper catalogWrapper =
Mockito.mock(CatalogManager.CatalogWrapper.class, Mockito.RETURNS_DEEP_STUBS);
Capability capability = Mockito.mock(Capability.class);
CapabilityResult unsupportedResult = CapabilityResult.unsupported("Not managed");
+ Mockito.when(catalogWrapper.tryAcquire()).thenReturn(true);
CatalogOperations operations =
Mockito.mock(
CatalogOperations.class,
Mockito.withSettings().extraInterfaces(CatalogDropAware.class));
- Mockito.doReturn(catalogWrapper).when(catalogManager).loadCatalogAndWrap(ident);
Mockito.doReturn(catalog).when(catalogWrapper).catalog();
Mockito.doReturn(capability).when(catalogWrapper).capabilities();
Mockito.doReturn(unsupportedResult).when(capability).managedStorage(any());
@@ -1409,11 +1426,8 @@ public class TestCatalogManager {
PROPERTY_KEY5_PREFIX + "1",
"value3");
- Catalog catalog =
- catalogManager.createCatalog(ident, Catalog.Type.RELATIONAL, provider, "comment", props);
+ catalogManager.createCatalog(ident, Catalog.Type.RELATIONAL, provider, "comment", props);
Assertions.assertDoesNotThrow(() -> catalogManager.disableCatalog(ident));
- CatalogEntity entity = entityStore.get(ident, EntityType.CATALOG, CatalogEntity.class);
- FieldUtils.writeField(catalog, "entity", entity, true);
CatalogManager.CatalogWrapper closedWrapper = catalogManager.loadCatalogAndWrap(ident);
closedWrapper.close();
@@ -1430,20 +1444,23 @@ public class TestCatalogManager {
void testLoadCatalogAndWrapDoesNotInvalidateConcurrentlyReloadedWrapper() {
NameIdentifier ident = NameIdentifier.of("metalake", "concurrent_cache_reload_test");
- CatalogManager.CatalogWrapper closedWrapper = Mockito.mock(CatalogManager.CatalogWrapper.class);
+ CatalogManager.CatalogWrapper retiredWrapper =
+ Mockito.mock(CatalogManager.CatalogWrapper.class);
CatalogManager.CatalogWrapper freshWrapper = Mockito.mock(CatalogManager.CatalogWrapper.class);
BaseCatalog<?> freshCatalog = Mockito.mock(BaseCatalog.class);
Mockito.doReturn(freshCatalog).when(freshWrapper).catalog();
+ // The retired wrapper reports its state only after another thread has already reloaded a fresh
+ // wrapper into the cache, so the stale-entry eviction must not clobber that fresh wrapper.
Mockito.doAnswer(
invocation -> {
catalogManager.getCatalogCache().put(ident, freshWrapper);
- return null;
+ return true;
})
- .when(closedWrapper)
- .catalog();
+ .when(retiredWrapper)
+ .isRetired();
try {
- catalogManager.getCatalogCache().put(ident, closedWrapper);
+ catalogManager.getCatalogCache().put(ident, retiredWrapper);
CatalogManager.CatalogWrapper loadedWrapper = catalogManager.loadCatalogAndWrap(ident);
@@ -1520,7 +1537,9 @@ public class TestCatalogManager {
CountDownLatch writeLockAcquired = new CountDownLatch(1);
ExecutorService executor = Executors.newFixedThreadPool(2);
- Mockito.doReturn(wrapper).when(catalogManager).loadCatalogAndWrap(ident);
+ Mockito.doAnswer(invocation -> new CatalogLease(wrapper))
+ .when(catalogManager)
+ .acquireCatalogLease(ident);
Mockito.doReturn(catalog).when(wrapper).catalog();
Mockito.doAnswer(
invocation -> {
@@ -1803,6 +1822,7 @@ public class TestCatalogManager {
CatalogEntity storedAfter = entityStore.get(ident, EntityType.CATALOG, CatalogEntity.class);
Assertions.assertEquals(stored.getProperties(), storedAfter.getProperties());
Assertions.assertEquals("stored-secret", secrets.readSecret(SecretUrn.parse(storedUrn)));
+ Mockito.verify(manager, Mockito.times(4)).acquireCatalogLease(ident);
Mockito.verify(temporaryWrapper, Mockito.times(3)).close();
}
}
diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestCatalogWrapperLease.java b/core/src/test/java/org/apache/gravitino/catalog/TestCatalogWrapperLease.java
new file mode 100644
index 0000000000..a524795e5f
--- /dev/null
+++ b/core/src/test/java/org/apache/gravitino/catalog/TestCatalogWrapperLease.java
@@ -0,0 +1,687 @@
+/*
+ * 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;
+
+import static org.awaitility.Awaitility.await;
+
+import com.google.common.collect.ImmutableMap;
+import java.io.IOException;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+import org.apache.commons.lang3.reflect.FieldUtils;
+import org.apache.gravitino.Catalog;
+import org.apache.gravitino.CatalogChange;
+import org.apache.gravitino.Config;
+import org.apache.gravitino.Configs;
+import org.apache.gravitino.GravitinoEnv;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.catalog.CatalogManager.CatalogWrapper;
+import org.apache.gravitino.connector.BaseCatalog;
+import org.apache.gravitino.lock.LockManager;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.BaseMetalake;
+import org.apache.gravitino.meta.SchemaVersion;
+import org.apache.gravitino.secret.SecretManager;
+import org.apache.gravitino.storage.RandomIdGenerator;
+import org.apache.gravitino.storage.memory.TestMemoryEntityStore;
+import org.apache.gravitino.storage.memory.TestMemoryEntityStore.InMemoryEntityStore;
+import org.apache.gravitino.storage.relational.po.cache.EntityChangeRecord;
+import org.apache.gravitino.storage.relational.po.cache.OperateType;
+import org.apache.gravitino.utils.ClassLoaderPool;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+
+/**
+ * Tests that a catalog wrapper evicted from the catalog cache is not torn down while an operation
+ * is still using it. Cache eviction (expiry, explicit invalidation, remote change-log invalidation,
+ * and drop) must only retire the wrapper; the catalog and the ClassLoader are cleaned up when the
+ * last lease is released, exactly once.
+ */
+public class TestCatalogWrapperLease {
+
+ private static final String METALAKE = "metalake";
+ private static final String PROVIDER = "test";
+ private static final Map<String, String> PROPS =
+ ImmutableMap.of("key1", "value1", "key2", "value2", "key5-1", "value3");
+
+ private static final BaseMetalake METALAKE_ENTITY =
+ BaseMetalake.builder()
+ .withId(1L)
+ .withName(METALAKE)
+ .withAuditInfo(
+ AuditInfo.builder().withCreator("test").withCreateTime(Instant.now()).build())
+ .withVersion(SchemaVersion.V_0_1)
+ .build();
+
+ private static Config config;
+ private static InMemoryEntityStore entityStore;
+
+ private CatalogManager catalogManager;
+
+ @BeforeAll
+ public static void setUp() throws IOException, IllegalAccessException {
+ config = new Config(false) {};
+ config.set(Configs.CATALOG_LOAD_ISOLATED, false);
+
+ entityStore = new TestMemoryEntityStore.InMemoryEntityStore();
+ entityStore.initialize(config);
+ entityStore.put(METALAKE_ENTITY, true);
+
+ FieldUtils.writeField(GravitinoEnv.getInstance(), "lockManager", new LockManager(config), true);
+ }
+
+ @AfterAll
+ public static void tearDown() throws IOException {
+ if (entityStore != null) {
+ entityStore.close();
+ entityStore = null;
+ }
+ }
+
+ @BeforeEach
+ public void beforeEach() {
+ catalogManager =
+ new CatalogManager(config, entityStore, new RandomIdGenerator(), new SecretManager(config));
+ }
+
+ @AfterEach
+ public void afterEach() throws IOException {
+ if (catalogManager != null) {
+ catalogManager.close();
+ catalogManager = null;
+ }
+ entityStore.clear();
+ entityStore.put(METALAKE_ENTITY, true);
+ }
+
+ @Test
+ public void testCacheInvalidationDefersCleanupUntilLeaseIsReleased() throws Exception {
+ NameIdentifier ident = createCatalog("invalidate_with_lease");
+
+ CatalogLease lease = catalogManager.acquireCatalogLease(ident);
+ CatalogWrapper wrapper = lease.wrapper();
+ Assertions.assertEquals(1, wrapper.activeOperations());
+
+ catalogManager.getCatalogCache().invalidate(ident);
+ // Caffeine runs the removal listener asynchronously, so wait for the retirement to land.
+ await().atMost(Duration.ofSeconds(10)).until(wrapper::isRetired);
+
+ Assertions.assertTrue(wrapper.isRetired(), "eviction must retire the wrapper");
+ Assertions.assertNotNull(
+ wrapper.catalog(), "a leased wrapper must not be closed by cache eviction");
+ // The leased wrapper is still fully usable: this is the operation that used to fail with an
+ // NPE (or NoClassDefFoundError) once the removal listener closed the wrapper underneath it.
+ Assertions.assertDoesNotThrow(
+ () ->
+ wrapper.doWithSchemaOps(ops -> ops.listSchemas(Namespace.of(METALAKE, ident.name()))));
+
+ lease.close();
+ // Closing the same lease twice must not double-release the active-operation count.
+ lease.close();
+
+ Assertions.assertEquals(0, wrapper.activeOperations());
+ Assertions.assertNull(wrapper.catalog(), "the last lease release must clean up the catalog");
+ }
+
+ @Test
+ public void testCacheExpiryDefersCleanupUntilLeaseIsReleased() throws Exception {
+ Config expiringConfig = new Config(false) {};
+ expiringConfig.set(Configs.CATALOG_LOAD_ISOLATED, false);
+ expiringConfig.set(Configs.CATALOG_CACHE_EVICTION_INTERVAL_MS, 1L);
+
+ CatalogManager expiringManager =
+ new CatalogManager(
+ expiringConfig,
+ entityStore,
+ new RandomIdGenerator(),
+ new SecretManager(expiringConfig));
+ try {
+ NameIdentifier ident = NameIdentifier.of(METALAKE, "expiring_catalog");
+ expiringManager.createCatalog(ident, Catalog.Type.RELATIONAL, PROVIDER, "comment", PROPS);
+
+ try (CatalogLease lease = expiringManager.acquireCatalogLease(ident)) {
+ CatalogWrapper wrapper = lease.wrapper();
+
+ await().atMost(Duration.ofSeconds(10)).until(wrapper::isRetired);
+
+ Assertions.assertNull(expiringManager.getCatalogCache().getIfPresent(ident));
+ Assertions.assertNotNull(
+ wrapper.catalog(), "a leased wrapper must survive cache expiration");
+ Assertions.assertDoesNotThrow(
+ () ->
+ wrapper.doWithSchemaOps(
+ ops -> ops.listSchemas(Namespace.of(METALAKE, ident.name()))));
+ }
+ } finally {
+ expiringManager.close();
+ }
+ }
+
+ @Test
+ public void testRemoteChangeLogInvalidationDefersCleanupUntilLeaseIsReleased() throws Exception {
+ NameIdentifier ident = createCatalog("remote_invalidation");
+
+ try (CatalogLease lease = catalogManager.acquireCatalogLease(ident)) {
+ CatalogWrapper wrapper = lease.wrapper();
+
+ new CatalogChangeLogListener(catalogManager)
+ .onEntityChange(
+ List.of(
+ new EntityChangeRecord(
+ 1L,
+ METALAKE,
+ "CATALOG",
+ METALAKE + "." + ident.name(),
+ OperateType.ALTER,
+ 0L)));
+
+ Assertions.assertNull(catalogManager.getCatalogCache().getIfPresent(ident));
+ await().atMost(Duration.ofSeconds(10)).until(wrapper::isRetired);
+ Assertions.assertTrue(wrapper.isRetired());
+ Assertions.assertNotNull(
+ wrapper.catalog(), "a leased wrapper must survive remote change-log invalidation");
+ Assertions.assertDoesNotThrow(
+ () ->
+ wrapper.doWithSchemaOps(
+ ops -> ops.listSchemas(Namespace.of(METALAKE, ident.name()))));
+ }
+ }
+
+ @Test
+ public void testDropCatalogDefersCleanupUntilLeaseIsReleased() throws Exception {
+ NameIdentifier ident = createCatalog("drop_with_lease");
+
+ CatalogLease lease = catalogManager.acquireCatalogLease(ident);
+ CatalogWrapper wrapper = lease.wrapper();
+
+ catalogManager.disableCatalog(ident);
+ Assertions.assertTrue(catalogManager.dropCatalog(ident));
+
+ Assertions.assertNotNull(wrapper.catalog(), "a leased wrapper must survive a concurrent drop");
+ // Caffeine runs the removal listener asynchronously, so wait for the retirement to land before
+ // releasing the lease that defers the cleanup.
+ await().atMost(Duration.ofSeconds(10)).until(wrapper::isRetired);
+ lease.close();
+ Assertions.assertNull(wrapper.catalog());
+ }
+
+ @Test
+ public void testAcquireLeaseReloadsRetiredWrapper() throws Exception {
+ NameIdentifier ident = createCatalog("retired_reload");
+
+ CatalogWrapper retiredWrapper = catalogManager.getCatalogCache().getIfPresent(ident);
+ Assertions.assertNotNull(retiredWrapper);
+ retiredWrapper.retire();
+
+ try (CatalogLease lease = catalogManager.acquireCatalogLease(ident)) {
+ Assertions.assertNotSame(
+ retiredWrapper, lease.wrapper(), "a retired wrapper must not be leased again");
+ Assertions.assertFalse(lease.wrapper().isRetired());
+ Assertions.assertNotNull(lease.catalog());
+ }
+ }
+
+ @Test
+ public void testConcurrentLeaseAcquisitionsLoadOneWrapperPerKey() throws Exception {
+ NameIdentifier ident = createCatalog("concurrent_reload");
+ CatalogWrapper oldWrapper = catalogManager.getCatalogCache().getIfPresent(ident);
+ Assertions.assertNotNull(oldWrapper);
+ catalogManager.getCatalogCache().invalidate(ident);
+ await().atMost(Duration.ofSeconds(10)).until(oldWrapper::isRetired);
+
+ catalogManager = Mockito.spy(catalogManager);
+ CountDownLatch loadStarted = new CountDownLatch(1);
+ CountDownLatch continueLoad = new CountDownLatch(1);
+ Mockito.doAnswer(
+ invocation -> {
+ loadStarted.countDown();
+ Assertions.assertTrue(continueLoad.await(10, TimeUnit.SECONDS));
+ return invocation.callRealMethod();
+ })
+ .when(catalogManager)
+ .createCatalogWrapper(Mockito.any(), Mockito.isNull());
+
+ ExecutorService executor = Executors.newFixedThreadPool(2);
+ try {
+ Future<CatalogLease> first = executor.submit(() -> catalogManager.acquireCatalogLease(ident));
+ Assertions.assertTrue(loadStarted.await(10, TimeUnit.SECONDS));
+ CountDownLatch secondStarted = new CountDownLatch(1);
+ Future<CatalogLease> second =
+ executor.submit(
+ () -> {
+ secondStarted.countDown();
+ return catalogManager.acquireCatalogLease(ident);
+ });
+ Assertions.assertTrue(secondStarted.await(10, TimeUnit.SECONDS));
+ await()
+ .during(Duration.ofMillis(200))
+ .atMost(Duration.ofSeconds(1))
+ .untilAsserted(
+ () ->
+ Mockito.verify(catalogManager, Mockito.times(1))
+ .createCatalogWrapper(Mockito.any(), Mockito.isNull()));
+
+ continueLoad.countDown();
+ try (CatalogLease firstLease = first.get(10, TimeUnit.SECONDS);
+ CatalogLease secondLease = second.get(10, TimeUnit.SECONDS)) {
+ Assertions.assertSame(firstLease.wrapper(), secondLease.wrapper());
+ Mockito.verify(catalogManager, Mockito.times(1))
+ .createCatalogWrapper(Mockito.any(), Mockito.isNull());
+ }
+ } finally {
+ continueLoad.countDown();
+ executor.shutdownNow();
+ }
+ }
+
+ @Test
+ public void testCleanupRunsExactlyOnceForRepeatedRetireAndRelease() throws Exception {
+ // Two catalogs of the same provider share one pooled ClassLoader, so the pool entry survives
+ // as long as exactly one reference is released per wrapper. A double cleanup would drop the
+ // reference count to zero and destroy the ClassLoader the second catalog is still using.
+ NameIdentifier ident1 = createCatalog("exactly_once_1");
+ createCatalog("exactly_once_2");
+
+ ClassLoaderPool pool =
+ (ClassLoaderPool) FieldUtils.readField(catalogManager, "classLoaderPool", true);
+ Assertions.assertEquals(1, pool.size(), "same-provider catalogs share one pooled entry");
+
+ CatalogLease lease = catalogManager.acquireCatalogLease(ident1);
+ CatalogWrapper wrapper = lease.wrapper();
+
+ // Repeated retirements (eviction + explicit invalidation + close) and a lease release must
+ // together release the pooled ClassLoader reference exactly once.
+ wrapper.retire();
+ wrapper.retire();
+ wrapper.close();
+ lease.close();
+ wrapper.retire();
+
+ Assertions.assertNull(wrapper.catalog());
+ Assertions.assertEquals(
+ 1, pool.size(), "the pooled ClassLoader of the second catalog must stay alive");
+ }
+
+ @Test
+ public void testConcurrentEvictionDoesNotCloseCatalogUnderRunningOperation() throws Exception {
+ NameIdentifier ident = createCatalog("concurrent_eviction");
+
+ CountDownLatch leaseAcquired = new CountDownLatch(1);
+ CountDownLatch evicted = new CountDownLatch(1);
+ ExecutorService executor = Executors.newSingleThreadExecutor();
+ try {
+ Future<Boolean> operation =
+ executor.submit(
+ () -> {
+ try (CatalogLease lease = catalogManager.acquireCatalogLease(ident)) {
+ leaseAcquired.countDown();
+ Assertions.assertTrue(evicted.await(10, TimeUnit.SECONDS));
+ // Runs after the wrapper has been evicted from the cache; without a lease the
+ // wrapper's catalog would already be closed here.
+ lease
+ .wrapper()
+ .doWithSchemaOps(
+ ops -> ops.listSchemas(Namespace.of(METALAKE, ident.name())));
+ return true;
+ }
+ });
+
+ Assertions.assertTrue(leaseAcquired.await(10, TimeUnit.SECONDS));
+ CatalogWrapper leasedWrapper = catalogManager.getCatalogCache().getIfPresent(ident);
+ Assertions.assertNotNull(leasedWrapper);
+ catalogManager.getCatalogCache().invalidate(ident);
+ await().atMost(Duration.ofSeconds(10)).until(leasedWrapper::isRetired);
+ evicted.countDown();
+
+ Assertions.assertTrue(operation.get(10, TimeUnit.SECONDS));
+ } finally {
+ executor.shutdownNow();
+ }
+ }
+
+ @Test
+ public void testLeaseCallbackKeepsTheApplicationClassLoader() throws Exception {
+ NameIdentifier ident = createCatalog("callback_classloader");
+ ClassLoader applicationClassLoader = Thread.currentThread().getContextClassLoader();
+
+ ClassLoader[] observed = new ClassLoader[2];
+ catalogManager.doWithCatalogWrapper(
+ ident,
+ wrapper -> {
+ // Gravitino's own work inside the callback, entity-store reads above all, must not run
+ // with a connector ClassLoader installed: MyBatis and DriverManager resolve through the
+ // thread context ClassLoader and a catalog that bundles its own JDBC driver would win.
+ observed[0] = Thread.currentThread().getContextClassLoader();
+ // Connector calls still get the catalog ClassLoader, from the wrapper itself.
+ observed[1] = wrapper.doWithCatalog(c -> Thread.currentThread().getContextClassLoader());
+ return null;
+ });
+
+ Assertions.assertSame(applicationClassLoader, observed[0]);
+ Assertions.assertNotSame(applicationClassLoader, observed[1]);
+ Assertions.assertSame(
+ applicationClassLoader,
+ Thread.currentThread().getContextClassLoader(),
+ "the connector ClassLoader must be restored when the callback returns");
+ }
+
+ @Test
+ public void testDoWithCatalogKeepsLeaseForEntireCallback() throws Exception {
+ NameIdentifier ident = createCatalog("callback_with_lease");
+ CountDownLatch callbackStarted = new CountDownLatch(1);
+ CountDownLatch continueCallback = new CountDownLatch(1);
+ ExecutorService executor = Executors.newSingleThreadExecutor();
+ try {
+ Future<Boolean> operation =
+ executor.submit(
+ () ->
+ catalogManager.doWithCatalog(
+ ident,
+ catalog -> {
+ callbackStarted.countDown();
+ Assertions.assertTrue(continueCallback.await(10, TimeUnit.SECONDS));
+ catalog.ops();
+ return true;
+ }));
+
+ Assertions.assertTrue(callbackStarted.await(10, TimeUnit.SECONDS));
+ CatalogWrapper wrapper = catalogManager.getCatalogCache().getIfPresent(ident);
+ Assertions.assertNotNull(wrapper);
+
+ catalogManager.getCatalogCache().invalidate(ident);
+ await().atMost(Duration.ofSeconds(10)).until(wrapper::isRetired);
+
+ Assertions.assertNotNull(
+ wrapper.catalog(), "the callback lease must survive a concurrent invalidation");
+ continueCallback.countDown();
+ Assertions.assertTrue(operation.get(10, TimeUnit.SECONDS));
+ Assertions.assertNull(wrapper.catalog());
+ } finally {
+ continueCallback.countDown();
+ executor.shutdownNow();
+ }
+ }
+
+ @Test
+ public void testManagerCloseDefersCleanupUntilLeaseIsReleased() throws Exception {
+ NameIdentifier ident = createCatalog("manager_close_with_lease");
+
+ CatalogLease lease = catalogManager.acquireCatalogLease(ident);
+ CatalogWrapper wrapper = lease.wrapper();
+ ClassLoaderPool pool =
+ (ClassLoaderPool) FieldUtils.readField(catalogManager, "classLoaderPool", true);
+
+ catalogManager.close();
+
+ Assertions.assertTrue(wrapper.isRetired());
+ Assertions.assertNotNull(
+ wrapper.catalog(), "manager shutdown must not close a catalog with an active lease");
+ Assertions.assertEquals(
+ 1, pool.size(), "manager shutdown must retain an actively leased ClassLoader");
+ Assertions.assertDoesNotThrow(
+ () ->
+ wrapper.doWithSchemaOps(ops -> ops.listSchemas(Namespace.of(METALAKE, ident.name()))));
+ Assertions.assertThrows(
+ IllegalStateException.class, () -> catalogManager.acquireCatalogLease(ident));
+
+ lease.close();
+
+ Assertions.assertNull(wrapper.catalog());
+ Assertions.assertEquals(0, pool.size());
+ }
+
+ @Test
+ public void testRemovalListenerFailureDoesNotSkipWrapperRetirement() {
+ NameIdentifier ident = createCatalog("failing_removal_listener");
+ CatalogWrapper wrapper = catalogManager.getCatalogCache().getIfPresent(ident);
+ Assertions.assertNotNull(wrapper);
+ catalogManager.addCatalogCacheRemoveListener(
+ ignored -> {
+ throw new RuntimeException("listener failed");
+ });
+
+ catalogManager.getCatalogCache().invalidate(ident);
+
+ await().atMost(Duration.ofSeconds(10)).until(wrapper::isRetired);
+ Assertions.assertNull(
+ wrapper.catalog(), "listener failures must not prevent wrapper resource cleanup");
+ }
+
+ @Test
+ public void testReleaseWithoutAcquireIsRejected() throws Exception {
+ NameIdentifier ident = createCatalog("release_without_acquire");
+ CatalogWrapper wrapper = catalogManager.getCatalogCache().getIfPresent(ident);
+ Assertions.assertNotNull(wrapper);
+
+ Assertions.assertThrows(IllegalStateException.class, wrapper::release);
+ }
+
+ @Test
+ public void testCleanupClearsCatalogEvenWhenCloseFails() throws Exception {
+ NameIdentifier ident = createCatalog("failing_close");
+
+ ClassLoaderPool pool =
+ (ClassLoaderPool) FieldUtils.readField(catalogManager, "classLoaderPool", true);
+ Assertions.assertEquals(1, pool.size());
+
+ CatalogWrapper wrapper = catalogManager.getCatalogCache().getIfPresent(ident);
+ Assertions.assertNotNull(wrapper);
+
+ BaseCatalog<?> failingCatalog = Mockito.mock(BaseCatalog.class);
+ Mockito.doThrow(new IOException("close failed")).when(failingCatalog).close();
+ FieldUtils.writeField(wrapper, "catalog", failingCatalog, true);
+
+ // Cleanup runs exactly once, so a close() failure must not leave the reference behind: there
+ // is no second chance to clear it.
+ wrapper.retire();
+
+ Mockito.verify(failingCatalog).close();
+ Assertions.assertNull(
+ wrapper.catalog(), "a failing close must still drop the catalog reference");
+ Assertions.assertEquals(
+ 0, pool.size(), "a failing close must still release the pooled ClassLoader");
+ }
+
+ @Test
+ public void testManagerCloseWaitsForConcurrentCatalogLoad() throws Exception {
+ NameIdentifier ident = createCatalog("load_while_closing");
+ CatalogWrapper oldWrapper = catalogManager.getCatalogCache().getIfPresent(ident);
+ catalogManager.getCatalogCache().invalidate(ident);
+ await().atMost(Duration.ofSeconds(10)).until(oldWrapper::isRetired);
+
+ catalogManager = Mockito.spy(catalogManager);
+ CountDownLatch loadStarted = new CountDownLatch(1);
+ CountDownLatch continueLoad = new CountDownLatch(1);
+ Mockito.doAnswer(
+ invocation -> {
+ loadStarted.countDown();
+ Assertions.assertTrue(continueLoad.await(10, TimeUnit.SECONDS));
+ return invocation.callRealMethod();
+ })
+ .when(catalogManager)
+ .createCatalogWrapper(Mockito.any(), Mockito.isNull());
+
+ ExecutorService executor = Executors.newFixedThreadPool(2);
+ try {
+ Future<CatalogLease> acquiredLease =
+ executor.submit(() -> catalogManager.acquireCatalogLease(ident));
+ Assertions.assertTrue(loadStarted.await(10, TimeUnit.SECONDS));
+
+ Future<?> closeFuture = submitCloseAndAssertBlocked(executor);
+
+ continueLoad.countDown();
+ CatalogLease lease = acquiredLease.get(10, TimeUnit.SECONDS);
+ closeFuture.get(10, TimeUnit.SECONDS);
+
+ CatalogWrapper loadedWrapper = lease.wrapper();
+ Assertions.assertTrue(loadedWrapper.isRetired());
+ Assertions.assertNotNull(
+ loadedWrapper.catalog(), "close must preserve a concurrently acquired lease");
+ Assertions.assertThrows(
+ IllegalStateException.class, () -> catalogManager.acquireCatalogLease(ident));
+
+ lease.close();
+ Assertions.assertNull(loadedWrapper.catalog());
+ } finally {
+ continueLoad.countDown();
+ executor.shutdownNow();
+ }
+ }
+
+ @Test
+ public void testManagerCloseWaitsForConcurrentCatalogPublication() throws Exception {
+ NameIdentifier ident = NameIdentifier.of(METALAKE, "publish_while_closing");
+ catalogManager = Mockito.spy(catalogManager);
+ CountDownLatch creationStarted = new CountDownLatch(1);
+ CountDownLatch continueCreation = new CountDownLatch(1);
+ AtomicReference<CatalogWrapper> createdWrapper = new AtomicReference<>();
+ Mockito.doAnswer(
+ invocation -> {
+ creationStarted.countDown();
+ Assertions.assertTrue(continueCreation.await(10, TimeUnit.SECONDS));
+ CatalogWrapper wrapper = (CatalogWrapper) invocation.callRealMethod();
+ createdWrapper.set(wrapper);
+ return wrapper;
+ })
+ .when(catalogManager)
+ .createCatalogWrapper(Mockito.any(), Mockito.any());
+
+ ExecutorService executor = Executors.newFixedThreadPool(2);
+ try {
+ Future<Catalog> createdCatalog =
+ executor.submit(
+ () ->
+ catalogManager.createCatalog(
+ ident, Catalog.Type.RELATIONAL, PROVIDER, "comment", PROPS));
+ Assertions.assertTrue(creationStarted.await(10, TimeUnit.SECONDS));
+
+ Future<?> closeFuture = submitCloseAndAssertBlocked(executor);
+
+ continueCreation.countDown();
+ Assertions.assertNotNull(createdCatalog.get(10, TimeUnit.SECONDS));
+ closeFuture.get(10, TimeUnit.SECONDS);
+
+ Assertions.assertTrue(createdWrapper.get().isRetired());
+ Assertions.assertNull(createdWrapper.get().catalog());
+ Assertions.assertNull(catalogManager.getCatalogCache().getIfPresent(ident));
+ Assertions.assertThrows(
+ IllegalStateException.class, () -> catalogManager.acquireCatalogLease(ident));
+ } finally {
+ continueCreation.countDown();
+ executor.shutdownNow();
+ }
+ }
+
+ @Test
+ public void testManagerCloseReleasesThePoolEvenIfRetiringAWrapperFails() throws Exception {
+ createCatalog("failing_retire");
+ ClassLoaderPool pool =
+ (ClassLoaderPool) FieldUtils.readField(catalogManager, "classLoaderPool", true);
+
+ CatalogWrapper failingWrapper = Mockito.mock(CatalogWrapper.class);
+ Mockito.doThrow(new RuntimeException("retire failed")).when(failingWrapper).retire();
+ catalogManager.getCatalogCache().put(NameIdentifier.of(METALAKE, "failing"), failingWrapper);
+
+ Assertions.assertDoesNotThrow(() -> catalogManager.close());
+
+ // The cache's removal listener retires the wrapper as well, asynchronously.
+ Mockito.verify(failingWrapper, Mockito.atLeastOnce()).retire();
+ Assertions.assertEquals(
+ 0, pool.size(), "a failing retirement must not keep the ClassLoader pool open");
+ }
+
+ private Future<?> submitCloseAndAssertBlocked(ExecutorService executor)
+ throws InterruptedException {
+ CountDownLatch closeStarted = new CountDownLatch(1);
+ Future<?> closeFuture =
+ executor.submit(
+ () -> {
+ closeStarted.countDown();
+ catalogManager.close();
+ });
+ Assertions.assertTrue(closeStarted.await(10, TimeUnit.SECONDS));
+ await()
+ .during(Duration.ofMillis(200))
+ .atMost(Duration.ofSeconds(1))
+ .until(() -> !closeFuture.isDone());
+ return closeFuture;
+ }
+
+ @Test
+ public void testManagerCloseWaitsForConcurrentCatalogAlter() throws Exception {
+ NameIdentifier ident = createCatalog("alter_while_closing");
+
+ catalogManager = Mockito.spy(catalogManager);
+ CountDownLatch publicationStarted = new CountDownLatch(1);
+ CountDownLatch continuePublication = new CountDownLatch(1);
+ // The only createCatalogWrapper(entity, null) call of alterCatalog happens after the entity
+ // has been persisted and before the refreshed wrapper is published, i.e. exactly in the window
+ // where a concurrent close() used to fail the alter that had already taken effect.
+ Mockito.doAnswer(
+ invocation -> {
+ publicationStarted.countDown();
+ Assertions.assertTrue(continuePublication.await(10, TimeUnit.SECONDS));
+ return invocation.callRealMethod();
+ })
+ .when(catalogManager)
+ .createCatalogWrapper(Mockito.any(), Mockito.isNull());
+
+ ExecutorService executor = Executors.newFixedThreadPool(2);
+ try {
+ Future<Catalog> alteredCatalog =
+ executor.submit(
+ () -> catalogManager.alterCatalog(ident, CatalogChange.updateComment("altered")));
+ Assertions.assertTrue(publicationStarted.await(10, TimeUnit.SECONDS));
+
+ Future<?> closeFuture = submitCloseAndAssertBlocked(executor);
+
+ continuePublication.countDown();
+ Catalog altered = alteredCatalog.get(10, TimeUnit.SECONDS);
+ Assertions.assertEquals(
+ "altered", altered.comment(), "the alter must succeed instead of racing with close()");
+ closeFuture.get(10, TimeUnit.SECONDS);
+
+ Assertions.assertThrows(
+ IllegalStateException.class, () -> catalogManager.acquireCatalogLease(ident));
+ } finally {
+ continuePublication.countDown();
+ executor.shutdownNow();
+ }
+ }
+
+ private NameIdentifier createCatalog(String name) {
+ NameIdentifier ident = NameIdentifier.of(METALAKE, name);
+ catalogManager.createCatalog(ident, Catalog.Type.RELATIONAL, PROVIDER, "comment", PROPS);
+ return ident;
+ }
+}
diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestFunctionOperationDispatcher.java b/core/src/test/java/org/apache/gravitino/catalog/TestFunctionOperationDispatcher.java
index 41caa1303f..19e459ece6 100644
--- a/core/src/test/java/org/apache/gravitino/catalog/TestFunctionOperationDispatcher.java
+++ b/core/src/test/java/org/apache/gravitino/catalog/TestFunctionOperationDispatcher.java
@@ -18,6 +18,9 @@
*/
package org.apache.gravitino.catalog;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -31,6 +34,7 @@ import org.apache.gravitino.function.FunctionType;
import org.apache.gravitino.secret.SecretManager;
import org.apache.gravitino.storage.IdGenerator;
import org.apache.gravitino.storage.RandomIdGenerator;
+import org.apache.gravitino.utils.ThrowableFunction;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -49,7 +53,7 @@ public class TestFunctionOperationDispatcher {
private EntityStore store;
@BeforeEach
- public void setUp() {
+ public void setUp() throws Exception {
catalogManager = mock(CatalogManager.class);
schemaOps = mock(SchemaOperationDispatcher.class);
store = mock(EntityStore.class);
@@ -57,10 +61,8 @@ public class TestFunctionOperationDispatcher {
CatalogManager.CatalogWrapper icebergWrapper = createMockCatalogWrapper("lakehouse-iceberg");
CatalogManager.CatalogWrapper hiveWrapper = createMockCatalogWrapper("hive");
- when(catalogManager.loadCatalogAndWrap(NameIdentifier.of(METALAKE, ICEBERG_CATALOG)))
- .thenReturn(icebergWrapper);
- when(catalogManager.loadCatalogAndWrap(NameIdentifier.of(METALAKE, HIVE_CATALOG)))
- .thenReturn(hiveWrapper);
+ mockCatalogWrapper(NameIdentifier.of(METALAKE, ICEBERG_CATALOG), icebergWrapper);
+ mockCatalogWrapper(NameIdentifier.of(METALAKE, HIVE_CATALOG), hiveWrapper);
dispatcher =
new FunctionOperationDispatcher(
@@ -118,6 +120,19 @@ public class TestFunctionOperationDispatcher {
CatalogManager.CatalogWrapper wrapper = mock(CatalogManager.CatalogWrapper.class);
when(wrapper.catalog()).thenReturn(catalog);
- return wrapper;
+ return CatalogTestUtils.mockDetachConnectorResult(wrapper);
+ }
+
+ @SuppressWarnings("unchecked")
+ private void mockCatalogWrapper(
+ NameIdentifier ident, CatalogManager.CatalogWrapper catalogWrapper) throws Exception {
+ doAnswer(
+ invocation -> {
+ ThrowableFunction<CatalogManager.CatalogWrapper, Object> operation =
+ invocation.getArgument(1);
+ return operation.apply(catalogWrapper);
+ })
+ .when(catalogManager)
+ .doWithCatalogWrapper(eq(ident), any());
}
}
diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestOperationDispatcherSnapshots.java b/core/src/test/java/org/apache/gravitino/catalog/TestOperationDispatcherSnapshots.java
new file mode 100644
index 0000000000..0fdce2d626
--- /dev/null
+++ b/core/src/test/java/org/apache/gravitino/catalog/TestOperationDispatcherSnapshots.java
@@ -0,0 +1,230 @@
+/*
+ * 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;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.lang.reflect.Method;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicBoolean;
+import org.apache.gravitino.EntityStore;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Schema;
+import org.apache.gravitino.dto.rel.TableDTO;
+import org.apache.gravitino.file.FileInfo;
+import org.apache.gravitino.file.Fileset;
+import org.apache.gravitino.function.Function;
+import org.apache.gravitino.messaging.Topic;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.model.Model;
+import org.apache.gravitino.model.ModelVersion;
+import org.apache.gravitino.rel.Column;
+import org.apache.gravitino.rel.Table;
+import org.apache.gravitino.rel.View;
+import org.apache.gravitino.rel.expressions.distributions.Distributions;
+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.gravitino.rel.partitions.Partition;
+import org.apache.gravitino.secret.SecretManager;
+import org.apache.gravitino.storage.IdGenerator;
+import org.apache.gravitino.utils.ThrowableFunction;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.mockito.stubbing.Answer;
+
+class TestOperationDispatcherSnapshots {
+
+ @Test
+ void testConnectorTableIsDetachedBeforeLeaseCallbackReturns() throws Exception {
+ AtomicBoolean callbackActive = new AtomicBoolean(false);
+ CatalogManager catalogManager = mock(CatalogManager.class);
+ CatalogManager.CatalogWrapper wrapper = mock(CatalogManager.CatalogWrapper.class);
+ doAnswer(
+ invocation -> {
+ ThrowableFunction<CatalogManager.CatalogWrapper, Object> operation =
+ invocation.getArgument(1);
+ callbackActive.set(true);
+ try {
+ return operation.apply(wrapper);
+ } finally {
+ callbackActive.set(false);
+ }
+ })
+ .when(catalogManager)
+ .doWithCatalogWrapper(any(), any());
+
+ CatalogTestUtils.mockDetachConnectorResult(wrapper);
+
+ Table connectorTable = mock(Table.class);
+ when(connectorTable.name()).thenAnswer(requireActive(callbackActive, "table"));
+ when(connectorTable.comment()).thenAnswer(requireActive(callbackActive, "comment"));
+ when(connectorTable.columns()).thenAnswer(requireActive(callbackActive, new Column[0]));
+ when(connectorTable.properties())
+ .thenAnswer(requireActive(callbackActive, Collections.emptyMap()));
+ when(connectorTable.sortOrder()).thenAnswer(requireActive(callbackActive, new SortOrder[0]));
+ when(connectorTable.distribution())
+ .thenAnswer(requireActive(callbackActive, Distributions.NONE));
+ when(connectorTable.partitioning()).thenAnswer(requireActive(callbackActive, new Transform[0]));
+ when(connectorTable.index()).thenAnswer(requireActive(callbackActive, new Index[0]));
+ when(connectorTable.auditInfo())
+ .thenAnswer(
+ requireActive(
+ callbackActive,
+ AuditInfo.builder().withCreator("user").withCreateTime(Instant.EPOCH).build()));
+
+ SnapshotDispatcher dispatcher = new SnapshotDispatcher(catalogManager);
+ Table result = dispatcher.returnTable(connectorTable);
+
+ Assertions.assertFalse(callbackActive.get());
+ Assertions.assertInstanceOf(TableDTO.class, result);
+ Assertions.assertEquals("table", result.name());
+ Assertions.assertEquals("comment", result.comment());
+ }
+
+ @Test
+ void testFilesetSnapshotCopiesMapsWithoutChangingMutability() {
+ Map<String, String> locations = new HashMap<>();
+ locations.put(Fileset.LOCATION_NAME_UNKNOWN, "file:/data");
+ Map<String, String> properties = new HashMap<>();
+ properties.put("key", "value");
+
+ Fileset fileset = mock(Fileset.class);
+ when(fileset.name()).thenReturn("fileset");
+ when(fileset.type()).thenReturn(Fileset.Type.MANAGED);
+ when(fileset.storageLocations()).thenReturn(locations);
+ when(fileset.properties()).thenReturn(properties);
+ when(fileset.auditInfo())
+ .thenReturn(AuditInfo.builder().withCreator("user").withCreateTime(Instant.EPOCH).build());
+
+ Fileset snapshot = ConnectorObjectSnapshot.detach(fileset);
+ locations.put("archive", "file:/archive");
+ properties.put("late", "change");
+
+ Assertions.assertFalse(snapshot.storageLocations().containsKey("archive"));
+ Assertions.assertFalse(snapshot.properties().containsKey("late"));
+ Assertions.assertDoesNotThrow(() -> snapshot.properties().put("consumer", "value"));
+ }
+
+ /**
+ * Every value a dispatcher returns leaves the catalog lease, so it must either carry no connector
+ * state or be converted by {@link ConnectorObjectSnapshot#detach}. That method is a manual type
+ * switch with a pass-through default, so nothing else stops a newly added return type from
+ * silently escaping with connector classes attached. This test is that stop.
+ */
+ @Test
+ void testEveryDispatcherReturnTypeIsDetachedOrCarriesNoConnectorState() {
+ List<Class<?>> dispatchers =
+ List.of(
+ TableDispatcher.class,
+ ViewDispatcher.class,
+ SchemaDispatcher.class,
+ FilesetDispatcher.class,
+ TopicDispatcher.class,
+ ModelDispatcher.class,
+ PartitionDispatcher.class,
+ FunctionDispatcher.class);
+
+ List<String> escaping = new ArrayList<>();
+ for (Class<?> dispatcher : dispatchers) {
+ for (Method method : dispatcher.getMethods()) {
+ Class<?> returnType = method.getReturnType();
+ if (!DETACHED_TYPES.contains(returnType) && !carriesNoConnectorState(returnType)) {
+ escaping.add(dispatcher.getSimpleName() + "#" + method.getName() + " -> " + returnType);
+ }
+ }
+ }
+
+ Assertions.assertTrue(
+ escaping.isEmpty(),
+ "These dispatcher results leave the catalog lease without being detached. Either add the "
+ + "type to ConnectorObjectSnapshot.detach or confirm it holds no connector state and "
+ + "list it here: "
+ + escaping);
+ }
+
+ /** Types ConnectorObjectSnapshot.detach knows how to convert. Keep in sync with that method. */
+ private static final Set<Class<?>> DETACHED_TYPES =
+ Set.of(
+ Table.class,
+ View.class,
+ Schema.class,
+ Fileset.class,
+ Topic.class,
+ Model.class,
+ ModelVersion.class,
+ Partition.class,
+ ModelVersion[].class,
+ Partition[].class,
+ FileInfo[].class);
+
+ /**
+ * Returns whether values of this type are built by Gravitino itself rather than by a connector,
+ * so they never reference a catalog ClassLoader.
+ *
+ * <p>{@code Function} is on this list because functions are managed-only: {@code CatalogWrapper}
+ * exposes no function operations at all and every {@code FunctionDispatcher} method goes through
+ * {@code ManagedFunctionOperations}, which builds its results from {@code FunctionEntity}. Give a
+ * catalog connector-backed functions and that stops being true, which is when this test should
+ * start failing.
+ */
+ private static boolean carriesNoConnectorState(Class<?> type) {
+ if (type.isArray()) {
+ Class<?> component = type.getComponentType();
+ return component.isPrimitive() || carriesNoConnectorState(component);
+ }
+ return type.isPrimitive()
+ || type == String.class
+ || type == NameIdentifier.class
+ || type == Function.class;
+ }
+
+ private static <T> Answer<T> requireActive(AtomicBoolean callbackActive, T value) {
+ return invocation -> {
+ Assertions.assertTrue(
+ callbackActive.get(), "connector metadata must be read while the lease is active");
+ return value;
+ };
+ }
+
+ private static final class SnapshotDispatcher extends OperationDispatcher {
+
+ private SnapshotDispatcher(CatalogManager catalogManager) {
+ super(
+ catalogManager,
+ mock(EntityStore.class),
+ mock(IdGenerator.class),
+ mock(SecretManager.class));
+ }
+
+ private Table returnTable(Table table) {
+ return doWithCatalog(
+ NameIdentifier.of("metalake", "catalog"), wrapper -> table, RuntimeException.class);
+ }
+ }
+}
diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestPartitionNormalizeDispatcher.java b/core/src/test/java/org/apache/gravitino/catalog/TestPartitionNormalizeDispatcher.java
index 84c9678a66..e23df1e0b1 100644
--- a/core/src/test/java/org/apache/gravitino/catalog/TestPartitionNormalizeDispatcher.java
+++ b/core/src/test/java/org/apache/gravitino/catalog/TestPartitionNormalizeDispatcher.java
@@ -20,6 +20,7 @@ package org.apache.gravitino.catalog;
import com.google.common.collect.Maps;
import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.connector.BaseCatalog;
import org.apache.gravitino.rel.Column;
import org.apache.gravitino.rel.expressions.literals.Literal;
import org.apache.gravitino.rel.expressions.literals.Literals;
@@ -108,11 +109,9 @@ public class TestPartitionNormalizeDispatcher extends TestOperationDispatcher {
PartitionDispatcher mockDispatcher = Mockito.mock(PartitionDispatcher.class);
CatalogManager mockCatalogManager = Mockito.mock(CatalogManager.class);
- CatalogManager.CatalogWrapper mockWrapper = Mockito.mock(CatalogManager.CatalogWrapper.class);
- Mockito.when(mockWrapper.capabilities())
- .thenReturn(TestCapabilityHelpers.QUOTE_AWARE_CAPABILITY);
- Mockito.when(mockCatalogManager.loadCatalogAndWrap(Mockito.any(NameIdentifier.class)))
- .thenReturn(mockWrapper);
+ BaseCatalog<?> mockCatalog = Mockito.mock(BaseCatalog.class);
+ Mockito.when(mockCatalog.capability()).thenReturn(TestCapabilityHelpers.QUOTE_AWARE_CAPABILITY);
+ CatalogTestUtils.mockDoWithCatalog(mockCatalogManager, mockCatalog);
PartitionNormalizeDispatcher dispatcher =
new PartitionNormalizeDispatcher(mockDispatcher, mockCatalogManager);
diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestPartitionOperationDispatcher.java b/core/src/test/java/org/apache/gravitino/catalog/TestPartitionOperationDispatcher.java
index bed4136ac9..af47be63d9 100644
--- a/core/src/test/java/org/apache/gravitino/catalog/TestPartitionOperationDispatcher.java
+++ b/core/src/test/java/org/apache/gravitino/catalog/TestPartitionOperationDispatcher.java
@@ -31,6 +31,7 @@ import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.gravitino.Config;
import org.apache.gravitino.GravitinoEnv;
import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.dto.util.DTOConverters;
import org.apache.gravitino.lock.LockManager;
import org.apache.gravitino.rel.Column;
import org.apache.gravitino.rel.expressions.literals.Literal;
@@ -111,13 +112,13 @@ public class TestPartitionOperationDispatcher extends TestOperationDispatcher {
@Test
public void testListPartitions() {
Partition[] partitions = partitionOperationDispatcher.listPartitions(TABLE_IDENT);
- Assertions.assertTrue(Arrays.asList(partitions).contains(PARTITION));
+ Assertions.assertTrue(Arrays.asList(partitions).contains(DTOConverters.toDTO(PARTITION)));
}
@Test
public void testGetPartition() {
Partition p = partitionOperationDispatcher.getPartition(TABLE_IDENT, PARTITION.name());
- Assertions.assertEquals(PARTITION, p);
+ Assertions.assertEquals(DTOConverters.toDTO(PARTITION), p);
}
@Test
diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestSchemaOperationDispatcher.java b/core/src/test/java/org/apache/gravitino/catalog/TestSchemaOperationDispatcher.java
index 05ca381d1c..a631e8fbbb 100644
--- a/core/src/test/java/org/apache/gravitino/catalog/TestSchemaOperationDispatcher.java
+++ b/core/src/test/java/org/apache/gravitino/catalog/TestSchemaOperationDispatcher.java
@@ -47,7 +47,6 @@ import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
import org.apache.gravitino.Schema;
import org.apache.gravitino.SchemaChange;
-import org.apache.gravitino.TestCatalog;
import org.apache.gravitino.auth.AuthConstants;
import org.apache.gravitino.connector.HiddenPropertyMaskUtils;
import org.apache.gravitino.connector.TestCatalogOperations;
@@ -389,10 +388,13 @@ public class TestSchemaOperationDispatcher extends TestOperationDispatcher {
Map<String, String> props = ImmutableMap.of("k1", "v1", "k2", "v2");
dispatcher.createSchema(schemaIdent, "comment", props);
- TestCatalog testCatalog =
- (TestCatalog) catalogManager.loadCatalog(NameIdentifier.of(metalake, catalog));
- TestCatalogOperations testCatalogOperations = (TestCatalogOperations) testCatalog.ops();
- Assertions.assertTrue(testCatalogOperations.dropSchema(schemaIdent, false));
+ catalogManager.doWithCatalog(
+ NameIdentifier.of(metalake, catalog),
+ liveCatalog -> {
+ TestCatalogOperations testCatalogOperations = (TestCatalogOperations) liveCatalog.ops();
+ Assertions.assertTrue(testCatalogOperations.dropSchema(schemaIdent, false));
+ return null;
+ });
Assertions.assertFalse(dispatcher.dropSchema(schemaIdent, false));
Assertions.assertTrue(entityStore.exists(schemaIdent, SCHEMA));
diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelNormalizeDispatcher.java b/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelNormalizeDispatcher.java
index 4f5401f29a..d10d207346 100644
--- a/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelNormalizeDispatcher.java
+++ b/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelNormalizeDispatcher.java
@@ -29,6 +29,7 @@ import java.util.Locale;
import java.util.Map;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
+import org.apache.gravitino.connector.BaseCatalog;
import org.apache.gravitino.connector.capability.Capability;
import org.apache.gravitino.connector.capability.CapabilityResult;
import org.apache.gravitino.semantic.Dataset;
@@ -56,10 +57,9 @@ public class TestSemanticModelNormalizeDispatcher {
public void setUp() throws Exception {
delegate = mock(SemanticModelDispatcher.class);
CatalogManager catalogManager = mock(CatalogManager.class);
- CatalogManager.CatalogWrapper wrapper = mock(CatalogManager.CatalogWrapper.class);
- when(wrapper.capabilities()).thenReturn(new ParentNormalizingCapability());
- when(catalogManager.loadCatalogAndWrap(NameIdentifier.of("metalake", "catalog")))
- .thenReturn(wrapper);
+ BaseCatalog<?> catalog = mock(BaseCatalog.class);
+ when(catalog.capability()).thenReturn(new ParentNormalizingCapability());
+ CatalogTestUtils.mockDoWithCatalog(catalogManager, catalog);
dispatcher = new SemanticModelNormalizeDispatcher(delegate, catalogManager);
}
diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestTableNormalizeDispatcher.java b/core/src/test/java/org/apache/gravitino/catalog/TestTableNormalizeDispatcher.java
index 85649cdea1..ae4685e351 100644
--- a/core/src/test/java/org/apache/gravitino/catalog/TestTableNormalizeDispatcher.java
+++ b/core/src/test/java/org/apache/gravitino/catalog/TestTableNormalizeDispatcher.java
@@ -28,6 +28,7 @@ import org.apache.gravitino.MetadataObjects;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
import org.apache.gravitino.TestColumn;
+import org.apache.gravitino.connector.BaseCatalog;
import org.apache.gravitino.exceptions.TableAlreadyExistsException;
import org.apache.gravitino.rel.Column;
import org.apache.gravitino.rel.Table;
@@ -223,11 +224,9 @@ public class TestTableNormalizeDispatcher extends TestOperationDispatcher {
.thenReturn(Mockito.mock(Table.class));
CatalogManager mockCatalogManager = Mockito.mock(CatalogManager.class);
- CatalogManager.CatalogWrapper mockWrapper = Mockito.mock(CatalogManager.CatalogWrapper.class);
- Mockito.when(mockWrapper.capabilities())
- .thenReturn(TestCapabilityHelpers.QUOTE_AWARE_CAPABILITY);
- Mockito.when(mockCatalogManager.loadCatalogAndWrap(Mockito.any(NameIdentifier.class)))
- .thenReturn(mockWrapper);
+ BaseCatalog<?> mockCatalog = Mockito.mock(BaseCatalog.class);
+ Mockito.when(mockCatalog.capability()).thenReturn(TestCapabilityHelpers.QUOTE_AWARE_CAPABILITY);
+ CatalogTestUtils.mockDoWithCatalog(mockCatalogManager, mockCatalog);
TableNormalizeDispatcher dispatcher =
new TableNormalizeDispatcher(mockDispatcher, mockCatalogManager);
diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestTableOperationDispatcher.java b/core/src/test/java/org/apache/gravitino/catalog/TestTableOperationDispatcher.java
index 90ad7c6696..39e85c1929 100644
--- a/core/src/test/java/org/apache/gravitino/catalog/TestTableOperationDispatcher.java
+++ b/core/src/test/java/org/apache/gravitino/catalog/TestTableOperationDispatcher.java
@@ -58,6 +58,7 @@ import org.apache.gravitino.TestColumn;
import org.apache.gravitino.auth.AuthConstants;
import org.apache.gravitino.connector.HiddenPropertyMaskUtils;
import org.apache.gravitino.connector.TestCatalogOperations;
+import org.apache.gravitino.dto.util.DTOConverters;
import org.apache.gravitino.exceptions.GravitinoRuntimeException;
import org.apache.gravitino.exceptions.NoSuchEntityException;
import org.apache.gravitino.exceptions.NoSuchTableException;
@@ -130,7 +131,7 @@ public class TestTableOperationDispatcher extends TestOperationDispatcher {
Assertions.assertEquals("comment", table1.comment());
testProperties(props, table1.properties());
Assertions.assertEquals(0, table1.partitioning().length);
- Assertions.assertArrayEquals(columns, table1.columns());
+ testColumns(columns, table1.columns());
// Test required table properties exception
Map<String, String> illegalTableProperties =
@@ -582,12 +583,15 @@ public class TestTableOperationDispatcher extends TestOperationDispatcher {
tableOperationDispatcher.alterTable(
tableIdent, TableChange.rename(renamedTableIdent.name())));
- TestCatalog testCatalog =
- (TestCatalog) catalogManager.loadCatalog(NameIdentifier.of(metalake, catalog));
- TestCatalogOperations testCatalogOperations = (TestCatalogOperations) testCatalog.ops();
- Assertions.assertDoesNotThrow(() -> testCatalogOperations.loadTable(tableIdent));
- Assertions.assertThrows(
- NoSuchTableException.class, () -> testCatalogOperations.loadTable(renamedTableIdent));
+ catalogManager.doWithCatalog(
+ NameIdentifier.of(metalake, catalog),
+ liveCatalog -> {
+ TestCatalogOperations testCatalogOperations = (TestCatalogOperations) liveCatalog.ops();
+ Assertions.assertDoesNotThrow(() -> testCatalogOperations.loadTable(tableIdent));
+ Assertions.assertThrows(
+ NoSuchTableException.class, () -> testCatalogOperations.loadTable(renamedTableIdent));
+ return null;
+ });
reset(entityStore);
}
@@ -685,7 +689,8 @@ public class TestTableOperationDispatcher extends TestOperationDispatcher {
tableOperationDispatcher.createTable(tableIdent, columns, "comment", props, new Transform[0]);
TestCatalog testCatalog =
- (TestCatalog) catalogManager.loadCatalog(NameIdentifier.of(metalake, catalog));
+ (TestCatalog)
+ catalogManager.loadCatalogAndWrap(NameIdentifier.of(metalake, catalog)).catalog();
TestCatalogOperations testCatalogOperations = (TestCatalogOperations) testCatalog.ops();
Assertions.assertTrue(testCatalogOperations.dropSchema(schemaIdent, false));
Assertions.assertFalse(testCatalogOperations.schemaExists(schemaIdent));
@@ -724,7 +729,8 @@ public class TestTableOperationDispatcher extends TestOperationDispatcher {
// now-empty namespaces, so the catalog no longer knows the table (dropTable returns false),
// while Gravitino still holds the orphaned schema entities.
TestCatalog testCatalog =
- (TestCatalog) catalogManager.loadCatalog(NameIdentifier.of(metalake, catalog));
+ (TestCatalog)
+ catalogManager.loadCatalogAndWrap(NameIdentifier.of(metalake, catalog)).catalog();
TestCatalogOperations testCatalogOperations = (TestCatalogOperations) testCatalog.ops();
Assertions.assertTrue(testCatalogOperations.dropTable(tableIdent));
Assertions.assertTrue(testCatalogOperations.dropSchema(schemaIdent, false));
@@ -768,7 +774,8 @@ public class TestTableOperationDispatcher extends TestOperationDispatcher {
// now-empty namespaces, so the catalog no longer knows the table (purgeTable returns false),
// while Gravitino still holds the orphaned schema entities.
TestCatalog testCatalog =
- (TestCatalog) catalogManager.loadCatalog(NameIdentifier.of(metalake, catalog));
+ (TestCatalog)
+ catalogManager.loadCatalogAndWrap(NameIdentifier.of(metalake, catalog)).catalog();
TestCatalogOperations testCatalogOperations = (TestCatalogOperations) testCatalog.ops();
Assertions.assertTrue(testCatalogOperations.purgeTable(tableIdent));
Assertions.assertTrue(testCatalogOperations.dropSchema(schemaIdent, false));
@@ -790,7 +797,8 @@ public class TestTableOperationDispatcher extends TestOperationDispatcher {
NameIdentifier tableIdent = NameIdentifier.of(tableNs, "topic81");
Map<String, String> props = ImmutableMap.of("k1", "v1", "k2", "v2");
TestCatalog testCatalog =
- (TestCatalog) catalogManager.loadCatalog(NameIdentifier.of(metalake, catalog));
+ (TestCatalog)
+ catalogManager.loadCatalogAndWrap(NameIdentifier.of(metalake, catalog)).catalog();
TestCatalogOperations testCatalogOperations = (TestCatalogOperations) testCatalog.ops();
testCatalogOperations.createSchema(
NameIdentifier.of(tableNs.levels()), "", Collections.emptyMap());
@@ -859,7 +867,8 @@ public class TestTableOperationDispatcher extends TestOperationDispatcher {
// Test if the column from table is not matched with the column from table entity
TestCatalog testCatalog =
- (TestCatalog) catalogManager.loadCatalog(NameIdentifier.of(metalake, catalog));
+ (TestCatalog)
+ catalogManager.loadCatalogAndWrap(NameIdentifier.of(metalake, catalog)).catalog();
TestCatalogOperations testCatalogOperations = (TestCatalogOperations) testCatalog.ops();
// 1. Update the existing column
@@ -1236,31 +1245,20 @@ public class TestTableOperationDispatcher extends TestOperationDispatcher {
}
private static void testColumns(Column[] expectedColumns, Column[] actualColumns) {
- Map<String, Column> expectedColumnMap =
- expectedColumns == null
- ? Collections.emptyMap()
- : Arrays.stream(expectedColumns)
- .collect(Collectors.toMap(c -> c.name().toLowerCase(), Function.identity()));
- Map<String, Column> actualColumnMap =
- actualColumns == null
- ? Collections.emptyMap()
- : Arrays.stream(actualColumns)
- .collect(Collectors.toMap(Column::name, Function.identity()));
-
- Assertions.assertEquals(expectedColumnMap.size(), actualColumnMap.size());
- expectedColumnMap.forEach(
- (name, expectedColumn) -> {
- TestColumn actualColumn = (TestColumn) actualColumnMap.get(name);
- TestColumn e = (TestColumn) expectedColumn;
- Assertions.assertNotNull(actualColumn);
- Assertions.assertEquals(e.name().toLowerCase(), actualColumn.name());
- Assertions.assertEquals(e.position(), actualColumn.position());
- Assertions.assertEquals(e.dataType(), actualColumn.dataType());
- Assertions.assertEquals(e.comment(), actualColumn.comment());
- Assertions.assertEquals(e.nullable(), actualColumn.nullable());
- Assertions.assertEquals(e.autoIncrement(), actualColumn.autoIncrement());
- Assertions.assertEquals(e.defaultValue(), actualColumn.defaultValue());
- });
+ int expectedSize = expectedColumns == null ? 0 : expectedColumns.length;
+ int actualSize = actualColumns == null ? 0 : actualColumns.length;
+ Assertions.assertEquals(expectedSize, actualSize);
+ for (int i = 0; i < expectedSize; i++) {
+ Column expectedColumn = expectedColumns[i];
+ Column actualColumn = actualColumns[i];
+ Assertions.assertEquals(expectedColumn.name().toLowerCase(), actualColumn.name());
+ Assertions.assertEquals(expectedColumn.dataType(), actualColumn.dataType());
+ Assertions.assertEquals(expectedColumn.comment(), actualColumn.comment());
+ Assertions.assertEquals(expectedColumn.nullable(), actualColumn.nullable());
+ Assertions.assertEquals(expectedColumn.autoIncrement(), actualColumn.autoIncrement());
+ Assertions.assertEquals(
+ DTOConverters.toDTO(expectedColumn).defaultValue(), actualColumn.defaultValue());
+ }
}
private static void testColumnAndColumnEntities(
@@ -1288,7 +1286,8 @@ public class TestTableOperationDispatcher extends TestOperationDispatcher {
Assertions.assertEquals(e.comment(), actualColumn.comment());
Assertions.assertEquals(e.nullable(), actualColumn.nullable());
Assertions.assertEquals(e.autoIncrement(), actualColumn.autoIncrement());
- Assertions.assertEquals(e.defaultValue(), actualColumn.defaultValue());
+ Assertions.assertEquals(
+ DTOConverters.toDTO(e).defaultValue(), actualColumn.defaultValue());
});
}
diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestTopicOperationDispatcher.java b/core/src/test/java/org/apache/gravitino/catalog/TestTopicOperationDispatcher.java
index f9c39548ed..abc7f732bb 100644
--- a/core/src/test/java/org/apache/gravitino/catalog/TestTopicOperationDispatcher.java
+++ b/core/src/test/java/org/apache/gravitino/catalog/TestTopicOperationDispatcher.java
@@ -266,7 +266,8 @@ public class TestTopicOperationDispatcher extends TestOperationDispatcher {
NameIdentifier topicIdent = NameIdentifier.of(topicNs, "topic61");
Map<String, String> props = ImmutableMap.of("k1", "v1", "k2", "v2");
TestCatalog testCatalog =
- (TestCatalog) catalogManager.loadCatalog(NameIdentifier.of(metalake, catalog));
+ (TestCatalog)
+ catalogManager.loadCatalogAndWrap(NameIdentifier.of(metalake, catalog)).catalog();
TestCatalogOperations testCatalogOperations = (TestCatalogOperations) testCatalog.ops();
testCatalogOperations.createSchema(
NameIdentifier.of(topicNs.levels()), "", Collections.emptyMap());
diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestViewOperationDispatcher.java b/core/src/test/java/org/apache/gravitino/catalog/TestViewOperationDispatcher.java
index 490e48052f..0b822169ff 100644
--- a/core/src/test/java/org/apache/gravitino/catalog/TestViewOperationDispatcher.java
+++ b/core/src/test/java/org/apache/gravitino/catalog/TestViewOperationDispatcher.java
@@ -161,7 +161,8 @@ public class TestViewOperationDispatcher extends TestOperationDispatcher {
// Mock the catalog operations to return the view
TestCatalog testCatalog =
- (TestCatalog) catalogManager.loadCatalog(NameIdentifier.of(metalake, catalog));
+ (TestCatalog)
+ catalogManager.loadCatalogAndWrap(NameIdentifier.of(metalake, catalog)).catalog();
TestCatalogOperations testCatalogOperations = (TestCatalogOperations) testCatalog.ops();
testCatalogOperations.views.put(viewIdent1, mockView);
@@ -193,7 +194,8 @@ public class TestViewOperationDispatcher extends TestOperationDispatcher {
// Create multiple views
TestCatalog testCatalog =
- (TestCatalog) catalogManager.loadCatalog(NameIdentifier.of(metalake, catalog));
+ (TestCatalog)
+ catalogManager.loadCatalogAndWrap(NameIdentifier.of(metalake, catalog)).catalog();
TestCatalogOperations testCatalogOperations = (TestCatalogOperations) testCatalog.ops();
for (int i = 1; i <= 3; i++) {
@@ -263,7 +265,8 @@ public class TestViewOperationDispatcher extends TestOperationDispatcher {
View mockView = createMockView("auto_import_view", props, auditInfo);
TestCatalog testCatalog =
- (TestCatalog) catalogManager.loadCatalog(NameIdentifier.of(metalake, catalog));
+ (TestCatalog)
+ catalogManager.loadCatalogAndWrap(NameIdentifier.of(metalake, catalog)).catalog();
TestCatalogOperations testCatalogOperations = (TestCatalogOperations) testCatalog.ops();
testCatalogOperations.views.put(viewIdent, mockView);
@@ -312,7 +315,8 @@ public class TestViewOperationDispatcher extends TestOperationDispatcher {
View mockView = createMockView("already_imported_view", props, auditInfo);
TestCatalog testCatalog =
- (TestCatalog) catalogManager.loadCatalog(NameIdentifier.of(metalake, catalog));
+ (TestCatalog)
+ catalogManager.loadCatalogAndWrap(NameIdentifier.of(metalake, catalog)).catalog();
TestCatalogOperations testCatalogOperations = (TestCatalogOperations) testCatalog.ops();
testCatalogOperations.views.put(viewIdent, mockView);
@@ -346,7 +350,8 @@ public class TestViewOperationDispatcher extends TestOperationDispatcher {
View mockView = createMockView("concurrent_view", props, auditInfo);
TestCatalog testCatalog =
- (TestCatalog) catalogManager.loadCatalog(NameIdentifier.of(metalake, catalog));
+ (TestCatalog)
+ catalogManager.loadCatalogAndWrap(NameIdentifier.of(metalake, catalog)).catalog();
TestCatalogOperations testCatalogOperations = (TestCatalogOperations) testCatalog.ops();
testCatalogOperations.views.put(viewIdent, mockView);
@@ -409,7 +414,8 @@ public class TestViewOperationDispatcher extends TestOperationDispatcher {
View mockView = createMockView("deleted_view", props, auditInfo);
TestCatalog testCatalog =
- (TestCatalog) catalogManager.loadCatalog(NameIdentifier.of(metalake, catalog));
+ (TestCatalog)
+ catalogManager.loadCatalogAndWrap(NameIdentifier.of(metalake, catalog)).catalog();
TestCatalogOperations testCatalogOperations = (TestCatalogOperations) testCatalog.ops();
testCatalogOperations.views.put(viewIdent, mockView);
@@ -534,7 +540,8 @@ public class TestViewOperationDispatcher extends TestOperationDispatcher {
viewIdent, null, new Column[0], representations, null, null, ImmutableMap.of("k1", "v1"));
TestCatalog testCatalog =
- (TestCatalog) catalogManager.loadCatalog(NameIdentifier.of(metalake, catalog));
+ (TestCatalog)
+ catalogManager.loadCatalogAndWrap(NameIdentifier.of(metalake, catalog)).catalog();
TestCatalogOperations testCatalogOperations = (TestCatalogOperations) testCatalog.ops();
Assertions.assertTrue(testCatalogOperations.dropSchema(schemaIdent, false));
Assertions.assertFalse(testCatalogOperations.schemaExists(schemaIdent));
@@ -568,7 +575,8 @@ public class TestViewOperationDispatcher extends TestOperationDispatcher {
// now-empty namespaces, so the catalog no longer knows the view (dropView returns false),
// while Gravitino still holds the orphaned schema entities.
TestCatalog testCatalog =
- (TestCatalog) catalogManager.loadCatalog(NameIdentifier.of(metalake, catalog));
+ (TestCatalog)
+ catalogManager.loadCatalogAndWrap(NameIdentifier.of(metalake, catalog)).catalog();
TestCatalogOperations testCatalogOperations = (TestCatalogOperations) testCatalog.ops();
Assertions.assertTrue(testCatalogOperations.dropView(viewIdent));
Assertions.assertTrue(testCatalogOperations.dropSchema(schemaIdent, false));
@@ -707,12 +715,15 @@ public class TestViewOperationDispatcher extends TestOperationDispatcher {
GravitinoRuntimeException.class,
() -> viewOperationDispatcher.alterView(oldIdent, ViewChange.rename(newIdent.name())));
- TestCatalog testCatalog =
- (TestCatalog) catalogManager.loadCatalog(NameIdentifier.of(metalake, catalog));
- TestCatalogOperations testCatalogOperations = (TestCatalogOperations) testCatalog.ops();
- Assertions.assertDoesNotThrow(() -> testCatalogOperations.loadView(oldIdent));
- Assertions.assertThrows(
- NoSuchViewException.class, () -> testCatalogOperations.loadView(newIdent));
+ catalogManager.doWithCatalog(
+ NameIdentifier.of(metalake, catalog),
+ liveCatalog -> {
+ TestCatalogOperations testCatalogOperations = (TestCatalogOperations) liveCatalog.ops();
+ Assertions.assertDoesNotThrow(() -> testCatalogOperations.loadView(oldIdent));
+ Assertions.assertThrows(
+ NoSuchViewException.class, () -> testCatalogOperations.loadView(newIdent));
+ return null;
+ });
reset(entityStore);
}
diff --git a/core/src/test/java/org/apache/gravitino/hook/TestFilesetHookDispatcher.java b/core/src/test/java/org/apache/gravitino/hook/TestFilesetHookDispatcher.java
index d3963d7280..2e95dabe13 100644
--- a/core/src/test/java/org/apache/gravitino/hook/TestFilesetHookDispatcher.java
+++ b/core/src/test/java/org/apache/gravitino/hook/TestFilesetHookDispatcher.java
@@ -53,6 +53,7 @@ import org.apache.gravitino.authorization.AccessControlManager;
import org.apache.gravitino.authorization.Owner;
import org.apache.gravitino.authorization.OwnerDispatcher;
import org.apache.gravitino.catalog.CatalogManager;
+import org.apache.gravitino.catalog.CatalogTestUtils;
import org.apache.gravitino.catalog.FilesetDispatcher;
import org.apache.gravitino.catalog.TestFilesetOperationDispatcher;
import org.apache.gravitino.catalog.TestOperationDispatcher;
@@ -87,17 +88,12 @@ public class TestFilesetHookDispatcher extends TestOperationDispatcher {
new SchemaHookDispatcher(TestFilesetOperationDispatcher.getSchemaOperationDispatcher());
FieldUtils.writeField(
- GravitinoEnv.getInstance(), "accessControlDispatcher", accessControlManager, true);
+ GravitinoEnv.getInstance(), "internalAccessControlDispatcher", accessControlManager, true);
catalogManager = Mockito.mock(CatalogManager.class);
FieldUtils.writeField(GravitinoEnv.getInstance(), "catalogManager", catalogManager, true);
BaseCatalog catalog = Mockito.mock(BaseCatalog.class);
Mockito.when(catalog.capability()).thenReturn(Capability.DEFAULT);
- CatalogManager.CatalogWrapper catalogWrapper =
- Mockito.mock(CatalogManager.CatalogWrapper.class);
- Mockito.when(catalogWrapper.catalog()).thenReturn(catalog);
- Mockito.when(catalogWrapper.capabilities()).thenReturn(Capability.DEFAULT);
- Mockito.when(catalogManager.loadCatalog(any())).thenReturn(catalog);
- Mockito.when(catalogManager.loadCatalogAndWrap(any())).thenReturn(catalogWrapper);
+ CatalogTestUtils.mockDoWithCatalog(catalogManager, catalog);
authorizationPlugin = Mockito.mock(AuthorizationPlugin.class);
Mockito.when(catalog.getAuthorizationPlugin()).thenReturn(authorizationPlugin);
}
@@ -110,9 +106,9 @@ public class TestFilesetHookDispatcher extends TestOperationDispatcher {
OwnerDispatcher savedOwnerDispatcher = GravitinoEnv.getInstance().internalOwnerDispatcher();
CatalogManager mockCatalogManager = Mockito.mock(CatalogManager.class);
- CatalogManager.CatalogWrapper mockWrapper = Mockito.mock(CatalogManager.CatalogWrapper.class);
- Mockito.when(mockWrapper.capabilities()).thenReturn(new CaseInsensitiveCapability());
- Mockito.when(mockCatalogManager.loadCatalogAndWrap(any())).thenReturn(mockWrapper);
+ BaseCatalog<?> mockCatalog = Mockito.mock(BaseCatalog.class);
+ Mockito.when(mockCatalog.capability()).thenReturn(new CaseInsensitiveCapability());
+ CatalogTestUtils.mockDoWithCatalog(mockCatalogManager, mockCatalog);
OwnerDispatcher mockOwnerDispatcher = Mockito.mock(OwnerDispatcher.class);
FilesetDispatcher mockFilesetDispatcher = Mockito.mock(FilesetDispatcher.class);
diff --git a/core/src/test/java/org/apache/gravitino/hook/TestFunctionHookDispatcher.java b/core/src/test/java/org/apache/gravitino/hook/TestFunctionHookDispatcher.java
index 104bcb6847..6b375f2af1 100644
--- a/core/src/test/java/org/apache/gravitino/hook/TestFunctionHookDispatcher.java
+++ b/core/src/test/java/org/apache/gravitino/hook/TestFunctionHookDispatcher.java
@@ -36,6 +36,7 @@ import org.apache.gravitino.authorization.GravitinoAuthorizer;
import org.apache.gravitino.authorization.Owner;
import org.apache.gravitino.authorization.OwnerDispatcher;
import org.apache.gravitino.catalog.CatalogManager;
+import org.apache.gravitino.catalog.CatalogTestUtils;
import org.apache.gravitino.catalog.FunctionDispatcher;
import org.apache.gravitino.connector.BaseCatalog;
import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
@@ -221,16 +222,15 @@ public class TestFunctionHookDispatcher {
// mock represents that integration boundary and must not receive a removal callback.
Mockito.verifyNoInteractions(catalogAuthorizationPlugin);
Mockito.verify(catalogManager, Mockito.never()).loadCatalog(any());
- Mockito.verify(catalogManager, Mockito.times(1)).loadCatalogAndWrap(any());
+ Mockito.verify(catalogManager, Mockito.times(1)).doWithCatalog(any(), any());
}
}
private static CatalogManager catalogManagerWith(Capability capability) throws Exception {
CatalogManager catalogManager = Mockito.mock(CatalogManager.class);
- CatalogManager.CatalogWrapper catalogWrapper =
- Mockito.mock(CatalogManager.CatalogWrapper.class);
- Mockito.when(catalogWrapper.capabilities()).thenReturn(capability);
- Mockito.when(catalogManager.loadCatalogAndWrap(any())).thenReturn(catalogWrapper);
+ BaseCatalog<?> catalog = Mockito.mock(BaseCatalog.class);
+ Mockito.when(catalog.capability()).thenReturn(capability);
+ CatalogTestUtils.mockDoWithCatalog(catalogManager, catalog);
return catalogManager;
}
diff --git a/core/src/test/java/org/apache/gravitino/hook/TestModelHookDispatcher.java b/core/src/test/java/org/apache/gravitino/hook/TestModelHookDispatcher.java
index b7c061058c..488cba5747 100644
--- a/core/src/test/java/org/apache/gravitino/hook/TestModelHookDispatcher.java
+++ b/core/src/test/java/org/apache/gravitino/hook/TestModelHookDispatcher.java
@@ -33,7 +33,9 @@ import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.authorization.Owner;
import org.apache.gravitino.authorization.OwnerDispatcher;
import org.apache.gravitino.catalog.CatalogManager;
+import org.apache.gravitino.catalog.CatalogTestUtils;
import org.apache.gravitino.catalog.ModelDispatcher;
+import org.apache.gravitino.connector.BaseCatalog;
import org.apache.gravitino.connector.capability.Capability;
import org.apache.gravitino.connector.capability.CapabilityResult;
import org.apache.gravitino.model.Model;
@@ -49,7 +51,7 @@ public class TestModelHookDispatcher {
private ModelDispatcher mockDispatcher;
private OwnerDispatcher mockOwnerDispatcher;
private CatalogManager mockCatalogManager;
- private CatalogManager.CatalogWrapper mockCatalogWrapper;
+ private BaseCatalog<?> mockCatalog;
// Save the originals before each test and restore them in tearDown so we do not leak null
// state into the GravitinoEnv singleton across tests.
private OwnerDispatcher savedOwnerDispatcher;
@@ -60,9 +62,9 @@ public class TestModelHookDispatcher {
mockDispatcher = mock(ModelDispatcher.class);
mockOwnerDispatcher = mock(OwnerDispatcher.class);
mockCatalogManager = mock(CatalogManager.class);
- mockCatalogWrapper = mock(CatalogManager.CatalogWrapper.class);
- when(mockCatalogManager.loadCatalogAndWrap(any())).thenReturn(mockCatalogWrapper);
- when(mockCatalogWrapper.capabilities()).thenReturn(Capability.DEFAULT);
+ mockCatalog = mock(BaseCatalog.class);
+ CatalogTestUtils.mockDoWithCatalog(mockCatalogManager, mockCatalog);
+ when(mockCatalog.capability()).thenReturn(Capability.DEFAULT);
savedOwnerDispatcher = GravitinoEnv.getInstance().internalOwnerDispatcher();
// Read the catalogManager field directly via reflection because the public accessor
// Preconditions-checks for non-null, which would fail when GravitinoEnv has not been
@@ -104,7 +106,7 @@ public class TestModelHookDispatcher {
@Test
public void testRegisterModelSetsOwnerWithNormalizedIdentifier() throws Exception {
- when(mockCatalogWrapper.capabilities()).thenReturn(new CaseInsensitiveCapability());
+ when(mockCatalog.capability()).thenReturn(new CaseInsensitiveCapability());
NameIdentifier ident =
NameIdentifier.of("test_metalake", "test_catalog", "TEST_SCHEMA", "MY_MODEL");
diff --git a/core/src/test/java/org/apache/gravitino/hook/TestSchemaHookDispatcher.java b/core/src/test/java/org/apache/gravitino/hook/TestSchemaHookDispatcher.java
index a4d0591d1f..66ed954e2e 100644
--- a/core/src/test/java/org/apache/gravitino/hook/TestSchemaHookDispatcher.java
+++ b/core/src/test/java/org/apache/gravitino/hook/TestSchemaHookDispatcher.java
@@ -48,7 +48,9 @@ import org.apache.gravitino.authorization.AuthorizationUtils;
import org.apache.gravitino.authorization.Owner;
import org.apache.gravitino.authorization.OwnerDispatcher;
import org.apache.gravitino.catalog.CatalogManager;
+import org.apache.gravitino.catalog.CatalogTestUtils;
import org.apache.gravitino.catalog.SchemaDispatcher;
+import org.apache.gravitino.connector.BaseCatalog;
import org.apache.gravitino.connector.capability.Capability;
import org.apache.gravitino.connector.capability.CapabilityResult;
import org.apache.gravitino.lock.LockManager;
@@ -66,7 +68,7 @@ public class TestSchemaHookDispatcher {
private SchemaDispatcher mockDispatcher;
private OwnerDispatcher mockOwnerDispatcher;
private CatalogManager mockCatalogManager;
- private CatalogManager.CatalogWrapper mockCatalogWrapper;
+ private BaseCatalog<?> mockCatalog;
// Save the originals before each test and restore them in tearDown so we do not leak null
// state into the GravitinoEnv singleton across tests.
private OwnerDispatcher savedOwnerDispatcher;
@@ -78,9 +80,9 @@ public class TestSchemaHookDispatcher {
mockDispatcher = mock(SchemaDispatcher.class);
mockOwnerDispatcher = mock(OwnerDispatcher.class);
mockCatalogManager = mock(CatalogManager.class);
- mockCatalogWrapper = mock(CatalogManager.CatalogWrapper.class);
- when(mockCatalogManager.loadCatalogAndWrap(any())).thenReturn(mockCatalogWrapper);
- when(mockCatalogWrapper.capabilities()).thenReturn(Capability.DEFAULT);
+ mockCatalog = mock(BaseCatalog.class);
+ CatalogTestUtils.mockDoWithCatalog(mockCatalogManager, mockCatalog);
+ when(mockCatalog.capability()).thenReturn(Capability.DEFAULT);
savedOwnerDispatcher = GravitinoEnv.getInstance().internalOwnerDispatcher();
// Tests in this class that rely on the singleton catalogManager always go through
// GravitinoEnv.getInstance().catalogManager(), but we cannot call the public accessor here
@@ -139,7 +141,7 @@ public class TestSchemaHookDispatcher {
public void testCreateSchemaSetsOwnerWithNormalizedIdentifier() throws Exception {
// Use a case-insensitive capability so the schema name is normalized to lower case before
// setOwners is called, mirroring what NormalizeDispatcher would do for the manager.
- when(mockCatalogWrapper.capabilities()).thenReturn(new CaseInsensitiveCapability());
+ when(mockCatalog.capability()).thenReturn(new CaseInsensitiveCapability());
NameIdentifier ident = NameIdentifier.of("test_metalake", "test_catalog", "MY_SCHEMA");
Schema mockSchema = mock(Schema.class);
@@ -168,7 +170,7 @@ public class TestSchemaHookDispatcher {
public void testCreateHierarchicalSchemaOwnsNewAncestors() throws Exception {
// A capability that permits hierarchical (":"-separated) schema names so the hierarchical name
// is not rejected during normalization.
- when(mockCatalogWrapper.capabilities()).thenReturn(new HierarchicalCapability());
+ when(mockCatalog.capability()).thenReturn(new HierarchicalCapability());
NameIdentifier ident = NameIdentifier.of("test_metalake", "test_catalog", "A:B:C");
Schema mockSchema = mock(Schema.class);
@@ -188,7 +190,7 @@ public class TestSchemaHookDispatcher {
@Test
public void testCreateHierarchicalSchemaKeepsExistingAncestorOwner() throws Exception {
- when(mockCatalogWrapper.capabilities()).thenReturn(new HierarchicalCapability());
+ when(mockCatalog.capability()).thenReturn(new HierarchicalCapability());
NameIdentifier ident = NameIdentifier.of("test_metalake", "test_catalog", "A:B:C");
Schema mockSchema = mock(Schema.class);
diff --git a/core/src/test/java/org/apache/gravitino/hook/TestTableHookDispatcher.java b/core/src/test/java/org/apache/gravitino/hook/TestTableHookDispatcher.java
index bf9431a504..6abb334569 100644
--- a/core/src/test/java/org/apache/gravitino/hook/TestTableHookDispatcher.java
+++ b/core/src/test/java/org/apache/gravitino/hook/TestTableHookDispatcher.java
@@ -35,7 +35,9 @@ import org.apache.gravitino.authorization.AuthorizationUtils;
import org.apache.gravitino.authorization.Owner;
import org.apache.gravitino.authorization.OwnerDispatcher;
import org.apache.gravitino.catalog.CatalogManager;
+import org.apache.gravitino.catalog.CatalogTestUtils;
import org.apache.gravitino.catalog.TableDispatcher;
+import org.apache.gravitino.connector.BaseCatalog;
import org.apache.gravitino.connector.capability.Capability;
import org.apache.gravitino.connector.capability.CapabilityResult;
import org.apache.gravitino.rel.Column;
@@ -82,9 +84,9 @@ public class TestTableHookDispatcher {
@Test
public void testCreateTableSetsOwnerWithNormalizedIdentifier() throws Exception {
CatalogManager catalogManager = Mockito.mock(CatalogManager.class);
- CatalogManager.CatalogWrapper wrapper = Mockito.mock(CatalogManager.CatalogWrapper.class);
- Mockito.when(wrapper.capabilities()).thenReturn(new CaseInsensitiveCapability());
- Mockito.when(catalogManager.loadCatalogAndWrap(any())).thenReturn(wrapper);
+ BaseCatalog<?> catalog = Mockito.mock(BaseCatalog.class);
+ Mockito.when(catalog.capability()).thenReturn(new CaseInsensitiveCapability());
+ CatalogTestUtils.mockDoWithCatalog(catalogManager, catalog);
OwnerDispatcher ownerDispatcher = Mockito.mock(OwnerDispatcher.class);
TableDispatcher dispatcher = Mockito.mock(TableDispatcher.class);
@@ -148,9 +150,9 @@ public class TestTableHookDispatcher {
Mockito.when(dispatcher.createTable(any(), any(), any(), any(), any(), any(), any(), any()))
.thenReturn(Mockito.mock(Table.class));
CatalogManager catalogManager = Mockito.mock(CatalogManager.class);
- CatalogManager.CatalogWrapper wrapper = Mockito.mock(CatalogManager.CatalogWrapper.class);
- Mockito.when(wrapper.capabilities()).thenReturn(Capability.DEFAULT);
- Mockito.when(catalogManager.loadCatalogAndWrap(any())).thenReturn(wrapper);
+ BaseCatalog<?> catalog = Mockito.mock(BaseCatalog.class);
+ Mockito.when(catalog.capability()).thenReturn(Capability.DEFAULT);
+ CatalogTestUtils.mockDoWithCatalog(catalogManager, catalog);
TableHookDispatcher hook =
new TableHookDispatcher(dispatcher, () -> ownerDispatcher, catalogManager);
diff --git a/core/src/test/java/org/apache/gravitino/hook/TestTopicHookDispatcher.java b/core/src/test/java/org/apache/gravitino/hook/TestTopicHookDispatcher.java
index 0d1a025cdd..91da438bcf 100644
--- a/core/src/test/java/org/apache/gravitino/hook/TestTopicHookDispatcher.java
+++ b/core/src/test/java/org/apache/gravitino/hook/TestTopicHookDispatcher.java
@@ -32,6 +32,7 @@ import org.apache.gravitino.authorization.AccessControlManager;
import org.apache.gravitino.authorization.Owner;
import org.apache.gravitino.authorization.OwnerDispatcher;
import org.apache.gravitino.catalog.CatalogManager;
+import org.apache.gravitino.catalog.CatalogTestUtils;
import org.apache.gravitino.catalog.TestOperationDispatcher;
import org.apache.gravitino.catalog.TestTopicOperationDispatcher;
import org.apache.gravitino.catalog.TopicDispatcher;
@@ -63,17 +64,12 @@ public class TestTopicHookDispatcher extends TestOperationDispatcher {
new SchemaHookDispatcher(TestTopicOperationDispatcher.getSchemaOperationDispatcher());
FieldUtils.writeField(
- GravitinoEnv.getInstance(), "accessControlDispatcher", accessControlManager, true);
+ GravitinoEnv.getInstance(), "internalAccessControlDispatcher", accessControlManager, true);
catalogManager = Mockito.mock(CatalogManager.class);
FieldUtils.writeField(GravitinoEnv.getInstance(), "catalogManager", catalogManager, true);
BaseCatalog catalog = Mockito.mock(BaseCatalog.class);
Mockito.when(catalog.capability()).thenReturn(Capability.DEFAULT);
- CatalogManager.CatalogWrapper catalogWrapper =
- Mockito.mock(CatalogManager.CatalogWrapper.class);
- Mockito.when(catalogWrapper.catalog()).thenReturn(catalog);
- Mockito.when(catalogWrapper.capabilities()).thenReturn(Capability.DEFAULT);
- Mockito.when(catalogManager.loadCatalog(any())).thenReturn(catalog);
- Mockito.when(catalogManager.loadCatalogAndWrap(any())).thenReturn(catalogWrapper);
+ CatalogTestUtils.mockDoWithCatalog(catalogManager, catalog);
authorizationPlugin = Mockito.mock(AuthorizationPlugin.class);
Mockito.when(catalog.getAuthorizationPlugin()).thenReturn(authorizationPlugin);
}
@@ -86,9 +82,9 @@ public class TestTopicHookDispatcher extends TestOperationDispatcher {
OwnerDispatcher savedOwnerDispatcher = GravitinoEnv.getInstance().internalOwnerDispatcher();
CatalogManager mockCatalogManager = Mockito.mock(CatalogManager.class);
- CatalogManager.CatalogWrapper mockWrapper = Mockito.mock(CatalogManager.CatalogWrapper.class);
- Mockito.when(mockWrapper.capabilities()).thenReturn(new CaseInsensitiveCapability());
- Mockito.when(mockCatalogManager.loadCatalogAndWrap(any())).thenReturn(mockWrapper);
+ BaseCatalog<?> mockCatalog = Mockito.mock(BaseCatalog.class);
+ Mockito.when(mockCatalog.capability()).thenReturn(new CaseInsensitiveCapability());
+ CatalogTestUtils.mockDoWithCatalog(mockCatalogManager, mockCatalog);
OwnerDispatcher mockOwnerDispatcher = Mockito.mock(OwnerDispatcher.class);
TopicDispatcher mockTopicDispatcher = Mockito.mock(TopicDispatcher.class);
diff --git a/core/src/test/java/org/apache/gravitino/hook/TestViewHookDispatcher.java b/core/src/test/java/org/apache/gravitino/hook/TestViewHookDispatcher.java
index 099a89478a..9bb348c4e4 100644
--- a/core/src/test/java/org/apache/gravitino/hook/TestViewHookDispatcher.java
+++ b/core/src/test/java/org/apache/gravitino/hook/TestViewHookDispatcher.java
@@ -32,7 +32,9 @@ import org.apache.gravitino.authorization.AuthorizationUtils;
import org.apache.gravitino.authorization.Owner;
import org.apache.gravitino.authorization.OwnerDispatcher;
import org.apache.gravitino.catalog.CatalogManager;
+import org.apache.gravitino.catalog.CatalogTestUtils;
import org.apache.gravitino.catalog.ViewDispatcher;
+import org.apache.gravitino.connector.BaseCatalog;
import org.apache.gravitino.connector.capability.Capability;
import org.apache.gravitino.connector.capability.CapabilityResult;
import org.apache.gravitino.rel.Column;
@@ -55,9 +57,9 @@ public class TestViewHookDispatcher {
@Test
public void testCreateViewSetsOwnerWithNormalizedIdentifier() throws Exception {
CatalogManager catalogManager = Mockito.mock(CatalogManager.class);
- CatalogManager.CatalogWrapper wrapper = Mockito.mock(CatalogManager.CatalogWrapper.class);
- Mockito.when(wrapper.capabilities()).thenReturn(new CaseInsensitiveCapability());
- Mockito.when(catalogManager.loadCatalogAndWrap(any())).thenReturn(wrapper);
+ BaseCatalog<?> catalog = Mockito.mock(BaseCatalog.class);
+ Mockito.when(catalog.capability()).thenReturn(new CaseInsensitiveCapability());
+ CatalogTestUtils.mockDoWithCatalog(catalogManager, catalog);
OwnerDispatcher ownerDispatcher = Mockito.mock(OwnerDispatcher.class);
ViewDispatcher dispatcher = Mockito.mock(ViewDispatcher.class);
@@ -103,9 +105,9 @@ public class TestViewHookDispatcher {
.when(ownerDispatcher)
.setOwner(any(), any(), any(), any());
CatalogManager catalogManager = Mockito.mock(CatalogManager.class);
- CatalogManager.CatalogWrapper wrapper = Mockito.mock(CatalogManager.CatalogWrapper.class);
- Mockito.when(wrapper.capabilities()).thenReturn(Capability.DEFAULT);
- Mockito.when(catalogManager.loadCatalogAndWrap(any())).thenReturn(wrapper);
+ BaseCatalog<?> catalog = Mockito.mock(BaseCatalog.class);
+ Mockito.when(catalog.capability()).thenReturn(Capability.DEFAULT);
+ CatalogTestUtils.mockDoWithCatalog(catalogManager, catalog);
ViewDispatcher dispatcher = Mockito.mock(ViewDispatcher.class);
Mockito.when(dispatcher.createView(any(), any(), any(), any(), any(), any(), any()))
.thenReturn(Mockito.mock(View.class));
diff --git a/core/src/test/java/org/apache/gravitino/utils/TestClassLoaderPool.java b/core/src/test/java/org/apache/gravitino/utils/TestClassLoaderPool.java
index 7af4836002..161ae295e1 100644
--- a/core/src/test/java/org/apache/gravitino/utils/TestClassLoaderPool.java
+++ b/core/src/test/java/org/apache/gravitino/utils/TestClassLoaderPool.java
@@ -213,6 +213,26 @@ public class TestClassLoaderPool {
Assertions.assertEquals(0, pool.size());
}
+ @Test
+ public void testCloseWhenIdleDefersActiveEntryCleanup() throws Exception {
+ try (ClassLoaderPool pool = new ClassLoaderPool()) {
+ ClassLoaderKey key = simpleKey("iceberg");
+ PooledClassLoaderEntry entry = pool.acquire(key, this::createDummyClassLoader);
+ entry.classLoader().withClassLoader(classLoader -> null);
+
+ pool.closeWhenIdle();
+
+ Assertions.assertEquals(1, pool.size());
+ Assertions.assertNotNull(entry.classLoader().getInternalClassLoader());
+ Assertions.assertThrows(
+ IllegalStateException.class, () -> pool.acquire(key, this::createDummyClassLoader));
+
+ pool.release(entry);
+ Assertions.assertEquals(0, pool.size());
+ Assertions.assertNull(entry.classLoader().getInternalClassLoader());
+ }
+ }
+
@Test
public void testKeyWithPackageProperty() {
try (ClassLoaderPool pool = new ClassLoaderPool()) {
diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergCleanupHelper.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergCleanupHelper.java
index b01f30eca0..7e6d061115 100644
--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergCleanupHelper.java
+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergCleanupHelper.java
@@ -44,10 +44,7 @@ final class IcebergCleanupHelper {
String metalake = IcebergRESTServerContext.getInstance().metalakeName();
return GravitinoEnv.getInstance()
.catalogManager()
- .loadCatalogAndWrap(NameIdentifier.of(metalake, catalogName))
- .catalog()
- .entity()
- .id();
+ .doWithCatalog(NameIdentifier.of(metalake, catalogName), catalog -> catalog.entity().id());
}
/**
diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/provider/DynamicIcebergConfigProvider.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/provider/DynamicIcebergConfigProvider.java
index fc9efbf8ab..eb48c38ff5 100644
--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/provider/DynamicIcebergConfigProvider.java
+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/provider/DynamicIcebergConfigProvider.java
@@ -32,7 +32,7 @@ import org.apache.gravitino.Catalog;
import org.apache.gravitino.GravitinoEnv;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.auth.AuthProperties;
-import org.apache.gravitino.catalog.CatalogDispatcher;
+import org.apache.gravitino.catalog.CatalogManager;
import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergConstants;
import org.apache.gravitino.client.DefaultOAuth2TokenProvider;
import org.apache.gravitino.client.GravitinoClient;
@@ -94,23 +94,22 @@ public class DynamicIcebergConfigProvider implements IcebergConfigProvider {
IcebergConfig.ICEBERG_CONFIG_PREFIX
+ IcebergConstants.ICEBERG_REST_DEFAULT_DYNAMIC_CATALOG_NAME)));
}
- Catalog catalog;
+ Map<String, String> catalogProperties;
try {
- catalog = getCatalogFetcher().loadCatalog(catalogName);
+ catalogProperties = getCatalogFetcher().loadCatalogProperties(catalogName);
} catch (NoSuchCatalogException e) {
return Optional.empty();
}
+ return Optional.of(getIcebergConfigFromCatalogProperties(catalogProperties));
+ }
+ private static Map<String, String> resolveProps(Catalog catalog) {
Preconditions.checkArgument(
"lakehouse-iceberg".equals(catalog.provider()),
- String.format("%s.%s is not iceberg catalog", gravitinoMetalake, catalogName));
+ String.format("Catalog %s is not an Iceberg catalog", catalog.name()));
// Auxiliary: BaseCatalog + SecretManager plaintext. Standalone: properties + getSecrets,
// then JdbcCredential overlays so credentials win.
- return Optional.of(getIcebergConfigFromCatalogProperties(resolveProps(catalog)));
- }
-
- private static Map<String, String> resolveProps(Catalog catalog) {
if (catalog instanceof BaseCatalog) {
BaseCatalog<?> baseCatalog = (BaseCatalog<?>) catalog;
Map<String, String> props =
@@ -278,13 +277,19 @@ public class DynamicIcebergConfigProvider implements IcebergConfigProvider {
interface CatalogFetcher extends Closeable {
Catalog loadCatalog(String catalogName) throws NoSuchCatalogException;
+ default Map<String, String> loadCatalogProperties(String catalogName)
+ throws NoSuchCatalogException {
+ Catalog catalog = loadCatalog(catalogName);
+ return resolveProps(catalog);
+ }
+
@Override
default void close() {}
}
/**
- * Internal catalog fetcher that uses CatalogDispatcher directly. This bypasses the HTTP layer and
- * is used when running in auxiliary mode (embedded in Gravitino server).
+ * Internal catalog fetcher that uses the lease-aware CatalogManager API. This bypasses the HTTP
+ * layer and is used when running in auxiliary mode (embedded in Gravitino server).
*
* <p>Note: When authorization is enabled (which requires auxiliary mode),
* IcebergCatalogWrapperManager bypasses its cache to avoid consistency issues between the
@@ -292,22 +297,43 @@ public class DynamicIcebergConfigProvider implements IcebergConfigProvider {
*/
private static class InternalCatalogFetcher implements CatalogFetcher {
private final String metalake;
- private final CatalogDispatcher catalogDispatcher;
+ private final CatalogManager catalogManager;
InternalCatalogFetcher(String metalake) {
this.metalake = metalake;
- CatalogDispatcher dispatcher = GravitinoEnv.getInstance().internalCatalogDispatcher();
+ CatalogManager manager;
+ try {
+ manager = GravitinoEnv.getInstance().catalogManager();
+ } catch (IllegalArgumentException e) {
+ throw new IllegalStateException(
+ "Internal CatalogManager is not available. "
+ + "Internal catalog fetcher requires running within Gravitino server.",
+ e);
+ }
Preconditions.checkState(
- dispatcher != null,
- "Internal CatalogDispatcher is not available. "
+ manager != null,
+ "Internal CatalogManager is not available. "
+ "Internal catalog fetcher requires running within Gravitino server.");
- this.catalogDispatcher = dispatcher;
+ this.catalogManager = manager;
}
@Override
public Catalog loadCatalog(String catalogName) throws NoSuchCatalogException {
NameIdentifier catalogIdent = NameIdentifierUtil.ofCatalog(metalake, catalogName);
- return catalogDispatcher.loadCatalog(catalogIdent);
+ return catalogManager.loadCatalog(catalogIdent);
+ }
+
+ @Override
+ public Map<String, String> loadCatalogProperties(String catalogName)
+ throws NoSuchCatalogException {
+ NameIdentifier catalogIdent = NameIdentifierUtil.ofCatalog(metalake, catalogName);
+ return catalogManager.doWithCatalog(
+ catalogIdent,
+ catalog -> {
+ // Auxiliary mode needs raw properties, including hidden credentials. Copy them while
+ // the lease is held so no live BaseCatalog escapes into the caller.
+ return resolveProps(catalog);
+ });
}
}
diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergAsyncPurge.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergAsyncPurge.java
index 3ee6bf6907..7b39b9bd71 100644
--- a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergAsyncPurge.java
+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergAsyncPurge.java
@@ -33,6 +33,7 @@ import java.util.Optional;
import org.apache.gravitino.GravitinoEnv;
import org.apache.gravitino.auth.AuthConstants;
import org.apache.gravitino.catalog.CatalogManager;
+import org.apache.gravitino.catalog.CatalogTestUtils;
import org.apache.gravitino.connector.BaseCatalog;
import org.apache.gravitino.iceberg.service.CatalogWrapperForREST;
import org.apache.gravitino.iceberg.service.IcebergCatalogWrapperManager;
@@ -235,13 +236,11 @@ class TestIcebergAsyncPurge {
MockedStatic<GravitinoEnv> envStatic = mockStatic(GravitinoEnv.class);
GravitinoEnv env = mock(GravitinoEnv.class);
CatalogManager catalogManager = mock(CatalogManager.class);
- CatalogManager.CatalogWrapper wrapper = mock(CatalogManager.CatalogWrapper.class);
BaseCatalog<?> catalog = mock(BaseCatalog.class);
CatalogEntity entity = mock(CatalogEntity.class);
envStatic.when(GravitinoEnv::getInstance).thenReturn(env);
when(env.catalogManager()).thenReturn(catalogManager);
- when(catalogManager.loadCatalogAndWrap(any())).thenReturn(wrapper);
- when(wrapper.catalog()).thenReturn(catalog);
+ CatalogTestUtils.mockDoWithCatalog(catalogManager, catalog);
when(catalog.entity()).thenReturn(entity);
when(entity.id()).thenReturn(CATALOG_ID);
return envStatic;
diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/provider/TestDynamicIcebergConfigProvider.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/provider/TestDynamicIcebergConfigProvider.java
index 3389768d54..18ddf24ca9 100644
--- a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/provider/TestDynamicIcebergConfigProvider.java
+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/provider/TestDynamicIcebergConfigProvider.java
@@ -35,7 +35,7 @@ import org.apache.gravitino.Catalog;
import org.apache.gravitino.Config;
import org.apache.gravitino.GravitinoEnv;
import org.apache.gravitino.NameIdentifier;
-import org.apache.gravitino.catalog.CatalogDispatcher;
+import org.apache.gravitino.catalog.CatalogManager;
import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergConstants;
import org.apache.gravitino.connector.BaseCatalog;
import org.apache.gravitino.credential.Credential;
@@ -54,6 +54,7 @@ import org.apache.gravitino.secret.SecretProviderRegistry;
import org.apache.gravitino.secret.SupportsSecrets;
import org.apache.gravitino.secret.memory.InMemorySecretsProvider;
import org.apache.gravitino.utils.NameIdentifierUtil;
+import org.apache.gravitino.utils.ThrowableFunction;
import org.apache.iceberg.hive.HiveCatalog;
import org.apache.iceberg.jdbc.JdbcCatalog;
import org.junit.jupiter.api.AfterEach;
@@ -77,6 +78,7 @@ public class TestDynamicIcebergConfigProvider {
public void tearDown() throws IllegalAccessException {
// Clean up GravitinoEnv and IcebergRESTServerContext state after each test
FieldUtils.writeField(GravitinoEnv.getInstance(), "internalCatalogDispatcher", null, true);
+ FieldUtils.writeField(GravitinoEnv.getInstance(), "catalogManager", null, true);
FieldUtils.writeField(GravitinoEnv.getInstance(), "secretManager", null, true);
resetServerContext();
}
@@ -300,13 +302,16 @@ public class TestDynamicIcebergConfigProvider {
// Enable authorization to use internal fetcher
createMockServerContext(true);
- // Mock CatalogDispatchers
- CatalogDispatcher mockCatalogDispatcher = Mockito.mock(CatalogDispatcher.class);
- CatalogDispatcher mockInternalCatalogDispatcher = Mockito.mock(CatalogDispatcher.class);
- Catalog mockCatalog = Mockito.mock(Catalog.class);
+ CatalogManager mockCatalogManager = Mockito.mock(CatalogManager.class);
+ BaseCatalog<?> mockCatalog = Mockito.mock(BaseCatalog.class);
+ // The internal fetcher now hands resolveProps the live BaseCatalog, which reads the catalog
+ // entity to publish the Iceberg catalog UUID.
+ CatalogEntity mockCatalogEntity = Mockito.mock(CatalogEntity.class);
+ Mockito.when(mockCatalog.entity()).thenReturn(mockCatalogEntity);
+ Mockito.when(mockCatalogEntity.id()).thenReturn(7L);
NameIdentifier catalogIdent = NameIdentifierUtil.ofCatalog(metalakeName, catalogName);
- Mockito.when(mockInternalCatalogDispatcher.loadCatalog(catalogIdent)).thenReturn(mockCatalog);
+ mockDoWithCatalog(mockCatalogManager, mockCatalog);
Map<String, String> catalogProperties =
new HashMap<String, String>() {
{
@@ -315,16 +320,13 @@ public class TestDynamicIcebergConfigProvider {
}
};
Mockito.when(mockCatalog.provider()).thenReturn("lakehouse-iceberg");
- Mockito.when(mockCatalog.properties()).thenReturn(catalogProperties);
+ Mockito.when(mockCatalog.propertiesWithCredentialProviders()).thenReturn(catalogProperties);
+ SecretManager mockSecretManager = Mockito.mock(SecretManager.class);
+ Mockito.when(mockSecretManager.toPlaintextProperties(catalogProperties))
+ .thenReturn(catalogProperties);
- // Set the mock CatalogDispatchers to GravitinoEnv
- FieldUtils.writeField(
- GravitinoEnv.getInstance(), "catalogDispatcher", mockCatalogDispatcher, true);
- FieldUtils.writeField(
- GravitinoEnv.getInstance(),
- "internalCatalogDispatcher",
- mockInternalCatalogDispatcher,
- true);
+ FieldUtils.writeField(GravitinoEnv.getInstance(), "catalogManager", mockCatalogManager, true);
+ FieldUtils.writeField(GravitinoEnv.getInstance(), "secretManager", mockSecretManager, true);
// Initialize provider with required properties
Map<String, String> properties = new HashMap<>();
@@ -333,12 +335,11 @@ public class TestDynamicIcebergConfigProvider {
DynamicIcebergConfigProvider provider = new DynamicIcebergConfigProvider();
provider.initialize(properties);
- // Test that internal interface is used (internal CatalogDispatcher should be called)
+ // Test that the internal lease-aware interface is used.
Optional<IcebergConfig> icebergConfig = provider.getIcebergCatalogConfig(catalogName);
Assertions.assertTrue(icebergConfig.isPresent());
- Mockito.verify(mockInternalCatalogDispatcher).loadCatalog(catalogIdent);
- Mockito.verify(mockCatalogDispatcher, Mockito.never()).loadCatalog(catalogIdent);
+ Mockito.verify(mockCatalogManager).doWithCatalog(Mockito.eq(catalogIdent), Mockito.any());
}
@Test
@@ -380,15 +381,15 @@ public class TestDynamicIcebergConfigProvider {
}
@Test
- public void testInternalCatalogFetcherWithNullCatalogDispatcher() throws IllegalAccessException {
+ public void testInternalCatalogFetcherWithNullCatalogManager() throws IllegalAccessException {
String metalakeName = "test_metalake";
String catalogName = "internal_catalog";
// Enable authorization to use internal fetcher
createMockServerContext(true);
- // Ensure internal CatalogDispatcher is null (simulating GravitinoEnv not initialized)
- FieldUtils.writeField(GravitinoEnv.getInstance(), "internalCatalogDispatcher", null, true);
+ // Ensure CatalogManager is null (simulating GravitinoEnv not initialized)
+ FieldUtils.writeField(GravitinoEnv.getInstance(), "catalogManager", null, true);
// Initialize provider with required properties
Map<String, String> properties = new HashMap<>();
@@ -401,7 +402,7 @@ public class TestDynamicIcebergConfigProvider {
Assertions.assertThrows(
IllegalStateException.class, () -> provider.getIcebergCatalogConfig(catalogName));
Assertions.assertEquals(
- "Internal CatalogDispatcher is not available. "
+ "Internal CatalogManager is not available. "
+ "Internal catalog fetcher requires running within Gravitino server.",
exception.getMessage());
}
@@ -414,22 +415,15 @@ public class TestDynamicIcebergConfigProvider {
// Enable authorization to use internal fetcher
createMockServerContext(true);
- // Mock internal CatalogDispatcher to throw NoSuchCatalogException
- CatalogDispatcher mockCatalogDispatcher = Mockito.mock(CatalogDispatcher.class);
- CatalogDispatcher mockInternalCatalogDispatcher = Mockito.mock(CatalogDispatcher.class);
+ // Mock the lease-aware CatalogManager to throw NoSuchCatalogException.
+ CatalogManager mockCatalogManager = Mockito.mock(CatalogManager.class);
NameIdentifier catalogIdent =
NameIdentifierUtil.ofCatalog(metalakeName, nonExistentCatalogName);
- Mockito.when(mockInternalCatalogDispatcher.loadCatalog(catalogIdent))
- .thenThrow(new NoSuchCatalogException("Catalog not found: %s", nonExistentCatalogName));
-
- // Set the mock CatalogDispatchers to GravitinoEnv
- FieldUtils.writeField(
- GravitinoEnv.getInstance(), "catalogDispatcher", mockCatalogDispatcher, true);
- FieldUtils.writeField(
- GravitinoEnv.getInstance(),
- "internalCatalogDispatcher",
- mockInternalCatalogDispatcher,
- true);
+ Mockito.doThrow(new NoSuchCatalogException("Catalog not found: %s", nonExistentCatalogName))
+ .when(mockCatalogManager)
+ .doWithCatalog(Mockito.eq(catalogIdent), Mockito.any());
+
+ FieldUtils.writeField(GravitinoEnv.getInstance(), "catalogManager", mockCatalogManager, true);
// Initialize provider with required properties
Map<String, String> properties = new HashMap<>();
@@ -442,8 +436,7 @@ public class TestDynamicIcebergConfigProvider {
Optional<IcebergConfig> result = provider.getIcebergCatalogConfig(nonExistentCatalogName);
Assertions.assertFalse(result.isPresent());
- Mockito.verify(mockInternalCatalogDispatcher).loadCatalog(catalogIdent);
- Mockito.verify(mockCatalogDispatcher, Mockito.never()).loadCatalog(catalogIdent);
+ Mockito.verify(mockCatalogManager).doWithCatalog(Mockito.eq(catalogIdent), Mockito.any());
}
@Test
@@ -527,13 +520,16 @@ public class TestDynamicIcebergConfigProvider {
// Enable authorization to use internal fetcher
createMockServerContext(true);
- // Mock CatalogDispatchers
- CatalogDispatcher mockCatalogDispatcher = Mockito.mock(CatalogDispatcher.class);
- CatalogDispatcher mockInternalCatalogDispatcher = Mockito.mock(CatalogDispatcher.class);
- Catalog mockCatalog = Mockito.mock(Catalog.class);
+ CatalogManager mockCatalogManager = Mockito.mock(CatalogManager.class);
+ BaseCatalog<?> mockCatalog = Mockito.mock(BaseCatalog.class);
+ // The internal fetcher now hands resolveProps the live BaseCatalog, which reads the catalog
+ // entity to publish the Iceberg catalog UUID.
+ CatalogEntity mockCatalogEntity = Mockito.mock(CatalogEntity.class);
+ Mockito.when(mockCatalog.entity()).thenReturn(mockCatalogEntity);
+ Mockito.when(mockCatalogEntity.id()).thenReturn(7L);
NameIdentifier catalogIdent = NameIdentifierUtil.ofCatalog(metalakeName, catalogName);
- Mockito.when(mockInternalCatalogDispatcher.loadCatalog(catalogIdent)).thenReturn(mockCatalog);
+ mockDoWithCatalog(mockCatalogManager, mockCatalog);
Map<String, String> catalogProperties =
new HashMap<String, String>() {
{
@@ -542,16 +538,13 @@ public class TestDynamicIcebergConfigProvider {
}
};
Mockito.when(mockCatalog.provider()).thenReturn("lakehouse-iceberg");
- Mockito.when(mockCatalog.properties()).thenReturn(catalogProperties);
+ Mockito.when(mockCatalog.propertiesWithCredentialProviders()).thenReturn(catalogProperties);
+ SecretManager mockSecretManager = Mockito.mock(SecretManager.class);
+ Mockito.when(mockSecretManager.toPlaintextProperties(catalogProperties))
+ .thenReturn(catalogProperties);
- // Set the mock CatalogDispatchers to GravitinoEnv
- FieldUtils.writeField(
- GravitinoEnv.getInstance(), "catalogDispatcher", mockCatalogDispatcher, true);
- FieldUtils.writeField(
- GravitinoEnv.getInstance(),
- "internalCatalogDispatcher",
- mockInternalCatalogDispatcher,
- true);
+ FieldUtils.writeField(GravitinoEnv.getInstance(), "catalogManager", mockCatalogManager, true);
+ FieldUtils.writeField(GravitinoEnv.getInstance(), "secretManager", mockSecretManager, true);
// Initialize provider with required properties
Map<String, String> properties = new HashMap<>();
@@ -594,15 +587,25 @@ public class TestDynamicIcebergConfigProvider {
Assertions.assertTrue(result.isPresent(), "Each thread should get a valid config");
}
- // Verify internal CatalogDispatcher was called (at least once, possibly more due to
- // concurrency)
- Mockito.verify(mockInternalCatalogDispatcher, Mockito.atLeastOnce()).loadCatalog(catalogIdent);
- Mockito.verify(mockCatalogDispatcher, Mockito.never()).loadCatalog(catalogIdent);
+ // Verify the internal lease-aware path was called (possibly more than once due to concurrency).
+ Mockito.verify(mockCatalogManager, Mockito.atLeastOnce())
+ .doWithCatalog(Mockito.eq(catalogIdent), Mockito.any());
executor.shutdown();
executor.awaitTermination(5, TimeUnit.SECONDS);
}
+ @SuppressWarnings("unchecked")
+ private static void mockDoWithCatalog(CatalogManager catalogManager, BaseCatalog<?> baseCatalog) {
+ Mockito.doAnswer(
+ invocation -> {
+ ThrowableFunction<BaseCatalog, Object> operation = invocation.getArgument(1);
+ return operation.apply(baseCatalog);
+ })
+ .when(catalogManager)
+ .doWithCatalog(Mockito.any(), Mockito.any());
+ }
+
@Test
public void testMergeSecrets() {
String metalakeName = "test_metalake";
diff --git a/server-common/src/test/java/org/apache/gravitino/server/authorization/TestMetadataIdConverter.java b/server-common/src/test/java/org/apache/gravitino/server/authorization/TestMetadataIdConverter.java
index 3adfa55f02..c2065bcbcc 100644
--- a/server-common/src/test/java/org/apache/gravitino/server/authorization/TestMetadataIdConverter.java
+++ b/server-common/src/test/java/org/apache/gravitino/server/authorization/TestMetadataIdConverter.java
@@ -20,6 +20,7 @@
package org.apache.gravitino.server.authorization;
import static org.mockito.Answers.CALLS_REAL_METHODS;
+import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
@@ -216,7 +217,8 @@ public class TestMetadataIdConverter {
MetadataObject fileset =
MetadataObjects.of(
ImmutableList.of("missing_catalog", "schema", "fileset"), MetadataObject.Type.FILESET);
- when(mockCatalogManager.loadCatalogAndWrap(NameIdentifier.of("metalake", "missing_catalog")))
+ when(mockCatalogManager.doWithCatalog(
+ eq(NameIdentifier.of("metalake", "missing_catalog")), any()))
.thenThrow(
new NoSuchCatalogException("Catalog %s does not exist", "metalake.missing_catalog"));