lasdf1234 commented on code in PR #13153: URL: https://github.com/apache/gravitino/pull/13153#discussion_r4068928938
########## maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/RemoteLocationValidator.java: ########## @@ -0,0 +1,74 @@ +/* + * 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.maintenance.jobs.iceberg; + +import com.google.common.base.Preconditions; +import java.io.IOException; +import java.util.ArrayDeque; +import java.util.Deque; +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.fs.FileStatus; +import org.apache.hadoop.fs.FileSystem; +import org.apache.hadoop.fs.Path; +import org.apache.hadoop.fs.RemoteIterator; + +/** Validates scan paths on Hadoop filesystems that can resolve symbolic links. */ +final class RemoteLocationValidator { + private RemoteLocationValidator() {} + + static void validate(Configuration conf, String tableLocation, String location) + throws IOException { + Path scan = new Path(location); + FileSystem fs = scan.getFileSystem(conf); + validate(fs, new Path(tableLocation), scan); + } + + static void validate(FileSystem fs, Path tableLocation, Path scan) throws IOException { + // Object stores do not support symbolic links. The URI containment check is sufficient there. + if (!fs.supportsSymlinks()) { + return; + } + Path root = fs.resolvePath(tableLocation); + IcebergRemoveOrphanFilesJob.validateLocation(root.toString(), fs.resolvePath(scan).toString()); + for (Path ancestor = scan; ancestor != null; ancestor = ancestor.getParent()) { + Preconditions.checkArgument( + !fs.getFileLinkStatus(ancestor).isSymlink(), + "Symlinks are not allowed in the scan location"); + } + Deque<Path> pending = new ArrayDeque<>(); + pending.add(scan); Review Comment: Raw types here (`Deque pending`, `RemoteIterator children` below) may trip checkstyle. Please parameterize, e.g. `Deque<Path>` and `RemoteIterator<FileStatus>`. ########## maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/RemoteLocationValidator.java: ########## @@ -0,0 +1,74 @@ +/* + * 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.maintenance.jobs.iceberg; + +import com.google.common.base.Preconditions; +import java.io.IOException; +import java.util.ArrayDeque; +import java.util.Deque; +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.fs.FileStatus; +import org.apache.hadoop.fs.FileSystem; +import org.apache.hadoop.fs.Path; +import org.apache.hadoop.fs.RemoteIterator; + +/** Validates scan paths on Hadoop filesystems that can resolve symbolic links. */ +final class RemoteLocationValidator { + private RemoteLocationValidator() {} + + static void validate(Configuration conf, String tableLocation, String location) + throws IOException { + Path scan = new Path(location); + FileSystem fs = scan.getFileSystem(conf); + validate(fs, new Path(tableLocation), scan); + } + + static void validate(FileSystem fs, Path tableLocation, Path scan) throws IOException { + // Object stores do not support symbolic links. The URI containment check is sufficient there. + if (!fs.supportsSymlinks()) { + return; + } + Path root = fs.resolvePath(tableLocation); + IcebergRemoveOrphanFilesJob.validateLocation(root.toString(), fs.resolvePath(scan).toString()); + for (Path ancestor = scan; ancestor != null; ancestor = ancestor.getParent()) { Review Comment: This ancestor symlink loop walks from the scan path all the way to the filesystem root. `validateLocalLocation` correctly bounds the walk to ancestors under the table root (`ancestor.startsWith(lexicalRoot)`). On HDFS and other symlink-capable filesystems, a legitimate warehouse parent symlink (or an unreadable ancestor above the table) can cause `getFileLinkStatus` to fail before `remove_orphan_files` runs, even when the scan directory is inside the table location. Suggest mirroring the local validator and stopping at the resolved table root. ########## maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRemoveOrphanFilesJob.java: ########## @@ -0,0 +1,280 @@ +/* + * 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.maintenance.jobs.iceberg; + +import static org.apache.spark.sql.functions.lit; + +import com.google.common.base.Preconditions; +import java.io.IOException; +import java.net.URI; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Arrays; +import java.util.Collections; +import java.util.Iterator; +import java.util.Map; +import java.util.Objects; +import java.util.stream.Stream; +import javax.annotation.Nullable; +import org.apache.gravitino.job.JobTemplateProvider; +import org.apache.gravitino.job.SparkJobTemplate; +import org.apache.gravitino.maintenance.jobs.BuiltInJob; +import org.apache.gravitino.maintenance.optimizer.common.util.IcebergSparkConfigUtils; +import org.apache.iceberg.Table; +import org.apache.iceberg.spark.Spark3Util; +import org.apache.spark.sql.AnalysisException; +import org.apache.spark.sql.Row; +import org.apache.spark.sql.SparkSession; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** Removes unreferenced Iceberg files after validating the requested scan location. */ +public class IcebergRemoveOrphanFilesJob implements BuiltInJob { + private static final Logger LOG = LoggerFactory.getLogger(IcebergRemoveOrphanFilesJob.class); + private static final String NAME = + JobTemplateProvider.BUILTIN_NAME_PREFIX + "iceberg-remove-orphan-files"; + + @Override + public SparkJobTemplate jobTemplate() { + return SparkJobTemplate.builder() + .withName(NAME) + .withComment("Built-in Iceberg orphan file cleanup job template") + .withExecutable(resolveExecutable(IcebergRemoveOrphanFilesJob.class)) + .withClassName(IcebergRemoveOrphanFilesJob.class.getName()) + .withArguments( + Arrays.asList( + "--catalog", + "{{catalog_name}}", + "--table", + "{{table_identifier}}", + "--older-than", + "{{older_than}}", + "--location", + "{{location}}", + "--dry-run", + "{{dry_run}}", + "--spark-conf", + "{{spark_conf}}")) + .withConfigs(IcebergSparkConfigUtils.buildTemplateSparkConfigs()) + .withCustomFields(Collections.singletonMap(JobTemplateProvider.PROPERTY_VERSION_KEY, "v1")) Review Comment: Sibling jobs (`IcebergExpireSnapshotsJob`, `IcebergRewriteDataFilesJob`) use a `VERSION` constant plus `buildArguments()` / `buildSparkConfigs()` helpers instead of inlining `"v1"` and the argument list here. Worth aligning for consistency. ########## maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRemoveOrphanFilesJob.java: ########## @@ -0,0 +1,280 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file Review Comment: License header spacing should match sibling files: `agreements. See` (two spaces before `See`), and double space after `http://www.apache.org/licenses/LICENSE-2.0`. ########## maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRemoveOrphanFilesJob.java: ########## @@ -0,0 +1,280 @@ +/* + * 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.maintenance.jobs.iceberg; + +import static org.apache.spark.sql.functions.lit; + +import com.google.common.base.Preconditions; +import java.io.IOException; +import java.net.URI; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Arrays; +import java.util.Collections; +import java.util.Iterator; +import java.util.Map; +import java.util.Objects; +import java.util.stream.Stream; +import javax.annotation.Nullable; +import org.apache.gravitino.job.JobTemplateProvider; +import org.apache.gravitino.job.SparkJobTemplate; +import org.apache.gravitino.maintenance.jobs.BuiltInJob; +import org.apache.gravitino.maintenance.optimizer.common.util.IcebergSparkConfigUtils; +import org.apache.iceberg.Table; +import org.apache.iceberg.spark.Spark3Util; +import org.apache.spark.sql.AnalysisException; +import org.apache.spark.sql.Row; +import org.apache.spark.sql.SparkSession; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** Removes unreferenced Iceberg files after validating the requested scan location. */ +public class IcebergRemoveOrphanFilesJob implements BuiltInJob { + private static final Logger LOG = LoggerFactory.getLogger(IcebergRemoveOrphanFilesJob.class); + private static final String NAME = + JobTemplateProvider.BUILTIN_NAME_PREFIX + "iceberg-remove-orphan-files"; + + @Override + public SparkJobTemplate jobTemplate() { + return SparkJobTemplate.builder() + .withName(NAME) + .withComment("Built-in Iceberg orphan file cleanup job template") + .withExecutable(resolveExecutable(IcebergRemoveOrphanFilesJob.class)) + .withClassName(IcebergRemoveOrphanFilesJob.class.getName()) + .withArguments( + Arrays.asList( + "--catalog", + "{{catalog_name}}", + "--table", + "{{table_identifier}}", + "--older-than", + "{{older_than}}", + "--location", + "{{location}}", + "--dry-run", + "{{dry_run}}", + "--spark-conf", + "{{spark_conf}}")) + .withConfigs(IcebergSparkConfigUtils.buildTemplateSparkConfigs()) + .withCustomFields(Collections.singletonMap(JobTemplateProvider.PROPERTY_VERSION_KEY, "v1")) + .build(); + } + + /** + * Runs orphan file cleanup using named arguments. + * + * <p>Required: {@code --catalog name --table db.table}. Optional: {@code --older-than 'yyyy-MM-dd + * HH:mm:ss'}, {@code --location path}, {@code --dry-run true|false}, and {@code --spark-conf + * json}. The cutoff defaults to three days ago and dry-run defaults to false. Iceberg's minimum + * retention interval is preserved. A custom location must be within the table. + * + * @param args named command-line arguments + */ + public static void main(String[] args) { + int exitCode = run(args); + if (exitCode != 0) { + System.exit(exitCode); + } + } + + static int run(String[] args) { + Map<String, String> options = IcebergJobUtils.parseArguments(args); + SparkSession.Builder builder = + SparkSession.builder().appName("Gravitino Built-in Iceberg Remove Orphan Files"); + try { + requireOption(options, "catalog"); + requireOption(options, "table"); + parseDryRun(options.get("dry-run")); + IcebergJobUtils.parseCustomSparkConfigs(options.get("spark-conf")).forEach(builder::config); + } catch (IllegalArgumentException e) { + LOG.error("Invalid remove orphan files job arguments: {}", e.getMessage()); + printUsage(); + return 1; + } + + SparkSession spark = null; + try { + spark = builder.getOrCreate(); + IcebergJobUtils.requireIcebergSparkRuntime(); + execute(spark, options); + return 0; + } catch (IOException | AnalysisException | RuntimeException e) { + LOG.error("Error executing remove orphan files job", e); + return 1; + } finally { + if (spark != null) { + spark.stop(); + } + } + } + + static long execute(SparkSession spark, Map<String, String> options) + throws IOException, AnalysisException { + String catalog = requireOption(options, "catalog"); + String identifier = requireOption(options, "table"); + boolean dryRun = parseDryRun(options.get("dry-run")); + // Backslash escapes in string literals must retain Spark's default interpretation. + Preconditions.checkArgument( + !Boolean.parseBoolean(spark.conf().get("spark.sql.parser.escapedStringLiterals", "false")), + "spark.sql.parser.escapedStringLiterals must be false"); + Table table = + Spark3Util.loadIcebergTable( + spark, IcebergJobUtils.escapeSqlIdentifier(catalog) + "." + identifier); + String location = options.getOrDefault("location", table.location()); + validateLocation(table.location(), location); + validateLocalLocation(table.location(), location); + validateRemoteLocation(spark, table.location(), location); + String sql = + buildProcedureCall( + catalog, + identifier, + options.get("older-than"), + normalizeLocation(location).toString(), + dryRun); + Iterator<Row> results = spark.sql(sql).toLocalIterator(); Review Comment: Please use a parameterized type, e.g. `Iterator<Row> results = spark.sql(sql).toLocalIterator();` — raw `Iterator` may fail checkstyle. ########## maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRemoveOrphanFilesJob.java: ########## @@ -0,0 +1,93 @@ +/* + * 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.maintenance.jobs.iceberg; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.apache.gravitino.maintenance.jobs.BuiltInJobTemplateProvider; +import org.junit.jupiter.api.Test; + +class TestIcebergRemoveOrphanFilesJob { + @Test Review Comment: Sibling test classes use `public class TestXxx` and `public void testXxx()` — please match that convention (same for the other new test classes in this PR). -- 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]
