World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#12429] feat(catalog-lakehouse-generic): Pluggable table location provider (#13058)
shaoyu-lie2aacafa15d0
diff --git a/catalogs/catalog-lakehouse-generic/src/main/java/org/apache/gravitino/catalog/lakehouse/generic/DefaultTableLocationProvider.java b/catalogs/catalog-lakehouse-generic/src/main/java/org/apache/gravitino/catalog/lakehouse/generic/DefaultTableLocationProvider.javanew file mode 100644index 0000000000..1e2e8350ac--- /dev/null+++ b/catalogs/catalog-lakehouse-generic/src/main/java/org/apache/gravitino/catalog/lakehouse/generic/DefaultTableLocationProvider.java@@ -0,0 +1,113 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.catalog.lakehouse.generic;++import org.apache.commons.lang3.StringUtils;+import org.apache.gravitino.Catalog;+import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.Schema;+import org.apache.gravitino.rel.Table;++/**+ * The built-in {@link TableLocationProvider}, used when the {@code table-location-provider} catalog+ * property is not set.+ *+ * <p>It derives the table location from the {@code location} property, falling back through three+ * levels:+ *+ * <ol>+ * <li>the table's own {@code location} property, with a trailing slash added;+ * <li>the schema's {@code location} property, with the table name appended;+ * <li>the catalog's {@code location} property, with the schema and table names appended.+ * </ol>+ *+ * If none of them is set, provisioning fails with an {@link IllegalArgumentException}.+ *+ * <p>The first level is what makes a caller-supplied location survive: a creation request carrying+ * its own {@code location} reaches this provider like any other, and returning it unchanged is how+ * this provider honours it. The catalog-level fallback is read from {@link+ * TableLocationContext#catalogProperties()} on each call, since this interface has no+ * initialization callback in which to capture it.+ */+public class DefaultTableLocationProvider implements TableLocationProvider {++ /** The name under which this provider is registered. */+ public static final String NAME = "default";++ private static final String SLASH = "/";++ @Override+ public String name() {+ return NAME;+ }++ @Override+ public String provisionTableLocation(TableLocationContext context) {+ NameIdentifier tableIdent = context.tableIdentifier();+ Schema schema = context.schema();++ String tableLocation = context.tableProperties().get(Table.PROPERTY_LOCATION);+ if (StringUtils.isNotBlank(tableLocation)) {+ return ensureTrailingSlash(tableLocation);+ }++ String schemaLocation =+ schema.properties() == null ? null : schema.properties().get(Schema.PROPERTY_LOCATION);++ // If we do not set location in table properties, and schema location is set, use schema+ // location as the base path.+ if (StringUtils.isNotBlank(schemaLocation)) {+ return ensureTrailingSlash(schemaLocation) + tableIdent.name() + SLASH;+ }++ // If the schema location is not set, use catalog lakehouse dir as the base path. Or else, throw+ // an exception. The catalog property is read per call rather than captured once, because the+ // interface has no initialization callback to capture it in.+ String catalogLocation = context.catalogProperties().get(Catalog.PROPERTY_LOCATION);+ if (StringUtils.isBlank(catalogLocation)) {+ throw new IllegalArgumentException(+ "'location' property is neither set in table properties "+ + "nor in schema properties, and no location is set in catalog properties either. "+ + "Please set the 'location' in either of them to create the table "+ + tableIdent);+ }++ return ensureTrailingSlash(catalogLocation) + schema.name() + SLASH + tableIdent.name() + SLASH;+ }++ /**+ * Does nothing: this provider composes the location from the table, schema and catalog {@code+ * location} properties and registers it nowhere, so there is nothing to hand back. Deleting the+ * data itself stays the responsibility of the table format.+ *+ * @param context the table that was dropped, unused+ */+ @Override+ public void unprovisionTableLocation(TableLocationContext context) {}++ /**+ * Appends a trailing slash to the given path unless it already ends with one.+ *+ * @param path the path to normalize+ * @return the path, ending with a slash+ */+ private static String ensureTrailingSlash(String path) {+ return path.endsWith(SLASH) ? path : path + SLASH;+ }+}diff --git a/catalogs/catalog-lakehouse-generic/src/main/java/org/apache/gravitino/catalog/lakehouse/generic/GenericCatalogOperations.java b/catalogs/catalog-lakehouse-generic/src/main/java/org/apache/gravitino/catalog/lakehouse/generic/GenericCatalogOperations.javaindex 11497e4d68..54999ca482 100644--- a/catalogs/catalog-lakehouse-generic/src/main/java/org/apache/gravitino/catalog/lakehouse/generic/GenericCatalogOperations.java+++ b/catalogs/catalog-lakehouse-generic/src/main/java/org/apache/gravitino/catalog/lakehouse/generic/GenericCatalogOperations.java@@ -34,8 +34,8 @@ import java.util.Map;import java.util.Optional;import java.util.function.Supplier;import java.util.stream.Collectors;+import javax.annotation.Nullable;import org.apache.commons.lang3.StringUtils;-import org.apache.gravitino.Catalog;import org.apache.gravitino.EntityStore;import org.apache.gravitino.GravitinoEnv;import org.apache.gravitino.NameIdentifier;@@ -67,21 +67,21 @@ import org.apache.gravitino.rel.expressions.transforms.Transform;import org.apache.gravitino.rel.indexes.Index;import org.apache.gravitino.storage.IdGenerator;import org.apache.gravitino.utils.ExceptionMessages;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;/** Operations for interacting with a generic lakehouse catalog in Apache Gravitino. */public class GenericCatalogOperations implements CatalogOperations, SupportsSchemas, TableCatalog {- private static final String SLASH = "/";+ private static final Logger LOG = LoggerFactory.getLogger(GenericCatalogOperations.class);private final ManagedSchemaOperations schemaOps;private final Map<String, Supplier<ManagedTableOperations>> tableOpsCache;- private Optional<String> catalogLocation;+ private volatile TableLocationProvider tableLocationProvider;- private Map<String, String> catalogProperties = Map.of();-- private HasPropertyMetadata propertiesMetadata;+ private volatile Map<String, String> catalogProperties = Map.of();private final Cache<NameIdentifier, String> tableFormatCache;@@ -129,17 +129,27 @@ public class GenericCatalogOperations implements CatalogOperations, SupportsSchepublic void initialize(Map<String, String> conf, CatalogInfo info, HasPropertyMetadata propertiesMetadata)throws RuntimeException {- this.catalogProperties = conf == null ? Map.of() : Maps.newHashMap(conf);- String location =- (String)- propertiesMetadata- .catalogPropertiesMetadata()- .getOrDefault(conf, Catalog.PROPERTY_LOCATION);- this.catalogLocation =- StringUtils.isNotBlank(location)- ? Optional.of(location).map(this::ensureTrailingSlash)- : Optional.empty();- this.propertiesMetadata = propertiesMetadata;+ // A defensive copy that tolerates null values, for the same reason as+ // TableLocationContext.Builder#withTableProperties: nothing upstream rejects a catalog+ // property whose value is null, and ImmutableMap.copyOf would turn one into a+ // NullPointerException. Here it would fail the creation of the whole catalog rather than a+ // single request.+ this.catalogProperties =+ conf == null ? Map.of() : Collections.unmodifiableMap(Maps.newHashMap(conf));++ // getOrDefault returns decode(null) rather than the default when the key is present with a+ // null value, and the decoder of a string property is the identity, so an explicitly null+ // `table-location-provider` arrives here as null. Falling back to the built-in provider is+ // the same answer as leaving the property out, which is what a null value means; failing the+ // whole catalog with "must not be blank" would contradict the null tolerance just above.+ String providerName =+ StringUtils.defaultIfBlank(+ (String)+ propertiesMetadata+ .catalogPropertiesMetadata()+ .getOrDefault(conf, GenericCatalogPropertiesMetadata.TABLE_LOCATION_PROVIDER),+ DefaultTableLocationProvider.NAME);+ this.tableLocationProvider = TableLocationProviderFactory.create(providerName);}@Override@@ -175,6 +185,21 @@ public class GenericCatalogOperations implements CatalogOperations, SupportsSchereturn schemaOps.alterSchema(ident, changes);}+ /**+ * Drops a schema, dropping every table it contains first when cascade is set.+ *+ * <p>The cascaded tables go through {@link #dropTable(NameIdentifier)} rather than straight to+ * the table operations, so that the location of each of them is unprovisioned and its cached+ * format invalidated. A table failing to drop aborts the cascade: the tables handled so far are+ * gone, the remaining ones and the schema itself are untouched, and the call can safely be+ * retried. A {@link TableLocationProvider} failing to unprovision a location does not abort it,+ * because the table it belongs to is already gone.+ *+ * @param ident the identifier of the schema to drop+ * @param cascade whether to drop the tables contained in the schema+ * @return true if the schema was dropped, false if it did not exist+ * @throws NonEmptySchemaException if the schema contains tables and cascade is not set+ */@Overridepublic boolean dropSchema(NameIdentifier ident, boolean cascade) throws NonEmptySchemaException {Namespace tableNs =@@ -192,9 +217,16 @@ public class GenericCatalogOperations implements CatalogOperations, SupportsSche"Schema %s is not empty, cannot drop it without cascade", ident);}- // Drop all tables under the schema first if cascade is true.- for (NameIdentifier tableIdent : tableIdents) {- tableOps(tableIdent).dropTable(tableIdent);+ // Drop all tables under the schema first if cascade is true. This goes through the same path+ // as the catalog level dropTable, so that the location of each table is unprovisioned and its+ // cached format invalidated. The schema is resolved once for the whole cascade rather than+ // once per table: every table here has the same parent, and the provider may not ask for it at+ // all.+ if (tableIdents.length > 0) {+ Schema cascadedSchema = loadSchema(ident);+ for (NameIdentifier tableIdent : tableIdents) {+ dropOrPurgeTable(tableIdent, false /* purge */, cascadedSchema);+ }}return schemaOps.dropSchema(ident, cascade);@@ -233,22 +265,34 @@ public class GenericCatalogOperations implements CatalogOperations, SupportsScheIndex[] indexes)throws NoSuchSchemaException, TableAlreadyExistsException {Schema schema = loadSchema(NameIdentifier.of(ident.namespace().levels()));- String tableLocation = calculateTableLocation(schema, ident, properties);String format = properties.getOrDefault(Table.PROPERTY_TABLE_FORMAT, null);Preconditions.checkArgument(format != null, "Table format must be specified in table properties");format = format.toLowerCase(Locale.ROOT);- Map<String, String> newProperties = Maps.newHashMap(properties);- newProperties.put(Table.PROPERTY_LOCATION, tableLocation);- newProperties.put(Table.PROPERTY_TABLE_FORMAT, format);-// Get the table operations for the specified table format.Supplier<ManagedTableOperations> tableOpsSupplier = tableOpsCache.get(format);Preconditions.checkArgument(tableOpsSupplier != null, "Unsupported table format: %s", format);ManagedTableOperations tableOps = configureTableOps(tableOpsSupplier.get());+ // The provider is consulted only once the request is known to be one this catalog can serve.+ // A provider that allocates real storage has no compensating callback, so every check that can+ // be made before asking it for a location is one reservation it does not have to reclaim.+ //+ // It is consulted even when the request carries its own `location`. The catalog used to skip+ // it there, which read as respect for the caller's choice but left the provider unable to see,+ // let alone refuse, a path outside the policy it exists to enforce -- the very bypass this SPI+ // is meant to close. The supplied value is visible as the `location` entry of the context's+ // table properties, and the built-in provider returns it verbatim as its first branch, so a+ // catalog on the built-in provider is unaffected. What an allocating provider does with it is+ // the provider's decision: honour it, rewrite it, or reject the creation.+ String tableLocation = provisionTableLocation(ident, properties, schema);++ Map<String, String> newProperties = Maps.newHashMap(properties);+ newProperties.put(Table.PROPERTY_LOCATION, tableLocation);+ newProperties.put(Table.PROPERTY_TABLE_FORMAT, format);+Table createdTable =tableOps.createTable(ident, columns, comment, newProperties, partitions, distribution, sortOrders, indexes);@@ -273,67 +317,180 @@ public class GenericCatalogOperations implements CatalogOperations, SupportsSche@Overridepublic boolean purgeTable(NameIdentifier ident) {- boolean purged = tableOps(ident).purgeTable(ident);- tableFormatCache.invalidate(ident);- return purged;+ return dropOrPurgeTable(ident, true /* purge */);}@Overridepublic boolean dropTable(NameIdentifier ident) throws UnsupportedOperationException {- boolean dropped = tableOps(ident).dropTable(ident);- tableFormatCache.invalidate(ident);- return dropped;+ return dropOrPurgeTable(ident, false /* purge */);}- private String calculateTableLocation(- Schema schema, NameIdentifier tableIdent, Map<String, String> tableProperties) {- String tableLocation =- (String)- propertiesMetadata- .tablePropertiesMetadata()- .getOrDefault(tableProperties, Table.PROPERTY_LOCATION);- if (StringUtils.isNotBlank(tableLocation)) {- return ensureTrailingSlash(tableLocation);- }+ /**+ * Returns the cache mapping a table to its format, so that tests can assert it is kept in step+ * with the tables that exist.+ *+ * @return the table format cache+ */+ @VisibleForTesting+ Cache<NameIdentifier, String> tableFormatCache() {+ return tableFormatCache;+ }- String schemaLocation =- schema.properties() == null ? null : schema.properties().get(Schema.PROPERTY_LOCATION);+ /**+ * Drops or purges a table, and hands its location back to the {@link TableLocationProvider}+ * afterwards.+ *+ * <p>The table properties are read before the removal, because they carry the location the+ * provider has to hand back, and the unprovisioning itself happens after the removal so that a+ * provider never reclaims the storage of a table that is still there. A provider failing to+ * unprovision is logged at WARN rather than propagated: the table is already gone at that point,+ * so failing the request would report a drop that did in fact happen as unsuccessful and invite a+ * retry that cannot undo anything.+ *+ * @param ident the identifier of the table to drop+ * @param purge whether to purge the table instead of dropping it+ * @return true if the table was dropped, false if it did not exist+ */+ private boolean dropOrPurgeTable(NameIdentifier ident, boolean purge) {+ return dropOrPurgeTable(+ ident, purge, loadSchema(NameIdentifier.of(ident.namespace().levels())));+ }- // If we do not set location in table properties, and schema location is set, use schema- // location as the base path.- if (StringUtils.isNotBlank(schemaLocation)) {- return ensureTrailingSlash(schemaLocation) + tableIdent.name() + SLASH;+ /**+ * Drops or purges a table, resolving its parent schema through the given supplier.+ *+ * <p>The schema is passed in rather than loaded here so that a cascading schema drop, where every+ * table shares one parent, loads it once instead of once per table. It stays eager: the context+ * is built in full before the table is removed, so that a store read failing fails the request+ * while the table is still there, rather than from inside a callback where it could only be+ * reported as a provider failure it is not.+ *+ * @param ident the identifier of the table to drop+ * @param purge whether to purge the table instead of dropping it+ * @param schema the table's parent schema+ * @return true if the table was dropped, false if it did not exist+ */+ private boolean dropOrPurgeTable(NameIdentifier ident, boolean purge, Schema schema) {+ Map<String, String> tableProperties;+ try {+ tableProperties = store.get(ident, TABLE, TableEntity.class).properties();+ } catch (NoSuchEntityException e) {+ return false;+ } catch (IOException e) {+ throw new RuntimeException(+ String.format("Failed to load table %s before dropping it", ident), e);}- // If the schema location is not set, use catalog lakehouse dir as the base path. Or else, throw- // an exception.- if (catalogLocation.isEmpty()) {- throw new IllegalArgumentException(- "'location' property is neither set in table properties "- + "nor in schema properties, and no location is set in catalog properties either. "- + "Please set the 'location' in either of them to create the table "- + tableIdent);+ // Built entirely before the drop, so that a store read failing here fails the request while+ // the table is still there, rather than after it is gone where it could only be reported as a+ // provider failure it is not.+ TableLocationContext context =+ TableLocationContext.builder()+ .withTableIdentifier(ident)+ .withTableProperties(tableProperties)+ .withSchema(schema)+ .withCatalogProperties(catalogProperties)+ .build();++ // The properties just read are handed on rather than left to be read again: resolving the+ // table format is a second store read for the very same entity whenever the format cache is+ // cold, which for a drop it usually is.+ ManagedTableOperations tableOps = tableOps(ident, tableProperties);+ boolean dropped;+ try {+ dropped = purge ? tableOps.purgeTable(ident) : tableOps.dropTable(ident);+ } catch (RuntimeException e) {+ // A format that fails partway through a removal may already have deleted the metadata --+ // LanceTableOperations removes the entity first and deletes the dataset second, and wraps a+ // failure of the second step. The table can be gone with its location still allocated, and+ // the caller sees only the format's exception, so the location is named here or nowhere. It+ // is not unprovisioned: the format may equally have failed before touching storage, and+ // handing back a location that still has data under it is the unrecoverable direction, the+ // same reasoning as limitation (2) on a failed creation.+ LOG.warn(+ "Table format failed to {} table {}. If the metadata was already removed, its location "+ + "'{}' is not handed back to table location provider '{}' and may be leaked.",+ purge ? "purge" : "drop",+ ident,+ context.tableProperties().get(Table.PROPERTY_LOCATION),+ tableLocationProvider.name(),+ e);+ throw e;+ } finally {+ // In a finally because a format that threw may still have removed the metadata, and a cache+ // entry for a table that no longer exists is a stale format for whatever is created next+ // under the same name.+ tableFormatCache.invalidate(ident);}- return ensureTrailingSlash(catalogLocation.get())- + tableIdent.namespace().level(2)- + SLASH- + tableIdent.name()- + SLASH;- }+ // The rule is "hand the location back once the data under it is gone", and `external` only+ // approximates it on a drop: the table formats leave an external dataset in place there, so+ // asking for the location back would invite the provider to delete exactly what the catalog+ // just promised not to touch. A purge is the opposite request --+ // LanceTableOperations#purgeTable+ // deletes the external dataset its dropTable leaves alone -- so the location is handed back+ // there whichever way `external` reads.+ //+ // The decision is made here rather than handed to the provider. By the time this runs the data+ // is gone in all three cases that reach it, so there is nothing left for a provider to decide+ // differently; and the case that is skipped is the one where a provider reclaiming by path+ // would delete a user's data irrecoverably.+ // Read the same way the table formats and the property metadata read it: a catalog that+ // disagreed with the format about a value like `external=yes` would skip reclaiming a location+ // the format had just deleted the data under.+ boolean external = Boolean.parseBoolean(context.tableProperties().get(Table.PROPERTY_EXTERNAL));+ if (dropped && (purge || !external)) {+ TableLocationProvider provider = tableLocationProvider;+ try {+ provider.unprovisionTableLocation(context);+ } catch (Exception e) {+ LOG.warn(+ "Table {} was already {}, but table location provider '{}' failed to unprovision its "+ + "location '{}'. The storage may be leaked and needs to be reclaimed manually.",+ ident,+ purge ? "purged" : "dropped",+ provider.name(),+ context.tableProperties().get(Table.PROPERTY_LOCATION),+ e);+ }+ } else if (dropped) {+ LOG.debug(+ "Table {} is external and was dropped rather than purged, so its location '{}' is left "+ + "alone rather than handed back to table location provider '{}': the data is still "+ + "there and the catalog does not own it.",+ ident,+ context.tableProperties().get(Table.PROPERTY_LOCATION),+ tableLocationProvider.name());+ }- private String ensureTrailingSlash(String path) {- return path.endsWith(SLASH) ? path : path + SLASH;+ return dropped;}private ManagedTableOperations tableOps(NameIdentifier tableIdent) {+ return tableOps(tableIdent, null);+ }++ /**+ * Returns the table operations for the format of the given table.+ *+ * @param tableIdent the identifier of the table+ * @param knownProperties the table's properties if the caller has already read them, null to have+ * them read from the store when the format cache misses. Passing them in only saves a store+ * read; it does not let a caller override the format of a table that is already cached.+ * @return the table operations for the table's format+ */+ private ManagedTableOperations tableOps(+ NameIdentifier tableIdent, @Nullable Map<String, String> knownProperties) {try {String tableFormat =tableFormatCache.get(tableIdent,() -> {- TableEntity table = store.get(tableIdent, TABLE, TableEntity.class);- String format = table.properties().getOrDefault(Table.PROPERTY_TABLE_FORMAT, null);+ Map<String, String> properties =+ knownProperties != null+ ? knownProperties+ : store.get(tableIdent, TABLE, TableEntity.class).properties();+ String format = properties.getOrDefault(Table.PROPERTY_TABLE_FORMAT, null);Preconditions.checkArgument(format != null, "Table format for %s is null, this is unexpected", tableIdent);@@ -367,4 +524,49 @@ public class GenericCatalogOperations implements CatalogOperations, SupportsSchereturn ops;}++ /**+ * Asks the {@link TableLocationProvider} where the table being created should live.+ *+ * <p>Called for every creation, including one whose request carries a location of its own, which+ * reaches the provider as the {@code location} entry of the context's table properties. Deciding+ * it here instead would leave a provider that exists to enforce a placement policy with nothing+ * to enforce, since a caller-supplied path is exactly the case such a policy is for.+ *+ * <p>What a provider does with it is its own decision, and one it has to make deliberately: in+ * this catalog a caller usually supplies a location because the data is already there -- an+ * external Delta table, or a Lance registration, both pointing at a dataset that exists.+ * Allocating a fresh path for one of those and returning it repoints the table at an empty+ * directory and orphans the caller's data while the creation still reports success. The built-in+ * provider returns the supplied value verbatim as its first branch, so a catalog on it is+ * unaffected.+ *+ * @param ident the identifier of the table being created+ * @param properties the table properties the caller supplied+ * @param schema the schema the table is created in+ * @return the provisioned location, never blank+ */+ private String provisionTableLocation(+ NameIdentifier ident, Map<String, String> properties, Schema schema) {+ TableLocationProvider provider = tableLocationProvider;+ String location =+ provider.provisionTableLocation(+ TableLocationContext.builder()+ .withTableIdentifier(ident)+ .withTableProperties(properties)+ .withSchema(schema)+ .withCatalogProperties(catalogProperties)+ .build());++ // Only blankness is checked. The shape of the path belongs to the provider: nothing downstream+ // appends to the location, and the value is stored verbatim so that a provider unprovisioning+ // it later sees exactly the string it returned.+ Preconditions.checkArgument(+ StringUtils.isNotBlank(location),+ "Table location provider '%s' returned a null or blank location for table %s",+ provider.name(),+ ident);++ return location;+ }}diff --git a/catalogs/catalog-lakehouse-generic/src/main/java/org/apache/gravitino/catalog/lakehouse/generic/GenericCatalogPropertiesMetadata.java b/catalogs/catalog-lakehouse-generic/src/main/java/org/apache/gravitino/catalog/lakehouse/generic/GenericCatalogPropertiesMetadata.javaindex 7bd6f58605..7c84d3a54d 100644--- a/catalogs/catalog-lakehouse-generic/src/main/java/org/apache/gravitino/catalog/lakehouse/generic/GenericCatalogPropertiesMetadata.java+++ b/catalogs/catalog-lakehouse-generic/src/main/java/org/apache/gravitino/catalog/lakehouse/generic/GenericCatalogPropertiesMetadata.java@@ -36,6 +36,13 @@ import org.apache.gravitino.connector.PropertyEntry;public class GenericCatalogPropertiesMetadata extends BaseCatalogPropertiesMetadata {+ /**+ * The name of the {@link TableLocationProvider} that provisions and unprovisions the locations of+ * this catalog's tables. Defaults to {@link DefaultTableLocationProvider#NAME} and is immutable+ * once the catalog is created.+ */+ public static final String TABLE_LOCATION_PROVIDER = "table-location-provider";+private static final Map<String, PropertyEntry<?>> PROPERTIES_METADATA;static {@@ -54,6 +61,15 @@ public class GenericCatalogPropertiesMetadata extends BaseCatalogPropertiesMetadnull, /* defaultValue */false /* hidden */,false /* reserved */),+ stringOptionalPropertyEntry(+ TABLE_LOCATION_PROVIDER,+ "The name of the table location provider that provisions and unprovisions the"+ + " locations of this catalog's tables. It is fixed when the catalog is"+ + " created, because switching it would leave the tables of a single catalog"+ + " spread over two different location schemes.",+ true /* immutable */,+ DefaultTableLocationProvider.NAME, /* defaultValue */+ false /* hidden */),enumPropertyEntry(LANCE_SCHEMA_REFRESH_MODE,"Controls when Lance table schemas are refreshed from the underlying dataset.",diff --git a/catalogs/catalog-lakehouse-generic/src/main/java/org/apache/gravitino/catalog/lakehouse/generic/TableLocationContext.java b/catalogs/catalog-lakehouse-generic/src/main/java/org/apache/gravitino/catalog/lakehouse/generic/TableLocationContext.javanew file mode 100644index 0000000000..7b98288cd5--- /dev/null+++ b/catalogs/catalog-lakehouse-generic/src/main/java/org/apache/gravitino/catalog/lakehouse/generic/TableLocationContext.java@@ -0,0 +1,211 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.catalog.lakehouse.generic;++import com.google.common.base.Preconditions;+import com.google.common.collect.ImmutableMap;+import com.google.common.collect.Maps;+import java.util.Collections;+import java.util.Map;+import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.Schema;+import org.apache.gravitino.rel.Table;++/**+ * The context passed to a {@link TableLocationProvider} on both of its callbacks: when a table is+ * being created and its location has to be provisioned, and when a table has been dropped and its+ * location has to be unprovisioned.+ *+ * <p>The same type is used for both so that a new input becomes an additional accessor rather than+ * a signature change: providers written against an older version keep compiling and running. For+ * that reason implementations should not rely on the constructor signature and should build+ * instances through {@link #builder()}.+ */+public class TableLocationContext {++ private final NameIdentifier tableIdentifier;++ private final Map<String, String> tableProperties;++ private final Schema schema;++ private final Map<String, String> catalogProperties;++ private TableLocationContext(+ NameIdentifier tableIdentifier,+ Map<String, String> tableProperties,+ Schema schema,+ Map<String, String> catalogProperties) {+ this.tableIdentifier = tableIdentifier;+ this.tableProperties = tableProperties;+ this.schema = schema;+ this.catalogProperties = catalogProperties;+ }++ /**+ * Returns the identifier of the table this context is about, in the form of {@code+ * metalake.catalog.schema.table}.+ *+ * @return the table identifier, never null+ */+ public NameIdentifier tableIdentifier() {+ return tableIdentifier;+ }++ /**+ * Returns the properties of the table this context is about. Which properties those are, and in+ * particular whether the {@code location} entry ({@link Table#PROPERTY_LOCATION}) is filled in,+ * depends on the callback being served:+ *+ * <ul>+ * <li>{@link TableLocationProvider#provisionTableLocation(TableLocationContext)} gets the+ * properties of the creation request, so the location entry holds whatever the caller+ * supplied, which may be nothing at all.+ * <li>{@link TableLocationProvider#unprovisionTableLocation(TableLocationContext)} gets the+ * stored properties of the table being dropped, read right before it was removed, so the+ * location entry holds the location that was provisioned for it.+ * </ul>+ *+ * <p>Values are carried through as they were given, null ones included: the catalog accepts a+ * property whose value is null, and this context is not the layer that starts to reject it. Read+ * a property with {@code get} rather than assuming that a key which is present has a value.+ *+ * @return the table properties, never null but possibly empty+ */+ public Map<String, String> tableProperties() {+ return tableProperties;+ }++ /**+ * Returns the schema the table belongs to, including its properties.+ *+ * @return the parent schema, never null+ */+ public Schema schema() {+ return schema;+ }++ /**+ * Returns the properties of the catalog this provider belongs to, as they were given when the+ * catalog was created.+ *+ * <p>This is the only channel through which a provider receives configuration of its own -- a+ * service endpoint, a quota group, a credential reference -- because the interface has no+ * initialization callback. The same map is handed to every call, so reading it per call costs+ * nothing beyond the lookup, but a provider that turns it into something expensive should build+ * that once and hold it rather than rebuilding it per table.+ *+ * <p>Values are carried through as they were given, null ones included, for the same reason as in+ * {@link #tableProperties()}.+ *+ * @return the catalog properties, never null but possibly empty+ */+ public Map<String, String> catalogProperties() {+ return catalogProperties;+ }++ /**+ * Creates a builder for {@link TableLocationContext}.+ *+ * @return a new builder+ */+ public static Builder builder() {+ return new Builder();+ }++ /** A builder for {@link TableLocationContext}. */+ public static class Builder {++ private NameIdentifier tableIdentifier;++ private Map<String, String> tableProperties = ImmutableMap.of();++ private Schema schema;++ private Map<String, String> catalogProperties = ImmutableMap.of();++ private Builder() {}++ /**+ * Sets the identifier of the table this context is about.+ *+ * @param tableIdentifier the table identifier+ * @return this builder+ */+ public Builder withTableIdentifier(NameIdentifier tableIdentifier) {+ this.tableIdentifier = tableIdentifier;+ return this;+ }++ /**+ * Sets the properties of the table this context is about. A null map is treated as an empty+ * one; a null value under a key is kept as it is.+ *+ * @param tableProperties the table properties+ * @return this builder+ */+ public Builder withTableProperties(Map<String, String> tableProperties) {+ // A defensive copy that tolerates null values, which ImmutableMap.copyOf would reject. The+ // catalog itself accepts a property whose value is null, and building this context must not+ // be what turns such a request into a failure.+ this.tableProperties =+ tableProperties == null+ ? ImmutableMap.of()+ : Collections.unmodifiableMap(Maps.newHashMap(tableProperties));+ return this;+ }++ /**+ * Sets the schema the table belongs to.+ *+ * @param schema the parent schema+ * @return this builder+ */+ public Builder withSchema(Schema schema) {+ this.schema = schema;+ return this;+ }++ /**+ * Sets the properties of the catalog the table belongs to. A null map is treated as an empty+ * one; a null value under a key is kept as it is.+ *+ * @param catalogProperties the catalog properties+ * @return this builder+ */+ public Builder withCatalogProperties(Map<String, String> catalogProperties) {+ this.catalogProperties =+ catalogProperties == null+ ? ImmutableMap.of()+ : Collections.unmodifiableMap(Maps.newHashMap(catalogProperties));+ return this;+ }++ /**+ * Builds the {@link TableLocationContext}.+ *+ * @return the built context+ */+ public TableLocationContext build() {+ Preconditions.checkArgument(tableIdentifier != null, "tableIdentifier must not be null");+ Preconditions.checkArgument(schema != null, "schema must not be null");+ return new TableLocationContext(tableIdentifier, tableProperties, schema, catalogProperties);+ }+ }+}diff --git a/catalogs/catalog-lakehouse-generic/src/main/java/org/apache/gravitino/catalog/lakehouse/generic/TableLocationProvider.java b/catalogs/catalog-lakehouse-generic/src/main/java/org/apache/gravitino/catalog/lakehouse/generic/TableLocationProvider.javanew file mode 100644index 0000000000..b5ce3ac5dd--- /dev/null+++ b/catalogs/catalog-lakehouse-generic/src/main/java/org/apache/gravitino/catalog/lakehouse/generic/TableLocationProvider.java@@ -0,0 +1,259 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.catalog.lakehouse.generic;++/**+ * A pluggable strategy for deciding where the data of a newly created table lives.+ *+ * <p>Implementations are discovered through Java's {@link java.util.ServiceLoader} and selected by+ * {@link #name()} using the {@code table-location-provider} catalog property. The built-in {@link+ * DefaultTableLocationProvider} derives the location from the table, schema and catalog {@code+ * location} properties; deployments that allocate storage through an external service can register+ * their own implementation instead.+ *+ * <p><b>The catalog reports; the provider decides.</b> The catalog's part is to hand over an+ * accurate account of what happened -- what the creation request asked for, where the table ended+ * up, whether the data under a location is gone -- and the provider's part is to decide what that+ * account means for the storage it manages. The catalog does not model what an implementation+ * keeps, and an implementation is never asked to reconstruct what the catalog or the table formats+ * did.+ *+ * <p>There is one exception, and it is written here as an exception rather than dressed up as the+ * rule: an external table that is <b>dropped</b> does not reach {@link+ * #unprovisionTableLocation(TableLocationContext)} at all. That is the one path where a provider+ * acting on an accurate report could still destroy data irrecoverably, because the table formats+ * leave an external dataset in place on a drop. A leaked location can be reconciled and deleted+ * data cannot, so the catalog withholds the call rather than making it.+ *+ * <p><b>Responsibilities.</b> A provider owns the right to use a path; the table format owns the+ * content at the path. The dividing line is not physical against logical -- a provider may well+ * create real infrastructure -- but what a thing was created for: anything brought into being so+ * that the path can be used belongs to the provider, and anything written into the path belongs to+ * the format. Concretely a provider owns its reservation, its registry entry, whatever quota or+ * grant it books, the name itself, and any container it created to make the path usable; a table+ * format owns the dataset, including deleting it; and the catalog owns neither, storing the+ * location string verbatim and sequencing the two calls below.+ *+ * <p><b>Scope.</b> What this interface offers is allocation hooks plus best-effort release+ * notification, with recovery owned by the provider and the deployment. It is deliberately not a+ * distributed transaction and not a recovery system. The limitations below are real, and an+ * implementation that manages storage has to reconcile against the catalog independently of these+ * two calls.+ *+ * <p><b>There is no lifecycle.</b> An instance is created per catalog and is never initialized or+ * closed by the catalog, so an implementation needing configuration of its own -- a service+ * endpoint, a credential -- has to obtain it without help from here, and anything it acquires is+ * held for the lifetime of the instance with no callback to release it. An implementation holding a+ * remote client should therefore acquire it lazily and make it safe to abandon, because catalogs+ * are evicted from the server's catalog cache when idle and a discarded provider is not told.+ *+ * <p>Implementations must be thread-safe: {@link #provisionTableLocation(TableLocationContext)} and+ * {@link #unprovisionTableLocation(TableLocationContext)} are both called concurrently by table+ * requests. A failure on the provisioning path fails the table creation; one on the drop path is+ * logged at WARN and nothing else happens.+ *+ * <p>Implementations must satisfy two constraints imposed by the {@link java.util.ServiceLoader}+ * based discovery:+ *+ * <ul>+ * <li>They must have a public no-argument constructor that is cheap, does not throw and acquires+ * nothing. Every provider registered on the classpath is instantiated before the one matching+ * the catalog property is selected, so a heavy constructor slows the initialization of every+ * catalog, including those using the built-in provider. One that throws is logged and skipped+ * rather than failing the lookup, which costs that provider the ability to be selected at+ * all. The instances that were not selected are then discarded, and nothing is closed on+ * them, so anything a constructor acquires is leaked once per catalog creation.+ * <li>{@link #name()} must be unique across the classpath, and must not be {@value+ * DefaultTableLocationProvider#NAME}, which is reserved by {@link+ * DefaultTableLocationProvider}. If two providers share a name, every catalog selecting that+ * name fails to initialize. A provider whose constructor or {@link #name()} throws is logged+ * and skipped rather than failing the lookup, so a provider that is broken at runtime does+ * not stop catalogs that named a different one from starting. A services file naming a class+ * that cannot be loaded at all still fails the lookup.+ * </ul>+ *+ * <p><b>Known limitations.</b> Six of them, and they all point the same way: a provider that+ * manages real storage needs its own reconciliation against the catalog and cannot treat the+ * callbacks here as a complete record of what it handed out.+ *+ * <ul>+ * <li>{@code location} is a mutable table property, so {@code alterTable(setProperty("location",+ * ...))} repoints a table without this provider being told. The old location is never+ * unprovisioned and the new one never went through this provider.+ * <li>{@link #provisionTableLocation(TableLocationContext)} is called before the table is+ * actually created, so a creation that fails afterwards -- a table that already exists, or a+ * failure inside the table format itself -- leaves a location provisioned for a table that+ * does not exist. There is no compensating unprovision, deliberately: a table format that+ * fails partway through creation may already have written to the location, and calling {@link+ * #unprovisionTableLocation(TableLocationContext)} would then tell the provider it is free to+ * reclaim a path that has data on it. Leaking an unused path is the safer of the two+ * failures, and doing better would need the format to report whether it touched storage+ * before failing, which this interface cannot express. Every check this catalog can make on+ * its own is made before the provider is consulted, so the cases that remain are the ones+ * only the table format can detect.+ * <li>A location that is provisioned but then not used is not handed back either. A creation mode+ * such as Lance's {@code EXIST_OK} returns the table that already exists, at the location it+ * already has, and the location provisioned for that call goes nowhere. Detecting that from+ * here would mean comparing two location strings and concluding from the comparison what an+ * implementation did internally, which is exactly the inference this interface leaves to the+ * provider; and a retried creation is the ordinary way to reach it, so an implementation that+ * allocates has to reconcile these along with the failures above.+ * <li>A table format that drops a table through its own internals, rather than through the+ * catalog, does not trigger {@link #unprovisionTableLocation(TableLocationContext)}. Lance's+ * {@code OVERWRITE} creation mode does this: it drops the existing table and creates a new+ * one, so the old location is never handed back. A format-internal drop is not visible to the+ * catalog, so this cannot be closed from here.+ * <li>A provider deriving a deterministic path from a table's identity hands out the same path+ * again when a table of the same name is created after the old one is gone, and the built-in+ * provider is one such provider. If anything survived under that path -- a drop whose data+ * deletion failed, or a format-internal drop as above -- the next creation of that name fails+ * inside the table format rather than here, and keeps failing, because every retry derives+ * the same path. Clearing what was left behind is outside what this interface can see or do.+ * <li>{@code alterTable(rename(...))} changes a table's identity without telling this provider,+ * and without moving any data. A provider deriving the path from the table name is left with+ * a path that no longer matches the name, which is cosmetic. A provider that books+ * allocations against {@code (schema, table)} loses the table altogether: the drop that+ * follows arrives under the new name, and the allocation booked under the old one is never+ * handed back. Such a provider has to reconcile renames out of band, or the deployment has to+ * forbid renaming tables in this catalog.+ * </ul>+ */+public interface TableLocationProvider {++ /**+ * Returns the name this provider is selected by, matched against the {@code+ * table-location-provider} catalog property.+ *+ * <p>It must be unique across the classpath and must not be {@value+ * DefaultTableLocationProvider#NAME}. It is read once per lookup, on every registered provider,+ * so it must be cheap and must not throw.+ *+ * @return the name of this provider, never null or blank+ */+ String name();++ /**+ * Provisions the location for the table that is being created.+ *+ * <p>The returned location is stored verbatim in the table's {@code location} property. It must+ * be non-blank; the caller rejects the table creation with an {@link IllegalArgumentException}+ * otherwise. Nothing else is required of it: the shape of the path belongs to the provider,+ * nothing downstream appends to the location, and storing it unchanged is what lets a provider+ * unprovisioning it later match the string it handed out.+ *+ * <p><b>What the returned location promises.</b> Exactly one thing: that the location is usable,+ * meaning a table format may create its dataset there and will not be refused for any reason+ * under the provider's control. Whether an implementation had to reserve, register or create+ * anything to make that true is its own business, neither required nor forbidden here. It does+ * <em>not</em> promise that a directory or prefix exists, that a dataset exists, or that the+ * location is empty -- the last one deliberately, because in this catalog a caller usually+ * supplies a location precisely when the data is already there.+ *+ * <p><b>A request that carries its own {@code location} reaches this method too</b>, with the+ * supplied value visible as the {@code location} entry of {@link+ * TableLocationContext#tableProperties()}. The decision is the provider's: return it unchanged to+ * honour it, return something else to place the table elsewhere, or throw to refuse the creation.+ * A provider enforcing a placement policy would have nothing to enforce if the catalog decided+ * this on its behalf, and a caller-supplied path is exactly the case such a policy exists for.+ *+ * <p>An implementation that allocates storage has to handle that case deliberately, because in+ * this catalog a caller usually supplies a location because the data is already there -- an+ * external Delta table, or a Lance registration. Allocating a fresh empty path for one of those+ * and returning it repoints the table at an empty directory and orphans the caller's data, while+ * the creation still reports success. Returning the supplied value unchanged is the safe default+ * and what the built-in provider does as its first branch, which is why a catalog on the built-in+ * provider sees no change.+ *+ * <p>Everything else reaches this method as well, including an external table that carries no+ * location. Whether a table is external can be read from the {@code external} entry of {@link+ * TableLocationContext#tableProperties()}.+ *+ * @param context the table being created and the context needed to derive its location+ * @return the provisioned table location, never null or blank+ * @throws IllegalArgumentException if no location can be derived from the given context+ */+ String provisionTableLocation(TableLocationContext context);++ /**+ * Unprovisions the location of a table that is gone, so that a provider allocating through an+ * external service can hand back what it issued instead of leaking it. The location in question+ * is the {@code location} entry of {@link TableLocationContext#tableProperties()}.+ *+ * <p>There is deliberately no default implementation. A provider allocating from an external+ * system has to state what happens when the table goes away, and a provider deriving the path+ * from configuration writes an empty body and says so; an inherited empty body would let the+ * second answer be given by accident.+ *+ * <p><b>What it releases.</b> What the implementation issued: the reservation, the registry+ * entry, whatever quota or grant it booked, and the name itself so that it can be handed out+ * again. An implementation may also remove a container it created itself -- a prefix or a bucket+ * it brought into being so the path could be used -- but only after establishing that the+ * container holds nothing except what the implementation itself put there, and it must leave the+ * container in place otherwise.+ *+ * <p><b>What it must not touch.</b> The content at the location. The table format owns the+ * lifecycle of the data and has already deleted it on every path that reaches this method;+ * deleting anything further is at best redundant and at worst destroys data this catalog has+ * promised not to touch. Nor does the location string establish ownership on its own: the catalog+ * supplies one fact, that nothing anyone needs is under that location any more, and whether the+ * implementation holds anything there is a fact only the implementation can establish, from its+ * own records.+ *+ * <p>It is called <em>after</em> the table metadata, and the underlying data of a managed table,+ * have been removed, so throwing does not roll the drop back: the table is gone either way. The+ * failure is logged at WARN and the drop still reports success. Dropping a schema with cascade+ * unprovisions the location of every table it contains, one by one.+ *+ * <p>It is <em>not</em> called when an external table is <b>dropped</b>, which is the exception+ * named in this interface's description. The catalog does not own their data -- the table formats+ * leave the dataset in place on drop -- so asking a provider to hand the location back would+ * invite it to delete exactly the data the catalog just promised not to touch. A leak is+ * recoverable and a deletion is not, so the callback is skipped.+ *+ * <p>It <em>is</em> called when an external table is <b>purged</b>. Purge and drop do not remove+ * the same things: {@code LanceTableOperations#purgeTable} deletes the external dataset that its+ * {@code dropTable} leaves alone, so by the time this runs the data is gone and the reason to+ * skip has gone with it.+ *+ * <p>Which means this callback is reached in exactly three situations: a dropped managed table, a+ * purged managed table, and a purged external one. There is deliberately no flag distinguishing+ * them, because the invariant they share is the one that matters, and it is about the location+ * rather than the table: <b>nothing anyone needs is under the location named in the context</b>.+ * In all three the table format has already deleted the data under it.+ *+ * <p>Even so, {@code external} is only an approximation of the rule this callback actually wants,+ * which is "hand back only what was handed out". An external table created without a location+ * <em>does</em> get one provisioned -- both table formats check the location after the catalog+ * has filled it in -- and skipping its drop leaks that one. Distinguishing exactly would need the+ * catalog to record, per table, whether it provisioned the location, which it does not do today.+ * That is why an implementation reclaiming real storage needs its own reconciliation, and why+ * this method must tolerate a location it does not recognize.+ *+ * <p>It is called once per dropped table, but it is not guaranteed to be called at all. A crash+ * between the removal and this call skips it, and so does a failure raised inside the drop after+ * the metadata is already gone, which takes no crash and leaves the server running normally. An+ * implementation reclaiming real storage needs its own reconciliation to catch both. It must also+ * tolerate being called for a location that is already released. Like {@link+ * #provisionTableLocation(TableLocationContext)}, it is called concurrently and must be+ * thread-safe.+ *+ * @param context the table that is gone and the context needed to release its location+ */+ void unprovisionTableLocation(TableLocationContext context);+}diff --git a/catalogs/catalog-lakehouse-generic/src/main/java/org/apache/gravitino/catalog/lakehouse/generic/TableLocationProviderFactory.java b/catalogs/catalog-lakehouse-generic/src/main/java/org/apache/gravitino/catalog/lakehouse/generic/TableLocationProviderFactory.javanew file mode 100644index 0000000000..6a96378c70--- /dev/null+++ b/catalogs/catalog-lakehouse-generic/src/main/java/org/apache/gravitino/catalog/lakehouse/generic/TableLocationProviderFactory.java@@ -0,0 +1,201 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.catalog.lakehouse.generic;++import com.google.common.base.Preconditions;+import java.util.HashMap;+import java.util.HashSet;+import java.util.List;+import java.util.Locale;+import java.util.Map;+import java.util.Optional;+import java.util.ServiceConfigurationError;+import java.util.ServiceLoader;+import java.util.Set;+import java.util.stream.Collectors;+import org.apache.commons.lang3.StringUtils;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++/**+ * A factory that discovers {@link TableLocationProvider}s through {@link ServiceLoader}.+ *+ * <p>Selecting by name costs one instantiation of every registered provider, because {@link+ * TableLocationProvider#name()} is an instance method and there is no way to learn the names+ * without one. That is why the interface requires a constructor that acquires nothing: the+ * candidates that are not selected are discarded on the spot, and the interface has no close+ * callback with which to release anything they took. The scan is repeated per catalog rather than+ * remembered, matching {@code LakehouseTableDelegatorFactory} in this module, and catalog creation+ * is rare enough that the trivial constructions it costs do not justify a cache keyed by class+ * loader.+ */+public class TableLocationProviderFactory {++ private static final Logger LOG = LoggerFactory.getLogger(TableLocationProviderFactory.class);++ private TableLocationProviderFactory() {}++ /**+ * Creates the {@link TableLocationProvider} registered under the given name.+ *+ * <p>A new instance is returned on every call. Nothing is initialized and nothing is closed, here+ * or later: the interface has no lifecycle callbacks, so the instances made while scanning for+ * the name are simply discarded, which is safe only because the interface requires a constructor+ * that acquires nothing.+ *+ * @param name the provider name to look up, matched case-insensitively against {@link+ * TableLocationProvider#name()}+ * @return the provider+ * @throws IllegalArgumentException if no provider, or more than one provider, is registered under+ * the given name, or if the selected provider cannot be instantiated+ * @throws ServiceConfigurationError if a {@code META-INF/services} file for this interface is+ * itself malformed, which fails the scan before any candidate is reached+ */+ public static TableLocationProvider create(String name) {+ Preconditions.checkArgument(+ StringUtils.isNotBlank(name), "Table location provider name must not be blank");++ ClassLoader cl =+ Optional.ofNullable(Thread.currentThread().getContextClassLoader())+ .orElse(TableLocationProvider.class.getClassLoader());+ String key = name.toLowerCase(Locale.ROOT);++ Index index = scan(cl);+ Class<? extends TableLocationProvider> type = index.get(key);++ Preconditions.checkArgument(+ !index.isDuplicated(key),+ "Multiple TableLocationProviders are registered under the name '%s'. Provider names must "+ + "be unique across the classpath.",+ name);+ Preconditions.checkArgument(type != null, "No TableLocationProvider found for name '%s'", name);++ TableLocationProvider provider = instantiate(type);++ LOG.info("Loaded TableLocationProvider '{}': {}", name, type.getName());+ return provider;+ }++ /**+ * Instantiates every registered provider once to learn its name, and returns the resulting+ * name-to-class mapping.+ *+ * <p>A candidate whose constructor or {@link TableLocationProvider#name()} throws is logged and+ * skipped rather than allowed to fail the scan, so a provider that is merely broken at runtime+ * does not stop catalogs that named a different one from starting.+ *+ * <p>That does not cover every broken jar. A services file naming a class that cannot be loaded+ * at all fails the whole scan with a {@link ServiceConfigurationError}, raised while the loader+ * is being iterated and before any candidate is reached, which is out of reach of the handling+ * here. Catching it per candidate would mean driving the loader's iterator by hand and risking a+ * loop that never terminates, which is the worse trade for a case an operator can see in the+ * failure it produces.+ *+ * <p>A name claimed by more than one provider is recorded rather than thrown here, and fails only+ * the catalogs that actually ask for that name. Throwing during the scan would let two unrelated+ * third-party jars break every catalog, which is the same failure the paragraph above avoids.+ *+ * @param cl the class loader to scan+ * @return the index for that class loader+ */+ private static Index scan(ClassLoader cl) {+ Map<String, Class<? extends TableLocationProvider>> byName = new HashMap<>();+ Set<String> duplicated = new HashSet<>();++ List<ServiceLoader.Provider<TableLocationProvider>> candidates =+ ServiceLoader.load(TableLocationProvider.class, cl).stream().collect(Collectors.toList());++ for (ServiceLoader.Provider<TableLocationProvider> candidate : candidates) {+ Class<? extends TableLocationProvider> type = candidate.type();+ String name;+ try {+ name = candidate.get().name();+ } catch (RuntimeException | Error e) {+ // Error, not just ServiceConfigurationError: the loader wraps a failing constructor for+ // us, but name() is called here rather than by the loader, so whatever it throws arrives+ // unwrapped. A plugin loaded through its own class loader reaches a missing class with a+ // NoClassDefFoundError, which is an Error, and letting it through would fail the whole+ // scan.+ LOG.warn(+ "Skipping TableLocationProvider {}, which could not be instantiated or could not "+ + "report its name. It cannot be selected by any catalog until this is fixed.",+ type.getName(),+ e);+ continue;+ }++ if (StringUtils.isBlank(name)) {+ LOG.warn(+ "Skipping TableLocationProvider {}, which reported a null or blank name.",+ type.getName());+ continue;+ }++ String key = name.toLowerCase(Locale.ROOT);+ Class<? extends TableLocationProvider> previous = byName.put(key, type);+ if (previous != null && previous != type) {+ duplicated.add(key);+ LOG.warn(+ "TableLocationProvider name '{}' is claimed by more than one implementation, including "+ + "{} and {}. Catalogs selecting that name will fail to initialize.",+ name,+ previous.getName(),+ type.getName());+ }+ }++ LOG.info("Discovered TableLocationProviders: {}", byName.keySet());+ return new Index(byName, duplicated);+ }++ private static TableLocationProvider instantiate(Class<? extends TableLocationProvider> type) {+ try {+ return type.getDeclaredConstructor().newInstance();+ } catch (ReflectiveOperationException | RuntimeException | Error e) {+ throw new IllegalArgumentException(+ String.format(+ "Failed to instantiate TableLocationProvider %s. It must have a public no-argument "+ + "constructor that does not throw.",+ type.getName()),+ e);+ }+ }++ /** The providers discovered under one class loader. */+ private static final class Index {++ private final Map<String, Class<? extends TableLocationProvider>> byName;++ private final Set<String> duplicated;++ private Index(+ Map<String, Class<? extends TableLocationProvider>> byName, Set<String> duplicated) {+ this.byName = byName;+ this.duplicated = duplicated;+ }++ private Class<? extends TableLocationProvider> get(String key) {+ return byName.get(key);+ }++ private boolean isDuplicated(String key) {+ return duplicated.contains(key);+ }+ }+}diff --git a/catalogs/catalog-lakehouse-generic/src/main/java/org/apache/gravitino/catalog/lakehouse/lance/LanceTableOperations.java b/catalogs/catalog-lakehouse-generic/src/main/java/org/apache/gravitino/catalog/lakehouse/lance/LanceTableOperations.javaindex a4d2a697e2..5d9d65cd96 100644--- a/catalogs/catalog-lakehouse-generic/src/main/java/org/apache/gravitino/catalog/lakehouse/lance/LanceTableOperations.java+++ b/catalogs/catalog-lakehouse-generic/src/main/java/org/apache/gravitino/catalog/lakehouse/lance/LanceTableOperations.java@@ -24,9 +24,11 @@ import static org.apache.gravitino.rel.Column.DEFAULT_VALUE_NOT_SET;import com.google.common.base.Preconditions;import com.google.common.collect.ImmutableMap;+import com.google.common.collect.Maps;import java.io.IOException;import java.time.Instant;import java.util.Arrays;+import java.util.Collections;import java.util.HashMap;import java.util.List;import java.util.Map;@@ -172,8 +174,14 @@ public class LanceTableOperations extends ManagedTableOperations {* @param catalogProperties the catalog properties*/public void setCatalogProperties(Map<String, String> catalogProperties) {+ // A copy that tolerates a null value, not ImmutableMap.copyOf, which throws on one. Nothing+ // upstream rejects a catalog property whose value is null, and the generic catalog hands this+ // map on unchanged, so copying it strictly here would fail every table operation on such a+ // catalog rather than the one property that is null.this.catalogProperties =- catalogProperties == null ? Map.of() : ImmutableMap.copyOf(catalogProperties);+ catalogProperties == null+ ? Map.of()+ : Collections.unmodifiableMap(Maps.newHashMap(catalogProperties));}@Overridediff --git a/catalogs/catalog-lakehouse-generic/src/main/resources/META-INF/services/org.apache.gravitino.catalog.lakehouse.generic.TableLocationProvider b/catalogs/catalog-lakehouse-generic/src/main/resources/META-INF/services/org.apache.gravitino.catalog.lakehouse.generic.TableLocationProvidernew file mode 100644index 0000000000..b26bdab836--- /dev/null+++ b/catalogs/catalog-lakehouse-generic/src/main/resources/META-INF/services/org.apache.gravitino.catalog.lakehouse.generic.TableLocationProvider@@ -0,0 +1,19 @@+#+# Licensed to the Apache Software Foundation (ASF) under one+# or more contributor license agreements. See the NOTICE file+# distributed with this work for additional information+# regarding copyright ownership. The ASF licenses this file+# to you under the Apache License, Version 2.0 (the+# "License"); you may not use this file except in compliance+# with the License. You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing,+# software distributed under the License is distributed on an+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+# KIND, either express or implied. See the License for the+# specific language governing permissions and limitations+# under the License.+#+org.apache.gravitino.catalog.lakehouse.generic.DefaultTableLocationProviderdiff --git a/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/generic/BrokenTableLocationProvider.java b/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/generic/BrokenTableLocationProvider.javanew file mode 100644index 0000000000..2e5bab0926--- /dev/null+++ b/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/generic/BrokenTableLocationProvider.java@@ -0,0 +1,47 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.catalog.lakehouse.generic;++/**+ * A provider that stands in for a broken third-party jar on the classpath. It is registered in the+ * test {@code META-INF/services} file alongside the working one, so every factory lookup in this+ * module has to get past it.+ *+ * <p>It fails from {@link #name()} with an {@link Error} rather than an exception, which is the way+ * a plugin loaded through its own classloader fails when a class it needs is missing. The factory+ * calls {@code name()} itself rather than going through the loader, so nothing wraps this into a+ * {@link java.util.ServiceConfigurationError} on the way out.+ */+public class BrokenTableLocationProvider implements TableLocationProvider {++ @Override+ public String name() {+ throw new NoClassDefFoundError("com/example/a/class/this/plugin/was/built/against");+ }++ @Override+ public String provisionTableLocation(TableLocationContext context) {+ throw new UnsupportedOperationException("This provider can never be selected");+ }++ @Override+ public void unprovisionTableLocation(TableLocationContext context) {+ throw new UnsupportedOperationException("This provider can never be selected");+ }+}diff --git a/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/generic/FakeTableDelegator.java b/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/generic/FakeTableDelegator.javanew file mode 100644index 0000000000..80f7aeb7b6--- /dev/null+++ b/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/generic/FakeTableDelegator.java@@ -0,0 +1,153 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.catalog.lakehouse.generic;++import com.google.common.collect.ImmutableList;+import com.google.common.collect.Maps;+import java.util.List;+import java.util.Map;+import org.apache.gravitino.EntityStore;+import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.catalog.ManagedSchemaOperations;+import org.apache.gravitino.catalog.ManagedTableOperations;+import org.apache.gravitino.connector.PropertyEntry;+import org.apache.gravitino.connector.SupportsSchemas;+import org.apache.gravitino.rel.Column;+import org.apache.gravitino.rel.Table;+import org.apache.gravitino.rel.expressions.distributions.Distribution;+import org.apache.gravitino.rel.expressions.sorts.SortOrder;+import org.apache.gravitino.rel.expressions.transforms.Transform;+import org.apache.gravitino.rel.indexes.Index;+import org.apache.gravitino.storage.IdGenerator;++/**+ * A {@link LakehouseTableDelegator} registered only in the test classpath, whose table operations+ * touch nothing but the entity store. It lets the tests drive the catalog level table operations,+ * and the {@link TableLocationProvider} callbacks hanging off them, without a real table format+ * behind them.+ */+public class FakeTableDelegator implements LakehouseTableDelegator {++ /** The table format handled by this delegator. */+ public static final String TABLE_FORMAT = "testing";++ // Set by a test to make createTable behave like a format that declines the location it was+ // given: Lance's EXIST_OK mode returns the table that already exists, at the location that table+ // already had. Static because the catalog builds its own table operations through ServiceLoader.+ private static volatile String locationToUseInstead;++ // Set by a test to reproduce the shape of LanceTableOperations#dropTable: the entity is removed+ // first and the data deleted second, and a failure of the second step arrives after the table+ // has already ceased to exist.+ private static volatile boolean failAfterRemovingMetadata;++ /**+ * Makes every subsequent creation store the given location instead of the one the catalog+ * provisioned, the way a format returning an already existing table does.+ *+ * @param location the location the created table will report, null to create normally+ */+ public static void useLocationInstead(String location) {+ locationToUseInstead = location;+ }++ /**+ * Makes every subsequent drop remove the table metadata and then throw, the way a format that+ * deletes the data as a second, non-atomic step fails.+ *+ * @param fail whether dropping should throw after the metadata is gone+ */+ public static void failAfterRemovingMetadata(boolean fail) {+ failAfterRemovingMetadata = fail;+ }++ /** Stops overriding the location of created tables and failing drops. */+ public static void reset() {+ locationToUseInstead = null;+ failAfterRemovingMetadata = false;+ }++ @Override+ public String tableFormat() {+ return TABLE_FORMAT;+ }++ @Override+ public List<PropertyEntry<?>> tablePropertyEntries() {+ return ImmutableList.of();+ }++ @Override+ public ManagedTableOperations createTableOps(+ EntityStore store, ManagedSchemaOperations schemaOps, IdGenerator idGenerator) {+ return new ManagedTableOperations() {+ @Override+ protected EntityStore store() {+ return store;+ }++ @Override+ protected SupportsSchemas schemas() {+ return schemaOps;+ }++ @Override+ protected IdGenerator idGenerator() {+ return idGenerator;+ }++ @Override+ public boolean dropTable(NameIdentifier ident) {+ boolean dropped = super.dropTable(ident);+ if (failAfterRemovingMetadata) {+ throw new RuntimeException("Failed to delete the data of table " + ident);+ }+ return dropped;+ }++ @Override+ public Table createTable(+ NameIdentifier ident,+ Column[] columns,+ String comment,+ Map<String, String> properties,+ Transform[] partitions,+ Distribution distribution,+ SortOrder[] sortOrders,+ Index[] indexes) {+ String override = locationToUseInstead;+ Map<String, String> storedProperties = properties;+ if (override != null) {+ storedProperties = Maps.newHashMap(properties);+ storedProperties.put(Table.PROPERTY_LOCATION, override);+ }++ return super.createTable(+ ident,+ columns,+ comment,+ storedProperties,+ partitions,+ distribution,+ sortOrders,+ indexes);+ }+ };+ }+}diff --git a/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/generic/FakeTableLocationProvider.java b/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/generic/FakeTableLocationProvider.javanew file mode 100644index 0000000000..1fa6fa79a1--- /dev/null+++ b/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/generic/FakeTableLocationProvider.java@@ -0,0 +1,141 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.catalog.lakehouse.generic;++import com.google.common.collect.Lists;+import java.util.Collections;+import java.util.List;+import java.util.concurrent.atomic.AtomicInteger;++/**+ * A {@link TableLocationProvider} registered only in the test classpath, used to verify that a+ * custom provider is discovered and consulted by the generic catalog.+ */+public class FakeTableLocationProvider implements TableLocationProvider {++ /** The name under which this provider is registered. */+ public static final String NAME = "testing";++ /** The prefix of every location allocated by this provider. */+ public static final String LOCATION_PREFIX = "testing://bucket/";++ // The provider instance used by a catalog is created by the ServiceLoader and not reachable from+ // the test, so the provision and unprovision calls are recorded statically.+ private static final List<TableLocationContext> PROVISIONED =+ Collections.synchronizedList(Lists.newArrayList());++ private static final List<TableLocationContext> UNPROVISIONED =+ Collections.synchronizedList(Lists.newArrayList());++ // Selection has to construct every registered provider to ask it its name, so counting+ // constructions is how a test observes whether a lookup scanned or answered from the index.+ private static final AtomicInteger CONSTRUCTED = new AtomicInteger();++ private static volatile boolean failOnUnprovision;++ private static volatile boolean overrideLocation;++ private static volatile String locationOverride;++ /** Public and no-argument, as the SPI requires; it acquires nothing. */+ public FakeTableLocationProvider() {+ CONSTRUCTED.incrementAndGet();+ }++ /**+ * Returns the contexts this provider was asked to provision, in the order the calls came in, so+ * that a test can assert the provider was or was not consulted for a given table.+ *+ * @return the recorded provision contexts+ */+ public static List<TableLocationContext> provisioned() {+ return Lists.newArrayList(PROVISIONED);+ }++ /**+ * Returns the contexts this provider was asked to unprovision, in the order the calls came in.+ *+ * @return the recorded unprovision contexts+ */+ public static List<TableLocationContext> unprovisioned() {+ return Lists.newArrayList(UNPROVISIONED);+ }++ /**+ * Makes every subsequent unprovision call fail, to verify how the catalog reports a provider that+ * cannot reclaim a location.+ *+ * @param fail whether unprovisioning should throw+ */+ public static void failOnUnprovision(boolean fail) {+ failOnUnprovision = fail;+ }++ /**+ * Returns how many instances have been constructed since the last {@link #reset()}, so that a+ * test can tell a lookup that scanned the classpath from one answered out of the cached index.+ *+ * @return the number of constructions+ */+ public static int constructedCount() {+ return CONSTRUCTED.get();+ }++ /**+ * Makes every subsequent provision call return the given location instead of the composed one, so+ * that a test can drive the catalog with a location a real provider should never return.+ *+ * @param location the location to return, null included+ */+ public static void provisionLocation(String location) {+ overrideLocation = true;+ locationOverride = location;+ }++ /** Clears the recorded calls and stops unprovisioning from failing. */+ public static void reset() {+ overrideLocation = false;+ locationOverride = null;+ PROVISIONED.clear();+ UNPROVISIONED.clear();+ CONSTRUCTED.set(0);+ failOnUnprovision = false;+ }++ @Override+ public String name() {+ return NAME;+ }++ @Override+ public String provisionTableLocation(TableLocationContext context) {+ PROVISIONED.add(context);+ return overrideLocation+ ? locationOverride+ : LOCATION_PREFIX + context.tableIdentifier().name() + "/";+ }++ @Override+ public void unprovisionTableLocation(TableLocationContext context) {+ UNPROVISIONED.add(context);+ if (failOnUnprovision) {+ throw new IllegalStateException("The path allocation service is unavailable");+ }+ }+}diff --git a/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/generic/TestDefaultTableLocationProvider.java b/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/generic/TestDefaultTableLocationProvider.javanew file mode 100644index 0000000000..704b4831be--- /dev/null+++ b/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/generic/TestDefaultTableLocationProvider.java@@ -0,0 +1,179 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.catalog.lakehouse.generic;++import com.google.common.collect.ImmutableMap;+import java.util.Map;+import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.Schema;+import org.apache.gravitino.rel.Table;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Test;+import org.mockito.Mockito;++public class TestDefaultTableLocationProvider {++ private static final NameIdentifier TABLE_IDENT =+ NameIdentifier.of("metalake", "catalog", "schema1", "table1");++ @Test+ void testTableLocationWins() {+ DefaultTableLocationProvider provider = new DefaultTableLocationProvider();+ Map<String, String> catalogProperties = ImmutableMap.of("location", "/tmp/catalog");+ Schema schema = mockSchema(ImmutableMap.of(Schema.PROPERTY_LOCATION, "/tmp/schema"));++ String location =+ provider.provisionTableLocation(+ context(+ schema,+ ImmutableMap.of(Table.PROPERTY_LOCATION, "/tmp/explicit"),+ catalogProperties));++ // The table's own location is used as-is, the table name is not appended.+ Assertions.assertEquals("/tmp/explicit/", location);+ }++ @Test+ void testFallBackToSchemaLocation() {+ DefaultTableLocationProvider provider = new DefaultTableLocationProvider();+ Map<String, String> catalogProperties = ImmutableMap.of("location", "/tmp/catalog");+ Schema schema = mockSchema(ImmutableMap.of(Schema.PROPERTY_LOCATION, "/tmp/schema"));++ String location =+ provider.provisionTableLocation(context(schema, ImmutableMap.of(), catalogProperties));++ Assertions.assertEquals("/tmp/schema/table1/", location);+ }++ @Test+ void testFallBackToCatalogLocation() {+ DefaultTableLocationProvider provider = new DefaultTableLocationProvider();+ Map<String, String> catalogProperties = ImmutableMap.of("location", "/tmp/catalog");+ Schema schema = mockSchema(ImmutableMap.of());++ String location =+ provider.provisionTableLocation(context(schema, ImmutableMap.of(), catalogProperties));++ // The schema name is taken from the table identifier's namespace.+ Assertions.assertEquals("/tmp/catalog/schema1/table1/", location);+ }++ @Test+ void testTrailingSlashIsNotDuplicated() {+ DefaultTableLocationProvider provider = new DefaultTableLocationProvider();+ Map<String, String> catalogProperties = ImmutableMap.of("location", "/tmp/catalog/");+ Schema schema = mockSchema(ImmutableMap.of(Schema.PROPERTY_LOCATION, "/tmp/schema/"));++ Assertions.assertEquals(+ "/tmp/schema/table1/",+ provider.provisionTableLocation(context(schema, ImmutableMap.of(), catalogProperties)));+ Assertions.assertEquals(+ "/tmp/explicit/",+ provider.provisionTableLocation(+ context(+ schema,+ ImmutableMap.of(Table.PROPERTY_LOCATION, "/tmp/explicit/"),+ catalogProperties)));+ }++ @Test+ void testNullSchemaPropertiesFallsBackToCatalogLocation() {+ DefaultTableLocationProvider provider = new DefaultTableLocationProvider();+ Map<String, String> catalogProperties = ImmutableMap.of("location", "/tmp/catalog");+ Schema schema = mockSchema(null);++ Assertions.assertEquals(+ "/tmp/catalog/schema1/table1/",+ provider.provisionTableLocation(context(schema, ImmutableMap.of(), catalogProperties)));+ }++ @Test+ void testNoLocationAnywhereThrows() {+ DefaultTableLocationProvider provider = new DefaultTableLocationProvider();+ Map<String, String> catalogProperties = ImmutableMap.of();+ Schema schema = mockSchema(ImmutableMap.of());++ IllegalArgumentException e =+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ provider.provisionTableLocation(+ context(schema, ImmutableMap.of(), catalogProperties)));+ Assertions.assertTrue(+ e.getMessage().contains("'location' property is neither set in table properties"),+ "Unexpected message: " + e.getMessage());+ }++ @Test+ void testTheCatalogLocationIsReadPerCallRatherThanCaptured() {+ // There is no initialization callback to capture it in, so one instance must serve contexts+ // carrying different catalog properties. Pinned because the provider used to hold the value+ // in a field, and a leftover field would make every catalog on a shared instance resolve to+ // whichever one initialized it first.+ DefaultTableLocationProvider provider = new DefaultTableLocationProvider();+ Schema schema = mockSchema(ImmutableMap.of());++ Assertions.assertEquals(+ "/tmp/one/schema1/table1/",+ provider.provisionTableLocation(+ context(schema, ImmutableMap.of(), ImmutableMap.of("location", "/tmp/one"))));+ Assertions.assertEquals(+ "/tmp/two/schema1/table1/",+ provider.provisionTableLocation(+ context(schema, ImmutableMap.of(), ImmutableMap.of("location", "/tmp/two"))));+ }++ @Test+ void testProviderName() {+ Assertions.assertEquals("default", new DefaultTableLocationProvider().name());+ }++ @Test+ void testUnprovisionIsANoOp() {+ // The built-in provider derives locations from properties and has nothing to reclaim, so+ // unprovisioning one has to be harmless rather than unsupported.+ Assertions.assertDoesNotThrow(+ () ->+ new DefaultTableLocationProvider()+ .unprovisionTableLocation(+ context(+ mockSchema(ImmutableMap.of()),+ ImmutableMap.of(Table.PROPERTY_LOCATION, "/tmp/schema/table1/"),+ ImmutableMap.of())));+ }++ private static Schema mockSchema(Map<String, String> properties) {+ Schema schema = Mockito.mock(Schema.class);+ // The context is always built from the schema the table is being created in, so the schema+ // name matches the second level of the table identifier by construction.+ Mockito.when(schema.name()).thenReturn(TABLE_IDENT.namespace().level(2));+ Mockito.when(schema.properties()).thenReturn(properties);+ return schema;+ }++ private static TableLocationContext context(+ Schema schema, Map<String, String> tableProperties, Map<String, String> catalogProperties) {+ return TableLocationContext.builder()+ .withTableIdentifier(TABLE_IDENT)+ .withTableProperties(tableProperties)+ .withSchema(schema)+ .withCatalogProperties(catalogProperties)+ .build();+ }+}diff --git a/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/generic/TestGenericCatalogOperations.java b/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/generic/TestGenericCatalogOperations.javaindex fc0c0859c1..9af6e3c189 100644--- a/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/generic/TestGenericCatalogOperations.java+++ b/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/generic/TestGenericCatalogOperations.java@@ -35,16 +35,22 @@ import static org.apache.gravitino.Configs.RELATIONAL_ENTITY_STORE;import static org.apache.gravitino.Configs.STORE_DELETE_AFTER_TIME;import static org.apache.gravitino.Configs.STORE_TRANSACTION_MAX_SKEW_TIME;import static org.apache.gravitino.Configs.VERSION_RETENTION_COUNT;+import static org.apache.gravitino.Entity.EntityType.SCHEMA;+import static org.apache.gravitino.Entity.EntityType.TABLE;import static org.mockito.Mockito.when;+import com.google.common.collect.ImmutableMap;+import com.google.common.collect.Maps;import java.io.File;import java.io.IOException;import java.time.Instant;import java.util.Arrays;+import java.util.List;import java.util.Map;import java.util.Set;import java.util.UUID;import java.util.stream.Collectors;+import javax.annotation.Nullable;import org.apache.commons.io.FileUtils;import org.apache.commons.lang3.reflect.FieldUtils;import org.apache.gravitino.Catalog;@@ -59,17 +65,25 @@ import org.apache.gravitino.Schema;import org.apache.gravitino.StringIdentifier;import org.apache.gravitino.exceptions.NoSuchCatalogException;import org.apache.gravitino.exceptions.NoSuchSchemaException;+import org.apache.gravitino.exceptions.NoSuchTableException;import org.apache.gravitino.exceptions.SchemaAlreadyExistsException;import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.meta.BaseMetalake;import org.apache.gravitino.meta.CatalogEntity;import org.apache.gravitino.meta.SchemaVersion;+import org.apache.gravitino.meta.TableEntity;+import org.apache.gravitino.rel.Column;+import org.apache.gravitino.rel.Table;+import org.apache.gravitino.rel.expressions.sorts.SortOrder;+import org.apache.gravitino.rel.expressions.transforms.Transform;+import org.apache.gravitino.rel.indexes.Index;import org.apache.gravitino.storage.IdGenerator;import org.apache.gravitino.storage.RandomIdGenerator;import org.apache.gravitino.utils.NameIdentifierUtil;import org.junit.jupiter.api.AfterAll;import org.junit.jupiter.api.Assertions;import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;import org.mockito.Mockito;@@ -82,6 +96,8 @@ public class TestGenericCatalogOperations {private static EntityStore store;private static IdGenerator idGenerator;private static GenericCatalogOperations ops;+ private static GenericCatalogOperations opsWithFakeProvider;+ private static GenericCatalogOperations opsWithDefaultProvider;@BeforeAllpublic static void setUp() throws IOException, IllegalAccessException {@@ -143,11 +159,36 @@ public class TestGenericCatalogOperations {FieldUtils.writeField(GravitinoEnv.getInstance(), "config", config, true);ops = new GenericCatalogOperations(store, idGenerator);++ // A second instance, initialized so that it uses the test provider, to exercise the provision+ // and unprovision callbacks. The shared instance above is never initialized and has no+ // provider.+ opsWithFakeProvider = new GenericCatalogOperations(store, idGenerator);+ opsWithFakeProvider.initialize(+ ImmutableMap.of(+ GenericCatalogPropertiesMetadata.TABLE_LOCATION_PROVIDER,+ FakeTableLocationProvider.NAME),+ null /* CatalogInfo, unused */,+ new GenericCatalog());++ // A third instance left on the built-in provider, to show that an external table carrying its+ // own location is resolved the same way whichever provider a catalog is configured with.+ opsWithDefaultProvider = new GenericCatalogOperations(store, idGenerator);+ opsWithDefaultProvider.initialize(+ ImmutableMap.of(), null /* CatalogInfo, unused */, new GenericCatalog());+ }++ @BeforeEach+ public void resetProvider() {+ FakeTableLocationProvider.reset();+ FakeTableDelegator.reset();}@AfterAllpublic static void tearDown() throws IOException {ops.close();+ opsWithFakeProvider.close();+ opsWithDefaultProvider.close();store.close();FileUtils.deleteDirectory(new File(STORE_PATH));}@@ -243,7 +284,674 @@ public class TestGenericCatalogOperations {false));}+ @Test+ public void testDropTableUnprovisionsItsLocation() {+ NameIdentifier schemaIdent = createSchema();+ NameIdentifier tableIdent = createTable(schemaIdent, "table1");++ Assertions.assertTrue(opsWithFakeProvider.dropTable(tableIdent));++ List<TableLocationContext> unprovisioned = FakeTableLocationProvider.unprovisioned();+ Assertions.assertEquals(1, unprovisioned.size());+ TableLocationContext context = unprovisioned.get(0);+ Assertions.assertEquals(tableIdent, context.tableIdentifier());+ // The location the provider has to hand back reaches it through the stored table properties,+ // which are read before the table is removed.+ Assertions.assertEquals(+ locationOf("table1"), context.tableProperties().get(Table.PROPERTY_LOCATION));+ Assertions.assertEquals(+ FakeTableDelegator.TABLE_FORMAT,+ context.tableProperties().get(Table.PROPERTY_TABLE_FORMAT));+ Assertions.assertEquals(schemaIdent.name(), context.schema().name());+ }++ @Test+ public void testPurgeTableUnprovisionsItsLocation() {+ NameIdentifier schemaIdent = createSchema();+ NameIdentifier tableIdent = createTable(schemaIdent, "table1");++ Assertions.assertTrue(opsWithFakeProvider.purgeTable(tableIdent));++ List<TableLocationContext> unprovisioned = FakeTableLocationProvider.unprovisioned();+ Assertions.assertEquals(1, unprovisioned.size());+ Assertions.assertEquals(tableIdent, unprovisioned.get(0).tableIdentifier());+ Assertions.assertEquals(+ locationOf("table1"), unprovisioned.get(0).tableProperties().get(Table.PROPERTY_LOCATION));+ }++ @Test+ public void testACatalogPropertyWithANullValueDoesNotFailInitialization() throws IOException {+ Map<String, String> conf = Maps.newHashMap();+ conf.put(+ GenericCatalogPropertiesMetadata.TABLE_LOCATION_PROVIDER, FakeTableLocationProvider.NAME);+ conf.put("a-property-with-no-value", null);++ // A null property value must not be able to fail the creation of a whole catalog. This is the+ // catalog-level counterpart of testAPropertyWithANullValueReachesTheProvider.+ GenericCatalogOperations catalogOps = new GenericCatalogOperations(store, idGenerator);+ catalogOps.initialize(conf, null /* CatalogInfo, unused */, new GenericCatalog());++ try {+ NameIdentifier schemaIdent = createSchema();+ Table created =+ createTableThroughCatalog(catalogOps, schemaIdent, "table1", ImmutableMap.of());+ Assertions.assertEquals(+ locationOf("table1"), created.properties().get(Table.PROPERTY_LOCATION));+ } finally {+ catalogOps.close();+ }+ }++ @Test+ public void testDroppingATableReadsItsEntityOnlyOnce() throws IOException {+ NameIdentifier schemaIdent = createSchema();+ NameIdentifier tableIdent = createTable(schemaIdent, "table1");++ EntityStore spiedStore = Mockito.spy(store);+ GenericCatalogOperations catalogOps = new GenericCatalogOperations(spiedStore, idGenerator);+ catalogOps.initialize(+ ImmutableMap.of(+ GenericCatalogPropertiesMetadata.TABLE_LOCATION_PROVIDER,+ FakeTableLocationProvider.NAME),+ null /* CatalogInfo, unused */,+ new GenericCatalog());++ try {+ Assertions.assertTrue(catalogOps.dropTable(tableIdent));++ // The properties read to build the unprovision context already carry the table format, so+ // resolving the operations to drop with must not go back to the store for the same entity.+ Mockito.verify(spiedStore, Mockito.times(1)).get(tableIdent, TABLE, TableEntity.class);+ } finally {+ catalogOps.close();+ }+ }++ @Test+ public void testDropNonExistentTableDoesNotUnprovision() {+ NameIdentifier schemaIdent = createSchema();+ NameIdentifier tableIdent =+ NameIdentifier.of(METALAKE_NAME, CATALOG_NAME, schemaIdent.name(), "no-such-table");++ Assertions.assertFalse(opsWithFakeProvider.dropTable(tableIdent));+ Assertions.assertTrue(FakeTableLocationProvider.unprovisioned().isEmpty());+ }++ @Test+ public void testDropSchemaWithCascadeUnprovisionsEveryTableLocation() {+ NameIdentifier schemaIdent = createSchema();+ NameIdentifier tableIdent1 = createTable(schemaIdent, "table1");+ NameIdentifier tableIdent2 = createTable(schemaIdent, "table2");++ // Load both tables so that their format is cached, to tell an invalidated cache apart from a+ // cache that was never populated.+ opsWithFakeProvider.loadTable(tableIdent1);+ opsWithFakeProvider.loadTable(tableIdent2);+ Assertions.assertNotNull(opsWithFakeProvider.tableFormatCache().getIfPresent(tableIdent1));+ Assertions.assertNotNull(opsWithFakeProvider.tableFormatCache().getIfPresent(tableIdent2));++ Assertions.assertTrue(opsWithFakeProvider.dropSchema(schemaIdent, true /* cascade */));++ Set<NameIdentifier> unprovisionedIdents =+ FakeTableLocationProvider.unprovisioned().stream()+ .map(TableLocationContext::tableIdentifier)+ .collect(Collectors.toSet());+ Assertions.assertEquals(Set.of(tableIdent1, tableIdent2), unprovisionedIdents);++ // The cascade also has to clear the cached table formats, which it only does when it goes+ // through the catalog level dropTable.+ Assertions.assertNull(opsWithFakeProvider.tableFormatCache().getIfPresent(tableIdent1));+ Assertions.assertNull(opsWithFakeProvider.tableFormatCache().getIfPresent(tableIdent2));+ }++ @Test+ public void testFailedUnprovisionStillReportsTheDropAsSuccessful() {+ NameIdentifier schemaIdent = createSchema();+ NameIdentifier tableIdent = createTable(schemaIdent, "table1");+ FakeTableLocationProvider.failOnUnprovision(true);++ // The table is already gone by the time the provider is called, so failing the request would+ // report a drop that did happen as unsuccessful. The failure is logged instead.+ Assertions.assertTrue(opsWithFakeProvider.dropTable(tableIdent));+ Assertions.assertEquals(1, FakeTableLocationProvider.unprovisioned().size());+ Assertions.assertThrows(+ NoSuchTableException.class, () -> opsWithFakeProvider.loadTable(tableIdent));+ }++ @Test+ public void testFailedUnprovisionDoesNotAbortACascadingSchemaDrop() {+ NameIdentifier schemaIdent = createSchema();+ createTable(schemaIdent, "table1");+ createTable(schemaIdent, "table2");+ FakeTableLocationProvider.failOnUnprovision(true);++ Assertions.assertTrue(opsWithFakeProvider.dropSchema(schemaIdent, true /* cascade */));++ // Both tables are attempted, rather than the first failure leaving the second one behind.+ Assertions.assertEquals(2, FakeTableLocationProvider.unprovisioned().size());+ Assertions.assertThrows(+ NoSuchSchemaException.class, () -> opsWithFakeProvider.loadSchema(schemaIdent));+ }++ @Test+ public void testAnExternalTableWithALocationReachesTheProviderToo() {+ NameIdentifier schemaIdent = createSchema();+ String suppliedLocation = "s3://caller-owned-bucket/existing/data";++ createTableThroughCatalog(+ opsWithFakeProvider,+ schemaIdent,+ "external_table",+ ImmutableMap.of(+ Table.PROPERTY_EXTERNAL, "true", Table.PROPERTY_LOCATION, suppliedLocation));++ // Registering data that already exists is the case a provider most needs to see rather than+ // have decided for it: both facts it would rule on are on the context, so it can return the+ // supplied path unchanged, place the table elsewhere, or refuse the creation outright.+ Assertions.assertEquals(1, FakeTableLocationProvider.provisioned().size());+ TableLocationContext context = FakeTableLocationProvider.provisioned().get(0);+ Assertions.assertTrue(+ Boolean.parseBoolean(context.tableProperties().get(Table.PROPERTY_EXTERNAL)));+ Assertions.assertEquals(+ suppliedLocation, context.tableProperties().get(Table.PROPERTY_LOCATION));+ }++ @Test+ public void testASuppliedLocationIsUnchangedUnderTheBuiltInProvider() {+ NameIdentifier schemaIdent = createSchema();+ // Without a trailing slash on purpose: with one there would be no normalization left to+ // preserve, and preserving it is the whole claim being made here.+ String suppliedLocation = "s3://caller-owned-bucket/existing/data";++ Table external =+ createTableThroughCatalog(+ opsWithDefaultProvider,+ schemaIdent,+ "external1",+ ImmutableMap.of(+ Table.PROPERTY_EXTERNAL, "true", Table.PROPERTY_LOCATION, suppliedLocation));+ Table managed =+ createTableThroughCatalog(+ opsWithDefaultProvider,+ schemaIdent,+ "managed1",+ ImmutableMap.of(Table.PROPERTY_LOCATION, suppliedLocation));++ // Routing a supplied location through the provider is not a behaviour change for a catalog on+ // the built-in one: returning it verbatim is that provider's first branch, and it is the same+ // branch the catalog used to apply itself, trailing slash included.+ Assertions.assertEquals(+ suppliedLocation + "/", external.properties().get(Table.PROPERTY_LOCATION));+ Assertions.assertEquals(+ suppliedLocation + "/", managed.properties().get(Table.PROPERTY_LOCATION));+ }++ @Test+ public void testACallerSuppliedLocationReachesTheProvider() {+ NameIdentifier schemaIdent = createSchema();+ String suppliedLocation = "s3://caller-owned-bucket/managed";++ Table created =+ createTableThroughCatalog(+ opsWithFakeProvider,+ schemaIdent,+ "managed_table",+ ImmutableMap.of(Table.PROPERTY_LOCATION, suppliedLocation));++ // The catalog does not decide on the provider's behalf. A supplied location is passed through+ // as the `location` property of the context, and what happens to it is the provider's call: a+ // provider enforcing a placement policy exists precisely for this request, and one that keeps+ // the caller's choice returns it unchanged. This provider allocates, so it allocates.+ Assertions.assertEquals(1, FakeTableLocationProvider.provisioned().size());+ Assertions.assertEquals(+ suppliedLocation,+ FakeTableLocationProvider.provisioned()+ .get(0)+ .tableProperties()+ .get(Table.PROPERTY_LOCATION));+ Assertions.assertEquals(+ FakeTableLocationProvider.LOCATION_PREFIX + "managed_table/",+ created.properties().get(Table.PROPERTY_LOCATION));+ }++ @Test+ public void testAPropertyWithANullValueReachesTheProvider() {+ NameIdentifier schemaIdent = createSchema();+ Map<String, String> properties = Maps.newHashMap();+ properties.put("a-property-with-no-value", null);++ // The catalog accepts a null property value, so building the context must not be what turns+ // such a request into a failure.+ Table created =+ createTableThroughCatalog(opsWithFakeProvider, schemaIdent, "null_value_table", properties);++ Assertions.assertEquals(+ locationOf("null_value_table"), created.properties().get(Table.PROPERTY_LOCATION));+ Assertions.assertEquals(1, FakeTableLocationProvider.provisioned().size());+ Map<String, String> seen = FakeTableLocationProvider.provisioned().get(0).tableProperties();+ Assertions.assertTrue(seen.containsKey("a-property-with-no-value"));+ Assertions.assertNull(seen.get("a-property-with-no-value"));+ }++ @Test+ public void testExternalTableWithoutLocationStillConsultsProvider() {+ NameIdentifier schemaIdent = createSchema();++ Table created =+ createTableThroughCatalog(+ opsWithFakeProvider,+ schemaIdent,+ "external_no_location",+ ImmutableMap.of(Table.PROPERTY_EXTERNAL, "true"));++ // There is no existing location to preserve here, so this case is left as it was: the table+ // format decides whether an external table without a location is valid at all.+ Assertions.assertEquals(+ locationOf("external_no_location"), created.properties().get(Table.PROPERTY_LOCATION));+ Assertions.assertEquals(1, FakeTableLocationProvider.provisioned().size());+ }++ @Test+ public void testDroppingExternalTableSkipsUnprovision() {+ NameIdentifier schemaIdent = createSchema();+ String suppliedLocation = "s3://caller-owned-bucket/existing/data/";+ createTableThroughCatalog(+ opsWithFakeProvider,+ schemaIdent,+ "external_table",+ ImmutableMap.of(+ Table.PROPERTY_EXTERNAL, "true", Table.PROPERTY_LOCATION, suppliedLocation));+ NameIdentifier tableIdent =+ NameIdentifier.of(METALAKE_NAME, CATALOG_NAME, schemaIdent.name(), "external_table");++ Assertions.assertTrue(opsWithFakeProvider.dropTable(tableIdent));++ // The data under an external table's location is not the catalog's to reclaim: the table+ // formats leave it in place on drop, and asking a provider to hand the location back would+ // invite it to delete exactly that data. Leaking beats deleting, so the callback is skipped.+ Assertions.assertTrue(FakeTableLocationProvider.unprovisioned().isEmpty());+ }++ @Test+ public void testDroppingExternalTableSkipsUnprovisionInACascade() {+ NameIdentifier schemaIdent = createSchema();+ createTableThroughCatalog(+ opsWithFakeProvider,+ schemaIdent,+ "external_table",+ ImmutableMap.of(+ Table.PROPERTY_EXTERNAL,+ "true",+ Table.PROPERTY_LOCATION,+ "s3://caller-owned-bucket/existing/data/"));+ createTableThroughCatalog(opsWithFakeProvider, schemaIdent, "managed_table", ImmutableMap.of());++ Assertions.assertTrue(opsWithFakeProvider.dropSchema(schemaIdent, true /* cascade */));++ // Only the managed table's location comes back; the external one is left alone, exactly as on+ // a single drop.+ List<TableLocationContext> unprovisioned = FakeTableLocationProvider.unprovisioned();+ Assertions.assertEquals(1, unprovisioned.size());+ Assertions.assertEquals("managed_table", unprovisioned.get(0).tableIdentifier().name());+ }++ @Test+ public void testACascadeResolvesTheSchemaOnlyOnce() {+ NameIdentifier schemaIdent = createSchema();+ createTableThroughCatalog(opsWithFakeProvider, schemaIdent, "t1", ImmutableMap.of());+ createTableThroughCatalog(opsWithFakeProvider, schemaIdent, "t2", ImmutableMap.of());+ createTableThroughCatalog(opsWithFakeProvider, schemaIdent, "t3", ImmutableMap.of());++ Assertions.assertTrue(opsWithFakeProvider.dropSchema(schemaIdent, true /* cascade */));++ // Three tables, one parent schema. Every context hands back the very same Schema instance,+ // which it could only do if the cascade resolved it once and shared it.+ List<TableLocationContext> unprovisioned = FakeTableLocationProvider.unprovisioned();+ Assertions.assertEquals(3, unprovisioned.size());+ Schema resolvedOnce = unprovisioned.get(0).schema();+ Assertions.assertSame(resolvedOnce, unprovisioned.get(1).schema());+ Assertions.assertSame(resolvedOnce, unprovisioned.get(2).schema());+ }++ @Test+ public void testPurgingAnExternalTableStillUnprovisions() {+ NameIdentifier schemaIdent = createSchema();+ String suppliedLocation = "s3://caller-owned-bucket/existing/data/";+ createTableThroughCatalog(+ opsWithFakeProvider,+ schemaIdent,+ "external_purged",+ ImmutableMap.of(+ Table.PROPERTY_EXTERNAL, "true", Table.PROPERTY_LOCATION, suppliedLocation));+ NameIdentifier tableIdent =+ NameIdentifier.of(METALAKE_NAME, CATALOG_NAME, schemaIdent.name(), "external_purged");++ Assertions.assertTrue(opsWithFakeProvider.purgeTable(tableIdent));++ // The mirror of testDroppingExternalTableSkipsUnprovision, and the reason that one cannot be+ // stated as "external tables are never unprovisioned". A purge is the explicit request to+ // destroy the data, and LanceTableOperations#purgeTable honours it for an external table --+ // deleting the dataset its dropTable leaves alone. Skipping here would leak an allocation+ // whose data the catalog had just deleted.+ List<TableLocationContext> unprovisioned = FakeTableLocationProvider.unprovisioned();+ Assertions.assertEquals(1, unprovisioned.size());+ Assertions.assertTrue(+ Boolean.parseBoolean(unprovisioned.get(0).tableProperties().get(Table.PROPERTY_EXTERNAL)));+ // The location handed back is the one that was stored, which for this catalog is the one the+ // provider itself returned when it saw the supplied value.+ Assertions.assertEquals(+ FakeTableLocationProvider.LOCATION_PREFIX + "external_purged/",+ unprovisioned.get(0).tableProperties().get(Table.PROPERTY_LOCATION));+ }++ @Test+ public void testAnExternalTableIsUnprovisionedOnPurgeButNotOnDrop() {+ NameIdentifier schemaIdent = createSchema();+ Map<String, String> external =+ ImmutableMap.of(+ Table.PROPERTY_EXTERNAL, "true",+ Table.PROPERTY_LOCATION, "s3://caller-owned-bucket/existing/");+ createTableThroughCatalog(opsWithFakeProvider, schemaIdent, "to_drop", external);+ createTableThroughCatalog(opsWithFakeProvider, schemaIdent, "to_purge", external);++ opsWithFakeProvider.dropTable(+ NameIdentifier.of(METALAKE_NAME, CATALOG_NAME, schemaIdent.name(), "to_drop"));+ opsWithFakeProvider.purgeTable(+ NameIdentifier.of(METALAKE_NAME, CATALOG_NAME, schemaIdent.name(), "to_purge"));++ // The whole of the drop-versus-purge distinction, stated where it is actually made. The+ // provider is told about the purge and not about the drop, which is the catalog's decision to+ // make: by the time the callback runs the data is gone, so there is nothing left for a+ // provider to decide differently, and the skipped case is the one where reclaiming by path+ // would destroy a user's data.+ List<TableLocationContext> unprovisioned = FakeTableLocationProvider.unprovisioned();+ Assertions.assertEquals(1, unprovisioned.size());+ Assertions.assertEquals("to_purge", unprovisioned.get(0).tableIdentifier().name());+ }++ @Test+ public void testAFormatFailingAfterRemovingMetadataStillInvalidatesTheFormatCache() {+ NameIdentifier schemaIdent = createSchema();+ createTableThroughCatalog(opsWithFakeProvider, schemaIdent, "half_dropped", ImmutableMap.of());+ NameIdentifier tableIdent =+ NameIdentifier.of(METALAKE_NAME, CATALOG_NAME, schemaIdent.name(), "half_dropped");+ Assertions.assertNotNull(opsWithFakeProvider.tableFormatCache().getIfPresent(tableIdent));++ FakeTableDelegator.failAfterRemovingMetadata(true);+ Assertions.assertThrows(+ RuntimeException.class, () -> opsWithFakeProvider.dropTable(tableIdent));++ // The metadata is gone even though the drop threw, so a cached format here would be read for+ // whatever is created next under the same name.+ Assertions.assertNull(opsWithFakeProvider.tableFormatCache().getIfPresent(tableIdent));+ // Not unprovisioned: the format may equally have failed before touching storage, and handing+ // back a location that still has data under it is the unrecoverable direction.+ Assertions.assertTrue(FakeTableLocationProvider.unprovisioned().isEmpty());+ }++ @Test+ public void testANullProviderNameFallsBackToTheBuiltInProvider() throws IOException {+ Map<String, String> conf = Maps.newHashMap();+ conf.put(GenericCatalogPropertiesMetadata.TABLE_LOCATION_PROVIDER, null);+ conf.put("a-property-with-no-value", null);++ // getOrDefault returns decode(null) rather than the default when the key is present with a+ // null value, so without the fallback this would fail the whole catalog with "must not be+ // blank" -- on a property the server accepted, and in a catalog that tolerates null values+ // everywhere else.+ GenericCatalogOperations catalogOps = new GenericCatalogOperations(store, idGenerator);+ catalogOps.initialize(conf, null /* CatalogInfo, unused */, new GenericCatalog());++ try {+ NameIdentifier schemaIdent = createSchema("s3://schema-bucket/db");+ Table created =+ createTableThroughCatalog(catalogOps, schemaIdent, "table1", ImmutableMap.of());++ // The built-in chain, not the test provider: a null name means the property was not set.+ Assertions.assertEquals(+ "s3://schema-bucket/db/table1/", created.properties().get(Table.PROPERTY_LOCATION));+ Assertions.assertTrue(FakeTableLocationProvider.provisioned().isEmpty());+ } finally {+ catalogOps.close();+ }+ }++ @Test+ public void testDroppingAnEmptySchemaDoesNotResolveIt() throws IOException {+ EntityStore spy = Mockito.spy(store);+ GenericCatalogOperations catalogOps = new GenericCatalogOperations(spy, idGenerator);+ catalogOps.initialize(+ ImmutableMap.of(+ GenericCatalogPropertiesMetadata.TABLE_LOCATION_PROVIDER,+ FakeTableLocationProvider.NAME),+ null /* CatalogInfo, unused */,+ new GenericCatalog());++ try {+ NameIdentifier schemaIdent = createSchema();+ Mockito.clearInvocations(spy);++ Assertions.assertTrue(catalogOps.dropSchema(schemaIdent, true /* cascade */));++ // The schema is resolved to build the contexts of the tables being cascaded, so with no+ // tables there is nothing to resolve it for. Dropping the schema itself is a single delete,+ // so this read is the catalog's alone and every drop of an empty schema would pay for it.+ Mockito.verify(spy, Mockito.never())+ .get(Mockito.eq(schemaIdent), Mockito.eq(SCHEMA), Mockito.any());+ } finally {+ catalogOps.close();+ }+ }++ @Test+ public void testAProviderRefusingTheCreationLeavesNoTable() {+ NameIdentifier schemaIdent = createSchema();+ FakeTableLocationProvider.provisionLocation(null);++ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ createTableThroughCatalog(+ opsWithFakeProvider, schemaIdent, "never_created", ImmutableMap.of()));++ NameIdentifier tableIdent =+ NameIdentifier.of(METALAKE_NAME, CATALOG_NAME, schemaIdent.name(), "never_created");+ Assertions.assertFalse(opsWithFakeProvider.tableExists(tableIdent));+ // The format cache is populated after a successful creation, so a refused one must leave no+ // entry behind for a later table of the same name to read.+ Assertions.assertNull(opsWithFakeProvider.tableFormatCache().getIfPresent(tableIdent));+ }++ private NameIdentifier createSchema() {+ return createSchema(null);+ }++ /**+ * Creates a schema, optionally carrying a {@code location} of its own so that the built-in+ * provider has a level to derive a table location from.+ */+ private NameIdentifier createSchema(@Nullable String location) {+ String schemaName = randomSchemaName();+ NameIdentifier schemaIdent =+ NameIdentifierUtil.ofSchema(METALAKE_NAME, CATALOG_NAME, schemaName);+ StringIdentifier stringId = StringIdentifier.fromId(idGenerator.nextId());+ Map<String, String> properties =+ location == null ? null : ImmutableMap.of(Table.PROPERTY_LOCATION, location);+ opsWithFakeProvider.createSchema(+ schemaIdent, "schema comment", StringIdentifier.newPropertiesWithId(stringId, properties));+ return schemaIdent;+ }++ /**+ * Puts a table entity straight into the entity store, instead of going through createTable, so+ * that the drop paths can be exercised without a real table format behind them.+ */+ private NameIdentifier createTable(NameIdentifier schemaIdent, String tableName) {+ TableEntity table =+ TableEntity.builder()+ .withId(idGenerator.nextId())+ .withName(tableName)+ .withNamespace(Namespace.of(METALAKE_NAME, CATALOG_NAME, schemaIdent.name()))+ .withAuditInfo(+ AuditInfo.builder().withCreator("test").withCreateTime(Instant.now()).build())+ .withProperties(+ ImmutableMap.of(+ Table.PROPERTY_TABLE_FORMAT,+ FakeTableDelegator.TABLE_FORMAT,+ Table.PROPERTY_LOCATION,+ locationOf(tableName)))+ .build();+ Assertions.assertDoesNotThrow(() -> store.put(table, false));+ return NameIdentifier.of(METALAKE_NAME, CATALOG_NAME, schemaIdent.name(), tableName);+ }++ /**+ * Creates a table through the catalog level createTable, so that the location resolution under+ * test actually runs, unlike {@link #createTable(NameIdentifier, String)} which bypasses it.+ */+ private Table createTableThroughCatalog(+ GenericCatalogOperations catalogOps,+ NameIdentifier schemaIdent,+ String tableName,+ Map<String, String> properties) {+ NameIdentifier tableIdent =+ NameIdentifier.of(METALAKE_NAME, CATALOG_NAME, schemaIdent.name(), tableName);+ // A plain map rather than an ImmutableMap: a creation request may carry a property whose+ // value is null, and the test helper must be able to pass one through.+ Map<String, String> allProperties = Maps.newHashMap(properties);+ allProperties.put(Table.PROPERTY_TABLE_FORMAT, FakeTableDelegator.TABLE_FORMAT);+ allProperties.putAll(+ StringIdentifier.newPropertiesWithId(StringIdentifier.fromId(idGenerator.nextId()), null));++ return catalogOps.createTable(+ tableIdent,+ new Column[0],+ "table comment",+ allProperties,+ new Transform[0],+ null /* distribution */,+ new SortOrder[0],+ new Index[0]);+ }++ private static String locationOf(String tableName) {+ return FakeTableLocationProvider.LOCATION_PREFIX + tableName + "/";+ }+private String randomSchemaName() {return "schema_" + UUID.randomUUID().toString().replace("-", "");}++ @Test+ public void testABlankProvisionedLocationFailsTheCreation() {+ NameIdentifier schemaIdent = createSchema();++ for (String location : Arrays.asList(null, "", " ")) {+ FakeTableLocationProvider.provisionLocation(location);+ IllegalArgumentException e =+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ createTableThroughCatalog(+ opsWithFakeProvider, schemaIdent, "blank_location", ImmutableMap.of()));+ Assertions.assertTrue(+ e.getMessage().contains("returned a null or blank location"), e.getMessage());+ Assertions.assertTrue(+ e.getMessage().contains(FakeTableLocationProvider.NAME), e.getMessage());+ }+ }++ @Test+ public void testAProvisionedLocationIsStoredVerbatim() {+ NameIdentifier schemaIdent = createSchema();+ // No trailing slash: the shape of the path belongs to the provider, so the catalog stores it+ // exactly as returned rather than normalizing it, and the provider unprovisioning it later+ // sees the same string it handed out.+ String opaque = "testing://bucket/9f1c2e04-6b3a-4a17-bd6e-1c0a5f2d8e77";+ FakeTableLocationProvider.provisionLocation(opaque);++ Table created =+ createTableThroughCatalog(+ opsWithFakeProvider, schemaIdent, "verbatim_location", ImmutableMap.of());++ Assertions.assertEquals(opaque, created.properties().get(Table.PROPERTY_LOCATION));++ // A trailing slash is left alone for the same reason. The catalog does append one when it+ // compares the location it handed out with the one the created table reports, so that a+ // provider is not told its location was declined over a slash; that normalization belongs to+ // the comparison and must not reach the stored property.+ String directory = "testing://bucket/9f1c2e04-6b3a-4a17-bd6e-1c0a5f2d8e77/";+ FakeTableLocationProvider.provisionLocation(directory);++ Table createdInDirectory =+ createTableThroughCatalog(+ opsWithFakeProvider, schemaIdent, "verbatim_directory", ImmutableMap.of());++ Assertions.assertEquals(+ directory, createdInDirectory.properties().get(Table.PROPERTY_LOCATION));+ }++ @Test+ public void testANonCanonicalExternalValueIsReadTheSameWayTheFormatsReadIt() {+ // `external=yes` is not external to the table formats: they read the flag with+ // Boolean.parseBoolean or an equalsIgnoreCase("true"), so they see false and treat the table+ // as managed, deleting its data on drop. If the catalog disagreed and read it as external, it+ // would skip handing the location back for a table whose data was just deleted: the data lost+ // and the allocation leaked at once. So the drop must reach the provider.+ NameIdentifier schemaIdent = createSchema();+ createTableThroughCatalog(+ opsWithFakeProvider,+ schemaIdent,+ "yes_table",+ ImmutableMap.of(Table.PROPERTY_EXTERNAL, "yes"));+ NameIdentifier tableIdent =+ NameIdentifier.of(METALAKE_NAME, CATALOG_NAME, schemaIdent.name(), "yes_table");++ Assertions.assertTrue(opsWithFakeProvider.dropTable(tableIdent));++ Assertions.assertEquals(+ 1,+ FakeTableLocationProvider.unprovisioned().size(),+ "'yes' is not read as external by the formats, so the catalog must not read it so either");+ }++ @Test+ public void testTheCatalogPropertiesReachTheProvider() throws IOException {+ // The built-in provider's last fallback is the catalog's own `location`, and with no+ // initialization callback the only way it can see that property is through the context. This+ // is the end-to-end wiring of it: a catalog that has a location, a schema that does not, and a+ // table that must therefore land under {catalog location}/{schema}/{table}/.+ GenericCatalogOperations catalogOps = new GenericCatalogOperations(store, idGenerator);+ catalogOps.initialize(+ ImmutableMap.of(Catalog.PROPERTY_LOCATION, "s3://catalog-owned"),+ null /* CatalogInfo, unused */,+ new GenericCatalog());+ try {+ NameIdentifier schemaIdent = createSchema();++ Table created =+ createTableThroughCatalog(catalogOps, schemaIdent, "catalog_level", ImmutableMap.of());++ Assertions.assertEquals(+ "s3://catalog-owned/" + schemaIdent.name() + "/catalog_level/",+ created.properties().get(Table.PROPERTY_LOCATION));+ } finally {+ catalogOps.close();+ }+ }++ @Test+ public void testManagedTableWithoutLocationConsultsProvider() {+ NameIdentifier schemaIdent = createSchema();++ createTableThroughCatalog(opsWithFakeProvider, schemaIdent, "managed_table", ImmutableMap.of());++ // The fourth cell of the external x supplied-location matrix: no location and not external is+ // the ordinary case the provider exists for.+ List<TableLocationContext> provisioned = FakeTableLocationProvider.provisioned();+ Assertions.assertEquals(1, provisioned.size());+ Assertions.assertEquals("managed_table", provisioned.get(0).tableIdentifier().name());+ Assertions.assertFalse(+ Boolean.parseBoolean(provisioned.get(0).tableProperties().get(Table.PROPERTY_EXTERNAL)));+ }}diff --git a/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/generic/TestPropertiesMetadata.java b/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/generic/TestPropertiesMetadata.javaindex a57474be2e..bbc1fbcd13 100644--- a/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/generic/TestPropertiesMetadata.java+++ b/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/generic/TestPropertiesMetadata.java@@ -37,6 +37,22 @@ public class TestPropertiesMetadata {genericCatalog = new GenericCatalog();}+ @Test+ void testTableLocationProviderPropertyIsImmutableWithDefault() {+ PropertiesMetadata catalogPropertiesMetadata = genericCatalog.catalogPropertiesMetadata();++ Assertions.assertTrue(+ catalogPropertiesMetadata.containsProperty(+ GenericCatalogPropertiesMetadata.TABLE_LOCATION_PROVIDER));+ Assertions.assertEquals(+ DefaultTableLocationProvider.NAME,+ catalogPropertiesMetadata.getOrDefault(+ ImmutableMap.of(), GenericCatalogPropertiesMetadata.TABLE_LOCATION_PROVIDER));+ Assertions.assertTrue(+ catalogPropertiesMetadata.isImmutableProperty(+ GenericCatalogPropertiesMetadata.TABLE_LOCATION_PROVIDER));+ }+@Testvoid testCatalogPropertiesMetadata() {PropertiesMetadata catalogPropertiesMetadata = genericCatalog.catalogPropertiesMetadata();diff --git a/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/generic/TestTableLocationProviderFactory.java b/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/generic/TestTableLocationProviderFactory.javanew file mode 100644index 0000000000..e4ca218553--- /dev/null+++ b/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/generic/TestTableLocationProviderFactory.java@@ -0,0 +1,115 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.catalog.lakehouse.generic;++import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Test;++public class TestTableLocationProviderFactory {++ @Test+ void testCreateDefaultProvider() {+ TableLocationProvider provider = create(DefaultTableLocationProvider.NAME);+ Assertions.assertInstanceOf(DefaultTableLocationProvider.class, provider);+ Assertions.assertEquals(DefaultTableLocationProvider.NAME, provider.name());+ }++ @Test+ void testProviderNameIsCaseInsensitive() {+ Assertions.assertInstanceOf(DefaultTableLocationProvider.class, create("DeFaUlT"));+ }++ @Test+ void testCreateCustomProviderDiscoveredViaServiceLoader() {+ Assertions.assertInstanceOf(+ FakeTableLocationProvider.class, create(FakeTableLocationProvider.NAME));+ }++ @Test+ void testEachCallReturnsANewInstance() {+ Assertions.assertNotSame(+ create(DefaultTableLocationProvider.NAME), create(DefaultTableLocationProvider.NAME));+ }++ @Test+ void testTheFactoryNeitherInitializesNorClosesAnything() {+ // The interface has no lifecycle callbacks, so a provider is handed back exactly as its+ // constructor left it. Pinned because the factory used to initialize it here, and a provider+ // written against that behaviour would otherwise fail in a way nothing else in the module+ // catches: the instance it gets is the instance it keeps.+ FakeTableLocationProvider.reset();+ TableLocationProvider provider = create(FakeTableLocationProvider.NAME);++ Assertions.assertInstanceOf(FakeTableLocationProvider.class, provider);+ Assertions.assertTrue(+ FakeTableLocationProvider.provisioned().isEmpty(),+ "creating a provider must not call anything on it");+ }++ @Test+ void testABrokenProviderOnTheClasspathIsSkippedRatherThanFailingTheLookup() {+ // BrokenTableLocationProvider is registered in this module's test services file, so it is+ // instantiated and asked for its name on every lookup here, including this one. That it fails+ // with an Error rather than an exception is the point: name() is called by the factory and not+ // by the loader, so nothing wraps it, and a catch that only took RuntimeException would let it+ // through and stop every catalog from starting over one broken jar.+ Assertions.assertInstanceOf(+ DefaultTableLocationProvider.class, create(DefaultTableLocationProvider.NAME));++ // The name it never managed to report is still not a name anyone can select.+ Assertions.assertThrows(IllegalArgumentException.class, () -> create("broken"));+ }++ @Test+ void testUnknownProviderThrows() {+ IllegalArgumentException e =+ Assertions.assertThrows(IllegalArgumentException.class, () -> create("no-such-provider"));+ Assertions.assertTrue(+ e.getMessage().contains("No TableLocationProvider found for name 'no-such-provider'"),+ "Unexpected message: " + e.getMessage());+ }++ @Test+ void testBlankProviderNameThrows() {+ Assertions.assertThrows(IllegalArgumentException.class, () -> create(" "));+ Assertions.assertThrows(IllegalArgumentException.class, () -> create(null));+ }++ @Test+ void testEveryLookupScansRatherThanAnsweringFromACache() {+ FakeTableLocationProvider.reset();++ create(DefaultTableLocationProvider.NAME);+ int afterFirstLookup = FakeTableLocationProvider.constructedCount();+ Assertions.assertTrue(afterFirstLookup >= 1, "selection has to construct every candidate");++ create(DefaultTableLocationProvider.NAME);++ // Discovery is repeated per catalog rather than remembered. Pinned because it is a deliberate+ // choice and not an oversight: a provider registered after the first catalog started is found+ // by the next one, and nothing static outlives the lookup to be invalidated later.+ Assertions.assertTrue(+ FakeTableLocationProvider.constructedCount() > afterFirstLookup,+ "a second lookup should scan again rather than answer from a remembered index");+ }++ private static TableLocationProvider create(String name) {+ return TableLocationProviderFactory.create(name);+ }+}diff --git a/catalogs/catalog-lakehouse-generic/src/test/resources/META-INF/services/org.apache.gravitino.catalog.lakehouse.generic.LakehouseTableDelegator b/catalogs/catalog-lakehouse-generic/src/test/resources/META-INF/services/org.apache.gravitino.catalog.lakehouse.generic.LakehouseTableDelegatornew file mode 100644index 0000000000..6a553c708e--- /dev/null+++ b/catalogs/catalog-lakehouse-generic/src/test/resources/META-INF/services/org.apache.gravitino.catalog.lakehouse.generic.LakehouseTableDelegator@@ -0,0 +1,19 @@+#+# Licensed to the Apache Software Foundation (ASF) under one+# or more contributor license agreements. See the NOTICE file+# distributed with this work for additional information+# regarding copyright ownership. The ASF licenses this file+# to you under the Apache License, Version 2.0 (the+# "License"); you may not use this file except in compliance+# with the License. You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing,+# software distributed under the License is distributed on an+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+# KIND, either express or implied. See the License for the+# specific language governing permissions and limitations+# under the License.+#+org.apache.gravitino.catalog.lakehouse.generic.FakeTableDelegatordiff --git a/catalogs/catalog-lakehouse-generic/src/test/resources/META-INF/services/org.apache.gravitino.catalog.lakehouse.generic.TableLocationProvider b/catalogs/catalog-lakehouse-generic/src/test/resources/META-INF/services/org.apache.gravitino.catalog.lakehouse.generic.TableLocationProvidernew file mode 100644index 0000000000..edf35230c0--- /dev/null+++ b/catalogs/catalog-lakehouse-generic/src/test/resources/META-INF/services/org.apache.gravitino.catalog.lakehouse.generic.TableLocationProvider@@ -0,0 +1,20 @@+#+# Licensed to the Apache Software Foundation (ASF) under one+# or more contributor license agreements. See the NOTICE file+# distributed with this work for additional information+# regarding copyright ownership. The ASF licenses this file+# to you under the Apache License, Version 2.0 (the+# "License"); you may not use this file except in compliance+# with the License. You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing,+# software distributed under the License is distributed on an+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+# KIND, either express or implied. See the License for the+# specific language governing permissions and limitations+# under the License.+#+org.apache.gravitino.catalog.lakehouse.generic.FakeTableLocationProvider+org.apache.gravitino.catalog.lakehouse.generic.BrokenTableLocationProviderdiff --git a/docs/lakehouse-generic-catalog.md b/docs/lakehouse-generic-catalog.mdindex e5471e9831..a2963807cb 100644--- a/docs/lakehouse-generic-catalog.md+++ b/docs/lakehouse-generic-catalog.md@@ -44,17 +44,256 @@ For detailed information on available operations, see [Manage Relational Metadat### Catalog Properties-| Property | Description | Example | Required |-|-----------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------|----------|-| `provider` | Catalog provider type | `lakehouse-generic` | Yes |-| `location` | Root storage path for all schemas and tables | `s3://bucket/lakehouse` | No |-| `lance.schema-refresh-mode` | Lance table schema refresh mode. `DECLARED_AND_EMPTY` (default) refreshes declared tables and tables with empty stored columns. `VERSION_CHECK` additionally refreshes when the Lance dataset version changes. | `DECLARED_AND_EMPTY` | No |+| Property | Description | Example | Required |+|-----------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------|----------|+| `provider` | Catalog provider type | `lakehouse-generic` | Yes |+| `location` | Root storage path for all schemas and tables | `s3://bucket/lakehouse` | No |+| `table-location-provider` | Name of the [table location provider](#pluggable-table-location-provider) that provisions and unprovisions the locations of this catalog's tables. Defaults to `default`, which resolves the location from the table, schema and catalog `location` properties as described below. Immutable once the catalog is created. | `default` | No |+| `lance.schema-refresh-mode` | Lance table schema refresh mode. `DECLARED_AND_EMPTY` (default) refreshes declared tables and tables with empty stored columns. `VERSION_CHECK` additionally refreshes when the Lance dataset version changes. | `DECLARED_AND_EMPTY` | No |++#### Pluggable table location provider++By default the catalog derives a new table's location from the `location` properties, following the+hierarchy described in [Key Property: `location`](#key-property-location). Deployments that allocate+storage through an external service can replace that logic with their own strategy.++Implement `org.apache.gravitino.catalog.lakehouse.generic.TableLocationProvider`, register it in+`META-INF/services/org.apache.gravitino.catalog.lakehouse.generic.TableLocationProvider`, drop the jar+into `catalogs/lakehouse-generic/libs`, and select it with the `table-location-provider` catalog+property (matched case-insensitively against `TableLocationProvider#name()`).++The interface is two operations wide -- `provisionTableLocation` and `unprovisionTableLocation` --+plus `name()`.++**The catalog reports; the provider decides.** The catalog's part is to hand over an accurate account+of what happened -- what the creation request asked for, where the table ended up, whether the data+under a location is gone -- and the provider's part is to decide what that account means for the+storage it manages. The catalog does not model what an implementation keeps, and an implementation is+never asked to reconstruct what the catalog or the table formats did. There is one exception, and it+is stated here as an exception rather than as the rule: an external table that is **dropped** does not+reach `unprovisionTableLocation` at all, for the reason given below.++**Responsibilities.** A provider owns the right to use a path; the table format owns the content at+the path. The dividing line is not physical against logical -- a provider may well create real+infrastructure -- but what a thing was created for: anything brought into being so that the path can+be used belongs to the provider, and anything written into the path belongs to the format. A provider+owns its reservation, its registry entry, whatever quota or grant it books, the name itself, and any+container it created to make the path usable; a table format owns the dataset, including deleting it;+the catalog owns neither, storing the location string verbatim and sequencing the two calls.++**Scope.** What this offers is allocation hooks plus best-effort release notification, with recovery+owned by the provider and the deployment. It is deliberately not a distributed transaction and not a+recovery system: the limitations below are real, and a provider that manages storage has to reconcile+against the catalog independently of these two calls.++One provider instance is created per catalog, and the property is immutable, so a catalog keeps the+provider it was created with. **There is no lifecycle**: the provider is never initialized and never+closed. A provider needing a remote client should create it lazily on first use and make it safe to+abandon, since a catalog is evicted from the server's catalog cache when idle and the provider it+held is simply discarded. Both callbacks are called concurrently and must be thread-safe.++Both callbacks receive a `TableLocationContext`, which carries `tableIdentifier()`,+`tableProperties()`, `schema()` -- the parent schema including its properties -- and+`catalogProperties()`. The last is how a provider receives configuration of its own, such as a+service endpoint or a quota group: the same map is handed to every call, so a provider that turns it+into something expensive should build that once and hold it rather than rebuilding it per table. The+`external` flag is available as the `external` entry of `tableProperties()`; read it with+`Boolean.parseBoolean`, which is how the table formats read it. Selection is per catalog, so a provider+that needs different behaviour for different schemas has to read a schema property and dispatch on it+itself. A provider doing that should reject an unrecognized value rather than falling back to another+strategy, and should treat the property as immutable: a table provisioned under one strategy has to be+unprovisioned under the same one.++A **request that supplies its own `location` reaches the provider too**, with the supplied value+visible as the `location` entry of `context.tableProperties()`. What happens to it is the provider's+decision: return it unchanged to honour it, return something else to place the table elsewhere, or+throw to refuse the creation. A provider enforcing a placement policy exists precisely for this+request, and deciding it in the catalog would leave that provider with nothing to enforce.++This is not a behaviour change for a catalog on the built-in provider, which returns a supplied+location verbatim as its first branch -- the same branch the catalog used to apply on its behalf.++An implementation that allocates storage has to handle the case deliberately. In this catalog a+caller usually supplies a location because the data is already there: an external Delta table, or a+Lance registration, both of which point at a dataset that exists. Allocating a fresh path for one of+those and returning it repoints the table at an empty directory and orphans the caller's data, while+the creation still reports success. Returning the supplied value unchanged is the safe default.+Everything else reaches the provider as well, including an external table that carries no+`location`; the table format decides whether that combination is valid at all.++`provisionTableLocation` runs on the server thread handling the table creation request. The catalog+applies no timeout, so a provider that calls a remote service must bound every call itself and fail+fast when the service is unavailable; a call that blocks holds that request thread until it returns.++`provisionTableLocation` must return a non-blank location; the catalog rejects the table creation+otherwise. That is the only check: the shape of the path belongs to the provider, nothing downstream+appends to it, and the value is stored verbatim so that a provider unprovisioning it later sees+exactly the string it returned.++**What the returned location promises, and what it does not.** It promises exactly one thing: that the+location is usable, meaning a table format may create its dataset there and will not be refused for+any reason under the provider's control. Whether an implementation had to reserve, register or create+anything to make that true is its own business, neither required nor forbidden. It does **not** promise+that a directory or prefix exists, that a dataset exists, or that the location is empty -- the last one+deliberately, because in this catalog a caller usually supplies a location precisely when the data is+already there.++When a table is dropped or purged, the catalog calls `unprovisionTableLocation` so that the provider+can hand the location back. It reads the location to reclaim from `context.tableProperties()` under+the `location` key, which the catalog fills in from the stored table properties read just before the+table was removed. Dropping a schema with cascade unprovisions the location of every table it+contains, one by one, resolving the shared parent schema once for the whole cascade.++The method has no default implementation, so every provider has to answer for it. A provider that+composes the path from configuration and registers it nowhere -- like the built-in one -- writes an+empty body.++**What the callback releases, and what it must not touch.** A provider releases what it issued: the+reservation, the registry entry, whatever quota or grant it booked, and the name itself so that it can+be handed out again. It may also remove a container it created itself -- a prefix or a bucket it+brought into being so the path could be used -- but only after establishing that the container holds+nothing except what the provider itself put there, and it must leave the container in place otherwise.+It must **not** delete content at the location: the table format owns the lifecycle of the data and has+already deleted it on every path that reaches the callback, so deleting anything further is at best+redundant and at worst destroys data this catalog promised not to touch.++Nothing about the location string establishes ownership on its own. The catalog supplies one fact, that+nothing anyone needs is under that location any more; whether the provider holds anything there is a+fact only the provider can establish, from its own records.++The unprovisioning happens *after* the table metadata, and the data of a managed table, have been+removed, so a provider that fails does not roll the drop back: the table is gone either way. The+failure is logged at WARN naming the table, the provider and the location that was not reclaimed,+and the drop still reports success, because reporting a drop that did happen as unsuccessful would+only invite a retry that cannot undo anything. For the same reason a failed unprovisioning does not+abort a cascading schema drop.++`unprovisionTableLocation` is called once per dropped table, but it is not guaranteed to be called+at all. A crash between the removal and the call skips it, and so does a failure raised inside the+drop after the metadata is already gone, which takes no crash and leaves the server running+normally. A provider reclaiming real storage needs its own reconciliation to catch both, and must+tolerate being called for a location that is already released.++**Dropping an external table skips the callback; purging one does not.** On a drop the catalog does+not own the data — the table formats leave the dataset in place — so asking a provider to hand the+location back would invite it to delete exactly the data the catalog just promised not to touch. A+leak is recoverable and a deletion is not, so `unprovisionTableLocation` is not called when a table+whose `external` property is true is dropped.++A purge is the opposite request. `LanceTableOperations.purgeTable` deletes the external dataset that+its `dropTable` leaves alone, so by the time the callback would run the data is gone and the reason+to skip has gone with it; the location is handed back.++The callback is therefore reached in exactly three situations: a dropped managed table, a purged+managed table, and a purged external one. There is deliberately no flag distinguishing them, because+the invariant they share is about the location rather than the table: **nothing anyone needs is under+the location named in the context**. In all three the table format has already deleted the data under+it. The catalog makes the drop-versus-purge and external distinctions rather than passing them on,+because the catalog is where the knowledge lives about which formats leave data in place.++Even so, `external` is only an approximation of the rule this callback wants, which is "hand back+only what was handed out". An external table created *without* a location does get one provisioned,+because both table formats check the location only after the catalog has filled it in, so skipping+its drop leaks that allocation.++Telling those apart exactly would need the catalog to record, per table, whether it provisioned the+location, which it does not do today. Both are why a provider reclaiming real storage needs its own+reconciliation, and why it must tolerate a location it does not recognize.++`ManagedTableOperations.purgeTable` delegates to `dropTable`, so for a format that does not override+it the two paths remove the same things -- but Lance overrides both, and its purge deletes data its+drop does not. A provider must not assume the two are interchangeable.++##### A worked example: a provider that allocates++A provider backed by an external path-allocation service is the case this interface exists for, and it+makes the boundary concrete.++On `provisionTableLocation` the provider asks the service for a path the table is permitted to use.+The service validates the request, creates on demand whatever container the path needs -- shared by+many tables, coarser than one table, and never removed for one -- records an entry in a registry+saying which table holds the path, and returns the path. The provider returns that string and nothing+else happens: no dataset is created, and the catalog stores the value verbatim.++The table format then creates its dataset at that path, and later, when the table is dropped or+purged, deletes it. Neither step involves the provider.++On `unprovisionTableLocation` the provider deletes the registry entry, which is also what frees the+name so the path can be issued again. The only storage object it touches is the empty directory marker+it created itself, and only after establishing that nothing else is under the prefix; if anything else+is there it leaves the prefix alone. It never deletes the dataset -- by then the format already has.++The built-in provider is the same contract with the allocation set empty. It composes a path from+configuration, holds no reservation and no registry entry, and therefore has nothing to hand back,+which is why its `unprovisionTableLocation` body is empty. That is the correct implementation for a+provider of that shape, and it is also exactly what this catalog did before this interface existed.++**Known limitations.** Six of them, and they all point the same way: a provider that manages real+storage needs its own reconciliation against the catalog, and cannot treat these callbacks as a+complete record of the locations it handed out.++- `location` is a mutable table property, so `alterTable(setProperty("location", ...))` repoints a+ table without the provider being told. The old location is never unprovisioned and the new one+ never went through the provider.+- `provisionTableLocation` runs before the table is actually created, so a creation that fails+ afterwards -- a table that already exists, or a failure inside the table format itself -- leaves a+ location provisioned for a table that does not exist. There is no compensating unprovision, and+ that is deliberate: a table format that fails partway through creation may already have written to+ the location, and unprovisioning would then tell the provider it may reclaim a path that has data+ on it. Leaking an unused path is the safer of the two failures, and doing better would need the+ format to report whether it touched storage before failing, which the interface cannot express.+ The table format itself compensates where it can: Lance deletes the dataset it just created when+ the metadata write then fails. Everything the catalog can check on its own -- the table format is+ given, the format is supported -- is checked before the provider is consulted, so the cases that+ remain are the ones only the table format can detect.+- A location that is provisioned but then not used is not handed back either. A creation mode such+ as Lance's `EXIST_OK` returns the table that already exists, at the location it already has, and+ the location provisioned for that call goes nowhere; a client retrying a create is the ordinary+ way to reach it. Detecting that from the catalog would mean comparing two location strings and+ concluding from the comparison what a provider did internally, which is exactly the inference this+ interface leaves to the provider, so an allocating provider reconciles these along with the+ failures above.+- A provider deriving a deterministic path from a table's identity hands out the same path again+ when a table of the same name is created after the old one is gone, and the built-in provider is+ one such provider. If anything survived under that path -- a drop whose data deletion failed, or a+ format-internal drop as below -- the next creation of that name fails inside the table format+ rather than in the provider, and keeps failing, because every retry derives the same path.+ Clearing what was left behind is outside what this interface can see or do.+- A table format that drops a table through its own internals rather than through the catalog does+ not trigger the unprovision callback. Lance's `OVERWRITE` creation mode does this: it drops the+ existing table and creates a new one, so the old location is never handed back. This is the same+ shape as the cascading schema drop, which the catalog does route through its own `dropTable`, but+ a format-internal drop is not visible to the catalog at all.+- `alterTable(rename(...))` changes a table's identity without telling the provider, and without+ moving any data. A provider deriving the path from the table name is left with a path that no+ longer matches the name, which is cosmetic. A provider that books allocations against+ `(schema, table)` loses the table altogether: the drop that follows arrives under the new name,+ and the allocation booked under the old one is never handed back. Such a provider has to reconcile+ renames out of band, or the deployment has to forbid renaming tables in this catalog.++Two constraints follow from `ServiceLoader` discovery:++- The implementation needs a public no-argument constructor that is cheap and does not throw.+ Selecting a provider means asking each candidate its name, and `name()` is an instance method, so+ every provider on the classpath is constructed once, per catalog, before the named one is+ selected -- including when the provider being constructed is not the one selected. A constructor+ that throws costs that provider the ability to be selected at all. Put clients, connection pools+ and other expensive setup out of the constructor and create them lazily on first use, since the+ candidates that are not selected are discarded and there is no close callback to release anything+ they took.+- `name()` must be unique across the classpath and must not be `default`, which is reserved by the+ built-in provider. If two providers share a name, every catalog selecting that name fails to+ initialize. A candidate whose constructor or `name()` throws is logged and skipped, so one+ misbehaving provider does not stop a catalog that named a different one. A services file naming a+ class that cannot be loaded at all is not survivable in the same way: it fails the scan before any+ candidate is reached.#### Key Property: `location`The `location` property specifies the root directory for the lakehouse table. All schemas and tables are stored under this location unless explicitly overridden at the schema or table level.-**Location Resolution Hierarchy:**+**Location Resolution Hierarchy** (applies to the built-in provider; a custom+`table-location-provider` defines its own):1. Table-level `location` (highest priority)2. Schema-level `location`, then the location of the table will be `{schema_location}/{table_name}`3. Catalog-level `location` (fallback), then the location of the table will be `{catalog_location}/{schema_name}/{table_name}`@@ -201,3 +440,19 @@ For additional operations, refer to [Schema Operations documentation](./manage-cSince different lakehouse table formats have varying capabilities, table operation support may differ. The following are table operations for different lakehouse formats:- [Lance Format Support](./lakehouse-generic-lance-table.md)++### Dropping a table that does not exist++Dropping or purging a table this catalog does not have answers `200` with `{"dropped": false}`. It+previously answered `404 NoSuchTableException`.++This is a wire-level change for clients that treated a repeated `DELETE` as an error: such a request+now succeeds with `dropped: false`. The new response is what `TableCatalog.dropTable` documents+("False if the table does not exist") and what the other catalogs already return, so this catalog+was the one out of step.++:::note+Introduced together with the [pluggable table location+provider](#pluggable-table-location-provider), whose drop path reads the table before removing it+so that the location can be handed back.+:::