World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#15073] improvement(flink-connector): Add session catalog shadowing option (#15074)
geyanggang7d96ddcfdec0
diff --git a/docs/flink-connector/flink-connector.md b/docs/flink-connector/flink-connector.mdindex 9cd5b1dd10..cb54e19aea 100644--- a/docs/flink-connector/flink-connector.md+++ b/docs/flink-connector/flink-connector.md@@ -58,6 +58,7 @@ Do not mix runtime JARs from different Flink minor versions in the same Flink de| table.catalog-store.gravitino.gravitino.uri | string | (none) | The uri of Gravitino server address. | Yes || table.catalog-store.gravitino.gravitino.enableSessionCatalogSupport | boolean | false | Whether to enable support for Flink's session catalog in the Gravitino catalog store. | No || table.catalog-store.gravitino.gravitino.excludedCatalogs | list | (none) | Semicolon-separated catalog names that are never resolved against Gravitino in this session. Only valid when `enableSessionCatalogSupport` is `true`. See [Use a session catalog with the name of a Gravitino catalog](#use-a-session-catalog-with-the-name-of-a-gravitino-catalog). | No |+| table.catalog-store.gravitino.gravitino.enableSessionCatalogShadowing | boolean | false | Whether a session catalog can use the name of a Gravitino catalog that the session has not accessed yet. Only valid when `enableSessionCatalogSupport` is `true`. See [Let session catalogs shadow Gravitino catalogs](#let-session-catalogs-shadow-gravitino-catalogs). | No || table.catalog-store.gravitino.gravitino.client. | string | (none) | The configuration key prefix for the Gravitino client config. | No |When `table.catalog-store.gravitino.gravitino.enableSessionCatalogSupport` is set to `true`, Gravitino uses `GravitinoSessionCatalogStore`, which combines a `GravitinoCatalogStore` (backed by the Gravitino server) with an in-memory store to support Flink's session catalog. When `false` (the default), only `GravitinoCatalogStore` is used.@@ -69,7 +70,7 @@ When session catalog support is enabled, the following behaviors apply:- **DROP CATALOG**: The in-memory store is checked first. If the catalog exists there it is removed from memory; otherwise it is removed from the Gravitino server.- **SHOW / LIST CATALOGS**: Returns the combined set of catalogs from both the in-memory store and the Gravitino server.- **Session scope**: Catalogs stored only in memory are session-scoped and will not survive when Flink restarts.-- **Name conflict**: `CREATE CATALOG` fails if a catalog with the same name already exists in either store, including a Gravitino catalog created by another client. If a Gravitino catalog with the same name as an existing in-memory catalog is created later, the in-memory entry takes precedence in this session. To create a session catalog with the name of an existing Gravitino catalog, use `excludedCatalogs`.+- **Name conflict**: `CREATE CATALOG` fails if a catalog with the same name already exists in either store, including a Gravitino catalog created by another client. If a Gravitino catalog with the same name as an existing in-memory catalog is created later, the in-memory entry takes precedence in this session. To create a session catalog with the name of an existing Gravitino catalog, use `excludedCatalogs` or `enableSessionCatalogShadowing`.To configure the Gravitino client, use properties prefixed with `table.catalog-store.gravitino.gravitino.client.`. These properties will be passed to the Gravitino client after removing the `table.catalog-store.gravitino.` prefix.@@ -138,9 +139,31 @@ For each excluded name, the Flink session behaves as follows:Exclusion only affects the current Flink session. The Gravitino catalog and its metadata are not modified, and other sessions still see it. Names are case-sensitive.:::caution-A session catalog uses its own connector configuration and authentication. Gravitino does not authorize access through a session catalog, regardless of whether its name is excluded. Excluding a name does not grant any additional access, but make sure that session catalogs are permitted by your platform's access policy.+A session catalog uses its own connector configuration and authentication. Gravitino does not authorize access through a session catalog, regardless of whether its name is excluded or it shadows a Gravitino catalog. Excluding a name or enabling shadowing does not grant any additional access, but make sure that session catalogs are permitted by your platform's access policy.:::+### Let session catalogs shadow Gravitino catalogs++`excludedCatalogs` requires the conflicting names to be known in advance, and it hides the Gravitino catalogs from every job that uses the configuration. If the names are not known, for example because the jobs are maintained by different teams, enable session catalog shadowing instead. The option has no catalog names, so it can be set once in the cluster-wide Flink configuration:++```yaml+table.catalog-store.gravitino.gravitino.enableSessionCatalogSupport: true+table.catalog-store.gravitino.gravitino.enableSessionCatalogShadowing: true+```++With shadowing enabled, a job that runs `CREATE CATALOG paimon_catalog WITH ('type'='paimon', ...)` gets its own session catalog, even if Gravitino has a catalog named `paimon_catalog`. A job that does not create the catalog keeps using the Gravitino catalog.++A Gravitino catalog is *accessed* by a session once the session loads it, for example through `USE CATALOG`, a table lookup, or `DESCRIBE CATALOG`, or creates it through Flink. The Flink session behaves as follows:++- `CREATE CATALOG` with a non-Gravitino-managed type, such as `paimon` or `hive`, creates a session catalog in memory if the session has not accessed a Gravitino catalog with the same name. The session catalog shadows the Gravitino catalog in this session: `USE CATALOG`, table lookups, `ALTER CATALOG`, and `DROP CATALOG` use the session catalog, and `SHOW CATALOGS` lists the name once. Creating a second catalog with the same name still fails.+- `DROP CATALOG` on the session catalog never drops the Gravitino catalog. After the drop, the name resolves to the Gravitino catalog again.+- A Gravitino catalog that the session has accessed cannot be shadowed. `CREATE CATALOG` with its name fails, as it does without shadowing.+- Creating a Gravitino-managed catalog type, such as `gravitino-paimon`, under the name of an existing Gravitino catalog fails, including with `IF NOT EXISTS`. Altering a session catalog that shadows a Gravitino catalog into a Gravitino-managed type also fails.+- `DROP CATALOG` on a Gravitino catalog that the session has not accessed fails with `does not exist`, and `DROP CATALOG IF EXISTS` does nothing. Flink SQL only drops Gravitino catalogs that the session has accessed. To drop a Gravitino catalog from Flink SQL, use it in the session first, or drop it through Gravitino.++Shadowing only affects the current Flink session. The Gravitino catalog and its metadata are not modified, and other sessions still see it. Names are case-sensitive. Names in `excludedCatalogs` are never resolved against Gravitino, regardless of shadowing. When a session catalog shadows a Gravitino catalog, the connector logs a warning.++## Catalog Naming Restrictions:::cautiondiff --git a/flink-connector/flink-common/src/main/java/org/apache/gravitino/flink/connector/store/GravitinoCatalogStoreFactory.java b/flink-connector/flink-common/src/main/java/org/apache/gravitino/flink/connector/store/GravitinoCatalogStoreFactory.javaindex 24f34dc98e..176da31a84 100644--- a/flink-connector/flink-common/src/main/java/org/apache/gravitino/flink/connector/store/GravitinoCatalogStoreFactory.java+++ b/flink-connector/flink-common/src/main/java/org/apache/gravitino/flink/connector/store/GravitinoCatalogStoreFactory.java@@ -22,6 +22,7 @@ package org.apache.gravitino.flink.connector.store;import static org.apache.flink.table.factories.FactoryUtil.createCatalogStoreFactoryHelper;import static org.apache.gravitino.flink.connector.store.GravitinoCatalogStoreFactoryOptions.GRAVITINO;import static org.apache.gravitino.flink.connector.store.GravitinoCatalogStoreFactoryOptions.GRAVITINO_CLIENT_CONFIG;+import static org.apache.gravitino.flink.connector.store.GravitinoCatalogStoreFactoryOptions.GRAVITINO_ENABLE_SESSION_CATALOG_SHADOWING;import static org.apache.gravitino.flink.connector.store.GravitinoCatalogStoreFactoryOptions.GRAVITINO_ENABLE_SESSION_CATALOG_SUPPORT;import static org.apache.gravitino.flink.connector.store.GravitinoCatalogStoreFactoryOptions.GRAVITINO_EXCLUDED_CATALOGS;import static org.apache.gravitino.flink.connector.store.GravitinoCatalogStoreFactoryOptions.GRAVITINO_METALAKE;@@ -83,6 +84,9 @@ public class GravitinoCatalogStoreFactory implements CatalogStoreFactory {// unused client behind.Set<String> excludedCatalogs =parseExcludedCatalogs(options.get(GRAVITINO_EXCLUDED_CATALOGS), sessionCatalogSupport);+ boolean sessionCatalogShadowing =+ parseSessionCatalogShadowing(+ options.get(GRAVITINO_ENABLE_SESSION_CATALOG_SHADOWING), sessionCatalogSupport);this.catalogManager =GravitinoCatalogManager.create(gravitinoUri, gravitinoName, extractClientConfig(options));@@ -97,9 +101,14 @@ public class GravitinoCatalogStoreFactory implements CatalogStoreFactory {+ "can use these names.",excludedCatalogs);}+ if (sessionCatalogShadowing) {+ LOG.info(+ "Session catalog shadowing is enabled; session catalogs can use the names of "+ + "Gravitino catalogs that this session has not accessed.");+ }this.catalogStore =new GravitinoSessionCatalogStore(- gravitinoCatalogStore, memoryCatalogStore, excludedCatalogs);+ gravitinoCatalogStore, memoryCatalogStore, excludedCatalogs, sessionCatalogShadowing);} else {this.catalogStore = gravitinoCatalogStore;}@@ -130,7 +139,28 @@ public class GravitinoCatalogStoreFactory implements CatalogStoreFactory {return ImmutableSet.of(GRAVITINO_CLIENT_CONFIG,GRAVITINO_ENABLE_SESSION_CATALOG_SUPPORT,- GRAVITINO_EXCLUDED_CATALOGS);+ GRAVITINO_EXCLUDED_CATALOGS,+ GRAVITINO_ENABLE_SESSION_CATALOG_SHADOWING);+ }++ /**+ * Validates the session catalog shadowing option.+ *+ * @param sessionCatalogShadowing the configured session catalog shadowing option+ * @param sessionCatalogSupport whether session catalog support is enabled+ * @return the session catalog shadowing option+ * @throws IllegalArgumentException if shadowing is enabled while session catalog support is+ * disabled+ */+ @VisibleForTesting+ static boolean parseSessionCatalogShadowing(+ boolean sessionCatalogShadowing, boolean sessionCatalogSupport) {+ Preconditions.checkArgument(+ !sessionCatalogShadowing || sessionCatalogSupport,+ "%s can only be enabled when %s is true",+ GRAVITINO_ENABLE_SESSION_CATALOG_SHADOWING.key(),+ GRAVITINO_ENABLE_SESSION_CATALOG_SUPPORT.key());+ return sessionCatalogShadowing;}/**diff --git a/flink-connector/flink-common/src/main/java/org/apache/gravitino/flink/connector/store/GravitinoCatalogStoreFactoryOptions.java b/flink-connector/flink-common/src/main/java/org/apache/gravitino/flink/connector/store/GravitinoCatalogStoreFactoryOptions.javaindex 9a4ea1a451..c164213141 100644--- a/flink-connector/flink-common/src/main/java/org/apache/gravitino/flink/connector/store/GravitinoCatalogStoreFactoryOptions.java+++ b/flink-connector/flink-common/src/main/java/org/apache/gravitino/flink/connector/store/GravitinoCatalogStoreFactoryOptions.java@@ -66,6 +66,23 @@ public class GravitinoCatalogStoreFactoryOptions {+ "are never loaded, modified, or dropped by this session. Only valid when "+ "'gravitino.enableSessionCatalogSupport' is true.");+ /**+ * Whether a session catalog that a Flink session explicitly creates can shadow a Gravitino+ * catalog with the same name in that session. The Gravitino catalog is never loaded, modified, or+ * dropped by the session while it is shadowed. Only valid when {@link+ * #GRAVITINO_ENABLE_SESSION_CATALOG_SUPPORT} is {@code true}.+ */+ public static final ConfigOption<Boolean> GRAVITINO_ENABLE_SESSION_CATALOG_SHADOWING =+ ConfigOptions.key("gravitino.enableSessionCatalogShadowing")+ .booleanType()+ .defaultValue(false)+ .withDescription(+ "Whether a session catalog created in a Flink session can use the name of a "+ + "Gravitino catalog that the session has not accessed yet. The session catalog "+ + "shadows the Gravitino catalog in this session only, and the Gravitino "+ + "catalog is never loaded, modified, or dropped while it is shadowed. Only "+ + "valid when 'gravitino.enableSessionCatalogSupport' is true.");+public static final ConfigOption<Map<String, String>> GRAVITINO_CLIENT_CONFIG =ConfigOptions.key("gravitino.client").mapType()diff --git a/flink-connector/flink-common/src/main/java/org/apache/gravitino/flink/connector/store/GravitinoSessionCatalogStore.java b/flink-connector/flink-common/src/main/java/org/apache/gravitino/flink/connector/store/GravitinoSessionCatalogStore.javaindex f31ca1d9d1..b07a367ab4 100644--- a/flink-connector/flink-common/src/main/java/org/apache/gravitino/flink/connector/store/GravitinoSessionCatalogStore.java+++ b/flink-connector/flink-common/src/main/java/org/apache/gravitino/flink/connector/store/GravitinoSessionCatalogStore.java@@ -21,17 +21,26 @@ package org.apache.gravitino.flink.connector.store;import static org.apache.gravitino.flink.connector.utils.FactoryUtils.isGravitinoManagedCatalogType;+import com.google.common.annotations.VisibleForTesting;import com.google.common.collect.ImmutableSet;+import java.lang.ref.WeakReference;import java.util.Collections;import java.util.HashSet;import java.util.Optional;import java.util.Set;+import java.util.concurrent.ConcurrentHashMap;+import javax.annotation.Nullable;+import org.apache.flink.configuration.ConfigOption;+import org.apache.flink.configuration.ConfigOptions;+import org.apache.flink.configuration.ReadableConfig;import org.apache.flink.table.catalog.AbstractCatalogStore;import org.apache.flink.table.catalog.CatalogDescriptor;import org.apache.flink.table.catalog.CommonCatalogOptions;import org.apache.flink.table.catalog.GenericInMemoryCatalogStore;import org.apache.flink.table.catalog.exceptions.CatalogException;import org.apache.flink.util.Preconditions;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;/*** A catalog store that combines a session-scoped in-memory {@link GenericInMemoryCatalogStore} with@@ -56,13 +65,71 @@ import org.apache.flink.util.Preconditions;* loading, modifying, or dropping the Gravitino catalog. Gravitino-managed catalog types cannot be* created under an excluded name because they would be persisted to Gravitino.*+ * <p>When session catalog shadowing is enabled, a session catalog can be created under the name of+ * a Gravitino catalog that this session has not accessed yet, without listing the name in advance.+ * Flink checks {@link #contains(String)} before it creates a catalog, but it also uses {@link+ * #contains(String)} before it drops or alters one. To keep both working, this store tracks the+ * Gravitino catalogs that the session has accessed, that is, loaded through {@link+ * #getCatalog(String)} or created through {@link #storeCatalog(String, CatalogDescriptor)}. These+ * catalogs keep the existing behavior. A Gravitino catalog that the session has not accessed is+ * reported as absent by {@link #contains(String)}, so a session catalog can take its name. The+ * session catalog then shadows the Gravitino catalog in this session, and dropping the session+ * catalog makes the Gravitino catalog visible again. Gravitino-managed catalog types cannot be+ * created under the name of an existing Gravitino catalog.+ ** <p>This store is intended to be used per Flink session, keeping transient catalogs in memory* while delegating persistent catalogs to Apache Gravitino.*/public class GravitinoSessionCatalogStore extends AbstractCatalogStore {++ private static final Logger LOG = LoggerFactory.getLogger(GravitinoSessionCatalogStore.class);++ /**+ * {@link GravitinoCatalogStoreFactoryOptions#GRAVITINO_ENABLE_SESSION_CATALOG_SUPPORT} as seen in+ * the session configuration, where catalog store options carry the {@code+ * table.catalog-store.gravitino.} prefix.+ */+ private static final ConfigOption<Boolean> SESSION_ENABLE_SESSION_CATALOG_SUPPORT =+ ConfigOptions.key(+ sessionConfigurationKey(+ GravitinoCatalogStoreFactoryOptions.GRAVITINO_ENABLE_SESSION_CATALOG_SUPPORT))+ .booleanType()+ .defaultValue(false);++ /**+ * {@link GravitinoCatalogStoreFactoryOptions#GRAVITINO_ENABLE_SESSION_CATALOG_SHADOWING} as seen+ * in the session configuration.+ */+ private static final ConfigOption<Boolean> SESSION_ENABLE_SESSION_CATALOG_SHADOWING =+ ConfigOptions.key(+ sessionConfigurationKey(+ GravitinoCatalogStoreFactoryOptions.GRAVITINO_ENABLE_SESSION_CATALOG_SHADOWING))+ .booleanType()+ .defaultValue(false);++ /**+ * The Gravitino catalog that {@link #contains(String)} has just found shadowed: either reported+ * as absent so that a session catalog can take its name, or already shadowed by a session+ * catalog. Flink calls {@link #contains(String)} and then, on the same thread, instantiates the+ * catalog for CREATE CATALOG or ALTER CATALOG without calling the catalog store in between. The+ * instantiation step reads it to reject Gravitino-managed catalog types, and {@link+ * #storeCatalog(String, CatalogDescriptor)} reads it to log the shadowing.+ *+ * <p>Every method of this store and every check by a Gravitino catalog factory clears it. Flink+ * calls the catalog store of a session before it instantiates a catalog in that session, so a+ * session that uses this store never sees a value left by another session. A value can still be+ * left behind when no catalog is instantiated after the check, for example after {@code DROP+ * CATALOG IF EXISTS}. Such a value is only honored by a factory whose session enables shadowing,+ * and only by the store that recorded it.+ */+ private static final ThreadLocal<ShadowedCatalog> SHADOWED_GRAVITINO_CATALOG =+ new ThreadLocal<>();+private final GenericInMemoryCatalogStore memoryCatalogStore;private final GravitinoCatalogStore gravitinoCatalogStore;private final Set<String> excludedCatalogs;+ private final boolean sessionCatalogShadowing;+ private final Set<String> accessedGravitinoCatalogs = ConcurrentHashMap.newKeySet();/*** Creates a session catalog store without excluded catalog names.@@ -76,7 +143,7 @@ public class GravitinoSessionCatalogStore extends AbstractCatalogStore {}/**- * Creates a session catalog store.+ * Creates a session catalog store with session catalog shadowing disabled.** @param gravitinoCatalogStore the Gravitino-backed catalog store* @param memoryCatalogStore the session-scoped in-memory catalog store@@ -87,17 +154,81 @@ public class GravitinoSessionCatalogStore extends AbstractCatalogStore {GravitinoCatalogStore gravitinoCatalogStore,GenericInMemoryCatalogStore memoryCatalogStore,Set<String> excludedCatalogs) {+ this(gravitinoCatalogStore, memoryCatalogStore, excludedCatalogs, false);+ }++ /**+ * Creates a session catalog store. Package-private because session catalog shadowing relies on+ * {@link GravitinoCatalogStoreFactoryOptions#GRAVITINO_ENABLE_SESSION_CATALOG_SHADOWING} being+ * set in the session configuration, which {@link GravitinoCatalogStoreFactory} guarantees.+ *+ * @param gravitinoCatalogStore the Gravitino-backed catalog store+ * @param memoryCatalogStore the session-scoped in-memory catalog store+ * @param excludedCatalogs catalog names that are never resolved against the Gravitino-backed+ * store+ * @param sessionCatalogShadowing whether a session catalog can shadow a Gravitino catalog with+ * the same name that this session has not accessed yet+ */+ GravitinoSessionCatalogStore(+ GravitinoCatalogStore gravitinoCatalogStore,+ GenericInMemoryCatalogStore memoryCatalogStore,+ Set<String> excludedCatalogs,+ boolean sessionCatalogShadowing) {Preconditions.checkArgument(gravitinoCatalogStore != null, "CatalogStore cannot be null");Preconditions.checkArgument(memoryCatalogStore != null, "MemoryCatalogStore cannot be null");Preconditions.checkArgument(excludedCatalogs != null, "ExcludedCatalogs cannot be null");this.gravitinoCatalogStore = gravitinoCatalogStore;this.memoryCatalogStore = memoryCatalogStore;this.excludedCatalogs = ImmutableSet.copyOf(excludedCatalogs);+ this.sessionCatalogShadowing = sessionCatalogShadowing;+ }++ /**+ * Rejects instantiating a Gravitino-managed catalog under the name of a shadowed Gravitino+ * catalog, either by CREATE CATALOG or by ALTER CATALOG on the session catalog that shadows it.+ * Gravitino catalog factories call this method before they create a catalog, because Flink may+ * instantiate and register a catalog before it stores the catalog in the catalog store. Loading+ * an existing Gravitino catalog is not affected, because Flink always resolves it through {@link+ * #getCatalog(String)} first.+ *+ * <p>The check only applies when the session configuration of the factory enables session catalog+ * shadowing, so a value left behind by another session cannot reject catalogs in a session that+ * does not use this store. A session that uses this store resets the value before every catalog+ * instantiation. This method is intended for Gravitino catalog factories only.+ *+ * @param catalogName the name of the catalog to create+ * @param catalogType the Gravitino-managed catalog type+ * @param sessionConfiguration the session configuration of the catalog factory context+ * @throws CatalogException if a Gravitino catalog with the same name exists and is shadowed in+ * the current session+ */+ public static void checkGravitinoManagedCatalogNotShadowing(+ String catalogName, String catalogType, @Nullable ReadableConfig sessionConfiguration)+ throws CatalogException {+ ShadowedCatalog shadowedCatalog = SHADOWED_GRAVITINO_CATALOG.get();+ SHADOWED_GRAVITINO_CATALOG.remove();+ if (shadowedCatalog == null+ || !shadowedCatalog.catalogName.equals(catalogName)+ || !isSessionCatalogShadowingEnabled(sessionConfiguration)) {+ return;+ }+ // A store that has been garbage collected belongs to a session that no longer exists.+ if (shadowedCatalog.owner.get() != null) {+ throw gravitinoManagedCatalogAlreadyExists(catalogName, catalogType);+ }+ }++ /** Clears the Gravitino catalog name recorded on the current thread. Used by tests only. */+ @VisibleForTesting+ static void clearShadowedGravitinoCatalog() {+ SHADOWED_GRAVITINO_CATALOG.remove();}@Overridepublic void storeCatalog(String catalogName, CatalogDescriptor descriptor)throws CatalogException {+ boolean shadowing = isShadowedGravitinoCatalog(catalogName);+ SHADOWED_GRAVITINO_CATALOG.remove();String catalogType = descriptor.getConfiguration().get(CommonCatalogOptions.CATALOG_TYPE);if (catalogType == null) {throw new CatalogException(@@ -106,6 +237,7 @@ public class GravitinoSessionCatalogStore extends AbstractCatalogStore {+ "Please specify a catalog type.",catalogName, CommonCatalogOptions.CATALOG_TYPE.key()));}+if (isGravitinoManagedCatalogType(catalogType)) {if (isExcluded(catalogName)) {throw new CatalogException(@@ -116,9 +248,23 @@ public class GravitinoSessionCatalogStore extends AbstractCatalogStore {catalogType,GravitinoCatalogStoreFactoryOptions.GRAVITINO_EXCLUDED_CATALOGS.key()));}+ if (shadowing) {+ throw gravitinoManagedCatalogAlreadyExists(catalogName, catalogType);+ }gravitinoCatalogStore.storeCatalog(catalogName, descriptor);+ if (sessionCatalogShadowing) {+ accessedGravitinoCatalogs.add(catalogName);+ }} else {memoryCatalogStore.storeCatalog(catalogName, descriptor);+ if (shadowing) {+ LOG.warn(+ "Session catalog '{}' of type '{}' shadows the Gravitino catalog with the same name "+ + "in this Flink session. The Gravitino catalog is not loaded, modified, or "+ + "dropped while it is shadowed.",+ catalogName,+ catalogType);+ }}}@@ -132,10 +278,12 @@ public class GravitinoSessionCatalogStore extends AbstractCatalogStore {*/@Overridepublic void removeCatalog(String catalogName, boolean ignoreIfNotExists) throws CatalogException {+ SHADOWED_GRAVITINO_CATALOG.remove();if (isExcluded(catalogName) || memoryCatalogStore.contains(catalogName)) {memoryCatalogStore.removeCatalog(catalogName, ignoreIfNotExists);} else {gravitinoCatalogStore.removeCatalog(catalogName, ignoreIfNotExists);+ accessedGravitinoCatalogs.remove(catalogName);}}@@ -148,11 +296,16 @@ public class GravitinoSessionCatalogStore extends AbstractCatalogStore {*/@Overridepublic Optional<CatalogDescriptor> getCatalog(String catalogName) throws CatalogException {+ SHADOWED_GRAVITINO_CATALOG.remove();Optional<CatalogDescriptor> descriptor = memoryCatalogStore.getCatalog(catalogName);if (descriptor.isPresent() || isExcluded(catalogName)) {return descriptor;}- return gravitinoCatalogStore.getCatalog(catalogName);+ Optional<CatalogDescriptor> gravitinoDescriptor = gravitinoCatalogStore.getCatalog(catalogName);+ if (sessionCatalogShadowing && gravitinoDescriptor.isPresent()) {+ accessedGravitinoCatalogs.add(catalogName);+ }+ return gravitinoDescriptor;}/**@@ -163,8 +316,10 @@ public class GravitinoSessionCatalogStore extends AbstractCatalogStore {*/@Overridepublic Set<String> listCatalogs() throws CatalogException {+ SHADOWED_GRAVITINO_CATALOG.remove();Set<String> catalogs = new HashSet<>();catalogs.addAll(memoryCatalogStore.listCatalogs());+Set<String> gravitinoCatalogs;try {gravitinoCatalogs = gravitinoCatalogStore.listCatalogs();@@ -183,7 +338,8 @@ public class GravitinoSessionCatalogStore extends AbstractCatalogStore {/*** Checks whether a catalog exists. Excluded catalog names are only checked in the in-memory- * store.+ * store. When session catalog shadowing is enabled, a Gravitino catalog that this session has not+ * accessed is reported as absent, so that a session catalog can be created under its name.** @param catalogName name of the catalog to check* @return true if the catalog exists in this session@@ -191,13 +347,86 @@ public class GravitinoSessionCatalogStore extends AbstractCatalogStore {*/@Overridepublic boolean contains(String catalogName) throws CatalogException {+ SHADOWED_GRAVITINO_CATALOG.remove();if (memoryCatalogStore.contains(catalogName)) {+ // Flink also checks the store before it replaces a catalog in ALTER CATALOG. Record a+ // session catalog that shadows a Gravitino catalog, so that it cannot be altered into a+ // Gravitino-managed catalog that would resolve the shadowed Gravitino catalog.+ if (sessionCatalogShadowing+ && !isExcluded(catalogName)+ && gravitinoCatalogStore.contains(catalogName)) {+ SHADOWED_GRAVITINO_CATALOG.set(new ShadowedCatalog(this, catalogName));+ }return true;}- return !isExcluded(catalogName) && gravitinoCatalogStore.contains(catalogName);+ if (isExcluded(catalogName)) {+ return false;+ }+ if (!sessionCatalogShadowing || accessedGravitinoCatalogs.contains(catalogName)) {+ return gravitinoCatalogStore.contains(catalogName);+ }+ if (gravitinoCatalogStore.contains(catalogName)) {+ SHADOWED_GRAVITINO_CATALOG.set(new ShadowedCatalog(this, catalogName));+ }+ return false;}private boolean isExcluded(String catalogName) {return excludedCatalogs.contains(catalogName);}++ /** Whether this store has just found the Gravitino catalog with the given name shadowed. */+ private boolean isShadowedGravitinoCatalog(String catalogName) {+ ShadowedCatalog shadowedCatalog = SHADOWED_GRAVITINO_CATALOG.get();+ return sessionCatalogShadowing+ && shadowedCatalog != null+ && shadowedCatalog.owner.get() == this+ && shadowedCatalog.catalogName.equals(catalogName);+ }++ private static boolean isSessionCatalogShadowingEnabled(+ @Nullable ReadableConfig sessionConfiguration) {+ if (sessionConfiguration == null) {+ return false;+ }+ try {+ return sessionConfiguration.get(SESSION_ENABLE_SESSION_CATALOG_SUPPORT)+ && sessionConfiguration.get(SESSION_ENABLE_SESSION_CATALOG_SHADOWING);+ } catch (IllegalArgumentException e) {+ // GravitinoCatalogStoreFactory rejects invalid values, so a session with an invalid value+ // does not use session catalog shadowing.+ return false;+ }+ }++ private static String sessionConfigurationKey(ConfigOption<?> catalogStoreOption) {+ return CommonCatalogOptions.TABLE_CATALOG_STORE_OPTION_PREFIX+ + GravitinoCatalogStoreFactoryOptions.GRAVITINO+ + "."+ + catalogStoreOption.key();+ }++ /**+ * A Gravitino catalog found shadowed by a store. The store is weakly referenced, so that a value+ * left on a pooled thread does not keep a closed session's store reachable.+ */+ private static final class ShadowedCatalog {+ private final WeakReference<GravitinoSessionCatalogStore> owner;+ private final String catalogName;++ private ShadowedCatalog(GravitinoSessionCatalogStore owner, String catalogName) {+ this.owner = new WeakReference<>(owner);+ this.catalogName = catalogName;+ }+ }++ private static CatalogException gravitinoManagedCatalogAlreadyExists(+ String catalogName, String catalogType) {+ return new CatalogException(+ String.format(+ "Cannot create Gravitino-managed catalog '%s' of type '%s': Catalog %s already "+ + "exists in Gravitino. Session catalog shadowing only allows session catalogs to "+ + "use the name of an existing Gravitino catalog.",+ catalogName, catalogType, catalogName));+ }}diff --git a/flink-connector/flink-common/src/main/java/org/apache/gravitino/flink/connector/utils/FactoryUtils.java b/flink-connector/flink-common/src/main/java/org/apache/gravitino/flink/connector/utils/FactoryUtils.javaindex 4556b6565b..786e2665eb 100644--- a/flink-connector/flink-common/src/main/java/org/apache/gravitino/flink/connector/utils/FactoryUtils.java+++ b/flink-connector/flink-common/src/main/java/org/apache/gravitino/flink/connector/utils/FactoryUtils.java@@ -46,6 +46,7 @@ import org.apache.gravitino.flink.connector.iceberg.GravitinoIcebergCatalogFactoimport org.apache.gravitino.flink.connector.jdbc.GravitinoJdbcCatalogFactoryOptions;import org.apache.gravitino.flink.connector.paimon.GravitinoPaimonCatalogFactoryOptions;import org.apache.gravitino.flink.connector.store.GravitinoCatalogStoreFactoryOptions;+import org.apache.gravitino.flink.connector.store.GravitinoSessionCatalogStore;import org.slf4j.Logger;import org.slf4j.LoggerFactory;@@ -179,7 +180,9 @@ public class FactoryUtils {** <p>Gravitino catalog factories must call this method before creating a catalog. It rejects* catalog names excluded from Gravitino by {@link- * GravitinoCatalogStoreFactoryOptions#GRAVITINO_EXCLUDED_CATALOGS} in the current session.+ * GravitinoCatalogStoreFactoryOptions#GRAVITINO_EXCLUDED_CATALOGS} in the current session, and+ * names of Gravitino catalogs that a session catalog would shadow by {@link+ * GravitinoCatalogStoreFactoryOptions#GRAVITINO_ENABLE_SESSION_CATALOG_SHADOWING}.** <p>Note: This utility checks for left-over options in the final step.*@@ -189,6 +192,8 @@ public class FactoryUtils {*/public static FactoryUtil.CatalogFactoryHelper createCatalogFactoryHelper(CatalogFactory factory, CatalogFactory.Context context) {+ GravitinoSessionCatalogStore.checkGravitinoManagedCatalogNotShadowing(+ context.getName(), factory.factoryIdentifier(), context.getConfiguration());checkCatalogNameNotExcluded(factory, context);return new FactoryUtils.GravitinoCatalogFactoryHelper(factory, context);}diff --git a/flink-connector/flink-common/src/test/java/org/apache/gravitino/flink/connector/integration/test/session/FlinkSupportsSessionCatalogIT.java b/flink-connector/flink-common/src/test/java/org/apache/gravitino/flink/connector/integration/test/session/FlinkSupportsSessionCatalogIT.javaindex 754c5c8573..46755893a3 100644--- a/flink-connector/flink-common/src/test/java/org/apache/gravitino/flink/connector/integration/test/session/FlinkSupportsSessionCatalogIT.java+++ b/flink-connector/flink-common/src/test/java/org/apache/gravitino/flink/connector/integration/test/session/FlinkSupportsSessionCatalogIT.java@@ -34,6 +34,7 @@ import org.apache.flink.table.api.EnvironmentSettings;import org.apache.flink.table.api.TableEnvironment;import org.apache.flink.table.catalog.Catalog;import org.apache.flink.table.catalog.CatalogDescriptor;+import org.apache.flink.table.catalog.CatalogManager;import org.apache.flink.table.catalog.CommonCatalogOptions;import org.apache.flink.table.catalog.GenericInMemoryCatalog;import org.apache.flink.table.catalog.hive.factories.HiveCatalogFactoryOptions;@@ -43,6 +44,7 @@ import org.apache.gravitino.flink.connector.integration.test.FlinkEnvIT;import org.apache.gravitino.flink.connector.store.GravitinoCatalogStoreFactoryOptions;import org.junit.jupiter.api.AfterAll;import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Assumptions;import org.junit.jupiter.api.BeforeAll;import org.junit.jupiter.api.Tag;import org.junit.jupiter.api.Test;@@ -62,6 +64,8 @@ import org.slf4j.LoggerFactory;* <li>Both stores contribute to the catalog list returned by {@code SHOW CATALOGS}.* <li>Names listed in {@code gravitino.excludedCatalogs} are never resolved against Gravitino, so* a session catalog can reuse the name of an existing Gravitino catalog without changing it.+ * <li>With {@code gravitino.enableSessionCatalogShadowing}, a session catalog can shadow a+ * Gravitino catalog that the session has not accessed, without changing it.* </ul>** <p>Requires a running Hive Docker container for the Gravitino-managed catalog tests. Concrete@@ -455,6 +459,166 @@ public abstract class FlinkSupportsSessionCatalogIT extends FlinkEnvIT {}}+ /**+ * With {@code gravitino.enableSessionCatalogShadowing}, a session catalog can use the name of a+ * Gravitino catalog without listing the name in advance. The Gravitino catalog is never modified+ * or dropped while it is shadowed, other sessions keep seeing it, and it is visible again in the+ * session once the session catalog is dropped.+ */+ @Test+ public void testShadowingAllowsSessionCatalogWithGravitinoCatalogName() {+ tableEnv.useCatalog(DEFAULT_CATALOG);+ String catalogName = "session_it_shadowed_hive";+ String sessionDatabase = "session_it_shadowing_db";+ createGravitinoHiveCatalog(catalogName);+ try {+ Map<String, String> propertiesBefore = metalake.loadCatalog(catalogName).properties();+ TableEnvironment shadowingEnv = createTableEnvWithShadowing();+ Assertions.assertTrue(Arrays.asList(shadowingEnv.listCatalogs()).contains(catalogName));++ shadowingEnv.executeSql(+ String.format("CREATE CATALOG %s WITH ('type'='generic_in_memory')", catalogName));+ Optional<Catalog> sessionCatalog = shadowingEnv.getCatalog(catalogName);+ Assertions.assertTrue(sessionCatalog.isPresent());+ Assertions.assertInstanceOf(GenericInMemoryCatalog.class, sessionCatalog.get());+ Assertions.assertEquals(+ 1, Arrays.stream(shadowingEnv.listCatalogs()).filter(catalogName::equals).count());+ Assertions.assertThrows(+ Exception.class,+ () ->+ shadowingEnv.executeSql(+ String.format(+ "CREATE CATALOG %s WITH ('type'='generic_in_memory')", catalogName)));++ shadowingEnv.useCatalog(catalogName);+ shadowingEnv.executeSql("CREATE DATABASE " + sessionDatabase);+ Assertions.assertTrue(Arrays.asList(shadowingEnv.listDatabases()).contains(sessionDatabase));+ shadowingEnv.useCatalog(DEFAULT_CATALOG);++ // The Gravitino catalog is untouched, and other sessions keep resolving it.+ org.apache.gravitino.Catalog gravitinoCatalog = metalake.loadCatalog(catalogName);+ Assertions.assertFalse(gravitinoCatalog.asSchemas().schemaExists(sessionDatabase));+ Assertions.assertEquals(propertiesBefore, gravitinoCatalog.properties());+ Assertions.assertFalse(+ tableEnv.getCatalog(catalogName).get() instanceof GenericInMemoryCatalog);++ // Dropping the session catalog never drops the Gravitino catalog, which becomes visible+ // again in the session.+ shadowingEnv.executeSql("DROP CATALOG " + catalogName);+ Assertions.assertTrue(metalake.catalogExists(catalogName));+ Assertions.assertEquals(propertiesBefore, metalake.loadCatalog(catalogName).properties());+ Optional<Catalog> gravitinoCatalogInSession = shadowingEnv.getCatalog(catalogName);+ Assertions.assertTrue(gravitinoCatalogInSession.isPresent());+ Assertions.assertFalse(gravitinoCatalogInSession.get() instanceof GenericInMemoryCatalog);++ // The session has now accessed the Gravitino catalog, so it keeps the existing behavior.+ shadowingEnv.executeSql("DROP CATALOG " + catalogName);+ Assertions.assertFalse(metalake.catalogExists(catalogName));+ } finally {+ tableEnv.useCatalog(DEFAULT_CATALOG);+ tableEnv.executeSql("DROP CATALOG IF EXISTS " + catalogName);+ Assertions.assertFalse(metalake.catalogExists(catalogName));+ }+ }++ /**+ * With shadowing, a Gravitino-managed catalog type cannot be created under the name of an+ * existing Gravitino catalog, and a Gravitino catalog that the session has not accessed is never+ * dropped by Flink SQL. The existing Gravitino catalog must be left unchanged.+ */+ @Test+ public void testShadowingNeverModifiesUnaccessedGravitinoCatalog() {+ tableEnv.useCatalog(DEFAULT_CATALOG);+ String catalogName = "session_it_shadowing_managed_hive";+ createGravitinoHiveCatalog(catalogName);+ try {+ Map<String, String> propertiesBefore = metalake.loadCatalog(catalogName).properties();+ TableEnvironment shadowingEnv = createTableEnvWithShadowing();++ Exception exception =+ Assertions.assertThrows(+ Exception.class,+ () ->+ shadowingEnv.executeSql(+ String.format(+ "CREATE CATALOG %s WITH ("+ + "'type'='%s',"+ + "'hive-conf-dir'='%s',"+ + "'hive.metastore.uris'='%s'"+ + ")",+ catalogName,+ GravitinoHiveCatalogFactoryOptions.IDENTIFIER,+ hiveConfDir,+ hiveMetastoreUri)));+ Assertions.assertTrue(+ containsMessage(exception, "already exists in Gravitino"), collectMessages(exception));+ Assertions.assertEquals(+ 1, Arrays.stream(shadowingEnv.listCatalogs()).filter(catalogName::equals).count());++ Assertions.assertThrows(+ Exception.class, () -> shadowingEnv.executeSql("DROP CATALOG " + catalogName));+ shadowingEnv.executeSql("DROP CATALOG IF EXISTS " + catalogName);+ Assertions.assertTrue(metalake.catalogExists(catalogName));+ Assertions.assertEquals(propertiesBefore, metalake.loadCatalog(catalogName).properties());++ // The Gravitino catalog can still be used in the session.+ shadowingEnv.useCatalog(catalogName);+ shadowingEnv.listDatabases();+ shadowingEnv.useCatalog(DEFAULT_CATALOG);+ } finally {+ tableEnv.useCatalog(DEFAULT_CATALOG);+ tableEnv.executeSql("DROP CATALOG IF EXISTS " + catalogName);+ Assertions.assertFalse(metalake.catalogExists(catalogName));+ }+ }++ /**+ * With shadowing, a session catalog that shadows a Gravitino catalog cannot be altered into a+ * Gravitino-managed catalog type. The session catalog and the Gravitino catalog must be left+ * unchanged. {@code ALTER CATALOG} is available since Flink 1.20.+ */+ @Test+ public void testShadowingRejectsAlteringSessionCatalogToGravitinoManagedType() {+ Assumptions.assumeTrue(+ Arrays.stream(CatalogManager.class.getMethods())+ .anyMatch(method -> method.getName().equals("alterCatalog")),+ "ALTER CATALOG requires Flink 1.20 or later");+ tableEnv.useCatalog(DEFAULT_CATALOG);+ String catalogName = "session_it_shadowing_alter_hive";+ createGravitinoHiveCatalog(catalogName);+ try {+ Map<String, String> propertiesBefore = metalake.loadCatalog(catalogName).properties();+ TableEnvironment shadowingEnv = createTableEnvWithShadowing();+ shadowingEnv.executeSql(+ String.format("CREATE CATALOG %s WITH ('type'='generic_in_memory')", catalogName));++ Exception exception =+ Assertions.assertThrows(+ Exception.class,+ () ->+ shadowingEnv.executeSql(+ String.format(+ "ALTER CATALOG %s SET ("+ + "'type'='%s',"+ + "'hive-conf-dir'='%s',"+ + "'hive.metastore.uris'='%s'"+ + ")",+ catalogName,+ GravitinoHiveCatalogFactoryOptions.IDENTIFIER,+ hiveConfDir,+ hiveMetastoreUri)));+ Assertions.assertTrue(+ containsMessage(exception, "already exists in Gravitino"), collectMessages(exception));+ Assertions.assertInstanceOf(+ GenericInMemoryCatalog.class, shadowingEnv.getCatalog(catalogName).get());+ Assertions.assertEquals(propertiesBefore, metalake.loadCatalog(catalogName).properties());+ } finally {+ tableEnv.useCatalog(DEFAULT_CATALOG);+ tableEnv.executeSql("DROP CATALOG IF EXISTS " + catalogName);+ Assertions.assertFalse(metalake.catalogExists(catalogName));+ }+ }+private static boolean containsMessage(Throwable throwable, String expectedMessage) {for (Throwable current = throwable; current != null; current = current.getCause()) {if (current.getMessage() != null && current.getMessage().contains(expectedMessage)) {@@ -494,6 +658,26 @@ public abstract class FlinkSupportsSessionCatalogIT extends FlinkEnvIT {* {@code tableEnv}.*/private TableEnvironment createTableEnvExcluding(String... catalogNames) {+ Configuration configuration = sessionCatalogConfiguration();+ configuration.setString(+ "table.catalog-store.gravitino.gravitino.excludedCatalogs", String.join(";", catalogNames));+ return TableEnvironment.create(+ EnvironmentSettings.newInstance().withConfiguration(configuration).inBatchMode().build());+ }++ /**+ * Creates a separate Flink session with session catalog shadowing enabled. The session is not+ * closed, for the same reason as {@link #createTableEnvExcluding(String...)}.+ */+ private TableEnvironment createTableEnvWithShadowing() {+ Configuration configuration = sessionCatalogConfiguration();+ configuration.setString(+ "table.catalog-store.gravitino.gravitino.enableSessionCatalogShadowing", "true");+ return TableEnvironment.create(+ EnvironmentSettings.newInstance().withConfiguration(configuration).inBatchMode().build());+ }++ private Configuration sessionCatalogConfiguration() {Configuration configuration = new Configuration();configuration.setString("table.catalog-store.kind", GravitinoCatalogStoreFactoryOptions.GRAVITINO);@@ -501,10 +685,7 @@ public abstract class FlinkSupportsSessionCatalogIT extends FlinkEnvIT {configuration.setString("table.catalog-store.gravitino.gravitino.uri", gravitinoUri);configuration.setString("table.catalog-store.gravitino.gravitino.enableSessionCatalogSupport", "true");- configuration.setString(- "table.catalog-store.gravitino.gravitino.excludedCatalogs", String.join(";", catalogNames));- return TableEnvironment.create(- EnvironmentSettings.newInstance().withConfiguration(configuration).inBatchMode().build());+ return configuration;}private static void initHiveConfDir() {diff --git a/flink-connector/flink-common/src/test/java/org/apache/gravitino/flink/connector/store/TestGravitinoCatalogStoreFactory.java b/flink-connector/flink-common/src/test/java/org/apache/gravitino/flink/connector/store/TestGravitinoCatalogStoreFactory.javaindex 30b0aeb3dc..52bd8f8085 100644--- a/flink-connector/flink-common/src/test/java/org/apache/gravitino/flink/connector/store/TestGravitinoCatalogStoreFactory.java+++ b/flink-connector/flink-common/src/test/java/org/apache/gravitino/flink/connector/store/TestGravitinoCatalogStoreFactory.java@@ -44,6 +44,8 @@ public class TestGravitinoCatalogStoreFactory {private static final String EXCLUDED_CATALOGS_KEY ="table.catalog-store.gravitino.gravitino.excludedCatalogs";+ private static final String SESSION_CATALOG_SHADOWING_KEY =+ "table.catalog-store.gravitino.gravitino.enableSessionCatalogShadowing";/*** When {@code gravitino.enableSessionCatalogSupport=true} the factory must return a {@link@@ -213,6 +215,58 @@ public class TestGravitinoCatalogStoreFactory {Assertions.assertNull(factory.createCatalogStore());}+ // -------------------------------------------------------------------------+ // session catalog shadowing+ // -------------------------------------------------------------------------++ @Test+ void testOptionParsing_sessionCatalogShadowingAbsent_defaultsToFalse() {+ Assertions.assertFalse(parseSessionCatalogShadowingOption(baseConfiguration()));+ }++ @Test+ @SuppressWarnings("deprecation")+ void testOptionParsing_sessionCatalogShadowing_isReadFromConfig() {+ Configuration configuration = baseConfiguration();+ configuration.setString(SESSION_CATALOG_SHADOWING_KEY, "true");+ Assertions.assertTrue(parseSessionCatalogShadowingOption(configuration));+ }++ @Test+ void testParseSessionCatalogShadowing() {+ Assertions.assertTrue(GravitinoCatalogStoreFactory.parseSessionCatalogShadowing(true, true));+ Assertions.assertFalse(GravitinoCatalogStoreFactory.parseSessionCatalogShadowing(false, true));+ Assertions.assertFalse(GravitinoCatalogStoreFactory.parseSessionCatalogShadowing(false, false));+ IllegalArgumentException exception =+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> GravitinoCatalogStoreFactory.parseSessionCatalogShadowing(true, false));+ Assertions.assertTrue(+ exception+ .getMessage()+ .contains(+ GravitinoCatalogStoreFactoryOptions.GRAVITINO_ENABLE_SESSION_CATALOG_SUPPORT+ .key()));+ }++ /**+ * The real {@link GravitinoCatalogStoreFactory#open} path must reject session catalog shadowing+ * when session catalog support is disabled, before any Gravitino client is created.+ */+ @Test+ @SuppressWarnings("deprecation")+ void testOpen_sessionCatalogShadowingWithoutSessionCatalogSupport_failsFast() {+ Configuration configuration = baseConfiguration();+ configuration.setString(SESSION_CATALOG_SHADOWING_KEY, "true");+ CatalogStoreFactory.Context context =+ TableFactoryUtil.buildCatalogStoreFactoryContext(+ configuration, TestGravitinoCatalogStoreFactory.class.getClassLoader());++ GravitinoCatalogStoreFactory factory = new GravitinoCatalogStoreFactory();+ Assertions.assertThrows(IllegalArgumentException.class, () -> factory.open(context));+ Assertions.assertNull(factory.createCatalogStore());+ }+// -------------------------------------------------------------------------// helpers// -------------------------------------------------------------------------@@ -283,6 +337,18 @@ public class TestGravitinoCatalogStoreFactory {return helper.getOptions().get(GravitinoCatalogStoreFactoryOptions.GRAVITINO_EXCLUDED_CATALOGS);}+ private static boolean parseSessionCatalogShadowingOption(Configuration configuration) {+ CatalogStoreFactory.Context context =+ TableFactoryUtil.buildCatalogStoreFactoryContext(+ configuration, TestGravitinoCatalogStoreFactory.class.getClassLoader());+ FactoryUtil.FactoryHelper<CatalogStoreFactory> helper =+ createCatalogStoreFactoryHelper(new GravitinoCatalogStoreFactory(), context);+ helper.validate();+ return helper+ .getOptions()+ .get(GravitinoCatalogStoreFactoryOptions.GRAVITINO_ENABLE_SESSION_CATALOG_SHADOWING);+ }+private static Configuration baseConfiguration() {Configuration configuration = new Configuration();configuration.setString(diff --git a/flink-connector/flink-common/src/test/java/org/apache/gravitino/flink/connector/store/TestGravitinoSessionCatalogStore.java b/flink-connector/flink-common/src/test/java/org/apache/gravitino/flink/connector/store/TestGravitinoSessionCatalogStore.javaindex a31037563a..4e6a89c205 100644--- a/flink-connector/flink-common/src/test/java/org/apache/gravitino/flink/connector/store/TestGravitinoSessionCatalogStore.java+++ b/flink-connector/flink-common/src/test/java/org/apache/gravitino/flink/connector/store/TestGravitinoSessionCatalogStore.java@@ -29,6 +29,7 @@ import static org.mockito.Mockito.verify;import static org.mockito.Mockito.when;import com.google.common.collect.ImmutableSet;+import java.util.HashMap;import java.util.Locale;import java.util.Optional;import java.util.Set;@@ -37,6 +38,11 @@ import org.apache.flink.table.catalog.CatalogDescriptor;import org.apache.flink.table.catalog.CommonCatalogOptions;import org.apache.flink.table.catalog.GenericInMemoryCatalogStore;import org.apache.flink.table.catalog.exceptions.CatalogException;+import org.apache.flink.table.factories.CatalogFactory;+import org.apache.flink.table.factories.FactoryUtil;+import org.apache.gravitino.flink.connector.utils.FactoryUtils;+import org.apache.gravitino.flink.connector.utils.FakeExternalCatalogFactory;+import org.junit.jupiter.api.AfterEach;import org.junit.jupiter.api.Assertions;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;@@ -59,6 +65,12 @@ public class TestGravitinoSessionCatalogStore {/** A catalog name excluded from Gravitino in the session. */private static final String EXCLUDED_CATALOG = "paimon_catalog";+ /** The name of a Gravitino catalog that a session catalog shadows. */+ private static final String SHADOWED_CATALOG = "shadowed_catalog";++ /** The session configuration of a session that enables session catalog shadowing. */+ private static final Configuration SHADOWING_SESSION_CONFIGURATION = shadowingConfiguration();+private GravitinoCatalogStore gravitinoCatalogStore;private GenericInMemoryCatalogStore memoryCatalogStore;private GravitinoSessionCatalogStore sessionCatalogStore;@@ -77,6 +89,11 @@ public class TestGravitinoSessionCatalogStore {new GravitinoSessionCatalogStore(gravitinoCatalogStore, memoryCatalogStore);}+ @AfterEach+ void tearDown() {+ GravitinoSessionCatalogStore.clearShadowedGravitinoCatalog();+ }+@Testvoid testKnownGravitinoCatalogTypesAreGravitinoManaged() {Assertions.assertTrue(isGravitinoManagedCatalogType("gravitino-hive"));@@ -359,10 +376,340 @@ public class TestGravitinoSessionCatalogStore {Assertions.assertTrue(store.contains(otherCase));}+ // -------------------------------------------------------------------------+ // session catalog shadowing+ // -------------------------------------------------------------------------++ @Test+ void testShadowing_contains_unaccessedGravitinoCatalog_returnsFalse() {+ GravitinoSessionCatalogStore store = shadowingStore(new GenericInMemoryCatalogStore());+ when(gravitinoCatalogStore.contains(SHADOWED_CATALOG)).thenReturn(true);++ Assertions.assertFalse(store.contains(SHADOWED_CATALOG));+ verify(gravitinoCatalogStore).contains(SHADOWED_CATALOG);+ Assertions.assertFalse(store.contains("missing_catalog"));+ }++ @Test+ void testShadowing_storeSessionCatalog_shadowsGravitinoCatalog() {+ GenericInMemoryCatalogStore memoryStore = new GenericInMemoryCatalogStore();+ GravitinoSessionCatalogStore store = shadowingStore(memoryStore);+ when(gravitinoCatalogStore.contains(SHADOWED_CATALOG)).thenReturn(true);+ CatalogDescriptor sessionDescriptor = descriptorWithType(SESSION_CATALOG_TYPE);++ Assertions.assertFalse(store.contains(SHADOWED_CATALOG));+ store.storeCatalog(SHADOWED_CATALOG, sessionDescriptor);++ Assertions.assertTrue(memoryStore.contains(SHADOWED_CATALOG));+ Assertions.assertTrue(store.contains(SHADOWED_CATALOG));+ Assertions.assertEquals(Optional.of(sessionDescriptor), store.getCatalog(SHADOWED_CATALOG));+ when(gravitinoCatalogStore.listCatalogs()).thenReturn(ImmutableSet.of(SHADOWED_CATALOG));+ Assertions.assertEquals(ImmutableSet.of(SHADOWED_CATALOG), store.listCatalogs());++ store.removeCatalog(SHADOWED_CATALOG, false);+ Assertions.assertFalse(memoryStore.contains(SHADOWED_CATALOG));+ verify(gravitinoCatalogStore, never()).getCatalog(anyString());+ verify(gravitinoCatalogStore, never()).storeCatalog(anyString(), any());+ verify(gravitinoCatalogStore, never()).removeCatalog(anyString(), anyBoolean());+ }++ @Test+ void testShadowing_removeSessionCatalog_revealsGravitinoCatalog() {+ GravitinoSessionCatalogStore store = shadowingStore(new GenericInMemoryCatalogStore());+ CatalogDescriptor gravitinoDescriptor = descriptorWithType(GRAVITINO_CATALOG_TYPE);+ when(gravitinoCatalogStore.contains(SHADOWED_CATALOG)).thenReturn(true);+ when(gravitinoCatalogStore.getCatalog(SHADOWED_CATALOG))+ .thenReturn(Optional.of(gravitinoDescriptor));++ Assertions.assertFalse(store.contains(SHADOWED_CATALOG));+ store.storeCatalog(SHADOWED_CATALOG, descriptorWithType(SESSION_CATALOG_TYPE));+ store.removeCatalog(SHADOWED_CATALOG, false);++ Assertions.assertEquals(Optional.of(gravitinoDescriptor), store.getCatalog(SHADOWED_CATALOG));+ verify(gravitinoCatalogStore, never()).removeCatalog(anyString(), anyBoolean());+ }++ @Test+ void testShadowing_accessedGravitinoCatalog_keepsExistingBehavior() {+ GravitinoSessionCatalogStore store = shadowingStore(new GenericInMemoryCatalogStore());+ when(gravitinoCatalogStore.contains(SHADOWED_CATALOG)).thenReturn(true);+ when(gravitinoCatalogStore.getCatalog(SHADOWED_CATALOG))+ .thenReturn(Optional.of(descriptorWithType(GRAVITINO_CATALOG_TYPE)));++ Assertions.assertTrue(store.getCatalog(SHADOWED_CATALOG).isPresent());+ Assertions.assertTrue(store.contains(SHADOWED_CATALOG));++ store.removeCatalog(SHADOWED_CATALOG, false);+ verify(gravitinoCatalogStore).removeCatalog(SHADOWED_CATALOG, false);+ // After the Gravitino catalog is dropped, the name is no longer tracked as accessed.+ Assertions.assertFalse(store.contains(SHADOWED_CATALOG));+ }++ @Test+ void testShadowing_missingGravitinoCatalog_isNotTrackedAsAccessed() {+ GravitinoSessionCatalogStore store = shadowingStore(new GenericInMemoryCatalogStore());+ when(gravitinoCatalogStore.getCatalog(SHADOWED_CATALOG)).thenReturn(Optional.empty());+ Assertions.assertFalse(store.getCatalog(SHADOWED_CATALOG).isPresent());++ when(gravitinoCatalogStore.contains(SHADOWED_CATALOG)).thenReturn(true);+ Assertions.assertFalse(store.contains(SHADOWED_CATALOG));+ }++ @Test+ void testShadowing_gravitinoCatalogCreatedInSession_keepsExistingBehavior() {+ GravitinoSessionCatalogStore store = shadowingStore(new GenericInMemoryCatalogStore());+ CatalogDescriptor gravitinoDescriptor = descriptorWithType(GRAVITINO_CATALOG_TYPE);++ Assertions.assertFalse(store.contains("new_gravitino_catalog"));+ store.storeCatalog("new_gravitino_catalog", gravitinoDescriptor);+ verify(gravitinoCatalogStore).storeCatalog("new_gravitino_catalog", gravitinoDescriptor);++ when(gravitinoCatalogStore.contains("new_gravitino_catalog")).thenReturn(true);+ Assertions.assertTrue(store.contains("new_gravitino_catalog"));+ store.removeCatalog("new_gravitino_catalog", false);+ verify(gravitinoCatalogStore).removeCatalog("new_gravitino_catalog", false);+ }++ @Test+ void testShadowing_storeGravitinoManagedCatalogUnderShadowedName_isRejected() {+ GenericInMemoryCatalogStore memoryStore = new GenericInMemoryCatalogStore();+ GravitinoSessionCatalogStore store = shadowingStore(memoryStore);+ when(gravitinoCatalogStore.contains(SHADOWED_CATALOG)).thenReturn(true);++ Assertions.assertFalse(store.contains(SHADOWED_CATALOG));+ CatalogException exception =+ Assertions.assertThrows(+ CatalogException.class,+ () -> store.storeCatalog(SHADOWED_CATALOG, descriptorWithType(GRAVITINO_CATALOG_TYPE)));++ Assertions.assertTrue(exception.getMessage().contains("already exists"));+ Assertions.assertTrue(exception.getMessage().contains(SHADOWED_CATALOG));+ Assertions.assertFalse(memoryStore.contains(SHADOWED_CATALOG));+ verify(gravitinoCatalogStore, never()).storeCatalog(anyString(), any());+ }++ @Test+ void testShadowing_factoryCheck_rejectsOnlyTheShadowedNameOnce() {+ GravitinoSessionCatalogStore store = shadowingStore(new GenericInMemoryCatalogStore());+ when(gravitinoCatalogStore.contains(SHADOWED_CATALOG)).thenReturn(true);++ Assertions.assertFalse(store.contains(SHADOWED_CATALOG));+ GravitinoSessionCatalogStore.checkGravitinoManagedCatalogNotShadowing(+ "other_catalog", GRAVITINO_CATALOG_TYPE, SHADOWING_SESSION_CONFIGURATION);+ // The check consumes the recorded name, whether it matches or not.+ GravitinoSessionCatalogStore.checkGravitinoManagedCatalogNotShadowing(+ SHADOWED_CATALOG, GRAVITINO_CATALOG_TYPE, SHADOWING_SESSION_CONFIGURATION);++ Assertions.assertFalse(store.contains(SHADOWED_CATALOG));+ CatalogException exception =+ Assertions.assertThrows(+ CatalogException.class,+ () ->+ GravitinoSessionCatalogStore.checkGravitinoManagedCatalogNotShadowing(+ SHADOWED_CATALOG, GRAVITINO_CATALOG_TYPE, SHADOWING_SESSION_CONFIGURATION));+ Assertions.assertTrue(exception.getMessage().contains(GRAVITINO_CATALOG_TYPE));+ GravitinoSessionCatalogStore.checkGravitinoManagedCatalogNotShadowing(+ SHADOWED_CATALOG, GRAVITINO_CATALOG_TYPE, SHADOWING_SESSION_CONFIGURATION);+ }++ @Test+ void testShadowing_contains_sessionCatalogShadowingGravitinoCatalog_isRecorded() {+ GenericInMemoryCatalogStore memoryStore = new GenericInMemoryCatalogStore();+ GravitinoSessionCatalogStore store = shadowingStore(memoryStore);+ memoryStore.storeCatalog(SHADOWED_CATALOG, descriptorWithType(SESSION_CATALOG_TYPE));+ memoryStore.storeCatalog("session_only_catalog", descriptorWithType(SESSION_CATALOG_TYPE));+ when(gravitinoCatalogStore.contains(SHADOWED_CATALOG)).thenReturn(true);++ // ALTER CATALOG checks the store before Flink instantiates the replacement catalog.+ Assertions.assertTrue(store.contains(SHADOWED_CATALOG));+ Assertions.assertThrows(+ CatalogException.class,+ () ->+ GravitinoSessionCatalogStore.checkGravitinoManagedCatalogNotShadowing(+ SHADOWED_CATALOG, GRAVITINO_CATALOG_TYPE, SHADOWING_SESSION_CONFIGURATION));++ // A session catalog without a Gravitino catalog of the same name is not recorded.+ Assertions.assertTrue(store.contains("session_only_catalog"));+ GravitinoSessionCatalogStore.checkGravitinoManagedCatalogNotShadowing(+ "session_only_catalog", GRAVITINO_CATALOG_TYPE, SHADOWING_SESSION_CONFIGURATION);+ }++ @Test+ void testShadowing_contains_excludedSessionCatalog_neverChecksGravitino() {+ GenericInMemoryCatalogStore memoryStore = openedMemoryStore();+ GravitinoSessionCatalogStore store =+ new GravitinoSessionCatalogStore(+ gravitinoCatalogStore, memoryStore, ImmutableSet.of(EXCLUDED_CATALOG), true);+ memoryStore.storeCatalog(EXCLUDED_CATALOG, descriptorWithType(SESSION_CATALOG_TYPE));++ Assertions.assertTrue(store.contains(EXCLUDED_CATALOG));+ verify(gravitinoCatalogStore, never()).contains(anyString());+ }++ @Test+ void testShadowing_factoryCheck_ignoresSessionsWithoutShadowing() {+ GravitinoSessionCatalogStore store = shadowingStore(new GenericInMemoryCatalogStore());+ when(gravitinoCatalogStore.contains(SHADOWED_CATALOG)).thenReturn(true);++ for (Configuration sessionConfiguration :+ new Configuration[] {+ null,+ new Configuration(),+ sessionCatalogSupportOnlyConfiguration(),+ invalidShadowingConfiguration()+ }) {+ Assertions.assertFalse(store.contains(SHADOWED_CATALOG));+ GravitinoSessionCatalogStore.checkGravitinoManagedCatalogNotShadowing(+ SHADOWED_CATALOG, GRAVITINO_CATALOG_TYPE, sessionConfiguration);+ // The check consumes the recorded name even when it does not apply.+ GravitinoSessionCatalogStore.checkGravitinoManagedCatalogNotShadowing(+ SHADOWED_CATALOG, GRAVITINO_CATALOG_TYPE, SHADOWING_SESSION_CONFIGURATION);+ }+ }++ @Test+ void testShadowing_storeCatalog_ignoresCatalogRecordedByAnotherStore() {+ GravitinoSessionCatalogStore store = shadowingStore(new GenericInMemoryCatalogStore());+ GravitinoCatalogStore otherGravitinoCatalogStore = mock(GravitinoCatalogStore.class);+ GravitinoSessionCatalogStore otherStore =+ new GravitinoSessionCatalogStore(+ otherGravitinoCatalogStore, openedMemoryStore(), ImmutableSet.of(), true);+ when(gravitinoCatalogStore.contains(SHADOWED_CATALOG)).thenReturn(true);++ Assertions.assertFalse(store.contains(SHADOWED_CATALOG));+ // Another store on the same thread stores a catalog with the same name without checking first.+ // The value recorded by the first store must not apply to it.+ CatalogDescriptor gravitinoDescriptor = descriptorWithType(GRAVITINO_CATALOG_TYPE);+ otherStore.storeCatalog(SHADOWED_CATALOG, gravitinoDescriptor);++ verify(otherGravitinoCatalogStore).storeCatalog(SHADOWED_CATALOG, gravitinoDescriptor);+ }++ @Test+ void testShadowing_catalogFactoryHelper_rejectsShadowedGravitinoCatalogName() {+ when(gravitinoCatalogStore.contains("paimon_catalog")).thenReturn(true);+ GravitinoSessionCatalogStore store = shadowingStore(new GenericInMemoryCatalogStore());++ // Flink checks the catalog store and then instantiates the catalog on the same thread.+ Assertions.assertFalse(store.contains("paimon_catalog"));+ CatalogException exception =+ Assertions.assertThrows(+ CatalogException.class,+ () ->+ FactoryUtils.createCatalogFactoryHelper(+ new FakeExternalCatalogFactory(),+ factoryContext("paimon_catalog", SHADOWING_SESSION_CONFIGURATION)));+ Assertions.assertTrue(exception.getMessage().contains("paimon_catalog"));+ Assertions.assertTrue(exception.getMessage().contains(FakeExternalCatalogFactory.IDENTIFIER));++ // The check applies to the creation that follows the store check only.+ Assertions.assertNotNull(+ FactoryUtils.createCatalogFactoryHelper(+ new FakeExternalCatalogFactory(),+ factoryContext("paimon_catalog", SHADOWING_SESSION_CONFIGURATION)));++ // A session that does not enable shadowing is never affected by the value left by the store.+ Assertions.assertFalse(store.contains("paimon_catalog"));+ Assertions.assertNotNull(+ FactoryUtils.createCatalogFactoryHelper(+ new FakeExternalCatalogFactory(),+ factoryContext("paimon_catalog", new Configuration())));+ }++ @Test+ void testShadowing_recordedNameIsClearedByEveryStoreOperation() {+ GravitinoSessionCatalogStore store = shadowingStore(new GenericInMemoryCatalogStore());+ when(gravitinoCatalogStore.contains(SHADOWED_CATALOG)).thenReturn(true);+ when(gravitinoCatalogStore.getCatalog(anyString())).thenReturn(Optional.empty());+ when(gravitinoCatalogStore.listCatalogs()).thenReturn(ImmutableSet.of());++ for (Runnable operation :+ new Runnable[] {+ () -> store.contains("missing_catalog"),+ () -> store.getCatalog("missing_catalog"),+ () -> store.listCatalogs(),+ () -> store.removeCatalog("missing_catalog", true),+ () -> store.storeCatalog("session_catalog", descriptorWithType(SESSION_CATALOG_TYPE))+ }) {+ Assertions.assertFalse(store.contains(SHADOWED_CATALOG));+ operation.run();+ GravitinoSessionCatalogStore.checkGravitinoManagedCatalogNotShadowing(+ SHADOWED_CATALOG, GRAVITINO_CATALOG_TYPE, SHADOWING_SESSION_CONFIGURATION);+ }+ }++ @Test+ void testShadowing_disabled_neverRecordsShadowedName() {+ GravitinoSessionCatalogStore store =+ new GravitinoSessionCatalogStore(+ gravitinoCatalogStore, openedMemoryStore(), ImmutableSet.of(), false);+ when(gravitinoCatalogStore.contains(SHADOWED_CATALOG)).thenReturn(true);++ Assertions.assertTrue(store.contains(SHADOWED_CATALOG));+ GravitinoSessionCatalogStore.checkGravitinoManagedCatalogNotShadowing(+ SHADOWED_CATALOG, GRAVITINO_CATALOG_TYPE, SHADOWING_SESSION_CONFIGURATION);+ }++ @Test+ void testShadowing_excludedName_isNeverResolvedAgainstGravitino() {+ GravitinoSessionCatalogStore store =+ new GravitinoSessionCatalogStore(+ gravitinoCatalogStore, openedMemoryStore(), ImmutableSet.of(EXCLUDED_CATALOG), true);++ Assertions.assertFalse(store.contains(EXCLUDED_CATALOG));+ Assertions.assertFalse(store.getCatalog(EXCLUDED_CATALOG).isPresent());+ GravitinoSessionCatalogStore.checkGravitinoManagedCatalogNotShadowing(+ EXCLUDED_CATALOG, GRAVITINO_CATALOG_TYPE, SHADOWING_SESSION_CONFIGURATION);+ verify(gravitinoCatalogStore, never()).contains(EXCLUDED_CATALOG);+ verify(gravitinoCatalogStore, never()).getCatalog(EXCLUDED_CATALOG);+ }+// -------------------------------------------------------------------------// helpers// -------------------------------------------------------------------------+ private static CatalogFactory.Context factoryContext(+ String catalogName, Configuration sessionConfiguration) {+ return new FactoryUtil.DefaultCatalogContext(+ catalogName,+ new HashMap<>(),+ sessionConfiguration,+ TestGravitinoSessionCatalogStore.class.getClassLoader());+ }++ private static Configuration shadowingConfiguration() {+ Configuration configuration = sessionCatalogSupportOnlyConfiguration();+ configuration.setString(+ "table.catalog-store.gravitino.gravitino.enableSessionCatalogShadowing", "true");+ return configuration;+ }++ private static Configuration sessionCatalogSupportOnlyConfiguration() {+ Configuration configuration = new Configuration();+ configuration.setString(+ "table.catalog-store.gravitino.gravitino.enableSessionCatalogSupport", "true");+ return configuration;+ }++ private static Configuration invalidShadowingConfiguration() {+ Configuration configuration = sessionCatalogSupportOnlyConfiguration();+ configuration.setString(+ "table.catalog-store.gravitino.gravitino.enableSessionCatalogShadowing", "not-a-boolean");+ return configuration;+ }++ private static GenericInMemoryCatalogStore openedMemoryStore() {+ GenericInMemoryCatalogStore memoryStore = new GenericInMemoryCatalogStore();+ memoryStore.open();+ return memoryStore;+ }++ private GravitinoSessionCatalogStore shadowingStore(GenericInMemoryCatalogStore memoryStore) {+ memoryStore.open();+ return new GravitinoSessionCatalogStore(+ gravitinoCatalogStore, memoryStore, ImmutableSet.of(), true);+ }+private GravitinoSessionCatalogStore storeExcluding(String... catalogNames) {return new GravitinoSessionCatalogStore(gravitinoCatalogStore, memoryCatalogStore, ImmutableSet.copyOf(catalogNames));diff --git a/flink-connector/flink-common/src/test/java/org/apache/gravitino/flink/connector/store/TestGravitinoSessionCatalogStoreWithCatalogManager.java b/flink-connector/flink-common/src/test/java/org/apache/gravitino/flink/connector/store/TestGravitinoSessionCatalogStoreWithCatalogManager.javaindex b086bd388f..bb2833e0d8 100644--- a/flink-connector/flink-common/src/test/java/org/apache/gravitino/flink/connector/store/TestGravitinoSessionCatalogStoreWithCatalogManager.java+++ b/flink-connector/flink-common/src/test/java/org/apache/gravitino/flink/connector/store/TestGravitinoSessionCatalogStoreWithCatalogManager.java@@ -40,11 +40,14 @@ import org.apache.flink.table.api.TableEnvironment;import org.apache.flink.table.catalog.CatalogDescriptor;import org.apache.flink.table.catalog.CatalogManager;import org.apache.flink.table.catalog.CommonCatalogOptions;+import org.apache.flink.table.catalog.GenericInMemoryCatalog;import org.apache.flink.table.catalog.GenericInMemoryCatalogStore;import org.apache.flink.table.factories.CatalogFactory;import org.apache.flink.table.factories.Factory;import org.apache.flink.types.Row;import org.apache.flink.util.CloseableIterator;+import org.apache.gravitino.flink.connector.utils.FakeExternalCatalogFactory;+import org.junit.jupiter.api.AfterEach;import org.junit.jupiter.api.Assertions;import org.junit.jupiter.api.Assumptions;import org.junit.jupiter.api.BeforeEach;@@ -60,21 +63,34 @@ public class TestGravitinoSessionCatalogStoreWithCatalogManager {private static final String EXCLUDED_CATALOG = "paimon_catalog";private static final String GRAVITINO_ONLY_CATALOG = "gravitino_only_catalog";private static final String GRAVITINO_PAIMON = "gravitino-paimon";+ private static final String SHADOWED_CATALOG = "shadowed_catalog";+ private static final String SESSION_CATALOG_SUPPORT_KEY =+ "table.catalog-store.gravitino.gravitino.enableSessionCatalogSupport";+ private static final String SESSION_CATALOG_SHADOWING_KEY =+ "table.catalog-store.gravitino.gravitino.enableSessionCatalogShadowing";+ private static final String CREATE_SHADOWING_CATALOG =+ "CREATE CATALOG " + SHADOWED_CATALOG + " WITH ('type'='generic_in_memory')";private static final String CREATE_EXCLUDED_CATALOG ="CREATE CATALOG " + EXCLUDED_CATALOG + " WITH ('type'='generic_in_memory')";private GravitinoCatalogStore gravitinoCatalogStore;+ @AfterEach+ void tearDown() {+ GravitinoSessionCatalogStore.clearShadowedGravitinoCatalog();+ }+@BeforeEachvoid setUp() {gravitinoCatalogStore = mock(GravitinoCatalogStore.class);- for (String catalogName : Arrays.asList(EXCLUDED_CATALOG, GRAVITINO_ONLY_CATALOG)) {+ for (String catalogName :+ Arrays.asList(EXCLUDED_CATALOG, GRAVITINO_ONLY_CATALOG, SHADOWED_CATALOG)) {when(gravitinoCatalogStore.contains(catalogName)).thenReturn(true);when(gravitinoCatalogStore.getCatalog(catalogName)).thenReturn(Optional.of(inMemoryDescriptor(catalogName)));}when(gravitinoCatalogStore.listCatalogs())- .thenReturn(ImmutableSet.of(EXCLUDED_CATALOG, GRAVITINO_ONLY_CATALOG));+ .thenReturn(ImmutableSet.of(EXCLUDED_CATALOG, GRAVITINO_ONLY_CATALOG, SHADOWED_CATALOG));}/** Without exclusion, a same-named session catalog is rejected (the behavior in #14756). */@@ -218,6 +234,286 @@ public class TestGravitinoSessionCatalogStoreWithCatalogManager {verifyGravitinoCatalogNeverTouched(EXCLUDED_CATALOG);}+ // -------------------------------------------------------------------------+ // session catalog shadowing+ // -------------------------------------------------------------------------++ /**+ * With shadowing, a session catalog can be created under the name of a Gravitino catalog that the+ * session has not accessed. The Gravitino catalog is never loaded, modified, or dropped while it+ * is shadowed, and it is visible again once the session catalog is dropped.+ */+ @Test+ void testShadowing_sessionCatalogLifecycle_neverTouchesShadowedGravitinoCatalog() {+ TableEnvironment tableEnv = shadowingTableEnv();+ Assertions.assertTrue(listCatalogs(tableEnv).contains(SHADOWED_CATALOG));++ execute(tableEnv, CREATE_SHADOWING_CATALOG);+ Assertions.assertEquals(+ 1, listCatalogs(tableEnv).stream().filter(SHADOWED_CATALOG::equals).count());++ // Flink's duplicate-name semantics are kept for the session catalog.+ Throwable duplicate =+ Assertions.assertThrows(Exception.class, () -> execute(tableEnv, CREATE_SHADOWING_CATALOG));+ Assertions.assertTrue(+ allMessages(duplicate).contains("already exists"), allMessages(duplicate));++ execute(tableEnv, "USE CATALOG " + SHADOWED_CATALOG);+ execute(tableEnv, "CREATE DATABASE session_db");+ Assertions.assertTrue(collect(tableEnv, "SHOW DATABASES").contains("session_db"));+ execute(tableEnv, "USE CATALOG default_catalog");+ verifyGravitinoCatalogNeverLoadedOrModified(SHADOWED_CATALOG);++ execute(tableEnv, "DROP CATALOG " + SHADOWED_CATALOG);+ verify(gravitinoCatalogStore, never()).removeCatalog(eq(SHADOWED_CATALOG), anyBoolean());++ // The Gravitino catalog is visible again and does not contain the session database.+ execute(tableEnv, "USE CATALOG " + SHADOWED_CATALOG);+ Assertions.assertFalse(collect(tableEnv, "SHOW DATABASES").contains("session_db"));+ verify(gravitinoCatalogStore, atLeastOnce()).getCatalog(SHADOWED_CATALOG);+ verify(gravitinoCatalogStore, never()).storeCatalog(eq(SHADOWED_CATALOG), any());+ verify(gravitinoCatalogStore, never()).removeCatalog(eq(SHADOWED_CATALOG), anyBoolean());+ }++ /** A Gravitino catalog that the session has accessed keeps the existing drop behavior. */+ @Test+ void testShadowing_dropAccessedGravitinoCatalog_dropsGravitinoCatalog() {+ TableEnvironment tableEnv = shadowingTableEnv();++ execute(tableEnv, "USE CATALOG " + GRAVITINO_ONLY_CATALOG);+ execute(tableEnv, "USE CATALOG default_catalog");+ execute(tableEnv, "DROP CATALOG " + GRAVITINO_ONLY_CATALOG);++ verify(gravitinoCatalogStore).removeCatalog(eq(GRAVITINO_ONLY_CATALOG), anyBoolean());+ }++ /** A Gravitino catalog that the session has accessed cannot be shadowed afterwards. */+ @Test+ void testShadowing_accessedGravitinoCatalog_cannotBeShadowed() {+ TableEnvironment tableEnv = shadowingTableEnv();++ execute(tableEnv, "USE CATALOG " + SHADOWED_CATALOG);+ execute(tableEnv, "USE CATALOG default_catalog");+ Throwable exception =+ Assertions.assertThrows(Exception.class, () -> execute(tableEnv, CREATE_SHADOWING_CATALOG));++ Assertions.assertTrue(+ allMessages(exception).contains("already exists"), allMessages(exception));+ verify(gravitinoCatalogStore, never()).storeCatalog(any(), any());+ }++ /**+ * Dropping a Gravitino catalog that the session has not accessed is reported as missing instead+ * of dropping it, so Flink SQL never drops a Gravitino catalog that the session did not use.+ */+ @Test+ void testShadowing_dropUnaccessedGravitinoCatalog_neverDropsGravitinoCatalog() {+ TableEnvironment tableEnv = shadowingTableEnv();++ Throwable exception =+ Assertions.assertThrows(+ Exception.class, () -> execute(tableEnv, "DROP CATALOG " + GRAVITINO_ONLY_CATALOG));+ Assertions.assertTrue(+ allMessages(exception).contains("does not exist"), allMessages(exception));+ execute(tableEnv, "DROP CATALOG IF EXISTS " + GRAVITINO_ONLY_CATALOG);++ verify(gravitinoCatalogStore, never()).removeCatalog(any(), anyBoolean());+ // The Gravitino catalog can still be used in the session.+ execute(tableEnv, "USE CATALOG " + GRAVITINO_ONLY_CATALOG);+ }++ /**+ * Creating a Gravitino-managed catalog type under the name of a shadowed Gravitino catalog must+ * fail before Flink instantiates and registers the catalog. Runs where the {@code+ * gravitino-paimon} catalog factory is registered, i.e. in the Flink-minor modules.+ */+ @Test+ void testShadowing_gravitinoManagedType_isRejectedBeforeRegistration() {+ Assumptions.assumeTrue(+ isCatalogFactoryRegistered(GRAVITINO_PAIMON),+ "The gravitino-paimon catalog factory is not registered in this module");+ TableEnvironment tableEnv = shadowingTableEnv();++ Throwable exception =+ Assertions.assertThrows(+ Exception.class,+ () ->+ execute(+ tableEnv,+ "CREATE CATALOG "+ + SHADOWED_CATALOG+ + " WITH ('type'='"+ + GRAVITINO_PAIMON+ + "', 'catalog-backend'='filesystem', 'warehouse'='/tmp/unused')"));++ Assertions.assertTrue(+ allMessages(exception).contains("already exists in Gravitino"), allMessages(exception));+ verify(gravitinoCatalogStore, never()).storeCatalog(any(), any());+ // No catalog was registered under the name: it still resolves to the Gravitino catalog.+ Assertions.assertInstanceOf(+ GenericInMemoryCatalog.class, tableEnv.getCatalog(SHADOWED_CATALOG).get());+ verify(gravitinoCatalogStore).getCatalog(SHADOWED_CATALOG);+ }++ /** A failed session catalog creation leaves no state that affects the Gravitino catalog. */+ @Test+ void testShadowing_failedSessionCatalogCreation_keepsGravitinoCatalogUsable() {+ TableEnvironment tableEnv = shadowingTableEnv();++ Assertions.assertThrows(+ Exception.class,+ () ->+ execute(+ tableEnv,+ "CREATE CATALOG " + SHADOWED_CATALOG + " WITH ('type'='no_such_catalog_type')"));+ // Flink 1.20.0 stores the catalog before it instantiates it, so remove what may be left.+ execute(tableEnv, "DROP CATALOG IF EXISTS " + SHADOWED_CATALOG);++ execute(tableEnv, "USE CATALOG " + SHADOWED_CATALOG);+ verify(gravitinoCatalogStore).getCatalog(SHADOWED_CATALOG);+ verify(gravitinoCatalogStore, never()).storeCatalog(any(), any());+ verify(gravitinoCatalogStore, never()).removeCatalog(any(), anyBoolean());+ }++ /** {@code CREATE CATALOG IF NOT EXISTS} and {@code ALTER CATALOG} are available since 1.20. */+ @Test+ void testShadowing_createIfNotExistsAndAlter_onlyAffectSessionCatalog() {+ Assumptions.assumeTrue(+ Arrays.stream(CatalogManager.class.getMethods())+ .anyMatch(method -> method.getName().equals("alterCatalog")),+ "CREATE CATALOG IF NOT EXISTS and ALTER CATALOG require Flink 1.20 or later");+ TableEnvironment tableEnv = shadowingTableEnv();++ execute(+ tableEnv,+ "CREATE CATALOG IF NOT EXISTS " + SHADOWED_CATALOG + " WITH ('type'='generic_in_memory')");+ execute(+ tableEnv,+ "CREATE CATALOG IF NOT EXISTS " + SHADOWED_CATALOG + " WITH ('type'='generic_in_memory')");+ execute(+ tableEnv, "ALTER CATALOG " + SHADOWED_CATALOG + " SET ('default-database'='session_db')");++ Assertions.assertTrue(+ collect(tableEnv, "DESCRIBE CATALOG " + SHADOWED_CATALOG).contains("generic_in_memory"));+ verifyGravitinoCatalogNeverLoadedOrModified(SHADOWED_CATALOG);+ }++ /**+ * A session catalog that shadows a Gravitino catalog cannot be altered into a Gravitino-managed+ * catalog type, which would resolve the shadowed Gravitino catalog. The rejection must happen+ * before Flink replaces the session catalog.+ */+ @Test+ void testShadowing_alterToGravitinoManagedType_isRejectedBeforeReplacement() {+ Assumptions.assumeTrue(+ isCatalogFactoryRegistered(GRAVITINO_PAIMON),+ "The gravitino-paimon catalog factory is not registered in this module");+ Assumptions.assumeTrue(+ Arrays.stream(CatalogManager.class.getMethods())+ .anyMatch(method -> method.getName().equals("alterCatalog")),+ "ALTER CATALOG requires Flink 1.20 or later");+ TableEnvironment tableEnv = shadowingTableEnv();+ execute(tableEnv, CREATE_SHADOWING_CATALOG);++ Throwable exception =+ Assertions.assertThrows(+ Exception.class,+ () ->+ execute(+ tableEnv,+ "ALTER CATALOG "+ + SHADOWED_CATALOG+ + " SET ('type'='"+ + GRAVITINO_PAIMON+ + "', 'catalog-backend'='filesystem', 'warehouse'='/tmp/unused')"));++ Assertions.assertTrue(+ allMessages(exception).contains("already exists in Gravitino"), allMessages(exception));+ // The session catalog is not replaced. Flink applies ALTER CATALOG options to the stored+ // descriptor in place, so DESCRIBE CATALOG shows them even after the rejection.+ Assertions.assertInstanceOf(+ GenericInMemoryCatalog.class, tableEnv.getCatalog(SHADOWED_CATALOG).get());+ Assertions.assertThrows(+ Exception.class,+ () ->+ execute(+ tableEnv,+ "ALTER CATALOG " + SHADOWED_CATALOG + " SET ('default-database'='session_db')"));+ execute(tableEnv, "DROP CATALOG " + SHADOWED_CATALOG);+ verifyGravitinoCatalogNeverLoadedOrModified(SHADOWED_CATALOG);+ }++ /**+ * Operations that check the catalog store without instantiating a catalog afterwards leave the+ * shadowed name on the thread. Another session on the same thread that does not enable shadowing+ * must still be able to create a Gravitino-managed catalog with that name.+ */+ @Test+ void testShadowing_leftOverCheck_doesNotAffectAnotherSessionOnTheSameThread() {+ String createGravitinoManagedCatalog =+ "CREATE CATALOG "+ + SHADOWED_CATALOG+ + " WITH ('type'='"+ + FakeExternalCatalogFactory.IDENTIFIER+ + "')";+ TableEnvironment shadowingEnv = shadowingTableEnv();+ String[] operationsWithoutInstantiation = {+ "DROP CATALOG IF EXISTS " + SHADOWED_CATALOG,+ "CREATE CATALOG " + SHADOWED_CATALOG + " WITH ('type'='no_such_catalog_type')",+ createGravitinoManagedCatalog+ };++ for (String operation : operationsWithoutInstantiation) {+ TableEnvironment otherEnv = defaultCatalogStoreTableEnv();+ try {+ execute(shadowingEnv, operation);+ } catch (RuntimeException e) {+ // Only the state left on the thread matters here.+ }+ execute(otherEnv, createGravitinoManagedCatalog);+ Assertions.assertInstanceOf(+ GenericInMemoryCatalog.class, otherEnv.getCatalog(SHADOWED_CATALOG).get(), operation);+ }++ // The shadowing session itself keeps rejecting the Gravitino-managed catalog type.+ execute(shadowingEnv, "DROP CATALOG IF EXISTS " + SHADOWED_CATALOG);+ Throwable exception =+ Assertions.assertThrows(+ Exception.class, () -> execute(shadowingEnv, createGravitinoManagedCatalog));+ Assertions.assertTrue(+ allMessages(exception).contains("already exists in Gravitino"), allMessages(exception));+ verify(gravitinoCatalogStore, never()).storeCatalog(any(), any());+ verify(gravitinoCatalogStore, never()).removeCatalog(any(), anyBoolean());+ }++ /** The same holds for another session that uses this store without enabling shadowing. */+ @Test+ void testShadowing_leftOverCheck_doesNotAffectNonShadowingGravitinoSession() {+ TableEnvironment shadowingEnv = shadowingTableEnv();+ TableEnvironment nonShadowingEnv = tableEnv(ImmutableSet.of());+ execute(shadowingEnv, "DROP CATALOG IF EXISTS " + SHADOWED_CATALOG);++ // Without shadowing, the Gravitino catalog with the name is visible and usable as before.+ execute(nonShadowingEnv, "USE CATALOG " + SHADOWED_CATALOG);+ execute(nonShadowingEnv, "USE CATALOG default_catalog");+ verify(gravitinoCatalogStore).getCatalog(SHADOWED_CATALOG);+ }++ /** Shadowing a catalog does not change how other Gravitino catalogs behave in the session. */+ @Test+ void testShadowing_otherGravitinoCatalogsKeepExistingBehavior() {+ TableEnvironment tableEnv = shadowingTableEnv();+ execute(tableEnv, CREATE_SHADOWING_CATALOG);++ execute(tableEnv, "USE CATALOG " + GRAVITINO_ONLY_CATALOG);+ execute(tableEnv, "USE CATALOG default_catalog");+ execute(tableEnv, "DROP CATALOG " + GRAVITINO_ONLY_CATALOG);++ verify(gravitinoCatalogStore, atLeastOnce()).getCatalog(GRAVITINO_ONLY_CATALOG);+ verify(gravitinoCatalogStore).removeCatalog(eq(GRAVITINO_ONLY_CATALOG), anyBoolean());+ verifyGravitinoCatalogNeverLoadedOrModified(SHADOWED_CATALOG);+ }+// -------------------------------------------------------------------------// helpers// -------------------------------------------------------------------------@@ -228,11 +524,35 @@ public class TestGravitinoSessionCatalogStoreWithCatalogManager {private TableEnvironment tableEnv(Set<String> excludedCatalogs, Configuration sessionConfiguration) {+ return tableEnv(excludedCatalogs, false, sessionConfiguration);+ }++ /**+ * Creates a session that enables shadowing. The options are also set in the session+ * configuration, as {@link GravitinoCatalogStoreFactory} requires, because Gravitino catalog+ * factories read them from there.+ */+ private TableEnvironment shadowingTableEnv() {+ Configuration sessionConfiguration = new Configuration();+ sessionConfiguration.setString(SESSION_CATALOG_SUPPORT_KEY, "true");+ sessionConfiguration.setString(SESSION_CATALOG_SHADOWING_KEY, "true");+ return tableEnv(ImmutableSet.of(), true, sessionConfiguration);+ }++ /** Creates a session that uses Flink's default in-memory catalog store. */+ private static TableEnvironment defaultCatalogStoreTableEnv() {+ return TableEnvironment.create(EnvironmentSettings.newInstance().inBatchMode().build());+ }++ private TableEnvironment tableEnv(+ Set<String> excludedCatalogs,+ boolean sessionCatalogShadowing,+ Configuration sessionConfiguration) {GenericInMemoryCatalogStore memoryCatalogStore = new GenericInMemoryCatalogStore();memoryCatalogStore.open();GravitinoSessionCatalogStore store =new GravitinoSessionCatalogStore(- gravitinoCatalogStore, memoryCatalogStore, excludedCatalogs);+ gravitinoCatalogStore, memoryCatalogStore, excludedCatalogs, sessionCatalogShadowing);return TableEnvironment.create(EnvironmentSettings.newInstance().withConfiguration(sessionConfiguration)@@ -257,6 +577,16 @@ public class TestGravitinoSessionCatalogStoreWithCatalogManager {verify(gravitinoCatalogStore, never()).removeCatalog(eq(catalogName), anyBoolean());}+ /**+ * Shadowing still checks whether the Gravitino catalog exists, but it never loads, creates, or+ * drops the shadowed Gravitino catalog.+ */+ private void verifyGravitinoCatalogNeverLoadedOrModified(String catalogName) {+ verify(gravitinoCatalogStore, never()).getCatalog(catalogName);+ verify(gravitinoCatalogStore, never()).storeCatalog(eq(catalogName), any());+ verify(gravitinoCatalogStore, never()).removeCatalog(eq(catalogName), anyBoolean());+ }+private static CatalogDescriptor inMemoryDescriptor(String catalogName) {Configuration configuration = new Configuration();configuration.set(CommonCatalogOptions.CATALOG_TYPE, "generic_in_memory");diff --git a/flink-connector/flink-common/src/test/java/org/apache/gravitino/flink/connector/utils/FakeExternalCatalogFactory.java b/flink-connector/flink-common/src/test/java/org/apache/gravitino/flink/connector/utils/FakeExternalCatalogFactory.javaindex 664ceeda5d..0409bfc4e2 100644--- a/flink-connector/flink-common/src/test/java/org/apache/gravitino/flink/connector/utils/FakeExternalCatalogFactory.java+++ b/flink-connector/flink-common/src/test/java/org/apache/gravitino/flink/connector/utils/FakeExternalCatalogFactory.java@@ -22,6 +22,7 @@ import java.util.Collections;import java.util.Set;import org.apache.flink.configuration.ConfigOption;import org.apache.flink.table.catalog.Catalog;+import org.apache.flink.table.catalog.GenericInMemoryCatalog;import org.apache.gravitino.flink.connector.CatalogPropertiesConverter;import org.apache.gravitino.flink.connector.PartitionConverter;import org.apache.gravitino.flink.connector.catalog.BaseCatalogFactory;@@ -46,9 +47,11 @@ public class FakeExternalCatalogFactory implements BaseCatalogFactory {return Collections.emptySet();}+ /** Creates an in-memory catalog after the checks that every Gravitino catalog factory runs. */@Overridepublic Catalog createCatalog(Context context) {- throw new UnsupportedOperationException();+ FactoryUtils.createCatalogFactoryHelper(this, context);+ return new GenericInMemoryCatalog(context.getName());}@Override