World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#12297] feat(secret): Add catalog and schema create-time secrets (#12420)
MaSai00e856fb7c76
diff --git a/api/src/main/java/org/apache/gravitino/SupportsCatalogs.java b/api/src/main/java/org/apache/gravitino/SupportsCatalogs.javaindex 650d60fdbb..d3560f5466 100644--- a/api/src/main/java/org/apache/gravitino/SupportsCatalogs.java+++ b/api/src/main/java/org/apache/gravitino/SupportsCatalogs.java@@ -18,6 +18,7 @@*/package org.apache.gravitino;+import java.util.Collections;import java.util.Map;import org.apache.gravitino.annotation.Evolving;import org.apache.gravitino.exceptions.CatalogAlreadyExistsException;@@ -26,6 +27,8 @@ import org.apache.gravitino.exceptions.CatalogNotInUseException;import org.apache.gravitino.exceptions.NoSuchCatalogException;import org.apache.gravitino.exceptions.NoSuchMetalakeException;import org.apache.gravitino.exceptions.NonEmptyEntityException;+import org.apache.gravitino.secret.SecretBinding;+import org.apache.gravitino.secret.SecretReference;/*** Client interface for supporting catalogs. It includes methods for listing, loading, creating,@@ -84,22 +87,66 @@ public interface SupportsCatalogs {* the created catalog is the managed catalog, like model, fileset catalog. For the details of the* provider definition, see {@link CatalogProvider}.*- * @param catalogName the name of the catalog.- * @param type the type of the catalog.- * @param provider the provider of the catalog, or null if the catalog is a managed catalog.- * @param comment the comment of the catalog.- * @param properties the properties of the catalog.- * @return The created catalog.- * @throws NoSuchMetalakeException If the metalake does not exist.- * @throws CatalogAlreadyExistsException If the catalog already exists.+ * <p>Delegates to {@link #createCatalog(String, Catalog.Type, String, String, Map, Map, Map)}+ * with empty secret maps.+ *+ * @param catalogName the name of the catalog+ * @param type the type of the catalog+ * @param provider the provider of the catalog, or null if the catalog is a managed catalog+ * @param comment the comment of the catalog+ * @param properties the properties of the catalog+ * @return the created catalog+ * @throws NoSuchMetalakeException if the metalake does not exist+ * @throws CatalogAlreadyExistsException if the catalog already exists*/- Catalog createCatalog(+ default Catalog createCatalog(String catalogName,Catalog.Type type,String provider,String comment,Map<String, String> properties)- throws NoSuchMetalakeException, CatalogAlreadyExistsException;+ throws NoSuchMetalakeException, CatalogAlreadyExistsException {+ return createCatalog(+ catalogName,+ type,+ provider,+ comment,+ properties,+ Collections.emptyMap(),+ Collections.emptyMap());+ }++ /**+ * Create a catalog with optional secret maps.+ *+ * <p>The default implementation rejects create-time secrets. Implementations that support secrets+ * must override this method.+ *+ * @param catalogName the name of the catalog+ * @param type the type of the catalog+ * @param provider the provider of the catalog, or null if managed+ * @param comment the comment of the catalog+ * @param properties the properties of the catalog+ * @param secretBindings optional property key → binding ({@code provider} + {@code plaintext})+ * for write-through+ * @param secretReferences optional property key → secret locator ({@code provider} plus+ * provider-specific attributes)+ * @return the created catalog+ * @throws NoSuchMetalakeException if the metalake does not exist+ * @throws CatalogAlreadyExistsException if the catalog already exists+ * @throws UnsupportedOperationException if create-time secrets are not supported+ */+ default Catalog createCatalog(+ String catalogName,+ Catalog.Type type,+ String provider,+ String comment,+ Map<String, String> properties,+ Map<String, SecretBinding> secretBindings,+ Map<String, SecretReference> secretReferences)+ throws NoSuchMetalakeException, CatalogAlreadyExistsException {+ throw new UnsupportedOperationException("Creating a catalog with secrets is not supported");+ }/*** Create a managed catalog with specified catalog name, type, comment, and properties.diff --git a/api/src/main/java/org/apache/gravitino/SupportsSchemas.java b/api/src/main/java/org/apache/gravitino/SupportsSchemas.javaindex 42284ed24d..cc059d9f09 100644--- a/api/src/main/java/org/apache/gravitino/SupportsSchemas.java+++ b/api/src/main/java/org/apache/gravitino/SupportsSchemas.java@@ -20,12 +20,15 @@package org.apache.gravitino;+import java.util.Collections;import java.util.Map;import org.apache.gravitino.annotation.Evolving;import org.apache.gravitino.exceptions.NoSuchCatalogException;import org.apache.gravitino.exceptions.NoSuchSchemaException;import org.apache.gravitino.exceptions.NonEmptySchemaException;import org.apache.gravitino.exceptions.SchemaAlreadyExistsException;+import org.apache.gravitino.secret.SecretBinding;+import org.apache.gravitino.secret.SecretReference;/*** The client interface to support schema operations. The server side should use the other one with@@ -93,15 +96,48 @@ public interface SupportsSchemas {* need the schema with default values applied, use the {@link #loadSchema(String)} method after* creation.*+ * <p>Delegates to {@link #createSchema(String, String, Map, Map, Map)} with empty secret maps.+ *+ * @param schemaName The name of the schema.+ * @param comment The comment of the schema.+ * @param properties The properties of the schema.+ * @return The schema as defined by the caller, without all default values.+ * @throws NoSuchCatalogException If the catalog does not exist.+ * @throws SchemaAlreadyExistsException If the schema already exists.+ */+ default Schema createSchema(String schemaName, String comment, Map<String, String> properties)+ throws NoSuchCatalogException, SchemaAlreadyExistsException {+ return createSchema(+ schemaName, comment, properties, Collections.emptyMap(), Collections.emptyMap());+ }++ /**+ * Creates a schema with optional secret maps.+ *+ * <p>The default implementation rejects create-time secrets. Implementations that support secrets+ * must override this method.+ ** @param schemaName The name of the schema.* @param comment The comment of the schema.* @param properties The properties of the schema.+ * @param secretBindings optional property key → binding ({@code provider} + {@code plaintext})+ * for write-through+ * @param secretReferences optional property key → secret locator ({@code provider} plus+ * provider-specific attributes)* @return The schema as defined by the caller, without all default values.* @throws NoSuchCatalogException If the catalog does not exist.* @throws SchemaAlreadyExistsException If the schema already exists.+ * @throws UnsupportedOperationException if create-time secrets are not supported*/- Schema createSchema(String schemaName, String comment, Map<String, String> properties)- throws NoSuchCatalogException, SchemaAlreadyExistsException;+ default Schema createSchema(+ String schemaName,+ String comment,+ Map<String, String> properties,+ Map<String, SecretBinding> secretBindings,+ Map<String, SecretReference> secretReferences)+ throws NoSuchCatalogException, SchemaAlreadyExistsException {+ throw new UnsupportedOperationException("Creating a schema with secrets is not supported");+ }/*** Load metadata properties for a schema.diff --git a/api/src/main/java/org/apache/gravitino/file/Fileset.java b/api/src/main/java/org/apache/gravitino/file/Fileset.javaindex 342161293d..644c516e69 100644--- a/api/src/main/java/org/apache/gravitino/file/Fileset.java+++ b/api/src/main/java/org/apache/gravitino/file/Fileset.java@@ -232,7 +232,7 @@ public interface Fileset extends Auditable {* location and the value is the storage location path.*/default Map<String, String> storageLocations() {- throw new UnsupportedOperationException("Not implemented");+ throw new UnsupportedOperationException("Fileset does not support storageLocations.");}/**diff --git a/api/src/main/java/org/apache/gravitino/file/FilesetCatalog.java b/api/src/main/java/org/apache/gravitino/file/FilesetCatalog.javaindex 68bddf96ed..54922a69f8 100644--- a/api/src/main/java/org/apache/gravitino/file/FilesetCatalog.java+++ b/api/src/main/java/org/apache/gravitino/file/FilesetCatalog.java@@ -170,7 +170,7 @@ public interface FilesetCatalog {Map<String, SecretBinding> secretBindings,Map<String, SecretReference> secretReferences)throws NoSuchSchemaException, FilesetAlreadyExistsException {- throw new UnsupportedOperationException("Not implemented");+ throw new UnsupportedOperationException("Creating a fileset with secrets is not supported");}/**@@ -258,6 +258,6 @@ public interface FilesetCatalog {*/default String getFileLocation(NameIdentifier ident, String subPath, String locationName)throws NoSuchFilesetException, NoSuchLocationNameException {- throw new UnsupportedOperationException("Not implemented");+ throw new UnsupportedOperationException("getFileLocation is not supported");}}diff --git a/catalogs/catalog-fileset/src/main/java/org/apache/gravitino/catalog/fileset/FilesetCatalogOperations.java b/catalogs/catalog-fileset/src/main/java/org/apache/gravitino/catalog/fileset/FilesetCatalogOperations.javaindex 95f037cf96..f08c416d7d 100644--- a/catalogs/catalog-fileset/src/main/java/org/apache/gravitino/catalog/fileset/FilesetCatalogOperations.java+++ b/catalogs/catalog-fileset/src/main/java/org/apache/gravitino/catalog/fileset/FilesetCatalogOperations.java@@ -874,6 +874,13 @@ public class FilesetCatalogOperations extends ManagedSchemaOperationsboolean dropped = super.dropSchema(ident, cascade);if (disableFSOps) {+ // No FS cleanup; still remove fileset write-through secrets when cascade deleted them.+ // Schema secrets are cleaned by SchemaOperationDispatcher.+ if (dropped && cascade) {+ for (FilesetEntity fileset : filesets) {+ secretManager.deleteSecretsFromProperties(fileset.properties());+ }+ }return dropped;}@@ -973,6 +980,16 @@ public class FilesetCatalogOperations extends ManagedSchemaOperations}}+ // Cascade store.delete removes fileset entities without+ // FilesetOperationDispatcher.dropFileset;+ // clean fileset secrets after FS ops (still need plaintext for mergeUpLevelConfigurations).+ // Schema secrets are cleaned by SchemaOperationDispatcher.+ if (cascade) {+ for (FilesetEntity fileset : filesets) {+ secretManager.deleteSecretsFromProperties(fileset.properties());+ }+ }+LOG.info("Deleted schema {}", ident);return true;diff --git a/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/TestFilesetCatalogOperations.java b/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/TestFilesetCatalogOperations.javaindex f96f7fb9bd..d4b70d3a8d 100644--- a/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/TestFilesetCatalogOperations.java+++ b/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/TestFilesetCatalogOperations.java@@ -3715,4 +3715,57 @@ public class TestFilesetCatalogOperations {Assertions.assertEquals(urn.toString(), schema.properties().get("aws-sk"));}}++ @Test+ public void testDropCascadeSecrets() throws Exception {+ long schemaId = idGenerator.nextId();+ long filesetId = idGenerator.nextId();+ SecretUrn schemaUrn = writeThroughUrn("schema", schemaId, "schema-sk");+ SecretUrn filesetUrn = writeThroughUrn("fileset", filesetId, "fileset-sk");+ secretManager.writeSecrets(+ List.of(+ new SecretMaterial(schemaUrn, "schema-secret"),+ new SecretMaterial(filesetUrn, "fileset-secret")));++ String schemaName = "schema_cascade_" + generateTestId();+ String catalogPath = TEST_ROOT_PATH + "/catalog_cascade_" + generateTestId();+ String schemaPath = catalogPath + "/" + schemaName;+ try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store, secretManager)) {+ ops.initialize(+ Maps.newHashMap(Map.of(LOCATION, catalogPath)),+ randomCatalogInfo("m1", "c1"),+ FILESET_PROPERTIES_METADATA);+ NameIdentifier schemaIdent = NameIdentifierUtil.ofSchema("m1", "c1", schemaName);+ ops.createSchema(+ schemaIdent,+ "comment",+ Maps.newHashMap(+ StringIdentifier.newPropertiesWithId(+ StringIdentifier.fromId(schemaId),+ Map.of(LOCATION, schemaPath, "schema-sk", schemaUrn.toString()))));+ ops.createFileset(+ NameIdentifierUtil.ofFileset("m1", "c1", schemaName, "fs_cascade"),+ "comment",+ Fileset.Type.MANAGED,+ null,+ Maps.newHashMap(+ StringIdentifier.newPropertiesWithId(+ StringIdentifier.fromId(filesetId),+ Map.of("fileset-sk", filesetUrn.toString()))));++ Assertions.assertTrue(ops.dropSchema(schemaIdent, true));+ Assertions.assertEquals("schema-secret", secretManager.readSecret(schemaUrn));+ Assertions.assertThrows(+ IllegalArgumentException.class, () -> secretManager.readSecret(filesetUrn));+ }+ }++ private static SecretUrn writeThroughUrn(String entityType, long entityId, String key) {+ return SecretUrn.buildWriteThrough(+ "memory",+ Map.of(+ SecretConstants.ATTR_ENTITY_TYPE, entityType,+ SecretConstants.ATTR_ENTITY_ID, String.valueOf(entityId),+ SecretConstants.ATTR_PROPERTY_KEY, key));+ }}diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/BaseSchemaCatalog.java b/clients/client-java/src/main/java/org/apache/gravitino/client/BaseSchemaCatalog.javaindex cba10fa820..56c5a5b0f5 100644--- a/clients/client-java/src/main/java/org/apache/gravitino/client/BaseSchemaCatalog.java+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/BaseSchemaCatalog.java@@ -42,6 +42,8 @@ import org.apache.gravitino.dto.requests.SchemaUpdatesRequest;import org.apache.gravitino.dto.responses.DropResponse;import org.apache.gravitino.dto.responses.EntityListResponse;import org.apache.gravitino.dto.responses.SchemaResponse;+import org.apache.gravitino.dto.secret.SecretBindingDTO;+import org.apache.gravitino.dto.secret.SecretReferenceDTO;import org.apache.gravitino.exceptions.NoSuchCatalogException;import org.apache.gravitino.exceptions.NoSuchPolicyException;import org.apache.gravitino.exceptions.NoSuchSchemaException;@@ -56,6 +58,8 @@ import org.apache.gravitino.function.FunctionType;import org.apache.gravitino.policy.Policy;import org.apache.gravitino.policy.SupportsPolicies;import org.apache.gravitino.rest.RESTUtils;+import org.apache.gravitino.secret.SecretBinding;+import org.apache.gravitino.secret.SecretReference;import org.apache.gravitino.tag.SupportsTags;import org.apache.gravitino.tag.Tag;import org.apache.gravitino.tag.TagValue;@@ -171,7 +175,7 @@ abstract class BaseSchemaCatalog extends CatalogDTO}/**- * Create a new schema with specified identifier, comment and metadata.+ * Create a new schema with specified identifier, comment and properties.** @param schemaName The name identifier of the schema.* @param comment The comment of the schema.@@ -183,8 +187,40 @@ abstract class BaseSchemaCatalog extends CatalogDTO@Overridepublic Schema createSchema(String schemaName, String comment, Map<String, String> properties)throws NoSuchCatalogException, SchemaAlreadyExistsException {+ return createSchema(+ schemaName, comment, properties, Collections.emptyMap(), Collections.emptyMap());+ }++ /**+ * Create a new schema with specified identifier, comment, properties, and optional secret maps.+ *+ * @param schemaName The name identifier of the schema.+ * @param comment The comment of the schema.+ * @param properties The properties of the schema.+ * @param secretBindings Optional property key → binding ({@code provider} + {@code plaintext})+ * for write-through.+ * @param secretReferences Optional property key → secret locator ({@code provider} plus+ * provider-specific attributes).+ * @return The created {@link Schema}.+ * @throws NoSuchCatalogException if the catalog with specified namespace does not exist.+ * @throws SchemaAlreadyExistsException if the schema with specified identifier already exists.+ */+ @Override+ public Schema createSchema(+ String schemaName,+ String comment,+ Map<String, String> properties,+ Map<String, SecretBinding> secretBindings,+ Map<String, SecretReference> secretReferences)+ throws NoSuchCatalogException, SchemaAlreadyExistsException {- SchemaCreateRequest req = new SchemaCreateRequest(schemaName, comment, properties);+ SchemaCreateRequest req =+ new SchemaCreateRequest(+ schemaName,+ comment,+ properties,+ SecretBindingDTO.fromSecretBindings(secretBindings),+ SecretReferenceDTO.fromSecretReferences(secretReferences));req.validate();SchemaResponse resp =diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/FilesetCatalog.java b/clients/client-java/src/main/java/org/apache/gravitino/client/FilesetCatalog.javaindex 6c144548b1..f7c8facd46 100644--- a/clients/client-java/src/main/java/org/apache/gravitino/client/FilesetCatalog.java+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/FilesetCatalog.java@@ -138,8 +138,38 @@ class FilesetCatalog extends BaseSchemaCatalog* @param type The type of the fileset.* @param storageLocations The location names and storage locations of the fileset.* @param properties The properties of the fileset.- * @param secretBindings Optional property key → binding ({ provider} + { plaintext}) for- * write-through.+ * @return The created fileset metadata+ * @throws NoSuchSchemaException If the schema does not exist.+ * @throws FilesetAlreadyExistsException If the fileset already exists.+ */+ @Override+ public Fileset createMultipleLocationFileset(+ NameIdentifier ident,+ String comment,+ Fileset.Type type,+ Map<String, String> storageLocations,+ Map<String, String> properties)+ throws NoSuchSchemaException, FilesetAlreadyExistsException {+ return createMultipleLocationFileset(+ ident,+ comment,+ type,+ storageLocations,+ properties,+ Collections.emptyMap(),+ Collections.emptyMap());+ }++ /**+ * Create a fileset metadata with multiple storage locations in the catalog.+ *+ * @param ident A fileset identifier.+ * @param comment The comment of the fileset.+ * @param type The type of the fileset.+ * @param storageLocations The location names and storage locations of the fileset.+ * @param properties The properties of the fileset.+ * @param secretBindings Optional property key → binding ({@code provider} + {@code plaintext})+ * for write-through.* @param secretReferences Optional property key → secret locator ({@code provider} plus* provider-specific attributes).* @return The created fileset metadatadiff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoClient.java b/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoClient.javaindex fa0a51757e..a1734ecb59 100644--- a/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoClient.java+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoClient.java@@ -21,6 +21,7 @@ package org.apache.gravitino.client;import com.google.common.base.Preconditions;import com.google.common.collect.Sets;+import java.util.Collections;import java.util.List;import java.util.Map;import java.util.Optional;@@ -67,6 +68,8 @@ import org.apache.gravitino.policy.Policy;import org.apache.gravitino.policy.PolicyChange;import org.apache.gravitino.policy.PolicyContent;import org.apache.gravitino.policy.PolicyOperations;+import org.apache.gravitino.secret.SecretBinding;+import org.apache.gravitino.secret.SecretReference;import org.apache.gravitino.tag.Tag;import org.apache.gravitino.tag.TagChange;import org.apache.gravitino.tag.TagOperations;@@ -140,7 +143,29 @@ public class GravitinoClient extends GravitinoClientBaseString comment,Map<String, String> properties)throws NoSuchMetalakeException, CatalogAlreadyExistsException {- return getMetalake().createCatalog(catalogName, type, provider, comment, properties);+ return createCatalog(+ catalogName,+ type,+ provider,+ comment,+ properties,+ Collections.emptyMap(),+ Collections.emptyMap());+ }++ @Override+ public Catalog createCatalog(+ String catalogName,+ Catalog.Type type,+ String provider,+ String comment,+ Map<String, String> properties,+ Map<String, SecretBinding> secretBindings,+ Map<String, SecretReference> secretReferences)+ throws NoSuchMetalakeException, CatalogAlreadyExistsException {+ return getMetalake()+ .createCatalog(+ catalogName, type, provider, comment, properties, secretBindings, secretReferences);}@Overridediff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoMetalake.java b/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoMetalake.javaindex 92d86bcb26..b9724b1b3f 100644--- a/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoMetalake.java+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoMetalake.java@@ -95,6 +95,8 @@ import org.apache.gravitino.dto.responses.TagListResponse;import org.apache.gravitino.dto.responses.TagResponse;import org.apache.gravitino.dto.responses.UserListResponse;import org.apache.gravitino.dto.responses.UserResponse;+import org.apache.gravitino.dto.secret.SecretBindingDTO;+import org.apache.gravitino.dto.secret.SecretReferenceDTO;import org.apache.gravitino.exceptions.CatalogAlreadyExistsException;import org.apache.gravitino.exceptions.CatalogInUseException;import org.apache.gravitino.exceptions.GroupAlreadyExistsException;@@ -128,6 +130,8 @@ import org.apache.gravitino.policy.PolicyChange;import org.apache.gravitino.policy.PolicyContent;import org.apache.gravitino.policy.PolicyOperations;import org.apache.gravitino.rest.RESTUtils;+import org.apache.gravitino.secret.SecretBinding;+import org.apache.gravitino.secret.SecretReference;import org.apache.gravitino.tag.Tag;import org.apache.gravitino.tag.TagChange;import org.apache.gravitino.tag.TagOperations;@@ -256,8 +260,52 @@ public class GravitinoMetalake extends MetalakeDTOString comment,Map<String, String> properties)throws NoSuchMetalakeException, CatalogAlreadyExistsException {+ return createCatalog(+ catalogName,+ type,+ provider,+ comment,+ properties,+ Collections.emptyMap(),+ Collections.emptyMap());+ }++ /**+ * Create a new catalog with specified identifier, type, comment, properties, and optional secret+ * maps.+ *+ * @param catalogName The identifier of the catalog.+ * @param type The type of the catalog.+ * @param provider The provider of the catalog.+ * @param comment The comment of the catalog.+ * @param properties The properties of the catalog.+ * @param secretBindings Optional property key → binding ({@code provider} + {@code plaintext})+ * for write-through.+ * @param secretReferences Optional property key → secret locator ({@code provider} plus+ * provider-specific attributes).+ * @return The created {@link Catalog}.+ * @throws NoSuchMetalakeException if the metalake with specified namespace does not exist.+ * @throws CatalogAlreadyExistsException if the catalog with specified identifier already exists.+ */+ @Override+ public Catalog createCatalog(+ String catalogName,+ Catalog.Type type,+ String provider,+ String comment,+ Map<String, String> properties,+ Map<String, SecretBinding> secretBindings,+ Map<String, SecretReference> secretReferences)+ throws NoSuchMetalakeException, CatalogAlreadyExistsException {CatalogCreateRequest req =- new CatalogCreateRequest(catalogName, type, provider, comment, properties);+ new CatalogCreateRequest(+ catalogName,+ type,+ provider,+ comment,+ properties,+ SecretBindingDTO.fromSecretBindings(secretBindings),+ SecretReferenceDTO.fromSecretReferences(secretReferences));req.validate();CatalogResponse resp =diff --git a/clients/client-python/gravitino/api/supports_schemas.py b/clients/client-python/gravitino/api/supports_schemas.pyindex 7a61400b6f..b81d74c153 100644--- a/clients/client-python/gravitino/api/supports_schemas.py+++ b/clients/client-python/gravitino/api/supports_schemas.py@@ -16,12 +16,17 @@# under the License.from abc import ABC, abstractmethod-from typing import Dict, List, Optional+from types import MappingProxyType+from typing import Dict, List, Mapping, Optionalfrom gravitino.api.schema import Schemafrom gravitino.api.schema_change import SchemaChange+from gravitino.api.secret import SecretBinding, SecretReferencefrom gravitino.exceptions.base import NoSuchSchemaException+_EMPTY_SECRET_BINDINGS: Mapping[str, SecretBinding] = MappingProxyType({})+_EMPTY_SECRET_REFERENCES: Mapping[str, SecretReference] = MappingProxyType({})+class SupportsSchemas(ABC):"""@@ -79,7 +84,12 @@ class SupportsSchemas(ABC):@abstractmethoddef create_schema(- self, schema_name: str, comment: str, properties: Dict[str, str]+ self,+ schema_name: str,+ comment: str,+ properties: Dict[str, str],+ secret_bindings: Mapping[str, SecretBinding] = _EMPTY_SECRET_BINDINGS,+ secret_references: Mapping[str, SecretReference] = _EMPTY_SECRET_REFERENCES,) -> Schema:"""Create a schema in the catalog.@@ -87,6 +97,8 @@ class SupportsSchemas(ABC):schema_name: The name of the schema.comment: The comment of the schema.properties: The properties of the schema.+ secret_bindings: Optional property key → binding (provider + plaintext) for write-through.+ secret_references: Optional property key → locator attributes.Raises:NoSuchCatalogException: If the catalog does not exist.diff --git a/clients/client-python/gravitino/client/base_schema_catalog.py b/clients/client-python/gravitino/client/base_schema_catalog.pyindex 88ab8f72cd..16d9884a5a 100644--- a/clients/client-python/gravitino/client/base_schema_catalog.py+++ b/clients/client-python/gravitino/client/base_schema_catalog.py@@ -16,7 +16,8 @@# under the License.import logging-from typing import Dict, List, Optional+from types import MappingProxyType+from typing import Dict, List, Mapping, Optionalfrom gravitino.api.authorization.supports_roles import SupportsRolesfrom gravitino.api.catalog import Catalog@@ -29,6 +30,7 @@ from gravitino.api.metadata_object import MetadataObjectfrom gravitino.api.metadata_objects import MetadataObjectsfrom gravitino.api.schema import Schemafrom gravitino.api.schema_change import SchemaChange+from gravitino.api.secret import SecretBinding, SecretReferencefrom gravitino.api.supports_schemas import SupportsSchemasfrom gravitino.api.tag.supports_tags import SupportsTagsfrom gravitino.api.tag.tag import Tag@@ -61,6 +63,9 @@ from gravitino.utils import HTTPClientlogger = logging.getLogger(__name__)+_EMPTY_SECRET_BINDINGS: Mapping[str, SecretBinding] = MappingProxyType({})+_EMPTY_SECRET_REFERENCES: Mapping[str, SecretReference] = MappingProxyType({})+class BaseSchemaCatalog(CatalogDTO,@@ -179,6 +184,8 @@ class BaseSchemaCatalog(schema_name: str = None,comment: str = None,properties: Dict[str, str] = None,+ secret_bindings: Mapping[str, SecretBinding] = _EMPTY_SECRET_BINDINGS,+ secret_references: Mapping[str, SecretReference] = _EMPTY_SECRET_REFERENCES,) -> Schema:"""Create a new schema with specified identifier, comment and metadata.@@ -186,6 +193,8 @@ class BaseSchemaCatalog(schema_name: The name of the schema.comment: The comment of the schema.properties: The properties of the schema.+ secret_bindings: Optional property key → binding (provider + plaintext) for write-through.+ secret_references: Optional property key → locator attributes.Raises:NoSuchCatalogException if the catalog with specified namespace does not exist.@@ -194,7 +203,13 @@ class BaseSchemaCatalog(Returns:The created Schema."""- req = SchemaCreateRequest(encode_string(schema_name), comment, properties)+ req = SchemaCreateRequest(+ encode_string(schema_name),+ comment,+ properties,+ secret_bindings,+ secret_references,+ )req.validate()resp = self.rest_client.post(diff --git a/clients/client-python/gravitino/client/gravitino_client.py b/clients/client-python/gravitino/client/gravitino_client.pyindex bdce8131bd..7a501deeb2 100644--- a/clients/client-python/gravitino/client/gravitino_client.py+++ b/clients/client-python/gravitino/client/gravitino_client.py@@ -17,7 +17,8 @@from __future__ import annotations-from typing import Dict, List, Optional+from types import MappingProxyType+from typing import Dict, List, Mapping, Optionalfrom gravitino.api.authorization.group import Groupfrom gravitino.api.authorization.owner import Owner@@ -32,6 +33,7 @@ from gravitino.api.job.job_template import JobTemplatefrom gravitino.api.job.job_template_change import JobTemplateChangefrom gravitino.api.job.supports_jobs import SupportsJobsfrom gravitino.api.metadata_object import MetadataObject+from gravitino.api.secret import SecretBinding, SecretReferencefrom gravitino.api.tag.tag_operations import TagOperationsfrom gravitino.auth.auth_data_provider import AuthDataProviderfrom gravitino.client.gravitino_client_base import GravitinoClientBase@@ -39,6 +41,9 @@ from gravitino.client.gravitino_metalake import GravitinoMetalakefrom ..api.tag.tag import Tag+_EMPTY_SECRET_BINDINGS: Mapping[str, SecretBinding] = MappingProxyType({})+_EMPTY_SECRET_REFERENCES: Mapping[str, SecretReference] = MappingProxyType({})+class GravitinoClient(GravitinoClientBase, SupportsJobs, TagOperations):"""Gravitino Client for a user to interact with the Gravitino API, allowing the client to list,@@ -103,9 +108,17 @@ class GravitinoClient(GravitinoClientBase, SupportsJobs, TagOperations):provider: str,comment: str,properties: Dict[str, str],+ secret_bindings: Mapping[str, SecretBinding] = _EMPTY_SECRET_BINDINGS,+ secret_references: Mapping[str, SecretReference] = _EMPTY_SECRET_REFERENCES,) -> Catalog:return self.get_metalake().create_catalog(- name, catalog_type, provider, comment, properties+ name,+ catalog_type,+ provider,+ comment,+ properties,+ secret_bindings,+ secret_references,)def alter_catalog(self, name: str, *changes: CatalogChange):diff --git a/clients/client-python/gravitino/client/gravitino_metalake.py b/clients/client-python/gravitino/client/gravitino_metalake.pyindex 32ed8656b3..68574cb2cb 100644--- a/clients/client-python/gravitino/client/gravitino_metalake.py+++ b/clients/client-python/gravitino/client/gravitino_metalake.py@@ -16,7 +16,8 @@# under the License.# pylint: disable=too-many-linesimport logging-from typing import Dict, List, Optional+from types import MappingProxyType+from typing import Dict, List, Mapping, Optionalfrom gravitino.api.authorization.group import Groupfrom gravitino.api.authorization.owner import Owner@@ -33,6 +34,7 @@ from gravitino.api.job.job_template_change import JobTemplateChangefrom gravitino.api.job.supports_jobs import SupportsJobsfrom gravitino.api.metadata_object import MetadataObjectfrom gravitino.api.metadata_objects import MetadataObjects+from gravitino.api.secret import SecretBinding, SecretReferencefrom gravitino.api.tag.tag import Tagfrom gravitino.api.tag.tag_operations import TagOperationsfrom gravitino.client.dto_converters import DTOConverters@@ -111,6 +113,9 @@ from gravitino.utils.string_utils import StringUtilslogger = logging.getLogger(__name__)+_EMPTY_SECRET_BINDINGS: Mapping[str, SecretBinding] = MappingProxyType({})+_EMPTY_SECRET_REFERENCES: Mapping[str, SecretReference] = MappingProxyType({})+class GravitinoMetalake(MetalakeDTO,@@ -231,6 +236,8 @@ class GravitinoMetalake(provider: str,comment: str,properties: Dict[str, str],+ secret_bindings: Mapping[str, SecretBinding] = _EMPTY_SECRET_BINDINGS,+ secret_references: Mapping[str, SecretReference] = _EMPTY_SECRET_REFERENCES,) -> Catalog:"""Create a new catalog with specified name, catalog type, comment and properties.@@ -242,6 +249,8 @@ class GravitinoMetalake(None provider. For the details, please refer to the Catalog.Type.comment: The comment of the catalog.properties: The properties of the catalog.+ secret_bindings: Optional property key → binding (provider + plaintext) for write-through.+ secret_references: Optional property key → locator attributes.Raises:NoSuchMetalakeException if the metalake does not exist.@@ -257,6 +266,8 @@ class GravitinoMetalake(provider=provider,comment=comment,properties=properties,+ secret_bindings=secret_bindings,+ secret_references=secret_references,)catalog_create_request.validate()@@ -265,6 +276,7 @@ class GravitinoMetalake(url, json=catalog_create_request, error_handler=CATALOG_ERROR_HANDLER)catalog_resp = CatalogResponse.from_json(response.body, infer_missing=True)+ catalog_resp.validate()return DTOConverters.to_catalog(self.name(), catalog_resp.catalog(), self.rest_clientdiff --git a/clients/client-python/gravitino/dto/requests/catalog_create_request.py b/clients/client-python/gravitino/dto/requests/catalog_create_request.pyindex 885011118d..f0cfdb62a1 100644--- a/clients/client-python/gravitino/dto/requests/catalog_create_request.py+++ b/clients/client-python/gravitino/dto/requests/catalog_create_request.py@@ -16,13 +16,18 @@# under the License.from dataclasses import dataclass, field-from typing import Optional, Dict+from types import MappingProxyType+from typing import Dict, Mapping, Optionalfrom dataclasses_json import configfrom gravitino.api.catalog import Catalog+from gravitino.api.secret import SecretBinding, SecretReferencefrom gravitino.rest.rest_message import RESTRequest+_EMPTY_SECRET_BINDINGS: Mapping[str, SecretBinding] = MappingProxyType({})+_EMPTY_SECRET_REFERENCES: Mapping[str, SecretReference] = MappingProxyType({})+@dataclassclass CatalogCreateRequest(RESTRequest):@@ -41,6 +46,12 @@ class CatalogCreateRequest(RESTRequest):_properties: Optional[Dict[str, str]] = field(metadata=config(field_name="properties"))+ _secret_bindings: Dict[str, SecretBinding] = field(+ default_factory=dict, metadata=config(field_name="secretBindings")+ )+ _secret_references: Dict[str, SecretReference] = field(+ default_factory=dict, metadata=config(field_name="secretReferences")+ )def __init__(self,@@ -49,12 +60,16 @@ class CatalogCreateRequest(RESTRequest):provider: str = None,comment: str = None,properties: Dict[str, str] = None,+ secret_bindings: Mapping[str, SecretBinding] = _EMPTY_SECRET_BINDINGS,+ secret_references: Mapping[str, SecretReference] = _EMPTY_SECRET_REFERENCES,):self._name = nameself._type = catalog_typeself._provider = providerself._comment = commentself._properties = properties+ self._secret_bindings = dict(secret_bindings)+ self._secret_references = dict(secret_references)def validate(self):"""Validates the fields of the request.diff --git a/clients/client-python/gravitino/dto/requests/schema_create_request.py b/clients/client-python/gravitino/dto/requests/schema_create_request.pyindex 3baae7e857..6cbcad81f3 100644--- a/clients/client-python/gravitino/dto/requests/schema_create_request.py+++ b/clients/client-python/gravitino/dto/requests/schema_create_request.py@@ -16,12 +16,17 @@# under the License.from dataclasses import dataclass, field-from typing import Optional, Dict+from types import MappingProxyType+from typing import Dict, Mapping, Optionalfrom dataclasses_json import config+from gravitino.api.secret import SecretBinding, SecretReferencefrom gravitino.rest.rest_message import RESTRequest+_EMPTY_SECRET_BINDINGS: Mapping[str, SecretBinding] = MappingProxyType({})+_EMPTY_SECRET_REFERENCES: Mapping[str, SecretReference] = MappingProxyType({})+@dataclassclass SchemaCreateRequest(RESTRequest):@@ -32,14 +37,32 @@ class SchemaCreateRequest(RESTRequest):_properties: Optional[Dict[str, str]] = field(metadata=config(field_name="properties"))+ _secret_bindings: Dict[str, SecretBinding] = field(+ default_factory=dict, metadata=config(field_name="secretBindings")+ )+ _secret_references: Dict[str, SecretReference] = field(+ default_factory=dict, metadata=config(field_name="secretReferences")+ )def __init__(- self, name: str, comment: Optional[str], properties: Optional[Dict[str, str]]+ self,+ name: str,+ comment: Optional[str],+ properties: Optional[Dict[str, str]],+ secret_bindings: Mapping[str, SecretBinding] = _EMPTY_SECRET_BINDINGS,+ secret_references: Mapping[str, SecretReference] = _EMPTY_SECRET_REFERENCES,):self._name = nameself._comment = commentself._properties = properties+ self._secret_bindings = dict(secret_bindings)+ self._secret_references = dict(secret_references)def validate(self):+ """Validates the request.++ Raises:+ IllegalArgumentException if the request is invalid.+ """if not self._name:raise ValueError('"name" field is required and cannot be empty')diff --git a/common/src/main/java/org/apache/gravitino/dto/requests/CatalogCreateRequest.java b/common/src/main/java/org/apache/gravitino/dto/requests/CatalogCreateRequest.javaindex 3223fce6c8..acf8442c4d 100644--- a/common/src/main/java/org/apache/gravitino/dto/requests/CatalogCreateRequest.java+++ b/common/src/main/java/org/apache/gravitino/dto/requests/CatalogCreateRequest.java@@ -19,8 +19,10 @@package org.apache.gravitino.dto.requests;import com.fasterxml.jackson.annotation.JsonCreator;+import com.fasterxml.jackson.annotation.JsonInclude;import com.fasterxml.jackson.annotation.JsonProperty;import com.google.common.base.Preconditions;+import java.util.Collections;import java.util.Map;import javax.annotation.Nullable;import lombok.EqualsAndHashCode;@@ -29,6 +31,8 @@ import lombok.ToString;import org.apache.commons.lang3.StringUtils;import org.apache.gravitino.Catalog;import org.apache.gravitino.CatalogProvider;+import org.apache.gravitino.dto.secret.SecretBindingDTO;+import org.apache.gravitino.dto.secret.SecretReferenceDTO;import org.apache.gravitino.rest.RESTRequest;/** Represents a request to create a catalog. */@@ -54,6 +58,32 @@ public class CatalogCreateRequest implements RESTRequest {@JsonProperty("properties")private final Map<String, String> properties;+ @JsonInclude(JsonInclude.Include.NON_EMPTY)+ @JsonProperty("secretBindings")+ private final Map<String, SecretBindingDTO> secretBindings;++ @JsonInclude(JsonInclude.Include.NON_EMPTY)+ @JsonProperty("secretReferences")+ private final Map<String, SecretReferenceDTO> secretReferences;++ /**+ * Constructor for CatalogCreateRequest without secret maps.+ *+ * @param name The name of the catalog.+ * @param type The type of the catalog.+ * @param provider The provider of the catalog.+ * @param comment The comment for the catalog.+ * @param properties The properties for the catalog.+ */+ public CatalogCreateRequest(+ String name,+ Catalog.Type type,+ String provider,+ String comment,+ Map<String, String> properties) {+ this(name, type, provider, comment, properties, Collections.emptyMap(), Collections.emptyMap());+ }+/*** Constructor for CatalogCreateRequest.*@@ -62,6 +92,10 @@ public class CatalogCreateRequest implements RESTRequest {* @param provider The provider of the catalog.* @param comment The comment for the catalog.* @param properties The properties for the catalog.+ * @param secretBindings Optional property key → binding DTO ({@code provider} + {@code+ * plaintext}) for write-through secrets.+ * @param secretReferences Optional property key → secret locator DTO ({@code provider} plus+ * provider-specific attributes).*/@JsonCreatorpublic CatalogCreateRequest(@@ -69,11 +103,17 @@ public class CatalogCreateRequest implements RESTRequest {@JsonProperty("type") Catalog.Type type,@JsonProperty("provider") String provider,@JsonProperty("comment") String comment,- @JsonProperty("properties") Map<String, String> properties) {+ @JsonProperty("properties") Map<String, String> properties,+ @JsonProperty("secretBindings") Map<String, SecretBindingDTO> secretBindings,+ @JsonProperty("secretReferences") Map<String, SecretReferenceDTO> secretReferences) {this.name = name;this.type = type;this.comment = comment;this.properties = properties;+ // Match FilesetCreateRequest field defaults when JSON omits secret maps (@JsonCreator passes+ // null for absent properties).+ this.secretBindings = secretBindings == null ? Collections.emptyMap() : secretBindings;+ this.secretReferences = secretReferences == null ? Collections.emptyMap() : secretReferences;if (StringUtils.isNotBlank(provider)) {this.provider = provider;diff --git a/common/src/main/java/org/apache/gravitino/dto/requests/SchemaCreateRequest.java b/common/src/main/java/org/apache/gravitino/dto/requests/SchemaCreateRequest.javaindex ec103c0629..3745686012 100644--- a/common/src/main/java/org/apache/gravitino/dto/requests/SchemaCreateRequest.java+++ b/common/src/main/java/org/apache/gravitino/dto/requests/SchemaCreateRequest.java@@ -18,14 +18,19 @@*/package org.apache.gravitino.dto.requests;+import com.fasterxml.jackson.annotation.JsonCreator;+import com.fasterxml.jackson.annotation.JsonInclude;import com.fasterxml.jackson.annotation.JsonProperty;import com.google.common.base.Preconditions;+import java.util.Collections;import java.util.Map;import javax.annotation.Nullable;import lombok.EqualsAndHashCode;import lombok.Getter;import lombok.ToString;import org.apache.commons.lang3.StringUtils;+import org.apache.gravitino.dto.secret.SecretBindingDTO;+import org.apache.gravitino.dto.secret.SecretReferenceDTO;import org.apache.gravitino.rest.RESTRequest;/** Represents a request to create a schema. */@@ -45,22 +50,53 @@ public class SchemaCreateRequest implements RESTRequest {@JsonProperty("properties")private final Map<String, String> properties;+ @JsonInclude(JsonInclude.Include.NON_EMPTY)+ @JsonProperty("secretBindings")+ private final Map<String, SecretBindingDTO> secretBindings;++ @JsonInclude(JsonInclude.Include.NON_EMPTY)+ @JsonProperty("secretReferences")+ private final Map<String, SecretReferenceDTO> secretReferences;+/** Default constructor for Jackson deserialization. */public SchemaCreateRequest() {- this(null, null, null);+ this(null, null, null, Collections.emptyMap(), Collections.emptyMap());}/**- * Creates a new SchemaCreateRequest.+ * Creates a new SchemaCreateRequest without secret maps.** @param name The name of the schema.* @param comment The comment of the schema.* @param properties The properties of the schema.*/public SchemaCreateRequest(String name, String comment, Map<String, String> properties) {+ this(name, comment, properties, Collections.emptyMap(), Collections.emptyMap());+ }++ /**+ * Creates a new SchemaCreateRequest.+ *+ * @param name The name of the schema.+ * @param comment The comment of the schema.+ * @param properties The properties of the schema.+ * @param secretBindings Optional property key → binding DTO ({@code provider} + {@code+ * plaintext}) for write-through secrets.+ * @param secretReferences Optional property key → secret locator DTO ({@code provider} plus+ * provider-specific attributes).+ */+ @JsonCreator+ public SchemaCreateRequest(+ @JsonProperty("name") String name,+ @JsonProperty("comment") String comment,+ @JsonProperty("properties") Map<String, String> properties,+ @JsonProperty("secretBindings") Map<String, SecretBindingDTO> secretBindings,+ @JsonProperty("secretReferences") Map<String, SecretReferenceDTO> secretReferences) {this.name = name;this.comment = comment;this.properties = properties;+ this.secretBindings = secretBindings == null ? Collections.emptyMap() : secretBindings;+ this.secretReferences = secretReferences == null ? Collections.emptyMap() : secretReferences;}/**diff --git a/core/src/main/java/org/apache/gravitino/GravitinoEnv.java b/core/src/main/java/org/apache/gravitino/GravitinoEnv.javaindex 6c9e9f52ea..597fa3d5a8 100644--- a/core/src/main/java/org/apache/gravitino/GravitinoEnv.java+++ b/core/src/main/java/org/apache/gravitino/GravitinoEnv.java@@ -741,22 +741,24 @@ public class GravitinoEnv {// Tree lockthis.lockManager = new LockManager(config);+ // Create and initialize Catalog related modules first so MetalakeManager can force-drop+ // child catalogs through CatalogManager.dropCatalog (same path as FilesetCatalogOperations).+ // CatalogHookDispatcher -> CatalogEventDispatcher -> CatalogNormalizeDispatcher ->+ // CatalogManager+ // CatalogManager registers its own change-log listener with the entity store (when the store+ // supports it), so no poller wiring is needed here.+ this.catalogManager = new CatalogManager(config, entityStore, idGenerator, secretManager);+// Create and initialize metalake related modules, the operation chain is:// MetalakeHookDispatcher -> MetalakeEventDispatcher -> MetalakeNormalizeDispatcher ->// MetalakeManager- this.metalakeManager = new MetalakeManager(entityStore, idGenerator);+ this.metalakeManager = new MetalakeManager(entityStore, idGenerator, catalogManager);MetalakeNormalizeDispatcher metalakeNormalizeDispatcher =new MetalakeNormalizeDispatcher(metalakeManager);MetalakeEventDispatcher metalakeEventDispatcher =new MetalakeEventDispatcher(eventBus, metalakeNormalizeDispatcher);this.metalakeDispatcher = new MetalakeHookDispatcher(metalakeEventDispatcher);- // Create and initialize Catalog related modules, the operation chain is:- // CatalogHookDispatcher -> CatalogEventDispatcher -> CatalogNormalizeDispatcher ->- // CatalogManager- // CatalogManager registers its own change-log listener with the entity store (when the store- // supports it), so no poller wiring is needed here.- this.catalogManager = new CatalogManager(config, entityStore, idGenerator, secretManager);this.internalCatalogDispatcher = catalogManager;CatalogNormalizeDispatcher catalogNormalizeDispatcher =new CatalogNormalizeDispatcher(catalogManager);@@ -772,8 +774,19 @@ public class GravitinoEnv {new SecretPropertyOperationDispatcher(catalogManager, entityStore, idGenerator, secretManager);+ // Fileset dispatcher is created before schema dispatcher so schema can take it directly.+ FilesetOperationDispatcher filesetOperationDispatcher =+ new FilesetOperationDispatcher(catalogManager, entityStore, idGenerator, secretManager);+ FilesetNormalizeDispatcher filesetNormalizeDispatcher =+ new FilesetNormalizeDispatcher(filesetOperationDispatcher, catalogManager);+ this.internalFilesetDispatcher = filesetNormalizeDispatcher;+ FilesetEventDispatcher filesetEventDispatcher =+ new FilesetEventDispatcher(eventBus, filesetNormalizeDispatcher);+ this.filesetDispatcher = new FilesetHookDispatcher(filesetEventDispatcher);+SchemaOperationDispatcher schemaOperationDispatcher =- new SchemaOperationDispatcher(catalogManager, entityStore, idGenerator, secretManager);+ new SchemaOperationDispatcher(+ catalogManager, entityStore, idGenerator, secretManager, filesetNormalizeDispatcher);this.internalSchemaDispatcher = schemaOperationDispatcher;SchemaNormalizeDispatcher schemaNormalizeDispatcher =new SchemaNormalizeDispatcher(schemaOperationDispatcher, catalogManager);@@ -809,15 +822,6 @@ public class GravitinoEnv {new PartitionNormalizeDispatcher(partitionOperationDispatcher, catalogManager);this.partitionDispatcher = new PartitionEventDispatcher(eventBus, partitionNormalizeDispatcher);- FilesetOperationDispatcher filesetOperationDispatcher =- new FilesetOperationDispatcher(catalogManager, entityStore, idGenerator, secretManager);- FilesetNormalizeDispatcher filesetNormalizeDispatcher =- new FilesetNormalizeDispatcher(filesetOperationDispatcher, catalogManager);- this.internalFilesetDispatcher = filesetNormalizeDispatcher;- FilesetEventDispatcher filesetEventDispatcher =- new FilesetEventDispatcher(eventBus, filesetNormalizeDispatcher);- this.filesetDispatcher = new FilesetHookDispatcher(filesetEventDispatcher);-TopicOperationDispatcher topicOperationDispatcher =new TopicOperationDispatcher(catalogManager, entityStore, idGenerator, secretManager);TopicNormalizeDispatcher topicNormalizeDispatcher =diff --git a/core/src/main/java/org/apache/gravitino/catalog/CatalogManager.java b/core/src/main/java/org/apache/gravitino/catalog/CatalogManager.javaindex 3af616040a..b6090c9671 100644--- a/core/src/main/java/org/apache/gravitino/catalog/CatalogManager.java+++ b/core/src/main/java/org/apache/gravitino/catalog/CatalogManager.java@@ -107,7 +107,11 @@ import org.apache.gravitino.rel.SupportsPartitions;import org.apache.gravitino.rel.Table;import org.apache.gravitino.rel.TableCatalog;import org.apache.gravitino.rel.ViewCatalog;+import org.apache.gravitino.secret.SecretBinding;import org.apache.gravitino.secret.SecretManager;+import org.apache.gravitino.secret.SecretMaterial;+import org.apache.gravitino.secret.SecretPropertyUtils;+import org.apache.gravitino.secret.SecretReference;import org.apache.gravitino.storage.IdGenerator;import org.apache.gravitino.storage.relational.SupportsEntityChangeLog;import org.apache.gravitino.utils.ClassLoaderKey;@@ -361,8 +365,6 @@ public class CatalogManager implements CatalogDispatcher, Closeable {private final IdGenerator idGenerator;- // Held for create-time secret writes; consumed by the entity-secrets create follow-up.- @SuppressWarnings("UnusedVariable")private final SecretManager secretManager;private final List<Consumer<NameIdentifier>> removalListeners = Lists.newArrayList();@@ -380,7 +382,7 @@ public class CatalogManager implements CatalogDispatcher, Closeable {* @param config The configuration for the manager.* @param store The entity store to use.* @param idGenerator The id generator to use.- * @param secretManager The secret manager used by catalog operations.+ * @param secretManager The secret manager to use for create-time secret bindings/references.*/public CatalogManager(Config config, EntityStore store, IdGenerator idGenerator, SecretManager secretManager) {@@ -596,10 +598,31 @@ public class CatalogManager implements CatalogDispatcher, Closeable {String comment,Map<String, String> properties)throws NoSuchMetalakeException, CatalogAlreadyExistsException {+ return createCatalog(+ ident, type, provider, comment, properties, Collections.emptyMap(), Collections.emptyMap());+ }++ @Override+ public Catalog createCatalog(+ NameIdentifier ident,+ Catalog.Type type,+ String provider,+ String comment,+ Map<String, String> properties,+ Map<String, SecretBinding> secretBindings,+ Map<String, SecretReference> secretReferences)+ throws NoSuchMetalakeException, CatalogAlreadyExistsException {NameIdentifier metalakeIdent = NameIdentifier.of(ident.namespace().levels());- Map<String, String> mergedConfig = buildCatalogConf(provider, properties);+ Map<String, String> mergedConfig =+ SecretPropertyUtils.copyEntityProperties(+ buildCatalogConf(provider, properties), secretBindings, secretReferences);long uid = idGenerator.nextId();++ List<SecretMaterial> secretMaterials =+ secretManager.assembleSecretMaterials(+ properties, mergedConfig, "catalog", uid, secretBindings, secretReferences);+StringIdentifier stringId = StringIdentifier.fromId(uid);Instant now = Instant.now();String creator = PrincipalUtils.getCurrentPrincipal().getName();@@ -626,7 +649,11 @@ public class CatalogManager implements CatalogDispatcher, Closeable {LockType.WRITE,() -> {checkMetalake(metalakeIdent, store);- boolean needClean = false;+ // Write secrets before store.put / init: createBaseCatalog resolves URNs via+ // toPlaintextProperties. Roll back on any create failure (same pattern as+ // schema/fileset).+ secretManager.writeSecrets(secretMaterials);+ boolean entityStored = false;try {try {store.put(e, false /* overwrite */);@@ -636,49 +663,23 @@ public class CatalogManager implements CatalogDispatcher, Closeable {// after checkMetalake() succeeds but before this insert starts.LOG.warn("Metalake {} does not exist", metalakeIdent, e1);throw new NoSuchMetalakeException(e1, "Metalake %s does not exist", metalakeIdent);+ } catch (EntityAlreadyExistsException e1) {+ LOG.warn("Catalog {} already exists", ident, e1);+ throw new CatalogAlreadyExistsException("Catalog %s already exists", ident);}- needClean = true;+ entityStored = true;CatalogWrapper wrapper =catalogCache.get(ident, id -> createCatalogWrapper(e, mergedConfig));-- needClean = false;return wrapper.catalog;- } catch (EntityAlreadyExistsException e1) {- needClean = false;- LOG.warn("Catalog {} already exists", ident, e1);- throw new CatalogAlreadyExistsException("Catalog %s already exists", ident);-- } catch (IllegalArgumentException | NoSuchMetalakeException e2) {- throw e2;+ } catch (RuntimeException re) {+ rollbackFailedCatalogCreate(ident, secretMaterials, entityStored);+ throw re;- } catch (Exception e3) {- catalogCache.invalidate(ident);- LOG.error("Failed to create catalog {}", ident, e3);- if (e3 instanceof RuntimeException) {- throw (RuntimeException) e3;- }- throw new RuntimeException(e3);-- } finally {- if (needClean) {- // since we put the catalog entity into the store but failed to create the catalog- // instance,- // we need to clean up the entity stored.- try {- if (store.delete(ident, EntityType.CATALOG, true)) {- // This cleanup deletion writes a DROP record to the entity change log. Mark it as- // a local mutation so the change-log poller consumes that record's token instead- // of one meant for a later mutation of the same identifier. Without this, the- // poller could treat a subsequent local change as remote and spuriously- // invalidate (and asynchronously close) a cached catalog wrapper that is still in- // use, causing a NullPointerException.- markLocalMutation(ident);- }- } catch (IOException e4) {- LOG.error("Failed to clean up catalog {}", ident, e4);- }- }+ } catch (Exception ex) {+ rollbackFailedCatalogCreate(ident, secretMaterials, entityStored);+ LOG.error("Failed to create catalog {}", ident, ex);+ throw new RuntimeException(ex);}});}@@ -997,29 +998,49 @@ public class CatalogManager implements CatalogDispatcher, Closeable {"Catalog %s has schemas, please drop them first or use force option", ident);}- if (isManagedStorageCatalog(catalogWrapper)) {- // For managed catalog, we need to call drop schema API to drop the underlying- // entities as well as the related resource first. Directly deleting the metadata from- // the store is not enough.- schemaEntities.forEach(- schema -> {- try {+ // Child write-through secrets: capture properties (URNs) from the entity, then+ // deleteSecrets after a successful drop — same capture-before-delete pattern as+ // FilesetCatalogOperations.dropSchema. Fileset secrets are cleaned inside that+ // dropSchema path; schema secrets are cleaned here.+ boolean managedStorage = isManagedStorageCatalog(catalogWrapper);+ List<Map<String, String>> unmanagedSchemaSecrets =+ managedStorage ? null : new ArrayList<>();+ if (managedStorage) {+ for (SchemaEntity schema : schemaEntities) {+ Map<String, String> schemaProps = copyProperties(schema.properties());+ try {+ boolean dropped =catalogWrapper.doWithSchemaOps(ops -> ops.dropSchema(schema.nameIdentifier(), true));- } catch (Exception e) {- LOG.warn("Failed to drop schema {}", schema.nameIdentifier());- throw new RuntimeException(- "Failed to drop schema " + schema.nameIdentifier(), e);- }- });+ if (dropped) {+ secretManager.deleteSecretsFromProperties(schemaProps);+ }+ } catch (Exception e) {+ LOG.warn("Failed to drop schema {}", schema.nameIdentifier());+ throw new RuntimeException("Failed to drop schema " + schema.nameIdentifier(), e);+ }+ }+ } else {+ for (SchemaEntity schema : schemaEntities) {+ unmanagedSchemaSecrets.add(copyProperties(schema.properties()));+ }}// Finally, delete the catalog entity as well as all its sub-entities from the store.// Invalidate after store.delete() to prevent a background thread from repopulating// the cache with stale data between invalidate and delete.+ Map<String, String> catalogProperties =+ copyProperties(catalogWrapper.catalog().entity().getProperties());boolean deleted = store.delete(ident, EntityType.CATALOG, true);if (deleted) {markLocalMutation(ident);+ // Unmanaged: schemas removed only via store cascade — clean secrets captured above.+ if (!managedStorage) {+ for (Map<String, String> schemaProperties : unmanagedSchemaSecrets) {+ secretManager.deleteSecretsFromProperties(schemaProperties);+ }+ }+ secretManager.deleteSecretsFromProperties(catalogProperties);}catalogCache.invalidate(ident);return deleted;@@ -1041,6 +1062,12 @@ public class CatalogManager implements CatalogDispatcher, Closeable {});}+ private static Map<String, String> copyProperties(Map<String, String> properties) {+ return properties == null || properties.isEmpty()+ ? Collections.emptyMap()+ : new HashMap<>(properties);+ }+/*** Check if the given list of schema entities contains any currently existing user-created* schemas.@@ -1365,7 +1392,6 @@ public class CatalogManager implements CatalogDispatcher, Closeable {// Load Catalog class instanceBaseCatalog<?> catalog = createCatalogInstance(classLoader, entity.getProvider());// Resolve secret URNs to plaintext for connector init only; entity storage keeps URNs.- // Fileset FS merge assumes catalog conf is already plaintext at this boundary.catalog.withCatalogConf(secretManager.toPlaintextProperties(entity.getProperties())).withCatalogEntity(entity);@@ -1665,4 +1691,29 @@ public class CatalogManager implements CatalogDispatcher, Closeable {throw new RuntimeException(ioe);}}++ /**+ * Rolls back secrets written for a catalog create attempt and, when {@code store.put} succeeded,+ * removes the catalog entity left behind by a failed init.+ */+ private void rollbackFailedCatalogCreate(+ NameIdentifier ident, List<SecretMaterial> secretMaterials, boolean entityStored) {+ secretManager.rollbackSecrets(secretMaterials);+ if (!entityStored) {+ return;+ }+ catalogCache.invalidate(ident);+ try {+ if (store.delete(ident, EntityType.CATALOG, true)) {+ // This cleanup deletion writes a DROP record to the entity change log. Mark it as a local+ // mutation so the change-log poller consumes that record's token instead of one meant for+ // a later mutation of the same identifier. Without this, the poller could treat a+ // subsequent local change as remote and spuriously invalidate (and asynchronously close) a+ // cached catalog wrapper that is still in use, causing a NullPointerException.+ markLocalMutation(ident);+ }+ } catch (IOException e) {+ LOG.error("Failed to clean up catalog {}", ident, e);+ }+ }}diff --git a/core/src/main/java/org/apache/gravitino/catalog/CatalogNormalizeDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/CatalogNormalizeDispatcher.javaindex 85ba013ba2..96202b0366 100644--- a/core/src/main/java/org/apache/gravitino/catalog/CatalogNormalizeDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/catalog/CatalogNormalizeDispatcher.java@@ -22,6 +22,7 @@ import static org.apache.gravitino.Entity.SYSTEM_CATALOG_RESERVED_NAME;import com.google.common.collect.ImmutableSet;import java.util.Arrays;+import java.util.Collections;import java.util.Map;import java.util.Set;import org.apache.gravitino.Catalog;@@ -34,6 +35,8 @@ import org.apache.gravitino.exceptions.CatalogInUseException;import org.apache.gravitino.exceptions.NoSuchCatalogException;import org.apache.gravitino.exceptions.NoSuchMetalakeException;import org.apache.gravitino.exceptions.NonEmptyEntityException;+import org.apache.gravitino.secret.SecretBinding;+import org.apache.gravitino.secret.SecretReference;public class CatalogNormalizeDispatcher implements CatalogDispatcher {private static final Set<String> RESERVED_WORDS =@@ -84,8 +87,23 @@ public class CatalogNormalizeDispatcher implements CatalogDispatcher {String comment,Map<String, String> properties)throws NoSuchMetalakeException, CatalogAlreadyExistsException {+ return createCatalog(+ ident, type, provider, comment, properties, Collections.emptyMap(), Collections.emptyMap());+ }++ @Override+ public Catalog createCatalog(+ NameIdentifier ident,+ Catalog.Type type,+ String provider,+ String comment,+ Map<String, String> properties,+ Map<String, SecretBinding> secretBindings,+ Map<String, SecretReference> secretReferences)+ throws NoSuchMetalakeException, CatalogAlreadyExistsException {validateCatalogName(ident.name());- return dispatcher.createCatalog(ident, type, provider, comment, properties);+ return dispatcher.createCatalog(+ ident, type, provider, comment, properties, secretBindings, secretReferences);}@Overridediff --git a/core/src/main/java/org/apache/gravitino/catalog/FilesetOperationDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/FilesetOperationDispatcher.javaindex b8fe860afe..46a1deb644 100644--- a/core/src/main/java/org/apache/gravitino/catalog/FilesetOperationDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/catalog/FilesetOperationDispatcher.java@@ -154,7 +154,8 @@ public class FilesetOperationDispatcher extends OperationDispatcher implements Fthrows NoSuchSchemaException, FilesetAlreadyExistsException {NameIdentifier catalogIdent = getCatalogIdentifier(ident);long uid = idGenerator.nextId();- Map<String, String> entityProperties = SecretPropertyUtils.copyEntityProperties(properties);+ Map<String, String> entityProperties =+ SecretPropertyUtils.copyEntityProperties(properties, secretBindings, secretReferences);List<SecretMaterial> secretMaterials =secretManager.assembleSecretMaterials(properties, entityProperties, "fileset", uid, secretBindings, secretReferences);@@ -167,7 +168,6 @@ public class FilesetOperationDispatcher extends OperationDispatcher implements Freturn null;}),IllegalArgumentException.class);- secretManager.writeSecrets(secretMaterials);StringIdentifier stringId = StringIdentifier.fromId(uid);// Same split as CatalogManager: create/storage properties keep secret URNs. Connectors that// need plaintext for runtime (e.g. Fileset FS) resolve at the conf boundary — see@@ -175,6 +175,10 @@ public class FilesetOperationDispatcher extends OperationDispatcher implements FMap<String, String> updatedProperties =StringIdentifier.newPropertiesWithId(stringId, entityProperties);+ // Write secrets before create: paths that resolve URNs (e.g. mergeUpLevelConfigurations for FS+ // mkdir, catalog createBaseCatalog) require secrets to exist first. Roll back on any create+ // failure (same pattern as CatalogManager / SchemaOperationDispatcher).+ secretManager.writeSecrets(secretMaterials);try {Fileset createdFileset =TreeLockUtils.doWithTreeLock(diff --git a/core/src/main/java/org/apache/gravitino/catalog/SchemaDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/SchemaDispatcher.javaindex 1b4ef6f178..f9efb3737a 100644--- a/core/src/main/java/org/apache/gravitino/catalog/SchemaDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/catalog/SchemaDispatcher.java@@ -19,7 +19,15 @@package org.apache.gravitino.catalog;+import java.util.Collections;+import java.util.Map;+import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.Schema;import org.apache.gravitino.connector.SupportsSchemas;+import org.apache.gravitino.exceptions.NoSuchCatalogException;+import org.apache.gravitino.exceptions.SchemaAlreadyExistsException;+import org.apache.gravitino.secret.SecretBinding;+import org.apache.gravitino.secret.SecretReference;/*** {@code SchemaDispatcher} interface acts as a specialization of the {@link SupportsSchemas}@@ -27,4 +35,52 @@ import org.apache.gravitino.connector.SupportsSchemas;* to dispatching or handling schema-related events or actions that are not covered by the standard* {@code SupportsSchemas} operations.*/-public interface SchemaDispatcher extends SupportsSchemas {}+public interface SchemaDispatcher extends SupportsSchemas {++ /**+ * Create a schema in the catalog.+ *+ * <p>Delegates to {@link #createSchema(NameIdentifier, String, Map, Map, Map)} with empty secret+ * maps.+ *+ * @param ident The name identifier of the schema.+ * @param comment The comment of the schema.+ * @param properties The properties of the schema.+ * @return The created schema.+ * @throws NoSuchCatalogException If the catalog does not exist.+ * @throws SchemaAlreadyExistsException If the schema already exists.+ */+ @Override+ default Schema createSchema(NameIdentifier ident, String comment, Map<String, String> properties)+ throws NoSuchCatalogException, SchemaAlreadyExistsException {+ return createSchema(ident, comment, properties, Collections.emptyMap(), Collections.emptyMap());+ }++ /**+ * Create a schema in the catalog with optional secret maps.+ *+ * <p>The default implementation rejects create-time secrets. Implementations that support secrets+ * must override this method.+ *+ * @param ident The name identifier of the schema.+ * @param comment The comment of the schema.+ * @param properties The properties of the schema.+ * @param secretBindings optional property key → binding ({@code provider} + {@code plaintext})+ * for write-through+ * @param secretReferences optional property key → secret locator ({@code provider} plus+ * provider-specific attributes).+ * @return The created schema.+ * @throws NoSuchCatalogException If the catalog does not exist.+ * @throws SchemaAlreadyExistsException If the schema already exists.+ * @throws UnsupportedOperationException if create-time secrets are not supported+ */+ default Schema createSchema(+ NameIdentifier ident,+ String comment,+ Map<String, String> properties,+ Map<String, SecretBinding> secretBindings,+ Map<String, SecretReference> secretReferences)+ throws NoSuchCatalogException, SchemaAlreadyExistsException {+ throw new UnsupportedOperationException("Creating a schema with secrets is not supported");+ }+}diff --git a/core/src/main/java/org/apache/gravitino/catalog/SchemaNormalizeDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/SchemaNormalizeDispatcher.javaindex 564d777820..31d77ef307 100644--- a/core/src/main/java/org/apache/gravitino/catalog/SchemaNormalizeDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/catalog/SchemaNormalizeDispatcher.java@@ -22,6 +22,7 @@ import static org.apache.gravitino.catalog.CapabilityHelpers.applyCapabilities;import static org.apache.gravitino.catalog.CapabilityHelpers.applyCaseSensitive;import static org.apache.gravitino.catalog.CapabilityHelpers.getCapability;+import java.util.Collections;import java.util.Map;import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.Namespace;@@ -32,6 +33,8 @@ import org.apache.gravitino.exceptions.NoSuchCatalogException;import org.apache.gravitino.exceptions.NoSuchSchemaException;import org.apache.gravitino.exceptions.NonEmptySchemaException;import org.apache.gravitino.exceptions.SchemaAlreadyExistsException;+import org.apache.gravitino.secret.SecretBinding;+import org.apache.gravitino.secret.SecretReference;/*** Note on list operations: names returned by list methods (e.g. {@link #listSchemas(Namespace)})@@ -73,7 +76,19 @@ public class SchemaNormalizeDispatcher implements SchemaDispatcher {@Overridepublic Schema createSchema(NameIdentifier ident, String comment, Map<String, String> properties)throws NoSuchCatalogException, SchemaAlreadyExistsException {- return dispatcher.createSchema(normalizeNameIdentifier(ident), comment, properties);+ return createSchema(ident, comment, properties, Collections.emptyMap(), Collections.emptyMap());+ }++ @Override+ public Schema createSchema(+ NameIdentifier ident,+ String comment,+ Map<String, String> properties,+ Map<String, SecretBinding> secretBindings,+ Map<String, SecretReference> secretReferences)+ throws NoSuchCatalogException, SchemaAlreadyExistsException {+ return dispatcher.createSchema(+ normalizeNameIdentifier(ident), comment, properties, secretBindings, secretReferences);}@Overridediff --git a/core/src/main/java/org/apache/gravitino/catalog/SchemaOperationDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/SchemaOperationDispatcher.javaindex 695f244aec..c98dfe5add 100644--- a/core/src/main/java/org/apache/gravitino/catalog/SchemaOperationDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/catalog/SchemaOperationDispatcher.java@@ -18,12 +18,19 @@*/package org.apache.gravitino.catalog;+import static org.apache.gravitino.Entity.EntityType.FILESET;import static org.apache.gravitino.Entity.EntityType.SCHEMA;import static org.apache.gravitino.catalog.PropertiesMetadataHelpers.validatePropertyForCreate;import static org.apache.gravitino.utils.NameIdentifierUtil.getCatalogIdentifier;+import static org.apache.gravitino.utils.NameIdentifierUtil.ofFileset;+import java.io.IOException;import java.time.Instant;+import java.util.Collections;+import java.util.HashMap;+import java.util.List;import java.util.Map;+import javax.annotation.Nullable;import org.apache.gravitino.EntityAlreadyExistsException;import org.apache.gravitino.EntityStore;import org.apache.gravitino.NameIdentifier;@@ -41,8 +48,13 @@ import org.apache.gravitino.exceptions.SchemaAlreadyExistsException;import org.apache.gravitino.lock.LockType;import org.apache.gravitino.lock.TreeLockUtils;import org.apache.gravitino.meta.AuditInfo;+import org.apache.gravitino.meta.FilesetEntity;import org.apache.gravitino.meta.SchemaEntity;+import org.apache.gravitino.secret.SecretBinding;import org.apache.gravitino.secret.SecretManager;+import org.apache.gravitino.secret.SecretMaterial;+import org.apache.gravitino.secret.SecretPropertyUtils;+import org.apache.gravitino.secret.SecretReference;import org.apache.gravitino.storage.IdGenerator;import org.apache.gravitino.utils.PrincipalUtils;import org.apache.gravitino.utils.SchemaEntityCleaner;@@ -53,6 +65,8 @@ public class SchemaOperationDispatcher extends OperationDispatcher implements Scprivate static final Logger LOG = LoggerFactory.getLogger(SchemaOperationDispatcher.class);+ @Nullable private final FilesetDispatcher filesetDispatcher;+/*** Creates a new SchemaOperationDispatcher instance.*@@ -66,7 +80,26 @@ public class SchemaOperationDispatcher extends OperationDispatcher implements ScEntityStore store,IdGenerator idGenerator,SecretManager secretManager) {+ this(catalogManager, store, idGenerator, secretManager, null);+ }++ /**+ * Creates a new SchemaOperationDispatcher instance.+ *+ * @param catalogManager The CatalogManager instance to be used for schema operations.+ * @param store The EntityStore instance to be used for schema operations.+ * @param idGenerator The IdGenerator instance to be used for schema operations.+ * @param secretManager The SecretManager instance to be used for secret operations.+ * @param filesetDispatcher The fileset dispatcher used to drop filesets on cascade schema drop.+ */+ public SchemaOperationDispatcher(+ CatalogManager catalogManager,+ EntityStore store,+ IdGenerator idGenerator,+ SecretManager secretManager,+ FilesetDispatcher filesetDispatcher) {super(catalogManager, store, idGenerator, secretManager);+ this.filesetDispatcher = filesetDispatcher;}/**@@ -103,82 +136,115 @@ public class SchemaOperationDispatcher extends OperationDispatcher implements Sc@Overridepublic Schema createSchema(NameIdentifier ident, String comment, Map<String, String> properties)throws NoSuchCatalogException, SchemaAlreadyExistsException {+ return createSchema(ident, comment, properties, Collections.emptyMap(), Collections.emptyMap());+ }++ @Override+ public Schema createSchema(+ NameIdentifier ident,+ String comment,+ Map<String, String> properties,+ Map<String, SecretBinding> secretBindings,+ Map<String, SecretReference> secretReferences)+ throws NoSuchCatalogException, SchemaAlreadyExistsException {NameIdentifier catalogIdent = getCatalogIdentifier(ident);+ long uid = idGenerator.nextId();+ Map<String, String> entityProperties =+ SecretPropertyUtils.copyEntityProperties(properties, secretBindings, secretReferences);+ List<SecretMaterial> secretMaterials =+ secretManager.assembleSecretMaterials(+ properties, entityProperties, "schema", uid, secretBindings, secretReferences);doWithCatalog(catalogIdent,c ->c.doWithPropertiesMeta(p -> {- validatePropertyForCreate(p.schemaPropertiesMetadata(), properties);+ validatePropertyForCreate(p.schemaPropertiesMetadata(), entityProperties);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// SchemaEntity will be visible.+ //+ // Same split as CatalogManager: create/storage properties keep secret URNs. Connectors that+ // need plaintext for runtime (e.g. Fileset FS) resolve at the conf boundary — see+ // FilesetCatalogOperations.mergeUpLevelConfigurations / CatalogManager.createBaseCatalog.StringIdentifier stringId = StringIdentifier.fromId(uid);Map<String, String> updatedProperties =- StringIdentifier.newPropertiesWithId(stringId, properties);+ StringIdentifier.newPropertiesWithId(stringId, entityProperties);- return TreeLockUtils.doWithTreeLock(- catalogIdent,- LockType.WRITE,- () -> {- // we do not retrieve the schema again (to obtain some values generated by underlying- // catalog)- // since some catalogs' API is async and the schema may not be created immediately- Schema schema =- doWithCatalog(- catalogIdent,- c -> c.doWithSchemaOps(s -> s.createSchema(ident, comment, updatedProperties)),- NoSuchCatalogException.class,- SchemaAlreadyExistsException.class);+ // Write secrets before createSchema: create paths that resolve URNs (e.g. Fileset FS+ // mergeUpLevelConfigurations, catalog createBaseCatalog) require secrets to exist first.+ // Roll back on any create failure (same pattern as CatalogManager /+ // FilesetOperationDispatcher).+ secretManager.writeSecrets(secretMaterials);+ try {+ return TreeLockUtils.doWithTreeLock(+ catalogIdent,+ LockType.WRITE,+ () -> {+ // we do not retrieve the schema again (to obtain some values generated by underlying+ // catalog)+ // since some catalogs' API is async and the schema may not be created immediately+ Schema schema =+ doWithCatalog(+ catalogIdent,+ c -> c.doWithSchemaOps(s -> s.createSchema(ident, comment, updatedProperties)),+ NoSuchCatalogException.class,+ SchemaAlreadyExistsException.class);++ // If the Schema is maintained by the Gravitino's store, we don't have to store again.+ boolean isManagedSchema = isManagedEntity(catalogIdent, Capability.Scope.SCHEMA);+ if (isManagedSchema) {+ return EntityCombinedSchema.of(schema)+ .withHiddenProperties(+ getHiddenPropertyNames(+ catalogIdent,+ HasPropertyMetadata::schemaPropertiesMetadata,+ schema.properties()));+ }- // If the Schema is maintained by the Gravitino's store, we don't have to store again.- boolean isManagedSchema = isManagedEntity(catalogIdent, Capability.Scope.SCHEMA);- if (isManagedSchema) {- return EntityCombinedSchema.of(schema)- .withHiddenProperties(- getHiddenPropertyNames(- catalogIdent,- HasPropertyMetadata::schemaPropertiesMetadata,- schema.properties()));- }+ // Persist properties (including secret URNs) in the entity store so cleanup still works+ // when the underlying catalog does not retain schema properties.+ SchemaEntity schemaEntity =+ SchemaEntity.builder()+ .withId(uid)+ .withName(ident.name())+ .withNamespace(ident.namespace())+ .withProperties(updatedProperties)+ .withAuditInfo(+ AuditInfo.builder()+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())+ .withCreateTime(Instant.now())+ .build())+ .build();- SchemaEntity schemaEntity =- SchemaEntity.builder()- .withId(uid)- .withName(ident.name())- .withNamespace(ident.namespace())- .withAuditInfo(- AuditInfo.builder()- .withCreator(PrincipalUtils.getCurrentPrincipal().getName())- .withCreateTime(Instant.now())- .build())- .build();-- try {- store.put(schemaEntity, true /* overwrite */);- } catch (Exception e) {- LOG.error(FormattedErrorMessages.STORE_OP_FAILURE, "put", ident, e);- return EntityCombinedSchema.of(schema)+ try {+ store.put(schemaEntity, true /* overwrite */);+ } catch (Exception e) {+ LOG.error(FormattedErrorMessages.STORE_OP_FAILURE, "put", ident, e);+ return EntityCombinedSchema.of(schema)+ .withHiddenProperties(+ getHiddenPropertyNames(+ catalogIdent,+ HasPropertyMetadata::schemaPropertiesMetadata,+ schema.properties()));+ }++ // Merge both the metadata from catalog operation and the metadata from entity store.+ return EntityCombinedSchema.of(schema, schemaEntity).withHiddenProperties(getHiddenPropertyNames(catalogIdent,HasPropertyMetadata::schemaPropertiesMetadata,schema.properties()));- }-- // Merge both the metadata from catalog operation and the metadata from entity store.- return EntityCombinedSchema.of(schema, schemaEntity)- .withHiddenProperties(- getHiddenPropertyNames(- catalogIdent,- HasPropertyMetadata::schemaPropertiesMetadata,- schema.properties()));- });+ });+ } catch (RuntimeException e) {+ secretManager.rollbackSecrets(secretMaterials);+ throw e;+ }}/**@@ -294,6 +360,8 @@ public class SchemaOperationDispatcher extends OperationDispatcher implements Sc.withId(schemaEntity.id()).withName(schemaEntity.name()).withNamespace(ident.namespace())+ .withProperties(+ propertiesForSchemaEntityAlter(schemaEntity, changes)).withAuditInfo(AuditInfo.builder().withCreator(schemaEntity.auditInfo().creator())@@ -327,10 +395,42 @@ public class SchemaOperationDispatcher extends OperationDispatcher implements Sc@Overridepublic boolean dropSchema(NameIdentifier ident, boolean cascade) throws NonEmptySchemaException {NameIdentifier catalogIdent = getCatalogIdentifier(ident);++ // Cascade: drop filesets via FilesetDispatcher first so each fileset cleans its own+ // write-through secrets (including under non-fileset catalogs). Do this before the catalog+ // lock to avoid nested TreeLocks.+ if (cascade && filesetDispatcher != null) {+ Namespace filesetNs =+ Namespace.of(ident.namespace().level(0), ident.namespace().level(1), ident.name());+ List<FilesetEntity> filesets;+ try {+ filesets = store.list(filesetNs, FilesetEntity.class, FILESET);+ } catch (NoSuchEntityException e) {+ filesets = Collections.emptyList();+ } catch (IOException e) {+ throw new RuntimeException("Failed to list filesets under schema " + ident, e);+ }+ for (FilesetEntity fileset : filesets) {+ filesetDispatcher.dropFileset(+ ofFileset(filesetNs.level(0), filesetNs.level(1), filesetNs.level(2), fileset.name()));+ }+ }+return TreeLockUtils.doWithTreeLock(catalogIdent,LockType.WRITE,() -> {+ // Schema secret URNs live on SchemaEntity in the store (catalog loadSchema may omit+ // them). Fileset write-through secrets on cascade are cleaned via FilesetDispatcher+ // above (and FilesetCatalogOperations.dropSchema as a fallback for fileset catalogs).+ Map<String, String> schemaProperties = new HashMap<>();+ SchemaEntity schemaEntity = getEntity(ident, SCHEMA, SchemaEntity.class);+ if (schemaEntity != null+ && schemaEntity.properties() != null+ && !schemaEntity.properties().isEmpty()) {+ schemaProperties = new HashMap<>(schemaEntity.properties());+ }+boolean droppedFromCatalog =doWithCatalog(catalogIdent,@@ -341,6 +441,9 @@ public class SchemaOperationDispatcher extends OperationDispatcher implements Sc// For managed schema, we don't need to drop the schema from the store again.boolean isManagedSchema = isManagedEntity(catalogIdent, Capability.Scope.SCHEMA);if (isManagedSchema) {+ if (droppedFromCatalog) {+ secretManager.deleteSecretsFromProperties(schemaProperties);+ }return droppedFromCatalog;}@@ -367,10 +470,33 @@ public class SchemaOperationDispatcher extends OperationDispatcher implements SccatalogIdent,c -> c.doWithSchemaOps(s -> s.schemaExists(schemaIdent)),RuntimeException.class));+ if (droppedFromCatalog) {+ secretManager.deleteSecretsFromProperties(schemaProperties);+ }return droppedFromCatalog;});}+ /**+ * Builds properties to persist on {@link SchemaEntity} after alter, matching catalog alter: start+ * from existing entity properties and apply set/remove changes so write-through secret URNs are+ * preserved when the underlying catalog omits them.+ */+ private static Map<String, String> propertiesForSchemaEntityAlter(+ SchemaEntity existing, SchemaChange[] changes) {+ Map<String, String> newProps =+ existing.properties() == null ? new HashMap<>() : new HashMap<>(existing.properties());+ for (SchemaChange change : changes) {+ if (change instanceof SchemaChange.SetProperty) {+ SchemaChange.SetProperty setProperty = (SchemaChange.SetProperty) change;+ newProps.put(setProperty.getProperty(), setProperty.getValue());+ } else if (change instanceof SchemaChange.RemoveProperty) {+ newProps.remove(((SchemaChange.RemoveProperty) change).getProperty());+ }+ }+ return newProps;+ }+private void importSchema(NameIdentifier identifier) {EntityCombinedSchema schema = internalLoadSchema(identifier);if (schema.imported()) {@@ -404,6 +530,8 @@ public class SchemaOperationDispatcher extends OperationDispatcher implements Sc.withId(uid).withName(identifier.name()).withNamespace(identifier.namespace())+ .withProperties(+ schema.properties() == null ? Collections.emptyMap() : schema.properties()).withAuditInfo(AuditInfo.builder().withCreator(schema.auditInfo().creator())diff --git a/core/src/main/java/org/apache/gravitino/catalog/SupportsCatalogs.java b/core/src/main/java/org/apache/gravitino/catalog/SupportsCatalogs.javaindex a6f6ccb11e..243a1dca20 100644--- a/core/src/main/java/org/apache/gravitino/catalog/SupportsCatalogs.java+++ b/core/src/main/java/org/apache/gravitino/catalog/SupportsCatalogs.java@@ -18,6 +18,7 @@*/package org.apache.gravitino.catalog;+import java.util.Collections;import java.util.Map;import org.apache.gravitino.Catalog;import org.apache.gravitino.CatalogChange;@@ -31,6 +32,8 @@ import org.apache.gravitino.exceptions.CatalogNotInUseException;import org.apache.gravitino.exceptions.NoSuchCatalogException;import org.apache.gravitino.exceptions.NoSuchMetalakeException;import org.apache.gravitino.exceptions.NonEmptyEntityException;+import org.apache.gravitino.secret.SecretBinding;+import org.apache.gravitino.secret.SecretReference;/*** Interface for supporting catalogs. It includes methods for listing, loading, creating, altering@@ -88,6 +91,9 @@ public interface SupportsCatalogs {* catalog should be created. The short name should be the same as the {@link CatalogProvider}* interface provided.*+ * <p>Delegates to {@link #createCatalog(NameIdentifier, Catalog.Type, String, String, Map, Map,+ * Map)} with empty secret maps.+ ** @param ident the identifier of the catalog.* @param type the type of the catalog.* @param comment the comment of the catalog.@@ -97,13 +103,48 @@ public interface SupportsCatalogs {* @throws NoSuchMetalakeException If the metalake does not exist.* @throws CatalogAlreadyExistsException If the catalog already exists.*/- Catalog createCatalog(+ default Catalog createCatalog(NameIdentifier ident,Catalog.Type type,String provider,String comment,Map<String, String> properties)- throws NoSuchMetalakeException, CatalogAlreadyExistsException;+ throws NoSuchMetalakeException, CatalogAlreadyExistsException {+ return createCatalog(+ ident, type, provider, comment, properties, Collections.emptyMap(), Collections.emptyMap());+ }++ /**+ * Create a catalog with optional secret maps.+ *+ * <p>The default implementation rejects create-time secrets. Implementations that support secrets+ * must override this method.+ *+ * @param ident the identifier of the catalog.+ * @param type the type of the catalog.+ * @param comment the comment of the catalog.+ * @param provider the provider of the catalog.+ * @param properties the properties of the catalog.+ * @param secretBindings optional property key → binding ({@code provider} + {@code plaintext})+ * for write-through+ * @param secretReferences optional property key → secret locator ({@code provider} plus+ * provider-specific attributes).+ * @return The created catalog.+ * @throws NoSuchMetalakeException If the metalake does not exist.+ * @throws CatalogAlreadyExistsException If the catalog already exists.+ * @throws UnsupportedOperationException if create-time secrets are not supported+ */+ default Catalog createCatalog(+ NameIdentifier ident,+ Catalog.Type type,+ String provider,+ String comment,+ Map<String, String> properties,+ Map<String, SecretBinding> secretBindings,+ Map<String, SecretReference> secretReferences)+ throws NoSuchMetalakeException, CatalogAlreadyExistsException {+ throw new UnsupportedOperationException("Creating a catalog with secrets is not supported");+ }/*** Alter a catalog with specified identifier.diff --git a/core/src/main/java/org/apache/gravitino/hook/CatalogHookDispatcher.java b/core/src/main/java/org/apache/gravitino/hook/CatalogHookDispatcher.javaindex 577c71dfd8..cc520f3d91 100644--- a/core/src/main/java/org/apache/gravitino/hook/CatalogHookDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/hook/CatalogHookDispatcher.java@@ -18,6 +18,7 @@*/package org.apache.gravitino.hook;+import java.util.Collections;import java.util.List;import java.util.Map;import org.apache.gravitino.Catalog;@@ -38,6 +39,8 @@ import org.apache.gravitino.exceptions.CatalogNotInUseException;import org.apache.gravitino.exceptions.NoSuchCatalogException;import org.apache.gravitino.exceptions.NoSuchMetalakeException;import org.apache.gravitino.exceptions.NonEmptyEntityException;+import org.apache.gravitino.secret.SecretBinding;+import org.apache.gravitino.secret.SecretReference;import org.apache.gravitino.utils.NameIdentifierUtil;import org.apache.gravitino.utils.PrincipalUtils;import org.slf4j.Logger;@@ -79,7 +82,23 @@ public class CatalogHookDispatcher implements CatalogDispatcher {String comment,Map<String, String> properties)throws NoSuchMetalakeException, CatalogAlreadyExistsException {- Catalog catalog = dispatcher.createCatalog(ident, type, provider, comment, properties);+ return createCatalog(+ ident, type, provider, comment, properties, Collections.emptyMap(), Collections.emptyMap());+ }++ @Override+ public Catalog createCatalog(+ NameIdentifier ident,+ Catalog.Type type,+ String provider,+ String comment,+ Map<String, String> properties,+ Map<String, SecretBinding> secretBindings,+ Map<String, SecretReference> secretReferences)+ throws NoSuchMetalakeException, CatalogAlreadyExistsException {+ Catalog catalog =+ dispatcher.createCatalog(+ ident, type, provider, comment, properties, secretBindings, secretReferences);try {// Set the creator as the owner of the catalog.@@ -152,7 +171,8 @@ public class CatalogHookDispatcher implements CatalogDispatcher {}// We should call the authorization plugin before dropping the catalog, because the dropping- // catalog will close the authorization plugin.+ // catalog will close the authorization plugin. Child schema/fileset write-through secrets are+ // cleaned in CatalogManager.dropCatalog / FilesetCatalogOperations.dropSchema.return dispatcher.dropCatalog(ident, force);}diff --git a/core/src/main/java/org/apache/gravitino/hook/MetalakeHookDispatcher.java b/core/src/main/java/org/apache/gravitino/hook/MetalakeHookDispatcher.javaindex 310368d67f..ef62bb839a 100644--- a/core/src/main/java/org/apache/gravitino/hook/MetalakeHookDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/hook/MetalakeHookDispatcher.java@@ -103,6 +103,8 @@ public class MetalakeHookDispatcher implements MetalakeDispatcher {@Overridepublic boolean dropMetalake(NameIdentifier ident, boolean force)throws NonEmptyEntityException, MetalakeInUseException {+ // Child catalog/schema/fileset write-through secrets are cleaned when MetalakeManager+ // force-drops catalogs via CatalogManager.dropCatalog → FilesetCatalogOperations.dropSchema.return dispatcher.dropMetalake(ident, force);}diff --git a/core/src/main/java/org/apache/gravitino/hook/SchemaHookDispatcher.java b/core/src/main/java/org/apache/gravitino/hook/SchemaHookDispatcher.javaindex dae07ffbc6..7bd644df16 100644--- a/core/src/main/java/org/apache/gravitino/hook/SchemaHookDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/hook/SchemaHookDispatcher.java@@ -41,6 +41,8 @@ import org.apache.gravitino.exceptions.NonEmptySchemaException;import org.apache.gravitino.exceptions.SchemaAlreadyExistsException;import org.apache.gravitino.lock.LockType;import org.apache.gravitino.lock.TreeLockUtils;+import org.apache.gravitino.secret.SecretBinding;+import org.apache.gravitino.secret.SecretReference;import org.apache.gravitino.utils.HierarchicalSchemaUtil;import org.apache.gravitino.utils.NameIdentifierUtil;import org.apache.gravitino.utils.PrincipalUtils;@@ -65,6 +67,17 @@ public class SchemaHookDispatcher implements SchemaDispatcher {@Overridepublic Schema createSchema(NameIdentifier ident, String comment, Map<String, String> properties)throws NoSuchCatalogException, SchemaAlreadyExistsException {+ return createSchema(ident, comment, properties, Collections.emptyMap(), Collections.emptyMap());+ }++ @Override+ public Schema createSchema(+ NameIdentifier ident,+ String comment,+ Map<String, String> properties,+ Map<String, SecretBinding> secretBindings,+ Map<String, SecretReference> secretReferences)+ throws NoSuchCatalogException, SchemaAlreadyExistsException {// The inner NormalizeDispatcher case-folds the schema name based on catalog capabilities, so// the entity is stored under the normalized identifier. Normalize here too so ownership is// attached to the identifiers the manager sees and ancestor probing matches stored names.@@ -91,7 +104,8 @@ public class SchemaHookDispatcher implements SchemaDispatcher {// ancestor's owner is never overwritten.List<NameIdentifier> newAncestors = findMissingAncestors(normalizedIdent);- Schema schema = dispatcher.createSchema(ident, comment, properties);+ Schema schema =+ dispatcher.createSchema(ident, comment, properties, secretBindings, secretReferences);// Set the creator as the owner of the new schema and of any ancestors it created. This// mirrors IcebergNamespaceHookDispatcher.createNamespace so ownership-baseddiff --git a/core/src/main/java/org/apache/gravitino/listener/CatalogEventDispatcher.java b/core/src/main/java/org/apache/gravitino/listener/CatalogEventDispatcher.javaindex bd738380b7..eec1732b50 100644--- a/core/src/main/java/org/apache/gravitino/listener/CatalogEventDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/listener/CatalogEventDispatcher.java@@ -19,6 +19,7 @@package org.apache.gravitino.listener;+import java.util.Collections;import java.util.Map;import org.apache.gravitino.Catalog;import org.apache.gravitino.CatalogChange;@@ -53,6 +54,8 @@ import org.apache.gravitino.listener.api.event.LoadCatalogEvent;import org.apache.gravitino.listener.api.event.LoadCatalogFailureEvent;import org.apache.gravitino.listener.api.event.LoadCatalogPreEvent;import org.apache.gravitino.listener.api.info.CatalogInfo;+import org.apache.gravitino.secret.SecretBinding;+import org.apache.gravitino.secret.SecretReference;import org.apache.gravitino.utils.PrincipalUtils;/**@@ -137,12 +140,28 @@ public class CatalogEventDispatcher implements CatalogDispatcher {String comment,Map<String, String> properties)throws NoSuchMetalakeException, CatalogAlreadyExistsException {+ return createCatalog(+ ident, type, provider, comment, properties, Collections.emptyMap(), Collections.emptyMap());+ }++ @Override+ public Catalog createCatalog(+ NameIdentifier ident,+ Catalog.Type type,+ String provider,+ String comment,+ Map<String, String> properties,+ Map<String, SecretBinding> secretBindings,+ Map<String, SecretReference> secretReferences)+ throws NoSuchMetalakeException, CatalogAlreadyExistsException {CatalogInfo catalogInfo =new CatalogInfo(ident.name(), type, provider, comment, properties, null);eventBus.dispatchEvent(new CreateCatalogPreEvent(PrincipalUtils.getCurrentUserName(), ident, catalogInfo));try {- Catalog catalog = dispatcher.createCatalog(ident, type, provider, comment, properties);+ Catalog catalog =+ dispatcher.createCatalog(+ ident, type, provider, comment, properties, secretBindings, secretReferences);eventBus.dispatchEvent(new CreateCatalogEvent(PrincipalUtils.getCurrentUserName(), ident, new CatalogInfo(catalog)));diff --git a/core/src/main/java/org/apache/gravitino/listener/SchemaEventDispatcher.java b/core/src/main/java/org/apache/gravitino/listener/SchemaEventDispatcher.javaindex 179609d584..e5ad603ebc 100644--- a/core/src/main/java/org/apache/gravitino/listener/SchemaEventDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/listener/SchemaEventDispatcher.java@@ -19,6 +19,7 @@package org.apache.gravitino.listener;+import java.util.Collections;import java.util.Map;import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.Namespace;@@ -46,6 +47,8 @@ import org.apache.gravitino.listener.api.event.LoadSchemaEvent;import org.apache.gravitino.listener.api.event.LoadSchemaFailureEvent;import org.apache.gravitino.listener.api.event.LoadSchemaPreEvent;import org.apache.gravitino.listener.api.info.SchemaInfo;+import org.apache.gravitino.secret.SecretBinding;+import org.apache.gravitino.secret.SecretReference;import org.apache.gravitino.utils.PrincipalUtils;/**@@ -96,11 +99,23 @@ public class SchemaEventDispatcher implements SchemaDispatcher {@Overridepublic Schema createSchema(NameIdentifier ident, String comment, Map<String, String> properties)throws NoSuchCatalogException, SchemaAlreadyExistsException {+ return createSchema(ident, comment, properties, Collections.emptyMap(), Collections.emptyMap());+ }++ @Override+ public Schema createSchema(+ NameIdentifier ident,+ String comment,+ Map<String, String> properties,+ Map<String, SecretBinding> secretBindings,+ Map<String, SecretReference> secretReferences)+ throws NoSuchCatalogException, SchemaAlreadyExistsException {SchemaInfo createSchemaRequest = new SchemaInfo(ident.name(), comment, properties, null);eventBus.dispatchEvent(new CreateSchemaPreEvent(PrincipalUtils.getCurrentUserName(), ident, createSchemaRequest));try {- Schema schema = dispatcher.createSchema(ident, comment, properties);+ Schema schema =+ dispatcher.createSchema(ident, comment, properties, secretBindings, secretReferences);eventBus.dispatchEvent(new CreateSchemaEvent(PrincipalUtils.getCurrentUserName(), ident, new SchemaInfo(schema)));diff --git a/core/src/main/java/org/apache/gravitino/metalake/MetalakeManager.java b/core/src/main/java/org/apache/gravitino/metalake/MetalakeManager.javaindex 8f4a038ae4..a6bcc59b03 100644--- a/core/src/main/java/org/apache/gravitino/metalake/MetalakeManager.java+++ b/core/src/main/java/org/apache/gravitino/metalake/MetalakeManager.java@@ -37,6 +37,7 @@ import org.apache.gravitino.GravitinoEnv;import org.apache.gravitino.MetalakeChange;import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.Namespace;+import org.apache.gravitino.catalog.CatalogManager;import org.apache.gravitino.exceptions.AlreadyExistsException;import org.apache.gravitino.exceptions.MetalakeAlreadyExistsException;import org.apache.gravitino.exceptions.MetalakeInUseException;@@ -69,6 +70,8 @@ public class MetalakeManager implements MetalakeDispatcher, Closeable {private final IdGenerator idGenerator;+ private final CatalogManager catalogManager;+@Overridepublic void close() {// do nothing@@ -81,8 +84,24 @@ public class MetalakeManager implements MetalakeDispatcher, Closeable {* @param idGenerator The IdGenerator to use for generating Metalake identifiers.*/public MetalakeManager(EntityStore store, IdGenerator idGenerator) {+ this(store, idGenerator, null);+ }++ /**+ * Constructs a MetalakeManager instance.+ *+ * @param store The EntityStore to use for managing Metalakes.+ * @param idGenerator The IdGenerator to use for generating Metalake identifiers.+ * @param catalogManager Used on force-drop to drop child catalogs via {@link+ * CatalogManager#dropCatalog} (schema/fileset secrets cleaned on that path, including {@code+ * FilesetCatalogOperations.dropSchema}); may be null in tests that do not exercise force-drop+ * with catalogs.+ */+ public MetalakeManager(+ EntityStore store, IdGenerator idGenerator, CatalogManager catalogManager) {this.store = store;this.idGenerator = idGenerator;+ this.catalogManager = catalogManager;// preload all metalakes and put them into cache, this is useful when user load schema/table// directly without list/get metalake first.@@ -340,6 +359,13 @@ public class MetalakeManager implements MetalakeDispatcher, Closeable {@Overridepublic boolean dropMetalake(NameIdentifier ident, boolean force)throws NonEmptyEntityException, MetalakeInUseException {+ // Mirror CatalogManager.dropCatalog → ops.dropSchema: force-drop children through the real+ // drop path so FilesetCatalogOperations / CatalogManager clean write-through secrets (and+ // managed storage). Do this before the metalake root lock to avoid nesting tree locks.+ if (force) {+ dropCatalogsUnderMetalake(ident);+ }+return TreeLockUtils.doWithRootTreeLock(LockType.WRITE,() -> {@@ -369,6 +395,37 @@ public class MetalakeManager implements MetalakeDispatcher, Closeable {});}+ /**+ * Force-drop child catalogs via {@link CatalogManager#dropCatalog} so schema/fileset secrets are+ * cleaned on the same path as a normal catalog force-drop ({@code ops.dropSchema} →+ * FilesetCatalogOperations, then catalog secrets in CatalogManager).+ *+ * <p>Callers typically {@code disableMetalake} before force-drop. {@link+ * CatalogManager#dropCatalog} requires catalog {@code metalake-in-use=true}, so a disabled+ * metalake is briefly re-enabled for child cleanup. The metalake entity is deleted immediately+ * afterward, so the temporary enable is not restored.+ */+ private void dropCatalogsUnderMetalake(NameIdentifier metalakeIdent) {+ if (catalogManager == null) {+ return;+ }+ try {+ if (!metalakeInUse(store, metalakeIdent)) {+ enableMetalake(metalakeIdent);+ }+ List<CatalogEntity> catalogs =+ store.list(Namespace.of(metalakeIdent.name()), CatalogEntity.class, EntityType.CATALOG);+ for (CatalogEntity catalog : catalogs) {+ catalogManager.dropCatalog(+ NameIdentifier.of(metalakeIdent.name(), catalog.name()), true /* force */);+ }+ } catch (NoSuchMetalakeException e) {+ // Metalake is already gone; dropMetalake will return false.+ } catch (IOException e) {+ throw new RuntimeException(e);+ }+ }+@Overridepublic void enableMetalake(NameIdentifier ident) throws NoSuchMetalakeException {TreeLockUtils.doWithTreeLock(diff --git a/core/src/main/java/org/apache/gravitino/secret/SecretManager.java b/core/src/main/java/org/apache/gravitino/secret/SecretManager.javaindex 3a989209df..46abd86f4d 100644--- a/core/src/main/java/org/apache/gravitino/secret/SecretManager.java+++ b/core/src/main/java/org/apache/gravitino/secret/SecretManager.java@@ -127,7 +127,8 @@ public class SecretManager implements Closeable {* is the mutable map that will be stored (may already contain merged catalog conf).** @param properties properties used for key uniqueness checks (may be null)- * @param targetProperties mutable properties that receive URN values+ * @param targetProperties mutable properties that receive URN values (may be null only when both+ * secret maps are null or empty)* @param entityType {@code catalog}, {@code schema}, or {@code fileset}* @param entityId stable numeric entity id* @param secretBindings property key → write-through binding (may be null)@@ -137,12 +138,17 @@ public class SecretManager implements Closeable {*/public List<SecretMaterial> assembleSecretMaterials(@Nullable Map<String, String> properties,- Map<String, String> targetProperties,+ @Nullable Map<String, String> targetProperties,String entityType,long entityId,@Nullable Map<String, SecretBinding> secretBindings,@Nullable Map<String, SecretReference> secretReferences) {checkSecretKeys(properties, secretBindings, secretReferences);+ if (!SecretPropertyUtils.hasSecretMaps(secretBindings, secretReferences)) {+ return List.of();+ }+ Preconditions.checkArgument(+ targetProperties != null, "targetProperties must not be null when secrets are present");Map<String, SecretBinding> bindings = secretBindings == null ? Map.of() : secretBindings;Map<String, SecretReference> references =secretReferences == null ? Map.of() : secretReferences;diff --git a/core/src/main/java/org/apache/gravitino/secret/SecretPropertyUtils.java b/core/src/main/java/org/apache/gravitino/secret/SecretPropertyUtils.javaindex f7ae60b570..fc51329c76 100644--- a/core/src/main/java/org/apache/gravitino/secret/SecretPropertyUtils.java+++ b/core/src/main/java/org/apache/gravitino/secret/SecretPropertyUtils.java@@ -106,6 +106,19 @@ public final class SecretPropertyUtils {return merged;}+ /**+ * Returns whether either secret map has at least one entry.+ *+ * @param secretBindings write-through bindings (may be null)+ * @param secretReferences secret locators (may be null)+ * @return true when at least one secret map is non-empty+ */+ public static boolean hasSecretMaps(+ @Nullable Map<?, ?> secretBindings, @Nullable Map<?, ?> secretReferences) {+ return (secretBindings != null && !secretBindings.isEmpty())+ || (secretReferences != null && !secretReferences.isEmpty());+ }+/*** Returns a mutable copy of a property map for create-time assembly.*@@ -119,6 +132,31 @@ public final class SecretPropertyUtils {return properties == null ? new HashMap<>() : new HashMap<>(properties);}+ /**+ * Returns a mutable property map for create-time assembly, or {@code null} when the caller+ * supplied no properties and no secrets.+ *+ * <p>When {@code properties} is {@code null} and both secret maps are null or empty, returns+ * {@code null} so {@code validatePropertyForCreate} can skip required-key checks (historical+ * behavior). When secrets are present but {@code properties} is null, returns an empty {@link+ * HashMap} for URN assembly. Otherwise returns a new {@link HashMap} copy of {@code properties}.+ *+ * @param properties property map to copy (may be null)+ * @param secretBindings write-through bindings (may be null)+ * @param secretReferences secret locators (may be null)+ * @return a mutable property map, or null when there are no properties and no secrets+ */+ @Nullable+ public static Map<String, String> copyEntityProperties(+ @Nullable Map<String, String> properties,+ @Nullable Map<?, ?> secretBindings,+ @Nullable Map<?, ?> secretReferences) {+ if (properties == null && !hasSecretMaps(secretBindings, secretReferences)) {+ return null;+ }+ return properties == null ? new HashMap<>() : new HashMap<>(properties);+ }+/*** Puts each URN string into {@code entityProperties} under the property key encoded in the URN* (last identifier segment).diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestCatalogManager.java b/core/src/test/java/org/apache/gravitino/catalog/TestCatalogManager.javaindex e1770ecc7b..23b9140a36 100644--- a/core/src/test/java/org/apache/gravitino/catalog/TestCatalogManager.java+++ b/core/src/test/java/org/apache/gravitino/catalog/TestCatalogManager.java@@ -37,6 +37,7 @@ import java.time.Duration;import java.time.Instant;import java.util.List;import java.util.Map;+import java.util.Properties;import java.util.Set;import java.util.concurrent.CountDownLatch;import java.util.concurrent.ExecutorService;@@ -44,6 +45,7 @@ import java.util.concurrent.Executors;import java.util.concurrent.Future;import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicBoolean;+import java.util.concurrent.atomic.AtomicLong;import java.util.concurrent.atomic.AtomicReference;import org.apache.commons.lang3.reflect.FieldUtils;import org.apache.gravitino.Catalog;@@ -76,7 +78,14 @@ import org.apache.gravitino.meta.BaseMetalake;import org.apache.gravitino.meta.CatalogEntity;import org.apache.gravitino.meta.SchemaEntity;import org.apache.gravitino.meta.SchemaVersion;+import org.apache.gravitino.secret.SecretBinding;+import org.apache.gravitino.secret.SecretConstants;import org.apache.gravitino.secret.SecretManager;+import org.apache.gravitino.secret.SecretPropertyUtils;+import org.apache.gravitino.secret.SecretProviderRegistry;+import org.apache.gravitino.secret.SecretUrn;+import org.apache.gravitino.secret.memory.InMemorySecretsProvider;+import org.apache.gravitino.storage.IdGenerator;import org.apache.gravitino.storage.RandomIdGenerator;import org.apache.gravitino.storage.memory.TestMemoryEntityStore;import org.apache.gravitino.storage.memory.TestMemoryEntityStore.InMemoryEntityStore;@@ -1475,4 +1484,117 @@ public class TestCatalogManager {Assertions.assertFalse(testProps.containsKey(ID_KEY), "`gravitino.identifier` is missing");}++ @Test+ void testSecrets() throws Exception {+ try (SecretManager secrets = memorySecretManager();+ CatalogManager manager =+ new CatalogManager(config, entityStore, new RandomIdGenerator(), secrets)) {+ NameIdentifier ident = NameIdentifier.of("metalake", "secret_ok");+ Catalog catalog =+ manager.createCatalog(+ ident,+ Catalog.Type.RELATIONAL,+ provider,+ "comment",+ catalogProps(),+ Map.of(PROPERTY_KEY4, new SecretBinding("memory", "s3cr3t")),+ Map.of());+ Assertions.assertFalse(catalog.properties().containsKey(PROPERTY_KEY4));+ String urn =+ entityStore+ .get(ident, EntityType.CATALOG, CatalogEntity.class)+ .getProperties()+ .get(PROPERTY_KEY4);+ Assertions.assertTrue(SecretPropertyUtils.isSecretProperty(PROPERTY_KEY4, urn));+ Assertions.assertEquals("s3cr3t", secrets.readSecret(SecretUrn.parse(urn)));+ Assertions.assertTrue(manager.dropCatalog(ident, true));+ Assertions.assertThrows(+ IllegalArgumentException.class, () -> secrets.readSecret(SecretUrn.parse(urn)));+ }+ }++ @Test+ void testSecretRollback() throws Exception {+ try (SecretManager secrets = memorySecretManager()) {+ IdGenerator ids = new AtomicLong(4242L)::getAndIncrement;+ CatalogManager manager = Mockito.spy(new CatalogManager(config, entityStore, ids, secrets));+ NameIdentifier ident = NameIdentifier.of("metalake", "secret_fail");+ Mockito.doThrow(new RuntimeException("init failed"))+ .when(manager)+ .createCatalogWrapper(any(CatalogEntity.class), any());+ SecretUrn urn = writeThroughUrn("catalog", 4242L, PROPERTY_KEY4);+ Assertions.assertThrows(+ RuntimeException.class,+ () ->+ manager.createCatalog(+ ident,+ Catalog.Type.RELATIONAL,+ provider,+ "comment",+ catalogProps(),+ Map.of(PROPERTY_KEY4, new SecretBinding("memory", "x")),+ Map.of()));+ Assertions.assertFalse(entityStore.exists(ident, EntityType.CATALOG));+ Assertions.assertThrows(IllegalArgumentException.class, () -> secrets.readSecret(urn));+ manager.close();+ }+ }++ @Test+ void testSecretNoMetalake() throws Exception {+ try (SecretManager secrets = memorySecretManager();+ CatalogManager manager =+ new CatalogManager(+ config, entityStore, new AtomicLong(4343L)::getAndIncrement, secrets)) {+ NameIdentifier ident = NameIdentifier.of("missing_metalake", "secret_catalog");+ SecretUrn urn = writeThroughUrn("catalog", 4343L, PROPERTY_KEY4);+ Assertions.assertThrows(+ NoSuchMetalakeException.class,+ () ->+ manager.createCatalog(+ ident,+ Catalog.Type.RELATIONAL,+ provider,+ "comment",+ catalogProps(),+ Map.of(PROPERTY_KEY4, new SecretBinding("memory", "x")),+ Map.of()));+ Assertions.assertThrows(IllegalArgumentException.class, () -> secrets.readSecret(urn));+ }+ }++ private static Map<String, String> catalogProps() {+ return ImmutableMap.of(+ "provider",+ "test",+ PROPERTY_KEY1,+ "value1",+ PROPERTY_KEY2,+ "value2",+ PROPERTY_KEY5_PREFIX + "1",+ "value3");+ }++ private static SecretUrn writeThroughUrn(String entityType, long entityId, String key) {+ return SecretUrn.buildWriteThrough(+ "memory",+ Map.of(+ SecretConstants.ATTR_ENTITY_TYPE, entityType,+ SecretConstants.ATTR_ENTITY_ID, String.valueOf(entityId),+ SecretConstants.ATTR_PROPERTY_KEY, key));+ }++ private static SecretManager memorySecretManager() {+ Config c = new Config(false) {};+ Properties p = new Properties();+ p.setProperty(SecretProviderRegistry.GRAVITINO_SECRET_PROVIDERS, "memory");+ p.setProperty(+ SecretProviderRegistry.GRAVITINO_SECRET_PROVIDER_PREFIX+ + "memory."+ + SecretProviderRegistry.CLASS_NAME,+ InMemorySecretsProvider.class.getName());+ c.loadFromProperties(p);+ return new SecretManager(c);+ }}diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestSchemaOperationDispatcher.java b/core/src/test/java/org/apache/gravitino/catalog/TestSchemaOperationDispatcher.javaindex c5ebe8ff74..84f3c8e4f2 100644--- a/core/src/test/java/org/apache/gravitino/catalog/TestSchemaOperationDispatcher.java+++ b/core/src/test/java/org/apache/gravitino/catalog/TestSchemaOperationDispatcher.java@@ -36,6 +36,7 @@ import java.util.Arrays;import java.util.HashMap;import java.util.Map;import java.util.Optional;+import java.util.Properties;import org.apache.commons.lang3.reflect.FieldUtils;import org.apache.gravitino.Config;import org.apache.gravitino.Configs;@@ -50,9 +51,17 @@ import org.apache.gravitino.TestCatalog;import org.apache.gravitino.auth.AuthConstants;import org.apache.gravitino.connector.TestCatalogOperations;import org.apache.gravitino.exceptions.NoSuchEntityException;+import org.apache.gravitino.exceptions.SchemaAlreadyExistsException;import org.apache.gravitino.lock.LockManager;import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.meta.SchemaEntity;+import org.apache.gravitino.secret.SecretBinding;+import org.apache.gravitino.secret.SecretConstants;+import org.apache.gravitino.secret.SecretManager;+import org.apache.gravitino.secret.SecretPropertyUtils;+import org.apache.gravitino.secret.SecretProviderRegistry;+import org.apache.gravitino.secret.SecretUrn;+import org.apache.gravitino.secret.memory.InMemorySecretsProvider;import org.junit.jupiter.api.Assertions;import org.junit.jupiter.api.BeforeAll;import org.junit.jupiter.api.Test;@@ -431,6 +440,53 @@ public class TestSchemaOperationDispatcher extends TestOperationDispatcher {Assertions.assertTrue(entityStore.exists(ancestorA, SCHEMA));}+ @Test+ public void testSecrets() throws Exception {+ try (SecretManager secrets = memorySecretManager()) {+ SchemaOperationDispatcher d =+ new SchemaOperationDispatcher(catalogManager, entityStore, idGenerator, secrets);+ NameIdentifier ident = NameIdentifier.of(metalake, catalog, "schema_secret");+ Map<String, SecretBinding> bindings = Map.of("k2", new SecretBinding("memory", "s3cr3t"));+ Schema schema =+ d.createSchema(ident, "comment", ImmutableMap.of("k1", "v1"), bindings, Map.of());+ Assertions.assertFalse(schema.properties().containsKey("k2"));++ Schema stored =+ catalogManager+ .loadCatalogAndWrap(NameIdentifier.of(metalake, catalog))+ .doWithSchemaOps(ops -> ops.loadSchema(ident));+ Assertions.assertTrue(+ SecretPropertyUtils.isSecretProperty("k2", stored.properties().get("k2")));+ SchemaEntity entity = entityStore.get(ident, SCHEMA, SchemaEntity.class);+ SecretUrn urn =+ SecretUrn.buildWriteThrough(+ "memory",+ Map.of(+ SecretConstants.ATTR_ENTITY_TYPE, "schema",+ SecretConstants.ATTR_ENTITY_ID, String.valueOf(entity.id()),+ SecretConstants.ATTR_PROPERTY_KEY, "k2"));+ Assertions.assertEquals("s3cr3t", secrets.readSecret(urn));+ Assertions.assertThrows(+ SchemaAlreadyExistsException.class,+ () -> d.createSchema(ident, "comment", ImmutableMap.of("k1", "v1"), bindings, Map.of()));+ Assertions.assertTrue(d.dropSchema(ident, false));+ Assertions.assertThrows(IllegalArgumentException.class, () -> secrets.readSecret(urn));+ }+ }++ private static SecretManager memorySecretManager() {+ Config c = new Config(false) {};+ Properties p = new Properties();+ p.setProperty(SecretProviderRegistry.GRAVITINO_SECRET_PROVIDERS, "memory");+ p.setProperty(+ SecretProviderRegistry.GRAVITINO_SECRET_PROVIDER_PREFIX+ + "memory."+ + SecretProviderRegistry.CLASS_NAME,+ InMemorySecretsProvider.class.getName());+ c.loadFromProperties(p);+ return new SecretManager(c);+ }+private void putSchemaEntity(NameIdentifier ident) throws IOException {SchemaEntity entity =SchemaEntity.builder()diff --git a/core/src/test/java/org/apache/gravitino/hook/TestCatalogHookDispatcher.java b/core/src/test/java/org/apache/gravitino/hook/TestCatalogHookDispatcher.javaindex 1803646fc2..a114953f34 100644--- a/core/src/test/java/org/apache/gravitino/hook/TestCatalogHookDispatcher.java+++ b/core/src/test/java/org/apache/gravitino/hook/TestCatalogHookDispatcher.java@@ -57,6 +57,8 @@ public class TestCatalogHookDispatcher {Mockito.eq(Catalog.Type.RELATIONAL),Mockito.eq("provider"),Mockito.eq("comment"),+ Mockito.anyMap(),+ Mockito.anyMap(),Mockito.anyMap())).thenReturn(catalog);@@ -107,6 +109,8 @@ public class TestCatalogHookDispatcher {Mockito.eq(Catalog.Type.RELATIONAL),Mockito.eq("provider"),Mockito.eq("comment"),+ Mockito.anyMap(),+ Mockito.anyMap(),Mockito.anyMap())).thenReturn(catalog);Mockito.doThrow(rollbackException).when(dispatcher).dropCatalog(ident, true);diff --git a/core/src/test/java/org/apache/gravitino/hook/TestSchemaHookDispatcher.java b/core/src/test/java/org/apache/gravitino/hook/TestSchemaHookDispatcher.javaindex 3e05c3c83c..d5ebd8893d 100644--- a/core/src/test/java/org/apache/gravitino/hook/TestSchemaHookDispatcher.java+++ b/core/src/test/java/org/apache/gravitino/hook/TestSchemaHookDispatcher.java@@ -22,11 +22,13 @@ 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.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.anyBoolean;import static org.mockito.ArgumentMatchers.anyList;import static org.mockito.ArgumentMatchers.eq;import static org.mockito.Mockito.doReturn;import static org.mockito.Mockito.doThrow;import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.never;import static org.mockito.Mockito.verify;import static org.mockito.Mockito.when;@@ -116,7 +118,7 @@ public class TestSchemaHookDispatcher {public void testCreateSchemaThrowsWhenSetOwnerFails() {NameIdentifier ident = NameIdentifier.of("test_metalake", "test_catalog", "test_schema");Schema mockSchema = mock(Schema.class);- when(mockDispatcher.createSchema(any(), any(), any())).thenReturn(mockSchema);+ when(mockDispatcher.createSchema(any(), any(), any(), any(), any())).thenReturn(mockSchema);doThrow(new RuntimeException("Set owner failed")).when(mockOwnerDispatcher)@@ -127,7 +129,9 @@ public class TestSchemaHookDispatcher {RuntimeException.class,() -> hookDispatcher.createSchema(ident, "comment", Collections.emptyMap()));Assertions.assertEquals("Set owner failed", thrown.getMessage());- verify(mockDispatcher).createSchema(any(), any(), any());+ verify(mockDispatcher).createSchema(any(), any(), any(), any(), any());+ // Align with FilesetHookDispatcher / #12366: do not drop the schema when setOwner fails.+ verify(mockDispatcher, never()).dropSchema(any(), anyBoolean());}@Test@@ -138,7 +142,7 @@ public class TestSchemaHookDispatcher {NameIdentifier ident = NameIdentifier.of("test_metalake", "test_catalog", "MY_SCHEMA");Schema mockSchema = mock(Schema.class);- when(mockDispatcher.createSchema(any(), any(), any())).thenReturn(mockSchema);+ when(mockDispatcher.createSchema(any(), any(), any(), any(), any())).thenReturn(mockSchema);hookDispatcher.createSchema(ident, "comment", Collections.emptyMap());@@ -167,7 +171,7 @@ public class TestSchemaHookDispatcher {NameIdentifier ident = NameIdentifier.of("test_metalake", "test_catalog", "A:B:C");Schema mockSchema = mock(Schema.class);- when(mockDispatcher.createSchema(any(), any(), any())).thenReturn(mockSchema);+ when(mockDispatcher.createSchema(any(), any(), any(), any(), any())).thenReturn(mockSchema);// No ancestor exists yet, so creating "A:B:C" auto-creates "A" and "A:B".when(mockDispatcher.schemaExists(any())).thenReturn(false);@@ -187,7 +191,7 @@ public class TestSchemaHookDispatcher {NameIdentifier ident = NameIdentifier.of("test_metalake", "test_catalog", "A:B:C");Schema mockSchema = mock(Schema.class);- when(mockDispatcher.createSchema(any(), any(), any())).thenReturn(mockSchema);+ when(mockDispatcher.createSchema(any(), any(), any(), any(), any())).thenReturn(mockSchema);// "A" already exists (and has its own owner); only "A:B" and the leaf are newly created.NameIdentifier existingA = NameIdentifier.of("test_metalake", "test_catalog", "A");when(mockDispatcher.schemaExists(any())).thenReturn(false);diff --git a/core/src/test/java/org/apache/gravitino/listener/api/event/TestCatalogEvent.java b/core/src/test/java/org/apache/gravitino/listener/api/event/TestCatalogEvent.javaindex eaf01f9fb3..51f26585e5 100644--- a/core/src/test/java/org/apache/gravitino/listener/api/event/TestCatalogEvent.java+++ b/core/src/test/java/org/apache/gravitino/listener/api/event/TestCatalogEvent.java@@ -20,6 +20,7 @@package org.apache.gravitino.listener.api.event;import static org.mockito.ArgumentMatchers.anyBoolean;+import static org.mockito.ArgumentMatchers.nullable;import static org.mockito.Mockito.any;import static org.mockito.Mockito.mock;import static org.mockito.Mockito.when;@@ -382,7 +383,9 @@ public class TestCatalogEvent {any(Catalog.Type.class),any(String.class),any(String.class),- any(Map.class)))+ nullable(Map.class),+ nullable(Map.class),+ nullable(Map.class))).thenReturn(catalog);when(dispatcher.loadCatalog(any(NameIdentifier.class))).thenReturn(catalog);when(dispatcher.dropCatalog(any(NameIdentifier.class), anyBoolean())).thenReturn(true);diff --git a/core/src/test/java/org/apache/gravitino/listener/api/event/TestSchemaEvent.java b/core/src/test/java/org/apache/gravitino/listener/api/event/TestSchemaEvent.javaindex 9e2e8fa293..646fc22035 100644--- a/core/src/test/java/org/apache/gravitino/listener/api/event/TestSchemaEvent.java+++ b/core/src/test/java/org/apache/gravitino/listener/api/event/TestSchemaEvent.java@@ -19,6 +19,7 @@package org.apache.gravitino.listener.api.event;+import static org.mockito.ArgumentMatchers.nullable;import static org.mockito.Mockito.any;import static org.mockito.Mockito.eq;import static org.mockito.Mockito.mock;@@ -274,7 +275,12 @@ public class TestSchemaEvent {private SchemaDispatcher mockSchemaDispatcher() {SchemaDispatcher dispatcher = mock(SchemaDispatcher.class);- when(dispatcher.createSchema(any(NameIdentifier.class), any(String.class), any(Map.class)))+ when(dispatcher.createSchema(+ any(NameIdentifier.class),+ any(String.class),+ nullable(Map.class),+ nullable(Map.class),+ nullable(Map.class))).thenReturn(schema);when(dispatcher.loadSchema(any(NameIdentifier.class))).thenReturn(schema);when(dispatcher.dropSchema(any(NameIdentifier.class), eq(true))).thenReturn(false);diff --git a/core/src/test/java/org/apache/gravitino/metalake/TestMetalakeManager.java b/core/src/test/java/org/apache/gravitino/metalake/TestMetalakeManager.javaindex 55084847f3..862bef68d7 100644--- a/core/src/test/java/org/apache/gravitino/metalake/TestMetalakeManager.java+++ b/core/src/test/java/org/apache/gravitino/metalake/TestMetalakeManager.java@@ -26,24 +26,30 @@ import static org.mockito.Mockito.doReturn;import com.google.common.collect.ImmutableMap;import com.google.common.collect.Sets;import java.io.IOException;+import java.time.Instant;import java.util.List;import java.util.Map;import java.util.Set;import org.apache.commons.lang3.reflect.FieldUtils;+import org.apache.gravitino.Catalog;import org.apache.gravitino.Config;import org.apache.gravitino.Entity.EntityType;import org.apache.gravitino.EntityStore;import org.apache.gravitino.GravitinoEnv;import org.apache.gravitino.MetalakeChange;import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.Namespace;import org.apache.gravitino.StringIdentifier;import org.apache.gravitino.UserPrincipal;import org.apache.gravitino.auth.AuthConstants;+import org.apache.gravitino.catalog.CatalogManager;import org.apache.gravitino.exceptions.MetalakeAlreadyExistsException;import org.apache.gravitino.exceptions.NoSuchEntityException;import org.apache.gravitino.exceptions.NoSuchMetalakeException;import org.apache.gravitino.lock.LockManager;+import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.meta.BaseMetalake;+import org.apache.gravitino.meta.CatalogEntity;import org.apache.gravitino.storage.RandomIdGenerator;import org.apache.gravitino.storage.memory.TestMemoryEntityStore;import org.apache.gravitino.storage.memory.TestMemoryEntityStore.InMemoryEntityStore;@@ -259,6 +265,44 @@ public class TestMetalakeManager {metalakeManager.dropMetalake(ident3, true);}+ @Test+ public void testForceDropMetalakeAfterDisableDropsLeftoverCatalogs() throws Exception {+ // Mirrors IT tearDown: disableMetalake then dropMetalake(force=true) while a catalog entity+ // may still remain. CatalogManager.dropCatalog requires metalake-in-use on the catalog.+ InMemoryEntityStore store = new InMemoryEntityStore();+ store.initialize(config);+ CatalogManager catalogManager = Mockito.mock(CatalogManager.class);+ Mockito.when(catalogManager.dropCatalog(Mockito.any(NameIdentifier.class), Mockito.eq(true)))+ .thenReturn(true);+ Mockito.doNothing()+ .when(catalogManager)+ .setMetalakeInUseStatus(Mockito.any(NameIdentifier.class), Mockito.anyBoolean());++ FieldUtils.writeField(GravitinoEnv.getInstance(), "catalogManager", catalogManager, true);+ MetalakeManager manager = new MetalakeManager(store, new RandomIdGenerator(), catalogManager);++ NameIdentifier metalakeIdent = NameIdentifier.of("force_drop_leftover_ml");+ manager.createMetalake(metalakeIdent, "comment", ImmutableMap.of());+ store.put(+ CatalogEntity.builder()+ .withId(99L)+ .withName("leftover_catalog")+ .withNamespace(Namespace.of(metalakeIdent.name()))+ .withType(Catalog.Type.RELATIONAL)+ .withProvider("test")+ .withAuditInfo(+ AuditInfo.builder().withCreator("test").withCreateTime(Instant.now()).build())+ .build(),+ true);++ manager.disableMetalake(metalakeIdent);+ Assertions.assertTrue(manager.dropMetalake(metalakeIdent, true));+ Mockito.verify(catalogManager)+ .dropCatalog(NameIdentifier.of(metalakeIdent.name(), "leftover_catalog"), true);++ store.close();+ }+private void testProperties(Map<String, String> expectedProps, Map<String, String> testProps) {expectedProps.forEach((k, v) -> {diff --git a/core/src/test/java/org/apache/gravitino/secret/TestSecretPropertyUtils.java b/core/src/test/java/org/apache/gravitino/secret/TestSecretPropertyUtils.javaindex d51e0a8859..9a95fc337e 100644--- a/core/src/test/java/org/apache/gravitino/secret/TestSecretPropertyUtils.java+++ b/core/src/test/java/org/apache/gravitino/secret/TestSecretPropertyUtils.java@@ -35,7 +35,8 @@ public class TestSecretPropertyUtils {Map<String, String> properties = Map.of("jdbc-user", "root");Map<String, SecretBinding> bindings =Map.of("jdbc-password", new SecretBinding("memory", "s3cr3t"));- Map<String, String> entityProps = SecretPropertyUtils.copyEntityProperties(properties);+ Map<String, String> entityProps =+ SecretPropertyUtils.copyEntityProperties(properties, bindings, Map.of());List<SecretMaterial> writes =sm.assembleSecretMaterials(properties, entityProps, "catalog", 42L, bindings, Map.of());sm.writeSecrets(writes);@@ -50,9 +51,17 @@ public class TestSecretPropertyUtils {@Testvoid testCopyEntityProperties() {- Assertions.assertTrue(SecretPropertyUtils.copyEntityProperties(null).isEmpty());+ Assertions.assertNull(SecretPropertyUtils.copyEntityProperties(null, null, null));+ Assertions.assertNull(SecretPropertyUtils.copyEntityProperties(null, Map.of(), Map.of()));++ Map<String, SecretBinding> bindings =+ Map.of("jdbc-password", new SecretBinding("memory", "s3cr3t"));+ Map<String, String> forSecrets = SecretPropertyUtils.copyEntityProperties(null, bindings, null);+ Assertions.assertNotNull(forSecrets);+ Assertions.assertTrue(forSecrets.isEmpty());+Map<String, String> original = Map.of("a", "b");- Map<String, String> copy = SecretPropertyUtils.copyEntityProperties(original);+ Map<String, String> copy = SecretPropertyUtils.copyEntityProperties(original, null, null);Assertions.assertEquals(original, copy);copy.put("c", "d");Assertions.assertFalse(original.containsKey("c"));@@ -127,6 +136,15 @@ public class TestSecretPropertyUtils {Assertions.assertTrue(SecretPropertyUtils.mergeProperties(null, null).isEmpty());}+ @Test+ void testAssembleWithNullTargetWhenNoSecrets() {+ try (SecretManager sm = memorySecretManager()) {+ List<SecretMaterial> writes =+ sm.assembleSecretMaterials(null, null, "schema", 1L, null, null);+ Assertions.assertTrue(writes.isEmpty());+ }+ }+private static SecretManager memorySecretManager() {Config config = new Config(false) {};Properties properties = new Properties();diff --git a/docs/open-api/catalogs.yaml b/docs/open-api/catalogs.yamlindex 026b361736..ae82be9ce8 100644--- a/docs/open-api/catalogs.yaml+++ b/docs/open-api/catalogs.yaml@@ -464,6 +464,22 @@ components:default: { }additionalProperties:type: string+ secretBindings:+ type: object+ description: >+ Optional map of property key to write-through binding. Persisted value+ becomes a URN.+ nullable: true+ additionalProperties:+ $ref: "./secrets.yaml#/components/schemas/SecretBinding"+ secretReferences:+ type: object+ description: >+ Optional map of property key to secret locator. Server builds and+ persists the URN. Must not overlap with secretBindings.+ nullable: true+ additionalProperties:+ $ref: "./secrets.yaml#/components/schemas/SecretReference"CatalogSetRequest:type: objectdiff --git a/docs/open-api/schemas.yaml b/docs/open-api/schemas.yamlindex 634519cbbb..df03ce4c52 100644--- a/docs/open-api/schemas.yaml+++ b/docs/open-api/schemas.yaml@@ -194,6 +194,22 @@ components:default: { }additionalProperties:type: string+ secretBindings:+ type: object+ description: >+ Optional map of property key to write-through binding. Persisted value+ becomes a URN.+ nullable: true+ additionalProperties:+ $ref: "./secrets.yaml#/components/schemas/SecretBinding"+ secretReferences:+ type: object+ description: >+ Optional map of property key to secret locator. Server builds and+ persists the URN. Must not overlap with secretBindings.+ nullable: true+ additionalProperties:+ $ref: "./secrets.yaml#/components/schemas/SecretReference"Schema:type: objectdiff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/CatalogOperations.java b/server/src/main/java/org/apache/gravitino/server/web/rest/CatalogOperations.javaindex 41f35ab7fb..79a260bfef 100644--- a/server/src/main/java/org/apache/gravitino/server/web/rest/CatalogOperations.java+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/CatalogOperations.java@@ -52,6 +52,8 @@ import org.apache.gravitino.dto.responses.CatalogListResponse;import org.apache.gravitino.dto.responses.CatalogResponse;import org.apache.gravitino.dto.responses.DropResponse;import org.apache.gravitino.dto.responses.EntityListResponse;+import org.apache.gravitino.dto.secret.SecretBindingDTO;+import org.apache.gravitino.dto.secret.SecretReferenceDTO;import org.apache.gravitino.dto.util.DTOConverters;import org.apache.gravitino.metrics.MetricNames;import org.apache.gravitino.server.authorization.MetadataAuthzHelper;@@ -154,7 +156,9 @@ public class CatalogOperations {request.getType(),request.getProvider(),request.getComment(),- request.getProperties());+ request.getProperties(),+ SecretBindingDTO.toSecretBindings(request.getSecretBindings()),+ SecretReferenceDTO.toSecretReferences(request.getSecretReferences()));Response response = Utils.ok(new CatalogResponse(DTOConverters.toDTO(catalog)));LOG.info("Catalog created: {}.{}", metalake, catalog.name());return response;diff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/SchemaOperations.java b/server/src/main/java/org/apache/gravitino/server/web/rest/SchemaOperations.javaindex 1b8167331a..49fc72941a 100644--- a/server/src/main/java/org/apache/gravitino/server/web/rest/SchemaOperations.java+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/SchemaOperations.java@@ -49,6 +49,8 @@ import org.apache.gravitino.dto.requests.SchemaUpdatesRequest;import org.apache.gravitino.dto.responses.DropResponse;import org.apache.gravitino.dto.responses.EntityListResponse;import org.apache.gravitino.dto.responses.SchemaResponse;+import org.apache.gravitino.dto.secret.SecretBindingDTO;+import org.apache.gravitino.dto.secret.SecretReferenceDTO;import org.apache.gravitino.dto.util.DTOConverters;import org.apache.gravitino.metrics.MetricNames;import org.apache.gravitino.server.authorization.MetadataAuthzHelper;@@ -150,7 +152,12 @@ public class SchemaOperations {NameIdentifier ident =NameIdentifierUtil.ofSchema(metalake, catalog, request.getName());Schema schema =- dispatcher.createSchema(ident, request.getComment(), request.getProperties());+ dispatcher.createSchema(+ ident,+ request.getComment(),+ request.getProperties(),+ SecretBindingDTO.toSecretBindings(request.getSecretBindings()),+ SecretReferenceDTO.toSecretReferences(request.getSecretReferences()));Response response = Utils.ok(new SchemaResponse(DTOConverters.toDTO(schema)));LOG.info("Schema created: {}.{}.{}", metalake, catalog, schema.name());return response;diff --git a/server/src/test/java/org/apache/gravitino/server/web/rest/TestCatalogOperations.java b/server/src/test/java/org/apache/gravitino/server/web/rest/TestCatalogOperations.javaindex 4c0da660df..8f0d7e98d5 100644--- a/server/src/test/java/org/apache/gravitino/server/web/rest/TestCatalogOperations.java+++ b/server/src/test/java/org/apache/gravitino/server/web/rest/TestCatalogOperations.java@@ -232,7 +232,8 @@ public class TestCatalogOperations extends BaseOperationsTest {ImmutableMap.of("key", "value"));TestCatalog catalog = buildCatalog("metalake1", "catalog1");- when(manager.createCatalog(any(), any(), any(), any(), any())).thenReturn(catalog);+ when(manager.createCatalog(any(), any(), any(), any(), any(), any(), any()))+ .thenReturn(catalog);Response resp =target("/metalakes/metalake1/catalogs")@@ -256,7 +257,7 @@ public class TestCatalogOperations extends BaseOperationsTest {// Test throw NoSuchMetalakeExceptiondoThrow(new NoSuchMetalakeException("mock error")).when(manager)- .createCatalog(any(), any(), any(), any(), any());+ .createCatalog(any(), any(), any(), any(), any(), any(), any());Response resp1 =target("/metalakes/metalake1/catalogs").request(MediaType.APPLICATION_JSON_TYPE)@@ -273,7 +274,7 @@ public class TestCatalogOperations extends BaseOperationsTest {// Test throw CatalogAlreadyExistsExceptiondoThrow(new CatalogAlreadyExistsException("mock error")).when(manager)- .createCatalog(any(), any(), any(), any(), any());+ .createCatalog(any(), any(), any(), any(), any(), any(), any());Response resp2 =target("/metalakes/metalake1/catalogs").request(MediaType.APPLICATION_JSON_TYPE)@@ -290,7 +291,7 @@ public class TestCatalogOperations extends BaseOperationsTest {// Test throw internal RuntimeExceptiondoThrow(new RuntimeException("mock error")).when(manager)- .createCatalog(any(), any(), any(), any(), any());+ .createCatalog(any(), any(), any(), any(), any(), any(), any());Response resp3 =target("/metalakes/metalake1/catalogs").request(MediaType.APPLICATION_JSON_TYPE)diff --git a/server/src/test/java/org/apache/gravitino/server/web/rest/TestSchemaOperations.java b/server/src/test/java/org/apache/gravitino/server/web/rest/TestSchemaOperations.javaindex 8981e5e29d..08f2fb2be9 100644--- a/server/src/test/java/org/apache/gravitino/server/web/rest/TestSchemaOperations.java+++ b/server/src/test/java/org/apache/gravitino/server/web/rest/TestSchemaOperations.java@@ -223,7 +223,7 @@ public class TestSchemaOperations extends BaseOperationsTest {new SchemaCreateRequest("schema1", "comment", ImmutableMap.of("key", "value"));Schema mockSchema = mockSchema("schema1", "comment", ImmutableMap.of("key", "value"));- when(dispatcher.createSchema(any(), any(), any())).thenReturn(mockSchema);+ when(dispatcher.createSchema(any(), any(), any(), any(), any())).thenReturn(mockSchema);Response resp =target("/metalakes/" + metalake + "/catalogs/" + catalog + "/schemas")@@ -245,7 +245,7 @@ public class TestSchemaOperations extends BaseOperationsTest {// Test throw NoSuchCatalogExceptiondoThrow(new NoSuchCatalogException("mock error")).when(dispatcher)- .createSchema(any(), any(), any());+ .createSchema(any(), any(), any(), any(), any());Response resp1 =target("/metalakes/" + metalake + "/catalogs/" + catalog + "/schemas").request(MediaType.APPLICATION_JSON_TYPE)@@ -262,7 +262,7 @@ public class TestSchemaOperations extends BaseOperationsTest {// Test throw SchemaAlreadyExistsExceptiondoThrow(new SchemaAlreadyExistsException("mock error")).when(dispatcher)- .createSchema(any(), any(), any());+ .createSchema(any(), any(), any(), any(), any());Response resp2 =target("/metalakes/" + metalake + "/catalogs/" + catalog + "/schemas")@@ -279,7 +279,9 @@ public class TestSchemaOperations extends BaseOperationsTest {SchemaAlreadyExistsException.class.getSimpleName(), errorResp2.getType());// Test throw RuntimeException- doThrow(new RuntimeException("mock error")).when(dispatcher).createSchema(any(), any(), any());+ doThrow(new RuntimeException("mock error"))+ .when(dispatcher)+ .createSchema(any(), any(), any(), any(), any());Response resp3 =target("/metalakes/" + metalake + "/catalogs/" + catalog + "/schemas")