Skip to content

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

[#9985] feat(optimzer): support updater related implement class (#10078)

FANNGed265cbe235c
diff --git a/clients/client-java/build.gradle.kts b/clients/client-java/build.gradle.kts
index 604f6912ba..17c6e2d7f8 100644
--- a/clients/client-java/build.gradle.kts
+++ b/clients/client-java/build.gradle.kts
@@ -90,7 +90,7 @@ tasks.javadoc {
classpath = configurations["compileClasspath"] +
project(":api").configurations["runtimeClasspath"] +
- project(":common").configurations["runtimeClasspath"]
+ project(":common").configurations["compileClasspath"]
}
tasks.clean {
diff --git a/common/build.gradle.kts b/common/build.gradle.kts
index d86654c089..b30f01f533 100644
--- a/common/build.gradle.kts
+++ b/common/build.gradle.kts
@@ -40,6 +40,7 @@ dependencies {
implementation(libs.slf4j.api)
annotationProcessor(libs.lombok)
+ compileOnly(libs.commons.dbcp2)
compileOnly(libs.lombok)
testAnnotationProcessor(libs.lombok)
testCompileOnly(libs.lombok)
diff --git a/common/src/main/java/org/apache/gravitino/utils/jdbc/JdbcDataSourceConfig.java b/common/src/main/java/org/apache/gravitino/utils/jdbc/JdbcDataSourceConfig.java
new file mode 100644
index 0000000000..9e79dadfc5
--- /dev/null
+++ b/common/src/main/java/org/apache/gravitino/utils/jdbc/JdbcDataSourceConfig.java
@@ -0,0 +1,142 @@
+/*
+ * 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.utils.jdbc;
+
+import com.google.common.base.Preconditions;
+import org.apache.commons.lang3.StringUtils;
+
+/** Immutable JDBC DataSource settings used to create a pooled {@code BasicDataSource}. */
+public class JdbcDataSourceConfig {
+
+ private final String jdbcUrl;
+ private final String username;
+ private final String password;
+ private final String driverClassName;
+ private final int maxTotal;
+ private final int minIdle;
+ private final long maxWaitMillis;
+ private final boolean testOnBorrow;
+ private final String validationQuery;
+
+ /**
+ * Creates a JDBC data source configuration.
+ *
+ * @param jdbcUrl JDBC URL
+ * @param username JDBC user name
+ * @param password JDBC password
+ * @param driverClassName JDBC driver class name, optional when driver auto-loading is available
+ * @param maxTotal max number of pooled connections
+ * @param minIdle minimum number of idle pooled connections
+ * @param maxWaitMillis max wait time in milliseconds when borrowing a connection
+ * @param testOnBorrow whether to validate connections when borrowing
+ * @param validationQuery validation SQL used when {@code testOnBorrow} is enabled
+ */
+ public JdbcDataSourceConfig(
+ String jdbcUrl,
+ String username,
+ String password,
+ String driverClassName,
+ int maxTotal,
+ int minIdle,
+ long maxWaitMillis,
+ boolean testOnBorrow,
+ String validationQuery) {
+ Preconditions.checkArgument(StringUtils.isNotBlank(jdbcUrl), "jdbcUrl must not be blank");
+ Preconditions.checkArgument(StringUtils.isNotBlank(username), "username must not be blank");
+ Preconditions.checkArgument(maxTotal > 0, "maxTotal must be positive");
+ Preconditions.checkArgument(minIdle >= 0, "minIdle must be non-negative");
+ Preconditions.checkArgument(maxWaitMillis > 0, "maxWaitMillis must be positive");
+ Preconditions.checkArgument(
+ !testOnBorrow || StringUtils.isNotBlank(validationQuery),
+ "validationQuery must not be blank when testOnBorrow is enabled");
+ this.jdbcUrl = jdbcUrl;
+ this.username = username;
+ this.password = password;
+ this.driverClassName = driverClassName;
+ this.maxTotal = maxTotal;
+ this.minIdle = minIdle;
+ this.maxWaitMillis = maxWaitMillis;
+ this.testOnBorrow = testOnBorrow;
+ this.validationQuery = validationQuery;
+ }
+
+ /**
+ * @return JDBC URL
+ */
+ public String jdbcUrl() {
+ return jdbcUrl;
+ }
+
+ /**
+ * @return JDBC user name
+ */
+ public String username() {
+ return username;
+ }
+
+ /**
+ * @return JDBC password
+ */
+ public String password() {
+ return password;
+ }
+
+ /**
+ * @return JDBC driver class name, or blank when not set
+ */
+ public String driverClassName() {
+ return driverClassName;
+ }
+
+ /**
+ * @return max number of pooled connections
+ */
+ public int maxTotal() {
+ return maxTotal;
+ }
+
+ /**
+ * @return minimum number of idle pooled connections
+ */
+ public int minIdle() {
+ return minIdle;
+ }
+
+ /**
+ * @return max wait time in milliseconds when borrowing a connection
+ */
+ public long maxWaitMillis() {
+ return maxWaitMillis;
+ }
+
+ /**
+ * @return whether to validate connections on borrow
+ */
+ public boolean testOnBorrow() {
+ return testOnBorrow;
+ }
+
+ /**
+ * @return validation SQL query
+ */
+ public String validationQuery() {
+ return validationQuery;
+ }
+}
diff --git a/common/src/main/java/org/apache/gravitino/utils/jdbc/JdbcDataSourceFactory.java b/common/src/main/java/org/apache/gravitino/utils/jdbc/JdbcDataSourceFactory.java
new file mode 100644
index 0000000000..2a24f980d5
--- /dev/null
+++ b/common/src/main/java/org/apache/gravitino/utils/jdbc/JdbcDataSourceFactory.java
@@ -0,0 +1,66 @@
+/*
+ * 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.utils.jdbc;
+
+import java.time.Duration;
+import org.apache.commons.dbcp2.BasicDataSource;
+import org.apache.commons.lang3.StringUtils;
+
+/** Utility for creating a pooled JDBC {@link BasicDataSource}. */
+public final class JdbcDataSourceFactory {
+
+ /** Default maximum number of pooled connections. */
+ public static final int DEFAULT_MAX_TOTAL = 10;
+ /** Default minimum number of idle pooled connections. */
+ public static final int DEFAULT_MIN_IDLE = 2;
+ /** Default max wait time in milliseconds when borrowing a connection. */
+ public static final long DEFAULT_MAX_WAIT_MILLIS = 30_000L;
+ /** Default flag to validate connections when borrowing. */
+ public static final boolean DEFAULT_TEST_ON_BORROW = true;
+ /** Default validation SQL query. */
+ public static final String DEFAULT_VALIDATION_QUERY = "SELECT 1";
+
+ private JdbcDataSourceFactory() {}
+
+ /**
+ * Creates a configured {@link BasicDataSource}.
+ *
+ * @param config JDBC data source configuration
+ * @return configured pooled data source
+ */
+ public static BasicDataSource create(JdbcDataSourceConfig config) {
+ BasicDataSource dataSource = new BasicDataSource();
+ dataSource.setUrl(config.jdbcUrl());
+ dataSource.setUsername(config.username());
+ dataSource.setPassword(config.password());
+
+ if (StringUtils.isNotBlank(config.driverClassName())) {
+ dataSource.setDriverClassName(config.driverClassName());
+ }
+ dataSource.setMaxTotal(config.maxTotal());
+ dataSource.setMinIdle(config.minIdle());
+ dataSource.setMaxWait(Duration.ofMillis(config.maxWaitMillis()));
+ dataSource.setTestOnBorrow(config.testOnBorrow());
+ if (config.testOnBorrow()) {
+ dataSource.setValidationQuery(config.validationQuery());
+ }
+ return dataSource;
+ }
+}
diff --git a/common/src/main/java/org/apache/gravitino/utils/jdbc/JdbcSqlScriptUtils.java b/common/src/main/java/org/apache/gravitino/utils/jdbc/JdbcSqlScriptUtils.java
new file mode 100644
index 0000000000..decf8a5fae
--- /dev/null
+++ b/common/src/main/java/org/apache/gravitino/utils/jdbc/JdbcSqlScriptUtils.java
@@ -0,0 +1,72 @@
+/*
+ * 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.utils.jdbc;
+
+import com.google.common.base.Preconditions;
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.Collectors;
+
+/** Utility methods for parsing and executing SQL scripts. */
+public final class JdbcSqlScriptUtils {
+
+ private JdbcSqlScriptUtils() {}
+
+ /**
+ * Splits SQL script content into executable statements.
+ *
+ * <p>Lines starting with {@code --} are treated as comments and removed before splitting.
+ *
+ * @param sqlContent SQL script content
+ * @return executable SQL statements in order
+ */
+ public static List<String> splitStatements(String sqlContent) {
+ Preconditions.checkArgument(sqlContent != null, "sqlContent must not be null");
+ String executableSql =
+ Arrays.stream(sqlContent.split("\\R"))
+ .map(String::trim)
+ .filter(line -> !line.startsWith("--"))
+ .collect(Collectors.joining("\n"));
+ return Arrays.stream(executableSql.split(";"))
+ .map(String::trim)
+ .filter(s -> !s.isEmpty())
+ .toList();
+ }
+
+ /**
+ * Executes all SQL statements parsed from the script content.
+ *
+ * @param connection JDBC connection used to execute statements
+ * @param sqlContent SQL script content
+ * @throws SQLException if statement execution fails
+ */
+ public static void executeSqlScript(Connection connection, String sqlContent)
+ throws SQLException {
+ List<String> statements = splitStatements(sqlContent);
+ try (Statement statement = connection.createStatement()) {
+ for (String ddl : statements) {
+ statement.execute(ddl);
+ }
+ }
+ }
+}
diff --git a/core/src/main/java/org/apache/gravitino/stats/storage/JdbcPartitionStatisticStorageFactory.java b/core/src/main/java/org/apache/gravitino/stats/storage/JdbcPartitionStatisticStorageFactory.java
index fc4261c412..b7a5d66fa9 100644
--- a/core/src/main/java/org/apache/gravitino/stats/storage/JdbcPartitionStatisticStorageFactory.java
+++ b/core/src/main/java/org/apache/gravitino/stats/storage/JdbcPartitionStatisticStorageFactory.java
@@ -20,11 +20,12 @@ package org.apache.gravitino.stats.storage;
import com.google.common.base.Preconditions;
import java.sql.SQLException;
-import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.gravitino.exceptions.GravitinoRuntimeException;
+import org.apache.gravitino.utils.jdbc.JdbcDataSourceConfig;
+import org.apache.gravitino.utils.jdbc.JdbcDataSourceFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -66,11 +67,6 @@ public class JdbcPartitionStatisticStorageFactory implements PartitionStatisticS
// Default values
private static final String DEFAULT_JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
- private static final int DEFAULT_POOL_MAX_SIZE = 10;
- private static final int DEFAULT_POOL_MIN_IDLE = 2;
- private static final long DEFAULT_CONNECTION_TIMEOUT_MS = 30000L;
- private static final boolean DEFAULT_TEST_ON_BORROW = true;
- private static final String VALIDATION_QUERY = "SELECT 1";
// Keep reference to DataSource for cleanup
private BasicDataSource dataSource;
@@ -105,45 +101,45 @@ public class JdbcPartitionStatisticStorageFactory implements PartitionStatisticS
* @return configured DataSource
*/
private BasicDataSource createDataSource(Map<String, String> properties) {
- BasicDataSource ds = new BasicDataSource();
-
- // Required properties
String jdbcUrl = properties.get(JDBC_URL);
String jdbcUser = properties.get(JDBC_USER);
String jdbcPassword = properties.get(JDBC_PASSWORD);
- ds.setUrl(jdbcUrl);
- ds.setUsername(jdbcUser);
- ds.setPassword(jdbcPassword);
-
// Optional properties with defaults
String driverClassName = properties.getOrDefault(JDBC_DRIVER, DEFAULT_JDBC_DRIVER);
- ds.setDriverClassName(driverClassName);
int maxSize =
Integer.parseInt(
- properties.getOrDefault(POOL_MAX_SIZE, String.valueOf(DEFAULT_POOL_MAX_SIZE)));
- ds.setMaxTotal(maxSize);
+ properties.getOrDefault(
+ POOL_MAX_SIZE, String.valueOf(JdbcDataSourceFactory.DEFAULT_MAX_TOTAL)));
int minIdle =
Integer.parseInt(
- properties.getOrDefault(POOL_MIN_IDLE, String.valueOf(DEFAULT_POOL_MIN_IDLE)));
- ds.setMinIdle(minIdle);
+ properties.getOrDefault(
+ POOL_MIN_IDLE, String.valueOf(JdbcDataSourceFactory.DEFAULT_MIN_IDLE)));
long timeoutMs =
Long.parseLong(
properties.getOrDefault(
- CONNECTION_TIMEOUT_MS, String.valueOf(DEFAULT_CONNECTION_TIMEOUT_MS)));
- ds.setMaxWait(Duration.ofMillis(timeoutMs));
+ CONNECTION_TIMEOUT_MS,
+ String.valueOf(JdbcDataSourceFactory.DEFAULT_MAX_WAIT_MILLIS)));
boolean testOnBorrow =
Boolean.parseBoolean(
- properties.getOrDefault(TEST_ON_BORROW, String.valueOf(DEFAULT_TEST_ON_BORROW)));
- ds.setTestOnBorrow(testOnBorrow);
-
- if (testOnBorrow) {
- ds.setValidationQuery(VALIDATION_QUERY);
- }
+ properties.getOrDefault(
+ TEST_ON_BORROW, String.valueOf(JdbcDataSourceFactory.DEFAULT_TEST_ON_BORROW)));
+
+ JdbcDataSourceConfig config =
+ new JdbcDataSourceConfig(
+ jdbcUrl,
+ jdbcUser,
+ jdbcPassword,
+ driverClassName,
+ maxSize,
+ minIdle,
+ timeoutMs,
+ testOnBorrow,
+ JdbcDataSourceFactory.DEFAULT_VALIDATION_QUERY);
LOG.info(
"Created JDBC DataSource: url={}, driver={}, maxPoolSize={}, minIdle={}, timeout={}ms",
@@ -153,7 +149,7 @@ public class JdbcPartitionStatisticStorageFactory implements PartitionStatisticS
minIdle,
timeoutMs);
- return ds;
+ return JdbcDataSourceFactory.create(config);
}
/**
diff --git a/core/src/test/java/org/apache/gravitino/storage/TestSQLScripts.java b/core/src/test/java/org/apache/gravitino/storage/TestSQLScripts.java
index 85ff8d0b22..d3aa2fbbcc 100644
--- a/core/src/test/java/org/apache/gravitino/storage/TestSQLScripts.java
+++ b/core/src/test/java/org/apache/gravitino/storage/TestSQLScripts.java
@@ -20,6 +20,7 @@ package org.apache.gravitino.storage;
import java.io.File;
import java.io.IOException;
+import java.nio.file.Files;
import java.nio.file.Path;
import java.sql.Connection;
import java.sql.ResultSet;
@@ -33,7 +34,6 @@ import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-import org.apache.commons.io.FileUtils;
import org.apache.gravitino.storage.relational.TestJDBCBackend;
import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;
import org.apache.ibatis.session.SqlSession;
@@ -59,7 +59,10 @@ public class TestSQLScripts extends TestJDBCBackend {
Pattern upgradePattern =
Pattern.compile("upgrade-([\\d.]+)-to-([\\d.]+)-" + backendType.toLowerCase() + "\\.sql");
Pattern metricsPattern =
- Pattern.compile("iceberg-metrics-schema-([\\d.]+)-" + backendType.toLowerCase() + "\\.sql");
+ Pattern.compile(
+ "(?:iceberg|optimizer)-metrics-schema-([\\d.]+)-"
+ + backendType.toLowerCase()
+ + "\\.sql");
Map<String, List<File>> versionScrips = new HashMap<>();
for (File scriptFile : scriptFiles) {
@@ -88,12 +91,7 @@ public class TestSQLScripts extends TestJDBCBackend {
for (List<File> scripts : versionScrips.values()) {
dropAllTables();
for (File scriptFile : scripts) {
- String sqlContent = FileUtils.readFileToString(scriptFile, "UTF-8");
- List<String> ddls =
- Arrays.stream(sqlContent.split(";"))
- .map(String::trim)
- .filter(s -> !s.isEmpty())
- .toList();
+ List<String> ddls = extractStatements(scriptFile.toPath());
try (SqlSession sqlSession =
SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true)) {
@@ -111,6 +109,21 @@ public class TestSQLScripts extends TestJDBCBackend {
}
}
+ private List<String> extractStatements(Path sqlFile) throws IOException {
+ String executableSql =
+ Files.readAllLines(sqlFile).stream()
+ .map(String::trim)
+ .filter(line -> !line.isEmpty())
+ .filter(line -> !line.startsWith("--"))
+ .reduce((left, right) -> left + "\n" + right)
+ .orElse("");
+
+ return Arrays.stream(executableSql.split(";"))
+ .map(String::trim)
+ .filter(s -> !s.isEmpty())
+ .toList();
+ }
+
private void dropAllTables() throws SQLException {
try (SqlSession sqlSession =
SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true)) {
diff --git a/maintenance/optimizer/build.gradle.kts b/maintenance/optimizer/build.gradle.kts
index 501b9ff3bb..f986287674 100644
--- a/maintenance/optimizer/build.gradle.kts
+++ b/maintenance/optimizer/build.gradle.kts
@@ -45,7 +45,9 @@ dependencies {
implementation(libs.jackson.databind)
implementation(libs.jackson.annotations)
implementation(libs.guava)
+ implementation(libs.commons.dbcp2)
implementation(libs.ql.expression)
+ implementation(libs.h2db)
annotationProcessor(libs.lombok)
compileOnly(libs.lombok)
diff --git a/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/api/common/TableStatisticsBundle.java b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/api/common/TableAndPartitionStatistics.java
similarity index 95%
rename from maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/api/common/TableStatisticsBundle.java
rename to maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/api/common/TableAndPartitionStatistics.java
index 1c718dcf48..2e7642c00e 100644
--- a/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/api/common/TableStatisticsBundle.java
+++ b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/api/common/TableAndPartitionStatistics.java
@@ -25,11 +25,11 @@ import org.apache.gravitino.annotation.DeveloperApi;
/** Container for table-level statistics and partition-level statistics. */
@DeveloperApi
-public class TableStatisticsBundle {
+public class TableAndPartitionStatistics {
private final List<StatisticEntry<?>> tableStatistics;
private final Map<PartitionPath, List<StatisticEntry<?>>> partitionStatistics;
- public TableStatisticsBundle(
+ public TableAndPartitionStatistics(
List<StatisticEntry<?>> tableStatistics,
Map<PartitionPath, List<StatisticEntry<?>>> partitionStatistics) {
this.tableStatistics = tableStatistics != null ? List.copyOf(tableStatistics) : List.of();
diff --git a/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/api/updater/MetricsUpdater.java b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/api/updater/MetricsUpdater.java
index 9cd0707e9f..f172192c53 100644
--- a/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/api/updater/MetricsUpdater.java
+++ b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/api/updater/MetricsUpdater.java
@@ -20,10 +20,10 @@
package org.apache.gravitino.maintenance.optimizer.api.updater;
import java.util.List;
-import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.annotation.DeveloperApi;
-import org.apache.gravitino.maintenance.optimizer.api.common.MetricSample;
import org.apache.gravitino.maintenance.optimizer.api.common.Provider;
+import org.apache.gravitino.maintenance.optimizer.updater.metrics.storage.JobMetricWriteRequest;
+import org.apache.gravitino.maintenance.optimizer.updater.metrics.storage.TableMetricWriteRequest;
/** Represents an updater that can update metrics for a table or job. */
@DeveloperApi
@@ -31,16 +31,14 @@ public interface MetricsUpdater extends Provider {
/**
* Persist table metrics.
*
- * @param nameIdentifier catalog/schema/table identifier
- * @param metrics time-series samples to write
+ * @param metrics table metric write requests
*/
- void updateTableMetrics(NameIdentifier nameIdentifier, List<MetricSample> metrics);
+ void updateTableMetrics(List<TableMetricWriteRequest> metrics);
/**
* Persist job metrics.
*
- * @param nameIdentifier job identifier
- * @param metrics time-series samples to write
+ * @param metrics job metric write requests
*/
- void updateJobMetrics(NameIdentifier nameIdentifier, List<MetricSample> metrics);
+ void updateJobMetrics(List<JobMetricWriteRequest> metrics);
}
diff --git a/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/api/updater/SupportsCalculateBulkTableStatistics.java b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/api/updater/SupportsCalculateBulkTableStatistics.java
index 30072fc662..c8651d04ca 100644
--- a/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/api/updater/SupportsCalculateBulkTableStatistics.java
+++ b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/api/updater/SupportsCalculateBulkTableStatistics.java
@@ -22,7 +22,7 @@ package org.apache.gravitino.maintenance.optimizer.api.updater;
import java.util.Map;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.annotation.DeveloperApi;
-import org.apache.gravitino.maintenance.optimizer.api.common.TableStatisticsBundle;
+import org.apache.gravitino.maintenance.optimizer.api.common.TableAndPartitionStatistics;
/** Represents a provider that supports bulk table statistics calculation. */
@DeveloperApi
@@ -33,5 +33,5 @@ public interface SupportsCalculateBulkTableStatistics extends SupportsCalculateT
*
* @return map of table identifier to its statistics bundle; empty when none are produced
*/
- Map<NameIdentifier, TableStatisticsBundle> calculateBulkTableStatistics();
+ Map<NameIdentifier, TableAndPartitionStatistics> calculateBulkTableStatistics();
}
diff --git a/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/api/updater/SupportsCalculateTableStatistics.java b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/api/updater/SupportsCalculateTableStatistics.java
index 586af4b5e1..b373cbd910 100644
--- a/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/api/updater/SupportsCalculateTableStatistics.java
+++ b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/api/updater/SupportsCalculateTableStatistics.java
@@ -21,7 +21,7 @@ package org.apache.gravitino.maintenance.optimizer.api.updater;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.annotation.DeveloperApi;
-import org.apache.gravitino.maintenance.optimizer.api.common.TableStatisticsBundle;
+import org.apache.gravitino.maintenance.optimizer.api.common.TableAndPartitionStatistics;
/** Represents a provider that supports table statistics. */
@DeveloperApi
@@ -32,5 +32,5 @@ public interface SupportsCalculateTableStatistics extends StatisticsCalculator {
* @param tableIdentifier catalog/schema/table identifier
* @return statistics bundle; contains table statistics and partition statistics
*/
- TableStatisticsBundle calculateTableStatistics(NameIdentifier tableIdentifier);
+ TableAndPartitionStatistics calculateTableStatistics(NameIdentifier tableIdentifier);
}
diff --git a/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/common/conf/OptimizerConfig.java b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/common/conf/OptimizerConfig.java
index d19eb5a220..ee22f46ead 100644
--- a/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/common/conf/OptimizerConfig.java
+++ b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/common/conf/OptimizerConfig.java
@@ -30,6 +30,8 @@ import org.apache.gravitino.maintenance.optimizer.recommender.job.NoopJobSubmitt
import org.apache.gravitino.maintenance.optimizer.recommender.statistics.GravitinoStatisticsProvider;
import org.apache.gravitino.maintenance.optimizer.recommender.strategy.GravitinoStrategyProvider;
import org.apache.gravitino.maintenance.optimizer.recommender.table.GravitinoTableMetadataProvider;
+import org.apache.gravitino.maintenance.optimizer.updater.metrics.GravitinoMetricsUpdater;
+import org.apache.gravitino.maintenance.optimizer.updater.statistics.GravitinoStatisticsUpdater;
/**
* Central configuration holder for the optimizer runtime. Keys are grouped under the {@code
@@ -53,7 +55,7 @@ public class OptimizerConfig extends Config {
private static final String TABLE_META_PROVIDER = RECOMMENDER_PREFIX + "tableMetaProvider";
private static final String JOB_SUBMITTER = RECOMMENDER_PREFIX + "jobSubmitter";
- private static final String UPDATER_PREFIX = OPTIMIZER_PREFIX + "updater.";
+ public static final String UPDATER_PREFIX = OPTIMIZER_PREFIX + "updater.";
private static final String STATISTICS_UPDATER = UPDATER_PREFIX + "statisticsUpdater";
private static final String METRICS_UPDATER = UPDATER_PREFIX + "metricsUpdater";
private static final String MONITOR_PREFIX = OPTIMIZER_PREFIX + "monitor.";
@@ -111,14 +113,14 @@ public class OptimizerConfig extends Config {
.doc("The statistics updater implementation name (matches Provider.name()).")
.version(ConfigConstants.VERSION_1_2_0)
.stringConf()
- .create();
+ .createWithDefault(GravitinoStatisticsUpdater.NAME);
public static final ConfigEntry<String> METRICS_UPDATER_CONFIG =
new ConfigBuilder(METRICS_UPDATER)
.doc("The metrics updater implementation name (matches Provider.name()).")
.version(ConfigConstants.VERSION_1_2_0)
.stringConf()
- .create();
+ .createWithDefault(GravitinoMetricsUpdater.NAME);
public static final ConfigEntry<String> METRICS_PROVIDER_CONFIG =
new ConfigBuilder(METRICS_PROVIDER)
diff --git a/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/Updater.java b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/Updater.java
index 3acbe2b188..c0c66c6304 100644
--- a/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/Updater.java
+++ b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/Updater.java
@@ -27,10 +27,9 @@ import java.util.Locale;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.gravitino.NameIdentifier;
-import org.apache.gravitino.maintenance.optimizer.api.common.MetricSample;
import org.apache.gravitino.maintenance.optimizer.api.common.PartitionPath;
import org.apache.gravitino.maintenance.optimizer.api.common.StatisticEntry;
-import org.apache.gravitino.maintenance.optimizer.api.common.TableStatisticsBundle;
+import org.apache.gravitino.maintenance.optimizer.api.common.TableAndPartitionStatistics;
import org.apache.gravitino.maintenance.optimizer.api.updater.MetricsUpdater;
import org.apache.gravitino.maintenance.optimizer.api.updater.StatisticsCalculator;
import org.apache.gravitino.maintenance.optimizer.api.updater.StatisticsUpdater;
@@ -39,13 +38,15 @@ import org.apache.gravitino.maintenance.optimizer.api.updater.SupportsCalculateB
import org.apache.gravitino.maintenance.optimizer.api.updater.SupportsCalculateJobStatistics;
import org.apache.gravitino.maintenance.optimizer.api.updater.SupportsCalculateTableStatistics;
import org.apache.gravitino.maintenance.optimizer.common.CloseableGroup;
-import org.apache.gravitino.maintenance.optimizer.common.MetricSampleImpl;
import org.apache.gravitino.maintenance.optimizer.common.OptimizerEnv;
-import org.apache.gravitino.maintenance.optimizer.common.PartitionMetricSampleImpl;
import org.apache.gravitino.maintenance.optimizer.common.conf.OptimizerConfig;
import org.apache.gravitino.maintenance.optimizer.common.util.InstanceLoaderUtils;
import org.apache.gravitino.maintenance.optimizer.common.util.ProviderUtils;
+import org.apache.gravitino.maintenance.optimizer.common.util.StatisticValueUtils;
import org.apache.gravitino.maintenance.optimizer.recommender.util.PartitionUtils;
+import org.apache.gravitino.maintenance.optimizer.updater.metrics.storage.JobMetricWriteRequest;
+import org.apache.gravitino.maintenance.optimizer.updater.metrics.storage.MetricRecordImpl;
+import org.apache.gravitino.maintenance.optimizer.updater.metrics.storage.TableMetricWriteRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -101,6 +102,8 @@ public class Updater implements AutoCloseable {
List<NameIdentifier> nameIdentifiers,
UpdateType updateType) {
StatisticsCalculator calculator = getStatisticsCalculator(statisticsCalculatorName);
+ List<TableMetricWriteRequest> tableMetricWriteRequests = new ArrayList<>();
+ List<JobMetricWriteRequest> jobMetricWriteRequests = new ArrayList<>();
long tableRecords = 0;
long partitionRecords = 0;
long jobRecords = 0;
@@ -108,7 +111,7 @@ public class Updater implements AutoCloseable {
if (calculator instanceof SupportsCalculateTableStatistics) {
SupportsCalculateTableStatistics supportTableStatistics =
((SupportsCalculateTableStatistics) calculator);
- TableStatisticsBundle bundle =
+ TableAndPartitionStatistics bundle =
supportTableStatistics.calculateTableStatistics(nameIdentifier);
List<StatisticEntry<?>> statistics = bundle != null ? bundle.tableStatistics() : List.of();
Map<PartitionPath, List<StatisticEntry<?>>> partitionStatistics =
@@ -120,8 +123,14 @@ public class Updater implements AutoCloseable {
statisticsCalculatorName,
updateType,
nameIdentifier);
- updateTable(statistics, nameIdentifier, updateType);
- updatePartition(partitionStatistics, nameIdentifier, updateType);
+ if (UpdateType.STATISTICS.equals(updateType)) {
+ updateTableStatistics(statistics, nameIdentifier);
+ updatePartitionStatistics(partitionStatistics, nameIdentifier);
+ } else {
+ tableMetricWriteRequests.addAll(collectTableMetrics(statistics, nameIdentifier));
+ tableMetricWriteRequests.addAll(
+ collectPartitionMetrics(partitionStatistics, nameIdentifier));
+ }
}
if (calculator instanceof SupportsCalculateJobStatistics
&& UpdateType.METRICS.equals(updateType)) {
@@ -134,9 +143,10 @@ public class Updater implements AutoCloseable {
"Updating job metrics: calculator={}, identifier={}",
statisticsCalculatorName,
nameIdentifier);
- updateJob(statistics, nameIdentifier);
+ jobMetricWriteRequests.addAll(collectJobMetrics(statistics, nameIdentifier));
}
}
+ updateTableAndJobMetrics(tableMetricWriteRequests, jobMetricWriteRequests);
System.out.println(
String.format(
"SUMMARY: %s totalRecords=%d tableRecords=%d partitionRecords=%d jobRecords=%d",
@@ -161,12 +171,14 @@ public class Updater implements AutoCloseable {
*/
public void updateAll(String statisticsCalculatorName, UpdateType updateType) {
StatisticsCalculator calculator = getStatisticsCalculator(statisticsCalculatorName);
+ List<TableMetricWriteRequest> tableMetricWriteRequests = new ArrayList<>();
+ List<JobMetricWriteRequest> jobMetricWriteRequests = new ArrayList<>();
long tableRecords = 0;
long partitionRecords = 0;
long jobRecords = 0;
if (calculator instanceof SupportsCalculateBulkTableStatistics supportBulkTableStatistics) {
- Map<NameIdentifier, TableStatisticsBundle> allTableStatistics =
+ Map<NameIdentifier, TableAndPartitionStatistics> allTableStatistics =
supportBulkTableStatistics.calculateBulkTableStatistics();
if (allTableStatistics == null) {
allTableStatistics = Map.of();
@@ -180,8 +192,14 @@ public class Updater implements AutoCloseable {
bundle != null ? bundle.tableStatistics() : List.of();
Map<PartitionPath, List<StatisticEntry<?>>> partitionStatistics =
bundle != null ? bundle.partitionStatistics() : Map.of();
- updateTable(statistics, identifier, updateType);
- updatePartition(partitionStatistics, identifier, updateType);
+ if (UpdateType.STATISTICS.equals(updateType)) {
+ updateTableStatistics(statistics, identifier);
+ updatePartitionStatistics(partitionStatistics, identifier);
+ } else {
+ tableMetricWriteRequests.addAll(collectTableMetrics(statistics, identifier));
+ tableMetricWriteRequests.addAll(
+ collectPartitionMetrics(partitionStatistics, identifier));
+ }
});
}
@@ -193,8 +211,11 @@ public class Updater implements AutoCloseable {
allJobStatistics = Map.of();
}
jobRecords += countAllStatistics(allJobStatistics);
- allJobStatistics.forEach((identifier, statistics) -> updateJob(statistics, identifier));
+ allJobStatistics.forEach(
+ (identifier, statistics) ->
+ jobMetricWriteRequests.addAll(collectJobMetrics(statistics, identifier)));
}
+ updateTableAndJobMetrics(tableMetricWriteRequests, jobMetricWriteRequests);
System.out.println(
String.format(
"SUMMARY: %s totalRecords=%d tableRecords=%d partitionRecords=%d jobRecords=%d",
@@ -215,32 +236,6 @@ public class Updater implements AutoCloseable {
closeableGroup.close();
}
- private void updateTable(
- List<StatisticEntry<?>> statistics, NameIdentifier tableIdentifier, UpdateType updateType) {
- switch (updateType) {
- case STATISTICS:
- updateTableStatistics(statistics, tableIdentifier);
- break;
- case METRICS:
- updateTableMetrics(statistics, tableIdentifier);
- break;
- }
- }
-
- private void updatePartition(
- Map<PartitionPath, List<StatisticEntry<?>>> partitionStatistics,
- NameIdentifier tableIdentifier,
- UpdateType updateType) {
- switch (updateType) {
- case STATISTICS:
- updatePartitionStatistics(partitionStatistics, tableIdentifier);
- break;
- case METRICS:
- updatePartitionMetrics(partitionStatistics, tableIdentifier);
- break;
- }
- }
-
private void updateTableStatistics(
List<StatisticEntry<?>> statistics, NameIdentifier tableIdentifier) {
LOG.info(
@@ -269,7 +264,7 @@ public class Updater implements AutoCloseable {
statisticsUpdater.updatePartitionStatistics(tableIdentifier, partitionStatistics);
}
- private void updateTableMetrics(
+ private List<TableMetricWriteRequest> collectTableMetrics(
List<StatisticEntry<?>> statistics, NameIdentifier tableIdentifier) {
long timestampSeconds = System.currentTimeMillis() / 1000;
LOG.info(
@@ -277,30 +272,30 @@ public class Updater implements AutoCloseable {
tableIdentifier,
statistics != null ? statistics.size() : 0,
summarize(statistics));
- metricsUpdater.updateTableMetrics(tableIdentifier, toMetrics(statistics, timestampSeconds));
+ return toTableMetricWriteRequests(tableIdentifier, statistics, timestampSeconds);
}
- private void updatePartitionMetrics(
+ private List<TableMetricWriteRequest> collectPartitionMetrics(
Map<PartitionPath, List<StatisticEntry<?>>> partitionStatistics,
NameIdentifier tableIdentifier) {
if (partitionStatistics == null || partitionStatistics.isEmpty()) {
LOG.info(
"Persist partition metrics skipped: identifier={}, reason=empty partitions",
tableIdentifier);
- return;
+ return List.of();
}
long timestampSeconds = System.currentTimeMillis() / 1000;
- List<MetricSample> partitionMetrics = toPartitionMetrics(partitionStatistics, timestampSeconds);
LOG.info(
"Persisting partition metrics: identifier={}, partitions={}, names={}, details={}",
tableIdentifier,
partitionStatistics.size(),
partitionNames(partitionStatistics),
summarize(partitionStatistics.values().stream().flatMap(Collection::stream).toList()));
- metricsUpdater.updateTableMetrics(tableIdentifier, partitionMetrics);
+ return toPartitionMetricWriteRequests(tableIdentifier, partitionStatistics, timestampSeconds);
}
- private void updateJob(List<StatisticEntry<?>> statistics, NameIdentifier jobIdentifier) {
+ private List<JobMetricWriteRequest> collectJobMetrics(
+ List<StatisticEntry<?>> statistics, NameIdentifier jobIdentifier) {
long timestampSeconds = System.currentTimeMillis() / 1000;
LOG.info(
@@ -308,7 +303,18 @@ public class Updater implements AutoCloseable {
jobIdentifier,
statistics != null ? statistics.size() : 0,
summarize(statistics));
- metricsUpdater.updateJobMetrics(jobIdentifier, toMetrics(statistics, timestampSeconds));
+ return toJobMetricWriteRequests(jobIdentifier, statistics, timestampSeconds);
+ }
+
+ private void updateTableAndJobMetrics(
+ List<TableMetricWriteRequest> tableMetricWriteRequests,
+ List<JobMetricWriteRequest> jobMetricWriteRequests) {
+ if (!tableMetricWriteRequests.isEmpty()) {
+ metricsUpdater.updateTableMetrics(tableMetricWriteRequests);
+ }
+ if (!jobMetricWriteRequests.isEmpty()) {
+ metricsUpdater.updateJobMetrics(jobMetricWriteRequests);
+ }
}
private String summarize(List<StatisticEntry<?>> statistics) {
@@ -327,23 +333,57 @@ public class Updater implements AutoCloseable {
return summary;
}
- private List<MetricSample> toMetrics(List<StatisticEntry<?>> statistics, long timestamp) {
- List<MetricSample> metrics = new ArrayList<>();
+ private List<TableMetricWriteRequest> toTableMetricWriteRequests(
+ NameIdentifier tableIdentifier, List<StatisticEntry<?>> statistics, long timestamp) {
+ List<TableMetricWriteRequest> metrics = new ArrayList<>();
if (statistics != null) {
- statistics.forEach(stat -> metrics.add(new MetricSampleImpl(timestamp, stat)));
+ statistics.forEach(
+ stat ->
+ metrics.add(
+ new TableMetricWriteRequest(
+ tableIdentifier,
+ stat.name(),
+ java.util.Optional.empty(),
+ new MetricRecordImpl(
+ timestamp, StatisticValueUtils.toString(stat.value())))));
}
return metrics;
}
- private List<MetricSample> toPartitionMetrics(
- Map<PartitionPath, List<StatisticEntry<?>>> partitionStatistics, long timestamp) {
- List<MetricSample> metrics = new ArrayList<>();
+ private List<TableMetricWriteRequest> toPartitionMetricWriteRequests(
+ NameIdentifier tableIdentifier,
+ Map<PartitionPath, List<StatisticEntry<?>>> partitionStatistics,
+ long timestamp) {
+ List<TableMetricWriteRequest> metrics = new ArrayList<>();
if (partitionStatistics != null) {
partitionStatistics.forEach(
(partitionPath, statisticEntries) ->
statisticEntries.forEach(
stat ->
- metrics.add(new PartitionMetricSampleImpl(timestamp, stat, partitionPath))));
+ metrics.add(
+ new TableMetricWriteRequest(
+ tableIdentifier,
+ stat.name(),
+ java.util.Optional.of(
+ PartitionUtils.encodePartitionPath(partitionPath)),
+ new MetricRecordImpl(
+ timestamp, StatisticValueUtils.toString(stat.value()))))));
+ }
+ return metrics;
+ }
+
+ private List<JobMetricWriteRequest> toJobMetricWriteRequests(
+ NameIdentifier jobIdentifier, List<StatisticEntry<?>> statistics, long timestamp) {
+ List<JobMetricWriteRequest> metrics = new ArrayList<>();
+ if (statistics != null) {
+ statistics.forEach(
+ stat ->
+ metrics.add(
+ new JobMetricWriteRequest(
+ jobIdentifier,
+ stat.name(),
+ new MetricRecordImpl(
+ timestamp, StatisticValueUtils.toString(stat.value())))));
}
return metrics;
}
@@ -403,7 +443,7 @@ public class Updater implements AutoCloseable {
}
private long countAllTableStatistics(
- Map<NameIdentifier, TableStatisticsBundle> statisticsByTable) {
+ Map<NameIdentifier, TableAndPartitionStatistics> statisticsByTable) {
if (statisticsByTable == null) {
return 0;
}
@@ -413,7 +453,7 @@ public class Updater implements AutoCloseable {
}
private long countAllPartitionStatistics(
- Map<NameIdentifier, TableStatisticsBundle> partitionStatisticsByTable) {
+ Map<NameIdentifier, TableAndPartitionStatistics> partitionStatisticsByTable) {
if (partitionStatisticsByTable == null) {
return 0;
}
diff --git a/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/calculator/local/AbstractStatisticsImporter.java b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/calculator/local/AbstractStatisticsImporter.java
new file mode 100644
index 0000000000..0bb5a693b0
--- /dev/null
+++ b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/calculator/local/AbstractStatisticsImporter.java
@@ -0,0 +1,546 @@
+/*
+ * 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.optimizer.updater.calculator.local;
+
+import com.fasterxml.jackson.annotation.JsonAnySetter;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectReader;
+import com.google.common.collect.ImmutableList;
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.function.Consumer;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.json.JsonUtils;
+import org.apache.gravitino.maintenance.optimizer.api.common.PartitionEntry;
+import org.apache.gravitino.maintenance.optimizer.api.common.PartitionPath;
+import org.apache.gravitino.maintenance.optimizer.api.common.StatisticEntry;
+import org.apache.gravitino.maintenance.optimizer.api.common.TableAndPartitionStatistics;
+import org.apache.gravitino.maintenance.optimizer.common.PartitionEntryImpl;
+import org.apache.gravitino.maintenance.optimizer.common.StatisticEntryImpl;
+import org.apache.gravitino.stats.StatisticValue;
+import org.apache.gravitino.stats.StatisticValues;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * partition schema: { "identifier": "schema.table", "stats-type": "partition", "partition-path":
+ * {"p1": "v1", "p2": "v2"}, "stats1":"100"}
+ *
+ * <p>table schema: { "identifier": "schema.table", "stats-type": "table", "stats1":"100"}
+ *
+ * <p>job schema: { "identifier": "schema.job", "stats-type": "job", "stats1":"100"}
+ *
+ * <p>For Iceberg we don't have restrict on partition name, but prefer to use the name in Iceberg
+ * transform name.
+ *
+ * <ul>
+ * <li>identity(col) -> col
+ * <li>year(col) -> col_year
+ * <li>month(col) -> col_month
+ * <li>day(col) / days(col) -> col_day
+ * <li>hour(col) / hours(col) -> col_hour
+ * <li>bucket(N, col) -> col_bucket_N
+ * <li>truncate(W, col) -> col_trunc
+ * </ul>
+ */
+abstract class AbstractStatisticsImporter implements StatisticsImporter {
+ private static final Logger LOG = LoggerFactory.getLogger(AbstractStatisticsImporter.class);
+ private static final ObjectReader RECORD_READER =
+ JsonUtils.anyFieldMapper().readerFor(StatisticsRecord.class);
+
+ private final String defaultCatalogName;
+
+ AbstractStatisticsImporter(String defaultCatalogName) {
+ this.defaultCatalogName = defaultCatalogName;
+ }
+
+ @Override
+ public TableAndPartitionStatistics readTableStatistics(NameIdentifier tableIdentifier) {
+ return aggregateTableAndPartitionStatistics(tableIdentifier);
+ }
+
+ @Override
+ public Map<NameIdentifier, TableAndPartitionStatistics> bulkReadAllTableStatistics() {
+ return aggregateAllTableAndPartitionStatistics();
+ }
+
+ @Override
+ public List<StatisticEntry<?>> readJobStatistics(NameIdentifier jobIdentifier) {
+ return toStatisticEntries(aggregateJobStatistics(jobIdentifier).get(jobIdentifier));
+ }
+
+ @Override
+ public Map<NameIdentifier, List<StatisticEntry<?>>> bulkReadAllJobStatistics() {
+ return toIdentifierStatisticEntries(aggregateJobStatistics(null));
+ }
+
+ private List<StatisticEntry<?>> toStatisticEntries(Map<String, StatisticValue<?>> statsByName) {
+ if (statsByName == null || statsByName.isEmpty()) {
+ return ImmutableList.of();
+ }
+
+ List<StatisticEntry<?>> statistics = new ArrayList<>();
+ statsByName.forEach((name, value) -> statistics.add(new StatisticEntryImpl<>(name, value)));
+ return ImmutableList.copyOf(statistics);
+ }
+
+ private Map<PartitionPath, List<StatisticEntry<?>>> toPartitionStatisticEntries(
+ Map<PartitionPath, Map<String, StatisticValue<?>>> statsByPartition) {
+ if (statsByPartition == null || statsByPartition.isEmpty()) {
+ return Map.of();
+ }
+
+ Map<PartitionPath, List<StatisticEntry<?>>> result = new LinkedHashMap<>();
+ statsByPartition.forEach(
+ (partitionPath, statsByName) -> result.put(partitionPath, toStatisticEntries(statsByName)));
+ return result;
+ }
+
+ private Map<NameIdentifier, List<StatisticEntry<?>>> toIdentifierStatisticEntries(
+ Map<NameIdentifier, Map<String, StatisticValue<?>>> statsByIdentifier) {
+ Map<NameIdentifier, List<StatisticEntry<?>>> result = new LinkedHashMap<>();
+ if (statsByIdentifier == null || statsByIdentifier.isEmpty()) {
+ return result;
+ }
+
+ statsByIdentifier.forEach(
+ (identifier, statsByName) -> result.put(identifier, toStatisticEntries(statsByName)));
+ return result;
+ }
+
+ private Map<NameIdentifier, Map<String, StatisticValue<?>>> aggregateStatistics(
+ NameIdentifier targetIdentifier) {
+ Map<NameIdentifier, Map<String, StatisticValue<?>>> aggregated = new LinkedHashMap<>();
+ visitParsedRecords(
+ new StatisticsRecordVisitor() {
+ @Override
+ public void onTable(StatisticsRecord record) {
+ NameIdentifier identifier = parseTableIdentifier(record.identifier());
+ if (identifier == null) {
+ return;
+ }
+ if (targetIdentifier != null && !targetIdentifier.equals(identifier)) {
+ return;
+ }
+
+ Map<String, StatisticValue<?>> statisticsByName =
+ aggregated.computeIfAbsent(identifier, k -> new LinkedHashMap<>());
+ populateStatistics(record, statisticsByName);
+ }
+ });
+
+ return aggregated;
+ }
+
+ private TableAndPartitionStatistics aggregateTableAndPartitionStatistics(
+ NameIdentifier targetIdentifier) {
+ if (targetIdentifier == null) {
+ return new TableAndPartitionStatistics(ImmutableList.of(), Map.of());
+ }
+
+ Map<String, StatisticValue<?>> tableStatistics = new LinkedHashMap<>();
+ Map<PartitionPath, Map<String, StatisticValue<?>>> partitionStatistics = new LinkedHashMap<>();
+ visitParsedRecords(
+ new StatisticsRecordVisitor() {
+ @Override
+ public void onTable(StatisticsRecord record) {
+ NameIdentifier identifier = parseTableIdentifier(record.identifier());
+ if (targetIdentifier.equals(identifier)) {
+ populateStatistics(record, tableStatistics);
+ }
+ }
+
+ @Override
+ public void onPartition(StatisticsRecord record) {
+ NameIdentifier identifier = parseTableIdentifier(record.identifier());
+ if (!targetIdentifier.equals(identifier)) {
+ return;
+ }
+
+ Optional<PartitionPath> partitionPathOpt = parsePartitionPath(record.partitionPath());
+ if (partitionPathOpt.isEmpty()) {
+ return;
+ }
+
+ Map<String, StatisticValue<?>> partitionStatsByName =
+ partitionStatistics.computeIfAbsent(
+ partitionPathOpt.get(), k -> new LinkedHashMap<>());
+ populateStatistics(record, partitionStatsByName);
+ }
+ });
+
+ return new TableAndPartitionStatistics(
+ toStatisticEntries(tableStatistics), toPartitionStatisticEntries(partitionStatistics));
+ }
+
+ private Map<NameIdentifier, TableAndPartitionStatistics>
+ aggregateAllTableAndPartitionStatistics() {
+ Map<NameIdentifier, Map<String, StatisticValue<?>>> tableStatisticsByIdentifier =
+ new LinkedHashMap<>();
+ Map<NameIdentifier, Map<PartitionPath, Map<String, StatisticValue<?>>>>
+ partitionStatisticsByIdentifier = new LinkedHashMap<>();
+ visitParsedRecords(
+ new StatisticsRecordVisitor() {
+ @Override
+ public void onTable(StatisticsRecord record) {
+ NameIdentifier identifier = parseTableIdentifier(record.identifier());
+ if (identifier == null) {
+ return;
+ }
+ Map<String, StatisticValue<?>> tableStats =
+ tableStatisticsByIdentifier.computeIfAbsent(identifier, k -> new LinkedHashMap<>());
+ populateStatistics(record, tableStats);
+ }
+
+ @Override
+ public void onPartition(StatisticsRecord record) {
+ NameIdentifier identifier = parseTableIdentifier(record.identifier());
+ if (identifier == null) {
+ return;
+ }
+
+ Optional<PartitionPath> partitionPathOpt = parsePartitionPath(record.partitionPath());
+ if (partitionPathOpt.isEmpty()) {
+ return;
+ }
+
+ Map<PartitionPath, Map<String, StatisticValue<?>>> partitionStatsByPath =
+ partitionStatisticsByIdentifier.computeIfAbsent(
+ identifier, k -> new LinkedHashMap<>());
+ Map<String, StatisticValue<?>> partitionStatsByName =
+ partitionStatsByPath.computeIfAbsent(
+ partitionPathOpt.get(), k -> new LinkedHashMap<>());
+ populateStatistics(record, partitionStatsByName);
+ }
+ });
+
+ Map<NameIdentifier, TableAndPartitionStatistics> bundles = new LinkedHashMap<>();
+ tableStatisticsByIdentifier.forEach(
+ (identifier, tableStats) ->
+ bundles.put(
+ identifier,
+ new TableAndPartitionStatistics(
+ toStatisticEntries(tableStats),
+ toPartitionStatisticEntries(partitionStatisticsByIdentifier.get(identifier)))));
+ partitionStatisticsByIdentifier.forEach(
+ (identifier, partitionStats) ->
+ bundles.putIfAbsent(
+ identifier,
+ new TableAndPartitionStatistics(
+ ImmutableList.of(), toPartitionStatisticEntries(partitionStats))));
+ return bundles;
+ }
+
+ private Map<NameIdentifier, Map<String, StatisticValue<?>>> aggregateJobStatistics(
+ NameIdentifier targetIdentifier) {
+ Map<NameIdentifier, Map<String, StatisticValue<?>>> aggregated = new LinkedHashMap<>();
+ visitParsedRecords(
+ new StatisticsRecordVisitor() {
+ @Override
+ public void onJob(StatisticsRecord record) {
+ NameIdentifier identifier = parseJobIdentifier(record.identifier());
+ if (identifier == null) {
+ return;
+ }
+ if (targetIdentifier != null && !targetIdentifier.equals(identifier)) {
+ return;
+ }
+
+ Map<String, StatisticValue<?>> statisticsByName =
+ aggregated.computeIfAbsent(identifier, k -> new LinkedHashMap<>());
+ populateStatistics(record, statisticsByName);
+ }
+ });
+
+ return aggregated;
+ }
+
+ protected abstract BufferedReader openReader() throws IOException;
+
+ private void forEachParsedRecord(Consumer<StatisticsRecord> recordConsumer) {
+ try (BufferedReader reader = openReader()) {
+ String line;
+ while ((line = reader.readLine()) != null) {
+ if (StringUtils.isBlank(line)) {
+ continue;
+ }
+
+ StatisticsRecord record = parseRecord(line);
+ if (record == null) {
+ continue;
+ }
+ recordConsumer.accept(record);
+ }
+ } catch (IOException e) {
+ throw new RuntimeException("Failed to read statistics", e);
+ }
+ }
+
+ private void visitParsedRecords(StatisticsRecordVisitor visitor) {
+ forEachParsedRecord(record -> dispatchRecordByStatisticsType(record, visitor));
+ }
+
+ private void dispatchRecordByStatisticsType(
+ StatisticsRecord record, StatisticsRecordVisitor visitor) {
+ Optional<StatisticsType> statisticsType = StatisticsType.from(record.statisticsType());
+ if (statisticsType.isEmpty()) {
+ return;
+ }
+
+ switch (statisticsType.get()) {
+ case TABLE:
+ visitor.onTable(record);
+ break;
+ case PARTITION:
+ visitor.onPartition(record);
+ break;
+ case JOB:
+ visitor.onJob(record);
+ break;
+ }
+ }
+
+ private StatisticsRecord parseRecord(String line) {
+ try {
+ return RECORD_READER.readValue(line);
+ } catch (IOException e) {
+ LOG.warn("Skip malformed statistics line: {}", line, e);
+ return null;
+ }
+ }
+
+ private void populateStatistics(
+ StatisticsRecord record, Map<String, StatisticValue<?>> statisticsByName) {
+ record
+ .statisticsFields()
+ .forEach(
+ (fieldName, node) -> {
+ StatisticValue<?> value = parseStatisticValue(fieldName, node);
+ if (value != null) {
+ statisticsByName.put(fieldName, value);
+ }
+ });
+ }
+
+ private interface StatisticsRecordVisitor {
+ default void onTable(StatisticsRecord record) {}
+
+ default void onPartition(StatisticsRecord record) {}
+
+ default void onJob(StatisticsRecord record) {}
+ }
+
+ private enum FieldName {
+ STATISTICS_TYPE("stats-type"),
+ IDENTIFIER("identifier"),
+ PARTITION_PATH("partition-path");
+
+ private final String key;
+
+ FieldName(String key) {
+ this.key = key;
+ }
+
+ private String key() {
+ return key;
+ }
+
+ private static final Set<String> RESERVED_FIELDS =
+ Set.of(STATISTICS_TYPE.key, IDENTIFIER.key, PARTITION_PATH.key);
+
+ private static boolean isReserved(String fieldName) {
+ return RESERVED_FIELDS.contains(fieldName);
+ }
+ }
+
+ private enum StatisticsType {
+ TABLE("table"),
+ PARTITION("partition"),
+ JOB("job");
+
+ private final String type;
+
+ StatisticsType(String type) {
+ this.type = type;
+ }
+
+ private static Optional<StatisticsType> from(String statisticsTypeValue) {
+ if (StringUtils.isBlank(statisticsTypeValue)) {
+ return Optional.empty();
+ }
+
+ String normalizedType = statisticsTypeValue.toLowerCase(Locale.ROOT);
+ for (StatisticsType value : values()) {
+ if (value.type.equals(normalizedType)) {
+ return Optional.of(value);
+ }
+ }
+ return Optional.empty();
+ }
+ }
+
+ private NameIdentifier parseTableIdentifier(String identifierText) {
+ if (StringUtils.isBlank(identifierText)) {
+ return null;
+ }
+ try {
+ NameIdentifier parsed = NameIdentifier.parse(identifierText);
+ int levels = parsed.namespace().levels().length;
+ if (levels == 0) {
+ return parsed;
+ } else if (levels == 1) {
+ if (StringUtils.isNotBlank(defaultCatalogName)) {
+ return NameIdentifier.of(
+ defaultCatalogName, parsed.namespace().levels()[0], parsed.name());
+ }
+ return parsed;
+ } else if (levels == 2) {
+ return parsed;
+ } else {
+ return null;
+ }
+ } catch (Exception e) {
+ LOG.warn("Skip line with invalid identifier: {}", identifierText);
+ return null;
+ }
+ }
+
+ private NameIdentifier parseJobIdentifier(String identifierText) {
+ if (StringUtils.isBlank(identifierText)) {
+ return null;
+ }
+ try {
+ return NameIdentifier.parse(identifierText);
+ } catch (Exception e) {
+ LOG.warn("Skip line with invalid identifier: {}", identifierText);
+ return null;
+ }
+ }
+
+ private static final class StatisticsRecord {
+ @JsonProperty("stats-type")
+ private String statisticsType;
+
+ @JsonProperty("identifier")
+ private String identifier;
+
+ @JsonProperty("partition-path")
+ private JsonNode partitionPath;
+
+ private final Map<String, JsonNode> statisticsFields = new LinkedHashMap<>();
+
+ @JsonAnySetter
+ void putField(String fieldName, JsonNode fieldValue) {
+ if (!FieldName.isReserved(fieldName)) {
+ statisticsFields.put(fieldName, fieldValue);
+ }
+ }
+
+ String statisticsType() {
+ return statisticsType;
+ }
+
+ String identifier() {
+ return identifier;
+ }
+
+ JsonNode partitionPath() {
+ return partitionPath;
+ }
+
+ Map<String, JsonNode> statisticsFields() {
+ return statisticsFields;
+ }
+ }
+
+ private Optional<PartitionPath> parsePartitionPath(JsonNode partitionPathNode) {
+ if (partitionPathNode == null || !partitionPathNode.isObject()) {
+ return Optional.empty();
+ }
+
+ List<PartitionEntry> entries = new ArrayList<>();
+ Iterator<Map.Entry<String, JsonNode>> iterator = partitionPathNode.fields();
+ while (iterator.hasNext()) {
+ Map.Entry<String, JsonNode> entry = iterator.next();
+ JsonNode valueNode = entry.getValue();
+ if (valueNode == null || valueNode.isNull() || !valueNode.isTextual()) {
+ return Optional.empty();
+ }
+ entries.add(new PartitionEntryImpl(entry.getKey(), valueNode.asText()));
+ }
+
+ if (entries.isEmpty()) {
+ return Optional.empty();
+ }
+
+ return Optional.of(PartitionPath.of(entries));
+ }
+
+ /**
+ * Parse metric values as numeric statistics only.
+ *
+ * <p>Non-numeric textual values are skipped and logged.
+ */
+ private StatisticValue<?> parseStatisticValue(String fieldName, JsonNode node) {
+ if (node == null || node.isNull()) {
+ return null;
+ }
+
+ if (node.isNumber()) {
+ return node.isIntegralNumber()
+ ? StatisticValues.longValue(node.longValue())
+ : StatisticValues.doubleValue(node.doubleValue());
+ }
+
+ if (node.isTextual()) {
+ String text = node.asText();
+ if (StringUtils.isBlank(text)) {
+ return null;
+ }
+
+ try {
+ long longValue = Long.parseLong(text);
+ return StatisticValues.longValue(longValue);
+ } catch (NumberFormatException e) {
+ // Ignore and try parsing as double
+ }
+
+ try {
+ double doubleValue = Double.parseDouble(text);
+ return StatisticValues.doubleValue(doubleValue);
+ } catch (NumberFormatException e) {
+ LOG.warn("Skip non-numeric textual statistic value for field '{}': {}", fieldName, text);
+ return null;
+ }
+ }
+
+ return null;
+ }
+}
diff --git a/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/calculator/local/FileStatisticsImporter.java b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/calculator/local/FileStatisticsImporter.java
new file mode 100644
index 0000000000..f5dcb24916
--- /dev/null
+++ b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/calculator/local/FileStatisticsImporter.java
@@ -0,0 +1,44 @@
+/*
+ * 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.optimizer.updater.calculator.local;
+
+import com.google.common.base.Preconditions;
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+
+/** Shared importer for file-based table statistics. */
+public class FileStatisticsImporter extends AbstractStatisticsImporter {
+
+ private final Path statisticsFilePath;
+
+ public FileStatisticsImporter(Path statisticsFilePath, String defaultCatalogName) {
+ super(defaultCatalogName);
+ Preconditions.checkArgument(statisticsFilePath != null, "statisticsFilePath must not be null");
+ this.statisticsFilePath = statisticsFilePath;
+ }
+
+ @Override
+ protected BufferedReader openReader() throws IOException {
+ return Files.newBufferedReader(statisticsFilePath, StandardCharsets.UTF_8);
+ }
+}
diff --git a/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/calculator/local/LocalStatisticsCalculator.java b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/calculator/local/LocalStatisticsCalculator.java
new file mode 100644
index 0000000000..2d2fe8c0b9
--- /dev/null
+++ b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/calculator/local/LocalStatisticsCalculator.java
@@ -0,0 +1,115 @@
+/*
+ * 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.optimizer.updater.calculator.local;
+
+import com.google.common.base.Preconditions;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Map;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.maintenance.optimizer.api.common.StatisticEntry;
+import org.apache.gravitino.maintenance.optimizer.api.common.TableAndPartitionStatistics;
+import org.apache.gravitino.maintenance.optimizer.api.updater.SupportsCalculateBulkJobStatistics;
+import org.apache.gravitino.maintenance.optimizer.api.updater.SupportsCalculateBulkTableStatistics;
+import org.apache.gravitino.maintenance.optimizer.common.OptimizerEnv;
+import org.apache.gravitino.maintenance.optimizer.common.conf.OptimizerConfig;
+
+/**
+ * Statistics calculator that reads statistics from either a local file path or an inline payload.
+ */
+public class LocalStatisticsCalculator
+ implements SupportsCalculateBulkTableStatistics, SupportsCalculateBulkJobStatistics {
+
+ public static final String NAME = "local-stats-calculator";
+ private static final String CONFIG_KEY = "localStatsCalculator";
+ public static final String STATISTICS_FILE_PATH_CONFIG =
+ OptimizerConfig.UPDATER_PREFIX + CONFIG_KEY + ".statisticsFilePath";
+ public static final String STATISTICS_PAYLOAD_CONFIG =
+ OptimizerConfig.UPDATER_PREFIX + CONFIG_KEY + ".statisticsPayload";
+
+ private StatisticsImporter statisticsImporter;
+
+ @Override
+ public String name() {
+ return NAME;
+ }
+
+ @Override
+ public void initialize(OptimizerEnv optimizerEnv) {
+ String defaultCatalog =
+ optimizerEnv.config().get(OptimizerConfig.GRAVITINO_DEFAULT_CATALOG_CONFIG);
+ String statisticsFilePath = optimizerEnv.config().getRawString(STATISTICS_FILE_PATH_CONFIG);
+ String statisticsPayload = optimizerEnv.config().getRawString(STATISTICS_PAYLOAD_CONFIG);
+ boolean hasStatisticsFilePath = StringUtils.isNotBlank(statisticsFilePath);
+ boolean hasStatisticsPayload = StringUtils.isNotBlank(statisticsPayload);
+
+ Preconditions.checkArgument(
+ hasStatisticsFilePath || hasStatisticsPayload,
+ "One of %s or %s must be provided",
+ STATISTICS_FILE_PATH_CONFIG,
+ STATISTICS_PAYLOAD_CONFIG);
+
+ Preconditions.checkArgument(
+ !(hasStatisticsFilePath && hasStatisticsPayload),
+ "Only one of %s or %s can be provided",
+ STATISTICS_FILE_PATH_CONFIG,
+ STATISTICS_PAYLOAD_CONFIG);
+
+ if (hasStatisticsFilePath) {
+ this.statisticsImporter =
+ new FileStatisticsImporter(Path.of(statisticsFilePath), defaultCatalog);
+ return;
+ }
+ this.statisticsImporter = new PayloadStatisticsImporter(statisticsPayload, defaultCatalog);
+ }
+
+ @Override
+ public TableAndPartitionStatistics calculateTableStatistics(NameIdentifier tableIdentifier) {
+ ensureInitialized();
+ Preconditions.checkArgument(tableIdentifier != null, "tableIdentifier must not be null");
+ return statisticsImporter.readTableStatistics(tableIdentifier);
+ }
+
+ @Override
+ public Map<NameIdentifier, TableAndPartitionStatistics> calculateBulkTableStatistics() {
+ ensureInitialized();
+ return statisticsImporter.bulkReadAllTableStatistics();
+ }
+
+ @Override
+ public List<StatisticEntry<?>> calculateJobStatistics(NameIdentifier jobIdentifier) {
+ ensureInitialized();
+ Preconditions.checkArgument(jobIdentifier != null, "jobIdentifier must not be null");
+ return statisticsImporter.readJobStatistics(jobIdentifier);
+ }
+
+ @Override
+ public Map<NameIdentifier, List<StatisticEntry<?>>> calculateAllJobStatistics() {
+ ensureInitialized();
+ return statisticsImporter.bulkReadAllJobStatistics();
+ }
+
+ private void ensureInitialized() {
+ Preconditions.checkState(
+ statisticsImporter != null,
+ "LocalStatisticsCalculator has not been initialized. Call initialize(optimizerEnv) first.");
+ }
+}
diff --git a/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/calculator/local/PayloadStatisticsImporter.java b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/calculator/local/PayloadStatisticsImporter.java
new file mode 100644
index 0000000000..c1edeaa55b
--- /dev/null
+++ b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/calculator/local/PayloadStatisticsImporter.java
@@ -0,0 +1,44 @@
+/*
+ * 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.optimizer.updater.calculator.local;
+
+import com.google.common.base.Preconditions;
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.StringReader;
+import org.apache.commons.lang3.StringUtils;
+
+/** Importer for inline JSON-lines statistics payloads. */
+public class PayloadStatisticsImporter extends AbstractStatisticsImporter {
+
+ private final String payload;
+
+ public PayloadStatisticsImporter(String payload, String defaultCatalogName) {
+ super(defaultCatalogName);
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(payload), "Statistics payload must be provided");
+ this.payload = payload;
+ }
+
+ @Override
+ protected BufferedReader openReader() throws IOException {
+ return new BufferedReader(new StringReader(payload));
+ }
+}
diff --git a/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/calculator/local/StatisticsImporter.java b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/calculator/local/StatisticsImporter.java
new file mode 100644
index 0000000000..6f5ec80a5b
--- /dev/null
+++ b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/calculator/local/StatisticsImporter.java
@@ -0,0 +1,59 @@
+/*
+ * 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.optimizer.updater.calculator.local;
+
+import java.util.List;
+import java.util.Map;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.maintenance.optimizer.api.common.StatisticEntry;
+import org.apache.gravitino.maintenance.optimizer.api.common.TableAndPartitionStatistics;
+
+/** Importer abstraction for table, partition, and job statistics. */
+public interface StatisticsImporter {
+ /**
+ * Reads table-level and partition-level statistics for a single table.
+ *
+ * @param tableIdentifier table identifier
+ * @return table statistics bundle for the table, empty when absent
+ */
+ TableAndPartitionStatistics readTableStatistics(NameIdentifier tableIdentifier);
+
+ /**
+ * Reads table-level and partition-level statistics for all tables in the source.
+ *
+ * @return map keyed by table identifier
+ */
+ Map<NameIdentifier, TableAndPartitionStatistics> bulkReadAllTableStatistics();
+
+ /**
+ * Reads job-level statistics for a single job.
+ *
+ * @param jobIdentifier job identifier
+ * @return job statistics for the job, empty when absent
+ */
+ List<StatisticEntry<?>> readJobStatistics(NameIdentifier jobIdentifier);
+
+ /**
+ * Reads job-level statistics for all jobs in the source.
+ *
+ * @return map keyed by job identifier
+ */
+ Map<NameIdentifier, List<StatisticEntry<?>>> bulkReadAllJobStatistics();
+}
diff --git a/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/metrics/GravitinoMetricsUpdater.java b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/metrics/GravitinoMetricsUpdater.java
new file mode 100644
index 0000000000..051149d4c3
--- /dev/null
+++ b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/metrics/GravitinoMetricsUpdater.java
@@ -0,0 +1,73 @@
+/*
+ * 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.optimizer.updater.metrics;
+
+import com.google.common.base.Preconditions;
+import java.util.List;
+import org.apache.gravitino.maintenance.optimizer.api.updater.MetricsUpdater;
+import org.apache.gravitino.maintenance.optimizer.common.OptimizerEnv;
+import org.apache.gravitino.maintenance.optimizer.updater.metrics.storage.JobMetricWriteRequest;
+import org.apache.gravitino.maintenance.optimizer.updater.metrics.storage.MetricsRepository;
+import org.apache.gravitino.maintenance.optimizer.updater.metrics.storage.TableMetricWriteRequest;
+import org.apache.gravitino.maintenance.optimizer.updater.metrics.storage.jdbc.GenericJdbcMetricsRepository;
+
+/** Metrics updater that persists table/job metrics into the configured metrics repository. */
+public class GravitinoMetricsUpdater implements MetricsUpdater {
+
+ public static final String NAME = "gravitino-metrics-updater";
+
+ private MetricsRepository metricsStorage;
+
+ @Override
+ public String name() {
+ return NAME;
+ }
+
+ @Override
+ public void initialize(OptimizerEnv optimizerEnv) {
+ this.metricsStorage = new GenericJdbcMetricsRepository();
+ this.metricsStorage.initialize(optimizerEnv.config().getAllConfig());
+ }
+
+ @Override
+ public void updateTableMetrics(List<TableMetricWriteRequest> metrics) {
+ ensureInitialized();
+ metricsStorage.storeTableMetrics(metrics);
+ }
+
+ @Override
+ public void updateJobMetrics(List<JobMetricWriteRequest> metrics) {
+ ensureInitialized();
+ metricsStorage.storeJobMetrics(metrics);
+ }
+
+ @Override
+ public void close() throws Exception {
+ if (metricsStorage != null) {
+ metricsStorage.close();
+ }
+ }
+
+ private void ensureInitialized() {
+ Preconditions.checkState(
+ metricsStorage != null,
+ "GravitinoMetricsUpdater has not been initialized. Call initialize() first.");
+ }
+}
diff --git a/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/metrics/storage/JobMetricWriteRequest.java b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/metrics/storage/JobMetricWriteRequest.java
new file mode 100644
index 0000000000..c18a1b175c
--- /dev/null
+++ b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/metrics/storage/JobMetricWriteRequest.java
@@ -0,0 +1,50 @@
+/*
+ * 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.optimizer.updater.metrics.storage;
+
+import com.google.common.base.Preconditions;
+import org.apache.gravitino.NameIdentifier;
+
+/** Write request for one job metric record. */
+public class JobMetricWriteRequest {
+ private final NameIdentifier nameIdentifier;
+ private final String metricName;
+ private final MetricRecord metric;
+
+ public JobMetricWriteRequest(
+ NameIdentifier nameIdentifier, String metricName, MetricRecord metric) {
+ Preconditions.checkArgument(nameIdentifier != null, "nameIdentifier must not be null");
+ this.nameIdentifier = nameIdentifier;
+ this.metricName = metricName;
+ this.metric = metric;
+ }
+
+ public NameIdentifier nameIdentifier() {
+ return nameIdentifier;
+ }
+
+ public String metricName() {
+ return metricName;
+ }
+
+ public MetricRecord metric() {
+ return metric;
+ }
+}
diff --git a/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/metrics/storage/MetricsRepository.java b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/metrics/storage/MetricsRepository.java
index c921164bf4..c1c6eb6b62 100644
--- a/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/metrics/storage/MetricsRepository.java
+++ b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/metrics/storage/MetricsRepository.java
@@ -21,7 +21,6 @@ package org.apache.gravitino.maintenance.optimizer.updater.metrics.storage;
import java.util.List;
import java.util.Map;
-import java.util.Optional;
import org.apache.gravitino.NameIdentifier;
/** SPI for persisting metrics produced by the optimizer updater. */
@@ -30,31 +29,31 @@ public interface MetricsRepository extends AutoCloseable {
/** Initialize the storage backend with configuration properties. */
void initialize(Map<String, String> properties);
- /** Persist a table metric (optionally scoped to a partition). */
- void storeTableMetric(
- NameIdentifier nameIdentifier,
- String metricName,
- Optional<String> partition,
- MetricRecord metric);
+ /** Persist multiple table metrics in one call. */
+ void storeTableMetrics(List<TableMetricWriteRequest> metrics);
- /** Load table-level metrics within a time window [fromTimestamp, toTimestamp). */
+ /** Load table-level metrics within a time window [fromSecs, toSecs) in epoch seconds. */
Map<String, List<MetricRecord>> getTableMetrics(
- NameIdentifier nameIdentifier, long fromTimestamp, long toTimestamp);
+ NameIdentifier nameIdentifier, long fromSecs, long toSecs);
- /** Load partition-level metrics within a time window [fromTimestamp, toTimestamp). */
+ /** Load partition-level metrics within a time window [fromSecs, toSecs) in epoch seconds. */
Map<String, List<MetricRecord>> getPartitionMetrics(
- NameIdentifier nameIdentifier, String partition, long fromTimestamp, long toTimestamp);
+ NameIdentifier nameIdentifier, String partition, long fromSecs, long toSecs);
/** Delete table metrics older than the supplied timestamp (epoch seconds), exclusive. */
int cleanupTableMetricsBefore(long timestamp);
- /** Persist a job metric. */
- void storeJobMetric(NameIdentifier nameIdentifier, String metricName, MetricRecord metric);
+ /** Persist multiple job metrics in one call. */
+ void storeJobMetrics(List<JobMetricWriteRequest> metrics);
- /** Load job metrics within a time window [fromTimestamp, toTimestamp). */
+ /** Load job metrics within a time window [fromSecs, toSecs) in epoch seconds. */
Map<String, List<MetricRecord>> getJobMetrics(
- NameIdentifier nameIdentifier, long fromTimestamp, long toTimestamp);
+ NameIdentifier nameIdentifier, long fromSecs, long toSecs);
/** Delete job metrics older than the supplied timestamp (epoch seconds), exclusive. */
int cleanupJobMetricsBefore(long timestamp);
+
+ /** Close repository resources. */
+ @Override
+ void close();
}
diff --git a/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/util/ToStatistic.java b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/metrics/storage/MetricsStorageException.java
similarity index 57%
rename from maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/util/ToStatistic.java
rename to maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/metrics/storage/MetricsStorageException.java
index 4a13628a93..1ee8545722 100644
--- a/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/util/ToStatistic.java
+++ b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/metrics/storage/MetricsStorageException.java
@@ -17,22 +17,12 @@
* under the License.
*/
-package org.apache.gravitino.maintenance.optimizer.updater.util;
+package org.apache.gravitino.maintenance.optimizer.updater.metrics.storage;
-import java.util.List;
-import org.apache.gravitino.maintenance.optimizer.api.common.StatisticEntry;
+/** Unchecked exception for metrics repository storage operations. */
+public class MetricsStorageException extends RuntimeException {
-/**
- * Represents an object that can be converted into statistics entries.
- *
- * <p>This interface is intended for updater components that need to expose their statistics in a
- * common format.
- */
-public interface ToStatistic {
- /**
- * Converts this object into a list of statistics entries.
- *
- * @return list of statistics entries; empty when no statistics are produced
- */
- List<StatisticEntry<?>> toStatistic();
+ public MetricsStorageException(String message, Throwable cause) {
+ super(message, cause);
+ }
}
diff --git a/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/metrics/storage/TableMetricWriteRequest.java b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/metrics/storage/TableMetricWriteRequest.java
new file mode 100644
index 0000000000..a57ec496df
--- /dev/null
+++ b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/metrics/storage/TableMetricWriteRequest.java
@@ -0,0 +1,61 @@
+/*
+ * 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.optimizer.updater.metrics.storage;
+
+import com.google.common.base.Preconditions;
+import java.util.Optional;
+import org.apache.gravitino.NameIdentifier;
+
+/** Write request for one table metric record. */
+public class TableMetricWriteRequest {
+ private final NameIdentifier nameIdentifier;
+ private final String metricName;
+ private final Optional<String> partition;
+ private final MetricRecord metric;
+
+ public TableMetricWriteRequest(
+ NameIdentifier nameIdentifier,
+ String metricName,
+ Optional<String> partition,
+ MetricRecord metric) {
+ Preconditions.checkArgument(nameIdentifier != null, "nameIdentifier must not be null");
+ Preconditions.checkArgument(partition != null, "partition must not be null");
+ this.nameIdentifier = nameIdentifier;
+ this.metricName = metricName;
+ this.partition = partition;
+ this.metric = metric;
+ }
+
+ public NameIdentifier nameIdentifier() {
+ return nameIdentifier;
+ }
+
+ public String metricName() {
+ return metricName;
+ }
+
+ public Optional<String> partition() {
+ return partition;
+ }
+
+ public MetricRecord metric() {
+ return metric;
+ }
+}
diff --git a/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/metrics/storage/jdbc/DataSourceJdbcConnectionProvider.java b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/metrics/storage/jdbc/DataSourceJdbcConnectionProvider.java
new file mode 100644
index 0000000000..ba71181828
--- /dev/null
+++ b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/metrics/storage/jdbc/DataSourceJdbcConnectionProvider.java
@@ -0,0 +1,62 @@
+/*
+ * 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.optimizer.updater.metrics.storage.jdbc;
+
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.util.Map;
+import org.apache.commons.dbcp2.BasicDataSource;
+import org.apache.gravitino.maintenance.optimizer.updater.metrics.storage.MetricsStorageException;
+import org.apache.gravitino.utils.jdbc.JdbcDataSourceConfig;
+import org.apache.gravitino.utils.jdbc.JdbcDataSourceFactory;
+
+/** DataSource-backed JDBC connection provider with basic pooling defaults. */
+public class DataSourceJdbcConnectionProvider {
+
+ private final BasicDataSource dataSource;
+
+ public DataSourceJdbcConnectionProvider(Map<String, String> jdbcProperties) {
+ JdbcConnectionConfig config = new JdbcConnectionConfig(jdbcProperties);
+ JdbcDataSourceConfig dataSourceConfig =
+ new JdbcDataSourceConfig(
+ config.jdbcUrl(),
+ config.username(),
+ config.password(),
+ config.driverClassName(),
+ config.maxTotal(),
+ config.minIdle(),
+ config.maxWaitMillis(),
+ config.testOnBorrow(),
+ JdbcDataSourceFactory.DEFAULT_VALIDATION_QUERY);
+ this.dataSource = JdbcDataSourceFactory.create(dataSourceConfig);
+ }
+
+ public Connection getConnection() throws SQLException {
+ return dataSource.getConnection();
+ }
+
+ public void close() {
+ try {
+ dataSource.close();
+ } catch (SQLException e) {
+ throw new MetricsStorageException("Failed to close JDBC DataSource", e);
+ }
+ }
+}
diff --git a/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/metrics/storage/jdbc/GenericJdbcMetricsRepository.java b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/metrics/storage/jdbc/GenericJdbcMetricsRepository.java
new file mode 100644
index 0000000000..3e7b818d3e
--- /dev/null
+++ b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/metrics/storage/jdbc/GenericJdbcMetricsRepository.java
@@ -0,0 +1,66 @@
+/*
+ * 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.optimizer.updater.metrics.storage.jdbc;
+
+import com.google.common.base.Preconditions;
+import java.util.HashMap;
+import java.util.Map;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.maintenance.optimizer.common.conf.OptimizerConfig;
+import org.apache.gravitino.utils.MapUtils;
+
+/** Generic JDBC repository entry for metrics storage. */
+public class GenericJdbcMetricsRepository extends JdbcMetricsRepository {
+
+ public static final String JDBC_METRICS_PREFIX = "jdbcMetrics.";
+ private static final String DEFAULT_H2_JDBC_URL =
+ "jdbc:h2:file:./data/metrics.db;DB_CLOSE_DELAY=-1;MODE=MYSQL;AUTO_SERVER=TRUE";
+
+ public static final String JDBC_URL = "jdbcUrl";
+ public static final String JDBC_USER = "jdbcUser";
+ public static final String JDBC_PASSWORD = "jdbcPassword";
+ public static final String JDBC_DRIVER = "jdbcDriver";
+ public static final String POOL_MAX_SIZE = "poolMaxSize";
+ public static final String POOL_MIN_IDLE = "poolMinIdle";
+ public static final String CONNECTION_TIMEOUT_MS = "connectionTimeoutMs";
+ public static final String TEST_ON_BORROW = "testOnBorrow";
+
+ @Override
+ public void initialize(Map<String, String> optimizerProperties) {
+ Map<String, String> jdbcProperties =
+ MapUtils.getPrefixMap(
+ optimizerProperties, OptimizerConfig.OPTIMIZER_PREFIX + JDBC_METRICS_PREFIX);
+ Map<String, String> effectiveJdbcProperties = new HashMap<>(jdbcProperties);
+
+ String jdbcUrl = effectiveJdbcProperties.getOrDefault(JDBC_URL, DEFAULT_H2_JDBC_URL);
+ if (StringUtils.isBlank(jdbcUrl)) {
+ jdbcUrl = DEFAULT_H2_JDBC_URL;
+ }
+ String username = effectiveJdbcProperties.getOrDefault(JDBC_USER, DEFAULT_USER);
+
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(username), "Property %s must be non-empty", JDBC_USER);
+
+ effectiveJdbcProperties.put(JDBC_URL, jdbcUrl);
+ DataSourceJdbcConnectionProvider connectionProvider =
+ new DataSourceJdbcConnectionProvider(effectiveJdbcProperties);
+ initializeStorage(connectionProvider);
+ }
+}
diff --git a/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/StatisticEntryImpl.java b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/metrics/storage/jdbc/H2MetricsDialect.java
similarity index 52%
rename from maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/StatisticEntryImpl.java
rename to maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/metrics/storage/jdbc/H2MetricsDialect.java
index d042a94abf..80203a0a3d 100644
--- a/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/StatisticEntryImpl.java
+++ b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/metrics/storage/jdbc/H2MetricsDialect.java
@@ -17,30 +17,13 @@
* under the License.
*/
-package org.apache.gravitino.maintenance.optimizer.updater;
+package org.apache.gravitino.maintenance.optimizer.updater.metrics.storage.jdbc;
-import lombok.AllArgsConstructor;
-import lombok.EqualsAndHashCode;
-import lombok.Getter;
-import lombok.experimental.Accessors;
-import org.apache.gravitino.maintenance.optimizer.api.common.StatisticEntry;
-import org.apache.gravitino.stats.StatisticValue;
-
-/**
- * Immutable {@link StatisticEntry} implementation used by the updater runtime.
- *
- * @param <T> underlying value type
- */
-@Accessors(fluent = true)
-@AllArgsConstructor
-@EqualsAndHashCode
-@Getter
-public final class StatisticEntryImpl<T> implements StatisticEntry<T> {
- private final String name;
- private final StatisticValue<T> value;
+/** H2 dialect marker for JDBC metrics storage. */
+public class H2MetricsDialect implements JdbcMetricsDialect {
@Override
- public String toString() {
- return "{ " + name + " : " + value.value() + '}';
+ public String name() {
+ return "h2";
}
}
diff --git a/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/metrics/storage/jdbc/JdbcConnectionConfig.java b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/metrics/storage/jdbc/JdbcConnectionConfig.java
new file mode 100644
index 0000000000..0357e44c00
--- /dev/null
+++ b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/metrics/storage/jdbc/JdbcConnectionConfig.java
@@ -0,0 +1,132 @@
+/*
+ * 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.optimizer.updater.metrics.storage.jdbc;
+
+import java.util.Map;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.Config;
+import org.apache.gravitino.config.ConfigBuilder;
+import org.apache.gravitino.config.ConfigConstants;
+import org.apache.gravitino.config.ConfigEntry;
+import org.apache.gravitino.utils.jdbc.JdbcDataSourceFactory;
+
+/** Typed JDBC connection config holder for metrics storage repositories. */
+public class JdbcConnectionConfig extends Config {
+
+ public static final ConfigEntry<String> JDBC_URL_CONFIG =
+ new ConfigBuilder(GenericJdbcMetricsRepository.JDBC_URL)
+ .doc("JDBC URL for metrics storage.")
+ .version(ConfigConstants.VERSION_1_2_0)
+ .stringConf()
+ .checkValue(StringUtils::isNotBlank, ConfigConstants.NOT_BLANK_ERROR_MSG)
+ .create();
+
+ public static final ConfigEntry<String> JDBC_USER_CONFIG =
+ new ConfigBuilder(GenericJdbcMetricsRepository.JDBC_USER)
+ .doc("JDBC username for metrics storage.")
+ .version(ConfigConstants.VERSION_1_2_0)
+ .stringConf()
+ .checkValue(StringUtils::isNotBlank, ConfigConstants.NOT_BLANK_ERROR_MSG)
+ .createWithDefault(JdbcMetricsRepository.DEFAULT_USER);
+
+ public static final ConfigEntry<String> JDBC_PASSWORD_CONFIG =
+ new ConfigBuilder(GenericJdbcMetricsRepository.JDBC_PASSWORD)
+ .doc("JDBC password for metrics storage.")
+ .version(ConfigConstants.VERSION_1_2_0)
+ .stringConf()
+ .createWithDefault(JdbcMetricsRepository.DEFAULT_PASSWORD);
+
+ public static final ConfigEntry<String> JDBC_DRIVER_CONFIG =
+ new ConfigBuilder(GenericJdbcMetricsRepository.JDBC_DRIVER)
+ .doc("Optional JDBC driver class name.")
+ .version(ConfigConstants.VERSION_1_2_0)
+ .stringConf()
+ .createWithDefault("");
+
+ public static final ConfigEntry<Integer> POOL_MAX_SIZE_CONFIG =
+ new ConfigBuilder(GenericJdbcMetricsRepository.POOL_MAX_SIZE)
+ .doc("JDBC connection pool max total size.")
+ .version(ConfigConstants.VERSION_1_2_0)
+ .intConf()
+ .checkValue(v -> v > 0, ConfigConstants.POSITIVE_NUMBER_ERROR_MSG)
+ .createWithDefault(JdbcDataSourceFactory.DEFAULT_MAX_TOTAL);
+
+ public static final ConfigEntry<Integer> POOL_MIN_IDLE_CONFIG =
+ new ConfigBuilder(GenericJdbcMetricsRepository.POOL_MIN_IDLE)
+ .doc("JDBC connection pool min idle size.")
+ .version(ConfigConstants.VERSION_1_2_0)
+ .intConf()
+ .checkValue(v -> v >= 0, "The value must be non-negative")
+ .createWithDefault(JdbcDataSourceFactory.DEFAULT_MIN_IDLE);
+
+ public static final ConfigEntry<Long> CONNECTION_TIMEOUT_MS_CONFIG =
+ new ConfigBuilder(GenericJdbcMetricsRepository.CONNECTION_TIMEOUT_MS)
+ .doc("JDBC connection max wait timeout in milliseconds.")
+ .version(ConfigConstants.VERSION_1_2_0)
+ .longConf()
+ .checkValue(v -> v > 0, ConfigConstants.POSITIVE_NUMBER_ERROR_MSG)
+ .createWithDefault(JdbcDataSourceFactory.DEFAULT_MAX_WAIT_MILLIS);
+
+ public static final ConfigEntry<Boolean> TEST_ON_BORROW_CONFIG =
+ new ConfigBuilder(GenericJdbcMetricsRepository.TEST_ON_BORROW)
+ .doc("Whether to validate JDBC connections when borrowing.")
+ .version(ConfigConstants.VERSION_1_2_0)
+ .booleanConf()
+ .createWithDefault(JdbcDataSourceFactory.DEFAULT_TEST_ON_BORROW);
+
+ public JdbcConnectionConfig(Map<String, String> properties) {
+ super(false);
+ if (properties != null) {
+ configMap.putAll(properties);
+ }
+ }
+
+ public String jdbcUrl() {
+ return get(JDBC_URL_CONFIG);
+ }
+
+ public String username() {
+ return get(JDBC_USER_CONFIG);
+ }
+
+ public String password() {
+ return get(JDBC_PASSWORD_CONFIG);
+ }
+
+ public String driverClassName() {
+ return get(JDBC_DRIVER_CONFIG);
+ }
+
+ public int maxTotal() {
+ return get(POOL_MAX_SIZE_CONFIG);
+ }
+
+ public int minIdle() {
+ return get(POOL_MIN_IDLE_CONFIG);
+ }
+
+ public long maxWaitMillis() {
+ return get(CONNECTION_TIMEOUT_MS_CONFIG);
+ }
+
+ public boolean testOnBorrow() {
+ return get(TEST_ON_BORROW_CONFIG);
+ }
+}
diff --git a/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/metrics/storage/jdbc/JdbcMetricsDialect.java b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/metrics/storage/jdbc/JdbcMetricsDialect.java
new file mode 100644
index 0000000000..5510379918
--- /dev/null
+++ b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/metrics/storage/jdbc/JdbcMetricsDialect.java
@@ -0,0 +1,27 @@
+/*
+ * 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.optimizer.updater.metrics.storage.jdbc;
+
+/** SQL dialect marker for JDBC metrics storage. */
+public interface JdbcMetricsDialect {
+
+ /** Dialect display name for logging. */
+ String name();
+}
diff --git a/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/metrics/storage/jdbc/JdbcMetricsRepository.java b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/metrics/storage/jdbc/JdbcMetricsRepository.java
new file mode 100644
index 0000000000..d16d0b0963
--- /dev/null
+++ b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/metrics/storage/jdbc/JdbcMetricsRepository.java
@@ -0,0 +1,550 @@
+/*
+ * 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.optimizer.updater.metrics.storage.jdbc;
+
+import com.google.common.base.Preconditions;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.sql.Connection;
+import java.sql.DatabaseMetaData;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.config.ConfigConstants;
+import org.apache.gravitino.maintenance.optimizer.updater.metrics.storage.JobMetricWriteRequest;
+import org.apache.gravitino.maintenance.optimizer.updater.metrics.storage.MetricRecord;
+import org.apache.gravitino.maintenance.optimizer.updater.metrics.storage.MetricRecordImpl;
+import org.apache.gravitino.maintenance.optimizer.updater.metrics.storage.MetricsRepository;
+import org.apache.gravitino.maintenance.optimizer.updater.metrics.storage.MetricsStorageException;
+import org.apache.gravitino.maintenance.optimizer.updater.metrics.storage.TableMetricWriteRequest;
+import org.apache.gravitino.utils.jdbc.JdbcSqlScriptUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * JDBC-based implementation of {@link MetricsRepository}.
+ *
+ * <p>All timestamps are epoch seconds. Read APIs use a half-open time window [fromSecs, toSecs).
+ */
+public abstract class JdbcMetricsRepository implements MetricsRepository {
+
+ private static final Logger LOG = LoggerFactory.getLogger(JdbcMetricsRepository.class);
+ private static final int BATCH_UPDATE_SIZE = 1000;
+ private static final int MAX_METRIC_VALUE_LENGTH = 1024;
+ private static final int MAX_IDENTIFIER_LENGTH = 1024;
+ private static final int MAX_METRIC_NAME_LENGTH = 1024;
+ private static final long MAX_REASONABLE_EPOCH_SECONDS = 9_999_999_999L;
+ private static final String DATABASE_PRODUCT_H2 = "h2";
+ private static final String H2_SCHEMA_FILE_NAME =
+ "optimizer-metrics-schema-" + ConfigConstants.CURRENT_SCRIPT_VERSION + "-h2.sql";
+ private static final String TABLE_METRICS_TABLE = "table_metrics";
+ private static final String JOB_METRICS_TABLE = "job_metrics";
+ private static final Set<String> REQUIRED_TABLE_METRICS_COLUMNS =
+ Set.of("table_identifier", "metric_name", "table_partition", "metric_ts", "metric_value");
+ private static final Set<String> REQUIRED_JOB_METRICS_COLUMNS =
+ Set.of("job_identifier", "metric_name", "metric_ts", "metric_value");
+
+ protected static final String DEFAULT_USER = "sa";
+ protected static final String DEFAULT_PASSWORD = "";
+
+ private DataSourceJdbcConnectionProvider connectionProvider;
+ private JdbcMetricsDialect dialect;
+ private volatile boolean initialized = false;
+
+ protected final void initializeStorage(DataSourceJdbcConnectionProvider connectionProvider) {
+ Preconditions.checkState(!initialized, "JdbcMetricsRepository has already been initialized.");
+ Preconditions.checkArgument(connectionProvider != null, "connectionProvider must not be null");
+
+ this.connectionProvider = connectionProvider;
+ initializeDatabase();
+ this.initialized = true;
+ }
+
+ private void initializeDatabase() {
+ try (Connection conn = connectionProvider.getConnection()) {
+ this.dialect = detectDialect(conn);
+ maybeInitializeSchema(conn);
+ validateSchema(conn);
+ } catch (SQLException e) {
+ String dialectName = dialect == null ? "unknown" : dialect.name();
+ throw new MetricsStorageException(
+ "Failed to initialize JDBC metrics storage, dialect=" + dialectName, e);
+ }
+ }
+
+ private void validateSchema(Connection connection) throws SQLException {
+ DatabaseMetaData metaData = connection.getMetaData();
+ checkRequiredTable(metaData, TABLE_METRICS_TABLE);
+ checkRequiredTable(metaData, JOB_METRICS_TABLE);
+ checkRequiredColumns(metaData, TABLE_METRICS_TABLE, REQUIRED_TABLE_METRICS_COLUMNS);
+ checkRequiredColumns(metaData, JOB_METRICS_TABLE, REQUIRED_JOB_METRICS_COLUMNS);
+ }
+
+ private void checkRequiredTable(DatabaseMetaData metaData, String tableName) throws SQLException {
+ if (hasTable(metaData, tableName)) {
+ return;
+ }
+
+ throw new MetricsStorageException(
+ "Required table '"
+ + tableName
+ + "' is missing. Initialize metrics schema with SQL scripts before startup.",
+ new IllegalStateException("Missing table: " + tableName));
+ }
+
+ private void checkRequiredColumns(
+ DatabaseMetaData metaData, String tableName, Set<String> requiredColumns)
+ throws SQLException {
+ Set<String> existingColumns = listColumns(metaData, tableName);
+ Set<String> missingColumns = new HashSet<>(requiredColumns);
+ missingColumns.removeAll(existingColumns);
+ if (!missingColumns.isEmpty()) {
+ throw new MetricsStorageException(
+ "Table '"
+ + tableName
+ + "' is missing required columns "
+ + missingColumns
+ + ". Run schema migration before startup.",
+ new IllegalStateException(
+ "Missing required columns in " + tableName + ": " + missingColumns));
+ }
+ }
+
+ private boolean hasTable(DatabaseMetaData metaData, String tableName) throws SQLException {
+ try (ResultSet rs = metaData.getTables(null, null, tableName, new String[] {"TABLE"})) {
+ if (rs.next()) {
+ return true;
+ }
+ }
+ try (ResultSet rs =
+ metaData.getTables(
+ null, null, tableName.toUpperCase(Locale.ROOT), new String[] {"TABLE"})) {
+ if (rs.next()) {
+ return true;
+ }
+ }
+ try (ResultSet rs =
+ metaData.getTables(
+ null, null, tableName.toLowerCase(Locale.ROOT), new String[] {"TABLE"})) {
+ return rs.next();
+ }
+ }
+
+ private Set<String> listColumns(DatabaseMetaData metaData, String tableName) throws SQLException {
+ Set<String> columns = new HashSet<>();
+ collectColumns(metaData, tableName, columns);
+ collectColumns(metaData, tableName.toUpperCase(Locale.ROOT), columns);
+ collectColumns(metaData, tableName.toLowerCase(Locale.ROOT), columns);
+ return columns;
+ }
+
+ private void collectColumns(DatabaseMetaData metaData, String tableName, Set<String> columns)
+ throws SQLException {
+ try (ResultSet rs = metaData.getColumns(null, null, tableName, null)) {
+ while (rs.next()) {
+ String columnName = rs.getString("COLUMN_NAME");
+ if (StringUtils.isNotBlank(columnName)) {
+ columns.add(columnName.toLowerCase(Locale.ROOT));
+ }
+ }
+ }
+ }
+
+ private JdbcMetricsDialect detectDialect(Connection connection) throws SQLException {
+ String databaseProduct =
+ connection.getMetaData().getDatabaseProductName().toLowerCase(Locale.ROOT);
+ if (databaseProduct.contains(DATABASE_PRODUCT_H2)) {
+ return new H2MetricsDialect();
+ }
+
+ throw new IllegalArgumentException(
+ "Unsupported JDBC database product for metrics repository: " + databaseProduct);
+ }
+
+ private void maybeInitializeSchema(Connection connection) {
+ if (!(dialect instanceof H2MetricsDialect)) {
+ return;
+ }
+
+ try {
+ executeH2SchemaSql(connection);
+ } catch (IOException | SQLException | IllegalStateException e) {
+ throw new MetricsStorageException(
+ "Failed to initialize H2 metrics schema from script: " + H2_SCHEMA_FILE_NAME, e);
+ }
+ }
+
+ private void executeH2SchemaSql(Connection connection) throws IOException, SQLException {
+ String gravitinoHome = System.getenv("GRAVITINO_HOME");
+ Preconditions.checkState(
+ StringUtils.isNotBlank(gravitinoHome),
+ "GRAVITINO_HOME is not set. Cannot locate H2 metrics schema script.");
+ Path scriptPath = Paths.get(gravitinoHome, "scripts", "h2", H2_SCHEMA_FILE_NAME);
+ Preconditions.checkState(
+ Files.exists(scriptPath),
+ "H2 metrics schema script not found at %s. Please ensure distribution scripts are present.",
+ scriptPath);
+ executeSchemaSql(connection, Files.readString(scriptPath, StandardCharsets.UTF_8));
+ }
+
+ private void executeSchemaSql(Connection connection, String sqlContent) throws SQLException {
+ JdbcSqlScriptUtils.executeSqlScript(connection, sqlContent);
+ }
+
+ @Override
+ public void storeTableMetrics(List<TableMetricWriteRequest> metrics) {
+ Preconditions.checkArgument(metrics != null, "metrics must not be null");
+ if (metrics.isEmpty()) {
+ return;
+ }
+
+ String insertSql =
+ "INSERT INTO table_metrics (table_identifier, metric_name, table_partition, metric_ts, metric_value) VALUES (?, ?, ?, ?, ?)";
+
+ try (Connection conn = getConnection();
+ PreparedStatement insertStmt = conn.prepareStatement(insertSql)) {
+ int batchCount = 0;
+ for (TableMetricWriteRequest request : metrics) {
+ Preconditions.checkArgument(request != null, "table metric request must not be null");
+ validateWriteArguments(
+ request.nameIdentifier(), request.metricName(), request.partition(), request.metric());
+ String normalizedIdentifier = normalizeIdentifier(request.nameIdentifier());
+ String normalizedMetricName = normalizeMetricName(request.metricName());
+ Optional<String> normalizedPartition = normalizePartition(request.partition());
+ MetricRecord metric = request.metric();
+ insertStmt.setString(1, normalizedIdentifier);
+ insertStmt.setString(2, normalizedMetricName);
+ insertStmt.setString(3, normalizedPartition.orElse(null));
+ insertStmt.setLong(4, metric.getTimestamp());
+ insertStmt.setString(5, metric.getValue());
+ insertStmt.addBatch();
+ batchCount++;
+ if (batchCount >= BATCH_UPDATE_SIZE) {
+ insertStmt.executeBatch();
+ batchCount = 0;
+ }
+ }
+ if (batchCount > 0) {
+ insertStmt.executeBatch();
+ }
+ } catch (SQLException e) {
+ throw new MetricsStorageException(
+ "Failed to batch store table metrics, size=" + metrics.size(), e);
+ }
+ }
+
+ @Override
+ public Map<String, List<MetricRecord>> getTableMetrics(
+ NameIdentifier nameIdentifier, long fromSecs, long toSecs) {
+ Preconditions.checkArgument(nameIdentifier != null, "nameIdentifier must not be null");
+ validateTimeWindow(fromSecs, toSecs);
+ Map<String, List<MetricRecord>> resultMap = new HashMap<>();
+ String sql =
+ "SELECT metric_name, metric_ts, metric_value FROM table_metrics "
+ + "WHERE table_identifier = ? AND metric_ts >= ? AND metric_ts < ? "
+ + "AND table_partition IS NULL";
+
+ try (Connection conn = getConnection();
+ PreparedStatement pstmt = conn.prepareStatement(sql)) {
+ pstmt.setString(1, normalizeIdentifier(nameIdentifier));
+ pstmt.setLong(2, fromSecs);
+ pstmt.setLong(3, toSecs);
+
+ try (ResultSet rs = pstmt.executeQuery()) {
+ while (rs.next()) {
+ String metricName = rs.getString("metric_name");
+ long timestamp = rs.getLong("metric_ts");
+ String value = rs.getString("metric_value");
+ MetricRecord metric = new MetricRecordImpl(timestamp, value);
+ resultMap.computeIfAbsent(metricName, k -> new ArrayList<>()).add(metric);
+ }
+ }
+ } catch (SQLException e) {
+ throw new MetricsStorageException(
+ "Failed to retrieve table metrics: identifier="
+ + nameIdentifier
+ + ", from="
+ + fromSecs
+ + ", to="
+ + toSecs,
+ e);
+ }
+ return resultMap;
+ }
+
+ @Override
+ public Map<String, List<MetricRecord>> getPartitionMetrics(
+ NameIdentifier nameIdentifier, String partition, long fromSecs, long toSecs) {
+ Preconditions.checkArgument(nameIdentifier != null, "nameIdentifier must not be null");
+ Preconditions.checkArgument(StringUtils.isNotBlank(partition), "partition must not be blank");
+ validateTimeWindow(fromSecs, toSecs);
+ Map<String, List<MetricRecord>> resultMap = new HashMap<>();
+ String normalizedPartition = normalizePartition(partition).orElse(null);
+ String sql =
+ "SELECT metric_name, metric_ts, metric_value FROM table_metrics "
+ + "WHERE table_identifier = ? AND table_partition = ? "
+ + "AND metric_ts >= ? AND metric_ts < ?";
+
+ try (Connection conn = getConnection();
+ PreparedStatement pstmt = conn.prepareStatement(sql)) {
+ pstmt.setString(1, normalizeIdentifier(nameIdentifier));
+ pstmt.setString(2, normalizedPartition);
+ pstmt.setLong(3, fromSecs);
+ pstmt.setLong(4, toSecs);
+
+ try (ResultSet rs = pstmt.executeQuery()) {
+ while (rs.next()) {
+ String metricName = rs.getString("metric_name");
+ long timestamp = rs.getLong("metric_ts");
+ String value = rs.getString("metric_value");
+ MetricRecord metric = new MetricRecordImpl(timestamp, value);
+ resultMap.computeIfAbsent(metricName, k -> new ArrayList<>()).add(metric);
+ }
+ }
+ } catch (SQLException e) {
+ throw new MetricsStorageException(
+ "Failed to retrieve partition metrics: identifier="
+ + nameIdentifier
+ + ", partition="
+ + partition
+ + ", from="
+ + fromSecs
+ + ", to="
+ + toSecs,
+ e);
+ }
+ return resultMap;
+ }
+
+ @Override
+ public void storeJobMetrics(List<JobMetricWriteRequest> metrics) {
+ Preconditions.checkArgument(metrics != null, "metrics must not be null");
+ if (metrics.isEmpty()) {
+ return;
+ }
+
+ String insertSql =
+ "INSERT INTO job_metrics (job_identifier, metric_name, metric_ts, metric_value) VALUES (?, ?, ?, ?)";
+
+ try (Connection conn = getConnection();
+ PreparedStatement insertStmt = conn.prepareStatement(insertSql)) {
+ int batchCount = 0;
+ for (JobMetricWriteRequest request : metrics) {
+ Preconditions.checkArgument(request != null, "job metric request must not be null");
+ validateWriteArguments(
+ request.nameIdentifier(), request.metricName(), Optional.empty(), request.metric());
+ String normalizedIdentifier = normalizeIdentifier(request.nameIdentifier());
+ String normalizedMetricName = normalizeMetricName(request.metricName());
+ MetricRecord metric = request.metric();
+ insertStmt.setString(1, normalizedIdentifier);
+ insertStmt.setString(2, normalizedMetricName);
+ insertStmt.setLong(3, metric.getTimestamp());
+ insertStmt.setString(4, metric.getValue());
+ insertStmt.addBatch();
+ batchCount++;
+ if (batchCount >= BATCH_UPDATE_SIZE) {
+ insertStmt.executeBatch();
+ batchCount = 0;
+ }
+ }
+ if (batchCount > 0) {
+ insertStmt.executeBatch();
+ }
+ } catch (SQLException e) {
+ throw new MetricsStorageException(
+ "Failed to batch store job metrics, size=" + metrics.size(), e);
+ }
+ }
+
+ @Override
+ public Map<String, List<MetricRecord>> getJobMetrics(
+ NameIdentifier nameIdentifier, long fromSecs, long toSecs) {
+ Preconditions.checkArgument(nameIdentifier != null, "nameIdentifier must not be null");
+ validateTimeWindow(fromSecs, toSecs);
+ Map<String, List<MetricRecord>> resultMap = new HashMap<>();
+ String sql =
+ "SELECT metric_name, metric_ts, metric_value FROM job_metrics "
+ + "WHERE job_identifier = ? AND metric_ts >= ? AND metric_ts < ?";
+
+ try (Connection conn = getConnection();
+ PreparedStatement pstmt = conn.prepareStatement(sql)) {
+ pstmt.setString(1, normalizeIdentifier(nameIdentifier));
+ pstmt.setLong(2, fromSecs);
+ pstmt.setLong(3, toSecs);
+
+ try (ResultSet rs = pstmt.executeQuery()) {
+ while (rs.next()) {
+ String metricName = rs.getString("metric_name");
+ long timestamp = rs.getLong("metric_ts");
+ String value = rs.getString("metric_value");
+ MetricRecord metric = new MetricRecordImpl(timestamp, value);
+ resultMap.computeIfAbsent(metricName, k -> new ArrayList<>()).add(metric);
+ }
+ }
+ } catch (SQLException e) {
+ throw new MetricsStorageException(
+ "Failed to retrieve job metrics: identifier="
+ + nameIdentifier
+ + ", from="
+ + fromSecs
+ + ", to="
+ + toSecs,
+ e);
+ }
+ return resultMap;
+ }
+
+ @Override
+ public int cleanupTableMetricsBefore(long beforeTimestamp) {
+ Preconditions.checkArgument(
+ beforeTimestamp >= 0, "beforeTimestamp must be non-negative, but got %s", beforeTimestamp);
+ Preconditions.checkArgument(
+ beforeTimestamp <= MAX_REASONABLE_EPOCH_SECONDS,
+ "beforeTimestamp must be epoch seconds, but got suspiciously large value %s",
+ beforeTimestamp);
+ String sql = "DELETE FROM table_metrics WHERE metric_ts < ?";
+
+ try (Connection conn = getConnection();
+ PreparedStatement pstmt = conn.prepareStatement(sql)) {
+ pstmt.setLong(1, beforeTimestamp);
+ int deletedRows = pstmt.executeUpdate();
+ LOG.info("Cleaned up {} rows from table_metrics before {}", deletedRows, beforeTimestamp);
+ return deletedRows;
+ } catch (SQLException e) {
+ throw new MetricsStorageException(
+ "Failed to cleanup table metrics before timestamp: " + beforeTimestamp, e);
+ }
+ }
+
+ @Override
+ public int cleanupJobMetricsBefore(long beforeTimestamp) {
+ Preconditions.checkArgument(
+ beforeTimestamp >= 0, "beforeTimestamp must be non-negative, but got %s", beforeTimestamp);
+ Preconditions.checkArgument(
+ beforeTimestamp <= MAX_REASONABLE_EPOCH_SECONDS,
+ "beforeTimestamp must be epoch seconds, but got suspiciously large value %s",
+ beforeTimestamp);
+ String sql = "DELETE FROM job_metrics WHERE metric_ts < ?";
+
+ try (Connection conn = getConnection();
+ PreparedStatement pstmt = conn.prepareStatement(sql)) {
+ pstmt.setLong(1, beforeTimestamp);
+ int deletedRows = pstmt.executeUpdate();
+ LOG.info("Cleaned up {} rows from job_metrics before {}", deletedRows, beforeTimestamp);
+ return deletedRows;
+ } catch (SQLException e) {
+ throw new MetricsStorageException(
+ "Failed to cleanup job metrics before timestamp: " + beforeTimestamp, e);
+ }
+ }
+
+ private Connection getConnection() throws SQLException {
+ ensureInitialized();
+ return connectionProvider.getConnection();
+ }
+
+ private void ensureInitialized() {
+ Preconditions.checkState(
+ initialized,
+ "JdbcMetricsRepository has not been initialized. Call initialize(properties) before use.");
+ }
+
+ @Override
+ public void close() {
+ if (connectionProvider != null) {
+ connectionProvider.close();
+ }
+ }
+
+ private void validateTimeWindow(long fromSecs, long toSecs) {
+ Preconditions.checkArgument(
+ fromSecs < toSecs,
+ "Invalid time window: fromSecs (%s) must be less than toSecs (%s)",
+ fromSecs,
+ toSecs);
+ }
+
+ private void validateWriteArguments(
+ NameIdentifier nameIdentifier,
+ String metricName,
+ Optional<String> partition,
+ MetricRecord metric) {
+ Preconditions.checkArgument(nameIdentifier != null, "nameIdentifier must not be null");
+ Preconditions.checkArgument(StringUtils.isNotBlank(metricName), "metricName must not be blank");
+ Preconditions.checkArgument(
+ nameIdentifier.toString().length() <= MAX_IDENTIFIER_LENGTH,
+ "nameIdentifier length exceeds max %s: actual=%s",
+ MAX_IDENTIFIER_LENGTH,
+ nameIdentifier.toString().length());
+ Preconditions.checkArgument(
+ metricName.length() <= MAX_METRIC_NAME_LENGTH,
+ "metricName length exceeds max %s: actual=%s",
+ MAX_METRIC_NAME_LENGTH,
+ metricName.length());
+ Preconditions.checkArgument(metric != null, "metric record must not be null");
+ Preconditions.checkArgument(
+ metric.getTimestamp() >= 0,
+ "metric timestamp must be non-negative, but got %s",
+ metric.getTimestamp());
+ Preconditions.checkArgument(
+ metric.getTimestamp() <= MAX_REASONABLE_EPOCH_SECONDS,
+ "metric timestamp must be epoch seconds, but got suspiciously large value %s",
+ metric.getTimestamp());
+ Preconditions.checkArgument(metric.getValue() != null, "metric value must not be null");
+ Preconditions.checkArgument(
+ metric.getValue().length() <= MAX_METRIC_VALUE_LENGTH,
+ "metric value length exceeds max %s: actual=%s",
+ MAX_METRIC_VALUE_LENGTH,
+ metric.getValue().length());
+ if (partition.isPresent()) {
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(partition.get()), "partition must not be blank");
+ }
+ }
+
+ private String normalizeIdentifier(NameIdentifier identifier) {
+ return identifier == null ? null : identifier.toString().toLowerCase(Locale.ROOT);
+ }
+
+ private String normalizeMetricName(String metricName) {
+ return metricName == null ? null : metricName.toLowerCase(Locale.ROOT);
+ }
+
+ private Optional<String> normalizePartition(String partition) {
+ return normalizePartition(Optional.ofNullable(partition));
+ }
+
+ private Optional<String> normalizePartition(Optional<String> partition) {
+ return partition.map(p -> p.toLowerCase(Locale.ROOT));
+ }
+}
diff --git a/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/statistics/GravitinoStatisticsUpdater.java b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/statistics/GravitinoStatisticsUpdater.java
new file mode 100644
index 0000000000..63fa0e65fa
--- /dev/null
+++ b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/updater/statistics/GravitinoStatisticsUpdater.java
@@ -0,0 +1,156 @@
+/*
+ * 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.optimizer.updater.statistics;
+
+import com.google.common.base.Preconditions;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.client.GravitinoClient;
+import org.apache.gravitino.maintenance.optimizer.api.common.PartitionPath;
+import org.apache.gravitino.maintenance.optimizer.api.common.StatisticEntry;
+import org.apache.gravitino.maintenance.optimizer.api.updater.StatisticsUpdater;
+import org.apache.gravitino.maintenance.optimizer.common.OptimizerEnv;
+import org.apache.gravitino.maintenance.optimizer.common.util.GravitinoClientUtils;
+import org.apache.gravitino.maintenance.optimizer.common.util.IdentifierUtils;
+import org.apache.gravitino.maintenance.optimizer.recommender.util.PartitionUtils;
+import org.apache.gravitino.stats.PartitionStatisticsUpdate;
+import org.apache.gravitino.stats.StatisticValue;
+
+/** Statistics updater that persists table/partition statistics to Gravitino. */
+public class GravitinoStatisticsUpdater implements StatisticsUpdater {
+
+ public static final String NAME = "gravitino-statistics-updater";
+ private GravitinoClient gravitinoClient;
+
+ @Override
+ public String name() {
+ return NAME;
+ }
+
+ @Override
+ public void initialize(OptimizerEnv optimizerEnv) {
+ this.gravitinoClient = GravitinoClientUtils.createClient(optimizerEnv);
+ }
+
+ @Override
+ public void updateTableStatistics(
+ NameIdentifier tableIdentifier, List<StatisticEntry<?>> tableStatistics) {
+ Preconditions.checkArgument(tableIdentifier != null, "tableIdentifier must not be null");
+ ensureInitialized();
+ doUpdateTableStatistics(tableIdentifier, getTableStatisticsMap(tableStatistics));
+ }
+
+ @Override
+ public void updatePartitionStatistics(
+ NameIdentifier tableIdentifier,
+ Map<PartitionPath, List<StatisticEntry<?>>> partitionStatistics) {
+ Preconditions.checkArgument(tableIdentifier != null, "tableIdentifier must not be null");
+ ensureInitialized();
+ doUpdatePartitionStatistics(
+ tableIdentifier, getPartitionStatisticsUpdates(partitionStatistics));
+ }
+
+ private void doUpdateTableStatistics(
+ NameIdentifier tableIdentifier, Map<String, StatisticValue<?>> tableStatisticsMap) {
+ if (tableStatisticsMap.isEmpty()) {
+ return;
+ }
+ gravitinoClient
+ .loadCatalog(IdentifierUtils.getCatalogNameFromTableIdentifier(tableIdentifier))
+ .asTableCatalog()
+ .loadTable(IdentifierUtils.removeCatalogFromIdentifier(tableIdentifier))
+ .supportsStatistics()
+ .updateStatistics(tableStatisticsMap);
+ }
+
+ private Map<String, StatisticValue<?>> getTableStatisticsMap(List<StatisticEntry<?>> statistics) {
+ if (statistics == null || statistics.isEmpty()) {
+ return Map.of();
+ }
+ return toStatisticValueMap(statistics, "table statistics");
+ }
+
+ private List<PartitionStatisticsUpdate> getPartitionStatisticsUpdates(
+ Map<PartitionPath, List<StatisticEntry<?>>> partitionStatistics) {
+ if (partitionStatistics == null || partitionStatistics.isEmpty()) {
+ return List.of();
+ }
+ return partitionStatistics.entrySet().stream()
+ .map(
+ entry -> {
+ Preconditions.checkArgument(
+ entry.getKey() != null, "partition path must not be null");
+ return new PartitionStatisticsUpdate() {
+ @Override
+ public String partitionName() {
+ return PartitionUtils.encodePartitionPath(entry.getKey());
+ }
+
+ @Override
+ public Map<String, StatisticValue<?>> statistics() {
+ return toStatisticValueMap(entry.getValue(), "partition statistics");
+ }
+ };
+ })
+ .collect(Collectors.toList());
+ }
+
+ private Map<String, StatisticValue<?>> toStatisticValueMap(
+ List<StatisticEntry<?>> statistics, String context) {
+ Preconditions.checkArgument(statistics != null, "%s list must not be null", context);
+ Map<String, StatisticValue<?>> result = new LinkedHashMap<>();
+ for (StatisticEntry<?> statistic : statistics) {
+ Preconditions.checkArgument(statistic != null, "%s entry must not be null", context);
+ Preconditions.checkArgument(statistic.name() != null, "%s name must not be null", context);
+ Preconditions.checkArgument(statistic.value() != null, "%s value must not be null", context);
+ result.put(statistic.name(), statistic.value());
+ }
+ return result;
+ }
+
+ private void ensureInitialized() {
+ Preconditions.checkState(
+ gravitinoClient != null,
+ "GravitinoStatisticsUpdater has not been initialized. Call initialize(optimizerEnv) first.");
+ }
+
+ private void doUpdatePartitionStatistics(
+ NameIdentifier tableIdentifier, List<PartitionStatisticsUpdate> partitionStatisticsUpdates) {
+ if (partitionStatisticsUpdates.isEmpty()) {
+ return;
+ }
+ gravitinoClient
+ .loadCatalog(IdentifierUtils.getCatalogNameFromTableIdentifier(tableIdentifier))
+ .asTableCatalog()
+ .loadTable(IdentifierUtils.removeCatalogFromIdentifier(tableIdentifier))
+ .supportsPartitionStatistics()
+ .updatePartitionStatistics(partitionStatisticsUpdates);
+ }
+
+ @Override
+ public void close() throws Exception {
+ if (gravitinoClient != null) {
+ gravitinoClient.close();
+ }
+ }
+}
diff --git a/maintenance/optimizer/src/main/resources/META-INF/services/org.apache.gravitino.maintenance.optimizer.api.common.Provider b/maintenance/optimizer/src/main/resources/META-INF/services/org.apache.gravitino.maintenance.optimizer.api.common.Provider
index 665bd4a3ff..2458ac7926 100644
--- a/maintenance/optimizer/src/main/resources/META-INF/services/org.apache.gravitino.maintenance.optimizer.api.common.Provider
+++ b/maintenance/optimizer/src/main/resources/META-INF/services/org.apache.gravitino.maintenance.optimizer.api.common.Provider
@@ -21,3 +21,5 @@ org.apache.gravitino.maintenance.optimizer.recommender.statistics.GravitinoStati
org.apache.gravitino.maintenance.optimizer.recommender.table.GravitinoTableMetadataProvider
org.apache.gravitino.maintenance.optimizer.recommender.job.GravitinoJobSubmitter
org.apache.gravitino.maintenance.optimizer.recommender.job.NoopJobSubmitter
+org.apache.gravitino.maintenance.optimizer.updater.statistics.GravitinoStatisticsUpdater
+org.apache.gravitino.maintenance.optimizer.updater.metrics.GravitinoMetricsUpdater
diff --git a/maintenance/optimizer/src/main/resources/META-INF/services/org.apache.gravitino.maintenance.optimizer.api.updater.StatisticsCalculator b/maintenance/optimizer/src/main/resources/META-INF/services/org.apache.gravitino.maintenance.optimizer.api.updater.StatisticsCalculator
new file mode 100644
index 0000000000..3cd336d866
--- /dev/null
+++ b/maintenance/optimizer/src/main/resources/META-INF/services/org.apache.gravitino.maintenance.optimizer.api.updater.StatisticsCalculator
@@ -0,0 +1,20 @@
+#
+# 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.
+#
+
+org.apache.gravitino.maintenance.optimizer.updater.calculator.local.LocalStatisticsCalculator
diff --git a/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/updater/MetricsUpdaterForTest.java b/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/updater/MetricsUpdaterForTest.java
index 5f02504306..90d019c7fe 100644
--- a/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/updater/MetricsUpdaterForTest.java
+++ b/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/updater/MetricsUpdaterForTest.java
@@ -23,10 +23,10 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
-import org.apache.gravitino.NameIdentifier;
-import org.apache.gravitino.maintenance.optimizer.api.common.MetricSample;
import org.apache.gravitino.maintenance.optimizer.api.updater.MetricsUpdater;
import org.apache.gravitino.maintenance.optimizer.common.OptimizerEnv;
+import org.apache.gravitino.maintenance.optimizer.updater.metrics.storage.JobMetricWriteRequest;
+import org.apache.gravitino.maintenance.optimizer.updater.metrics.storage.TableMetricWriteRequest;
public class MetricsUpdaterForTest implements MetricsUpdater {
@@ -70,12 +70,12 @@ public class MetricsUpdaterForTest implements MetricsUpdater {
public void initialize(OptimizerEnv optimizerEnv) {}
@Override
- public void updateTableMetrics(NameIdentifier nameIdentifier, List<MetricSample> metrics) {
+ public void updateTableMetrics(List<TableMetricWriteRequest> metrics) {
tableUpdates.incrementAndGet();
}
@Override
- public void updateJobMetrics(NameIdentifier nameIdentifier, List<MetricSample> metrics) {
+ public void updateJobMetrics(List<JobMetricWriteRequest> metrics) {
jobUpdates.incrementAndGet();
}
diff --git a/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/updater/StatisticsCalculatorForTest.java b/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/updater/StatisticsCalculatorForTest.java
index 3736deff07..66be571dfb 100644
--- a/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/updater/StatisticsCalculatorForTest.java
+++ b/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/updater/StatisticsCalculatorForTest.java
@@ -25,10 +25,11 @@ import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.maintenance.optimizer.api.common.PartitionEntry;
import org.apache.gravitino.maintenance.optimizer.api.common.PartitionPath;
import org.apache.gravitino.maintenance.optimizer.api.common.StatisticEntry;
-import org.apache.gravitino.maintenance.optimizer.api.common.TableStatisticsBundle;
+import org.apache.gravitino.maintenance.optimizer.api.common.TableAndPartitionStatistics;
import org.apache.gravitino.maintenance.optimizer.api.updater.SupportsCalculateBulkJobStatistics;
import org.apache.gravitino.maintenance.optimizer.api.updater.SupportsCalculateBulkTableStatistics;
import org.apache.gravitino.maintenance.optimizer.common.OptimizerEnv;
+import org.apache.gravitino.maintenance.optimizer.common.StatisticEntryImpl;
import org.apache.gravitino.stats.StatisticValue;
import org.apache.gravitino.stats.StatisticValues;
@@ -46,7 +47,7 @@ public class StatisticsCalculatorForTest
public void initialize(OptimizerEnv optimizerEnv) {}
@Override
- public TableStatisticsBundle calculateTableStatistics(NameIdentifier tableIdentifier) {
+ public TableAndPartitionStatistics calculateTableStatistics(NameIdentifier tableIdentifier) {
List<StatisticEntry<?>> tableStatistics = List.of(entry("row_count", 10L));
Map<PartitionPath, List<StatisticEntry<?>>> partitionStatistics =
Map.of(
@@ -54,7 +55,7 @@ public class StatisticsCalculatorForTest
List.of(entry("row_count", 3L)),
PartitionPath.of(List.of(new TestPartitionEntry("p2", "v2"))),
List.of(entry("row_count", 7L)));
- return new TableStatisticsBundle(tableStatistics, partitionStatistics);
+ return new TableAndPartitionStatistics(tableStatistics, partitionStatistics);
}
@Override
@@ -63,7 +64,7 @@ public class StatisticsCalculatorForTest
}
@Override
- public Map<NameIdentifier, TableStatisticsBundle> calculateBulkTableStatistics() {
+ public Map<NameIdentifier, TableAndPartitionStatistics> calculateBulkTableStatistics() {
NameIdentifier identifier = NameIdentifier.of("catalog", "schema", "table");
return Map.of(identifier, calculateTableStatistics(identifier));
}
@@ -76,7 +77,7 @@ public class StatisticsCalculatorForTest
private static StatisticEntry<?> entry(String name, long value) {
StatisticValue statisticValue = StatisticValues.longValue(value);
- return new StatisticEntryImpl(name, statisticValue);
+ return new StatisticEntryImpl<>(name, statisticValue);
}
private static final class TestPartitionEntry implements PartitionEntry {
diff --git a/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/updater/TestUpdater.java b/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/updater/TestUpdater.java
index f7eb63b8c8..89ec15c3f8 100644
--- a/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/updater/TestUpdater.java
+++ b/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/updater/TestUpdater.java
@@ -73,7 +73,7 @@ public class TestUpdater {
assertNotNull(metricsUpdater);
assertEquals(0, statisticsUpdater.tableUpdates());
assertEquals(0, statisticsUpdater.partitionUpdates());
- assertEquals(2, metricsUpdater.tableUpdates());
+ assertEquals(1, metricsUpdater.tableUpdates());
assertEquals(1, metricsUpdater.jobUpdates());
}
@@ -107,7 +107,7 @@ public class TestUpdater {
assertNotNull(metricsUpdater);
assertEquals(0, statisticsUpdater.tableUpdates());
assertEquals(0, statisticsUpdater.partitionUpdates());
- assertEquals(2, metricsUpdater.tableUpdates());
+ assertEquals(1, metricsUpdater.tableUpdates());
assertEquals(1, metricsUpdater.jobUpdates());
}
diff --git a/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/updater/calculator/local/TestLocalStatisticsCalculator.java b/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/updater/calculator/local/TestLocalStatisticsCalculator.java
new file mode 100644
index 0000000000..b065528945
--- /dev/null
+++ b/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/updater/calculator/local/TestLocalStatisticsCalculator.java
@@ -0,0 +1,472 @@
+/*
+ * 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.optimizer.updater.calculator.local;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.maintenance.optimizer.api.common.PartitionPath;
+import org.apache.gravitino.maintenance.optimizer.api.common.StatisticEntry;
+import org.apache.gravitino.maintenance.optimizer.api.common.TableAndPartitionStatistics;
+import org.apache.gravitino.maintenance.optimizer.common.OptimizerEnv;
+import org.apache.gravitino.maintenance.optimizer.common.PartitionEntryImpl;
+import org.apache.gravitino.maintenance.optimizer.common.conf.OptimizerConfig;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+class TestLocalStatisticsCalculator {
+
+ @TempDir Path tempDir;
+
+ @Test
+ void testComputeTableStatisticsUsesReader() throws IOException {
+ Path statsFile = tempDir.resolve("stats.json");
+ Files.write(
+ statsFile,
+ List.of(
+ "{\"identifier\":\"catalog.schema.table\",\"stats-type\":\"table\",\"s1\":1}",
+ "{\"identifier\":\"catalog.schema.table\",\"stats-type\":\"table\",\"s1\":2}",
+ "{\"identifier\":\"other\",\"stats-type\":\"table\",\"s1\":100}"));
+
+ LocalStatisticsCalculator calculator = new LocalStatisticsCalculator();
+ OptimizerEnv env = new OptimizerEnv(createConfig(statsFile.toString(), null));
+ calculator.initialize(env);
+
+ List<StatisticEntry<?>> stats =
+ calculator
+ .calculateTableStatistics(NameIdentifier.parse("catalog.schema.table"))
+ .tableStatistics();
+ Assertions.assertEquals(1, stats.size());
+ Assertions.assertEquals("s1", stats.get(0).name());
+ Assertions.assertEquals(2L, stats.get(0).value().value());
+ }
+
+ @Test
+ void testComputeAllTableStatistics() throws IOException {
+ Path statsFile = tempDir.resolve("stats.json");
+ Files.write(
+ statsFile,
+ List.of(
+ "{\"identifier\":\"catalog.schema.table\",\"stats-type\":\"table\",\"s1\":1,\"s2\":5}",
+ "{\"identifier\":\"catalog.schema.table\",\"stats-type\":\"table\",\"s1\":3}",
+ "{\"identifier\":\"catalog.schema.other\",\"stats-type\":\"table\",\"s1\":10}"));
+
+ LocalStatisticsCalculator calculator = new LocalStatisticsCalculator();
+ OptimizerEnv env = new OptimizerEnv(createConfig(statsFile.toString(), null));
+ calculator.initialize(env);
+
+ Map<NameIdentifier, TableAndPartitionStatistics> allStatistics =
+ calculator.calculateBulkTableStatistics();
+ Assertions.assertEquals(2, allStatistics.size());
+
+ Map<String, StatisticEntry<?>> tableStats =
+ toNameMap(
+ allStatistics.get(NameIdentifier.parse("catalog.schema.table")).tableStatistics());
+ Assertions.assertEquals(2, tableStats.size());
+ Assertions.assertEquals(3L, tableStats.get("s1").value().value());
+ Assertions.assertEquals(5L, tableStats.get("s2").value().value());
+
+ Map<String, StatisticEntry<?>> otherStats =
+ toNameMap(
+ allStatistics.get(NameIdentifier.parse("catalog.schema.other")).tableStatistics());
+ Assertions.assertEquals(1, otherStats.size());
+ Assertions.assertEquals(10L, otherStats.get("s1").value().value());
+ }
+
+ @Test
+ void testComputeTableStatisticsFromPayload() {
+ String payload =
+ String.join(
+ "\n",
+ "{\"identifier\":\"catalog.schema.table\",\"stats-type\":\"table\",\"s1\":1,\"s2\":5}",
+ "{\"identifier\":\"catalog.schema.table\",\"stats-type\":\"table\",\"s1\":3}");
+
+ LocalStatisticsCalculator calculator = new LocalStatisticsCalculator();
+ OptimizerEnv env = new OptimizerEnv(createConfig(null, payload));
+ calculator.initialize(env);
+
+ List<StatisticEntry<?>> stats =
+ calculator
+ .calculateTableStatistics(NameIdentifier.parse("catalog.schema.table"))
+ .tableStatistics();
+ Map<String, StatisticEntry<?>> map = toNameMap(stats);
+ Assertions.assertEquals(2, map.size());
+ Assertions.assertEquals(3L, map.get("s1").value().value());
+ Assertions.assertEquals(5L, map.get("s2").value().value());
+ }
+
+ @Test
+ void testSkipNonNumericTextualStatistics() {
+ String payload =
+ String.join(
+ "\n",
+ "{\"identifier\":\"catalog.schema.table\",\"stats-type\":\"table\",\"s1\":1,"
+ + "\"text_metric\":\"abc\"}",
+ "{\"identifier\":\"catalog.schema.table\",\"stats-type\":\"table\",\"s2\":\"2.5\"}");
+
+ LocalStatisticsCalculator calculator = new LocalStatisticsCalculator();
+ OptimizerEnv env = new OptimizerEnv(createConfig(null, payload));
+ calculator.initialize(env);
+
+ List<StatisticEntry<?>> stats =
+ calculator
+ .calculateTableStatistics(NameIdentifier.parse("catalog.schema.table"))
+ .tableStatistics();
+ Map<String, StatisticEntry<?>> map = toNameMap(stats);
+ Assertions.assertEquals(2, map.size());
+ Assertions.assertEquals(1L, map.get("s1").value().value());
+ Assertions.assertEquals(2.5D, map.get("s2").value().value());
+ Assertions.assertFalse(map.containsKey("text_metric"));
+ }
+
+ @Test
+ void testComputeJobStatisticsFromPayload() {
+ String payload =
+ String.join(
+ "\n",
+ "{\"identifier\":\"catalog.schema.job1\",\"stats-type\":\"job\",\"duration\":10}",
+ "{\"identifier\":\"catalog.schema.job1\",\"stats-type\":\"job\",\"duration\":20,"
+ + "\"planning\":5}",
+ "{\"identifier\":\"catalog.schema.job2\",\"stats-type\":\"job\",\"duration\":1}");
+
+ LocalStatisticsCalculator calculator = new LocalStatisticsCalculator();
+ OptimizerEnv env = new OptimizerEnv(createConfig(null, payload));
+ calculator.initialize(env);
+
+ List<StatisticEntry<?>> stats =
+ calculator.calculateJobStatistics(NameIdentifier.parse("catalog.schema.job1"));
+ Map<String, StatisticEntry<?>> map = toNameMap(stats);
+ Assertions.assertEquals(2, map.size());
+ Assertions.assertEquals(20L, map.get("duration").value().value());
+ Assertions.assertEquals(5L, map.get("planning").value().value());
+ }
+
+ @Test
+ void testJobIdentifierWithMultipleDotsIsSupported() {
+ String payload =
+ "{\"identifier\":\"org.team.pipeline.stage.job42\",\"stats-type\":\"job\",\"duration\":10}";
+
+ LocalStatisticsCalculator calculator = new LocalStatisticsCalculator();
+ OptimizerEnv env = new OptimizerEnv(createConfig(null, payload));
+ calculator.initialize(env);
+
+ List<StatisticEntry<?>> stats =
+ calculator.calculateJobStatistics(NameIdentifier.parse("org.team.pipeline.stage.job42"));
+ Assertions.assertEquals(1, stats.size());
+ Assertions.assertEquals(10L, stats.get(0).value().value());
+ }
+
+ @Test
+ void testTableIdentifierWithMultipleDotsIsStillIgnored() {
+ String payload =
+ "{\"identifier\":\"catalog.db.schema.extra.table\",\"stats-type\":\"table\",\"rows\":10}";
+
+ LocalStatisticsCalculator calculator = new LocalStatisticsCalculator();
+ OptimizerEnv env = new OptimizerEnv(createConfig(null, payload));
+ calculator.initialize(env);
+
+ List<StatisticEntry<?>> stats =
+ calculator
+ .calculateTableStatistics(NameIdentifier.parse("catalog.db.schema.extra.table"))
+ .tableStatistics();
+ Assertions.assertTrue(stats.isEmpty());
+ }
+
+ @Test
+ void testComputePartitionStatisticsFromPayload() {
+ String payload =
+ String.join(
+ "\n",
+ "{\"identifier\":\"catalog.schema.table\",\"stats-type\":\"partition\","
+ + "\"partition-path\":{\"dt\":\"2024-01-01\"},\"rows\":10,\"size\":100}",
+ "{\"identifier\":\"catalog.schema.table\",\"stats-type\":\"partition\","
+ + "\"partition-path\":{\"dt\":\"2024-01-01\"},\"rows\":20,\"size\":200}",
+ "{\"identifier\":\"catalog.schema.table\",\"stats-type\":\"partition\","
+ + "\"partition-path\":{\"dt\":\"2024-01-02\"},\"rows\":5}");
+
+ LocalStatisticsCalculator calculator = new LocalStatisticsCalculator();
+ OptimizerEnv env = new OptimizerEnv(createConfig(null, payload));
+ calculator.initialize(env);
+
+ Map<PartitionPath, List<StatisticEntry<?>>> partitionStatistics =
+ calculator
+ .calculateTableStatistics(NameIdentifier.parse("catalog.schema.table"))
+ .partitionStatistics();
+
+ Assertions.assertEquals(2, partitionStatistics.size());
+
+ PartitionPath p1 = PartitionPath.of(List.of(new PartitionEntryImpl("dt", "2024-01-01")));
+ Map<String, StatisticEntry<?>> p1Stats = toNameMap(partitionStatistics.get(p1));
+ Assertions.assertEquals(2, p1Stats.size());
+ Assertions.assertEquals(20L, p1Stats.get("rows").value().value());
+ Assertions.assertEquals(200L, p1Stats.get("size").value().value());
+
+ PartitionPath p2 = PartitionPath.of(List.of(new PartitionEntryImpl("dt", "2024-01-02")));
+ Map<String, StatisticEntry<?>> p2Stats = toNameMap(partitionStatistics.get(p2));
+ Assertions.assertEquals(1, p2Stats.size());
+ Assertions.assertEquals(5L, p2Stats.get("rows").value().value());
+ }
+
+ @Test
+ void testComputeAllPartitionStatistics() {
+ String payload =
+ String.join(
+ "\n",
+ "{\"identifier\":\"catalog.schema.table1\",\"stats-type\":\"partition\","
+ + "\"partition-path\":{\"dt\":\"2024-01-01\"},\"rows\":10}",
+ "{\"identifier\":\"catalog.schema.table2\",\"stats-type\":\"partition\","
+ + "\"partition-path\":{\"dt\":\"2024-01-02\"},\"rows\":30}");
+
+ LocalStatisticsCalculator calculator = new LocalStatisticsCalculator();
+ OptimizerEnv env = new OptimizerEnv(createConfig(null, payload));
+ calculator.initialize(env);
+
+ Map<NameIdentifier, TableAndPartitionStatistics> allStatistics =
+ calculator.calculateBulkTableStatistics();
+ Assertions.assertEquals(2, allStatistics.size());
+
+ PartitionPath p1 = PartitionPath.of(List.of(new PartitionEntryImpl("dt", "2024-01-01")));
+ Map<PartitionPath, List<StatisticEntry<?>>> table1Partitions =
+ allStatistics.get(NameIdentifier.parse("catalog.schema.table1")).partitionStatistics();
+ Assertions.assertEquals(1, table1Partitions.size());
+ Assertions.assertEquals(10L, toNameMap(table1Partitions.get(p1)).get("rows").value().value());
+ Assertions.assertTrue(
+ allStatistics
+ .get(NameIdentifier.parse("catalog.schema.table1"))
+ .tableStatistics()
+ .isEmpty());
+
+ PartitionPath p2 = PartitionPath.of(List.of(new PartitionEntryImpl("dt", "2024-01-02")));
+ Map<PartitionPath, List<StatisticEntry<?>>> table2Partitions =
+ allStatistics.get(NameIdentifier.parse("catalog.schema.table2")).partitionStatistics();
+ Assertions.assertEquals(1, table2Partitions.size());
+ Assertions.assertEquals(30L, toNameMap(table2Partitions.get(p2)).get("rows").value().value());
+ Assertions.assertTrue(
+ allStatistics
+ .get(NameIdentifier.parse("catalog.schema.table2"))
+ .tableStatistics()
+ .isEmpty());
+ }
+
+ @Test
+ void testComputeAllJobStatistics() {
+ String payload =
+ String.join(
+ "\n",
+ "{\"identifier\":\"catalog.schema.job1\",\"stats-type\":\"job\",\"duration\":10}",
+ "{\"identifier\":\"catalog.schema.job2\",\"stats-type\":\"job\",\"duration\":7}");
+
+ LocalStatisticsCalculator calculator = new LocalStatisticsCalculator();
+ OptimizerEnv env = new OptimizerEnv(createConfig(null, payload));
+ calculator.initialize(env);
+
+ Map<NameIdentifier, List<StatisticEntry<?>>> allStatistics =
+ calculator.calculateAllJobStatistics();
+ Assertions.assertEquals(2, allStatistics.size());
+ Assertions.assertEquals(
+ 10L,
+ toNameMap(allStatistics.get(NameIdentifier.parse("catalog.schema.job1")))
+ .get("duration")
+ .value()
+ .value());
+ Assertions.assertEquals(
+ 7L,
+ toNameMap(allStatistics.get(NameIdentifier.parse("catalog.schema.job2")))
+ .get("duration")
+ .value()
+ .value());
+ }
+
+ @Test
+ void testSkipMalformedJsonLine() {
+ String payload =
+ String.join(
+ "\n",
+ "{\"identifier\":\"catalog.schema.table\",\"stats-type\":\"table\",\"s1\":1}",
+ "{\"identifier\":\"catalog.schema.table\",\"stats-type\":\"table\",\"s1\":",
+ "{\"identifier\":\"catalog.schema.table\",\"stats-type\":\"table\",\"s2\":2}");
+
+ LocalStatisticsCalculator calculator = new LocalStatisticsCalculator();
+ OptimizerEnv env = new OptimizerEnv(createConfig(null, payload));
+ calculator.initialize(env);
+
+ List<StatisticEntry<?>> stats =
+ calculator
+ .calculateTableStatistics(NameIdentifier.parse("catalog.schema.table"))
+ .tableStatistics();
+ Map<String, StatisticEntry<?>> map = toNameMap(stats);
+ Assertions.assertEquals(2, map.size());
+ Assertions.assertEquals(1L, map.get("s1").value().value());
+ Assertions.assertEquals(2L, map.get("s2").value().value());
+ }
+
+ @Test
+ void testSkipRecordWithMissingOrInvalidStatsType() {
+ String payload =
+ String.join(
+ "\n",
+ "{\"identifier\":\"catalog.schema.table\",\"s1\":1}",
+ "{\"identifier\":\"catalog.schema.table\",\"stats-type\":\"unknown\",\"s2\":2}",
+ "{\"identifier\":\"catalog.schema.table\",\"stats-type\":\"table\",\"s3\":3}");
+
+ LocalStatisticsCalculator calculator = new LocalStatisticsCalculator();
+ OptimizerEnv env = new OptimizerEnv(createConfig(null, payload));
+ calculator.initialize(env);
+
+ List<StatisticEntry<?>> stats =
+ calculator
+ .calculateTableStatistics(NameIdentifier.parse("catalog.schema.table"))
+ .tableStatistics();
+ Map<String, StatisticEntry<?>> map = toNameMap(stats);
+ Assertions.assertEquals(1, map.size());
+ Assertions.assertEquals(3L, map.get("s3").value().value());
+ }
+
+ @Test
+ void testSkipPartitionRecordWithInvalidPartitionPath() {
+ String payload =
+ String.join(
+ "\n",
+ "{\"identifier\":\"catalog.schema.table\",\"stats-type\":\"partition\","
+ + "\"partition-path\":\"dt=2024-01-01\",\"rows\":1}",
+ "{\"identifier\":\"catalog.schema.table\",\"stats-type\":\"partition\","
+ + "\"partition-path\":{\"dt\":100},\"rows\":2}",
+ "{\"identifier\":\"catalog.schema.table\",\"stats-type\":\"partition\","
+ + "\"partition-path\":{\"dt\":\"2024-01-02\"},\"rows\":3}");
+
+ LocalStatisticsCalculator calculator = new LocalStatisticsCalculator();
+ OptimizerEnv env = new OptimizerEnv(createConfig(null, payload));
+ calculator.initialize(env);
+
+ Map<PartitionPath, List<StatisticEntry<?>>> partitionStatistics =
+ calculator
+ .calculateTableStatistics(NameIdentifier.parse("catalog.schema.table"))
+ .partitionStatistics();
+ Assertions.assertEquals(1, partitionStatistics.size());
+
+ PartitionPath valid = PartitionPath.of(List.of(new PartitionEntryImpl("dt", "2024-01-02")));
+ Assertions.assertEquals(
+ 3L, toNameMap(partitionStatistics.get(valid)).get("rows").value().value());
+ }
+
+ @Test
+ void testPartitionPathOrderIsPreserved() {
+ String payload =
+ "{\"identifier\":\"catalog.schema.table\",\"stats-type\":\"partition\","
+ + "\"partition-path\":{\"p1\":\"v1\",\"p2\":\"v2\"},\"rows\":1}";
+
+ LocalStatisticsCalculator calculator = new LocalStatisticsCalculator();
+ OptimizerEnv env = new OptimizerEnv(createConfig(null, payload));
+ calculator.initialize(env);
+
+ Map<PartitionPath, List<StatisticEntry<?>>> partitionStatistics =
+ calculator
+ .calculateTableStatistics(NameIdentifier.parse("catalog.schema.table"))
+ .partitionStatistics();
+ Assertions.assertEquals(1, partitionStatistics.size());
+
+ PartitionPath actual = partitionStatistics.keySet().iterator().next();
+ Assertions.assertEquals(2, actual.entries().size());
+ Assertions.assertEquals("p1", actual.entries().get(0).partitionName());
+ Assertions.assertEquals("v1", actual.entries().get(0).partitionValue());
+ Assertions.assertEquals("p2", actual.entries().get(1).partitionName());
+ Assertions.assertEquals("v2", actual.entries().get(1).partitionValue());
+ }
+
+ @Test
+ void testJobIdentifiersDoNotApplyDefaultCatalog() {
+ String payload = "{\"identifier\":\"job-1\",\"stats-type\":\"job\",\"duration\":10}";
+
+ LocalStatisticsCalculator calculator = new LocalStatisticsCalculator();
+ OptimizerEnv env = new OptimizerEnv(createConfig(null, payload));
+ calculator.initialize(env);
+
+ List<StatisticEntry<?>> stats =
+ calculator.calculateJobStatistics(NameIdentifier.parse("job-1"));
+ Assertions.assertEquals(1, stats.size());
+ Assertions.assertEquals(10L, stats.get(0).value().value());
+ Assertions.assertTrue(
+ calculator.calculateJobStatistics(NameIdentifier.parse("catalog.job-1")).isEmpty());
+ }
+
+ @Test
+ void testCalculateWithoutInitializeFails() {
+ LocalStatisticsCalculator calculator = new LocalStatisticsCalculator();
+ Assertions.assertThrows(
+ IllegalStateException.class,
+ () -> calculator.calculateTableStatistics(NameIdentifier.parse("catalog.db.table")));
+ Assertions.assertThrows(IllegalStateException.class, calculator::calculateBulkTableStatistics);
+ Assertions.assertThrows(
+ IllegalStateException.class,
+ () -> calculator.calculateJobStatistics(NameIdentifier.parse("catalog.db.job")));
+ Assertions.assertThrows(IllegalStateException.class, calculator::calculateAllJobStatistics);
+ }
+
+ @Test
+ void testNullIdentifierFailsFast() {
+ String payload = "{\"identifier\":\"catalog.schema.table\",\"stats-type\":\"table\",\"s1\":1}";
+ LocalStatisticsCalculator calculator = new LocalStatisticsCalculator();
+ OptimizerEnv env = new OptimizerEnv(createConfig(null, payload));
+ calculator.initialize(env);
+
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> calculator.calculateTableStatistics(null));
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> calculator.calculateJobStatistics(null));
+ }
+
+ @Test
+ void testInitializeWithoutFilePathAndPayloadFails() {
+ LocalStatisticsCalculator calculator = new LocalStatisticsCalculator();
+ OptimizerEnv env = new OptimizerEnv(createConfig(null, null));
+
+ IllegalArgumentException exception =
+ Assertions.assertThrows(IllegalArgumentException.class, () -> calculator.initialize(env));
+ Assertions.assertTrue(
+ exception.getMessage().contains(LocalStatisticsCalculator.STATISTICS_FILE_PATH_CONFIG));
+ Assertions.assertTrue(
+ exception.getMessage().contains(LocalStatisticsCalculator.STATISTICS_PAYLOAD_CONFIG));
+ }
+
+ private OptimizerConfig createConfig(String statisticsFilePath, String statisticsPayload) {
+ Map<String, String> configs = new HashMap<>();
+ configs.put(OptimizerConfig.GRAVITINO_DEFAULT_CATALOG_CONFIG.getKey(), "catalog");
+ if (statisticsFilePath != null) {
+ configs.put(LocalStatisticsCalculator.STATISTICS_FILE_PATH_CONFIG, statisticsFilePath);
+ }
+ if (statisticsPayload != null) {
+ configs.put(LocalStatisticsCalculator.STATISTICS_PAYLOAD_CONFIG, statisticsPayload);
+ }
+ return new OptimizerConfig(configs);
+ }
+
+ private Map<String, StatisticEntry<?>> toNameMap(List<StatisticEntry<?>> stats) {
+ Map<String, StatisticEntry<?>> map = new HashMap<>();
+ for (StatisticEntry<?> stat : stats) {
+ map.put(stat.name(), stat);
+ }
+ return map;
+ }
+}
diff --git a/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/updater/metrics/TestGravitinoMetricsUpdater.java b/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/updater/metrics/TestGravitinoMetricsUpdater.java
new file mode 100644
index 0000000000..57411eedf8
--- /dev/null
+++ b/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/updater/metrics/TestGravitinoMetricsUpdater.java
@@ -0,0 +1,194 @@
+/*
+ * 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.optimizer.updater.metrics;
+
+import java.lang.reflect.Field;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.maintenance.optimizer.common.OptimizerEnv;
+import org.apache.gravitino.maintenance.optimizer.common.conf.OptimizerConfig;
+import org.apache.gravitino.maintenance.optimizer.updater.metrics.storage.JobMetricWriteRequest;
+import org.apache.gravitino.maintenance.optimizer.updater.metrics.storage.MetricRecord;
+import org.apache.gravitino.maintenance.optimizer.updater.metrics.storage.MetricRecordImpl;
+import org.apache.gravitino.maintenance.optimizer.updater.metrics.storage.MetricsRepository;
+import org.apache.gravitino.maintenance.optimizer.updater.metrics.storage.TableMetricWriteRequest;
+import org.apache.gravitino.maintenance.optimizer.updater.metrics.storage.jdbc.GenericJdbcMetricsRepository;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mockito;
+
+class TestGravitinoMetricsUpdater {
+
+ @Test
+ void testUpdateTableMetricsWithoutInitializeFailsFast() {
+ GravitinoMetricsUpdater updater = new GravitinoMetricsUpdater();
+ IllegalStateException exception =
+ Assertions.assertThrows(
+ IllegalStateException.class, () -> updater.updateTableMetrics(List.of()));
+ Assertions.assertTrue(exception.getMessage().contains("has not been initialized"));
+ }
+
+ @Test
+ void testUpdateJobMetricsWithoutInitializeFailsFast() {
+ GravitinoMetricsUpdater updater = new GravitinoMetricsUpdater();
+ IllegalStateException exception =
+ Assertions.assertThrows(
+ IllegalStateException.class, () -> updater.updateJobMetrics(List.of()));
+ Assertions.assertTrue(exception.getMessage().contains("has not been initialized"));
+ }
+
+ @Test
+ void testUpdateTableMetricsPassThroughRequests() throws Exception {
+ GravitinoMetricsUpdater updater = new GravitinoMetricsUpdater();
+ MetricsRepository repository = Mockito.mock(MetricsRepository.class);
+ setMetricsRepository(updater, repository);
+ NameIdentifier tableId = NameIdentifier.of("catalog", "db", "table");
+ List<TableMetricWriteRequest> inputRequests =
+ List.of(
+ new TableMetricWriteRequest(
+ tableId, "row_count", Optional.empty(), new MetricRecordImpl(100L, "10")),
+ new TableMetricWriteRequest(
+ tableId,
+ "file_count",
+ Optional.of("dt=2026-01-01"),
+ new MetricRecordImpl(101L, "3")));
+
+ updater.updateTableMetrics(inputRequests);
+
+ @SuppressWarnings("unchecked")
+ ArgumentCaptor<List<TableMetricWriteRequest>> requestsCaptor =
+ ArgumentCaptor.forClass(List.class);
+
+ Mockito.verify(repository, Mockito.times(1)).storeTableMetrics(requestsCaptor.capture());
+
+ List<TableMetricWriteRequest> requests = requestsCaptor.getValue();
+ Assertions.assertEquals(2, requests.size());
+ Assertions.assertEquals(tableId, requests.get(0).nameIdentifier());
+ Assertions.assertEquals(tableId, requests.get(1).nameIdentifier());
+ Assertions.assertEquals(Optional.empty(), requests.get(0).partition());
+ Assertions.assertEquals(Optional.of("dt=2026-01-01"), requests.get(1).partition());
+
+ List<MetricRecord> records = requests.stream().map(TableMetricWriteRequest::metric).toList();
+ Assertions.assertEquals(100L, records.get(0).getTimestamp());
+ Assertions.assertEquals(101L, records.get(1).getTimestamp());
+
+ Assertions.assertEquals("10", records.get(0).getValue());
+ Assertions.assertEquals("3", records.get(1).getValue());
+ }
+
+ @Test
+ void testUpdateJobMetricsPassThroughRequests() throws Exception {
+ GravitinoMetricsUpdater updater = new GravitinoMetricsUpdater();
+ MetricsRepository repository = Mockito.mock(MetricsRepository.class);
+ setMetricsRepository(updater, repository);
+ NameIdentifier jobId = NameIdentifier.of("catalog", "db", "job");
+ List<JobMetricWriteRequest> inputRequests =
+ List.of(
+ new JobMetricWriteRequest(jobId, "duration", new MetricRecordImpl(200L, "20")),
+ new JobMetricWriteRequest(jobId, "planning", new MetricRecordImpl(201L, "1.5")));
+
+ updater.updateJobMetrics(inputRequests);
+
+ @SuppressWarnings("unchecked")
+ ArgumentCaptor<List<JobMetricWriteRequest>> requestsCaptor =
+ ArgumentCaptor.forClass(List.class);
+ Mockito.verify(repository, Mockito.times(1)).storeJobMetrics(requestsCaptor.capture());
+
+ List<JobMetricWriteRequest> requests = requestsCaptor.getValue();
+ Assertions.assertEquals(jobId, requests.get(0).nameIdentifier());
+ Assertions.assertEquals(jobId, requests.get(1).nameIdentifier());
+ List<MetricRecord> records = requests.stream().map(JobMetricWriteRequest::metric).toList();
+ Assertions.assertEquals(200L, records.get(0).getTimestamp());
+ Assertions.assertEquals(201L, records.get(1).getTimestamp());
+ Assertions.assertEquals("20", records.get(0).getValue());
+ Assertions.assertEquals("1.5", records.get(1).getValue());
+ }
+
+ @Test
+ void testCloseDelegatesToRepository() throws Exception {
+ GravitinoMetricsUpdater updater = new GravitinoMetricsUpdater();
+ MetricsRepository repository = Mockito.mock(MetricsRepository.class);
+ setMetricsRepository(updater, repository);
+
+ updater.close();
+
+ Mockito.verify(repository).close();
+ }
+
+ @Test
+ void testInitializeDefaultUsesGenericJdbcRepository() throws Exception {
+ GravitinoMetricsUpdater updater = new GravitinoMetricsUpdater();
+ String storagePath = "data/test-metrics-updater-default-" + System.nanoTime() + ".db";
+ String jdbcUrl = "jdbc:h2:file:./" + storagePath + ";DB_CLOSE_DELAY=-1;MODE=MYSQL";
+ updater.initialize(
+ new OptimizerEnv(
+ new OptimizerConfig(
+ Map.of(
+ OptimizerConfig.OPTIMIZER_PREFIX + "jdbcMetrics." + "jdbcUrl",
+ jdbcUrl,
+ OptimizerConfig.OPTIMIZER_PREFIX + "jdbcMetrics." + "jdbcUser",
+ "sa",
+ OptimizerConfig.OPTIMIZER_PREFIX + "jdbcMetrics." + "jdbcPassword",
+ "",
+ OptimizerConfig.OPTIMIZER_PREFIX + "jdbcMetrics." + "jdbcDriver",
+ "org.h2.Driver",
+ OptimizerConfig.OPTIMIZER_PREFIX + "jdbcMetrics." + "testOnBorrow",
+ "false"))));
+ MetricsRepository repository = getMetricsRepository(updater);
+ Assertions.assertInstanceOf(GenericJdbcMetricsRepository.class, repository);
+ updater.close();
+ }
+
+ @Test
+ void testInitializeWithJdbcConfigStillUsesGenericJdbcRepository() throws Exception {
+ GravitinoMetricsUpdater updater = new GravitinoMetricsUpdater();
+ String jdbcUrl = "jdbc:h2:mem:test_metrics_updater_repo_type;DB_CLOSE_DELAY=-1";
+ OptimizerConfig config =
+ new OptimizerConfig(
+ Map.of(
+ "gravitino.optimizer.jdbcMetrics.jdbcUrl",
+ jdbcUrl,
+ "gravitino.optimizer.jdbcMetrics.jdbcUser",
+ "sa",
+ "gravitino.optimizer.jdbcMetrics.jdbcPassword",
+ ""));
+ updater.initialize(new OptimizerEnv(config));
+ MetricsRepository repository = getMetricsRepository(updater);
+ Assertions.assertInstanceOf(GenericJdbcMetricsRepository.class, repository);
+ updater.close();
+ }
+
+ private void setMetricsRepository(GravitinoMetricsUpdater updater, MetricsRepository repository)
+ throws ReflectiveOperationException {
+ Field field = GravitinoMetricsUpdater.class.getDeclaredField("metricsStorage");
+ field.setAccessible(true);
+ field.set(updater, repository);
+ }
+
+ private MetricsRepository getMetricsRepository(GravitinoMetricsUpdater updater)
+ throws ReflectiveOperationException {
+ Field field = GravitinoMetricsUpdater.class.getDeclaredField("metricsStorage");
+ field.setAccessible(true);
+ return (MetricsRepository) field.get(updater);
+ }
+}
diff --git a/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/updater/metrics/storage/TestGenericJdbcMetricsRepository.java b/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/updater/metrics/storage/TestGenericJdbcMetricsRepository.java
new file mode 100644
index 0000000000..6c03b4f41c
--- /dev/null
+++ b/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/updater/metrics/storage/TestGenericJdbcMetricsRepository.java
@@ -0,0 +1,459 @@
+/*
+ * 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.optimizer.updater.metrics.storage;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.config.ConfigConstants;
+import org.apache.gravitino.maintenance.optimizer.common.conf.OptimizerConfig;
+import org.apache.gravitino.maintenance.optimizer.updater.metrics.storage.jdbc.GenericJdbcMetricsRepository;
+import org.apache.gravitino.utils.jdbc.JdbcSqlScriptUtils;
+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.junit.jupiter.api.TestInstance;
+
+@TestInstance(TestInstance.Lifecycle.PER_CLASS)
+class TestGenericJdbcMetricsRepository {
+ private static final long MAX_REASONABLE_EPOCH_SECONDS = 9_999_999_999L;
+ private GenericJdbcMetricsRepository storage;
+ private String jdbcUrl;
+
+ @BeforeAll
+ void setUp() throws IOException {
+ cleanupLegacyDataFiles();
+ Path testDir = Files.createTempDirectory("optimizer-h2-metrics");
+ jdbcUrl = "jdbc:h2:file:" + testDir.resolve("metrics.db");
+ initializeSchema(jdbcUrl);
+ storage = new GenericJdbcMetricsRepository();
+ storage.initialize(createJdbcConfigs(jdbcUrl));
+ storage.cleanupTableMetricsBefore(MAX_REASONABLE_EPOCH_SECONDS);
+ storage.cleanupJobMetricsBefore(MAX_REASONABLE_EPOCH_SECONDS);
+ }
+
+ @AfterAll
+ void tearDown() {
+ storage.cleanupTableMetricsBefore(MAX_REASONABLE_EPOCH_SECONDS);
+ storage.cleanupJobMetricsBefore(MAX_REASONABLE_EPOCH_SECONDS);
+ storage.close();
+ }
+
+ @Test
+ void testStoreAndRetrieveTableMetricsWithNullPartition() {
+ NameIdentifier nameIdentifier = NameIdentifier.of("catalog", "db", "test_null_partition");
+ long now = currentEpochSeconds();
+ MetricRecord metric = new MetricRecordImpl(now, "value1");
+ MetricRecord metric2 = new MetricRecordImpl(now, "value2");
+
+ storeTableMetric(nameIdentifier, "metric1", Optional.empty(), metric);
+ storeTableMetric(nameIdentifier, "metric2", Optional.empty(), metric);
+ storeTableMetric(nameIdentifier, "metric2", Optional.empty(), metric2);
+
+ storeTableMetric(
+ NameIdentifier.of("catalog2", "db", "test_null_partition"),
+ "metric1",
+ Optional.empty(),
+ metric);
+ storeTableMetric(
+ NameIdentifier.of("catalog", "db2", "test_null_partition"),
+ "metric1",
+ Optional.empty(),
+ metric);
+ storeTableMetric(
+ NameIdentifier.of("catalog", "db", "test_null_partition2"),
+ "metric1",
+ Optional.empty(),
+ metric);
+
+ Map<String, List<MetricRecord>> metrics =
+ storage.getTableMetrics(nameIdentifier, 0, Long.MAX_VALUE);
+
+ Assertions.assertEquals(2, metrics.size());
+
+ Assertions.assertTrue(metrics.containsKey("metric1"));
+ Assertions.assertEquals(Arrays.asList("value1"), getMetricValues(metrics.get("metric1")));
+
+ Assertions.assertTrue(metrics.containsKey("metric2"));
+ Assertions.assertEquals(2, getMetricValues(metrics.get("metric2")).size());
+ Assertions.assertEquals(
+ Arrays.asList("value1", "value2"), getMetricValues(metrics.get("metric2")));
+ }
+
+ @Test
+ void testStoreAndRetrieveMetricsWithNonNullPartition() {
+ NameIdentifier nameIdentifier = NameIdentifier.of("catalog", "db", "test_non_null_partition");
+ long now = currentEpochSeconds();
+ MetricRecord metric = new MetricRecordImpl(now, "value1");
+ MetricRecord metric2 = new MetricRecordImpl(now, "value2");
+ MetricRecord metric3 = new MetricRecordImpl(now, "value3");
+
+ String partition1 = "a=1/b=2";
+ String partition2 = "a=1/b=3";
+
+ storeTableMetric(nameIdentifier, "metric", Optional.of(partition1), metric);
+ storeTableMetric(nameIdentifier, "metric", Optional.of(partition2), metric);
+ storeTableMetric(nameIdentifier, "metric2", Optional.of(partition2), metric2);
+ storeTableMetric(nameIdentifier, "metric2", Optional.of(partition2), metric3);
+
+ Map<String, List<MetricRecord>> metrics =
+ storage.getPartitionMetrics(nameIdentifier, partition1, 0, Long.MAX_VALUE);
+
+ Assertions.assertEquals(1, metrics.size());
+ Assertions.assertTrue(metrics.containsKey("metric"));
+ Assertions.assertEquals(Arrays.asList("value1"), getMetricValues(metrics.get("metric")));
+
+ metrics = storage.getPartitionMetrics(nameIdentifier, partition2, 0, Long.MAX_VALUE);
+ Assertions.assertEquals(2, metrics.size());
+ Assertions.assertTrue(metrics.containsKey("metric"));
+ Assertions.assertEquals(Arrays.asList("value1"), getMetricValues(metrics.get("metric")));
+ Assertions.assertTrue(metrics.containsKey("metric2"));
+ Assertions.assertEquals(
+ Arrays.asList("value2", "value3"), getMetricValues(metrics.get("metric2")));
+ }
+
+ @Test
+ void testRetrieveMetricsWithNullAndNonNullPartition() {
+ NameIdentifier nameIdentifier = NameIdentifier.of("test_mismatch_partition");
+ MetricRecord metric = new MetricRecordImpl(0, "value1");
+ MetricRecord metric2 = new MetricRecordImpl(1, "value2");
+ MetricRecord metric3 = new MetricRecordImpl(2, "value3");
+
+ String partition1 = "a=1/b=2";
+ String partition2 = "a=1/b=3";
+
+ storeTableMetric(nameIdentifier, "metric1", Optional.empty(), metric);
+ storeTableMetric(nameIdentifier, "metric1", Optional.empty(), metric2);
+ storeTableMetric(nameIdentifier, "metric1", Optional.empty(), metric3);
+ storeTableMetric(nameIdentifier, "metric1", Optional.of(partition1), metric);
+ storeTableMetric(nameIdentifier, "metric1", Optional.of(partition2), metric2);
+ storeTableMetric(nameIdentifier, "metric1", Optional.of(partition2), metric3);
+
+ Map<String, List<MetricRecord>> metrics =
+ storage.getTableMetrics(nameIdentifier, 0, Long.MAX_VALUE);
+ Assertions.assertEquals(1, metrics.size());
+ Assertions.assertTrue(metrics.containsKey("metric1"));
+ Assertions.assertEquals(
+ Arrays.asList("value1", "value2", "value3"), getMetricValues(metrics.get("metric1")));
+
+ metrics = storage.getPartitionMetrics(nameIdentifier, partition1, 0, Long.MAX_VALUE);
+ Assertions.assertEquals(1, metrics.size());
+ Assertions.assertTrue(metrics.containsKey("metric1"));
+ Assertions.assertEquals(Arrays.asList("value1"), getMetricValues(metrics.get("metric1")));
+
+ metrics = storage.getPartitionMetrics(nameIdentifier, partition2, 0, Long.MAX_VALUE);
+ Assertions.assertEquals(1, metrics.size());
+ Assertions.assertTrue(metrics.containsKey("metric1"));
+ Assertions.assertEquals(
+ Arrays.asList("value2", "value3"), getMetricValues(metrics.get("metric1")));
+ }
+
+ @Test
+ void testCaseInsensitiveIdentifierPartitionAndMetricName() {
+ NameIdentifier storedId = NameIdentifier.of("CATALOGX", "DBX", "TABLEX");
+ NameIdentifier queryId = NameIdentifier.of("catalogx", "dbx", "tablex");
+ MetricRecord metric = new MetricRecordImpl(currentEpochSeconds(), "v1");
+ String storedPartition = "Region=US/Day=2025-01-01";
+ String queryPartition = "region=us/day=2025-01-01";
+
+ storeTableMetric(storedId, "METRIC_UPPER", Optional.of(storedPartition), metric);
+ storeJobMetric(storedId, "JOB_METRIC", metric);
+
+ Map<String, List<MetricRecord>> partitionMetrics =
+ storage.getPartitionMetrics(queryId, queryPartition, 0, Long.MAX_VALUE);
+ Assertions.assertTrue(partitionMetrics.containsKey("metric_upper"));
+ Assertions.assertEquals(List.of("v1"), getMetricValues(partitionMetrics.get("metric_upper")));
+
+ Map<String, List<MetricRecord>> jobMetrics = storage.getJobMetrics(queryId, 0, Long.MAX_VALUE);
+ Assertions.assertTrue(jobMetrics.containsKey("job_metric"));
+ Assertions.assertEquals(List.of("v1"), getMetricValues(jobMetrics.get("job_metric")));
+ }
+
+ @Test
+ void testInitializeTwiceFails() {
+ GenericJdbcMetricsRepository repository = new GenericJdbcMetricsRepository();
+ initializeSchema(jdbcUrl + "_init_twice");
+ repository.initialize(createJdbcConfigs(jdbcUrl + "_init_twice"));
+
+ IllegalStateException e =
+ Assertions.assertThrows(
+ IllegalStateException.class,
+ () -> repository.initialize(createJdbcConfigs(jdbcUrl + "_init_twice")));
+ Assertions.assertTrue(e.getMessage().contains("already been initialized"));
+ }
+
+ @Test
+ void testInvalidTimeWindowFailsFast() {
+ NameIdentifier id = NameIdentifier.of("catalog", "db", "table");
+
+ IllegalArgumentException tableException =
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> storage.getTableMetrics(id, 10, 10));
+ Assertions.assertTrue(tableException.getMessage().contains("Invalid time window"));
+
+ IllegalArgumentException partitionException =
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> storage.getPartitionMetrics(id, "p=1", 20, 10));
+ Assertions.assertTrue(partitionException.getMessage().contains("Invalid time window"));
+
+ IllegalArgumentException jobException =
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> storage.getJobMetrics(id, 30, 30));
+ Assertions.assertTrue(jobException.getMessage().contains("Invalid time window"));
+
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> storage.getTableMetrics(null, 0, 1));
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> storage.getJobMetrics(null, 0, 1));
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> storage.getPartitionMetrics(null, "p=1", 0, 1));
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> storage.getPartitionMetrics(id, " ", 0, 1));
+ }
+
+ @Test
+ void testWriteValidationFailsFast() {
+ MetricRecord metric = new MetricRecordImpl(currentEpochSeconds(), "v1");
+ NameIdentifier id = NameIdentifier.of("catalog", "db", "table");
+
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> storeTableMetric(null, "metric", Optional.empty(), metric));
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> storeTableMetric(id, " ", Optional.empty(), metric));
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> storeTableMetric(id, "metric", Optional.empty(), null));
+
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> storeJobMetric(null, "metric", metric));
+ Assertions.assertThrows(IllegalArgumentException.class, () -> storeJobMetric(id, "", metric));
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> storeJobMetric(id, "metric", null));
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> storeTableMetric(id, "metric", Optional.empty(), new MetricRecordImpl(-1, "v1")));
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ storeTableMetric(
+ id,
+ "metric",
+ Optional.empty(),
+ new MetricRecordImpl(System.currentTimeMillis(), "v1")));
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> storeJobMetric(id, "metric", new MetricRecordImpl(-1, "v1")));
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ storeTableMetric(
+ id, "metric", Optional.of(" "), new MetricRecordImpl(currentEpochSeconds(), "v1")));
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ storeTableMetric(
+ id, "metric", Optional.empty(), new MetricRecordImpl(currentEpochSeconds(), null)));
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ storeTableMetric(
+ NameIdentifier.of("catalog", "db", "t".repeat(1021)),
+ "metric",
+ Optional.empty(),
+ new MetricRecordImpl(currentEpochSeconds(), "v1")));
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ storeTableMetric(
+ id,
+ "m".repeat(1025),
+ Optional.empty(),
+ new MetricRecordImpl(currentEpochSeconds(), "v1")));
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ storeTableMetric(
+ id,
+ "metric",
+ Optional.empty(),
+ new MetricRecordImpl(currentEpochSeconds(), "x".repeat(1025))));
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ storeJobMetric(
+ id, "metric", new MetricRecordImpl(currentEpochSeconds(), "x".repeat(1025))));
+ }
+
+ @Test
+ void testCleanupValidationFailsFast() {
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> storage.cleanupTableMetricsBefore(-1));
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> storage.cleanupJobMetricsBefore(-1));
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> storage.cleanupTableMetricsBefore(System.currentTimeMillis()));
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> storage.cleanupJobMetricsBefore(System.currentTimeMillis()));
+ }
+
+ @Test
+ void testLongPartitionAndValueAreSupported() {
+ NameIdentifier tableId = NameIdentifier.of("catalog", "db", "long_payload_table");
+ NameIdentifier jobId = NameIdentifier.of("catalog", "db", "long_payload_job");
+ String partition = "p=" + "x".repeat(300);
+ String longValue = "v".repeat(1000);
+ long now = currentEpochSeconds();
+
+ storeTableMetric(
+ tableId, "metric_long", Optional.of(partition), new MetricRecordImpl(now, longValue));
+ storeJobMetric(jobId, "metric_long", new MetricRecordImpl(now, longValue));
+
+ Map<String, List<MetricRecord>> tableMetrics =
+ storage.getPartitionMetrics(tableId, partition, 0, Long.MAX_VALUE);
+ Assertions.assertTrue(tableMetrics.containsKey("metric_long"));
+ Assertions.assertEquals(longValue, tableMetrics.get("metric_long").get(0).getValue());
+
+ Map<String, List<MetricRecord>> jobMetrics = storage.getJobMetrics(jobId, 0, Long.MAX_VALUE);
+ Assertions.assertTrue(jobMetrics.containsKey("metric_long"));
+ Assertions.assertEquals(longValue, jobMetrics.get("metric_long").get(0).getValue());
+ }
+
+ @Test
+ void testInitializeWithoutSchemaAutoCreatesForH2() {
+ GenericJdbcMetricsRepository repository = new GenericJdbcMetricsRepository();
+ String autoCreateSchemaJdbcUrl = jdbcUrl + "_auto_create_schema";
+ repository.initialize(createJdbcConfigs(autoCreateSchemaJdbcUrl));
+
+ NameIdentifier tableId = NameIdentifier.of("catalog", "db", "auto_create_table");
+ long now = currentEpochSeconds();
+ repository.storeTableMetrics(
+ List.of(
+ new TableMetricWriteRequest(
+ tableId, "row_count", Optional.empty(), new MetricRecordImpl(now, "12"))));
+
+ Map<String, List<MetricRecord>> metrics = repository.getTableMetrics(tableId, now - 1, now + 1);
+ Assertions.assertTrue(metrics.containsKey("row_count"));
+ Assertions.assertEquals(List.of("12"), getMetricValues(metrics.get("row_count")));
+ repository.cleanupTableMetricsBefore(MAX_REASONABLE_EPOCH_SECONDS);
+ repository.cleanupJobMetricsBefore(MAX_REASONABLE_EPOCH_SECONDS);
+ repository.close();
+ }
+
+ private List<String> getMetricValues(List<MetricRecord> metrics) {
+ return metrics.stream().map(MetricRecord::getValue).toList();
+ }
+
+ private void storeTableMetric(
+ NameIdentifier nameIdentifier,
+ String metricName,
+ Optional<String> partition,
+ MetricRecord metric) {
+ storage.storeTableMetrics(
+ List.of(new TableMetricWriteRequest(nameIdentifier, metricName, partition, metric)));
+ }
+
+ private void storeJobMetric(
+ NameIdentifier nameIdentifier, String metricName, MetricRecord metric) {
+ storage.storeJobMetrics(List.of(new JobMetricWriteRequest(nameIdentifier, metricName, metric)));
+ }
+
+ private long currentEpochSeconds() {
+ return Instant.now().getEpochSecond();
+ }
+
+ private void cleanupLegacyDataFiles() throws IOException {
+ deleteIfExists("data/metrics.db.mv.db");
+ deleteIfExists("data/metrics.db.trace.db");
+ deleteIfExists("maintenance/optimizer/data/metrics.db.mv.db");
+ deleteIfExists("maintenance/optimizer/data/metrics.db.trace.db");
+ deleteIfExists("maintenance/optimizer/metrics_db.mv.db");
+ deleteIfExists("maintenance/optimizer/metrics_db.trace.db");
+ deleteIfExists("metrics_db.mv.db");
+ deleteIfExists("metrics_db.trace.db");
+ }
+
+ private void deleteIfExists(String filePath) throws IOException {
+ Files.deleteIfExists(Path.of(filePath));
+ }
+
+ private Map<String, String> createJdbcConfigs(String jdbcUrl) {
+ return Map.of(
+ OptimizerConfig.OPTIMIZER_PREFIX
+ + GenericJdbcMetricsRepository.JDBC_METRICS_PREFIX
+ + GenericJdbcMetricsRepository.JDBC_URL,
+ jdbcUrl,
+ OptimizerConfig.OPTIMIZER_PREFIX
+ + GenericJdbcMetricsRepository.JDBC_METRICS_PREFIX
+ + GenericJdbcMetricsRepository.JDBC_USER,
+ "sa",
+ OptimizerConfig.OPTIMIZER_PREFIX
+ + GenericJdbcMetricsRepository.JDBC_METRICS_PREFIX
+ + GenericJdbcMetricsRepository.JDBC_PASSWORD,
+ "",
+ OptimizerConfig.OPTIMIZER_PREFIX
+ + GenericJdbcMetricsRepository.JDBC_METRICS_PREFIX
+ + GenericJdbcMetricsRepository.JDBC_DRIVER,
+ "org.h2.Driver");
+ }
+
+ private void initializeSchema(String jdbcUrl) {
+ String schemaSql = loadSchemaSql();
+ try (Connection conn = DriverManager.getConnection(jdbcUrl, "sa", "")) {
+ JdbcSqlScriptUtils.executeSqlScript(conn, schemaSql);
+ } catch (SQLException e) {
+ throw new RuntimeException("Failed to initialize test schema for metrics", e);
+ }
+ }
+
+ private String loadSchemaSql() {
+ String gravitinoHome = System.getenv("GRAVITINO_HOME");
+ if (StringUtils.isBlank(gravitinoHome)) {
+ throw new RuntimeException("GRAVITINO_HOME environment variable is not set");
+ }
+
+ Path scriptPath =
+ Paths.get(
+ gravitinoHome,
+ "scripts",
+ "h2",
+ "optimizer-metrics-schema-" + ConfigConstants.CURRENT_SCRIPT_VERSION + "-h2.sql");
+ try {
+ return Files.readString(scriptPath, StandardCharsets.UTF_8);
+ } catch (IOException e) {
+ throw new RuntimeException("Failed to load schema script: " + scriptPath, e);
+ }
+ }
+}
diff --git a/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/updater/statistics/TestGravitinoStatisticsUpdater.java b/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/updater/statistics/TestGravitinoStatisticsUpdater.java
new file mode 100644
index 0000000000..65e5ea4b6c
--- /dev/null
+++ b/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/updater/statistics/TestGravitinoStatisticsUpdater.java
@@ -0,0 +1,138 @@
+/*
+ * 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.optimizer.updater.statistics;
+
+import java.lang.reflect.Field;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.client.GravitinoClient;
+import org.apache.gravitino.maintenance.optimizer.api.common.PartitionPath;
+import org.apache.gravitino.maintenance.optimizer.api.common.StatisticEntry;
+import org.apache.gravitino.maintenance.optimizer.common.PartitionEntryImpl;
+import org.apache.gravitino.maintenance.optimizer.common.StatisticEntryImpl;
+import org.apache.gravitino.maintenance.optimizer.recommender.util.PartitionUtils;
+import org.apache.gravitino.stats.PartitionStatisticsUpdate;
+import org.apache.gravitino.stats.StatisticValue;
+import org.apache.gravitino.stats.StatisticValues;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mockito;
+
+class TestGravitinoStatisticsUpdater {
+
+ @Test
+ void testUpdateTableStatisticsWithoutInitializeFails() {
+ GravitinoStatisticsUpdater updater = new GravitinoStatisticsUpdater();
+ IllegalStateException exception =
+ Assertions.assertThrows(
+ IllegalStateException.class,
+ () ->
+ updater.updateTableStatistics(
+ NameIdentifier.of("catalog", "db", "table"), List.of()));
+ Assertions.assertTrue(exception.getMessage().contains("has not been initialized"));
+ }
+
+ @Test
+ @SuppressWarnings("unchecked")
+ void testUpdateTableStatisticsDuplicateNameLastWins() throws Exception {
+ GravitinoStatisticsUpdater updater = new GravitinoStatisticsUpdater();
+ GravitinoClient client = Mockito.mock(GravitinoClient.class, Mockito.RETURNS_DEEP_STUBS);
+ setClient(updater, client);
+ NameIdentifier tableIdentifier = NameIdentifier.of("catalog", "db", "table");
+
+ updater.updateTableStatistics(
+ tableIdentifier,
+ List.of(stat("row_count", 10L), stat("row_count", 20L), stat("size", 30L)));
+
+ ArgumentCaptor<Map<String, StatisticValue<?>>> captor = ArgumentCaptor.forClass(Map.class);
+ Mockito.verify(
+ client
+ .loadCatalog("catalog")
+ .asTableCatalog()
+ .loadTable(NameIdentifier.of("db", "table"))
+ .supportsStatistics())
+ .updateStatistics(captor.capture());
+ Map<String, StatisticValue<?>> result = captor.getValue();
+ Assertions.assertEquals(2, result.size());
+ Assertions.assertEquals(20L, result.get("row_count").value());
+ Assertions.assertEquals(30L, result.get("size").value());
+ }
+
+ @Test
+ void testUpdatePartitionStatisticsNullPartitionPathFails() throws Exception {
+ GravitinoStatisticsUpdater updater = new GravitinoStatisticsUpdater();
+ GravitinoClient client = Mockito.mock(GravitinoClient.class, Mockito.RETURNS_DEEP_STUBS);
+ setClient(updater, client);
+
+ Map<PartitionPath, List<StatisticEntry<?>>> partitionStatistics = new HashMap<>();
+ partitionStatistics.put(null, List.of(stat("s1", 1L)));
+
+ IllegalArgumentException exception =
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ updater.updatePartitionStatistics(
+ NameIdentifier.of("catalog", "db", "table"), partitionStatistics));
+ Assertions.assertTrue(exception.getMessage().contains("partition path must not be null"));
+ }
+
+ @Test
+ @SuppressWarnings("unchecked")
+ void testUpdatePartitionStatisticsDuplicateNameLastWins() throws Exception {
+ GravitinoStatisticsUpdater updater = new GravitinoStatisticsUpdater();
+ GravitinoClient client = Mockito.mock(GravitinoClient.class, Mockito.RETURNS_DEEP_STUBS);
+ setClient(updater, client);
+ NameIdentifier tableIdentifier = NameIdentifier.of("catalog", "db", "table");
+ PartitionPath partitionPath = PartitionPath.of(List.of(new PartitionEntryImpl("p", "1")));
+
+ updater.updatePartitionStatistics(
+ tableIdentifier,
+ Map.of(partitionPath, List.of(stat("s1", 1L), stat("s1", 2L), stat("s2", 3L))));
+
+ ArgumentCaptor<List<PartitionStatisticsUpdate>> captor = ArgumentCaptor.forClass(List.class);
+ Mockito.verify(
+ client
+ .loadCatalog("catalog")
+ .asTableCatalog()
+ .loadTable(NameIdentifier.of("db", "table"))
+ .supportsPartitionStatistics())
+ .updatePartitionStatistics(captor.capture());
+ List<PartitionStatisticsUpdate> updates = captor.getValue();
+ Assertions.assertEquals(1, updates.size());
+ Assertions.assertEquals(
+ PartitionUtils.encodePartitionPath(partitionPath), updates.get(0).partitionName());
+ Assertions.assertEquals(2L, updates.get(0).statistics().get("s1").value());
+ Assertions.assertEquals(3L, updates.get(0).statistics().get("s2").value());
+ }
+
+ private StatisticEntry<?> stat(String name, long value) {
+ return new StatisticEntryImpl<>(name, StatisticValues.longValue(value));
+ }
+
+ private void setClient(GravitinoStatisticsUpdater updater, GravitinoClient client)
+ throws ReflectiveOperationException {
+ Field field = GravitinoStatisticsUpdater.class.getDeclaredField("gravitinoClient");
+ field.setAccessible(true);
+ field.set(updater, client);
+ }
+}
diff --git a/scripts/h2/optimizer-metrics-schema-1.2.0-h2.sql b/scripts/h2/optimizer-metrics-schema-1.2.0-h2.sql
new file mode 100644
index 0000000000..1c81c024ec
--- /dev/null
+++ b/scripts/h2/optimizer-metrics-schema-1.2.0-h2.sql
@@ -0,0 +1,41 @@
+-- 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.
+
+-- Optimizer metrics schema for H2
+CREATE TABLE IF NOT EXISTS table_metrics (
+ id BIGINT AUTO_INCREMENT PRIMARY KEY,
+ table_identifier VARCHAR(1024) NOT NULL,
+ metric_name VARCHAR(1024) NOT NULL,
+ table_partition VARCHAR(1024),
+ metric_ts BIGINT NOT NULL,
+ metric_value VARCHAR(1024) NOT NULL
+);
+
+CREATE TABLE IF NOT EXISTS job_metrics (
+ id BIGINT AUTO_INCREMENT PRIMARY KEY,
+ job_identifier VARCHAR(1024) NOT NULL,
+ metric_name VARCHAR(1024) NOT NULL,
+ metric_ts BIGINT NOT NULL,
+ metric_value VARCHAR(1024) NOT NULL
+);
+
+CREATE INDEX IF NOT EXISTS idx_table_metrics_metric_ts ON table_metrics(metric_ts);
+CREATE INDEX IF NOT EXISTS idx_job_metrics_metric_ts ON job_metrics(metric_ts);
+CREATE INDEX IF NOT EXISTS idx_table_metrics_composite
+ ON table_metrics(table_identifier, table_partition, metric_ts);
+CREATE INDEX IF NOT EXISTS idx_job_metrics_identifier_metric_ts
+ ON job_metrics(job_identifier, metric_ts);