Skip to content

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

[#12179] feat(core): Migrate legacy policy bindings through hidden tags (#14375)

roryqi51012c832fd7
diff --git a/bin/migrate-policy-bindings.sh.template b/bin/migrate-policy-bindings.sh.template
new file mode 100644
index 0000000000..36d2359733
--- /dev/null
+++ b/bin/migrate-policy-bindings.sh.template
@@ -0,0 +1,35 @@
+#!/bin/bash
+#
+# 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.
+#
+
+set -eo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+# shellcheck source=bin/common.sh.template
+. "${SCRIPT_DIR}/common.sh"
+check_java_version
+if [[ "$#" -eq 1 && "$1" == "--help" ]]; then
+ echo "Usage: bin/migrate-policy-bindings.sh [--help]"
+ echo "Stop all servers and back up the metadata database before running this tool."
+ exit 0
+fi
+addJarInDir "${GRAVITINO_HOME}/libs"
+cd "${GRAVITINO_HOME}"
+exec "${JAVA_RUNNER}" -Dlog4j2.configurationFile=classpath:policy-binding-migration-log4j2.properties -cp "${GRAVITINO_CLASSPATH}" \
+ org.apache.gravitino.policy.PolicyBindingMigrationTool "$@"
diff --git a/core/src/main/java/org/apache/gravitino/policy/PolicyBindingMigration.java b/core/src/main/java/org/apache/gravitino/policy/PolicyBindingMigration.java
new file mode 100644
index 0000000000..6d3c5725fd
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/policy/PolicyBindingMigration.java
@@ -0,0 +1,337 @@
+/*
+ * 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.policy;
+
+import static org.apache.gravitino.tag.TagManager.SUPPORTED_METADATA_OBJECT_TYPES_FOR_TAGS;
+
+import com.google.common.base.Preconditions;
+import java.io.IOException;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import javax.annotation.Nullable;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.EntityStore;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.RelationEdgeTarget;
+import org.apache.gravitino.RelationUpdate;
+import org.apache.gravitino.SupportsRelationOperations;
+import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.json.JsonUtils;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GenericEntity;
+import org.apache.gravitino.meta.PolicyEntity;
+import org.apache.gravitino.meta.TagEntity;
+import org.apache.gravitino.storage.RandomIdGenerator;
+import org.apache.gravitino.storage.relational.service.MetadataObjectService;
+import org.apache.gravitino.storage.relational.session.SqlSessions;
+import org.apache.gravitino.tag.TagValueConstraint;
+import org.apache.gravitino.utils.MetadataObjectUtil;
+import org.apache.gravitino.utils.NameIdentifierUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Offline conversion of legacy object-policy relations into server-managed tag relations. */
+public final class PolicyBindingMigration {
+
+ private static final Logger LOG = LoggerFactory.getLogger(PolicyBindingMigration.class);
+ private final Connection connection;
+ private final EntityStore entityStore;
+ private final PolicyManager policyManager;
+
+ /**
+ * Creates a migrator in the current SQL session. All servers must be stopped before running it.
+ *
+ * @param connection The current entity store session's connection.
+ * @param entityStore An uncached entity store participating in that session.
+ */
+ public PolicyBindingMigration(Connection connection, EntityStore entityStore) {
+ this.connection = connection;
+ this.entityStore = entityStore;
+ this.policyManager = new PolicyManager(RandomIdGenerator.INSTANCE, entityStore);
+ }
+
+ /**
+ * Converts and verifies each policy's bindings before retiring its legacy rows in one
+ * transaction. A failure rolls back that policy and is reported after the remaining policies are
+ * processed. If rollback fails, processing stops and the summary includes unprocessed policies.
+ * Rerunning resumes from the active legacy rows. Missing owners and objects are logged and
+ * skipped without retiring their bindings.
+ *
+ * @return The number of migrated bindings.
+ * @throws SQLException If a binding cannot be converted or verified.
+ */
+ public long migrate() throws SQLException {
+ Preconditions.checkState(!connection.getAutoCommit(), "Migration requires a transaction");
+ long migrated = 0;
+ long skippedPolicies = 0;
+ long skippedBindings = 0;
+ long skippedObjectBindings = 0;
+ long failedPolicies = 0;
+ SQLException firstFailure = null;
+ List<Long> policyIds = pendingPolicies();
+ long unprocessedPolicies = policyIds.size();
+ for (long policyId : policyIds) {
+ unprocessedPolicies--;
+ try {
+ long bindings =
+ count(
+ "SELECT COUNT(*) FROM policy_relation_meta WHERE policy_id = ? AND deleted_at = 0",
+ policyId);
+ PolicyEntity policy = loadPolicy(policyId);
+ if (policy == null) {
+ skippedPolicies++;
+ skippedBindings += bindings;
+ LOG.warn(
+ "Skipping {} legacy bindings for policy_id={}: policy or metalake is missing or deleted;"
+ + " bindings remain active",
+ bindings,
+ policyId);
+ continue;
+ }
+ TagEntity tag = hiddenTag(policy);
+ long converted = bindObjects(policy);
+ verifyReplacement(policyId, tag.id(), converted);
+ try (PreparedStatement statement =
+ prepare(
+ "UPDATE policy_relation_meta SET deleted_at = ?, last_version = current_version + 1,"
+ + " current_version = current_version + 1 WHERE policy_id = ? AND deleted_at = 0"
+ + " AND EXISTS (SELECT 1 FROM tag_relation_meta r WHERE r.tag_id = ?"
+ + " AND r.metadata_object_id = policy_relation_meta.metadata_object_id"
+ + " AND r.metadata_object_type = policy_relation_meta.metadata_object_type"
+ + " AND r.deleted_at = 0 AND r.tag_value = '')",
+ System.currentTimeMillis(),
+ policyId,
+ tag.id())) {
+ if (statement.executeUpdate() != converted) {
+ throw new SQLException("Legacy bindings changed for policy " + policyId);
+ }
+ }
+ connection.commit();
+ migrated += converted;
+ skippedObjectBindings += bindings - converted;
+ LOG.info("Migrated {} bindings for policy {}", converted, policyId);
+ } catch (IOException | SQLException | RuntimeException e) {
+ failedPolicies++;
+ LOG.error("Failed to migrate policy_id={}; legacy bindings remain active", policyId, e);
+ if (firstFailure == null) {
+ firstFailure =
+ new SQLException(
+ "Cannot migrate policy " + policyId + "; legacy bindings remain active", e);
+ }
+ try {
+ connection.rollback();
+ } catch (SQLException rollbackFailure) {
+ firstFailure.addSuppressed(rollbackFailure);
+ LOG.error(
+ "Rollback failed for policy_id={}; stopping migration with {} unprocessed policies",
+ policyId,
+ unprocessedPolicies,
+ rollbackFailure);
+ break;
+ }
+ } finally {
+ // Balance this temporary reference; the caller still owns the thread-bound session.
+ SqlSessions.getSqlSession().clearCache();
+ SqlSessions.closeSqlSession();
+ }
+ }
+ LOG.info(
+ "Migration complete: migrated_bindings={}, skipped_orphan_policies={}, skipped_orphan_bindings={},"
+ + " skipped_missing_object_bindings={}, failed_policies={}, unprocessed_policies={};"
+ + " skipped bindings remain active",
+ migrated,
+ skippedPolicies,
+ skippedBindings,
+ skippedObjectBindings,
+ failedPolicies,
+ unprocessedPolicies);
+ if (skippedBindings > 0 || skippedObjectBindings > 0) {
+ LOG.warn(
+ "Migration left {} orphaned bindings and {} bindings to missing objects active in the legacy"
+ + " table. The new server does not read these bindings; review the logged IDs before"
+ + " completing the upgrade.",
+ skippedBindings,
+ skippedObjectBindings);
+ }
+ if (firstFailure != null) {
+ throw firstFailure;
+ }
+ return migrated;
+ }
+
+ private List<Long> pendingPolicies() throws SQLException {
+ List<Long> ids = new ArrayList<>();
+ try (PreparedStatement statement =
+ connection.prepareStatement(
+ "SELECT DISTINCT policy_id FROM policy_relation_meta WHERE deleted_at = 0 ORDER BY policy_id");
+ ResultSet rows = statement.executeQuery()) {
+ while (rows.next()) {
+ ids.add(rows.getLong(1));
+ }
+ }
+ return ids;
+ }
+
+ @Nullable
+ private PolicyEntity loadPolicy(long policyId) throws IOException, SQLException {
+ try (PreparedStatement statement =
+ prepare(
+ "SELECT m.metalake_name, p.policy_name FROM policy_meta p JOIN metalake_meta m"
+ + " ON p.metalake_id = m.metalake_id WHERE p.policy_id = ?"
+ + " AND p.deleted_at = 0 AND m.deleted_at = 0",
+ policyId);
+ ResultSet rows = statement.executeQuery()) {
+ if (!rows.next()) {
+ return null;
+ }
+ return entityStore.get(
+ NameIdentifierUtil.ofPolicy(rows.getString(1), rows.getString(2)),
+ Entity.EntityType.POLICY,
+ PolicyEntity.class);
+ }
+ }
+
+ private TagEntity hiddenTag(PolicyEntity policy) throws IOException, SQLException {
+ NameIdentifier identifier =
+ NameIdentifierUtil.ofTag(policy.namespace().level(0), HiddenPolicyTag.name(policy.id()));
+ try {
+ TagEntity tag = entityStore.get(identifier, Entity.EntityType.TAG, TagEntity.class);
+ if (!HiddenPolicyTag.create(policy, tag.id()).properties().equals(tag.properties())
+ || tag.valueConstraint().type() != TagValueConstraint.Type.NO_VALUE) {
+ throw new SQLException(
+ "Hidden tag name collision for policy " + policy.id() + ": " + identifier);
+ }
+ return tag;
+ } catch (NoSuchEntityException e) {
+ TagEntity tag = HiddenPolicyTag.create(policy, RandomIdGenerator.INSTANCE.nextId());
+ entityStore.put(tag, false);
+ entityStore
+ .relationOperations()
+ .updateEntityRelations(
+ RelationUpdate.of(
+ SupportsRelationOperations.Type.POLICY_TAG_REL,
+ identifier,
+ Entity.EntityType.TAG,
+ new RelationEdgeTarget[] {
+ RelationEdgeTarget.of(
+ policy.nameIdentifier(), Entity.EntityType.POLICY, null)
+ },
+ null)
+ .withAuditInfo(policy.auditInfo()));
+ return tag;
+ }
+ }
+
+ private long bindObjects(PolicyEntity policy) throws IOException, SQLException {
+ long converted = 0;
+ try (PreparedStatement statement =
+ prepare(
+ "SELECT metadata_object_id, metadata_object_type, audit_info FROM policy_relation_meta"
+ + " WHERE policy_id = ? AND deleted_at = 0 ORDER BY id",
+ policy.id());
+ ResultSet rows = statement.executeQuery()) {
+ while (rows.next()) {
+ long objectId = rows.getLong(1);
+ MetadataObject.Type type = MetadataObject.Type.valueOf(rows.getString(2));
+ Preconditions.checkArgument(
+ SUPPORTED_METADATA_OBJECT_TYPES_FOR_TAGS.contains(type),
+ "Unsupported policy binding object type: %s",
+ type);
+ List<MetadataObject> objects =
+ MetadataObjectService.fromGenericEntities(
+ Collections.singletonList(
+ GenericEntity.builder()
+ .withId(objectId)
+ .withEntityType(MetadataObjectUtil.toEntityType(type))
+ .build()));
+ if (objects.isEmpty()) {
+ LOG.warn(
+ "Skipping legacy binding for policy_id={}, metadata_object_id={}, metadata_object_type={}:"
+ + " target is missing or deleted; binding remains active",
+ policy.id(),
+ objectId,
+ type);
+ continue;
+ }
+ policyManager.addPolicyToObject(
+ policy.namespace().level(0),
+ policy.name(),
+ objects.get(0),
+ JsonUtils.anyFieldMapper().readValue(rows.getString(3), AuditInfo.class));
+ converted++;
+ }
+ }
+ return converted;
+ }
+
+ private void verifyReplacement(long policyId, long tagId, long converted) throws SQLException {
+ // addPolicyToObject does not check the policy-to-tag relation. Verify it before retiring rows.
+ if (count(
+ "SELECT COUNT(*) FROM policy_tag_relation_meta WHERE tag_id = ? AND deleted_at = 0",
+ tagId)
+ != 1
+ || count(
+ "SELECT COUNT(*) FROM policy_tag_relation_meta WHERE tag_id = ?"
+ + " AND policy_id = ? AND selector IS NULL AND deleted_at = 0",
+ tagId,
+ policyId)
+ != 1) {
+ throw new SQLException(
+ "Replacement policy relation is missing or invalid for policy " + policyId);
+ }
+ if (count(
+ "SELECT COUNT(*) FROM policy_relation_meta l WHERE l.policy_id = ?"
+ + " AND l.deleted_at = 0 AND EXISTS (SELECT 1 FROM tag_relation_meta r"
+ + " WHERE r.tag_id = ? AND r.metadata_object_id = l.metadata_object_id"
+ + " AND r.metadata_object_type = l.metadata_object_type"
+ + " AND r.deleted_at = 0 AND r.tag_value = '')",
+ policyId,
+ tagId)
+ != converted) {
+ throw new SQLException("Replacement object relation is missing for policy " + policyId);
+ }
+ }
+
+ private long count(String sql, Object... parameters) throws SQLException {
+ try (PreparedStatement statement = prepare(sql, parameters);
+ ResultSet rows = statement.executeQuery()) {
+ rows.next();
+ return rows.getLong(1);
+ }
+ }
+
+ private PreparedStatement prepare(String sql, Object... parameters) throws SQLException {
+ PreparedStatement statement = connection.prepareStatement(sql);
+ try {
+ for (int i = 0; i < parameters.length; i++) {
+ statement.setObject(i + 1, parameters[i]);
+ }
+ return statement;
+ } catch (SQLException | RuntimeException e) {
+ statement.close();
+ throw e;
+ }
+ }
+}
diff --git a/core/src/main/java/org/apache/gravitino/policy/PolicyBindingMigrationTool.java b/core/src/main/java/org/apache/gravitino/policy/PolicyBindingMigrationTool.java
new file mode 100644
index 0000000000..e7650275a6
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/policy/PolicyBindingMigrationTool.java
@@ -0,0 +1,82 @@
+/*
+ * 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.policy;
+
+import com.google.common.base.Preconditions;
+import java.sql.Connection;
+import org.apache.gravitino.Config;
+import org.apache.gravitino.Configs;
+import org.apache.gravitino.EntityStore;
+import org.apache.gravitino.storage.relational.JDBCBackend;
+import org.apache.gravitino.storage.relational.JDBCBackend.JDBCBackendType;
+import org.apache.gravitino.storage.relational.RelationalEntityStore;
+import org.apache.gravitino.storage.relational.converters.SQLExceptionConverterFactory;
+import org.apache.gravitino.storage.relational.database.H2Database;
+import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;
+import org.apache.gravitino.storage.relational.session.SqlSessions;
+import org.apache.gravitino.storage.relational.utils.SessionUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Command-line entry point for offline policy binding migration. */
+public final class PolicyBindingMigrationTool {
+
+ private static final Logger LOG = LoggerFactory.getLogger(PolicyBindingMigrationTool.class);
+
+ private PolicyBindingMigrationTool() {}
+
+ /**
+ * Runs the offline migration against the configured metadata store.
+ *
+ * @param args No arguments; configuration is read from gravitino.conf.
+ * @throws Exception If configuration or migration fails.
+ */
+ public static void main(String[] args) throws Exception {
+ Preconditions.checkArgument(args.length == 0, "Usage: bin/migrate-policy-bindings.sh [--help]");
+ Config config = new Config() {};
+ // Config resolves GRAVITINO_CONF_DIR, falling back to GRAVITINO_HOME/conf.
+ config.loadFromFile("gravitino.conf");
+ Preconditions.checkArgument(
+ Configs.RELATIONAL_ENTITY_STORE.equals(config.get(Configs.ENTITY_STORE))
+ && Configs.DEFAULT_ENTITY_RELATIONAL_STORE.equals(
+ config.get(Configs.ENTITY_RELATIONAL_STORE)),
+ "Policy migration requires the JDBC relational entity store");
+ String url = config.get(Configs.ENTITY_RELATIONAL_JDBC_BACKEND_URL);
+ if (JDBCBackendType.fromURI(url) == JDBCBackendType.H2) {
+ url = H2Database.getConnectionUrl(config);
+ // Never initialize an empty database when the configured path is wrong.
+ url = url.replaceAll("(?i);IFEXISTS=[^;]*", "") + ";IFEXISTS=TRUE";
+ }
+ config.set(Configs.ENTITY_RELATIONAL_JDBC_BACKEND_URL, url);
+ SqlSessionFactoryHelper.getInstance().init(config);
+ SQLExceptionConverterFactory.initConverter(config);
+ try (EntityStore entityStore =
+ RelationalEntityStore.forOfflineMigration(new JDBCBackend(), config)) {
+ SessionUtils.beginTransaction();
+ try {
+ Connection connection = SqlSessions.currentConnection();
+ LOG.info(
+ "Migrated {} legacy policy bindings",
+ new PolicyBindingMigration(connection, entityStore).migrate());
+ } finally {
+ SessionUtils.rollbackTransaction();
+ }
+ }
+ }
+}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStore.java b/core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStore.java
index 3844759c8a..1a48861955 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStore.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStore.java
@@ -110,6 +110,25 @@ public class RelationalEntityStore
return cache;
}
+ /**
+ * Wraps a relational backend for offline migration without caches or background workers.
+ *
+ * <p>The caller initializes the SQL session factory and owns transaction boundaries. Closing the
+ * returned store also closes the backend. All servers sharing the database must be stopped.
+ *
+ * @param backend The backend using the caller's SQL session factory.
+ * @param config The configuration for the uncached store.
+ * @return A store that participates in the current thread's SQL transaction.
+ */
+ public static RelationalEntityStore forOfflineMigration(
+ RelationalBackend backend, Config config) {
+ RelationalEntityStore store = new RelationalEntityStore();
+ store.backend = backend;
+ store.cache = new NoOpsCache(config);
+ EntityIdService.initialize(new RelationalEntityStoreIdResolver());
+ return store;
+ }
+
@Override
public void initialize(Config config) throws RuntimeException {
if (config.get(Configs.CACHE_ENABLED)) {
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/database/H2Database.java b/core/src/main/java/org/apache/gravitino/storage/relational/database/H2Database.java
index bc4801d62a..92bfb97455 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/database/H2Database.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/database/H2Database.java
@@ -48,12 +48,10 @@ public class H2Database implements JDBCDatabase {
public String startH2Database(Config config) {
String gravitinoHome = System.getenv("GRAVITINO_HOME");
- String storagePath = getStoragePath(config);
- String originalJDBCUrl = config.get(Configs.ENTITY_RELATIONAL_JDBC_BACKEND_URL);
this.username = config.get(Configs.ENTITY_RELATIONAL_JDBC_BACKEND_USER);
this.password = config.get(Configs.ENTITY_RELATIONAL_JDBC_BACKEND_PASSWORD);
- String connectionUrl = constructH2URI(originalJDBCUrl, storagePath);
+ String connectionUrl = getConnectionUrl(config);
try (Connection connection = DriverManager.getConnection(connectionUrl, username, password);
Statement statement = connection.createStatement()) {
@@ -77,6 +75,17 @@ public class H2Database implements JDBCDatabase {
return connectionUrl;
}
+ /**
+ * Resolves the configured H2 connection URL without initializing or upgrading the database.
+ *
+ * @param config The server configuration.
+ * @return The same file URL used by the embedded backend.
+ */
+ public static String getConnectionUrl(Config config) {
+ return constructH2URI(
+ config.get(Configs.ENTITY_RELATIONAL_JDBC_BACKEND_URL), getStoragePath(config));
+ }
+
private static String constructH2URI(String originURI, String storagePath) {
if (!originURI.contains(":file:")) {
originURI = "jdbc:h2:file:" + storagePath;
diff --git a/core/src/main/resources/policy-binding-migration-log4j2.properties b/core/src/main/resources/policy-binding-migration-log4j2.properties
new file mode 100644
index 0000000000..b09c0ec29c
--- /dev/null
+++ b/core/src/main/resources/policy-binding-migration-log4j2.properties
@@ -0,0 +1,26 @@
+#
+# 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.
+#
+
+status = warn
+appender.console.type = Console
+appender.console.name = console
+appender.console.layout.type = PatternLayout
+appender.console.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %-5p %m%n
+rootLogger.level = info
+rootLogger.appenderRef.console.ref = console
diff --git a/core/src/test/java/org/apache/gravitino/policy/TestPolicyBindingMigration.java b/core/src/test/java/org/apache/gravitino/policy/TestPolicyBindingMigration.java
new file mode 100644
index 0000000000..60cb9a3536
--- /dev/null
+++ b/core/src/test/java/org/apache/gravitino/policy/TestPolicyBindingMigration.java
@@ -0,0 +1,695 @@
+/*
+ * 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.policy;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.startsWith;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.spy;
+
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicInteger;
+import org.apache.gravitino.Config;
+import org.apache.gravitino.EntityStore;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.json.JsonUtils;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.CatalogEntity;
+import org.apache.gravitino.meta.ColumnEntity;
+import org.apache.gravitino.meta.PolicyEntity;
+import org.apache.gravitino.meta.TableEntity;
+import org.apache.gravitino.meta.TagEntity;
+import org.apache.gravitino.rel.types.Types;
+import org.apache.gravitino.storage.relational.RelationalEntityStore;
+import org.apache.gravitino.storage.relational.TestJDBCBackend;
+import org.apache.gravitino.storage.relational.session.SqlSessions;
+import org.apache.gravitino.storage.relational.utils.SessionUtils;
+import org.apache.logging.log4j.Level;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.core.LogEvent;
+import org.apache.logging.log4j.core.LoggerContext;
+import org.apache.logging.log4j.core.appender.AbstractAppender;
+import org.apache.logging.log4j.core.config.Configuration;
+import org.apache.logging.log4j.core.config.LoggerConfig;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.TestTemplate;
+
+/** Exercises the offline migrator against every supported metadata database. */
+public class TestPolicyBindingMigration extends TestJDBCBackend {
+
+ private Connection connection;
+ private EntityStore entityStore;
+ private PolicyEntity policy;
+ private CatalogEntity catalog;
+
+ /** Creates a legacy binding alongside the existing policy and tag tables. */
+ @BeforeEach
+ public void prepareLegacyDatabase() throws Exception {
+ entityStore = RelationalEntityStore.forOfflineMigration(backend, new Config(false) {});
+ SessionUtils.beginTransaction();
+ connection = SqlSessions.currentConnection();
+ try (Statement statement = connection.createStatement()) {
+ statement.execute(
+ "CREATE TABLE policy_relation_meta (id BIGINT PRIMARY KEY, policy_id BIGINT NOT NULL,"
+ + " metadata_object_id BIGINT NOT NULL, metadata_object_type VARCHAR(64) NOT NULL,"
+ + " audit_info TEXT NOT NULL, current_version INT NOT NULL DEFAULT 1,"
+ + " last_version INT NOT NULL DEFAULT 1, deleted_at BIGINT NOT NULL DEFAULT 0)");
+ }
+ connection.commit();
+ createAndInsertMakeLake("migration_test");
+ catalog = createAndInsertCatalog("migration_test", "catalog");
+ policy = createPolicy(20L, Namespace.of("migration_test"), "policy", AUDIT_INFO);
+ backend.insert(policy, false);
+ removeAutomaticallyCreatedTag(policy.id());
+ insertBinding(1, policy.id(), catalog.id(), "CATALOG");
+ connection.commit();
+ }
+
+ /** Removes the legacy-only table, which is absent from new installations. */
+ @AfterEach
+ public void removeLegacyDatabase() throws SQLException {
+ if (connection != null) {
+ connection.rollback();
+ try (Statement statement = connection.createStatement()) {
+ statement.execute("DROP TABLE IF EXISTS policy_relation_meta");
+ }
+ connection.commit();
+ SessionUtils.rollbackTransaction();
+ }
+ }
+
+ /** Verifies migration, audit preservation and repeat execution. */
+ @TestTemplate
+ public void testMigrationAndVerification() throws Exception {
+ PolicyBindingMigration migration = new PolicyBindingMigration(connection, entityStore);
+ assertEquals(0, count("tag_meta"));
+ assertEquals(1, migration.migrate());
+ assertEquals(0, activeLegacyBindings());
+ assertEquals(1, count("tag_meta"));
+ assertEquals(1, count("tag_relation_meta"));
+ assertEquals(1, count("policy_tag_relation_meta"));
+ assertEquals(1, count("policy_relation_meta"));
+ assertEquals(0, migration.migrate());
+ assertEquals(1, count("tag_meta"));
+ try (Statement statement = connection.createStatement();
+ ResultSet rows =
+ statement.executeQuery(
+ "SELECT r.audit_info, t.tag_name, t.allowed_values, p.selector FROM tag_relation_meta r"
+ + " JOIN tag_meta t ON r.tag_id = t.tag_id JOIN policy_tag_relation_meta p ON p.tag_id = t.tag_id")) {
+ assertTrue(rows.next());
+ assertEquals(
+ JsonUtils.anyFieldMapper().readValue("{}", AuditInfo.class),
+ JsonUtils.anyFieldMapper().readValue(rows.getString(1), AuditInfo.class));
+ assertEquals(HiddenPolicyTag.name(policy.id()), rows.getString(2));
+ assertEquals("[]", rows.getString(3));
+ assertEquals(null, rows.getString(4));
+ }
+ }
+
+ /** Verifies a failed cleanup rolls back only its policy and a retry resumes safely. */
+ @TestTemplate
+ public void testInterruptedMigrationResumesAfterCommittedPolicy() throws Exception {
+ PolicyEntity second = createPolicy(21L, policy.namespace(), "second_policy", AUDIT_INFO);
+ backend.insert(second, false);
+ removeAutomaticallyCreatedTag(second.id());
+ insertBinding(2, second.id(), catalog.id(), "CATALOG");
+ connection.commit();
+ Connection failing = spy(connection);
+ AtomicInteger cleanups = new AtomicInteger();
+ doAnswer(
+ invocation -> {
+ if (cleanups.incrementAndGet() == 2) {
+ throw new SQLException("Injected cleanup failure");
+ }
+ return connection.prepareStatement(invocation.getArgument(0));
+ })
+ .when(failing)
+ .prepareStatement(startsWith("UPDATE policy_relation_meta"));
+ assertThrows(
+ SQLException.class, () -> new PolicyBindingMigration(failing, entityStore).migrate());
+ assertEquals(1, activeLegacyBindings());
+ assertEquals(1, count("tag_meta"));
+ assertEquals(1, count("tag_relation_meta"));
+ // Restart the caller's session, as a new invocation would after an interruption.
+ SessionUtils.rollbackTransaction();
+ SessionUtils.beginTransaction();
+ connection = SqlSessions.currentConnection();
+ assertEquals(1, new PolicyBindingMigration(connection, entityStore).migrate());
+ assertEquals(2, count("tag_meta"));
+ }
+
+ /**
+ * Reports a collision without changing legacy rows, and permits retry after a user tag rename.
+ */
+ @TestTemplate
+ public void testReservedNameCollision() throws Exception {
+ entityStore.put(
+ TagEntity.builder()
+ .withId(100L)
+ .withName(HiddenPolicyTag.name(policy.id()))
+ .withNamespace(policy.namespace())
+ .withAuditInfo(AUDIT_INFO)
+ .build(),
+ false);
+ connection.commit();
+ SQLException failure =
+ assertThrows(
+ SQLException.class,
+ () -> new PolicyBindingMigration(connection, entityStore).migrate());
+ assertTrue(
+ failure.getCause().getMessage().contains("Hidden tag name collision for policy 20"),
+ () -> failure.getCause().toString());
+ assertTrue(failure.getCause().getMessage().contains(HiddenPolicyTag.name(policy.id())));
+ assertEquals(1, activeLegacyBindings());
+ assertEquals(0, count("tag_relation_meta"));
+ // Model the user tag rename performed on the old version before retrying the upgrade.
+ try (Statement statement = connection.createStatement()) {
+ statement.executeUpdate(
+ "UPDATE tag_meta SET tag_name = 'renamed_user_tag' WHERE tag_id = 100");
+ }
+ connection.commit();
+ assertEquals(1, new PolicyBindingMigration(connection, entityStore).migrate());
+ assertEquals(0, activeLegacyBindings());
+ assertEquals(2, activeCount("tag_meta"));
+ assertEquals(1, activeCount("tag_relation_meta"));
+ }
+
+ /** Missing objects remain active while valid bindings migrate and retry stays safe. */
+ @TestTemplate
+ public void testMissingObjectIsSkipped() throws Exception {
+ insertBinding(2, policy.id(), Long.MAX_VALUE, "TABLE");
+ connection.commit();
+ PolicyBindingMigration migration = new PolicyBindingMigration(connection, entityStore);
+ assertEquals(1, migration.migrate());
+ assertEquals(1, count("tag_relation_meta"));
+ assertEquals(1, activeLegacyBindings());
+ assertEquals(
+ 1,
+ queryCount("SELECT COUNT(*) FROM policy_relation_meta WHERE id = 1 AND deleted_at <> 0"));
+ assertEquals(
+ 1, queryCount("SELECT COUNT(*) FROM policy_relation_meta WHERE id = 2 AND deleted_at = 0"));
+ assertEquals(0, migration.migrate());
+ assertEquals(1, activeLegacyBindings());
+ }
+
+ /** Soft-deleted objects are skipped without retiring the dangling legacy binding. */
+ @TestTemplate
+ public void testDeletedObjectIsSkipped() throws Exception {
+ CatalogEntity deleted = createAndInsertCatalog("migration_test", "deleted_catalog");
+ insertBinding(2, policy.id(), deleted.id(), "CATALOG");
+ try (PreparedStatement statement =
+ connection.prepareStatement(
+ "UPDATE catalog_meta SET deleted_at = 1 WHERE catalog_id = ?")) {
+ statement.setLong(1, deleted.id());
+ statement.executeUpdate();
+ }
+ connection.commit();
+ assertEquals(1, new PolicyBindingMigration(connection, entityStore).migrate());
+ assertEquals(1, activeLegacyBindings());
+ assertEquals(1, count("tag_relation_meta"));
+ }
+
+ /** Failures preserve their policy's bindings while later policies still commit. */
+ @TestTemplate
+ public void testFailedPolicyDoesNotBlockLaterPolicies() throws Exception {
+ PolicyEntity bad = createPolicy(21L, policy.namespace(), "bad_policy", AUDIT_INFO);
+ PolicyEntity later = createPolicy(22L, policy.namespace(), "later_policy", AUDIT_INFO);
+ backend.insert(bad, false);
+ backend.insert(later, false);
+ removeAutomaticallyCreatedTag(bad.id());
+ removeAutomaticallyCreatedTag(later.id());
+ insertBinding(2, bad.id(), catalog.id(), "INVALID");
+ insertBinding(3, later.id(), catalog.id(), "CATALOG");
+ connection.commit();
+ SQLException failure =
+ assertThrows(
+ SQLException.class,
+ () -> new PolicyBindingMigration(connection, entityStore).migrate());
+ assertTrue(failure.getMessage().contains("policy 21"));
+ assertEquals(1, activeLegacyBindings());
+ assertEquals(2, count("tag_meta"));
+ assertEquals(2, count("policy_tag_relation_meta"));
+ assertEquals(2, count("tag_relation_meta"));
+ assertEquals(
+ 1,
+ queryCount("SELECT COUNT(*) FROM policy_relation_meta WHERE id = 3 AND deleted_at <> 0"));
+ try (Statement statement = connection.createStatement()) {
+ statement.executeUpdate(
+ "UPDATE policy_relation_meta SET metadata_object_type = 'CATALOG' WHERE id = 2");
+ }
+ connection.commit();
+ assertEquals(1, new PolicyBindingMigration(connection, entityStore).migrate());
+ assertEquals(0, activeLegacyBindings());
+ assertEquals(3, count("tag_relation_meta"));
+ }
+
+ /** Verification counts legacy rows, so duplicate rows can reuse one idempotent assignment. */
+ @TestTemplate
+ public void testDuplicateLegacyBindings() throws Exception {
+ insertBinding(2, policy.id(), catalog.id(), "CATALOG");
+ insertBinding(3, policy.id(), catalog.id(), "CATALOG");
+ connection.commit();
+ PolicyBindingMigration migration = new PolicyBindingMigration(connection, entityStore);
+ assertEquals(3, migration.migrate());
+ assertEquals(0, activeLegacyBindings());
+ assertEquals(1, count("tag_relation_meta"));
+ assertEquals(3, count("policy_relation_meta"));
+ assertEquals(0, migration.migrate());
+ }
+
+ /** Rejects references to a live object in another metalake. */
+ @TestTemplate
+ public void testForeignObjectBlocksMigration() throws Exception {
+ createAndInsertMakeLake("other_metalake");
+ CatalogEntity foreign = createAndInsertCatalog("other_metalake", catalog.name());
+ insertBinding(2, policy.id(), foreign.id(), "CATALOG");
+ connection.commit();
+ assertThrows(
+ SQLException.class, () -> new PolicyBindingMigration(connection, entityStore).migrate());
+ assertEquals(0, count("tag_meta"));
+ }
+
+ /** Missing policy rows are retained without preventing later live policies from migrating. */
+ @TestTemplate
+ public void testMissingPolicyDoesNotBlockLaterPolicies() throws Exception {
+ insertBinding(2, 19L, catalog.id(), "CATALOG");
+ connection.commit();
+ PolicyBindingMigration migration = new PolicyBindingMigration(connection, entityStore);
+ assertEquals(1, migration.migrate());
+ assertEquals(1, count("tag_meta"));
+ assertEquals(1, activeLegacyBindings());
+ assertEquals(0, migration.migrate());
+ assertEquals(1, activeLegacyBindings());
+ }
+
+ /**
+ * Summaries distinguish skips, failures and unprocessed policies, and warn about retained rows.
+ */
+ @TestTemplate
+ public void testMigrationSummaryAndRepeatExecution() throws Exception {
+ LoggerContext context =
+ (LoggerContext) LogManager.getContext(PolicyBindingMigration.class.getClassLoader(), false);
+ Configuration config = context.getConfiguration();
+ List<String> messages = new ArrayList<>();
+ List<String> warnings = new ArrayList<>();
+ AbstractAppender appender =
+ new AbstractAppender("migrationSummaryCapture", null, null, true, null) {
+ @Override
+ public void append(LogEvent event) {
+ messages.add(event.getMessage().getFormattedMessage());
+ if (Level.WARN.equals(event.getLevel())) {
+ warnings.add(event.getMessage().getFormattedMessage());
+ }
+ }
+ };
+ appender.start();
+ String loggerName = PolicyBindingMigration.class.getName();
+ LoggerConfig logger = new LoggerConfig(loggerName, Level.INFO, false);
+ logger.addAppender(appender, Level.INFO, null);
+ config.addLogger(loggerName, logger);
+ context.updateLoggers();
+ try {
+ PolicyBindingMigration migration = new PolicyBindingMigration(connection, entityStore);
+ assertEquals(1, migration.migrate());
+ assertTrue(warnings.isEmpty());
+ assertTrue(
+ messages.contains(
+ "Migration complete: migrated_bindings=1, skipped_orphan_policies=0, skipped_orphan_bindings=0, skipped_missing_object_bindings=0, failed_policies=0, unprocessed_policies=0;"
+ + " skipped bindings remain active"));
+ messages.clear();
+ assertEquals(0, migration.migrate());
+ assertTrue(
+ messages.contains(
+ "Migration complete: migrated_bindings=0, skipped_orphan_policies=0, skipped_orphan_bindings=0, skipped_missing_object_bindings=0, failed_policies=0, unprocessed_policies=0;"
+ + " skipped bindings remain active"));
+
+ insertBinding(2, 18L, catalog.id(), "CATALOG");
+ insertBinding(3, 18L, catalog.id(), "CATALOG");
+ insertBinding(4, 19L, catalog.id(), "CATALOG");
+ insertBinding(5, 17L, catalog.id(), "CATALOG");
+ insertBinding(6, policy.id(), catalog.id(), "CATALOG");
+ try (Statement statement = connection.createStatement()) {
+ statement.executeUpdate("UPDATE policy_relation_meta SET deleted_at = 1 WHERE id = 5");
+ }
+ connection.commit();
+ messages.clear();
+ assertEquals(1, migration.migrate());
+ assertEquals(3, activeLegacyBindings());
+ assertTrue(
+ messages.contains(
+ "Migration complete: migrated_bindings=1, skipped_orphan_policies=2, skipped_orphan_bindings=3, skipped_missing_object_bindings=0, failed_policies=0, unprocessed_policies=0;"
+ + " skipped bindings remain active"));
+ assertTrue(
+ messages.contains(
+ "Skipping 2 legacy bindings for policy_id=18: policy or metalake is missing or deleted;"
+ + " bindings remain active"));
+ assertTrue(
+ warnings.contains(
+ "Migration left 3 orphaned bindings and 0 bindings to missing objects active in the legacy"
+ + " table. The new server does not read these bindings; review the logged IDs before"
+ + " completing the upgrade."));
+ messages.clear();
+ assertEquals(0, migration.migrate());
+ assertEquals(3, activeLegacyBindings());
+ assertTrue(
+ messages.contains(
+ "Migration complete: migrated_bindings=0, skipped_orphan_policies=2, skipped_orphan_bindings=3, skipped_missing_object_bindings=0, failed_policies=0, unprocessed_policies=0;"
+ + " skipped bindings remain active"));
+ insertBinding(7, policy.id(), Long.MAX_VALUE, "TABLE");
+ connection.commit();
+ messages.clear();
+ assertEquals(0, migration.migrate());
+ assertEquals(4, activeLegacyBindings());
+ assertTrue(
+ messages.contains(
+ "Migration complete: migrated_bindings=0, skipped_orphan_policies=2, skipped_orphan_bindings=3,"
+ + " skipped_missing_object_bindings=1, failed_policies=0, unprocessed_policies=0; skipped bindings remain active"));
+ assertTrue(
+ messages.contains(
+ "Skipping legacy binding for policy_id=20, metadata_object_id="
+ + Long.MAX_VALUE
+ + ", metadata_object_type=TABLE: target is missing or deleted; binding remains active"));
+ assertTrue(
+ warnings.contains(
+ "Migration left 3 orphaned bindings and 1 bindings to missing objects active in the legacy"
+ + " table. The new server does not read these bindings; review the logged IDs before"
+ + " completing the upgrade."));
+
+ PolicyEntity later = createPolicy(21L, policy.namespace(), "later_policy", AUDIT_INFO);
+ backend.insert(later, false);
+ removeAutomaticallyCreatedTag(later.id());
+ insertBinding(8, later.id(), catalog.id(), "CATALOG");
+ connection.commit();
+ Connection failing = spy(connection);
+ SQLException migrationFailure = new SQLException("Injected cleanup failure");
+ SQLException rollbackFailure = new SQLException("Injected rollback failure");
+ doThrow(migrationFailure)
+ .when(failing)
+ .prepareStatement(startsWith("UPDATE policy_relation_meta"));
+ doThrow(rollbackFailure).when(failing).rollback();
+ messages.clear();
+ SQLException failure =
+ assertThrows(
+ SQLException.class, () -> new PolicyBindingMigration(failing, entityStore).migrate());
+ assertSame(migrationFailure, failure.getCause());
+ assertEquals(1, failure.getSuppressed().length);
+ assertSame(rollbackFailure, failure.getSuppressed()[0]);
+ assertTrue(
+ messages.contains(
+ "Migration complete: migrated_bindings=0, skipped_orphan_policies=2, skipped_orphan_bindings=3,"
+ + " skipped_missing_object_bindings=0, failed_policies=1, unprocessed_policies=1;"
+ + " skipped bindings remain active"));
+ assertTrue(
+ messages.contains(
+ "Rollback failed for policy_id=20; stopping migration with 1 unprocessed policies"));
+ assertEquals(5, activeLegacyBindings());
+ assertEquals(1, count("tag_meta"));
+ } finally {
+ config.removeLogger(loggerName);
+ context.updateLoggers();
+ appender.stop();
+ }
+ }
+
+ /** A soft-deleted policy's orphaned bindings must not abort the run. */
+ @TestTemplate
+ public void testDeletedPolicyDoesNotBlockLaterPolicies() throws Exception {
+ PolicyEntity deleted = createPolicy(19L, policy.namespace(), "deleted_policy", AUDIT_INFO);
+ backend.insert(deleted, false);
+ removeAutomaticallyCreatedTag(deleted.id());
+ insertBinding(2, deleted.id(), catalog.id(), "CATALOG");
+ try (Statement statement = connection.createStatement()) {
+ statement.executeUpdate("UPDATE policy_meta SET deleted_at = 1 WHERE policy_id = 19");
+ }
+ connection.commit();
+ assertEquals(1, new PolicyBindingMigration(connection, entityStore).migrate());
+ assertEquals(1, activeLegacyBindings());
+ assertEquals(1, count("tag_relation_meta"));
+ }
+
+ /** A soft-deleted metalake's orphaned bindings must not abort the run. */
+ @TestTemplate
+ public void testDeletedMetalakeDoesNotBlockLaterPolicies() throws Exception {
+ createAndInsertMakeLake("deleted_metalake");
+ PolicyEntity deleted =
+ createPolicy(19L, Namespace.of("deleted_metalake"), "deleted_policy", AUDIT_INFO);
+ backend.insert(deleted, false);
+ removeAutomaticallyCreatedTag(deleted.id());
+ insertBinding(2, deleted.id(), catalog.id(), "CATALOG");
+ try (Statement statement = connection.createStatement()) {
+ statement.executeUpdate(
+ "UPDATE metalake_meta SET deleted_at = 1 WHERE metalake_name = 'deleted_metalake'");
+ }
+ connection.commit();
+ assertEquals(1, new PolicyBindingMigration(connection, entityStore).migrate());
+ assertEquals(1, activeLegacyBindings());
+ assertEquals(1, count("tag_relation_meta"));
+ }
+
+ /** Both policy transactions keep the caller's connection live with auto-commit disabled. */
+ @TestTemplate
+ public void testMultiplePoliciesKeepSessionOpen() throws Exception {
+ PolicyEntity second = createPolicy(21L, policy.namespace(), "second_policy", AUDIT_INFO);
+ backend.insert(second, false);
+ removeAutomaticallyCreatedTag(second.id());
+ insertBinding(2, second.id(), catalog.id(), "CATALOG");
+ connection.commit();
+ Connection checked = spy(connection);
+ AtomicInteger policyLoads = new AtomicInteger();
+ doAnswer(
+ invocation -> {
+ assertFalse(connection.isClosed());
+ assertFalse(connection.getAutoCommit());
+ assertSame(connection, SqlSessions.currentConnection());
+ policyLoads.incrementAndGet();
+ return connection.prepareStatement(invocation.getArgument(0));
+ })
+ .when(checked)
+ .prepareStatement(startsWith("SELECT m.metalake_name, p.policy_name"));
+ assertEquals(2, new PolicyBindingMigration(checked, entityStore).migrate());
+ assertEquals(2, policyLoads.get());
+ assertFalse(connection.isClosed());
+ assertFalse(connection.getAutoCommit());
+ assertSame(connection, SqlSessions.currentConnection());
+ assertEquals(0, activeLegacyBindings());
+ assertEquals(2, count("tag_relation_meta"));
+ }
+
+ /** Object types without tag support and noncanonical names are rejected. */
+ @TestTemplate
+ public void testUnsupportedLegacyObjectType() throws Exception {
+ for (String type : new String[] {"METALAKE", "POLICY", "catalog"}) {
+ insertBinding(2, policy.id(), catalog.id(), type);
+ connection.commit();
+ assertThrows(
+ SQLException.class, () -> new PolicyBindingMigration(connection, entityStore).migrate());
+ assertEquals(0, count("tag_meta"));
+ try (Statement statement = connection.createStatement()) {
+ statement.executeUpdate("DELETE FROM policy_relation_meta WHERE id = 2");
+ }
+ connection.commit();
+ }
+ }
+
+ /** A changed selector must not silently narrow a migrated binding. */
+ @TestTemplate
+ public void testChangedSelectorRollsBackObjectAssignment() throws Exception {
+ new PolicyBindingMigration(connection, entityStore).migrate();
+ try (Statement statement = connection.createStatement()) {
+ statement.executeUpdate("UPDATE policy_relation_meta SET deleted_at = 0");
+ statement.executeUpdate("UPDATE policy_tag_relation_meta SET selector = '{}'");
+ statement.executeUpdate("DELETE FROM tag_relation_meta");
+ }
+ connection.commit();
+ assertThrows(
+ SQLException.class, () -> new PolicyBindingMigration(connection, entityStore).migrate());
+ assertEquals(1, activeLegacyBindings());
+ assertEquals(0, count("tag_relation_meta"));
+ }
+
+ /** Does not migrate already deleted legacy bindings. */
+ @TestTemplate
+ public void testDeletedBindingsAreIgnored() throws Exception {
+ insertBinding(2, Long.MAX_VALUE, Long.MAX_VALUE, "TABLE");
+ try (Statement statement = connection.createStatement()) {
+ statement.executeUpdate("UPDATE policy_relation_meta SET deleted_at = 1 WHERE id = 2");
+ }
+ connection.commit();
+ assertEquals(1, new PolicyBindingMigration(connection, entityStore).migrate());
+ assertEquals(1, count("tag_relation_meta"));
+ }
+
+ /** Column bindings use the same tag-supported object types as ordinary assignments. */
+ @TestTemplate
+ public void testMigratesColumnBinding() throws Exception {
+ createAndInsertSchema("migration_test", catalog.name(), "schema");
+ ColumnEntity column =
+ ColumnEntity.builder()
+ .withId(42L)
+ .withName("column")
+ .withPosition(0)
+ .withDataType(Types.IntegerType.get())
+ .withNullable(true)
+ .withAutoIncrement(false)
+ .withAuditInfo(AUDIT_INFO)
+ .build();
+ TableEntity table =
+ TableEntity.builder()
+ .withId(43L)
+ .withName("table")
+ .withNamespace(Namespace.of("migration_test", catalog.name(), "schema"))
+ .withColumns(Collections.singletonList(column))
+ .withAuditInfo(AUDIT_INFO)
+ .build();
+ entityStore.put(table, false);
+ insertBinding(2, policy.id(), column.id(), "COLUMN");
+ connection.commit();
+ assertEquals(2, new PolicyBindingMigration(connection, entityStore).migrate());
+ assertEquals(2, activeCount("tag_relation_meta"));
+ }
+
+ /** A canonical tag without its policy relation must never replace an active legacy binding. */
+ @TestTemplate
+ public void testMissingPolicyRelationRollsBackObjectAssignment() throws Exception {
+ entityStore.put(HiddenPolicyTag.create(policy, 100L), false);
+ connection.commit();
+ SQLException failure =
+ assertThrows(
+ SQLException.class,
+ () -> new PolicyBindingMigration(connection, entityStore).migrate());
+ assertTrue(failure.getCause().getMessage().contains("Replacement policy relation is missing"));
+ assertEquals(1, activeLegacyBindings());
+ assertEquals(1, activeCount("tag_meta"));
+ assertEquals(0, count("tag_relation_meta"));
+ assertEquals(0, count("policy_tag_relation_meta"));
+ }
+
+ /** The replacement must resolve only to the original policy with a presence selector. */
+ @TestTemplate
+ public void testWrongPolicyRelationRollsBackObjectAssignment() throws Exception {
+ new PolicyBindingMigration(connection, entityStore).migrate();
+ try (Statement statement = connection.createStatement()) {
+ statement.executeUpdate("UPDATE policy_relation_meta SET deleted_at = 0");
+ statement.executeUpdate("UPDATE policy_tag_relation_meta SET policy_id = 999");
+ statement.executeUpdate("DELETE FROM tag_relation_meta");
+ }
+ connection.commit();
+ assertThrows(
+ SQLException.class, () -> new PolicyBindingMigration(connection, entityStore).migrate());
+ assertEquals(1, activeLegacyBindings());
+ assertEquals(0, count("tag_relation_meta"));
+ }
+
+ /** A verification failure rolls back new tags and assignments, and retry succeeds. */
+ @TestTemplate
+ public void testVerificationRollbackAndRetry() throws Exception {
+ Connection failing = spy(connection);
+ doAnswer(
+ invocation -> {
+ throw new SQLException("Injected replacement verification failure");
+ })
+ .when(failing)
+ .prepareStatement(startsWith("SELECT COUNT(*) FROM policy_relation_meta l"));
+ assertThrows(
+ SQLException.class, () -> new PolicyBindingMigration(failing, entityStore).migrate());
+ assertEquals(1, activeLegacyBindings());
+ assertEquals(0, count("tag_meta"));
+ assertEquals(0, count("tag_relation_meta"));
+ assertEquals(1, new PolicyBindingMigration(connection, entityStore).migrate());
+ assertEquals(1, activeCount("tag_relation_meta"));
+ assertEquals(0, activeLegacyBindings());
+ }
+
+ /** User tag names outside the canonical hidden namespace must not block migration. */
+ @TestTemplate
+ public void testUnrelatedReservedTagsDoNotBlockMigration() throws Exception {
+ entityStore.put(
+ TagEntity.builder()
+ .withId(100L)
+ .withName("reserved_legacy")
+ .withNamespace(policy.namespace())
+ .withAuditInfo(AUDIT_INFO)
+ .build(),
+ false);
+ connection.commit();
+ assertEquals(1, new PolicyBindingMigration(connection, entityStore).migrate());
+ assertEquals(2, activeCount("tag_meta"));
+ }
+
+ private void removeAutomaticallyCreatedTag(long policyId) throws SQLException {
+ // This fixture represents a policy persisted by a pre-hidden-tag server.
+ try (PreparedStatement relation =
+ connection.prepareStatement(
+ "DELETE FROM policy_tag_relation_meta WHERE policy_id = ?");
+ PreparedStatement tag =
+ connection.prepareStatement("DELETE FROM tag_meta WHERE tag_name = ?")) {
+ relation.setLong(1, policyId);
+ relation.executeUpdate();
+ tag.setString(1, HiddenPolicyTag.name(policyId));
+ tag.executeUpdate();
+ }
+ }
+
+ private void insertBinding(long id, long policyId, long objectId, String type)
+ throws SQLException {
+ try (PreparedStatement statement =
+ connection.prepareStatement(
+ "INSERT INTO policy_relation_meta (id, policy_id, metadata_object_id, metadata_object_type, audit_info)"
+ + " VALUES (?, ?, ?, ?, '{}')")) {
+ statement.setLong(1, id);
+ statement.setLong(2, policyId);
+ statement.setLong(3, objectId);
+ statement.setString(4, type);
+ statement.executeUpdate();
+ }
+ }
+
+ private long activeLegacyBindings() throws SQLException {
+ return activeCount("policy_relation_meta");
+ }
+
+ private long activeCount(String table) throws SQLException {
+ return queryCount("SELECT COUNT(*) FROM " + table + " WHERE deleted_at = 0");
+ }
+
+ private long count(String table) throws SQLException {
+ return queryCount("SELECT COUNT(*) FROM " + table);
+ }
+
+ private long queryCount(String sql) throws SQLException {
+ try (Statement statement = connection.createStatement();
+ ResultSet rows = statement.executeQuery(sql)) {
+ rows.next();
+ return rows.getLong(1);
+ }
+ }
+}
diff --git a/core/src/test/java/org/apache/gravitino/policy/TestPolicyBindingMigrationTool.java b/core/src/test/java/org/apache/gravitino/policy/TestPolicyBindingMigrationTool.java
new file mode 100644
index 0000000000..b5cfd20fcf
--- /dev/null
+++ b/core/src/test/java/org/apache/gravitino/policy/TestPolicyBindingMigrationTool.java
@@ -0,0 +1,137 @@
+/*
+ * 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.policy;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.io.Reader;
+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.Statement;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.h2.tools.RunScript;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+/** Exercises the distribution launcher, configuration loading, and existing-file protection. */
+public class TestPolicyBindingMigrationTool {
+
+ @TempDir private Path directory;
+
+ /** Runs the launcher against an existing metadata database and checks help and retry. */
+ @Test
+ public void testDistributionLauncher() throws Exception {
+ Path repository = Paths.get(System.getProperty("gravitino.repositoryRoot"));
+ Path bin = Files.createDirectories(directory.resolve("bin"));
+ Files.copy(repository.resolve("bin/common.sh.template"), bin.resolve("common.sh"));
+ Files.copy(
+ repository.resolve("bin/migrate-policy-bindings.sh.template"),
+ bin.resolve("migrate-policy-bindings.sh"));
+ Path conf = Files.createDirectories(directory.resolve("conf"));
+ Files.writeString(
+ conf.resolve("gravitino-env.sh"),
+ "export GRAVITINO_VERSION=test\n",
+ StandardCharsets.UTF_8);
+ String url = "jdbc:h2:file:" + directory.resolve("db") + ";MODE=MYSQL;AUTO_SERVER=FALSE";
+ Files.writeString(
+ conf.resolve("gravitino.conf"),
+ "gravitino.entity.store.relational.jdbcUrl="
+ + url
+ + "\n"
+ + "gravitino.entity.store.relational.jdbcDriver=org.h2.Driver\n"
+ + "gravitino.entity.store.relational.jdbcUser=test\n"
+ + "gravitino.entity.store.relational.jdbcPassword=test\n",
+ StandardCharsets.UTF_8);
+ assertLaunchSucceeds(bin, "--help");
+ assertTrue(Files.readString(directory.resolve("launcher.log")).contains("Usage:"));
+ assertFalse(Files.exists(directory.resolve("db.mv.db")));
+ assertTrue(launch(bin) != 0);
+ assertFalse(Files.exists(directory.resolve("db.mv.db")));
+ try (Connection connection = DriverManager.getConnection(url, "test", "test");
+ Reader schema =
+ Files.newBufferedReader(
+ repository.resolve("scripts/h2/schema-2.0.0-h2.sql"), StandardCharsets.UTF_8)) {
+ RunScript.execute(connection, schema);
+ try (Statement statement = connection.createStatement()) {
+ statement.execute(
+ "CREATE TABLE policy_relation_meta (id BIGINT PRIMARY KEY, policy_id BIGINT NOT NULL,"
+ + " metadata_object_id BIGINT NOT NULL, metadata_object_type VARCHAR(64) NOT NULL,"
+ + " audit_info TEXT NOT NULL, current_version INT NOT NULL DEFAULT 1,"
+ + " last_version INT NOT NULL DEFAULT 1, deleted_at BIGINT NOT NULL DEFAULT 0)");
+ }
+ }
+ assertLaunchSucceeds(bin);
+ assertLaunchSucceeds(bin);
+ assertTrue(launch(bin, "--unknown") != 0);
+ assertEquals(0, launch(bin, (Path) null), Files.readString(directory.resolve("launcher.log")));
+ Path customConf = Files.createDirectories(directory.resolve("custom-conf"));
+ Files.copy(conf.resolve("gravitino-env.sh"), customConf.resolve("gravitino-env.sh"));
+ Files.move(conf.resolve("gravitino.conf"), customConf.resolve("gravitino.conf"));
+ assertEquals(0, launch(bin, customConf), Files.readString(directory.resolve("launcher.log")));
+ Files.delete(customConf.resolve("gravitino.conf"));
+ assertTrue(launch(bin, customConf) != 0);
+ assertTrue(
+ Files.readString(directory.resolve("launcher.log"))
+ .contains("Config file " + customConf.resolve("gravitino.conf") + " not found"));
+ }
+
+ private void assertLaunchSucceeds(Path bin, String... args) throws Exception {
+ int exitCode = launch(bin, args);
+ assertEquals(0, exitCode, Files.readString(directory.resolve("launcher.log")));
+ }
+
+ private int launch(Path bin, String... args) throws Exception {
+ return launch(bin, directory.resolve("conf"), args);
+ }
+
+ private int launch(Path bin, @Nullable Path confDirectory, String... args) throws Exception {
+ List<String> command = new ArrayList<>();
+ command.add("bash");
+ command.add(bin.resolve("migrate-policy-bindings.sh").toString());
+ command.addAll(Arrays.asList(args));
+ ProcessBuilder builder = new ProcessBuilder(command);
+ builder.environment().put("GRAVITINO_HOME", directory.toString());
+ if (confDirectory == null) {
+ builder.environment().remove("GRAVITINO_CONF_DIR");
+ } else {
+ builder.environment().put("GRAVITINO_CONF_DIR", confDirectory.toString());
+ }
+ builder.directory(Files.createDirectories(directory.resolve("unrelated-cwd")).toFile());
+ builder.environment().put("GRAVITINO_CLASSPATH", System.getProperty("java.class.path"));
+ builder.environment().put("JAVA_HOME", System.getProperty("java.home"));
+ Path output = directory.resolve("launcher.log");
+ builder.redirectErrorStream(true).redirectOutput(output.toFile());
+ Process process = builder.start();
+ if (!process.waitFor(45, TimeUnit.SECONDS)) {
+ process.destroyForcibly();
+ throw new AssertionError("Migration launcher timed out: " + Files.readString(output));
+ }
+ return process.exitValue();
+ }
+}
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/database/TestH2Database.java b/core/src/test/java/org/apache/gravitino/storage/relational/database/TestH2Database.java
index dae67bf58d..ba7e738758 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/database/TestH2Database.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/database/TestH2Database.java
@@ -26,6 +26,21 @@ import org.junit.jupiter.api.Test;
public class TestH2Database {
+ /** Resolves an existing file without creating or upgrading a database. */
+ @Test
+ public void testOfflineConnectionUrl() {
+ Config config = new Config(false) {};
+ config.set(Configs.ENTITY_RELATIONAL_JDBC_BACKEND_URL, "jdbc:h2");
+ config.set(Configs.ENTITY_RELATIONAL_JDBC_BACKEND_PATH, "/tmp/migration-db");
+ Assertions.assertEquals(
+ "jdbc:h2:file:/tmp/migration-db;DB_CLOSE_DELAY=-1;MODE=MYSQL;AUTO_SERVER=TRUE",
+ H2Database.getConnectionUrl(config));
+ config.set(
+ Configs.ENTITY_RELATIONAL_JDBC_BACKEND_URL, "jdbc:h2:file:/tmp/explicit-db;MODE=MYSQL");
+ Assertions.assertTrue(
+ H2Database.getConnectionUrl(config).startsWith("jdbc:h2:file:/tmp/explicit-db;"));
+ }
+
@Test
public void testGetStoragePathWithRelativePathWhenGravitinoHomeMissing() throws Exception {
String javaBin = System.getProperty("java.home") + "/bin/java";
diff --git a/core/src/test/java/org/apache/gravitino/tag/TestTagManager.java b/core/src/test/java/org/apache/gravitino/tag/TestTagManager.java
index 94790a2f64..f12b9da0d1 100644
--- a/core/src/test/java/org/apache/gravitino/tag/TestTagManager.java
+++ b/core/src/test/java/org/apache/gravitino/tag/TestTagManager.java
@@ -51,6 +51,9 @@ import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import java.io.File;
import java.io.IOException;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.Statement;
import java.time.Instant;
import java.util.Arrays;
import java.util.List;
@@ -133,8 +136,13 @@ import org.apache.gravitino.meta.TopicEntity;
import org.apache.gravitino.meta.ViewEntity;
import org.apache.gravitino.metalake.MetalakeDispatcher;
import org.apache.gravitino.policy.AllValuesSelector;
+import org.apache.gravitino.policy.HiddenPolicyTag;
+import org.apache.gravitino.policy.ObjectPolicyResolver;
import org.apache.gravitino.policy.Policy;
+import org.apache.gravitino.policy.PolicyBindingMigration;
+import org.apache.gravitino.policy.PolicyChange;
import org.apache.gravitino.policy.PolicyContents;
+import org.apache.gravitino.policy.PolicyManager;
import org.apache.gravitino.policy.TagValueSelector;
import org.apache.gravitino.rel.Column;
import org.apache.gravitino.rel.Representation;
@@ -144,6 +152,10 @@ import org.apache.gravitino.semantic.Dataset;
import org.apache.gravitino.semantic.SemanticModelDefinition;
import org.apache.gravitino.storage.IdGenerator;
import org.apache.gravitino.storage.RandomIdGenerator;
+import org.apache.gravitino.storage.relational.JDBCBackend;
+import org.apache.gravitino.storage.relational.RelationalEntityStore;
+import org.apache.gravitino.storage.relational.session.SqlSessions;
+import org.apache.gravitino.storage.relational.utils.SessionUtils;
import org.apache.gravitino.utils.NameIdentifierUtil;
import org.apache.gravitino.utils.RaceTestUtils;
import org.junit.jupiter.api.AfterAll;
@@ -1779,6 +1791,123 @@ public class TestTagManager {
}
}
+ /** Verifies migrated bindings preserve inheritance and coexist with visible business tags. */
+ @Test
+ public void testMigratedHiddenPolicyTags() throws Exception {
+ AuditInfo audit = AuditInfo.builder().withCreator("test").withCreateTime(Instant.now()).build();
+ PolicyEntity policy =
+ PolicyEntity.builder()
+ .withId(idGenerator.nextId())
+ .withName("hidden_policy")
+ .withNamespace(Namespace.of(METALAKE))
+ .withPolicyType(Policy.BuiltInType.CUSTOM)
+ .withEnabled(true)
+ .withContent(
+ PolicyContents.custom(
+ ImmutableMap.of("rule", "value"),
+ ImmutableSet.of(MetadataObject.Type.CATALOG, MetadataObject.Type.TABLE),
+ null))
+ .withAuditInfo(audit)
+ .build();
+ entityStore.put(policy, false);
+ CatalogEntity catalog =
+ entityStore.get(
+ NameIdentifier.of(METALAKE, CATALOG), Entity.EntityType.CATALOG, CatalogEntity.class);
+ TableEntity table =
+ entityStore.get(
+ NameIdentifier.of(METALAKE, CATALOG, SCHEMA, TABLE),
+ Entity.EntityType.TABLE,
+ TableEntity.class);
+ MetadataObject catalogObject = MetadataObjects.parse(CATALOG, MetadataObject.Type.CATALOG);
+ MetadataObject tableObject =
+ MetadataObjects.parse(CATALOG + "." + SCHEMA + "." + TABLE, MetadataObject.Type.TABLE);
+ MetadataObject columnObject =
+ MetadataObjects.parse(tableObject.fullName() + "." + COLUMN, MetadataObject.Type.COLUMN);
+ String hidden = HiddenPolicyTag.name(policy.id());
+ PolicyManager policies = new PolicyManager(idGenerator, entityStore);
+ EntityStore migrationStore =
+ RelationalEntityStore.forOfflineMigration(new JDBCBackend(), new Config(false) {});
+ SessionUtils.beginTransaction();
+ Connection connection = SqlSessions.currentConnection();
+ try {
+ try (Statement statement = connection.createStatement()) {
+ statement.execute(
+ "CREATE TABLE policy_relation_meta (id BIGINT PRIMARY KEY, policy_id BIGINT NOT NULL,"
+ + " metadata_object_id BIGINT NOT NULL, metadata_object_type VARCHAR(64) NOT NULL,"
+ + " audit_info TEXT NOT NULL, current_version INT NOT NULL DEFAULT 1,"
+ + " last_version INT NOT NULL DEFAULT 1, deleted_at BIGINT NOT NULL DEFAULT 0)");
+ }
+ try {
+ try (PreparedStatement statement =
+ connection.prepareStatement(
+ "INSERT INTO policy_relation_meta (id, policy_id, metadata_object_id, metadata_object_type, audit_info)"
+ + " VALUES (?, ?, ?, ?, '{}')")) {
+ statement.setLong(1, 1);
+ statement.setLong(2, policy.id());
+ statement.setLong(3, catalog.id());
+ statement.setString(4, "CATALOG");
+ statement.executeUpdate();
+ }
+ connection.commit();
+ new PolicyBindingMigration(connection, migrationStore).migrate();
+ ObjectPolicyResolver resolver = new ObjectPolicyResolver(entityStore);
+ Assertions.assertFalse(
+ resolver.resolve(METALAKE, catalogObject)[0].inherited().orElseThrow());
+ Assertions.assertTrue(resolver.resolve(METALAKE, tableObject)[0].inherited().orElseThrow());
+ Assertions.assertTrue(
+ resolver.resolve(METALAKE, columnObject)[0].inherited().orElseThrow());
+ // Managers expose internal tags; REST Operations own visibility and parameter checks.
+ Assertions.assertEquals(hidden, tagManager.getTag(METALAKE, hidden).name());
+ Assertions.assertEquals(1, tagManager.listTags(METALAKE).length);
+ Assertions.assertEquals(
+ 1, tagManager.listTagsForMetadataObject(METALAKE, catalogObject).length);
+ Assertions.assertEquals(
+ 1, policies.listTagAssociationsForPolicy(METALAKE, policy.name()).length);
+ tagManager.createTag(METALAKE, "visible", null, null);
+ tagManager.addPolicyForTag(METALAKE, "visible", policy.name(), AllValuesSelector.get());
+ Assertions.assertEquals(
+ ImmutableSet.of(hidden, "visible"),
+ ImmutableSet.copyOf(
+ tagManager.associateTagsForMetadataObject(
+ METALAKE, catalogObject, new String[] {"visible"}, null)));
+ Assertions.assertEquals(1, resolver.resolve(METALAKE, tableObject).length);
+ policies.disablePolicy(METALAKE, policy.name());
+ Assertions.assertEquals(0, resolver.resolve(METALAKE, tableObject).length);
+ policies.enablePolicy(METALAKE, policy.name());
+ policies.alterPolicy(METALAKE, policy.name(), PolicyChange.rename("renamed_hidden_policy"));
+ Assertions.assertEquals(
+ "renamed_hidden_policy", resolver.resolve(METALAKE, tableObject)[0].name());
+ // A direct assignment of the same hidden tag must preserve a direct match on the child.
+ try (PreparedStatement statement =
+ connection.prepareStatement(
+ "INSERT INTO policy_relation_meta (id, policy_id, metadata_object_id, metadata_object_type, audit_info)"
+ + " VALUES (2, ?, ?, 'TABLE', '{}')")) {
+ statement.setLong(1, policy.id());
+ statement.setLong(2, table.id());
+ statement.executeUpdate();
+ }
+ connection.commit();
+ new PolicyBindingMigration(connection, migrationStore).migrate();
+ Assertions.assertFalse(
+ resolver.resolve(METALAKE, tableObject)[0].inherited().orElseThrow());
+ } finally {
+ connection.rollback();
+ try (Statement statement = connection.createStatement()) {
+ statement.execute("DROP TABLE policy_relation_meta");
+ }
+ connection.commit();
+ entityStore.delete(
+ NameIdentifierUtil.ofPolicy(METALAKE, policy.name()), Entity.EntityType.POLICY);
+ entityStore.delete(
+ NameIdentifierUtil.ofPolicy(METALAKE, "renamed_hidden_policy"),
+ Entity.EntityType.POLICY);
+ connection.commit();
+ }
+ } finally {
+ SessionUtils.rollbackTransaction();
+ }
+ }
+
@Test
public void testPolicyAssociationsForTag() throws IOException {
String tagName = "policy_tag";
diff --git a/docs/how-to-upgrade.md b/docs/how-to-upgrade.md
index 8de22b1977..358ff5c32e 100644
--- a/docs/how-to-upgrade.md
+++ b/docs/how-to-upgrade.md
@@ -166,6 +166,11 @@ restarted upgrade skips the steps that already completed. The PostgreSQL and H2
1.3.0-to-2.0.0 upgrade scripts are retryable as well. Unexpected schema differences, such
as a missing MySQL index during a rename, require manual schema repair before retrying.
+For existing direct policy bindings, run `bin/migrate-policy-bindings.sh` while all servers are
+stopped and before starting the new server. This is a data conversion using existing tables;
+it adds no schema or index changes. See
+[Offline policy binding migration](./migration-guide.md#offline-policy-binding-migration).
+
### Step 6: Verify the Upgrade
The final step of the upgrade process is validating your freshly
diff --git a/docs/migration-guide.md b/docs/migration-guide.md
index c66233a377..c30d4a257e 100644
--- a/docs/migration-guide.md
+++ b/docs/migration-guide.md
@@ -30,15 +30,14 @@ existing deployments. For database backup, schema scripts, and rollback commands
### Policies are selected through tags
-- Direct policy associations with metadata objects are no longer read or written. The upgrade
- does not convert existing direct associations. Before upgrading, export each policy's directly
- associated objects from `GET /api/metalakes/{metalake}/policies/{policy}/objects`. Save the
- policy name, object type, and full name, including direct associations on ancestor objects.
- Back up the metadata database before the schema upgrade.
-- To preserve the old scope, create one dedicated tag per policy, associate the policy with that
- tag using the `ALL_VALUES` selector, and assign the tag to every object that had a direct
- policy association. A tag on a catalog or schema reaches its descendants. If a policy was
- directly associated with both a parent and a child, assign the tag to both.
+- Direct policy associations with metadata objects are no longer read or written at runtime.
+ Use the offline migration command below to convert existing bindings to `object → hidden tag → policy`.
+ It uses the existing tables and requires no additional schema changes.
+- The tool assigns each policy's hidden tag to the objects with historical direct bindings.
+ It preserves assignments on both parents and children, so descendant inheritance and direct-match
+ flags remain unchanged. Hidden tag names use `gravitino_hidden_{policyId}` and survive policy renames.
+- Hidden tags have no assignment values and select the policy by tag presence. REST APIs hide
+ these tags and prevent users from modifying them. Use visible business tags for future scope changes.
- Object policy lookup at `GET /api/metalakes/{metalake}/objects/{type}/{fullName}/policies`
remains available, but now returns enabled policies matching the object's effective tags.
A policy matching through multiple tags appears once. With `details=true`, `inherited` is
@@ -82,17 +81,17 @@ policy-to-tag association changes.
inherited values, and a nearer ancestor overrides a farther one. For example,
`data_domain=risk` on a schema overrides `data_domain=finance` on its catalog for every table
in that schema, so a `TAG_VALUE("finance")` association no longer matches those tables. A
- dedicated migration tag with `ALL_VALUES` avoids this interaction.
+ hidden migration tag matching presence avoids this interaction.
See [Manage Tags](./manage-tags-in-gravitino.md#create-a-tag-with-a-value-constraint)
for tag creation and value assignment examples.
### Authorization, UI, and consumers
-- Creating a migration tag requires `CREATE_TAG` on the metalake or ownership. Associating
- a policy with a tag requires access to both: `APPLY_POLICY` on the policy and `APPLY_TAG`
- on the tag, or the corresponding ownership. Assigning a tag also requires access to the
- target metadata object.
+- The offline tool uses the metadata database credentials from the server configuration.
+ Run it only while every server using that database is stopped. It does not start the server,
+ run schema upgrades, or expose a direct-binding REST or client API. Normal policy-to-tag
+ operations retain their existing authorization requirements.
- Read-only inspection requires `VIEW_TAG` or `APPLY_TAG` for tags and `VIEW_POLICY` or
`APPLY_POLICY` for policies. Object policy results include only policies visible to the caller;
use an account with the same policy visibility when comparing results before and after migration.
@@ -101,25 +100,51 @@ for tag creation and value assignment examples.
- Update TMS and other policy consumers to read the resolved object policy list. Confirm the
expected policy appears on representative tables before resuming maintenance jobs.
-### Migration checklist
-
-1. On the old runtime, back up the database. Export direct policy associations for **each
- metalake**, inventory disabled policies, and record policy results on representative
- descendants. Re-enable disabled policies that consumers must continue to receive. The old
- `/policies/{policy}/objects` endpoint is unavailable after the upgrade.
-2. Map each direct relation to a tag assignment. A dedicated tag per policy with
- `ALL_VALUES` preserves the original scope; review existing tag values and child overrides
- before choosing `TAG_VALUE`.
-3. Stop direct policy writes and pause consumers that require complete policy results. Upgrade
- the server and schema using [Upgrade Gravitino](./how-to-upgrade.md).
-4. Create the tags, add policy-to-tag associations, and assign tags to every object from the
- exported direct-relation inventory.
-5. Compare resolved policy names and `inherited` values for every inventoried object and
- representative descendants. Check enabled and disabled policies, direct child assignments,
- and value selectors. Use the same policy visibility for before and after comparisons.
-6. Resume consumers after verification. Keep the inventory and database backup until the
- deployment is stable. If rollback is needed, stop the new server and follow the
- [database rollback procedure](./how-to-upgrade.md#rollback-if-upgrade-fails).
-
-There is no automatic converter or verification command for direct policy relations. Do not
-edit relation tables directly as part of this migration.
+### Offline policy binding migration
+
+The distribution includes `bin/migrate-policy-bindings.sh`. It reads `gravitino.conf` from
+`GRAVITINO_CONF_DIR` (default: `$GRAVITINO_HOME/conf`) and connects to the configured metadata
+store. H2, MySQL, and PostgreSQL are supported; use the same JDBC driver as the server.
+
+1. Record representative policy results, stop all servers sharing the metadata database, pause
+ policy consumers, and back up the database.
+2. Run the command from the new distribution:
+
+ ```shell
+ bin/migrate-policy-bindings.sh
+ ```
+
+ Each policy migrates in one transaction: create or reuse its hidden tag, copy its direct object
+ assignments with their audit information, verify the replacements, then soft-delete the legacy
+ rows. A missing or incorrect policy-to-tag relation fails verification and leaves the legacy
+ bindings active. No tables, columns, or indexes are added.
+ Bindings whose policy, metalake, or target object is missing or deleted are logged and left
+ active. Other valid bindings still migrate. The final summary reports migrated bindings,
+ skipped owners and bindings, missing-object bindings, failed policies, and unprocessed policies.
+ Skipped bindings alone do not cause a nonzero exit code. A final WARN reports their counts:
+ the new server reads tag-based associations and does not read these retained legacy rows.
+ Review the logged IDs before completing the upgrade; a successful exit does not mean all
+ legacy bindings were migrated.
+3. If a policy fails, its changes roll back and other policies are still attempted. Any failed
+ policy makes the command exit unsuccessfully after printing the summary. If rollback itself
+ fails, processing stops and the summary reports how many policies were not attempted.
+ Keep all servers and policy consumers stopped on failure or interruption. Fix the reported cause
+ and rerun the same command: completed policies remain committed, while unfinished policies are
+ retried from their active legacy rows. A partially migrated
+ database is only an offline intermediate state, not a deployment to start serving requests.
+ Restore the backup only when abandoning or rolling back the upgrade.
+ A `Hidden tag name collision` error identifies the policy and tag and rolls back that policy. If an
+ existing user tag occupies `gravitino_hidden_{policyId}`, restore the pre-upgrade backup, run
+ the old server version, and rename that user tag to a name outside `gravitino_hidden_` through
+ the tag API. Stop the old servers, take a fresh backup, and repeat the upgrade and migration.
+ Renaming preserves the tag's assignments. If the conflicting tag is a damaged server-managed
+ tag, restore a known-good backup and investigate the corruption before retrying. Do not delete
+ legacy bindings or overwrite the conflicting tag to force migration to finish.
+4. Start the server and compare resolved policy names and `inherited` values on representative
+ objects and descendants. Check disabled policies and existing business tag associations before
+ resuming consumers.
+
+Migrated policies retain their normal lifecycle: disabling a policy suspends its effect, and
+removing it cleans up its hidden tag and assignments. Keep the database backup until the deployment
+is stable. For rollback, stop the new server and restore the complete pre-upgrade backup using
+[Upgrade Gravitino](./how-to-upgrade.md#rollback-if-upgrade-fails).
diff --git a/docs/policies.md b/docs/policies.md
index 0f940d2f2d..759fb66cdb 100644
--- a/docs/policies.md
+++ b/docs/policies.md
@@ -411,6 +411,8 @@ create a missing hidden tag.
Do not run old and new server versions together after internal policy tags have been created:
old servers do not recognize the internal name prefix and can expose or modify these tags.
+Historical direct object policy associations must be converted with the offline migration tool
+before starting the new server. See [Migration Guide](./migration-guide.md#offline-policy-binding-migration).
To add or remove an association, a user must own the metalake or have the required access to both
the tag and the policy (`APPLY_TAG` and `APPLY_POLICY`, or ownership of each). Object policy