diff --git a/config/src/main/java/com/alibaba/nacos/config/server/aspect/CapacityManagementAspect.java b/config/src/main/java/com/alibaba/nacos/config/server/aspect/CapacityManagementAspect.java index 5be7fd2c8b9..0968945a538 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/aspect/CapacityManagementAspect.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/aspect/CapacityManagementAspect.java @@ -19,7 +19,9 @@ import com.alibaba.nacos.common.utils.StringUtils; import com.alibaba.nacos.config.server.constant.CounterMode; import com.alibaba.nacos.config.server.model.ConfigInfo; +import com.alibaba.nacos.config.server.model.ConfigRequestInfo; import com.alibaba.nacos.config.server.model.capacity.Capacity; +import com.alibaba.nacos.config.server.model.form.ConfigForm; import com.alibaba.nacos.config.server.service.capacity.CapacityService; import com.alibaba.nacos.config.server.service.repository.ConfigInfoPersistService; import com.alibaba.nacos.config.server.utils.PropertyUtil; @@ -28,31 +30,28 @@ import org.aspectj.lang.annotation.Aspect; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import java.nio.charset.StandardCharsets; import static com.alibaba.nacos.config.server.constant.Constants.LIMIT_ERROR_CODE; /** - * Capacity management aspect: batch write and update but don't process it. + * Capacity management aspect for config service. * - * @author hexu.hxy - * @date 2018/3/13 + * @author Nacos */ @Aspect +@Component public class CapacityManagementAspect { private static final Logger LOGGER = LoggerFactory.getLogger(CapacityManagementAspect.class); - private static final String SYNC_UPDATE_CONFIG_ALL = - "execution(* com.alibaba.nacos.config.server.controller.ConfigController.publishConfig(..)) && args" - + "(request,response,dataId,group,content,appName,srcUser,tenant,tag,..)"; + private static final String PUBLISH_CONFIG = + "execution(* com.alibaba.nacos.config.server.service.ConfigOperationService.publishConfig(..))"; private static final String DELETE_CONFIG = - "execution(* com.alibaba.nacos.config.server.controller.ConfigController.deleteConfig(..)) && args" - + "(request,response,dataId,group,tenant,..)"; + "execution(* com.alibaba.nacos.config.server.service.ConfigOperationService.deleteConfig(..))"; private final CapacityService capacityService; @@ -64,49 +63,58 @@ public CapacityManagementAspect(ConfigInfoPersistService configInfoPersistServic } /** - * Need to judge the size of content whether to exceed the limitation. + * Intercept publish config operations to perform capacity management checks. */ - @Around(SYNC_UPDATE_CONFIG_ALL) - public Object aroundSyncUpdateConfigAll(ProceedingJoinPoint pjp, HttpServletRequest request, - HttpServletResponse response, String dataId, String group, String content, String appName, String srcUser, - String tenant, String tag) throws Throwable { + @Around(PUBLISH_CONFIG) + public Object aroundSyncUpdateConfigAll(ProceedingJoinPoint pjp) throws Throwable { if (!PropertyUtil.isManageCapacity()) { return pjp.proceed(); } - LOGGER.info("[capacityManagement] aroundSyncUpdateConfigAll"); - String betaIps = request.getHeader("betaIps"); - if (StringUtils.isBlank(betaIps)) { - if (StringUtils.isBlank(tag)) { - // do capacity management limitation check for writing or updating config_info table. - if (configInfoPersistService.findConfigInfo(dataId, group, tenant) == null) { - // Write operation. - return do4Insert(pjp, request, response, group, tenant, content); - } + + Object[] args = pjp.getArgs(); + ConfigForm configForm = (ConfigForm) args[0]; + ConfigRequestInfo configRequestInfo = (ConfigRequestInfo) args[1]; + String dataId = configForm.getDataId(); + String group = configForm.getGroup(); + String namespaceId = configForm.getNamespaceId(); + String content = configForm.getContent(); + String betaIps = configRequestInfo.getBetaIps(); + String tag = configForm.getTag(); + + LOGGER.info("[CapacityManagement] Intercepting publishConfig operation for dataId: {}, group: {}, namespaceId: {}", + dataId, group, namespaceId); + + if (StringUtils.isBlank(betaIps) && StringUtils.isBlank(tag)) { + // do capacity management limitation check for writing or updating config_info table. + if (configInfoPersistService.findConfigInfo(dataId, group, namespaceId) == null) { + // Write operation. + return do4Insert(pjp, group, namespaceId, content); + } else { // Update operation. - return do4Update(pjp, request, response, dataId, group, tenant, content); + return do4Update(pjp, dataId, group, namespaceId, content); } } return pjp.proceed(); } /** - * Update operation: open the limitation of capacity management and it will check the size of content. + * Update operation: open the limitation of capacity management, and it will check the size of content. * * @throws Throwable Throws Exception when actually operate. */ - private Object do4Update(ProceedingJoinPoint pjp, HttpServletRequest request, HttpServletResponse response, - String dataId, String group, String tenant, String content) throws Throwable { + private Object do4Update(ProceedingJoinPoint pjp, String dataId, String group, String namespaceId, String content) throws Throwable { if (!PropertyUtil.isCapacityLimitCheck()) { return pjp.proceed(); } try { - boolean hasTenant = hasTenant(tenant); - Capacity capacity = getCapacity(group, tenant, hasTenant); - if (isSizeLimited(group, tenant, getCurrentSize(content), hasTenant, false, capacity)) { - return response4Limit(request, response, LimitType.OVER_MAX_SIZE); + boolean hasTenant = StringUtils.isNotBlank(namespaceId); + Capacity capacity = getCapacity(group, namespaceId, hasTenant); + if (isSizeLimited(group, namespaceId, getCurrentSize(content), hasTenant, false, capacity)) { + return false; } } catch (Exception e) { - LOGGER.error("[capacityManagement] do4Update ", e); + LOGGER.error("[CapacityManagement] Error during update operation for dataId: {}, group: {}, namespaceId: {}", + dataId, group, namespaceId, e); } return pjp.proceed(); } @@ -117,49 +125,46 @@ private Object do4Update(ProceedingJoinPoint pjp, HttpServletRequest request, Ht * * @throws Throwable Exception. */ - private Object do4Insert(ProceedingJoinPoint pjp, HttpServletRequest request, HttpServletResponse response, - String group, String tenant, String content) throws Throwable { - LOGGER.info("[capacityManagement] do4Insert"); + private Object do4Insert(ProceedingJoinPoint pjp, String group, String namespaceId, String content) throws Throwable { + LOGGER.info("[CapacityManagement] Handling insert operation for group: {}, namespaceId: {}", group, namespaceId); CounterMode counterMode = CounterMode.INCREMENT; - boolean hasTenant = hasTenant(tenant); + boolean hasTenant = StringUtils.isNotBlank(namespaceId); + if (PropertyUtil.isCapacityLimitCheck()) { // Write or update: usage + 1 - LimitType limitType = getLimitType(counterMode, group, tenant, content, hasTenant); + LimitType limitType = getLimitType(counterMode, group, namespaceId, content, hasTenant); if (limitType != null) { - return response4Limit(request, response, limitType); + return false; } } else { // Write or update: usage + 1 - insertOrUpdateUsage(group, tenant, counterMode, hasTenant); + insertOrUpdateUsage(group, namespaceId, counterMode, hasTenant); } - return getResult(pjp, response, group, tenant, counterMode, hasTenant); - } - - private Object response4Limit(HttpServletRequest request, HttpServletResponse response, LimitType limitType) { - response.setStatus(limitType.status); - return String.valueOf(limitType.status); - } - - private boolean hasTenant(String tenant) { - return StringUtils.isNotBlank(tenant); + return getResult(pjp, group, namespaceId, counterMode, hasTenant); } /** - * The usage of capacity table for counting module will subtracte one whether open the limitation check of capacity - * management. + * Intercept delete config operations to perform capacity management checks. */ @Around(DELETE_CONFIG) - public Object aroundDeleteConfig(ProceedingJoinPoint pjp, HttpServletRequest request, HttpServletResponse response, - String dataId, String group, String tenant) throws Throwable { + public Object aroundDeleteConfig(ProceedingJoinPoint pjp) throws Throwable { if (!PropertyUtil.isManageCapacity()) { return pjp.proceed(); } - LOGGER.info("[capacityManagement] aroundDeleteConfig"); - ConfigInfo configInfo = configInfoPersistService.findConfigInfo(dataId, group, tenant); + + Object[] args = pjp.getArgs(); + String dataId = (String) args[0]; + String group = (String) args[1]; + String namespaceId = (String) args[2]; + + LOGGER.info("[CapacityManagement] Intercepting deleteConfig operation for dataId: {}, group: {}, namespaceId: {}", dataId, group, + namespaceId); + + ConfigInfo configInfo = configInfoPersistService.findConfigInfo(dataId, group, namespaceId); if (configInfo == null) { return pjp.proceed(); } - return do4Delete(pjp, response, group, tenant, configInfo); + return do4Delete(pjp, group, namespaceId, configInfo); } /** @@ -167,9 +172,8 @@ public Object aroundDeleteConfig(ProceedingJoinPoint pjp, HttpServletRequest req * * @throws Throwable Exception. */ - private Object do4Delete(ProceedingJoinPoint pjp, HttpServletResponse response, String group, String tenant, - ConfigInfo configInfo) throws Throwable { - boolean hasTenant = hasTenant(tenant); + private Object do4Delete(ProceedingJoinPoint pjp, String group, String namespaceId, ConfigInfo configInfo) throws Throwable { + boolean hasTenant = StringUtils.isNotBlank(namespaceId); if (configInfo == null) { // "configInfo == null", has two possible points. // 1. Concurrently deletion. @@ -181,7 +185,7 @@ private Object do4Delete(ProceedingJoinPoint pjp, HttpServletResponse response, // Modify usage when the task of info is finished, and usage = 1. // The following "delete config_info" task will not be executed with usage-1, because the request has already returned. // Therefore, it is necessary to modify the usage job regularly. - correctUsage(group, tenant, hasTenant); + correctUsage(group, namespaceId, hasTenant); return pjp.proceed(); } @@ -189,15 +193,15 @@ private Object do4Delete(ProceedingJoinPoint pjp, HttpServletResponse response, // to MergeTaskProcessor for processing), It may lead to more than one decrease in usage. // Therefore, it is necessary to modify the usage job regularly. CounterMode counterMode = CounterMode.DECREMENT; - insertOrUpdateUsage(group, tenant, counterMode, hasTenant); - return getResult(pjp, response, group, tenant, counterMode, hasTenant); + insertOrUpdateUsage(group, namespaceId, counterMode, hasTenant); + return getResult(pjp, group, namespaceId, counterMode, hasTenant); } - private void correctUsage(String group, String tenant, boolean hasTenant) { + private void correctUsage(String group, String namespaceId, boolean hasTenant) { try { if (hasTenant) { - LOGGER.info("[capacityManagement] correct usage, tenant: {}", tenant); - capacityService.correctTenantUsage(tenant); + LOGGER.info("[capacityManagement] correct usage, namespaceId: {}", namespaceId); + capacityService.correctTenantUsage(namespaceId); } else { LOGGER.info("[capacityManagement] correct usage, group: {}", group); capacityService.correctGroupUsage(group); @@ -207,18 +211,14 @@ private void correctUsage(String group, String tenant, boolean hasTenant) { } } - private Object getResult(ProceedingJoinPoint pjp, HttpServletResponse response, String group, String tenant, - CounterMode counterMode, boolean hasTenant) throws Throwable { + private Object getResult(ProceedingJoinPoint pjp, String group, String namespaceId, CounterMode counterMode, boolean hasTenant) throws Throwable { try { // Execute operation actually. - Object result = pjp.proceed(); - // Execute whether to callback based on the sql operation result. - doResult(counterMode, response, group, tenant, result, hasTenant); - return result; + return pjp.proceed(); } catch (Throwable throwable) { - LOGGER.warn("[capacityManagement] inner operation throw exception, rollback, group: {}, tenant: {}", group, - tenant, throwable); - rollback(counterMode, group, tenant, hasTenant); + LOGGER.warn("[capacityManagement] inner operation throw exception, rollback, group: {}, namespaceId: {}", group, + namespaceId, throwable); + rollbackUsage(counterMode, group, namespaceId, hasTenant); throw throwable; } } @@ -226,11 +226,11 @@ private Object getResult(ProceedingJoinPoint pjp, HttpServletResponse response, /** * Usage counting service: it will count whether the limitation check function will be open. */ - private void insertOrUpdateUsage(String group, String tenant, CounterMode counterMode, boolean hasTenant) { + private void insertOrUpdateUsage(String group, String namespaceId, CounterMode counterMode, boolean hasTenant) { try { capacityService.insertAndUpdateClusterUsage(counterMode, true); if (hasTenant) { - capacityService.insertAndUpdateTenantUsage(counterMode, tenant, true); + capacityService.insertAndUpdateTenantUsage(counterMode, namespaceId, true); } else { capacityService.insertAndUpdateGroupUsage(counterMode, group, true); } @@ -239,7 +239,7 @@ private void insertOrUpdateUsage(String group, String tenant, CounterMode counte } } - private LimitType getLimitType(CounterMode counterMode, String group, String tenant, String content, + private LimitType getLimitType(CounterMode counterMode, String group, String namespaceId, String content, boolean hasTenant) { try { boolean clusterLimited = !capacityService.insertAndUpdateClusterUsage(counterMode, false); @@ -251,7 +251,7 @@ private LimitType getLimitType(CounterMode counterMode, String group, String ten return null; } int currentSize = getCurrentSize(content); - LimitType limitType = getGroupOrTenantLimitType(counterMode, group, tenant, currentSize, hasTenant); + LimitType limitType = getGroupOrTenantLimitType(counterMode, group, namespaceId, currentSize, hasTenant); if (limitType != null) { rollbackClusterUsage(counterMode); return limitType; @@ -274,19 +274,19 @@ private int getCurrentSize(String content) { return 0; } - private LimitType getGroupOrTenantLimitType(CounterMode counterMode, String group, String tenant, int currentSize, + private LimitType getGroupOrTenantLimitType(CounterMode counterMode, String group, String namespaceId, int currentSize, boolean hasTenant) { if (group == null) { return null; } - Capacity capacity = getCapacity(group, tenant, hasTenant); - if (isSizeLimited(group, tenant, currentSize, hasTenant, false, capacity)) { + Capacity capacity = getCapacity(group, namespaceId, hasTenant); + if (isSizeLimited(group, namespaceId, currentSize, hasTenant, false, capacity)) { return LimitType.OVER_MAX_SIZE; } if (capacity == null) { - insertCapacity(group, tenant, hasTenant); + insertCapacity(group, namespaceId, hasTenant); } - boolean updateSuccess = isUpdateSuccess(counterMode, group, tenant, hasTenant); + boolean updateSuccess = isUpdateSuccess(counterMode, group, namespaceId, hasTenant); if (updateSuccess) { return null; } @@ -296,12 +296,12 @@ private LimitType getGroupOrTenantLimitType(CounterMode counterMode, String grou return LimitType.OVER_GROUP_QUOTA; } - private boolean isUpdateSuccess(CounterMode counterMode, String group, String tenant, boolean hasTenant) { + private boolean isUpdateSuccess(CounterMode counterMode, String group, String namespaceId, boolean hasTenant) { boolean updateSuccess; if (hasTenant) { - updateSuccess = capacityService.updateTenantUsage(counterMode, tenant); + updateSuccess = capacityService.updateTenantUsage(counterMode, namespaceId); if (!updateSuccess) { - LOGGER.warn("[capacityManagement] tenant capacity reaches quota, tenant: {}", tenant); + LOGGER.warn("[capacityManagement] namespaceId capacity reaches quota, namespaceId: {}", namespaceId); } } else { updateSuccess = capacityService.updateGroupUsage(counterMode, group); @@ -312,38 +312,38 @@ private boolean isUpdateSuccess(CounterMode counterMode, String group, String te return updateSuccess; } - private void insertCapacity(String group, String tenant, boolean hasTenant) { + private void insertCapacity(String group, String namespaceId, boolean hasTenant) { if (hasTenant) { - capacityService.initTenantCapacity(tenant); + capacityService.initTenantCapacity(namespaceId); } else { capacityService.initGroupCapacity(group); } } - private Capacity getCapacity(String group, String tenant, boolean hasTenant) { + private Capacity getCapacity(String group, String namespaceId, boolean hasTenant) { Capacity capacity; if (hasTenant) { - capacity = capacityService.getTenantCapacity(tenant); + capacity = capacityService.getTenantCapacity(namespaceId); } else { capacity = capacityService.getGroupCapacity(group); } return capacity; } - private boolean isSizeLimited(String group, String tenant, int currentSize, boolean hasTenant, boolean isAggr, + private boolean isSizeLimited(String group, String namespaceId, int currentSize, boolean hasTenant, boolean isAggr, Capacity capacity) { int defaultMaxSize = getDefaultMaxSize(isAggr); if (capacity != null) { Integer maxSize = getMaxSize(isAggr, capacity); if (maxSize == 0) { // If there exists capacity info and maxSize = 0, then it uses maxSize limitation default value to compare. - return isOverSize(group, tenant, currentSize, defaultMaxSize, hasTenant); + return isOverSize(group, namespaceId, currentSize, defaultMaxSize, hasTenant); } // If there exists capacity info, then maxSize!=0. - return isOverSize(group, tenant, currentSize, maxSize, hasTenant); + return isOverSize(group, namespaceId, currentSize, maxSize, hasTenant); } // If there no exists capacity info, then it uses maxSize limitation default value to compare. - return isOverSize(group, tenant, currentSize, defaultMaxSize, hasTenant); + return isOverSize(group, namespaceId, currentSize, defaultMaxSize, hasTenant); } private Integer getMaxSize(boolean isAggr, Capacity capacity) { @@ -360,12 +360,12 @@ private int getDefaultMaxSize(boolean isAggr) { return PropertyUtil.getDefaultMaxSize(); } - private boolean isOverSize(String group, String tenant, int currentSize, int maxSize, boolean hasTenant) { + private boolean isOverSize(String group, String namespaceId, int currentSize, int maxSize, boolean hasTenant) { if (currentSize > maxSize) { if (hasTenant) { LOGGER.warn( - "[capacityManagement] tenant content is over maxSize, tenant: {}, maxSize: {}, currentSize: {}", - tenant, maxSize, currentSize); + "[capacityManagement] namespaceId content is over maxSize, namespaceId: {}, maxSize: {}, currentSize: {}", + namespaceId, maxSize, currentSize); } else { LOGGER.warn( "[capacityManagement] group content is over maxSize, group: {}, maxSize: {}, currentSize: {}", @@ -376,34 +376,11 @@ private boolean isOverSize(String group, String tenant, int currentSize, int max return false; } - private void doResult(CounterMode counterMode, HttpServletResponse response, String group, String tenant, - Object result, boolean hasTenant) { - try { - if (!isSuccess(response, result)) { - LOGGER.warn( - "[capacityManagement] inner operation is fail, rollback, counterMode: {}, group: {}, tenant: {}", - counterMode, group, tenant); - rollback(counterMode, group, tenant, hasTenant); - } - } catch (Exception e) { - LOGGER.error("[capacityManagement] doResult ", e); - } - } - - private boolean isSuccess(HttpServletResponse response, Object result) { - int status = response.getStatus(); - if (status == HttpServletResponse.SC_OK) { - return true; - } - LOGGER.warn("[capacityManagement] response status is not 200, status: {}, result: {}", status, result); - return false; - } - - private void rollback(CounterMode counterMode, String group, String tenant, boolean hasTenant) { + private void rollbackUsage(CounterMode counterMode, String group, String namespaceId, boolean hasTenant) { try { rollbackClusterUsage(counterMode); if (hasTenant) { - capacityService.updateTenantUsage(counterMode.reverse(), tenant); + capacityService.updateTenantUsage(counterMode.reverse(), namespaceId); } else { capacityService.updateGroupUsage(counterMode.reverse(), group); } @@ -431,10 +408,10 @@ public enum LimitType { /** * over limit. */ - OVER_CLUSTER_QUOTA("超过集群配置个数上限", LIMIT_ERROR_CODE), - OVER_GROUP_QUOTA("超过该Group配置个数上限", LIMIT_ERROR_CODE), - OVER_TENANT_QUOTA("超过该租户配置个数上限", LIMIT_ERROR_CODE), - OVER_MAX_SIZE("超过配置的内容大小上限", LIMIT_ERROR_CODE); + OVER_CLUSTER_QUOTA("Exceeded the maximum number of configurations in the cluster", LIMIT_ERROR_CODE), + OVER_GROUP_QUOTA("Exceeded the maximum number of configurations in this group", LIMIT_ERROR_CODE), + OVER_TENANT_QUOTA("Exceeded the maximum number of configurations for this namespaceId", LIMIT_ERROR_CODE), + OVER_MAX_SIZE("Exceeded the maximum size limit of the configuration content", LIMIT_ERROR_CODE); public final String description; diff --git a/config/src/main/java/com/alibaba/nacos/config/server/aspect/ConfigChangeAspect.java b/config/src/main/java/com/alibaba/nacos/config/server/aspect/ConfigChangeAspect.java index 069e8cc8d4a..7aafed65a8a 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/aspect/ConfigChangeAspect.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/aspect/ConfigChangeAspect.java @@ -16,15 +16,14 @@ package com.alibaba.nacos.config.server.aspect; -import com.alibaba.nacos.api.config.remote.request.ConfigPublishRequest; -import com.alibaba.nacos.api.config.remote.request.ConfigRemoveRequest; import com.alibaba.nacos.api.config.remote.response.ConfigPublishResponse; import com.alibaba.nacos.api.config.remote.response.ConfigRemoveResponse; -import com.alibaba.nacos.api.remote.request.RequestMeta; import com.alibaba.nacos.api.remote.response.ResponseCode; import com.alibaba.nacos.common.model.RestResultUtils; import com.alibaba.nacos.config.server.configuration.ConfigChangeConfigs; +import com.alibaba.nacos.config.server.model.ConfigRequestInfo; import com.alibaba.nacos.config.server.model.SameConfigPolicy; +import com.alibaba.nacos.config.server.model.form.ConfigForm; import com.alibaba.nacos.config.server.utils.ConfigExecutor; import com.alibaba.nacos.config.server.utils.RequestUtil; import com.alibaba.nacos.config.server.utils.TimeUtils; @@ -44,7 +43,6 @@ import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import java.util.List; import java.util.ArrayList; import java.util.Properties; @@ -53,7 +51,7 @@ /** * Config change pointcut aspect,which config change plugin services will pointcut. * - * @author liyunfei + * @author Nacos */ @Aspect @Component @@ -67,84 +65,86 @@ public class ConfigChangeAspect { private static final String ENABLED = "enabled"; - /** - * Publish or update config through http. - */ - private static final String CLIENT_INTERFACE_PUBLISH_CONFIG = - "execution(* com.alibaba.nacos.config.server.controller.ConfigController.publishConfig(..)) " - + "&& args(request,response,dataId,group,tenant,content,tag,appName,srcUser,configTags,desc,use,effect,type,..) " - + "&& @annotation(org.springframework.web.bind.annotation.PostMapping)"; + private static final String SCR_TYPE_HTTP = "http"; - /** - * Publish or update config through rpc. - */ - private static final String CLIENT_INTERFACE_PUBLISH_CONFIG_RPC = - "execution(* com.alibaba.nacos.core.remote.RequestHandler.handleRequest(..)) " - + "&& target(com.alibaba.nacos.config.server.remote.ConfigPublishRequestHandler) " - + "&& args(request,meta)"; + private static final String SCR_TYPE_RPC = "rpc"; /** - * Remove config by id through http. + * Publish config. */ - private static final String CLIENT_INTERFACE_REMOVE_CONFIG = - "execution(* com.alibaba.nacos.config.server.controller.ConfigController.deleteConfig(..))" - + " && args(request,response,dataId,group,tenant,..)"; + private static final String PUBLISH_CONFIG = + "execution(* com.alibaba.nacos.config.server.service.ConfigOperationService.publishConfig(..))"; /** - * Remove config by ids through http. + * Delete config. */ - private static final String CLIENT_INTERFACE_BATCH_REMOVE_CONFIG = - "execution(* com.alibaba.nacos.config.server.controller.ConfigController.deleteConfigs(..))" - + " && args(request,ids)"; + private static final String DELETE_CONFIG = + "execution(* com.alibaba.nacos.config.server.service.ConfigOperationService.deleteConfig(..))"; /** - * Remove config through rpc. + * Batch delete config by ids. */ - @SuppressWarnings("checkstyle:linelength") - private static final String CLIENT_INTERFACE_REMOVE_CONFIG_RPC = - "execution(* com.alibaba.nacos.core.remote.RequestHandler.handleRequest(..)) " - + " && target(com.alibaba.nacos.config.server.remote.ConfigRemoveRequestHandler)" - + " && args(request,meta)"; - + private static final String BATCH_DELETE_CONFIG = + "execution(* com.alibaba.nacos.config.server.service.ConfigOperationService.deleteConfigs(..))"; + /** - * Import file through http. + * Import file. */ - private static final String CLIENT_INTERFACE_IMPORT_CONFIG = + private static final String IMPORT_CONFIG = "execution(* com.alibaba.nacos.config.server.controller.ConfigController.importAndPublishConfig(..)) " + "&& args(request,srcUser,namespace,policy,file)"; private final ConfigChangeConfigs configChangeConfigs; - private ConfigChangePluginManager configChangeManager; - public ConfigChangeAspect(ConfigChangeConfigs configChangeConfigs) { this.configChangeConfigs = configChangeConfigs; - configChangeManager = ConfigChangePluginManager.getInstance(); } /** * Publish or update config. */ - @Around(CLIENT_INTERFACE_PUBLISH_CONFIG) - Object publishOrUpdateConfigAround(ProceedingJoinPoint pjp, HttpServletRequest request, - HttpServletResponse response, String dataId, String group, String tenant, String content, String tag, - String appName, String srcUser, String configTags, String desc, String use, String effect, String type) - throws Throwable { - final ConfigChangePointCutTypes configChangePointCutType = ConfigChangePointCutTypes.PUBLISH_BY_HTTP; + @Around(PUBLISH_CONFIG) + Object publishOrUpdateConfigAround(ProceedingJoinPoint pjp) throws Throwable { + Object[] args = pjp.getArgs(); + ConfigForm configForm = (ConfigForm) args[0]; + ConfigRequestInfo configRequestInfo = (ConfigRequestInfo) args[1]; + final String dataId = configForm.getDataId(); + final String group = configForm.getGroup(); + final String namespaceId = configForm.getNamespaceId(); + final String content = configForm.getContent(); + final String desc = configForm.getDesc(); + final String use = configForm.getUse(); + final String effect = configForm.getEffect(); + final String type = configForm.getType(); + final String tag = configForm.getTag(); + final String configTags = configForm.getConfigTags(); + final String requestIpApp = configRequestInfo.getRequestIpApp(); + final String scrIp = configRequestInfo.getSrcIp(); + final String scrType = configRequestInfo.getSrcType(); + + ConfigChangePointCutTypes configChangePointCutType = null; + if (SCR_TYPE_HTTP.equals(scrType)) { + // via console or api calls + configChangePointCutType = ConfigChangePointCutTypes.PUBLISH_BY_HTTP; + } else if (SCR_TYPE_RPC.equals(scrType)) { + // via sdk rpc calls + configChangePointCutType = ConfigChangePointCutTypes.PUBLISH_BY_RPC; + } final List pluginServices = getPluginServices( configChangePointCutType); // didn't enabled or add relative plugin if (pluginServices.isEmpty()) { return pjp.proceed(); } + ConfigChangeRequest configChangeRequest = new ConfigChangeRequest(configChangePointCutType); configChangeRequest.setArg("dataId", dataId); configChangeRequest.setArg("group", group); - configChangeRequest.setArg("tenant", tenant); + configChangeRequest.setArg("namespaceId", namespaceId); configChangeRequest.setArg("content", content); configChangeRequest.setArg("tag", tag); - configChangeRequest.setArg("requestIpApp", appName); - configChangeRequest.setArg("srcIp", RequestUtil.getRemoteIp(request)); + configChangeRequest.setArg("requestIpApp", requestIpApp); + configChangeRequest.setArg("srcIp", scrIp); configChangeRequest.setArg("configTags", configTags); configChangeRequest.setArg("desc", desc); configChangeRequest.setArg("use", use); @@ -156,51 +156,68 @@ Object publishOrUpdateConfigAround(ProceedingJoinPoint pjp, HttpServletRequest r /** * Remove config. */ - @Around(CLIENT_INTERFACE_REMOVE_CONFIG) - Object removeConfigByIdAround(ProceedingJoinPoint pjp, HttpServletRequest request, HttpServletResponse response, - String dataId, String group, String tenant) throws Throwable { - final ConfigChangePointCutTypes configChangePointCutType = ConfigChangePointCutTypes.REMOVE_BY_HTTP; - final List pluginServices = getPluginServices( - configChangePointCutType); + @Around(DELETE_CONFIG) + Object removeConfigByIdAround(ProceedingJoinPoint pjp) throws Throwable { + Object[] args = pjp.getArgs(); + final String dataId = (String) args[0]; + final String group = (String) args[1]; + final String namespaceId = (String) args[2]; + final String tag = (String) args[3]; + final String srcUser = (String) args[4]; + String scrType = (String) args[5]; + + ConfigChangePointCutTypes configChangePointCutType = null; + if (SCR_TYPE_HTTP.equals(scrType)) { + // via console or api calls + configChangePointCutType = ConfigChangePointCutTypes.PUBLISH_BY_HTTP; + } else if (SCR_TYPE_RPC.equals(scrType)) { + // via sdk rpc calls + configChangePointCutType = ConfigChangePointCutTypes.PUBLISH_BY_RPC; + } + final List pluginServices = getPluginServices(configChangePointCutType); // didn't enabled or add relative plugin if (pluginServices.isEmpty()) { return pjp.proceed(); } + ConfigChangeRequest configChangeRequest = new ConfigChangeRequest(configChangePointCutType); configChangeRequest.setArg("dataId", dataId); configChangeRequest.setArg("group", group); - configChangeRequest.setArg("tenant", tenant); - configChangeRequest.setArg("srcIp", RequestUtil.getRemoteIp(request)); - configChangeRequest.setArg("requestIpApp", RequestUtil.getAppName(request)); - configChangeRequest.setArg("use", RequestUtil.getSrcUserName(request)); + configChangeRequest.setArg("namespaceId", namespaceId); + configChangeRequest.setArg("srcUser", srcUser); + configChangeRequest.setArg("tag", tag); + configChangeRequest.setArg("modifyTime", TimeUtils.getCurrentTimeStr()); return configChangeServiceHandle(pjp, pluginServices, configChangeRequest); } /** - * Remove config by ids. + * Delete config by ids. */ - @Around(CLIENT_INTERFACE_BATCH_REMOVE_CONFIG) - public Object removeConfigByIdsAround(ProceedingJoinPoint pjp, HttpServletRequest request, List ids) - throws Throwable { + @Around(BATCH_DELETE_CONFIG) + public Object removeConfigByIdsAround(ProceedingJoinPoint pjp) throws Throwable { + Object[] args = pjp.getArgs(); + List ids = (List) args[0]; + String srcIp = (String) args[1]; + final String srcUser = (String) args[2]; + final ConfigChangePointCutTypes configChangePointCutType = ConfigChangePointCutTypes.REMOVE_BATCH_HTTP; - final List pluginServices = getPluginServices( - configChangePointCutType); + final List pluginServices = getPluginServices(configChangePointCutType); // didn't enabled or add relative plugin if (pluginServices.isEmpty()) { return pjp.proceed(); } + ConfigChangeRequest configChangeRequest = new ConfigChangeRequest(configChangePointCutType); configChangeRequest.setArg("dataId", ids.toString()); - configChangeRequest.setArg("srcIp", RequestUtil.getRemoteIp(request)); - configChangeRequest.setArg("requestIpApp", RequestUtil.getAppName(request)); - configChangeRequest.setArg("use", RequestUtil.getSrcUserName(request)); + configChangeRequest.setArg("srcIp", srcIp); + configChangeRequest.setArg("srcUser", srcUser); return configChangeServiceHandle(pjp, pluginServices, configChangeRequest); } /** * Import config. */ - @Around(CLIENT_INTERFACE_IMPORT_CONFIG) + @Around(IMPORT_CONFIG) public Object importConfigAround(ProceedingJoinPoint pjp, HttpServletRequest request, String srcUser, String namespace, SameConfigPolicy policy, MultipartFile file) throws Throwable { final ConfigChangePointCutTypes configChangePointCutType = ConfigChangePointCutTypes.IMPORT_BY_HTTP; @@ -221,69 +238,12 @@ public Object importConfigAround(ProceedingJoinPoint pjp, HttpServletRequest req return configChangeServiceHandle(pjp, pluginServices, configChangeRequest); } - /** - * Publish or update config. - */ - @Around(CLIENT_INTERFACE_PUBLISH_CONFIG_RPC) - Object publishConfigAroundRpc(ProceedingJoinPoint pjp, ConfigPublishRequest request, RequestMeta meta) - throws Throwable { - final ConfigChangePointCutTypes configChangePointCutType = ConfigChangePointCutTypes.PUBLISH_BY_RPC; - final List pluginServices = getPluginServices( - configChangePointCutType); - // didn't enabled or add relative plugin - if (pluginServices.isEmpty()) { - return pjp.proceed(); - } - ConfigChangeRequest configChangeRequest = new ConfigChangeRequest(configChangePointCutType); - configChangeRequest.setArg("dataId", request.getDataId()); - configChangeRequest.setArg("group", request.getGroup()); - configChangeRequest.setArg("tenant", request.getTenant()); - configChangeRequest.setArg("content", request.getContent()); - configChangeRequest.setArg("type", request.getAdditionParam("type")); - configChangeRequest.setArg("tag", request.getAdditionParam("tag")); - configChangeRequest.setArg("configTags", request.getAdditionParam("config_tags")); - configChangeRequest.setArg("desc", request.getAdditionParam("desc")); - configChangeRequest.setArg("effect", request.getAdditionParam("effect")); - configChangeRequest.setArg("appName", request.getAdditionParam("appName")); - configChangeRequest.setArg("srcIp", meta.getClientIp()); - configChangeRequest.setArg("requestIpApp", request.getAdditionParam("requestIpApp")); - configChangeRequest.setArg("srcUser", request.getAdditionParam("src_user")); - configChangeRequest.setArg("use", request.getAdditionParam("use")); - return configChangeServiceHandle(pjp, pluginServices, configChangeRequest); - } - - /** - * Remove config. - */ - @Around(CLIENT_INTERFACE_REMOVE_CONFIG_RPC) - Object removeConfigAroundRpc(ProceedingJoinPoint pjp, ConfigRemoveRequest request, RequestMeta meta) - throws Throwable { - final ConfigChangePointCutTypes configChangePointCutType = ConfigChangePointCutTypes.REMOVE_BY_RPC; - final List pluginServices = getPluginServices( - configChangePointCutType); - // didn't enabled or add relative plugin - if (pluginServices.isEmpty()) { - return pjp.proceed(); - } - ConfigChangeRequest configChangeRequest = new ConfigChangeRequest(configChangePointCutType); - configChangeRequest.setArg("dataId", request.getDataId()); - configChangeRequest.setArg("group", request.getGroup()); - configChangeRequest.setArg("tenant", request.getTenant()); - configChangeRequest.setArg("appName", request.getHeader("appName")); - configChangeRequest.setArg("srcIp", meta.getClientIp()); - configChangeRequest.setArg("requestIpApp", request.getHeader("requestIpApp")); - configChangeRequest.setArg("srcUser", request.getHeader("src_user")); - configChangeRequest.setArg("use", request.getHeader("use")); - return configChangeServiceHandle(pjp, pluginServices, configChangeRequest); - } - /** * Execute relevant config change plugin services. */ private Object configChangeServiceHandle(ProceedingJoinPoint pjp, List configChangePluginServiceList, ConfigChangeRequest configChangeRequest) { - configChangeRequest.setArg("modifyTime", TimeUtils.getCurrentTimeStr()); ConfigChangePointCutTypes handleType = configChangeRequest.getRequestType(); ConfigChangeResponse configChangeResponse = new ConfigChangeResponse(handleType); // default success,when before plugin service verify failed , set false @@ -376,7 +336,7 @@ private boolean isEnabled(ConfigChangePluginService configChangePluginService) { private Object wrapErrorResp(ConfigChangeResponse configChangeResponse) { Object retVal = null; switch (configChangeResponse.getResponseType()) { - // some of controller did'nt design error msg resp + // some of controller didn't design error msg resp case IMPORT_BY_HTTP: case REMOVE_BATCH_HTTP: case REMOVE_BY_HTTP: diff --git a/config/src/main/java/com/alibaba/nacos/config/server/aspect/RequestLogAspect.java b/config/src/main/java/com/alibaba/nacos/config/server/aspect/RequestLogAspect.java index 67832d02b61..d0e84a224c9 100755 --- a/config/src/main/java/com/alibaba/nacos/config/server/aspect/RequestLogAspect.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/aspect/RequestLogAspect.java @@ -17,16 +17,16 @@ package com.alibaba.nacos.config.server.aspect; import com.alibaba.nacos.api.config.remote.request.ConfigBatchListenRequest; -import com.alibaba.nacos.api.config.remote.request.ConfigPublishRequest; -import com.alibaba.nacos.api.config.remote.request.ConfigQueryRequest; -import com.alibaba.nacos.api.config.remote.request.ConfigRemoveRequest; -import com.alibaba.nacos.api.remote.request.Request; import com.alibaba.nacos.api.remote.request.RequestMeta; import com.alibaba.nacos.api.remote.response.Response; import com.alibaba.nacos.common.utils.MD5Utils; import com.alibaba.nacos.config.server.constant.Constants; +import com.alibaba.nacos.config.server.model.ConfigRequestInfo; +import com.alibaba.nacos.config.server.model.form.ConfigForm; +import com.alibaba.nacos.config.server.model.gray.BetaGrayRule; import com.alibaba.nacos.config.server.monitor.MetricsMonitor; import com.alibaba.nacos.config.server.service.ConfigCacheService; +import com.alibaba.nacos.config.server.service.query.model.ConfigQueryChainRequest; import com.alibaba.nacos.config.server.utils.GroupKey2; import com.alibaba.nacos.config.server.utils.LogUtil; import com.alibaba.nacos.config.server.utils.RequestUtil; @@ -35,13 +35,11 @@ import org.aspectj.lang.annotation.Aspect; import org.springframework.stereotype.Component; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; /** - * * Created with IntelliJ IDEA. User: dingjoey Date: 13-12-12 Time: 21:12 client api && sdk api 请求日志打点逻辑 + * Aspect for logging HTTP API and SDK API requests in Nacos. * * @author Nacos */ @@ -49,186 +47,124 @@ @Component public class RequestLogAspect { - /** - * Publish config. - */ - private static final String CLIENT_INTERFACE_PUBLISH_SINGLE_CONFIG = - "execution(* com.alibaba.nacos.config.server.controller.ConfigController.publishConfig(..)) && args" - + "(request,response,dataId,group,tenant,content,..)"; - - /** - * Publish config. - */ - private static final String CLIENT_INTERFACE_PUBLISH_SINGLE_CONFIG_RPC = - "execution(* com.alibaba.nacos.core.remote.RequestHandler.handleRequest(..)) " - + "&& target(com.alibaba.nacos.config.server.remote.ConfigPublishRequestHandler) " - + "&& args(request,meta)"; - - /** - * Get config. - */ - private static final String CLIENT_INTERFACE_GET_CONFIG = - "execution(* com.alibaba.nacos.config.server.controller.ConfigController.getConfig(..)) && args(request," - + "response,dataId,group,tenant,..)"; + private static final String PUBLISH_CONFIG = + "execution(* com.alibaba.nacos.config.server.service.ConfigOperationService.publishConfig(..))"; - /** - * Get config. - */ - @SuppressWarnings("checkstyle:linelength") - private static final String CLIENT_INTERFACE_GET_CONFIG_RPC = - "execution(* com.alibaba.nacos.core.remote.RequestHandler.handleRequest(..)) " - + " && target(com.alibaba.nacos.config.server.remote.ConfigQueryRequestHandler) && args(request,meta)"; - - /** - * Remove config. - */ - private static final String CLIENT_INTERFACE_REMOVE_ALL_CONFIG = - "execution(* com.alibaba.nacos.config.server.controller.ConfigController.deleteConfig(..)) && args(request," - + "response,dataId,group,tenant,..)"; + private static final String GET_CONFIG = + "execution(* com.alibaba.nacos.config.server.service.query.ConfigQueryChainService.handle(..))"; - /** - * Remove config. - */ - @SuppressWarnings("checkstyle:linelength") - private static final String CLIENT_INTERFACE_REMOVE_ALL_CONFIG_RPC = - "execution(* com.alibaba.nacos.core.remote.RequestHandler.handleRequest(..)) " - + " && target(com.alibaba.nacos.config.server.remote.ConfigRemoveRequestHandler) && args(request,meta)"; + private static final String DELETE_CONFIG = + "execution(* com.alibaba.nacos.config.server.service.ConfigOperationService.deleteConfig(..))"; - /** - * Remove config. - */ - @SuppressWarnings("checkstyle:linelength") - private static final String CLIENT_INTERFACE_LISTEN_CONFIG_RPC = + private static final String CONFIG_CHANGE_LISTEN_RPC = "execution(* com.alibaba.nacos.core.remote.RequestHandler.handleRequest(..)) " + " && target(com.alibaba.nacos.config.server.remote.ConfigChangeBatchListenRequestHandler) && args(request,meta)"; - /** - * PublishSingle. - */ - @Around(CLIENT_INTERFACE_PUBLISH_SINGLE_CONFIG_RPC) - public Object interfacePublishSingleRpc(ProceedingJoinPoint pjp, ConfigPublishRequest request, RequestMeta meta) - throws Throwable { - final String md5 = - request.getContent() == null ? null : MD5Utils.md5Hex(request.getContent(), Constants.ENCODE); + * Intercepts configuration publishing operations, records metrics, and logs client requests. + */ + @Around(PUBLISH_CONFIG) + public Object interfacePublishConfig(ProceedingJoinPoint pjp) throws Throwable { + Object[] args = pjp.getArgs(); + ConfigForm configForm = (ConfigForm) args[0]; + ConfigRequestInfo configRequestInfo = (ConfigRequestInfo) args[1]; + String dataId = configForm.getDataId(); + String group = configForm.getGroup(); + String namespaceId = configForm.getNamespaceId(); + String content = configForm.getContent(); + String requestIp = configRequestInfo.getSrcIp(); + String md5 = content == null ? null : MD5Utils.md5Hex(content, Constants.ENCODE); + MetricsMonitor.getPublishMonitor().incrementAndGet(); AtomicLong rtHolder = new AtomicLong(); - Object retVal = logClientRequestRpc("publish", pjp, request, meta, request.getDataId(), request.getGroup(), - request.getTenant(), md5, rtHolder); - MetricsMonitor.getWriteConfigRpcRtTimer().record(rtHolder.get(), TimeUnit.MILLISECONDS); - return retVal; - } - - /** - * PublishSingle. - */ - @Around(CLIENT_INTERFACE_PUBLISH_SINGLE_CONFIG) - public Object interfacePublishSingle(ProceedingJoinPoint pjp, HttpServletRequest request, - HttpServletResponse response, String dataId, String group, String tenant, String content) throws Throwable { - final String md5 = content == null ? null : MD5Utils.md5Hex(content, Constants.ENCODE); - MetricsMonitor.getPublishMonitor().incrementAndGet(); - AtomicLong rtHolder = new AtomicLong(); - Object retVal = logClientRequest("publish", pjp, request, response, dataId, group, tenant, md5, rtHolder); + Object retVal = logClientRequest("publish", pjp, dataId, group, namespaceId, requestIp, md5, rtHolder); MetricsMonitor.getWriteConfigRtTimer().record(rtHolder.get(), TimeUnit.MILLISECONDS); + return retVal; } /** - * RemoveAll. - */ - @Around(CLIENT_INTERFACE_REMOVE_ALL_CONFIG) - public Object interfaceRemoveAll(ProceedingJoinPoint pjp, HttpServletRequest request, HttpServletResponse response, - String dataId, String group, String tenant) throws Throwable { - return logClientRequest("remove", pjp, request, response, dataId, group, tenant, null, null); - } - - /** - * RemoveAll. - */ - @Around(CLIENT_INTERFACE_REMOVE_ALL_CONFIG_RPC) - public Object interfaceRemoveAllRpc(ProceedingJoinPoint pjp, ConfigRemoveRequest request, RequestMeta meta) - throws Throwable { - return logClientRequestRpc("remove", pjp, request, meta, request.getDataId(), request.getGroup(), - request.getTenant(), null, null); - } - - /** - * GetConfig. + * Intercepts configuration get operations, records metrics, and logs client requests. */ - @Around(CLIENT_INTERFACE_GET_CONFIG) - public Object interfaceGetConfig(ProceedingJoinPoint pjp, HttpServletRequest request, HttpServletResponse response, - String dataId, String group, String tenant) throws Throwable { - final String groupKey = GroupKey2.getKey(dataId, group, tenant); - final String md5 = ConfigCacheService.getContentMd5(groupKey); + @Around(GET_CONFIG) + public Object interfaceGetConfig(ProceedingJoinPoint pjp) throws Throwable { + Object[] args = pjp.getArgs(); + ConfigQueryChainRequest chainRequest = (ConfigQueryChainRequest) args[0]; + String dataId = chainRequest.getDataId(); + String group = chainRequest.getGroup(); + String tenant = chainRequest.getTenant(); + String requestIp = null; + if (chainRequest.getAppLabels() != null) { + requestIp = chainRequest.getAppLabels().getOrDefault(BetaGrayRule.CLIENT_IP_LABEL, null); + } + String groupKey = GroupKey2.getKey(dataId, group, tenant); + String md5 = ConfigCacheService.getContentMd5(groupKey); + MetricsMonitor.getConfigMonitor().incrementAndGet(); AtomicLong rtHolder = new AtomicLong(); - Object retVal = logClientRequest("get", pjp, request, response, dataId, group, tenant, md5, rtHolder); + Object retVal = logClientRequest("get", pjp, dataId, group, tenant, requestIp, md5, rtHolder); MetricsMonitor.getReadConfigRtTimer().record(rtHolder.get(), TimeUnit.MILLISECONDS); + return retVal; } /** - * GetConfig. + * Deletes a configuration entry and logs the operation. */ - @Around(CLIENT_INTERFACE_GET_CONFIG_RPC) - public Object interfaceGetConfigRpc(ProceedingJoinPoint pjp, ConfigQueryRequest request, RequestMeta meta) - throws Throwable { - final String groupKey = GroupKey2.getKey(request.getDataId(), request.getGroup(), request.getTenant()); - final String md5 = ConfigCacheService.getContentMd5(groupKey); + @Around(DELETE_CONFIG) + public Object interfaceRemoveConfig(ProceedingJoinPoint pjp) throws Throwable { + Object[] args = pjp.getArgs(); + String dataId = (String) args[0]; + String group = (String) args[1]; + String tenant = (String) args[2]; + String clientIp = (String) args[4]; + String groupKey = GroupKey2.getKey(dataId, group, tenant); + String md5 = ConfigCacheService.getContentMd5(groupKey); + MetricsMonitor.getConfigMonitor().incrementAndGet(); AtomicLong rtHolder = new AtomicLong(); - Object retVal = logClientRequestRpc("get", pjp, request, meta, request.getDataId(), request.getGroup(), - request.getTenant(), md5, rtHolder); - MetricsMonitor.getReadConfigRpcRtTimer().record(rtHolder.get(), TimeUnit.MILLISECONDS); - return retVal; - } - - /** - * Client api request log rt | status | requestIp | opType | dataId | group | datumId | md5. - */ - private Object logClientRequest(String requestType, ProceedingJoinPoint pjp, HttpServletRequest request, - HttpServletResponse response, String dataId, String group, String tenant, String md5, AtomicLong rtHolder) throws Throwable { - final String requestIp = RequestUtil.getRemoteIp(request); - String appName = request.getHeader(RequestUtil.CLIENT_APPNAME_HEADER); - final long st = System.currentTimeMillis(); - Object retVal = pjp.proceed(); - final long rt = System.currentTimeMillis() - st; - if (rtHolder != null) { - rtHolder.set(rt); - } - // rt | status | requestIp | opType | dataId | group | datumId | md5 | - // appName - LogUtil.CLIENT_LOG - .info("{}|{}|{}|{}|{}|{}|{}|{}|{}", rt, retVal, requestIp, requestType, dataId, group, tenant, md5, - appName); + Object retVal = logClientRequest("delete", pjp, dataId, group, tenant, clientIp, md5, rtHolder); + MetricsMonitor.getReadConfigRtTimer().record(rtHolder.get(), TimeUnit.MILLISECONDS); + return retVal; } /** * Client api request log rt | status | requestIp | opType | dataId | group | datumId | md5. */ - private Object logClientRequestRpc(String requestType, ProceedingJoinPoint pjp, Request request, RequestMeta meta, - String dataId, String group, String tenant, String md5, AtomicLong rtHolder) throws Throwable { - final String requestIp = meta.getClientIp(); - String appName = request.getHeader(RequestUtil.CLIENT_APPNAME_HEADER); - final long st = System.currentTimeMillis(); - Response retVal = (Response) pjp.proceed(); - final long rt = System.currentTimeMillis() - st; - if (rtHolder != null) { - rtHolder.set(rt); + private Object logClientRequest(String requestType, ProceedingJoinPoint pjp, String dataId, String group, + String tenant, String requestIp, String md5, AtomicLong rtHolder) throws Throwable { + long startTime = System.currentTimeMillis(); + try { + Object retVal = pjp.proceed(); + + long rt = System.currentTimeMillis() - startTime; + if (rtHolder != null) { + rtHolder.set(rt); + } + + LogUtil.CLIENT_LOG.info("opType: {} | rt: {}ms | status: success | requestIp: {} | dataId: {} | group: {} | tenant: {} | md5: {}", + requestType, rt, requestIp, dataId, group, tenant, md5); + + return retVal; + + } catch (Throwable e) { + long rt = System.currentTimeMillis() - startTime; + if (rtHolder != null) { + rtHolder.set(rt); + } + + LogUtil.CLIENT_LOG.error("opType: {} | rt: {}ms | status: failure | requestIp: {} | dataId: {} | group: {} | tenant: {} | md5: {}", + requestType, rt, requestIp, dataId, group, tenant, md5); + + throw e; } - // rt | status | requestIp | opType | dataId | group | datumId | md5 | - // appName - LogUtil.CLIENT_LOG.info("{}|{}|{}|{}|{}|{}|{}|{}|{}", rt, - retVal.isSuccess() ? retVal.getResultCode() : retVal.getErrorCode(), requestIp, requestType, dataId, - group, tenant, md5, appName); - return retVal; } /** - * GetConfig. + * Handles configuration change listening requests. */ - @Around(CLIENT_INTERFACE_LISTEN_CONFIG_RPC) + @Around(CONFIG_CHANGE_LISTEN_RPC) public Object interfaceListenConfigRpc(ProceedingJoinPoint pjp, ConfigBatchListenRequest request, RequestMeta meta) throws Throwable { MetricsMonitor.getConfigMonitor().incrementAndGet(); @@ -237,11 +173,9 @@ public Object interfaceListenConfigRpc(ProceedingJoinPoint pjp, ConfigBatchListe final long st = System.currentTimeMillis(); Response retVal = (Response) pjp.proceed(); final long rt = System.currentTimeMillis() - st; - // rt | status | requestIp | opType | listen size | listen or cancel | empty | empty | - // appName - LogUtil.CLIENT_LOG.info("{}|{}|{}|{}|{}|{}|{}|{}|{}", rt, - retVal.isSuccess() ? retVal.getResultCode() : retVal.getErrorCode(), requestIp, "listen", request.getConfigListenContexts().size(), - request.isListen(), "", "", appName); + LogUtil.CLIENT_LOG.info("opType: {} | rt: {}ms | status: {} | requestIp: {} | listenSize: {} | listenOrCancel: {} | appName: {}", "listen", + rt, retVal.isSuccess() ? retVal.getResultCode() : retVal.getErrorCode(), requestIp, request.getConfigListenContexts().size(), + request.isListen(), appName); return retVal; } } diff --git a/config/src/main/java/com/alibaba/nacos/config/server/controller/ConfigController.java b/config/src/main/java/com/alibaba/nacos/config/server/controller/ConfigController.java index 07754698852..aa46e63f9fb 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/controller/ConfigController.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/controller/ConfigController.java @@ -214,6 +214,7 @@ public Boolean publishConfig(HttpServletRequest request, HttpServletResponse res ConfigRequestInfo configRequestInfo = new ConfigRequestInfo(); configRequestInfo.setSrcIp(RequestUtil.getRemoteIp(request)); + configRequestInfo.setSrcType("http"); configRequestInfo.setRequestIpApp(RequestUtil.getAppName(request)); configRequestInfo.setBetaIps(request.getHeader("betaIps")); configRequestInfo.setCasMd5(request.getHeader("casMd5")); @@ -299,38 +300,19 @@ public Boolean deleteConfig(HttpServletRequest request, HttpServletResponse resp String clientIp = RequestUtil.getRemoteIp(request); String srcUser = RequestUtil.getSrcUserName(request); - return configOperationService.deleteConfig(dataId, group, tenant, tag, clientIp, srcUser); + return configOperationService.deleteConfig(dataId, group, tenant, tag, clientIp, srcUser, "http"); } /** - * Execute delete config operation. - * - * @return java.lang.Boolean - * @author klw - * @Description: delete configuration based on multiple config ids - * @Date 2019/7/5 10:26 - * @Param [request, response, dataId, group, tenant, tag] + * delete configs based on the IDs list. */ @DeleteMapping(params = "delType=ids") @Secured(action = ActionTypes.WRITE, signType = SignType.CONFIG) public RestResult deleteConfigs(HttpServletRequest request, @RequestParam(value = "ids") List ids) { String clientIp = RequestUtil.getRemoteIp(request); String srcUser = RequestUtil.getSrcUserName(request); - final Timestamp time = TimeUtils.getCurrentTime(); - List configInfoList = configInfoPersistService.removeConfigInfoByIds(ids, clientIp, srcUser); - if (CollectionUtils.isEmpty(configInfoList)) { - return RestResultUtils.success(true); - } - for (ConfigAllInfo configInfo : configInfoList) { - ConfigChangePublisher.notifyConfigChange( - new ConfigDataChangeEvent(configInfo.getDataId(), configInfo.getGroup(), configInfo.getTenant(), - time.getTime())); - - ConfigTraceService.logPersistenceEvent(configInfo.getDataId(), configInfo.getGroup(), - configInfo.getTenant(), null, time.getTime(), clientIp, ConfigTraceService.PERSISTENCE_EVENT, - ConfigTraceService.PERSISTENCE_TYPE_REMOVE, null); - } - return RestResultUtils.success(true); + + return RestResultUtils.success(configOperationService.deleteConfigs(ids, clientIp, srcUser)); } @GetMapping("/catalog") @@ -683,7 +665,7 @@ public RestResult> importAndPublishConfig(HttpServletRequest final String srcIp = RequestUtil.getRemoteIp(request); String requestIpApp = RequestUtil.getAppName(request); final Timestamp time = TimeUtils.getCurrentTime(); - Map saveResult = configInfoPersistService.batchInsertOrUpdate(configInfoList, srcUser, srcIp, + Map saveResult = configOperationService.batchInsertOrUpdate(configInfoList, srcUser, srcIp, null, policy); for (ConfigInfo configInfo : configInfoList) { ConfigChangePublisher.notifyConfigChange( @@ -935,7 +917,7 @@ public RestResult> cloneConfig(HttpServletRequest request, final String srcIp = RequestUtil.getRemoteIp(request); String requestIpApp = RequestUtil.getAppName(request); final Timestamp time = TimeUtils.getCurrentTime(); - Map saveResult = configInfoPersistService.batchInsertOrUpdate(configInfoList4Clone, srcUser, + Map saveResult = configOperationService.batchInsertOrUpdate(configInfoList4Clone, srcUser, srcIp, null, policy); for (ConfigInfo configInfo : configInfoList4Clone) { ConfigChangePublisher.notifyConfigChange( diff --git a/config/src/main/java/com/alibaba/nacos/config/server/controller/v2/ConfigControllerV2.java b/config/src/main/java/com/alibaba/nacos/config/server/controller/v2/ConfigControllerV2.java index f6897265173..942fe1e6ad5 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/controller/v2/ConfigControllerV2.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/controller/v2/ConfigControllerV2.java @@ -142,6 +142,7 @@ public Result publishConfig(ConfigForm configForm, HttpServletRequest r ConfigRequestInfo configRequestInfo = new ConfigRequestInfo(); configRequestInfo.setSrcIp(RequestUtil.getRemoteIp(request)); + configRequestInfo.setSrcType("http"); configRequestInfo.setRequestIpApp(RequestUtil.getAppName(request)); configRequestInfo.setBetaIps(request.getHeader("betaIps")); configRequestInfo.setCasMd5(request.getHeader("casMd5")); @@ -169,7 +170,7 @@ public Result deleteConfig(HttpServletRequest request, @RequestParam("d String clientIp = RequestUtil.getRemoteIp(request); String srcUser = RequestUtil.getSrcUserName(request); - return Result.success(configOperationService.deleteConfig(dataId, group, namespaceId, tag, clientIp, srcUser)); + return Result.success(configOperationService.deleteConfig(dataId, group, namespaceId, tag, clientIp, srcUser, "http")); } /** diff --git a/config/src/main/java/com/alibaba/nacos/config/server/model/ConfigRequestInfo.java b/config/src/main/java/com/alibaba/nacos/config/server/model/ConfigRequestInfo.java index a5724fdbf1a..bed97a5e4ee 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/model/ConfigRequestInfo.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/model/ConfigRequestInfo.java @@ -30,14 +30,17 @@ public class ConfigRequestInfo implements Serializable { private String srcIp; + private String srcType; + private String requestIpApp; private String betaIps; private String casMd5; - public ConfigRequestInfo(String srcIp, String requestIpApp, String betaIps, String casMd5) { + public ConfigRequestInfo(String srcIp, String srcType, String requestIpApp, String betaIps, String casMd5) { this.srcIp = srcIp; + this.srcType = srcType; this.requestIpApp = requestIpApp; this.betaIps = betaIps; this.casMd5 = casMd5; @@ -54,6 +57,14 @@ public void setSrcIp(String srcIp) { this.srcIp = srcIp; } + public String getSrcType() { + return srcType; + } + + public void setSrcType(String srcType) { + this.srcType = srcType; + } + public String getRequestIpApp() { return requestIpApp; } diff --git a/config/src/main/java/com/alibaba/nacos/config/server/monitor/MetricsMonitor.java b/config/src/main/java/com/alibaba/nacos/config/server/monitor/MetricsMonitor.java index 33842db2616..c83aa8252f0 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/monitor/MetricsMonitor.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/monitor/MetricsMonitor.java @@ -175,21 +175,11 @@ public static Timer getReadConfigRtTimer() { .timer(METER_REGISTRY, "nacos_timer", "module", "config", "name", "readConfigRt"); } - public static Timer getReadConfigRpcRtTimer() { - return NacosMeterRegistryCenter - .timer(METER_REGISTRY, "nacos_timer", "module", "config", "name", "readConfigRpcRt"); - } - public static Timer getWriteConfigRtTimer() { return NacosMeterRegistryCenter .timer(METER_REGISTRY, "nacos_timer", "module", "config", "name", "writeConfigRt"); } - public static Timer getWriteConfigRpcRtTimer() { - return NacosMeterRegistryCenter - .timer(METER_REGISTRY, "nacos_timer", "module", "config", "name", "writeConfigRpcRt"); - } - public static Timer getNotifyRtTimer() { return NacosMeterRegistryCenter.timer(METER_REGISTRY, "nacos_timer", "module", "config", "name", "notifyRt"); } diff --git a/config/src/main/java/com/alibaba/nacos/config/server/remote/ConfigPublishRequestHandler.java b/config/src/main/java/com/alibaba/nacos/config/server/remote/ConfigPublishRequestHandler.java index 83af673362b..4f459b80599 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/remote/ConfigPublishRequestHandler.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/remote/ConfigPublishRequestHandler.java @@ -100,6 +100,7 @@ public ConfigPublishResponse handle(ConfigPublishRequest request, RequestMeta me ConfigRequestInfo configRequestInfo = new ConfigRequestInfo(); configRequestInfo.setSrcIp(srcIp); + configRequestInfo.setSrcType("rpc"); configRequestInfo.setRequestIpApp(meta.getLabels().get(Constants.APPNAME)); configRequestInfo.setBetaIps(request.getAdditionParam("betaIps")); configRequestInfo.setCasMd5(request.getCasMd5()); diff --git a/config/src/main/java/com/alibaba/nacos/config/server/remote/ConfigRemoveRequestHandler.java b/config/src/main/java/com/alibaba/nacos/config/server/remote/ConfigRemoveRequestHandler.java index 94e46006d69..ebbd25cbdf2 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/remote/ConfigRemoveRequestHandler.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/remote/ConfigRemoveRequestHandler.java @@ -21,15 +21,8 @@ import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.remote.request.RequestMeta; import com.alibaba.nacos.auth.annotation.Secured; -import com.alibaba.nacos.common.utils.StringUtils; -import com.alibaba.nacos.config.server.model.event.ConfigDataChangeEvent; -import com.alibaba.nacos.config.server.model.gray.TagGrayRule; -import com.alibaba.nacos.config.server.service.ConfigChangePublisher; -import com.alibaba.nacos.config.server.service.repository.ConfigInfoGrayPersistService; -import com.alibaba.nacos.config.server.service.repository.ConfigInfoPersistService; -import com.alibaba.nacos.config.server.service.trace.ConfigTraceService; +import com.alibaba.nacos.config.server.service.ConfigOperationService; import com.alibaba.nacos.config.server.utils.ParamUtils; -import com.alibaba.nacos.config.server.utils.TimeUtils; import com.alibaba.nacos.core.control.TpsControl; import com.alibaba.nacos.core.paramcheck.ExtractorManager; import com.alibaba.nacos.core.paramcheck.impl.ConfigRequestParamExtractor; @@ -39,8 +32,6 @@ import com.alibaba.nacos.plugin.auth.constant.SignType; import org.springframework.stereotype.Component; -import java.sql.Timestamp; - /** * handler to remove config. * @@ -50,14 +41,10 @@ @Component public class ConfigRemoveRequestHandler extends RequestHandler { - private final ConfigInfoPersistService configInfoPersistService; - - private final ConfigInfoGrayPersistService configInfoGrayPersistService; + private final ConfigOperationService configOperationService; - public ConfigRemoveRequestHandler(ConfigInfoPersistService configInfoPersistService, - ConfigInfoGrayPersistService configInfoGrayPersistService) { - this.configInfoPersistService = configInfoPersistService; - this.configInfoGrayPersistService = configInfoGrayPersistService; + public ConfigRemoveRequestHandler(ConfigOperationService configOperationService) { + this.configOperationService = configOperationService; } @Override @@ -66,36 +53,18 @@ public ConfigRemoveRequestHandler(ConfigInfoPersistService configInfoPersistServ @ExtractorManager.Extractor(rpcExtractor = ConfigRequestParamExtractor.class) public ConfigRemoveResponse handle(ConfigRemoveRequest configRemoveRequest, RequestMeta meta) throws NacosException { - // check tenant String tenant = configRemoveRequest.getTenant(); String dataId = configRemoveRequest.getDataId(); String group = configRemoveRequest.getGroup(); String tag = configRemoveRequest.getTag(); - String underLine = "_"; + String clientIp = meta.getClientIp(); + ParamUtils.checkTenant(tenant); + ParamUtils.checkParam(dataId, group, "datumId", "rm"); + ParamUtils.checkParam(tag); + try { - ParamUtils.checkTenant(tenant); - ParamUtils.checkParam(dataId, group, "datumId", "rm"); - ParamUtils.checkParam(tag); - String persistEvent = ConfigTraceService.PERSISTENCE_EVENT; - - String clientIp = meta.getClientIp(); - String grayName = null; - if (StringUtils.isBlank(tag)) { - - configInfoPersistService.removeConfigInfo(dataId, group, tenant, clientIp, null); - } else { - persistEvent = ConfigTraceService.PERSISTENCE_EVENT_TAG + underLine + tag; - - grayName = TagGrayRule.TYPE_TAG + underLine + tag; - configInfoGrayPersistService.removeConfigInfoGray(dataId, group, tenant, grayName, clientIp, null); - } - final Timestamp time = TimeUtils.getCurrentTime(); - ConfigTraceService.logPersistenceEvent(dataId, group, tenant, null, time.getTime(), clientIp, persistEvent, - ConfigTraceService.PERSISTENCE_TYPE_REMOVE, null); - ConfigChangePublisher.notifyConfigChange( - new ConfigDataChangeEvent(dataId, group, tenant, grayName, time.getTime())); + configOperationService.deleteConfig(dataId, group, tenant, tag, clientIp, null, "rpc"); return ConfigRemoveResponse.buildSuccessResponse(); - } catch (Exception e) { Loggers.REMOTE_DIGEST.error("remove config error,error msg is {}", e.getMessage(), e); return ConfigRemoveResponse.buildFailResponse(e.getMessage()); diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigOperationService.java b/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigOperationService.java index 3b3f36b8a4a..e4cc39ddec9 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigOperationService.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigOperationService.java @@ -22,9 +22,11 @@ import com.alibaba.nacos.common.utils.MapUtil; import com.alibaba.nacos.common.utils.NumberUtils; import com.alibaba.nacos.common.utils.StringUtils; +import com.alibaba.nacos.config.server.model.ConfigAllInfo; import com.alibaba.nacos.config.server.model.ConfigInfo; import com.alibaba.nacos.config.server.model.ConfigOperateResult; import com.alibaba.nacos.config.server.model.ConfigRequestInfo; +import com.alibaba.nacos.config.server.model.SameConfigPolicy; import com.alibaba.nacos.config.server.model.event.ConfigDataChangeEvent; import com.alibaba.nacos.config.server.model.form.ConfigForm; import com.alibaba.nacos.config.server.model.gray.BetaGrayRule; @@ -293,13 +295,13 @@ private int getMaxGrayVersionCount() { * Synchronously delete all pre-aggregation data under a dataId. */ public Boolean deleteConfig(String dataId, String group, String namespaceId, String tag, String clientIp, - String srcUser) { + String srcUser, String srcType) { String persistEvent = ConfigTraceService.PERSISTENCE_EVENT; String grayName = ""; if (StringUtils.isBlank(tag)) { configInfoPersistService.removeConfigInfo(dataId, group, namespaceId, clientIp, srcUser); } else { - persistEvent = ConfigTraceService.PERSISTENCE_EVENT_TAG + "-" + tag; + persistEvent = ConfigTraceService.PERSISTENCE_EVENT_TAG + "_" + tag; grayName = TagGrayRule.TYPE_TAG + "_" + tag; configInfoGrayPersistService.removeConfigInfoGray(dataId, group, namespaceId, grayName, clientIp, srcUser); deleteConfigTagv1(dataId, group, namespaceId, tag, clientIp, srcUser); @@ -319,6 +321,36 @@ private void deleteConfigTagv1(String dataId, String group, String namespaceId, configInfoTagPersistService.removeConfigInfoTag(dataId, group, namespaceId, tag, clientIp, srcUser); } } + + /** + * Deletes configuration information based on the IDs list. + */ + public Boolean deleteConfigs(List ids, String srcIp, String srcUser) { + List configInfoList = configInfoPersistService.removeConfigInfoByIds(ids, srcIp, srcUser); + if (configInfoList == null || configInfoList.isEmpty()) { + return true; + } + + Timestamp time = TimeUtils.getCurrentTime(); + for (ConfigAllInfo configInfo : configInfoList) { + ConfigChangePublisher.notifyConfigChange( + new ConfigDataChangeEvent(configInfo.getDataId(), configInfo.getGroup(), configInfo.getTenant(), + time.getTime())); + ConfigTraceService.logPersistenceEvent(configInfo.getDataId(), configInfo.getGroup(), + configInfo.getTenant(), null, time.getTime(), srcIp, ConfigTraceService.PERSISTENCE_EVENT, + ConfigTraceService.PERSISTENCE_TYPE_REMOVE, null); + } + + return true; + } + + /** + * Batch insert or update configuration information. + */ + public Map batchInsertOrUpdate(List configInfoList, String srcUser, String srcIp, + Map configAdvanceInfo, SameConfigPolicy policy) throws NacosException { + return configInfoPersistService.batchInsertOrUpdate(configInfoList, srcUser, srcIp, configAdvanceInfo, policy); + } public Map getConfigAdvanceInfo(ConfigForm configForm) { Map configAdvanceInfo = new HashMap<>(10); diff --git a/config/src/test/java/com/alibaba/nacos/config/server/aspect/CapacityManagementAspectTest.java b/config/src/test/java/com/alibaba/nacos/config/server/aspect/CapacityManagementAspectTest.java index 8e3d8622ab8..62da946990d 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/aspect/CapacityManagementAspectTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/aspect/CapacityManagementAspectTest.java @@ -18,8 +18,10 @@ import com.alibaba.nacos.config.server.constant.CounterMode; import com.alibaba.nacos.config.server.model.ConfigInfoWrapper; +import com.alibaba.nacos.config.server.model.ConfigRequestInfo; import com.alibaba.nacos.config.server.model.capacity.GroupCapacity; import com.alibaba.nacos.config.server.model.capacity.TenantCapacity; +import com.alibaba.nacos.config.server.model.form.ConfigForm; import com.alibaba.nacos.config.server.service.capacity.CapacityService; import com.alibaba.nacos.config.server.service.repository.ConfigInfoPersistService; import com.alibaba.nacos.config.server.utils.PropertyUtil; @@ -33,12 +35,8 @@ import org.mockito.Mock; import org.mockito.MockedStatic; import org.mockito.Mockito; -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.test.context.junit.jupiter.SpringExtension; -import static com.alibaba.nacos.config.server.aspect.CapacityManagementAspect.LimitType.OVER_CLUSTER_QUOTA; -import static com.alibaba.nacos.config.server.aspect.CapacityManagementAspect.LimitType.OVER_MAX_SIZE; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.ArgumentMatchers.any; @@ -49,7 +47,7 @@ @ExtendWith(SpringExtension.class) class CapacityManagementAspectTest { - final String mockProceedingJoinPointResult = "mock success return"; + final Boolean mockProceedingJoinPointResult = true; final String mockDataId = "mockDataId"; @@ -57,7 +55,11 @@ class CapacityManagementAspectTest { final String mockTenant = "mockTenant"; - final String mockContent = "mockContent"; + @Mock + private ConfigForm configForm; + + @Mock + private ConfigRequestInfo configRequestInfo; @Mock ProceedingJoinPoint proceedingJoinPoint; @@ -81,7 +83,7 @@ class CapacityManagementAspectTest { @BeforeEach void before() throws Throwable { - //PropertyUtil.isCapacityLimitCheck() + // Mock static methods propertyUtilMockedStatic = Mockito.mockStatic(PropertyUtil.class); when(PropertyUtil.getCorrectUsageDelay()).thenReturn(10 * 60); when(PropertyUtil.getDefaultMaxAggrSize()).thenReturn(1024); @@ -90,15 +92,17 @@ void before() throws Throwable { envUtilMockedStatic = Mockito.mockStatic(EnvUtil.class); when(EnvUtil.getProperty(CommonConstant.NACOS_PLUGIN_DATASOURCE_LOG, Boolean.class, false)).thenReturn(true); + // Initialize the aspect with mocked dependencies capacityManagementAspect = new CapacityManagementAspect(configInfoPersistService, capacityService); - when(proceedingJoinPoint.proceed()).thenReturn(mockProceedingJoinPointResult); - + // Mock the behavior of the ProceedingJoinPoint + mockException = new RuntimeException("mock exception"); when(localMockProceedingJoinPoint.proceed()).thenThrow(mockException); } @AfterEach void after() { + // Close static mocks propertyUtilMockedStatic.close(); envUtilMockedStatic.close(); } @@ -110,12 +114,9 @@ void testAroundSyncUpdateConfigAllForInsertAspect() throws Throwable { // 1. has tenant: true // 2. capacity limit check: false when(PropertyUtil.isManageCapacity()).thenReturn(false); - MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(); - MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse(); + when(proceedingJoinPoint.proceed()).thenReturn(mockProceedingJoinPointResult); - String localMockResult = (String) capacityManagementAspect.aroundSyncUpdateConfigAll(proceedingJoinPoint, - mockHttpServletRequest, mockHttpServletResponse, mockDataId, mockGroup, mockContent, null, null, - mockTenant, null); + Boolean localMockResult = (Boolean) capacityManagementAspect.aroundSyncUpdateConfigAll(proceedingJoinPoint); Mockito.verify(proceedingJoinPoint, Mockito.times(1)).proceed(); Mockito.verify(configInfoPersistService, Mockito.times(0)).findConfigInfo(any(), any(), any()); assert localMockResult.equals(mockProceedingJoinPointResult); @@ -130,15 +131,17 @@ void testAroundSyncUpdateConfigAllForInsertAspect1() throws Throwable { // 3. over cluster quota: true when(PropertyUtil.isManageCapacity()).thenReturn(true); when(PropertyUtil.isCapacityLimitCheck()).thenReturn(true); + when(proceedingJoinPoint.getArgs()).thenReturn(new Object[]{configForm, configRequestInfo}); + when(configForm.getDataId()).thenReturn(mockDataId); + when(configForm.getGroup()).thenReturn(mockGroup); + when(configForm.getNamespaceId()).thenReturn(mockTenant); + when(configForm.getContent()).thenReturn("content"); + when(configRequestInfo.getSrcIp()).thenReturn("127.0.0.1"); when(configInfoPersistService.findConfigInfo(any(), any(), any())).thenReturn(null); when(capacityService.insertAndUpdateClusterUsage(any(), anyBoolean())).thenReturn(false); - MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(); - MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse(); - String localMockResult = (String) capacityManagementAspect.aroundSyncUpdateConfigAll(proceedingJoinPoint, - mockHttpServletRequest, mockHttpServletResponse, mockDataId, mockGroup, mockContent, null, null, - mockTenant, null); - assertEquals(localMockResult, String.valueOf(OVER_CLUSTER_QUOTA.status)); + Boolean localMockResult = (Boolean) capacityManagementAspect.aroundSyncUpdateConfigAll(proceedingJoinPoint); + assertEquals(false, localMockResult); Mockito.verify(proceedingJoinPoint, Mockito.times(0)).proceed(); } @@ -152,18 +155,21 @@ void testAroundSyncUpdateConfigAllForInsertAspect2Tenant() throws Throwable { // 4. tenant capacity: null when(PropertyUtil.isManageCapacity()).thenReturn(true); when(PropertyUtil.isCapacityLimitCheck()).thenReturn(true); + when(proceedingJoinPoint.getArgs()).thenReturn(new Object[]{configForm, configRequestInfo}); + when(proceedingJoinPoint.proceed()).thenReturn(mockProceedingJoinPointResult); + when(configForm.getDataId()).thenReturn(mockDataId); + when(configForm.getGroup()).thenReturn(mockGroup); + when(configForm.getNamespaceId()).thenReturn(mockTenant); + when(configForm.getContent()).thenReturn("content"); + when(configRequestInfo.getSrcIp()).thenReturn("127.0.0.1"); when(configInfoPersistService.findConfigInfo(any(), any(), any())).thenReturn(null); when(capacityService.insertAndUpdateClusterUsage(any(), anyBoolean())).thenReturn(true); when(capacityService.getTenantCapacity(eq(mockTenant))).thenReturn(null); when(capacityService.updateTenantUsage(eq(CounterMode.INCREMENT), eq(mockTenant))).thenReturn(true); - MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(); - MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse(); - String localMockResult = (String) capacityManagementAspect.aroundSyncUpdateConfigAll(proceedingJoinPoint, - mockHttpServletRequest, mockHttpServletResponse, mockDataId, mockGroup, mockContent, null, null, - mockTenant, null); - assertEquals(localMockResult, mockProceedingJoinPointResult); + Boolean localMockResult = (Boolean) capacityManagementAspect.aroundSyncUpdateConfigAll(proceedingJoinPoint); + assertEquals(mockProceedingJoinPointResult, localMockResult); Mockito.verify(capacityService, Mockito.times(1)).initTenantCapacity(eq(mockTenant)); Mockito.verify(capacityService, Mockito.times(1)).updateTenantUsage(eq(CounterMode.INCREMENT), eq(mockTenant)); Mockito.verify(proceedingJoinPoint, Mockito.times(1)).proceed(); @@ -181,16 +187,19 @@ void testAroundSyncUpdateConfigAllForInsertAspect2Group() throws Throwable { when(PropertyUtil.isCapacityLimitCheck()).thenReturn(true); when(configInfoPersistService.findConfigInfo(any(), any(), any())).thenReturn(null); when(capacityService.insertAndUpdateClusterUsage(any(), anyBoolean())).thenReturn(true); - when(capacityService.getGroupCapacity(eq(mockGroup))).thenReturn(null); when(capacityService.updateGroupUsage(eq(CounterMode.INCREMENT), eq(mockGroup))).thenReturn(true); - MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(); - MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse(); - String localMockResult = (String) capacityManagementAspect.aroundSyncUpdateConfigAll(proceedingJoinPoint, - mockHttpServletRequest, mockHttpServletResponse, mockDataId, mockGroup, mockContent, null, null, null, - null); - assertEquals(localMockResult, mockProceedingJoinPointResult); + when(proceedingJoinPoint.getArgs()).thenReturn(new Object[]{configForm, configRequestInfo}); + when(configForm.getDataId()).thenReturn(mockDataId); + when(configForm.getGroup()).thenReturn(mockGroup); + when(configForm.getContent()).thenReturn("content"); + when(configRequestInfo.getSrcIp()).thenReturn("127.0.0.1"); + when(configRequestInfo.getSrcType()).thenReturn("http"); + when(proceedingJoinPoint.proceed()).thenReturn(mockProceedingJoinPointResult); + + Boolean localMockResult = (Boolean) capacityManagementAspect.aroundSyncUpdateConfigAll(proceedingJoinPoint); + assertEquals(mockProceedingJoinPointResult, localMockResult); Mockito.verify(capacityService, Mockito.times(1)).initGroupCapacity(eq(mockGroup)); Mockito.verify(capacityService, Mockito.times(1)).updateGroupUsage(eq(CounterMode.INCREMENT), eq(mockGroup)); Mockito.verify(proceedingJoinPoint, Mockito.times(1)).proceed(); @@ -207,21 +216,25 @@ void testAroundSyncUpdateConfigAllForInsertAspect3Tenant() throws Throwable { // 5. over tenant max size: true/false (if tenant max size is 0, will use default max size) when(PropertyUtil.isManageCapacity()).thenReturn(true); when(PropertyUtil.isCapacityLimitCheck()).thenReturn(true); + when(proceedingJoinPoint.getArgs()).thenReturn(new Object[]{configForm, configRequestInfo}); + when(proceedingJoinPoint.proceed()).thenReturn(mockProceedingJoinPointResult); + when(configForm.getDataId()).thenReturn(mockDataId); + when(configForm.getGroup()).thenReturn(mockGroup); + when(configForm.getNamespaceId()).thenReturn(mockTenant); + when(configForm.getContent()).thenReturn("content"); + when(configRequestInfo.getSrcIp()).thenReturn("127.0.0.1"); when(configInfoPersistService.findConfigInfo(any(), any(), any())).thenReturn(null); when(capacityService.insertAndUpdateClusterUsage(any(), anyBoolean())).thenReturn(true); when(capacityService.updateTenantUsage(eq(CounterMode.INCREMENT), eq(mockTenant))).thenReturn(true); + TenantCapacity localTenantCapacity = new TenantCapacity(); localTenantCapacity.setTenant(mockTenant); localTenantCapacity.setMaxSize(0); localTenantCapacity.setMaxAggrCount(0); when(capacityService.getTenantCapacity(eq(mockTenant))).thenReturn(localTenantCapacity); - MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(); - MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse(); - String localMockResult = (String) capacityManagementAspect.aroundSyncUpdateConfigAll(proceedingJoinPoint, - mockHttpServletRequest, mockHttpServletResponse, mockDataId, mockGroup, mockContent, null, null, - mockTenant, null); - assertEquals(localMockResult, mockProceedingJoinPointResult); + Boolean localMockResult = (Boolean) capacityManagementAspect.aroundSyncUpdateConfigAll(proceedingJoinPoint); + assertEquals(mockProceedingJoinPointResult, localMockResult); Mockito.verify(capacityService, Mockito.times(0)).initTenantCapacity(eq(mockTenant)); Mockito.verify(capacityService, Mockito.times(1)).updateTenantUsage(eq(CounterMode.INCREMENT), eq(mockTenant)); Mockito.verify(proceedingJoinPoint, Mockito.times(1)).proceed(); @@ -229,18 +242,14 @@ void testAroundSyncUpdateConfigAllForInsertAspect3Tenant() throws Throwable { // 5. over tenant max size: true localTenantCapacity.setMaxSize(1); localTenantCapacity.setMaxAggrCount(1); - localMockResult = (String) capacityManagementAspect.aroundSyncUpdateConfigAll(proceedingJoinPoint, - mockHttpServletRequest, mockHttpServletResponse, mockDataId, mockGroup, mockContent, null, null, - mockTenant, null); - assertEquals(localMockResult, String.valueOf(OVER_MAX_SIZE.status)); + localMockResult = (Boolean) capacityManagementAspect.aroundSyncUpdateConfigAll(proceedingJoinPoint); + assertEquals(false, localMockResult); // 5. over tenant max size: true localTenantCapacity.setMaxSize(10 * 1024); localTenantCapacity.setMaxAggrCount(1024); - localMockResult = (String) capacityManagementAspect.aroundSyncUpdateConfigAll(proceedingJoinPoint, - mockHttpServletRequest, mockHttpServletResponse, mockDataId, mockGroup, mockContent, null, null, - mockTenant, null); - assertEquals(localMockResult, mockProceedingJoinPointResult); + localMockResult = (Boolean) capacityManagementAspect.aroundSyncUpdateConfigAll(proceedingJoinPoint); + assertEquals(mockProceedingJoinPointResult, localMockResult); } @Test @@ -254,21 +263,24 @@ void testAroundSyncUpdateConfigAllForInsertAspect3Group() throws Throwable { // 5. over tenant max size: true/false (if tenant max size is 0, will use default max size) when(PropertyUtil.isManageCapacity()).thenReturn(true); when(PropertyUtil.isCapacityLimitCheck()).thenReturn(true); + when(proceedingJoinPoint.getArgs()).thenReturn(new Object[]{configForm, configRequestInfo}); + when(proceedingJoinPoint.proceed()).thenReturn(mockProceedingJoinPointResult); + when(configForm.getDataId()).thenReturn(mockDataId); + when(configForm.getGroup()).thenReturn(mockGroup); + when(configForm.getContent()).thenReturn("content"); + when(configRequestInfo.getSrcIp()).thenReturn("127.0.0.1"); when(configInfoPersistService.findConfigInfo(any(), any(), any())).thenReturn(null); when(capacityService.insertAndUpdateClusterUsage(any(), anyBoolean())).thenReturn(true); when(capacityService.updateGroupUsage(eq(CounterMode.INCREMENT), eq(mockGroup))).thenReturn(true); + GroupCapacity localGroupCapacity = new GroupCapacity(); localGroupCapacity.setGroup(mockGroup); localGroupCapacity.setMaxSize(0); localGroupCapacity.setMaxAggrCount(0); when(capacityService.getGroupCapacity(eq(mockGroup))).thenReturn(localGroupCapacity); - MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(); - MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse(); - String localMockResult = (String) capacityManagementAspect.aroundSyncUpdateConfigAll(proceedingJoinPoint, - mockHttpServletRequest, mockHttpServletResponse, mockDataId, mockGroup, mockContent, null, null, null, - null); - assertEquals(localMockResult, mockProceedingJoinPointResult); + Boolean localMockResult = (Boolean) capacityManagementAspect.aroundSyncUpdateConfigAll(proceedingJoinPoint); + assertEquals(true, localMockResult); Mockito.verify(capacityService, Mockito.times(0)).initGroupCapacity(eq(mockGroup)); Mockito.verify(capacityService, Mockito.times(1)).updateGroupUsage(eq(CounterMode.INCREMENT), eq(mockGroup)); Mockito.verify(proceedingJoinPoint, Mockito.times(1)).proceed(); @@ -276,18 +288,14 @@ void testAroundSyncUpdateConfigAllForInsertAspect3Group() throws Throwable { // 5. over tenant max size: true localGroupCapacity.setMaxSize(1); localGroupCapacity.setMaxAggrCount(1); - localMockResult = (String) capacityManagementAspect.aroundSyncUpdateConfigAll(proceedingJoinPoint, - mockHttpServletRequest, mockHttpServletResponse, mockDataId, mockGroup, mockContent, null, null, null, - null); - assertEquals(localMockResult, String.valueOf(OVER_MAX_SIZE.status)); + localMockResult = (Boolean) capacityManagementAspect.aroundSyncUpdateConfigAll(proceedingJoinPoint); + assertEquals(false, localMockResult); - // 5. over tenant max size: true + // 5. over tenant max size: true localGroupCapacity.setMaxSize(10 * 1024); localGroupCapacity.setMaxAggrCount(1024); - localMockResult = (String) capacityManagementAspect.aroundSyncUpdateConfigAll(proceedingJoinPoint, - mockHttpServletRequest, mockHttpServletResponse, mockDataId, mockGroup, mockContent, null, null, null, - null); - assertEquals(localMockResult, mockProceedingJoinPointResult); + localMockResult = (Boolean) capacityManagementAspect.aroundSyncUpdateConfigAll(proceedingJoinPoint); + assertEquals(mockProceedingJoinPointResult, localMockResult); } @Test @@ -300,21 +308,25 @@ void testAroundSyncUpdateConfigAllForUpdateAspectTenant() throws Throwable { // 5. over tenant quota: false when(PropertyUtil.isManageCapacity()).thenReturn(true); when(PropertyUtil.isCapacityLimitCheck()).thenReturn(true); + when(proceedingJoinPoint.getArgs()).thenReturn(new Object[]{configForm, configRequestInfo}); + when(proceedingJoinPoint.proceed()).thenReturn(mockProceedingJoinPointResult); + when(configForm.getDataId()).thenReturn("dataId"); + when(configForm.getGroup()).thenReturn("group"); + when(configForm.getNamespaceId()).thenReturn("mockTenant"); + when(configForm.getContent()).thenReturn("content"); + when(configRequestInfo.getSrcIp()).thenReturn("127.0.0.1"); when(configInfoPersistService.findConfigInfo(any(), any(), any())).thenReturn(new ConfigInfoWrapper()); when(capacityService.insertAndUpdateClusterUsage(any(), anyBoolean())).thenReturn(true); when(capacityService.updateTenantUsage(eq(CounterMode.INCREMENT), eq(mockTenant))).thenReturn(true); + TenantCapacity localTenantCapacity = new TenantCapacity(); localTenantCapacity.setTenant(mockTenant); localTenantCapacity.setMaxSize(10 * 1024); localTenantCapacity.setMaxAggrCount(1024); when(capacityService.getTenantCapacity(eq(mockTenant))).thenReturn(localTenantCapacity); - MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(); - MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse(); - String localMockResult = (String) capacityManagementAspect.aroundSyncUpdateConfigAll(proceedingJoinPoint, - mockHttpServletRequest, mockHttpServletResponse, mockDataId, mockGroup, mockContent, null, null, - mockTenant, null); - assertEquals(localMockResult, mockProceedingJoinPointResult); + Boolean localMockResult = (Boolean) capacityManagementAspect.aroundSyncUpdateConfigAll(proceedingJoinPoint); + assertEquals(mockProceedingJoinPointResult, localMockResult); Mockito.verify(capacityService, Mockito.times(0)).initTenantCapacity(eq(mockTenant)); Mockito.verify(capacityService, Mockito.times(0)).updateTenantUsage(eq(CounterMode.INCREMENT), eq(mockTenant)); Mockito.verify(capacityService, Mockito.times(1)).getTenantCapacity(eq(mockTenant)); @@ -331,21 +343,25 @@ void testAroundSyncUpdateConfigAllForUpdateAspectGroup() throws Throwable { // 5. over group quota: false when(PropertyUtil.isManageCapacity()).thenReturn(true); when(PropertyUtil.isCapacityLimitCheck()).thenReturn(true); + when(proceedingJoinPoint.getArgs()).thenReturn(new Object[]{configForm, configRequestInfo}); + when(proceedingJoinPoint.proceed()).thenReturn(mockProceedingJoinPointResult); + when(configForm.getDataId()).thenReturn("dataId"); + when(configForm.getContent()).thenReturn("content"); + when(configForm.getGroup()).thenReturn(mockGroup); + when(configRequestInfo.getSrcIp()).thenReturn("127.0.0.1"); + when(configRequestInfo.getSrcType()).thenReturn("http"); when(configInfoPersistService.findConfigInfo(any(), any(), any())).thenReturn(new ConfigInfoWrapper()); when(capacityService.insertAndUpdateClusterUsage(any(), anyBoolean())).thenReturn(true); when(capacityService.updateGroupUsage(eq(CounterMode.INCREMENT), eq(mockGroup))).thenReturn(true); + GroupCapacity localGroupCapacity = new GroupCapacity(); localGroupCapacity.setGroup(mockGroup); localGroupCapacity.setMaxSize(10 * 1024); localGroupCapacity.setMaxAggrCount(1024); when(capacityService.getGroupCapacity(eq(mockGroup))).thenReturn(localGroupCapacity); - MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(); - MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse(); - String localMockResult = (String) capacityManagementAspect.aroundSyncUpdateConfigAll(proceedingJoinPoint, - mockHttpServletRequest, mockHttpServletResponse, mockDataId, mockGroup, mockContent, null, null, null, - null); - assertEquals(localMockResult, mockProceedingJoinPointResult); + Boolean localMockResult = (Boolean) capacityManagementAspect.aroundSyncUpdateConfigAll(proceedingJoinPoint); + assertEquals(mockProceedingJoinPointResult, localMockResult); Mockito.verify(capacityService, Mockito.times(0)).initGroupCapacity(eq(mockGroup)); Mockito.verify(capacityService, Mockito.times(1)).getGroupCapacity(eq(mockGroup)); Mockito.verify(capacityService, Mockito.times(0)).updateGroupUsage(eq(CounterMode.INCREMENT), eq(mockGroup)); @@ -363,25 +379,28 @@ void testAroundSyncUpdateConfigAllForInsertRollbackAspect() throws Throwable { // 5. over tenant max size: true/false (if tenant max size is 0, will use default max size) when(PropertyUtil.isManageCapacity()).thenReturn(true); when(PropertyUtil.isCapacityLimitCheck()).thenReturn(true); + when(localMockProceedingJoinPoint.getArgs()).thenReturn(new Object[]{configForm, configRequestInfo}); + when(configForm.getDataId()).thenReturn("dataId"); + when(configForm.getGroup()).thenReturn("group"); + when(configForm.getNamespaceId()).thenReturn("mockTenant"); + when(configForm.getContent()).thenReturn("content"); + when(configRequestInfo.getSrcIp()).thenReturn("127.0.0.1"); when(configInfoPersistService.findConfigInfo(any(), any(), any())).thenReturn(null); when(capacityService.insertAndUpdateClusterUsage(any(), anyBoolean())).thenReturn(true); when(capacityService.updateClusterUsage(any())).thenReturn(true); when(capacityService.updateTenantUsage(any(), eq(mockTenant))).thenReturn(true); + TenantCapacity localTenantCapacity = new TenantCapacity(); localTenantCapacity.setTenant(mockTenant); localTenantCapacity.setMaxSize(10 * 1024); localTenantCapacity.setMaxAggrCount(1024); when(capacityService.getTenantCapacity(eq(mockTenant))).thenReturn(localTenantCapacity); - String localMockResult = null; - MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(); - MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse(); + Boolean localMockResult = null; try { - localMockResult = (String) capacityManagementAspect.aroundSyncUpdateConfigAll(localMockProceedingJoinPoint, - mockHttpServletRequest, mockHttpServletResponse, mockDataId, mockGroup, mockContent, null, null, - mockTenant, null); + localMockResult = (Boolean) capacityManagementAspect.aroundSyncUpdateConfigAll(localMockProceedingJoinPoint); } catch (Throwable e) { - assertEquals(e.getMessage(), mockException.getMessage()); + assertEquals(mockException.getMessage(), e.getMessage()); } assertNull(localMockResult); Mockito.verify(capacityService, Mockito.times(0)).initTenantCapacity(eq(mockTenant)); @@ -396,23 +415,22 @@ void testAroundSyncUpdateConfigAllForInsertRollbackAspect() throws Throwable { @Test void testAroundDeleteConfigForTenant() throws Throwable { when(PropertyUtil.isManageCapacity()).thenReturn(true); + when(proceedingJoinPoint.getArgs()).thenReturn(new Object[]{mockDataId, mockGroup, mockTenant}); + when(localMockProceedingJoinPoint.getArgs()).thenReturn(new Object[]{mockDataId, mockGroup, mockTenant}); + when(proceedingJoinPoint.proceed()).thenReturn(mockProceedingJoinPointResult); when(configInfoPersistService.findConfigInfo(any(), any(), any())).thenReturn(null); when(capacityService.insertAndUpdateClusterUsage(any(), anyBoolean())).thenReturn(true); when(capacityService.insertAndUpdateTenantUsage(any(), eq(mockTenant), anyBoolean())).thenReturn(true); when(capacityService.updateClusterUsage(any())).thenReturn(true); when(capacityService.updateTenantUsage(any(), eq(mockTenant))).thenReturn(true); - MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(); - MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse(); - String localMockResult = (String) capacityManagementAspect.aroundDeleteConfig(proceedingJoinPoint, - mockHttpServletRequest, mockHttpServletResponse, mockDataId, mockGroup, mockTenant); - assertEquals(localMockResult, mockProceedingJoinPointResult); + Boolean localMockResult = (Boolean) capacityManagementAspect.aroundDeleteConfig(proceedingJoinPoint); + assertEquals(mockProceedingJoinPointResult, localMockResult); Mockito.verify(proceedingJoinPoint, Mockito.times(1)).proceed(); when(configInfoPersistService.findConfigInfo(any(), any(), any())).thenReturn(new ConfigInfoWrapper()); - localMockResult = (String) capacityManagementAspect.aroundDeleteConfig(proceedingJoinPoint, - mockHttpServletRequest, mockHttpServletResponse, mockDataId, mockGroup, mockTenant); - assertEquals(localMockResult, mockProceedingJoinPointResult); + localMockResult = (Boolean) capacityManagementAspect.aroundDeleteConfig(proceedingJoinPoint); + assertEquals(mockProceedingJoinPointResult, localMockResult); Mockito.verify(capacityService, Mockito.times(1)) .insertAndUpdateClusterUsage(eq(CounterMode.DECREMENT), anyBoolean()); Mockito.verify(capacityService, Mockito.times(1)) @@ -421,10 +439,9 @@ void testAroundDeleteConfigForTenant() throws Throwable { localMockResult = null; try { - localMockResult = (String) capacityManagementAspect.aroundDeleteConfig(localMockProceedingJoinPoint, - mockHttpServletRequest, mockHttpServletResponse, mockDataId, mockGroup, mockTenant); + localMockResult = (Boolean) capacityManagementAspect.aroundDeleteConfig(localMockProceedingJoinPoint); } catch (Throwable e) { - assertEquals(e.getMessage(), mockException.getMessage()); + assertEquals(mockException.getMessage(), e.getMessage()); } assertNull(localMockResult); Mockito.verify(capacityService, Mockito.times(2)) @@ -439,43 +456,40 @@ void testAroundDeleteConfigForTenant() throws Throwable { @Test void testAroundDeleteConfigForGroup() throws Throwable { when(PropertyUtil.isManageCapacity()).thenReturn(true); + when(proceedingJoinPoint.getArgs()).thenReturn(new Object[]{mockDataId, mockGroup, mockTenant}); + when(localMockProceedingJoinPoint.getArgs()).thenReturn(new Object[]{mockDataId, mockGroup, mockTenant}); + when(proceedingJoinPoint.proceed()).thenReturn(mockProceedingJoinPointResult); when(configInfoPersistService.findConfigInfo(any(), any(), any())).thenReturn(null); when(capacityService.insertAndUpdateClusterUsage(any(), anyBoolean())).thenReturn(true); when(capacityService.insertAndUpdateGroupUsage(any(), eq(mockGroup), anyBoolean())).thenReturn(true); when(capacityService.updateClusterUsage(any())).thenReturn(true); when(capacityService.updateGroupUsage(any(), eq(mockGroup))).thenReturn(true); - MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(); - MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse(); - String localMockResult = (String) capacityManagementAspect.aroundDeleteConfig(proceedingJoinPoint, - mockHttpServletRequest, mockHttpServletResponse, mockDataId, mockGroup, null); - assertEquals(localMockResult, mockProceedingJoinPointResult); + Boolean localMockResult = (Boolean) capacityManagementAspect.aroundDeleteConfig(proceedingJoinPoint); + assertEquals(mockProceedingJoinPointResult, localMockResult); Mockito.verify(proceedingJoinPoint, Mockito.times(1)).proceed(); when(configInfoPersistService.findConfigInfo(any(), any(), any())).thenReturn(new ConfigInfoWrapper()); - localMockResult = (String) capacityManagementAspect.aroundDeleteConfig(proceedingJoinPoint, - mockHttpServletRequest, mockHttpServletResponse, mockDataId, mockGroup, null); - assertEquals(localMockResult, mockProceedingJoinPointResult); + localMockResult = (Boolean) capacityManagementAspect.aroundDeleteConfig(proceedingJoinPoint); + assertEquals(mockProceedingJoinPointResult, localMockResult); Mockito.verify(capacityService, Mockito.times(1)) .insertAndUpdateClusterUsage(eq(CounterMode.DECREMENT), anyBoolean()); Mockito.verify(capacityService, Mockito.times(1)) - .insertAndUpdateGroupUsage(eq(CounterMode.DECREMENT), eq(mockGroup), anyBoolean()); + .insertAndUpdateTenantUsage(eq(CounterMode.DECREMENT), eq(mockTenant), anyBoolean()); Mockito.verify(proceedingJoinPoint, Mockito.times(2)).proceed(); localMockResult = null; try { - localMockResult = (String) capacityManagementAspect.aroundDeleteConfig(localMockProceedingJoinPoint, - mockHttpServletRequest, mockHttpServletResponse, mockDataId, mockGroup, null); + localMockResult = (Boolean) capacityManagementAspect.aroundDeleteConfig(localMockProceedingJoinPoint); } catch (Throwable e) { - assertEquals(e.getMessage(), mockException.getMessage()); + assertEquals(mockException.getMessage(), e.getMessage()); } assertNull(localMockResult); Mockito.verify(capacityService, Mockito.times(2)) .insertAndUpdateClusterUsage(eq(CounterMode.DECREMENT), anyBoolean()); Mockito.verify(capacityService, Mockito.times(1)).updateClusterUsage(eq(CounterMode.INCREMENT)); Mockito.verify(capacityService, Mockito.times(2)) - .insertAndUpdateGroupUsage(eq(CounterMode.DECREMENT), eq(mockGroup), anyBoolean()); - Mockito.verify(capacityService, Mockito.times(1)).updateGroupUsage(eq(CounterMode.INCREMENT), eq(mockGroup)); + .insertAndUpdateTenantUsage(eq(CounterMode.DECREMENT), eq(mockTenant), anyBoolean()); Mockito.verify(localMockProceedingJoinPoint, Mockito.times(1)).proceed(); } -} +} \ No newline at end of file diff --git a/config/src/test/java/com/alibaba/nacos/config/server/aspect/ConfigChangeAspectTest.java b/config/src/test/java/com/alibaba/nacos/config/server/aspect/ConfigChangeAspectTest.java index 0f31ad53ae5..d2f0425edc5 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/aspect/ConfigChangeAspectTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/aspect/ConfigChangeAspectTest.java @@ -16,15 +16,12 @@ package com.alibaba.nacos.config.server.aspect; -import com.alibaba.nacos.api.config.remote.request.ConfigPublishRequest; -import com.alibaba.nacos.api.config.remote.request.ConfigRemoveRequest; import com.alibaba.nacos.api.config.remote.response.ConfigPublishResponse; -import com.alibaba.nacos.api.config.remote.response.ConfigRemoveResponse; -import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException; -import com.alibaba.nacos.api.remote.request.RequestMeta; import com.alibaba.nacos.common.event.ServerConfigChangeEvent; import com.alibaba.nacos.config.server.configuration.ConfigChangeConfigs; +import com.alibaba.nacos.config.server.model.ConfigRequestInfo; import com.alibaba.nacos.config.server.model.SameConfigPolicy; +import com.alibaba.nacos.config.server.model.form.ConfigForm; import com.alibaba.nacos.config.server.utils.RequestUtil; import com.alibaba.nacos.plugin.config.ConfigChangePluginManager; import com.alibaba.nacos.plugin.config.constants.ConfigChangeConstants; @@ -46,15 +43,15 @@ import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import java.util.Arrays; +import java.util.List; import java.util.Properties; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; @ExtendWith(SpringExtension.class) class ConfigChangeAspectTest { @@ -70,6 +67,15 @@ class ConfigChangeAspectTest { MockedStatic requestUtilMockedStatic; + @Mock + private ProceedingJoinPoint pjp; + + @Mock + private ConfigForm configForm; + + @Mock + private ConfigRequestInfo configRequestInfo; + @BeforeEach void before() { //mock config change service enabled. @@ -120,38 +126,40 @@ void testImportConfigAround() throws Throwable { @Test void testPublishOrUpdateConfigAround() throws Throwable { Mockito.when(configChangePluginService.executeType()).thenReturn(ConfigChangeExecuteTypes.EXECUTE_AFTER_TYPE); - ProceedingJoinPoint proceedingJoinPoint = Mockito.mock(ProceedingJoinPoint.class); - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - HttpServletResponse response = Mockito.mock(HttpServletResponse.class); - String srcUser = "user12324"; - String dataId = "d1"; - String group = "g1"; - String tenant = "t1"; - Mockito.when(proceedingJoinPoint.proceed(any())).thenReturn("mock success return"); - Object o = configChangeAspect.publishOrUpdateConfigAround(proceedingJoinPoint, request, response, dataId, group, tenant, "c1", null, - null, srcUser, null, null, null, null, null); + when(pjp.getArgs()).thenReturn(new Object[]{configForm, configRequestInfo}); + when(configForm.getDataId()).thenReturn("dataId"); + when(configForm.getGroup()).thenReturn("group"); + when(configForm.getNamespaceId()).thenReturn("namespaceId"); + when(configForm.getContent()).thenReturn("content"); + when(configRequestInfo.getSrcIp()).thenReturn("127.0.0.1"); + when(configRequestInfo.getSrcType()).thenReturn("http"); + when(pjp.proceed(any())).thenReturn("Success"); + + Object o = configChangeAspect.publishOrUpdateConfigAround(pjp); Thread.sleep(20L); // expect service executed. Mockito.verify(configChangePluginService, Mockito.times(1)) .execute(any(ConfigChangeRequest.class), any(ConfigChangeResponse.class)); //expect join point processed success. - assertEquals("mock success return", o); + assertEquals("Success", o); } @Test void testRemoveConfigByIdAround() throws Throwable { Mockito.when(configChangePluginService.executeType()).thenReturn(ConfigChangeExecuteTypes.EXECUTE_AFTER_TYPE); - ProceedingJoinPoint proceedingJoinPoint = Mockito.mock(ProceedingJoinPoint.class); - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - HttpServletResponse response = Mockito.mock(HttpServletResponse.class); - String dataId = "d1"; - String group = "g1"; - String tenant = "t1"; - Mockito.when(proceedingJoinPoint.proceed(any())).thenReturn("mock success return"); - Object o = configChangeAspect.removeConfigByIdAround(proceedingJoinPoint, request, response, dataId, group, tenant); + String dataId = "dataId1"; + String group = "group1"; + String namespaceId = "namespaceId1"; + String tag = "tag1"; + String clientIp = "127.0.0.1"; + String srcType = "http"; + + when(pjp.getArgs()).thenReturn(new Object[]{dataId, group, namespaceId, tag, clientIp, srcType}); + Mockito.when(pjp.proceed(any())).thenReturn("mock success return"); + Object o = configChangeAspect.removeConfigByIdAround(pjp); Thread.sleep(20L); // expect service executed. @@ -163,12 +171,13 @@ void testRemoveConfigByIdAround() throws Throwable { @Test void testRemoveConfigByIdsAround() throws Throwable { + List ids = Arrays.asList(1, 2, 3); + String srcIp = "dataId1"; + String srcUser = "group1"; + when(pjp.getArgs()).thenReturn(new Object[]{ids, srcIp, srcUser}); Mockito.when(configChangePluginService.executeType()).thenReturn(ConfigChangeExecuteTypes.EXECUTE_AFTER_TYPE); - ProceedingJoinPoint proceedingJoinPoint = Mockito.mock(ProceedingJoinPoint.class); - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - - Mockito.when(proceedingJoinPoint.proceed(any())).thenReturn("mock success return"); - Object o = configChangeAspect.removeConfigByIdsAround(proceedingJoinPoint, request, Arrays.asList(1L, 2L)); + Mockito.when(pjp.proceed(any())).thenReturn("mock success return"); + Object o = configChangeAspect.removeConfigByIdsAround(pjp); Thread.sleep(20L); // expect service executed. Mockito.verify(configChangePluginService, Mockito.times(1)) @@ -177,76 +186,18 @@ void testRemoveConfigByIdsAround() throws Throwable { assertEquals("mock success return", o); } - @Test - void testPublishConfigAroundRpc() throws Throwable { - Mockito.when(configChangePluginService.executeType()).thenReturn(ConfigChangeExecuteTypes.EXECUTE_BEFORE_TYPE); - ProceedingJoinPoint proceedingJoinPoint = Mockito.mock(ProceedingJoinPoint.class); - ConfigPublishRequest request = new ConfigPublishRequest(); - RequestMeta requestMeta = new RequestMeta(); - ConfigPublishResponse configPublishResponse = ConfigPublishResponse.buildSuccessResponse(); - Mockito.when(proceedingJoinPoint.proceed(any())).thenReturn(configPublishResponse); - //execute - Object o = configChangeAspect.publishConfigAroundRpc(proceedingJoinPoint, request, requestMeta); - //expect - Mockito.verify(configChangePluginService, Mockito.times(1)) - .execute(any(ConfigChangeRequest.class), any(ConfigChangeResponse.class)); - assertEquals(configPublishResponse, o); - } - - @Test - void testPublishConfigAroundRpcException() throws Throwable { - Mockito.when(configChangePluginService.executeType()).thenReturn(ConfigChangeExecuteTypes.EXECUTE_BEFORE_TYPE); - ProceedingJoinPoint proceedingJoinPoint = Mockito.mock(ProceedingJoinPoint.class); - ConfigPublishRequest request = new ConfigPublishRequest(); - RequestMeta requestMeta = new RequestMeta(); - - Mockito.when(proceedingJoinPoint.proceed(any())).thenThrow(new NacosRuntimeException(503)); - //execute - Object o = configChangeAspect.publishConfigAroundRpc(proceedingJoinPoint, request, requestMeta); - //expect - Mockito.verify(configChangePluginService, Mockito.times(1)) - .execute(any(ConfigChangeRequest.class), any(ConfigChangeResponse.class)); - - assertTrue(((ConfigPublishResponse) o).getMessage().contains("config change join point fail")); - } - - @Test - void testRemoveConfigAroundRpc() throws Throwable { - Mockito.when(configChangePluginService.executeType()).thenReturn(ConfigChangeExecuteTypes.EXECUTE_BEFORE_TYPE); - ProceedingJoinPoint proceedingJoinPoint = Mockito.mock(ProceedingJoinPoint.class); - ConfigRemoveRequest request = new ConfigRemoveRequest(); - RequestMeta requestMeta = new RequestMeta(); - ConfigPublishResponse configPublishResponse = ConfigPublishResponse.buildSuccessResponse(); - Mockito.when(proceedingJoinPoint.proceed(any())).thenReturn(configPublishResponse); - //execute - Object o = configChangeAspect.removeConfigAroundRpc(proceedingJoinPoint, request, requestMeta); - //expect - Mockito.verify(configChangePluginService, Mockito.times(1)) - .execute(any(ConfigChangeRequest.class), any(ConfigChangeResponse.class)); - assertEquals(configPublishResponse, o); - } - - @Test - void testRemoveConfigAroundRpcException() throws Throwable { - Mockito.when(configChangePluginService.executeType()).thenReturn(ConfigChangeExecuteTypes.EXECUTE_BEFORE_TYPE); - ProceedingJoinPoint proceedingJoinPoint = Mockito.mock(ProceedingJoinPoint.class); - ConfigRemoveRequest request = new ConfigRemoveRequest(); - RequestMeta requestMeta = new RequestMeta(); - - Mockito.when(proceedingJoinPoint.proceed(any())).thenThrow(new NacosRuntimeException(503)); - //execute - Object o = configChangeAspect.removeConfigAroundRpc(proceedingJoinPoint, request, requestMeta); - //expect - Mockito.verify(configChangePluginService, Mockito.times(1)) - .execute(any(ConfigChangeRequest.class), any(ConfigChangeResponse.class)); - - assertTrue(((ConfigRemoveResponse) o).getMessage().contains("config change join point fail")); - } - @Test void testDisEnablePluginService() throws Throwable { Properties properties = new Properties(); properties.put("mockedConfigChangeService.enabled", "false"); + String dataId = "dataId1"; + String group = "group1"; + String namespaceId = "namespaceId1"; + String tag = "tag1"; + String clientIp = "127.0.0.1"; + String srcType = "http"; + + when(pjp.getArgs()).thenReturn(new Object[]{dataId, group, namespaceId, tag, clientIp, srcType}); propertiesStatic.when( () -> PropertiesUtil.getPropertiesWithPrefix(any(), eq(ConfigChangeConstants.NACOS_CORE_CONFIG_PLUGIN_PREFIX))) .thenReturn(properties); @@ -255,13 +206,10 @@ void testDisEnablePluginService() throws Throwable { Mockito.when(configChangePluginService.executeType()).thenReturn(ConfigChangeExecuteTypes.EXECUTE_BEFORE_TYPE); Mockito.when(configChangePluginService.getServiceType()).thenReturn("mockedConfigChangeService"); - ProceedingJoinPoint proceedingJoinPoint = Mockito.mock(ProceedingJoinPoint.class); - ConfigRemoveRequest request = new ConfigRemoveRequest(); - RequestMeta requestMeta = new RequestMeta(); ConfigPublishResponse configPublishResponse = ConfigPublishResponse.buildSuccessResponse(); - Mockito.when(proceedingJoinPoint.proceed()).thenReturn(configPublishResponse); + Mockito.when(pjp.proceed()).thenReturn(configPublishResponse); //execute - Object o = configChangeAspect.removeConfigAroundRpc(proceedingJoinPoint, request, requestMeta); + Object o = configChangeAspect.removeConfigByIdAround(pjp); //expect Mockito.verify(configChangePluginService, Mockito.times(0)) .execute(any(ConfigChangeRequest.class), any(ConfigChangeResponse.class)); diff --git a/config/src/test/java/com/alibaba/nacos/config/server/aspect/RequestLogAspectTest.java b/config/src/test/java/com/alibaba/nacos/config/server/aspect/RequestLogAspectTest.java new file mode 100644 index 00000000000..b1e430d2516 --- /dev/null +++ b/config/src/test/java/com/alibaba/nacos/config/server/aspect/RequestLogAspectTest.java @@ -0,0 +1,146 @@ +/* + * Copyright 1999-$toady.year Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.config.server.aspect; + +import com.alibaba.nacos.api.config.remote.request.ConfigBatchListenRequest; +import com.alibaba.nacos.api.config.remote.response.ConfigChangeBatchListenResponse; +import com.alibaba.nacos.api.remote.request.RequestMeta; +import com.alibaba.nacos.api.remote.response.Response; +import com.alibaba.nacos.config.server.model.ConfigRequestInfo; +import com.alibaba.nacos.config.server.model.form.ConfigForm; +import com.alibaba.nacos.config.server.monitor.MetricsMonitor; +import com.alibaba.nacos.config.server.service.query.model.ConfigQueryChainRequest; +import org.aspectj.lang.ProceedingJoinPoint; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(SpringExtension.class) +class RequestLogAspectTest { + + @Mock + private ProceedingJoinPoint pjp; + + @Mock + private ConfigForm configForm; + + @Mock + private ConfigRequestInfo configRequestInfo; + + @Mock + private ConfigQueryChainRequest chainRequest; + + @Mock + private ConfigBatchListenRequest request; + + @Mock + private Response response; + + @Mock + private RequestMeta meta; + + private RequestLogAspect requestLogAspect; + + @BeforeEach + void setUp() { + requestLogAspect = new RequestLogAspect(); + } + + @Test + void testInterfacePublishConfig() throws Throwable { + when(pjp.getArgs()).thenReturn(new Object[]{configForm, configRequestInfo}); + when(configForm.getDataId()).thenReturn("dataId"); + when(configForm.getGroup()).thenReturn("group"); + when(configForm.getNamespaceId()).thenReturn("namespaceId"); + when(configForm.getContent()).thenReturn("content"); + when(configRequestInfo.getSrcIp()).thenReturn("127.0.0.1"); + + when(pjp.proceed()).thenReturn("Success"); + AtomicInteger publishMonitor = MetricsMonitor.getPublishMonitor(); + int initialValue = publishMonitor.get(); + + Object result = requestLogAspect.interfacePublishConfig(pjp); + + verify(pjp, times(1)).proceed(); + assertEquals("Success", result); + + assertEquals(initialValue + 1, publishMonitor.get()); + } + + @Test + void testInterfaceGetConfig() throws Throwable { + when(pjp.getArgs()).thenReturn(new Object[]{chainRequest}); + when(chainRequest.getDataId()).thenReturn("dataId"); + when(chainRequest.getGroup()).thenReturn("group"); + when(chainRequest.getTenant()).thenReturn("tenant"); + + when(pjp.proceed()).thenReturn("ConfigData"); + + AtomicInteger configMonitor = MetricsMonitor.getConfigMonitor(); + int initialValue = configMonitor.get(); + + Object result = requestLogAspect.interfaceGetConfig(pjp); + + verify(pjp, times(1)).proceed(); + assertEquals("ConfigData", result); + assertEquals(initialValue + 1, configMonitor.get()); + } + + @Test + void testInterfaceDeleteConfig() throws Throwable { + String dataId = "dataId1"; + String group = "group1"; + String namespaceId = "namespaceId1"; + String tag = "tag1"; + String clientIp = "127.0.0.1"; + when(pjp.getArgs()).thenReturn(new Object[]{dataId, group, namespaceId, tag, clientIp}); + + when(pjp.proceed()).thenReturn("Success"); + AtomicInteger configMonitor = MetricsMonitor.getConfigMonitor(); + int initialValue = configMonitor.get(); + + Object result = requestLogAspect.interfaceRemoveConfig(pjp); + + verify(pjp, times(1)).proceed(); + assertEquals("Success", result); + assertEquals(initialValue + 1, configMonitor.get()); + } + + @Test + void testInterfaceListenConfigRpc() throws Throwable { + when(meta.getClientIp()).thenReturn("127.0.0.1"); + when(request.isListen()).thenReturn(true); + + when(pjp.proceed()).thenReturn(new ConfigChangeBatchListenResponse()); + AtomicInteger configMonitor = MetricsMonitor.getConfigMonitor(); + int initialValue = configMonitor.get(); + + Response result = (Response) requestLogAspect.interfaceListenConfigRpc(pjp, request, meta); + + assertEquals(result.getResultCode(), 200); + assertEquals(initialValue + 1, configMonitor.get()); + } +} diff --git a/config/src/test/java/com/alibaba/nacos/config/server/controller/ConfigControllerTest.java b/config/src/test/java/com/alibaba/nacos/config/server/controller/ConfigControllerTest.java index ff30cf0d250..7d3e425265d 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/controller/ConfigControllerTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/controller/ConfigControllerTest.java @@ -17,9 +17,6 @@ package com.alibaba.nacos.config.server.controller; import com.alibaba.nacos.common.http.param.MediaType; -import com.alibaba.nacos.common.notify.Event; -import com.alibaba.nacos.common.notify.NotifyCenter; -import com.alibaba.nacos.common.notify.listener.Subscriber; import com.alibaba.nacos.common.utils.JacksonUtils; import com.alibaba.nacos.config.server.constant.Constants; import com.alibaba.nacos.config.server.controller.parameters.SameNamespaceCloneConfigBean; @@ -31,7 +28,6 @@ import com.alibaba.nacos.config.server.model.ConfigMetadata; import com.alibaba.nacos.config.server.model.GroupkeyListenserStatus; import com.alibaba.nacos.config.server.model.SampleResult; -import com.alibaba.nacos.config.server.model.event.ConfigDataChangeEvent; import com.alibaba.nacos.config.server.service.ConfigOperationService; import com.alibaba.nacos.config.server.service.ConfigSubService; import com.alibaba.nacos.config.server.service.repository.ConfigInfoBetaPersistService; @@ -68,10 +64,8 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.concurrent.atomic.AtomicReference; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.anyString; @@ -172,7 +166,7 @@ void testDetailConfigInfo() throws Exception { @Test void testDeleteConfig() throws Exception { when(configOperationService.deleteConfig(anyString(), anyString(), anyString(), anyString(), any(), - any())).thenReturn(true); + any(), any())).thenReturn(true); MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.delete(Constants.CONFIG_CONTROLLER_PATH) .param("dataId", "test").param("group", "test").param("tenant", "").param("tag", ""); @@ -192,37 +186,13 @@ void testDeleteConfigs() throws Exception { configAllInfo.setGroup(group); configAllInfo.setTenant(tenant); resultInfos.add(configAllInfo); - Mockito.when(configInfoPersistService.removeConfigInfoByIds(eq(Arrays.asList(1L, 2L)), anyString(), eq(null))) - .thenReturn(resultInfos); - AtomicReference reference = new AtomicReference<>(); - NotifyCenter.registerSubscriber(new Subscriber() { - - @Override - public void onEvent(Event event) { - ConfigDataChangeEvent event1 = (ConfigDataChangeEvent) event; - if (event1.dataId.equals(dataId)) { - reference.set((ConfigDataChangeEvent) event); - } - } - - @Override - public Class subscribeType() { - return ConfigDataChangeEvent.class; - } - }); - + Mockito.when(configOperationService.deleteConfigs(any(), any(), any())).thenReturn(true); MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.delete(Constants.CONFIG_CONTROLLER_PATH) .param("delType", "ids").param("ids", "1,2"); String actualValue = mockmvc.perform(builder).andReturn().getResponse().getContentAsString(); - - String code = JacksonUtils.toObj(actualValue).get("code").toString(); String data = JacksonUtils.toObj(actualValue).get("data").toString(); - assertEquals("200", code); assertEquals("true", data); - Thread.sleep(200L); - //expect - assertTrue(reference.get() != null); } @Test @@ -451,7 +421,7 @@ void testImportAndPublishConfig() throws Exception { when(namespacePersistService.tenantInfoCountByTenantId("public")).thenReturn(1); Map map = new HashMap<>(); map.put("test", "test"); - when(configInfoPersistService.batchInsertOrUpdate(anyList(), anyString(), anyString(), any(), + when(configOperationService.batchInsertOrUpdate(anyList(), anyString(), anyString(), any(), any())).thenReturn(map); MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.multipart(Constants.CONFIG_CONTROLLER_PATH) @@ -493,7 +463,7 @@ void testImportAndPublishConfigV2() throws Exception { when(namespacePersistService.tenantInfoCountByTenantId("public")).thenReturn(1); Map map = new HashMap<>(); map.put("test", "test"); - when(configInfoPersistService.batchInsertOrUpdate(anyList(), anyString(), anyString(), any(), + when(configOperationService.batchInsertOrUpdate(anyList(), anyString(), anyString(), any(), any())).thenReturn(map); MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.multipart(Constants.CONFIG_CONTROLLER_PATH) @@ -536,7 +506,7 @@ void testCloneConfig() throws Exception { Map map = new HashMap<>(); map.put("test", "test"); - when(configInfoPersistService.batchInsertOrUpdate(anyList(), anyString(), anyString(), any(), + when(configOperationService.batchInsertOrUpdate(anyList(), anyString(), anyString(), any(), any())).thenReturn(map); MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.post(Constants.CONFIG_CONTROLLER_PATH) diff --git a/config/src/test/java/com/alibaba/nacos/config/server/controller/v2/ConfigControllerV2Test.java b/config/src/test/java/com/alibaba/nacos/config/server/controller/v2/ConfigControllerV2Test.java index a94130b7f07..f34b38b2b8f 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/controller/v2/ConfigControllerV2Test.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/controller/v2/ConfigControllerV2Test.java @@ -225,11 +225,12 @@ void testDeleteConfigWhenNameSpaceIsPublic() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); when(configOperationService.deleteConfig(eq(TEST_DATA_ID), eq(TEST_GROUP), eq(TEST_NAMESPACE_ID), eq(TEST_TAG), any(), - any())).thenReturn(true); + any(), eq("http"))).thenReturn(true); Result booleanResult = configControllerV2.deleteConfig(request, TEST_DATA_ID, TEST_GROUP, TEST_NAMESPACE_ID_PUBLIC, TEST_TAG); - verify(configOperationService).deleteConfig(eq(TEST_DATA_ID), eq(TEST_GROUP), eq(TEST_NAMESPACE_ID), eq(TEST_TAG), any(), any()); + verify(configOperationService).deleteConfig(eq(TEST_DATA_ID), eq(TEST_GROUP), eq(TEST_NAMESPACE_ID), eq(TEST_TAG), any(), any(), + eq("http")); assertEquals(ErrorCode.SUCCESS.getCode(), booleanResult.getCode()); assertTrue(booleanResult.getData()); @@ -241,11 +242,12 @@ void testDeleteConfig() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); when(configOperationService.deleteConfig(eq(TEST_DATA_ID), eq(TEST_GROUP), eq(TEST_NAMESPACE_ID), eq(TEST_TAG), any(), - any())).thenReturn(true); + any(), eq("http"))).thenReturn(true); Result booleanResult = configControllerV2.deleteConfig(request, TEST_DATA_ID, TEST_GROUP, TEST_NAMESPACE_ID, TEST_TAG); - verify(configOperationService).deleteConfig(eq(TEST_DATA_ID), eq(TEST_GROUP), eq(TEST_NAMESPACE_ID), eq(TEST_TAG), any(), any()); + verify(configOperationService).deleteConfig(eq(TEST_DATA_ID), eq(TEST_GROUP), eq(TEST_NAMESPACE_ID), eq(TEST_TAG), any(), any(), + eq("http")); assertEquals(ErrorCode.SUCCESS.getCode(), booleanResult.getCode()); assertTrue(booleanResult.getData()); diff --git a/config/src/test/java/com/alibaba/nacos/config/server/remote/ConfigRemoveRequestHandlerTest.java b/config/src/test/java/com/alibaba/nacos/config/server/remote/ConfigRemoveRequestHandlerTest.java index 8d05297ccff..91202d121cd 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/remote/ConfigRemoveRequestHandlerTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/remote/ConfigRemoveRequestHandlerTest.java @@ -21,8 +21,7 @@ import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.remote.request.RequestMeta; import com.alibaba.nacos.api.remote.response.ResponseCode; -import com.alibaba.nacos.config.server.service.repository.ConfigInfoGrayPersistService; -import com.alibaba.nacos.config.server.service.repository.ConfigInfoPersistService; +import com.alibaba.nacos.config.server.service.ConfigOperationService; import com.alibaba.nacos.config.server.service.trace.ConfigTraceService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -40,15 +39,11 @@ class ConfigRemoveRequestHandlerTest { private ConfigRemoveRequestHandler configRemoveRequestHandler; @Mock - private ConfigInfoPersistService configInfoPersistService; - - @Mock - private ConfigInfoGrayPersistService configInfoGrayPersistService; + private ConfigOperationService configOperationService; @BeforeEach void setUp() throws Exception { - configRemoveRequestHandler = new ConfigRemoveRequestHandler(configInfoPersistService, - configInfoGrayPersistService); + configRemoveRequestHandler = new ConfigRemoveRequestHandler(configOperationService); Mockito.mockStatic(ConfigTraceService.class); } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/service/ConfigOperationServiceTest.java b/config/src/test/java/com/alibaba/nacos/config/server/service/ConfigOperationServiceTest.java index 48414cd2098..e9bb8e29502 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/service/ConfigOperationServiceTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/service/ConfigOperationServiceTest.java @@ -195,12 +195,12 @@ void testPublishConfig() throws NacosException { void testDeleteConfig() { // if tag is blank - Boolean aResult = configOperationService.deleteConfig("test", "test", "", "", "1.1.1.1", "test"); + Boolean aResult = configOperationService.deleteConfig("test", "test", "", "", "1.1.1.1", "test", "http"); verify(configInfoPersistService).removeConfigInfo(eq("test"), eq("test"), eq(""), any(), any()); assertTrue(aResult); // if tag is not blank - Boolean bResult = configOperationService.deleteConfig("test", "test", "", "test", "1.1.1.1", "test"); + Boolean bResult = configOperationService.deleteConfig("test", "test", "", "test", "1.1.1.1", "test", "http"); verify(configInfoTagPersistService).removeConfigInfoTag(eq("test"), eq("test"), eq(""), eq("test"), any(), any()); assertTrue(bResult);