Skip to content

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

[#2240] feat(server): Add the operations for the group (#2752)

qqqttt123a1c1d53777d8
diff --git a/common/src/main/java/com/datastrato/gravitino/dto/authorization/GroupDTO.java b/common/src/main/java/com/datastrato/gravitino/dto/authorization/GroupDTO.java
new file mode 100644
index 0000000000..2c4720bc9d
--- /dev/null
+++ b/common/src/main/java/com/datastrato/gravitino/dto/authorization/GroupDTO.java
@@ -0,0 +1,139 @@
+/*
+ * Copyright 2024 Datastrato Pvt Ltd.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.gravitino.dto.authorization;
+
+import com.datastrato.gravitino.Audit;
+import com.datastrato.gravitino.authorization.Group;
+import com.datastrato.gravitino.dto.AuditDTO;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.google.common.base.Preconditions;
+import java.util.Collections;
+import java.util.List;
+import org.apache.commons.lang3.StringUtils;
+
+/** Represents a Group Data Transfer Object (DTO). */
+public class GroupDTO implements Group {
+
+ @JsonProperty("name")
+ private String name;
+
+ @JsonProperty("audit")
+ private AuditDTO audit;
+
+ @JsonProperty("roles")
+ private List<String> roles;
+
+ /** Default constructor for Jackson deserialization. */
+ protected GroupDTO() {}
+
+ /**
+ * Creates a new instance of GroupDTO.
+ *
+ * @param name The name of the Group DTO.
+ * @param roles The roles of the Group DTO.
+ * @param audit The audit information of the Group DTO.
+ */
+ protected GroupDTO(String name, List<String> roles, AuditDTO audit) {
+ this.name = name;
+ this.audit = audit;
+ this.roles = roles;
+ }
+
+ /** @return The name of the Group DTO. */
+ @Override
+ public String name() {
+ return name;
+ }
+
+ /**
+ * The roles of the group. A group can have multiple roles. Every role binds several privileges.
+ *
+ * @return The roles of the group.
+ */
+ @Override
+ public List<String> roles() {
+ return roles;
+ }
+
+ /** @return The audit information of the Group DTO. */
+ @Override
+ public Audit auditInfo() {
+ return audit;
+ }
+
+ /**
+ * Creates a new Builder for constructing a Group DTO.
+ *
+ * @return A new Builder instance.
+ */
+ public static Builder builder() {
+ return new Builder();
+ }
+
+ /**
+ * Builder class for constructing a GroupDTO instance.
+ *
+ * @param <S> The type of the builder instance.
+ */
+ public static class Builder<S extends Builder> {
+
+ /** The name of the group. */
+ protected String name;
+
+ /** The roles of the group. */
+ protected List<String> roles = Collections.emptyList();
+
+ /** The audit information of the group. */
+ protected AuditDTO audit;
+
+ /**
+ * Sets the name of the group.
+ *
+ * @param name The name of the group.
+ * @return The builder instance.
+ */
+ public S withName(String name) {
+ this.name = name;
+ return (S) this;
+ }
+
+ /**
+ * Sets the roles of the group.
+ *
+ * @param roles The roles of the group.
+ * @return The builder instance.
+ */
+ public S withRoles(List<String> roles) {
+ if (roles != null) {
+ this.roles = roles;
+ }
+
+ return (S) this;
+ }
+
+ /**
+ * Sets the audit information of the group.
+ *
+ * @param audit The audit information of the group.
+ * @return The builder instance.
+ */
+ public S withAudit(AuditDTO audit) {
+ this.audit = audit;
+ return (S) this;
+ }
+
+ /**
+ * Builds an instance of GroupDTO using the builder's properties.
+ *
+ * @return An instance of GroupDTO.
+ * @throws IllegalArgumentException If the name or audit are not set.
+ */
+ public GroupDTO build() {
+ Preconditions.checkArgument(StringUtils.isNotBlank(name), "name cannot be null or empty");
+ Preconditions.checkArgument(audit != null, "audit cannot be null");
+ return new GroupDTO(name, roles, audit);
+ }
+ }
+}
diff --git a/common/src/main/java/com/datastrato/gravitino/dto/requests/GroupAddRequest.java b/common/src/main/java/com/datastrato/gravitino/dto/requests/GroupAddRequest.java
new file mode 100644
index 0000000000..5c41fdaefe
--- /dev/null
+++ b/common/src/main/java/com/datastrato/gravitino/dto/requests/GroupAddRequest.java
@@ -0,0 +1,53 @@
+/*
+ * Copyright 2024 Datastrato Pvt Ltd.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.gravitino.dto.requests;
+
+import com.datastrato.gravitino.rest.RESTRequest;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.google.common.base.Preconditions;
+import lombok.Builder;
+import lombok.EqualsAndHashCode;
+import lombok.Getter;
+import lombok.ToString;
+import lombok.extern.jackson.Jacksonized;
+import org.apache.commons.lang3.StringUtils;
+
+/** Represents a request to add a group. */
+@Getter
+@EqualsAndHashCode
+@ToString
+@Builder
+@Jacksonized
+public class GroupAddRequest implements RESTRequest {
+
+ @JsonProperty("name")
+ private final String name;
+
+ /** Default constructor for GroupAddRequest. (Used for Jackson deserialization.) */
+ public GroupAddRequest() {
+ this(null);
+ }
+
+ /**
+ * Creates a new GroupAddRequest.
+ *
+ * @param name The name of the group.
+ */
+ public GroupAddRequest(String name) {
+ super();
+ this.name = name;
+ }
+
+ /**
+ * Validates the {@link GroupAddRequest} request.
+ *
+ * @throws IllegalArgumentException If the request is invalid, this exception is thrown.
+ */
+ @Override
+ public void validate() throws IllegalArgumentException {
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(name), "\"name\" field is required and cannot be empty");
+ }
+}
diff --git a/common/src/main/java/com/datastrato/gravitino/dto/responses/GroupResponse.java b/common/src/main/java/com/datastrato/gravitino/dto/responses/GroupResponse.java
new file mode 100644
index 0000000000..100f2fa13b
--- /dev/null
+++ b/common/src/main/java/com/datastrato/gravitino/dto/responses/GroupResponse.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright 2024 Datastrato Pvt Ltd.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.gravitino.dto.responses;
+
+import com.datastrato.gravitino.dto.authorization.GroupDTO;
+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;
+
+/** Represents a response for a group. */
+@Getter
+@ToString
+@EqualsAndHashCode(callSuper = true)
+public class GroupResponse extends BaseResponse {
+
+ @JsonProperty("group")
+ private final GroupDTO group;
+
+ /**
+ * Constructor for GroupResponse.
+ *
+ * @param group The group data transfer object.
+ */
+ public GroupResponse(GroupDTO group) {
+ super(0);
+ this.group = group;
+ }
+
+ /** Default constructor for GroupResponse. (Used for Jackson deserialization.) */
+ public GroupResponse() {
+ super();
+ this.group = null;
+ }
+
+ /**
+ * Validates the response data.
+ *
+ * @throws IllegalArgumentException if the name or audit is not set.
+ */
+ @Override
+ public void validate() throws IllegalArgumentException {
+ super.validate();
+
+ Preconditions.checkArgument(group != null, "group must not be null");
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(group.name()), "group 'name' must not be null and empty");
+ Preconditions.checkArgument(group.auditInfo() != null, "group 'auditInfo' must not be null");
+ }
+}
diff --git a/common/src/main/java/com/datastrato/gravitino/dto/util/DTOConverters.java b/common/src/main/java/com/datastrato/gravitino/dto/util/DTOConverters.java
index e9868b9b37..a2050e5354 100644
--- a/common/src/main/java/com/datastrato/gravitino/dto/util/DTOConverters.java
+++ b/common/src/main/java/com/datastrato/gravitino/dto/util/DTOConverters.java
@@ -9,10 +9,12 @@ import static com.datastrato.gravitino.rel.expressions.transforms.Transforms.NAM
import com.datastrato.gravitino.Audit;
import com.datastrato.gravitino.Catalog;
import com.datastrato.gravitino.Metalake;
+import com.datastrato.gravitino.authorization.Group;
import com.datastrato.gravitino.authorization.User;
import com.datastrato.gravitino.dto.AuditDTO;
import com.datastrato.gravitino.dto.CatalogDTO;
import com.datastrato.gravitino.dto.MetalakeDTO;
+import com.datastrato.gravitino.dto.authorization.GroupDTO;
import com.datastrato.gravitino.dto.authorization.UserDTO;
import com.datastrato.gravitino.dto.file.FilesetDTO;
import com.datastrato.gravitino.dto.messaging.TopicDTO;
@@ -349,6 +351,24 @@ public class DTOConverters {
.build();
}
+ /**
+ * Converts a group implementation to a GroupDTO.
+ *
+ * @param group The group implementation.
+ * @return The group DTO.
+ */
+ public static GroupDTO toDTO(Group group) {
+ if (group instanceof GroupDTO) {
+ return (GroupDTO) group;
+ }
+
+ return GroupDTO.builder()
+ .withName(group.name())
+ .withRoles(group.roles())
+ .withAudit(toDTO(group.auditInfo()))
+ .build();
+ }
+
/**
* Converts a Expression to an FunctionArg DTO.
*
diff --git a/common/src/test/java/com/datastrato/gravitino/dto/responses/TestResponses.java b/common/src/test/java/com/datastrato/gravitino/dto/responses/TestResponses.java
index 6176b6bf7a..4465cc34f1 100644
--- a/common/src/test/java/com/datastrato/gravitino/dto/responses/TestResponses.java
+++ b/common/src/test/java/com/datastrato/gravitino/dto/responses/TestResponses.java
@@ -14,6 +14,7 @@ import com.datastrato.gravitino.NameIdentifier;
import com.datastrato.gravitino.dto.AuditDTO;
import com.datastrato.gravitino.dto.CatalogDTO;
import com.datastrato.gravitino.dto.MetalakeDTO;
+import com.datastrato.gravitino.dto.authorization.GroupDTO;
import com.datastrato.gravitino.dto.authorization.UserDTO;
import com.datastrato.gravitino.dto.rel.ColumnDTO;
import com.datastrato.gravitino.dto.rel.SchemaDTO;
@@ -239,4 +240,18 @@ public class TestResponses {
UserResponse user = new UserResponse();
assertThrows(IllegalArgumentException.class, () -> user.validate());
}
+
+ void testGroupResponse() throws IllegalArgumentException {
+ AuditDTO audit =
+ AuditDTO.builder().withCreator("creator").withCreateTime(Instant.now()).build();
+ GroupDTO group = GroupDTO.builder().withName("group1").withAudit(audit).build();
+ GroupResponse response = new GroupResponse(group);
+ response.validate(); // No exception thrown
+ }
+
+ @Test
+ void testGroupResponseException() throws IllegalArgumentException {
+ GroupResponse group = new GroupResponse();
+ assertThrows(IllegalArgumentException.class, () -> group.validate());
+ }
}
diff --git a/core/src/test/java/com/datastrato/gravitino/authorization/TestAccessControlManager.java b/core/src/test/java/com/datastrato/gravitino/authorization/TestAccessControlManager.java
index 2a1e023d6c..03c51ad03e 100644
--- a/core/src/test/java/com/datastrato/gravitino/authorization/TestAccessControlManager.java
+++ b/core/src/test/java/com/datastrato/gravitino/authorization/TestAccessControlManager.java
@@ -64,7 +64,6 @@ public class TestAccessControlManager {
@Test
public void testAddUser() {
-
User user = accessControlManager.addUser("metalake", "testAdd");
Assertions.assertEquals("testAdd", user.name());
Assertions.assertTrue(user.roles().isEmpty());
@@ -82,7 +81,6 @@ public class TestAccessControlManager {
@Test
public void testGetUser() {
-
accessControlManager.addUser("metalake", "testGet");
User user = accessControlManager.getUser("metalake", "testGet");
@@ -97,7 +95,6 @@ public class TestAccessControlManager {
@Test
public void testRemoveUser() {
-
accessControlManager.addUser("metalake", "testRemove");
// Test to remove user
@@ -111,7 +108,6 @@ public class TestAccessControlManager {
@Test
public void testAddGroup() {
-
Group group = accessControlManager.addGroup("metalake", "testAdd");
Assertions.assertEquals("testAdd", group.name());
Assertions.assertTrue(group.roles().isEmpty());
@@ -129,7 +125,6 @@ public class TestAccessControlManager {
@Test
public void testGetGroup() {
-
accessControlManager.addGroup("metalake", "testGet");
Group group = accessControlManager.getGroup("metalake", "testGet");
@@ -145,7 +140,6 @@ public class TestAccessControlManager {
@Test
public void testRemoveGroup() {
-
accessControlManager.addGroup("metalake", "testRemove");
// Test to remove group
diff --git a/server/src/main/java/com/datastrato/gravitino/server/web/rest/ExceptionHandlers.java b/server/src/main/java/com/datastrato/gravitino/server/web/rest/ExceptionHandlers.java
index 2c4c9e5f5c..9b32d3c82e 100644
--- a/server/src/main/java/com/datastrato/gravitino/server/web/rest/ExceptionHandlers.java
+++ b/server/src/main/java/com/datastrato/gravitino/server/web/rest/ExceptionHandlers.java
@@ -6,6 +6,7 @@ package com.datastrato.gravitino.server.web.rest;
import com.datastrato.gravitino.exceptions.CatalogAlreadyExistsException;
import com.datastrato.gravitino.exceptions.FilesetAlreadyExistsException;
+import com.datastrato.gravitino.exceptions.GroupAlreadyExistsException;
import com.datastrato.gravitino.exceptions.MetalakeAlreadyExistsException;
import com.datastrato.gravitino.exceptions.NoSuchMetalakeException;
import com.datastrato.gravitino.exceptions.NonEmptySchemaException;
@@ -62,6 +63,11 @@ public class ExceptionHandlers {
return UserExceptionHandler.INSTANCE.handle(op, user, metalake, e);
}
+ public static Response handleGroupException(
+ OperationType op, String group, String metalake, Exception e) {
+ return GroupExceptionHandler.INSTANCE.handle(op, group, metalake, e);
+ }
+
public static Response handleTopicException(
OperationType op, String topic, String schema, Exception e) {
return TopicExceptionHandler.INSTANCE.handle(op, topic, schema, e);
@@ -271,10 +277,10 @@ public class ExceptionHandlers {
private static final ExceptionHandler INSTANCE = new UserExceptionHandler();
private static String getUserErrorMsg(
- String fileset, String operation, String metalake, String reason) {
+ String user, String operation, String metalake, String reason) {
return String.format(
"Failed to operate user %s operation [%s] under metalake [%s], reason [%s]",
- fileset, operation, metalake, reason);
+ user, operation, metalake, reason);
}
@Override
@@ -298,6 +304,38 @@ public class ExceptionHandlers {
}
}
+ private static class GroupExceptionHandler extends BaseExceptionHandler {
+
+ private static final ExceptionHandler INSTANCE = new GroupExceptionHandler();
+
+ private static String getGroupErrorMsg(
+ String group, String operation, String metalake, String reason) {
+ return String.format(
+ "Failed to operate group %s operation [%s] under metalake [%s], reason [%s]",
+ group, operation, metalake, reason);
+ }
+
+ @Override
+ public Response handle(OperationType op, String group, String metalake, Exception e) {
+ String formatted = StringUtil.isBlank(group) ? "" : " [" + group + "]";
+ String errorMsg = getGroupErrorMsg(formatted, op.name(), metalake, getErrorMsg(e));
+ LOG.warn(errorMsg, e);
+
+ if (e instanceof IllegalArgumentException) {
+ return Utils.illegalArguments(errorMsg, e);
+
+ } else if (e instanceof NotFoundException) {
+ return Utils.notFound(errorMsg, e);
+
+ } else if (e instanceof GroupAlreadyExistsException) {
+ return Utils.alreadyExists(errorMsg, e);
+
+ } else {
+ return super.handle(op, group, metalake, e);
+ }
+ }
+ }
+
private static class TopicExceptionHandler extends BaseExceptionHandler {
private static final ExceptionHandler INSTANCE = new TopicExceptionHandler();
diff --git a/server/src/main/java/com/datastrato/gravitino/server/web/rest/GroupOperations.java b/server/src/main/java/com/datastrato/gravitino/server/web/rest/GroupOperations.java
new file mode 100644
index 0000000000..692d7bf31c
--- /dev/null
+++ b/server/src/main/java/com/datastrato/gravitino/server/web/rest/GroupOperations.java
@@ -0,0 +1,124 @@
+/*
+ * Copyright 2024 Datastrato Pvt Ltd.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.gravitino.server.web.rest;
+
+import com.codahale.metrics.annotation.ResponseMetered;
+import com.codahale.metrics.annotation.Timed;
+import com.datastrato.gravitino.NameIdentifier;
+import com.datastrato.gravitino.authorization.AccessControlManager;
+import com.datastrato.gravitino.dto.requests.GroupAddRequest;
+import com.datastrato.gravitino.dto.responses.GroupResponse;
+import com.datastrato.gravitino.dto.responses.RemoveResponse;
+import com.datastrato.gravitino.dto.util.DTOConverters;
+import com.datastrato.gravitino.lock.LockType;
+import com.datastrato.gravitino.lock.TreeLockUtils;
+import com.datastrato.gravitino.meta.CatalogEntity;
+import com.datastrato.gravitino.meta.GroupEntity;
+import com.datastrato.gravitino.metrics.MetricNames;
+import com.datastrato.gravitino.server.web.Utils;
+import javax.inject.Inject;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.DELETE;
+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;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.Response;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Path("/metalakes/{metalake}/groups")
+public class GroupOperations {
+
+ private static final Logger LOG = LoggerFactory.getLogger(GroupOperations.class);
+
+ private final AccessControlManager accessControlManager;
+
+ @Context private HttpServletRequest httpRequest;
+
+ @Inject
+ public GroupOperations(AccessControlManager accessControlManager) {
+ this.accessControlManager = accessControlManager;
+ }
+
+ @GET
+ @Path("{group}")
+ @Produces("application/vnd.gravitino.v1+json")
+ @Timed(name = "get-group." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)
+ @ResponseMetered(name = "get-group", absolute = true)
+ public Response getGroup(
+ @PathParam("metalake") String metalake, @PathParam("group") String group) {
+ try {
+ NameIdentifier ident = ofGroup(metalake, group);
+ return Utils.doAs(
+ httpRequest,
+ () ->
+ Utils.ok(
+ new GroupResponse(
+ DTOConverters.toDTO(
+ TreeLockUtils.doWithTreeLock(
+ ident,
+ LockType.READ,
+ () -> accessControlManager.getGroup(metalake, group))))));
+ } catch (Exception e) {
+ return ExceptionHandlers.handleGroupException(OperationType.GET, group, metalake, e);
+ }
+ }
+
+ @POST
+ @Produces("application/vnd.gravitino.v1+json")
+ @Timed(name = "add-group." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)
+ @ResponseMetered(name = "add-group", absolute = true)
+ public Response addGroup(@PathParam("metalake") String metalake, GroupAddRequest request) {
+ try {
+ NameIdentifier ident = ofGroup(metalake, request.getName());
+ return Utils.doAs(
+ httpRequest,
+ () ->
+ Utils.ok(
+ new GroupResponse(
+ DTOConverters.toDTO(
+ TreeLockUtils.doWithTreeLock(
+ ident,
+ LockType.WRITE,
+ () -> accessControlManager.addGroup(metalake, request.getName()))))));
+ } catch (Exception e) {
+ return ExceptionHandlers.handleGroupException(
+ OperationType.ADD, request.getName(), metalake, e);
+ }
+ }
+
+ @DELETE
+ @Path("{group}")
+ @Produces("application/vnd.gravitino.v1+json")
+ @Timed(name = "remove-group." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)
+ @ResponseMetered(name = "remove-group", absolute = true)
+ public Response removeGroup(
+ @PathParam("metalake") String metalake, @PathParam("group") String group) {
+ try {
+ return Utils.doAs(
+ httpRequest,
+ () -> {
+ NameIdentifier ident = ofGroup(metalake, group);
+ boolean removed =
+ TreeLockUtils.doWithTreeLock(
+ ident, LockType.WRITE, () -> accessControlManager.removeGroup(metalake, group));
+ if (!removed) {
+ LOG.warn("Failed to remove group {} under metalake {}", group, metalake);
+ }
+ return Utils.ok(new RemoveResponse(removed));
+ });
+ } catch (Exception e) {
+ return ExceptionHandlers.handleGroupException(OperationType.REMOVE, group, metalake, e);
+ }
+ }
+
+ private NameIdentifier ofGroup(String metalake, String group) {
+ return NameIdentifier.of(
+ metalake, CatalogEntity.SYSTEM_CATALOG_RESERVED_NAME, GroupEntity.GROUP_SCHEMA_NAME, group);
+ }
+}
diff --git a/server/src/test/java/com/datastrato/gravitino/server/web/rest/TestGroupOperations.java b/server/src/test/java/com/datastrato/gravitino/server/web/rest/TestGroupOperations.java
new file mode 100644
index 0000000000..d7d175236b
--- /dev/null
+++ b/server/src/test/java/com/datastrato/gravitino/server/web/rest/TestGroupOperations.java
@@ -0,0 +1,281 @@
+/*
+ * Copyright 2024 Datastrato Pvt Ltd.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.gravitino.server.web.rest;
+
+import static com.datastrato.gravitino.Configs.TREE_LOCK_CLEAN_INTERVAL;
+import static com.datastrato.gravitino.Configs.TREE_LOCK_MAX_NODE_IN_MEMORY;
+import static com.datastrato.gravitino.Configs.TREE_LOCK_MIN_NODE_IN_MEMORY;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import com.datastrato.gravitino.Config;
+import com.datastrato.gravitino.GravitinoEnv;
+import com.datastrato.gravitino.authorization.AccessControlManager;
+import com.datastrato.gravitino.authorization.Group;
+import com.datastrato.gravitino.dto.authorization.GroupDTO;
+import com.datastrato.gravitino.dto.requests.GroupAddRequest;
+import com.datastrato.gravitino.dto.responses.ErrorConstants;
+import com.datastrato.gravitino.dto.responses.ErrorResponse;
+import com.datastrato.gravitino.dto.responses.GroupResponse;
+import com.datastrato.gravitino.dto.responses.RemoveResponse;
+import com.datastrato.gravitino.exceptions.GroupAlreadyExistsException;
+import com.datastrato.gravitino.exceptions.NoSuchGroupException;
+import com.datastrato.gravitino.exceptions.NoSuchMetalakeException;
+import com.datastrato.gravitino.lock.LockManager;
+import com.datastrato.gravitino.meta.AuditInfo;
+import com.datastrato.gravitino.meta.GroupEntity;
+import com.datastrato.gravitino.rest.RESTUtils;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.client.Entity;
+import javax.ws.rs.core.Application;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import org.glassfish.hk2.utilities.binding.AbstractBinder;
+import org.glassfish.jersey.server.ResourceConfig;
+import org.glassfish.jersey.test.JerseyTest;
+import org.glassfish.jersey.test.TestProperties;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+
+public class TestGroupOperations extends JerseyTest {
+
+ private final AccessControlManager manager = mock(AccessControlManager.class);
+
+ private static class MockServletRequestFactory extends ServletRequestFactoryBase {
+ @Override
+ public HttpServletRequest get() {
+ HttpServletRequest request = mock(HttpServletRequest.class);
+ when(request.getRemoteUser()).thenReturn(null);
+ return request;
+ }
+ }
+
+ @BeforeAll
+ public static void setup() {
+ Config config = mock(Config.class);
+ Mockito.doReturn(100000L).when(config).get(TREE_LOCK_MAX_NODE_IN_MEMORY);
+ Mockito.doReturn(1000L).when(config).get(TREE_LOCK_MIN_NODE_IN_MEMORY);
+ Mockito.doReturn(36000L).when(config).get(TREE_LOCK_CLEAN_INTERVAL);
+ GravitinoEnv.getInstance().setLockManager(new LockManager(config));
+ }
+
+ @Override
+ protected Application configure() {
+ try {
+ forceSet(
+ TestProperties.CONTAINER_PORT, String.valueOf(RESTUtils.findAvailablePort(2000, 3000)));
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+
+ ResourceConfig resourceConfig = new ResourceConfig();
+ resourceConfig.register(GroupOperations.class);
+ resourceConfig.register(
+ new AbstractBinder() {
+ @Override
+ protected void configure() {
+ bind(manager).to(AccessControlManager.class).ranked(2);
+ bindFactory(MockServletRequestFactory.class).to(HttpServletRequest.class);
+ }
+ });
+
+ return resourceConfig;
+ }
+
+ @Test
+ public void testAddGroup() {
+ GroupAddRequest req = new GroupAddRequest("group1");
+ Group group = buildGroup("group1");
+
+ when(manager.addGroup(any(), any())).thenReturn(group);
+
+ Response resp =
+ target("/metalakes/metalake1/groups")
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept("application/vnd.gravitino.v1+json")
+ .post(Entity.entity(req, MediaType.APPLICATION_JSON_TYPE));
+
+ Assertions.assertEquals(Response.Status.OK.getStatusCode(), resp.getStatus());
+ Assertions.assertEquals(MediaType.APPLICATION_JSON_TYPE, resp.getMediaType());
+
+ GroupResponse groupResponse = resp.readEntity(GroupResponse.class);
+ Assertions.assertEquals(0, groupResponse.getCode());
+
+ GroupDTO groupDTO = groupResponse.getGroup();
+ Assertions.assertEquals("group1", groupDTO.name());
+ Assertions.assertNotNull(groupDTO.roles());
+ Assertions.assertTrue(groupDTO.roles().isEmpty());
+
+ // Test to throw NoSuchMetalakeException
+ doThrow(new NoSuchMetalakeException("mock error")).when(manager).addGroup(any(), any());
+ Response resp1 =
+ target("/metalakes/metalake1/groups")
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept("application/vnd.gravitino.v1+json")
+ .post(Entity.entity(req, MediaType.APPLICATION_JSON_TYPE));
+
+ Assertions.assertEquals(Response.Status.NOT_FOUND.getStatusCode(), resp1.getStatus());
+ Assertions.assertEquals(MediaType.APPLICATION_JSON_TYPE, resp1.getMediaType());
+
+ ErrorResponse errorResponse = resp1.readEntity(ErrorResponse.class);
+ Assertions.assertEquals(ErrorConstants.NOT_FOUND_CODE, errorResponse.getCode());
+ Assertions.assertEquals(NoSuchMetalakeException.class.getSimpleName(), errorResponse.getType());
+
+ // Test to throw GroupAlreadyExistsException
+ doThrow(new GroupAlreadyExistsException("mock error")).when(manager).addGroup(any(), any());
+ Response resp2 =
+ target("/metalakes/metalake1/groups")
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept("application/vnd.gravitino.v1+json")
+ .post(Entity.entity(req, MediaType.APPLICATION_JSON_TYPE));
+
+ Assertions.assertEquals(Response.Status.CONFLICT.getStatusCode(), resp2.getStatus());
+
+ ErrorResponse errorResponse1 = resp2.readEntity(ErrorResponse.class);
+ Assertions.assertEquals(ErrorConstants.ALREADY_EXISTS_CODE, errorResponse1.getCode());
+ Assertions.assertEquals(
+ GroupAlreadyExistsException.class.getSimpleName(), errorResponse1.getType());
+
+ // Test to throw internal RuntimeException
+ doThrow(new RuntimeException("mock error")).when(manager).addGroup(any(), any());
+ Response resp3 =
+ target("/metalakes/metalake1/groups")
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept("application/vnd.gravitino.v1+json")
+ .post(Entity.entity(req, MediaType.APPLICATION_JSON_TYPE));
+
+ Assertions.assertEquals(
+ Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), resp3.getStatus());
+
+ ErrorResponse errorResponse2 = resp3.readEntity(ErrorResponse.class);
+ Assertions.assertEquals(ErrorConstants.INTERNAL_ERROR_CODE, errorResponse2.getCode());
+ Assertions.assertEquals(RuntimeException.class.getSimpleName(), errorResponse2.getType());
+ }
+
+ @Test
+ public void testGetGroup() {
+ Group group = buildGroup("group1");
+
+ when(manager.getGroup(any(), any())).thenReturn(group);
+
+ Response resp =
+ target("/metalakes/metalake1/groups/group1")
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept("application/vnd.gravitino.v1+json")
+ .get();
+
+ Assertions.assertEquals(Response.Status.OK.getStatusCode(), resp.getStatus());
+
+ GroupResponse groupResponse = resp.readEntity(GroupResponse.class);
+ Assertions.assertEquals(0, groupResponse.getCode());
+ GroupDTO groupDTO = groupResponse.getGroup();
+ Assertions.assertEquals("group1", groupDTO.name());
+ Assertions.assertNotNull(groupDTO.roles());
+ Assertions.assertTrue(groupDTO.roles().isEmpty());
+
+ // Test to throw NoSuchMetalakeException
+ doThrow(new NoSuchMetalakeException("mock error")).when(manager).getGroup(any(), any());
+ Response resp1 =
+ target("/metalakes/metalake1/groups/group1")
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept("application/vnd.gravitino.v1+json")
+ .get();
+
+ Assertions.assertEquals(Response.Status.NOT_FOUND.getStatusCode(), resp1.getStatus());
+
+ ErrorResponse errorResponse = resp1.readEntity(ErrorResponse.class);
+ Assertions.assertEquals(ErrorConstants.NOT_FOUND_CODE, errorResponse.getCode());
+ Assertions.assertEquals(NoSuchMetalakeException.class.getSimpleName(), errorResponse.getType());
+
+ // Test to throw NoSuchGroupException
+ doThrow(new NoSuchGroupException("mock error")).when(manager).getGroup(any(), any());
+ Response resp2 =
+ target("/metalakes/metalake1/groups/group1")
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept("application/vnd.gravitino.v1+json")
+ .get();
+
+ Assertions.assertEquals(Response.Status.NOT_FOUND.getStatusCode(), resp2.getStatus());
+
+ ErrorResponse errorResponse1 = resp2.readEntity(ErrorResponse.class);
+ Assertions.assertEquals(ErrorConstants.NOT_FOUND_CODE, errorResponse1.getCode());
+ Assertions.assertEquals(NoSuchGroupException.class.getSimpleName(), errorResponse1.getType());
+
+ // Test to throw internal RuntimeException
+ doThrow(new RuntimeException("mock error")).when(manager).getGroup(any(), any());
+ Response resp3 =
+ target("/metalakes/metalake1/groups/group1")
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept("application/vnd.gravitino.v1+json")
+ .get();
+
+ Assertions.assertEquals(
+ Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), resp3.getStatus());
+
+ ErrorResponse errorResponse2 = resp3.readEntity(ErrorResponse.class);
+ Assertions.assertEquals(ErrorConstants.INTERNAL_ERROR_CODE, errorResponse2.getCode());
+ Assertions.assertEquals(RuntimeException.class.getSimpleName(), errorResponse2.getType());
+ }
+
+ private Group buildGroup(String group) {
+ return GroupEntity.builder()
+ .withId(1L)
+ .withName(group)
+ .withRoles(Collections.emptyList())
+ .withAuditInfo(
+ AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build())
+ .build();
+ }
+
+ @Test
+ public void testRemoveGroup() {
+ when(manager.removeGroup(any(), any())).thenReturn(true);
+
+ Response resp =
+ target("/metalakes/metalake1/groups/group1")
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept("application/vnd.gravitino.v1+json")
+ .delete();
+
+ Assertions.assertEquals(Response.Status.OK.getStatusCode(), resp.getStatus());
+ RemoveResponse removeResponse = resp.readEntity(RemoveResponse.class);
+ Assertions.assertEquals(0, removeResponse.getCode());
+ Assertions.assertTrue(removeResponse.removed());
+
+ // Test when failed to remove group
+ when(manager.removeGroup(any(), any())).thenReturn(false);
+ Response resp2 =
+ target("/metalakes/metalake1/groups/group1")
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept("application/vnd.gravitino.v1+json")
+ .delete();
+
+ Assertions.assertEquals(Response.Status.OK.getStatusCode(), resp2.getStatus());
+ RemoveResponse removeResponse2 = resp2.readEntity(RemoveResponse.class);
+ Assertions.assertEquals(0, removeResponse2.getCode());
+ Assertions.assertFalse(removeResponse2.removed());
+
+ doThrow(new RuntimeException("mock error")).when(manager).removeGroup(any(), any());
+ Response resp3 =
+ target("/metalakes/metalake1/groups/group1")
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept("application/vnd.gravitino.v1+json")
+ .delete();
+
+ Assertions.assertEquals(
+ Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), resp3.getStatus());
+
+ ErrorResponse errorResponse = resp3.readEntity(ErrorResponse.class);
+ Assertions.assertEquals(ErrorConstants.INTERNAL_ERROR_CODE, errorResponse.getCode());
+ Assertions.assertEquals(RuntimeException.class.getSimpleName(), errorResponse.getType());
+ }
+}