Skip to content

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

[#12176] fix(policy): remove deprecated direct object policy APIs (#13355)

roryqi8ffb60f70080
diff --git a/api/src/main/java/org/apache/gravitino/policy/Policy.java b/api/src/main/java/org/apache/gravitino/policy/Policy.java
index 7b27b01fcd..d7173d233f 100644
--- a/api/src/main/java/org/apache/gravitino/policy/Policy.java
+++ b/api/src/main/java/org/apache/gravitino/policy/Policy.java
@@ -22,7 +22,6 @@ import com.google.common.base.Preconditions;
import java.util.Optional;
import org.apache.commons.lang3.StringUtils;
import org.apache.gravitino.Auditable;
-import org.apache.gravitino.MetadataObject;
import org.apache.gravitino.annotation.Evolving;
/**
@@ -148,28 +147,4 @@ public interface Policy extends Auditable {
* the policy is not associated with any object.
*/
Optional<Boolean> inherited();
-
- /**
- * @return The associated objects of the policy.
- */
- default AssociatedObjects associatedObjects() {
- throw new UnsupportedOperationException("The associatedObjects method is not supported.");
- }
-
- /** The interface of the associated objects of the policy. */
- interface AssociatedObjects {
-
- /**
- * @return The number of objects that are associated with this policy
- */
- default int count() {
- MetadataObject[] objects = objects();
- return objects == null ? 0 : objects.length;
- }
-
- /**
- * @return The list of objects that are associated with this policy.
- */
- MetadataObject[] objects();
- }
}
diff --git a/api/src/main/java/org/apache/gravitino/policy/SupportsPolicies.java b/api/src/main/java/org/apache/gravitino/policy/SupportsPolicies.java
index 21af7de6be..af0ed772c6 100644
--- a/api/src/main/java/org/apache/gravitino/policy/SupportsPolicies.java
+++ b/api/src/main/java/org/apache/gravitino/policy/SupportsPolicies.java
@@ -19,8 +19,6 @@
package org.apache.gravitino.policy;
import org.apache.gravitino.annotation.Evolving;
-import org.apache.gravitino.exceptions.NoSuchPolicyException;
-import org.apache.gravitino.exceptions.PolicyAlreadyAssociatedException;
/**
* Interface for policy operations on a metadata object.
@@ -39,33 +37,4 @@ public interface SupportsPolicies {
* @return The policies that apply to the metadata object.
*/
Policy[] listPolicyInfos();
-
- /**
- * Get an applicable policy by its name for the metadata object.
- *
- * @param name The name of the policy.
- * @return The policy.
- * @throws NoSuchPolicyException If the policy does not apply to the object.
- */
- Policy getPolicy(String name) throws NoSuchPolicyException;
-
- /**
- * Associate policies to the specific object. The policiesToAdd will be applied to the object and
- * the policiesToRemove will be removed from the object. Note that:
- *
- * <ol>
- * <li>Adding or removing policies that are not existed will be ignored.
- * <li>If the same name policy is in both policiesToAdd and policiesToRemove, it will be
- * ignored.
- * <li>If the policy is already applied to the object, it will throw {@link
- * PolicyAlreadyAssociatedException}
- * </ol>
- *
- * @param policiesToAdd The policies to be added to the object.
- * @param policiesToRemove The policies to remove.
- * @return The list of applied policies.
- * @throws PolicyAlreadyAssociatedException If the policy is already applied to the object.
- */
- String[] associatePolicies(String[] policiesToAdd, String[] policiesToRemove)
- throws PolicyAlreadyAssociatedException;
}
diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/BaseSchemaCatalog.java b/clients/client-java/src/main/java/org/apache/gravitino/client/BaseSchemaCatalog.java
index 56c5a5b0f5..ca4b17ce0c 100644
--- a/clients/client-java/src/main/java/org/apache/gravitino/client/BaseSchemaCatalog.java
+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/BaseSchemaCatalog.java
@@ -45,10 +45,8 @@ import org.apache.gravitino.dto.responses.SchemaResponse;
import org.apache.gravitino.dto.secret.SecretBindingDTO;
import org.apache.gravitino.dto.secret.SecretReferenceDTO;
import org.apache.gravitino.exceptions.NoSuchCatalogException;
-import org.apache.gravitino.exceptions.NoSuchPolicyException;
import org.apache.gravitino.exceptions.NoSuchSchemaException;
import org.apache.gravitino.exceptions.NonEmptySchemaException;
-import org.apache.gravitino.exceptions.PolicyAlreadyAssociatedException;
import org.apache.gravitino.exceptions.SchemaAlreadyExistsException;
import org.apache.gravitino.function.Function;
import org.apache.gravitino.function.FunctionCatalog;
@@ -343,17 +341,6 @@ abstract class BaseSchemaCatalog extends CatalogDTO
return objectPolicyOperations.listPolicyInfos();
}
- @Override
- public Policy getPolicy(String name) throws NoSuchPolicyException {
- return objectPolicyOperations.getPolicy(name);
- }
-
- @Override
- public String[] associatePolicies(String[] policiesToAdd, String[] policiesToRemove)
- throws PolicyAlreadyAssociatedException {
- return objectPolicyOperations.associatePolicies(policiesToAdd, policiesToRemove);
- }
-
@Override
public String[] listBindingRoleNames() {
return objectRoleOperations.listBindingRoleNames();
diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/GenericFileset.java b/clients/client-java/src/main/java/org/apache/gravitino/client/GenericFileset.java
index 065445ada3..844621573d 100644
--- a/clients/client-java/src/main/java/org/apache/gravitino/client/GenericFileset.java
+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/GenericFileset.java
@@ -30,9 +30,7 @@ import org.apache.gravitino.authorization.SupportsRoles;
import org.apache.gravitino.credential.Credential;
import org.apache.gravitino.credential.SupportsCredentials;
import org.apache.gravitino.dto.file.FilesetDTO;
-import org.apache.gravitino.exceptions.NoSuchPolicyException;
import org.apache.gravitino.exceptions.NoSuchTagException;
-import org.apache.gravitino.exceptions.PolicyAlreadyAssociatedException;
import org.apache.gravitino.file.Fileset;
import org.apache.gravitino.policy.Policy;
import org.apache.gravitino.policy.SupportsPolicies;
@@ -166,17 +164,6 @@ class GenericFileset
return objectPolicyOperations.listPolicyInfos();
}
- @Override
- public Policy getPolicy(String name) throws NoSuchPolicyException {
- return objectPolicyOperations.getPolicy(name);
- }
-
- @Override
- public String[] associatePolicies(String[] policiesToAdd, String[] policiesToRemove)
- throws PolicyAlreadyAssociatedException {
- return objectPolicyOperations.associatePolicies(policiesToAdd, policiesToRemove);
- }
-
@Override
public String[] listBindingRoleNames() {
return objectRoleOperations.listBindingRoleNames();
diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/GenericModel.java b/clients/client-java/src/main/java/org/apache/gravitino/client/GenericModel.java
index ca74615c43..f12177af4d 100644
--- a/clients/client-java/src/main/java/org/apache/gravitino/client/GenericModel.java
+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/GenericModel.java
@@ -27,9 +27,7 @@ import org.apache.gravitino.MetadataObjects;
import org.apache.gravitino.Namespace;
import org.apache.gravitino.authorization.SupportsRoles;
import org.apache.gravitino.dto.model.ModelDTO;
-import org.apache.gravitino.exceptions.NoSuchPolicyException;
import org.apache.gravitino.exceptions.NoSuchTagException;
-import org.apache.gravitino.exceptions.PolicyAlreadyAssociatedException;
import org.apache.gravitino.exceptions.TagAlreadyAssociatedException;
import org.apache.gravitino.model.Model;
import org.apache.gravitino.policy.Policy;
@@ -164,15 +162,4 @@ class GenericModel implements Model, SupportsTags, SupportsPolicies, SupportsSec
public Policy[] listPolicyInfos() {
return objectPolicyOperations.listPolicyInfos();
}
-
- @Override
- public Policy getPolicy(String name) throws NoSuchPolicyException {
- return objectPolicyOperations.getPolicy(name);
- }
-
- @Override
- public String[] associatePolicies(String[] policiesToAdd, String[] policiesToRemove)
- throws PolicyAlreadyAssociatedException {
- return objectPolicyOperations.associatePolicies(policiesToAdd, policiesToRemove);
- }
}
diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/GenericPolicy.java b/clients/client-java/src/main/java/org/apache/gravitino/client/GenericPolicy.java
index 5ae1936f6d..2748267a92 100644
--- a/clients/client-java/src/main/java/org/apache/gravitino/client/GenericPolicy.java
+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/GenericPolicy.java
@@ -20,32 +20,22 @@ package org.apache.gravitino.client;
import static org.apache.gravitino.dto.util.DTOConverters.fromDTO;
-import java.util.Collections;
import java.util.Optional;
import org.apache.gravitino.Audit;
-import org.apache.gravitino.MetadataObject;
import org.apache.gravitino.dto.policy.PolicyDTO;
-import org.apache.gravitino.dto.responses.MetadataObjectListResponse;
import org.apache.gravitino.policy.Policy;
import org.apache.gravitino.policy.PolicyContent;
-import org.apache.gravitino.rest.RESTUtils;
/** Represents a generic policy. */
-class GenericPolicy implements Policy, Policy.AssociatedObjects {
+class GenericPolicy implements Policy {
private final PolicyDTO policyDTO;
private final PolicyContent content;
- private final RESTClient restClient;
-
- private final String metalake;
-
- GenericPolicy(PolicyDTO policyDTO, RESTClient restClient, String metalake) {
+ GenericPolicy(PolicyDTO policyDTO) {
this.policyDTO = policyDTO;
this.content = fromDTO(policyDTO.content());
- this.restClient = restClient;
- this.metalake = metalake;
}
@Override
@@ -83,26 +73,6 @@ class GenericPolicy implements Policy, Policy.AssociatedObjects {
return policyDTO.auditInfo();
}
- @Override
- public AssociatedObjects associatedObjects() {
- return this;
- }
-
- @Override
- public MetadataObject[] objects() {
- MetadataObjectListResponse resp =
- restClient.get(
- String.format(
- "api/metalakes/%s/policies/%s/objects",
- RESTUtils.encodeString(metalake), RESTUtils.encodeString(name())),
- MetadataObjectListResponse.class,
- Collections.emptyMap(),
- ErrorHandlers.policyErrorHandler());
-
- resp.validate();
- return resp.getMetadataObjects();
- }
-
@Override
public boolean equals(Object obj) {
if (this == obj) {
@@ -123,14 +93,6 @@ class GenericPolicy implements Policy, Policy.AssociatedObjects {
@Override
public String toString() {
- return "GenericPolicy{"
- + "policyDTO="
- + policyDTO
- + ", content="
- + content
- + ", metalake='"
- + metalake
- + '\''
- + '}';
+ return "GenericPolicy{" + "policyDTO=" + policyDTO + ", content=" + content + '}';
}
}
diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/GenericSchema.java b/clients/client-java/src/main/java/org/apache/gravitino/client/GenericSchema.java
index 6c4d437643..756e0640ab 100644
--- a/clients/client-java/src/main/java/org/apache/gravitino/client/GenericSchema.java
+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/GenericSchema.java
@@ -26,9 +26,7 @@ import org.apache.gravitino.MetadataObjects;
import org.apache.gravitino.Schema;
import org.apache.gravitino.authorization.SupportsRoles;
import org.apache.gravitino.dto.SchemaDTO;
-import org.apache.gravitino.exceptions.NoSuchPolicyException;
import org.apache.gravitino.exceptions.NoSuchTagException;
-import org.apache.gravitino.exceptions.PolicyAlreadyAssociatedException;
import org.apache.gravitino.policy.Policy;
import org.apache.gravitino.policy.SupportsPolicies;
import org.apache.gravitino.secret.SupportsSecrets;
@@ -140,17 +138,6 @@ class GenericSchema
return objectPolicyOperations.listPolicyInfos();
}
- @Override
- public Policy getPolicy(String name) throws NoSuchPolicyException {
- return objectPolicyOperations.getPolicy(name);
- }
-
- @Override
- public String[] associatePolicies(String[] policiesToAdd, String[] policiesToRemove)
- throws PolicyAlreadyAssociatedException {
- return objectPolicyOperations.associatePolicies(policiesToAdd, policiesToRemove);
- }
-
@Override
public String[] listBindingRoleNames() {
return objectRoleOperations.listBindingRoleNames();
diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/GenericTopic.java b/clients/client-java/src/main/java/org/apache/gravitino/client/GenericTopic.java
index 63f00b288f..6ed87337eb 100644
--- a/clients/client-java/src/main/java/org/apache/gravitino/client/GenericTopic.java
+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/GenericTopic.java
@@ -27,9 +27,7 @@ import org.apache.gravitino.MetadataObjects;
import org.apache.gravitino.Namespace;
import org.apache.gravitino.authorization.SupportsRoles;
import org.apache.gravitino.dto.messaging.TopicDTO;
-import org.apache.gravitino.exceptions.NoSuchPolicyException;
import org.apache.gravitino.exceptions.NoSuchTagException;
-import org.apache.gravitino.exceptions.PolicyAlreadyAssociatedException;
import org.apache.gravitino.messaging.Topic;
import org.apache.gravitino.policy.Policy;
import org.apache.gravitino.policy.SupportsPolicies;
@@ -144,17 +142,6 @@ class GenericTopic
return objectPolicyOperations.listPolicyInfos();
}
- @Override
- public Policy getPolicy(String name) throws NoSuchPolicyException {
- return objectPolicyOperations.getPolicy(name);
- }
-
- @Override
- public String[] associatePolicies(String[] policiesToAdd, String[] policiesToRemove)
- throws PolicyAlreadyAssociatedException {
- return objectPolicyOperations.associatePolicies(policiesToAdd, policiesToRemove);
- }
-
@Override
public String[] listBindingRoleNames() {
return objectRoleOperations.listBindingRoleNames();
diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoMetalake.java b/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoMetalake.java
index 96072b7d8d..d03f1922be 100644
--- a/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoMetalake.java
+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoMetalake.java
@@ -770,7 +770,7 @@ public class GravitinoMetalake extends MetalakeDTO
.map(
association ->
new GenericPolicyTagAssociation(
- new GenericPolicy(association.getPolicy(), restClient, this.name()),
+ new GenericPolicy(association.getPolicy()),
tag,
association.getSelector().toSelector()))
.toArray(PolicyTagAssociation[]::new);
@@ -848,9 +848,7 @@ public class GravitinoMetalake extends MetalakeDTO
ErrorHandlers.policyErrorHandler());
resp.validate();
- return Arrays.stream(resp.getPolicies())
- .map(p -> new GenericPolicy(p, restClient, this.name()))
- .toArray(Policy[]::new);
+ return Arrays.stream(resp.getPolicies()).map(p -> new GenericPolicy(p)).toArray(Policy[]::new);
}
/**
@@ -875,7 +873,7 @@ public class GravitinoMetalake extends MetalakeDTO
ErrorHandlers.policyErrorHandler());
resp.validate();
- return new GenericPolicy(resp.getPolicy(), restClient, this.name());
+ return new GenericPolicy(resp.getPolicy());
}
/**
@@ -905,7 +903,7 @@ public class GravitinoMetalake extends MetalakeDTO
ErrorHandlers.policyErrorHandler());
resp.validate();
- return new GenericPolicy(resp.getPolicy(), restClient, this.name());
+ return new GenericPolicy(resp.getPolicy());
}
/**
@@ -964,7 +962,7 @@ public class GravitinoMetalake extends MetalakeDTO
ErrorHandlers.policyErrorHandler());
resp.validate();
- return new GenericPolicy(resp.getPolicy(), restClient, this.name());
+ return new GenericPolicy(resp.getPolicy());
}
/**
diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/MetadataObjectPolicyOperations.java b/clients/client-java/src/main/java/org/apache/gravitino/client/MetadataObjectPolicyOperations.java
index 820bd890eb..79292cee44 100644
--- a/clients/client-java/src/main/java/org/apache/gravitino/client/MetadataObjectPolicyOperations.java
+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/MetadataObjectPolicyOperations.java
@@ -18,18 +18,13 @@
*/
package org.apache.gravitino.client;
-import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import java.util.Arrays;
import java.util.Collections;
import java.util.Locale;
-import org.apache.commons.lang3.StringUtils;
import org.apache.gravitino.MetadataObject;
-import org.apache.gravitino.dto.requests.PoliciesAssociateRequest;
import org.apache.gravitino.dto.responses.NameListResponse;
import org.apache.gravitino.dto.responses.PolicyListResponse;
-import org.apache.gravitino.dto.responses.PolicyResponse;
-import org.apache.gravitino.exceptions.NoSuchPolicyException;
import org.apache.gravitino.policy.Policy;
import org.apache.gravitino.policy.SupportsPolicies;
import org.apache.gravitino.rest.RESTUtils;
@@ -40,15 +35,12 @@ import org.apache.gravitino.rest.RESTUtils;
*/
class MetadataObjectPolicyOperations implements SupportsPolicies {
- private final String metalakeName;
-
private final RESTClient restClient;
private final String policyRequestPath;
MetadataObjectPolicyOperations(
String metalakeName, MetadataObject metadataObject, RESTClient restClient) {
- this.metalakeName = metalakeName;
this.restClient = restClient;
this.policyRequestPath =
String.format(
@@ -83,41 +75,7 @@ class MetadataObjectPolicyOperations implements SupportsPolicies {
resp.validate();
return Arrays.stream(resp.getPolicies())
- .map(policyDTO -> new GenericPolicy(policyDTO, restClient, metalakeName))
+ .map(policyDTO -> new GenericPolicy(policyDTO))
.toArray(Policy[]::new);
}
-
- @Override
- public Policy getPolicy(String name) throws NoSuchPolicyException {
- Preconditions.checkArgument(
- StringUtils.isNotBlank(name), "Policy name must not be null or empty");
-
- PolicyResponse resp =
- restClient.get(
- policyRequestPath + "/" + RESTUtils.encodeString(name),
- PolicyResponse.class,
- Collections.emptyMap(),
- ErrorHandlers.policyErrorHandler());
-
- resp.validate();
- return new GenericPolicy(resp.getPolicy(), restClient, metalakeName);
- }
-
- @Override
- public String[] associatePolicies(String[] policiesToAdd, String[] policiesToRemove) {
- PoliciesAssociateRequest request =
- new PoliciesAssociateRequest(policiesToAdd, policiesToRemove);
- request.validate();
-
- NameListResponse resp =
- restClient.post(
- policyRequestPath,
- request,
- NameListResponse.class,
- Collections.emptyMap(),
- ErrorHandlers.policyErrorHandler());
-
- resp.validate();
- return resp.getNames();
- }
}
diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/RelationalTable.java b/clients/client-java/src/main/java/org/apache/gravitino/client/RelationalTable.java
index 7b7e93c4c0..36348080e2 100644
--- a/clients/client-java/src/main/java/org/apache/gravitino/client/RelationalTable.java
+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/RelationalTable.java
@@ -43,10 +43,8 @@ import org.apache.gravitino.dto.responses.PartitionNameListResponse;
import org.apache.gravitino.dto.responses.PartitionResponse;
import org.apache.gravitino.exceptions.IllegalStatisticNameException;
import org.apache.gravitino.exceptions.NoSuchPartitionException;
-import org.apache.gravitino.exceptions.NoSuchPolicyException;
import org.apache.gravitino.exceptions.NoSuchTagException;
import org.apache.gravitino.exceptions.PartitionAlreadyExistsException;
-import org.apache.gravitino.exceptions.PolicyAlreadyAssociatedException;
import org.apache.gravitino.exceptions.UnmodifiableStatisticException;
import org.apache.gravitino.policy.Policy;
import org.apache.gravitino.policy.SupportsPolicies;
@@ -423,17 +421,6 @@ class RelationalTable
return objectPolicyOperations.listPolicyInfos();
}
- @Override
- public Policy getPolicy(String name) throws NoSuchPolicyException {
- return objectPolicyOperations.getPolicy(name);
- }
-
- @Override
- public String[] associatePolicies(String[] policiesToAdd, String[] policiesToRemove)
- throws PolicyAlreadyAssociatedException {
- return objectPolicyOperations.associatePolicies(policiesToAdd, policiesToRemove);
- }
-
@Override
public String[] listBindingRoleNames() {
return objectRoleOperations.listBindingRoleNames();
diff --git a/clients/client-java/src/test/java/org/apache/gravitino/client/TestGenericPolicy.java b/clients/client-java/src/test/java/org/apache/gravitino/client/TestGenericPolicy.java
deleted file mode 100644
index b8478da7f0..0000000000
--- a/clients/client-java/src/test/java/org/apache/gravitino/client/TestGenericPolicy.java
+++ /dev/null
@@ -1,156 +0,0 @@
-/*
- * 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.client;
-
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.ImmutableSet;
-import java.time.Instant;
-import org.apache.gravitino.MetadataObject;
-import org.apache.gravitino.dto.AuditDTO;
-import org.apache.gravitino.dto.MetalakeDTO;
-import org.apache.gravitino.dto.policy.PolicyContentDTO;
-import org.apache.gravitino.dto.policy.PolicyDTO;
-import org.apache.gravitino.dto.responses.ErrorResponse;
-import org.apache.gravitino.dto.responses.MetadataObjectListResponse;
-import org.apache.gravitino.dto.responses.MetalakeResponse;
-import org.apache.gravitino.dto.tag.MetadataObjectDTO;
-import org.apache.gravitino.exceptions.NoSuchMetalakeException;
-import org.apache.gravitino.policy.Policy;
-import org.apache.hc.core5.http.HttpStatus;
-import org.apache.hc.core5.http.Method;
-import org.junit.jupiter.api.AfterAll;
-import org.junit.jupiter.api.Assertions;
-import org.junit.jupiter.api.BeforeAll;
-import org.junit.jupiter.api.Test;
-
-public class TestGenericPolicy extends TestBase {
-
- private static final String metalakeName = "metalake1";
-
- private static final PolicyDTO policyDTO =
- PolicyDTO.builder()
- .withName("policy1")
- .withComment("comment1")
- .withPolicyType("my_compaction")
- .withEnabled(true)
- .withContent(
- PolicyContentDTO.CustomContentDTO.builder()
- .withCustomRules(ImmutableMap.of("key1", "value1"))
- .withSupportedObjectTypes(ImmutableSet.of(MetadataObject.Type.TABLE))
- .withProperties(ImmutableMap.of("prop1", "value1"))
- .build())
- .withAudit(AuditDTO.builder().withCreator("test").withCreateTime(Instant.now()).build())
- .build();
-
- private static GravitinoClient gravitinoClient;
-
- @BeforeAll
- public static void setUp() throws Exception {
- TestBase.setUp();
-
- MetalakeDTO mockMetalake =
- MetalakeDTO.builder()
- .withName(metalakeName)
- .withComment("comment")
- .withAudit(
- AuditDTO.builder().withCreator("creator").withCreateTime(Instant.now()).build())
- .build();
- MetalakeResponse resp = new MetalakeResponse(mockMetalake);
- buildMockResource(Method.GET, "/api/metalakes/" + metalakeName, null, resp, HttpStatus.SC_OK);
-
- gravitinoClient =
- GravitinoClient.builder("http://127.0.0.1:" + mockServer.getLocalPort())
- .withMetalake(metalakeName)
- .withVersionCheckDisabled()
- .build();
- }
-
- @AfterAll
- public static void tearDown() {
- TestBase.tearDown();
- gravitinoClient.close();
- }
-
- @Test
- public void testAssociatedObjects() throws JsonProcessingException {
- Policy policy = new GenericPolicy(policyDTO, gravitinoClient.restClient(), metalakeName);
- String path = "/api/metalakes/" + metalakeName + "/policies/" + policyDTO.name() + "/objects";
-
- MetadataObjectDTO[] objects =
- new MetadataObjectDTO[] {
- MetadataObjectDTO.builder()
- .withParent(null)
- .withName("catalog1")
- .withType(MetadataObject.Type.CATALOG)
- .build(),
- MetadataObjectDTO.builder()
- .withParent("catalog1")
- .withName("schema1")
- .withType(MetadataObject.Type.SCHEMA)
- .build(),
- MetadataObjectDTO.builder()
- .withParent("catalog1.schema1")
- .withName("table1")
- .withType(MetadataObject.Type.TABLE)
- .build(),
- };
-
- MetadataObjectListResponse resp = new MetadataObjectListResponse(objects);
- buildMockResource(Method.GET, path, null, resp, HttpStatus.SC_OK);
-
- MetadataObject[] actualObjects = policy.associatedObjects().objects();
- Assertions.assertEquals(objects.length, actualObjects.length);
- for (int i = 0; i < objects.length; i++) {
- MetadataObjectDTO object = objects[i];
- MetadataObject actualObject = actualObjects[i];
- Assertions.assertEquals(object.parent(), actualObject.parent());
- Assertions.assertEquals(object.name(), actualObject.name());
- Assertions.assertEquals(object.type(), actualObject.type());
- }
-
- // Test return empty array
- buildMockResource(
- Method.GET,
- path,
- null,
- new MetadataObjectListResponse(new MetadataObjectDTO[0]),
- HttpStatus.SC_OK);
- MetadataObject[] actualObjects1 = policy.associatedObjects().objects();
- Assertions.assertEquals(0, actualObjects1.length);
-
- // Test throw NoSuchMetalakeException
- ErrorResponse errorResponse =
- ErrorResponse.notFound(NoSuchMetalakeException.class.getSimpleName(), "mock error");
- buildMockResource(Method.GET, path, null, errorResponse, HttpStatus.SC_NOT_FOUND);
-
- Throwable ex =
- Assertions.assertThrows(
- NoSuchMetalakeException.class, () -> policy.associatedObjects().objects());
- Assertions.assertEquals("mock error", ex.getMessage());
-
- // Test throw internal error
- ErrorResponse errorResponse1 = ErrorResponse.internalError("mock error");
- buildMockResource(Method.GET, path, null, errorResponse1, HttpStatus.SC_INTERNAL_SERVER_ERROR);
-
- Throwable ex1 =
- Assertions.assertThrows(RuntimeException.class, () -> policy.associatedObjects().objects());
- Assertions.assertEquals("mock error", ex1.getMessage());
- }
-}
diff --git a/clients/client-java/src/test/java/org/apache/gravitino/client/TestSupportPolicies.java b/clients/client-java/src/test/java/org/apache/gravitino/client/TestSupportPolicies.java
index da58d21c65..dbd2f9c2fe 100644
--- a/clients/client-java/src/test/java/org/apache/gravitino/client/TestSupportPolicies.java
+++ b/clients/client-java/src/test/java/org/apache/gravitino/client/TestSupportPolicies.java
@@ -41,12 +41,9 @@ import org.apache.gravitino.dto.policy.PolicyContentDTO;
import org.apache.gravitino.dto.policy.PolicyDTO;
import org.apache.gravitino.dto.rel.ColumnDTO;
import org.apache.gravitino.dto.rel.TableDTO;
-import org.apache.gravitino.dto.requests.PoliciesAssociateRequest;
import org.apache.gravitino.dto.responses.ErrorResponse;
import org.apache.gravitino.dto.responses.NameListResponse;
import org.apache.gravitino.dto.responses.PolicyListResponse;
-import org.apache.gravitino.dto.responses.PolicyResponse;
-import org.apache.gravitino.exceptions.NoSuchPolicyException;
import org.apache.gravitino.exceptions.NotFoundException;
import org.apache.gravitino.file.Fileset;
import org.apache.gravitino.messaging.Topic;
@@ -263,92 +260,6 @@ public class TestSupportPolicies extends TestBase {
MetadataObjects.of("catalog1.schema1", genericTopic.name(), MetadataObject.Type.TOPIC));
}
- @Test
- public void testGetPolicyForCatalog() throws JsonProcessingException {
- testGetPolicy(
- relationalCatalog.supportsPolicies(),
- MetadataObjects.of(null, relationalCatalog.name(), MetadataObject.Type.CATALOG));
-
- testGetPolicy(
- filesetCatalog.supportsPolicies(),
- MetadataObjects.of(null, filesetCatalog.name(), MetadataObject.Type.CATALOG));
-
- testGetPolicy(
- messagingCatalog.supportsPolicies(),
- MetadataObjects.of(null, messagingCatalog.name(), MetadataObject.Type.CATALOG));
- }
-
- @Test
- public void testGetPolicyForSchema() throws JsonProcessingException {
- testGetPolicy(
- genericSchema.supportsPolicies(),
- MetadataObjects.of("catalog1", genericSchema.name(), MetadataObject.Type.SCHEMA));
- }
-
- @Test
- public void testGetPolicyForTable() throws JsonProcessingException {
- testGetPolicy(
- relationalTable.supportsPolicies(),
- MetadataObjects.of("catalog1.schema1", relationalTable.name(), MetadataObject.Type.TABLE));
- }
-
- @Test
- public void testGetPolicyForFileset() throws JsonProcessingException {
- testGetPolicy(
- genericFileset.supportsPolicies(),
- MetadataObjects.of("catalog1.schema1", genericFileset.name(), MetadataObject.Type.FILESET));
- }
-
- @Test
- public void testGetPolicyForTopic() throws JsonProcessingException {
- testGetPolicy(
- genericTopic.supportsPolicies(),
- MetadataObjects.of("catalog1.schema1", genericTopic.name(), MetadataObject.Type.TOPIC));
- }
-
- @Test
- public void testAssociatePoliciesForCatalog() throws JsonProcessingException {
- testAssociatePolicies(
- relationalCatalog.supportsPolicies(),
- MetadataObjects.of(null, relationalCatalog.name(), MetadataObject.Type.CATALOG));
-
- testAssociatePolicies(
- filesetCatalog.supportsPolicies(),
- MetadataObjects.of(null, filesetCatalog.name(), MetadataObject.Type.CATALOG));
-
- testAssociatePolicies(
- messagingCatalog.supportsPolicies(),
- MetadataObjects.of(null, messagingCatalog.name(), MetadataObject.Type.CATALOG));
- }
-
- @Test
- public void testAssociatePoliciesForSchema() throws JsonProcessingException {
- testAssociatePolicies(
- genericSchema.supportsPolicies(),
- MetadataObjects.of("catalog1", genericSchema.name(), MetadataObject.Type.SCHEMA));
- }
-
- @Test
- public void testAssociatePoliciesForTable() throws JsonProcessingException {
- testAssociatePolicies(
- relationalTable.supportsPolicies(),
- MetadataObjects.of("catalog1.schema1", relationalTable.name(), MetadataObject.Type.TABLE));
- }
-
- @Test
- public void testAssociatePoliciesForFileset() throws JsonProcessingException {
- testAssociatePolicies(
- genericFileset.supportsPolicies(),
- MetadataObjects.of("catalog1.schema1", genericFileset.name(), MetadataObject.Type.FILESET));
- }
-
- @Test
- public void testAssociatePoliciesForTopic() throws JsonProcessingException {
- testAssociatePolicies(
- genericTopic.supportsPolicies(),
- MetadataObjects.of("catalog1.schema1", genericTopic.name(), MetadataObject.Type.TOPIC));
- }
-
private void testListPolicies(SupportsPolicies supportsPolicies, MetadataObject metadataObject)
throws JsonProcessingException {
String path =
@@ -447,83 +358,4 @@ public class TestSupportPolicies extends TestBase {
Throwable ex1 = Assertions.assertThrows(RuntimeException.class, supportsPolicies::listPolicies);
Assertions.assertTrue(ex1.getMessage().contains("mock error"));
}
-
- private void testGetPolicy(SupportsPolicies supportsPolicies, MetadataObject metadataObject)
- throws JsonProcessingException {
- String path =
- "/api/metalakes/"
- + METALAKE_NAME
- + "/objects/"
- + metadataObject.type().name().toLowerCase(Locale.ROOT)
- + "/"
- + metadataObject.fullName()
- + "/policies/policy1";
-
- PolicyDTO policy1 =
- PolicyDTO.builder()
- .withName("policy1")
- .withPolicyType("test")
- .withContent(contentDTO)
- .withAudit(AuditDTO.builder().withCreator("test").build())
- .build();
-
- PolicyResponse resp = new PolicyResponse(policy1);
- buildMockResource(Method.GET, path, null, resp, SC_OK);
-
- Policy actualPolicy = supportsPolicies.getPolicy("policy1");
- Assertions.assertEquals("policy1", actualPolicy.name());
-
- // Test throw NoSuchPolicyException
- ErrorResponse errorResp =
- ErrorResponse.notFound(NoSuchPolicyException.class.getSimpleName(), "mock error");
- buildMockResource(Method.GET, path, null, errorResp, SC_NOT_FOUND);
-
- Throwable ex =
- Assertions.assertThrows(
- NoSuchPolicyException.class, () -> supportsPolicies.getPolicy("policy1"));
- Assertions.assertTrue(ex.getMessage().contains("mock error"));
-
- // Test throw internal error
- ErrorResponse errorResp1 = ErrorResponse.internalError("mock error");
- buildMockResource(Method.GET, path, null, errorResp1, SC_INTERNAL_SERVER_ERROR);
-
- Throwable ex1 =
- Assertions.assertThrows(
- RuntimeException.class, () -> supportsPolicies.getPolicy("policy1"));
- Assertions.assertTrue(ex1.getMessage().contains("mock error"));
- }
-
- private void testAssociatePolicies(
- SupportsPolicies supportsPolicies, MetadataObject metadataObject)
- throws JsonProcessingException {
- String path =
- "/api/metalakes/"
- + METALAKE_NAME
- + "/objects/"
- + metadataObject.type().name().toLowerCase(Locale.ROOT)
- + "/"
- + metadataObject.fullName()
- + "/policies";
-
- String[] policiesToAdd = new String[] {"policy1", "policy2"};
- String[] policiesToRemove = new String[] {"policy3", "policy4"};
- PoliciesAssociateRequest request =
- new PoliciesAssociateRequest(policiesToAdd, policiesToRemove);
-
- NameListResponse resp = new NameListResponse(policiesToAdd);
- buildMockResource(Method.POST, path, request, resp, SC_OK);
-
- String[] actualPolicies = supportsPolicies.associatePolicies(policiesToAdd, policiesToRemove);
- Assertions.assertArrayEquals(policiesToAdd, actualPolicies);
-
- // Test throw internal error
- ErrorResponse errorResp1 = ErrorResponse.internalError("mock error");
- buildMockResource(Method.POST, path, request, errorResp1, SC_INTERNAL_SERVER_ERROR);
-
- Throwable ex1 =
- Assertions.assertThrows(
- RuntimeException.class,
- () -> supportsPolicies.associatePolicies(policiesToAdd, policiesToRemove));
- Assertions.assertTrue(ex1.getMessage().contains("mock error"));
- }
}
diff --git a/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/HierarchicalSchemaTagPolicyIT.java b/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/HierarchicalSchemaTagPolicyIT.java
index c782a7d119..b591e3d0a4 100644
--- a/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/HierarchicalSchemaTagPolicyIT.java
+++ b/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/HierarchicalSchemaTagPolicyIT.java
@@ -18,25 +18,18 @@
*/
package org.apache.gravitino.client.integration.test;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.ImmutableSet;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
-import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.gravitino.Catalog;
import org.apache.gravitino.Configs;
-import org.apache.gravitino.MetadataObject;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Schema;
import org.apache.gravitino.client.GravitinoMetalake;
import org.apache.gravitino.integration.test.util.BaseIT;
import org.apache.gravitino.integration.test.util.GravitinoITUtils;
-import org.apache.gravitino.policy.PolicyContent;
-import org.apache.gravitino.policy.PolicyContents;
-import org.apache.gravitino.policy.SupportsPolicies;
import org.apache.gravitino.rel.Column;
import org.apache.gravitino.rel.Table;
import org.apache.gravitino.rel.types.Types;
@@ -201,68 +194,6 @@ public class HierarchicalSchemaTagPolicyIT extends BaseIT {
}
}
- @Test
- public void testPolicyInheritanceThroughHierarchicalSchema() {
- Set<MetadataObject.Type> types =
- ImmutableSet.of(MetadataObject.Type.CATALOG, MetadataObject.Type.SCHEMA);
- PolicyContent content = PolicyContents.custom(ImmutableMap.of("rule", "value"), types, null);
-
- String catalogPolicy = GravitinoITUtils.genRandomName("h_catalog_policy");
- String rootPolicy = GravitinoITUtils.genRandomName("h_root_policy");
- String midPolicy = GravitinoITUtils.genRandomName("h_mid_policy");
- String leafPolicy = GravitinoITUtils.genRandomName("h_leaf_policy");
- for (String policy : new String[] {catalogPolicy, rootPolicy, midPolicy, leafPolicy}) {
- metalake.createPolicy(policy, "custom", "comment", true, content);
- }
-
- catalog.supportsPolicies().associatePolicies(new String[] {catalogPolicy}, null);
- catalog
- .asSchemas()
- .loadSchema(ROOT_A)
- .supportsPolicies()
- .associatePolicies(new String[] {rootPolicy}, null);
- catalog
- .asSchemas()
- .loadSchema(SCHEMA_AB)
- .supportsPolicies()
- .associatePolicies(new String[] {midPolicy}, null);
- Schema leafSchema = catalog.asSchemas().loadSchema(SCHEMA_ABC);
- leafSchema.supportsPolicies().associatePolicies(new String[] {leafPolicy}, null);
-
- Map<String, Boolean> inheritedByName = policyInheritanceByName(leafSchema.supportsPolicies());
-
- Assertions.assertTrue(inheritedByName.containsKey(leafPolicy), "leaf policy should be present");
- Assertions.assertTrue(
- inheritedByName.containsKey(midPolicy),
- "policy on intermediate schema A:B should be inherited");
- Assertions.assertTrue(
- inheritedByName.containsKey(rootPolicy), "policy on ancestor schema A should be inherited");
- Assertions.assertTrue(
- inheritedByName.containsKey(catalogPolicy), "catalog policy should be inherited");
-
- Assertions.assertFalse(inheritedByName.get(leafPolicy));
- Assertions.assertTrue(inheritedByName.get(midPolicy));
- Assertions.assertTrue(inheritedByName.get(rootPolicy));
- Assertions.assertTrue(inheritedByName.get(catalogPolicy));
-
- // Clean up associations and policies so the test is repeatable.
- catalog.supportsPolicies().associatePolicies(null, new String[] {catalogPolicy});
- catalog
- .asSchemas()
- .loadSchema(ROOT_A)
- .supportsPolicies()
- .associatePolicies(null, new String[] {rootPolicy});
- catalog
- .asSchemas()
- .loadSchema(SCHEMA_AB)
- .supportsPolicies()
- .associatePolicies(null, new String[] {midPolicy});
- leafSchema.supportsPolicies().associatePolicies(null, new String[] {leafPolicy});
- for (String policy : new String[] {catalogPolicy, rootPolicy, midPolicy, leafPolicy}) {
- metalake.deletePolicy(policy);
- }
- }
-
@Test
public void testTagInheritanceForTableAndColumnUnderHierarchicalSchema() {
String catalogTag = GravitinoITUtils.genRandomName("ht_catalog_tag");
@@ -344,99 +275,11 @@ public class HierarchicalSchemaTagPolicyIT extends BaseIT {
}
}
- @Test
- public void testPolicyInheritanceForTableUnderHierarchicalSchema() {
- Set<MetadataObject.Type> types =
- ImmutableSet.of(
- MetadataObject.Type.CATALOG, MetadataObject.Type.SCHEMA, MetadataObject.Type.TABLE);
- PolicyContent content = PolicyContents.custom(ImmutableMap.of("rule", "value"), types, null);
-
- String catalogPolicy = GravitinoITUtils.genRandomName("ht_catalog_policy");
- String rootPolicy = GravitinoITUtils.genRandomName("ht_root_policy");
- String midPolicy = GravitinoITUtils.genRandomName("ht_mid_policy");
- String leafPolicy = GravitinoITUtils.genRandomName("ht_leaf_policy");
- for (String policy : new String[] {catalogPolicy, rootPolicy, midPolicy, leafPolicy}) {
- metalake.createPolicy(policy, "custom", "comment", true, content);
- }
-
- catalog.supportsPolicies().associatePolicies(new String[] {catalogPolicy}, null);
- catalog
- .asSchemas()
- .loadSchema(ROOT_A)
- .supportsPolicies()
- .associatePolicies(new String[] {rootPolicy}, null);
- catalog
- .asSchemas()
- .loadSchema(SCHEMA_AB)
- .supportsPolicies()
- .associatePolicies(new String[] {midPolicy}, null);
- catalog
- .asSchemas()
- .loadSchema(SCHEMA_ABC)
- .supportsPolicies()
- .associatePolicies(new String[] {leafPolicy}, null);
-
- // A table under the deepest schema A:B:C inherits policies through the whole chain.
- Map<String, Boolean> tablePolicies =
- policyInheritanceByName(
- catalog
- .asTableCatalog()
- .loadTable(NameIdentifier.of(SCHEMA_ABC, LEAF_TABLE))
- .supportsPolicies());
- for (String policy : new String[] {catalogPolicy, rootPolicy, midPolicy, leafPolicy}) {
- Assertions.assertTrue(
- tablePolicies.containsKey(policy), policy + " should be inherited by the table");
- Assertions.assertTrue(
- tablePolicies.get(policy), policy + " on an ancestor must be marked inherited");
- }
-
- // A table under the intermediate schema A:B does not inherit the policy assigned only to the
- // deeper sibling schema A:B:C.
- Map<String, Boolean> midTablePolicies =
- policyInheritanceByName(
- catalog
- .asTableCatalog()
- .loadTable(NameIdentifier.of(SCHEMA_AB, MID_TABLE))
- .supportsPolicies());
- Assertions.assertTrue(midTablePolicies.containsKey(catalogPolicy));
- Assertions.assertTrue(midTablePolicies.containsKey(rootPolicy));
- Assertions.assertTrue(midTablePolicies.containsKey(midPolicy));
- Assertions.assertFalse(
- midTablePolicies.containsKey(leafPolicy),
- "policy on A:B:C must not leak to a table under A:B");
-
- // Clean up associations and policies so the test is repeatable.
- catalog.supportsPolicies().associatePolicies(null, new String[] {catalogPolicy});
- catalog
- .asSchemas()
- .loadSchema(ROOT_A)
- .supportsPolicies()
- .associatePolicies(null, new String[] {rootPolicy});
- catalog
- .asSchemas()
- .loadSchema(SCHEMA_AB)
- .supportsPolicies()
- .associatePolicies(null, new String[] {midPolicy});
- catalog
- .asSchemas()
- .loadSchema(SCHEMA_ABC)
- .supportsPolicies()
- .associatePolicies(null, new String[] {leafPolicy});
- for (String policy : new String[] {catalogPolicy, rootPolicy, midPolicy, leafPolicy}) {
- metalake.deletePolicy(policy);
- }
- }
-
private static Map<String, Boolean> tagInheritanceByName(SupportsTags supportsTags) {
return Stream.of(supportsTags.listTagsInfo())
.collect(Collectors.toMap(tag -> tag.name(), tag -> tag.inherited().get()));
}
- private static Map<String, Boolean> policyInheritanceByName(SupportsPolicies supportsPolicies) {
- return Stream.of(supportsPolicies.listPolicyInfos())
- .collect(Collectors.toMap(policy -> policy.name(), policy -> policy.inherited().get()));
- }
-
private static Column columnByName(Table table, String columnName) {
return Stream.of(table.columns())
.filter(column -> column.name().equals(columnName))
diff --git a/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/PolicyIT.java b/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/PolicyIT.java
index 815e49f0d3..37af461056 100644
--- a/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/PolicyIT.java
+++ b/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/PolicyIT.java
@@ -21,27 +21,14 @@ package org.apache.gravitino.client.integration.test;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
-import java.util.Arrays;
import java.util.Collections;
-import java.util.HashSet;
-import java.util.Locale;
import java.util.Set;
-import java.util.stream.Collectors;
import org.apache.gravitino.Catalog;
import org.apache.gravitino.MetadataObject;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Schema;
-import org.apache.gravitino.client.ErrorHandlers;
import org.apache.gravitino.client.GravitinoMetalake;
-import org.apache.gravitino.client.HTTPClient;
-import org.apache.gravitino.client.RESTClient;
-import org.apache.gravitino.dto.requests.PoliciesAssociateRequest;
-import org.apache.gravitino.dto.responses.NameListResponse;
-import org.apache.gravitino.dto.responses.PolicyListResponse;
-import org.apache.gravitino.dto.responses.PolicyResponse;
-import org.apache.gravitino.dto.tag.MetadataObjectDTO;
import org.apache.gravitino.exceptions.NoSuchPolicyException;
-import org.apache.gravitino.exceptions.PolicyAlreadyAssociatedException;
import org.apache.gravitino.exceptions.PolicyAlreadyExistsException;
import org.apache.gravitino.function.Function;
import org.apache.gravitino.function.FunctionDefinition;
@@ -60,14 +47,12 @@ import org.apache.gravitino.policy.Policy;
import org.apache.gravitino.policy.PolicyChange;
import org.apache.gravitino.policy.PolicyContent;
import org.apache.gravitino.policy.PolicyContents;
-import org.apache.gravitino.policy.SupportsPolicies;
import org.apache.gravitino.rel.Column;
import org.apache.gravitino.rel.Dialects;
import org.apache.gravitino.rel.SQLRepresentation;
import org.apache.gravitino.rel.Table;
import org.apache.gravitino.rel.View;
import org.apache.gravitino.rel.types.Types;
-import org.apache.gravitino.rest.RESTUtils;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
@@ -88,9 +73,6 @@ public class PolicyIT extends BaseIT {
private static Table table;
private static View view;
private static Function function;
- private static SupportsPolicies viewPolicyOperations;
- private static SupportsPolicies functionPolicyOperations;
- private static RESTClient policyRestClient;
private static Catalog modelCatalog;
private static Schema modelSchema;
@@ -99,8 +81,6 @@ public class PolicyIT extends BaseIT {
@BeforeAll
public void setUp() {
containerSuite.startHiveContainer();
- policyRestClient =
- closer.register(HTTPClient.builder(Collections.emptyMap()).uri(serverUri).build());
String hmsUri =
String.format(
"thrift://%s:%d",
@@ -167,9 +147,6 @@ public class PolicyIT extends BaseIT {
null,
null,
Collections.emptyMap());
- viewPolicyOperations =
- policyOperations(
- relationalCatalog, schema, view.name(), MetadataObject.Type.VIEW, policyRestClient);
// Create function
String functionName = GravitinoITUtils.genRandomName("policy_it_function");
@@ -191,13 +168,6 @@ public class PolicyIT extends BaseIT {
FunctionType.SCALAR,
true,
new FunctionDefinition[] {definition});
- functionPolicyOperations =
- policyOperations(
- relationalCatalog,
- schema,
- function.name(),
- MetadataObject.Type.FUNCTION,
- policyRestClient);
// Create model catalog
String modelCatalogName = GravitinoITUtils.genRandomName("policy_it_model_catalog");
@@ -253,21 +223,6 @@ public class PolicyIT extends BaseIT {
@AfterEach
public void cleanUp() {
- String[] functionPolicies = functionPolicyOperations.listPolicies();
- functionPolicyOperations.associatePolicies(null, functionPolicies);
-
- String[] viewPolicies = viewPolicyOperations.listPolicies();
- viewPolicyOperations.associatePolicies(null, viewPolicies);
-
- String[] tablePolicies = table.supportsPolicies().listPolicies();
- table.supportsPolicies().associatePolicies(null, tablePolicies);
-
- String[] schemaPolicies = schema.supportsPolicies().listPolicies();
- schema.supportsPolicies().associatePolicies(null, schemaPolicies);
-
- String[] catalogPolicies = relationalCatalog.supportsPolicies().listPolicies();
- relationalCatalog.supportsPolicies().associatePolicies(null, catalogPolicies);
-
String[] policies = metalake.listPolicies();
for (String policy : policies) {
metalake.deletePolicy(policy);
@@ -484,1000 +439,4 @@ public class PolicyIT extends BaseIT {
Assertions.assertTrue(metalake.deletePolicy(policyName));
Assertions.assertFalse(metalake.deletePolicy(policyName));
}
-
- @Test
- public void testAssociatePoliciesToCatalog() {
- Policy policy1 =
- createCustomPolicy(
- GravitinoITUtils.genRandomName("policy_it_catalog_policy1"),
- ImmutableSet.of(MetadataObject.Type.CATALOG));
- Policy policy2 =
- createCustomPolicy(
- GravitinoITUtils.genRandomName("policy_it_catalog_policy2"),
- ImmutableSet.of(MetadataObject.Type.CATALOG));
-
- // Test associate policies to catalog
- String[] policies =
- relationalCatalog
- .supportsPolicies()
- .associatePolicies(new String[] {policy1.name(), policy2.name()}, null);
-
- Assertions.assertEquals(2, policies.length);
- Set<String> policyNames = Sets.newHashSet(policies);
- Assertions.assertTrue(policyNames.contains(policy1.name()));
- Assertions.assertTrue(policyNames.contains(policy2.name()));
-
- // Test disassociate policies from catalog
- String[] policies1 =
- relationalCatalog
- .supportsPolicies()
- .associatePolicies(null, new String[] {policy1.name(), policy2.name()});
- Assertions.assertEquals(0, policies1.length);
-
- // Test associate non-existed policies to catalog
- String[] policies2 =
- relationalCatalog
- .supportsPolicies()
- .associatePolicies(new String[] {"non-existed-policy"}, null);
- Assertions.assertEquals(0, policies2.length);
-
- // Test disassociate non-existed policies from catalog
- String[] policies3 =
- relationalCatalog
- .supportsPolicies()
- .associatePolicies(null, new String[] {"non-existed-policy"});
- Assertions.assertEquals(0, policies3.length);
-
- // Test associate same policies to catalog
- String[] policies4 =
- relationalCatalog
- .supportsPolicies()
- .associatePolicies(new String[] {policy1.name(), policy1.name()}, null);
- Assertions.assertEquals(1, policies4.length);
- Assertions.assertEquals(policy1.name(), policies4[0]);
-
- // Test associate same policy again to catalog
- Assertions.assertThrows(
- PolicyAlreadyAssociatedException.class,
- () ->
- relationalCatalog
- .supportsPolicies()
- .associatePolicies(new String[] {policy1.name()}, null));
-
- // Test associate and disassociate same policies to catalog
- String[] policies5 =
- relationalCatalog
- .supportsPolicies()
- .associatePolicies(new String[] {policy2.name()}, new String[] {policy2.name()});
- Assertions.assertEquals(1, policies5.length);
- Assertions.assertEquals(policy1.name(), policies5[0]);
-
- // Test List associated policies for catalog
- String[] policies6 = relationalCatalog.supportsPolicies().listPolicies();
- Assertions.assertEquals(1, policies6.length);
- Assertions.assertEquals(policy1.name(), policies6[0]);
-
- // Test List associated policies with details for catalog
- Policy[] policies7 = relationalCatalog.supportsPolicies().listPolicyInfos();
- Assertions.assertEquals(1, policies7.length);
- Assertions.assertEquals(policy1, policies7[0]);
- Assertions.assertFalse(policies7[0].inherited().get());
- Assertions.assertTrue(policies7[0].enabled());
-
- // Test disabled policies are excluded when listing associated policies
- Assertions.assertDoesNotThrow(() -> metalake.disablePolicy(policy1.name()));
- Policy[] policies8 = relationalCatalog.supportsPolicies().listPolicyInfos();
- Assertions.assertEquals(0, policies8.length);
- Assertions.assertDoesNotThrow(() -> metalake.enablePolicy(policy1.name()));
-
- // Test get associated policy for catalog
- Policy policy = relationalCatalog.supportsPolicies().getPolicy(policy1.name());
- Assertions.assertEquals(policy1.enabled(), policy.enabled());
- Assertions.assertFalse(policy.inherited().get());
-
- // Test get non-existed policy for catalog
- Assertions.assertThrows(
- NoSuchPolicyException.class,
- () -> relationalCatalog.supportsPolicies().getPolicy("non-existed-policy"));
-
- // Test get objects associated with policy
- Assertions.assertEquals(1, policy.associatedObjects().count());
- MetadataObject catalogObject = policy.associatedObjects().objects()[0];
- Assertions.assertEquals(relationalCatalog.name(), catalogObject.name());
- Assertions.assertEquals(MetadataObject.Type.CATALOG, catalogObject.type());
- }
-
- @Test
- public void testAssociatePoliciesToSchema() {
- Policy policy1 =
- createCustomPolicy(
- GravitinoITUtils.genRandomName("policy_it_schema_policy1"),
- ImmutableSet.of(MetadataObject.Type.CATALOG));
- Policy policy2 =
- createCustomPolicy(
- GravitinoITUtils.genRandomName("policy_it_schema_policy2"),
- ImmutableSet.of(MetadataObject.Type.CATALOG));
-
- // Associate policies to catalog
- relationalCatalog.supportsPolicies().associatePolicies(new String[] {policy1.name()}, null);
-
- // Test list associated policies for schema
- String[] policies1 = schema.supportsPolicies().listPolicies();
- Assertions.assertEquals(Sets.newHashSet(policy1.name()), Sets.newHashSet(policies1));
-
- // Test associate policies to schema
- String[] policies =
- schema
- .supportsPolicies()
- .associatePolicies(new String[] {policy1.name(), policy2.name()}, null);
-
- Assertions.assertEquals(2, policies.length);
- HashSet<String> expected = Sets.newHashSet(policy1.name(), policy2.name());
- Assertions.assertEquals(expected, Sets.newHashSet(policies));
-
- // Test list associated policies with details for schema
- Policy[] policies2 = schema.supportsPolicies().listPolicyInfos();
- Assertions.assertEquals(2, policies2.length);
-
- Set<Policy> nonInheritedPolicies =
- Arrays.stream(policies2)
- .filter(policy -> !policy.inherited().get())
- .collect(Collectors.toSet());
- Set<Policy> inheritedPolicies =
- Arrays.stream(policies2)
- .filter(policy -> policy.inherited().get())
- .collect(Collectors.toSet());
-
- Assertions.assertEquals(2, nonInheritedPolicies.size());
- Assertions.assertEquals(0, inheritedPolicies.size());
- Assertions.assertTrue(nonInheritedPolicies.contains(policy1));
- Assertions.assertTrue(nonInheritedPolicies.contains(policy2));
- Assertions.assertFalse(inheritedPolicies.contains(policy2));
-
- // Test get associated policy for schema
- Policy policy = schema.supportsPolicies().getPolicy(policy1.name());
- Assertions.assertEquals(policy1, policy);
- Assertions.assertFalse(policy.inherited().get());
-
- // Test get objects associated with policy
- Assertions.assertEquals(2, policy.associatedObjects().count());
- Set<MetadataObject> resultObjects = Sets.newHashSet(policy.associatedObjects().objects());
- Set<MetadataObject> expectedObjects =
- Sets.newHashSet(
- MetadataObjectDTO.builder()
- .withName(relationalCatalog.name())
- .withType(MetadataObject.Type.CATALOG)
- .build(),
- MetadataObjectDTO.builder()
- .withParent(relationalCatalog.name())
- .withName(schema.name())
- .withType(MetadataObject.Type.SCHEMA)
- .build());
- Assertions.assertEquals(expectedObjects, resultObjects);
- }
-
- @Test
- public void testAssociatePoliciesToTable() {
- PolicyContent content =
- PolicyContents.custom(
- ImmutableMap.of("rule1", "value1"), ImmutableSet.of(MetadataObject.Type.TABLE), null);
- Policy policy1 =
- metalake.createPolicy(
- GravitinoITUtils.genRandomName("policy_it_table_policy1"),
- "custom",
- null,
- true,
- content);
- Policy policy2 =
- metalake.createPolicy(
- GravitinoITUtils.genRandomName("policy_it_table_policy2"),
- "custom",
- null,
- true,
- content);
- Policy policy3 =
- metalake.createPolicy(
- GravitinoITUtils.genRandomName("policy_it_table_policy3"),
- "custom",
- null,
- true,
- content);
-
- // Associate policies to catalog
- relationalCatalog.supportsPolicies().associatePolicies(new String[] {policy1.name()}, null);
-
- // Associate policies to schema
- schema.supportsPolicies().associatePolicies(new String[] {policy2.name()}, null);
-
- // Test associate policies to table
- String[] policies =
- table.supportsPolicies().associatePolicies(new String[] {policy3.name()}, null);
-
- Assertions.assertEquals(1, policies.length);
- Assertions.assertEquals(policy3.name(), policies[0]);
-
- // Test list associated policies for table
- String[] policies1 = table.supportsPolicies().listPolicies();
- Assertions.assertEquals(3, policies1.length);
- Set<String> policyNames = Sets.newHashSet(policies1);
- Assertions.assertTrue(policyNames.contains(policy1.name()));
- Assertions.assertTrue(policyNames.contains(policy2.name()));
- Assertions.assertTrue(policyNames.contains(policy3.name()));
-
- // Test list associated policies with details for table
- Policy[] policies2 = table.supportsPolicies().listPolicyInfos();
- Assertions.assertEquals(3, policies2.length);
-
- Set<Policy> nonInheritedPolicies =
- Arrays.stream(policies2)
- .filter(policy -> !policy.inherited().get())
- .collect(Collectors.toSet());
- Set<Policy> inheritedPolicies =
- Arrays.stream(policies2)
- .filter(policy -> policy.inherited().get())
- .collect(Collectors.toSet());
-
- Assertions.assertEquals(1, nonInheritedPolicies.size());
- Assertions.assertEquals(2, inheritedPolicies.size());
- Assertions.assertTrue(nonInheritedPolicies.contains(policy3));
- Assertions.assertTrue(inheritedPolicies.contains(policy1));
- Assertions.assertTrue(inheritedPolicies.contains(policy2));
-
- // Test get associated policy for table
- Policy resultPolicy1 = table.supportsPolicies().getPolicy(policy1.name());
- Assertions.assertEquals(policy1, resultPolicy1);
- Assertions.assertTrue(resultPolicy1.inherited().get());
-
- Policy resultPolicy2 = table.supportsPolicies().getPolicy(policy2.name());
- Assertions.assertEquals(policy2, resultPolicy2);
- Assertions.assertTrue(resultPolicy2.inherited().get());
-
- Policy resultPolicy3 = table.supportsPolicies().getPolicy(policy3.name());
- Assertions.assertEquals(policy3, resultPolicy3);
- Assertions.assertFalse(resultPolicy3.inherited().get());
-
- // Test get objects associated with policy
- Assertions.assertEquals(1, policy1.associatedObjects().count());
- Assertions.assertEquals(
- relationalCatalog.name(), policy1.associatedObjects().objects()[0].name());
- Assertions.assertEquals(
- MetadataObject.Type.CATALOG, policy1.associatedObjects().objects()[0].type());
-
- Assertions.assertEquals(1, policy2.associatedObjects().count());
- Assertions.assertEquals(schema.name(), policy2.associatedObjects().objects()[0].name());
- Assertions.assertEquals(
- MetadataObject.Type.SCHEMA, policy2.associatedObjects().objects()[0].type());
-
- Assertions.assertEquals(1, policy3.associatedObjects().count());
- Assertions.assertEquals(table.name(), policy3.associatedObjects().objects()[0].name());
- Assertions.assertEquals(
- MetadataObject.Type.TABLE, policy3.associatedObjects().objects()[0].type());
- }
-
- @Test
- public void testAssociateAndDeletePolicies() {
- Policy policy1 =
- createCustomPolicy(
- GravitinoITUtils.genRandomName("policy_it_policy1"),
- ImmutableSet.of(MetadataObject.Type.CATALOG));
- Policy policy2 =
- createCustomPolicy(
- GravitinoITUtils.genRandomName("policy_it_policy2"),
- ImmutableSet.of(MetadataObject.Type.CATALOG));
- Policy policy3 =
- createCustomPolicy(
- GravitinoITUtils.genRandomName("policy_it_policy3"),
- ImmutableSet.of(MetadataObject.Type.CATALOG));
-
- String[] associatedPolicies =
- relationalCatalog
- .supportsPolicies()
- .associatePolicies(
- new String[] {policy1.name(), policy2.name()}, new String[] {policy3.name()});
-
- Assertions.assertEquals(2, associatedPolicies.length);
- Set<String> policyNames = Sets.newHashSet(associatedPolicies);
- Assertions.assertTrue(policyNames.contains(policy1.name()));
- Assertions.assertTrue(policyNames.contains(policy2.name()));
- Assertions.assertFalse(policyNames.contains(policy3.name()));
-
- Policy retrievedPolicy = relationalCatalog.supportsPolicies().getPolicy(policy2.name());
- Assertions.assertEquals(policy2.name(), retrievedPolicy.name());
- Assertions.assertEquals(policy2.comment(), retrievedPolicy.comment());
-
- boolean deleted = metalake.deletePolicy("null");
- Assertions.assertFalse(deleted);
-
- deleted = metalake.deletePolicy(policy1.name());
- Assertions.assertTrue(deleted);
- deleted = metalake.deletePolicy(policy1.name());
- Assertions.assertFalse(deleted);
-
- String[] associatedPolicies1 = relationalCatalog.supportsPolicies().listPolicies();
- Assertions.assertArrayEquals(new String[] {policy2.name()}, associatedPolicies1);
- }
-
- @Test
- public void testAssociatePoliciesToModel() {
- Policy policy1 =
- createCustomPolicy(
- GravitinoITUtils.genRandomName("policy_it_model_policy1"),
- ImmutableSet.of(MetadataObject.Type.CATALOG));
- Policy policy2 =
- createCustomPolicy(
- GravitinoITUtils.genRandomName("policy_it_model_policy2"),
- ImmutableSet.of(MetadataObject.Type.CATALOG));
- Policy policy3 =
- createCustomPolicy(
- GravitinoITUtils.genRandomName("policy_it_model_policy3"),
- ImmutableSet.of(MetadataObject.Type.CATALOG));
-
- // Associate policies to catalog
- modelCatalog.supportsPolicies().associatePolicies(new String[] {policy1.name()}, null);
-
- // Associate policies to schema
- modelSchema.supportsPolicies().associatePolicies(new String[] {policy2.name()}, null);
-
- // Associate policies to model
- model.supportsPolicies().associatePolicies(new String[] {policy3.name()}, null);
-
- // Test list associated policies for model
- String[] policies1 = model.supportsPolicies().listPolicies();
- Assertions.assertEquals(3, policies1.length);
- Set<String> policyNames = Sets.newHashSet(policies1);
- Assertions.assertTrue(policyNames.contains(policy1.name()));
- Assertions.assertTrue(policyNames.contains(policy2.name()));
- Assertions.assertTrue(policyNames.contains(policy3.name()));
-
- // Test list associated policies with details for model
- Policy[] policies2 = model.supportsPolicies().listPolicyInfos();
- Assertions.assertEquals(3, policies2.length);
-
- Set<Policy> nonInheritedPolicies =
- Arrays.stream(policies2)
- .filter(policy -> !policy.inherited().get())
- .collect(Collectors.toSet());
- Set<Policy> inheritedPolicies =
- Arrays.stream(policies2)
- .filter(policy -> policy.inherited().get())
- .collect(Collectors.toSet());
-
- Assertions.assertEquals(1, nonInheritedPolicies.size());
- Assertions.assertEquals(2, inheritedPolicies.size());
- Assertions.assertTrue(nonInheritedPolicies.contains(policy3));
- Assertions.assertTrue(inheritedPolicies.contains(policy1));
- Assertions.assertTrue(inheritedPolicies.contains(policy2));
-
- // Test get associated policy for model
- Policy resultPolicy1 = model.supportsPolicies().getPolicy(policy1.name());
- Assertions.assertEquals(policy1, resultPolicy1);
- Assertions.assertTrue(resultPolicy1.inherited().get());
-
- Policy resultPolicy2 = model.supportsPolicies().getPolicy(policy2.name());
- Assertions.assertEquals(policy2, resultPolicy2);
- Assertions.assertTrue(resultPolicy2.inherited().get());
-
- Policy resultPolicy3 = model.supportsPolicies().getPolicy(policy3.name());
- Assertions.assertEquals(policy3, resultPolicy3);
- Assertions.assertFalse(resultPolicy3.inherited().get());
-
- // Test get objects associated with policy
- Assertions.assertEquals(1, policy1.associatedObjects().count());
- Assertions.assertEquals(modelCatalog.name(), policy1.associatedObjects().objects()[0].name());
- Assertions.assertEquals(
- MetadataObject.Type.CATALOG, policy1.associatedObjects().objects()[0].type());
-
- Assertions.assertEquals(1, policy2.associatedObjects().count());
- Assertions.assertEquals(modelSchema.name(), policy2.associatedObjects().objects()[0].name());
- Assertions.assertEquals(
- MetadataObject.Type.SCHEMA, policy2.associatedObjects().objects()[0].type());
-
- Assertions.assertEquals(1, policy3.associatedObjects().count());
- Assertions.assertEquals(model.name(), policy3.associatedObjects().objects()[0].name());
- Assertions.assertEquals(
- MetadataObject.Type.MODEL, policy3.associatedObjects().objects()[0].type());
- }
-
- @Test
- public void testAssociatePoliciesToView() {
- Policy policy1 =
- createCustomPolicy(
- GravitinoITUtils.genRandomName("policy_it_view_policy1"),
- ImmutableSet.of(MetadataObject.Type.CATALOG));
- Policy policy2 =
- createCustomPolicy(
- GravitinoITUtils.genRandomName("policy_it_view_policy2"),
- ImmutableSet.of(MetadataObject.Type.SCHEMA));
- Policy policy3 =
- createCustomPolicy(
- GravitinoITUtils.genRandomName("policy_it_view_policy3"),
- ImmutableSet.of(MetadataObject.Type.VIEW));
-
- // Associate policies to catalog
- relationalCatalog.supportsPolicies().associatePolicies(new String[] {policy1.name()}, null);
-
- // Associate policies to schema
- schema.supportsPolicies().associatePolicies(new String[] {policy2.name()}, null);
-
- // Test associate policies to view
- String[] policies = viewPolicyOperations.associatePolicies(new String[] {policy3.name()}, null);
-
- Assertions.assertEquals(1, policies.length);
- Assertions.assertEquals(policy3.name(), policies[0]);
-
- // Test list associated policies for view
- String[] policies1 = viewPolicyOperations.listPolicies();
- Assertions.assertEquals(3, policies1.length);
- Set<String> policyNames = Sets.newHashSet(policies1);
- Assertions.assertTrue(policyNames.contains(policy1.name()));
- Assertions.assertTrue(policyNames.contains(policy2.name()));
- Assertions.assertTrue(policyNames.contains(policy3.name()));
-
- // Test list associated policies with details for view
- Policy[] policies2 = viewPolicyOperations.listPolicyInfos();
- Assertions.assertEquals(3, policies2.length);
-
- Set<String> nonInheritedPolicies =
- Arrays.stream(policies2)
- .filter(policy -> !policy.inherited().get())
- .map(Policy::name)
- .collect(Collectors.toSet());
- Set<String> inheritedPolicies =
- Arrays.stream(policies2)
- .filter(policy -> policy.inherited().get())
- .map(Policy::name)
- .collect(Collectors.toSet());
-
- Assertions.assertEquals(ImmutableSet.of(policy3.name()), nonInheritedPolicies);
- Assertions.assertEquals(ImmutableSet.of(policy1.name(), policy2.name()), inheritedPolicies);
-
- // Test get associated policy for view
- Policy resultPolicy1 = viewPolicyOperations.getPolicy(policy1.name());
- Assertions.assertEquals(policy1.name(), resultPolicy1.name());
- Assertions.assertTrue(resultPolicy1.inherited().get());
-
- Policy resultPolicy2 = viewPolicyOperations.getPolicy(policy2.name());
- Assertions.assertEquals(policy2.name(), resultPolicy2.name());
- Assertions.assertTrue(resultPolicy2.inherited().get());
-
- Policy resultPolicy3 = viewPolicyOperations.getPolicy(policy3.name());
- Assertions.assertEquals(policy3.name(), resultPolicy3.name());
- Assertions.assertFalse(resultPolicy3.inherited().get());
-
- // Test get objects associated with policy
- Assertions.assertEquals(1, policy1.associatedObjects().count());
- Assertions.assertEquals(
- relationalCatalog.name(), policy1.associatedObjects().objects()[0].name());
- Assertions.assertEquals(
- MetadataObject.Type.CATALOG, policy1.associatedObjects().objects()[0].type());
-
- Assertions.assertEquals(1, policy2.associatedObjects().count());
- Assertions.assertEquals(schema.name(), policy2.associatedObjects().objects()[0].name());
- Assertions.assertEquals(
- MetadataObject.Type.SCHEMA, policy2.associatedObjects().objects()[0].type());
-
- Assertions.assertEquals(1, policy3.associatedObjects().count());
- Assertions.assertEquals(view.name(), policy3.associatedObjects().objects()[0].name());
- Assertions.assertEquals(
- MetadataObject.Type.VIEW, policy3.associatedObjects().objects()[0].type());
-
- // Test disassociate policy from view
- String[] policies3 =
- viewPolicyOperations.associatePolicies(null, new String[] {policy3.name()});
- Assertions.assertEquals(0, policies3.length);
- Assertions.assertEquals(
- ImmutableSet.of(policy1.name(), policy2.name()),
- ImmutableSet.copyOf(viewPolicyOperations.listPolicies()));
- Assertions.assertEquals(0, policy3.associatedObjects().count());
- }
-
- @Test
- public void testAssociatePoliciesToFunction() {
- Policy policy1 =
- createCustomPolicy(
- GravitinoITUtils.genRandomName("policy_it_func_policy1"),
- ImmutableSet.of(MetadataObject.Type.CATALOG));
- Policy policy2 =
- createCustomPolicy(
- GravitinoITUtils.genRandomName("policy_it_func_policy2"),
- ImmutableSet.of(MetadataObject.Type.SCHEMA));
- Policy policy3 =
- createCustomPolicy(
- GravitinoITUtils.genRandomName("policy_it_func_policy3"),
- ImmutableSet.of(MetadataObject.Type.FUNCTION));
-
- // Associate policies to catalog
- relationalCatalog.supportsPolicies().associatePolicies(new String[] {policy1.name()}, null);
-
- // Associate policies to schema
- schema.supportsPolicies().associatePolicies(new String[] {policy2.name()}, null);
-
- // Test associate policies to function
- String[] policies =
- functionPolicyOperations.associatePolicies(new String[] {policy3.name()}, null);
-
- Assertions.assertEquals(1, policies.length);
- Assertions.assertEquals(policy3.name(), policies[0]);
-
- // Test list associated policies for function
- String[] policies1 = functionPolicyOperations.listPolicies();
- Assertions.assertEquals(3, policies1.length);
- Set<String> policyNames = Sets.newHashSet(policies1);
- Assertions.assertTrue(policyNames.contains(policy1.name()));
- Assertions.assertTrue(policyNames.contains(policy2.name()));
- Assertions.assertTrue(policyNames.contains(policy3.name()));
-
- // Test list associated policies with details for function
- Policy[] policies2 = functionPolicyOperations.listPolicyInfos();
- Assertions.assertEquals(3, policies2.length);
-
- Set<String> nonInheritedPolicies =
- Arrays.stream(policies2)
- .filter(policy -> !policy.inherited().get())
- .map(Policy::name)
- .collect(Collectors.toSet());
- Set<String> inheritedPolicies =
- Arrays.stream(policies2)
- .filter(policy -> policy.inherited().get())
- .map(Policy::name)
- .collect(Collectors.toSet());
-
- Assertions.assertEquals(ImmutableSet.of(policy3.name()), nonInheritedPolicies);
- Assertions.assertEquals(ImmutableSet.of(policy1.name(), policy2.name()), inheritedPolicies);
-
- // Test get associated policy for function
- Policy resultPolicy1 = functionPolicyOperations.getPolicy(policy1.name());
- Assertions.assertEquals(policy1.name(), resultPolicy1.name());
- Assertions.assertTrue(resultPolicy1.inherited().get());
-
- Policy resultPolicy2 = functionPolicyOperations.getPolicy(policy2.name());
- Assertions.assertEquals(policy2.name(), resultPolicy2.name());
- Assertions.assertTrue(resultPolicy2.inherited().get());
-
- Policy resultPolicy3 = functionPolicyOperations.getPolicy(policy3.name());
- Assertions.assertEquals(policy3.name(), resultPolicy3.name());
- Assertions.assertFalse(resultPolicy3.inherited().get());
-
- // Test get objects associated with policy
- Assertions.assertEquals(1, policy1.associatedObjects().count());
- Assertions.assertEquals(
- relationalCatalog.name(), policy1.associatedObjects().objects()[0].name());
- Assertions.assertEquals(
- MetadataObject.Type.CATALOG, policy1.associatedObjects().objects()[0].type());
-
- Assertions.assertEquals(1, policy2.associatedObjects().count());
- Assertions.assertEquals(schema.name(), policy2.associatedObjects().objects()[0].name());
- Assertions.assertEquals(
- MetadataObject.Type.SCHEMA, policy2.associatedObjects().objects()[0].type());
-
- Assertions.assertEquals(1, policy3.associatedObjects().count());
- Assertions.assertEquals(function.name(), policy3.associatedObjects().objects()[0].name());
- Assertions.assertEquals(
- MetadataObject.Type.FUNCTION, policy3.associatedObjects().objects()[0].type());
-
- // Test disassociate policy from function
- String[] policies3 =
- functionPolicyOperations.associatePolicies(null, new String[] {policy3.name()});
- Assertions.assertEquals(0, policies3.length);
- Assertions.assertEquals(
- ImmutableSet.of(policy1.name(), policy2.name()),
- ImmutableSet.copyOf(functionPolicyOperations.listPolicies()));
- Assertions.assertEquals(0, policy3.associatedObjects().count());
- }
-
- @Test
- public void testCascadeDeleteView() {
- // Create a policy that supports VIEW
- Policy policy =
- createCustomPolicy(
- GravitinoITUtils.genRandomName("policy_it_cascade_view"),
- ImmutableSet.of(MetadataObject.Type.VIEW));
-
- // Create a view in the existing schema
- String viewName = GravitinoITUtils.genRandomName("policy_it_cascade_view");
- NameIdentifier viewIdent = NameIdentifier.of(schema.name(), viewName);
- Assertions.assertFalse(relationalCatalog.asViewCatalog().viewExists(viewIdent));
- View cascadeView =
- relationalCatalog
- .asViewCatalog()
- .createView(
- viewIdent,
- "comment",
- new Column[] {
- Column.of("col1", Types.IntegerType.get()),
- Column.of("col2", Types.StringType.get())
- },
- new SQLRepresentation[] {
- SQLRepresentation.builder()
- .withDialect(Dialects.HIVE)
- .withSql("SELECT col1, col2 FROM " + table.name())
- .build()
- },
- null,
- null,
- Collections.emptyMap());
-
- // Associate the policy with the view
- SupportsPolicies cascadeViewPolicyOperations =
- policyOperations(
- relationalCatalog,
- schema,
- cascadeView.name(),
- MetadataObject.Type.VIEW,
- policyRestClient);
- cascadeViewPolicyOperations.associatePolicies(new String[] {policy.name()}, null);
-
- // Verify the policy is associated with the view
- Policy fetchedPolicy = metalake.getPolicy(policy.name());
- Assertions.assertEquals(1, fetchedPolicy.associatedObjects().count());
- Assertions.assertEquals(
- cascadeView.name(), fetchedPolicy.associatedObjects().objects()[0].name());
- Assertions.assertEquals(
- MetadataObject.Type.VIEW, fetchedPolicy.associatedObjects().objects()[0].type());
-
- // Delete the view — this should cascade-delete policy relations
- Assertions.assertTrue(relationalCatalog.asViewCatalog().dropView(viewIdent));
-
- // Verify the policy's associated objects are cleaned up
- fetchedPolicy = metalake.getPolicy(policy.name());
- Assertions.assertEquals(0, fetchedPolicy.associatedObjects().count());
- }
-
- @Test
- public void testCascadeDeleteFunction() {
- // Create a policy that supports FUNCTION
- Policy policy =
- createCustomPolicy(
- GravitinoITUtils.genRandomName("policy_it_cascade_func"),
- ImmutableSet.of(MetadataObject.Type.FUNCTION));
-
- // Create a function in the existing schema
- String funcName = GravitinoITUtils.genRandomName("policy_it_cascade_func");
- NameIdentifier funcIdent = NameIdentifier.of(schema.name(), funcName);
- Assertions.assertFalse(relationalCatalog.asFunctionCatalog().functionExists(funcIdent));
- FunctionParam param = FunctionParams.of("x", Types.IntegerType.get());
- FunctionImpl impl = FunctionImpls.ofSql(FunctionImpl.RuntimeType.SPARK, "SELECT x + 1");
- FunctionDefinition definition =
- FunctionDefinitions.of(
- new FunctionParam[] {param}, Types.IntegerType.get(), new FunctionImpl[] {impl});
- Function cascadeFunc =
- relationalCatalog
- .asFunctionCatalog()
- .registerFunction(
- funcIdent,
- "comment",
- FunctionType.SCALAR,
- true,
- new FunctionDefinition[] {definition});
-
- // Associate the policy with the function
- SupportsPolicies cascadeFunctionPolicyOperations =
- policyOperations(
- relationalCatalog,
- schema,
- cascadeFunc.name(),
- MetadataObject.Type.FUNCTION,
- policyRestClient);
- cascadeFunctionPolicyOperations.associatePolicies(new String[] {policy.name()}, null);
-
- // Verify the policy is associated with the function
- Policy fetchedPolicy = metalake.getPolicy(policy.name());
- Assertions.assertEquals(1, fetchedPolicy.associatedObjects().count());
- Assertions.assertEquals(
- cascadeFunc.name(), fetchedPolicy.associatedObjects().objects()[0].name());
- Assertions.assertEquals(
- MetadataObject.Type.FUNCTION, fetchedPolicy.associatedObjects().objects()[0].type());
-
- // Delete the function — this should cascade-delete policy relations
- Assertions.assertTrue(relationalCatalog.asFunctionCatalog().dropFunction(funcIdent));
-
- // Verify the policy's associated objects are cleaned up
- fetchedPolicy = metalake.getPolicy(policy.name());
- Assertions.assertEquals(0, fetchedPolicy.associatedObjects().count());
- }
-
- @Test
- public void testCascadeDeleteSchemaWithViewAndFunction() {
- // Create a policy that supports VIEW and FUNCTION
- Policy policy =
- metalake.createPolicy(
- GravitinoITUtils.genRandomName("policy_it_cascade_schema"),
- "custom",
- "test comment",
- true,
- PolicyContents.custom(
- ImmutableMap.of("rule1", "value1"),
- ImmutableSet.of(MetadataObject.Type.VIEW, MetadataObject.Type.FUNCTION),
- null));
-
- // Create a new schema
- String cascadeSchemaName = GravitinoITUtils.genRandomName("policy_it_cascade_schema");
- Assertions.assertFalse(relationalCatalog.asSchemas().schemaExists(cascadeSchemaName));
- Schema cascadeSchema =
- relationalCatalog
- .asSchemas()
- .createSchema(cascadeSchemaName, "comment", Collections.emptyMap());
-
- // Create a view in the new schema
- String cascadeViewName = GravitinoITUtils.genRandomName("policy_it_cascade_schema_view");
- NameIdentifier cascadeViewIdent = NameIdentifier.of(cascadeSchemaName, cascadeViewName);
- View cascadeView =
- relationalCatalog
- .asViewCatalog()
- .createView(
- cascadeViewIdent,
- "comment",
- new Column[] {
- Column.of("col1", Types.IntegerType.get()),
- Column.of("col2", Types.StringType.get())
- },
- new SQLRepresentation[] {
- SQLRepresentation.builder()
- .withDialect(Dialects.HIVE)
- .withSql("SELECT col1, col2 FROM " + table.name())
- .build()
- },
- null,
- null,
- Collections.emptyMap());
-
- // Create a function in the new schema
- String cascadeFuncName = GravitinoITUtils.genRandomName("policy_it_cascade_schema_func");
- NameIdentifier cascadeFuncIdent = NameIdentifier.of(cascadeSchemaName, cascadeFuncName);
- FunctionParam param = FunctionParams.of("x", Types.IntegerType.get());
- FunctionImpl impl = FunctionImpls.ofSql(FunctionImpl.RuntimeType.SPARK, "SELECT x + 1");
- FunctionDefinition definition =
- FunctionDefinitions.of(
- new FunctionParam[] {param}, Types.IntegerType.get(), new FunctionImpl[] {impl});
- Function cascadeFunc =
- relationalCatalog
- .asFunctionCatalog()
- .registerFunction(
- cascadeFuncIdent,
- "comment",
- FunctionType.SCALAR,
- true,
- new FunctionDefinition[] {definition});
-
- // Associate the policy with the view and function
- SupportsPolicies cascadeViewPolicyOperations =
- policyOperations(
- relationalCatalog,
- cascadeSchema,
- cascadeView.name(),
- MetadataObject.Type.VIEW,
- policyRestClient);
- SupportsPolicies cascadeFunctionPolicyOperations =
- policyOperations(
- relationalCatalog,
- cascadeSchema,
- cascadeFunc.name(),
- MetadataObject.Type.FUNCTION,
- policyRestClient);
- cascadeViewPolicyOperations.associatePolicies(new String[] {policy.name()}, null);
- cascadeFunctionPolicyOperations.associatePolicies(new String[] {policy.name()}, null);
-
- // Verify the policy is associated with both view and function
- Policy fetchedPolicy = metalake.getPolicy(policy.name());
- Assertions.assertEquals(2, fetchedPolicy.associatedObjects().count());
- Set<String> associatedNames =
- Arrays.stream(fetchedPolicy.associatedObjects().objects())
- .map(MetadataObject::name)
- .collect(Collectors.toSet());
- Assertions.assertTrue(associatedNames.contains(cascadeViewName));
- Assertions.assertTrue(associatedNames.contains(cascadeFuncName));
-
- // Drop the schema with cascade — this should cascade-delete policy relations
- Assertions.assertTrue(relationalCatalog.asSchemas().dropSchema(cascadeSchemaName, true));
-
- // Verify the policy's associated objects are cleaned up
- fetchedPolicy = metalake.getPolicy(policy.name());
- Assertions.assertEquals(0, fetchedPolicy.associatedObjects().count());
- }
-
- @Test
- public void testCascadeDeleteCatalogWithViewAndFunction() {
- // Create a policy that supports VIEW and FUNCTION
- Policy policy =
- metalake.createPolicy(
- GravitinoITUtils.genRandomName("policy_it_cascade_catalog"),
- "custom",
- "test comment",
- true,
- PolicyContents.custom(
- ImmutableMap.of("rule1", "value1"),
- ImmutableSet.of(MetadataObject.Type.VIEW, MetadataObject.Type.FUNCTION),
- null));
-
- // Create a new catalog for cascade test
- String cascadeCatalogName = GravitinoITUtils.genRandomName("policy_it_cascade_catalog");
- Assertions.assertFalse(metalake.catalogExists(cascadeCatalogName));
- String hmsUri =
- String.format(
- "thrift://%s:%d",
- containerSuite.getHiveContainer().getContainerIpAddress(),
- HiveContainer.HIVE_METASTORE_PORT);
- Catalog cascadeCatalog =
- metalake.createCatalog(
- cascadeCatalogName,
- Catalog.Type.RELATIONAL,
- "hive",
- "comment",
- ImmutableMap.of("metastore.uris", hmsUri));
-
- // Create a schema in the cascade catalog
- String cascadeSchemaName = GravitinoITUtils.genRandomName("policy_it_cascade_catalog_schema");
- Assertions.assertFalse(cascadeCatalog.asSchemas().schemaExists(cascadeSchemaName));
- Schema cascadeSchema =
- cascadeCatalog
- .asSchemas()
- .createSchema(cascadeSchemaName, "comment", Collections.emptyMap());
-
- // Create a view in the cascade catalog
- String cascadeViewName = GravitinoITUtils.genRandomName("policy_it_cascade_catalog_view");
- NameIdentifier cascadeViewIdent = NameIdentifier.of(cascadeSchemaName, cascadeViewName);
- View cascadeView =
- cascadeCatalog
- .asViewCatalog()
- .createView(
- cascadeViewIdent,
- "comment",
- new Column[] {
- Column.of("col1", Types.IntegerType.get()),
- Column.of("col2", Types.StringType.get())
- },
- new SQLRepresentation[] {
- SQLRepresentation.builder().withDialect(Dialects.HIVE).withSql("SELECT 1").build()
- },
- null,
- null,
- Collections.emptyMap());
-
- // Create a function in the cascade catalog
- String cascadeFuncName = GravitinoITUtils.genRandomName("policy_it_cascade_catalog_func");
- NameIdentifier cascadeFuncIdent = NameIdentifier.of(cascadeSchemaName, cascadeFuncName);
- FunctionParam param = FunctionParams.of("x", Types.IntegerType.get());
- FunctionImpl impl = FunctionImpls.ofSql(FunctionImpl.RuntimeType.SPARK, "SELECT x + 1");
- FunctionDefinition definition =
- FunctionDefinitions.of(
- new FunctionParam[] {param}, Types.IntegerType.get(), new FunctionImpl[] {impl});
- Function cascadeFunc =
- cascadeCatalog
- .asFunctionCatalog()
- .registerFunction(
- cascadeFuncIdent,
- "comment",
- FunctionType.SCALAR,
- true,
- new FunctionDefinition[] {definition});
-
- // Associate the policy with the view and function
- SupportsPolicies cascadeViewPolicyOperations =
- policyOperations(
- cascadeCatalog,
- cascadeSchema,
- cascadeView.name(),
- MetadataObject.Type.VIEW,
- policyRestClient);
- SupportsPolicies cascadeFunctionPolicyOperations =
- policyOperations(
- cascadeCatalog,
- cascadeSchema,
- cascadeFunc.name(),
- MetadataObject.Type.FUNCTION,
- policyRestClient);
- cascadeViewPolicyOperations.associatePolicies(new String[] {policy.name()}, null);
- cascadeFunctionPolicyOperations.associatePolicies(new String[] {policy.name()}, null);
-
- // Verify the policy is associated with both view and function
- Policy fetchedPolicy = metalake.getPolicy(policy.name());
- Assertions.assertEquals(2, fetchedPolicy.associatedObjects().count());
- Set<String> associatedNames =
- Arrays.stream(fetchedPolicy.associatedObjects().objects())
- .map(MetadataObject::name)
- .collect(Collectors.toSet());
- Assertions.assertTrue(associatedNames.contains(cascadeViewName));
- Assertions.assertTrue(associatedNames.contains(cascadeFuncName));
-
- // Drop the catalog with cascade — this should cascade-delete policy relations
- Assertions.assertTrue(metalake.dropCatalog(cascadeCatalogName, true));
-
- // Verify the policy's associated objects are cleaned up
- fetchedPolicy = metalake.getPolicy(policy.name());
- Assertions.assertEquals(0, fetchedPolicy.associatedObjects().count());
- }
-
- private Policy createCustomPolicy(String name, Set<MetadataObject.Type> types) {
- return metalake.createPolicy(
- name,
- "custom",
- "test comment",
- true,
- PolicyContents.custom(ImmutableMap.of("rule1", "value1"), types, null));
- }
-
- private static SupportsPolicies policyOperations(
- Catalog catalog,
- Schema schema,
- String objectName,
- MetadataObject.Type objectType,
- RESTClient restClient) {
- MetadataObject metadataObject =
- MetadataObjectDTO.builder()
- .withParent(String.join(".", catalog.name(), schema.name()))
- .withName(objectName)
- .withType(objectType)
- .build();
- return new RestPolicyOperations(metalakeName, metadataObject, restClient);
- }
-
- private static final class RestPolicyOperations implements SupportsPolicies {
- private final RESTClient restClient;
- private final String requestPath;
-
- private RestPolicyOperations(
- String metalakeName, MetadataObject metadataObject, RESTClient restClient) {
- this.restClient = restClient;
- this.requestPath =
- String.format(
- "api/metalakes/%s/objects/%s/%s/policies",
- RESTUtils.encodeString(metalakeName),
- metadataObject.type().name().toLowerCase(Locale.ROOT),
- RESTUtils.encodeString(metadataObject.fullName()));
- }
-
- @Override
- public String[] listPolicies() {
- NameListResponse response =
- restClient.get(
- requestPath,
- NameListResponse.class,
- Collections.emptyMap(),
- ErrorHandlers.policyErrorHandler());
- response.validate();
- return response.getNames();
- }
-
- @Override
- public Policy[] listPolicyInfos() {
- PolicyListResponse response =
- restClient.get(
- requestPath,
- ImmutableMap.of("details", "true"),
- PolicyListResponse.class,
- Collections.emptyMap(),
- ErrorHandlers.policyErrorHandler());
- response.validate();
- return response.getPolicies();
- }
-
- @Override
- public Policy getPolicy(String name) throws NoSuchPolicyException {
- PolicyResponse response =
- restClient.get(
- requestPath + "/" + RESTUtils.encodeString(name),
- PolicyResponse.class,
- Collections.emptyMap(),
- ErrorHandlers.policyErrorHandler());
- response.validate();
- return response.getPolicy();
- }
-
- @Override
- public String[] associatePolicies(String[] policiesToAdd, String[] policiesToRemove) {
- PoliciesAssociateRequest request =
- new PoliciesAssociateRequest(policiesToAdd, policiesToRemove);
- request.validate();
-
- NameListResponse response =
- restClient.post(
- requestPath,
- request,
- NameListResponse.class,
- Collections.emptyMap(),
- ErrorHandlers.policyErrorHandler());
- response.validate();
- return response.getNames();
- }
- }
}
diff --git a/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/authorization/PolicyAuthorizationIT.java b/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/authorization/PolicyAuthorizationIT.java
index 5776ce1b9f..dc8ec96d0b 100644
--- a/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/authorization/PolicyAuthorizationIT.java
+++ b/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/authorization/PolicyAuthorizationIT.java
@@ -25,7 +25,6 @@ import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import java.io.IOException;
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -34,7 +33,6 @@ import org.apache.gravitino.Catalog;
import org.apache.gravitino.MetadataObject;
import org.apache.gravitino.MetadataObjects;
import org.apache.gravitino.NameIdentifier;
-import org.apache.gravitino.authorization.Owner;
import org.apache.gravitino.authorization.Privileges;
import org.apache.gravitino.authorization.SecurableObject;
import org.apache.gravitino.authorization.SecurableObjects;
@@ -44,7 +42,6 @@ import org.apache.gravitino.integration.test.container.ContainerSuite;
import org.apache.gravitino.integration.test.container.HiveContainer;
import org.apache.gravitino.policy.PolicyChange;
import org.apache.gravitino.policy.PolicyContents;
-import org.apache.gravitino.policy.SupportsPolicies;
import org.apache.gravitino.rel.Column;
import org.apache.gravitino.rel.TableCatalog;
import org.apache.gravitino.rel.types.Types;
@@ -215,210 +212,6 @@ public class PolicyAuthorizationIT extends BaseRestApiAuthorizationIT {
metalakeLoadByNormalUser.alterPolicy("policy2", PolicyChange.updateComment("222"));
}
- @Test
- @Order(6)
- public void testAssociatePolicy() {
- GravitinoMetalake gravitinoMetalake = client.loadMetalake(METALAKE);
- GravitinoMetalake metalakeLoadByNormalUser = normalUserClient.loadMetalake(METALAKE);
- SupportsPolicies supportsPolicies =
- gravitinoMetalake
- .loadCatalog(CATALOG)
- .asTableCatalog()
- .loadTable(NameIdentifier.of(SCHEMA, "table1"))
- .supportsPolicies();
- gravitinoMetalake.grantPrivilegesToRole(
- role,
- MetadataObjects.of(ImmutableList.of(CATALOG, SCHEMA), MetadataObject.Type.SCHEMA),
- ImmutableList.of(Privileges.SelectTable.allow(), Privileges.UseSchema.allow()));
- SupportsPolicies supportsPoliciesByNormalUser =
- metalakeLoadByNormalUser
- .loadCatalog(CATALOG)
- .asTableCatalog()
- .loadTable(NameIdentifier.of(SCHEMA, "table1"))
- .supportsPolicies();
- supportsPolicies.associatePolicies(new String[] {"policy1"}, new String[] {});
- assertThrows(
- "Can not access metadata.",
- ForbiddenException.class,
- () -> {
- supportsPoliciesByNormalUser.associatePolicies(new String[] {"policy1"}, new String[] {});
- });
- gravitinoMetalake.grantPrivilegesToRole(
- role,
- MetadataObjects.of(ImmutableList.of(METALAKE), MetadataObject.Type.METALAKE),
- ImmutableSet.of(Privileges.CreateTable.allow()));
- TableCatalog tableCatalog =
- normalUserClient.loadMetalake(METALAKE).loadCatalog(CATALOG).asTableCatalog();
- tableCatalog.createTable(
- NameIdentifier.of(SCHEMA, "table2"), createColumns(), "test", new HashMap<>());
- tableCatalog.createTable(
- NameIdentifier.of(SCHEMA, "table3"), createColumns(), "test", new HashMap<>());
- metalakeLoadByNormalUser
- .loadCatalog(CATALOG)
- .asTableCatalog()
- .loadTable(NameIdentifier.of(SCHEMA, "table2"))
- .supportsPolicies()
- .associatePolicies(new String[] {"policy2"}, new String[] {});
-
- metalakeLoadByNormalUser
- .loadCatalog(CATALOG)
- .asTableCatalog()
- .loadTable(NameIdentifier.of(SCHEMA, "table3"))
- .supportsPolicies()
- .associatePolicies(new String[] {"policy2"}, new String[] {});
- }
-
- @Test
- @Order(7)
- public void testListPolicyForTable() {
- GravitinoMetalake gravitinoMetalake = client.loadMetalake(METALAKE);
- GravitinoMetalake gravitinoMetalakeLoadByNormalUser = normalUserClient.loadMetalake(METALAKE);
- String[] policies =
- gravitinoMetalake
- .loadCatalog(CATALOG)
- .asTableCatalog()
- .loadTable(NameIdentifier.of(SCHEMA, "table1"))
- .supportsPolicies()
- .listPolicies();
- Assertions.assertArrayEquals(new String[] {"policy1"}, policies);
- policies =
- gravitinoMetalake
- .loadCatalog(CATALOG)
- .asTableCatalog()
- .loadTable(NameIdentifier.of(SCHEMA, "table2"))
- .supportsPolicies()
- .listPolicies();
- Assertions.assertArrayEquals(new String[] {"policy2"}, policies);
- policies =
- gravitinoMetalake
- .loadCatalog(CATALOG)
- .asTableCatalog()
- .loadTable(NameIdentifier.of(SCHEMA, "table3"))
- .supportsPolicies()
- .listPolicies();
- Assertions.assertArrayEquals(new String[] {"policy2"}, policies);
- policies =
- gravitinoMetalakeLoadByNormalUser
- .loadCatalog(CATALOG)
- .asTableCatalog()
- .loadTable(NameIdentifier.of(SCHEMA, "table1"))
- .supportsPolicies()
- .listPolicies();
- Assertions.assertArrayEquals(new String[] {}, policies);
- policies =
- gravitinoMetalakeLoadByNormalUser
- .loadCatalog(CATALOG)
- .asTableCatalog()
- .loadTable(NameIdentifier.of(SCHEMA, "table2"))
- .supportsPolicies()
- .listPolicies();
- Assertions.assertArrayEquals(new String[] {"policy2"}, policies);
- policies =
- gravitinoMetalakeLoadByNormalUser
- .loadCatalog(CATALOG)
- .asTableCatalog()
- .loadTable(NameIdentifier.of(SCHEMA, "table3"))
- .supportsPolicies()
- .listPolicies();
- Assertions.assertArrayEquals(new String[] {"policy2"}, policies);
- }
-
- @Test
- @Order(8)
- public void testGetPolicyForTable() {
- GravitinoMetalake gravitinoMetalake = client.loadMetalake(METALAKE);
- GravitinoMetalake gravitinoMetalakeLoadByNormalUser = normalUserClient.loadMetalake(METALAKE);
- gravitinoMetalake
- .loadCatalog(CATALOG)
- .asTableCatalog()
- .loadTable(NameIdentifier.of(SCHEMA, "table1"))
- .supportsPolicies()
- .getPolicy("policy1");
- gravitinoMetalake
- .loadCatalog(CATALOG)
- .asTableCatalog()
- .loadTable(NameIdentifier.of(SCHEMA, "table2"))
- .supportsPolicies()
- .getPolicy("policy2");
- gravitinoMetalake
- .loadCatalog(CATALOG)
- .asTableCatalog()
- .loadTable(NameIdentifier.of(SCHEMA, "table3"))
- .supportsPolicies()
- .getPolicy("policy2");
- assertThrows(
- "Can not access metadata.",
- ForbiddenException.class,
- () -> {
- gravitinoMetalakeLoadByNormalUser
- .loadCatalog(CATALOG)
- .asTableCatalog()
- .loadTable(NameIdentifier.of(SCHEMA, "table1"))
- .supportsPolicies()
- .getPolicy("policy1");
- });
-
- gravitinoMetalakeLoadByNormalUser
- .loadCatalog(CATALOG)
- .asTableCatalog()
- .loadTable(NameIdentifier.of(SCHEMA, "table2"))
- .supportsPolicies()
- .getPolicy("policy2");
- gravitinoMetalakeLoadByNormalUser
- .loadCatalog(CATALOG)
- .asTableCatalog()
- .loadTable(NameIdentifier.of(SCHEMA, "table3"))
- .supportsPolicies()
- .getPolicy("policy2");
- }
-
- @Test
- @Order(9)
- public void testListObjForPolicy() {
- GravitinoMetalake gravitinoMetalake = client.loadMetalake(METALAKE);
- GravitinoMetalake gravitinoMetalakeLoadByNormalUser = normalUserClient.loadMetalake(METALAKE);
- String[] tables =
- Arrays.stream(
- gravitinoMetalakeLoadByNormalUser
- .getPolicy("policy2")
- .associatedObjects()
- .objects())
- .map(MetadataObject::name)
- .toList()
- .toArray(new String[0]);
- Arrays.sort(tables);
- Assertions.assertArrayEquals(new String[] {"table2", "table3"}, tables);
- MetadataObject metadataObject =
- MetadataObjects.of(ImmutableList.of(CATALOG, SCHEMA, "table2"), MetadataObject.Type.TABLE);
- gravitinoMetalake.setOwner(metadataObject, USER, Owner.Type.USER);
- gravitinoMetalake.grantPrivilegesToRole(
- role, metadataObject, ImmutableSet.of(Privileges.SelectTable.deny()));
- tables =
- Arrays.stream(
- gravitinoMetalakeLoadByNormalUser
- .getPolicy("policy2")
- .associatedObjects()
- .objects())
- .map(MetadataObject::name)
- .toList()
- .toArray(new String[0]);
- Arrays.sort(tables);
- Assertions.assertArrayEquals(new String[] {"table3"}, tables);
- assertThrows(
- "Can not access metadata.",
- ForbiddenException.class,
- () -> {
- gravitinoMetalakeLoadByNormalUser.getPolicy("policy1").associatedObjects().objects();
- });
- tables =
- Arrays.stream(gravitinoMetalake.getPolicy("policy1").associatedObjects().objects())
- .map(MetadataObject::name)
- .toList()
- .toArray(new String[0]);
- Arrays.sort(tables);
- Assertions.assertArrayEquals(new String[] {"table1"}, tables);
- }
-
@Test
@Order(10)
public void testDropPolicy() {
diff --git a/common/src/main/java/org/apache/gravitino/dto/requests/PoliciesAssociateRequest.java b/common/src/main/java/org/apache/gravitino/dto/requests/PoliciesAssociateRequest.java
deleted file mode 100644
index 6fb44c090d..0000000000
--- a/common/src/main/java/org/apache/gravitino/dto/requests/PoliciesAssociateRequest.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * 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.dto.requests;
-
-import com.fasterxml.jackson.annotation.JsonProperty;
-import com.google.common.base.Preconditions;
-import lombok.EqualsAndHashCode;
-import lombok.Getter;
-import lombok.ToString;
-import org.apache.commons.lang3.StringUtils;
-import org.apache.gravitino.rest.RESTRequest;
-
-/** Represents a request to associate policies. */
-@Getter
-@EqualsAndHashCode
-@ToString
-public class PoliciesAssociateRequest implements RESTRequest {
-
- @JsonProperty("policiesToAdd")
- private final String[] policiesToAdd;
-
- @JsonProperty("policiesToRemove")
- private final String[] policiesToRemove;
-
- /**
- * Creates a new PoliciesAssociateRequest.
- *
- * @param policiesToAdd The policies to add.
- * @param policiesToRemove The policies to remove.
- */
- public PoliciesAssociateRequest(String[] policiesToAdd, String[] policiesToRemove) {
- this.policiesToAdd = policiesToAdd;
- this.policiesToRemove = policiesToRemove;
- }
-
- /** This is the constructor that is used by Jackson deserializer */
- private PoliciesAssociateRequest() {
- this(null, null);
- }
-
- /**
- * Validates the request.
- *
- * @throws IllegalArgumentException If the request is invalid, this exception is thrown.
- */
- @Override
- public void validate() throws IllegalArgumentException {
- Preconditions.checkArgument(
- policiesToAdd != null || policiesToRemove != null,
- "policiesToAdd and policiesToRemove cannot both be null");
-
- if (policiesToAdd != null) {
- for (String policy : policiesToAdd) {
- Preconditions.checkArgument(
- StringUtils.isNotBlank(policy),
- "policiesToAdd must not contain null or empty policy names");
- }
- }
-
- if (policiesToRemove != null) {
- for (String policy : policiesToRemove) {
- Preconditions.checkArgument(
- StringUtils.isNotBlank(policy),
- "policiesToRemove must not contain null or empty policy names");
- }
- }
- }
-}
diff --git a/core/src/main/java/org/apache/gravitino/RelationQuery.java b/core/src/main/java/org/apache/gravitino/RelationQuery.java
index 2947a2ab76..7c9cd579d7 100644
--- a/core/src/main/java/org/apache/gravitino/RelationQuery.java
+++ b/core/src/main/java/org/apache/gravitino/RelationQuery.java
@@ -27,9 +27,7 @@ import javax.annotation.Nullable;
* relation edge, and the returned entities come from the opposite endpoint.
*
* <p>For reverse lookups, callers still use the same relation type. For example, querying all
- * metadata objects that have a specific policy uses {@link
- * SupportsRelationOperations.Type#POLICY_METADATA_OBJECT_REL} with the policy as the anchor entity,
- * and querying all metadata objects that have a specific tag uses {@link
+ * metadata objects that have a specific tag uses {@link
* SupportsRelationOperations.Type#TAG_METADATA_OBJECT_REL} with the tag as the anchor entity.
*
* <p>The optional relation value is an exact string value carried by the relation edge, such as a
diff --git a/core/src/main/java/org/apache/gravitino/SupportsRelationOperations.java b/core/src/main/java/org/apache/gravitino/SupportsRelationOperations.java
index 6158c6c3bd..97e0105873 100644
--- a/core/src/main/java/org/apache/gravitino/SupportsRelationOperations.java
+++ b/core/src/main/java/org/apache/gravitino/SupportsRelationOperations.java
@@ -39,8 +39,6 @@ public interface SupportsRelationOperations {
ROLE_USER_REL,
/** Role and group relationship */
ROLE_GROUP_REL,
- /** Policy and metadata object relationship */
- POLICY_METADATA_OBJECT_REL,
/** Metadata object to tag relationship */
TAG_METADATA_OBJECT_REL,
/** Policy to tag relationship */
@@ -220,11 +218,10 @@ public interface SupportsRelationOperations {
* removing another set of relation targets. Compatibility adapter for {@link
* #updateEntityRelations(RelationUpdate)}.
*
- * <p>For {@link Type#POLICY_METADATA_OBJECT_REL} and {@link Type#TAG_METADATA_OBJECT_REL}, this
- * update adapter treats the source entity as the metadata object and the destination identifiers
- * as policies or tags. Reverse traversal is done by {@link
- * #listEntitiesByRelation(RelationQuery)} using the same relation type with the policy or tag as
- * the query anchor.
+ * <p>For {@link Type#TAG_METADATA_OBJECT_REL}, this update adapter treats the source entity as
+ * the metadata object and the destination identifiers as tags. Reverse traversal is done by
+ * {@link #listEntitiesByRelation(RelationQuery)} using the same relation type with the tag as the
+ * query anchor.
*
* @param <E> The type of the entity returned in the list, which represents the final state of
* related entities.
@@ -289,8 +286,6 @@ public interface SupportsRelationOperations {
private static Entity.EntityType relationUpdateTargetType(
Type relType, Entity.EntityType srcEntityType) {
switch (relType) {
- case POLICY_METADATA_OBJECT_REL:
- return Entity.EntityType.POLICY;
case TAG_METADATA_OBJECT_REL:
return Entity.EntityType.TAG;
case POLICY_TAG_REL:
diff --git a/core/src/main/java/org/apache/gravitino/hook/PolicyHookDispatcher.java b/core/src/main/java/org/apache/gravitino/hook/PolicyHookDispatcher.java
index 0b2ee2e34b..34394357b3 100644
--- a/core/src/main/java/org/apache/gravitino/hook/PolicyHookDispatcher.java
+++ b/core/src/main/java/org/apache/gravitino/hook/PolicyHookDispatcher.java
@@ -100,11 +100,6 @@ public class PolicyHookDispatcher implements PolicyDispatcher {
return dispatcher.deletePolicy(metalake, policyName);
}
- @Override
- public MetadataObject[] listMetadataObjectsForPolicy(String metalake, String policyName) {
- return dispatcher.listMetadataObjectsForPolicy(metalake, policyName);
- }
-
@Override
public RelationalEntity<?>[] listTagAssociationsForPolicy(String metalake, String policyName) {
return dispatcher.listTagAssociationsForPolicy(metalake, policyName);
@@ -115,20 +110,4 @@ public class PolicyHookDispatcher implements PolicyDispatcher {
String metalake, MetadataObject metadataObject) {
return dispatcher.listPolicyInfosForMetadataObject(metalake, metadataObject);
}
-
- @Override
- public String[] associatePoliciesForMetadataObject(
- String metalake,
- MetadataObject metadataObject,
- String[] policiesToAdd,
- String[] policiesToRemove) {
- return dispatcher.associatePoliciesForMetadataObject(
- metalake, metadataObject, policiesToAdd, policiesToRemove);
- }
-
- @Override
- public PolicyEntity getPolicyForMetadataObject(
- String metalake, MetadataObject metadataObject, String policyName) {
- return dispatcher.getPolicyForMetadataObject(metalake, metadataObject, policyName);
- }
}
diff --git a/core/src/main/java/org/apache/gravitino/listener/PolicyEventDispatcher.java b/core/src/main/java/org/apache/gravitino/listener/PolicyEventDispatcher.java
index 1ac5d5d153..8869222622 100644
--- a/core/src/main/java/org/apache/gravitino/listener/PolicyEventDispatcher.java
+++ b/core/src/main/java/org/apache/gravitino/listener/PolicyEventDispatcher.java
@@ -25,9 +25,6 @@ import org.apache.gravitino.exceptions.NoSuchPolicyException;
import org.apache.gravitino.listener.api.event.policy.AlterPolicyEvent;
import org.apache.gravitino.listener.api.event.policy.AlterPolicyFailureEvent;
import org.apache.gravitino.listener.api.event.policy.AlterPolicyPreEvent;
-import org.apache.gravitino.listener.api.event.policy.AssociatePoliciesForMetadataObjectEvent;
-import org.apache.gravitino.listener.api.event.policy.AssociatePoliciesForMetadataObjectFailureEvent;
-import org.apache.gravitino.listener.api.event.policy.AssociatePoliciesForMetadataObjectPreEvent;
import org.apache.gravitino.listener.api.event.policy.CreatePolicyEvent;
import org.apache.gravitino.listener.api.event.policy.CreatePolicyFailureEvent;
import org.apache.gravitino.listener.api.event.policy.CreatePolicyPreEvent;
@@ -42,13 +39,7 @@ import org.apache.gravitino.listener.api.event.policy.EnablePolicyFailureEvent;
import org.apache.gravitino.listener.api.event.policy.EnablePolicyPreEvent;
import org.apache.gravitino.listener.api.event.policy.GetPolicyEvent;
import org.apache.gravitino.listener.api.event.policy.GetPolicyFailureEvent;
-import org.apache.gravitino.listener.api.event.policy.GetPolicyForMetadataObjectEvent;
-import org.apache.gravitino.listener.api.event.policy.GetPolicyForMetadataObjectFailureEvent;
-import org.apache.gravitino.listener.api.event.policy.GetPolicyForMetadataObjectPreEvent;
import org.apache.gravitino.listener.api.event.policy.GetPolicyPreEvent;
-import org.apache.gravitino.listener.api.event.policy.ListMetadataObjectsForPolicyEvent;
-import org.apache.gravitino.listener.api.event.policy.ListMetadataObjectsForPolicyFailureEvent;
-import org.apache.gravitino.listener.api.event.policy.ListMetadataObjectsForPolicyPreEvent;
import org.apache.gravitino.listener.api.event.policy.ListPoliciesEvent;
import org.apache.gravitino.listener.api.event.policy.ListPoliciesFailureEvent;
import org.apache.gravitino.listener.api.event.policy.ListPoliciesPreEvent;
@@ -264,31 +255,6 @@ public class PolicyEventDispatcher implements PolicyDispatcher {
}
}
- @Override
- public MetadataObject[] listMetadataObjectsForPolicy(String metalake, String policyName) {
- eventBus.dispatchEvent(
- new ListMetadataObjectsForPolicyPreEvent(
- PrincipalUtils.getCurrentUserName(),
- NameIdentifierUtil.ofPolicy(metalake, policyName)));
- try {
- MetadataObject[] metadataObjects =
- dispatcher.listMetadataObjectsForPolicy(metalake, policyName);
- eventBus.dispatchEvent(
- new ListMetadataObjectsForPolicyEvent(
- PrincipalUtils.getCurrentUserName(),
- NameIdentifierUtil.ofPolicy(metalake, policyName),
- metadataObjects != null ? metadataObjects.length : -1));
- return metadataObjects;
- } catch (Exception e) {
- eventBus.dispatchEvent(
- new ListMetadataObjectsForPolicyFailureEvent(
- PrincipalUtils.getCurrentUserName(),
- NameIdentifierUtil.ofPolicy(metalake, policyName),
- e));
- throw e;
- }
- }
-
@Override
public RelationalEntity<?>[] listTagAssociationsForPolicy(String metalake, String policyName) {
return dispatcher.listTagAssociationsForPolicy(metalake, policyName);
@@ -318,67 +284,6 @@ public class PolicyEventDispatcher implements PolicyDispatcher {
}
}
- @Override
- public String[] associatePoliciesForMetadataObject(
- String metalake,
- MetadataObject metadataObject,
- String[] policiesToAdd,
- String[] policiesToRemove) {
- eventBus.dispatchEvent(
- new AssociatePoliciesForMetadataObjectPreEvent(
- PrincipalUtils.getCurrentUserName(),
- metalake,
- metadataObject,
- policiesToAdd,
- policiesToRemove));
-
- try {
- String[] associatedPolicies =
- dispatcher.associatePoliciesForMetadataObject(
- metalake, metadataObject, policiesToAdd, policiesToRemove);
- eventBus.dispatchEvent(
- new AssociatePoliciesForMetadataObjectEvent(
- PrincipalUtils.getCurrentUserName(),
- metalake,
- metadataObject,
- policiesToAdd,
- policiesToRemove));
- return associatedPolicies;
- } catch (Exception e) {
- eventBus.dispatchEvent(
- new AssociatePoliciesForMetadataObjectFailureEvent(
- PrincipalUtils.getCurrentUserName(),
- metalake,
- metadataObject,
- policiesToAdd,
- policiesToRemove,
- e));
- throw e;
- }
- }
-
- @Override
- public PolicyEntity getPolicyForMetadataObject(
- String metalake, MetadataObject metadataObject, String policyName) {
- eventBus.dispatchEvent(
- new GetPolicyForMetadataObjectPreEvent(
- PrincipalUtils.getCurrentUserName(), metalake, metadataObject, policyName));
- try {
- PolicyEntity policy =
- dispatcher.getPolicyForMetadataObject(metalake, metadataObject, policyName);
- PolicyInfo policyInfo = toPolicyInfo(policy);
- eventBus.dispatchEvent(
- new GetPolicyForMetadataObjectEvent(
- PrincipalUtils.getCurrentUserName(), metalake, metadataObject, policyInfo));
- return policy;
- } catch (Exception e) {
- eventBus.dispatchEvent(
- new GetPolicyForMetadataObjectFailureEvent(
- PrincipalUtils.getCurrentUserName(), metalake, metadataObject, policyName, e));
- throw e;
- }
- }
-
private PolicyInfo toPolicyInfo(PolicyEntity policy) {
return new PolicyInfo(
policy.name(),
diff --git a/core/src/main/java/org/apache/gravitino/listener/api/event/policy/AssociatePoliciesForMetadataObjectEvent.java b/core/src/main/java/org/apache/gravitino/listener/api/event/policy/AssociatePoliciesForMetadataObjectEvent.java
deleted file mode 100644
index 932a7e53a4..0000000000
--- a/core/src/main/java/org/apache/gravitino/listener/api/event/policy/AssociatePoliciesForMetadataObjectEvent.java
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * 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.listener.api.event.policy;
-
-import org.apache.gravitino.MetadataObject;
-import org.apache.gravitino.annotation.DeveloperApi;
-import org.apache.gravitino.listener.api.event.OperationType;
-import org.apache.gravitino.utils.MetadataObjectUtil;
-
-/**
- * Represents an event that is triggered upon successfully associating policies with a metadata
- * object.
- */
-@DeveloperApi
-public final class AssociatePoliciesForMetadataObjectEvent extends PolicyEvent {
- private final MetadataObject metadataObject;
- private final String[] policiesToAdd;
- private final String[] policiesToRemove;
-
- /**
- * Constructs an instance of {@code AssociatePoliciesForMetadataObjectEvent}.
- *
- * @param user The username of the individual who initiated the associate policies operation.
- * @param metalake The metalake from which the policies were associated.
- * @param metadataObject The metadata object with which the policies were associated.
- * @param policiesToAdd The policies that were added.
- * @param policiesToRemove The policies that were removed.
- */
- public AssociatePoliciesForMetadataObjectEvent(
- String user,
- String metalake,
- MetadataObject metadataObject,
- String[] policiesToAdd,
- String[] policiesToRemove) {
- super(user, MetadataObjectUtil.toEntityIdent(metalake, metadataObject));
- this.metadataObject = metadataObject;
- this.policiesToAdd = policiesToAdd != null ? policiesToAdd : new String[0];
- this.policiesToRemove = policiesToRemove != null ? policiesToRemove : new String[0];
- }
-
- /**
- * Returns the metadata object with which policies were associated.
- *
- * @return the metadata object.
- */
- public MetadataObject metadataObject() {
- return metadataObject;
- }
-
- /**
- * Returns the policies that were added.
- *
- * @return an array of policy names that were added.
- */
- public String[] policiesToAdd() {
- return policiesToAdd;
- }
-
- /**
- * Returns the policies that were removed.
- *
- * @return an array of policy names that were removed.
- */
- public String[] policiesToRemove() {
- return policiesToRemove;
- }
-
- /**
- * Returns the type of operation.
- *
- * @return the operation type.
- */
- @Override
- public OperationType operationType() {
- return OperationType.ASSOCIATE_POLICIES_FOR_METADATA_OBJECT;
- }
-}
diff --git a/core/src/main/java/org/apache/gravitino/listener/api/event/policy/AssociatePoliciesForMetadataObjectFailureEvent.java b/core/src/main/java/org/apache/gravitino/listener/api/event/policy/AssociatePoliciesForMetadataObjectFailureEvent.java
deleted file mode 100644
index 38b872d0da..0000000000
--- a/core/src/main/java/org/apache/gravitino/listener/api/event/policy/AssociatePoliciesForMetadataObjectFailureEvent.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * 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.listener.api.event.policy;
-
-import org.apache.gravitino.MetadataObject;
-import org.apache.gravitino.annotation.DeveloperApi;
-import org.apache.gravitino.listener.api.event.OperationType;
-import org.apache.gravitino.utils.MetadataObjectUtil;
-
-/**
- * Represents an event that is triggered when an attempt to associate policies with a metadata
- * object fails.
- */
-@DeveloperApi
-public final class AssociatePoliciesForMetadataObjectFailureEvent extends PolicyFailureEvent {
- private final MetadataObject metadataObject;
- private final String[] policiesToAdd;
- private final String[] policiesToRemove;
-
- /**
- * Constructs an instance of {@code AssociatePoliciesForMetadataObjectFailureEvent}.
- *
- * @param user The username of the individual who initiated the associate policies operation.
- * @param metalake The metalake from which the policies were to be associated.
- * @param metadataObject The metadata object with which the policies were to be associated.
- * @param policiesToAdd The policies to be added.
- * @param policiesToRemove The policies to be removed.
- * @param exception The exception that was encountered during the associate policies attempt.
- */
- public AssociatePoliciesForMetadataObjectFailureEvent(
- String user,
- String metalake,
- MetadataObject metadataObject,
- String[] policiesToAdd,
- String[] policiesToRemove,
- Exception exception) {
- super(user, MetadataObjectUtil.toEntityIdent(metalake, metadataObject), exception);
- this.metadataObject = metadataObject;
- this.policiesToAdd = policiesToAdd != null ? policiesToAdd : new String[0];
- this.policiesToRemove = policiesToRemove != null ? policiesToRemove : new String[0];
- }
-
- /**
- * Returns the metadata object with which policies were to be associated.
- *
- * @return the metadata object.
- */
- public MetadataObject metadataObject() {
- return metadataObject;
- }
-
- /**
- * Returns the policies to be added.
- *
- * @return an array of policy names to be added.
- */
- public String[] policiesToAdd() {
- return policiesToAdd;
- }
-
- /**
- * Returns the policies to be removed.
- *
- * @return an array of policy names to be removed.
- */
- public String[] policiesToRemove() {
- return policiesToRemove;
- }
-
- /**
- * Returns the type of operation.
- *
- * @return the operation type.
- */
- @Override
- public OperationType operationType() {
- return OperationType.ASSOCIATE_POLICIES_FOR_METADATA_OBJECT;
- }
-}
diff --git a/core/src/main/java/org/apache/gravitino/listener/api/event/policy/AssociatePoliciesForMetadataObjectPreEvent.java b/core/src/main/java/org/apache/gravitino/listener/api/event/policy/AssociatePoliciesForMetadataObjectPreEvent.java
deleted file mode 100644
index 06f93105c2..0000000000
--- a/core/src/main/java/org/apache/gravitino/listener/api/event/policy/AssociatePoliciesForMetadataObjectPreEvent.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * 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.listener.api.event.policy;
-
-import org.apache.gravitino.MetadataObject;
-import org.apache.gravitino.annotation.DeveloperApi;
-import org.apache.gravitino.listener.api.event.OperationType;
-import org.apache.gravitino.utils.MetadataObjectUtil;
-
-/** Represents an event that is triggered before associating policies with a metadata object. */
-@DeveloperApi
-public final class AssociatePoliciesForMetadataObjectPreEvent extends PolicyPreEvent {
- private final MetadataObject metadataObject;
- private final String[] policiesToAdd;
- private final String[] policiesToRemove;
-
- /**
- * Constructs an instance of {@code AssociatePoliciesForMetadataObjectPreEvent}.
- *
- * @param user The username of the individual who initiated the associate policies operation.
- * @param metalake The metalake from which the policies will be associated.
- * @param metadataObject The metadata object with which the policies will be associated.
- * @param policiesToAdd The policies to be added.
- * @param policiesToRemove The policies to be removed.
- */
- public AssociatePoliciesForMetadataObjectPreEvent(
- String user,
- String metalake,
- MetadataObject metadataObject,
- String[] policiesToAdd,
- String[] policiesToRemove) {
- super(user, MetadataObjectUtil.toEntityIdent(metalake, metadataObject));
- this.metadataObject = metadataObject;
- this.policiesToAdd = policiesToAdd != null ? policiesToAdd.clone() : new String[0];
- this.policiesToRemove = policiesToRemove != null ? policiesToRemove.clone() : new String[0];
- }
-
- /**
- * Returns the metadata object with which policies will be associated.
- *
- * @return the metadata object.
- */
- public MetadataObject metadataObject() {
- return metadataObject;
- }
-
- /**
- * Returns the policies to be added.
- *
- * @return an array of policy names to be added.
- */
- public String[] policiesToAdd() {
- return policiesToAdd;
- }
-
- /**
- * Returns the policies to be removed.
- *
- * @return an array of policy names to be removed.
- */
- public String[] policiesToRemove() {
- return policiesToRemove;
- }
-
- /**
- * Returns the type of operation.
- *
- * @return the operation type.
- */
- @Override
- public OperationType operationType() {
- return OperationType.ASSOCIATE_POLICIES_FOR_METADATA_OBJECT;
- }
-}
diff --git a/core/src/main/java/org/apache/gravitino/listener/api/event/policy/GetPolicyForMetadataObjectEvent.java b/core/src/main/java/org/apache/gravitino/listener/api/event/policy/GetPolicyForMetadataObjectEvent.java
deleted file mode 100644
index bfa4c0eb13..0000000000
--- a/core/src/main/java/org/apache/gravitino/listener/api/event/policy/GetPolicyForMetadataObjectEvent.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * 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.listener.api.event.policy;
-
-import org.apache.gravitino.MetadataObject;
-import org.apache.gravitino.annotation.DeveloperApi;
-import org.apache.gravitino.listener.api.event.OperationType;
-import org.apache.gravitino.listener.api.info.PolicyInfo;
-import org.apache.gravitino.utils.MetadataObjectUtil;
-
-/**
- * Represents an event that is triggered upon successfully retrieving a policy for a metadata
- * object.
- */
-@DeveloperApi
-public final class GetPolicyForMetadataObjectEvent extends PolicyEvent {
- private final MetadataObject metadataObject;
- private final PolicyInfo policyInfo;
-
- /**
- * Constructs an instance of {@code GetPolicyForMetadataObjectEvent}.
- *
- * @param user The username of the individual who initiated the policy retrieval.
- * @param metalake The metalake from which the policy was retrieved.
- * @param metadataObject The metadata object for which the policy was retrieved.
- * @param policyInfo The {@link PolicyInfo} object representing the retrieved policy.
- */
- public GetPolicyForMetadataObjectEvent(
- String user, String metalake, MetadataObject metadataObject, PolicyInfo policyInfo) {
- super(user, MetadataObjectUtil.toEntityIdent(metalake, metadataObject));
- this.metadataObject = metadataObject;
- this.policyInfo = policyInfo;
- }
-
- /**
- * Returns the metadata object for which the policy was retrieved.
- *
- * @return the metadata object.
- */
- public MetadataObject metadataObject() {
- return metadataObject;
- }
-
- /**
- * Returns the {@link PolicyInfo} object representing the retrieved policy.
- *
- * @return the policy information.
- */
- public PolicyInfo policyInfo() {
- return policyInfo;
- }
-
- /**
- * Returns the type of operation.
- *
- * @return the operation type.
- */
- @Override
- public OperationType operationType() {
- return OperationType.GET_POLICY_FOR_METADATA_OBJECT;
- }
-}
diff --git a/core/src/main/java/org/apache/gravitino/listener/api/event/policy/GetPolicyForMetadataObjectFailureEvent.java b/core/src/main/java/org/apache/gravitino/listener/api/event/policy/GetPolicyForMetadataObjectFailureEvent.java
deleted file mode 100644
index 62198c4410..0000000000
--- a/core/src/main/java/org/apache/gravitino/listener/api/event/policy/GetPolicyForMetadataObjectFailureEvent.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * 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.listener.api.event.policy;
-
-import org.apache.gravitino.MetadataObject;
-import org.apache.gravitino.annotation.DeveloperApi;
-import org.apache.gravitino.listener.api.event.OperationType;
-import org.apache.gravitino.utils.MetadataObjectUtil;
-
-/**
- * Represents an event that is triggered when an attempt to retrieve a policy for a metadata object
- * fails.
- */
-@DeveloperApi
-public final class GetPolicyForMetadataObjectFailureEvent extends PolicyFailureEvent {
- private final MetadataObject metadataObject;
- private final String policyName;
-
- /**
- * Constructs an instance of {@code GetPolicyForMetadataObjectFailureEvent}.
- *
- * @param user The username of the individual who initiated the policy retrieval.
- * @param metalake The metalake from which the policy was to be retrieved.
- * @param metadataObject The metadata object for which the policy was to be retrieved.
- * @param policyName The name of the policy that was to be retrieved.
- * @param exception The exception that was encountered during the policy retrieval attempt.
- */
- public GetPolicyForMetadataObjectFailureEvent(
- String user,
- String metalake,
- MetadataObject metadataObject,
- String policyName,
- Exception exception) {
- super(user, MetadataObjectUtil.toEntityIdent(metalake, metadataObject), exception);
- this.metadataObject = metadataObject;
- this.policyName = policyName;
- }
-
- /**
- * Returns the metadata object for which the policy retrieval was attempted.
- *
- * @return the metadata object.
- */
- public MetadataObject metadataObject() {
- return metadataObject;
- }
-
- /**
- * Returns the name of the policy that was to be retrieved.
- *
- * @return the policy name.
- */
- public String policyName() {
- return policyName;
- }
-
- /**
- * Returns the type of operation.
- *
- * @return the operation type.
- */
- @Override
- public OperationType operationType() {
- return OperationType.GET_POLICY_FOR_METADATA_OBJECT;
- }
-}
diff --git a/core/src/main/java/org/apache/gravitino/listener/api/event/policy/GetPolicyForMetadataObjectPreEvent.java b/core/src/main/java/org/apache/gravitino/listener/api/event/policy/GetPolicyForMetadataObjectPreEvent.java
deleted file mode 100644
index a5392ba9be..0000000000
--- a/core/src/main/java/org/apache/gravitino/listener/api/event/policy/GetPolicyForMetadataObjectPreEvent.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * 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.listener.api.event.policy;
-
-import org.apache.gravitino.MetadataObject;
-import org.apache.gravitino.annotation.DeveloperApi;
-import org.apache.gravitino.listener.api.event.OperationType;
-import org.apache.gravitino.utils.MetadataObjectUtil;
-
-/** Represents an event triggered before retrieving a policy for a metadata object. */
-@DeveloperApi
-public final class GetPolicyForMetadataObjectPreEvent extends PolicyPreEvent {
- private final MetadataObject metadataObject;
- private final String policyName;
-
- /**
- * Constructs an instance of {@code GetPolicyForMetadataObjectPreEvent}.
- *
- * @param user The username of the individual who initiated the policy retrieval operation.
- * @param metalake The metalake from which the policy will be retrieved.
- * @param metadataObject The metadata object for which the policy will be retrieved.
- * @param policyName The name of the policy to be retrieved.
- */
- public GetPolicyForMetadataObjectPreEvent(
- String user, String metalake, MetadataObject metadataObject, String policyName) {
- super(user, MetadataObjectUtil.toEntityIdent(metalake, metadataObject));
- this.metadataObject = metadataObject;
- this.policyName = policyName;
- }
-
- /**
- * Returns the metadata object for which the policy will be retrieved.
- *
- * @return the metadata object.
- */
- public MetadataObject metadataObject() {
- return metadataObject;
- }
-
- /**
- * Returns the name of the policy to be retrieved.
- *
- * @return the policy name.
- */
- public String policyName() {
- return policyName;
- }
-
- /**
- * Returns the type of operation.
- *
- * @return the operation type.
- */
- @Override
- public OperationType operationType() {
- return OperationType.GET_POLICY_FOR_METADATA_OBJECT;
- }
-}
diff --git a/core/src/main/java/org/apache/gravitino/listener/api/event/policy/ListMetadataObjectsForPolicyEvent.java b/core/src/main/java/org/apache/gravitino/listener/api/event/policy/ListMetadataObjectsForPolicyEvent.java
deleted file mode 100644
index 087f756566..0000000000
--- a/core/src/main/java/org/apache/gravitino/listener/api/event/policy/ListMetadataObjectsForPolicyEvent.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * 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.listener.api.event.policy;
-
-import org.apache.gravitino.NameIdentifier;
-import org.apache.gravitino.annotation.DeveloperApi;
-import org.apache.gravitino.listener.api.event.ListEvent;
-import org.apache.gravitino.listener.api.event.OperationType;
-
-/**
- * Represents an event that is triggered upon successfully listing metadata objects associated with
- * a policy.
- */
-@DeveloperApi
-public final class ListMetadataObjectsForPolicyEvent extends PolicyEvent implements ListEvent {
-
- private final int count;
-
- /**
- * Constructs an instance of {@code ListMetadataObjectsForPolicyEvent}.
- *
- * @param user The username of the individual who initiated the list metadata objects operation.
- * @param identifier The identifier of the policy.
- * @param count The number of metadata objects returned by the list operation.
- */
- public ListMetadataObjectsForPolicyEvent(String user, NameIdentifier identifier, int count) {
- super(user, identifier);
- this.count = count;
- }
-
- /**
- * Constructs an instance of {@code ListMetadataObjectsForPolicyEvent} without a count.
- *
- * @param user The username of the individual who initiated the list metadata objects operation.
- * @param identifier The identifier of the policy.
- * @deprecated Use {@link #ListMetadataObjectsForPolicyEvent(String, NameIdentifier, int)}
- * instead.
- */
- @Deprecated
- @SuppressWarnings("InlineMeSuggester")
- public ListMetadataObjectsForPolicyEvent(String user, NameIdentifier identifier) {
- this(user, identifier, -1);
- }
-
- /** {@inheritDoc} */
- @Override
- public int resultCount() {
- return count;
- }
-
- /**
- * Returns the type of operation.
- *
- * @return the operation type.
- */
- @Override
- public OperationType operationType() {
- return OperationType.LIST_METADATA_OBJECTS_FOR_POLICY;
- }
-}
diff --git a/core/src/main/java/org/apache/gravitino/listener/api/event/policy/ListMetadataObjectsForPolicyFailureEvent.java b/core/src/main/java/org/apache/gravitino/listener/api/event/policy/ListMetadataObjectsForPolicyFailureEvent.java
deleted file mode 100644
index 147622f162..0000000000
--- a/core/src/main/java/org/apache/gravitino/listener/api/event/policy/ListMetadataObjectsForPolicyFailureEvent.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * 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.listener.api.event.policy;
-
-import org.apache.gravitino.NameIdentifier;
-import org.apache.gravitino.annotation.DeveloperApi;
-import org.apache.gravitino.listener.api.event.OperationType;
-
-/**
- * Represents an event that is triggered when an attempt to list metadata objects associated with a
- * policy fails.
- */
-@DeveloperApi
-public final class ListMetadataObjectsForPolicyFailureEvent extends PolicyFailureEvent {
- /**
- * Constructs an instance of {@code ListMetadataObjectsForPolicyFailureEvent}.
- *
- * @param user The username of the individual who initiated the list metadata objects operation.
- * @param identifier The identifier of the policy.
- * @param exception The exception that was encountered during the list metadata objects attempt.
- */
- public ListMetadataObjectsForPolicyFailureEvent(
- String user, NameIdentifier identifier, Exception exception) {
- super(user, identifier, exception);
- }
-
- /**
- * Returns the type of operation.
- *
- * @return the operation type.
- */
- @Override
- public OperationType operationType() {
- return OperationType.LIST_METADATA_OBJECTS_FOR_POLICY;
- }
-}
diff --git a/core/src/main/java/org/apache/gravitino/listener/api/event/policy/ListMetadataObjectsForPolicyPreEvent.java b/core/src/main/java/org/apache/gravitino/listener/api/event/policy/ListMetadataObjectsForPolicyPreEvent.java
deleted file mode 100644
index d4e3e63753..0000000000
--- a/core/src/main/java/org/apache/gravitino/listener/api/event/policy/ListMetadataObjectsForPolicyPreEvent.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * 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.listener.api.event.policy;
-
-import org.apache.gravitino.NameIdentifier;
-import org.apache.gravitino.annotation.DeveloperApi;
-import org.apache.gravitino.listener.api.event.OperationType;
-
-/**
- * Represents an event that is triggered before listing metadata objects associated with a policy.
- */
-@DeveloperApi
-public final class ListMetadataObjectsForPolicyPreEvent extends PolicyPreEvent {
- /**
- * Constructs an instance of {@code ListMetadataObjectsForPolicyPreEvent}.
- *
- * @param user The username of the individual who initiated the list metadata objects operation.
- * @param identifier The identifier of the policy.
- */
- public ListMetadataObjectsForPolicyPreEvent(String user, NameIdentifier identifier) {
- super(user, identifier);
- }
-
- /**
- * Returns the type of operation.
- *
- * @return the operation type.
- */
- @Override
- public OperationType operationType() {
- return OperationType.LIST_METADATA_OBJECTS_FOR_POLICY;
- }
-}
diff --git a/core/src/main/java/org/apache/gravitino/meta/GenericEntity.java b/core/src/main/java/org/apache/gravitino/meta/GenericEntity.java
index e8e9a7e3d0..ab27866607 100644
--- a/core/src/main/java/org/apache/gravitino/meta/GenericEntity.java
+++ b/core/src/main/java/org/apache/gravitino/meta/GenericEntity.java
@@ -27,15 +27,8 @@ import org.apache.gravitino.Entity;
import org.apache.gravitino.Field;
import org.apache.gravitino.HasIdentifier;
import org.apache.gravitino.Namespace;
-import org.apache.gravitino.policy.PolicyManager;
-/**
- * A generic entity that mainly used for temporary transactions or internal operations.
- *
- * <p>For example, it can be used to represent different types of entities for {@link
- * PolicyManager#listMetadataObjectsForPolicy(String, String)} intermediate result then can be
- * converted to metadata objects.
- */
+/** A generic entity that mainly used for temporary transactions or internal operations. */
@EqualsAndHashCode
@ToString
public class GenericEntity implements Entity, HasIdentifier {
diff --git a/core/src/main/java/org/apache/gravitino/policy/PolicyDispatcher.java b/core/src/main/java/org/apache/gravitino/policy/PolicyDispatcher.java
index fd4f4b9d6a..0f1ee9203a 100644
--- a/core/src/main/java/org/apache/gravitino/policy/PolicyDispatcher.java
+++ b/core/src/main/java/org/apache/gravitino/policy/PolicyDispatcher.java
@@ -118,15 +118,6 @@ public interface PolicyDispatcher {
*/
boolean deletePolicy(String metalake, String policyName);
- /**
- * List all metadata objects associated with the specified policy under a metalake.
- *
- * @param metalake the name of the metalake
- * @param policyName the name of the policy
- * @return The array of metadata objects associated with the specified policy.
- */
- MetadataObject[] listMetadataObjectsForPolicy(String metalake, String policyName);
-
/**
* List tag names directly associated with the specified policy.
*
@@ -172,30 +163,4 @@ public interface PolicyDispatcher {
* @return The array of policies associated with the specified metadata object.
*/
PolicyEntity[] listPolicyInfosForMetadataObject(String metalake, MetadataObject metadataObject);
-
- /**
- * Associate policies to a metadata object under a metalake.
- *
- * @param metalake the name of the metalake
- * @param metadataObject the metadata object to associate policies with
- * @param policiesToAdd the policies to be added to the metadata object
- * @param policiesToRemove the policies to remove from the metadata object
- * @return An array of updated policy names.
- */
- String[] associatePoliciesForMetadataObject(
- String metalake,
- MetadataObject metadataObject,
- String[] policiesToAdd,
- String[] policiesToRemove);
-
- /**
- * Get a specific policy associated with the specified metadata object.
- *
- * @param metalake the name of the metalake
- * @param metadataObject the metadata object for which to retrieve the policy
- * @param policyName the name of the policy to retrieve
- * @return The policy associated with the metadata object.
- */
- PolicyEntity getPolicyForMetadataObject(
- String metalake, MetadataObject metadataObject, String policyName);
}
diff --git a/core/src/main/java/org/apache/gravitino/policy/PolicyManager.java b/core/src/main/java/org/apache/gravitino/policy/PolicyManager.java
index 457a4a0b7c..04da88ef7f 100644
--- a/core/src/main/java/org/apache/gravitino/policy/PolicyManager.java
+++ b/core/src/main/java/org/apache/gravitino/policy/PolicyManager.java
@@ -27,10 +27,6 @@ import java.io.IOException;
import java.time.Instant;
import java.util.Arrays;
import java.util.Collections;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
import org.apache.gravitino.Entity;
import org.apache.gravitino.EntityAlreadyExistsException;
import org.apache.gravitino.EntityStore;
@@ -39,17 +35,13 @@ import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.RelationalEntity;
import org.apache.gravitino.SupportsRelationOperations;
import org.apache.gravitino.exceptions.NoSuchEntityException;
-import org.apache.gravitino.exceptions.NoSuchMetadataObjectException;
import org.apache.gravitino.exceptions.NoSuchPolicyException;
-import org.apache.gravitino.exceptions.PolicyAlreadyAssociatedException;
import org.apache.gravitino.exceptions.PolicyAlreadyExistsException;
import org.apache.gravitino.lock.LockType;
import org.apache.gravitino.lock.TreeLockUtils;
import org.apache.gravitino.meta.AuditInfo;
-import org.apache.gravitino.meta.GenericEntity;
import org.apache.gravitino.meta.PolicyEntity;
import org.apache.gravitino.storage.IdGenerator;
-import org.apache.gravitino.storage.relational.service.MetadataObjectService;
import org.apache.gravitino.utils.MetadataObjectUtil;
import org.apache.gravitino.utils.NameIdentifierUtil;
import org.apache.gravitino.utils.NamespaceUtil;
@@ -60,17 +52,6 @@ import org.slf4j.LoggerFactory;
public class PolicyManager implements PolicyDispatcher {
private static final Logger LOG = LoggerFactory.getLogger(PolicyManager.class);
- private static final Set<MetadataObject.Type> SUPPORTED_METADATA_OBJECT_TYPES_FOR_POLICIES =
- Sets.newHashSet(
- MetadataObject.Type.CATALOG,
- MetadataObject.Type.SCHEMA,
- MetadataObject.Type.TABLE,
- MetadataObject.Type.FILESET,
- MetadataObject.Type.TOPIC,
- MetadataObject.Type.MODEL,
- MetadataObject.Type.VIEW,
- MetadataObject.Type.FUNCTION);
-
private final IdGenerator idGenerator;
private final EntityStore entityStore;
private final ObjectPolicyResolver objectPolicyResolver;
@@ -237,37 +218,6 @@ public class PolicyManager implements PolicyDispatcher {
});
}
- @Override
- public MetadataObject[] listMetadataObjectsForPolicy(String metalake, String policyName) {
- NameIdentifier policyIdent = NameIdentifierUtil.ofPolicy(metalake, policyName);
- checkMetalake(NameIdentifier.of(metalake), entityStore);
-
- return TreeLockUtils.doWithTreeLock(
- policyIdent,
- LockType.READ,
- () -> {
- try {
- if (!entityStore.exists(policyIdent, Entity.EntityType.POLICY)) {
- throw new NoSuchPolicyException(
- "Policy with name %s under metalake %s does not exist", policyName, metalake);
- }
-
- List<GenericEntity> entities =
- entityStore
- .relationOperations()
- .listEntitiesByRelation(
- SupportsRelationOperations.Type.POLICY_METADATA_OBJECT_REL,
- policyIdent,
- Entity.EntityType.POLICY);
- return MetadataObjectService.fromGenericEntities(entities)
- .toArray(new MetadataObject[0]);
- } catch (IOException e) {
- LOG.error("Failed to list metadata objects for policy {}", policyName, e);
- throw new RuntimeException(e);
- }
- });
- }
-
@Override
public RelationalEntity<?>[] listTagAssociationsForPolicy(String metalake, String policyName) {
NameIdentifier policyIdentifier = NameIdentifierUtil.ofPolicy(metalake, policyName);
@@ -302,150 +252,8 @@ public class PolicyManager implements PolicyDispatcher {
MetadataObjectUtil.checkMetadataObject(metalake, metadataObject);
checkMetalake(NameIdentifier.of(metalake), entityStore);
- Map<Long, PolicyEntity> policiesById = new LinkedHashMap<>();
- Arrays.stream(listDirectPoliciesForMetadataObject(metalake, metadataObject, false))
- .forEach(policy -> policiesById.put(policy.id(), policy));
-
- Arrays.stream(objectPolicyResolver.resolve(metalake, metadataObject))
- .forEach(
- policy -> {
- if (policy.inherited().orElse(false)) {
- policiesById.putIfAbsent(policy.id(), policy);
- } else {
- policiesById.put(policy.id(), policy);
- }
- });
-
- for (MetadataObject parent : MetadataObjectUtil.getParentMetadataObjects(metadataObject)) {
- Arrays.stream(listDirectPoliciesForMetadataObject(metalake, parent, true))
- .forEach(policy -> policiesById.putIfAbsent(policy.id(), policy));
- }
- return policiesById.values().stream()
- .filter(PolicyEntity::enabled)
- .toArray(PolicyEntity[]::new);
- }
-
- @Override
- public String[] associatePoliciesForMetadataObject(
- String metalake,
- MetadataObject metadataObject,
- String[] policiesToAdd,
- String[] policiesToRemove) {
- Preconditions.checkArgument(
- SUPPORTED_METADATA_OBJECT_TYPES_FOR_POLICIES.contains(metadataObject.type()),
- "Cannot associate policies for unsupported metadata object type %s",
- metadataObject.type());
-
- NameIdentifier entityIdent = MetadataObjectUtil.toEntityIdent(metalake, metadataObject);
- Entity.EntityType entityType = MetadataObjectUtil.toEntityType(metadataObject);
-
- MetadataObjectUtil.checkMetadataObject(metalake, metadataObject);
-
- // Remove all the policies that are both set to add and remove
- Set<String> policiesToAddSet =
- policiesToAdd == null ? Sets.newHashSet() : Sets.newHashSet(policiesToAdd);
- Set<String> policiesToRemoveSet =
- policiesToRemove == null ? Sets.newHashSet() : Sets.newHashSet(policiesToRemove);
- Set<String> common = Sets.intersection(policiesToAddSet, policiesToRemoveSet).immutableCopy();
- policiesToAddSet.removeAll(common);
- policiesToRemoveSet.removeAll(common);
-
- NameIdentifier[] policiesToAddIdent =
- policiesToAddSet.stream()
- .map(p -> NameIdentifierUtil.ofPolicy(metalake, p))
- .toArray(NameIdentifier[]::new);
- NameIdentifier[] policiesToRemoveIdent =
- policiesToRemoveSet.stream()
- .map(p -> NameIdentifierUtil.ofPolicy(metalake, p))
- .toArray(NameIdentifier[]::new);
-
- checkMetalake(NameIdentifier.of(metalake), entityStore);
- return TreeLockUtils.doWithTreeLock(
- entityIdent,
- LockType.READ,
- () ->
- TreeLockUtils.doWithTreeLock(
- NameIdentifier.of(NamespaceUtil.ofPolicy(metalake).levels()),
- LockType.WRITE,
- () -> {
- try {
- List<PolicyEntity> updatedPolicies =
- entityStore
- .relationOperations()
- .updateEntityRelations(
- SupportsRelationOperations.Type.POLICY_METADATA_OBJECT_REL,
- entityIdent,
- entityType,
- policiesToAddIdent,
- policiesToRemoveIdent);
- return updatedPolicies.stream().map(PolicyEntity::name).toArray(String[]::new);
- } catch (NoSuchEntityException e) {
- throw new NoSuchMetadataObjectException(
- e,
- "Failed to associate policies for metadata object %s due to not found",
- metadataObject);
- } catch (EntityAlreadyExistsException e) {
- throw new PolicyAlreadyAssociatedException(
- e,
- "Failed to associate policies for metadata object due to some policies %s already "
- + "associated to the metadata object %s",
- Arrays.toString(policiesToAdd),
- metadataObject);
- } catch (IOException e) {
- LOG.error(
- "Failed to associate policies for metadata object {}", metadataObject, e);
- throw new RuntimeException(e);
- }
- }));
- }
-
- @Override
- public PolicyEntity getPolicyForMetadataObject(
- String metalake, MetadataObject metadataObject, String policyName) {
- try {
- return Arrays.stream(listPolicyInfosForMetadataObject(metalake, metadataObject))
- .filter(policy -> policy.name().equals(policyName))
- .findFirst()
- .orElseThrow(
- () ->
- new NoSuchPolicyException(
- "Policy %s does not exist for metadata object %s",
- policyName, metadataObject));
- } catch (NoSuchMetadataObjectException e) {
- throw new NoSuchMetadataObjectException(
- e, "Failed to get policy for metadata object %s due to not found", metadataObject);
- }
- }
-
- private PolicyEntity[] listDirectPoliciesForMetadataObject(
- String metalake, MetadataObject metadataObject, boolean inherited) {
- NameIdentifier entityIdent = MetadataObjectUtil.toEntityIdent(metalake, metadataObject);
- Entity.EntityType entityType = MetadataObjectUtil.toEntityType(metadataObject);
- return TreeLockUtils.doWithTreeLock(
- entityIdent,
- LockType.READ,
- () -> {
- try {
- return entityStore
- .relationOperations()
- .listEntitiesByRelation(
- SupportsRelationOperations.Type.POLICY_METADATA_OBJECT_REL,
- entityIdent,
- entityType,
- true /* allFields */)
- .stream()
- .map(entity -> ((PolicyEntity) entity).copyWithInherited(inherited))
- .toArray(PolicyEntity[]::new);
- } catch (NoSuchEntityException e) {
- throw new NoSuchMetadataObjectException(
- e,
- "Failed to list policies for metadata object %s due to not found",
- metadataObject);
- } catch (IOException e) {
- LOG.error("Failed to list policies for metadata object {}", metadataObject, e);
- throw new RuntimeException(e);
- }
- });
+ // Tag-derived policy reads are best-effort across the object and its ancestors.
+ return objectPolicyResolver.resolve(metalake, metadataObject);
}
private PolicyEntity getPolicyWithoutLock(String metalake, String policyName) {
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/JDBCBackend.java b/core/src/main/java/org/apache/gravitino/storage/relational/JDBCBackend.java
index c6f949cfd8..7ab84f9005 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/JDBCBackend.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/JDBCBackend.java
@@ -694,16 +694,6 @@ public class JDBCBackend implements RelationalBackend, SupportsOrphanedRelationC
String.format("ROLE_USER_REL doesn't support type %s", identType.name()));
}
- case POLICY_METADATA_OBJECT_REL:
- if (identType == Entity.EntityType.POLICY) {
- return (List<E>)
- PolicyMetaService.getInstance().listAssociatedEntitiesForPolicy(nameIdentifier);
- } else {
- return (List<E>)
- PolicyMetaService.getInstance()
- .listPoliciesForMetadataObject(nameIdentifier, identType);
- }
-
case TAG_METADATA_OBJECT_REL:
if (identType == Entity.EntityType.TAG) {
return (List<E>)
@@ -790,11 +780,6 @@ public class JDBCBackend implements RelationalBackend, SupportsOrphanedRelationC
NameIdentifier[] destEntitiesToRemove)
throws IOException, NoSuchEntityException, EntityAlreadyExistsException {
switch (relType) {
- case POLICY_METADATA_OBJECT_REL:
- return (List<E>)
- PolicyMetaService.getInstance()
- .associatePoliciesWithMetadataObject(
- srcEntityIdent, srcEntityType, destEntitiesToAdd, destEntitiesToRemove);
case TAG_METADATA_OBJECT_REL:
return (List<E>)
TagMetaService.getInstance()
@@ -905,10 +890,6 @@ public class JDBCBackend implements RelationalBackend, SupportsOrphanedRelationC
NameIdentifier destEntityIdent)
throws IOException, NoSuchEntityException {
switch (relType) {
- case POLICY_METADATA_OBJECT_REL:
- return (E)
- PolicyMetaService.getInstance()
- .getPolicyForMetadataObject(srcIdentifier, srcType, destEntityIdent);
case TAG_METADATA_OBJECT_REL:
return (E)
TagMetaService.getInstance()
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 4892cca90c..50572c5b9d 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
@@ -353,7 +353,7 @@ public class RelationalEntityStore
throws IOException {
backend.insertRelation(relType, srcIdentifier, srcType, dstIdentifier, dstType, override);
// Relation query results themselves are not cached, but both endpoints may be cached entities
- // (OWNER_REL, TAG_/POLICY_METADATA_OBJECT_REL and METADATA_OBJECT_ROLE_REL are keyed by
+ // (OWNER_REL, TAG_METADATA_OBJECT_REL and METADATA_OBJECT_ROLE_REL are keyed by
// catalog/schema/table/... on the source side), so drop their entries conservatively: a
// relation write can change data materialized into the endpoint entity. Note this is not free —
// EntityCache#invalidate cascades over the identifier hierarchy, so invalidating a catalog also
@@ -499,8 +499,6 @@ public class RelationalEntityStore
private static Entity.EntityType relationUpdateTargetType(Type relType) {
switch (relType) {
- case POLICY_METADATA_OBJECT_REL:
- return Entity.EntityType.POLICY;
case TAG_METADATA_OBJECT_REL:
return Entity.EntityType.TAG;
case POLICY_TAG_REL:
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/OrphanedMetadataObjectRelationMapper.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/OrphanedMetadataObjectRelationMapper.java
index fbb63e0f58..30832ff08f 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/OrphanedMetadataObjectRelationMapper.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/OrphanedMetadataObjectRelationMapper.java
@@ -46,17 +46,6 @@ public interface OrphanedMetadataObjectRelationMapper {
@Param("deletedAt") long deletedAt,
@Param("limit") int limit);
- /** Soft-deletes orphaned policy relations and returns the affected row count. */
- @UpdateProvider(
- type = OrphanedMetadataObjectRelationSQLProvider.class,
- method = "softDeleteOrphanedPolicyRelations")
- int softDeleteOrphanedPolicyRelations(
- @Param("entityTable") String entityTable,
- @Param("entityIdColumn") String entityIdColumn,
- @Param("metadataObjectType") String metadataObjectType,
- @Param("deletedAt") long deletedAt,
- @Param("limit") int limit);
-
/** Soft-deletes orphaned statistics and returns the affected row count. */
@UpdateProvider(
type = OrphanedMetadataObjectRelationSQLProvider.class,
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/OrphanedMetadataObjectRelationSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/OrphanedMetadataObjectRelationSQLProvider.java
index 09d509a895..07290fbba4 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/OrphanedMetadataObjectRelationSQLProvider.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/OrphanedMetadataObjectRelationSQLProvider.java
@@ -19,7 +19,6 @@
package org.apache.gravitino.storage.relational.mapper;
import static org.apache.gravitino.storage.relational.mapper.OwnerMetaMapper.OWNER_TABLE_NAME;
-import static org.apache.gravitino.storage.relational.mapper.PolicyMetadataObjectRelMapper.POLICY_METADATA_OBJECT_RELATION_TABLE_NAME;
import static org.apache.gravitino.storage.relational.mapper.SecurableObjectMapper.SECURABLE_OBJECT_TABLE_NAME;
import static org.apache.gravitino.storage.relational.mapper.StatisticMetaMapper.STATISTIC_META_TABLE_NAME;
import static org.apache.gravitino.storage.relational.mapper.TagMetadataObjectRelMapper.TAG_METADATA_OBJECT_RELATION_TABLE_NAME;
@@ -47,16 +46,6 @@ public class OrphanedMetadataObjectRelationSQLProvider {
entityIdColumn);
}
- /** Returns SQL that soft-deletes orphaned policy relations. */
- public static String softDeleteOrphanedPolicyRelations(
- @Param("entityTable") String entityTable, @Param("entityIdColumn") String entityIdColumn) {
- return softDeleteOrphans(
- POLICY_METADATA_OBJECT_RELATION_TABLE_NAME,
- "metadata_object_type",
- entityTable,
- entityIdColumn);
- }
-
/** Returns SQL that soft-deletes orphaned statistics. */
public static String softDeleteOrphanedStatistics(
@Param("entityTable") String entityTable, @Param("entityIdColumn") String entityIdColumn) {
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/PolicyMetadataObjectRelMapper.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/PolicyMetadataObjectRelMapper.java
deleted file mode 100644
index b3ddb04368..0000000000
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/PolicyMetadataObjectRelMapper.java
+++ /dev/null
@@ -1,149 +0,0 @@
-/*
- * 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.storage.relational.mapper;
-
-import java.util.List;
-import org.apache.gravitino.storage.relational.po.PolicyMetadataObjectRelPO;
-import org.apache.gravitino.storage.relational.po.PolicyPO;
-import org.apache.ibatis.annotations.DeleteProvider;
-import org.apache.ibatis.annotations.InsertProvider;
-import org.apache.ibatis.annotations.Param;
-import org.apache.ibatis.annotations.Result;
-import org.apache.ibatis.annotations.Results;
-import org.apache.ibatis.annotations.SelectProvider;
-import org.apache.ibatis.annotations.UpdateProvider;
-
-public interface PolicyMetadataObjectRelMapper {
- String POLICY_METADATA_OBJECT_RELATION_TABLE_NAME = "policy_relation_meta";
-
- @Results({
- @Result(property = "policyId", column = "policy_id"),
- @Result(property = "policyName", column = "policy_name"),
- @Result(property = "policyType", column = "policy_type"),
- @Result(property = "metalakeId", column = "metalake_id"),
- @Result(property = "auditInfo", column = "audit_info"),
- @Result(property = "currentVersion", column = "current_version"),
- @Result(property = "lastVersion", column = "last_version"),
- @Result(property = "deletedAt", column = "deleted_at"),
- @Result(property = "policyVersionPO.id", column = "id"),
- @Result(property = "policyVersionPO.metalakeId", column = "version_metalake_id"),
- @Result(property = "policyVersionPO.policyId", column = "version_policy_id"),
- @Result(property = "policyVersionPO.version", column = "version"),
- @Result(property = "policyVersionPO.policyComment", column = "policy_comment"),
- @Result(property = "policyVersionPO.enabled", column = "enabled"),
- @Result(property = "policyVersionPO.content", column = "content"),
- @Result(property = "policyVersionPO.deletedAt", column = "version_deleted_at")
- })
- @SelectProvider(
- type = PolicyMetadataObjectRelSQLProviderFactory.class,
- method = "listPolicyPOsByMetadataObjectIdAndType")
- List<PolicyPO> listPolicyPOsByMetadataObjectIdAndType(
- @Param("metadataObjectId") Long metadataObjectId,
- @Param("metadataObjectType") String metadataObjectType);
-
- @Results({
- @Result(property = "policyId", column = "policy_id"),
- @Result(property = "policyName", column = "policy_name"),
- @Result(property = "policyType", column = "policy_type"),
- @Result(property = "metalakeId", column = "metalake_id"),
- @Result(property = "auditInfo", column = "audit_info"),
- @Result(property = "currentVersion", column = "current_version"),
- @Result(property = "lastVersion", column = "last_version"),
- @Result(property = "deletedAt", column = "deleted_at"),
- @Result(property = "policyVersionPO.id", column = "id"),
- @Result(property = "policyVersionPO.metalakeId", column = "version_metalake_id"),
- @Result(property = "policyVersionPO.policyId", column = "version_policy_id"),
- @Result(property = "policyVersionPO.version", column = "version"),
- @Result(property = "policyVersionPO.policyComment", column = "policy_comment"),
- @Result(property = "policyVersionPO.enabled", column = "enabled"),
- @Result(property = "policyVersionPO.content", column = "content"),
- @Result(property = "policyVersionPO.deletedAt", column = "version_deleted_at")
- })
- @SelectProvider(
- type = PolicyMetadataObjectRelSQLProviderFactory.class,
- method = "getPolicyPOsByMetadataObjectAndPolicyName")
- PolicyPO getPolicyPOsByMetadataObjectAndPolicyName(
- @Param("metadataObjectId") Long metadataObjectId,
- @Param("metadataObjectType") String metadataObjectType,
- @Param("policyName") String policyName);
-
- @SelectProvider(
- type = PolicyMetadataObjectRelSQLProviderFactory.class,
- method = "listPolicyMetadataObjectRelsByMetalakeAndPolicyName")
- List<PolicyMetadataObjectRelPO> listPolicyMetadataObjectRelsByMetalakeAndPolicyName(
- @Param("metalakeName") String metalakeName, @Param("policyName") String policyName);
-
- @InsertProvider(
- type = PolicyMetadataObjectRelSQLProviderFactory.class,
- method = "batchInsertPolicyMetadataObjectRels")
- void batchInsertPolicyMetadataObjectRels(
- @Param("policyRels") List<PolicyMetadataObjectRelPO> policyRelPOs);
-
- @UpdateProvider(
- type = PolicyMetadataObjectRelSQLProviderFactory.class,
- method = "batchDeletePolicyMetadataObjectRelsByPolicyIdsAndMetadataObject")
- void batchDeletePolicyMetadataObjectRelsByPolicyIdsAndMetadataObject(
- @Param("metadataObjectId") Long metadataObjectId,
- @Param("metadataObjectType") String metadataObjectType,
- @Param("policyIds") List<Long> policyIds);
-
- /**
- * Soft-deletes all active metadata-object relations for a policy.
- *
- * @param policyId The policy ID.
- * @return The number of affected rows.
- */
- @UpdateProvider(
- type = PolicyMetadataObjectRelSQLProviderFactory.class,
- method = "softDeletePolicyMetadataObjectRelsByPolicyId")
- Integer softDeletePolicyMetadataObjectRelsByPolicyId(@Param("policyId") Long policyId);
-
- @UpdateProvider(
- type = PolicyMetadataObjectRelSQLProviderFactory.class,
- method = "softDeletePolicyMetadataObjectRelsByMetalakeId")
- void softDeletePolicyMetadataObjectRelsByMetalakeId(@Param("metalakeId") Long metalakeId);
-
- @UpdateProvider(
- type = PolicyMetadataObjectRelSQLProviderFactory.class,
- method = "softDeletePolicyMetadataObjectRelsByMetadataObject")
- void softDeletePolicyMetadataObjectRelsByMetadataObject(
- @Param("metadataObjectId") Long metadataObjectId,
- @Param("metadataObjectType") String metadataObjectType);
-
- @UpdateProvider(
- type = PolicyMetadataObjectRelSQLProviderFactory.class,
- method = "softDeletePolicyMetadataObjectRelsByCatalogId")
- void softDeletePolicyMetadataObjectRelsByCatalogId(@Param("catalogId") Long catalogId);
-
- @UpdateProvider(
- type = PolicyMetadataObjectRelSQLProviderFactory.class,
- method = "softDeletePolicyMetadataObjectRelsBySchemaIds")
- void softDeletePolicyMetadataObjectRelsBySchemaIds(@Param("schemaIds") List<Long> schemaIds);
-
- @UpdateProvider(
- type = PolicyMetadataObjectRelSQLProviderFactory.class,
- method = "softDeletePolicyMetadataObjectRelsByTableId")
- void softDeletePolicyMetadataObjectRelsByTableId(@Param("tableId") Long tableId);
-
- @DeleteProvider(
- type = PolicyMetadataObjectRelSQLProviderFactory.class,
- method = "deletePolicyEntityRelsByLegacyTimeline")
- Integer deletePolicyEntityRelsByLegacyTimeline(
- @Param("legacyTimeline") Long legacyTimeline, @Param("limit") int limit);
-}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/PolicyMetadataObjectRelSQLProviderFactory.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/PolicyMetadataObjectRelSQLProviderFactory.java
deleted file mode 100644
index e968bfcc44..0000000000
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/PolicyMetadataObjectRelSQLProviderFactory.java
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- * 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.storage.relational.mapper;
-
-import com.google.common.collect.ImmutableMap;
-import java.util.List;
-import java.util.Map;
-import org.apache.gravitino.storage.relational.JDBCBackend.JDBCBackendType;
-import org.apache.gravitino.storage.relational.mapper.provider.base.PolicyMetadataObjectRelBaseSQLProvider;
-import org.apache.gravitino.storage.relational.mapper.provider.postgresql.PolicyMetadataObjectRelPostgreSQLProvider;
-import org.apache.gravitino.storage.relational.po.PolicyMetadataObjectRelPO;
-import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;
-import org.apache.ibatis.annotations.Param;
-
-public class PolicyMetadataObjectRelSQLProviderFactory {
-
- private static final Map<JDBCBackendType, PolicyMetadataObjectRelBaseSQLProvider>
- POLICY_METADATA_OBJECT_RELATION_SQL_PROVIDER_MAP =
- ImmutableMap.of(
- JDBCBackendType.MYSQL, new PolicyMetadataObjectRelMySQLProvider(),
- JDBCBackendType.H2, new PolicyMetadataObjectRelH2Provider(),
- JDBCBackendType.POSTGRESQL, new PolicyMetadataObjectRelPostgreSQLProvider());
-
- public static PolicyMetadataObjectRelBaseSQLProvider getProvider() {
- String databaseId =
- SqlSessionFactoryHelper.getInstance()
- .getSqlSessionFactory()
- .getConfiguration()
- .getDatabaseId();
-
- JDBCBackendType jdbcBackendType = JDBCBackendType.fromString(databaseId);
- return POLICY_METADATA_OBJECT_RELATION_SQL_PROVIDER_MAP.get(jdbcBackendType);
- }
-
- static class PolicyMetadataObjectRelMySQLProvider
- extends PolicyMetadataObjectRelBaseSQLProvider {}
-
- static class PolicyMetadataObjectRelH2Provider extends PolicyMetadataObjectRelBaseSQLProvider {}
-
- public static String listPolicyPOsByMetadataObjectIdAndType(
- @Param("metadataObjectId") Long metadataObjectId,
- @Param("metadataObjectType") String metadataObjectType) {
- return getProvider()
- .listPolicyPOsByMetadataObjectIdAndType(metadataObjectId, metadataObjectType);
- }
-
- public static String getPolicyPOsByMetadataObjectAndPolicyName(
- @Param("metadataObjectId") Long metadataObjectId,
- @Param("metadataObjectType") String metadataObjectType,
- @Param("policyName") String policyName) {
- return getProvider()
- .getPolicyPOsByMetadataObjectAndPolicyName(
- metadataObjectId, metadataObjectType, policyName);
- }
-
- public static String listPolicyMetadataObjectRelsByMetalakeAndPolicyName(
- @Param("metalakeName") String metalakeName, @Param("policyName") String policyName) {
- return getProvider()
- .listPolicyMetadataObjectRelsByMetalakeAndPolicyName(metalakeName, policyName);
- }
-
- public static String batchInsertPolicyMetadataObjectRels(
- @Param("policyRels") List<PolicyMetadataObjectRelPO> policyRelPOs) {
- return getProvider().batchInsertPolicyMetadataObjectRels(policyRelPOs);
- }
-
- public static String batchDeletePolicyMetadataObjectRelsByPolicyIdsAndMetadataObject(
- @Param("metadataObjectId") Long metadataObjectId,
- @Param("metadataObjectType") String metadataObjectType,
- @Param("policyIds") List<Long> policyIds) {
- return getProvider()
- .batchDeletePolicyMetadataObjectRelsByPolicyIdsAndMetadataObject(
- metadataObjectId, metadataObjectType, policyIds);
- }
-
- /** Delegates cleanup of metadata-object relations by policy ID. */
- public static String softDeletePolicyMetadataObjectRelsByPolicyId(
- @Param("policyId") Long policyId) {
- return getProvider().softDeletePolicyMetadataObjectRelsByPolicyId(policyId);
- }
-
- public static String softDeletePolicyMetadataObjectRelsByMetalakeId(
- @Param("metalakeId") Long metalakeId) {
- return getProvider().softDeletePolicyMetadataObjectRelsByMetalakeId(metalakeId);
- }
-
- public static String softDeletePolicyMetadataObjectRelsByMetadataObject(
- @Param("metadataObjectId") Long metadataObjectId,
- @Param("metadataObjectType") String metadataObjectType) {
- return getProvider()
- .softDeletePolicyMetadataObjectRelsByMetadataObject(metadataObjectId, metadataObjectType);
- }
-
- public static String softDeletePolicyMetadataObjectRelsByCatalogId(
- @Param("catalogId") Long catalogId) {
- return getProvider().softDeletePolicyMetadataObjectRelsByCatalogId(catalogId);
- }
-
- public static String softDeletePolicyMetadataObjectRelsBySchemaIds(
- @Param("schemaIds") List<Long> schemaIds) {
- return getProvider().softDeletePolicyMetadataObjectRelsBySchemaIds(schemaIds);
- }
-
- public static String softDeletePolicyMetadataObjectRelsByTableId(@Param("tableId") Long tableId) {
- return getProvider().softDeletePolicyMetadataObjectRelsByTableId(tableId);
- }
-
- public static String deletePolicyEntityRelsByLegacyTimeline(
- @Param("legacyTimeline") Long legacyTimeline, @Param("limit") int limit) {
- return getProvider().deletePolicyEntityRelsByLegacyTimeline(legacyTimeline, limit);
- }
-}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/DefaultMapperPackageProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/DefaultMapperPackageProvider.java
index 6fdf25d142..6a2bd9ca85 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/DefaultMapperPackageProvider.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/DefaultMapperPackageProvider.java
@@ -37,7 +37,6 @@ import org.apache.gravitino.storage.relational.mapper.ModelVersionMetaMapper;
import org.apache.gravitino.storage.relational.mapper.OrphanedMetadataObjectRelationMapper;
import org.apache.gravitino.storage.relational.mapper.OwnerMetaMapper;
import org.apache.gravitino.storage.relational.mapper.PolicyMetaMapper;
-import org.apache.gravitino.storage.relational.mapper.PolicyMetadataObjectRelMapper;
import org.apache.gravitino.storage.relational.mapper.PolicyTagRelMapper;
import org.apache.gravitino.storage.relational.mapper.PolicyVersionMapper;
import org.apache.gravitino.storage.relational.mapper.RoleMetaMapper;
@@ -77,7 +76,6 @@ public class DefaultMapperPackageProvider implements MapperPackageProvider {
ModelVersionMetaMapper.class,
OrphanedMetadataObjectRelationMapper.class,
OwnerMetaMapper.class,
- PolicyMetadataObjectRelMapper.class,
PolicyTagRelMapper.class,
PolicyMetaMapper.class,
PolicyVersionMapper.class,
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/PolicyMetadataObjectRelBaseSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/PolicyMetadataObjectRelBaseSQLProvider.java
deleted file mode 100644
index e239139d5a..0000000000
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/PolicyMetadataObjectRelBaseSQLProvider.java
+++ /dev/null
@@ -1,276 +0,0 @@
-/*
- * 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.storage.relational.mapper.provider.base;
-
-import static org.apache.gravitino.storage.relational.mapper.PolicyVersionMapper.POLICY_VERSION_TABLE_NAME;
-
-import java.util.List;
-import org.apache.gravitino.storage.relational.mapper.FilesetMetaMapper;
-import org.apache.gravitino.storage.relational.mapper.FunctionMetaMapper;
-import org.apache.gravitino.storage.relational.mapper.MetalakeMetaMapper;
-import org.apache.gravitino.storage.relational.mapper.ModelMetaMapper;
-import org.apache.gravitino.storage.relational.mapper.PolicyMetaMapper;
-import org.apache.gravitino.storage.relational.mapper.PolicyMetadataObjectRelMapper;
-import org.apache.gravitino.storage.relational.mapper.SchemaMetaMapper;
-import org.apache.gravitino.storage.relational.mapper.TableMetaMapper;
-import org.apache.gravitino.storage.relational.mapper.TopicMetaMapper;
-import org.apache.gravitino.storage.relational.mapper.ViewMetaMapper;
-import org.apache.gravitino.storage.relational.mapper.provider.DatabaseTimeSQL;
-import org.apache.gravitino.storage.relational.po.PolicyMetadataObjectRelPO;
-import org.apache.ibatis.annotations.Param;
-
-public class PolicyMetadataObjectRelBaseSQLProvider {
-
- public String listPolicyPOsByMetadataObjectIdAndType(
- @Param("metadataObjectId") Long metadataObjectId,
- @Param("metadataObjectType") String metadataObjectType) {
- return "SELECT pm.policy_id, pm.policy_name, pm.policy_type, pm.metalake_id,"
- + " pm.audit_info, pm.current_version, pm.last_version,"
- + " pm.deleted_at, pvi.id, pvi.metalake_id as version_metalake_id, pvi.policy_id as version_policy_id,"
- + " pvi.version, pvi.policy_comment, pvi.enabled, pvi.content, pvi.deleted_at as version_deleted_at"
- + " FROM "
- + PolicyMetaMapper.POLICY_META_TABLE_NAME
- + " pm JOIN "
- + PolicyMetadataObjectRelMapper.POLICY_METADATA_OBJECT_RELATION_TABLE_NAME
- + " pe ON pm.policy_id = pe.policy_id"
- + " JOIN "
- + POLICY_VERSION_TABLE_NAME
- + " pvi ON pm.policy_id = pvi.policy_id AND pm.current_version = pvi.version"
- + " WHERE pe.metadata_object_id = #{metadataObjectId}"
- + " AND pe.metadata_object_type = #{metadataObjectType} AND pe.deleted_at = 0"
- + " AND pm.deleted_at = 0 AND pvi.deleted_at = 0";
- }
-
- public String getPolicyPOsByMetadataObjectAndPolicyName(
- @Param("metadataObjectId") Long metadataObjectId,
- @Param("metadataObjectType") String metadataObjectType,
- @Param("policyName") String policyName) {
- return "SELECT pm.policy_id, pm.policy_name, pm.policy_type, pm.metalake_id,"
- + " pm.audit_info, pm.current_version, pm.last_version,"
- + " pm.deleted_at, pvi.id, pvi.metalake_id as version_metalake_id, pvi.policy_id as version_policy_id,"
- + " pvi.version, pvi.policy_comment, pvi.enabled, pvi.content, pvi.deleted_at as version_deleted_at"
- + " FROM "
- + PolicyMetaMapper.POLICY_META_TABLE_NAME
- + " pm JOIN "
- + PolicyMetadataObjectRelMapper.POLICY_METADATA_OBJECT_RELATION_TABLE_NAME
- + " pe ON pm.policy_id = pe.policy_id"
- + " JOIN "
- + POLICY_VERSION_TABLE_NAME
- + " pvi ON pm.policy_id = pvi.policy_id AND pm.current_version = pvi.version"
- + " WHERE pe.metadata_object_id = #{metadataObjectId}"
- + " AND pe.metadata_object_type = #{metadataObjectType} AND pm.policy_name = #{policyName}"
- + " AND pe.deleted_at = 0 AND pm.deleted_at = 0 AND pvi.deleted_at = 0";
- }
-
- public String listPolicyMetadataObjectRelsByMetalakeAndPolicyName(
- @Param("metalakeName") String metalakeName, @Param("policyName") String policyName) {
- return "SELECT pe.policy_id as policyId, pe.metadata_object_id as metadataObjectId,"
- + " pe.metadata_object_type as metadataObjectType, pe.audit_info as auditInfo,"
- + " pe.current_version as currentVersion, pe.last_version as lastVersion,"
- + " pe.deleted_at as deletedAt"
- + " FROM "
- + PolicyMetadataObjectRelMapper.POLICY_METADATA_OBJECT_RELATION_TABLE_NAME
- + " pe JOIN "
- + PolicyMetaMapper.POLICY_META_TABLE_NAME
- + " pm ON pe.policy_id = pm.policy_id"
- + " JOIN "
- + MetalakeMetaMapper.TABLE_NAME
- + " mm ON pm.metalake_id = mm.metalake_id"
- + " WHERE mm.metalake_name = #{metalakeName} AND pm.policy_name = #{policyName}"
- + " AND pe.deleted_at = 0 AND pm.deleted_at = 0 AND mm.deleted_at = 0";
- }
-
- public String batchInsertPolicyMetadataObjectRels(
- @Param("policyRels") List<PolicyMetadataObjectRelPO> policyRelPOs) {
- return "<script>"
- + "INSERT INTO "
- + PolicyMetadataObjectRelMapper.POLICY_METADATA_OBJECT_RELATION_TABLE_NAME
- + " (policy_id, metadata_object_id, metadata_object_type, audit_info,"
- + " current_version, last_version, deleted_at)"
- + " VALUES "
- + "<foreach collection='policyRels' item='item' separator=','>"
- + "(#{item.policyId},"
- + " #{item.metadataObjectId},"
- + " #{item.metadataObjectType},"
- + " #{item.auditInfo},"
- + " #{item.currentVersion},"
- + " #{item.lastVersion},"
- + " #{item.deletedAt})"
- + "</foreach>"
- + "</script>";
- }
-
- public String batchDeletePolicyMetadataObjectRelsByPolicyIdsAndMetadataObject(
- @Param("metadataObjectId") Long metadataObjectId,
- @Param("metadataObjectType") String metadataObjectType,
- @Param("policyIds") List<Long> policyIds) {
- return "<script>"
- + "UPDATE "
- + PolicyMetadataObjectRelMapper.POLICY_METADATA_OBJECT_RELATION_TABLE_NAME
- + " SET deleted_at = "
- + DatabaseTimeSQL.MYSQL
- + " WHERE policy_id IN "
- + "<foreach item='policyId' collection='policyIds' open='(' separator=',' close=')'>"
- + "#{policyId}"
- + "</foreach>"
- + " AND metadata_object_id = #{metadataObjectId}"
- + " AND metadata_object_type = #{metadataObjectType} AND deleted_at = 0"
- + "</script>";
- }
-
- /** Returns SQL that soft-deletes every active metadata-object relation for a policy ID. */
- public String softDeletePolicyMetadataObjectRelsByPolicyId(@Param("policyId") Long policyId) {
- return "UPDATE "
- + PolicyMetadataObjectRelMapper.POLICY_METADATA_OBJECT_RELATION_TABLE_NAME
- + " SET deleted_at = (UNIX_TIMESTAMP() * 1000.0)"
- + " + EXTRACT(MICROSECOND FROM CURRENT_TIMESTAMP(3)) / 1000"
- + " WHERE policy_id = #{policyId} AND deleted_at = 0";
- }
-
- public String softDeletePolicyMetadataObjectRelsByMetalakeId(
- @Param("metalakeId") Long metalakeId) {
- return "UPDATE "
- + PolicyMetadataObjectRelMapper.POLICY_METADATA_OBJECT_RELATION_TABLE_NAME
- + " pe JOIN "
- + PolicyMetaMapper.POLICY_META_TABLE_NAME
- + " pm ON pe.policy_id = pm.policy_id"
- + " SET pe.deleted_at = "
- + DatabaseTimeSQL.MYSQL
- + " WHERE pm.metalake_id = #{metalakeId}"
- + " AND pe.deleted_at = 0 AND pm.deleted_at = 0";
- }
-
- public String softDeletePolicyMetadataObjectRelsByMetadataObject(
- @Param("metadataObjectId") Long metadataObjectId,
- @Param("metadataObjectType") String metadataObjectType) {
- return " UPDATE "
- + PolicyMetadataObjectRelMapper.POLICY_METADATA_OBJECT_RELATION_TABLE_NAME
- + " SET deleted_at = "
- + DatabaseTimeSQL.MYSQL
- + " WHERE metadata_object_id = #{metadataObjectId} AND deleted_at = 0"
- + " AND metadata_object_type = #{metadataObjectType}";
- }
-
- public String softDeletePolicyMetadataObjectRelsByCatalogId(@Param("catalogId") Long catalogId) {
- return "UPDATE "
- + PolicyMetadataObjectRelMapper.POLICY_METADATA_OBJECT_RELATION_TABLE_NAME
- + " SET deleted_at = "
- + DatabaseTimeSQL.MYSQL
- + " WHERE deleted_at = 0 AND ("
- + " (metadata_object_type = 'CATALOG' AND metadata_object_id = #{catalogId})"
- + " OR (metadata_object_type = 'SCHEMA' AND metadata_object_id IN (SELECT schema_id FROM "
- + SchemaMetaMapper.TABLE_NAME
- + " WHERE catalog_id = #{catalogId}))"
- + " OR (metadata_object_type = 'TOPIC' AND metadata_object_id IN (SELECT topic_id FROM "
- + TopicMetaMapper.TABLE_NAME
- + " WHERE catalog_id = #{catalogId}))"
- + " OR (metadata_object_type = 'TABLE' AND metadata_object_id IN (SELECT table_id FROM "
- + TableMetaMapper.TABLE_NAME
- + " WHERE catalog_id = #{catalogId}))"
- + " OR (metadata_object_type = 'FILESET' AND metadata_object_id IN (SELECT fileset_id FROM "
- + FilesetMetaMapper.META_TABLE_NAME
- + " WHERE catalog_id = #{catalogId}))"
- + " OR (metadata_object_type = 'MODEL' AND metadata_object_id IN (SELECT model_id FROM "
- + ModelMetaMapper.TABLE_NAME
- + " WHERE catalog_id = #{catalogId}))"
- + " OR (metadata_object_type = 'VIEW' AND metadata_object_id IN (SELECT view_id FROM "
- + ViewMetaMapper.TABLE_NAME
- + " WHERE catalog_id = #{catalogId}))"
- + " OR (metadata_object_type = 'FUNCTION' AND metadata_object_id IN (SELECT function_id FROM "
- + FunctionMetaMapper.TABLE_NAME
- + " WHERE catalog_id = #{catalogId}))"
- + " )";
- }
-
- public String softDeletePolicyMetadataObjectRelsBySchemaIds(
- @Param("schemaIds") List<Long> schemaIds) {
- return "<script>"
- + "UPDATE "
- + PolicyMetadataObjectRelMapper.POLICY_METADATA_OBJECT_RELATION_TABLE_NAME
- + " SET deleted_at = "
- + DatabaseTimeSQL.MYSQL
- + " WHERE deleted_at = 0 AND ("
- + " (metadata_object_type = 'SCHEMA' AND metadata_object_id IN "
- + "<foreach collection='schemaIds' item='schemaId' open='(' close=')' separator=','>"
- + "#{schemaId}"
- + "</foreach>"
- + ")"
- + " OR (metadata_object_type = 'TOPIC' AND metadata_object_id IN (SELECT topic_id FROM "
- + TopicMetaMapper.TABLE_NAME
- + " WHERE schema_id IN "
- + "<foreach collection='schemaIds' item='schemaId' open='(' close=')' separator=','>"
- + "#{schemaId}"
- + "</foreach>"
- + "))"
- + " OR (metadata_object_type = 'TABLE' AND metadata_object_id IN (SELECT table_id FROM "
- + TableMetaMapper.TABLE_NAME
- + " WHERE schema_id IN "
- + "<foreach collection='schemaIds' item='schemaId' open='(' close=')' separator=','>"
- + "#{schemaId}"
- + "</foreach>"
- + "))"
- + " OR (metadata_object_type = 'FILESET' AND metadata_object_id IN (SELECT fileset_id FROM "
- + FilesetMetaMapper.META_TABLE_NAME
- + " WHERE schema_id IN "
- + "<foreach collection='schemaIds' item='schemaId' open='(' close=')' separator=','>"
- + "#{schemaId}"
- + "</foreach>"
- + "))"
- + " OR (metadata_object_type = 'MODEL' AND metadata_object_id IN (SELECT model_id FROM "
- + ModelMetaMapper.TABLE_NAME
- + " WHERE schema_id IN "
- + "<foreach collection='schemaIds' item='schemaId' open='(' close=')' separator=','>"
- + "#{schemaId}"
- + "</foreach>"
- + "))"
- + " OR (metadata_object_type = 'VIEW' AND metadata_object_id IN (SELECT view_id FROM "
- + ViewMetaMapper.TABLE_NAME
- + " WHERE schema_id IN "
- + "<foreach collection='schemaIds' item='schemaId' open='(' close=')' separator=','>"
- + "#{schemaId}"
- + "</foreach>"
- + "))"
- + " OR (metadata_object_type = 'FUNCTION' AND metadata_object_id IN (SELECT function_id FROM "
- + FunctionMetaMapper.TABLE_NAME
- + " WHERE schema_id IN "
- + "<foreach collection='schemaIds' item='schemaId' open='(' close=')' separator=','>"
- + "#{schemaId}"
- + "</foreach>"
- + "))"
- + " )"
- + "</script>";
- }
-
- public String softDeletePolicyMetadataObjectRelsByTableId(@Param("tableId") Long tableId) {
- return "UPDATE "
- + PolicyMetadataObjectRelMapper.POLICY_METADATA_OBJECT_RELATION_TABLE_NAME
- + " SET deleted_at = "
- + DatabaseTimeSQL.MYSQL
- + " WHERE metadata_object_id = #{tableId}"
- + " AND metadata_object_type = 'TABLE'"
- + " AND deleted_at = 0";
- }
-
- public String deletePolicyEntityRelsByLegacyTimeline(
- @Param("legacyTimeline") Long legacyTimeline, @Param("limit") int limit) {
- return "DELETE FROM "
- + PolicyMetadataObjectRelMapper.POLICY_METADATA_OBJECT_RELATION_TABLE_NAME
- + " WHERE deleted_at > 0 AND deleted_at < #{legacyTimeline} LIMIT #{limit}";
- }
-}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/PolicyMetadataObjectRelPostgreSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/PolicyMetadataObjectRelPostgreSQLProvider.java
deleted file mode 100644
index e2ae7b9345..0000000000
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/PolicyMetadataObjectRelPostgreSQLProvider.java
+++ /dev/null
@@ -1,239 +0,0 @@
-/*
- * 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.storage.relational.mapper.provider.postgresql;
-
-import static org.apache.gravitino.storage.relational.mapper.PolicyMetadataObjectRelMapper.POLICY_METADATA_OBJECT_RELATION_TABLE_NAME;
-
-import java.util.List;
-import org.apache.gravitino.storage.relational.mapper.CatalogMetaMapper;
-import org.apache.gravitino.storage.relational.mapper.FilesetMetaMapper;
-import org.apache.gravitino.storage.relational.mapper.FunctionMetaMapper;
-import org.apache.gravitino.storage.relational.mapper.MetalakeMetaMapper;
-import org.apache.gravitino.storage.relational.mapper.ModelMetaMapper;
-import org.apache.gravitino.storage.relational.mapper.PolicyMetaMapper;
-import org.apache.gravitino.storage.relational.mapper.SchemaMetaMapper;
-import org.apache.gravitino.storage.relational.mapper.TableColumnMapper;
-import org.apache.gravitino.storage.relational.mapper.TableMetaMapper;
-import org.apache.gravitino.storage.relational.mapper.TopicMetaMapper;
-import org.apache.gravitino.storage.relational.mapper.ViewMetaMapper;
-import org.apache.gravitino.storage.relational.mapper.provider.DatabaseTimeSQL;
-import org.apache.gravitino.storage.relational.mapper.provider.base.PolicyMetadataObjectRelBaseSQLProvider;
-import org.apache.ibatis.annotations.Param;
-
-public class PolicyMetadataObjectRelPostgreSQLProvider
- extends PolicyMetadataObjectRelBaseSQLProvider {
- private static final String DELETED_AT_NOW_EXPRESSION = " " + DatabaseTimeSQL.POSTGRESQL;
-
- @Override
- public String softDeletePolicyMetadataObjectRelsByPolicyId(Long policyId) {
- return "UPDATE "
- + POLICY_METADATA_OBJECT_RELATION_TABLE_NAME
- + " SET deleted_at ="
- + DELETED_AT_NOW_EXPRESSION
- + " WHERE policy_id = #{policyId} AND deleted_at = 0";
- }
-
- @Override
- public String softDeletePolicyMetadataObjectRelsByMetalakeId(Long metalakeId) {
- return "UPDATE "
- + POLICY_METADATA_OBJECT_RELATION_TABLE_NAME
- + " te SET deleted_at ="
- + DELETED_AT_NOW_EXPRESSION
- + " WHERE te.policy_id IN (SELECT tm.policy_id FROM "
- + PolicyMetaMapper.POLICY_META_TABLE_NAME
- + " tm WHERE tm.metalake_id = #{metalakeId} AND tm.deleted_at = 0) AND te.deleted_at = 0";
- }
-
- @Override
- public String softDeletePolicyMetadataObjectRelsByMetadataObject(
- @Param("metadataObjectId") Long metadataObjectId,
- @Param("metadataObjectType") String metadataObjectType) {
- return "UPDATE "
- + POLICY_METADATA_OBJECT_RELATION_TABLE_NAME
- + " SET deleted_at ="
- + DELETED_AT_NOW_EXPRESSION
- + " WHERE metadata_object_id = #{metadataObjectId} AND deleted_at = 0"
- + " AND metadata_object_type = #{metadataObjectType}";
- }
-
- @Override
- public String softDeletePolicyMetadataObjectRelsByCatalogId(@Param("catalogId") Long catalogId) {
- return "UPDATE "
- + POLICY_METADATA_OBJECT_RELATION_TABLE_NAME
- + " pe SET deleted_at ="
- + DELETED_AT_NOW_EXPRESSION
- + " FROM "
- + POLICY_METADATA_OBJECT_RELATION_TABLE_NAME
- + " pe_alias"
- + " LEFT JOIN "
- + CatalogMetaMapper.TABLE_NAME
- + " ct ON pe_alias.metadata_object_id = ct.catalog_id AND pe_alias.metadata_object_type = 'CATALOG'"
- + " LEFT JOIN "
- + SchemaMetaMapper.TABLE_NAME
- + " st ON pe_alias.metadata_object_id = st.schema_id AND pe_alias.metadata_object_type = 'SCHEMA'"
- + " LEFT JOIN "
- + TopicMetaMapper.TABLE_NAME
- + " tt ON pe_alias.metadata_object_id = tt.topic_id AND pe_alias.metadata_object_type = 'TOPIC'"
- + " LEFT JOIN "
- + TableMetaMapper.TABLE_NAME
- + " tat ON pe_alias.metadata_object_id = tat.table_id AND pe_alias.metadata_object_type = 'TABLE'"
- + " LEFT JOIN "
- + FilesetMetaMapper.META_TABLE_NAME
- + " ft ON pe_alias.metadata_object_id = ft.fileset_id AND pe_alias.metadata_object_type = 'FILESET'"
- + " LEFT JOIN "
- + ModelMetaMapper.TABLE_NAME
- + " mt ON pe_alias.metadata_object_id = mt.model_id AND pe_alias.metadata_object_type = 'MODEL'"
- + " LEFT JOIN "
- + ViewMetaMapper.TABLE_NAME
- + " vt ON pe_alias.metadata_object_id = vt.view_id AND pe_alias.metadata_object_type = 'VIEW'"
- + " LEFT JOIN "
- + FunctionMetaMapper.TABLE_NAME
- + " ft2 ON pe_alias.metadata_object_id = ft2.function_id AND pe_alias.metadata_object_type = 'FUNCTION'"
- + " WHERE pe.id = pe_alias.id AND pe.deleted_at = 0 AND ("
- + " ct.catalog_id = #{catalogId} OR st.catalog_id = #{catalogId} OR tt.catalog_id = #{catalogId}"
- + " OR tat.catalog_id = #{catalogId} OR ft.catalog_id = #{catalogId} OR mt.catalog_id = #{catalogId}"
- + " OR vt.catalog_id = #{catalogId} OR ft2.catalog_id = #{catalogId}"
- + " )";
- }
-
- @Override
- public String softDeletePolicyMetadataObjectRelsBySchemaIds(
- @Param("schemaIds") List<Long> schemaIds) {
- return "<script>"
- + "UPDATE "
- + POLICY_METADATA_OBJECT_RELATION_TABLE_NAME
- + " pe SET deleted_at ="
- + DELETED_AT_NOW_EXPRESSION
- + " FROM "
- + POLICY_METADATA_OBJECT_RELATION_TABLE_NAME
- + " pe_alias"
- + " LEFT JOIN "
- + SchemaMetaMapper.TABLE_NAME
- + " st ON pe_alias.metadata_object_id = st.schema_id AND pe_alias.metadata_object_type = 'SCHEMA'"
- + " LEFT JOIN "
- + TopicMetaMapper.TABLE_NAME
- + " tt ON pe_alias.metadata_object_id = tt.topic_id AND pe_alias.metadata_object_type = 'TOPIC'"
- + " LEFT JOIN "
- + TableMetaMapper.TABLE_NAME
- + " tat ON pe_alias.metadata_object_id = tat.table_id AND pe_alias.metadata_object_type = 'TABLE'"
- + " LEFT JOIN "
- + FilesetMetaMapper.META_TABLE_NAME
- + " ft ON pe_alias.metadata_object_id = ft.fileset_id AND pe_alias.metadata_object_type = 'FILESET'"
- + " LEFT JOIN "
- + ModelMetaMapper.TABLE_NAME
- + " mt ON pe_alias.metadata_object_id = mt.model_id AND pe_alias.metadata_object_type = 'MODEL'"
- + " LEFT JOIN "
- + ViewMetaMapper.TABLE_NAME
- + " vt ON pe_alias.metadata_object_id = vt.view_id AND pe_alias.metadata_object_type = 'VIEW'"
- + " LEFT JOIN "
- + FunctionMetaMapper.TABLE_NAME
- + " ft2 ON pe_alias.metadata_object_id = ft2.function_id AND pe_alias.metadata_object_type = 'FUNCTION'"
- + " WHERE pe.id = pe_alias.id AND pe.deleted_at = 0 AND ("
- + " st.schema_id IN "
- + "<foreach collection='schemaIds' item='schemaId' open='(' close=')' separator=','>"
- + "#{schemaId}"
- + "</foreach>"
- + " OR tt.schema_id IN "
- + "<foreach collection='schemaIds' item='schemaId' open='(' close=')' separator=','>"
- + "#{schemaId}"
- + "</foreach>"
- + " OR tat.schema_id IN "
- + "<foreach collection='schemaIds' item='schemaId' open='(' close=')' separator=','>"
- + "#{schemaId}"
- + "</foreach>"
- + " OR ft.schema_id IN "
- + "<foreach collection='schemaIds' item='schemaId' open='(' close=')' separator=','>"
- + "#{schemaId}"
- + "</foreach>"
- + " OR mt.schema_id IN "
- + "<foreach collection='schemaIds' item='schemaId' open='(' close=')' separator=','>"
- + "#{schemaId}"
- + "</foreach>"
- + " OR vt.schema_id IN "
- + "<foreach collection='schemaIds' item='schemaId' open='(' close=')' separator=','>"
- + "#{schemaId}"
- + "</foreach>"
- + " OR ft2.schema_id IN "
- + "<foreach collection='schemaIds' item='schemaId' open='(' close=')' separator=','>"
- + "#{schemaId}"
- + "</foreach>"
- + " )"
- + "</script>";
- }
-
- @Override
- public String softDeletePolicyMetadataObjectRelsByTableId(@Param("tableId") Long tableId) {
- return "UPDATE "
- + POLICY_METADATA_OBJECT_RELATION_TABLE_NAME
- + " SET deleted_at ="
- + DELETED_AT_NOW_EXPRESSION
- + " WHERE deleted_at = 0 AND ("
- + " (metadata_object_id = #{tableId} AND metadata_object_type = 'TABLE') OR "
- + " metadata_object_id IN (SELECT column_id FROM "
- + TableColumnMapper.COLUMN_TABLE_NAME
- + " WHERE table_id = #{tableId} AND deleted_at = 0)"
- + " AND metadata_object_type = 'COLUMN'"
- + ")";
- }
-
- @Override
- public String batchDeletePolicyMetadataObjectRelsByPolicyIdsAndMetadataObject(
- Long metadataObjectId, String metadataObjectType, List<Long> policyIds) {
- return "<script>"
- + "UPDATE "
- + POLICY_METADATA_OBJECT_RELATION_TABLE_NAME
- + " SET deleted_at ="
- + DELETED_AT_NOW_EXPRESSION
- + " WHERE policy_id IN "
- + "<foreach item='policyId' collection='policyIds' open='(' separator=',' close=')'>"
- + "#{policyId}"
- + "</foreach>"
- + " AND metadata_object_id = #{metadataObjectId}"
- + " AND metadata_object_type = #{metadataObjectType} AND deleted_at = 0"
- + "</script>";
- }
-
- @Override
- public String listPolicyMetadataObjectRelsByMetalakeAndPolicyName(
- String metalakeName, String policyName) {
- return "SELECT te.policy_id as policyId, te.metadata_object_id as metadataObjectId,"
- + " te.metadata_object_type as metadataObjectType, te.audit_info as auditInfo,"
- + " te.current_version as currentVersion, te.last_version as lastVersion,"
- + " te.deleted_at as deletedAt"
- + " FROM "
- + POLICY_METADATA_OBJECT_RELATION_TABLE_NAME
- + " te JOIN "
- + PolicyMetaMapper.POLICY_META_TABLE_NAME
- + " tm ON te.policy_id = tm.policy_id JOIN "
- + MetalakeMetaMapper.TABLE_NAME
- + " mm ON tm.metalake_id = mm.metalake_id"
- + " WHERE mm.metalake_name = #{metalakeName} AND tm.policy_name = #{policyName}"
- + " AND te.deleted_at = 0 AND tm.deleted_at = 0 AND mm.deleted_at = 0";
- }
-
- @Override
- public String deletePolicyEntityRelsByLegacyTimeline(
- @Param("legacyTimeline") Long legacyTimeline, @Param("limit") int limit) {
- return "DELETE FROM "
- + POLICY_METADATA_OBJECT_RELATION_TABLE_NAME
- + " WHERE id IN (SELECT id FROM "
- + POLICY_METADATA_OBJECT_RELATION_TABLE_NAME
- + " WHERE deleted_at > 0 AND deleted_at < #{legacyTimeline} LIMIT #{limit})";
- }
-}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/po/PolicyMetadataObjectRelPO.java b/core/src/main/java/org/apache/gravitino/storage/relational/po/PolicyMetadataObjectRelPO.java
deleted file mode 100644
index 4c24746124..0000000000
--- a/core/src/main/java/org/apache/gravitino/storage/relational/po/PolicyMetadataObjectRelPO.java
+++ /dev/null
@@ -1,131 +0,0 @@
-/*
- * 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.storage.relational.po;
-
-import com.google.common.base.Objects;
-import com.google.common.base.Preconditions;
-import lombok.Getter;
-import org.apache.commons.lang3.StringUtils;
-
-@Getter
-public class PolicyMetadataObjectRelPO {
- private Long policyId;
- private Long metadataObjectId;
- private String metadataObjectType;
- private String auditInfo;
- private Long currentVersion;
- private Long lastVersion;
- private Long deletedAt;
-
- public static Builder builder() {
- return new Builder();
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) {
- return true;
- }
- if (!(o instanceof PolicyMetadataObjectRelPO)) {
- return false;
- }
- PolicyMetadataObjectRelPO policyRelPO = (PolicyMetadataObjectRelPO) o;
- return Objects.equal(policyId, policyRelPO.policyId)
- && Objects.equal(metadataObjectId, policyRelPO.metadataObjectId)
- && Objects.equal(metadataObjectType, policyRelPO.metadataObjectType)
- && Objects.equal(auditInfo, policyRelPO.auditInfo)
- && Objects.equal(currentVersion, policyRelPO.currentVersion)
- && Objects.equal(lastVersion, policyRelPO.lastVersion)
- && Objects.equal(deletedAt, policyRelPO.deletedAt);
- }
-
- @Override
- public int hashCode() {
- return Objects.hashCode(
- policyId,
- metadataObjectId,
- metadataObjectType,
- auditInfo,
- currentVersion,
- lastVersion,
- deletedAt);
- }
-
- public static class Builder {
- private final PolicyMetadataObjectRelPO policyRelPO;
-
- private Builder() {
- policyRelPO = new PolicyMetadataObjectRelPO();
- }
-
- public Builder withPolicyId(Long policyId) {
- policyRelPO.policyId = policyId;
- return this;
- }
-
- public Builder withMetadataObjectId(Long metadataObjectId) {
- policyRelPO.metadataObjectId = metadataObjectId;
- return this;
- }
-
- public Builder withMetadataObjectType(String metadataObjectType) {
- policyRelPO.metadataObjectType = metadataObjectType;
- return this;
- }
-
- public Builder withAuditInfo(String auditInfo) {
- policyRelPO.auditInfo = auditInfo;
- return this;
- }
-
- public Builder withCurrentVersion(Long currentVersion) {
- policyRelPO.currentVersion = currentVersion;
- return this;
- }
-
- public Builder withLastVersion(Long lastVersion) {
- policyRelPO.lastVersion = lastVersion;
- return this;
- }
-
- public Builder withDeletedAt(Long deletedAt) {
- policyRelPO.deletedAt = deletedAt;
- return this;
- }
-
- private void validate() {
- Preconditions.checkArgument(policyRelPO.policyId != null, "Policy id is required");
- Preconditions.checkArgument(
- policyRelPO.metadataObjectId != null, "Metadata object id is required");
- Preconditions.checkArgument(
- StringUtils.isNotBlank(policyRelPO.metadataObjectType),
- "Metadata object type should not be empty");
- Preconditions.checkArgument(policyRelPO.auditInfo != null, "Audit info is required");
- Preconditions.checkArgument(
- policyRelPO.currentVersion != null, "Current version is required");
- Preconditions.checkArgument(policyRelPO.lastVersion != null, "Last version is required");
- Preconditions.checkArgument(policyRelPO.deletedAt != null, "Deleted at is required");
- }
-
- public PolicyMetadataObjectRelPO build() {
- validate();
- return policyRelPO;
- }
- }
-}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/CatalogMetaService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/CatalogMetaService.java
index d7895ec7c8..fdf966321f 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/service/CatalogMetaService.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/CatalogMetaService.java
@@ -46,7 +46,6 @@ import org.apache.gravitino.storage.relational.mapper.ModelMetaMapper;
import org.apache.gravitino.storage.relational.mapper.ModelVersionAliasRelMapper;
import org.apache.gravitino.storage.relational.mapper.ModelVersionMetaMapper;
import org.apache.gravitino.storage.relational.mapper.OwnerMetaMapper;
-import org.apache.gravitino.storage.relational.mapper.PolicyMetadataObjectRelMapper;
import org.apache.gravitino.storage.relational.mapper.SchemaMetaMapper;
import org.apache.gravitino.storage.relational.mapper.SecurableObjectMapper;
import org.apache.gravitino.storage.relational.mapper.StatisticMetaMapper;
@@ -326,10 +325,6 @@ public class CatalogMetaService {
SessionUtils.doWithoutCommit(
TagMetadataObjectRelMapper.class,
mapper -> mapper.softDeleteTagMetadataObjectRelsByCatalogId(catalogId)),
- () ->
- SessionUtils.doWithoutCommit(
- PolicyMetadataObjectRelMapper.class,
- mapper -> mapper.softDeletePolicyMetadataObjectRelsByCatalogId(catalogId)),
() ->
SessionUtils.doWithoutCommit(
ModelVersionAliasRelMapper.class,
@@ -393,13 +388,7 @@ public class CatalogMetaService {
() ->
SessionUtils.doWithoutCommit(
StatisticMetaMapper.class,
- mapper -> mapper.softDeleteStatisticsByEntityId(catalogId)),
- () ->
- SessionUtils.doWithoutCommit(
- PolicyMetadataObjectRelMapper.class,
- mapper ->
- mapper.softDeletePolicyMetadataObjectRelsByMetadataObject(
- catalogId, MetadataObject.Type.CATALOG.name())));
+ mapper -> mapper.softDeleteStatisticsByEntityId(catalogId)));
}
return true;
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/FilesetMetaService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/FilesetMetaService.java
index 67069b4244..29642f9106 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/service/FilesetMetaService.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/FilesetMetaService.java
@@ -43,7 +43,6 @@ import org.apache.gravitino.metrics.Monitored;
import org.apache.gravitino.storage.relational.mapper.FilesetMetaMapper;
import org.apache.gravitino.storage.relational.mapper.FilesetVersionMapper;
import org.apache.gravitino.storage.relational.mapper.OwnerMetaMapper;
-import org.apache.gravitino.storage.relational.mapper.PolicyMetadataObjectRelMapper;
import org.apache.gravitino.storage.relational.mapper.SecurableObjectMapper;
import org.apache.gravitino.storage.relational.mapper.StatisticMetaMapper;
import org.apache.gravitino.storage.relational.mapper.TagMetadataObjectRelMapper;
@@ -539,11 +538,6 @@ public class FilesetMetaService {
filesetId, MetadataObject.Type.FILESET.name()));
SessionUtils.doWithoutCommit(
StatisticMetaMapper.class, mapper -> mapper.softDeleteStatisticsByEntityId(filesetId));
- SessionUtils.doWithoutCommit(
- PolicyMetadataObjectRelMapper.class,
- mapper ->
- mapper.softDeletePolicyMetadataObjectRelsByMetadataObject(
- filesetId, MetadataObject.Type.FILESET.name()));
}
private RuntimeException filesetWriteFailure(
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/FunctionMetaService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/FunctionMetaService.java
index 9ffcaafe66..5719534ae3 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/service/FunctionMetaService.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/FunctionMetaService.java
@@ -44,7 +44,6 @@ import org.apache.gravitino.metrics.Monitored;
import org.apache.gravitino.storage.relational.mapper.FunctionMetaMapper;
import org.apache.gravitino.storage.relational.mapper.FunctionVersionMetaMapper;
import org.apache.gravitino.storage.relational.mapper.OwnerMetaMapper;
-import org.apache.gravitino.storage.relational.mapper.PolicyMetadataObjectRelMapper;
import org.apache.gravitino.storage.relational.mapper.SecurableObjectMapper;
import org.apache.gravitino.storage.relational.mapper.TagMetadataObjectRelMapper;
import org.apache.gravitino.storage.relational.po.FunctionMaxVersionPO;
@@ -462,11 +461,6 @@ public class FunctionMetaService {
mapper ->
mapper.softDeleteTagMetadataObjectRelsByMetadataObject(
functionId, MetadataObject.Type.FUNCTION.name()));
- SessionUtils.doWithoutCommit(
- PolicyMetadataObjectRelMapper.class,
- mapper ->
- mapper.softDeletePolicyMetadataObjectRelsByMetadataObject(
- functionId, MetadataObject.Type.FUNCTION.name()));
}
private RuntimeException functionWriteFailure(
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/ModelMetaService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/ModelMetaService.java
index eb8b3d8f70..386ff0f9fc 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/service/ModelMetaService.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/ModelMetaService.java
@@ -44,7 +44,6 @@ import org.apache.gravitino.storage.relational.mapper.ModelMetaMapper;
import org.apache.gravitino.storage.relational.mapper.ModelVersionAliasRelMapper;
import org.apache.gravitino.storage.relational.mapper.ModelVersionMetaMapper;
import org.apache.gravitino.storage.relational.mapper.OwnerMetaMapper;
-import org.apache.gravitino.storage.relational.mapper.PolicyMetadataObjectRelMapper;
import org.apache.gravitino.storage.relational.mapper.SecurableObjectMapper;
import org.apache.gravitino.storage.relational.mapper.StatisticMetaMapper;
import org.apache.gravitino.storage.relational.mapper.TagMetadataObjectRelMapper;
@@ -517,10 +516,5 @@ public class ModelMetaService {
modelId, MetadataObject.Type.MODEL.name()));
SessionUtils.doWithoutCommit(
StatisticMetaMapper.class, mapper -> mapper.softDeleteStatisticsByEntityId(modelId));
- SessionUtils.doWithoutCommit(
- PolicyMetadataObjectRelMapper.class,
- mapper ->
- mapper.softDeletePolicyMetadataObjectRelsByMetadataObject(
- modelId, MetadataObject.Type.MODEL.name()));
}
}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/OrphanedMetadataObjectRelationService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/OrphanedMetadataObjectRelationService.java
index a0b21d3c28..d4269bf7e4 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/service/OrphanedMetadataObjectRelationService.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/OrphanedMetadataObjectRelationService.java
@@ -121,12 +121,6 @@ public class OrphanedMetadataObjectRelationService {
metadataObjectType.name(),
deletedAt,
limit)
- + mapper.softDeleteOrphanedPolicyRelations(
- entityTable.tableName,
- entityTable.idColumn,
- metadataObjectType.name(),
- deletedAt,
- limit)
+ mapper.softDeleteOrphanedStatistics(
entityTable.tableName,
entityTable.idColumn,
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/PolicyMetaService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/PolicyMetaService.java
index 71ed987f9c..2dc8e1be43 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/service/PolicyMetaService.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/PolicyMetaService.java
@@ -24,8 +24,6 @@ import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import java.io.IOException;
import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -39,27 +37,21 @@ import org.apache.gravitino.MetadataObject;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
import org.apache.gravitino.exceptions.NoSuchEntityException;
-import org.apache.gravitino.meta.GenericEntity;
import org.apache.gravitino.meta.PolicyEntity;
import org.apache.gravitino.metrics.Monitored;
import org.apache.gravitino.storage.relational.mapper.MetalakeMetaMapper;
import org.apache.gravitino.storage.relational.mapper.OwnerMetaMapper;
import org.apache.gravitino.storage.relational.mapper.PolicyMetaMapper;
-import org.apache.gravitino.storage.relational.mapper.PolicyMetadataObjectRelMapper;
import org.apache.gravitino.storage.relational.mapper.PolicyTagRelMapper;
import org.apache.gravitino.storage.relational.mapper.PolicyVersionMapper;
import org.apache.gravitino.storage.relational.mapper.SecurableObjectMapper;
import org.apache.gravitino.storage.relational.mapper.TagMetadataObjectRelMapper;
import org.apache.gravitino.storage.relational.po.MetalakePO;
import org.apache.gravitino.storage.relational.po.PolicyMaxVersionPO;
-import org.apache.gravitino.storage.relational.po.PolicyMetadataObjectRelPO;
import org.apache.gravitino.storage.relational.po.PolicyPO;
import org.apache.gravitino.storage.relational.utils.ExceptionUtils;
import org.apache.gravitino.storage.relational.utils.POConverters;
import org.apache.gravitino.storage.relational.utils.SessionUtils;
-import org.apache.gravitino.utils.MetadataObjectUtil;
-import org.apache.gravitino.utils.NameIdentifierUtil;
-import org.apache.gravitino.utils.NamespaceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -204,10 +196,6 @@ public class PolicyMetaService {
SessionUtils.doWithoutCommit(
PolicyVersionMapper.class,
mapper -> mapper.softDeletePolicyVersionsByPolicyId(policyId)),
- () ->
- SessionUtils.doWithoutCommit(
- PolicyMetadataObjectRelMapper.class,
- mapper -> mapper.softDeletePolicyMetadataObjectRelsByPolicyId(policyId)),
() ->
SessionUtils.doWithoutCommit(
PolicyTagRelMapper.class, mapper -> mapper.softDeleteByPolicyId(policyId)),
@@ -235,127 +223,6 @@ public class PolicyMetaService {
}
}
- @Monitored(
- metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
- baseMetricName = "listPoliciesForMetadataObject")
- public List<PolicyEntity> listPoliciesForMetadataObject(
- NameIdentifier objectIdent, Entity.EntityType objectType)
- throws NoSuchEntityException, IOException {
- MetadataObject metadataObject = NameIdentifierUtil.toMetadataObject(objectIdent, objectType);
- String metalake = objectIdent.namespace().level(0);
-
- List<PolicyPO> PolicyPOs;
- try {
- Long metadataObjectId = EntityIdService.getEntityId(objectIdent, objectType);
-
- PolicyPOs =
- SessionUtils.getWithoutCommit(
- PolicyMetadataObjectRelMapper.class,
- mapper ->
- mapper.listPolicyPOsByMetadataObjectIdAndType(
- metadataObjectId, metadataObject.type().toString()));
- } catch (RuntimeException e) {
- ExceptionUtils.checkSQLException(e, Entity.EntityType.POLICY, objectIdent.toString());
- throw e;
- }
-
- return PolicyPOs.stream()
- .map(PolicyPO -> POConverters.fromPolicyPO(PolicyPO, NamespaceUtil.ofPolicy(metalake)))
- .collect(Collectors.toList());
- }
-
- @Monitored(
- metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
- baseMetricName = "getPolicyForMetadataObject")
- public PolicyEntity getPolicyForMetadataObject(
- NameIdentifier objectIdent, Entity.EntityType objectType, NameIdentifier policyIdent)
- throws NoSuchEntityException, IOException {
- MetadataObject metadataObject = NameIdentifierUtil.toMetadataObject(objectIdent, objectType);
- String metalake = objectIdent.namespace().level(0);
-
- PolicyPO policyPO;
- try {
- Long metadataObjectId = EntityIdService.getEntityId(objectIdent, objectType);
-
- policyPO =
- SessionUtils.getWithoutCommit(
- PolicyMetadataObjectRelMapper.class,
- mapper ->
- mapper.getPolicyPOsByMetadataObjectAndPolicyName(
- metadataObjectId, metadataObject.type().toString(), policyIdent.name()));
- } catch (RuntimeException e) {
- ExceptionUtils.checkSQLException(e, Entity.EntityType.POLICY, policyIdent.toString());
- throw e;
- }
-
- if (policyPO == null) {
- throw new NoSuchEntityException(
- NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
- Entity.EntityType.POLICY.name().toLowerCase(),
- policyIdent.name());
- }
-
- return POConverters.fromPolicyPO(policyPO, NamespaceUtil.ofPolicy(metalake));
- }
-
- @Monitored(
- metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
- baseMetricName = "listAssociatedEntitiesForPolicy")
- public List<GenericEntity> listAssociatedEntitiesForPolicy(NameIdentifier policyIdent)
- throws IOException {
- String metalakeName = policyIdent.namespace().level(0);
- String policyName = policyIdent.name();
-
- try {
- List<PolicyMetadataObjectRelPO> policyMetadataObjectRelPOs =
- SessionUtils.doWithCommitAndFetchResult(
- PolicyMetadataObjectRelMapper.class,
- mapper ->
- mapper.listPolicyMetadataObjectRelsByMetalakeAndPolicyName(
- metalakeName, policyName));
-
- return policyMetadataObjectRelPOs.stream()
- .map(
- r ->
- GenericEntity.builder()
- .withId(r.getMetadataObjectId())
- .withEntityType(
- MetadataObjectUtil.toEntityType(
- MetadataObject.Type.valueOf(r.getMetadataObjectType())))
- .build())
- .collect(Collectors.toList());
-
- } catch (RuntimeException e) {
- ExceptionUtils.checkSQLException(e, Entity.EntityType.POLICY, policyIdent.toString());
- throw e;
- }
- }
-
- @Monitored(
- metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
- baseMetricName = "associatePoliciesWithMetadataObject")
- public List<PolicyEntity> associatePoliciesWithMetadataObject(
- NameIdentifier objectIdent,
- Entity.EntityType objectType,
- NameIdentifier[] policiesToAdd,
- NameIdentifier[] policiesToRemove)
- throws NoSuchEntityException, EntityAlreadyExistsException, IOException {
- try {
- // One transaction for the whole association change: the policy rows stay locked from the
- // moment they are read until the relation rows are rewritten and read back, so a conflict
- // rolls the whole change back instead of leaving a half-applied association set behind. The
- // mapper handed to the callback is unused; the call only opens and closes the transaction.
- return SessionUtils.doWithCommitAndFetchResult(
- PolicyMetaMapper.class,
- ignored ->
- associatePoliciesWithMetadataObjectWithoutCommit(
- objectIdent, objectType, policiesToAdd, policiesToRemove));
- } catch (RuntimeException e) {
- ExceptionUtils.checkSQLException(e, Entity.EntityType.POLICY, objectIdent.toString());
- throw e;
- }
- }
-
@Monitored(
metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
baseMetricName = "deletePolicyAndVersionMetasByLegacyTimeline")
@@ -447,73 +314,6 @@ public class PolicyMetaService {
});
}
- private List<PolicyEntity> associatePoliciesWithMetadataObjectWithoutCommit(
- NameIdentifier objectIdent,
- Entity.EntityType objectType,
- NameIdentifier[] policiesToAdd,
- NameIdentifier[] policiesToRemove) {
- MetadataObject metadataObject = NameIdentifierUtil.toMetadataObject(objectIdent, objectType);
- String metalake = objectIdent.namespace().level(0);
-
- Long metadataObjectId = EntityIdService.getEntityId(objectIdent, objectType);
-
- // Fetch all the policies need to associate with the metadata object.
- List<String> policyNamesToAdd =
- Arrays.stream(policiesToAdd).map(NameIdentifier::name).collect(Collectors.toList());
- List<PolicyPO> policyPOsToAdd =
- policyNamesToAdd.isEmpty()
- ? Collections.emptyList()
- : getPolicyPOsByMetalakeAndNames(metalake, policyNamesToAdd);
-
- // Fetch all the policies need to remove from the metadata object.
- List<String> policyNamesToRemove =
- Arrays.stream(policiesToRemove).map(NameIdentifier::name).collect(Collectors.toList());
- List<PolicyPO> policyPOsToRemove =
- policyNamesToRemove.isEmpty()
- ? Collections.emptyList()
- : getPolicyPOsByMetalakeAndNames(metalake, policyNamesToRemove);
- Map<Long, PolicyPO> lockedPolicyPOs =
- lockPoliciesForAssociation(policyPOsToAdd, policyPOsToRemove);
- policyPOsToAdd = currentPolicyPOs(policyPOsToAdd, lockedPolicyPOs);
- policyPOsToRemove = currentPolicyPOs(policyPOsToRemove, lockedPolicyPOs);
-
- if (!policyPOsToAdd.isEmpty()) {
- List<PolicyMetadataObjectRelPO> policyRelsToAdd =
- policyPOsToAdd.stream()
- .map(
- policyPO ->
- POConverters.initializePolicyMetadataObjectRelPOWithVersion(
- policyPO.getPolicyId(),
- metadataObjectId,
- metadataObject.type().toString()))
- .collect(Collectors.toList());
- SessionUtils.doWithoutCommit(
- PolicyMetadataObjectRelMapper.class,
- mapper -> mapper.batchInsertPolicyMetadataObjectRels(policyRelsToAdd));
- }
- if (!policyPOsToRemove.isEmpty()) {
- List<Long> policyIdsToRemove =
- policyPOsToRemove.stream().map(PolicyPO::getPolicyId).collect(Collectors.toList());
- SessionUtils.doWithoutCommit(
- PolicyMetadataObjectRelMapper.class,
- mapper ->
- mapper.batchDeletePolicyMetadataObjectRelsByPolicyIdsAndMetadataObject(
- metadataObjectId, metadataObject.type().toString(), policyIdsToRemove));
- }
-
- // Fetch all the policies associated with the metadata object after the operation.
- List<PolicyPO> policyPOs =
- SessionUtils.getWithoutCommit(
- PolicyMetadataObjectRelMapper.class,
- mapper ->
- mapper.listPolicyPOsByMetadataObjectIdAndType(
- metadataObjectId, metadataObject.type().toString()));
-
- return policyPOs.stream()
- .map(policyPO -> POConverters.fromPolicyPO(policyPO, NamespaceUtil.ofPolicy(metalake)))
- .collect(Collectors.toList());
- }
-
/**
* Holds the parent metalake row for the rest of the transaction, so a policy cannot be created
* under a metalake that is going away.
@@ -676,21 +476,6 @@ public class PolicyMetaService {
&& Objects.equals(current.getMetalakeId(), observedPolicyPO.getMetalakeId()));
}
- /**
- * Locks every policy taking part in an association change and returns the rows as they are now,
- * keyed by policy ID, so the association cannot be written against a policy that is being renamed
- * or dropped.
- *
- * <p>The rows are locked in policy-ID order. Two association changes that touch the same policies
- * therefore take the locks in the same order and queue up instead of deadlocking.
- */
- private Map<Long, PolicyPO> lockPoliciesForAssociation(
- List<PolicyPO> policyPOsToAdd, List<PolicyPO> policyPOsToRemove) {
- List<PolicyPO> observedPolicyPOs = new ArrayList<>(policyPOsToAdd);
- observedPolicyPOs.addAll(policyPOsToRemove);
- return lockPolicies(observedPolicyPOs);
- }
-
/**
* Locks the given policy rows and returns them as they are now, keyed by policy ID.
*
@@ -733,13 +518,6 @@ public class PolicyMetaService {
return lockedPolicyPOs;
}
- private static List<PolicyPO> currentPolicyPOs(
- List<PolicyPO> observedPolicyPOs, Map<Long, PolicyPO> lockedPolicyPOs) {
- return observedPolicyPOs.stream()
- .map(policyPO -> lockedPolicyPOs.get(policyPO.getPolicyId()))
- .collect(Collectors.toList());
- }
-
private PolicyPO getPolicyPOByMetalakeAndName(String metalakeName, String policyName) {
PolicyPO policyPO =
SessionUtils.getWithoutCommit(
@@ -754,11 +532,4 @@ public class PolicyMetaService {
}
return policyPO;
}
-
- private List<PolicyPO> getPolicyPOsByMetalakeAndNames(
- String metalakeName, List<String> policyNames) {
- return SessionUtils.getWithoutCommit(
- PolicyMetaMapper.class,
- mapper -> mapper.listPolicyPOsByMetalakeAndPolicyNames(metalakeName, policyNames));
- }
}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/SchemaMetaService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/SchemaMetaService.java
index 151da5beac..5e03b3d860 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/service/SchemaMetaService.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/SchemaMetaService.java
@@ -53,7 +53,6 @@ import org.apache.gravitino.storage.relational.mapper.ModelMetaMapper;
import org.apache.gravitino.storage.relational.mapper.ModelVersionAliasRelMapper;
import org.apache.gravitino.storage.relational.mapper.ModelVersionMetaMapper;
import org.apache.gravitino.storage.relational.mapper.OwnerMetaMapper;
-import org.apache.gravitino.storage.relational.mapper.PolicyMetadataObjectRelMapper;
import org.apache.gravitino.storage.relational.mapper.SchemaMetaMapper;
import org.apache.gravitino.storage.relational.mapper.SecurableObjectMapper;
import org.apache.gravitino.storage.relational.mapper.StatisticMetaMapper;
@@ -332,10 +331,6 @@ public class SchemaMetaService {
SessionUtils.doWithoutCommit(
TagMetadataObjectRelMapper.class,
mapper -> mapper.softDeleteTagMetadataObjectRelsBySchemaIds(schemaIds.get())),
- () ->
- SessionUtils.doWithoutCommit(
- PolicyMetadataObjectRelMapper.class,
- mapper -> mapper.softDeletePolicyMetadataObjectRelsBySchemaIds(schemaIds.get())),
() ->
SessionUtils.doWithoutCommit(
ModelVersionAliasRelMapper.class,
@@ -393,13 +388,7 @@ public class SchemaMetaService {
() ->
SessionUtils.doWithoutCommit(
StatisticMetaMapper.class,
- mapper -> mapper.softDeleteStatisticsByEntityId(schemaId)),
- () ->
- SessionUtils.doWithoutCommit(
- PolicyMetadataObjectRelMapper.class,
- mapper ->
- mapper.softDeletePolicyMetadataObjectRelsByMetadataObject(
- schemaId, MetadataObject.Type.SCHEMA.name())));
+ mapper -> mapper.softDeleteStatisticsByEntityId(schemaId)));
}
return true;
}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/TableMetaService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/TableMetaService.java
index 3342715558..e0da487bbd 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/service/TableMetaService.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/TableMetaService.java
@@ -38,7 +38,6 @@ import org.apache.gravitino.meta.NamespacedEntityId;
import org.apache.gravitino.meta.TableEntity;
import org.apache.gravitino.metrics.Monitored;
import org.apache.gravitino.storage.relational.mapper.OwnerMetaMapper;
-import org.apache.gravitino.storage.relational.mapper.PolicyMetadataObjectRelMapper;
import org.apache.gravitino.storage.relational.mapper.SecurableObjectMapper;
import org.apache.gravitino.storage.relational.mapper.StatisticMetaMapper;
import org.apache.gravitino.storage.relational.mapper.TableMetaMapper;
@@ -408,9 +407,6 @@ public class TableMetaService {
SessionUtils.doWithoutCommit(
StatisticMetaMapper.class,
mapper -> mapper.softDeleteStatisticsByEntityId(tablePO.getTableId()));
- SessionUtils.doWithoutCommit(
- PolicyMetadataObjectRelMapper.class,
- mapper -> mapper.softDeletePolicyMetadataObjectRelsByTableId(tablePO.getTableId()));
SessionUtils.doWithoutCommit(
TableVersionMapper.class,
mapper ->
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/TagMetaService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/TagMetaService.java
index 01f214234b..cbf8b2e3a6 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/service/TagMetaService.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/TagMetaService.java
@@ -53,7 +53,6 @@ import org.apache.gravitino.meta.TagEntity;
import org.apache.gravitino.metrics.Monitored;
import org.apache.gravitino.storage.relational.mapper.MetalakeMetaMapper;
import org.apache.gravitino.storage.relational.mapper.OwnerMetaMapper;
-import org.apache.gravitino.storage.relational.mapper.PolicyMetadataObjectRelMapper;
import org.apache.gravitino.storage.relational.mapper.PolicyTagRelMapper;
import org.apache.gravitino.storage.relational.mapper.SecurableObjectMapper;
import org.apache.gravitino.storage.relational.mapper.TagMetaMapper;
@@ -588,12 +587,6 @@ public class TagMetaService {
() ->
SessionUtils.doWithoutCommit(
PolicyTagRelMapper.class, mapper -> mapper.softDeleteByTagId(tagId)),
- () ->
- SessionUtils.doWithoutCommit(
- PolicyMetadataObjectRelMapper.class,
- mapper ->
- mapper.softDeletePolicyMetadataObjectRelsByMetadataObject(
- tagId, MetadataObject.Type.TAG.name())),
() ->
SessionUtils.doWithoutCommit(
OwnerMetaMapper.class,
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/TopicMetaService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/TopicMetaService.java
index 28c94cd763..0b4072d85c 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/service/TopicMetaService.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/TopicMetaService.java
@@ -37,7 +37,6 @@ import org.apache.gravitino.meta.NamespacedEntityId;
import org.apache.gravitino.meta.TopicEntity;
import org.apache.gravitino.metrics.Monitored;
import org.apache.gravitino.storage.relational.mapper.OwnerMetaMapper;
-import org.apache.gravitino.storage.relational.mapper.PolicyMetadataObjectRelMapper;
import org.apache.gravitino.storage.relational.mapper.SecurableObjectMapper;
import org.apache.gravitino.storage.relational.mapper.StatisticMetaMapper;
import org.apache.gravitino.storage.relational.mapper.TagMetadataObjectRelMapper;
@@ -380,11 +379,6 @@ public class TopicMetaService {
topicId, MetadataObject.Type.TOPIC.name()));
SessionUtils.doWithoutCommit(
StatisticMetaMapper.class, mapper -> mapper.softDeleteStatisticsByEntityId(topicId));
- SessionUtils.doWithoutCommit(
- PolicyMetadataObjectRelMapper.class,
- mapper ->
- mapper.softDeletePolicyMetadataObjectRelsByMetadataObject(
- topicId, MetadataObject.Type.TOPIC.name()));
}
private RuntimeException topicWriteFailure(NameIdentifier identifier, TopicPO observedTopicPO) {
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/ViewMetaService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/ViewMetaService.java
index 614f2c0f26..d5b2f8026f 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/service/ViewMetaService.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/ViewMetaService.java
@@ -40,7 +40,6 @@ import org.apache.gravitino.meta.NamespacedEntityId;
import org.apache.gravitino.meta.ViewEntity;
import org.apache.gravitino.metrics.Monitored;
import org.apache.gravitino.storage.relational.mapper.OwnerMetaMapper;
-import org.apache.gravitino.storage.relational.mapper.PolicyMetadataObjectRelMapper;
import org.apache.gravitino.storage.relational.mapper.SecurableObjectMapper;
import org.apache.gravitino.storage.relational.mapper.TagMetadataObjectRelMapper;
import org.apache.gravitino.storage.relational.mapper.ViewMetaMapper;
@@ -396,11 +395,6 @@ public class ViewMetaService {
mapper ->
mapper.softDeleteTagMetadataObjectRelsByMetadataObject(
viewId, MetadataObject.Type.VIEW.name()));
- SessionUtils.doWithoutCommit(
- PolicyMetadataObjectRelMapper.class,
- mapper ->
- mapper.softDeletePolicyMetadataObjectRelsByMetadataObject(
- viewId, MetadataObject.Type.VIEW.name()));
}
private RuntimeException viewWriteFailure(NameIdentifier identifier, ViewPO observedViewPO) {
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/utils/POConverters.java b/core/src/main/java/org/apache/gravitino/storage/relational/utils/POConverters.java
index 9f87f4c0fb..71025147dc 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/utils/POConverters.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/utils/POConverters.java
@@ -81,7 +81,6 @@ import org.apache.gravitino.storage.relational.po.ModelPO;
import org.apache.gravitino.storage.relational.po.ModelVersionAliasRelPO;
import org.apache.gravitino.storage.relational.po.ModelVersionPO;
import org.apache.gravitino.storage.relational.po.OwnerRelPO;
-import org.apache.gravitino.storage.relational.po.PolicyMetadataObjectRelPO;
import org.apache.gravitino.storage.relational.po.PolicyPO;
import org.apache.gravitino.storage.relational.po.PolicyVersionPO;
import org.apache.gravitino.storage.relational.po.RolePO;
@@ -1538,29 +1537,6 @@ public class POConverters {
}
}
- public static PolicyMetadataObjectRelPO initializePolicyMetadataObjectRelPOWithVersion(
- Long policyId, Long metadataObjectId, String metadataObjectType) {
- try {
- AuditInfo auditInfo =
- AuditInfo.builder()
- .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
- .withCreateTime(Instant.now())
- .build();
-
- return PolicyMetadataObjectRelPO.builder()
- .withPolicyId(policyId)
- .withMetadataObjectId(metadataObjectId)
- .withMetadataObjectType(metadataObjectType)
- .withAuditInfo(JsonUtils.anyFieldMapper().writeValueAsString(auditInfo))
- .withCurrentVersion(INIT_VERSION)
- .withLastVersion(INIT_VERSION)
- .withDeletedAt(DEFAULT_DELETED_AT)
- .build();
- } catch (JsonProcessingException e) {
- throw new RuntimeException("Failed to serialize json object:", e);
- }
- }
-
public static OwnerRelPO initializeOwnerRelPOsWithVersion(
Long metalakeId,
String ownerType,
diff --git a/core/src/test/java/org/apache/gravitino/listener/api/event/TestPolicyEvent.java b/core/src/test/java/org/apache/gravitino/listener/api/event/TestPolicyEvent.java
index eed972ead6..49c9b05fe0 100644
--- a/core/src/test/java/org/apache/gravitino/listener/api/event/TestPolicyEvent.java
+++ b/core/src/test/java/org/apache/gravitino/listener/api/event/TestPolicyEvent.java
@@ -37,9 +37,6 @@ import org.apache.gravitino.listener.PolicyEventDispatcher;
import org.apache.gravitino.listener.api.event.policy.AlterPolicyEvent;
import org.apache.gravitino.listener.api.event.policy.AlterPolicyFailureEvent;
import org.apache.gravitino.listener.api.event.policy.AlterPolicyPreEvent;
-import org.apache.gravitino.listener.api.event.policy.AssociatePoliciesForMetadataObjectEvent;
-import org.apache.gravitino.listener.api.event.policy.AssociatePoliciesForMetadataObjectFailureEvent;
-import org.apache.gravitino.listener.api.event.policy.AssociatePoliciesForMetadataObjectPreEvent;
import org.apache.gravitino.listener.api.event.policy.CreatePolicyEvent;
import org.apache.gravitino.listener.api.event.policy.CreatePolicyFailureEvent;
import org.apache.gravitino.listener.api.event.policy.CreatePolicyPreEvent;
@@ -54,13 +51,7 @@ import org.apache.gravitino.listener.api.event.policy.EnablePolicyFailureEvent;
import org.apache.gravitino.listener.api.event.policy.EnablePolicyPreEvent;
import org.apache.gravitino.listener.api.event.policy.GetPolicyEvent;
import org.apache.gravitino.listener.api.event.policy.GetPolicyFailureEvent;
-import org.apache.gravitino.listener.api.event.policy.GetPolicyForMetadataObjectEvent;
-import org.apache.gravitino.listener.api.event.policy.GetPolicyForMetadataObjectFailureEvent;
-import org.apache.gravitino.listener.api.event.policy.GetPolicyForMetadataObjectPreEvent;
import org.apache.gravitino.listener.api.event.policy.GetPolicyPreEvent;
-import org.apache.gravitino.listener.api.event.policy.ListMetadataObjectsForPolicyEvent;
-import org.apache.gravitino.listener.api.event.policy.ListMetadataObjectsForPolicyFailureEvent;
-import org.apache.gravitino.listener.api.event.policy.ListMetadataObjectsForPolicyPreEvent;
import org.apache.gravitino.listener.api.event.policy.ListPoliciesEvent;
import org.apache.gravitino.listener.api.event.policy.ListPoliciesFailureEvent;
import org.apache.gravitino.listener.api.event.policy.ListPoliciesPreEvent;
@@ -290,36 +281,6 @@ public class TestPolicyEvent {
Assertions.assertEquals(OperationStatus.SUCCESS, postevent.operationStatus());
}
- @Test
- void testListMetadataObjectsForPolicyEvent() {
- dispatcher.listMetadataObjectsForPolicy("metalake", policy.name());
- PreEvent preEvent = dummyEventListener.popPreEvent();
- NameIdentifier identifier = NameIdentifierUtil.ofPolicy("metalake", policy.name());
-
- Assertions.assertEquals(identifier.toString(), preEvent.identifier().toString());
- Assertions.assertEquals(ListMetadataObjectsForPolicyPreEvent.class, preEvent.getClass());
- Assertions.assertEquals(
- OperationType.LIST_METADATA_OBJECTS_FOR_POLICY, preEvent.operationType());
- Assertions.assertEquals(OperationStatus.UNPROCESSED, preEvent.operationStatus());
-
- Event postevent = dummyEventListener.popPostEvent();
- Assertions.assertEquals(identifier.toString(), postevent.identifier().toString());
- Assertions.assertEquals(ListMetadataObjectsForPolicyEvent.class, postevent.getClass());
- Assertions.assertEquals(
- OperationType.LIST_METADATA_OBJECTS_FOR_POLICY, postevent.operationType());
- Assertions.assertEquals(OperationStatus.SUCCESS, postevent.operationStatus());
- Assertions.assertEquals(1, ((ListMetadataObjectsForPolicyEvent) postevent).resultCount());
- }
-
- @Test
- @SuppressWarnings("deprecation")
- void testListMetadataObjectsForPolicyEventDeprecatedConstructorReturnsNegativeCount() {
- NameIdentifier identifier = NameIdentifierUtil.ofPolicy("metalake", policy.name());
- ListMetadataObjectsForPolicyEvent event =
- new ListMetadataObjectsForPolicyEvent("user", identifier);
- Assertions.assertEquals(-1, event.resultCount());
- }
-
@Test
void testListPolicyInfosForMetadataObjectEvent() {
MetadataObject metadataObject =
@@ -358,80 +319,6 @@ public class TestPolicyEvent {
Assertions.assertEquals(-1, event.resultCount());
}
- @Test
- void testAssociatePoliciesForMetadataObjectEvent() {
- MetadataObject metadataObject =
- NameIdentifierUtil.toMetadataObject(
- NameIdentifierUtil.ofCatalog("metalake", "catalog_for_test"),
- Entity.EntityType.CATALOG);
-
- String[] policiesToAdd = {"policy1", "policy2"};
- String[] policiesToRemove = {"policy3"};
-
- dispatcher.associatePoliciesForMetadataObject(
- "metalake", metadataObject, policiesToAdd, policiesToRemove);
- PreEvent preEvent = dummyEventListener.popPreEvent();
-
- NameIdentifier identifier = MetadataObjectUtil.toEntityIdent("metalake", metadataObject);
-
- Assertions.assertEquals(identifier.toString(), preEvent.identifier().toString());
- Assertions.assertEquals(AssociatePoliciesForMetadataObjectPreEvent.class, preEvent.getClass());
- Assertions.assertEquals(
- MetadataObject.Type.CATALOG,
- ((AssociatePoliciesForMetadataObjectPreEvent) preEvent).metadataObject().type());
- Assertions.assertArrayEquals(
- policiesToAdd, ((AssociatePoliciesForMetadataObjectPreEvent) preEvent).policiesToAdd());
- Assertions.assertArrayEquals(
- policiesToRemove,
- ((AssociatePoliciesForMetadataObjectPreEvent) preEvent).policiesToRemove());
-
- Assertions.assertEquals(
- OperationType.ASSOCIATE_POLICIES_FOR_METADATA_OBJECT, preEvent.operationType());
- Assertions.assertEquals(OperationStatus.UNPROCESSED, preEvent.operationStatus());
-
- Event postevent = dummyEventListener.popPostEvent();
- Assertions.assertEquals(identifier.toString(), postevent.identifier().toString());
- Assertions.assertEquals(AssociatePoliciesForMetadataObjectEvent.class, postevent.getClass());
- Assertions.assertEquals(
- MetadataObject.Type.CATALOG,
- ((AssociatePoliciesForMetadataObjectEvent) postevent).metadataObject().type());
- Assertions.assertArrayEquals(
- policiesToAdd, ((AssociatePoliciesForMetadataObjectEvent) postevent).policiesToAdd());
- Assertions.assertArrayEquals(
- policiesToRemove, ((AssociatePoliciesForMetadataObjectEvent) postevent).policiesToRemove());
- Assertions.assertEquals(
- OperationType.ASSOCIATE_POLICIES_FOR_METADATA_OBJECT, postevent.operationType());
- Assertions.assertEquals(OperationStatus.SUCCESS, postevent.operationStatus());
- }
-
- @Test
- void testGetPolicyForMetadataObjectEvent() {
- MetadataObject metadataObject =
- NameIdentifierUtil.toMetadataObject(
- NameIdentifierUtil.ofCatalog("metalake", "catalog_for_test"),
- Entity.EntityType.CATALOG);
-
- dispatcher.getPolicyForMetadataObject("metalake", metadataObject, policy.name());
- PreEvent preEvent = dummyEventListener.popPreEvent();
-
- NameIdentifier identifier = MetadataObjectUtil.toEntityIdent("metalake", metadataObject);
-
- Assertions.assertEquals(identifier.toString(), preEvent.identifier().toString());
- Assertions.assertEquals(GetPolicyForMetadataObjectPreEvent.class, preEvent.getClass());
- Assertions.assertEquals(OperationType.GET_POLICY_FOR_METADATA_OBJECT, preEvent.operationType());
- Assertions.assertEquals(OperationStatus.UNPROCESSED, preEvent.operationStatus());
-
- Event postevent = dummyEventListener.popPostEvent();
- Assertions.assertEquals(identifier.toString(), postevent.identifier().toString());
- Assertions.assertEquals(GetPolicyForMetadataObjectEvent.class, postevent.getClass());
- Assertions.assertEquals(
- OperationType.GET_POLICY_FOR_METADATA_OBJECT, postevent.operationType());
- Assertions.assertEquals(OperationStatus.SUCCESS, postevent.operationStatus());
-
- PolicyInfo policyInfo = ((GetPolicyForMetadataObjectEvent) postevent).policyInfo();
- checkPolicyInfo(policyInfo, policy);
- }
-
@Test
void testCreatePolicyFailureEvent() {
Assertions.assertThrowsExactly(
@@ -558,20 +445,6 @@ public class TestPolicyEvent {
Assertions.assertEquals(OperationStatus.FAILURE, event.operationStatus());
}
- @Test
- void testListMetadataObjectsForPolicyFailureEvent() {
- Assertions.assertThrowsExactly(
- GravitinoRuntimeException.class,
- () -> failureDispatcher.listMetadataObjectsForPolicy("metalake", policy.name()));
- Event event = dummyEventListener.popPostEvent();
- Assertions.assertEquals(ListMetadataObjectsForPolicyFailureEvent.class, event.getClass());
- Assertions.assertEquals(
- GravitinoRuntimeException.class,
- ((ListMetadataObjectsForPolicyFailureEvent) event).exception().getClass());
- Assertions.assertEquals(OperationType.LIST_METADATA_OBJECTS_FOR_POLICY, event.operationType());
- Assertions.assertEquals(OperationStatus.FAILURE, event.operationStatus());
- }
-
@Test
void testListPolicyInfosForMetadataObjectFailureEvent() {
MetadataObject metadataObject =
@@ -592,61 +465,6 @@ public class TestPolicyEvent {
Assertions.assertEquals(OperationStatus.FAILURE, event.operationStatus());
}
- @Test
- void testAssociatePoliciesForMetadataObjectFailureEvent() {
- MetadataObject metadataObject =
- NameIdentifierUtil.toMetadataObject(
- NameIdentifierUtil.ofCatalog("metalake", "catalog_for_test"),
- Entity.EntityType.CATALOG);
-
- String[] policiesToAssociate = new String[] {"policy1", "policy2"};
- String[] policiesToDisassociate = new String[] {"policy3", "policy4"};
-
- Assertions.assertThrowsExactly(
- GravitinoRuntimeException.class,
- () ->
- failureDispatcher.associatePoliciesForMetadataObject(
- "metalake", metadataObject, policiesToAssociate, policiesToDisassociate));
- Event event = dummyEventListener.popPostEvent();
- Assertions.assertEquals(AssociatePoliciesForMetadataObjectFailureEvent.class, event.getClass());
- Assertions.assertEquals(
- GravitinoRuntimeException.class,
- ((AssociatePoliciesForMetadataObjectFailureEvent) event).exception().getClass());
- Assertions.assertEquals(
- MetadataObject.Type.CATALOG,
- ((AssociatePoliciesForMetadataObjectFailureEvent) event).metadataObject().type());
- Assertions.assertArrayEquals(
- policiesToAssociate,
- ((AssociatePoliciesForMetadataObjectFailureEvent) event).policiesToAdd());
- Assertions.assertArrayEquals(
- policiesToDisassociate,
- ((AssociatePoliciesForMetadataObjectFailureEvent) event).policiesToRemove());
- Assertions.assertEquals(
- OperationType.ASSOCIATE_POLICIES_FOR_METADATA_OBJECT, event.operationType());
- Assertions.assertEquals(OperationStatus.FAILURE, event.operationStatus());
- }
-
- @Test
- void testGetPolicyForMetadataObjectFailureEvent() {
- MetadataObject metadataObject =
- NameIdentifierUtil.toMetadataObject(
- NameIdentifierUtil.ofCatalog("metalake", "catalog_for_test"),
- Entity.EntityType.CATALOG);
-
- Assertions.assertThrowsExactly(
- GravitinoRuntimeException.class,
- () ->
- failureDispatcher.getPolicyForMetadataObject(
- "metalake", metadataObject, policy.name()));
- Event event = dummyEventListener.popPostEvent();
- Assertions.assertEquals(GetPolicyForMetadataObjectFailureEvent.class, event.getClass());
- Assertions.assertEquals(
- GravitinoRuntimeException.class,
- ((GetPolicyForMetadataObjectFailureEvent) event).exception().getClass());
- Assertions.assertEquals(OperationType.GET_POLICY_FOR_METADATA_OBJECT, event.operationType());
- Assertions.assertEquals(OperationStatus.FAILURE, event.operationStatus());
- }
-
private PolicyEntity mockPolicy() {
PolicyContent content =
PolicyContents.custom(
@@ -704,22 +522,6 @@ public class TestPolicyEvent {
.thenReturn(policy);
when(dispatcher.getPolicy(any(String.class), any(String.class))).thenReturn(policy);
when(dispatcher.deletePolicy(metalake, policy.name())).thenReturn(true);
- when(dispatcher.getPolicyForMetadataObject(
- any(String.class), any(MetadataObject.class), any(String.class)))
- .thenReturn(policy);
- MetadataObject catalog =
- NameIdentifierUtil.toMetadataObject(
- NameIdentifierUtil.ofCatalog("metalake", "catalog_for_test"),
- Entity.EntityType.CATALOG);
- MetadataObject[] objects = new MetadataObject[] {catalog};
-
- when(dispatcher.listMetadataObjectsForPolicy(any(String.class), any(String.class)))
- .thenReturn(objects);
-
- when(dispatcher.associatePoliciesForMetadataObject(
- any(String.class), any(MetadataObject.class), any(String[].class), any(String[].class)))
- .thenReturn(new String[] {"policy1", "policy2"});
-
when(dispatcher.listPolicyInfosForMetadataObject(any(String.class), any(MetadataObject.class)))
.thenReturn(new PolicyEntity[] {policy, policy});
diff --git a/core/src/test/java/org/apache/gravitino/policy/TestPolicyManager.java b/core/src/test/java/org/apache/gravitino/policy/TestPolicyManager.java
index 425ea3d3f7..e588b24374 100644
--- a/core/src/test/java/org/apache/gravitino/policy/TestPolicyManager.java
+++ b/core/src/test/java/org/apache/gravitino/policy/TestPolicyManager.java
@@ -70,7 +70,6 @@ import org.apache.gravitino.catalog.ViewDispatcher;
import org.apache.gravitino.exceptions.NoSuchMetalakeException;
import org.apache.gravitino.exceptions.NoSuchPolicyException;
import org.apache.gravitino.exceptions.NotFoundException;
-import org.apache.gravitino.exceptions.PolicyAlreadyAssociatedException;
import org.apache.gravitino.exceptions.PolicyAlreadyExistsException;
import org.apache.gravitino.function.FunctionDefinition;
import org.apache.gravitino.function.FunctionType;
@@ -483,230 +482,6 @@ public class TestPolicyManager {
Assertions.assertFalse(() -> policyManager.deletePolicy(METALAKE, "non_existent_policy"));
}
- @Test
- public void testAssociatePoliciesForMetadataObject() {
- Map<String, Object> customRules = ImmutableMap.of("rule1", 1, "rule2", "value2");
- PolicyContent content = PolicyContents.custom(customRules, SUPPORTS_OBJECT_TYPES, null);
- String policyName1 = "policy1" + UUID.randomUUID().toString().replace("-", "");
- createCustomPolicy(METALAKE, policyName1, content);
- String policyName2 = "policy2" + UUID.randomUUID().toString().replace("-", "");
- createCustomPolicy(METALAKE, policyName2, content);
- String policyName3 = "policy3" + UUID.randomUUID().toString().replace("-", "");
- createCustomPolicy(METALAKE, policyName3, content);
-
- // Test associate policies for catalog
- MetadataObject catalogObject =
- NameIdentifierUtil.toMetadataObject(
- NameIdentifierUtil.ofCatalog(METALAKE, CATALOG), Entity.EntityType.CATALOG);
- String[] policiesToAdd = new String[] {policyName1, policyName2, policyName3};
-
- String[] policies =
- policyManager.associatePoliciesForMetadataObject(
- METALAKE, catalogObject, policiesToAdd, null);
-
- Assertions.assertEquals(3, policies.length);
- Assertions.assertEquals(
- ImmutableSet.of(policyName1, policyName2, policyName3), ImmutableSet.copyOf(policies));
-
- // Test disassociate policies for catalog
- String[] policiesToRemove = new String[] {policyName1};
- String[] policies1 =
- policyManager.associatePoliciesForMetadataObject(
- METALAKE, catalogObject, null, policiesToRemove);
-
- Assertions.assertEquals(2, policies1.length);
- Assertions.assertEquals(
- ImmutableSet.of(policyName2, policyName3), ImmutableSet.copyOf(policies1));
-
- // Test associate and disassociate no policies for catalog
- String[] policies2 =
- policyManager.associatePoliciesForMetadataObject(METALAKE, catalogObject, null, null);
-
- Assertions.assertEquals(2, policies2.length);
- Assertions.assertEquals(
- ImmutableSet.of(policyName2, policyName3), ImmutableSet.copyOf(policies2));
-
- // Test re-associate policies for catalog
- Throwable e =
- Assertions.assertThrows(
- PolicyAlreadyAssociatedException.class,
- () ->
- policyManager.associatePoliciesForMetadataObject(
- METALAKE, catalogObject, policiesToAdd, null));
- Assertions.assertTrue(
- e.getMessage().contains("Failed to associate policies for metadata object"));
-
- // Test associate and disassociate non-existent policies for catalog
- String[] policies3 =
- policyManager.associatePoliciesForMetadataObject(
- METALAKE, catalogObject, new String[] {"policy4", "policy5"}, new String[] {"policy6"});
-
- Assertions.assertEquals(2, policies3.length);
- Assertions.assertEquals(
- ImmutableSet.of(policyName2, policyName3), ImmutableSet.copyOf(policies3));
-
- // Test associate policies for non-existent metadata object
- MetadataObject nonExistentObject =
- NameIdentifierUtil.toMetadataObject(
- NameIdentifierUtil.ofCatalog(METALAKE, "non_existent_catalog"),
- Entity.EntityType.CATALOG);
- Throwable e1 =
- Assertions.assertThrows(
- NotFoundException.class,
- () ->
- policyManager.associatePoliciesForMetadataObject(
- METALAKE, nonExistentObject, policiesToAdd, null));
- Assertions.assertTrue(
- e1.getMessage().contains("Failed to associate policies for metadata object"));
-
- // Test associate policies for unsupported metadata object
- MetadataObject metalakeObject =
- NameIdentifierUtil.toMetadataObject(
- NameIdentifierUtil.ofMetalake(METALAKE), Entity.EntityType.METALAKE);
- Throwable e2 =
- Assertions.assertThrows(
- IllegalArgumentException.class,
- () ->
- policyManager.associatePoliciesForMetadataObject(
- METALAKE, metalakeObject, policiesToAdd, null));
- Assertions.assertTrue(
- e2.getMessage().contains("Cannot associate policies for unsupported metadata object type"),
- "Actual message: " + e2.getMessage());
-
- Assertions.assertTrue(
- e2.getMessage().contains("Cannot associate policies for unsupported metadata object type"),
- "Actual message: " + e2.getMessage());
-
- // Test associate policies for schema
- MetadataObject schemaObject =
- NameIdentifierUtil.toMetadataObject(
- NameIdentifierUtil.ofSchema(METALAKE, CATALOG, SCHEMA), Entity.EntityType.SCHEMA);
- String[] policies4 =
- policyManager.associatePoliciesForMetadataObject(
- METALAKE, schemaObject, policiesToAdd, null);
-
- Assertions.assertEquals(3, policies4.length);
- Assertions.assertEquals(
- ImmutableSet.of(policyName1, policyName2, policyName3), ImmutableSet.copyOf(policies4));
-
- // Test associate policies for table
- String[] policiesToAdd1 = new String[] {policyName1};
- MetadataObject tableObject =
- NameIdentifierUtil.toMetadataObject(
- NameIdentifierUtil.ofTable(METALAKE, CATALOG, SCHEMA, TABLE), Entity.EntityType.TABLE);
- String[] policies5 =
- policyManager.associatePoliciesForMetadataObject(
- METALAKE, tableObject, policiesToAdd1, null);
-
- Assertions.assertEquals(1, policies5.length);
- Assertions.assertEquals(ImmutableSet.of(policyName1), ImmutableSet.copyOf(policies5));
-
- // Test associate and disassociate same policies for table
- String[] policiesToAdd2 = new String[] {policyName2, policyName3};
- String[] policiesToRemove1 = new String[] {policyName2};
- String[] policies6 =
- policyManager.associatePoliciesForMetadataObject(
- METALAKE, tableObject, policiesToAdd2, policiesToRemove1);
-
- Assertions.assertEquals(2, policies6.length);
- Assertions.assertEquals(
- ImmutableSet.of(policyName1, policyName3), ImmutableSet.copyOf(policies6));
-
- // Test associate policies for view
- MetadataObject viewObject =
- NameIdentifierUtil.toMetadataObject(
- NameIdentifierUtil.ofView(METALAKE, CATALOG, SCHEMA, VIEW), Entity.EntityType.VIEW);
- String[] policies7 =
- policyManager.associatePoliciesForMetadataObject(
- METALAKE, viewObject, new String[] {policyName1}, null);
-
- Assertions.assertEquals(1, policies7.length);
- Assertions.assertEquals(ImmutableSet.of(policyName1), ImmutableSet.copyOf(policies7));
-
- // Test associate and disassociate policies for view
- String[] policies8 =
- policyManager.associatePoliciesForMetadataObject(
- METALAKE, viewObject, new String[] {policyName2}, new String[] {policyName1});
-
- Assertions.assertEquals(1, policies8.length);
- Assertions.assertEquals(ImmutableSet.of(policyName2), ImmutableSet.copyOf(policies8));
-
- // Test associate policies for function
- MetadataObject functionObject =
- NameIdentifierUtil.toMetadataObject(
- NameIdentifierUtil.ofFunction(METALAKE, CATALOG, SCHEMA, FUNCTION),
- Entity.EntityType.FUNCTION);
- String[] policies9 =
- policyManager.associatePoliciesForMetadataObject(
- METALAKE, functionObject, new String[] {policyName1}, null);
-
- Assertions.assertEquals(1, policies9.length);
- Assertions.assertEquals(ImmutableSet.of(policyName1), ImmutableSet.copyOf(policies9));
-
- // Test associate and disassociate policies for function
- String[] policies10 =
- policyManager.associatePoliciesForMetadataObject(
- METALAKE, functionObject, new String[] {policyName3}, new String[] {policyName1});
-
- Assertions.assertEquals(1, policies10.length);
- Assertions.assertEquals(ImmutableSet.of(policyName3), ImmutableSet.copyOf(policies10));
- }
-
- @Test
- public void testListMetadataObjectsForPolicy() {
- Map<String, Object> customRules = ImmutableMap.of("rule1", 1, "rule2", "value2");
- PolicyContent content = PolicyContents.custom(customRules, SUPPORTS_OBJECT_TYPES, null);
- String policyName1 = "policy1" + UUID.randomUUID().toString().replace("-", "");
- createCustomPolicy(METALAKE, policyName1, content);
- String policyName2 = "policy2" + UUID.randomUUID().toString().replace("-", "");
- createCustomPolicy(METALAKE, policyName2, content);
- String policyName3 = "policy3" + UUID.randomUUID().toString().replace("-", "");
- createCustomPolicy(METALAKE, policyName3, content);
-
- MetadataObject catalogObject =
- NameIdentifierUtil.toMetadataObject(
- NameIdentifierUtil.ofCatalog(METALAKE, CATALOG), Entity.EntityType.CATALOG);
- MetadataObject schemaObject =
- NameIdentifierUtil.toMetadataObject(
- NameIdentifierUtil.ofSchema(METALAKE, CATALOG, SCHEMA), Entity.EntityType.SCHEMA);
- MetadataObject tableObject =
- NameIdentifierUtil.toMetadataObject(
- NameIdentifierUtil.ofTable(METALAKE, CATALOG, SCHEMA, TABLE), Entity.EntityType.TABLE);
-
- policyManager.associatePoliciesForMetadataObject(
- METALAKE, catalogObject, new String[] {policyName1, policyName2, policyName3}, null);
- policyManager.associatePoliciesForMetadataObject(
- METALAKE, schemaObject, new String[] {policyName1, policyName2}, null);
- policyManager.associatePoliciesForMetadataObject(
- METALAKE, tableObject, new String[] {policyName1}, null);
-
- MetadataObject[] objects = policyManager.listMetadataObjectsForPolicy(METALAKE, policyName1);
- Assertions.assertEquals(3, objects.length);
- Assertions.assertEquals(
- ImmutableSet.of(catalogObject, schemaObject, tableObject), ImmutableSet.copyOf(objects));
-
- MetadataObject[] objects1 = policyManager.listMetadataObjectsForPolicy(METALAKE, policyName2);
- Assertions.assertEquals(2, objects1.length);
- Assertions.assertEquals(
- ImmutableSet.of(catalogObject, schemaObject), ImmutableSet.copyOf(objects1));
-
- MetadataObject[] objects2 = policyManager.listMetadataObjectsForPolicy(METALAKE, policyName3);
- Assertions.assertEquals(1, objects2.length);
- Assertions.assertEquals(ImmutableSet.of(catalogObject), ImmutableSet.copyOf(objects2));
-
- // List metadata objects for non-existent policy
- Throwable e =
- Assertions.assertThrows(
- NoSuchPolicyException.class,
- () -> policyManager.listMetadataObjectsForPolicy(METALAKE, "non_existent_policy"));
- Assertions.assertTrue(
- e.getMessage()
- .contains(
- "Policy with name non_existent_policy under metalake "
- + METALAKE
- + " does not exist"));
- }
-
@Test
public void testListPoliciesForMetadataObject() {
Map<String, Object> customRules = ImmutableMap.of("rule1", 1, "rule2", "value2");
@@ -732,30 +507,24 @@ public class TestPolicyManager {
associatePolicyThroughTag(policy2, schemaObject);
associatePolicyThroughTag(policy3, tableObject);
- // Legacy direct object-policy relations remain readable during the compatibility window.
- policyManager.associatePoliciesForMetadataObject(
- METALAKE, catalogObject, new String[] {policy3.name()}, null);
-
String[] policies = policyManager.listPoliciesForMetadataObject(METALAKE, catalogObject);
- Assertions.assertEquals(2, policies.length);
- Assertions.assertEquals(
- ImmutableSet.of(policyName1, policyName3), ImmutableSet.copyOf(policies));
+ Assertions.assertEquals(1, policies.length);
+ Assertions.assertEquals(ImmutableSet.of(policyName1), ImmutableSet.copyOf(policies));
PolicyEntity[] policiesInfo =
policyManager.listPolicyInfosForMetadataObject(METALAKE, catalogObject);
- Assertions.assertEquals(2, policiesInfo.length);
- Assertions.assertEquals(ImmutableSet.of(policy1, policy3), ImmutableSet.copyOf(policiesInfo));
+ Assertions.assertEquals(1, policiesInfo.length);
+ Assertions.assertEquals(ImmutableSet.of(policy1), ImmutableSet.copyOf(policiesInfo));
String[] policies1 = policyManager.listPoliciesForMetadataObject(METALAKE, schemaObject);
- Assertions.assertEquals(3, policies1.length);
+ Assertions.assertEquals(2, policies1.length);
Assertions.assertEquals(
- ImmutableSet.of(policyName1, policyName2, policyName3), ImmutableSet.copyOf(policies1));
+ ImmutableSet.of(policyName1, policyName2), ImmutableSet.copyOf(policies1));
PolicyEntity[] policiesInfo1 =
policyManager.listPolicyInfosForMetadataObject(METALAKE, schemaObject);
- Assertions.assertEquals(3, policiesInfo1.length);
- Assertions.assertEquals(
- ImmutableSet.of(policy1, policy2, policy3), ImmutableSet.copyOf(policiesInfo1));
+ Assertions.assertEquals(2, policiesInfo1.length);
+ Assertions.assertEquals(ImmutableSet.of(policy1, policy2), ImmutableSet.copyOf(policiesInfo1));
String[] policies2 = policyManager.listPoliciesForMetadataObject(METALAKE, tableObject);
Assertions.assertEquals(3, policies2.length);
@@ -785,37 +554,22 @@ public class TestPolicyManager {
public void testDisabledPoliciesAreExcludedFromMetadataObjectResults() {
PolicyContent content =
PolicyContents.custom(ImmutableMap.of("rule", "value"), SUPPORTS_OBJECT_TYPES, null);
- String directPolicyName = "disabled_direct_" + UUID.randomUUID().toString().replace("-", "");
- PolicyEntity directPolicy =
- policyManager.createPolicy(
- METALAKE, directPolicyName, Policy.BuiltInType.CUSTOM, null, false, content);
- String tagPolicyName = "disabled_tag_" + UUID.randomUUID().toString().replace("-", "");
- PolicyEntity tagPolicy =
+ String policyName = "disabled_tag_" + UUID.randomUUID().toString().replace("-", "");
+ PolicyEntity policy =
policyManager.createPolicy(
- METALAKE, tagPolicyName, Policy.BuiltInType.CUSTOM, null, false, content);
+ METALAKE, policyName, Policy.BuiltInType.CUSTOM, null, false, content);
MetadataObject tableObject =
NameIdentifierUtil.toMetadataObject(
NameIdentifierUtil.ofTable(METALAKE, CATALOG, SCHEMA, TABLE), Entity.EntityType.TABLE);
- policyManager.associatePoliciesForMetadataObject(
- METALAKE, tableObject, new String[] {directPolicy.name()}, null);
- associatePolicyThroughTag(tagPolicy, tableObject);
-
+ associatePolicyThroughTag(policy, tableObject);
Assertions.assertEquals(
0, policyManager.listPolicyInfosForMetadataObject(METALAKE, tableObject).length);
- Assertions.assertThrows(
- NoSuchPolicyException.class,
- () -> policyManager.getPolicyForMetadataObject(METALAKE, tableObject, directPolicy.name()));
- Assertions.assertThrows(
- NoSuchPolicyException.class,
- () -> policyManager.getPolicyForMetadataObject(METALAKE, tableObject, tagPolicy.name()));
-
- policyManager.enablePolicy(METALAKE, directPolicy.name());
- policyManager.enablePolicy(METALAKE, tagPolicy.name());
- Assertions.assertEquals(
- ImmutableSet.of(directPolicy.name(), tagPolicy.name()),
- ImmutableSet.copyOf(policyManager.listPoliciesForMetadataObject(METALAKE, tableObject)));
+ policyManager.enablePolicy(METALAKE, policy.name());
+ Assertions.assertArrayEquals(
+ new String[] {policy.name()},
+ policyManager.listPoliciesForMetadataObject(METALAKE, tableObject));
}
@Test
@@ -846,102 +600,6 @@ public class TestPolicyManager {
policyManager.listPolicyInfosForMetadataObject(METALAKE, schemaObject));
Assertions.assertEquals(
0, policyManager.listPolicyInfosForMetadataObject(METALAKE, tableObject).length);
- Assertions.assertThrows(
- NoSuchPolicyException.class,
- () -> policyManager.getPolicyForMetadataObject(METALAKE, tableObject, policyName));
- }
-
- @Test
- public void testGetPolicyForMetadataObject() {
- Map<String, Object> customRules = ImmutableMap.of("rule1", 1, "rule2", "value2");
- PolicyContent content = PolicyContents.custom(customRules, SUPPORTS_OBJECT_TYPES, null);
- String policyName1 = "policy1" + UUID.randomUUID().toString().replace("-", "");
- PolicyEntity policy1 = createCustomPolicy(METALAKE, policyName1, content);
- String policyName2 = "policy2" + UUID.randomUUID().toString().replace("-", "");
- PolicyEntity policy2 = createCustomPolicy(METALAKE, policyName2, content);
- String policyName3 = "policy3" + UUID.randomUUID().toString().replace("-", "");
- PolicyEntity policy3 = createCustomPolicy(METALAKE, policyName3, content);
-
- MetadataObject catalogObject =
- NameIdentifierUtil.toMetadataObject(
- NameIdentifierUtil.ofCatalog(METALAKE, CATALOG), Entity.EntityType.CATALOG);
- MetadataObject schemaObject =
- NameIdentifierUtil.toMetadataObject(
- NameIdentifierUtil.ofSchema(METALAKE, CATALOG, SCHEMA), Entity.EntityType.SCHEMA);
- MetadataObject tableObject =
- NameIdentifierUtil.toMetadataObject(
- NameIdentifierUtil.ofTable(METALAKE, CATALOG, SCHEMA, TABLE), Entity.EntityType.TABLE);
-
- associatePolicyThroughTag(policy1, catalogObject);
- associatePolicyThroughTag(policy2, schemaObject);
- associatePolicyThroughTag(policy3, tableObject);
-
- // Keep one legacy direct relation to verify it remains readable during the compatibility
- // window.
- policyManager.associatePoliciesForMetadataObject(
- METALAKE, catalogObject, new String[] {policyName3}, null);
-
- PolicyEntity result =
- policyManager.getPolicyForMetadataObject(METALAKE, catalogObject, policyName1);
- Assertions.assertEquals(policy1, result);
- Assertions.assertFalse(result.inherited().orElseThrow());
-
- PolicyEntity result1 =
- policyManager.getPolicyForMetadataObject(METALAKE, tableObject, policyName1);
- Assertions.assertEquals(policy1, result1);
- Assertions.assertTrue(result1.inherited().orElseThrow());
-
- PolicyEntity result2 =
- policyManager.getPolicyForMetadataObject(METALAKE, tableObject, policy2.name());
- Assertions.assertEquals(policy2, result2);
- Assertions.assertTrue(result2.inherited().orElseThrow());
-
- PolicyEntity result3 =
- policyManager.getPolicyForMetadataObject(METALAKE, tableObject, policy3.name());
- Assertions.assertEquals(policy3, result3);
- Assertions.assertFalse(result3.inherited().orElseThrow());
-
- PolicyEntity result4 =
- policyManager.getPolicyForMetadataObject(METALAKE, tableObject, policy1.name());
- Assertions.assertEquals(policy1, result4);
- Assertions.assertTrue(result4.inherited().orElseThrow());
-
- // Test get non-existent policy for metadata object
- Throwable e =
- Assertions.assertThrows(
- NoSuchPolicyException.class,
- () ->
- policyManager.getPolicyForMetadataObject(
- METALAKE, catalogObject, "non_existent_policy"));
- Assertions.assertTrue(e.getMessage().contains("Policy non_existent_policy does not exist"));
-
- PolicyEntity directResult =
- policyManager.getPolicyForMetadataObject(METALAKE, catalogObject, policy3.name());
- Assertions.assertEquals(policy3, directResult);
- Assertions.assertFalse(directResult.inherited().orElseThrow());
-
- Throwable e2 =
- Assertions.assertThrows(
- NoSuchPolicyException.class,
- () ->
- policyManager.getPolicyForMetadataObject(METALAKE, catalogObject, policy2.name()));
- Assertions.assertTrue(
- e2.getMessage().contains("Policy " + policyName2 + " does not exist"),
- "Actual message: " + e2.getMessage());
-
- // Test get policy for non-existent metadata object
- MetadataObject nonExistentObject =
- NameIdentifierUtil.toMetadataObject(
- NameIdentifierUtil.ofCatalog(METALAKE, "non_existent_catalog"),
- Entity.EntityType.CATALOG);
- Throwable e3 =
- Assertions.assertThrows(
- NotFoundException.class,
- () ->
- policyManager.getPolicyForMetadataObject(
- METALAKE, nonExistentObject, policy1.name()));
- Assertions.assertTrue(
- e3.getMessage().contains("Failed to get policy for metadata object " + nonExistentObject));
}
private PolicyEntity createCustomPolicy(
diff --git a/core/src/test/java/org/apache/gravitino/storage/TestEntityStorageRelationCache.java b/core/src/test/java/org/apache/gravitino/storage/TestEntityStorageRelationCache.java
index 396e24b861..95b28b3606 100644
--- a/core/src/test/java/org/apache/gravitino/storage/TestEntityStorageRelationCache.java
+++ b/core/src/test/java/org/apache/gravitino/storage/TestEntityStorageRelationCache.java
@@ -19,7 +19,6 @@
package org.apache.gravitino.storage;
-import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import java.time.Instant;
import java.util.Collections;
@@ -54,14 +53,11 @@ import org.apache.gravitino.meta.FilesetEntity;
import org.apache.gravitino.meta.FunctionEntity;
import org.apache.gravitino.meta.GenericEntity;
import org.apache.gravitino.meta.GroupEntity;
-import org.apache.gravitino.meta.PolicyEntity;
import org.apache.gravitino.meta.RoleEntity;
import org.apache.gravitino.meta.SchemaEntity;
import org.apache.gravitino.meta.TagEntity;
import org.apache.gravitino.meta.UserEntity;
import org.apache.gravitino.meta.ViewEntity;
-import org.apache.gravitino.policy.Policy;
-import org.apache.gravitino.policy.PolicyContents;
import org.apache.gravitino.rel.Column;
import org.apache.gravitino.rel.Representation;
import org.apache.gravitino.rel.SQLRepresentation;
@@ -544,123 +540,6 @@ public class TestEntityStorageRelationCache extends AbstractEntityStorageTest {
}
}
- @ParameterizedTest
- @MethodSource("storageProvider")
- void testPolicyRelationMultipleBindings(String type, boolean enableCache) throws Exception {
- Config config = Mockito.mock(Config.class);
- Mockito.when(config.get(Configs.CACHE_ENABLED)).thenReturn(enableCache);
- init(type, config);
-
- AuditInfo auditInfo =
- AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();
-
- try (EntityStore store = EntityStoreFactory.createEntityStore(config)) {
- store.initialize(config);
-
- BaseMetalake metalake =
- createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), "metalake", auditInfo);
- store.put(metalake, false);
-
- Namespace policyNamespace = NameIdentifierUtil.ofPolicy("metalake", "policy1").namespace();
- PolicyEntity policy1 =
- PolicyEntity.builder()
- .withId(RandomIdGenerator.INSTANCE.nextId())
- .withNamespace(policyNamespace)
- .withName("policy1")
- .withPolicyType(Policy.BuiltInType.CUSTOM)
- .withContent(
- PolicyContents.custom(
- ImmutableMap.of("rule", "allow-all"),
- Collections.singleton(MetadataObject.Type.CATALOG),
- Collections.emptyMap()))
- .withAuditInfo(auditInfo)
- .build();
-
- CatalogEntity catalog1 =
- createCatalog(
- RandomIdGenerator.INSTANCE.nextId(),
- NamespaceUtil.ofCatalog("metalake"),
- "catalog1",
- auditInfo);
-
- store.put(policy1, false);
- store.put(catalog1, false);
-
- SupportsRelationOperations relationOperations = (SupportsRelationOperations) store;
-
- relationOperations.updateEntityRelations(
- SupportsRelationOperations.Type.POLICY_METADATA_OBJECT_REL,
- catalog1.nameIdentifier(),
- Entity.EntityType.CATALOG,
- new NameIdentifier[] {policy1.nameIdentifier()},
- new NameIdentifier[] {});
-
- List<PolicyEntity> policiesForCatalog1 =
- relationOperations.listEntitiesByRelation(
- SupportsRelationOperations.Type.POLICY_METADATA_OBJECT_REL,
- catalog1.nameIdentifier(),
- Entity.EntityType.CATALOG,
- true);
- Assertions.assertEquals(1, policiesForCatalog1.size());
- Assertions.assertEquals(policy1, policiesForCatalog1.get(0));
-
- List<GenericEntity> entitiesForPolicy1 =
- relationOperations.listEntitiesByRelation(
- SupportsRelationOperations.Type.POLICY_METADATA_OBJECT_REL,
- policy1.nameIdentifier(),
- Entity.EntityType.POLICY,
- true);
- Assertions.assertEquals(1, entitiesForPolicy1.size());
- Assertions.assertEquals(catalog1.id(), entitiesForPolicy1.get(0).id());
-
- CatalogEntity catalog2 =
- createCatalog(
- RandomIdGenerator.INSTANCE.nextId(),
- NamespaceUtil.ofCatalog("metalake"),
- "catalog2",
- auditInfo);
- store.put(catalog2, false);
-
- relationOperations.updateEntityRelations(
- SupportsRelationOperations.Type.POLICY_METADATA_OBJECT_REL,
- catalog2.nameIdentifier(),
- Entity.EntityType.CATALOG,
- new NameIdentifier[] {policy1.nameIdentifier()},
- new NameIdentifier[] {});
-
- policiesForCatalog1 =
- relationOperations.listEntitiesByRelation(
- SupportsRelationOperations.Type.POLICY_METADATA_OBJECT_REL,
- catalog1.nameIdentifier(),
- Entity.EntityType.CATALOG,
- true);
- Assertions.assertEquals(1, policiesForCatalog1.size());
- Assertions.assertEquals(policy1, policiesForCatalog1.get(0));
-
- List<PolicyEntity> policiesForCatalog2 =
- relationOperations.listEntitiesByRelation(
- SupportsRelationOperations.Type.POLICY_METADATA_OBJECT_REL,
- catalog2.nameIdentifier(),
- Entity.EntityType.CATALOG,
- true);
- Assertions.assertEquals(1, policiesForCatalog2.size());
- Assertions.assertEquals(policy1, policiesForCatalog2.get(0));
-
- entitiesForPolicy1 =
- relationOperations.listEntitiesByRelation(
- SupportsRelationOperations.Type.POLICY_METADATA_OBJECT_REL,
- policy1.nameIdentifier(),
- Entity.EntityType.POLICY,
- true);
- Assertions.assertEquals(2, entitiesForPolicy1.size());
- List<Long> entityIds =
- entitiesForPolicy1.stream().map(GenericEntity::id).collect(Collectors.toList());
- Assertions.assertTrue(entityIds.contains(catalog1.id()));
- Assertions.assertTrue(entityIds.contains(catalog2.id()));
- destroy(type);
- }
- }
-
@ParameterizedTest
@MethodSource("storageProvider")
void testFunctionTagRelationCacheInvalidation(String type, boolean enableCache) throws Exception {
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalEntityStore.java b/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalEntityStore.java
index 09a003cebc..35ad8fe0ec 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalEntityStore.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalEntityStore.java
@@ -42,8 +42,6 @@ import org.apache.gravitino.meta.TopicEntity;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
-import org.junit.jupiter.params.ParameterizedTest;
-import org.junit.jupiter.params.provider.CsvSource;
import org.mockito.InOrder;
import org.mockito.Mockito;
@@ -176,10 +174,8 @@ public class TestRelationalEntityStore {
inOrder.verify(cache).invalidate(dst, Entity.EntityType.TAG);
}
- @ParameterizedTest
- @CsvSource({"TAG_METADATA_OBJECT_REL, TAG", "POLICY_METADATA_OBJECT_REL, POLICY"})
- void testUpdateEntityRelationsInvalidatesDestinationTypeAfterBackendUpdate(
- SupportsRelationOperations.Type relationType, Entity.EntityType destinationType)
+ @Test
+ void testUpdateEntityRelationsInvalidatesDestinationTypeAfterBackendUpdate()
throws IOException, NoSuchEntityException, EntityAlreadyExistsException,
IllegalAccessException {
NameIdentifier src = NameIdentifier.of("metalake", "catalog", "schema", "table1");
@@ -189,52 +185,40 @@ public class TestRelationalEntityStore {
NameIdentifier[] destEntitiesToRemove = new NameIdentifier[] {destToRemove};
NoOpsCache cache = (NoOpsCache) FieldUtils.readField(store, "cache", true);
- if (relationType == SupportsRelationOperations.Type.TAG_METADATA_OBJECT_REL) {
- Mockito.doAnswer(
- invocation -> {
- Mockito.verify(cache, Mockito.never()).invalidate(src, Entity.EntityType.TABLE);
- Mockito.verify(cache, Mockito.never()).invalidate(destToAdd, destinationType);
- Mockito.verify(cache, Mockito.never()).invalidate(destToRemove, destinationType);
- return List.of();
- })
- .when(backend)
- .updateEntityRelations(
- eq(relationType),
- eq(src),
- eq(Entity.EntityType.TABLE),
- any(NameIdentifier[].class),
- any(NameIdentifier[].class));
- } else {
- Mockito.doAnswer(
- invocation -> {
- Mockito.verify(cache, Mockito.never()).invalidate(src, Entity.EntityType.TABLE);
- Mockito.verify(cache, Mockito.never()).invalidate(destToAdd, destinationType);
- Mockito.verify(cache, Mockito.never()).invalidate(destToRemove, destinationType);
- return List.of();
- })
- .when(backend)
- .updateEntityRelations(any(RelationUpdate.class));
- }
-
+ Mockito.doAnswer(
+ invocation -> {
+ Mockito.verify(cache, Mockito.never()).invalidate(src, Entity.EntityType.TABLE);
+ Mockito.verify(cache, Mockito.never()).invalidate(destToAdd, Entity.EntityType.TAG);
+ Mockito.verify(cache, Mockito.never())
+ .invalidate(destToRemove, Entity.EntityType.TAG);
+ return List.of();
+ })
+ .when(backend)
+ .updateEntityRelations(
+ eq(SupportsRelationOperations.Type.TAG_METADATA_OBJECT_REL),
+ eq(src),
+ eq(Entity.EntityType.TABLE),
+ any(NameIdentifier[].class),
+ any(NameIdentifier[].class));
store.updateEntityRelations(
- relationType, src, Entity.EntityType.TABLE, destEntitiesToAdd, destEntitiesToRemove);
+ SupportsRelationOperations.Type.TAG_METADATA_OBJECT_REL,
+ src,
+ Entity.EntityType.TABLE,
+ destEntitiesToAdd,
+ destEntitiesToRemove);
InOrder inOrder = Mockito.inOrder(backend, cache);
- if (relationType == SupportsRelationOperations.Type.TAG_METADATA_OBJECT_REL) {
- inOrder
- .verify(backend)
- .updateEntityRelations(
- eq(relationType),
- eq(src),
- eq(Entity.EntityType.TABLE),
- any(NameIdentifier[].class),
- any(NameIdentifier[].class));
- } else {
- inOrder.verify(backend).updateEntityRelations(any(RelationUpdate.class));
- }
+ inOrder
+ .verify(backend)
+ .updateEntityRelations(
+ eq(SupportsRelationOperations.Type.TAG_METADATA_OBJECT_REL),
+ eq(src),
+ eq(Entity.EntityType.TABLE),
+ any(NameIdentifier[].class),
+ any(NameIdentifier[].class));
inOrder.verify(cache).invalidate(src, Entity.EntityType.TABLE);
- inOrder.verify(cache).invalidate(destToAdd, destinationType);
- inOrder.verify(cache).invalidate(destToRemove, destinationType);
+ inOrder.verify(cache).invalidate(destToAdd, Entity.EntityType.TAG);
+ inOrder.verify(cache).invalidate(destToRemove, Entity.EntityType.TAG);
}
@Test
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestOrphanedMetadataObjectRelationService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestOrphanedMetadataObjectRelationService.java
index 8cf19b3eee..c89b4b162f 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestOrphanedMetadataObjectRelationService.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestOrphanedMetadataObjectRelationService.java
@@ -53,10 +53,10 @@ public class TestOrphanedMetadataObjectRelationService extends TestJDBCBackend {
insertRelations("TABLE", liveTable.id(), ORPHAN_ID);
Assertions.assertEquals(
- 5,
+ 4,
OrphanedMetadataObjectRelationService.getInstance()
.softDeleteOrphanedRelations(MetadataObject.Type.TABLE, 10));
- Assertions.assertEquals(5, countActiveRelations(liveTable.id()));
+ Assertions.assertEquals(4, countActiveRelations(liveTable.id()));
Assertions.assertEquals(0, countActiveRelations(ORPHAN_ID));
Assertions.assertEquals(
0,
@@ -101,10 +101,10 @@ public class TestOrphanedMetadataObjectRelationService extends TestJDBCBackend {
insertRelations("COLUMN", liveColumn.id(), droppedColumn.id());
Assertions.assertEquals(
- 5,
+ 4,
OrphanedMetadataObjectRelationService.getInstance()
.softDeleteOrphanedRelations(MetadataObject.Type.COLUMN, 10));
- Assertions.assertEquals(5, countActiveRelations(liveColumn.id()));
+ Assertions.assertEquals(4, countActiveRelations(liveColumn.id()));
Assertions.assertEquals(0, countActiveRelations(droppedColumn.id()));
}
@@ -143,16 +143,6 @@ public class TestOrphanedMetadataObjectRelationService extends TestJDBCBackend {
+ ", '"
+ type
+ "', '{}', 0, 0, 0)");
- statement.executeUpdate(
- "INSERT INTO policy_relation_meta (policy_id, metadata_object_id,"
- + " metadata_object_type, audit_info, current_version, last_version, deleted_at)"
- + " VALUES ("
- + objectId
- + ", "
- + objectId
- + ", '"
- + type
- + "', '{}', 0, 0, 0)");
statement.executeUpdate(
"INSERT INTO statistic_meta (statistic_id, statistic_name, statistic_value,"
+ " metalake_id, metadata_object_id, metadata_object_type, audit_info,"
@@ -188,9 +178,6 @@ public class TestOrphanedMetadataObjectRelationService extends TestJDBCBackend {
+ "SELECT COUNT(*) FROM tag_relation_meta WHERE metadata_object_id = "
+ objectId
+ " AND deleted_at = 0 UNION ALL "
- + "SELECT COUNT(*) FROM policy_relation_meta WHERE metadata_object_id = "
- + objectId
- + " AND deleted_at = 0 UNION ALL "
+ "SELECT COUNT(*) FROM statistic_meta WHERE metadata_object_id = "
+ objectId
+ " AND deleted_at = 0 UNION ALL "
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestPolicyMetaService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestPolicyMetaService.java
index ec4d530da3..fb523b7f3a 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestPolicyMetaService.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestPolicyMetaService.java
@@ -41,7 +41,6 @@ import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
-import java.util.stream.Collectors;
import org.apache.gravitino.Entity;
import org.apache.gravitino.EntityAlreadyExistsException;
import org.apache.gravitino.MetadataObject;
@@ -57,16 +56,9 @@ import org.apache.gravitino.exceptions.NoSuchEntityException;
import org.apache.gravitino.exceptions.OptimisticLockException;
import org.apache.gravitino.meta.AuditInfo;
import org.apache.gravitino.meta.BaseMetalake;
-import org.apache.gravitino.meta.CatalogEntity;
-import org.apache.gravitino.meta.FilesetEntity;
-import org.apache.gravitino.meta.GenericEntity;
-import org.apache.gravitino.meta.ModelEntity;
import org.apache.gravitino.meta.PolicyEntity;
import org.apache.gravitino.meta.RoleEntity;
-import org.apache.gravitino.meta.SchemaEntity;
-import org.apache.gravitino.meta.TableEntity;
import org.apache.gravitino.meta.TagEntity;
-import org.apache.gravitino.meta.TopicEntity;
import org.apache.gravitino.meta.UserEntity;
import org.apache.gravitino.policy.Policy;
import org.apache.gravitino.policy.PolicyContent;
@@ -541,7 +533,6 @@ public class TestPolicyMetaService extends TestJDBCBackend {
@TestTemplate
public void testStalePolicyDeleteRollsBackRelationshipCleanup() throws IOException {
createAndInsertMakeLake(METALAKE_NAME);
- CatalogEntity catalog = createAndInsertCatalog(METALAKE_NAME, "catalog_policy_delete_occ");
PolicyMetaService policyMetaService = PolicyMetaService.getInstance();
PolicyEntity policy =
createPolicy(
@@ -550,11 +541,6 @@ public class TestPolicyMetaService extends TestJDBCBackend {
"policy_delete_occ",
AUDIT_INFO);
policyMetaService.insertPolicy(policy, false);
- policyMetaService.associatePoliciesWithMetadataObject(
- catalog.nameIdentifier(),
- catalog.type(),
- new NameIdentifier[] {policy.nameIdentifier()},
- new NameIdentifier[0]);
PolicyPO stalePO = getPolicyPO(policy.nameIdentifier());
policyMetaService.updatePolicy(
policy.nameIdentifier(),
@@ -563,14 +549,12 @@ public class TestPolicyMetaService extends TestJDBCBackend {
assertThrows(
OptimisticLockException.class,
() -> policyMetaService.deletePolicy(policy.nameIdentifier(), stalePO));
- assertEquals(1, countActivePolicyRel(policy.id()));
assertTrue(backend.exists(policy.nameIdentifier(), Entity.EntityType.POLICY));
assertEquals(
2,
listPolicyVersions(policy.id()).values().stream().filter(v -> v.longValue() == 0L).count());
assertTrue(policyMetaService.deletePolicy(policy.nameIdentifier()));
- assertEquals(0, countActivePolicyRel(policy.id()));
assertEquals(
0,
listPolicyVersions(policy.id()).values().stream().filter(v -> v.longValue() == 0L).count());
@@ -834,7 +818,6 @@ public class TestPolicyMetaService extends TestJDBCBackend {
@TestTemplate
public void testDeletePolicyCleansEveryDependentRelation() throws IOException {
createAndInsertMakeLake(METALAKE_NAME);
- CatalogEntity catalog = createAndInsertCatalog(METALAKE_NAME, "catalog_policy_cascade");
PolicyMetaService policyMetaService = PolicyMetaService.getInstance();
PolicyEntity policy =
createPolicy(
@@ -843,12 +826,6 @@ public class TestPolicyMetaService extends TestJDBCBackend {
"policy_cascade_occ",
AUDIT_INFO);
policyMetaService.insertPolicy(policy, false);
- policyMetaService.associatePoliciesWithMetadataObject(
- catalog.nameIdentifier(),
- catalog.type(),
- new NameIdentifier[] {policy.nameIdentifier()},
- new NameIdentifier[0]);
-
TagEntity tag = createAndInsertTagEntity("tag_policy_cascade", "tag comment", METALAKE_NAME);
backend.updateEntityRelations(
RelationUpdate.of(
@@ -894,7 +871,6 @@ public class TestPolicyMetaService extends TestJDBCBackend {
String policyAsMetadataObject =
String.format("metadata_object_id = %d AND metadata_object_type = 'POLICY'", policy.id());
- assertEquals(1, countActivePolicyRel(policy.id()));
assertEquals(1, countActiveRows("policy_tag_relation_meta", "policy_id = " + policy.id()));
assertEquals(1, countActiveRows("tag_relation_meta", policyAsMetadataObject));
assertEquals(1, countActiveRows("owner_meta", policyAsMetadataObject));
@@ -906,7 +882,6 @@ public class TestPolicyMetaService extends TestJDBCBackend {
assertTrue(policyMetaService.deletePolicy(policy.nameIdentifier()));
- assertEquals(0, countActivePolicyRel(policy.id()));
assertEquals(0, countActiveRows("policy_tag_relation_meta", "policy_id = " + policy.id()));
assertEquals(0, countActiveRows("tag_relation_meta", policyAsMetadataObject));
assertEquals(0, countActiveRows("owner_meta", policyAsMetadataObject));
@@ -1002,545 +977,6 @@ public class TestPolicyMetaService extends TestJDBCBackend {
NameIdentifierUtil.ofPolicy(METALAKE_NAME + "1", "policy2")));
}
- @TestTemplate
- public void testAssociateAndDisassociatePoliciesWithMetadataObject() throws IOException {
- createAndInsertMakeLake(METALAKE_NAME);
-
- CatalogEntity catalog =
- createCatalog(
- RandomIdGenerator.INSTANCE.nextId(),
- Namespace.of(METALAKE_NAME),
- "catalog1",
- AUDIT_INFO);
- backend.insert(catalog, false);
-
- SchemaEntity schema =
- createSchemaEntity(
- RandomIdGenerator.INSTANCE.nextId(),
- Namespace.of(METALAKE_NAME, catalog.name()),
- "schema1",
- AUDIT_INFO);
- backend.insert(schema, false);
-
- TableEntity table =
- createTableEntity(
- RandomIdGenerator.INSTANCE.nextId(),
- Namespace.of(METALAKE_NAME, catalog.name(), schema.name()),
- "table1",
- AUDIT_INFO);
- backend.insert(table, false);
-
- // Create policies to associate
- PolicyMetaService policyMetaService = PolicyMetaService.getInstance();
- PolicyEntity policyEntity1 =
- PolicyEntity.builder()
- .withId(RandomIdGenerator.INSTANCE.nextId())
- .withName("policy1")
- .withNamespace(NamespaceUtil.ofPolicy(METALAKE_NAME))
- .withComment("comment")
- .withPolicyType(Policy.BuiltInType.CUSTOM)
- .withContent(content)
- .withAuditInfo(AUDIT_INFO)
- .build();
- policyMetaService.insertPolicy(policyEntity1, false);
-
- PolicyEntity policyEntity2 =
- PolicyEntity.builder()
- .withId(RandomIdGenerator.INSTANCE.nextId())
- .withName("policy2")
- .withNamespace(NamespaceUtil.ofPolicy(METALAKE_NAME))
- .withComment("comment")
- .withPolicyType(Policy.BuiltInType.CUSTOM)
- .withContent(content)
- .withAuditInfo(AUDIT_INFO)
- .build();
- policyMetaService.insertPolicy(policyEntity2, false);
-
- PolicyEntity policyEntity3 =
- PolicyEntity.builder()
- .withId(RandomIdGenerator.INSTANCE.nextId())
- .withName("policy3")
- .withNamespace(NamespaceUtil.ofPolicy(METALAKE_NAME))
- .withComment("comment")
- .withPolicyType(Policy.BuiltInType.CUSTOM)
- .withContent(content)
- .withAuditInfo(AUDIT_INFO)
- .build();
- policyMetaService.insertPolicy(policyEntity3, false);
-
- // Test associate policies with metadata object
- NameIdentifier[] policiesToAdd =
- new NameIdentifier[] {
- NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy1"),
- NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy2"),
- NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy3")
- };
-
- List<PolicyEntity> policyEntities =
- policyMetaService.associatePoliciesWithMetadataObject(
- catalog.nameIdentifier(), catalog.type(), policiesToAdd, new NameIdentifier[0]);
- assertEquals(3, policyEntities.size());
- Assertions.assertTrue(policyEntities.contains(policyEntity1));
- Assertions.assertTrue(policyEntities.contains(policyEntity2));
- Assertions.assertTrue(policyEntities.contains(policyEntity3));
-
- // Test disassociate policies with metadata object
- NameIdentifier[] policiesToRemove =
- new NameIdentifier[] {NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy1")};
-
- List<PolicyEntity> policyEntities1 =
- policyMetaService.associatePoliciesWithMetadataObject(
- catalog.nameIdentifier(), catalog.type(), new NameIdentifier[0], policiesToRemove);
-
- assertEquals(2, policyEntities1.size());
- Assertions.assertFalse(policyEntities1.contains(policyEntity1));
- Assertions.assertTrue(policyEntities1.contains(policyEntity2));
- Assertions.assertTrue(policyEntities1.contains(policyEntity3));
-
- // Test no policies to associate and disassociate
- List<PolicyEntity> policyEntities2 =
- policyMetaService.associatePoliciesWithMetadataObject(
- catalog.nameIdentifier(), catalog.type(), new NameIdentifier[0], new NameIdentifier[0]);
- assertEquals(2, policyEntities2.size());
- Assertions.assertFalse(policyEntities2.contains(policyEntity1));
- Assertions.assertTrue(policyEntities2.contains(policyEntity2));
- Assertions.assertTrue(policyEntities2.contains(policyEntity3));
-
- // Test associate and disassociate same policies with metadata object
- List<PolicyEntity> policyEntities3 =
- policyMetaService.associatePoliciesWithMetadataObject(
- catalog.nameIdentifier(), catalog.type(), policiesToRemove, policiesToRemove);
-
- assertEquals(2, policyEntities3.size());
- Assertions.assertFalse(policyEntities3.contains(policyEntity1));
- Assertions.assertTrue(policyEntities3.contains(policyEntity2));
- Assertions.assertTrue(policyEntities3.contains(policyEntity3));
-
- // Test associate and disassociate in-existent policies with metadata object
- NameIdentifier[] policiesToAdd1 =
- new NameIdentifier[] {
- NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy4"),
- NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy5")
- };
-
- NameIdentifier[] policiesToRemove1 =
- new NameIdentifier[] {
- NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy6"),
- NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy7")
- };
-
- List<PolicyEntity> policyEntities4 =
- policyMetaService.associatePoliciesWithMetadataObject(
- catalog.nameIdentifier(), catalog.type(), policiesToAdd1, policiesToRemove1);
-
- assertEquals(2, policyEntities4.size());
- Assertions.assertTrue(policyEntities4.contains(policyEntity2));
- Assertions.assertTrue(policyEntities4.contains(policyEntity3));
-
- // Test associate already associated policies with metadata object
- Assertions.assertThrows(
- EntityAlreadyExistsException.class,
- () ->
- policyMetaService.associatePoliciesWithMetadataObject(
- catalog.nameIdentifier(), catalog.type(), policiesToAdd, new NameIdentifier[0]));
-
- // Test disassociate already disassociated policies with metadata object
- List<PolicyEntity> policyEntities5 =
- policyMetaService.associatePoliciesWithMetadataObject(
- catalog.nameIdentifier(), catalog.type(), new NameIdentifier[0], policiesToRemove);
-
- assertEquals(2, policyEntities5.size());
- Assertions.assertTrue(policyEntities5.contains(policyEntity2));
- Assertions.assertTrue(policyEntities5.contains(policyEntity3));
-
- // Test associate and disassociate with invalid metadata object
- Assertions.assertThrows(
- NoSuchEntityException.class,
- () ->
- policyMetaService.associatePoliciesWithMetadataObject(
- NameIdentifier.of(METALAKE_NAME, "non-existent-catalog"),
- catalog.type(),
- policiesToAdd,
- policiesToRemove));
-
- // Test associate and disassociate to a schema
- List<PolicyEntity> policyEntities6 =
- policyMetaService.associatePoliciesWithMetadataObject(
- schema.nameIdentifier(), schema.type(), policiesToAdd, policiesToRemove);
-
- assertEquals(2, policyEntities6.size());
- Assertions.assertTrue(policyEntities6.contains(policyEntity2));
- Assertions.assertTrue(policyEntities6.contains(policyEntity3));
-
- // Test associate and disassociate to a table
- List<PolicyEntity> policyEntities7 =
- policyMetaService.associatePoliciesWithMetadataObject(
- table.nameIdentifier(), table.type(), policiesToAdd, policiesToRemove);
-
- assertEquals(2, policyEntities7.size());
- Assertions.assertTrue(policyEntities7.contains(policyEntity2));
- Assertions.assertTrue(policyEntities7.contains(policyEntity3));
- }
-
- @TestTemplate
- public void testListPoliciesForMetadataObject() throws IOException {
- testAssociateAndDisassociatePoliciesWithMetadataObject();
-
- PolicyMetaService policyMetaService = PolicyMetaService.getInstance();
-
- // Test list policies for catalog
- List<PolicyEntity> policyEntities =
- policyMetaService.listPoliciesForMetadataObject(
- NameIdentifier.of(METALAKE_NAME, "catalog1"), Entity.EntityType.CATALOG);
- assertEquals(2, policyEntities.size());
- Assertions.assertTrue(
- policyEntities.stream().anyMatch(policyEntity -> policyEntity.name().equals("policy2")));
- Assertions.assertTrue(
- policyEntities.stream().anyMatch(policyEntity -> policyEntity.name().equals("policy3")));
-
- // Test list policies for schema
- List<PolicyEntity> policyEntities1 =
- policyMetaService.listPoliciesForMetadataObject(
- NameIdentifier.of(METALAKE_NAME, "catalog1", "schema1"), Entity.EntityType.SCHEMA);
-
- assertEquals(2, policyEntities1.size());
- Assertions.assertTrue(
- policyEntities1.stream().anyMatch(policyEntity -> policyEntity.name().equals("policy2")));
- Assertions.assertTrue(
- policyEntities1.stream().anyMatch(policyEntity -> policyEntity.name().equals("policy3")));
-
- // Test list policies for table
- List<PolicyEntity> policyEntities2 =
- policyMetaService.listPoliciesForMetadataObject(
- NameIdentifier.of(METALAKE_NAME, "catalog1", "schema1", "table1"),
- Entity.EntityType.TABLE);
-
- assertEquals(2, policyEntities2.size());
- Assertions.assertTrue(
- policyEntities2.stream().anyMatch(policyEntity -> policyEntity.name().equals("policy2")));
- Assertions.assertTrue(
- policyEntities2.stream().anyMatch(policyEntity -> policyEntity.name().equals("policy3")));
-
- // Test list policies for non-existent metadata object
- Assertions.assertThrows(
- NoSuchEntityException.class,
- () ->
- policyMetaService.listPoliciesForMetadataObject(
- NameIdentifier.of(METALAKE_NAME, "catalog1", "schema1", "table2"),
- Entity.EntityType.TABLE));
- }
-
- @TestTemplate
- public void testGetPolicyForMetadataObject() throws IOException {
- testAssociateAndDisassociatePoliciesWithMetadataObject();
-
- PolicyMetaService policyMetaService = PolicyMetaService.getInstance();
-
- // Test get policy for catalog
- PolicyEntity policyEntity =
- policyMetaService.getPolicyForMetadataObject(
- NameIdentifier.of(METALAKE_NAME, "catalog1"),
- Entity.EntityType.CATALOG,
- NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy2"));
- assertEquals("policy2", policyEntity.name());
-
- // Test get policy for schema
- PolicyEntity policyEntity1 =
- policyMetaService.getPolicyForMetadataObject(
- NameIdentifier.of(METALAKE_NAME, "catalog1", "schema1"),
- Entity.EntityType.SCHEMA,
- NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy3"));
- assertEquals("policy3", policyEntity1.name());
-
- // Test get policy for table
- PolicyEntity policyEntity2 =
- policyMetaService.getPolicyForMetadataObject(
- NameIdentifier.of(METALAKE_NAME, "catalog1", "schema1", "table1"),
- Entity.EntityType.TABLE,
- NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy2"));
- assertEquals("policy2", policyEntity2.name());
-
- // Test get policy for non-existent metadata object
- Assertions.assertThrows(
- NoSuchEntityException.class,
- () ->
- policyMetaService.getPolicyForMetadataObject(
- NameIdentifier.of(METALAKE_NAME, "catalog1", "schema1", "table2"),
- Entity.EntityType.TABLE,
- NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy2")));
-
- // Test get policy for non-existent policy
- Throwable e =
- Assertions.assertThrows(
- NoSuchEntityException.class,
- () ->
- policyMetaService.getPolicyForMetadataObject(
- NameIdentifier.of(METALAKE_NAME, "catalog1", "schema1", "table1"),
- Entity.EntityType.TABLE,
- NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy4")));
- Assertions.assertTrue(e.getMessage().contains("No such policy entity: policy4"));
- }
-
- @TestTemplate
- public void testListAssociatedEntitiesForPolicy() throws IOException {
- testAssociateAndDisassociatePoliciesWithMetadataObject();
-
- PolicyMetaService policyMetaService = PolicyMetaService.getInstance();
-
- // Test list associated dummy entities for policy2
- List<GenericEntity> entities =
- policyMetaService.listAssociatedEntitiesForPolicy(
- NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy2"));
-
- assertEquals(3, entities.size());
- Set<Entity.EntityType> actualTypes =
- entities.stream().map(GenericEntity::type).collect(Collectors.toSet());
- Assertions.assertTrue(actualTypes.contains(Entity.EntityType.CATALOG));
- Assertions.assertTrue(actualTypes.contains(Entity.EntityType.SCHEMA));
- Assertions.assertTrue(actualTypes.contains(Entity.EntityType.TABLE));
-
- // Test list associated dummy entities for policy3
- List<GenericEntity> entities1 =
- policyMetaService.listAssociatedEntitiesForPolicy(
- NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy3"));
-
- assertEquals(3, entities1.size());
- Set<Entity.EntityType> actualTypes1 =
- entities1.stream().map(GenericEntity::type).collect(Collectors.toSet());
- Assertions.assertTrue(actualTypes1.contains(Entity.EntityType.CATALOG));
- Assertions.assertTrue(actualTypes1.contains(Entity.EntityType.SCHEMA));
- Assertions.assertTrue(actualTypes1.contains(Entity.EntityType.TABLE));
-
- // Test list associated dummy entities for non-existent policy
- List<GenericEntity> entities2 =
- policyMetaService.listAssociatedEntitiesForPolicy(
- NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy4"));
- assertEquals(0, entities2.size());
-
- // Test metadata object non-exist scenario.
- backend.delete(
- NameIdentifier.of(METALAKE_NAME, "catalog1", "schema1", "table1"),
- Entity.EntityType.TABLE,
- false);
-
- List<GenericEntity> entities3 =
- policyMetaService.listAssociatedEntitiesForPolicy(
- NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy2"));
-
- assertEquals(2, entities3.size());
- Set<Entity.EntityType> actualTypes3 =
- entities3.stream().map(GenericEntity::type).collect(Collectors.toSet());
- Assertions.assertTrue(actualTypes3.contains(Entity.EntityType.CATALOG));
- Assertions.assertTrue(actualTypes3.contains(Entity.EntityType.SCHEMA));
-
- backend.delete(
- NameIdentifier.of(METALAKE_NAME, "catalog1", "schema1"), Entity.EntityType.SCHEMA, false);
-
- List<GenericEntity> entities4 =
- policyMetaService.listAssociatedEntitiesForPolicy(
- NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy2"));
-
- assertEquals(1, entities4.size());
- Set<Entity.EntityType> actualTypes4 =
- entities4.stream().map(GenericEntity::type).collect(Collectors.toSet());
- Assertions.assertTrue(actualTypes4.contains(Entity.EntityType.CATALOG));
-
- backend.delete(NameIdentifier.of(METALAKE_NAME, "catalog1"), Entity.EntityType.CATALOG, false);
-
- List<GenericEntity> entities5 =
- policyMetaService.listAssociatedEntitiesForPolicy(
- NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy2"));
-
- assertEquals(0, entities5.size());
- }
-
- @TestTemplate
- public void testDeleteMetadataObjectForPolicy() throws IOException {
- createAndInsertMakeLake(METALAKE_NAME);
-
- PolicyMetaService policyMetaService = PolicyMetaService.getInstance();
- PolicyEntity policyEntity1 =
- PolicyEntity.builder()
- .withId(RandomIdGenerator.INSTANCE.nextId())
- .withName("policy1")
- .withNamespace(NamespaceUtil.ofPolicy(METALAKE_NAME))
- .withComment("comment")
- .withPolicyType(Policy.BuiltInType.CUSTOM)
- .withContent(content)
- .withAuditInfo(AUDIT_INFO)
- .build();
- policyMetaService.insertPolicy(policyEntity1, false);
-
- // 1. Test non-cascade deletion
- EntitiesToTest entities = createAndAssociateEntities("catalog1", "schema1", policyEntity1);
- assertEquals(6, countActivePolicyRel(policyEntity1.id()));
- assertEquals(6, countAllPolicyRel(policyEntity1.id()));
-
- // Test to delete a model
- ModelMetaService.getInstance().deleteModel(entities.model.nameIdentifier());
- assertEquals(5, countActivePolicyRel(policyEntity1.id()));
- assertEquals(6, countAllPolicyRel(policyEntity1.id()));
-
- // Test to drop a table
- TableMetaService.getInstance().deleteTable(entities.table.nameIdentifier());
- assertEquals(4, countActivePolicyRel(policyEntity1.id()));
- assertEquals(6, countAllPolicyRel(policyEntity1.id()));
-
- // Test to drop a topic
- TopicMetaService.getInstance().deleteTopic(entities.topic.nameIdentifier());
- assertEquals(3, countActivePolicyRel(policyEntity1.id()));
- assertEquals(6, countAllPolicyRel(policyEntity1.id()));
-
- // Test to drop a fileset
- FilesetMetaService.getInstance().deleteFileset(entities.fileset.nameIdentifier());
- assertEquals(2, countActivePolicyRel(policyEntity1.id()));
- assertEquals(6, countAllPolicyRel(policyEntity1.id()));
-
- // Test to drop a schema
- SchemaMetaService.getInstance().deleteSchema(entities.schema.nameIdentifier(), false);
- assertEquals(1, countActivePolicyRel(policyEntity1.id()));
- assertEquals(6, countAllPolicyRel(policyEntity1.id()));
-
- // Test to drop a catalog
- CatalogMetaService.getInstance().deleteCatalog(entities.catalog.nameIdentifier(), false);
- assertEquals(0, countActivePolicyRel(policyEntity1.id()));
- assertEquals(6, countAllPolicyRel(policyEntity1.id()));
-
- // 2. Test cascade deletion for catalog
- EntitiesToTest entitiesForCascadeCatalog =
- createAndAssociateEntities("catalog2", "schema2", policyEntity1);
- CatalogMetaService.getInstance()
- .deleteCatalog(entitiesForCascadeCatalog.catalog.nameIdentifier(), true);
- assertEquals(0, countActivePolicyRel(policyEntity1.id()));
- // 6 from previous test + 6 from this test
- assertEquals(12, countAllPolicyRel(policyEntity1.id()));
-
- // 3. Test cascade deletion for schema
- EntitiesToTest entitiesForCascadeSchema =
- createAndAssociateEntities("catalog3", "schema3", policyEntity1);
- SchemaMetaService.getInstance()
- .deleteSchema(entitiesForCascadeSchema.schema.nameIdentifier(), true);
- assertEquals(1, countActivePolicyRel(policyEntity1.id()));
- // 12 from previous tests + 6 from this test
- assertEquals(18, countAllPolicyRel(policyEntity1.id()));
- }
-
- private static class EntitiesToTest {
- final CatalogEntity catalog;
- final SchemaEntity schema;
- final TableEntity table;
- final TopicEntity topic;
- final FilesetEntity fileset;
- final ModelEntity model;
-
- EntitiesToTest(
- CatalogEntity catalog,
- SchemaEntity schema,
- TableEntity table,
- TopicEntity topic,
- FilesetEntity fileset,
- ModelEntity model) {
- this.catalog = catalog;
- this.schema = schema;
- this.table = table;
- this.topic = topic;
- this.fileset = fileset;
- this.model = model;
- }
- }
-
- private EntitiesToTest createAndAssociateEntities(
- String catalogName, String schemaName, PolicyEntity policyEntity) throws IOException {
- PolicyMetaService policyMetaService = PolicyMetaService.getInstance();
- NameIdentifier policyIdent = policyEntity.nameIdentifier();
-
- // Create entities
- CatalogEntity catalog =
- createCatalog(
- RandomIdGenerator.INSTANCE.nextId(),
- Namespace.of(METALAKE_NAME),
- catalogName,
- AUDIT_INFO);
- backend.insert(catalog, false);
-
- SchemaEntity schema =
- createSchemaEntity(
- RandomIdGenerator.INSTANCE.nextId(),
- Namespace.of(METALAKE_NAME, catalog.name()),
- schemaName,
- AUDIT_INFO);
- backend.insert(schema, false);
-
- TableEntity table =
- createTableEntity(
- RandomIdGenerator.INSTANCE.nextId(),
- Namespace.of(METALAKE_NAME, catalog.name(), schema.name()),
- "table1",
- AUDIT_INFO);
- backend.insert(table, false);
-
- TopicEntity topic =
- createTopicEntity(
- RandomIdGenerator.INSTANCE.nextId(),
- Namespace.of(METALAKE_NAME, catalog.name(), schema.name()),
- "topic1",
- AUDIT_INFO);
- backend.insert(topic, false);
-
- FilesetEntity fileset =
- createFilesetEntity(
- RandomIdGenerator.INSTANCE.nextId(),
- Namespace.of(METALAKE_NAME, catalog.name(), schema.name()),
- "fileset1",
- AUDIT_INFO);
- backend.insert(fileset, false);
-
- ModelEntity model =
- createModelEntity(
- RandomIdGenerator.INSTANCE.nextId(),
- Namespace.of(METALAKE_NAME, catalog.name(), schema.name()),
- "model1",
- "comment",
- 1,
- null,
- AUDIT_INFO);
- backend.insert(model, false);
-
- // Associate policy with all entities
- policyMetaService.associatePoliciesWithMetadataObject(
- catalog.nameIdentifier(),
- catalog.type(),
- new NameIdentifier[] {policyIdent},
- new NameIdentifier[0]);
- policyMetaService.associatePoliciesWithMetadataObject(
- schema.nameIdentifier(),
- schema.type(),
- new NameIdentifier[] {policyIdent},
- new NameIdentifier[0]);
- policyMetaService.associatePoliciesWithMetadataObject(
- table.nameIdentifier(),
- table.type(),
- new NameIdentifier[] {policyIdent},
- new NameIdentifier[0]);
- policyMetaService.associatePoliciesWithMetadataObject(
- topic.nameIdentifier(),
- topic.type(),
- new NameIdentifier[] {policyIdent},
- new NameIdentifier[0]);
- policyMetaService.associatePoliciesWithMetadataObject(
- fileset.nameIdentifier(),
- fileset.type(),
- new NameIdentifier[] {policyIdent},
- new NameIdentifier[0]);
- policyMetaService.associatePoliciesWithMetadataObject(
- model.nameIdentifier(),
- model.type(),
- new NameIdentifier[] {policyIdent},
- new NameIdentifier[0]);
-
- return new EntitiesToTest(catalog, schema, table, topic, fileset, model);
- }
-
private int countActiveRows(String table, String whereClause) {
try (SqlSession sqlSession =
SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);
@@ -1559,29 +995,6 @@ public class TestPolicyMetaService extends TestJDBCBackend {
}
}
- private Integer countActivePolicyRel(Long policyId) {
- return countActiveRows("policy_relation_meta", "policy_id = " + policyId);
- }
-
- private Integer countAllPolicyRel(Long policyId) {
- try (SqlSession sqlSession =
- SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);
- Connection connection = sqlSession.getConnection();
- Statement statement1 = connection.createStatement();
- ResultSet rs1 =
- statement1.executeQuery(
- String.format(
- "SELECT count(*) FROM policy_relation_meta WHERE policy_id = %d", policyId))) {
- if (rs1.next()) {
- return rs1.getInt(1);
- } else {
- throw new RuntimeException("Doesn't contain data");
- }
- } catch (SQLException se) {
- throw new RuntimeException("SQL execution failed", se);
- }
- }
-
private PolicyPO getPolicyPO(NameIdentifier identifier) {
return SessionUtils.getWithoutCommit(
PolicyMetaMapper.class,
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestTagMetaService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestTagMetaService.java
index 5d9be0ae21..51c0bda9c1 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestTagMetaService.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestTagMetaService.java
@@ -906,13 +906,6 @@ public class TestTagMetaService extends TestJDBCBackend {
"{\"type\":\"TAG_VALUE\",\"value\":\"finance\"}")
},
new RelationEdgeTarget[0]));
- PolicyMetaService.getInstance()
- .associatePoliciesWithMetadataObject(
- tag.nameIdentifier(),
- Entity.EntityType.TAG,
- new NameIdentifier[] {policy.nameIdentifier()},
- new NameIdentifier[0]);
-
UserEntity user =
createUserEntity(
RandomIdGenerator.INSTANCE.nextId(),
@@ -941,7 +934,6 @@ public class TestTagMetaService extends TestJDBCBackend {
String.format("metadata_object_id = %d AND type = 'TAG'", tag.id());
assertEquals(1, countActiveTagRel(tag.id()));
assertEquals(1, countActiveRows("policy_tag_relation_meta", "tag_id = " + tag.id()));
- assertEquals(1, countActiveRows("policy_relation_meta", tagAsMetadataObject));
assertEquals(1, countActiveRows("owner_meta", tagAsMetadataObject));
assertEquals(1, countActiveRows("role_meta_securable_object", tagAsSecurableObject));
@@ -949,7 +941,6 @@ public class TestTagMetaService extends TestJDBCBackend {
assertEquals(0, countActiveTagRel(tag.id()));
assertEquals(0, countActiveRows("policy_tag_relation_meta", "tag_id = " + tag.id()));
- assertEquals(0, countActiveRows("policy_relation_meta", tagAsMetadataObject));
assertEquals(0, countActiveRows("owner_meta", tagAsMetadataObject));
assertEquals(0, countActiveRows("role_meta_securable_object", tagAsSecurableObject));
}
diff --git a/docs/gravitino-mcp-server.md b/docs/gravitino-mcp-server.md
index d32770e4bb..fa8b539948 100644
--- a/docs/gravitino-mcp-server.md
+++ b/docs/gravitino-mcp-server.md
@@ -130,9 +130,7 @@ Gravitino MCP server supports the following tools, and you could export tool by
| `list_statistics_for_partition` | Retrieve a list of statistics associated with a specific partition. | `statistics` |
| `get_list_of_policies` | Retrieve a list of policies in the system. | `policy` |
| `get_policy_detail_information` | Retrieve detailed information for a specific policy by policy name. | `policy` |
-| `list_policies_for_metadata` | List all policies associated with a specific metadata item. | `policy` |
-| `list_metadata_by_policy` | List all metadata items associated with a specific policy. | `policy` |
-| `get_policy_for_metadata` | Get a policy associated with a specific metadata item. | `policy` |
+| `list_policies_for_metadata` | List all policies derived for a specific metadata item. | `policy` |
| `list_of_partitions` | Retrieve partitions for a table. Only for catalogs with a partition API. | `partition` |
| `get_partition` | Retrieve a partition's metadata. Only for catalogs with a partition API. | `partition` |
| `list_of_views` | Retrieve a list of views for a schema. Only for catalogs supporting views. | `view` |
diff --git a/docs/manage-policies-in-gravitino.md b/docs/manage-policies-in-gravitino.md
index a8face785f..8654a89545 100644
--- a/docs/manage-policies-in-gravitino.md
+++ b/docs/manage-policies-in-gravitino.md
@@ -195,7 +195,7 @@ client.enablePolicy("retention_30d");
### Delete a Policy
-Deleting a policy also removes it from every object it was attached to.
+Deleting a policy also removes its associations with tags.
<Tabs groupId='language' queryString>
<TabItem value="shell" label="REST">
@@ -217,42 +217,17 @@ client.deletePolicy("retention_30d");
## Object Operations
-### Attach and Detach Policies
-
-Both happen in one request, and either list can be omitted. Catalogs, schemas, tables, filesets,
-topics, models, views, and functions can carry a policy.
-
-<Tabs groupId='language' queryString>
-<TabItem value="shell" label="REST">
-
-```shell
-curl -X POST -H "Accept: application/vnd.gravitino.v1+json" \
- -H "Content-Type: application/json" -d '{
- "policiesToAdd": ["retention_30d"],
- "policiesToRemove": ["retention_7d"]
-}' http://localhost:8090/api/metalakes/test/objects/catalog/catalog1/policies
-```
-
-</TabItem>
-<TabItem value="java" label="Java">
-
-```java
-Catalog catalog = client.loadCatalog("catalog1");
-catalog.supportsPolicies().associatePolicies(
- new String[] {"retention_30d"},
- new String[] {"retention_7d"});
-
-Schema schema = catalog.asSchemas().loadSchema("schema1");
-schema.supportsPolicies().associatePolicies(new String[] {"retention_30d"}, null);
-```
-
-</TabItem>
-</Tabs>
+Object policies are read-only results derived from effective tags. To change the policies that apply
+to an object, associate a policy with a tag and then assign or remove that tag on the object or one
+of its ancestors. See [Manage tags in Gravitino](./manage-tags-in-gravitino.md) for tag assignment
+operations.
### List Policies on an Object
-The response includes policies inherited from ancestors. With `details=true` each policy carries an
-`inherited` field, which a plain name listing does not.
+The response includes policies derived from effective tags assigned to the object or its ancestors.
+With `details=true`, the response returns full policy objects instead of policy names.
+Each policy includes an `inherited` field, which is `true` when it matches only through a tag
+assigned to an ancestor of the object.
<Tabs groupId='language' queryString>
<TabItem value="shell" label="REST">
@@ -273,48 +248,3 @@ Policy[] policies = catalog.supportsPolicies().listPolicyInfos();
</TabItem>
</Tabs>
-
-### Get One Policy on an Object
-
-<Tabs groupId='language' queryString>
-<TabItem value="shell" label="REST">
-
-```shell
-curl -X GET -H "Accept: application/vnd.gravitino.v1+json" \
- http://localhost:8090/api/metalakes/test/objects/catalog/catalog1/policies/retention_30d
-```
-
-</TabItem>
-<TabItem value="java" label="Java">
-
-```java
-Policy policy = catalog.supportsPolicies().getPolicy("retention_30d");
-```
-
-</TabItem>
-</Tabs>
-
-### List Objects Carrying a Policy
-
-The response lists direct attachments only, so a policy attached to a catalog returns that catalog
-rather than the objects beneath it.
-
-<Tabs groupId='language' queryString>
-<TabItem value="shell" label="REST">
-
-```shell
-curl -X GET -H "Accept: application/vnd.gravitino.v1+json" \
- http://localhost:8090/api/metalakes/test/policies/retention_30d/objects
-```
-
-</TabItem>
-<TabItem value="java" label="Java">
-
-```java
-Policy policy = client.getPolicy("retention_30d");
-MetadataObject[] objects = policy.associatedObjects().objects();
-int count = policy.associatedObjects().count();
-```
-
-</TabItem>
-</Tabs>
diff --git a/docs/open-api/openapi.yaml b/docs/open-api/openapi.yaml
index 63ef9c0651..70a05abe55 100644
--- a/docs/open-api/openapi.yaml
+++ b/docs/open-api/openapi.yaml
@@ -99,9 +99,6 @@ paths:
/metalakes/{metalake}/policies/{policy}:
$ref: "./policies.yaml#/paths/~1metalakes~1%7Bmetalake%7D~1policies~1%7Bpolicy%7D"
- /metalakes/{metalake}/policies/{policy}/objects:
- $ref: "./policies.yaml#/paths/~1metalakes~1%7Bmetalake%7D~1policies~1%7Bpolicy%7D~1objects"
-
/metalakes/{metalake}/policies/{policy}/tags:
$ref: "./policies.yaml#/paths/~1metalakes~1%7Bmetalake%7D~1policies~1%7Bpolicy%7D~1tags"
@@ -117,9 +114,6 @@ paths:
/metalakes/{metalake}/objects/{metadataObjectType}/{metadataObjectFullName}/tags/{tag}:
$ref: "./tags.yaml#/paths/~1metalakes~1%7Bmetalake%7D~1objects~1%7BmetadataObjectType%7D~1%7BmetadataObjectFullName%7D~1tags~1%7Btag%7D"
- /metalakes/{metalake}/objects/{metadataObjectType}/{metadataObjectFullName}/policies/{policy}:
- $ref: "./policies.yaml#/paths/~1metalakes~1%7Bmetalake%7D~1objects~1%7BmetadataObjectType%7D~1%7BmetadataObjectFullName%7D~1policies~1%7Bpolicy%7D"
-
/metalakes/{metalake}/tags/{tag}/objects:
$ref: "./tags.yaml#/paths/~1metalakes~1%7Bmetalake%7D~1tags~1%7Btag%7D~1objects"
diff --git a/docs/open-api/policies.yaml b/docs/open-api/policies.yaml
index 55efb0f824..a079097ad5 100644
--- a/docs/open-api/policies.yaml
+++ b/docs/open-api/policies.yaml
@@ -219,7 +219,7 @@ paths:
- $ref: "#/components/parameters/details"
responses:
"200":
- description: Returns the list of policy objects associated with specified metadata object if {details} is true, otherwise returns the list of policy name
+ description: Returns policies derived from the effective tags of the specified metadata object; details=true returns policy objects, otherwise policy names
content:
application/vnd.gravitino.v1+json:
schema:
@@ -245,125 +245,8 @@ paths:
"5xx":
$ref: "./openapi.yaml#/components/responses/ServerErrorResponse"
- post:
- tags:
- - policy
- summary: Associate policies with metadata object
- description: Associate and disassociate policies with metadata object, please be aware that supported metadata objects are CATALOG, SCHEMA, TABLE, FILESET, TOPIC, MODEL, VIEW, FUNCTION
- operationId: associatePoliciesForObject
- requestBody:
- content:
- application/json:
- schema:
- $ref: "#/components/schemas/PoliciesAssociateRequest"
- examples:
- PolicyAssociate:
- $ref: "#/components/examples/PolicyAssociate"
- responses:
- "200":
- description: Returns the list of policy names associated with the specified metadata object
- content:
- application/vnd.gravitino.v1+json:
- schema:
- $ref: "./openapi.yaml#/components/schemas/NameListResponse"
- examples:
- NameListResponse:
- $ref: "#/components/examples/NameListResponse"
- "404":
- description: Not Found - The specified metalake does not exist
- content:
- application/vnd.gravitino.v1+json:
- schema:
- $ref: "./openapi.yaml#/components/schemas/ErrorModel"
- examples:
- NoSuchMetalakeException:
- $ref: "./metalakes.yaml#/components/examples/NoSuchMetalakeException"
- "409":
- description: Conflict - The target policy already associated with the specified metadata object
- content:
- application/vnd.gravitino.v1+json:
- schema:
- $ref: "./openapi.yaml#/components/schemas/ErrorModel"
- examples:
- PolicyAlreadyAssociatedException:
- $ref: "#/components/examples/PolicyAlreadyAssociatedException"
- "5xx":
- $ref: "./openapi.yaml#/components/responses/ServerErrorResponse"
-
-
- /metalakes/{metalake}/objects/{metadataObjectType}/{metadataObjectFullName}/policies/{policy}:
- parameters:
- - $ref: "./openapi.yaml#/components/parameters/metalake"
- - $ref: "./openapi.yaml#/components/parameters/metadataObjectType"
- - $ref: "./openapi.yaml#/components/parameters/metadataObjectFullName"
- - $ref: "./openapi.yaml#/components/parameters/policy"
- get:
- tags:
- - policy
- summary: Get policy for metadata object
- operationId: getPolicyForObject
- parameters:
- - $ref: "#/components/parameters/details"
- responses:
- "200":
- description: Returns the policy object associated with specified metadata object
- content:
- application/vnd.gravitino.v1+json:
- schema:
- $ref: "#/components/schemas/PolicyResponse"
- examples:
- PolicyResponse:
- $ref: "#/components/examples/PolicyResponse"
- "400":
- $ref: "./openapi.yaml#/components/responses/BadRequestErrorResponse"
- "404":
- description: Not Found - The specified metalake does not exist or the specified policy is not associated with the specified metadata object
- content:
- application/vnd.gravitino.v1+json:
- schema:
- $ref: "./openapi.yaml#/components/schemas/ErrorModel"
- examples:
- NoSuchPolicyException:
- $ref: "#/components/examples/NoSuchPolicyException"
- NoSuchMetalakeException:
- $ref: "./metalakes.yaml#/components/examples/NoSuchMetalakeException"
- "5xx":
- $ref: "./openapi.yaml#/components/responses/ServerErrorResponse"
- /metalakes/{metalake}/policies/{policy}/objects:
- parameters:
- - $ref: "./openapi.yaml#/components/parameters/metalake"
- - $ref: "./openapi.yaml#/components/parameters/policy"
- get:
- tags:
- - policy
- summary: list metadata objects for policy
- operationId: listMetadataObjectsForPolicy
- responses:
- "200":
- description: Returns the list of metadata objects associated with specified policy
- content:
- application/vnd.gravitino.v1+json:
- schema:
- $ref: "#/components/schemas/MetadataObjectListResponse"
- examples:
- PolicyResponse:
- $ref: "#/components/examples/MetadataObjectListResponse"
- "400":
- $ref: "./openapi.yaml#/components/responses/BadRequestErrorResponse"
- "404":
- description: Not Found - The specified policy does not exist
- content:
- application/vnd.gravitino.v1+json:
- schema:
- $ref: "./openapi.yaml#/components/schemas/ErrorModel"
- examples:
- NoSuchPolicyException:
- $ref: "#/components/examples/NoSuchPolicyException"
- "5xx":
- $ref: "./openapi.yaml#/components/responses/ServerErrorResponse"
-
/metalakes/{metalake}/policies/{policy}/tags:
parameters:
@@ -730,21 +613,6 @@ components:
}
}
- PoliciesAssociateRequest:
- type: object
- properties:
- policiesToAdd:
- type: array
- items:
- type: string
- description: The policies to add
- nullable: true
- policiesToRemove:
- type: array
- items:
- type: string
- description: The policies to remove
- nullable: true
PolicyResponse:
type: object
@@ -758,21 +626,6 @@ components:
policy:
$ref: "#/components/schemas/Policy"
- MetadataObjectListResponse:
- type: object
- properties:
- code:
- type: integer
- format: int32
- description: Status code of the response
- enum:
- - 0
- metadataObjects:
- type: array
- description: A list of metadata objects
- items:
- $ref: "#/components/schemas/MetadataObject"
-
examples:
NameListResponse:
value: {
@@ -838,12 +691,6 @@ components:
}
}
- PolicyAssociate:
- value: {
- "policiesToAdd": ["my_policy1", "my_policy2"],
- "policiesToRemove": ["my_policy3"]
- }
-
PolicyResponse:
value: {
"code": 0,
@@ -876,25 +723,6 @@ components:
}
}
- MetadataObjectListResponse:
- value: {
- "code": 0,
- "metadataObjects": [
- {
- "type": "CATALOG",
- "fullName":"my_catalog",
- },
- {
- "type": "SCHEMA",
- "fullName":"my_catalog.my_schema",
- },
- {
- "type": "TABLE",
- "fullName":"my_catalog.my_schema.my_table",
- }
- ]
- }
-
PolicyAlreadyExistsException:
value: {
"code": 1004,
@@ -906,17 +734,6 @@ components:
]
}
- PolicyAlreadyAssociatedException:
- value: {
- "code": 1004,
- "type": "PolicyAlreadyAssociatedException",
- "message": "Failed to operate policy(s) [my_policy] operation [ASSOCIATE] under metalake [my_test_metalake], reason [PolicyAlreadyAssociatedException]",
- "stack": [
- "org.apache.gravitino.exceptions.PolicyAlreadyAssociatedException: Policy my_policy already associated",
- "..."
- ]
- }
-
NoSuchPolicyException:
value: {
"code": 1003,
diff --git a/docs/table-maintenance-service/optimizer.md b/docs/table-maintenance-service/optimizer.md
index 4a0acb8d77..b1c66b557c 100644
--- a/docs/table-maintenance-service/optimizer.md
+++ b/docs/table-maintenance-service/optimizer.md
@@ -149,9 +149,10 @@ ${SPARK_HOME}/bin/spark-sql \
Without `spark.hadoop.fs.defaultFS=file:///`, Spark reaches for `hdfs://localhost:9000` and fails.
-### Step 4: Attach a Compaction Policy
+### Step 4: Configure a Compaction Policy Through a Tag
-Creating the policy is not enough. It has to be attached to the table, and the attachment is what the service reads.
+Creating the policy is not enough. Associate it with a tag, then assign that tag to the table. The
+service resolves the table's effective policies from its effective tags.
```bash
curl -X POST -H "Accept: application/vnd.gravitino.v1+json" \
@@ -167,11 +168,25 @@ curl -X POST -H "Accept: application/vnd.gravitino.v1+json" \
curl -X POST -H "Accept: application/vnd.gravitino.v1+json" \
-H "Content-Type: application/json" \
- -d '{"policiesToAdd": ["iceberg_compaction_default"]}' \
- http://localhost:8090/api/metalakes/test/objects/table/rest_catalog.db.t1/policies
+ -d '{
+ "name": "iceberg_compaction",
+ "comment": "Tables eligible for automatic compaction",
+ "properties": {}
+ }' \
+ http://localhost:8090/api/metalakes/test/tags
+
+curl -X POST -H "Accept: application/vnd.gravitino.v1+json" \
+ -H "Content-Type: application/json" \
+ -d '{"selector": {"type": "ALL_VALUES"}}' \
+ http://localhost:8090/api/metalakes/test/tags/iceberg_compaction/policies/iceberg_compaction_default
+
+curl -X POST -H "Accept: application/vnd.gravitino.v1+json" \
+ -H "Content-Type: application/json" \
+ -d '{"tagsToAdd": ["iceberg_compaction"]}' \
+ http://localhost:8090/api/metalakes/test/objects/table/rest_catalog.db.t1/tags
```
-Confirm the attachment before moving on:
+Confirm the derived policy before moving on:
```bash
curl -sS "http://localhost:8090/api/metalakes/test/objects/table/rest_catalog.db.t1/policies?details=true" | jq
diff --git a/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/recommender/strategy/GravitinoStrategyProvider.java b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/recommender/strategy/GravitinoStrategyProvider.java
index 6ff802873f..3f1da5c378 100644
--- a/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/recommender/strategy/GravitinoStrategyProvider.java
+++ b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/recommender/strategy/GravitinoStrategyProvider.java
@@ -77,14 +77,10 @@ public class GravitinoStrategyProvider implements StrategyProvider {
.loadCatalog(IdentifierUtils.getCatalogNameFromTableIdentifier(nameIdentifier))
.asTableCatalog()
.loadTable(IdentifierUtils.removeCatalogFromIdentifier(nameIdentifier));
- String[] policyNames = t.supportsPolicies().listPolicies();
- List<Strategy> policies =
- Arrays.stream(policyNames)
- .map(t.supportsPolicies()::getPolicy)
- .filter(Objects::nonNull)
- .map(this::toStrategy)
- .collect(Collectors.toList());
- return policies;
+ return Arrays.stream(t.supportsPolicies().listPolicyInfos())
+ .filter(Objects::nonNull)
+ .map(this::toStrategy)
+ .collect(Collectors.toList());
}
/**
diff --git a/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/integration/test/AbstractGravitinoOptimizerEnvIT.java b/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/integration/test/AbstractGravitinoOptimizerEnvIT.java
index 0cb70f0094..faa6d4d484 100644
--- a/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/integration/test/AbstractGravitinoOptimizerEnvIT.java
+++ b/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/integration/test/AbstractGravitinoOptimizerEnvIT.java
@@ -37,6 +37,7 @@ import org.apache.gravitino.maintenance.optimizer.common.OptimizerEnv;
import org.apache.gravitino.maintenance.optimizer.common.conf.OptimizerConfig;
import org.apache.gravitino.maintenance.optimizer.recommender.strategy.GravitinoStrategy;
import org.apache.gravitino.maintenance.optimizer.updater.metrics.storage.jdbc.GenericJdbcMetricsRepository;
+import org.apache.gravitino.policy.AllValuesSelector;
import org.apache.gravitino.policy.PolicyContent;
import org.apache.gravitino.policy.PolicyContents;
import org.apache.gravitino.rel.Column;
@@ -117,15 +118,30 @@ public abstract class AbstractGravitinoOptimizerEnvIT extends BaseIT {
metalakeClient.createPolicy(policyName, "custom", "comment", true, content);
}
- protected void associatePoliciesToTable(String policyName, String tableName) {
+ /**
+ * Creates a tag associated with the named policy.
+ *
+ * @param policyName The name of the policy to associate with the tag.
+ */
+ protected void createTagForPolicy(String policyName) {
+ String tagName = policyTagName(policyName);
+ metalakeClient.createTag(tagName, "comment", Map.of());
+ metalakeClient.addPolicyForTag(tagName, policyName, AllValuesSelector.get());
+ }
+
+ protected void associatePolicyTagToTable(String policyName, String tableName) {
Table table =
catalogClient.asTableCatalog().loadTable(NameIdentifier.of(TEST_SCHEMA, tableName));
- table.supportsPolicies().associatePolicies(new String[] {policyName}, new String[] {});
+ table.supportsTags().associateTags(new String[] {policyTagName(policyName)}, null);
}
- protected void associatePoliciesToSchema(String policyName, String schemaName) {
+ protected void associatePolicyTagToSchema(String policyName, String schemaName) {
Schema schema = catalogClient.asSchemas().loadSchema(schemaName);
- schema.supportsPolicies().associatePolicies(new String[] {policyName}, new String[] {});
+ schema.supportsTags().associateTags(new String[] {policyTagName(policyName)}, null);
+ }
+
+ private String policyTagName(String policyName) {
+ return "tag_" + policyName;
}
protected Map<String, String> getSpecifyConfigs() {
diff --git a/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/integration/test/GravitinoStrategyIT.java b/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/integration/test/GravitinoStrategyIT.java
index fb0382a818..f9b6fa2b51 100644
--- a/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/integration/test/GravitinoStrategyIT.java
+++ b/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/integration/test/GravitinoStrategyIT.java
@@ -62,8 +62,10 @@ public class GravitinoStrategyIT extends AbstractGravitinoOptimizerEnvIT {
createTable(tableName);
createPolicy("policy1", ImmutableMap.of("rule1", "value1"), "test");
createPolicy("policy2", ImmutableMap.of("rule2", "value2"), "test");
- associatePoliciesToTable("policy1", tableName);
- associatePoliciesToTable("policy2", tableName);
+ createTagForPolicy("policy1");
+ createTagForPolicy("policy2");
+ associatePolicyTagToTable("policy1", tableName);
+ associatePolicyTagToTable("policy2", tableName);
List<Strategy> strategies = strategyProvider.strategies(getTableIdentifier(tableName));
Assertions.assertNotNull(strategies);
diff --git a/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/integration/test/RecommenderIT.java b/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/integration/test/RecommenderIT.java
index a896eb2295..9076719ad0 100644
--- a/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/integration/test/RecommenderIT.java
+++ b/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/integration/test/RecommenderIT.java
@@ -121,8 +121,10 @@ public class RecommenderIT extends AbstractGravitinoOptimizerEnvIT {
DATAFILE_MSE + "/100 + " + DELETE_FILE_NUM + " * 100"),
CompactionStrategyHandler.NAME);
- associatePoliciesToSchema(policyForSmallFile, TEST_SCHEMA);
- associatePoliciesToSchema(policyForDelete, TEST_SCHEMA);
+ createTagForPolicy(policyForSmallFile);
+ createTagForPolicy(policyForDelete);
+ associatePolicyTagToSchema(policyForSmallFile, TEST_SCHEMA);
+ associatePolicyTagToSchema(policyForDelete, TEST_SCHEMA);
statisticsUpdater.updateTableStatistics(
getTableIdentifier(tableWithSmallFile),
@@ -186,8 +188,9 @@ public class RecommenderIT extends AbstractGravitinoOptimizerEnvIT {
StrategyUtils.SCORE_EXPR,
DELETE_FILE_NUM + " * 100 + " + DATAFILE_MSE),
CompactionStrategyHandler.NAME);
- associatePoliciesToTable(policyName, tableName);
- associatePoliciesToTable(policyName, tableName2);
+ createTagForPolicy(policyName);
+ associatePolicyTagToTable(policyName, tableName);
+ associatePolicyTagToTable(policyName, tableName2);
List<PartitionEntry> partition1 =
Arrays.asList(new PartitionEntryImpl("col1", "1"), new PartitionEntryImpl("col2", "3"));
diff --git a/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/recommender/strategy/TestGravitinoStrategyProvider.java b/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/recommender/strategy/TestGravitinoStrategyProvider.java
new file mode 100644
index 0000000000..3091fc2f87
--- /dev/null
+++ b/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/recommender/strategy/TestGravitinoStrategyProvider.java
@@ -0,0 +1,71 @@
+/*
+ * 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.recommender.strategy;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+import static org.mockito.Mockito.when;
+
+import java.util.List;
+import org.apache.commons.lang3.reflect.FieldUtils;
+import org.apache.gravitino.Catalog;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.client.GravitinoClient;
+import org.apache.gravitino.maintenance.optimizer.api.common.Strategy;
+import org.apache.gravitino.policy.Policy;
+import org.apache.gravitino.policy.SupportsPolicies;
+import org.apache.gravitino.rel.Table;
+import org.apache.gravitino.rel.TableCatalog;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+class TestGravitinoStrategyProvider {
+ @Test
+ void testStrategiesUseApplicablePolicyInfos() throws IllegalAccessException {
+ GravitinoClient client = mock(GravitinoClient.class);
+ Catalog catalog = mock(Catalog.class);
+ TableCatalog tableCatalog = mock(TableCatalog.class);
+ Table table = mock(Table.class);
+ SupportsPolicies supportsPolicies = mock(SupportsPolicies.class);
+ Policy policy1 = mock(Policy.class);
+ Policy policy2 = mock(Policy.class);
+ NameIdentifier identifier = NameIdentifier.of("catalog", "schema", "table");
+
+ when(client.loadCatalog("catalog")).thenReturn(catalog);
+ when(catalog.asTableCatalog()).thenReturn(tableCatalog);
+ when(tableCatalog.loadTable(NameIdentifier.of("schema", "table"))).thenReturn(table);
+ when(table.supportsPolicies()).thenReturn(supportsPolicies);
+ when(supportsPolicies.listPolicyInfos()).thenReturn(new Policy[] {policy1, null, policy2});
+ when(policy1.name()).thenReturn("policy1");
+ when(policy2.name()).thenReturn("policy2");
+
+ GravitinoStrategyProvider provider = new GravitinoStrategyProvider();
+ FieldUtils.writeField(provider, "gravitinoClient", client, true);
+
+ List<Strategy> strategies = provider.strategies(identifier);
+
+ Assertions.assertArrayEquals(
+ new String[] {"policy1", "policy2"},
+ strategies.stream().map(Strategy::name).toArray(String[]::new));
+ verify(supportsPolicies).listPolicyInfos();
+ verifyNoMoreInteractions(supportsPolicies);
+ }
+}
diff --git a/mcp-server/mcp_server/client/plain/plain_rest_client_policy_operation.py b/mcp-server/mcp_server/client/plain/plain_rest_client_policy_operation.py
index a32663985a..8d16e27cca 100644
--- a/mcp-server/mcp_server/client/plain/plain_rest_client_policy_operation.py
+++ b/mcp-server/mcp_server/client/plain/plain_rest_client_policy_operation.py
@@ -46,35 +46,6 @@ class PlainRESTClientPolicyOperation(PolicyOperation):
)
return extract_content_from_response(response, "policy", {})
- async def associate_policy_with_metadata(
- self,
- metadata_full_name: str,
- metadata_type: str,
- policies_to_add: list,
- policies_to_remove: list,
- ) -> str:
- response = await self.rest_client.post(
- f"/api/metalakes/{encode_path_segment(self.metalake_name)}"
- f"/objects/{encode_path_segment(metadata_type)}"
- f"/{encode_path_segment(metadata_full_name)}/policies",
- json={
- "policiesToAdd": policies_to_add,
- "policiesToRemove": policies_to_remove,
- },
- )
- return extract_content_from_response(response, "names", [])
-
- async def get_policy_for_metadata(
- self, metadata_full_name: str, metadata_type: str, policy_name: str
- ) -> str:
- response = await self.rest_client.get(
- f"/api/metalakes/{encode_path_segment(self.metalake_name)}"
- f"/objects/{encode_path_segment(metadata_type)}"
- f"/{encode_path_segment(metadata_full_name)}"
- f"/policies/{encode_path_segment(policy_name)}",
- )
- return extract_content_from_response(response, "policy", {})
-
async def list_policies_for_metadata(
self, metadata_full_name: str, metadata_type: str
) -> str:
@@ -84,10 +55,3 @@ class PlainRESTClientPolicyOperation(PolicyOperation):
f"/{encode_path_segment(metadata_full_name)}/policies?details=true",
)
return extract_content_from_response(response, "policies", [])
-
- async def list_metadata_by_policy(self, policy_name: str) -> str:
- response = await self.rest_client.get(
- f"/api/metalakes/{encode_path_segment(self.metalake_name)}"
- f"/policies/{encode_path_segment(policy_name)}/objects"
- )
- return extract_content_from_response(response, "metadataObjects", [])
diff --git a/mcp-server/mcp_server/client/policy_operation.py b/mcp-server/mcp_server/client/policy_operation.py
index 6634b8676c..00ce3b45c6 100644
--- a/mcp-server/mcp_server/client/policy_operation.py
+++ b/mcp-server/mcp_server/client/policy_operation.py
@@ -46,52 +46,6 @@ class PolicyOperation(ABC):
"""
pass
- @abstractmethod
- async def associate_policy_with_metadata(
- self,
- metadata_full_name: str,
- metadata_type: str,
- policies_to_add: list,
- policies_to_remove: list,
- ) -> str:
- """
- Associate policies with metadata.
-
- Args:
- metadata_full_name: Full name of the metadata object to associate policies with.
- It's typically in the format "catalog.schema.table" or "catalog.schema" or "catalog"
- or "catalog.schema.fileset". The "model", "topic" are also supported and the format
- is the same as for "catalog.schema.table".
- metadata_type: Type of the metadata (e.g., "table", "column")
- policies_to_add: List of policy names to associate with the metadata
- policies_to_remove: List of policy names to disassociate from the metadata
-
- Returns:
- str: JSON formatted string containing list of policy names that were
- successfully associated with the metadata
- """
- pass
-
- @abstractmethod
- async def get_policy_for_metadata(
- self, metadata_full_name: str, metadata_type: str, policy_name: str
- ) -> str:
- """
- Get the policy associated with a specific metadata item.
-
- Args:
- metadata_full_name: Full name of the metadata object to associate policies with.
- It's typically in the format "catalog.schema.table" or "catalog.schema" or "catalog"
- or "catalog.schema.fileset". The "model", "topic" are also supported and the format
- is the same as for "catalog.schema.table".
- metadata_type: Type of the metadata (e.g., "table", "column")
- policy_name: Name of the policy
-
- Returns:
- str: JSON formatted string containing policy metadata
- """
- pass
-
@abstractmethod
async def list_policies_for_metadata(
self, metadata_full_name: str, metadata_type: str
@@ -110,16 +64,3 @@ class PolicyOperation(ABC):
str: JSON formatted string containing list of policy metadata associated with the metadata
"""
pass
-
- @abstractmethod
- async def list_metadata_by_policy(self, policy_name: str) -> str:
- """
- List all metadata items associated with a specific policy.
-
- Args:
- policy_name: Name of the policy to filter metadata by
-
- Returns:
- str: JSON formatted string containing list of metadata items associated with the policy
- """
- pass
diff --git a/mcp-server/mcp_server/tools/policy.py b/mcp-server/mcp_server/tools/policy.py
index 6507446778..0ec1672d49 100644
--- a/mcp-server/mcp_server/tools/policy.py
+++ b/mcp-server/mcp_server/tools/policy.py
@@ -132,94 +132,6 @@ def load_policy_tools(mcp: FastMCP):
client = ctx.request_context.lifespan_context.rest_client()
return await client.as_policy_operation().load_policy(policy_name)
- @mcp.tool(tags={"policy"})
- async def associate_policy_with_metadata(
- ctx: Context,
- metadata_full_name: str,
- metadata_type: str,
- policies_to_add: list,
- ) -> str:
- """
- Associate policies with metadata.
-
- Args:
- ctx (Context): The request context object containing lifespan context
- and connector information.
- metadata_full_name (str): Full name of the metadata object to associate policies with.
- It's typically in the format "catalog.schema.table" or "catalog.schema" or "catalog"
- or "catalog.schema.fileset". The "model", "topic" are also supported and the format
- is the same as for "catalog.schema.table". For more, please see tool
- `get_metadata_fullname_formats`.
-
- metadata_type (str): Type of the metadata object (e.g., "table", "schema", "catalog",
- "fileset", "model", "topic"). For More information, please see
- tool `list_all_metadata_types`.
- policies_to_add (list): List of policy names to associate with the metadata.
-
- Example input:
- metadata_full_name: "catalog.schema.table"
- metadata_type: "table"
- policies_to_add: ["policy1", "policy2"]
-
- Returns:
- str: JSON-formatted string containing the names of associated policies.
-
- Example Return Value:
- [
- "policy1",
- "policy2"
- ]
- """
- client = ctx.request_context.lifespan_context.rest_client()
- return (
- await client.as_policy_operation().associate_policy_with_metadata(
- metadata_full_name,
- metadata_type,
- policies_to_add,
- [],
- )
- )
-
- @mcp.tool(tags={"policy"})
- async def disassociate_policy_from_metadata(
- ctx: Context,
- metadata_full_name: str,
- metadata_type: str,
- policies_to_remove: list,
- ) -> str:
- """
- Disassociate policies from metadata.
-
- Args:
- ctx (Context): The request context object containing lifespan context
- and connector information.
- metadata_full_name (str): Full name of the metadata object to disassociate policies from.
- For more, please see tool `get_metadata_fullname_formats`.
- metadata_type (str): Type of the metadata object (e.g., "table", "schema", "catalog",
- "fileset", "model", "topic"). For More information, please see
- tool `list_all_metadata_types`.
- policies_to_remove (list): List of policy names to disassociate from the metadata.
-
- Example input:
- metadata_full_name: "catalog.schema.table"
- metadata_type: "table"
- policies_to_remove: ["policy1", "policy2"]
-
- Returns:
- str: JSON-formatted string containing the names of associated policies.
-
- Example Return Value:
- [
- "policy3"
- ]
- """
- client = ctx.request_context.lifespan_context.rest_client()
- return (
- await client.as_policy_operation().associate_policy_with_metadata(
- metadata_full_name, metadata_type, [], policies_to_remove
- )
- )
-
@mcp.tool(tags={"policy"})
async def list_policies_for_metadata(
ctx: Context, metadata_full_name: str, metadata_type: str
@@ -277,117 +189,3 @@ def load_policy_tools(mcp: FastMCP):
return await client.as_policy_operation().list_policies_for_metadata(
metadata_full_name, metadata_type
)
-
- @mcp.tool(tags={"policy"})
- async def list_metadata_by_policy(ctx: Context, policy_name: str) -> str:
- """
- List all metadata items associated with a specific policy.
-
- The child metadata items which inherit the associate from the parent metadata
- will be excluded in the result. For example, if the policy is associated with
- the catalog, the catalog's child metadata items will be excluded in the result.
-
- Args:
- ctx (Context): The request context object containing lifespan context
- and connector information.
- policy_name (str): Name of the policy to filter metadata by.
-
- Returns:
- str: JSON-formatted string containing the list of metadata items associated with the policy.
-
- Example Return Value:
- [
- {
- "fullName": "model_catalog",
- "type": "catalog"
- },
- {
- "fullName": "catalog.schema.table",
- "type": "table"
- },
- {
- "fullName": "catalog.schema.fileset",
- "type": "fileset"
- },
- {
- "fullName": "catalog.schema.model",
- "type": "model"
- },
- {
- "fullName": "catalog.schema.topic",
- "type": "topic"
- }
- {
- "fullName": "catalog.schema",
- "type": "schema"
- }
- ...
- ]
- """
- client = ctx.request_context.lifespan_context.rest_client()
- return await client.as_policy_operation().list_metadata_by_policy(
- policy_name
- )
-
- @mcp.tool(tags={"policy"})
- async def get_policy_for_metadata(
- ctx: Context,
- metadata_full_name: str,
- metadata_type: str,
- policy_name: str,
- ) -> str:
- """
- Get the policy associated with a specific metadata item by policy name.
-
- This tool is used to check whether a policy is associated with the metadata item.
-
- Args:
- ctx (Context): The request context object containing lifespan context
- and connector information.
- metadata_full_name (str): Full name of the metadata item. For more, please see tool
- `get_metadata_fullname_formats`.
- metadata_type (str): Type of the metadata (e.g., "table", "column"). For More information, please see
- tool `list_all_metadata_types`.
- policy_name (str): Name of the policy to filter metadata by.
-
- Example input:
- metadata_full_name: "catalog.schema.table"
- metadata_type: "table"
- policy_name: "policy_a"
-
- Returns:
- str: JSON-formatted string containing the detailed policy information associated with the metadata.
-
- Example Return Value:
- {
- "name": "my_policy1",
- "comment": "This is a test policy",
- "policyType": "custom",
- "enabled": true,
- "content": {
- "customRules": {
- "rule1": 123
- },
- "properties": {
- "key1": "value1"
- },
- "supportedObjectTypes": [
- "fileset",
- "schema",
- "topic",
- "table",
- "model",
- "catalog"
- ]
- },
- "inherited": false,
- "audit": {
- "creator": "anonymous",
- "createTime": "2025-08-18T08:29:30.016501Z"
- }
- }
- """
- client = ctx.request_context.lifespan_context.rest_client()
- return await client.as_policy_operation().get_policy_for_metadata(
- metadata_full_name, metadata_type, policy_name
- )
diff --git a/mcp-server/tests/unit/client/test_url_encoding.py b/mcp-server/tests/unit/client/test_url_encoding.py
index 6ff7a182b1..3b84d32544 100644
--- a/mcp-server/tests/unit/client/test_url_encoding.py
+++ b/mcp-server/tests/unit/client/test_url_encoding.py
@@ -496,37 +496,6 @@ class TestPolicyOperationUrlEncoding(unittest.TestCase):
self.assertIn(_ENCODED_PATH_TRAVERSAL, url)
self.assertNotIn("../../", url)
- def test_associate_policy_encodes_metadata_full_name_and_type(self):
- client = _make_mock_client({"names": []})
- op = PlainRESTClientPolicyOperation(METALAKE, client)
- asyncio.run(
- op.associate_policy_with_metadata(_QUERY_INJECTION, _SLASH, [], [])
- )
- url = _called_url(client.post)
- self.assertIn(_ENCODED_QUERY_INJECTION, url)
- self.assertIn(_ENCODED_SLASH, url)
- self.assertNotIn("?admin=true", url)
-
- def test_get_policy_for_metadata_encodes_policy_name(self):
- client = _make_mock_client({"policy": {}})
- op = PlainRESTClientPolicyOperation(METALAKE, client)
- asyncio.run(
- op.get_policy_for_metadata(
- "meta.full.name", "table", _PATH_TRAVERSAL
- )
- )
- url = _called_url(client.get)
- self.assertIn(_ENCODED_PATH_TRAVERSAL, url)
- self.assertNotIn("../../", url)
-
- def test_list_metadata_by_policy_encodes_policy_name(self):
- client = _make_mock_client({"metadataObjects": []})
- op = PlainRESTClientPolicyOperation(METALAKE, client)
- asyncio.run(op.list_metadata_by_policy(_QUERY_INJECTION))
- url = _called_url(client.get)
- self.assertIn(_ENCODED_QUERY_INJECTION, url)
- self.assertNotIn("?admin=true", url)
-
class TestStatisticOperationUrlEncoding(unittest.TestCase):
def test_list_of_statistics_encodes_metadata_fullname(self):
diff --git a/mcp-server/tests/unit/tools/mock_operation.py b/mcp-server/tests/unit/tools/mock_operation.py
index 1a879e93cd..dfe6125525 100644
--- a/mcp-server/tests/unit/tools/mock_operation.py
+++ b/mcp-server/tests/unit/tools/mock_operation.py
@@ -225,23 +225,6 @@ class MockFilesetOperation(FilesetOperation):
class MockPolicyOperation(PolicyOperation):
- async def associate_policy_with_metadata(
- self,
- metadata_full_name: str,
- metadata_type: str,
- policies_to_add: list,
- policies_to_remove: list,
- ) -> str:
- return (
- f"associate_policy_with_metadata: {metadata_full_name}, {metadata_type}, "
- f"{policies_to_add}, {policies_to_remove}"
- )
-
- async def get_policy_for_metadata(
- self, metadata_full_name: str, metadata_type: str, policy_name: str
- ) -> str:
- return f"get_policy_for_metadata: {metadata_full_name}, {metadata_type}, {policy_name}"
-
async def list_policies_for_metadata(
self, metadata_full_name: str, metadata_type: str
) -> str:
@@ -249,9 +232,6 @@ class MockPolicyOperation(PolicyOperation):
f"list_policies_for_metadata: {metadata_full_name}, {metadata_type}"
)
- async def list_metadata_by_policy(self, policy_name: str) -> str:
- return f"list_metadata_by_policy: {policy_name}"
-
async def get_list_of_policies(self) -> str:
return "mock_policies"
diff --git a/mcp-server/tests/unit/tools/test_policy.py b/mcp-server/tests/unit/tools/test_policy.py
index 3b49d2a246..fc49b5e312 100644
--- a/mcp-server/tests/unit/tools/test_policy.py
+++ b/mcp-server/tests/unit/tools/test_policy.py
@@ -71,70 +71,17 @@ class TestPolicyTool(unittest.TestCase):
asyncio.run(_test_list_policies_for_metadata(self.mcp))
- def test_list_metadata_for_policy(self):
- async def _test_list_metadata_for_policy(mcp_server):
- async with Client(mcp_server) as client:
- result = await client.call_tool(
- "list_metadata_by_policy",
- {"policy_name": "mock_policy"},
- )
- self.assertEqual(
- "list_metadata_by_policy: mock_policy",
- result.content[0].text,
- )
-
- asyncio.run(_test_list_metadata_for_policy(self.mcp))
-
- def test_disassociate_policy_from_metadata(self):
- async def _test_disassociate_policy_from_metadata(mcp_server):
- async with Client(mcp_server) as client:
- result = await client.call_tool(
- "disassociate_policy_from_metadata",
- {
- "metadata_full_name": "catalog.db.table",
- "metadata_type": "table",
- "policies_to_remove": ["mock_policy"],
- },
- )
- self.assertEqual(
- """associate_policy_with_metadata: catalog.db.table, table, [], ['mock_policy']""",
- result.content[0].text,
- )
-
- asyncio.run(_test_disassociate_policy_from_metadata(self.mcp))
-
- def test_associate_policy_with_metadata(self):
- async def _test_associate_policy_with_metadata(mcp_server):
- async with Client(mcp_server) as client:
- result = await client.call_tool(
+ def test_removed_object_policy_tools_are_not_exposed(self):
+ async def _test():
+ async with Client(self.mcp) as client:
+ names = {tool.name for tool in await client.list_tools()}
+ for name in (
"associate_policy_with_metadata",
- {
- "metadata_full_name": "catalog.db.table",
- "metadata_type": "table",
- "policies_to_add": ["mock_policy"],
- },
- )
- self.assertEqual(
- """associate_policy_with_metadata: catalog.db.table, table, ['mock_policy'], []""",
- result.content[0].text,
- )
-
- asyncio.run(_test_associate_policy_with_metadata(self.mcp))
-
- def test_get_policy_for_metadata(self):
- async def _test_get_policy_for_metadata(mcp_server):
- async with Client(mcp_server) as client:
- result = await client.call_tool(
+ "disassociate_policy_from_metadata",
"get_policy_for_metadata",
- {
- "metadata_full_name": "catalog.db.table",
- "metadata_type": "table",
- "policy_name": "mock_policy",
- },
- )
- self.assertEqual(
- """get_policy_for_metadata: catalog.db.table, table, mock_policy""",
- result.content[0].text,
- )
+ "list_metadata_by_policy",
+ ):
+ with self.subTest(tool=name):
+ self.assertNotIn(name, names)
- asyncio.run(_test_get_policy_for_metadata(self.mcp))
+ asyncio.run(_test())
diff --git a/mcp-server/tests/unit/tools/test_statistic.py b/mcp-server/tests/unit/tools/test_statistic.py
index 560b7eeef4..4f9a385baa 100644
--- a/mcp-server/tests/unit/tools/test_statistic.py
+++ b/mcp-server/tests/unit/tools/test_statistic.py
@@ -80,10 +80,7 @@ class TestStatisticTool(unittest.TestCase):
"associate_tag_with_metadata",
"disassociate_tag_from_metadata",
"list_tags_for_metadata",
- "associate_policy_with_metadata",
- "disassociate_policy_from_metadata",
"list_policies_for_metadata",
- "get_policy_for_metadata",
):
with self.subTest(tool=name):
schema = tools[name].inputSchema
diff --git a/scripts/h2/schema-2.0.0-h2.sql b/scripts/h2/schema-2.0.0-h2.sql
index ba2a256b2d..e01f35e812 100644
--- a/scripts/h2/schema-2.0.0-h2.sql
+++ b/scripts/h2/schema-2.0.0-h2.sql
@@ -417,21 +417,6 @@ CREATE TABLE IF NOT EXISTS `policy_version_info` (
KEY `idx_pmid` (`metalake_id`)
) ENGINE=InnoDB;
-CREATE TABLE IF NOT EXISTS `policy_relation_meta` (
- `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'auto increment id',
- `policy_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'policy id',
- `metadata_object_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'metadata object id',
- `metadata_object_type` VARCHAR(64) NOT NULL COMMENT 'metadata object type',
- `audit_info` CLOB NOT NULL COMMENT 'policy relation audit info',
- `current_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'policy relation current version',
- `last_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'policy relation last version',
- `deleted_at` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'policy relation deleted at',
- PRIMARY KEY (`id`),
- UNIQUE KEY `uk_pi_mi_mo_del` (`policy_id`, `metadata_object_id`, `metadata_object_type`, `deleted_at`),
- KEY `idx_pid` (`policy_id`),
- KEY `idx_prmid` (`metadata_object_id`)
-) ENGINE=InnoDB;
-
CREATE TABLE IF NOT EXISTS `policy_tag_relation_meta` (
`id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'auto increment id',
`policy_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'policy id',
diff --git a/scripts/h2/upgrade-1.3.0-to-2.0.0-h2.sql b/scripts/h2/upgrade-1.3.0-to-2.0.0-h2.sql
index 5d93944881..947bef162d 100644
--- a/scripts/h2/upgrade-1.3.0-to-2.0.0-h2.sql
+++ b/scripts/h2/upgrade-1.3.0-to-2.0.0-h2.sql
@@ -20,6 +20,9 @@
+-- Preserve policy_relation_meta from pre-2.0 installations, including its existing data.
+-- The 2.0 server no longer reads direct object-policy assignments from this table.
+
ALTER TABLE `table_column_version_info`
ALTER COLUMN `column_comment` VARCHAR(4096) DEFAULT '';
diff --git a/scripts/mysql/schema-2.0.0-mysql.sql b/scripts/mysql/schema-2.0.0-mysql.sql
index 7831d811d8..70505d3a9e 100644
--- a/scripts/mysql/schema-2.0.0-mysql.sql
+++ b/scripts/mysql/schema-2.0.0-mysql.sql
@@ -408,21 +408,6 @@ CREATE TABLE IF NOT EXISTS `policy_version_info` (
KEY `policy_version_info_idx_mid` (`metalake_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT 'policy version info';
-CREATE TABLE IF NOT EXISTS `policy_relation_meta` (
- `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'auto increment id',
- `policy_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'policy id',
- `metadata_object_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'metadata object id',
- `metadata_object_type` VARCHAR(64) NOT NULL COMMENT 'metadata object type',
- `audit_info` MEDIUMTEXT NOT NULL COMMENT 'policy relation audit info',
- `current_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'policy relation current version',
- `last_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'policy relation last version',
- `deleted_at` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'policy relation deleted at',
- PRIMARY KEY (`id`),
- UNIQUE KEY `uk_pi_mi_mo_del` (`policy_id`, `metadata_object_id`, `metadata_object_type`, `deleted_at`),
- KEY `idx_pid` (`policy_id`),
- KEY `policy_relation_meta_idx_mid` (`metadata_object_id`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT 'policy metadata object relation';
-
CREATE TABLE IF NOT EXISTS `policy_tag_relation_meta` (
`id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'auto increment id',
`policy_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'policy id',
diff --git a/scripts/mysql/upgrade-1.3.0-to-2.0.0-mysql.sql b/scripts/mysql/upgrade-1.3.0-to-2.0.0-mysql.sql
index a603af129e..678767d88d 100644
--- a/scripts/mysql/upgrade-1.3.0-to-2.0.0-mysql.sql
+++ b/scripts/mysql/upgrade-1.3.0-to-2.0.0-mysql.sql
@@ -17,6 +17,9 @@
-- under the License.
--
+-- Preserve policy_relation_meta from pre-2.0 installations, including its existing data.
+-- The 2.0 server no longer reads direct object-policy assignments from this table.
+
ALTER TABLE `table_column_version_info`
MODIFY COLUMN `column_comment` VARCHAR(4096) DEFAULT '' COMMENT 'column comment';
@@ -102,7 +105,6 @@ ALTER TABLE `model_version_info` RENAME INDEX `idx_mid` TO `model_version_info_i
ALTER TABLE `model_version_info` RENAME INDEX `idx_cid` TO `model_version_info_idx_cid`;
ALTER TABLE `model_version_info` RENAME INDEX `idx_sid` TO `model_version_info_idx_sid`;
ALTER TABLE `policy_version_info` RENAME INDEX `idx_mid` TO `policy_version_info_idx_mid`;
-ALTER TABLE `policy_relation_meta` RENAME INDEX `idx_mid` TO `policy_relation_meta_idx_mid`;
ALTER TABLE `function_meta` RENAME INDEX `uk_sid_fn_del` TO `function_meta_uk_sid_fn_del`;
ALTER TABLE `function_meta` RENAME INDEX `idx_mid` TO `function_meta_idx_mid`;
ALTER TABLE `function_meta` RENAME INDEX `idx_cid` TO `function_meta_idx_cid`;
diff --git a/scripts/postgresql/schema-2.0.0-postgresql.sql b/scripts/postgresql/schema-2.0.0-postgresql.sql
index b3a6812d15..0d4bab39f7 100644
--- a/scripts/postgresql/schema-2.0.0-postgresql.sql
+++ b/scripts/postgresql/schema-2.0.0-postgresql.sql
@@ -729,31 +729,6 @@ COMMENT ON COLUMN policy_version_info.content IS 'policy content';
COMMENT ON COLUMN policy_version_info.deleted_at IS 'policy deleted at';
-CREATE TABLE IF NOT EXISTS policy_relation_meta (
- id BIGINT NOT NULL GENERATED BY DEFAULT AS IDENTITY,
- 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,
- PRIMARY KEY (id),
- UNIQUE (policy_id, metadata_object_id, metadata_object_type, deleted_at)
-);
-
-CREATE INDEX IF NOT EXISTS policy_relation_meta_idx_policy_id ON policy_relation_meta (policy_id);
-CREATE INDEX IF NOT EXISTS policy_relation_meta_idx_metadata_object_id ON policy_relation_meta (metadata_object_id);
-COMMENT ON TABLE policy_relation_meta IS 'policy metadata object relation';
-COMMENT ON COLUMN policy_relation_meta.id IS 'auto increment id';
-COMMENT ON COLUMN policy_relation_meta.policy_id IS 'policy id';
-COMMENT ON COLUMN policy_relation_meta.metadata_object_id IS 'metadata object id';
-COMMENT ON COLUMN policy_relation_meta.metadata_object_type IS 'metadata object type';
-COMMENT ON COLUMN policy_relation_meta.audit_info IS 'policy relation audit info';
-COMMENT ON COLUMN policy_relation_meta.current_version IS 'policy relation current version';
-COMMENT ON COLUMN policy_relation_meta.last_version IS 'policy relation last version';
-COMMENT ON COLUMN policy_relation_meta.deleted_at IS 'policy relation deleted at';
-
CREATE TABLE IF NOT EXISTS policy_tag_relation_meta (
id BIGSERIAL NOT NULL,
policy_id BIGINT NOT NULL,
diff --git a/scripts/postgresql/upgrade-1.3.0-to-2.0.0-postgresql.sql b/scripts/postgresql/upgrade-1.3.0-to-2.0.0-postgresql.sql
index 7e780bb845..4a64d43798 100644
--- a/scripts/postgresql/upgrade-1.3.0-to-2.0.0-postgresql.sql
+++ b/scripts/postgresql/upgrade-1.3.0-to-2.0.0-postgresql.sql
@@ -21,6 +21,9 @@
+-- Preserve policy_relation_meta from pre-2.0 installations, including its existing data.
+-- The 2.0 server no longer reads direct object-policy assignments from this table.
+
ALTER TABLE table_column_version_info
ALTER COLUMN column_comment TYPE VARCHAR(4096);
diff --git a/server-common/src/main/java/org/apache/gravitino/server/authorization/annotations/AuthorizationRequest.java b/server-common/src/main/java/org/apache/gravitino/server/authorization/annotations/AuthorizationRequest.java
index f90679324f..33e2a79b25 100644
--- a/server-common/src/main/java/org/apache/gravitino/server/authorization/annotations/AuthorizationRequest.java
+++ b/server-common/src/main/java/org/apache/gravitino/server/authorization/annotations/AuthorizationRequest.java
@@ -31,7 +31,6 @@ public @interface AuthorizationRequest {
enum RequestType {
COMMON,
ASSOCIATE_TAG,
- ASSOCIATE_POLICY,
RUN_JOB,
LINEAGE,
LOAD_TABLE,
diff --git a/server/src/main/java/org/apache/gravitino/server/web/filter/authorization/AssociatePolicyAuthorizationExecutor.java b/server/src/main/java/org/apache/gravitino/server/web/filter/authorization/AssociatePolicyAuthorizationExecutor.java
deleted file mode 100644
index 59b2e83305..0000000000
--- a/server/src/main/java/org/apache/gravitino/server/web/filter/authorization/AssociatePolicyAuthorizationExecutor.java
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * 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.server.web.filter.authorization;
-
-import static org.apache.gravitino.server.web.filter.ParameterUtil.buildNameIdentifierForBatchAuthorization;
-import static org.apache.gravitino.server.web.filter.ParameterUtil.extractFromParameters;
-
-import com.google.common.base.Preconditions;
-import java.lang.reflect.Parameter;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Optional;
-import org.apache.gravitino.Entity;
-import org.apache.gravitino.NameIdentifier;
-import org.apache.gravitino.authorization.AuthorizationRequestContext;
-import org.apache.gravitino.dto.requests.PoliciesAssociateRequest;
-
-/**
- * Metadata object authorization for {@link
- * org.apache.gravitino.server.web.rest.MetadataObjectPolicyOperations#associatePoliciesForObject(String,
- * String, String, PoliciesAssociateRequest)}
- */
-public class AssociatePolicyAuthorizationExecutor extends CommonAuthorizerExecutor
- implements AuthorizationExecutor {
-
- private final Parameter[] parameters;
- private final Object[] args;
-
- public AssociatePolicyAuthorizationExecutor(
- String expression,
- Parameter[] parameters,
- Object[] args,
- Map<Entity.EntityType, NameIdentifier> metadataContext,
- Map<String, Object> pathParams,
- Optional<String> entityType) {
- super(expression, metadataContext, pathParams, entityType);
- this.parameters = parameters;
- this.args = args;
- }
-
- @Override
- public boolean execute(AuthorizationRequestContext context) throws Exception {
- Object request = extractFromParameters(parameters, args);
- if (request == null) {
- return false;
- }
-
- context.setOriginalAuthorizationExpression(expression);
- Entity.EntityType targetType =
- Entity.EntityType.POLICY; // policies are the only supported batch target here
- Preconditions.checkArgument(
- request instanceof PoliciesAssociateRequest,
- "Only policy can use AssociatePolicyAuthorizationExecutor, please contact the administrator.");
- PoliciesAssociateRequest policiesAssociateRequest = (PoliciesAssociateRequest) request;
- policiesAssociateRequest.validate();
- // Authorize both 'policiesToAdd' and 'policiesToRemove' fields.
- return authorizePolicy(policiesAssociateRequest.getPoliciesToAdd(), context, targetType)
- && authorizePolicy(policiesAssociateRequest.getPoliciesToRemove(), context, targetType);
- }
-
- /**
- * Performs batch authorization for a given field (e.g., "policiesToAdd" or "policiesToRemove")
- * containing an array of policy names.
- *
- * @param policies policies
- * @param context The shared authorization request context.
- * @param targetType The entity type being authorized (expected to be TAG).
- * @return {@code true} if all policies in the field pass authorization; {@code false} otherwise.
- */
- private boolean authorizePolicy(
- String[] policies, AuthorizationRequestContext context, Entity.EntityType targetType) {
-
- // Treat null or empty arrays as no-op (implicitly authorized)
- if (policies == null) {
- return true;
- }
-
- for (String policy : policies) {
- // Use a fresh context copy for each policy to avoid cross-contamination
- Map<Entity.EntityType, NameIdentifier> currentContext = new HashMap<>(this.metadataContext);
- buildNameIdentifierForBatchAuthorization(currentContext, policy, targetType);
-
- boolean authorized =
- authorizationExpressionEvaluator.evaluate(
- currentContext, pathParams, context, entityType);
-
- if (!authorized) {
- return false; // Fail fast on first unauthorized policy
- }
- }
- return true;
- }
-}
diff --git a/server/src/main/java/org/apache/gravitino/server/web/filter/authorization/AuthorizeExecutorFactory.java b/server/src/main/java/org/apache/gravitino/server/web/filter/authorization/AuthorizeExecutorFactory.java
index 12a526cb2b..8f4e4ad466 100644
--- a/server/src/main/java/org/apache/gravitino/server/web/filter/authorization/AuthorizeExecutorFactory.java
+++ b/server/src/main/java/org/apache/gravitino/server/web/filter/authorization/AuthorizeExecutorFactory.java
@@ -43,8 +43,6 @@ public class AuthorizeExecutorFactory {
expression, metadataContext, pathParams, entityType);
case ASSOCIATE_TAG -> new AssociateTagAuthorizationExecutor(
expression, parameters, args, metadataContext, pathParams, entityType);
- case ASSOCIATE_POLICY -> new AssociatePolicyAuthorizationExecutor(
- expression, parameters, args, metadataContext, pathParams, entityType);
case RUN_JOB -> new RunJobAuthorizationExecutor(
parameters, args, expression, metadataContext, pathParams, entityType);
case LINEAGE -> new LineageAuthorizationExecutor(parameters, args, expression);
diff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/MetadataObjectPolicyOperations.java b/server/src/main/java/org/apache/gravitino/server/web/rest/MetadataObjectPolicyOperations.java
index bd01f76a75..0788720b4d 100644
--- a/server/src/main/java/org/apache/gravitino/server/web/rest/MetadataObjectPolicyOperations.java
+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/MetadataObjectPolicyOperations.java
@@ -29,7 +29,6 @@ import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
-import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
@@ -40,11 +39,8 @@ import org.apache.gravitino.Entity;
import org.apache.gravitino.MetadataObject;
import org.apache.gravitino.MetadataObjects;
import org.apache.gravitino.dto.policy.PolicyDTO;
-import org.apache.gravitino.dto.requests.PoliciesAssociateRequest;
import org.apache.gravitino.dto.responses.NameListResponse;
import org.apache.gravitino.dto.responses.PolicyListResponse;
-import org.apache.gravitino.dto.responses.PolicyResponse;
-import org.apache.gravitino.exceptions.NoSuchPolicyException;
import org.apache.gravitino.meta.PolicyEntity;
import org.apache.gravitino.metrics.MetricNames;
import org.apache.gravitino.policy.PolicyDispatcher;
@@ -53,7 +49,6 @@ import org.apache.gravitino.server.authorization.annotations.AuthorizationExpres
import org.apache.gravitino.server.authorization.annotations.AuthorizationFullName;
import org.apache.gravitino.server.authorization.annotations.AuthorizationMetadata;
import org.apache.gravitino.server.authorization.annotations.AuthorizationObjectType;
-import org.apache.gravitino.server.authorization.annotations.AuthorizationRequest;
import org.apache.gravitino.server.authorization.expression.AuthorizationExpressionConstants;
import org.apache.gravitino.server.web.Utils;
import org.apache.gravitino.utils.NameIdentifierUtil;
@@ -73,75 +68,6 @@ public class MetadataObjectPolicyOperations {
this.policyDispatcher = policyDispatcher;
}
- @GET
- @Path("{policy}")
- @Produces("application/vnd.gravitino.v1+json")
- @Timed(name = "get-object-policy." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)
- @ResponseMetered(name = "get-object-policy", absolute = true)
- @AuthorizationExpression(
- expression =
- "METALAKE::OWNER || ((POLICY::OWNER || ANY_VIEW_POLICY || ANY_APPLY_POLICY) && (CAN_ACCESS_METADATA))")
- public Response getPolicyForObject(
- @PathParam("metalake") @AuthorizationMetadata(type = Entity.EntityType.METALAKE)
- String metalake,
- @PathParam("type") @AuthorizationObjectType String type,
- @PathParam("fullName") @AuthorizationFullName String fullName,
- @PathParam("policy") @AuthorizationMetadata(type = Entity.EntityType.POLICY)
- String policyName) {
- LOG.info(
- "Received get policy {} request for object type: {}, full name: {} under metalake: {}",
- policyName,
- type,
- fullName,
- metalake);
-
- try {
- return Utils.doAs(
- httpRequest,
- () -> {
- MetadataObject object =
- MetadataObjects.parse(
- fullName, MetadataObject.Type.valueOf(type.toUpperCase(Locale.ROOT)));
- Optional<PolicyEntity> policyEntity = getPolicyForObject(metalake, object, policyName);
- Optional<PolicyDTO> policyDTO =
- policyEntity.map(
- policy ->
- PolicyOperations.toDTO(
- policy, Optional.of(policy.inherited().orElse(false))));
-
- if (!policyDTO.isPresent()) {
- LOG.warn(
- "Policy {} not found for object type: {}, full name: {} under metalake: {}",
- policyName,
- type,
- fullName,
- metalake);
- return Utils.notFound(
- NoSuchPolicyException.class.getSimpleName(),
- "Policy not found: "
- + policyName
- + " for object type: "
- + type
- + ", full name: "
- + fullName
- + " under metalake: "
- + metalake);
- } else {
- LOG.info(
- "Get policy: {} for object type: {}, full name: {} under metalake: {}",
- policyName,
- type,
- fullName,
- metalake);
- return Utils.ok(new PolicyResponse(policyDTO.get()));
- }
- });
-
- } catch (Exception e) {
- return ExceptionHandlers.handlePolicyException(OperationType.GET, policyName, fullName, e);
- }
- }
-
@GET
@Produces("application/vnd.gravitino.v1+json")
@Timed(name = "list-object-policies." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)
@@ -213,79 +139,4 @@ public class MetadataObjectPolicyOperations {
return ExceptionHandlers.handlePolicyException(OperationType.LIST, "", fullName, e);
}
}
-
- @Deprecated
- @POST
- @Produces("application/vnd.gravitino.v1+json")
- @Timed(name = "associate-object-policies." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)
- @ResponseMetered(name = "associate-object-policies", absolute = true)
- @AuthorizationExpression(
- expression =
- "METALAKE::OWNER || ((POLICY::OWNER || ANY_APPLY_POLICY) && (CAN_ACCESS_METADATA))")
- public Response associatePoliciesForObject(
- @PathParam("metalake") @AuthorizationMetadata(type = Entity.EntityType.METALAKE)
- String metalake,
- @PathParam("type") @AuthorizationObjectType String type,
- @PathParam("fullName") @AuthorizationFullName String fullName,
- @AuthorizationRequest(type = AuthorizationRequest.RequestType.ASSOCIATE_POLICY)
- PoliciesAssociateRequest request) {
- if (request == null) {
- return ExceptionHandlers.handlePolicyException(
- OperationType.ASSOCIATE,
- "",
- fullName,
- new IllegalArgumentException("Request body cannot be null"));
- }
-
- LOG.info(
- "Received associate policies request for object type: {}, full name: {} under metalake: {}",
- type,
- fullName,
- metalake);
- try {
- return Utils.doAs(
- httpRequest,
- () -> {
- request.validate();
- MetadataObject object =
- MetadataObjects.parse(
- fullName, MetadataObject.Type.valueOf(type.toUpperCase(Locale.ROOT)));
- String[] policyNames =
- policyDispatcher.associatePoliciesForMetadataObject(
- metalake, object, request.getPoliciesToAdd(), request.getPoliciesToRemove());
- policyNames = policyNames == null ? new String[0] : policyNames;
-
- LOG.info(
- "Associated policies: {} for object type: {}, full name: {} under metalake: {}",
- Arrays.toString(policyNames),
- type,
- fullName,
- metalake);
- return Utils.ok(new NameListResponse(policyNames));
- });
-
- } catch (Exception e) {
- return ExceptionHandlers.handlePolicyException(OperationType.ASSOCIATE, "", fullName, e);
- }
- }
-
- /**
- * Get the policy for the given metadata object and policy name. If the policy is not found,
- * return an empty Optional.
- *
- * @param metalake the name of the metalake
- * @param object the metadata object for which the policy is associated
- * @param policyName the name of the policy to retrieve
- * @return an Optional containing the policy if found, otherwise an empty Optional
- */
- private Optional<PolicyEntity> getPolicyForObject(
- String metalake, MetadataObject object, String policyName) {
- try {
- return Optional.ofNullable(
- policyDispatcher.getPolicyForMetadataObject(metalake, object, policyName));
- } catch (NoSuchPolicyException e) {
- LOG.info("Policy {} not found for object: {}", policyName, object);
- return Optional.empty();
- }
- }
}
diff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/PolicyOperations.java b/server/src/main/java/org/apache/gravitino/server/web/rest/PolicyOperations.java
index 2f2305176b..14c20a1c31 100644
--- a/server/src/main/java/org/apache/gravitino/server/web/rest/PolicyOperations.java
+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/PolicyOperations.java
@@ -39,7 +39,6 @@ import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import org.apache.gravitino.Entity;
-import org.apache.gravitino.MetadataObject;
import org.apache.gravitino.RelationalEntity;
import org.apache.gravitino.dto.policy.PolicyAssociationSelectorDTO;
import org.apache.gravitino.dto.policy.PolicyDTO;
@@ -49,12 +48,10 @@ import org.apache.gravitino.dto.requests.PolicyUpdateRequest;
import org.apache.gravitino.dto.requests.PolicyUpdatesRequest;
import org.apache.gravitino.dto.responses.BaseResponse;
import org.apache.gravitino.dto.responses.DropResponse;
-import org.apache.gravitino.dto.responses.MetadataObjectListResponse;
import org.apache.gravitino.dto.responses.NameListResponse;
import org.apache.gravitino.dto.responses.PolicyListResponse;
import org.apache.gravitino.dto.responses.PolicyResponse;
import org.apache.gravitino.dto.responses.TagForPolicyAssociationListResponse;
-import org.apache.gravitino.dto.tag.MetadataObjectDTO;
import org.apache.gravitino.dto.tag.TagForPolicyAssociationDTO;
import org.apache.gravitino.dto.util.DTOConverters;
import org.apache.gravitino.json.PolicyAssociationSelectorSerde;
@@ -324,45 +321,6 @@ public class PolicyOperations {
}
}
- @GET
- @Path("{policy}/objects")
- @Produces("application/vnd.gravitino.v1+json")
- @Timed(name = "list-objects-for-policy." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)
- @ResponseMetered(name = "list-objects-for-policy", absolute = true)
- @AuthorizationExpression(
- expression = AuthorizationExpressionConstants.LOAD_POLICY_AUTHORIZATION_EXPRESSION)
- public Response listMetadataObjectsForPolicy(
- @PathParam("metalake") @AuthorizationMetadata(type = Entity.EntityType.METALAKE)
- String metalake,
- @PathParam("policy") @AuthorizationMetadata(type = Entity.EntityType.POLICY)
- String policyName) {
- LOG.info("Received list objects for policy: {} under metalake: {}", policyName, metalake);
-
- try {
- return Utils.doAs(
- httpRequest,
- () -> {
- MetadataObject[] objects =
- policyDispatcher.listMetadataObjectsForPolicy(metalake, policyName);
- objects = objects == null ? new MetadataObject[0] : objects;
- objects = MetadataAuthzHelper.filterMetadataObject(metalake, objects);
- LOG.info(
- "List {} objects for policy: {} under metalake: {}",
- objects.length,
- policyName,
- metalake);
-
- MetadataObjectDTO[] objectDTOs =
- Arrays.stream(objects).map(DTOConverters::toDTO).toArray(MetadataObjectDTO[]::new);
-
- return Utils.ok(new MetadataObjectListResponse(objectDTOs));
- });
-
- } catch (Exception e) {
- return ExceptionHandlers.handlePolicyException(OperationType.LIST, "", metalake, e);
- }
- }
-
@GET
@Path("{policy}/tags")
@Produces("application/vnd.gravitino.v1+json")
diff --git a/server/src/test/java/org/apache/gravitino/server/web/rest/TestMetadataObjectPolicyOperations.java b/server/src/test/java/org/apache/gravitino/server/web/rest/TestMetadataObjectPolicyOperations.java
index f3d8d52dfb..e7703609d8 100644
--- a/server/src/test/java/org/apache/gravitino/server/web/rest/TestMetadataObjectPolicyOperations.java
+++ b/server/src/test/java/org/apache/gravitino/server/web/rest/TestMetadataObjectPolicyOperations.java
@@ -20,8 +20,6 @@ package org.apache.gravitino.server.web.rest;
import static org.apache.gravitino.Configs.CACHE_ENABLED;
import static org.apache.gravitino.Configs.ENABLE_AUTHORIZATION;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -44,14 +42,8 @@ import org.apache.gravitino.Config;
import org.apache.gravitino.GravitinoEnv;
import org.apache.gravitino.MetadataObject;
import org.apache.gravitino.MetadataObjects;
-import org.apache.gravitino.dto.requests.PoliciesAssociateRequest;
-import org.apache.gravitino.dto.responses.ErrorConstants;
-import org.apache.gravitino.dto.responses.ErrorResponse;
import org.apache.gravitino.dto.responses.NameListResponse;
import org.apache.gravitino.dto.responses.PolicyListResponse;
-import org.apache.gravitino.dto.responses.PolicyResponse;
-import org.apache.gravitino.exceptions.NoSuchPolicyException;
-import org.apache.gravitino.exceptions.PolicyAlreadyAssociatedException;
import org.apache.gravitino.meta.AuditInfo;
import org.apache.gravitino.meta.PolicyEntity;
import org.apache.gravitino.policy.Policy;
@@ -366,95 +358,6 @@ public class TestMetadataObjectPolicyOperations extends BaseOperationsTest {
Assertions.assertTrue(resultPolicies.get("catalogPolicy").inherited().get());
}
- @Test
- public void testGetPolicyForObjectUnderHierarchicalSchema() {
- // The manager resolves policies from the table's effective tags, including inherited tags.
- // The REST layer queries only the requested table.
- MetadataObject table = MetadataObjects.parse("hcat.a:b:c.tbl", MetadataObject.Type.TABLE);
-
- PolicyEntity schemaAPolicy = createPolicy("schemaAPolicy").copyWithInherited(true);
- PolicyEntity schemaBPolicy = createPolicy("schemaBPolicy").copyWithInherited(true);
- when(policyManager.getPolicyForMetadataObject(metalake, table, schemaAPolicy.name()))
- .thenReturn(schemaAPolicy);
- when(policyManager.getPolicyForMetadataObject(metalake, table, schemaBPolicy.name()))
- .thenReturn(schemaBPolicy);
-
- // A policy selected by an inherited tag is resolved directly for the table.
- Response responseB =
- target(basePath(metalake))
- .path(table.type().toString())
- .path(table.fullName())
- .path("policies")
- .path("schemaBPolicy")
- .request(MediaType.APPLICATION_JSON_TYPE)
- .accept("application/vnd.gravitino.v1+json")
- .get();
- Assertions.assertEquals(Response.Status.OK.getStatusCode(), responseB.getStatus());
- Policy respPolicyB = responseB.readEntity(PolicyResponse.class).getPolicy();
- Assertions.assertEquals("schemaBPolicy", respPolicyB.name());
- Assertions.assertTrue(respPolicyB.inherited().get());
-
- // The same rule applies to a tag inherited from a more distant ancestor.
- Response responseA =
- target(basePath(metalake))
- .path(table.type().toString())
- .path(table.fullName())
- .path("policies")
- .path("schemaAPolicy")
- .request(MediaType.APPLICATION_JSON_TYPE)
- .accept("application/vnd.gravitino.v1+json")
- .get();
- Assertions.assertEquals(Response.Status.OK.getStatusCode(), responseA.getStatus());
- Policy respPolicyA = responseA.readEntity(PolicyResponse.class).getPolicy();
- Assertions.assertEquals("schemaAPolicy", respPolicyA.name());
- Assertions.assertTrue(respPolicyA.inherited().get());
- }
-
- @Test
- public void testParentTagDerivedPolicyIsNotReturnedForChild() {
- MetadataObject schema = MetadataObjects.parse("catalog.schema", MetadataObject.Type.SCHEMA);
- MetadataObject table = MetadataObjects.parse("catalog.schema.table", MetadataObject.Type.TABLE);
- PolicyEntity parentDerivedPolicy = createPolicy("financePolicy");
-
- when(policyManager.listPolicyInfosForMetadataObject(metalake, table))
- .thenReturn(new PolicyEntity[0]);
- when(policyManager.listPolicyInfosForMetadataObject(metalake, schema))
- .thenReturn(new PolicyEntity[] {parentDerivedPolicy});
- when(policyManager.getPolicyForMetadataObject(metalake, table, parentDerivedPolicy.name()))
- .thenThrow(new NoSuchPolicyException("not applicable"));
- when(policyManager.getPolicyForMetadataObject(metalake, schema, parentDerivedPolicy.name()))
- .thenReturn(parentDerivedPolicy);
-
- Response listResponse =
- target(basePath(metalake))
- .path(table.type().toString())
- .path(table.fullName())
- .path("policies")
- .queryParam("details", true)
- .request(MediaType.APPLICATION_JSON_TYPE)
- .accept("application/vnd.gravitino.v1+json")
- .get();
- Assertions.assertEquals(Response.Status.OK.getStatusCode(), listResponse.getStatus());
- Assertions.assertEquals(
- 0, listResponse.readEntity(PolicyListResponse.class).getPolicies().length);
-
- Response getResponse =
- target(basePath(metalake))
- .path(table.type().toString())
- .path(table.fullName())
- .path("policies")
- .path(parentDerivedPolicy.name())
- .request(MediaType.APPLICATION_JSON_TYPE)
- .accept("application/vnd.gravitino.v1+json")
- .get();
- Assertions.assertEquals(Response.Status.NOT_FOUND.getStatusCode(), getResponse.getStatus());
-
- Mockito.verify(policyManager, Mockito.never())
- .listPolicyInfosForMetadataObject(metalake, schema);
- Mockito.verify(policyManager, Mockito.never())
- .getPolicyForMetadataObject(metalake, schema, parentDerivedPolicy.name());
- }
-
@Test
public void testListPoliciesFiltersResolvedResult() throws IllegalAccessException {
MetadataObject schema = MetadataObjects.parse("catalog.schema", MetadataObject.Type.SCHEMA);
@@ -501,254 +404,20 @@ public class TestMetadataObjectPolicyOperations extends BaseOperationsTest {
}
@Test
- public void testGetPolicyForObject() {
- PolicyEntity policy1 = createPolicy("policy1");
+ public void testRemovedObjectPolicyEndpoints() {
MetadataObject catalog = MetadataObjects.parse("object1", MetadataObject.Type.CATALOG);
- when(policyManager.getPolicyForMetadataObject(metalake, catalog, "policy1"))
- .thenReturn(policy1);
+ String path =
+ basePath(metalake) + "/" + catalog.type() + "/" + catalog.fullName() + "/policies";
- PolicyEntity policy2 = createPolicy("policy2");
- MetadataObject schema = MetadataObjects.parse("object1.object2", MetadataObject.Type.SCHEMA);
- when(policyManager.getPolicyForMetadataObject(metalake, schema, "policy2")).thenReturn(policy2);
-
- PolicyEntity policy3 = createPolicy("policy3");
- MetadataObject table =
- MetadataObjects.parse("object1.object2.object3", MetadataObject.Type.TABLE);
- when(policyManager.getPolicyForMetadataObject(metalake, table, "policy3")).thenReturn(policy3);
- when(policyManager.getPolicyForMetadataObject(metalake, schema, "policy1"))
- .thenReturn(policy1.copyWithInherited(true));
- when(policyManager.getPolicyForMetadataObject(metalake, table, "policy2"))
- .thenReturn(policy2.copyWithInherited(true));
-
- // Test catalog policy
- Response response =
- target(basePath(metalake))
- .path(catalog.type().toString())
- .path(catalog.fullName())
- .path("policies")
- .path("policy1")
- .request(MediaType.APPLICATION_JSON_TYPE)
- .accept("application/vnd.gravitino.v1+json")
- .get();
-
- Assertions.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
-
- PolicyResponse policyResponse = response.readEntity(PolicyResponse.class);
- Assertions.assertEquals(0, policyResponse.getCode());
-
- Policy respPolicy = policyResponse.getPolicy();
- Assertions.assertEquals(policy1.name(), respPolicy.name());
- Assertions.assertEquals(policy1.comment(), respPolicy.comment());
- Assertions.assertFalse(respPolicy.inherited().get());
-
- // Test schema policy
- Response response1 =
- target(basePath(metalake))
- .path(schema.type().toString())
- .path(schema.fullName())
- .path("policies")
- .path("policy2")
- .request(MediaType.APPLICATION_JSON_TYPE)
- .accept("application/vnd.gravitino.v1+json")
- .get();
-
- Assertions.assertEquals(Response.Status.OK.getStatusCode(), response1.getStatus());
-
- PolicyResponse policyResponse1 = response1.readEntity(PolicyResponse.class);
- Assertions.assertEquals(0, policyResponse1.getCode());
-
- Policy respPolicy1 = policyResponse1.getPolicy();
- Assertions.assertEquals(policy2.name(), respPolicy1.name());
- Assertions.assertEquals(policy2.comment(), respPolicy1.comment());
- Assertions.assertFalse(respPolicy1.inherited().get());
-
- // Test table policy
- Response response2 =
- target(basePath(metalake))
- .path(table.type().toString())
- .path(table.fullName())
- .path("policies")
- .path("policy3")
- .request(MediaType.APPLICATION_JSON_TYPE)
- .accept("application/vnd.gravitino.v1+json")
- .get();
-
- Assertions.assertEquals(Response.Status.OK.getStatusCode(), response2.getStatus());
-
- PolicyResponse policyResponse2 = response2.readEntity(PolicyResponse.class);
- Assertions.assertEquals(0, policyResponse2.getCode());
-
- Policy respPolicy2 = policyResponse2.getPolicy();
- Assertions.assertEquals(policy3.name(), respPolicy2.name());
- Assertions.assertEquals(policy3.comment(), respPolicy2.comment());
- Assertions.assertFalse(respPolicy2.inherited().get());
-
- // Test a schema policy resolved from an effective tag
- Response response4 =
- target(basePath(metalake))
- .path(schema.type().toString())
- .path(schema.fullName())
- .path("policies")
- .path("policy1")
- .request(MediaType.APPLICATION_JSON_TYPE)
- .accept("application/vnd.gravitino.v1+json")
- .get();
-
- Assertions.assertEquals(Response.Status.OK.getStatusCode(), response4.getStatus());
-
- PolicyResponse policyResponse4 = response4.readEntity(PolicyResponse.class);
- Assertions.assertEquals(0, policyResponse4.getCode());
-
- Policy respPolicy4 = policyResponse4.getPolicy();
- Assertions.assertEquals(policy1.name(), respPolicy4.name());
- Assertions.assertEquals(policy1.comment(), respPolicy4.comment());
- Assertions.assertTrue(respPolicy4.inherited().get());
-
- // Test a table policy resolved from an effective tag
- Response response5 =
- target(basePath(metalake))
- .path(table.type().toString())
- .path(table.fullName())
- .path("policies")
- .path("policy2")
- .request(MediaType.APPLICATION_JSON_TYPE)
- .accept("application/vnd.gravitino.v1+json")
- .get();
-
- Assertions.assertEquals(Response.Status.OK.getStatusCode(), response5.getStatus());
-
- PolicyResponse policyResponse5 = response5.readEntity(PolicyResponse.class);
- Assertions.assertEquals(0, policyResponse5.getCode());
-
- Policy respPolicy5 = policyResponse5.getPolicy();
- Assertions.assertEquals(policy2.name(), respPolicy5.name());
- Assertions.assertEquals(policy2.comment(), respPolicy5.comment());
- Assertions.assertTrue(respPolicy5.inherited().get());
-
- // Test catalog policy throw NoSuchPolicyException
- Response response7 =
- target(basePath(metalake))
- .path(catalog.type().toString())
- .path(catalog.fullName())
- .path("policies")
- .path("policy2")
- .request(MediaType.APPLICATION_JSON_TYPE)
- .accept("application/vnd.gravitino.v1+json")
- .get();
-
- Assertions.assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response7.getStatus());
-
- ErrorResponse errorResponse = response7.readEntity(ErrorResponse.class);
- Assertions.assertEquals(ErrorConstants.NOT_FOUND_CODE, errorResponse.getCode());
- Assertions.assertEquals(NoSuchPolicyException.class.getSimpleName(), errorResponse.getType());
-
- // Test schema policy throw NoSuchPolicyException
- Response response8 =
- target(basePath(metalake))
- .path(schema.type().toString())
- .path(schema.fullName())
- .path("policies")
- .path("policy3")
- .request(MediaType.APPLICATION_JSON_TYPE)
- .accept("application/vnd.gravitino.v1+json")
- .get();
-
- Assertions.assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response8.getStatus());
-
- ErrorResponse errorResponse1 = response8.readEntity(ErrorResponse.class);
- Assertions.assertEquals(ErrorConstants.NOT_FOUND_CODE, errorResponse1.getCode());
- Assertions.assertEquals(NoSuchPolicyException.class.getSimpleName(), errorResponse1.getType());
- }
-
- @Test
- public void testAssociatePoliciesForObject() {
- String[] policiesToAdd = new String[] {"policy1", "policy2"};
- String[] policiesToRemove = new String[] {"policy3", "policy4"};
-
- MetadataObject catalog = MetadataObjects.parse("object1", MetadataObject.Type.CATALOG);
- when(policyManager.associatePoliciesForMetadataObject(
- metalake, catalog, policiesToAdd, policiesToRemove))
- .thenReturn(policiesToAdd);
-
- PoliciesAssociateRequest request =
- new PoliciesAssociateRequest(policiesToAdd, policiesToRemove);
- Response response =
- target(basePath(metalake))
- .path(catalog.type().toString())
- .path(catalog.fullName())
- .path("policies")
- .request(MediaType.APPLICATION_JSON_TYPE)
- .accept("application/vnd.gravitino.v1+json")
- .post(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));
-
- Assertions.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
- Assertions.assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getMediaType());
-
- NameListResponse nameListResponse = response.readEntity(NameListResponse.class);
- Assertions.assertEquals(0, nameListResponse.getCode());
-
- Assertions.assertArrayEquals(policiesToAdd, nameListResponse.getNames());
-
- // Test throw null policies
- when(policyManager.associatePoliciesForMetadataObject(
- metalake, catalog, policiesToAdd, policiesToRemove))
- .thenReturn(null);
- Response response1 =
- target(basePath(metalake))
- .path(catalog.type().toString())
- .path(catalog.fullName())
- .path("policies")
- .request(MediaType.APPLICATION_JSON_TYPE)
- .accept("application/vnd.gravitino.v1+json")
- .post(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));
-
- Assertions.assertEquals(Response.Status.OK.getStatusCode(), response1.getStatus());
-
- NameListResponse nameListResponse1 = response1.readEntity(NameListResponse.class);
- Assertions.assertEquals(0, nameListResponse1.getCode());
-
- Assertions.assertEquals(0, nameListResponse1.getNames().length);
-
- // Test throw PolicyAlreadyAssociatedException
- doThrow(new PolicyAlreadyAssociatedException("mock error"))
- .when(policyManager)
- .associatePoliciesForMetadataObject(metalake, catalog, policiesToAdd, policiesToRemove);
- Response response2 =
- target(basePath(metalake))
- .path(catalog.type().toString())
- .path(catalog.fullName())
- .path("policies")
- .request(MediaType.APPLICATION_JSON_TYPE)
- .accept("application/vnd.gravitino.v1+json")
- .post(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));
-
- Assertions.assertEquals(Response.Status.CONFLICT.getStatusCode(), response2.getStatus());
-
- ErrorResponse errorResponse = response2.readEntity(ErrorResponse.class);
- Assertions.assertEquals(ErrorConstants.ALREADY_EXISTS_CODE, errorResponse.getCode());
+ Response singlePolicyResponse =
+ target(path).path("policy1").request(MediaType.APPLICATION_JSON_TYPE).get();
Assertions.assertEquals(
- PolicyAlreadyAssociatedException.class.getSimpleName(), errorResponse.getType());
-
- // Test throw RuntimeException
- doThrow(new RuntimeException("mock error"))
- .when(policyManager)
- .associatePoliciesForMetadataObject(any(), any(), any(), any());
-
- Response response3 =
- target(basePath(metalake))
- .path(catalog.type().toString())
- .path(catalog.fullName())
- .path("policies")
- .request(MediaType.APPLICATION_JSON_TYPE)
- .accept("application/vnd.gravitino.v1+json")
- .post(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));
+ Response.Status.NOT_FOUND.getStatusCode(), singlePolicyResponse.getStatus());
+ Response associationResponse =
+ target(path).request(MediaType.APPLICATION_JSON_TYPE).post(Entity.json("{}"));
Assertions.assertEquals(
- Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response3.getStatus());
-
- ErrorResponse errorResponse1 = response3.readEntity(ErrorResponse.class);
- Assertions.assertEquals(ErrorConstants.INTERNAL_ERROR_CODE, errorResponse1.getCode());
- Assertions.assertEquals(RuntimeException.class.getSimpleName(), errorResponse1.getType());
+ Response.Status.METHOD_NOT_ALLOWED.getStatusCode(), associationResponse.getStatus());
}
private String basePath(String metalake) {
@@ -764,20 +433,4 @@ public class TestMetadataObjectPolicyOperations extends BaseOperationsTest {
.withAuditInfo(testAuditInfo1)
.build();
}
-
- @Test
- public void testAssociatePoliciesForObjectWithNullRequest() {
- MetadataObject catalog = MetadataObjects.parse("object1", MetadataObject.Type.CATALOG);
-
- Response response =
- target(basePath(metalake))
- .path(catalog.type().toString())
- .path(catalog.fullName())
- .path("policies")
- .request(MediaType.APPLICATION_JSON_TYPE)
- .accept("application/vnd.gravitino.v1+json")
- .post(Entity.entity("null", MediaType.APPLICATION_JSON_TYPE));
-
- assertNullRequestBodyRejected(response);
- }
}
diff --git a/server/src/test/java/org/apache/gravitino/server/web/rest/TestPolicyOperations.java b/server/src/test/java/org/apache/gravitino/server/web/rest/TestPolicyOperations.java
index 76c66e38fb..1d53af9576 100644
--- a/server/src/test/java/org/apache/gravitino/server/web/rest/TestPolicyOperations.java
+++ b/server/src/test/java/org/apache/gravitino/server/web/rest/TestPolicyOperations.java
@@ -43,7 +43,6 @@ import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.gravitino.Config;
import org.apache.gravitino.GravitinoEnv;
import org.apache.gravitino.MetadataObject;
-import org.apache.gravitino.MetadataObjects;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.RelationalEntity;
import org.apache.gravitino.SupportsRelationOperations;
@@ -56,7 +55,6 @@ import org.apache.gravitino.dto.responses.BaseResponse;
import org.apache.gravitino.dto.responses.DropResponse;
import org.apache.gravitino.dto.responses.ErrorConstants;
import org.apache.gravitino.dto.responses.ErrorResponse;
-import org.apache.gravitino.dto.responses.MetadataObjectListResponse;
import org.apache.gravitino.dto.responses.NameListResponse;
import org.apache.gravitino.dto.responses.PolicyListResponse;
import org.apache.gravitino.dto.responses.PolicyResponse;
@@ -205,6 +203,17 @@ public class TestPolicyOperations extends BaseOperationsTest {
Assertions.assertEquals(RuntimeException.class.getSimpleName(), errorResp1.getType());
}
+ @Test
+ public void testRemovedPolicyObjectsEndpoint() {
+ Response response =
+ target(policyPath(metalake))
+ .path("policy1")
+ .path("objects")
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .get();
+ Assertions.assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus());
+ }
+
@Test
public void testTagAssociationsForPolicy() {
String policyName = "policy1";
@@ -783,80 +792,6 @@ public class TestPolicyOperations extends BaseOperationsTest {
Assertions.assertEquals(RuntimeException.class.getSimpleName(), errorResp1.getType());
}
- @Test
- public void testListMetadataObjectForPolicy() {
- MetadataObject[] objects =
- new MetadataObject[] {
- MetadataObjects.parse("object1", MetadataObject.Type.CATALOG),
- MetadataObjects.parse("object1.object2", MetadataObject.Type.SCHEMA),
- MetadataObjects.parse("object1.object2.object3", MetadataObject.Type.TABLE),
- };
-
- when(policyManager.listMetadataObjectsForPolicy(metalake, "policy1")).thenReturn(objects);
-
- Response response =
- target(policyPath(metalake))
- .path("policy1")
- .path("objects")
- .request(MediaType.APPLICATION_JSON_TYPE)
- .accept("application/vnd.gravitino.v1+json")
- .get();
-
- Assertions.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
- Assertions.assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getMediaType());
-
- MetadataObjectListResponse objectListResponse =
- response.readEntity(MetadataObjectListResponse.class);
- Assertions.assertEquals(0, objectListResponse.getCode());
-
- MetadataObject[] respObjects = objectListResponse.getMetadataObjects();
- Assertions.assertEquals(objects.length, respObjects.length);
-
- for (int i = 0; i < objects.length; i++) {
- Assertions.assertEquals(objects[i].type(), respObjects[i].type());
- Assertions.assertEquals(objects[i].fullName(), respObjects[i].fullName());
- }
-
- // Test throw NoSuchPolicyException
- doThrow(new NoSuchPolicyException("mock error"))
- .when(policyManager)
- .listMetadataObjectsForPolicy(metalake, "policy1");
-
- Response response1 =
- target(policyPath(metalake))
- .path("policy1")
- .path("objects")
- .request(MediaType.APPLICATION_JSON_TYPE)
- .accept("application/vnd.gravitino.v1+json")
- .get();
-
- Assertions.assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response1.getStatus());
-
- ErrorResponse errorResponse = response1.readEntity(ErrorResponse.class);
- Assertions.assertEquals(ErrorConstants.NOT_FOUND_CODE, errorResponse.getCode());
- Assertions.assertEquals(NoSuchPolicyException.class.getSimpleName(), errorResponse.getType());
-
- // Test throw RuntimeException
- doThrow(new RuntimeException("mock error"))
- .when(policyManager)
- .listMetadataObjectsForPolicy(any(), any());
-
- Response response2 =
- target(policyPath(metalake))
- .path("policy1")
- .path("objects")
- .request(MediaType.APPLICATION_JSON_TYPE)
- .accept("application/vnd.gravitino.v1+json")
- .get();
-
- Assertions.assertEquals(
- Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response2.getStatus());
-
- ErrorResponse errorResponse1 = response2.readEntity(ErrorResponse.class);
- Assertions.assertEquals(ErrorConstants.INTERNAL_ERROR_CODE, errorResponse1.getCode());
- Assertions.assertEquals(RuntimeException.class.getSimpleName(), errorResponse1.getType());
- }
-
private String policyPath(String metalake) {
return "/metalakes/" + metalake + "/policies";
}
diff --git a/server/src/test/java/org/apache/gravitino/server/web/rest/authorization/TestTagPolicyAuthorizationExpression.java b/server/src/test/java/org/apache/gravitino/server/web/rest/authorization/TestTagPolicyAuthorizationExpression.java
index 534f8ef933..715ab6f496 100644
--- a/server/src/test/java/org/apache/gravitino/server/web/rest/authorization/TestTagPolicyAuthorizationExpression.java
+++ b/server/src/test/java/org/apache/gravitino/server/web/rest/authorization/TestTagPolicyAuthorizationExpression.java
@@ -19,8 +19,10 @@
package org.apache.gravitino.server.web.rest.authorization;
import static org.apache.gravitino.server.authorization.expression.AuthorizationExpressionConstants.APPLY_TAG_AUTHORIZATION_EXPRESSION;
+import static org.apache.gravitino.server.authorization.expression.AuthorizationExpressionConstants.CAN_ACCESS_METADATA;
import static org.apache.gravitino.server.authorization.expression.AuthorizationExpressionConstants.LOAD_POLICY_AUTHORIZATION_EXPRESSION;
import static org.apache.gravitino.server.authorization.expression.AuthorizationExpressionConstants.LOAD_TAG_AUTHORIZATION_EXPRESSION;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -73,24 +75,17 @@ public class TestTagPolicyAuthorizationExpression {
}
@Test
- public void testGetMetadataObjectPolicyWithViewOrApplyPrivilege()
- throws ReflectiveOperationException, OgnlException {
+ public void testListMetadataObjectPoliciesRequiresMetadataAccess()
+ throws ReflectiveOperationException {
Method method =
MetadataObjectPolicyOperations.class.getDeclaredMethod(
- "getPolicyForObject", String.class, String.class, String.class, String.class);
- assertFalse(method.isAnnotationPresent(Deprecated.class));
+ "listPoliciesForMetadataObject",
+ String.class,
+ String.class,
+ String.class,
+ boolean.class);
AuthorizationExpression annotation = method.getAnnotation(AuthorizationExpression.class);
- MockAuthorizationExpressionEvaluator evaluator =
- new MockAuthorizationExpressionEvaluator(
- annotation.expression().replace("CAN_ACCESS_METADATA", "CATALOG::OWNER"));
-
- assertTrue(evaluator.getResult(ImmutableSet.of("POLICY::VIEW_POLICY", "CATALOG::OWNER")));
- assertTrue(evaluator.getResult(ImmutableSet.of("POLICY::APPLY_POLICY", "CATALOG::OWNER")));
- assertFalse(
- evaluator.getResult(
- ImmutableSet.of(
- "POLICY::APPLY_POLICY", "POLICY::DENY_APPLY_POLICY", "CATALOG::OWNER")));
- assertFalse(evaluator.getResult(ImmutableSet.of("POLICY::APPLY_POLICY")));
+ assertEquals(CAN_ACCESS_METADATA, annotation.expression());
}
}