lasdf1234 commented on code in PR #13153:
URL: https://github.com/apache/gravitino/pull/13153#discussion_r4011751815


##########
maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRemoveOrphanFilesJob.java:
##########
@@ -0,0 +1,251 @@
+/*
+ * 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.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
+   * @throws IOException if a location cannot be validated
+   * @throws AnalysisException if the table identifier is invalid or the table 
does not exist
+   */
+  public static void main(String[] args) throws IOException, AnalysisException 
{
+    Map<String, String> options = IcebergJobUtils.parseArguments(args);

Review Comment:
   public static void main(String[] args) {
     if (args.length < 4) {
       printUsage();
       System.exit(1);
     }
   
     Map<String, String> options = IcebergJobUtils.parseArguments(args);
     String catalogName = options.get("catalog");
     String tableIdentifier = options.get("table");
     if (catalogName == null || tableIdentifier == null) {
       System.err.println("Error: --catalog and --table are required 
arguments");
       printUsage();
       System.exit(1);
     }
   
     try {
       parseDryRun(options.get("dry-run"));
     } catch (IllegalArgumentException e) {
       System.err.println("Error: " + e.getMessage());
       printUsage();
       System.exit(1);
     }
   
     SparkSession.Builder builder =
         SparkSession.builder().appName("Gravitino Built-in Iceberg Remove 
Orphan Files");
     IcebergJobUtils.applyIcebergRestAuth(builder, catalogName, null);
   
     String sparkConfJson = options.get("spark-conf");
     if (sparkConfJson != null && !sparkConfJson.isEmpty()) {
       try {
         Map<String, String> customConfigs = 
IcebergJobUtils.parseCustomSparkConfigs(sparkConfJson);
         customConfigs.forEach(builder::config);
         System.out.println("Applied custom Spark configurations: " + 
customConfigs);
       } catch (IllegalArgumentException e) {
         System.err.println("Error: " + e.getMessage());
         printUsage();
         System.exit(1);
       }
     }
   
     SparkSession spark = builder.getOrCreate();
     try {
       IcebergJobUtils.requireIcebergSparkRuntime();
     } catch (IllegalStateException e) {
       System.err.println("Error: " + e.getMessage());
       spark.stop();
       System.exit(1);
     }
   
     try {
       long count = execute(spark, options);
       System.out.printf("Remove orphan files completed: %d files%n", count);
     } catch (Exception e) {
       System.err.println("Error executing remove orphan files job: " + 
e.getMessage());
       e.printStackTrace();
       System.exit(1);
     } finally {
       spark.stop();
     }
   }
   
   private static void printUsage() {
     System.err.println(
         "Usage: IcebergRemoveOrphanFilesJob --catalog <name> --table 
<db.table> "
             + "[--older-than 'yyyy-MM-dd HH:mm:ss'] [--location <path>] "
             + "[--dry-run true|false] [--spark-conf <json>]");
   }
   
   The above code is merely a suggestion.Please align main() with 
IcebergExpireSnapshotsJob: no checked exceptions on main, add printUsage() + 
System.exit(1) for CLI errors, wrap execute() in try/catch/finally with 
spark.stop().
   
   



-- 
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]

Reply via email to