World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#2780] Improvement(server,core): Move tree lock from rest api to the corresponding implementation to minimize tree lock range. (#2873)
Qi Yu9f5f3ee2d164
diff --git a/core/src/main/java/org/apache/gravitino/authorization/AccessControlManager.java b/core/src/main/java/org/apache/gravitino/authorization/AccessControlManager.javaindex 2d756646b6..aa7476534e 100644--- a/core/src/main/java/org/apache/gravitino/authorization/AccessControlManager.java+++ b/core/src/main/java/org/apache/gravitino/authorization/AccessControlManager.java@@ -25,6 +25,7 @@ import org.apache.gravitino.Config;import org.apache.gravitino.Configs;import org.apache.gravitino.EntityStore;import org.apache.gravitino.MetadataObject;+import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.exceptions.GroupAlreadyExistsException;import org.apache.gravitino.exceptions.IllegalRoleException;import org.apache.gravitino.exceptions.NoSuchGroupException;@@ -34,7 +35,10 @@ import org.apache.gravitino.exceptions.NoSuchRoleException;import org.apache.gravitino.exceptions.NoSuchUserException;import org.apache.gravitino.exceptions.RoleAlreadyExistsException;import org.apache.gravitino.exceptions.UserAlreadyExistsException;+import org.apache.gravitino.lock.LockType;+import org.apache.gravitino.lock.TreeLockUtils;import org.apache.gravitino.storage.IdGenerator;+import org.apache.gravitino.utils.MetadataObjectUtil;/*** AccessControlManager is used for manage users, roles, grant information, this class is an@@ -57,78 +61,120 @@ public class AccessControlManager implements AccessControlDispatcher {@Overridepublic User addUser(String metalake, String user)throws UserAlreadyExistsException, NoSuchMetalakeException {- return userGroupManager.addUser(metalake, user);+ return TreeLockUtils.doWithTreeLock(+ NameIdentifier.of(AuthorizationUtils.ofUserNamespace(metalake).levels()),+ LockType.WRITE,+ () -> userGroupManager.addUser(metalake, user));}@Overridepublic boolean removeUser(String metalake, String user) throws NoSuchMetalakeException {- return userGroupManager.removeUser(metalake, user);+ return TreeLockUtils.doWithTreeLock(+ NameIdentifier.of(AuthorizationUtils.ofUserNamespace(metalake).levels()),+ LockType.WRITE,+ () -> userGroupManager.removeUser(metalake, user));}@Overridepublic User getUser(String metalake, String user)throws NoSuchUserException, NoSuchMetalakeException {- return userGroupManager.getUser(metalake, user);+ return TreeLockUtils.doWithTreeLock(+ AuthorizationUtils.ofUser(metalake, user),+ LockType.READ,+ () -> userGroupManager.getUser(metalake, user));}@Overridepublic String[] listUserNames(String metalake) throws NoSuchMetalakeException {- return userGroupManager.listUserNames(metalake);+ return TreeLockUtils.doWithTreeLock(+ NameIdentifier.of(AuthorizationUtils.ofUserNamespace(metalake).levels()),+ LockType.READ,+ () -> userGroupManager.listUserNames(metalake));}@Overridepublic User[] listUsers(String metalake) throws NoSuchMetalakeException {- return userGroupManager.listUsers(metalake);+ return TreeLockUtils.doWithTreeLock(+ NameIdentifier.of(AuthorizationUtils.ofUserNamespace(metalake).levels()),+ LockType.READ,+ () -> userGroupManager.listUsers(metalake));}public Group addGroup(String metalake, String group)throws GroupAlreadyExistsException, NoSuchMetalakeException {- return userGroupManager.addGroup(metalake, group);+ return TreeLockUtils.doWithTreeLock(+ NameIdentifier.of(AuthorizationUtils.ofGroupNamespace(metalake).levels()),+ LockType.WRITE,+ () -> userGroupManager.addGroup(metalake, group));}@Overridepublic boolean removeGroup(String metalake, String group) throws NoSuchMetalakeException {- return userGroupManager.removeGroup(metalake, group);+ return TreeLockUtils.doWithTreeLock(+ NameIdentifier.of(AuthorizationUtils.ofGroupNamespace(metalake).levels()),+ LockType.WRITE,+ () -> userGroupManager.removeGroup(metalake, group));}@Overridepublic Group getGroup(String metalake, String group)throws NoSuchGroupException, NoSuchMetalakeException {- return userGroupManager.getGroup(metalake, group);+ return TreeLockUtils.doWithTreeLock(+ AuthorizationUtils.ofGroup(metalake, group),+ LockType.READ,+ () -> userGroupManager.getGroup(metalake, group));}@Overridepublic Group[] listGroups(String metalake) throws NoSuchMetalakeException {- return userGroupManager.listGroups(metalake);+ return TreeLockUtils.doWithTreeLock(+ NameIdentifier.of(AuthorizationUtils.ofGroupNamespace(metalake).levels()),+ LockType.READ,+ () -> userGroupManager.listGroups(metalake));}@Overridepublic String[] listGroupNames(String metalake) throws NoSuchMetalakeException {- return userGroupManager.listGroupNames(metalake);+ return TreeLockUtils.doWithTreeLock(+ NameIdentifier.of(AuthorizationUtils.ofGroupNamespace(metalake).levels()),+ LockType.READ,+ () -> userGroupManager.listGroupNames(metalake));}@Overridepublic User grantRolesToUser(String metalake, List<String> roles, String user)throws NoSuchUserException, IllegalRoleException, NoSuchMetalakeException {- return permissionManager.grantRolesToUser(metalake, roles, user);+ return TreeLockUtils.doWithTreeLock(+ AuthorizationUtils.ofUser(metalake, user),+ LockType.WRITE,+ () -> permissionManager.grantRolesToUser(metalake, roles, user));}@Overridepublic Group grantRolesToGroup(String metalake, List<String> roles, String group)throws NoSuchGroupException, IllegalRoleException, NoSuchMetalakeException {- return permissionManager.grantRolesToGroup(metalake, roles, group);+ return TreeLockUtils.doWithTreeLock(+ AuthorizationUtils.ofGroup(metalake, group),+ LockType.WRITE,+ () -> permissionManager.grantRolesToGroup(metalake, roles, group));}@Overridepublic Group revokeRolesFromGroup(String metalake, List<String> roles, String group)throws NoSuchGroupException, IllegalRoleException, NoSuchMetalakeException {- return permissionManager.revokeRolesFromGroup(metalake, roles, group);+ return TreeLockUtils.doWithTreeLock(+ AuthorizationUtils.ofGroup(metalake, group),+ LockType.WRITE,+ () -> permissionManager.revokeRolesFromGroup(metalake, roles, group));}@Overridepublic User revokeRolesFromUser(String metalake, List<String> roles, String user)throws NoSuchUserException, IllegalRoleException, NoSuchMetalakeException {- return permissionManager.revokeRolesFromUser(metalake, roles, user);+ return TreeLockUtils.doWithTreeLock(+ AuthorizationUtils.ofUser(metalake, user),+ LockType.WRITE,+ () -> permissionManager.revokeRolesFromUser(metalake, roles, user));}@Override@@ -143,42 +189,62 @@ public class AccessControlManager implements AccessControlDispatcher {Map<String, String> properties,List<SecurableObject> securableObjects)throws RoleAlreadyExistsException, NoSuchMetalakeException {- return roleManager.createRole(metalake, role, properties, securableObjects);+ return TreeLockUtils.doWithTreeLock(+ NameIdentifier.of(AuthorizationUtils.ofRoleNamespace(metalake).levels()),+ LockType.WRITE,+ () -> roleManager.createRole(metalake, role, properties, securableObjects));}@Overridepublic Role getRole(String metalake, String role)throws NoSuchRoleException, NoSuchMetalakeException {- return roleManager.getRole(metalake, role);+ return TreeLockUtils.doWithTreeLock(+ AuthorizationUtils.ofRole(metalake, role),+ LockType.READ,+ () -> roleManager.getRole(metalake, role));}@Overridepublic boolean deleteRole(String metalake, String role) throws NoSuchMetalakeException {- return roleManager.deleteRole(metalake, role);+ return TreeLockUtils.doWithTreeLock(+ NameIdentifier.of(AuthorizationUtils.ofRoleNamespace(metalake).levels()),+ LockType.WRITE,+ () -> roleManager.deleteRole(metalake, role));}@Overridepublic String[] listRoleNames(String metalake) throws NoSuchMetalakeException {- return roleManager.listRoleNames(metalake);+ return TreeLockUtils.doWithTreeLock(+ NameIdentifier.of(AuthorizationUtils.ofRoleNamespace(metalake).levels()),+ LockType.READ,+ () -> roleManager.listRoleNames(metalake));}@Overridepublic String[] listRoleNamesByObject(String metalake, MetadataObject object)throws NoSuchMetalakeException, NoSuchMetadataObjectException {- return roleManager.listRoleNamesByObject(metalake, object);+ NameIdentifier identifier = MetadataObjectUtil.toEntityIdent(metalake, object);+ return TreeLockUtils.doWithTreeLock(+ identifier, LockType.READ, () -> roleManager.listRoleNamesByObject(metalake, object));}@Overridepublic Role grantPrivilegeToRole(String metalake, String role, MetadataObject object, Set<Privilege> privileges)throws NoSuchRoleException, NoSuchMetalakeException {- return permissionManager.grantPrivilegesToRole(metalake, role, object, privileges);+ return TreeLockUtils.doWithTreeLock(+ AuthorizationUtils.ofRole(metalake, role),+ LockType.WRITE,+ () -> permissionManager.grantPrivilegesToRole(metalake, role, object, privileges));}@Overridepublic Role revokePrivilegesFromRole(String metalake, String role, MetadataObject object, Set<Privilege> privileges)throws NoSuchRoleException, NoSuchMetalakeException {- return permissionManager.revokePrivilegesFromRole(metalake, role, object, privileges);+ return TreeLockUtils.doWithTreeLock(+ AuthorizationUtils.ofRole(metalake, role),+ LockType.WRITE,+ () -> permissionManager.revokePrivilegesFromRole(metalake, role, object, privileges));}}diff --git a/core/src/main/java/org/apache/gravitino/authorization/OwnerManager.java b/core/src/main/java/org/apache/gravitino/authorization/OwnerManager.javaindex fa4e678654..b6c44f4ac3 100644--- a/core/src/main/java/org/apache/gravitino/authorization/OwnerManager.java+++ b/core/src/main/java/org/apache/gravitino/authorization/OwnerManager.java@@ -60,12 +60,12 @@ public class OwnerManager {public void setOwner(String metalake, MetadataObject metadataObject, String ownerName, Owner.Type ownerType) {++ NameIdentifier objectIdent = MetadataObjectUtil.toEntityIdent(metalake, metadataObject);try {Optional<Owner> originOwner = getOwner(metalake, metadataObject);- NameIdentifier objectIdent = MetadataObjectUtil.toEntityIdent(metalake, metadataObject);OwnerImpl newOwner = new OwnerImpl();-if (ownerType == Owner.Type.USER) {NameIdentifier ownerIdent = AuthorizationUtils.ofUser(metalake, ownerName);TreeLockUtils.doWithTreeLock(@@ -129,16 +129,20 @@ public class OwnerManager {}public Optional<Owner> getOwner(String metalake, MetadataObject metadataObject) {+ NameIdentifier ident = MetadataObjectUtil.toEntityIdent(metalake, metadataObject);+ OwnerImpl owner = new OwnerImpl();try {- OwnerImpl owner = new OwnerImpl();- NameIdentifier ident = MetadataObjectUtil.toEntityIdent(metalake, metadataObject);List<? extends Entity> entities =- store- .relationOperations()- .listEntitiesByRelation(- SupportsRelationOperations.Type.OWNER_REL,- ident,- MetadataObjectUtil.toEntityType(metadataObject));+ TreeLockUtils.doWithTreeLock(+ ident,+ LockType.READ,+ () ->+ store+ .relationOperations()+ .listEntitiesByRelation(+ SupportsRelationOperations.Type.OWNER_REL,+ ident,+ MetadataObjectUtil.toEntityType(metadataObject)));if (entities.isEmpty()) {return Optional.empty();diff --git a/core/src/main/java/org/apache/gravitino/authorization/PermissionManager.java b/core/src/main/java/org/apache/gravitino/authorization/PermissionManager.javaindex 1046723d70..60fac44fd8 100644--- a/core/src/main/java/org/apache/gravitino/authorization/PermissionManager.java+++ b/core/src/main/java/org/apache/gravitino/authorization/PermissionManager.java@@ -39,6 +39,8 @@ import org.apache.gravitino.exceptions.NoSuchEntityException;import org.apache.gravitino.exceptions.NoSuchGroupException;import org.apache.gravitino.exceptions.NoSuchRoleException;import org.apache.gravitino.exceptions.NoSuchUserException;+import org.apache.gravitino.lock.LockType;+import org.apache.gravitino.lock.TreeLockUtils;import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.meta.GroupEntity;import org.apache.gravitino.meta.RoleEntity;@@ -67,7 +69,10 @@ class PermissionManager {try {List<RoleEntity> roleEntitiesToGrant = Lists.newArrayList();for (String role : roles) {- roleEntitiesToGrant.add(roleManager.getRole(metalake, role));+ TreeLockUtils.doWithTreeLock(+ AuthorizationUtils.ofRole(metalake, role),+ LockType.READ,+ () -> roleEntitiesToGrant.add(roleManager.getRole(metalake, role)));}User updatedUser =@@ -153,7 +158,10 @@ class PermissionManager {try {List<RoleEntity> roleEntitiesToGrant = Lists.newArrayList();for (String role : roles) {- roleEntitiesToGrant.add(roleManager.getRole(metalake, role));+ TreeLockUtils.doWithTreeLock(+ AuthorizationUtils.ofRole(metalake, role),+ LockType.READ,+ () -> roleEntitiesToGrant.add(roleManager.getRole(metalake, role)));}Group updatedGroup =@@ -239,7 +247,10 @@ class PermissionManager {try {List<RoleEntity> roleEntitiesToRevoke = Lists.newArrayList();for (String role : roles) {- roleEntitiesToRevoke.add(roleManager.getRole(metalake, role));+ TreeLockUtils.doWithTreeLock(+ AuthorizationUtils.ofRole(metalake, role),+ LockType.READ,+ () -> roleEntitiesToRevoke.add(roleManager.getRole(metalake, role)));}Group updatedGroup =@@ -325,7 +336,10 @@ class PermissionManager {try {List<RoleEntity> roleEntitiesToRevoke = Lists.newArrayList();for (String role : roles) {- roleEntitiesToRevoke.add(roleManager.getRole(metalake, role));+ TreeLockUtils.doWithTreeLock(+ AuthorizationUtils.ofRole(metalake, role),+ LockType.READ,+ () -> roleEntitiesToRevoke.add(roleManager.getRole(metalake, role)));}User updatedUser =diff --git a/core/src/main/java/org/apache/gravitino/catalog/CatalogManager.java b/core/src/main/java/org/apache/gravitino/catalog/CatalogManager.javaindex a3d55d4a72..7c1722c1ce 100644--- a/core/src/main/java/org/apache/gravitino/catalog/CatalogManager.java+++ b/core/src/main/java/org/apache/gravitino/catalog/CatalogManager.java@@ -91,6 +91,8 @@ import org.apache.gravitino.exceptions.NoSuchMetalakeException;import org.apache.gravitino.exceptions.NonEmptyCatalogException;import org.apache.gravitino.exceptions.NonEmptyEntityException;import org.apache.gravitino.file.FilesetCatalog;+import org.apache.gravitino.lock.LockType;+import org.apache.gravitino.lock.TreeLockUtils;import org.apache.gravitino.messaging.TopicCatalog;import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.meta.CatalogEntity;@@ -317,32 +319,39 @@ public class CatalogManager implements CatalogDispatcher, Closeable {@Overridepublic NameIdentifier[] listCatalogs(Namespace namespace) throws NoSuchMetalakeException {NameIdentifier metalakeIdent = NameIdentifier.of(namespace.levels());- checkMetalake(NameIdentifier.of(namespace.level(0)), store);- try {- return store.list(namespace, CatalogEntity.class, EntityType.CATALOG).stream()- .map(entity -> NameIdentifier.of(namespace, entity.name()))- .toArray(NameIdentifier[]::new);-- } catch (IOException ioe) {- LOG.error("Failed to list catalogs in metalake {}", metalakeIdent, ioe);- throw new RuntimeException(ioe);- }+ return TreeLockUtils.doWithTreeLock(+ metalakeIdent,+ LockType.READ,+ () -> {+ checkMetalake(metalakeIdent, store);+ try {+ return store.list(namespace, CatalogEntity.class, EntityType.CATALOG).stream()+ .map(entity -> NameIdentifier.of(namespace, entity.name()))+ .toArray(NameIdentifier[]::new);++ } catch (IOException ioe) {+ LOG.error("Failed to list catalogs in metalake {}", metalakeIdent, ioe);+ throw new RuntimeException(ioe);+ }+ });}@Overridepublic Catalog[] listCatalogsInfo(Namespace namespace) throws NoSuchMetalakeException {NameIdentifier metalakeIdent = NameIdentifier.of(namespace.levels());- checkMetalake(metalakeIdent, store);-try {List<CatalogEntity> catalogEntities =- store.list(namespace, CatalogEntity.class, EntityType.CATALOG);-+ TreeLockUtils.doWithTreeLock(+ metalakeIdent,+ LockType.READ,+ () -> {+ checkMetalake(metalakeIdent, store);+ return store.list(namespace, CatalogEntity.class, EntityType.CATALOG);+ });return catalogEntities.stream().map(e -> e.toCatalogInfoWithResolvedProps(getResolvedProperties(e))).toArray(Catalog[]::new);-} catch (IOException ioe) {LOG.error("Failed to list catalogs in metalake {}", metalakeIdent, ioe);throw new RuntimeException(ioe);@@ -359,9 +368,13 @@ public class CatalogManager implements CatalogDispatcher, Closeable {@Overridepublic Catalog loadCatalog(NameIdentifier ident) throws NoSuchCatalogException {NameIdentifier metalakeIdent = NameIdentifier.of(ident.namespace().levels());- checkMetalake(metalakeIdent, store);-- return loadCatalogAndWrap(ident).catalog;+ return TreeLockUtils.doWithTreeLock(+ ident,+ LockType.READ,+ () -> {+ checkMetalake(metalakeIdent, store);+ return loadCatalogAndWrap(ident).catalog;+ });}/**@@ -385,10 +398,8 @@ public class CatalogManager implements CatalogDispatcher, Closeable {Map<String, String> properties)throws NoSuchMetalakeException, CatalogAlreadyExistsException {NameIdentifier metalakeIdent = NameIdentifier.of(ident.namespace().levels());- checkMetalake(metalakeIdent, store);Map<String, String> mergedConfig = buildCatalogConf(provider, properties);-long uid = idGenerator.nextId();StringIdentifier stringId = StringIdentifier.fromId(uid);Instant now = Instant.now();@@ -411,41 +422,49 @@ public class CatalogManager implements CatalogDispatcher, Closeable {.build()).build();- boolean needClean = true;- try {- store.put(e, false /* overwrite */);- CatalogWrapper wrapper = catalogCache.get(ident, id -> createCatalogWrapper(e, mergedConfig));-- needClean = false;- return wrapper.catalog;-- } catch (EntityAlreadyExistsException e1) {- needClean = false;- LOG.warn("Catalog {} already exists", ident, e1);- throw new CatalogAlreadyExistsException("Catalog %s already exists", ident);-- } catch (IllegalArgumentException | NoSuchMetalakeException e2) {- throw e2;+ return TreeLockUtils.doWithTreeLock(+ metalakeIdent,+ LockType.WRITE,+ () -> {+ checkMetalake(metalakeIdent, store);+ boolean needClean = true;+ try {+ store.put(e, false /* overwrite */);+ CatalogWrapper wrapper =+ catalogCache.get(ident, id -> createCatalogWrapper(e, mergedConfig));++ needClean = false;+ return wrapper.catalog;++ } catch (EntityAlreadyExistsException e1) {+ needClean = false;+ LOG.warn("Catalog {} already exists", ident, e1);+ throw new CatalogAlreadyExistsException("Catalog %s already exists", ident);++ } catch (IllegalArgumentException | NoSuchMetalakeException e2) {+ throw e2;++ } catch (Exception e3) {+ catalogCache.invalidate(ident);+ LOG.error("Failed to create catalog {}", ident, e3);+ if (e3 instanceof RuntimeException) {+ throw (RuntimeException) e3;+ }+ throw new RuntimeException(e3);- } catch (Exception e3) {- catalogCache.invalidate(ident);- LOG.error("Failed to create catalog {}", ident, e3);- if (e3 instanceof RuntimeException) {- throw (RuntimeException) e3;- }- throw new RuntimeException(e3);-- } finally {- if (needClean) {- // since we put the catalog entity into the store but failed to create the catalog instance,- // we need to clean up the entity stored.- try {- store.delete(ident, EntityType.CATALOG, true);- } catch (IOException e4) {- LOG.error("Failed to clean up catalog {}", ident, e4);- }- }- }+ } finally {+ if (needClean) {+ // since we put the catalog entity into the store but failed to create the catalog+ // instance,+ // we need to clean up the entity stored.+ try {+ store.delete(ident, EntityType.CATALOG, true);+ } catch (IOException e4) {+ LOG.error("Failed to clean up catalog {}", ident, e4);+ }+ }+ }+ });}/**@@ -466,8 +485,8 @@ public class CatalogManager implements CatalogDispatcher, Closeable {String comment,Map<String, String> properties) {NameIdentifier metalakeIdent = NameIdentifier.of(ident.namespace().levels());- checkMetalake(metalakeIdent, store);+ checkMetalake(metalakeIdent, store);try {if (store.exists(ident, EntityType.CATALOG)) {throw new CatalogAlreadyExistsException("Catalog %s already exists", ident);@@ -515,66 +534,80 @@ public class CatalogManager implements CatalogDispatcher, Closeable {public void enableCatalog(NameIdentifier ident)throws NoSuchCatalogException, CatalogNotInUseException {NameIdentifier metalakeIdent = NameIdentifier.of(ident.namespace().levels());- checkMetalake(metalakeIdent, store);- try {- if (catalogInUse(store, ident)) {- return;- }+ TreeLockUtils.doWithTreeLock(+ metalakeIdent,+ LockType.WRITE,+ () -> {+ checkMetalake(metalakeIdent, store);- store.update(- ident,- CatalogEntity.class,- EntityType.CATALOG,- catalog -> {- CatalogEntity.Builder newCatalogBuilder = newCatalogBuilder(ident.namespace(), catalog);-- Map<String, String> newProps =- catalog.getProperties() == null- ? new HashMap<>()- : new HashMap<>(catalog.getProperties());- newProps.put(PROPERTY_IN_USE, "true");- newCatalogBuilder.withProperties(newProps);-- return newCatalogBuilder.build();- });- catalogCache.invalidate(ident);+ try {+ if (catalogInUse(store, ident)) {+ return null;+ }- } catch (IOException e) {- throw new RuntimeException(e);- }+ store.update(+ ident,+ CatalogEntity.class,+ EntityType.CATALOG,+ catalog -> {+ CatalogEntity.Builder newCatalogBuilder =+ newCatalogBuilder(ident.namespace(), catalog);++ Map<String, String> newProps =+ catalog.getProperties() == null+ ? new HashMap<>()+ : new HashMap<>(catalog.getProperties());+ newProps.put(PROPERTY_IN_USE, "true");+ newCatalogBuilder.withProperties(newProps);++ return newCatalogBuilder.build();+ });+ catalogCache.invalidate(ident);+ return null;+ } catch (IOException e) {+ throw new RuntimeException(e);+ }+ });}@Overridepublic void disableCatalog(NameIdentifier ident) throws NoSuchCatalogException {NameIdentifier metalakeIdent = NameIdentifier.of(ident.namespace().levels());- checkMetalake(metalakeIdent, store);- try {- if (!catalogInUse(store, ident)) {- return;- }- store.update(- ident,- CatalogEntity.class,- EntityType.CATALOG,- catalog -> {- CatalogEntity.Builder newCatalogBuilder = newCatalogBuilder(ident.namespace(), catalog);-- Map<String, String> newProps =- catalog.getProperties() == null- ? new HashMap<>()- : new HashMap<>(catalog.getProperties());- newProps.put(PROPERTY_IN_USE, "false");- newCatalogBuilder.withProperties(newProps);-- return newCatalogBuilder.build();- });- catalogCache.invalidate(ident);+ TreeLockUtils.doWithTreeLock(+ metalakeIdent,+ LockType.WRITE,+ () -> {+ checkMetalake(metalakeIdent, store);- } catch (IOException e) {- throw new RuntimeException(e);- }+ try {+ if (!catalogInUse(store, ident)) {+ return null;+ }+ store.update(+ ident,+ CatalogEntity.class,+ EntityType.CATALOG,+ catalog -> {+ CatalogEntity.Builder newCatalogBuilder =+ newCatalogBuilder(ident.namespace(), catalog);++ Map<String, String> newProps =+ catalog.getProperties() == null+ ? new HashMap<>()+ : new HashMap<>(catalog.getProperties());+ newProps.put(PROPERTY_IN_USE, "false");+ newCatalogBuilder.withProperties(newProps);++ return newCatalogBuilder.build();+ });+ catalogCache.invalidate(ident);+ return null;+ } catch (IOException e) {+ throw new RuntimeException(e);+ }+ });}/**@@ -589,124 +622,148 @@ public class CatalogManager implements CatalogDispatcher, Closeable {@Overridepublic Catalog alterCatalog(NameIdentifier ident, CatalogChange... changes)throws NoSuchCatalogException, IllegalArgumentException {- checkCatalogInUse(store, ident);-- // There could be a race issue that someone is using the catalog from cache while we are- // updating it.-- CatalogWrapper catalogWrapper = loadCatalogAndWrap(ident);- if (catalogWrapper == null) {- throw new NoSuchCatalogException(CATALOG_DOES_NOT_EXIST_MSG, ident);- }-- try {- catalogWrapper.doWithPropertiesMeta(- f -> {- Pair<Map<String, String>, Map<String, String>> alterProperty =- getCatalogAlterProperty(changes);- validatePropertyForAlter(- f.catalogPropertiesMetadata(), alterProperty.getLeft(), alterProperty.getRight());- return null;- });- } catch (IllegalArgumentException e1) {- throw e1;- } catch (Exception e) {- LOG.error("Failed to alter catalog {}", ident, e);- throw new RuntimeException(e);- }-- catalogCache.invalidate(ident);- try {- CatalogEntity updatedCatalog =- store.update(- ident,- CatalogEntity.class,- EntityType.CATALOG,- catalog -> {- CatalogEntity.Builder newCatalogBuilder =- newCatalogBuilder(ident.namespace(), catalog);-- Map<String, String> newProps =- catalog.getProperties() == null- ? new HashMap<>()- : new HashMap<>(catalog.getProperties());- newCatalogBuilder = updateEntity(newCatalogBuilder, newProps, changes);-- return newCatalogBuilder.build();- });- return Objects.requireNonNull(- catalogCache.get(- updatedCatalog.nameIdentifier(),- id -> createCatalogWrapper(updatedCatalog, null)))- .catalog;-- } catch (NoSuchEntityException ne) {- LOG.warn("Catalog {} does not exist", ident, ne);- throw new NoSuchCatalogException(CATALOG_DOES_NOT_EXIST_MSG, ident);-- } catch (IllegalArgumentException iae) {- LOG.warn("Failed to alter catalog {} with unknown change", ident, iae);- throw iae;-- } catch (IOException ioe) {- LOG.error("Failed to alter catalog {}", ident, ioe);- throw new RuntimeException(ioe);- }+ TreeLockUtils.doWithTreeLock(+ ident,+ LockType.READ,+ () -> {+ checkCatalogInUse(store, ident);++ // There could be a race issue that someone is using the catalog from cache while we are+ // updating it.++ CatalogWrapper catalogWrapper = loadCatalogAndWrap(ident);+ if (catalogWrapper == null) {+ throw new NoSuchCatalogException(CATALOG_DOES_NOT_EXIST_MSG, ident);+ }++ try {+ catalogWrapper.doWithPropertiesMeta(+ f -> {+ Pair<Map<String, String>, Map<String, String>> alterProperty =+ getCatalogAlterProperty(changes);+ validatePropertyForAlter(+ f.catalogPropertiesMetadata(),+ alterProperty.getLeft(),+ alterProperty.getRight());+ return null;+ });+ } catch (IllegalArgumentException e1) {+ throw e1;+ } catch (Exception e) {+ LOG.error("Failed to alter catalog {}", ident, e);+ throw new RuntimeException(e);+ }+ return null;+ });++ boolean containsRenameCatalog =+ Arrays.stream(changes).anyMatch(c -> c instanceof CatalogChange.RenameCatalog);+ NameIdentifier nameIdentifierForLock =+ containsRenameCatalog ? NameIdentifier.of(ident.namespace().level(0)) : ident;++ return TreeLockUtils.doWithTreeLock(+ nameIdentifierForLock,+ LockType.WRITE,+ () -> {+ catalogCache.invalidate(ident);+ try {+ CatalogEntity updatedCatalog =+ store.update(+ ident,+ CatalogEntity.class,+ EntityType.CATALOG,+ catalog -> {+ CatalogEntity.Builder newCatalogBuilder =+ newCatalogBuilder(ident.namespace(), catalog);++ Map<String, String> newProps =+ catalog.getProperties() == null+ ? new HashMap<>()+ : new HashMap<>(catalog.getProperties());+ newCatalogBuilder = updateEntity(newCatalogBuilder, newProps, changes);++ return newCatalogBuilder.build();+ });+ return Objects.requireNonNull(+ catalogCache.get(+ updatedCatalog.nameIdentifier(),+ id -> createCatalogWrapper(updatedCatalog, null)))+ .catalog;++ } catch (NoSuchEntityException ne) {+ LOG.warn("Catalog {} does not exist", ident, ne);+ throw new NoSuchCatalogException(CATALOG_DOES_NOT_EXIST_MSG, ident);++ } catch (IllegalArgumentException iae) {+ LOG.warn("Failed to alter catalog {} with unknown change", ident, iae);+ throw iae;++ } catch (IOException ioe) {+ LOG.error("Failed to alter catalog {}", ident, ioe);+ throw new RuntimeException(ioe);+ }+ });}@Overridepublic boolean dropCatalog(NameIdentifier ident, boolean force)throws NonEmptyEntityException, CatalogInUseException {NameIdentifier metalakeIdent = NameIdentifier.of(ident.namespace().levels());- checkMetalake(metalakeIdent, store);-- try {- boolean catalogInUse = catalogInUse(store, ident);- if (catalogInUse && !force) {- throw new CatalogInUseException(- "Catalog %s is in use, please disable it first or use force option", ident);- }- Namespace schemaNamespace = Namespace.of(ident.namespace().level(0), ident.name());- CatalogWrapper catalogWrapper = loadCatalogAndWrap(ident);+ return TreeLockUtils.doWithTreeLock(+ metalakeIdent,+ LockType.WRITE,+ () -> {+ checkMetalake(metalakeIdent, store);+ try {+ boolean catalogInUse = catalogInUse(store, ident);+ if (catalogInUse && !force) {+ throw new CatalogInUseException(+ "Catalog %s is in use, please disable it first or use force option", ident);+ }- List<SchemaEntity> schemaEntities =- store.list(schemaNamespace, SchemaEntity.class, EntityType.SCHEMA);- CatalogEntity catalogEntity = store.get(ident, EntityType.CATALOG, CatalogEntity.class);+ Namespace schemaNamespace = Namespace.of(ident.namespace().level(0), ident.name());+ CatalogWrapper catalogWrapper = loadCatalogAndWrap(ident);- if (containsUserCreatedSchemas(schemaEntities, catalogEntity, catalogWrapper) && !force) {- throw new NonEmptyCatalogException(- "Catalog %s has schemas, please drop them first or use force option", ident);- }+ List<SchemaEntity> schemaEntities =+ store.list(schemaNamespace, SchemaEntity.class, EntityType.SCHEMA);+ CatalogEntity catalogEntity = store.get(ident, EntityType.CATALOG, CatalogEntity.class);- if (includeManagedEntities(catalogEntity)) {- // code reach here in two cases:- // 1. the catalog does not have available schemas- // 2. the catalog has available schemas, and force is true- // for case 1, the forEach block can drop them without any side effect- // for case 2, the forEach block will drop all managed sub-entities- schemaEntities.forEach(- schema -> {- try {- catalogWrapper.doWithSchemaOps(- schemaOps -> schemaOps.dropSchema(schema.nameIdentifier(), true));- } catch (Exception e) {- LOG.warn("Failed to drop schema {}", schema.nameIdentifier());- throw new RuntimeException("Failed to drop schema " + schema.nameIdentifier(), e);- }- });- }- catalogCache.invalidate(ident);- return store.delete(ident, EntityType.CATALOG, true);-- } catch (NoSuchMetalakeException | NoSuchCatalogException ignored) {- return false;+ if (containsUserCreatedSchemas(schemaEntities, catalogEntity, catalogWrapper)+ && !force) {+ throw new NonEmptyCatalogException(+ "Catalog %s has schemas, please drop them first or use force option", ident);+ }- } catch (GravitinoRuntimeException e) {- throw e;- } catch (Exception e) {- throw new RuntimeException(e);- }+ if (includeManagedEntities(catalogEntity)) {+ // code reach here in two cases:+ // 1. the catalog does not have available schemas+ // 2. the catalog has available schemas, and force is true+ // for case 1, the forEach block can drop them without any side effect+ // for case 2, the forEach block will drop all managed sub-entities+ schemaEntities.forEach(+ schema -> {+ try {+ catalogWrapper.doWithSchemaOps(+ schemaOps -> schemaOps.dropSchema(schema.nameIdentifier(), true));+ } catch (Exception e) {+ LOG.warn("Failed to drop schema {}", schema.nameIdentifier());+ throw new RuntimeException(+ "Failed to drop schema " + schema.nameIdentifier(), e);+ }+ });+ }+ catalogCache.invalidate(ident);+ return store.delete(ident, EntityType.CATALOG, true);++ } catch (NoSuchMetalakeException | NoSuchCatalogException ignored) {+ return false;+ } catch (GravitinoRuntimeException e) {+ throw e;+ } catch (Exception e) {+ throw new RuntimeException(e);+ }+ });}/**diff --git a/core/src/main/java/org/apache/gravitino/catalog/FilesetOperationDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/FilesetOperationDispatcher.javaindex 828e981380..ff1e8b6adc 100644--- a/core/src/main/java/org/apache/gravitino/catalog/FilesetOperationDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/catalog/FilesetOperationDispatcher.java@@ -21,6 +21,7 @@ package org.apache.gravitino.catalog;import static org.apache.gravitino.catalog.PropertiesMetadataHelpers.validatePropertyForCreate;import static org.apache.gravitino.utils.NameIdentifierUtil.getCatalogIdentifier;+import java.util.Arrays;import java.util.Map;import org.apache.gravitino.EntityStore;import org.apache.gravitino.NameIdentifier;@@ -33,6 +34,8 @@ import org.apache.gravitino.exceptions.NoSuchSchemaException;import org.apache.gravitino.exceptions.NonEmptyEntityException;import org.apache.gravitino.file.Fileset;import org.apache.gravitino.file.FilesetChange;+import org.apache.gravitino.lock.LockType;+import org.apache.gravitino.lock.TreeLockUtils;import org.apache.gravitino.storage.IdGenerator;public class FilesetOperationDispatcher extends OperationDispatcher implements FilesetDispatcher {@@ -57,10 +60,14 @@ public class FilesetOperationDispatcher extends OperationDispatcher implements F*/@Overridepublic NameIdentifier[] listFilesets(Namespace namespace) throws NoSuchSchemaException {- return doWithCatalog(- getCatalogIdentifier(NameIdentifier.of(namespace.levels())),- c -> c.doWithFilesetOps(f -> f.listFilesets(namespace)),- NoSuchSchemaException.class);+ return TreeLockUtils.doWithTreeLock(+ NameIdentifier.of(namespace.levels()),+ LockType.READ,+ () ->+ doWithCatalog(+ getCatalogIdentifier(NameIdentifier.of(namespace.levels())),+ c -> c.doWithFilesetOps(f -> f.listFilesets(namespace)),+ NoSuchSchemaException.class));}/**@@ -74,11 +81,14 @@ public class FilesetOperationDispatcher extends OperationDispatcher implements Fpublic Fileset loadFileset(NameIdentifier ident) throws NoSuchFilesetException {NameIdentifier catalogIdent = getCatalogIdentifier(ident);Fileset fileset =- doWithCatalog(- catalogIdent,- c -> c.doWithFilesetOps(f -> f.loadFileset(ident)),- NoSuchFilesetException.class);-+ TreeLockUtils.doWithTreeLock(+ ident,+ LockType.READ,+ () ->+ doWithCatalog(+ catalogIdent,+ c -> c.doWithFilesetOps(f -> f.loadFileset(ident)),+ NoSuchFilesetException.class));// Currently we only support maintaining the Fileset in the Gravitino's store.return EntityCombinedFileset.of(fileset).withHiddenProperties(@@ -129,13 +139,19 @@ public class FilesetOperationDispatcher extends OperationDispatcher implements FStringIdentifier.newPropertiesWithId(stringId, properties);Fileset createdFileset =- doWithCatalog(- catalogIdent,- c ->- c.doWithFilesetOps(- f -> f.createFileset(ident, comment, type, storageLocation, updatedProperties)),- NoSuchSchemaException.class,- FilesetAlreadyExistsException.class);+ TreeLockUtils.doWithTreeLock(+ NameIdentifier.of(ident.namespace().levels()),+ LockType.WRITE,+ () ->+ doWithCatalog(+ catalogIdent,+ c ->+ c.doWithFilesetOps(+ f ->+ f.createFileset(+ ident, comment, type, storageLocation, updatedProperties)),+ NoSuchSchemaException.class,+ FilesetAlreadyExistsException.class));return EntityCombinedFileset.of(createdFileset).withHiddenProperties(getHiddenPropertyNames(@@ -163,14 +179,24 @@ public class FilesetOperationDispatcher extends OperationDispatcher implements Fpublic Fileset alterFileset(NameIdentifier ident, FilesetChange... changes)throws NoSuchFilesetException, IllegalArgumentException {validateAlterProperties(ident, HasPropertyMetadata::filesetPropertiesMetadata, changes);-NameIdentifier catalogIdent = getCatalogIdentifier(ident);++ boolean containsRenameFileset =+ Arrays.stream(changes).anyMatch(c -> c instanceof FilesetChange.RenameFileset);+ NameIdentifier nameIdentifierForLock =+ containsRenameFileset ? NameIdentifier.of(ident.namespace().levels()) : ident;+Fileset alteredFileset =- doWithCatalog(- catalogIdent,- c -> c.doWithFilesetOps(f -> f.alterFileset(ident, changes)),- NoSuchFilesetException.class,- IllegalArgumentException.class);+ TreeLockUtils.doWithTreeLock(+ nameIdentifierForLock,+ LockType.WRITE,+ () ->+ doWithCatalog(+ catalogIdent,+ c -> c.doWithFilesetOps(f -> f.alterFileset(ident, changes)),+ NoSuchFilesetException.class,+ IllegalArgumentException.class));+return EntityCombinedFileset.of(alteredFileset).withHiddenProperties(getHiddenPropertyNames(@@ -190,10 +216,14 @@ public class FilesetOperationDispatcher extends OperationDispatcher implements F*/@Overridepublic boolean dropFileset(NameIdentifier ident) {- return doWithCatalog(- getCatalogIdentifier(ident),- c -> c.doWithFilesetOps(f -> f.dropFileset(ident)),- NonEmptyEntityException.class);+ return TreeLockUtils.doWithTreeLock(+ NameIdentifier.of(ident.namespace().levels()),+ LockType.WRITE,+ () ->+ doWithCatalog(+ getCatalogIdentifier(ident),+ c -> c.doWithFilesetOps(f -> f.dropFileset(ident)),+ NonEmptyEntityException.class));}/**@@ -208,9 +238,13 @@ public class FilesetOperationDispatcher extends OperationDispatcher implements F@Overridepublic String getFileLocation(NameIdentifier ident, String subPath)throws NoSuchFilesetException {- return doWithCatalog(- getCatalogIdentifier(ident),- c -> c.doWithFilesetOps(f -> f.getFileLocation(ident, subPath)),- NonEmptyEntityException.class);+ return TreeLockUtils.doWithTreeLock(+ ident,+ LockType.READ,+ () ->+ doWithCatalog(+ getCatalogIdentifier(ident),+ c -> c.doWithFilesetOps(f -> f.getFileLocation(ident, subPath)),+ NonEmptyEntityException.class));}}diff --git a/core/src/main/java/org/apache/gravitino/catalog/PartitionOperationDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/PartitionOperationDispatcher.javaindex 5ff0696d51..37173b6293 100644--- a/core/src/main/java/org/apache/gravitino/catalog/PartitionOperationDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/catalog/PartitionOperationDispatcher.java@@ -23,6 +23,8 @@ import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.exceptions.NoSuchPartitionException;import org.apache.gravitino.exceptions.NoSuchTableException;import org.apache.gravitino.exceptions.PartitionAlreadyExistsException;+import org.apache.gravitino.lock.LockType;+import org.apache.gravitino.lock.TreeLockUtils;import org.apache.gravitino.rel.SupportsPartitions;import org.apache.gravitino.rel.partitions.Partition;import org.apache.gravitino.storage.IdGenerator;@@ -44,39 +46,64 @@ public class PartitionOperationDispatcher extends OperationDispatcher@Overridepublic String[] listPartitionNames(NameIdentifier tableIdent) {- return doWithTable(- tableIdent, SupportsPartitions::listPartitionNames, NoSuchTableException.class);+ return TreeLockUtils.doWithTreeLock(+ tableIdent,+ LockType.READ,+ () ->+ doWithTable(+ tableIdent, SupportsPartitions::listPartitionNames, NoSuchTableException.class));}@Overridepublic Partition[] listPartitions(NameIdentifier tableIdent) {- return doWithTable(tableIdent, SupportsPartitions::listPartitions, NoSuchTableException.class);+ return TreeLockUtils.doWithTreeLock(+ tableIdent,+ LockType.READ,+ () ->+ doWithTable(+ tableIdent, SupportsPartitions::listPartitions, NoSuchTableException.class));}@Overridepublic Partition getPartition(NameIdentifier tableIdent, String partitionName)throws NoSuchPartitionException {- return doWithTable(- tableIdent, p -> p.getPartition(partitionName), NoSuchPartitionException.class);+ return TreeLockUtils.doWithTreeLock(+ tableIdent,+ LockType.READ,+ () ->+ doWithTable(+ tableIdent, p -> p.getPartition(partitionName), NoSuchPartitionException.class));}@Overridepublic Partition addPartition(NameIdentifier tableIdent, Partition partition)throws PartitionAlreadyExistsException {- return doWithTable(- tableIdent, p -> p.addPartition(partition), PartitionAlreadyExistsException.class);+ return TreeLockUtils.doWithTreeLock(+ tableIdent,+ LockType.WRITE,+ () ->+ doWithTable(+ tableIdent, p -> p.addPartition(partition), PartitionAlreadyExistsException.class));}@Overridepublic boolean dropPartition(NameIdentifier tableIdent, String partitionName) {- return doWithTable(- tableIdent, p -> p.dropPartition(partitionName), NoSuchPartitionException.class);+ return TreeLockUtils.doWithTreeLock(+ tableIdent,+ LockType.WRITE,+ () ->+ doWithTable(+ tableIdent, p -> p.dropPartition(partitionName), NoSuchPartitionException.class));}@Overridepublic boolean purgePartition(NameIdentifier tableIdent, String partitionName)throws UnsupportedOperationException {- return doWithTable(- tableIdent, p -> p.purgePartition(partitionName), NoSuchPartitionException.class);+ return TreeLockUtils.doWithTreeLock(+ tableIdent,+ LockType.WRITE,+ () ->+ doWithTable(+ tableIdent, p -> p.purgePartition(partitionName), NoSuchPartitionException.class));}}diff --git a/core/src/main/java/org/apache/gravitino/catalog/SchemaOperationDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/SchemaOperationDispatcher.javaindex 8f36ce0d95..b9f382e46a 100644--- a/core/src/main/java/org/apache/gravitino/catalog/SchemaOperationDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/catalog/SchemaOperationDispatcher.java@@ -73,10 +73,14 @@ public class SchemaOperationDispatcher extends OperationDispatcher implements Sc*/@Overridepublic NameIdentifier[] listSchemas(Namespace namespace) throws NoSuchCatalogException {- return doWithCatalog(- getCatalogIdentifier(NameIdentifier.of(namespace.levels())),- c -> c.doWithSchemaOps(s -> s.listSchemas(namespace)),- NoSuchCatalogException.class);+ return TreeLockUtils.doWithTreeLock(+ NameIdentifier.of(namespace.levels()),+ LockType.READ,+ () ->+ doWithCatalog(+ getCatalogIdentifier(NameIdentifier.of(namespace.levels())),+ c -> c.doWithSchemaOps(s -> s.listSchemas(namespace)),+ NoSuchCatalogException.class));}/**@@ -93,8 +97,8 @@ public class SchemaOperationDispatcher extends OperationDispatcher implements Sc@Overridepublic Schema createSchema(NameIdentifier ident, String comment, Map<String, String> properties)throws NoSuchCatalogException, SchemaAlreadyExistsException {-NameIdentifier catalogIdent = getCatalogIdentifier(ident);+doWithCatalog(catalogIdent,c ->@@ -112,55 +116,63 @@ public class SchemaOperationDispatcher extends OperationDispatcher implements ScMap<String, String> updatedProperties =StringIdentifier.newPropertiesWithId(stringId, properties);- // we do not retrieve the schema again (to obtain some values generated by underlying catalog)- // since some catalogs' API is async and the schema may not be created immediately- Schema schema =- doWithCatalog(- catalogIdent,- c -> c.doWithSchemaOps(s -> s.createSchema(ident, comment, updatedProperties)),- NoSuchCatalogException.class,- SchemaAlreadyExistsException.class);-- // If the Schema is maintained by the Gravitino's store, we don't have to store again.- boolean isManagedSchema = isManagedEntity(catalogIdent, Capability.Scope.SCHEMA);- if (isManagedSchema) {- return EntityCombinedSchema.of(schema)- .withHiddenProperties(- getHiddenPropertyNames(+ return TreeLockUtils.doWithTreeLock(+ catalogIdent,+ LockType.WRITE,+ () -> {+ // we do not retrieve the schema again (to obtain some values generated by underlying+ // catalog)+ // since some catalogs' API is async and the schema may not be created immediately+ Schema schema =+ doWithCatalog(catalogIdent,- HasPropertyMetadata::schemaPropertiesMetadata,- schema.properties()));- }+ c -> c.doWithSchemaOps(s -> s.createSchema(ident, comment, updatedProperties)),+ NoSuchCatalogException.class,+ SchemaAlreadyExistsException.class);- SchemaEntity schemaEntity =- SchemaEntity.builder()- .withId(uid)- .withName(ident.name())- .withNamespace(ident.namespace())- .withAuditInfo(- AuditInfo.builder()- .withCreator(PrincipalUtils.getCurrentPrincipal().getName())- .withCreateTime(Instant.now())- .build())- .build();+ // If the Schema is maintained by the Gravitino's store, we don't have to store again.+ boolean isManagedSchema = isManagedEntity(catalogIdent, Capability.Scope.SCHEMA);+ if (isManagedSchema) {+ return EntityCombinedSchema.of(schema)+ .withHiddenProperties(+ getHiddenPropertyNames(+ catalogIdent,+ HasPropertyMetadata::schemaPropertiesMetadata,+ schema.properties()));+ }- try {- store.put(schemaEntity, true /* overwrite */);- } catch (Exception e) {- LOG.error(FormattedErrorMessages.STORE_OP_FAILURE, "put", ident, e);- return EntityCombinedSchema.of(schema)- .withHiddenProperties(- getHiddenPropertyNames(- catalogIdent,- HasPropertyMetadata::schemaPropertiesMetadata,- schema.properties()));- }+ SchemaEntity schemaEntity =+ SchemaEntity.builder()+ .withId(uid)+ .withName(ident.name())+ .withNamespace(ident.namespace())+ .withAuditInfo(+ AuditInfo.builder()+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())+ .withCreateTime(Instant.now())+ .build())+ .build();- // Merge both the metadata from catalog operation and the metadata from entity store.- return EntityCombinedSchema.of(schema, schemaEntity)- .withHiddenProperties(- getHiddenPropertyNames(- catalogIdent, HasPropertyMetadata::schemaPropertiesMetadata, schema.properties()));+ try {+ store.put(schemaEntity, true /* overwrite */);+ } catch (Exception e) {+ LOG.error(FormattedErrorMessages.STORE_OP_FAILURE, "put", ident, e);+ return EntityCombinedSchema.of(schema)+ .withHiddenProperties(+ getHiddenPropertyNames(+ catalogIdent,+ HasPropertyMetadata::schemaPropertiesMetadata,+ schema.properties()));+ }++ // Merge both the metadata from catalog operation and the metadata from entity store.+ return EntityCombinedSchema.of(schema, schemaEntity)+ .withHiddenProperties(+ getHiddenPropertyNames(+ catalogIdent,+ HasPropertyMetadata::schemaPropertiesMetadata,+ schema.properties()));+ });}/**@@ -201,68 +213,75 @@ public class SchemaOperationDispatcher extends OperationDispatcher implements Sc@Overridepublic Schema alterSchema(NameIdentifier ident, SchemaChange... changes)throws NoSuchSchemaException {- validateAlterProperties(ident, HasPropertyMetadata::schemaPropertiesMetadata, changes);NameIdentifier catalogIdent = getCatalogIdentifier(ident);- Schema alteredSchema =- doWithCatalog(- catalogIdent,- c -> c.doWithSchemaOps(s -> s.alterSchema(ident, changes)),- NoSuchSchemaException.class);-- // If the Schema is maintained by the Gravitino's store, we don't have to alter again.- boolean isManagedSchema = isManagedEntity(catalogIdent, Capability.Scope.SCHEMA);- if (isManagedSchema) {- return EntityCombinedSchema.of(alteredSchema)- .withHiddenProperties(- getHiddenPropertyNames(+ // Gravitino does not support alter schema currently, so we do not need to check whether there+ // exists SchemaChange.renameSchema in the changes and can lock schema directly.+ return TreeLockUtils.doWithTreeLock(+ ident,+ LockType.WRITE,+ () -> {+ validateAlterProperties(ident, HasPropertyMetadata::schemaPropertiesMetadata, changes);+ Schema alteredSchema =+ doWithCatalog(catalogIdent,- HasPropertyMetadata::schemaPropertiesMetadata,- alteredSchema.properties()));- }+ c -> c.doWithSchemaOps(s -> s.alterSchema(ident, changes)),+ NoSuchSchemaException.class);- StringIdentifier stringId = getStringIdFromProperties(alteredSchema.properties());- // Case 1: The schema is not created by Gravitino.- if (stringId == null) {- return EntityCombinedSchema.of(alteredSchema)- .withHiddenProperties(- getHiddenPropertyNames(- catalogIdent,- HasPropertyMetadata::schemaPropertiesMetadata,- alteredSchema.properties()));- }+ // If the Schema is maintained by the Gravitino's store, we don't have to alter again.+ boolean isManagedSchema = isManagedEntity(catalogIdent, Capability.Scope.SCHEMA);+ if (isManagedSchema) {+ return EntityCombinedSchema.of(alteredSchema)+ .withHiddenProperties(+ getHiddenPropertyNames(+ catalogIdent,+ HasPropertyMetadata::schemaPropertiesMetadata,+ alteredSchema.properties()));+ }- SchemaEntity updatedSchemaEntity =- operateOnEntity(- ident,- id ->- store.update(- id,- SchemaEntity.class,- SCHEMA,- schemaEntity ->- SchemaEntity.builder()- .withId(schemaEntity.id())- .withName(schemaEntity.name())- .withNamespace(ident.namespace())- .withAuditInfo(- AuditInfo.builder()- .withCreator(schemaEntity.auditInfo().creator())- .withCreateTime(schemaEntity.auditInfo().createTime())- .withLastModifier(- PrincipalUtils.getCurrentPrincipal().getName())- .withLastModifiedTime(Instant.now())- .build())- .build()),- "UPDATE",- stringId.id());+ StringIdentifier stringId = getStringIdFromProperties(alteredSchema.properties());+ // Case 1: The schema is not created by Gravitino.+ if (stringId == null) {+ return EntityCombinedSchema.of(alteredSchema)+ .withHiddenProperties(+ getHiddenPropertyNames(+ catalogIdent,+ HasPropertyMetadata::schemaPropertiesMetadata,+ alteredSchema.properties()));+ }- return EntityCombinedSchema.of(alteredSchema, updatedSchemaEntity)- .withHiddenProperties(- getHiddenPropertyNames(- catalogIdent,- HasPropertyMetadata::schemaPropertiesMetadata,- alteredSchema.properties()));+ SchemaEntity updatedSchemaEntity =+ operateOnEntity(+ ident,+ id ->+ store.update(+ id,+ SchemaEntity.class,+ SCHEMA,+ schemaEntity ->+ SchemaEntity.builder()+ .withId(schemaEntity.id())+ .withName(schemaEntity.name())+ .withNamespace(ident.namespace())+ .withAuditInfo(+ AuditInfo.builder()+ .withCreator(schemaEntity.auditInfo().creator())+ .withCreateTime(schemaEntity.auditInfo().createTime())+ .withLastModifier(+ PrincipalUtils.getCurrentPrincipal().getName())+ .withLastModifiedTime(Instant.now())+ .build())+ .build()),+ "UPDATE",+ stringId.id());++ return EntityCombinedSchema.of(alteredSchema, updatedSchemaEntity)+ .withHiddenProperties(+ getHiddenPropertyNames(+ catalogIdent,+ HasPropertyMetadata::schemaPropertiesMetadata,+ alteredSchema.properties()));+ });}/**@@ -294,10 +313,10 @@ public class SchemaOperationDispatcher extends OperationDispatcher implements Screturn droppedFromCatalog;}- // For unmanaged schema, it could happen that the schema:- // 1. Is not found in the catalog (dropped directly from underlying sources)- // 2. Is found in the catalog but not in the store (not managed by Gravitino)- // 3. Is found in the catalog and the store (managed by Gravitino)+ // For the unmanaged schema, it could happen that the schema:+ // 1. It's not found in the catalog (dropped directly from underlying sources)+ // 2. It's found in the catalog but not in the store (not managed by Gravitino)+ // 3. It's found in the catalog and the store (managed by Gravitino)// 4. Neither found in the catalog nor in the store.// In all situations, we try to delete the schema from the store, but we don't take the// return value of the store operation into account. We only take the return value of the@@ -337,7 +356,7 @@ public class SchemaOperationDispatcher extends OperationDispatcher implements ScstringId);uid = stringId.id();} else {- // If entity doesn't exist, we import the entity from the external system.+ // If the entity doesn't exist, we import the entity from the external system.uid = idGenerator.nextId();}diff --git a/core/src/main/java/org/apache/gravitino/catalog/TableOperationDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/TableOperationDispatcher.javaindex 3e6aa2abbe..49e892196c 100644--- a/core/src/main/java/org/apache/gravitino/catalog/TableOperationDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/catalog/TableOperationDispatcher.java@@ -93,10 +93,14 @@ public class TableOperationDispatcher extends OperationDispatcher implements Tab*/@Overridepublic NameIdentifier[] listTables(Namespace namespace) throws NoSuchSchemaException {- return doWithCatalog(- getCatalogIdentifier(NameIdentifier.of(namespace.levels())),- c -> c.doWithTableOps(t -> t.listTables(namespace)),- NoSuchSchemaException.class);+ return TreeLockUtils.doWithTreeLock(+ NameIdentifier.of(namespace.levels()),+ LockType.READ,+ () ->+ doWithCatalog(+ getCatalogIdentifier(NameIdentifier.of(namespace.levels())),+ c -> c.doWithTableOps(t -> t.listTables(namespace)),+ NoSuchSchemaException.class));}/**@@ -195,69 +199,82 @@ public class TableOperationDispatcher extends OperationDispatcher implements Tabthrows NoSuchTableException, IllegalArgumentException {validateAlterProperties(ident, HasPropertyMetadata::tablePropertiesMetadata, changes);- NameIdentifier catalogIdent = getCatalogIdentifier(ident);- Table alteredTable =- doWithCatalog(- catalogIdent,- c ->- c.doWithTableOps(- t -> t.alterTable(ident, applyCapabilities(c.capabilities(), changes))),- NoSuchTableException.class,- IllegalArgumentException.class);+ // Check if there exist TableChange.RenameTable in the changes, if so, we need to TreeLock of+ // write on the new table name, or use the read lock on the table instead.+ boolean containsRenameTable =+ Arrays.stream(changes).anyMatch(c -> c instanceof TableChange.RenameTable);+ NameIdentifier nameIdentifierForLock =+ containsRenameTable ? NameIdentifier.of(ident.namespace().levels()) : ident;- StringIdentifier stringId = getStringIdFromProperties(alteredTable.properties());- // Case 1: The table is not created by Gravitino.- if (stringId == null) {- return EntityCombinedTable.of(alteredTable)- .withHiddenProperties(- getHiddenPropertyNames(- getCatalogIdentifier(ident),- HasPropertyMetadata::tablePropertiesMetadata,- alteredTable.properties()));- }-- TableEntity updatedTableEntity =- operateOnEntity(- ident,- id ->- store.update(- id,- TableEntity.class,- TABLE,- tableEntity -> {- String newName =- Arrays.stream(changes)- .filter(c -> c instanceof TableChange.RenameTable)- .map(c -> ((TableChange.RenameTable) c).getNewName())- .reduce((c1, c2) -> c2)- .orElse(tableEntity.name());- // Update the columns- Pair<Boolean, List<ColumnEntity>> columnsUpdateResult =- updateColumnsIfNecessary(alteredTable, tableEntity);-- return TableEntity.builder()- .withId(tableEntity.id())- .withName(newName)- .withNamespace(ident.namespace())- .withColumns(columnsUpdateResult.getRight())- .withAuditInfo(- AuditInfo.builder()- .withCreator(tableEntity.auditInfo().creator())- .withCreateTime(tableEntity.auditInfo().createTime())- .withLastModifier(PrincipalUtils.getCurrentPrincipal().getName())- .withLastModifiedTime(Instant.now())- .build())- .build();- }),- "UPDATE",- stringId.id());+ return TreeLockUtils.doWithTreeLock(+ nameIdentifierForLock,+ LockType.WRITE,+ () -> {+ NameIdentifier catalogIdent = getCatalogIdentifier(ident);+ Table alteredTable =+ doWithCatalog(+ catalogIdent,+ c ->+ c.doWithTableOps(+ t -> t.alterTable(ident, applyCapabilities(c.capabilities(), changes))),+ NoSuchTableException.class,+ IllegalArgumentException.class);++ StringIdentifier stringId = getStringIdFromProperties(alteredTable.properties());+ // Case 1: The table is not created by Gravitino.+ if (stringId == null) {+ return EntityCombinedTable.of(alteredTable)+ .withHiddenProperties(+ getHiddenPropertyNames(+ getCatalogIdentifier(ident),+ HasPropertyMetadata::tablePropertiesMetadata,+ alteredTable.properties()));+ }- return EntityCombinedTable.of(alteredTable, updatedTableEntity)- .withHiddenProperties(- getHiddenPropertyNames(- getCatalogIdentifier(ident),- HasPropertyMetadata::tablePropertiesMetadata,- alteredTable.properties()));+ TableEntity updatedTableEntity =+ operateOnEntity(+ ident,+ id ->+ store.update(+ id,+ TableEntity.class,+ TABLE,+ tableEntity -> {+ String newName =+ Arrays.stream(changes)+ .filter(c -> c instanceof TableChange.RenameTable)+ .map(c -> ((TableChange.RenameTable) c).getNewName())+ .reduce((c1, c2) -> c2)+ .orElse(tableEntity.name());+ // Update the columns+ Pair<Boolean, List<ColumnEntity>> columnsUpdateResult =+ updateColumnsIfNecessary(alteredTable, tableEntity);++ return TableEntity.builder()+ .withId(tableEntity.id())+ .withName(newName)+ .withNamespace(ident.namespace())+ .withColumns(columnsUpdateResult.getRight())+ .withAuditInfo(+ AuditInfo.builder()+ .withCreator(tableEntity.auditInfo().creator())+ .withCreateTime(tableEntity.auditInfo().createTime())+ .withLastModifier(+ PrincipalUtils.getCurrentPrincipal().getName())+ .withLastModifiedTime(Instant.now())+ .build())+ .build();+ }),+ "UPDATE",+ stringId.id());++ return EntityCombinedTable.of(alteredTable, updatedTableEntity)+ .withHiddenProperties(+ getHiddenPropertyNames(+ getCatalogIdentifier(ident),+ HasPropertyMetadata::tablePropertiesMetadata,+ alteredTable.properties()));+ });}/**@@ -324,11 +341,11 @@ public class TableOperationDispatcher extends OperationDispatcher implements Tab@Overridepublic boolean purgeTable(NameIdentifier ident) throws UnsupportedOperationException {NameIdentifier schemaIdentifier = NameIdentifierUtil.getSchemaIdentifier(ident);+ NameIdentifier catalogIdent = getCatalogIdentifier(ident);return TreeLockUtils.doWithTreeLock(schemaIdentifier,LockType.WRITE,() -> {- NameIdentifier catalogIdent = getCatalogIdentifier(ident);boolean droppedFromCatalog =doWithCatalog(catalogIdent,@@ -346,7 +363,7 @@ public class TableOperationDispatcher extends OperationDispatcher implements Tab// catalog into account.//// For managed table, we should take the return value of the store operation into account.- boolean droppedFromStore = false;+ boolean droppedFromStore;try {droppedFromStore = store.delete(ident, TABLE);} catch (NoSuchEntityException e) {diff --git a/core/src/main/java/org/apache/gravitino/catalog/TopicOperationDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/TopicOperationDispatcher.javaindex eb4914b08f..7ecc1107ff 100644--- a/core/src/main/java/org/apache/gravitino/catalog/TopicOperationDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/catalog/TopicOperationDispatcher.java@@ -73,10 +73,14 @@ public class TopicOperationDispatcher extends OperationDispatcher implements Top*/@Overridepublic NameIdentifier[] listTopics(Namespace namespace) throws NoSuchSchemaException {- return doWithCatalog(- getCatalogIdentifier(NameIdentifier.of(namespace.levels())),- c -> c.doWithTopicOps(t -> t.listTopics(namespace)),- NoSuchSchemaException.class);+ return TreeLockUtils.doWithTreeLock(+ NameIdentifier.of(namespace.levels()),+ LockType.READ,+ () ->+ doWithCatalog(+ getCatalogIdentifier(NameIdentifier.of(namespace.levels())),+ c -> c.doWithTopicOps(t -> t.listTopics(namespace)),+ NoSuchSchemaException.class));}/**@@ -93,7 +97,7 @@ public class TopicOperationDispatcher extends OperationDispatcher implements Topif (!topic.imported()) {// Load the schema to make sure the schema is imported.- // This is not necessary for Kafka catalog.+ // This is not necessary for Kafka catalogs.SchemaDispatcher schemaDispatcher = GravitinoEnv.getInstance().schemaDispatcher();NameIdentifier schemaIdent = NameIdentifier.of(ident.namespace().levels());schemaDispatcher.loadSchema(schemaIdent);@@ -147,59 +151,67 @@ public class TopicOperationDispatcher extends OperationDispatcher implements Top* @param changes The changes to apply to the topic.* @return The altered topic metadata.* @throws NoSuchTopicException If the topic does not exist.- * @throws IllegalArgumentException If the changes is rejected by the implementation.+ * @throws IllegalArgumentException If any change is rejected by the implementation.*/@Overridepublic Topic alterTopic(NameIdentifier ident, TopicChange... changes)throws NoSuchTopicException, IllegalArgumentException {- validateAlterProperties(ident, HasPropertyMetadata::topicPropertiesMetadata, changes);-- NameIdentifier catalogIdent = getCatalogIdentifier(ident);- // we do not retrieve the topic again (to obtain some values generated by underlying catalog)- // since some catalogs' API is async and the topic may not be created immediately- Topic alteredTopic =- doWithCatalog(- catalogIdent,- c -> c.doWithTopicOps(t -> t.alterTopic(ident, changes)),- NoSuchTopicException.class,- IllegalArgumentException.class);+ validateAlterProperties(ident, HasPropertyMetadata::topicPropertiesMetadata, changes);- TopicEntity updatedTopicEntity =- operateOnEntity(- ident,- id ->- store.update(- id,- TopicEntity.class,- TOPIC,- topicEntity ->- TopicEntity.builder()- .withId(topicEntity.id())- .withName(topicEntity.name())- .withNamespace(ident.namespace())- .withComment(- StringUtils.isBlank(alteredTopic.comment())- ? topicEntity.comment()- : alteredTopic.comment())- .withAuditInfo(- AuditInfo.builder()- .withCreator(topicEntity.auditInfo().creator())- .withCreateTime(topicEntity.auditInfo().createTime())- .withLastModifier(- PrincipalUtils.getCurrentPrincipal().getName())- .withLastModifiedTime(Instant.now())- .build())- .build()),- "UPDATE",- getStringIdFromProperties(alteredTopic.properties()).id());-- return EntityCombinedTopic.of(alteredTopic, updatedTopicEntity)- .withHiddenProperties(- getHiddenPropertyNames(- catalogIdent,- HasPropertyMetadata::topicPropertiesMetadata,- alteredTopic.properties()));+ // As Gravitino does not support TopicChange.renameTopic, we can directly lock the topic.+ return TreeLockUtils.doWithTreeLock(+ ident,+ LockType.WRITE,+ () -> {+ NameIdentifier catalogIdent = getCatalogIdentifier(ident);++ // we do not retrieve the topic again (to obtain some values generated by underlying+ // catalog)+ // since some catalogs' API is async and the topic may not be created immediately+ Topic alteredTopic =+ doWithCatalog(+ catalogIdent,+ c -> c.doWithTopicOps(t -> t.alterTopic(ident, changes)),+ NoSuchTopicException.class,+ IllegalArgumentException.class);++ TopicEntity updatedTopicEntity =+ operateOnEntity(+ ident,+ id ->+ store.update(+ id,+ TopicEntity.class,+ TOPIC,+ topicEntity ->+ TopicEntity.builder()+ .withId(topicEntity.id())+ .withName(topicEntity.name())+ .withNamespace(ident.namespace())+ .withComment(+ StringUtils.isBlank(alteredTopic.comment())+ ? topicEntity.comment()+ : alteredTopic.comment())+ .withAuditInfo(+ AuditInfo.builder()+ .withCreator(topicEntity.auditInfo().creator())+ .withCreateTime(topicEntity.auditInfo().createTime())+ .withLastModifier(+ PrincipalUtils.getCurrentPrincipal().getName())+ .withLastModifiedTime(Instant.now())+ .build())+ .build()),+ "UPDATE",+ getStringIdFromProperties(alteredTopic.properties()).id());++ return EntityCombinedTopic.of(alteredTopic, updatedTopicEntity)+ .withHiddenProperties(+ getHiddenPropertyNames(+ catalogIdent,+ HasPropertyMetadata::topicPropertiesMetadata,+ alteredTopic.properties()));+ });}/**@@ -211,33 +223,40 @@ public class TopicOperationDispatcher extends OperationDispatcher implements Top*/@Overridepublic boolean dropTopic(NameIdentifier ident) {- NameIdentifier catalogIdent = getCatalogIdentifier(ident);- boolean droppedFromCatalog =- doWithCatalog(- catalogIdent, c -> c.doWithTopicOps(t -> t.dropTopic(ident)), RuntimeException.class);-- // For unmanaged topic, it could happen that the topic:- // 1. Is not found in the catalog (dropped directly from underlying sources)- // 2. Is found in the catalog but not in the store (not managed by Gravitino)- // 3. Is found in the catalog and the store (managed by Gravitino)- // 4. Neither found in the catalog nor in the store.- // In all situations, we try to delete the schema from the store, but we don't take the- // return value of the store operation into account. We only take the return value of the- // catalog into account.- //- // For managed topic, we should take the return value of the store operation into account.- boolean droppedFromStore = false;- try {- droppedFromStore = store.delete(ident, TOPIC);- } catch (NoSuchEntityException e) {- LOG.warn("The topic to be dropped does not exist in the store: {}", ident, e);- } catch (Exception e) {- throw new RuntimeException(e);- }-- return isManagedEntity(catalogIdent, Capability.Scope.TOPIC)- ? droppedFromStore- : droppedFromCatalog;+ return TreeLockUtils.doWithTreeLock(+ NameIdentifier.of(ident.namespace().levels()),+ LockType.WRITE,+ () -> {+ NameIdentifier catalogIdent = getCatalogIdentifier(ident);+ boolean droppedFromCatalog =+ doWithCatalog(+ catalogIdent,+ c -> c.doWithTopicOps(t -> t.dropTopic(ident)),+ RuntimeException.class);++ // For the unmanaged topic, it could happen that the topic:+ // 1. It's not found in the catalog (dropped directly from underlying sources)+ // 2. It's found in the catalog but not in the store (not managed by Gravitino)+ // 3. It's found in the catalog and the store (managed by Gravitino)+ // 4. Neither found in the catalog nor in the store.+ // In all situations, we try to delete the schema from the store, but we don't take the+ // return value of the store operation into account. We only take the return value of the+ // catalog into account.+ //+ // For managed topic, we should take the return value of the store operation into account.+ boolean droppedFromStore = false;+ try {+ droppedFromStore = store.delete(ident, TOPIC);+ } catch (NoSuchEntityException e) {+ LOG.warn("The topic to be dropped does not exist in the store: {}", ident, e);+ } catch (Exception e) {+ throw new RuntimeException(e);+ }++ return isManagedEntity(catalogIdent, Capability.Scope.TOPIC)+ ? droppedFromStore+ : droppedFromCatalog;+ });}private void importTopic(NameIdentifier identifier) {@@ -257,7 +276,7 @@ public class TopicOperationDispatcher extends OperationDispatcher implements Toplong uid;if (stringId != null) {- // For Kafka topic, the uid is coming from topic UUID, which is always existed.+ // For Kafka topics, the uid is coming from topic UUID, which is always existed.LOG.warn("The Topic uid {} existed but still needs to be imported, this could be happened "+ "when Topic is created externally without leveraging Gravitino. In this "diff --git a/core/src/main/java/org/apache/gravitino/metalake/MetalakeManager.java b/core/src/main/java/org/apache/gravitino/metalake/MetalakeManager.javaindex 0239526e5e..c1b464f436 100644--- a/core/src/main/java/org/apache/gravitino/metalake/MetalakeManager.java+++ b/core/src/main/java/org/apache/gravitino/metalake/MetalakeManager.java@@ -23,6 +23,7 @@ import static org.apache.gravitino.Metalake.PROPERTY_IN_USE;import com.google.common.collect.Maps;import java.io.IOException;import java.time.Instant;+import java.util.Arrays;import java.util.HashMap;import java.util.List;import java.util.Map;@@ -40,11 +41,14 @@ import org.apache.gravitino.exceptions.NoSuchEntityException;import org.apache.gravitino.exceptions.NoSuchMetalakeException;import org.apache.gravitino.exceptions.NonEmptyEntityException;import org.apache.gravitino.exceptions.NonEmptyMetalakeException;+import org.apache.gravitino.lock.LockType;+import org.apache.gravitino.lock.TreeLockUtils;import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.meta.BaseMetalake;import org.apache.gravitino.meta.CatalogEntity;import org.apache.gravitino.meta.SchemaVersion;import org.apache.gravitino.storage.IdGenerator;+import org.apache.gravitino.utils.Executable;import org.apache.gravitino.utils.PrincipalUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;@@ -122,7 +126,12 @@ public class MetalakeManager implements MetalakeDispatcher {@Overridepublic BaseMetalake[] listMetalakes() {try {- return store.list(Namespace.empty(), BaseMetalake.class, EntityType.METALAKE).stream()+ List<BaseMetalake> metalakes =+ TreeLockUtils.doWithRootTreeLock(+ LockType.READ,+ () -> store.list(Namespace.empty(), BaseMetalake.class, EntityType.METALAKE));++ return metalakes.stream().map(this::newMetalakeWithResolvedProperties).toArray(BaseMetalake[]::new);} catch (IOException ioe) {@@ -130,7 +139,6 @@ public class MetalakeManager implements MetalakeDispatcher {throw new RuntimeException(ioe);}}-/*** Loads a Metalake.*@@ -142,8 +150,12 @@ public class MetalakeManager implements MetalakeDispatcher {@Overridepublic BaseMetalake loadMetalake(NameIdentifier ident) throws NoSuchMetalakeException {try {- return newMetalakeWithResolvedProperties(- store.get(ident, EntityType.METALAKE, BaseMetalake.class));+ BaseMetalake baseMetalake =+ TreeLockUtils.doWithTreeLock(+ ident,+ LockType.READ,+ () -> store.get(ident, EntityType.METALAKE, BaseMetalake.class));+ return newMetalakeWithResolvedProperties(baseMetalake);} catch (NoSuchEntityException e) {LOG.warn("Metalake {} does not exist", ident, e);throw new NoSuchMetalakeException(METALAKE_DOES_NOT_EXIST_MSG, ident);@@ -205,16 +217,20 @@ public class MetalakeManager implements MetalakeDispatcher {.build()).build();- try {- store.put(metalake, false /* overwritten */);- return metalake;- } catch (EntityAlreadyExistsException | AlreadyExistsException e) {- LOG.warn("Metalake {} already exists", ident, e);- throw new MetalakeAlreadyExistsException("Metalake %s already exists", ident);- } catch (IOException ioe) {- LOG.error("Loading Metalake {} failed due to storage issues", ident, ioe);- throw new RuntimeException(ioe);- }+ return TreeLockUtils.doWithRootTreeLock(+ LockType.WRITE,+ () -> {+ try {+ store.put(metalake, false /* overwritten */);+ return metalake;+ } catch (EntityAlreadyExistsException | AlreadyExistsException e) {+ LOG.warn("Metalake {} already exists", ident, e);+ throw new MetalakeAlreadyExistsException("Metalake %s already exists", ident);+ } catch (IOException ioe) {+ LOG.error("Loading Metalake {} failed due to storage issues", ident, ioe);+ throw new RuntimeException(ioe);+ }+ });}/**@@ -230,120 +246,147 @@ public class MetalakeManager implements MetalakeDispatcher {@Overridepublic BaseMetalake alterMetalake(NameIdentifier ident, MetalakeChange... changes)throws NoSuchMetalakeException, IllegalArgumentException {- try {- if (!metalakeInUse(store, ident)) {- throw new MetalakeNotInUseException(- "Metalake %s is not in use, please enable it first", ident);- }-- return store.update(- ident,- BaseMetalake.class,- EntityType.METALAKE,- metalake -> {- BaseMetalake.Builder builder = newMetalakeBuilder(metalake);- Map<String, String> newProps =- metalake.properties() == null- ? Maps.newHashMap()- : Maps.newHashMap(metalake.properties());- builder = updateEntity(builder, newProps, changes);-- return builder.build();- });-- } catch (NoSuchEntityException ne) {- LOG.warn("Metalake {} does not exist", ident, ne);- throw new NoSuchMetalakeException(METALAKE_DOES_NOT_EXIST_MSG, ident);-- } catch (IllegalArgumentException iae) {- LOG.warn("Altering Metalake {} failed due to invalid changes", ident, iae);- throw iae;-- } catch (IOException ioe) {- LOG.error("Loading Metalake {} failed due to storage issues", ident, ioe);- throw new RuntimeException(ioe);+ Executable<BaseMetalake, RuntimeException> exceptionExecutable =+ () -> {+ try {+ if (!metalakeInUse(store, ident)) {+ throw new MetalakeNotInUseException(+ "Metalake %s is not in use, please enable it first", ident);+ }++ return store.update(+ ident,+ BaseMetalake.class,+ EntityType.METALAKE,+ metalake -> {+ BaseMetalake.Builder builder = newMetalakeBuilder(metalake);+ Map<String, String> newProps =+ metalake.properties() == null+ ? Maps.newHashMap()+ : Maps.newHashMap(metalake.properties());+ builder = updateEntity(builder, newProps, changes);++ return builder.build();+ });++ } catch (NoSuchEntityException ne) {+ LOG.warn("Metalake {} does not exist", ident, ne);+ throw new NoSuchMetalakeException(METALAKE_DOES_NOT_EXIST_MSG, ident);++ } catch (IllegalArgumentException iae) {+ LOG.warn("Altering Metalake {} failed due to invalid changes", ident, iae);+ throw iae;++ } catch (IOException ioe) {+ LOG.error("Loading Metalake {} failed due to storage issues", ident, ioe);+ throw new RuntimeException(ioe);+ }+ };++ boolean containsRenameMetalake =+ Arrays.stream(changes).anyMatch(c -> c instanceof MetalakeChange.RenameMetalake);+ if (containsRenameMetalake) {+ return TreeLockUtils.doWithRootTreeLock(LockType.WRITE, exceptionExecutable);}++ return TreeLockUtils.doWithTreeLock(ident, LockType.WRITE, exceptionExecutable);}@Overridepublic boolean dropMetalake(NameIdentifier ident, boolean force)throws NonEmptyEntityException, MetalakeInUseException {- try {- boolean inUse = metalakeInUse(store, ident);- if (inUse && !force) {- throw new MetalakeInUseException(- "Metalake %s is in use, please disable it first or use force option", ident);- }-- List<CatalogEntity> catalogEntities =- store.list(Namespace.of(ident.name()), CatalogEntity.class, EntityType.CATALOG);- if (!catalogEntities.isEmpty() && !force) {- throw new NonEmptyMetalakeException(- "Metalake %s has catalogs, please drop them first or use force option", ident);- }-- return store.delete(ident, EntityType.METALAKE, true);- } catch (NoSuchMetalakeException e) {- return false;-- } catch (IOException e) {- throw new RuntimeException(e);- }+ return TreeLockUtils.doWithRootTreeLock(+ LockType.WRITE,+ () -> {+ try {+ boolean inUse = metalakeInUse(store, ident);+ if (inUse && !force) {+ throw new MetalakeInUseException(+ "Metalake %s is in use, please disable it first or use force option", ident);+ }++ List<CatalogEntity> catalogEntities =+ store.list(Namespace.of(ident.name()), CatalogEntity.class, EntityType.CATALOG);+ if (!catalogEntities.isEmpty() && !force) {+ throw new NonEmptyMetalakeException(+ "Metalake %s has catalogs, please drop them first or use force option", ident);+ }++ return store.delete(ident, EntityType.METALAKE, true);+ } catch (NoSuchMetalakeException e) {+ return false;++ } catch (IOException e) {+ throw new RuntimeException(e);+ }+ });}@Overridepublic void enableMetalake(NameIdentifier ident) throws NoSuchMetalakeException {- try {-- boolean inUse = metalakeInUse(store, ident);- if (!inUse) {- store.update(- ident,- BaseMetalake.class,- EntityType.METALAKE,- metalake -> {- BaseMetalake.Builder builder = newMetalakeBuilder(metalake);-- Map<String, String> newProps =- metalake.properties() == null- ? Maps.newHashMap()- : Maps.newHashMap(metalake.properties());- newProps.put(PROPERTY_IN_USE, "true");- builder.withProperties(newProps);-- return builder.build();- });- }- } catch (IOException e) {- throw new RuntimeException(e);- }+ TreeLockUtils.doWithTreeLock(+ ident,+ LockType.WRITE,+ () -> {+ try {+ boolean inUse = metalakeInUse(store, ident);+ if (!inUse) {+ store.update(+ ident,+ BaseMetalake.class,+ EntityType.METALAKE,+ metalake -> {+ BaseMetalake.Builder builder = newMetalakeBuilder(metalake);++ Map<String, String> newProps =+ metalake.properties() == null+ ? Maps.newHashMap()+ : Maps.newHashMap(metalake.properties());+ newProps.put(PROPERTY_IN_USE, "true");+ builder.withProperties(newProps);++ return builder.build();+ });+ }++ return null;+ } catch (IOException e) {+ throw new RuntimeException(e);+ }+ });}@Overridepublic void disableMetalake(NameIdentifier ident) throws NoSuchMetalakeException {- try {- boolean inUse = metalakeInUse(store, ident);- if (inUse) {- store.update(- ident,- BaseMetalake.class,- EntityType.METALAKE,- metalake -> {- BaseMetalake.Builder builder = newMetalakeBuilder(metalake);-- Map<String, String> newProps =- metalake.properties() == null- ? Maps.newHashMap()- : Maps.newHashMap(metalake.properties());- newProps.put(PROPERTY_IN_USE, "false");- builder.withProperties(newProps);-- return builder.build();- });- }- } catch (IOException e) {- throw new RuntimeException(e);- }+ TreeLockUtils.doWithTreeLock(+ ident,+ LockType.WRITE,+ () -> {+ try {+ boolean inUse = metalakeInUse(store, ident);+ if (inUse) {+ store.update(+ ident,+ BaseMetalake.class,+ EntityType.METALAKE,+ metalake -> {+ BaseMetalake.Builder builder = newMetalakeBuilder(metalake);++ Map<String, String> newProps =+ metalake.properties() == null+ ? Maps.newHashMap()+ : Maps.newHashMap(metalake.properties());+ newProps.put(PROPERTY_IN_USE, "false");+ builder.withProperties(newProps);++ return builder.build();+ });+ }+ return null;+ } catch (IOException e) {+ throw new RuntimeException(e);+ }+ });}private BaseMetalake.Builder newMetalakeBuilder(BaseMetalake metalake) {diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestOperationDispatcher.java b/core/src/test/java/org/apache/gravitino/catalog/TestOperationDispatcher.javaindex 45e821515d..99a51e10d4 100644--- a/core/src/test/java/org/apache/gravitino/catalog/TestOperationDispatcher.java+++ b/core/src/test/java/org/apache/gravitino/catalog/TestOperationDispatcher.java@@ -18,10 +18,15 @@*/package org.apache.gravitino.catalog;+import static org.apache.gravitino.Configs.TREE_LOCK_CLEAN_INTERVAL;+import static org.apache.gravitino.Configs.TREE_LOCK_MAX_NODE_IN_MEMORY;+import static org.apache.gravitino.Configs.TREE_LOCK_MIN_NODE_IN_MEMORY;import static org.apache.gravitino.TestFilesetPropertiesMetadata.TEST_FILESET_HIDDEN_KEY;import static org.apache.gravitino.utils.NameIdentifierUtil.getCatalogIdentifier;import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.mockito.Mockito.doReturn;+import static org.mockito.Mockito.mock;import static org.mockito.Mockito.reset;import static org.mockito.Mockito.spy;@@ -30,15 +35,18 @@ import com.google.common.collect.ImmutableMap;import java.io.IOException;import java.time.Instant;import java.util.Map;+import org.apache.commons.lang3.reflect.FieldUtils;import org.apache.gravitino.Catalog;import org.apache.gravitino.Config;import org.apache.gravitino.Configs;import org.apache.gravitino.Entity;import org.apache.gravitino.EntityStore;+import org.apache.gravitino.GravitinoEnv;import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.StringIdentifier;import org.apache.gravitino.authorization.AuthorizationUtils;import org.apache.gravitino.exceptions.IllegalNamespaceException;+import org.apache.gravitino.lock.LockManager;import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.meta.BaseMetalake;import org.apache.gravitino.meta.SchemaVersion;@@ -69,7 +77,7 @@ public abstract class TestOperationDispatcher {private static Config config;@BeforeAll- public static void setUp() throws IOException {+ public static void setUp() throws IOException, IllegalAccessException {config = new Config(false) {};config.set(Configs.CATALOG_LOAD_ISOLATED, false);@@ -88,6 +96,12 @@ public abstract class TestOperationDispatcher {catalogManager = new CatalogManager(config, entityStore, idGenerator);+ Config config = mock(Config.class);+ doReturn(100000L).when(config).get(TREE_LOCK_MAX_NODE_IN_MEMORY);+ doReturn(1000L).when(config).get(TREE_LOCK_MIN_NODE_IN_MEMORY);+ doReturn(36000L).when(config).get(TREE_LOCK_CLEAN_INTERVAL);+ FieldUtils.writeField(GravitinoEnv.getInstance(), "lockManager", new LockManager(config), true);+NameIdentifier ident = NameIdentifier.of(metalake, catalog);Map<String, String> props = ImmutableMap.of("key1", "value1", "key2", "value2");catalogManager.createCatalog(ident, Catalog.Type.RELATIONAL, "test", "comment", props);diff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/CatalogOperations.java b/server/src/main/java/org/apache/gravitino/server/web/rest/CatalogOperations.javaindex ba934d5bdc..5a1ebcaded 100644--- a/server/src/main/java/org/apache/gravitino/server/web/rest/CatalogOperations.java+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/CatalogOperations.java@@ -51,8 +51,6 @@ import org.apache.gravitino.dto.responses.CatalogResponse;import org.apache.gravitino.dto.responses.DropResponse;import org.apache.gravitino.dto.responses.EntityListResponse;import org.apache.gravitino.dto.util.DTOConverters;-import org.apache.gravitino.lock.LockType;-import org.apache.gravitino.lock.TreeLockUtils;import org.apache.gravitino.metrics.MetricNames;import org.apache.gravitino.server.web.Utils;import org.apache.gravitino.utils.NameIdentifierUtil;@@ -93,23 +91,17 @@ public class CatalogOperations {() -> {Namespace catalogNS = NamespaceUtil.ofCatalog(metalake);// Lock the root and the metalake with WRITE lock to ensure the consistency of the list.- return TreeLockUtils.doWithTreeLock(- NameIdentifier.of(metalake),- LockType.READ,- () -> {- if (verbose) {- Catalog[] catalogs = catalogDispatcher.listCatalogsInfo(catalogNS);- Response response =- Utils.ok(new CatalogListResponse(DTOConverters.toDTOs(catalogs)));- LOG.info("List {} catalogs info under metalake: {}", catalogs.length, metalake);- return response;- } else {- NameIdentifier[] idents = catalogDispatcher.listCatalogs(catalogNS);- Response response = Utils.ok(new EntityListResponse(idents));- LOG.info("List {} catalogs under metalake: {}", idents.length, metalake);- return response;- }- });+ if (verbose) {+ Catalog[] catalogs = catalogDispatcher.listCatalogsInfo(catalogNS);+ Response response = Utils.ok(new CatalogListResponse(DTOConverters.toDTOs(catalogs)));+ LOG.info("List {} catalogs info under metalake: {}", catalogs.length, metalake);+ return response;+ } else {+ NameIdentifier[] idents = catalogDispatcher.listCatalogs(catalogNS);+ Response response = Utils.ok(new EntityListResponse(idents));+ LOG.info("List {} catalogs under metalake: {}", idents.length, metalake);+ return response;+ }});} catch (Exception e) {return ExceptionHandlers.handleCatalogException(OperationType.LIST, "", metalake, e);@@ -130,16 +122,12 @@ public class CatalogOperations {request.validate();NameIdentifier ident = NameIdentifierUtil.ofCatalog(metalake, request.getName());Catalog catalog =- TreeLockUtils.doWithTreeLock(- NameIdentifierUtil.ofMetalake(metalake),- LockType.WRITE,- () ->- catalogDispatcher.createCatalog(- ident,- request.getType(),- request.getProvider(),- request.getComment(),- request.getProperties()));+ catalogDispatcher.createCatalog(+ ident,+ request.getType(),+ request.getProvider(),+ request.getComment(),+ request.getProperties());Response response = Utils.ok(new CatalogResponse(DTOConverters.toDTO(catalog)));LOG.info("Catalog created: {}.{}", metalake, catalog.name());return response;@@ -165,18 +153,12 @@ public class CatalogOperations {() -> {request.validate();NameIdentifier ident = NameIdentifierUtil.ofCatalog(metalake, request.getName());- TreeLockUtils.doWithTreeLock(- NameIdentifierUtil.ofMetalake(metalake),- LockType.READ,- () -> {- catalogDispatcher.testConnection(- ident,- request.getType(),- request.getProvider(),- request.getComment(),- request.getProperties());- return null;- });+ catalogDispatcher.testConnection(+ ident,+ request.getType(),+ request.getProvider(),+ request.getComment(),+ request.getProperties());Response response = Utils.ok(new BaseResponse());LOG.info("Successfully test connection for catalog: {}.{}", metalake, request.getName());@@ -204,17 +186,12 @@ public class CatalogOperations {httpRequest,() -> {NameIdentifier ident = NameIdentifierUtil.ofCatalog(metalake, catalogName);- TreeLockUtils.doWithTreeLock(- NameIdentifierUtil.ofMetalake(metalake),- LockType.WRITE,- () -> {- if (request.isInUse()) {- catalogDispatcher.enableCatalog(ident);- } else {- catalogDispatcher.disableCatalog(ident);- }- return null;- });+ if (request.isInUse()) {+ catalogDispatcher.enableCatalog(ident);+ } else {+ catalogDispatcher.disableCatalog(ident);+ }+Response response = Utils.ok(new BaseResponse());LOG.info("Successfully {} catalog: {}.{}",@@ -245,9 +222,7 @@ public class CatalogOperations {LOG.info("Received load catalog request for catalog: {}.{}", metalakeName, catalogName);try {NameIdentifier ident = NameIdentifierUtil.ofCatalog(metalakeName, catalogName);- Catalog catalog =- TreeLockUtils.doWithTreeLock(- ident, LockType.READ, () -> catalogDispatcher.loadCatalog(ident));+ Catalog catalog = catalogDispatcher.loadCatalog(ident);Response response = Utils.ok(new CatalogResponse(DTOConverters.toDTO(catalog)));LOG.info("Catalog loaded: {}.{}", metalakeName, catalogName);return response;@@ -278,11 +253,7 @@ public class CatalogOperations {request.getUpdates().stream().map(CatalogUpdateRequest::catalogChange).toArray(CatalogChange[]::new);- Catalog catalog =- TreeLockUtils.doWithTreeLock(- NameIdentifierUtil.ofMetalake(metalakeName),- LockType.WRITE,- () -> catalogDispatcher.alterCatalog(ident, changes));+ Catalog catalog = catalogDispatcher.alterCatalog(ident, changes);Response response = Utils.ok(new CatalogResponse(DTOConverters.toDTO(catalog)));LOG.info("Catalog altered: {}.{}", metalakeName, catalog.name());return response;@@ -309,11 +280,7 @@ public class CatalogOperations {httpRequest,() -> {NameIdentifier ident = NameIdentifierUtil.ofCatalog(metalakeName, catalogName);- boolean dropped =- TreeLockUtils.doWithTreeLock(- NameIdentifierUtil.ofMetalake(metalakeName),- LockType.WRITE,- () -> catalogDispatcher.dropCatalog(ident, force));+ boolean dropped = catalogDispatcher.dropCatalog(ident, force);if (!dropped) {LOG.warn("Failed to drop catalog {} under metalake {}", catalogName, metalakeName);}diff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/FilesetOperations.java b/server/src/main/java/org/apache/gravitino/server/web/rest/FilesetOperations.javaindex b010f26097..713ba0c8eb 100644--- a/server/src/main/java/org/apache/gravitino/server/web/rest/FilesetOperations.java+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/FilesetOperations.java@@ -49,8 +49,6 @@ import org.apache.gravitino.dto.responses.FilesetResponse;import org.apache.gravitino.dto.util.DTOConverters;import org.apache.gravitino.file.Fileset;import org.apache.gravitino.file.FilesetChange;-import org.apache.gravitino.lock.LockType;-import org.apache.gravitino.lock.TreeLockUtils;import org.apache.gravitino.metrics.MetricNames;import org.apache.gravitino.rest.RESTUtils;import org.apache.gravitino.server.web.Utils;@@ -87,11 +85,7 @@ public class FilesetOperations {httpRequest,() -> {Namespace filesetNS = NamespaceUtil.ofFileset(metalake, catalog, schema);- NameIdentifier[] idents =- TreeLockUtils.doWithTreeLock(- NameIdentifier.of(metalake, catalog, schema),- LockType.READ,- () -> dispatcher.listFilesets(filesetNS));+ NameIdentifier[] idents = dispatcher.listFilesets(filesetNS);Response response = Utils.ok(new EntityListResponse(idents));LOG.info("List {} filesets under schema: {}.{}.{}",@@ -131,16 +125,12 @@ public class FilesetOperations {NameIdentifierUtil.ofFileset(metalake, catalog, schema, request.getName());Fileset fileset =- TreeLockUtils.doWithTreeLock(- NameIdentifierUtil.ofSchema(metalake, catalog, schema),- LockType.WRITE,- () ->- dispatcher.createFileset(- ident,- request.getComment(),- Optional.ofNullable(request.getType()).orElse(Fileset.Type.MANAGED),- request.getStorageLocation(),- request.getProperties()));+ dispatcher.createFileset(+ ident,+ request.getComment(),+ Optional.ofNullable(request.getType()).orElse(Fileset.Type.MANAGED),+ request.getStorageLocation(),+ request.getProperties());Response response = Utils.ok(new FilesetResponse(DTOConverters.toDTO(fileset)));LOG.info("Fileset created: {}.{}.{}.{}", metalake, catalog, schema, request.getName());return response;@@ -168,9 +158,7 @@ public class FilesetOperations {httpRequest,() -> {NameIdentifier ident = NameIdentifierUtil.ofFileset(metalake, catalog, schema, fileset);- Fileset t =- TreeLockUtils.doWithTreeLock(- ident, LockType.READ, () -> dispatcher.loadFileset(ident));+ Fileset t = dispatcher.loadFileset(ident);Response response = Utils.ok(new FilesetResponse(DTOConverters.toDTO(t)));LOG.info("Fileset loaded: {}.{}.{}.{}", metalake, catalog, schema, fileset);return response;@@ -202,11 +190,7 @@ public class FilesetOperations {request.getUpdates().stream().map(FilesetUpdateRequest::filesetChange).toArray(FilesetChange[]::new);- Fileset t =- TreeLockUtils.doWithTreeLock(- NameIdentifierUtil.ofSchema(metalake, catalog, schema),- LockType.WRITE,- () -> dispatcher.alterFileset(ident, changes));+ Fileset t = dispatcher.alterFileset(ident, changes);Response response = Utils.ok(new FilesetResponse(DTOConverters.toDTO(t)));LOG.info("Fileset altered: {}.{}.{}.{}", metalake, catalog, schema, t.name());return response;@@ -233,11 +217,7 @@ public class FilesetOperations {httpRequest,() -> {NameIdentifier ident = NameIdentifierUtil.ofFileset(metalake, catalog, schema, fileset);- boolean dropped =- TreeLockUtils.doWithTreeLock(- NameIdentifierUtil.ofSchema(metalake, catalog, schema),- LockType.WRITE,- () -> dispatcher.dropFileset(ident));+ boolean dropped = dispatcher.dropFileset(ident);if (!dropped) {LOG.warn("Failed to drop fileset {} under schema {}", fileset, schema);}@@ -283,10 +263,7 @@ public class FilesetOperations {CallerContext.CallerContextHolder.set(context);}String actualFileLocation =- TreeLockUtils.doWithTreeLock(- ident,- LockType.READ,- () -> dispatcher.getFileLocation(ident, RESTUtils.decodeString(subPath)));+ dispatcher.getFileLocation(ident, RESTUtils.decodeString(subPath));return Utils.ok(new FileLocationResponse(actualFileLocation));});} catch (Exception e) {diff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/GroupOperations.java b/server/src/main/java/org/apache/gravitino/server/web/rest/GroupOperations.javaindex 95db0ca67f..e157edc46a 100644--- a/server/src/main/java/org/apache/gravitino/server/web/rest/GroupOperations.java+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/GroupOperations.java@@ -32,18 +32,14 @@ import javax.ws.rs.QueryParam;import javax.ws.rs.core.Context;import javax.ws.rs.core.Response;import org.apache.gravitino.GravitinoEnv;-import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.Namespace;import org.apache.gravitino.authorization.AccessControlDispatcher;-import org.apache.gravitino.authorization.AuthorizationUtils;import org.apache.gravitino.dto.requests.GroupAddRequest;import org.apache.gravitino.dto.responses.GroupListResponse;import org.apache.gravitino.dto.responses.GroupResponse;import org.apache.gravitino.dto.responses.NameListResponse;import org.apache.gravitino.dto.responses.RemoveResponse;import org.apache.gravitino.dto.util.DTOConverters;-import org.apache.gravitino.lock.LockType;-import org.apache.gravitino.lock.TreeLockUtils;import org.apache.gravitino.metrics.MetricNames;import org.apache.gravitino.server.authorization.NameBindings;import org.apache.gravitino.server.web.Utils;@@ -78,14 +74,9 @@ public class GroupOperations {return Utils.doAs(httpRequest,() ->- TreeLockUtils.doWithTreeLock(- AuthorizationUtils.ofGroup(metalake, group),- LockType.READ,- () ->- Utils.ok(- new GroupResponse(- DTOConverters.toDTO(- accessControlManager.getGroup(metalake, group))))));+ Utils.ok(+ new GroupResponse(+ DTOConverters.toDTO(accessControlManager.getGroup(metalake, group)))));} catch (Exception e) {return ExceptionHandlers.handleGroupException(OperationType.GET, group, metalake, e);}@@ -99,17 +90,13 @@ public class GroupOperations {try {return Utils.doAs(httpRequest,- () ->- TreeLockUtils.doWithTreeLock(- NameIdentifier.of(AuthorizationUtils.ofGroupNamespace(metalake).levels()),- LockType.WRITE,- () -> {- request.validate();- return Utils.ok(- new GroupResponse(- DTOConverters.toDTO(- accessControlManager.addGroup(metalake, request.getName()))));- }));+ () -> {+ request.validate();+ return Utils.ok(+ new GroupResponse(+ DTOConverters.toDTO(+ accessControlManager.addGroup(metalake, request.getName()))));+ });} catch (Exception e) {return ExceptionHandlers.handleGroupException(OperationType.ADD, request.getName(), metalake, e);@@ -127,11 +114,7 @@ public class GroupOperations {return Utils.doAs(httpRequest,() -> {- boolean removed =- TreeLockUtils.doWithTreeLock(- NameIdentifier.of(AuthorizationUtils.ofGroupNamespace(metalake).levels()),- LockType.WRITE,- () -> accessControlManager.removeGroup(metalake, group));+ boolean removed = accessControlManager.removeGroup(metalake, group);if (!removed) {LOG.warn("Failed to remove group {} under metalake {}", group, metalake);}diff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/MetadataObjectRoleOperations.java b/server/src/main/java/org/apache/gravitino/server/web/rest/MetadataObjectRoleOperations.javaindex ad27b22a3e..39ddb35343 100644--- a/server/src/main/java/org/apache/gravitino/server/web/rest/MetadataObjectRoleOperations.java+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/MetadataObjectRoleOperations.java@@ -31,15 +31,11 @@ import javax.ws.rs.core.Response;import org.apache.gravitino.GravitinoEnv;import org.apache.gravitino.MetadataObject;import org.apache.gravitino.MetadataObjects;-import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.authorization.AccessControlDispatcher;import org.apache.gravitino.dto.responses.NameListResponse;-import org.apache.gravitino.lock.LockType;-import org.apache.gravitino.lock.TreeLockUtils;import org.apache.gravitino.metrics.MetricNames;import org.apache.gravitino.server.authorization.NameBindings;import org.apache.gravitino.server.web.Utils;-import org.apache.gravitino.utils.MetadataObjectUtil;@NameBindings.AccessControlInterfaces@Path("/metalakes/{metalake}/objects/{type}/{fullName}/roles")@@ -70,18 +66,12 @@ public class MetadataObjectRoleOperations {MetadataObjects.parse(fullName, MetadataObject.Type.valueOf(type.toUpperCase(Locale.ROOT)));- NameIdentifier identifier = MetadataObjectUtil.toEntityIdent(metalake, object);return Utils.doAs(httpRequest,- () ->- TreeLockUtils.doWithTreeLock(- identifier,- LockType.READ,- () -> {- String[] names =- accessControlDispatcher.listRoleNamesByObject(metalake, object);- return Utils.ok(new NameListResponse(names));- }));+ () -> {+ String[] names = accessControlDispatcher.listRoleNamesByObject(metalake, object);+ return Utils.ok(new NameListResponse(names));+ });} catch (Exception e) {return ExceptionHandlers.handleRoleException(OperationType.LIST, "", metalake, e);}diff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/MetalakeOperations.java b/server/src/main/java/org/apache/gravitino/server/web/rest/MetalakeOperations.javaindex e28f28f15e..827c7a0b9d 100644--- a/server/src/main/java/org/apache/gravitino/server/web/rest/MetalakeOperations.java+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/MetalakeOperations.java@@ -51,8 +51,6 @@ import org.apache.gravitino.dto.responses.DropResponse;import org.apache.gravitino.dto.responses.MetalakeListResponse;import org.apache.gravitino.dto.responses.MetalakeResponse;import org.apache.gravitino.dto.util.DTOConverters;-import org.apache.gravitino.lock.LockType;-import org.apache.gravitino.lock.TreeLockUtils;import org.apache.gravitino.metalake.MetalakeDispatcher;import org.apache.gravitino.metrics.MetricNames;import org.apache.gravitino.server.web.Utils;@@ -86,8 +84,7 @@ public class MetalakeOperations {return Utils.doAs(httpRequest,() -> {- Metalake[] metalakes =- TreeLockUtils.doWithRootTreeLock(LockType.READ, metalakeDispatcher::listMetalakes);+ Metalake[] metalakes = metalakeDispatcher.listMetalakes();MetalakeDTO[] metalakeDTOs =Arrays.stream(metalakes).map(DTOConverters::toDTO).toArray(MetalakeDTO[]::new);Response response = Utils.ok(new MetalakeListResponse(metalakeDTOs));@@ -114,11 +111,8 @@ public class MetalakeOperations {request.validate();NameIdentifier ident = NameIdentifierUtil.ofMetalake(request.getName());Metalake metalake =- TreeLockUtils.doWithRootTreeLock(- LockType.WRITE,- () ->- metalakeDispatcher.createMetalake(- ident, request.getComment(), request.getProperties()));+ metalakeDispatcher.createMetalake(+ ident, request.getComment(), request.getProperties());Response response = Utils.ok(new MetalakeResponse(DTOConverters.toDTO(metalake)));LOG.info("Metalake created: {}", metalake.name());return response;@@ -141,9 +135,7 @@ public class MetalakeOperations {httpRequest,() -> {NameIdentifier identifier = NameIdentifierUtil.ofMetalake(metalakeName);- Metalake metalake =- TreeLockUtils.doWithTreeLock(- identifier, LockType.READ, () -> metalakeDispatcher.loadMetalake(identifier));+ Metalake metalake = metalakeDispatcher.loadMetalake(identifier);Response response = Utils.ok(new MetalakeResponse(DTOConverters.toDTO(metalake)));LOG.info("Metalake loaded: {}", metalake.name());return response;@@ -166,17 +158,11 @@ public class MetalakeOperations {httpRequest,() -> {NameIdentifier identifier = NameIdentifierUtil.ofMetalake(metalakeName);- TreeLockUtils.doWithTreeLock(- identifier,- LockType.WRITE,- () -> {- if (request.isInUse()) {- metalakeDispatcher.enableMetalake(identifier);- } else {- metalakeDispatcher.disableMetalake(identifier);- }- return null;- });+ if (request.isInUse()) {+ metalakeDispatcher.enableMetalake(identifier);+ } else {+ metalakeDispatcher.disableMetalake(identifier);+ }Response response = Utils.ok(new BaseResponse());LOG.info("Successfully {} metalake: {}",@@ -209,9 +195,7 @@ public class MetalakeOperations {updatesRequest.getUpdates().stream().map(MetalakeUpdateRequest::metalakeChange).toArray(MetalakeChange[]::new);- Metalake updatedMetalake =- TreeLockUtils.doWithRootTreeLock(- LockType.WRITE, () -> metalakeDispatcher.alterMetalake(identifier, changes));+ Metalake updatedMetalake = metalakeDispatcher.alterMetalake(identifier, changes);Response response =Utils.ok(new MetalakeResponse(DTOConverters.toDTO(updatedMetalake)));LOG.info("Metalake altered: {}", updatedMetalake.name());@@ -237,9 +221,7 @@ public class MetalakeOperations {httpRequest,() -> {NameIdentifier identifier = NameIdentifierUtil.ofMetalake(metalakeName);- boolean dropped =- TreeLockUtils.doWithRootTreeLock(- LockType.WRITE, () -> metalakeDispatcher.dropMetalake(identifier, force));+ boolean dropped = metalakeDispatcher.dropMetalake(identifier, force);if (!dropped) {LOG.warn("Failed to drop metalake by name {}", metalakeName);}diff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/OwnerOperations.java b/server/src/main/java/org/apache/gravitino/server/web/rest/OwnerOperations.javaindex 7dcfcfd067..001770f6a5 100644--- a/server/src/main/java/org/apache/gravitino/server/web/rest/OwnerOperations.java+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/OwnerOperations.java@@ -33,15 +33,12 @@ import javax.ws.rs.core.Response;import org.apache.gravitino.GravitinoEnv;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.OwnerManager;import org.apache.gravitino.dto.requests.OwnerSetRequest;import org.apache.gravitino.dto.responses.OwnerResponse;import org.apache.gravitino.dto.responses.SetResponse;import org.apache.gravitino.dto.util.DTOConverters;-import org.apache.gravitino.lock.LockType;-import org.apache.gravitino.lock.TreeLockUtils;import org.apache.gravitino.metrics.MetricNames;import org.apache.gravitino.server.authorization.NameBindings;import org.apache.gravitino.server.web.Utils;@@ -79,10 +76,7 @@ public class OwnerOperations {httpRequest,() -> {MetadataObjectUtil.checkMetadataObject(metalake, object);- NameIdentifier ident = MetadataObjectUtil.toEntityIdent(metalake, object);- Optional<Owner> owner =- TreeLockUtils.doWithTreeLock(- ident, LockType.READ, () -> ownerManager.getOwner(metalake, object));+ Optional<Owner> owner = ownerManager.getOwner(metalake, object);if (owner.isPresent()) {return Utils.ok(new OwnerResponse(DTOConverters.toDTO(owner.get())));} else {@@ -115,14 +109,7 @@ public class OwnerOperations {() -> {request.validate();MetadataObjectUtil.checkMetadataObject(metalake, object);- NameIdentifier objectIdent = MetadataObjectUtil.toEntityIdent(metalake, object);- TreeLockUtils.doWithTreeLock(- objectIdent,- LockType.READ,- () -> {- ownerManager.setOwner(metalake, object, request.getName(), request.getType());- return null;- });+ ownerManager.setOwner(metalake, object, request.getName(), request.getType());return Utils.ok(new SetResponse(true));});} catch (Exception e) {diff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/PartitionOperations.java b/server/src/main/java/org/apache/gravitino/server/web/rest/PartitionOperations.javaindex 4c488db7cb..5f545f745a 100644--- a/server/src/main/java/org/apache/gravitino/server/web/rest/PartitionOperations.java+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/PartitionOperations.java@@ -45,8 +45,6 @@ import org.apache.gravitino.dto.responses.PartitionListResponse;import org.apache.gravitino.dto.responses.PartitionNameListResponse;import org.apache.gravitino.dto.responses.PartitionResponse;import org.apache.gravitino.dto.util.DTOConverters;-import org.apache.gravitino.lock.LockType;-import org.apache.gravitino.lock.TreeLockUtils;import org.apache.gravitino.metrics.MetricNames;import org.apache.gravitino.rel.partitions.Partition;import org.apache.gravitino.server.web.Utils;@@ -87,34 +85,29 @@ public class PartitionOperations {httpRequest,() -> {NameIdentifier tableIdent = NameIdentifier.of(metalake, catalog, schema, table);- return TreeLockUtils.doWithTreeLock(- tableIdent,- LockType.READ,- () -> {- if (verbose) {- Partition[] partitions = dispatcher.listPartitions(tableIdent);- Response response = Utils.ok(new PartitionListResponse(toDTOs(partitions)));- LOG.info(- "List {} partitions in table {}.{}.{}.{}",- partitions.length,- metalake,- catalog,- schema,- table);- return response;- } else {- String[] partitionNames = dispatcher.listPartitionNames(tableIdent);- Response response = Utils.ok(new PartitionNameListResponse((partitionNames)));- LOG.info(- "List {} partition names in table {}.{}.{}.{}",- partitionNames.length,- metalake,- catalog,- schema,- table);- return response;- }- });+ if (verbose) {+ Partition[] partitions = dispatcher.listPartitions(tableIdent);+ Response response = Utils.ok(new PartitionListResponse(toDTOs(partitions)));+ LOG.info(+ "List {} partitions in table {}.{}.{}.{}",+ partitions.length,+ metalake,+ catalog,+ schema,+ table);+ return response;+ } else {+ String[] partitionNames = dispatcher.listPartitionNames(tableIdent);+ Response response = Utils.ok(new PartitionNameListResponse((partitionNames)));+ LOG.info(+ "List {} partition names in table {}.{}.{}.{}",+ partitionNames.length,+ metalake,+ catalog,+ schema,+ table);+ return response;+ }});} catch (Exception e) {return ExceptionHandlers.handlePartitionException(OperationType.LIST, "", table, e);@@ -144,21 +137,16 @@ public class PartitionOperations {httpRequest,() -> {NameIdentifier tableIdent = NameIdentifier.of(metalake, catalog, schema, table);- return TreeLockUtils.doWithTreeLock(- tableIdent,- LockType.READ,- () -> {- Partition p = dispatcher.getPartition(tableIdent, partition);- Response response = Utils.ok(new PartitionResponse(DTOConverters.toDTO(p)));- LOG.info(- "Got partition[{}] in table[{}.{}.{}.{}]",- partition,- metalake,- catalog,- schema,- table);- return response;- });+ Partition p = dispatcher.getPartition(tableIdent, partition);+ Response response = Utils.ok(new PartitionResponse(DTOConverters.toDTO(p)));+ LOG.info(+ "Got partition[{}] in table[{}.{}.{}.{}]",+ partition,+ metalake,+ catalog,+ schema,+ table);+ return response;});} catch (Exception e) {return ExceptionHandlers.handlePartitionException(OperationType.GET, "", table, e);@@ -190,24 +178,12 @@ public class PartitionOperations {httpRequest,() -> {NameIdentifier tableIdent = NameIdentifier.of(metalake, catalog, schema, table);- return TreeLockUtils.doWithTreeLock(- tableIdent,- LockType.WRITE,- () -> {- Partition p =- dispatcher.addPartition(tableIdent, fromDTO(request.getPartitions()[0]));- Response response =- Utils.ok(- new PartitionListResponse(new PartitionDTO[] {DTOConverters.toDTO(p)}));- LOG.info(- "Added {} partition(s) to table {}.{}.{}.{} ",- 1,- metalake,- catalog,- schema,- table);- return response;- });+ Partition p = dispatcher.addPartition(tableIdent, fromDTO(request.getPartitions()[0]));+ Response response =+ Utils.ok(new PartitionListResponse(new PartitionDTO[] {DTOConverters.toDTO(p)}));+ LOG.info(+ "Added {} partition(s) to table {}.{}.{}.{} ", 1, metalake, catalog, schema, table);+ return response;});} catch (Exception e) {return ExceptionHandlers.handlePartitionException(OperationType.CREATE, "", table, e);@@ -239,32 +215,27 @@ public class PartitionOperations {httpRequest,() -> {NameIdentifier tableIdent = NameIdentifier.of(metalake, catalog, schema, table);- return TreeLockUtils.doWithTreeLock(- tableIdent,- LockType.WRITE,- () -> {- boolean dropped =- purge- ? dispatcher.purgePartition(tableIdent, partition)- : dispatcher.dropPartition(tableIdent, partition);- if (!dropped) {- LOG.warn(- "Failed to drop partition {} under table {} under schema {}",- partition,- table,- schema);- }- Response response = Utils.ok(new DropResponse(dropped));- LOG.info(- "Partition {} {} in table {}.{}.{}.{}",- partition,- purge ? "purged" : "dropped",- metalake,- catalog,- schema,- table);- return response;- });+ boolean dropped =+ purge+ ? dispatcher.purgePartition(tableIdent, partition)+ : dispatcher.dropPartition(tableIdent, partition);+ if (!dropped) {+ LOG.warn(+ "Failed to drop partition {} under table {} under schema {}",+ partition,+ table,+ schema);+ }+ Response response = Utils.ok(new DropResponse(dropped));+ LOG.info(+ "Partition {} {} in table {}.{}.{}.{}",+ partition,+ purge ? "purged" : "dropped",+ metalake,+ catalog,+ schema,+ table);+ return response;});} catch (Exception e) {return ExceptionHandlers.handlePartitionException(OperationType.DROP, "", table, e);diff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/PermissionOperations.java b/server/src/main/java/org/apache/gravitino/server/web/rest/PermissionOperations.javaindex 3f89cc7eea..8ef902a994 100644--- a/server/src/main/java/org/apache/gravitino/server/web/rest/PermissionOperations.java+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/PermissionOperations.java@@ -33,7 +33,6 @@ import org.apache.commons.lang3.StringUtils;import org.apache.gravitino.GravitinoEnv;import org.apache.gravitino.MetadataObject;import org.apache.gravitino.MetadataObjects;-import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.authorization.AccessControlDispatcher;import org.apache.gravitino.authorization.AuthorizationUtils;import org.apache.gravitino.dto.authorization.PrivilegeDTO;@@ -45,8 +44,6 @@ import org.apache.gravitino.dto.responses.GroupResponse;import org.apache.gravitino.dto.responses.RoleResponse;import org.apache.gravitino.dto.responses.UserResponse;import org.apache.gravitino.dto.util.DTOConverters;-import org.apache.gravitino.lock.LockType;-import org.apache.gravitino.lock.TreeLockUtils;import org.apache.gravitino.metrics.MetricNames;import org.apache.gravitino.server.authorization.NameBindings;import org.apache.gravitino.server.web.Utils;@@ -79,22 +76,14 @@ public class PermissionOperations {try {return Utils.doAs(httpRequest,- () ->- TreeLockUtils.doWithTreeLock(- AuthorizationUtils.ofUser(metalake, user),- LockType.WRITE,- () ->- TreeLockUtils.doWithTreeLock(- NameIdentifier.of(AuthorizationUtils.ofRoleNamespace(metalake).levels()),- LockType.READ,- () -> {- request.validate();- return Utils.ok(- new UserResponse(- DTOConverters.toDTO(- accessControlManager.grantRolesToUser(- metalake, request.getRoleNames(), user))));- })));+ () -> {+ request.validate();+ return Utils.ok(+ new UserResponse(+ DTOConverters.toDTO(+ accessControlManager.grantRolesToUser(+ metalake, request.getRoleNames(), user))));+ });} catch (Exception e) {return ExceptionHandlers.handleUserPermissionOperationException(OperationType.GRANT, StringUtils.join(request.getRoleNames(), ","), user, e);@@ -113,22 +102,14 @@ public class PermissionOperations {try {return Utils.doAs(httpRequest,- () ->- TreeLockUtils.doWithTreeLock(- AuthorizationUtils.ofGroup(metalake, group),- LockType.WRITE,- () ->- TreeLockUtils.doWithTreeLock(- NameIdentifier.of(AuthorizationUtils.ofRoleNamespace(metalake).levels()),- LockType.READ,- () -> {- request.validate();- return Utils.ok(- new GroupResponse(- DTOConverters.toDTO(- accessControlManager.grantRolesToGroup(- metalake, request.getRoleNames(), group))));- })));+ () -> {+ request.validate();+ return Utils.ok(+ new GroupResponse(+ DTOConverters.toDTO(+ accessControlManager.grantRolesToGroup(+ metalake, request.getRoleNames(), group))));+ });} catch (Exception e) {return ExceptionHandlers.handleGroupPermissionOperationException(OperationType.GRANT, StringUtils.join(request.getRoleNames(), ","), group, e);@@ -147,22 +128,14 @@ public class PermissionOperations {try {return Utils.doAs(httpRequest,- () ->- TreeLockUtils.doWithTreeLock(- AuthorizationUtils.ofUser(metalake, user),- LockType.WRITE,- () ->- TreeLockUtils.doWithTreeLock(- NameIdentifier.of(AuthorizationUtils.ofRoleNamespace(metalake).levels()),- LockType.READ,- () -> {- request.validate();- return Utils.ok(- new UserResponse(- DTOConverters.toDTO(- accessControlManager.revokeRolesFromUser(- metalake, request.getRoleNames(), user))));- })));+ () -> {+ request.validate();+ return Utils.ok(+ new UserResponse(+ DTOConverters.toDTO(+ accessControlManager.revokeRolesFromUser(+ metalake, request.getRoleNames(), user))));+ });} catch (Exception e) {return ExceptionHandlers.handleUserPermissionOperationException(OperationType.REVOKE, StringUtils.join(request.getRoleNames(), ","), user, e);@@ -181,22 +154,14 @@ public class PermissionOperations {try {return Utils.doAs(httpRequest,- () ->- TreeLockUtils.doWithTreeLock(- AuthorizationUtils.ofGroup(metalake, group),- LockType.WRITE,- () ->- TreeLockUtils.doWithTreeLock(- NameIdentifier.of(AuthorizationUtils.ofRoleNamespace(metalake).levels()),- LockType.READ,- () -> {- request.validate();- return Utils.ok(- new GroupResponse(- DTOConverters.toDTO(- accessControlManager.revokeRolesFromGroup(- metalake, request.getRoleNames(), group))));- })));+ () -> {+ request.validate();+ return Utils.ok(+ new GroupResponse(+ DTOConverters.toDTO(+ accessControlManager.revokeRolesFromGroup(+ metalake, request.getRoleNames(), group))));+ });} catch (Exception e) {return ExceptionHandlers.handleGroupPermissionOperationException(OperationType.REVOKE, StringUtils.join(request.getRoleNames()), group, e);@@ -229,20 +194,16 @@ public class PermissionOperations {}MetadataObjectUtil.checkMetadataObject(metalake, object);- return TreeLockUtils.doWithTreeLock(- AuthorizationUtils.ofRole(metalake, role),- LockType.WRITE,- () ->- Utils.ok(- new RoleResponse(- DTOConverters.toDTO(- accessControlManager.grantPrivilegeToRole(- metalake,- role,- object,- privilegeGrantRequest.getPrivileges().stream()- .map(DTOConverters::fromPrivilegeDTO)- .collect(Collectors.toSet()))))));+ return Utils.ok(+ new RoleResponse(+ DTOConverters.toDTO(+ accessControlManager.grantPrivilegeToRole(+ metalake,+ role,+ object,+ privilegeGrantRequest.getPrivileges().stream()+ .map(DTOConverters::fromPrivilegeDTO)+ .collect(Collectors.toSet())))));});} catch (Exception e) {return ExceptionHandlers.handleRolePermissionOperationException(@@ -276,20 +237,16 @@ public class PermissionOperations {}MetadataObjectUtil.checkMetadataObject(metalake, object);- return TreeLockUtils.doWithTreeLock(- AuthorizationUtils.ofRole(metalake, role),- LockType.WRITE,- () ->- Utils.ok(- new RoleResponse(- DTOConverters.toDTO(- accessControlManager.revokePrivilegesFromRole(- metalake,- role,- object,- privilegeRevokeRequest.getPrivileges().stream()- .map(DTOConverters::fromPrivilegeDTO)- .collect(Collectors.toSet()))))));+ return Utils.ok(+ new RoleResponse(+ DTOConverters.toDTO(+ accessControlManager.revokePrivilegesFromRole(+ metalake,+ role,+ object,+ privilegeRevokeRequest.getPrivileges().stream()+ .map(DTOConverters::fromPrivilegeDTO)+ .collect(Collectors.toSet())))));});} catch (Exception e) {return ExceptionHandlers.handleRolePermissionOperationException(diff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/RoleOperations.java b/server/src/main/java/org/apache/gravitino/server/web/rest/RoleOperations.javaindex 9690afe13f..844547853f 100644--- a/server/src/main/java/org/apache/gravitino/server/web/rest/RoleOperations.java+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/RoleOperations.java@@ -37,7 +37,6 @@ import javax.ws.rs.core.Response;import org.apache.gravitino.GravitinoEnv;import org.apache.gravitino.MetadataObject;import org.apache.gravitino.MetadataObjects;-import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.authorization.AccessControlDispatcher;import org.apache.gravitino.authorization.AuthorizationUtils;import org.apache.gravitino.authorization.Privilege;@@ -52,8 +51,6 @@ import org.apache.gravitino.dto.responses.RoleResponse;import org.apache.gravitino.dto.util.DTOConverters;import org.apache.gravitino.exceptions.IllegalMetadataObjectException;import org.apache.gravitino.exceptions.NoSuchMetadataObjectException;-import org.apache.gravitino.lock.LockType;-import org.apache.gravitino.lock.TreeLockUtils;import org.apache.gravitino.metrics.MetricNames;import org.apache.gravitino.server.authorization.NameBindings;import org.apache.gravitino.server.web.Utils;@@ -82,14 +79,10 @@ public class RoleOperations {try {return Utils.doAs(httpRequest,- () ->- TreeLockUtils.doWithTreeLock(- NameIdentifier.of(metalake),- LockType.READ,- () -> {- String[] names = accessControlManager.listRoleNames(metalake);- return Utils.ok(new NameListResponse(names));- }));+ () -> {+ String[] names = accessControlManager.listRoleNames(metalake);+ return Utils.ok(new NameListResponse(names));+ });} catch (Exception e) {return ExceptionHandlers.handleRoleException(OperationType.LIST, "", metalake, e);}@@ -105,13 +98,9 @@ public class RoleOperations {return Utils.doAs(httpRequest,() ->- TreeLockUtils.doWithTreeLock(- AuthorizationUtils.ofRole(metalake, role),- LockType.READ,- () ->- Utils.ok(- new RoleResponse(- DTOConverters.toDTO(accessControlManager.getRole(metalake, role))))));+ Utils.ok(+ new RoleResponse(+ DTOConverters.toDTO(accessControlManager.getRole(metalake, role)))));} catch (Exception e) {return ExceptionHandlers.handleRoleException(OperationType.GET, role, metalake, e);}@@ -167,19 +156,14 @@ public class RoleOperations {(PrivilegeDTO) privilege)).collect(Collectors.toList()))).collect(Collectors.toList());-- return TreeLockUtils.doWithTreeLock(- NameIdentifier.of(AuthorizationUtils.ofRoleNamespace(metalake).levels()),- LockType.WRITE,- () ->- Utils.ok(- new RoleResponse(- DTOConverters.toDTO(- accessControlManager.createRole(- metalake,- request.getName(),- request.getProperties(),- securableObjects)))));+ return Utils.ok(+ new RoleResponse(+ DTOConverters.toDTO(+ accessControlManager.createRole(+ metalake,+ request.getName(),+ request.getProperties(),+ securableObjects))));});} catch (Exception e) {@@ -199,11 +183,7 @@ public class RoleOperations {return Utils.doAs(httpRequest,() -> {- boolean deleted =- TreeLockUtils.doWithTreeLock(- NameIdentifier.of(AuthorizationUtils.ofRoleNamespace(metalake).levels()),- LockType.WRITE,- () -> accessControlManager.deleteRole(metalake, role));+ boolean deleted = accessControlManager.deleteRole(metalake, role);if (!deleted) {LOG.warn("Failed to delete role {} under metalake {}", role, metalake);}diff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/SchemaOperations.java b/server/src/main/java/org/apache/gravitino/server/web/rest/SchemaOperations.javaindex 55341627b9..9fda549ebf 100644--- a/server/src/main/java/org/apache/gravitino/server/web/rest/SchemaOperations.java+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/SchemaOperations.java@@ -47,8 +47,6 @@ import org.apache.gravitino.dto.responses.DropResponse;import org.apache.gravitino.dto.responses.EntityListResponse;import org.apache.gravitino.dto.responses.SchemaResponse;import org.apache.gravitino.dto.util.DTOConverters;-import org.apache.gravitino.lock.LockType;-import org.apache.gravitino.lock.TreeLockUtils;import org.apache.gravitino.metrics.MetricNames;import org.apache.gravitino.server.web.Utils;import org.apache.gravitino.utils.NameIdentifierUtil;@@ -84,11 +82,7 @@ public class SchemaOperations {httpRequest,() -> {Namespace schemaNS = NamespaceUtil.ofSchema(metalake, catalog);- NameIdentifier[] idents =- TreeLockUtils.doWithTreeLock(- NameIdentifier.of(metalake, catalog),- LockType.READ,- () -> dispatcher.listSchemas(schemaNS));+ NameIdentifier[] idents = dispatcher.listSchemas(schemaNS);Response response = Utils.ok(new EntityListResponse(idents));LOG.info("List {} schemas in catalog {}.{}", idents.length, metalake, catalog);return response;@@ -115,12 +109,7 @@ public class SchemaOperations {NameIdentifier ident =NameIdentifierUtil.ofSchema(metalake, catalog, request.getName());Schema schema =- TreeLockUtils.doWithTreeLock(- NameIdentifierUtil.ofCatalog(metalake, catalog),- LockType.WRITE,- () ->- dispatcher.createSchema(- ident, request.getComment(), request.getProperties()));+ dispatcher.createSchema(ident, request.getComment(), request.getProperties());Response response = Utils.ok(new SchemaResponse(DTOConverters.toDTO(schema)));LOG.info("Schema created: {}.{}.{}", metalake, catalog, schema.name());return response;@@ -179,11 +168,7 @@ public class SchemaOperations {request.getUpdates().stream().map(SchemaUpdateRequest::schemaChange).toArray(SchemaChange[]::new);- Schema s =- TreeLockUtils.doWithTreeLock(- NameIdentifierUtil.ofCatalog(metalake, catalog),- LockType.WRITE,- () -> dispatcher.alterSchema(ident, changes));+ Schema s = dispatcher.alterSchema(ident, changes);Response response = Utils.ok(new SchemaResponse(DTOConverters.toDTO(s)));LOG.info("Schema altered: {}.{}.{}", metalake, catalog, s.name());return response;diff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/TableOperations.java b/server/src/main/java/org/apache/gravitino/server/web/rest/TableOperations.javaindex 3d9d863e98..41146d2546 100644--- a/server/src/main/java/org/apache/gravitino/server/web/rest/TableOperations.java+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/TableOperations.java@@ -46,8 +46,6 @@ import org.apache.gravitino.dto.responses.DropResponse;import org.apache.gravitino.dto.responses.EntityListResponse;import org.apache.gravitino.dto.responses.TableResponse;import org.apache.gravitino.dto.util.DTOConverters;-import org.apache.gravitino.lock.LockType;-import org.apache.gravitino.lock.TreeLockUtils;import org.apache.gravitino.metrics.MetricNames;import org.apache.gravitino.rel.Table;import org.apache.gravitino.rel.TableChange;@@ -85,11 +83,7 @@ public class TableOperations {httpRequest,() -> {Namespace tableNS = NamespaceUtil.ofTable(metalake, catalog, schema);- NameIdentifier[] idents =- TreeLockUtils.doWithTreeLock(- NameIdentifier.of(metalake, catalog, schema),- LockType.READ,- () -> dispatcher.listTables(tableNS));+ NameIdentifier[] idents = dispatcher.listTables(tableNS);Response response = Utils.ok(new EntityListResponse(idents));LOG.info("List {} tables under schema: {}.{}.{}", idents.length, metalake, catalog, schema);@@ -190,11 +184,7 @@ public class TableOperations {request.getUpdates().stream().map(TableUpdateRequest::tableChange).toArray(TableChange[]::new);- Table t =- TreeLockUtils.doWithTreeLock(- NameIdentifier.of(metalake, catalog, schema),- LockType.WRITE,- () -> dispatcher.alterTable(ident, changes));+ Table t = dispatcher.alterTable(ident, changes);Response response = Utils.ok(new TableResponse(DTOConverters.toDTO(t)));LOG.info("Table altered: {}.{}.{}.{}", metalake, catalog, schema, t.name());return response;diff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/TopicOperations.java b/server/src/main/java/org/apache/gravitino/server/web/rest/TopicOperations.javaindex 4e9bcd5507..471a194a4f 100644--- a/server/src/main/java/org/apache/gravitino/server/web/rest/TopicOperations.java+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/TopicOperations.java@@ -41,8 +41,6 @@ import org.apache.gravitino.dto.responses.DropResponse;import org.apache.gravitino.dto.responses.EntityListResponse;import org.apache.gravitino.dto.responses.TopicResponse;import org.apache.gravitino.dto.util.DTOConverters;-import org.apache.gravitino.lock.LockType;-import org.apache.gravitino.lock.TreeLockUtils;import org.apache.gravitino.messaging.Topic;import org.apache.gravitino.messaging.TopicChange;import org.apache.gravitino.metrics.MetricNames;@@ -79,11 +77,7 @@ public class TopicOperations {() -> {LOG.info("Listing topics under schema: {}.{}.{}", metalake, catalog, schema);Namespace topicNS = NamespaceUtil.ofTopic(metalake, catalog, schema);- NameIdentifier[] topics =- TreeLockUtils.doWithTreeLock(- NameIdentifier.of(metalake, catalog, schema),- LockType.READ,- () -> dispatcher.listTopics(topicNS));+ NameIdentifier[] topics = dispatcher.listTopics(topicNS);Response response = Utils.ok(new EntityListResponse(topics));LOG.info("List {} topics under schema: {}.{}.{}", topics.length, metalake, catalog, schema);@@ -186,11 +180,7 @@ public class TopicOperations {.map(TopicUpdateRequest::topicChange).toArray(TopicChange[]::new);- Topic t =- TreeLockUtils.doWithTreeLock(- NameIdentifierUtil.ofSchema(metalake, catalog, schema),- LockType.WRITE,- () -> dispatcher.alterTopic(ident, changes));+ Topic t = dispatcher.alterTopic(ident, changes);Response response = Utils.ok(new TopicResponse(DTOConverters.toDTO(t)));LOG.info("Topic altered: {}.{}.{}.{}", metalake, catalog, schema, t.name());return response;@@ -217,11 +207,7 @@ public class TopicOperations {() -> {LOG.info("Dropping topic under schema: {}.{}.{}", metalake, catalog, schema);NameIdentifier ident = NameIdentifierUtil.ofTopic(metalake, catalog, schema, topic);- boolean dropped =- TreeLockUtils.doWithTreeLock(- NameIdentifierUtil.ofSchema(metalake, catalog, schema),- LockType.WRITE,- () -> dispatcher.dropTopic(ident));+ boolean dropped = dispatcher.dropTopic(ident);if (!dropped) {LOG.warn("Failed to drop topic {} under schema {}", topic, schema);diff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/UserOperations.java b/server/src/main/java/org/apache/gravitino/server/web/rest/UserOperations.javaindex 518178cd32..48147368ea 100644--- a/server/src/main/java/org/apache/gravitino/server/web/rest/UserOperations.java+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/UserOperations.java@@ -32,17 +32,13 @@ import javax.ws.rs.QueryParam;import javax.ws.rs.core.Context;import javax.ws.rs.core.Response;import org.apache.gravitino.GravitinoEnv;-import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.authorization.AccessControlDispatcher;-import org.apache.gravitino.authorization.AuthorizationUtils;import org.apache.gravitino.dto.requests.UserAddRequest;import org.apache.gravitino.dto.responses.NameListResponse;import org.apache.gravitino.dto.responses.RemoveResponse;import org.apache.gravitino.dto.responses.UserListResponse;import org.apache.gravitino.dto.responses.UserResponse;import org.apache.gravitino.dto.util.DTOConverters;-import org.apache.gravitino.lock.LockType;-import org.apache.gravitino.lock.TreeLockUtils;import org.apache.gravitino.metrics.MetricNames;import org.apache.gravitino.server.authorization.NameBindings;import org.apache.gravitino.server.web.Utils;@@ -76,13 +72,9 @@ public class UserOperations {return Utils.doAs(httpRequest,() ->- TreeLockUtils.doWithTreeLock(- AuthorizationUtils.ofGroup(metalake, user),- LockType.READ,- () ->- Utils.ok(- new UserResponse(- DTOConverters.toDTO(accessControlManager.getUser(metalake, user))))));+ Utils.ok(+ new UserResponse(+ DTOConverters.toDTO(accessControlManager.getUser(metalake, user)))));} catch (Exception e) {return ExceptionHandlers.handleUserException(OperationType.GET, user, metalake, e);}@@ -98,20 +90,15 @@ public class UserOperations {try {return Utils.doAs(httpRequest,- () ->- TreeLockUtils.doWithTreeLock(- NameIdentifier.of(AuthorizationUtils.ofUserNamespace(metalake).levels()),- LockType.READ,- () -> {- if (verbose) {- return Utils.ok(- new UserListResponse(- DTOConverters.toDTOs(accessControlManager.listUsers(metalake))));- } else {- return Utils.ok(- new NameListResponse(accessControlManager.listUserNames(metalake)));- }- }));+ () -> {+ if (verbose) {+ return Utils.ok(+ new UserListResponse(+ DTOConverters.toDTOs(accessControlManager.listUsers(metalake))));+ } else {+ return Utils.ok(new NameListResponse(accessControlManager.listUserNames(metalake)));+ }+ });} catch (Exception e) {return ExceptionHandlers.handleUserException(OperationType.LIST, "", metalake, e);}@@ -125,17 +112,13 @@ public class UserOperations {try {return Utils.doAs(httpRequest,- () ->- TreeLockUtils.doWithTreeLock(- NameIdentifier.of(AuthorizationUtils.ofGroupNamespace(metalake).levels()),- LockType.WRITE,- () -> {- request.validate();- return Utils.ok(- new UserResponse(- DTOConverters.toDTO(- accessControlManager.addUser(metalake, request.getName()))));- }));+ () -> {+ request.validate();+ return Utils.ok(+ new UserResponse(+ DTOConverters.toDTO(+ accessControlManager.addUser(metalake, request.getName()))));+ });} catch (Exception e) {return ExceptionHandlers.handleUserException(OperationType.ADD, request.getName(), metalake, e);@@ -153,11 +136,7 @@ public class UserOperations {return Utils.doAs(httpRequest,() -> {- boolean removed =- TreeLockUtils.doWithTreeLock(- NameIdentifier.of(AuthorizationUtils.ofGroupNamespace(metalake).levels()),- LockType.WRITE,- () -> accessControlManager.removeUser(metalake, user));+ boolean removed = accessControlManager.removeUser(metalake, user);if (!removed) {LOG.warn("Failed to remove user {} under metalake {}", user, metalake);}