laserninja commented on code in PR #13153: URL: https://github.com/apache/gravitino/pull/13153#discussion_r4074219862
########## 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: Fixed in 7446e95d0. The ancestor walk now includes the table root and stops there. It uses the normalized lexical table root as the boundary, since a warehouse parent symlink can change the resolved path; resolved-path containment is still checked separately. Added regression tests for parent symlinks, inaccessible parents, normalized paths, whole-table scans, and rejection of symlinks within the table. ########## 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: Checked the source: these are already declared as `Deque<Path>` and `RemoteIterator<FileStatus>`. No raw types remain at these sites; the jobs build and formatting checks pass. ########## 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: Updated in 7446e95d0: added `VERSION` and extracted `buildArguments()` and `buildSparkConfigs()` to match the sibling jobs. ########## 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: Verified that this is already declared as `Iterator<Row> results = spark.sql(sql).toLocalIterator();`. No change was needed here. ########## 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: Compared the header directly with `IcebergExpireSnapshotsJob`: they match exactly, including the spacing in `agreements. See` and the license URL indentation. Left the matching header unchanged. ########## 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: Updated all four new test classes and their test methods to `public` in 7446e95d0. All 165 jobs tests pass, including the new regression tests. -- 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]
