roryqi commented on code in PR #11364: URL: https://github.com/apache/gravitino/pull/11364#discussion_r3345798581
########## iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergCleanupHelper.java: ########## @@ -0,0 +1,79 @@ +/* + * 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.iceberg.service.dispatcher; + +import java.util.Optional; +import org.apache.gravitino.GravitinoEnv; +import org.apache.gravitino.NameIdentifier; +import org.apache.gravitino.iceberg.service.authorization.IcebergRESTServerContext; +import org.apache.gravitino.iceberg.service.cleanup.IcebergCleanupManager; +import org.apache.iceberg.catalog.Namespace; +import org.apache.iceberg.exceptions.AlreadyExistsException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** Request-path helpers shared by the table and namespace executors for async table purge. */ +final class IcebergCleanupHelper { + + private static final Logger LOG = LoggerFactory.getLogger(IcebergCleanupHelper.class); + + private IcebergCleanupHelper() {} + + /** + * Returns the catalog entity id for {@code catalogName}. The catalog is already loaded for the + * current request, so this reads its in-memory entity without an extra entity-store lookup. + */ + static long catalogId(String catalogName) { + String metalake = IcebergRESTServerContext.getInstance().metalakeName(); + return GravitinoEnv.getInstance() + .catalogManager() + .loadCatalogAndWrap(NameIdentifier.of(metalake, catalogName)) + .catalog() + .entity() + .id(); + } + + /** + * Fails a create or register with {@code 409} while a cleanup job still holds the identifier. + * Reusing the name before its files are gone would let the new table share the old table's + * storage prefix. A name with no resolvable catalog entity cannot have a cleanup job, so it stays + * usable. + */ + static void rejectIfBeingPurged( + Optional<IcebergCleanupManager> cleanupManager, + String catalogName, + Namespace namespace, + String tableName) { + if (cleanupManager.isEmpty()) { + return; + } + long catalogId; + try { + catalogId = catalogId(catalogName); + } catch (RuntimeException e) { + LOG.debug("No catalog id for {}; skipping purge check", catalogName, e); Review Comment: Done — changed to `LOG.warn` in c7c4cb7e8. ########## iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/listener/api/event/IcebergRequestContext.java: ########## @@ -113,6 +116,24 @@ public Map<String, String> httpHeaders() { return httpHeaders; } + /** + * Checks whether this request opted into asynchronous table purge. + * + * <p>Async purge is opt-in. Standard Iceberg clients send no header and keep synchronous purge + * behavior; a client opts in with {@code X-Gravitino-Async-Purge: True}. + * + * @return true only when the async purge header explicitly says {@code True} + */ + public boolean asyncPurge() { + for (Map.Entry<String, String> header : httpHeaders.entrySet()) { + // HTTP header names are case-insensitive; the value is matched exactly as "True". + if (ASYNC_PURGE_HEADER.equalsIgnoreCase(header.getKey())) { + return "True".equals(header.getValue().trim()); Review Comment: We switched to lowercase `true`. There is no HTTP standard mandating a `True` capitalization for a boolean header value, so the value is now matched exactly as `true` (case-sensitive, per RFC 7230 header-value semantics). Updated the parser, docs, and tests in 2676b2dc5. ########## iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/RESTService.java: ########## @@ -198,11 +220,14 @@ public void serviceInit(Map<String, String> properties, boolean auxMode) { @Override public void serviceStart() { icebergMetricsManager.start(); + cleanupManager.ifPresent(IcebergCleanupManager::start); if (server != null) { try { server.start(); LOG.info("Iceberg REST service started"); } catch (Exception e) { + // Stop the cleanup workers we just started so they don't outlive a failed startup. + cleanupManager.ifPresent(IcebergCleanupManager::close); throw new RuntimeException(e); Review Comment: Good catch — the catch block now also closes the metrics manager (c7c4cb7e8), so a failed `server.start()` leaks neither the cleanup workers nor the metrics threads. ########## iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/integration/test/IcebergRESTAsyncPurgeIT.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.iceberg.integration.test; + +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Maps; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.stream.Stream; +import org.apache.gravitino.Catalog; +import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergConstants; +import org.apache.gravitino.client.GravitinoMetalake; +import org.apache.gravitino.iceberg.common.IcebergConfig; +import org.apache.gravitino.integration.test.container.ContainerSuite; +import org.apache.gravitino.integration.test.util.BaseIT; +import org.apache.gravitino.integration.test.util.TestDatabaseName; +import org.apache.gravitino.listener.api.event.IcebergRequestContext; +import org.apache.hadoop.conf.Configuration; +import org.apache.iceberg.CatalogProperties; +import org.apache.iceberg.DataFile; +import org.apache.iceberg.DataFiles; +import org.apache.iceberg.FileFormat; +import org.apache.iceberg.PartitionSpec; +import org.apache.iceberg.Schema; +import org.apache.iceberg.Table; +import org.apache.iceberg.catalog.Namespace; +import org.apache.iceberg.catalog.TableIdentifier; +import org.apache.iceberg.exceptions.AlreadyExistsException; +import org.apache.iceberg.io.OutputFile; +import org.apache.iceberg.io.PositionOutputStream; +import org.apache.iceberg.rest.RESTCatalog; +import org.apache.iceberg.types.Types; +import org.awaitility.Awaitility; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * End-to-end test for async table purge. A table dropped with {@code purgeRequested=true} plus the + * {@link IcebergRequestContext#ASYNC_PURGE_HEADER} should keep its files on disk while the drop + * returns, block recreating the same name with {@code 409} until cleanup finishes, and have its + * files deleted by the background worker. + * + * <p>It drives the server with the {@link RESTCatalog} client, not Spark: Spark purges files + * client-side and sends {@code purgeRequested=false}, which skips the server-side path. It uses the + * dynamic config provider over a PostgreSQL-backed {@code lakehouse-iceberg} catalog with a local + * {@code file://} warehouse, since cleanup jobs are keyed by catalog id and the files must be + * visible on disk. + */ +public class IcebergRESTAsyncPurgeIT extends BaseIT { + + private static final Logger LOG = LoggerFactory.getLogger(IcebergRESTAsyncPurgeIT.class); + private static final String GRAVITINO_ICEBERG_REST_PREFIX = "gravitino.iceberg-rest."; + private static final String METALAKE_NAME = "async_cleanup_metalake"; + private static final String CATALOG_NAME = "iceberg_cleanup"; + private static final String USER = "test"; + private static final String DATABASE_NAME = "purge_db"; + private static final String TABLE_NAME = "t_async"; + // Poll interval large enough that the background worker provably cannot claim the job during the + // synchronous in-flight assertions, yet small enough to keep the eventual-cleanup wait short. + private static final int CLEANUP_POLL_INTERVAL_SECS = 5; + + private static final Schema SCHEMA = + new Schema( + Types.NestedField.required(1, "id", Types.LongType.get()), + Types.NestedField.optional(2, "data", Types.StringType.get())); + + private static final ContainerSuite CONTAINER_SUITE = ContainerSuite.getInstance(); + + private Path warehouseDir; + private RESTCatalog restCatalog; + + @BeforeAll + @Override + public void startIntegrationTest() throws Exception { + CONTAINER_SUITE.startPostgreSQLContainer(TestDatabaseName.PG_ICEBERG_ASYNC_CLEANUP_IT); + warehouseDir = Files.createTempDirectory("gravitino-iceberg-async-cleanup"); + ignoreIcebergAuxRestService = false; + + // Simple authentication so the dynamic config provider can authenticate to Gravitino and the + // REST client can identify itself; authorization stays disabled to keep the test focused. + customConfigs.put("gravitino.authenticators", "simple"); + customConfigs.put("SimpleAuthUserName", USER); + customConfigs.put( + GRAVITINO_ICEBERG_REST_PREFIX + IcebergConstants.ICEBERG_REST_CATALOG_CONFIG_PROVIDER, + IcebergConstants.DYNAMIC_ICEBERG_CATALOG_CONFIG_PROVIDER_NAME); + customConfigs.put( + GRAVITINO_ICEBERG_REST_PREFIX + IcebergConstants.GRAVITINO_METALAKE, METALAKE_NAME); + customConfigs.put( + GRAVITINO_ICEBERG_REST_PREFIX + IcebergConstants.ICEBERG_REST_DEFAULT_DYNAMIC_CATALOG_NAME, + CATALOG_NAME); + customConfigs.put( + GRAVITINO_ICEBERG_REST_PREFIX + IcebergConstants.GRAVITINO_SIMPLE_USERNAME, USER); + customConfigs.put( + GRAVITINO_ICEBERG_REST_PREFIX + IcebergConfig.ASYNC_CLEANUP_POLL_INTERVAL_SECS.getKey(), + String.valueOf(CLEANUP_POLL_INTERVAL_SECS)); + + super.startIntegrationTest(); + initMetalakeAndCatalog(); + initRESTCatalog(); + } + + @AfterAll + @Override + public void stopIntegrationTest() throws IOException, InterruptedException { + if (restCatalog != null) { + try { + restCatalog.close(); + } catch (IOException e) { + LOG.warn("Failed to close Iceberg REST catalog", e); + } + restCatalog = null; + } + try { + client.dropMetalake(METALAKE_NAME, true); + } catch (Exception e) { + LOG.warn("Failed to drop metalake {}", METALAKE_NAME, e); + } + super.stopIntegrationTest(); Review Comment: Done — `stopIntegrationTest()` now deletes the temp warehouse directory via `FileUtils.deleteQuietly` (c7c4cb7e8). ########## iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/listener/api/event/IcebergRequestContext.java: ########## @@ -113,6 +116,24 @@ public Map<String, String> httpHeaders() { return httpHeaders; } + /** + * Checks whether this request opted into asynchronous table purge. + * + * <p>Async purge is opt-in. Standard Iceberg clients send no header and keep synchronous purge + * behavior; a client opts in with {@code X-Gravitino-Async-Purge: True}. + * + * @return true only when the async purge header explicitly says {@code True} Review Comment: Fixed — the implementation, tests, and docs now consistently use lowercase `true` (2676b2dc5). ########## docs/iceberg-rest-service.md: ########## @@ -91,6 +91,28 @@ Please note that, it only takes affect in `gravitino.conf`, you don't need to sp The filter in `customFilters` should be a standard javax servlet filter. You can also specify filter parameters by setting configuration entries in the style `gravitino.iceberg-rest.<class name of filter>.param.<param name>=<value>`. +### Table purge behavior + +When a client drops a table with `purgeRequested=true`, Gravitino keeps the existing synchronous behavior by default: the catalog entry and the table files are removed before the `DELETE` request returns. + +When the Iceberg REST service runs as an auxiliary service inside Gravitino, an async cleanup worker pool starts automatically and reuses the Gravitino entity store relational backend. In standalone mode, async cleanup is not available and purge requests always run synchronously. + +In auxiliary mode, a client can opt in to asynchronous file cleanup per request by sending the HTTP header `X-Gravitino-Async-Purge: true` together with `DELETE ...?purgeRequested=true`. The server then removes the catalog entry before returning `204 No Content`, records a durable cleanup job in the Gravitino relational backend, and deletes the table files in the background. While an active cleanup job exists for a table identifier, `createTable` and `registerTable` for the same catalog, namespace, and table return `409 Conflict`; after the cleanup job reaches a terminal state the identifier can be reused. Review Comment: Agreed — I could not find an HTTP standard that prescribes a `True` capitalization for a boolean header value, so I have standardized on lowercase `true` (exact, case-sensitive match per RFC 7230). Done in 2676b2dc5. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
