Skip to content

World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.

[#14811] improvement(maintenance): Unify Iceberg CLI usage and drop thin helpers (#14813)

MaSaied342796850c
diff --git a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergExpireSnapshotsJob.java b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergExpireSnapshotsJob.java
index 914c19bcb3..df0bf02df3 100644
--- a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergExpireSnapshotsJob.java
+++ b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergExpireSnapshotsJob.java
@@ -19,6 +19,7 @@
package org.apache.gravitino.maintenance.jobs.iceberg;
import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
@@ -63,7 +64,7 @@ public class IcebergExpireSnapshotsJob implements BuiltInJob, IcebergMaintenance
.withExecutable(resolveExecutable(IcebergExpireSnapshotsJob.class))
.withClassName(IcebergExpireSnapshotsJob.class.getName())
.withArguments(buildArguments())
- .withConfigs(buildSparkConfigs())
+ .withConfigs(IcebergSparkConfigUtils.buildTemplateSparkConfigs())
.withCustomFields(
Collections.singletonMap(JobTemplateProvider.PROPERTY_VERSION_KEY, VERSION))
.build();
@@ -216,8 +217,10 @@ public class IcebergExpireSnapshotsJob implements BuiltInJob, IcebergMaintenance
SparkSession spark, String catalogName, String tableIdentifier) {
long snapshotId = IcebergJobUtils.requireCurrentSnapshotId(spark, catalogName, tableIdentifier);
preExpireData = collectTableData(spark, catalogName, tableIdentifier);
- Map<String, Object> payload = expireBeforeMetrics(preExpireData.snapshotCount());
- return TableSnapshotMetrics.of(snapshotId, payload);
+ Map<String, Object> metrics = new HashMap<>();
+ metrics.put(
+ IcebergSnapshotExpirationContent.SNAPSHOT_NUMBER_METRIC, preExpireData.snapshotCount());
+ return TableSnapshotMetrics.of(snapshotId, metrics);
}
@Override
@@ -251,11 +254,15 @@ public class IcebergExpireSnapshotsJob implements BuiltInJob, IcebergMaintenance
PreExpireData after = collectTableData(spark, catalogName, tableIdentifier);
PreExpireData beforeData = preExpireData == null ? after : preExpireData;
preExpireData = null;
+ Map<String, Object> metrics = new HashMap<>();
+ metrics.put(
+ IcebergSnapshotExpirationContent.EXPIRED_SNAPSHOT_NUMBER_METRIC,
+ snapshotsCleared(beforeData.snapshotIds(), after.snapshotIds()));
+ metrics.put(
+ IcebergSnapshotExpirationContent.EXPIRED_FILE_SIZE_METRIC,
+ bytesReclaimed(beforeData.fileSizesByPath(), after.fileSizesByPath()));
return TableSnapshotMetrics.of(
- IcebergJobUtils.currentSnapshotIdOrEmpty(spark, catalogName, tableIdentifier),
- expireAfterMetrics(
- snapshotsCleared(beforeData.snapshotIds(), after.snapshotIds()),
- bytesReclaimed(beforeData.fileSizesByPath(), after.fileSizesByPath())));
+ IcebergJobUtils.currentSnapshotIdOrEmpty(spark, catalogName, tableIdentifier), metrics);
}
/**
@@ -347,39 +354,33 @@ public class IcebergExpireSnapshotsJob implements BuiltInJob, IcebergMaintenance
/** Print usage information. */
private static void printUsage() {
- System.err.println(
- "Usage: IcebergExpireSnapshotsJob [OPTIONS]\n"
- + "\n"
- + "Required Options:\n"
- + " --catalog <name> Iceberg catalog name registered in Spark\n"
- + " --table <identifier> Fully qualified table name (e.g., db.table_name)\n"
- + "\n"
- + "Optional Options:\n"
- + " --older-than <timestamp> Expire snapshots older than this timestamp\n"
- + " Example: '2024-01-01 00:00:00'\n"
- + " Default: 5 days ago (Iceberg default)\n"
- + " --retain-last <count> Number of most recent snapshots to retain\n"
- + " Must be a positive integer (>= 1)\n"
- + " Default: 1 (Iceberg default)\n"
- + " --stream-results [bool] Stream intermediate delete results (true or false)\n"
- + " A bare --stream-results means true\n"
- + " --spark-conf <json> JSON map of custom Spark configurations\n"
- + " Example: '{\"spark.sql.shuffle.partitions\":\"200\"}'\n"
- + " Note: Overriding required catalog/extensions/app-name configs is unsupported\n"
- + "\n"
- + "Examples:\n"
- + " # Basic expire with defaults (5 days, retain 1)\n"
- + " --catalog iceberg_prod --table db.sample\n"
- + "\n"
- + " # Expire snapshots older than a specific date\n"
- + " --catalog iceberg_prod --table db.sample --older-than '2024-01-01 00:00:00'\n"
- + "\n"
- + " # Retain the last 5 snapshots\n"
- + " --catalog iceberg_prod --table db.sample --retain-last 5\n"
- + "\n"
- + " # Expire with all options and streaming\n"
- + " --catalog iceberg_prod --table db.sample --older-than '2024-06-01 00:00:00' \\\n"
- + " --retain-last 3 --stream-results");
+ IcebergJobUtils.printCliUsage(
+ IcebergExpireSnapshotsJob.class.getSimpleName(),
+ ImmutableList.of(
+ " --catalog <name> Iceberg catalog name registered in Spark",
+ " --table <identifier> Fully qualified table name (e.g., db.table_name)"),
+ IcebergJobUtils.withSparkConfUsage(
+ " --older-than <timestamp> Expire snapshots older than this timestamp",
+ " Example: '2024-01-01 00:00:00'",
+ " Default: 5 days ago (Iceberg default)",
+ " --retain-last <count> Number of most recent snapshots to retain",
+ " Must be a positive integer (>= 1)",
+ " Default: 1 (Iceberg default)",
+ " --stream-results [bool] Stream intermediate delete results (true or false)",
+ " A bare --stream-results means true"),
+ ImmutableList.of(
+ " # Basic expire with defaults (5 days, retain 1)",
+ " --catalog iceberg_prod --table db.sample",
+ "",
+ " # Expire snapshots older than a specific date",
+ " --catalog iceberg_prod --table db.sample --older-than '2024-01-01 00:00:00'",
+ "",
+ " # Retain the last 5 snapshots",
+ " --catalog iceberg_prod --table db.sample --retain-last 5",
+ "",
+ " # Expire with all options and streaming",
+ " --catalog iceberg_prod --table db.sample --older-than '2024-06-01 00:00:00' \\",
+ " --retain-last 3 --stream-results"));
}
/**
@@ -403,15 +404,6 @@ public class IcebergExpireSnapshotsJob implements BuiltInJob, IcebergMaintenance
"{{spark_conf:-}}");
}
- /**
- * Build Spark configuration template.
- *
- * @return map of Spark configuration keys to template values
- */
- private static Map<String, String> buildSparkConfigs() {
- return IcebergSparkConfigUtils.buildTemplateSparkConfigs();
- }
-
// -------------------------------------------------------------------------
// TMS metrics helpers (not used by CLI {@link #main})
// -------------------------------------------------------------------------
@@ -445,22 +437,6 @@ public class IcebergExpireSnapshotsJob implements BuiltInJob, IcebergMaintenance
}
}
- @VisibleForTesting
- static Map<String, Object> expireBeforeMetrics(long snapshotNumber) {
- Map<String, Object> metrics = new HashMap<>();
- metrics.put(IcebergSnapshotExpirationContent.SNAPSHOT_NUMBER_METRIC, snapshotNumber);
- return metrics;
- }
-
- @VisibleForTesting
- static Map<String, Object> expireAfterMetrics(long expiredSnapshotNumber, long expiredFileSize) {
- Map<String, Object> metrics = new HashMap<>();
- metrics.put(
- IcebergSnapshotExpirationContent.EXPIRED_SNAPSHOT_NUMBER_METRIC, expiredSnapshotNumber);
- metrics.put(IcebergSnapshotExpirationContent.EXPIRED_FILE_SIZE_METRIC, expiredFileSize);
- return metrics;
- }
-
@VisibleForTesting
static long snapshotsCleared(Set<Long> beforeSnapshotIds, Set<Long> afterSnapshotIds) {
long cleared = 0L;
diff --git a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergJobUtils.java b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergJobUtils.java
index 3236de0c55..b132d3d7b4 100644
--- a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergJobUtils.java
+++ b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergJobUtils.java
@@ -19,10 +19,13 @@
package org.apache.gravitino.maintenance.jobs.iceberg;
import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import java.util.HashMap;
import java.util.LinkedHashMap;
+import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
@@ -74,8 +77,85 @@ public final class IcebergJobUtils {
*/
private static final String SPARK_KUBERNETES_PREFIX = "spark.kubernetes.";
+ /**
+ * Shared {@code --spark-conf} usage lines aligned with {@link #filterCustomSparkConfigs}. Catalog
+ * and Iceberg extensions are <em>not</em> blocked: CLI jobs register them through spark-conf.
+ */
+ public static final List<String> SPARK_CONF_USAGE_LINES =
+ ImmutableList.of(
+ " --spark-conf <json> JSON map of custom Spark configurations",
+ " Example: '{\"spark.sql.shuffle.partitions\":\"200\"}'",
+ " Note: Ignored when already set by spark-submit: spark.master,",
+ " spark.submit.deployMode. Always ignored: spark.kubernetes.*.",
+ " CLI jobs must pass Iceberg catalog (and usually extensions)",
+ " via spark-conf; those keys are not blocked.");
+
private IcebergJobUtils() {}
+ /**
+ * Prints a consistent CLI usage block to {@code System.err}.
+ *
+ * @param jobSimpleName simple class name shown after {@code Usage:}
+ * @param requiredLines required option lines (already indented)
+ * @param optionalLines optional option lines (already indented); may be empty
+ * @param exampleLines example lines; may be empty to omit the Examples section
+ */
+ public static void printCliUsage(
+ String jobSimpleName,
+ List<String> requiredLines,
+ List<String> optionalLines,
+ List<String> exampleLines) {
+ System.err.println(formatCliUsage(jobSimpleName, requiredLines, optionalLines, exampleLines));
+ }
+
+ @VisibleForTesting
+ static String formatCliUsage(
+ String jobSimpleName,
+ List<String> requiredLines,
+ List<String> optionalLines,
+ List<String> exampleLines) {
+ Preconditions.checkArgument(jobSimpleName != null && !jobSimpleName.isEmpty(), "jobSimpleName");
+ Preconditions.checkNotNull(requiredLines, "requiredLines");
+ Preconditions.checkNotNull(optionalLines, "optionalLines");
+ Preconditions.checkNotNull(exampleLines, "exampleLines");
+
+ StringBuilder sb = new StringBuilder();
+ sb.append("Usage: ").append(jobSimpleName).append(" [OPTIONS]\n\n");
+ sb.append("Required Options:\n");
+ appendLines(sb, requiredLines);
+ if (!optionalLines.isEmpty()) {
+ sb.append("\nOptional Options:\n");
+ appendLines(sb, optionalLines);
+ }
+ if (!exampleLines.isEmpty()) {
+ sb.append("\nExamples:\n");
+ appendLines(sb, exampleLines);
+ }
+ return sb.toString();
+ }
+
+ /**
+ * Appends {@link #SPARK_CONF_USAGE_LINES} after job-specific optional option lines.
+ *
+ * @param optionalWithoutSparkConf optional lines excluding {@code --spark-conf}
+ * @return optional lines including the shared spark-conf note
+ */
+ public static List<String> withSparkConfUsage(String... optionalWithoutSparkConf) {
+ return ImmutableList.<String>builder()
+ .add(optionalWithoutSparkConf)
+ .addAll(SPARK_CONF_USAGE_LINES)
+ .build();
+ }
+
+ private static void appendLines(StringBuilder sb, List<String> lines) {
+ for (String line : lines) {
+ sb.append(line);
+ if (!line.endsWith("\n")) {
+ sb.append('\n');
+ }
+ }
+ }
+
/**
* Return the given argument value unless it is an unresolved job template placeholder.
*
diff --git a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRemoveOrphanFilesJob.java b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRemoveOrphanFilesJob.java
index 0ad464cbcb..d2f2451313 100644
--- a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRemoveOrphanFilesJob.java
+++ b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRemoveOrphanFilesJob.java
@@ -23,6 +23,7 @@ import static org.apache.spark.sql.functions.lit;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Files;
@@ -97,7 +98,7 @@ public class IcebergRemoveOrphanFilesJob implements BuiltInJob, IcebergMaintenan
.withExecutable(resolveExecutable(IcebergRemoveOrphanFilesJob.class))
.withClassName(IcebergRemoveOrphanFilesJob.class.getName())
.withArguments(buildArguments())
- .withConfigs(buildSparkConfigs())
+ .withConfigs(IcebergSparkConfigUtils.buildTemplateSparkConfigs())
.withCustomFields(
Collections.singletonMap(JobTemplateProvider.PROPERTY_VERSION_KEY, VERSION))
.build();
@@ -268,17 +269,11 @@ public class IcebergRemoveOrphanFilesJob implements BuiltInJob, IcebergMaintenan
IcebergJobUtils.nullIfUnresolvedPlaceholder(argsByName.get("older-than")),
IcebergJobUtils.nullIfUnresolvedPlaceholder(argsByName.get("location")),
parseDryRun(IcebergJobUtils.nullIfUnresolvedPlaceholder(argsByName.get("dry-run"))));
- return TableSnapshotMetrics.of(
- IcebergJobUtils.currentSnapshotIdOrEmpty(spark, catalogName, tableIdentifier),
- orphanAfterMetrics(orphan.filesRemoved(), orphan.bytesReclaimed()));
- }
-
- @VisibleForTesting
- static Map<String, Object> orphanAfterMetrics(long removedFileNumber, long removedFileSize) {
Map<String, Object> metrics = new HashMap<>();
- metrics.put(IcebergOrphanFileRemovalContent.REMOVED_FILE_NUMBER_METRIC, removedFileNumber);
- metrics.put(IcebergOrphanFileRemovalContent.REMOVED_FILE_SIZE_METRIC, removedFileSize);
- return metrics;
+ metrics.put(IcebergOrphanFileRemovalContent.REMOVED_FILE_NUMBER_METRIC, orphan.filesRemoved());
+ metrics.put(IcebergOrphanFileRemovalContent.REMOVED_FILE_SIZE_METRIC, orphan.bytesReclaimed());
+ return TableSnapshotMetrics.of(
+ IcebergJobUtils.currentSnapshotIdOrEmpty(spark, catalogName, tableIdentifier), metrics);
}
static String buildProcedureCall(
@@ -399,14 +394,19 @@ public class IcebergRemoveOrphanFilesJob implements BuiltInJob, IcebergMaintenan
"{{spark_conf:-}}");
}
- private static Map<String, String> buildSparkConfigs() {
- return IcebergSparkConfigUtils.buildTemplateSparkConfigs();
- }
-
private static void printUsage() {
- LOG.error(
- "Usage: IcebergRemoveOrphanFilesJob --catalog <name> --table <db.table> "
- + "[--older-than 'yyyy-MM-dd HH:mm:ss'] [--location <path>] "
- + "[--dry-run true|false] [--spark-conf <json>]");
+ IcebergJobUtils.printCliUsage(
+ IcebergRemoveOrphanFilesJob.class.getSimpleName(),
+ ImmutableList.of(
+ " --catalog <name> Iceberg catalog name registered in Spark",
+ " --table <identifier> Fully qualified table name (e.g., db.table_name)"),
+ IcebergJobUtils.withSparkConfUsage(
+ " --older-than <timestamp> Remove orphans older than this timestamp",
+ " Example: '2024-01-01 00:00:00'",
+ " --location <path> Orphan scan root location",
+ " --dry-run <bool> List orphans without deleting (true or false)"),
+ ImmutableList.of(
+ " --catalog iceberg_prod --table db.sample --dry-run true",
+ " --catalog iceberg_prod --table db.sample --older-than '2024-01-01 00:00:00'"));
}
}
diff --git a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRewriteDataFilesJob.java b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRewriteDataFilesJob.java
index 8dd8474be6..e90ad35869 100644
--- a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRewriteDataFilesJob.java
+++ b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRewriteDataFilesJob.java
@@ -19,6 +19,7 @@
package org.apache.gravitino.maintenance.jobs.iceberg;
import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
@@ -61,7 +62,7 @@ public class IcebergRewriteDataFilesJob implements BuiltInJob, IcebergMaintenanc
.withExecutable(resolveExecutable(IcebergRewriteDataFilesJob.class))
.withClassName(IcebergRewriteDataFilesJob.class.getName())
.withArguments(buildArguments())
- .withConfigs(buildSparkConfigs())
+ .withConfigs(IcebergSparkConfigUtils.buildTemplateSparkConfigs())
.withCustomFields(
Collections.singletonMap(JobTemplateProvider.PROPERTY_VERSION_KEY, VERSION))
.build();
@@ -295,41 +296,35 @@ public class IcebergRewriteDataFilesJob implements BuiltInJob, IcebergMaintenanc
/** Print usage information. */
private static void printUsage() {
- System.err.println(
- "Usage: IcebergRewriteDataFilesJob [OPTIONS]\n"
- + "\n"
- + "Required Options:\n"
- + " --catalog <name> Iceberg catalog name registered in Spark\n"
- + " --table <identifier> Fully qualified table name (e.g., db.table_name)\n"
- + "\n"
- + "Optional Options:\n"
- + " --strategy <name> Rewrite strategy: binpack (default) or sort\n"
- + " --sort-order <spec> Sort order specification:\n"
- + " For columns: 'id DESC NULLS LAST, name ASC'\n"
- + " For Z-Order: 'zorder(c1,c2,c3)'\n"
- + " --where <predicate> Filter predicate to select files\n"
- + " Example: 'year = 2024 and status = ''active'''\n"
- + " --options <json> JSON map of Iceberg rewrite options\n"
- + " Example: '{\"min-input-files\":\"2\"}'\n"
- + " --spark-conf <json> JSON map of custom Spark configurations\n"
- + " Example: '{\"spark.sql.shuffle.partitions\":\"200\"}'\n"
- + " Note: Cannot override catalog, extensions, or app name configs\n"
- + "\n"
- + "Examples:\n"
- + " # Basic binpack\n"
- + " --catalog iceberg_prod --table db.sample\n"
- + "\n"
- + " # Sort by columns\n"
- + " --catalog iceberg_prod --table db.sample --strategy sort \\\n"
- + " --sort-order 'id DESC NULLS LAST'\n"
- + "\n"
- + " # With filter and options\n"
- + " --catalog iceberg_prod --table db.sample --where 'year = 2024 and status = ''active''' \\\n"
- + " --options '{\"min-input-files\":\"2\",\"remove-dangling-deletes\":\"true\"}'\n"
- + "\n"
- + " # With custom Spark configurations\n"
- + " --catalog iceberg_prod --table db.sample --strategy binpack \\\n"
- + " --spark-conf '{\"spark.sql.shuffle.partitions\":\"200\",\"spark.executor.memory\":\"4g\"}'");
+ IcebergJobUtils.printCliUsage(
+ IcebergRewriteDataFilesJob.class.getSimpleName(),
+ ImmutableList.of(
+ " --catalog <name> Iceberg catalog name registered in Spark",
+ " --table <identifier> Fully qualified table name (e.g., db.table_name)"),
+ IcebergJobUtils.withSparkConfUsage(
+ " --strategy <name> Rewrite strategy: binpack (default) or sort",
+ " --sort-order <spec> Sort order specification:",
+ " For columns: 'id DESC NULLS LAST, name ASC'",
+ " For Z-Order: 'zorder(c1,c2,c3)'",
+ " --where <predicate> Filter predicate to select files",
+ " Example: 'year = 2024 and status = ''active'''",
+ " --options <json> JSON map of Iceberg rewrite options",
+ " Example: '{\"min-input-files\":\"2\"}'"),
+ ImmutableList.of(
+ " # Basic binpack",
+ " --catalog iceberg_prod --table db.sample",
+ "",
+ " # Sort by columns",
+ " --catalog iceberg_prod --table db.sample --strategy sort \\",
+ " --sort-order 'id DESC NULLS LAST'",
+ "",
+ " # With filter and options",
+ " --catalog iceberg_prod --table db.sample --where 'year = 2024 and status = ''active''' \\",
+ " --options '{\"min-input-files\":\"2\",\"remove-dangling-deletes\":\"true\"}'",
+ "",
+ " # With custom Spark configurations",
+ " --catalog iceberg_prod --table db.sample --strategy binpack \\",
+ " --spark-conf '{\"spark.sql.shuffle.partitions\":\"200\",\"spark.executor.memory\":\"4g\"}'"));
}
/**
@@ -369,15 +364,6 @@ public class IcebergRewriteDataFilesJob implements BuiltInJob, IcebergMaintenanc
"{{spark_conf:-}}");
}
- /**
- * Build Spark configuration template.
- *
- * @return map of Spark configuration keys to template values
- */
- private static Map<String, String> buildSparkConfigs() {
- return IcebergSparkConfigUtils.buildTemplateSparkConfigs();
- }
-
/**
* Runs {@code rewrite_data_files} on an existing Spark session. Shared by CLI {@link #main} and
* TMS {@link #executeAndCollectAfter}.
@@ -409,8 +395,8 @@ public class IcebergRewriteDataFilesJob implements BuiltInJob, IcebergMaintenanc
public TableSnapshotMetrics collectBeforeMetrics(
SparkSession spark, String catalogName, String tableIdentifier) {
long snapshotId = IcebergJobUtils.requireCurrentSnapshotId(spark, catalogName, tableIdentifier);
- Map<String, Object> payload = collectCompactionMetrics(spark, catalogName, tableIdentifier);
- return TableSnapshotMetrics.of(snapshotId, payload);
+ Map<String, Object> metrics = collectCompactionMetrics(spark, catalogName, tableIdentifier);
+ return TableSnapshotMetrics.of(snapshotId, metrics);
}
@Override
@@ -492,8 +478,7 @@ public class IcebergRewriteDataFilesJob implements BuiltInJob, IcebergMaintenanc
return compactionMetrics(maxMse, deleteFiles, avgFileSize, totalFileSize, fileNumber);
}
- @VisibleForTesting
- static Map<String, Object> compactionMetrics(
+ private static Map<String, Object> compactionMetrics(
double dataFileMse,
long deleteFileNumber,
double avgFileSize,
diff --git a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRewriteManifestsJob.java b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRewriteManifestsJob.java
index 0e8aca63f5..915d898067 100644
--- a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRewriteManifestsJob.java
+++ b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRewriteManifestsJob.java
@@ -19,6 +19,7 @@
package org.apache.gravitino.maintenance.jobs.iceberg;
import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
@@ -62,7 +63,7 @@ public class IcebergRewriteManifestsJob implements BuiltInJob, IcebergMaintenanc
.withExecutable(resolveExecutable(IcebergRewriteManifestsJob.class))
.withClassName(IcebergRewriteManifestsJob.class.getName())
.withArguments(buildArguments())
- .withConfigs(buildSparkConfigs())
+ .withConfigs(IcebergSparkConfigUtils.buildTemplateSparkConfigs())
.withCustomFields(
Collections.singletonMap(JobTemplateProvider.PROPERTY_VERSION_KEY, VERSION))
.build();
@@ -263,8 +264,8 @@ public class IcebergRewriteManifestsJob implements BuiltInJob, IcebergMaintenanc
public TableSnapshotMetrics collectBeforeMetrics(
SparkSession spark, String catalogName, String tableIdentifier) {
long snapshotId = IcebergJobUtils.requireCurrentSnapshotId(spark, catalogName, tableIdentifier);
- Map<String, Object> payload = collectManifestBeforeMetrics(spark, catalogName, tableIdentifier);
- return TableSnapshotMetrics.of(snapshotId, payload);
+ Map<String, Object> metrics = collectManifestBeforeMetrics(spark, catalogName, tableIdentifier);
+ return TableSnapshotMetrics.of(snapshotId, metrics);
}
@Override
@@ -295,16 +296,24 @@ public class IcebergRewriteManifestsJob implements BuiltInJob, IcebergMaintenanc
rewritten,
((Number) result.get(1)).longValue());
}
+ Map<String, Object> metrics = new HashMap<>();
+ metrics.put(IcebergRewriteManifestsContent.REWRITTEN_MANIFEST_NUMBER_METRIC, rewritten);
return TableSnapshotMetrics.of(
- IcebergJobUtils.requireCurrentSnapshotId(spark, catalogName, tableIdentifier),
- manifestAfterMetrics(rewritten));
+ IcebergJobUtils.requireCurrentSnapshotId(spark, catalogName, tableIdentifier), metrics);
}
private static void printUsage() {
- System.err.println(
- "Usage: IcebergRewriteManifestsJob --catalog <catalog_name> --table <table_identifier>"
- + " [--use-caching <true|false>] [--spec-id <non-negative integer>]"
- + " [--spark-conf <json>]");
+ IcebergJobUtils.printCliUsage(
+ IcebergRewriteManifestsJob.class.getSimpleName(),
+ ImmutableList.of(
+ " --catalog <name> Iceberg catalog name registered in Spark",
+ " --table <identifier> Fully qualified table name (e.g., db.table_name)"),
+ IcebergJobUtils.withSparkConfUsage(
+ " --use-caching <bool> Whether to use caching during rewrite",
+ " --spec-id <int> Non-negative partition spec id to rewrite"),
+ ImmutableList.of(
+ " --catalog iceberg_prod --table db.sample",
+ " --catalog iceberg_prod --table db.sample --use-caching false --spec-id 0"));
}
/**
@@ -326,15 +335,6 @@ public class IcebergRewriteManifestsJob implements BuiltInJob, IcebergMaintenanc
"{{spark_conf:-}}");
}
- /**
- * Build Spark configuration template.
- *
- * @return map of Spark configuration keys to template values
- */
- private static Map<String, String> buildSparkConfigs() {
- return IcebergSparkConfigUtils.buildTemplateSparkConfigs();
- }
-
// -------------------------------------------------------------------------
// TMS metrics helpers (not used by CLI {@link #main})
// -------------------------------------------------------------------------
@@ -356,22 +356,11 @@ public class IcebergRewriteManifestsJob implements BuiltInJob, IcebergMaintenanc
totalSize += manifest.length();
}
}
- return manifestBeforeMetrics(count, count == 0L ? 0D : (double) totalSize / count);
- }
-
- @VisibleForTesting
- static Map<String, Object> manifestBeforeMetrics(long manifestNumber, double avgManifestSize) {
- Map<String, Object> metrics = new HashMap<>();
- metrics.put(IcebergRewriteManifestsContent.MANIFEST_NUMBER_METRIC, manifestNumber);
- metrics.put(IcebergRewriteManifestsContent.AVG_MANIFEST_SIZE_METRIC, avgManifestSize);
- return metrics;
- }
-
- @VisibleForTesting
- static Map<String, Object> manifestAfterMetrics(long rewrittenManifestNumber) {
Map<String, Object> metrics = new HashMap<>();
+ metrics.put(IcebergRewriteManifestsContent.MANIFEST_NUMBER_METRIC, count);
metrics.put(
- IcebergRewriteManifestsContent.REWRITTEN_MANIFEST_NUMBER_METRIC, rewrittenManifestNumber);
+ IcebergRewriteManifestsContent.AVG_MANIFEST_SIZE_METRIC,
+ count == 0L ? 0D : (double) totalSize / count);
return metrics;
}
}
diff --git a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergUpdateStatsAndMetricsJob.java b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergUpdateStatsAndMetricsJob.java
index 843b589553..60238506c7 100644
--- a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergUpdateStatsAndMetricsJob.java
+++ b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergUpdateStatsAndMetricsJob.java
@@ -19,6 +19,7 @@
package org.apache.gravitino.maintenance.jobs.iceberg;
import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@@ -570,28 +571,24 @@ public class IcebergUpdateStatsAndMetricsJob implements BuiltInJob {
}
private static void printUsage() {
- System.err.println(
- "Usage: IcebergUpdateStatsAndMetricsJob [OPTIONS]\\n"
- + "\\n"
- + "Required Options:\\n"
- + " --catalog <name> Iceberg catalog name registered in Spark\\n"
- + " --table <identifier> Table name in schema.table format\\n"
- + "\\n"
- + "Optional Options:\\n"
- + " --update-mode <stats|metrics|all> Update behavior mode, default: all\\n"
- + " data-file-mse target file size is fixed at 134217728 (128MB)\\n"
- + " small-file-number threshold is fixed at 33554432 (32MB)\\n"
- + " --updater-options <json> JSON map for updater and repository settings\\n"
- + " Example: '{\"gravitino_uri\":\"http://localhost:8090\",\\n"
- + " \"metalake\":\"test\",\"statistics_updater\":\"gravitino-statistics-updater\",\\n"
- + " \"metrics_updater\":\"gravitino-metrics-updater\",\\n"
- + " \"auth_type\":\"basic\",\"username\":\"admin\",\"password\":\"YourSecureGravitinoPassword\"}'\\n"
- + " --spark-conf <json> JSON map of custom Spark configs\\n"
- + " Must include Iceberg catalog configs for --catalog\\n"
- + " Example: '{\"spark.master\":\"local[2]\","
- + "\"spark.sql.catalog.rest_catalog\":\"org.apache.iceberg.spark.SparkCatalog\","
- + "\"spark.sql.catalog.rest_catalog.type\":\"rest\","
- + "\"spark.sql.catalog.rest_catalog.uri\":\"http://localhost:9001/iceberg\"}'");
+ IcebergJobUtils.printCliUsage(
+ IcebergUpdateStatsAndMetricsJob.class.getSimpleName(),
+ ImmutableList.of(
+ " --catalog <name> Iceberg catalog name registered in Spark",
+ " --table <identifier> Table name in schema.table format"),
+ IcebergJobUtils.withSparkConfUsage(
+ " --update-mode <mode> stats | metrics | all (default: all)",
+ " data-file-mse target size is fixed at 134217728 (128MB)",
+ " small-file-number threshold is fixed at 33554432 (32MB)",
+ " --updater-options <json> Updater and repository settings",
+ " Example: '{\"gravitino_uri\":\"http://localhost:8090\",",
+ " \"metalake\":\"test\",\"auth_type\":\"basic\",",
+ " \"username\":\"admin\",\"password\":\"...\"}'"),
+ ImmutableList.of(
+ " --catalog rest_catalog --table db.sample --update-mode all \\",
+ " --spark-conf '{\"spark.sql.catalog.rest_catalog\":\"org.apache.iceberg.spark.SparkCatalog\",",
+ " \"spark.sql.catalog.rest_catalog.type\":\"rest\",",
+ " \"spark.sql.catalog.rest_catalog.uri\":\"http://localhost:9001/iceberg\"}'"));
}
enum UpdateMode {
diff --git a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergExpireSnapshotsJob.java b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergExpireSnapshotsJob.java
index 24607f23e4..5c16c98cf3 100644
--- a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergExpireSnapshotsJob.java
+++ b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergExpireSnapshotsJob.java
@@ -529,13 +529,11 @@ public class TestIcebergExpireSnapshotsJob {
@Test
public void testExpireMetricNames() {
- Map<String, Object> before = IcebergExpireSnapshotsJob.expireBeforeMetrics(3L);
- assertEquals(1, before.size());
- assertEquals(3L, before.get(IcebergSnapshotExpirationContent.SNAPSHOT_NUMBER_METRIC));
-
- Map<String, Object> after = IcebergExpireSnapshotsJob.expireAfterMetrics(2L, 100L);
- assertEquals(2, after.size());
- assertEquals(2L, after.get(IcebergSnapshotExpirationContent.EXPIRED_SNAPSHOT_NUMBER_METRIC));
- assertEquals(100L, after.get(IcebergSnapshotExpirationContent.EXPIRED_FILE_SIZE_METRIC));
+ assertEquals("custom-snapshot-number", IcebergSnapshotExpirationContent.SNAPSHOT_NUMBER_METRIC);
+ assertEquals(
+ "custom-expired-snapshot-number",
+ IcebergSnapshotExpirationContent.EXPIRED_SNAPSHOT_NUMBER_METRIC);
+ assertEquals(
+ "custom-expired-file-size", IcebergSnapshotExpirationContent.EXPIRED_FILE_SIZE_METRIC);
}
}
diff --git a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergJobUtils.java b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergJobUtils.java
index 867ec45591..8559cebb5c 100644
--- a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergJobUtils.java
+++ b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergJobUtils.java
@@ -142,4 +142,22 @@ public class TestIcebergJobUtils {
ImmutableMap.of("spark.executor.memory", "2g"),
IcebergJobUtils.filterCustomSparkConfigs(configs, new SparkConf(false)));
}
+
+ @Test
+ public void testFormatCliUsageIncludesSharedSparkConfNote() {
+ String usage =
+ IcebergJobUtils.formatCliUsage(
+ "DemoJob",
+ java.util.Collections.singletonList(" --catalog <name>"),
+ IcebergJobUtils.withSparkConfUsage(" --dry-run <bool>"),
+ java.util.Collections.singletonList(" --catalog c --table db.t"));
+ assertTrue(usage.startsWith("Usage: DemoJob [OPTIONS]"));
+ assertTrue(usage.contains("Required Options:"));
+ assertTrue(usage.contains("Optional Options:"));
+ assertTrue(usage.contains("--dry-run <bool>"));
+ assertTrue(usage.contains("--spark-conf <json>"));
+ assertTrue(usage.contains("spark.kubernetes.*"));
+ assertTrue(usage.contains("Examples:"));
+ assertTrue(!usage.contains("Cannot override catalog"));
+ }
}
diff --git a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRemoveOrphanFilesJob.java b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRemoveOrphanFilesJob.java
index c044f3003d..47a1dc0e90 100644
--- a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRemoveOrphanFilesJob.java
+++ b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRemoveOrphanFilesJob.java
@@ -107,11 +107,10 @@ public class TestIcebergRemoveOrphanFilesJob {
@Test
public void testOrphanAfterMetricNames() {
- java.util.Map<String, Object> metrics =
- IcebergRemoveOrphanFilesJob.orphanAfterMetrics(10L, 200L);
- assertEquals(2, metrics.size());
- assertEquals(10L, metrics.get(IcebergOrphanFileRemovalContent.REMOVED_FILE_NUMBER_METRIC));
- assertEquals(200L, metrics.get(IcebergOrphanFileRemovalContent.REMOVED_FILE_SIZE_METRIC));
+ assertEquals(
+ "custom-removed-file-number", IcebergOrphanFileRemovalContent.REMOVED_FILE_NUMBER_METRIC);
+ assertEquals(
+ "custom-removed-file-size", IcebergOrphanFileRemovalContent.REMOVED_FILE_SIZE_METRIC);
}
/** Verifies location boundaries. */
diff --git a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteDataFilesJob.java b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteDataFilesJob.java
index 0fc2d0bd54..fab1e8dbdb 100644
--- a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteDataFilesJob.java
+++ b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteDataFilesJob.java
@@ -29,6 +29,7 @@ import java.util.Map;
import org.apache.gravitino.job.JobTemplateProvider;
import org.apache.gravitino.job.SparkJobTemplate;
import org.apache.gravitino.policy.IcebergDataCompactionContent;
+import org.apache.spark.sql.Row;
import org.junit.jupiter.api.Test;
public class TestIcebergRewriteDataFilesJob {
@@ -540,18 +541,21 @@ public class TestIcebergRewriteDataFilesJob {
@Test
public void testCompactionMetricsSchemaForTms() {
Map<String, Object> metrics =
- IcebergRewriteDataFilesJob.compactionMetrics(1.23e15, 42L, 126877696D, 9876543210L, 80L);
+ IcebergRewriteDataFilesJob.aggregatePartitionCompactionMetrics(new Row[0]);
assertEquals(5, metrics.size());
assertEquals(
- 1.23e15,
+ 0D,
((Number) metrics.get(IcebergDataCompactionContent.DATA_FILE_MSE_METRIC)).doubleValue());
assertEquals(
- 126877696D,
+ 0L,
+ ((Number) metrics.get(IcebergDataCompactionContent.DELETE_FILE_NUMBER_METRIC)).longValue());
+ assertEquals(
+ 0D,
((Number) metrics.get(IcebergDataCompactionContent.AVG_FILE_SIZE_METRIC)).doubleValue());
assertEquals(
- 9876543210L,
+ 0L,
((Number) metrics.get(IcebergDataCompactionContent.TOTAL_FILE_SIZE_METRIC)).longValue());
assertEquals(
- 80L, ((Number) metrics.get(IcebergDataCompactionContent.FILE_NUMBER_METRIC)).longValue());
+ 0L, ((Number) metrics.get(IcebergDataCompactionContent.FILE_NUMBER_METRIC)).longValue());
}
}
diff --git a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteManifestsJob.java b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteManifestsJob.java
index f49afa3c11..85b7eb61cb 100644
--- a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteManifestsJob.java
+++ b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteManifestsJob.java
@@ -449,16 +449,11 @@ public class TestIcebergRewriteManifestsJob {
@Test
public void testManifestMetricsSchemaForTms() {
- Map<String, Object> before = IcebergRewriteManifestsJob.manifestBeforeMetrics(120L, 8388608D);
- assertEquals(2, before.size());
+ assertEquals("custom-manifest-number", IcebergRewriteManifestsContent.MANIFEST_NUMBER_METRIC);
assertEquals(
- 120L,
- ((Number) before.get(IcebergRewriteManifestsContent.MANIFEST_NUMBER_METRIC)).longValue());
- Map<String, Object> after = IcebergRewriteManifestsJob.manifestAfterMetrics(18750L);
- assertEquals(1, after.size());
+ "custom-avg-manifest-size", IcebergRewriteManifestsContent.AVG_MANIFEST_SIZE_METRIC);
assertEquals(
- 18750L,
- ((Number) after.get(IcebergRewriteManifestsContent.REWRITTEN_MANIFEST_NUMBER_METRIC))
- .longValue());
+ "custom-rewritten-manifest-number",
+ IcebergRewriteManifestsContent.REWRITTEN_MANIFEST_NUMBER_METRIC);
}
}