diff --git a/config/src/main/java/com/alibaba/nacos/config/server/monitor/ThreadTaskQueueMonitorTask.java b/config/src/main/java/com/alibaba/nacos/config/server/monitor/ThreadTaskQueueMonitorTask.java index 3949e51bc..72a924977 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/monitor/ThreadTaskQueueMonitorTask.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/monitor/ThreadTaskQueueMonitorTask.java @@ -18,7 +18,6 @@ package com.alibaba.nacos.config.server.monitor; import com.alibaba.nacos.config.server.service.notify.AsyncNotifyService; import com.alibaba.nacos.config.server.utils.ConfigExecutor; -import com.alibaba.nacos.core.utils.GlobalExecutor; import static com.alibaba.nacos.config.server.utils.LogUtil.MEMORY_LOG; diff --git a/naming/src/main/java/com/alibaba/nacos/naming/core/InstanceOperatorClientImpl.java b/naming/src/main/java/com/alibaba/nacos/naming/core/InstanceOperatorClientImpl.java index 44c93f4eb..08c9f39d1 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/core/InstanceOperatorClientImpl.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/core/InstanceOperatorClientImpl.java @@ -112,7 +112,8 @@ public class InstanceOperatorClientImpl implements InstanceOperator { throw new NacosException(NacosException.INVALID_PARAM, "service not found, namespace: " + namespaceId + ", service: " + service); } - metadataOperateService.updateInstanceMetadata(service, instance.toInetAddr(), buildMetadata(instance)); + String metadataId = InstancePublishInfo.genMetadataId(instance.getIp(), instance.getPort(), instance.getClusterName()); + metadataOperateService.updateInstanceMetadata(service, metadataId, buildMetadata(instance)); } private InstanceMetadata buildMetadata(Instance instance) { @@ -129,11 +130,12 @@ public class InstanceOperatorClientImpl implements InstanceOperator { Service service = getService(namespaceId, serviceName, true); Instance instance = getInstance(namespaceId, serviceName, patchObject.getCluster(), patchObject.getIp(), patchObject.getPort()); - String instanceId = instance.toInetAddr(); - Optional instanceMetadata = metadataManager.getInstanceMetadata(service, instanceId); + String metadataId = InstancePublishInfo + .genMetadataId(instance.getIp(), instance.getPort(), instance.getClusterName()); + Optional instanceMetadata = metadataManager.getInstanceMetadata(service, metadataId); InstanceMetadata newMetadata = instanceMetadata.map(this::cloneMetadata).orElseGet(InstanceMetadata::new); mergeMetadata(newMetadata, patchObject); - metadataOperateService.updateInstanceMetadata(service, instanceId, newMetadata); + metadataOperateService.updateInstanceMetadata(service, metadataId, newMetadata); } private InstanceMetadata cloneMetadata(InstanceMetadata instanceMetadata) { @@ -231,7 +233,8 @@ public class InstanceOperatorClientImpl implements InstanceOperator { @Override public long getHeartBeatInterval(String namespaceId, String serviceName, String ip, int port, String cluster) { Service service = getService(namespaceId, serviceName, true); - Optional metadata = metadataManager.getInstanceMetadata(service, ip); + String metadataId = InstancePublishInfo.genMetadataId(ip, port, cluster); + Optional metadata = metadataManager.getInstanceMetadata(service, metadataId); if (metadata.isPresent() && metadata.get().getExtendData() .containsKey(PreservedMetadataKeys.HEART_BEAT_INTERVAL)) { return ConvertUtils.toLong(metadata.get().getExtendData().get(PreservedMetadataKeys.HEART_BEAT_INTERVAL)); diff --git a/naming/src/main/java/com/alibaba/nacos/naming/core/v2/cleaner/ExpiredMetadataCleaner.java b/naming/src/main/java/com/alibaba/nacos/naming/core/v2/cleaner/ExpiredMetadataCleaner.java index ef66547e6..b42a208b9 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/core/v2/cleaner/ExpiredMetadataCleaner.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/core/v2/cleaner/ExpiredMetadataCleaner.java @@ -65,13 +65,13 @@ public class ExpiredMetadataCleaner extends AbstractNamingCleaner { private void removeExpiredMetadata(ExpiredMetadataInfo expiredInfo) { Loggers.SRV_LOG.info("Remove expired metadata {}", expiredInfo); - if (null == expiredInfo.getInstanceId()) { + if (null == expiredInfo.getMetadataId()) { if (metadataManager.containServiceMetadata(expiredInfo.getService())) { metadataOperateService.deleteServiceMetadata(expiredInfo.getService()); } } else { - if (metadataManager.containInstanceMetadata(expiredInfo.getService(), expiredInfo.getInstanceId())) { - metadataOperateService.deleteInstanceMetadata(expiredInfo.getService(), expiredInfo.getInstanceId()); + if (metadataManager.containInstanceMetadata(expiredInfo.getService(), expiredInfo.getMetadataId())) { + metadataOperateService.deleteInstanceMetadata(expiredInfo.getService(), expiredInfo.getMetadataId()); } } } diff --git a/naming/src/main/java/com/alibaba/nacos/naming/core/v2/client/impl/IpPortBasedClient.java b/naming/src/main/java/com/alibaba/nacos/naming/core/v2/client/impl/IpPortBasedClient.java index 93732bfc4..1df0257c6 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/core/v2/client/impl/IpPortBasedClient.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/core/v2/client/impl/IpPortBasedClient.java @@ -121,6 +121,7 @@ public class IpPortBasedClient extends AbstractClient { result.setIp(instancePublishInfo.getIp()); result.setPort(instancePublishInfo.getPort()); result.setHealthy(instancePublishInfo.isHealthy()); + result.setCluster(instancePublishInfo.getCluster()); result.setExtendDatum(instancePublishInfo.getExtendDatum()); if (!ephemeral) { result.initHealthCheck(); diff --git a/naming/src/main/java/com/alibaba/nacos/naming/core/v2/event/metadata/MetadataEvent.java b/naming/src/main/java/com/alibaba/nacos/naming/core/v2/event/metadata/MetadataEvent.java index c3faf2485..ed77618c7 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/core/v2/event/metadata/MetadataEvent.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/core/v2/event/metadata/MetadataEvent.java @@ -67,15 +67,15 @@ public class MetadataEvent extends Event { private static final long serialVersionUID = 5781016126117637520L; - private final String instanceId; + private final String metadataId; - public InstanceMetadataEvent(Service service, String instanceId, boolean expired) { + public InstanceMetadataEvent(Service service, String metadataId, boolean expired) { super(service, expired); - this.instanceId = instanceId; + this.metadataId = metadataId; } - public String getInstanceId() { - return instanceId; + public String getMetadataId() { + return metadataId; } } } diff --git a/naming/src/main/java/com/alibaba/nacos/naming/core/v2/index/ServiceStorage.java b/naming/src/main/java/com/alibaba/nacos/naming/core/v2/index/ServiceStorage.java index af666e29d..ab1dc5bf7 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/core/v2/index/ServiceStorage.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/core/v2/index/ServiceStorage.java @@ -16,10 +16,8 @@ package com.alibaba.nacos.naming.core.v2.index; -import com.alibaba.nacos.api.naming.CommonParams; import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.pojo.ServiceInfo; -import com.alibaba.nacos.api.naming.utils.NamingUtils; import com.alibaba.nacos.naming.core.v2.ServiceManager; import com.alibaba.nacos.naming.core.v2.client.Client; import com.alibaba.nacos.naming.core.v2.client.manager.ClientManager; @@ -29,13 +27,12 @@ import com.alibaba.nacos.naming.core.v2.metadata.NamingMetadataManager; import com.alibaba.nacos.naming.core.v2.pojo.InstancePublishInfo; import com.alibaba.nacos.naming.core.v2.pojo.Service; import com.alibaba.nacos.naming.misc.SwitchDomain; +import com.alibaba.nacos.naming.utils.InstanceUtil; import org.springframework.stereotype.Component; -import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; -import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; @@ -128,30 +125,10 @@ public class ServiceStorage { } private Instance parseInstance(Service service, InstancePublishInfo instanceInfo) { - Instance result = new Instance(); - result.setIp(instanceInfo.getIp()); - result.setPort(instanceInfo.getPort()); - result.setServiceName(NamingUtils.getGroupedName(service.getName(), service.getGroup())); - Map instanceMetadata = new HashMap<>(instanceInfo.getExtendDatum().size()); - for (Map.Entry entry : instanceInfo.getExtendDatum().entrySet()) { - if (CommonParams.CLUSTER_NAME.equals(entry.getKey())) { - result.setClusterName(entry.getValue().toString()); - } else { - instanceMetadata.put(entry.getKey(), entry.getValue().toString()); - } - } + Instance result = InstanceUtil.parseToApiInstance(service, instanceInfo); Optional metadata = metadataManager - .getInstanceMetadata(service, instanceInfo.getInstanceId()); - if (metadata.isPresent()) { - result.setEnabled(metadata.get().isEnabled()); - result.setWeight(metadata.get().getWeight()); - for (Map.Entry entry : metadata.get().getExtendData().entrySet()) { - instanceMetadata.put(entry.getKey(), entry.getValue().toString()); - } - } - result.setMetadata(instanceMetadata); - result.setEphemeral(service.isEphemeral()); - result.setHealthy(instanceInfo.isHealthy()); + .getInstanceMetadata(service, instanceInfo.getMetadataId()); + metadata.ifPresent(instanceMetadata -> InstanceUtil.updateInstanceMetadata(result, instanceMetadata)); return result; } } diff --git a/naming/src/main/java/com/alibaba/nacos/naming/core/v2/metadata/ExpiredMetadataInfo.java b/naming/src/main/java/com/alibaba/nacos/naming/core/v2/metadata/ExpiredMetadataInfo.java index 9e2748517..ec88a8546 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/core/v2/metadata/ExpiredMetadataInfo.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/core/v2/metadata/ExpiredMetadataInfo.java @@ -33,13 +33,13 @@ public class ExpiredMetadataInfo { private final Service service; - private final String instanceId; + private final String metadataId; private final long createTime; - private ExpiredMetadataInfo(Service service, String instanceId) { + private ExpiredMetadataInfo(Service service, String metadataId) { this.service = service; - this.instanceId = instanceId; + this.metadataId = metadataId; this.createTime = System.currentTimeMillis(); } @@ -47,16 +47,16 @@ public class ExpiredMetadataInfo { return new ExpiredMetadataInfo(service, null); } - public static ExpiredMetadataInfo newExpiredInstanceMetadata(Service service, String instanceId) { - return new ExpiredMetadataInfo(service, instanceId); + public static ExpiredMetadataInfo newExpiredInstanceMetadata(Service service, String metadataId) { + return new ExpiredMetadataInfo(service, metadataId); } public Service getService() { return service; } - public String getInstanceId() { - return instanceId; + public String getMetadataId() { + return metadataId; } public long getCreateTime() { @@ -72,17 +72,17 @@ public class ExpiredMetadataInfo { return false; } ExpiredMetadataInfo that = (ExpiredMetadataInfo) o; - return Objects.equals(service, that.service) && Objects.equals(instanceId, that.instanceId); + return Objects.equals(service, that.service) && Objects.equals(metadataId, that.metadataId); } @Override public int hashCode() { - return Objects.hash(service, instanceId); + return Objects.hash(service, metadataId); } @Override public String toString() { - return "ExpiredMetadataInfo{" + "service=" + service + ", instanceId='" + instanceId + '\'' + ", createTime=" + return "ExpiredMetadataInfo{" + "service=" + service + ", metadataId='" + metadataId + '\'' + ", createTime=" + new Date(createTime) + '}'; } } diff --git a/naming/src/main/java/com/alibaba/nacos/naming/core/v2/metadata/NamingMetadataManager.java b/naming/src/main/java/com/alibaba/nacos/naming/core/v2/metadata/NamingMetadataManager.java index 09d3a5c19..981bf9ebc 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/core/v2/metadata/NamingMetadataManager.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/core/v2/metadata/NamingMetadataManager.java @@ -68,11 +68,12 @@ public class NamingMetadataManager extends SmartSubscriber { /** * Whether instance metadata metadata for instance of {@link Service}. * - * @param service service + * @param service service + * @param metadataId instance metadata id * @return true if contain instance metadata, otherwise false */ - public boolean containInstanceMetadata(Service service, String instanceId) { - return instanceMetadataMap.containsKey(service) && instanceMetadataMap.get(service).containsKey(instanceId); + public boolean containInstanceMetadata(Service service, String metadataId) { + return instanceMetadataMap.containsKey(service) && instanceMetadataMap.get(service).containsKey(metadataId); } /** @@ -93,15 +94,15 @@ public class NamingMetadataManager extends SmartSubscriber { *

This method should use only query, can't modified metadata. * * @param service service - * @param instanceId instance id + * @param metadataId instance metadata id * @return instance metadata */ - public Optional getInstanceMetadata(Service service, String instanceId) { + public Optional getInstanceMetadata(Service service, String metadataId) { ConcurrentMap instanceMetadataMapForService = instanceMetadataMap.get(service); if (null == instanceMetadataMapForService) { return Optional.empty(); } - return Optional.ofNullable(instanceMetadataMapForService.get(instanceId)); + return Optional.ofNullable(instanceMetadataMapForService.get(metadataId)); } /** @@ -119,14 +120,14 @@ public class NamingMetadataManager extends SmartSubscriber { * Update instance metadata. * * @param service service - * @param instanceId instance id + * @param metadataId instance metadata id * @param instanceMetadata new instance metadata */ - public void updateInstanceMetadata(Service service, String instanceId, InstanceMetadata instanceMetadata) { + public void updateInstanceMetadata(Service service, String metadataId, InstanceMetadata instanceMetadata) { if (!instanceMetadataMap.containsKey(service)) { instanceMetadataMap.putIfAbsent(service, new ConcurrentHashMap<>(1)); } - instanceMetadataMap.get(service).put(instanceId, instanceMetadata); + instanceMetadataMap.get(service).put(metadataId, instanceMetadata); } /** @@ -143,15 +144,15 @@ public class NamingMetadataManager extends SmartSubscriber { * Remove instance metadata. * * @param service service - * @param instanceId instance id + * @param metadataId instance metadata id */ - public void removeInstanceMetadata(Service service, String instanceId) { + public void removeInstanceMetadata(Service service, String metadataId) { ConcurrentMap instanceMetadataMapForService = instanceMetadataMap.get(service); - instanceMetadataMapForService.remove(instanceId); + instanceMetadataMapForService.remove(metadataId); if (instanceMetadataMapForService.isEmpty()) { serviceMetadataMap.remove(service); } - expiredMetadataInfos.remove(ExpiredMetadataInfo.newExpiredInstanceMetadata(service, instanceId)); + expiredMetadataInfos.remove(ExpiredMetadataInfo.newExpiredInstanceMetadata(service, metadataId)); } /** @@ -230,9 +231,9 @@ public class NamingMetadataManager extends SmartSubscriber { private void handleClientDisconnectEvent(ClientEvent.ClientDisconnectEvent event) { for (Service each : event.getClient().getAllPublishedService()) { - String instanceId = event.getClient().getInstancePublishInfo(each).getInstanceId(); - if (containInstanceMetadata(each, instanceId)) { - updateExpiredInfo(true, ExpiredMetadataInfo.newExpiredInstanceMetadata(each, instanceId)); + String metadataId = event.getClient().getInstancePublishInfo(each).getMetadataId(); + if (containInstanceMetadata(each, metadataId)) { + updateExpiredInfo(true, ExpiredMetadataInfo.newExpiredInstanceMetadata(each, metadataId)); } } } @@ -246,10 +247,10 @@ public class NamingMetadataManager extends SmartSubscriber { private void handleInstanceMetadataEvent(MetadataEvent.InstanceMetadataEvent event) { Service service = event.getService(); - String instanceId = event.getInstanceId(); - if (containInstanceMetadata(service, instanceId)) { + String metadataId = event.getMetadataId(); + if (containInstanceMetadata(service, metadataId)) { updateExpiredInfo(event.isExpired(), - ExpiredMetadataInfo.newExpiredInstanceMetadata(event.getService(), event.getInstanceId())); + ExpiredMetadataInfo.newExpiredInstanceMetadata(event.getService(), event.getMetadataId())); } } diff --git a/naming/src/main/java/com/alibaba/nacos/naming/core/v2/metadata/NamingMetadataOperateService.java b/naming/src/main/java/com/alibaba/nacos/naming/core/v2/metadata/NamingMetadataOperateService.java index 969436506..7aac419bd 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/core/v2/metadata/NamingMetadataOperateService.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/core/v2/metadata/NamingMetadataOperateService.java @@ -79,12 +79,12 @@ public class NamingMetadataOperateService { * Update instance metadata. * * @param service service of metadata - * @param instanceId instance Id + * @param metadataId instance metadataId Id * @param instanceMetadata metadata */ - public void updateInstanceMetadata(Service service, String instanceId, InstanceMetadata instanceMetadata) { + public void updateInstanceMetadata(Service service, String metadataId, InstanceMetadata instanceMetadata) { MetadataOperation operation = buildMetadataOperation(service); - operation.setTag(instanceId); + operation.setTag(metadataId); operation.setMetadata(instanceMetadata); WriteRequest operationLog = WriteRequest.newBuilder().setGroup(Constants.INSTANCE_METADATA) .setOperation(DataOperation.CHANGE.name()).setData(ByteString.copyFrom(serializer.serialize(operation))) @@ -96,11 +96,11 @@ public class NamingMetadataOperateService { * Delete instance metadata. * * @param service service of metadata - * @param instanceId instance Id + * @param metadataId instance metadata Id */ - public void deleteInstanceMetadata(Service service, String instanceId) { + public void deleteInstanceMetadata(Service service, String metadataId) { MetadataOperation operation = buildMetadataOperation(service); - operation.setTag(instanceId); + operation.setTag(metadataId); WriteRequest operationLog = WriteRequest.newBuilder().setGroup(Constants.INSTANCE_METADATA) .setOperation(DataOperation.DELETE.name()).setData(ByteString.copyFrom(serializer.serialize(operation))) .build(); diff --git a/naming/src/main/java/com/alibaba/nacos/naming/core/v2/pojo/InstancePublishInfo.java b/naming/src/main/java/com/alibaba/nacos/naming/core/v2/pojo/InstancePublishInfo.java index ae58054e9..9aa89d82a 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/core/v2/pojo/InstancePublishInfo.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/core/v2/pojo/InstancePublishInfo.java @@ -38,6 +38,8 @@ public class InstancePublishInfo implements Serializable { private boolean healthy; + private String cluster; + private Map extendDatum; public InstancePublishInfo() { @@ -65,6 +67,14 @@ public class InstancePublishInfo implements Serializable { return port; } + public void setCluster(String cluster) { + this.cluster = cluster; + } + + public String getCluster() { + return cluster; + } + public Map getExtendDatum() { return extendDatum; } @@ -81,8 +91,8 @@ public class InstancePublishInfo implements Serializable { this.healthy = healthy; } - public String getInstanceId() { - return ip + IPUtil.IP_PORT_SPLITER + port; + public String getMetadataId() { + return genMetadataId(ip, port, cluster); } @Override @@ -107,4 +117,8 @@ public class InstancePublishInfo implements Serializable { public String toString() { return "InstancePublishInfo{" + "ip='" + ip + '\'' + ", port=" + port + ", healthy=" + healthy + '}'; } + + public static String genMetadataId(String ip, int port, String cluster) { + return ip + IPUtil.IP_PORT_SPLITER + port + IPUtil.IP_PORT_SPLITER + cluster; + } } diff --git a/naming/src/main/java/com/alibaba/nacos/naming/core/v2/service/ClientOperationService.java b/naming/src/main/java/com/alibaba/nacos/naming/core/v2/service/ClientOperationService.java index 790a99df0..a5e9dff3b 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/core/v2/service/ClientOperationService.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/core/v2/service/ClientOperationService.java @@ -16,13 +16,13 @@ package com.alibaba.nacos.naming.core.v2.service; -import com.alibaba.nacos.api.naming.CommonParams; import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.common.utils.StringUtils; import com.alibaba.nacos.naming.core.v2.pojo.InstancePublishInfo; import com.alibaba.nacos.naming.core.v2.pojo.Service; import com.alibaba.nacos.naming.misc.UtilsAndCommons; import com.alibaba.nacos.naming.pojo.Subscriber; +import com.alibaba.nacos.naming.utils.Constants; /** * Client operation service. @@ -82,10 +82,19 @@ public interface ClientOperationService { if (null != instance.getMetadata() && !instance.getMetadata().isEmpty()) { result.getExtendDatum().putAll(instance.getMetadata()); } + if (StringUtils.isNotEmpty(instance.getInstanceId())) { + result.getExtendDatum().put(Constants.CUSTOM_INSTANCE_ID, instance.getInstanceId()); + } + if (Constants.DEFAULT_INSTANCE_WEIGHT != instance.getWeight()) { + result.getExtendDatum().put(Constants.PUBLISH_INSTANCE_WEIGHT, instance.getWeight()); + } + if (!instance.isEnabled()) { + result.getExtendDatum().put(Constants.PUBLISH_INSTANCE_ENABLE, instance.isEnabled()); + } String clusterName = StringUtils.isBlank(instance.getClusterName()) ? UtilsAndCommons.DEFAULT_CLUSTER_NAME : instance.getClusterName(); result.setHealthy(instance.isHealthy()); - result.getExtendDatum().put(CommonParams.CLUSTER_NAME, clusterName); + result.setCluster(clusterName); return result; } -} \ No newline at end of file +} diff --git a/naming/src/main/java/com/alibaba/nacos/naming/core/v2/service/impl/EphemeralClientOperationServiceImpl.java b/naming/src/main/java/com/alibaba/nacos/naming/core/v2/service/impl/EphemeralClientOperationServiceImpl.java index 7633b0bc8..5daccdfeb 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/core/v2/service/impl/EphemeralClientOperationServiceImpl.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/core/v2/service/impl/EphemeralClientOperationServiceImpl.java @@ -54,7 +54,7 @@ public class EphemeralClientOperationServiceImpl implements ClientOperationServi client.setLastUpdatedTime(); NotifyCenter.publishEvent(new ClientOperationEvent.ClientRegisterServiceEvent(singleton, clientId)); NotifyCenter - .publishEvent(new MetadataEvent.InstanceMetadataEvent(singleton, instanceInfo.getInstanceId(), false)); + .publishEvent(new MetadataEvent.InstanceMetadataEvent(singleton, instanceInfo.getMetadataId(), false)); } @Override @@ -70,7 +70,7 @@ public class EphemeralClientOperationServiceImpl implements ClientOperationServi if (null != removedInstance) { NotifyCenter.publishEvent(new ClientOperationEvent.ClientDeregisterServiceEvent(singleton, clientId)); NotifyCenter.publishEvent( - new MetadataEvent.InstanceMetadataEvent(singleton, removedInstance.getInstanceId(), true)); + new MetadataEvent.InstanceMetadataEvent(singleton, removedInstance.getMetadataId(), true)); } } diff --git a/naming/src/main/java/com/alibaba/nacos/naming/core/v2/upgrade/doublewrite/delay/DoubleWriteEventListener.java b/naming/src/main/java/com/alibaba/nacos/naming/core/v2/upgrade/doublewrite/delay/DoubleWriteEventListener.java index 106d50319..0ce680121 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/core/v2/upgrade/doublewrite/delay/DoubleWriteEventListener.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/core/v2/upgrade/doublewrite/delay/DoubleWriteEventListener.java @@ -22,6 +22,7 @@ import com.alibaba.nacos.common.notify.listener.Subscriber; import com.alibaba.nacos.naming.core.Service; import com.alibaba.nacos.naming.core.v2.event.service.ServiceEvent; import com.alibaba.nacos.naming.core.v2.upgrade.UpgradeJudgement; +import com.alibaba.nacos.sys.env.EnvUtil; import org.springframework.stereotype.Component; /** @@ -36,15 +37,21 @@ public class DoubleWriteEventListener extends Subscriber getTimeoutFromMetadata(Service service, InstancePublishInfo instance) { Optional instanceMetadata = ApplicationUtils.getBean(NamingMetadataManager.class) - .getInstanceMetadata(service, instance.getInstanceId()); + .getInstanceMetadata(service, instance.getMetadataId()); return instanceMetadata.map(metadata -> metadata.getExtendData().get(PreservedMetadataKeys.IP_DELETE_TIMEOUT)); } diff --git a/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/heartbeat/InstanceEnableBeatCheckInterceptor.java b/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/heartbeat/InstanceEnableBeatCheckInterceptor.java index e8c7b4126..9e6467147 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/heartbeat/InstanceEnableBeatCheckInterceptor.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/heartbeat/InstanceEnableBeatCheckInterceptor.java @@ -36,7 +36,7 @@ public class InstanceEnableBeatCheckInterceptor extends AbstractBeatCheckInterce public boolean intercept(InstanceBeatCheckTask object) { NamingMetadataManager metadataManager = ApplicationUtils.getBean(NamingMetadataManager.class); HealthCheckInstancePublishInfo instance = object.getInstancePublishInfo(); - Optional metadata = metadataManager.getInstanceMetadata(object.getService(), instance.getInstanceId()); + Optional metadata = metadataManager.getInstanceMetadata(object.getService(), instance.getMetadataId()); if (metadata.isPresent() && metadata.get().getExtendData().containsKey(UtilsAndCommons.ENABLE_CLIENT_BEAT)) { return ConvertUtils.toBoolean(metadata.get().getExtendData().get(UtilsAndCommons.ENABLE_CLIENT_BEAT).toString()); } diff --git a/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/heartbeat/UnhealthyInstanceChecker.java b/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/heartbeat/UnhealthyInstanceChecker.java index 2eaa8b1cd..16c1df207 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/heartbeat/UnhealthyInstanceChecker.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/heartbeat/UnhealthyInstanceChecker.java @@ -17,7 +17,6 @@ package com.alibaba.nacos.naming.healthcheck.heartbeat; import com.alibaba.nacos.api.common.Constants; -import com.alibaba.nacos.api.naming.CommonParams; import com.alibaba.nacos.api.naming.PreservedMetadataKeys; import com.alibaba.nacos.common.notify.NotifyCenter; import com.alibaba.nacos.common.utils.ConvertUtils; @@ -66,16 +65,15 @@ public class UnhealthyInstanceChecker implements InstanceBeatChecker { private Optional getTimeoutFromMetadata(Service service, InstancePublishInfo instance) { Optional instanceMetadata = ApplicationUtils.getBean(NamingMetadataManager.class) - .getInstanceMetadata(service, instance.getInstanceId()); + .getInstanceMetadata(service, instance.getMetadataId()); return instanceMetadata.map(metadata -> metadata.getExtendData().get(PreservedMetadataKeys.HEART_BEAT_TIMEOUT)); } private void changeHealthyStatus(Client client, Service service, HealthCheckInstancePublishInfo instance) { instance.setHealthy(false); - Object cluster = instance.getExtendDatum().get(CommonParams.CLUSTER_NAME); Loggers.EVT_LOG .info("{POS} {IP-DISABLED} valid: {}:{}@{}@{}, region: {}, msg: client last beat: {}", instance.getIp(), - instance.getPort(), cluster, service.getName(), UtilsAndCommons.LOCALHOST_SITE, + instance.getPort(), instance.getCluster(), service.getName(), UtilsAndCommons.LOCALHOST_SITE, instance.getLastHeartBeatTime()); NotifyCenter.publishEvent(new ServiceEvent.ServiceChangedEvent(service)); NotifyCenter.publishEvent(new ClientEvent.ClientChangedEvent(client)); diff --git a/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/v2/HealthCheckTaskV2.java b/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/v2/HealthCheckTaskV2.java index fd408818c..698ac3e96 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/v2/HealthCheckTaskV2.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/v2/HealthCheckTaskV2.java @@ -16,7 +16,6 @@ package com.alibaba.nacos.naming.healthcheck.v2; -import com.alibaba.nacos.api.naming.CommonParams; import com.alibaba.nacos.common.task.AbstractExecuteTask; import com.alibaba.nacos.naming.core.v2.client.impl.IpPortBasedClient; import com.alibaba.nacos.naming.core.v2.metadata.ClusterMetadata; @@ -148,7 +147,7 @@ public class HealthCheckTaskV2 extends AbstractExecuteTask implements NacosHealt if (!serviceMetadata.isPresent()) { return new ClusterMetadata(); } - String cluster = instancePublishInfo.getExtendDatum().get(CommonParams.CLUSTER_NAME).toString(); + String cluster = instancePublishInfo.getCluster(); ClusterMetadata result = serviceMetadata.get().getClusters().get(cluster); return null == result ? new ClusterMetadata() : result; } diff --git a/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/v2/PersistentHealthStatusSynchronizer.java b/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/v2/PersistentHealthStatusSynchronizer.java index 625edd0fc..85b524d11 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/v2/PersistentHealthStatusSynchronizer.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/v2/PersistentHealthStatusSynchronizer.java @@ -16,18 +16,14 @@ package com.alibaba.nacos.naming.healthcheck.v2; -import com.alibaba.nacos.api.naming.CommonParams; import com.alibaba.nacos.api.naming.pojo.Instance; -import com.alibaba.nacos.api.naming.utils.NamingUtils; import com.alibaba.nacos.naming.core.v2.client.Client; import com.alibaba.nacos.naming.core.v2.pojo.InstancePublishInfo; import com.alibaba.nacos.naming.core.v2.pojo.Service; import com.alibaba.nacos.naming.core.v2.service.impl.PersistentClientOperationServiceImpl; +import com.alibaba.nacos.naming.utils.InstanceUtil; import org.springframework.stereotype.Component; -import java.util.HashMap; -import java.util.Map; - /** * Health status synchronizer for persistent service, implementation by CP. * @@ -45,26 +41,8 @@ public class PersistentHealthStatusSynchronizer implements HealthStatusSynchroni @Override public void instanceHealthStatusChange(boolean isHealthy, Client client, Service service, InstancePublishInfo instance) { - Instance updateInstance = parseInstance(service, instance); + Instance updateInstance = InstanceUtil.parseToApiInstance(service, instance); updateInstance.setHealthy(isHealthy); persistentClientOperationService.registerInstance(service, updateInstance, client.getClientId()); } - - private Instance parseInstance(Service service, InstancePublishInfo instanceInfo) { - Instance result = new Instance(); - result.setIp(instanceInfo.getIp()); - result.setPort(instanceInfo.getPort()); - result.setServiceName(NamingUtils.getGroupedName(service.getName(), service.getGroup())); - Map instanceMetadata = new HashMap<>(instanceInfo.getExtendDatum().size()); - for (Map.Entry entry : instanceInfo.getExtendDatum().entrySet()) { - if (CommonParams.CLUSTER_NAME.equals(entry.getKey())) { - result.setClusterName(entry.getValue().toString()); - } else { - instanceMetadata.put(entry.getKey(), entry.getValue().toString()); - } - } - result.setMetadata(instanceMetadata); - result.setEphemeral(service.isEphemeral()); - return result; - } } diff --git a/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/v2/processor/HealthCheckCommonV2.java b/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/v2/processor/HealthCheckCommonV2.java index 93f438a87..0d9e75049 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/v2/processor/HealthCheckCommonV2.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/v2/processor/HealthCheckCommonV2.java @@ -16,7 +16,6 @@ package com.alibaba.nacos.naming.healthcheck.v2.processor; -import com.alibaba.nacos.api.naming.CommonParams; import com.alibaba.nacos.naming.core.DistroMapper; import com.alibaba.nacos.naming.core.v2.pojo.HealthCheckInstancePublishInfo; import com.alibaba.nacos.naming.core.v2.pojo.Service; @@ -93,7 +92,7 @@ public class HealthCheckCommonV2 { .getInstancePublishInfo(service); if (null != instance && !instance.isHealthy()) { String serviceName = service.getGroupedServiceName(); - String clusterName = instance.getExtendDatum().get(CommonParams.CLUSTER_NAME).toString(); + String clusterName = instance.getCluster(); if (instance.getOkCount().incrementAndGet() >= switchDomain.getCheckTimes()) { if (switchDomain.isHealthCheckEnabled(serviceName) && !task.isCancelled() && distroMapper .responsible(task.getClient().getResponsibleId())) { @@ -127,7 +126,7 @@ public class HealthCheckCommonV2 { .getInstancePublishInfo(service); if (null != instance && instance.isHealthy()) { String serviceName = service.getGroupedServiceName(); - String clusterName = instance.getExtendDatum().get(CommonParams.CLUSTER_NAME).toString(); + String clusterName = instance.getCluster(); if (instance.getFailCount().incrementAndGet() >= switchDomain.getCheckTimes()) { if (switchDomain.isHealthCheckEnabled(serviceName) && !task.isCancelled() && distroMapper .responsible(task.getClient().getResponsibleId())) { @@ -163,7 +162,7 @@ public class HealthCheckCommonV2 { .getInstancePublishInfo(service); if (null != instance && instance.isHealthy()) { String serviceName = service.getGroupedServiceName(); - String clusterName = instance.getExtendDatum().get(CommonParams.CLUSTER_NAME).toString(); + String clusterName = instance.getCluster(); if (switchDomain.isHealthCheckEnabled(serviceName) && !task.isCancelled() && distroMapper .responsible(task.getClient().getResponsibleId())) { healthStatusSynchronizer.instanceHealthStatusChange(false, task.getClient(), service, instance); diff --git a/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/v2/processor/HttpHealthCheckProcessor.java b/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/v2/processor/HttpHealthCheckProcessor.java index 230286501..a8667f208 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/v2/processor/HttpHealthCheckProcessor.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/v2/processor/HttpHealthCheckProcessor.java @@ -16,7 +16,6 @@ package com.alibaba.nacos.naming.healthcheck.v2.processor; -import com.alibaba.nacos.api.naming.CommonParams; import com.alibaba.nacos.api.naming.pojo.healthcheck.HealthCheckType; import com.alibaba.nacos.api.naming.pojo.healthcheck.impl.Http; import com.alibaba.nacos.common.http.Callback; @@ -53,7 +52,8 @@ public class HttpHealthCheckProcessor implements HealthCheckProcessorV2 { public static final String TYPE = HealthCheckType.HTTP.name(); - private static final NacosAsyncRestTemplate ASYNC_REST_TEMPLATE = HttpClientManager.getProcessorNacosAsyncRestTemplate(); + private static final NacosAsyncRestTemplate ASYNC_REST_TEMPLATE = HttpClientManager + .getProcessorNacosAsyncRestTemplate(); private final HealthCheckCommonV2 healthCheckCommon; @@ -75,8 +75,7 @@ public class HttpHealthCheckProcessor implements HealthCheckProcessorV2 { // TODO handle marked(white list) logic like v1.x. if (instance.tryStartCheck()) { SRV_LOG.warn("http check started before last one finished, service: {} : {} : {}:{}", - service.getGroupedServiceName(), instance.getExtendDatum().get(CommonParams.CLUSTER_NAME), - instance.getIp(), instance.getPort()); + service.getGroupedServiceName(), instance.getCluster(), instance.getIp(), instance.getPort()); healthCheckCommon .reEvaluateCheckRT(task.getCheckRtNormalized() * 2, task, switchDomain.getHttpHealthParams()); return; diff --git a/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/v2/processor/MysqlHealthCheckProcessor.java b/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/v2/processor/MysqlHealthCheckProcessor.java index dd31bc5a9..3070eca7a 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/v2/processor/MysqlHealthCheckProcessor.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/v2/processor/MysqlHealthCheckProcessor.java @@ -16,7 +16,6 @@ package com.alibaba.nacos.naming.healthcheck.v2.processor; -import com.alibaba.nacos.api.naming.CommonParams; import com.alibaba.nacos.api.naming.pojo.healthcheck.HealthCheckType; import com.alibaba.nacos.api.naming.pojo.healthcheck.impl.Mysql; import com.alibaba.nacos.naming.core.v2.metadata.ClusterMetadata; @@ -89,8 +88,7 @@ public class MysqlHealthCheckProcessor implements HealthCheckProcessorV2 { // TODO handle marked(white list) logic like v1.x. if (instance.tryStartCheck()) { SRV_LOG.warn("mysql check started before last one finished, service: {} : {} : {}:{}", - service.getGroupedServiceName(), instance.getExtendDatum().get(CommonParams.CLUSTER_NAME), - instance.getIp(), instance.getPort()); + service.getGroupedServiceName(), instance.getCluster(), instance.getIp(), instance.getPort()); healthCheckCommon .reEvaluateCheckRT(task.getCheckRtNormalized() * 2, task, switchDomain.getMysqlHealthParams()); return; @@ -132,7 +130,7 @@ public class MysqlHealthCheckProcessor implements HealthCheckProcessorV2 { ResultSet resultSet = null; try { - String clusterName = instance.getExtendDatum().get(CommonParams.CLUSTER_NAME).toString(); + String clusterName = instance.getCluster(); String key = service.getGroupedServiceName() + ":" + clusterName + ":" + instance.getIp() + ":" + instance .getPort(); diff --git a/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/v2/processor/TcpHealthCheckProcessor.java b/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/v2/processor/TcpHealthCheckProcessor.java index af85acd77..e48f8b7c3 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/v2/processor/TcpHealthCheckProcessor.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/v2/processor/TcpHealthCheckProcessor.java @@ -16,7 +16,6 @@ package com.alibaba.nacos.naming.healthcheck.v2.processor; -import com.alibaba.nacos.api.naming.CommonParams; import com.alibaba.nacos.api.naming.pojo.healthcheck.HealthCheckType; import com.alibaba.nacos.naming.core.v2.metadata.ClusterMetadata; import com.alibaba.nacos.naming.core.v2.pojo.HealthCheckInstancePublishInfo; @@ -103,8 +102,7 @@ public class TcpHealthCheckProcessor implements HealthCheckProcessorV2, Runnable // TODO handle marked(white list) logic like v1.x. if (instance.tryStartCheck()) { SRV_LOG.warn("tcp check started before last one finished, service: {} : {} : {}:{}", - service.getGroupedServiceName(), instance.getExtendDatum().get(CommonParams.CLUSTER_NAME), - instance.getIp(), instance.getPort()); + service.getGroupedServiceName(), instance.getCluster(), instance.getIp(), instance.getPort()); healthCheckCommon .reEvaluateCheckRT(task.getCheckRtNormalized() * 2, task, switchDomain.getTcpHealthParams()); return; @@ -287,8 +285,8 @@ public class TcpHealthCheckProcessor implements HealthCheckProcessorV2, Runnable @Override public String toString() { - return service.getGroupedServiceName() + ":" + instance.getExtendDatum().get(CommonParams.CLUSTER_NAME) - + ":" + instance.getIp() + ":" + instance.getPort(); + return service.getGroupedServiceName() + ":" + instance.getCluster() + ":" + instance.getIp() + ":" + + instance.getPort(); } @Override diff --git a/naming/src/main/java/com/alibaba/nacos/naming/utils/Constants.java b/naming/src/main/java/com/alibaba/nacos/naming/utils/Constants.java index c390b8c64..e73131a71 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/utils/Constants.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/utils/Constants.java @@ -102,4 +102,24 @@ public final class Constants { * The Milliseconds for push timeout. */ public static final long DEFAULT_PUSH_TIMEOUT_MILLS = TimeUnit.SECONDS.toNanos(3L); + + /** + * The custom instance id key. + */ + public static final String CUSTOM_INSTANCE_ID = "customInstanceId"; + + /** + * The weight of instance according to instance self publish. + */ + public static final String PUBLISH_INSTANCE_WEIGHT = "publishInstanceWeight"; + + /** + * The weight of instance according to instance self publish. + */ + public static final double DEFAULT_INSTANCE_WEIGHT = 1.0D; + + /** + * Whether enabled for instance according to instance self publish. + */ + public static final String PUBLISH_INSTANCE_ENABLE = "publishInstanceEnable"; } diff --git a/naming/src/main/java/com/alibaba/nacos/naming/utils/InstanceUtil.java b/naming/src/main/java/com/alibaba/nacos/naming/utils/InstanceUtil.java new file mode 100644 index 000000000..29ff65e49 --- /dev/null +++ b/naming/src/main/java/com/alibaba/nacos/naming/utils/InstanceUtil.java @@ -0,0 +1,79 @@ +/* + * Copyright 1999-2020 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.naming.utils; + +import com.alibaba.nacos.api.naming.pojo.Instance; +import com.alibaba.nacos.api.naming.utils.NamingUtils; +import com.alibaba.nacos.naming.core.v2.metadata.InstanceMetadata; +import com.alibaba.nacos.naming.core.v2.pojo.InstancePublishInfo; +import com.alibaba.nacos.naming.core.v2.pojo.Service; + +import java.util.HashMap; +import java.util.Map; + +/** + * Instance util. + * + * @author xiweng.yy + */ +public class InstanceUtil { + + /** + * Parse {@code InstancePublishInfo} to {@code Instance}. + * + * @param service service of instance + * @param instanceInfo instance info + * @return api instance + */ + public static Instance parseToApiInstance(Service service, InstancePublishInfo instanceInfo) { + Instance result = new Instance(); + result.setIp(instanceInfo.getIp()); + result.setPort(instanceInfo.getPort()); + result.setServiceName(NamingUtils.getGroupedName(service.getName(), service.getGroup())); + result.setClusterName(instanceInfo.getCluster()); + Map instanceMetadata = new HashMap<>(instanceInfo.getExtendDatum().size()); + for (Map.Entry entry : instanceInfo.getExtendDatum().entrySet()) { + if (Constants.CUSTOM_INSTANCE_ID.equals(entry.getKey())) { + result.setInstanceId(entry.getValue().toString()); + } else if (Constants.PUBLISH_INSTANCE_ENABLE.equals(entry.getKey())) { + result.setEnabled((boolean) entry.getValue()); + } else if (Constants.PUBLISH_INSTANCE_WEIGHT.equals(entry.getKey())) { + result.setWeight((Double) entry.getValue()); + } else { + instanceMetadata.put(entry.getKey(), entry.getValue().toString()); + } + } + result.setMetadata(instanceMetadata); + result.setEphemeral(service.isEphemeral()); + result.setHealthy(instanceInfo.isHealthy()); + return result; + } + + /** + * Update metadata in {@code Instance} according to {@code InstanceMetadata}. + * + * @param instance instance need to be update + * @param metadata instance metadata + */ + public static void updateInstanceMetadata(Instance instance, InstanceMetadata metadata) { + instance.setEnabled(metadata.isEnabled()); + instance.setWeight(metadata.getWeight()); + for (Map.Entry entry : metadata.getExtendData().entrySet()) { + instance.getMetadata().put(entry.getKey(), entry.getValue().toString()); + } + } +} diff --git a/naming/src/test/java/com/alibaba/nacos/naming/BaseTest.java b/naming/src/test/java/com/alibaba/nacos/naming/BaseTest.java index 74366425d..6b186f51b 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/BaseTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/BaseTest.java @@ -21,6 +21,7 @@ import com.alibaba.nacos.naming.consistency.persistent.raft.RaftPeer; import com.alibaba.nacos.naming.consistency.persistent.raft.RaftPeerSet; import com.alibaba.nacos.naming.core.DistroMapper; import com.alibaba.nacos.naming.core.ServiceManager; +import com.alibaba.nacos.naming.core.v2.upgrade.UpgradeJudgement; import com.alibaba.nacos.naming.healthcheck.HealthCheckProcessorDelegate; import com.alibaba.nacos.naming.misc.NetUtils; import com.alibaba.nacos.naming.misc.SwitchDomain; @@ -41,7 +42,7 @@ import org.springframework.mock.env.MockEnvironment; import static org.mockito.Mockito.doReturn; @RunWith(MockitoJUnitRunner.class) -public class BaseTest { +public abstract class BaseTest { protected static final String TEST_CLUSTER_NAME = "test-cluster"; @@ -78,6 +79,9 @@ public class BaseTest { @Mock protected UdpPushService pushService; + @Mock + protected UpgradeJudgement upgradeJudgement; + @Spy private MockEnvironment environment; @@ -111,4 +115,8 @@ public class BaseTest { protected void mockInjectDistroMapper() { doReturn(distroMapper).when(context).getBean(DistroMapper.class); } + + protected void mockInjectUpgradeJudgement() { + doReturn(upgradeJudgement).when(context).getBean(UpgradeJudgement.class); + } } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/consistency/ephemeral/distro/DistroConsistencyServiceImplTest.java b/naming/src/test/java/com/alibaba/nacos/naming/consistency/ephemeral/distro/DistroConsistencyServiceImplTest.java index 4a76dc1b4..653ae6371 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/consistency/ephemeral/distro/DistroConsistencyServiceImplTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/consistency/ephemeral/distro/DistroConsistencyServiceImplTest.java @@ -17,14 +17,14 @@ package com.alibaba.nacos.naming.consistency.ephemeral.distro; import com.alibaba.nacos.api.exception.NacosException; +import com.alibaba.nacos.consistency.DataOperation; +import com.alibaba.nacos.core.distributed.distro.DistroProtocol; +import com.alibaba.nacos.core.distributed.distro.entity.DistroKey; import com.alibaba.nacos.naming.BaseTest; import com.alibaba.nacos.naming.cluster.transport.Serializer; -import com.alibaba.nacos.consistency.DataOperation; import com.alibaba.nacos.naming.consistency.Datum; import com.alibaba.nacos.naming.consistency.KeyBuilder; import com.alibaba.nacos.naming.consistency.RecordListener; -import com.alibaba.nacos.core.distributed.distro.DistroProtocol; -import com.alibaba.nacos.core.distributed.distro.entity.DistroKey; import com.alibaba.nacos.naming.core.Instances; import com.alibaba.nacos.naming.misc.GlobalConfig; import org.junit.After; @@ -79,7 +79,7 @@ public class DistroConsistencyServiceImplTest extends BaseTest { listeners = (Map>) ReflectionTestUtils .getField(distroConsistencyService, "listeners"); instances = new Instances(); - + mockInjectUpgradeJudgement(); } @After @@ -91,7 +91,8 @@ public class DistroConsistencyServiceImplTest extends BaseTest { String key = KeyBuilder.buildInstanceListKey(TEST_NAMESPACE, TEST_SERVICE_NAME, true); distroConsistencyService.listen(key, recordListener); distroConsistencyService.put(key, instances); - verify(distroProtocol).sync(new DistroKey(key, KeyBuilder.INSTANCE_LIST_KEY_PREFIX), DataOperation.CHANGE, 1000L); + verify(distroProtocol) + .sync(new DistroKey(key, KeyBuilder.INSTANCE_LIST_KEY_PREFIX), DataOperation.CHANGE, 1000L); verify(notifier).addTask(key, DataOperation.CHANGE); verify(dataStore).put(eq(key), any(Datum.class)); } @@ -100,7 +101,8 @@ public class DistroConsistencyServiceImplTest extends BaseTest { public void testPutWithoutListener() throws NacosException { String key = KeyBuilder.buildInstanceListKey(TEST_NAMESPACE, TEST_SERVICE_NAME, true); distroConsistencyService.put(key, instances); - verify(distroProtocol).sync(new DistroKey(key, KeyBuilder.INSTANCE_LIST_KEY_PREFIX), DataOperation.CHANGE, 1000L); + verify(distroProtocol) + .sync(new DistroKey(key, KeyBuilder.INSTANCE_LIST_KEY_PREFIX), DataOperation.CHANGE, 1000L); verify(notifier, never()).addTask(key, DataOperation.CHANGE); verify(dataStore).put(eq(key), any(Datum.class)); } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/consistency/persistent/impl/NamingSnapshotOperationTest.java b/naming/src/test/java/com/alibaba/nacos/naming/consistency/persistent/impl/NamingSnapshotOperationTest.java index 9d1d1eda2..7a7dc96de 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/consistency/persistent/impl/NamingSnapshotOperationTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/consistency/persistent/impl/NamingSnapshotOperationTest.java @@ -27,7 +27,9 @@ import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; import org.springframework.mock.env.MockEnvironment; import java.nio.file.Paths; @@ -36,6 +38,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.ReentrantReadWriteLock; +@RunWith(MockitoJUnitRunner.class) public class NamingSnapshotOperationTest { static { diff --git a/naming/src/test/java/com/alibaba/nacos/naming/controllers/CatalogControllerTest.java b/naming/src/test/java/com/alibaba/nacos/naming/controllers/CatalogControllerTest.java index 0372c4f33..929453bdb 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/controllers/CatalogControllerTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/controllers/CatalogControllerTest.java @@ -18,19 +18,20 @@ package com.alibaba.nacos.naming.controllers; import com.alibaba.nacos.api.common.Constants; import com.alibaba.nacos.api.exception.NacosException; +import com.alibaba.nacos.naming.core.CatalogServiceV1Impl; import com.alibaba.nacos.naming.core.Cluster; import com.alibaba.nacos.naming.core.Instance; import com.alibaba.nacos.naming.core.Service; import com.alibaba.nacos.naming.core.ServiceManager; +import com.alibaba.nacos.naming.core.v2.upgrade.UpgradeJudgement; import com.fasterxml.jackson.databind.node.ObjectNode; - import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.test.util.ReflectionTestUtils; -import java.lang.reflect.Field; import java.util.Collections; import static org.junit.Assert.assertTrue; @@ -42,6 +43,11 @@ public class CatalogControllerTest { @Mock private ServiceManager serviceManager; + @Mock + protected UpgradeJudgement upgradeJudgement; + + private CatalogServiceV1Impl catalogServiceV1; + private CatalogController catalogController; private Service service; @@ -51,9 +57,10 @@ public class CatalogControllerTest { @Before public void setUp() throws NoSuchFieldException, IllegalAccessException { catalogController = new CatalogController(); - Field field = catalogController.getClass().getDeclaredField("serviceManager"); - field.setAccessible(true); - field.set(catalogController, serviceManager); + catalogServiceV1 = new CatalogServiceV1Impl(serviceManager); + ReflectionTestUtils.setField(catalogController, "serviceManager", serviceManager); + ReflectionTestUtils.setField(catalogController, "upgradeJudgement", upgradeJudgement); + ReflectionTestUtils.setField(catalogController, "catalogServiceV1", catalogServiceV1); service = new Service(TEST_SERVICE_NAME); service.setNamespaceId(Constants.DEFAULT_NAMESPACE_ID); service.setProtectThreshold(12.34f); diff --git a/naming/src/test/java/com/alibaba/nacos/naming/controllers/ClusterControllerTest.java b/naming/src/test/java/com/alibaba/nacos/naming/controllers/ClusterControllerTest.java index 2e18a0a7f..db76d8618 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/controllers/ClusterControllerTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/controllers/ClusterControllerTest.java @@ -20,6 +20,7 @@ import com.alibaba.nacos.api.common.Constants; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.naming.BaseTest; import com.alibaba.nacos.naming.core.Cluster; +import com.alibaba.nacos.naming.core.ClusterOperatorV1Impl; import com.alibaba.nacos.naming.core.Service; import com.alibaba.nacos.naming.misc.UtilsAndCommons; import org.junit.Assert; @@ -31,6 +32,7 @@ import org.springframework.mock.web.MockServletContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; @@ -47,6 +49,9 @@ public class ClusterControllerTest extends BaseTest { @InjectMocks private ClusterController clusterController; + @InjectMocks + private ClusterOperatorV1Impl clusterOperatorV1; + private MockMvc mockmvc; @Before @@ -55,6 +60,8 @@ public class ClusterControllerTest extends BaseTest { mockInjectSwitchDomain(); mockInjectDistroMapper(); mockmvc = MockMvcBuilders.standaloneSetup(clusterController).build(); + ReflectionTestUtils.setField(clusterController, "upgradeJudgement", upgradeJudgement); + ReflectionTestUtils.setField(clusterController, "clusterOperatorV1", clusterOperatorV1); } @Test @@ -118,13 +125,13 @@ public class ClusterControllerTest extends BaseTest { mockmvc.perform(builder3); Assert.assertEquals("HTTP", service.getClusterMap().get(TEST_CLUSTER_NAME).getHealthChecker().getType()); - + MockHttpServletRequestBuilder builder4 = MockMvcRequestBuilders .put(UtilsAndCommons.NACOS_NAMING_CONTEXT + "/cluster").param("clusterName", TEST_CLUSTER_NAME) .param("serviceName", TEST_SERVICE_NAME).param("healthChecker", "{\"type\":\"MYSQL\"}") .param("checkPort", "1").param("useInstancePort4Check", "true"); mockmvc.perform(builder4); - + Assert.assertEquals("MYSQL", service.getClusterMap().get(TEST_CLUSTER_NAME).getHealthChecker().getType()); } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/controllers/InstanceControllerTest.java b/naming/src/test/java/com/alibaba/nacos/naming/controllers/InstanceControllerTest.java index 173cc8269..8131bcde7 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/controllers/InstanceControllerTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/controllers/InstanceControllerTest.java @@ -17,12 +17,15 @@ package com.alibaba.nacos.naming.controllers; import com.alibaba.nacos.api.common.Constants; +import com.alibaba.nacos.common.constant.HttpHeaderConsts; import com.alibaba.nacos.common.utils.JacksonUtils; import com.alibaba.nacos.naming.BaseTest; import com.alibaba.nacos.naming.consistency.persistent.raft.RaftPeerSet; import com.alibaba.nacos.naming.core.Cluster; import com.alibaba.nacos.naming.core.Instance; +import com.alibaba.nacos.naming.core.InstanceOperatorServiceImpl; import com.alibaba.nacos.naming.core.Service; +import com.alibaba.nacos.naming.core.v2.upgrade.doublewrite.delay.DoubleWriteEventListener; import com.alibaba.nacos.naming.misc.UtilsAndCommons; import com.alibaba.nacos.naming.pojo.InstanceOperationInfo; import com.fasterxml.jackson.databind.JsonNode; @@ -33,12 +36,12 @@ import org.junit.runner.RunWith; import org.mockito.ArgumentMatchers; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.Mockito; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockServletContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; @@ -51,6 +54,8 @@ import java.util.List; import java.util.Map; import java.util.function.Function; +import static org.mockito.Mockito.when; + @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = MockServletContext.class) @WebAppConfiguration @@ -59,6 +64,12 @@ public class InstanceControllerTest extends BaseTest { @InjectMocks private InstanceController instanceController; + @InjectMocks + private InstanceOperatorServiceImpl instanceOperatorService; + + @Mock + private DoubleWriteEventListener doubleWriteEventListener; + @Mock private RaftPeerSet peerSet; @@ -68,6 +79,9 @@ public class InstanceControllerTest extends BaseTest { public void before() { super.before(); mockInjectPushServer(); + ReflectionTestUtils.setField(instanceController, "upgradeJudgement", upgradeJudgement); + ReflectionTestUtils.setField(instanceController, "instanceServiceV1", instanceOperatorService); + when(context.getBean(DoubleWriteEventListener.class)).thenReturn(doubleWriteEventListener); mockmvc = MockMvcBuilders.standaloneSetup(instanceController).build(); } @@ -87,7 +101,7 @@ public class InstanceControllerTest extends BaseTest { ipList.add(instance); service.updateIPs(ipList, false); - Mockito.when(serviceManager.getService(Constants.DEFAULT_NAMESPACE_ID, TEST_SERVICE_NAME)).thenReturn(service); + when(serviceManager.getService(Constants.DEFAULT_NAMESPACE_ID, TEST_SERVICE_NAME)).thenReturn(service); MockHttpServletRequestBuilder builder = MockMvcRequestBuilders .post(UtilsAndCommons.NACOS_NAMING_CONTEXT + "/instance").param("serviceName", TEST_SERVICE_NAME) @@ -127,10 +141,11 @@ public class InstanceControllerTest extends BaseTest { ipList.add(instance); service.updateIPs(ipList, false); - Mockito.when(serviceManager.getService(Constants.DEFAULT_NAMESPACE_ID, TEST_SERVICE_NAME)).thenReturn(service); + when(serviceManager.getService(Constants.DEFAULT_NAMESPACE_ID, TEST_SERVICE_NAME)).thenReturn(service); MockHttpServletRequestBuilder builder = MockMvcRequestBuilders - .get(UtilsAndCommons.NACOS_NAMING_CONTEXT + "/instance/list").param("serviceName", TEST_SERVICE_NAME); + .get(UtilsAndCommons.NACOS_NAMING_CONTEXT + "/instance/list").param("serviceName", TEST_SERVICE_NAME) + .header(HttpHeaderConsts.USER_AGENT_HEADER, "Nacos-Server:v1"); MockHttpServletResponse response = mockmvc.perform(builder).andReturn().getResponse(); String actualValue = response.getContentAsString(); @@ -150,10 +165,11 @@ public class InstanceControllerTest extends BaseTest { @Test public void getNullServiceInstances() throws Exception { - Mockito.when(serviceManager.getService(Constants.DEFAULT_NAMESPACE_ID, TEST_SERVICE_NAME)).thenReturn(null); + when(serviceManager.getService(Constants.DEFAULT_NAMESPACE_ID, TEST_SERVICE_NAME)).thenReturn(null); MockHttpServletRequestBuilder builder = MockMvcRequestBuilders - .get(UtilsAndCommons.NACOS_NAMING_CONTEXT + "/instance/list").param("serviceName", TEST_SERVICE_NAME); + .get(UtilsAndCommons.NACOS_NAMING_CONTEXT + "/instance/list").param("serviceName", TEST_SERVICE_NAME) + .header(HttpHeaderConsts.USER_AGENT_HEADER, "Nacos-Server:v1"); MockHttpServletResponse response = mockmvc.perform(builder).andReturn().getResponse(); String actualValue = response.getContentAsString(); @@ -178,7 +194,7 @@ public class InstanceControllerTest extends BaseTest { instanceList.add(instance); instanceList.add(instance2); - Mockito.when(serviceManager + when(serviceManager .batchOperate(ArgumentMatchers.anyString(), ArgumentMatchers.any(InstanceOperationInfo.class), ArgumentMatchers.any(Function.class))).thenReturn(instanceList); @@ -223,7 +239,7 @@ public class InstanceControllerTest extends BaseTest { instanceList.add(instance); instanceList.add(instance2); - Mockito.when(serviceManager + when(serviceManager .batchOperate(ArgumentMatchers.anyString(), ArgumentMatchers.any(InstanceOperationInfo.class), ArgumentMatchers.any(Function.class))).thenReturn(instanceList); diff --git a/naming/src/test/java/com/alibaba/nacos/naming/controllers/ServiceControllerTest.java b/naming/src/test/java/com/alibaba/nacos/naming/controllers/ServiceControllerTest.java index 30ca14d37..672eea034 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/controllers/ServiceControllerTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/controllers/ServiceControllerTest.java @@ -18,6 +18,8 @@ package com.alibaba.nacos.naming.controllers; import com.alibaba.nacos.api.common.Constants; import com.alibaba.nacos.naming.BaseTest; +import com.alibaba.nacos.naming.core.Service; +import com.alibaba.nacos.naming.core.ServiceOperatorV1Impl; import com.alibaba.nacos.naming.misc.UtilsAndCommons; import org.junit.Before; import org.junit.Test; @@ -29,13 +31,14 @@ import org.springframework.mock.web.MockServletContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import java.util.ArrayList; -import java.util.List; +import java.util.HashMap; +import java.util.Map; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -47,29 +50,31 @@ public class ServiceControllerTest extends BaseTest { @InjectMocks private ServiceController serviceController; + @InjectMocks + private ServiceOperatorV1Impl serviceOperatorV1; + private MockMvc mockmvc; @Before public void before() { super.before(); + ReflectionTestUtils.setField(serviceController, "serviceOperatorV1", serviceOperatorV1); mockmvc = MockMvcBuilders.standaloneSetup(serviceController).build(); } @Test public void testList() throws Exception { - List serviceNameList = new ArrayList<>(); + Map serviceNameList = new HashMap<>(); for (int i = 0; i < 3; i++) { - serviceNameList.add("DEFAULT_GROUP@@providers:com.alibaba.nacos.controller.test:" + i); + serviceNameList.put("DEFAULT_GROUP@@providers:com.alibaba.nacos.controller.test:" + i, new Service()); } - Mockito.when(serviceManager.getAllServiceNameList(Constants.DEFAULT_NAMESPACE_ID)).thenReturn(serviceNameList); + Mockito.when(serviceManager.chooseServiceMap(Constants.DEFAULT_NAMESPACE_ID)).thenReturn(serviceNameList); mockmvc.perform(MockMvcRequestBuilders.get(UtilsAndCommons.NACOS_NAMING_CONTEXT + "/service" + "/list") - .param("pageNo", "2").param("pageSize", "10") - .accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(MockMvcResultMatchers.jsonPath("$.doms").isArray()) - .andExpect(MockMvcResultMatchers.jsonPath("$.doms").isEmpty()) + .param("pageNo", "2").param("pageSize", "10").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()).andExpect(MockMvcResultMatchers.jsonPath("$.doms").isArray()) + .andExpect(MockMvcResultMatchers.jsonPath("$.doms").isNotEmpty()) .andExpect(MockMvcResultMatchers.jsonPath("$.count").value(serviceNameList.size())); } } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/core/DomainTest.java b/naming/src/test/java/com/alibaba/nacos/naming/core/DomainTest.java index 0df3ffa17..4f559b394 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/core/DomainTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/core/DomainTest.java @@ -17,22 +17,30 @@ package com.alibaba.nacos.naming.core; import com.alibaba.nacos.naming.BaseTest; +import com.alibaba.nacos.naming.core.v2.upgrade.doublewrite.delay.DoubleWriteEventListener; import com.alibaba.nacos.naming.misc.UtilsAndCommons; import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.mockito.Mock; import java.util.ArrayList; import java.util.List; import java.util.Map; +import static org.mockito.Mockito.when; + public class DomainTest extends BaseTest { private Service service; + @Mock + private DoubleWriteEventListener doubleWriteEventListener; + @Before public void before() { super.before(); + when(context.getBean(DoubleWriteEventListener.class)).thenReturn(doubleWriteEventListener); service = new Service(); service.setName("nacos.service.1"); Cluster cluster = new Cluster(UtilsAndCommons.DEFAULT_CLUSTER_NAME, service); diff --git a/naming/src/test/java/com/alibaba/nacos/naming/core/DomainsManagerTest.java b/naming/src/test/java/com/alibaba/nacos/naming/core/DomainsManagerTest.java index 27cd4c212..6d7e0dfe4 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/core/DomainsManagerTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/core/DomainsManagerTest.java @@ -17,6 +17,7 @@ package com.alibaba.nacos.naming.core; import com.alibaba.nacos.api.common.Constants; +import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.naming.BaseTest; import com.alibaba.nacos.naming.consistency.ephemeral.distro.DistroConsistencyServiceImpl; import org.junit.Assert; @@ -46,7 +47,7 @@ public class DomainsManagerTest extends BaseTest { @Test public void easyRemoveDomNotExist() throws Exception { - expectedException.expect(IllegalArgumentException.class); + expectedException.expect(NacosException.class); expectedException.expectMessage("specified service not exist, serviceName : " + TEST_SERVICE_NAME); manager.easyRemoveService(Constants.DEFAULT_NAMESPACE_ID, TEST_SERVICE_NAME); } @@ -57,7 +58,7 @@ public class DomainsManagerTest extends BaseTest { service.setNamespaceId(TEST_NAMESPACE); manager.putService(service); - List list = manager.searchServices(TEST_NAMESPACE, "test.*"); + List list = manager.searchServices(TEST_NAMESPACE, "(.*)test(.*)"); Assert.assertNotNull(list); Assert.assertEquals(1, list.size()); Assert.assertEquals(TEST_SERVICE_NAME, list.get(0).getName()); diff --git a/naming/src/test/java/com/alibaba/nacos/naming/core/ServiceManagerTest.java b/naming/src/test/java/com/alibaba/nacos/naming/core/ServiceManagerTest.java index 8ca3c2623..f481cf04b 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/core/ServiceManagerTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/core/ServiceManagerTest.java @@ -244,7 +244,7 @@ public class ServiceManagerTest extends BaseTest { @Test public void testEasyRemoveServiceFailed() throws Exception { - expectedException.expect(IllegalArgumentException.class); + expectedException.expect(NacosException.class); expectedException.expectMessage("specified service not exist, serviceName : " + TEST_SERVICE_NAME); serviceManager.easyRemoveService(TEST_NAMESPACE, TEST_SERVICE_NAME); } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/core/ServiceTest.java b/naming/src/test/java/com/alibaba/nacos/naming/core/ServiceTest.java index 4e0bce967..dc38170c0 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/core/ServiceTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/core/ServiceTest.java @@ -18,11 +18,13 @@ package com.alibaba.nacos.naming.core; import com.alibaba.nacos.common.utils.JacksonUtils; import com.alibaba.nacos.naming.BaseTest; +import com.alibaba.nacos.naming.core.v2.upgrade.doublewrite.delay.DoubleWriteEventListener; import com.alibaba.nacos.naming.selector.NoneSelector; import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.mockito.Mock; import java.util.ArrayList; import java.util.List; @@ -32,14 +34,19 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; public class ServiceTest extends BaseTest { private Service service; + @Mock + private DoubleWriteEventListener doubleWriteEventListener; + @Before public void before() { super.before(); + when(context.getBean(DoubleWriteEventListener.class)).thenReturn(doubleWriteEventListener); service = new Service("test-service"); mockInjectPushServer(); mockInjectHealthCheckProcessor(); diff --git a/naming/src/test/java/com/alibaba/nacos/naming/core/v2/upgrade/UpgradeJudgementTest.java b/naming/src/test/java/com/alibaba/nacos/naming/core/v2/upgrade/UpgradeJudgementTest.java index 244e25496..adc42f5f7 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/core/v2/upgrade/UpgradeJudgementTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/core/v2/upgrade/UpgradeJudgementTest.java @@ -49,6 +49,8 @@ import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class UpgradeJudgementTest { + private final long sleepForCheck = 800L; + @Mock private ConfigurableEnvironment environment; @@ -75,6 +77,7 @@ public class UpgradeJudgementTest { @Before public void setUp() throws Exception { EnvUtil.setEnvironment(environment); + EnvUtil.setIsStandalone(false); upgradeJudgement = new UpgradeJudgement(raftPeerSet, raftCore, versionJudgement, memberManager, serviceManager, doubleWriteDelayTaskEngine); } @@ -91,7 +94,7 @@ public class UpgradeJudgementTest { verify(raftPeerSet, never()).init(); verify(raftCore, never()).init(); verify(versionJudgement, never()).reset(); - TimeUnit.MILLISECONDS.sleep(500); + TimeUnit.MILLISECONDS.sleep(sleepForCheck); assertFalse(upgradeJudgement.isUseGrpcFeatures()); assertFalse(upgradeJudgement.isUseJraftFeatures()); } @@ -103,7 +106,7 @@ public class UpgradeJudgementTest { verify(raftPeerSet, never()).init(); verify(raftCore, never()).init(); verify(versionJudgement, never()).reset(); - TimeUnit.MILLISECONDS.sleep(500); + TimeUnit.MILLISECONDS.sleep(sleepForCheck); assertFalse(upgradeJudgement.isUseGrpcFeatures()); assertTrue(upgradeJudgement.isUseJraftFeatures()); } @@ -115,7 +118,7 @@ public class UpgradeJudgementTest { verify(raftPeerSet, never()).init(); verify(raftCore, never()).init(); verify(versionJudgement, never()).reset(); - TimeUnit.MILLISECONDS.sleep(500); + TimeUnit.MILLISECONDS.sleep(sleepForCheck); assertFalse(upgradeJudgement.isUseGrpcFeatures()); assertFalse(upgradeJudgement.isUseJraftFeatures()); } @@ -133,7 +136,7 @@ public class UpgradeJudgementTest { verify(raftPeerSet, never()).init(); verify(raftCore, never()).init(); verify(versionJudgement, never()).reset(); - TimeUnit.MILLISECONDS.sleep(500); + TimeUnit.MILLISECONDS.sleep(sleepForCheck); assertTrue(upgradeJudgement.isUseGrpcFeatures()); assertTrue(upgradeJudgement.isUseJraftFeatures()); } @@ -151,7 +154,7 @@ public class UpgradeJudgementTest { verify(raftPeerSet, never()).init(); verify(raftCore, never()).init(); verify(versionJudgement, never()).reset(); - TimeUnit.MILLISECONDS.sleep(500); + TimeUnit.MILLISECONDS.sleep(sleepForCheck); assertFalse(upgradeJudgement.isUseGrpcFeatures()); assertFalse(upgradeJudgement.isUseJraftFeatures()); } @@ -164,7 +167,7 @@ public class UpgradeJudgementTest { verify(raftPeerSet, never()).init(); verify(raftCore, never()).init(); verify(versionJudgement, never()).reset(); - TimeUnit.MILLISECONDS.sleep(500); + TimeUnit.MILLISECONDS.sleep(sleepForCheck); assertFalse(upgradeJudgement.isUseGrpcFeatures()); assertFalse(upgradeJudgement.isUseJraftFeatures()); } @@ -178,7 +181,7 @@ public class UpgradeJudgementTest { verify(raftPeerSet, never()).init(); verify(raftCore, never()).init(); verify(versionJudgement, never()).reset(); - TimeUnit.MILLISECONDS.sleep(500); + TimeUnit.MILLISECONDS.sleep(sleepForCheck); assertFalse(upgradeJudgement.isUseGrpcFeatures()); assertTrue(upgradeJudgement.isUseJraftFeatures()); } @@ -192,7 +195,7 @@ public class UpgradeJudgementTest { verify(raftPeerSet).init(); verify(raftCore).init(); verify(versionJudgement).reset(); - TimeUnit.MILLISECONDS.sleep(500); + TimeUnit.MILLISECONDS.sleep(sleepForCheck); assertFalse(upgradeJudgement.isUseGrpcFeatures()); assertFalse(upgradeJudgement.isUseJraftFeatures()); } @@ -206,7 +209,7 @@ public class UpgradeJudgementTest { verify(raftPeerSet).init(); verify(raftCore).init(); verify(versionJudgement).reset(); - TimeUnit.MILLISECONDS.sleep(500); + TimeUnit.MILLISECONDS.sleep(sleepForCheck); assertFalse(upgradeJudgement.isUseGrpcFeatures()); assertFalse(upgradeJudgement.isUseJraftFeatures()); } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/ClientBeatCheckTaskTest.java b/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/ClientBeatCheckTaskTest.java index cdf915ee2..4e06397af 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/ClientBeatCheckTaskTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/ClientBeatCheckTaskTest.java @@ -20,9 +20,11 @@ import com.alibaba.nacos.api.naming.PreservedMetadataKeys; import com.alibaba.nacos.naming.core.DistroMapper; import com.alibaba.nacos.naming.core.Instance; import com.alibaba.nacos.naming.core.Service; +import com.alibaba.nacos.naming.core.v2.upgrade.UpgradeJudgement; import com.alibaba.nacos.naming.misc.GlobalConfig; import com.alibaba.nacos.naming.misc.SwitchDomain; import com.alibaba.nacos.naming.push.UdpPushService; +import com.alibaba.nacos.sys.utils.ApplicationUtils; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -32,6 +34,7 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.context.ConfigurableApplicationContext; import org.springframework.test.util.ReflectionTestUtils; import java.util.ArrayList; @@ -39,6 +42,8 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import static org.mockito.Mockito.when; + @RunWith(MockitoJUnitRunner.class) public class ClientBeatCheckTaskTest { @@ -61,6 +66,12 @@ public class ClientBeatCheckTaskTest { @Mock private SwitchDomain switchDomain; + @Mock + private UpgradeJudgement upgradeJudgement; + + @Mock + private ConfigurableApplicationContext context; + @Before public void init() { ReflectionTestUtils.setField(clientBeatCheckTask, "service", serviceSpy); @@ -68,6 +79,8 @@ public class ClientBeatCheckTaskTest { Mockito.doReturn(globalConfig).when(clientBeatCheckTask).getGlobalConfig(); Mockito.doReturn(pushService).when(clientBeatCheckTask).getPushService(); Mockito.doReturn(switchDomain).when(clientBeatCheckTask).getSwitchDomain(); + ApplicationUtils.injectContext(context); + when(context.getBean(UpgradeJudgement.class)).thenReturn(upgradeJudgement); } @Test @@ -79,9 +92,6 @@ public class ClientBeatCheckTaskTest { Map metadata = new HashMap<>(); metadata.put(PreservedMetadataKeys.HEART_BEAT_TIMEOUT, "1000000000"); instance.setMetadata(metadata); - List instances = new ArrayList<>(); - instances.add(instance); - Mockito.when(serviceSpy.allIPs(true)).thenReturn(instances); Mockito.doReturn("test").when(serviceSpy).getName(); Mockito.doReturn(true).when(distroMapperSpy).responsible(Mockito.anyString()); @@ -104,7 +114,7 @@ public class ClientBeatCheckTaskTest { Mockito.doReturn(true).when(distroMapperSpy).responsible(Mockito.anyString()); Mockito.doReturn(true).when(switchDomain).isHealthCheckEnabled(); - Mockito.when(serviceSpy.allIPs(true)).thenReturn(instances); + when(serviceSpy.allIPs(true)).thenReturn(instances); clientBeatCheckTask.run(); Assert.assertFalse(instance.isHealthy()); @@ -119,11 +129,7 @@ public class ClientBeatCheckTaskTest { Map metadata = new HashMap<>(); metadata.put(PreservedMetadataKeys.IP_DELETE_TIMEOUT, "10"); instance.setMetadata(metadata); - List instances = new ArrayList<>(); - instances.add(instance); Mockito.doReturn(true).when(distroMapperSpy).responsible(null); - Mockito.doReturn(true).when(globalConfig).isExpireInstance(); - Mockito.when(serviceSpy.allIPs(true)).thenReturn(instances); clientBeatCheckTask.run(); } @@ -137,12 +143,8 @@ public class ClientBeatCheckTaskTest { Map metadata = new HashMap<>(); metadata.put(PreservedMetadataKeys.IP_DELETE_TIMEOUT, "10000"); instance.setMetadata(metadata); - List instances = new ArrayList<>(); - instances.add(instance); Mockito.doReturn(true).when(distroMapperSpy).responsible(null); - Mockito.doReturn(true).when(globalConfig).isExpireInstance(); - Mockito.when(serviceSpy.allIPs(true)).thenReturn(instances); clientBeatCheckTask.run(); } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/heartbeat/ClientBeatCheckTaskV2Test.java b/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/heartbeat/ClientBeatCheckTaskV2Test.java index 3e0e9da3e..ed3df924b 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/heartbeat/ClientBeatCheckTaskV2Test.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/heartbeat/ClientBeatCheckTaskV2Test.java @@ -25,6 +25,7 @@ import com.alibaba.nacos.naming.core.v2.metadata.NamingMetadataManager; import com.alibaba.nacos.naming.core.v2.pojo.HealthCheckInstancePublishInfo; import com.alibaba.nacos.naming.core.v2.pojo.Service; import com.alibaba.nacos.naming.misc.GlobalConfig; +import com.alibaba.nacos.naming.misc.UtilsAndCommons; import com.alibaba.nacos.sys.utils.ApplicationUtils; import org.junit.Before; import org.junit.Test; @@ -139,8 +140,9 @@ public class ClientBeatCheckTaskV2Test { injectInstance(true, System.currentTimeMillis()); Service service = Service.newService(NAMESPACE, GROUP_NAME, SERVICE_NAME); InstanceMetadata metadata = new InstanceMetadata(); - metadata.getExtendData().put(PreservedMetadataKeys.HEART_BEAT_TIMEOUT, 1000L); - String address = IP + IPUtil.IP_PORT_SPLITER + PORT; + metadata.getExtendData().put(PreservedMetadataKeys.HEART_BEAT_TIMEOUT, 500L); + String address = + IP + IPUtil.IP_PORT_SPLITER + PORT + IPUtil.IP_PORT_SPLITER + UtilsAndCommons.DEFAULT_CLUSTER_NAME; when(namingMetadataManager.getInstanceMetadata(service, address)).thenReturn(Optional.of(metadata)); when(globalConfig.isExpireInstance()).thenReturn(true); TimeUnit.SECONDS.sleep(1); @@ -150,10 +152,11 @@ public class ClientBeatCheckTaskV2Test { } private HealthCheckInstancePublishInfo injectInstance(boolean healthy, long heartbeatTime) { - Service service = Service.newService(NAMESPACE, GROUP_NAME, SERVICE_NAME); HealthCheckInstancePublishInfo instance = new HealthCheckInstancePublishInfo(IP, PORT); instance.setHealthy(healthy); instance.setLastHeartBeatTime(heartbeatTime); + instance.setCluster(UtilsAndCommons.DEFAULT_CLUSTER_NAME); + Service service = Service.newService(NAMESPACE, GROUP_NAME, SERVICE_NAME); client.addServiceInstance(service, instance); return instance; } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/interceptor/HealthCheckTaskInterceptWrapperTest.java b/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/interceptor/HealthCheckTaskInterceptWrapperTest.java index 4440935b7..b00391a18 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/interceptor/HealthCheckTaskInterceptWrapperTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/interceptor/HealthCheckTaskInterceptWrapperTest.java @@ -24,6 +24,7 @@ import com.alibaba.nacos.naming.core.v2.metadata.NamingMetadataManager; import com.alibaba.nacos.naming.core.v2.pojo.HealthCheckInstancePublishInfo; import com.alibaba.nacos.naming.core.v2.pojo.InstancePublishInfo; import com.alibaba.nacos.naming.core.v2.pojo.Service; +import com.alibaba.nacos.naming.core.v2.upgrade.UpgradeJudgement; import com.alibaba.nacos.naming.healthcheck.heartbeat.ClientBeatCheckTaskV2; import com.alibaba.nacos.naming.misc.GlobalConfig; import com.alibaba.nacos.naming.misc.SwitchDomain; @@ -76,6 +77,9 @@ public class HealthCheckTaskInterceptWrapperTest { @Mock private ConfigurableApplicationContext applicationContext; + @Mock + private UpgradeJudgement upgradeJudgement; + private IpPortBasedClient client; @Before @@ -84,10 +88,12 @@ public class HealthCheckTaskInterceptWrapperTest { when(applicationContext.getBean(GlobalConfig.class)).thenReturn(globalConfig); when(applicationContext.getBean(SwitchDomain.class)).thenReturn(switchDomain); when(applicationContext.getBean(DistroMapper.class)).thenReturn(distroMapper); + when(applicationContext.getBean(UpgradeJudgement.class)).thenReturn(upgradeJudgement); ApplicationUtils.injectContext(applicationContext); client = new IpPortBasedClient(CLIENT_ID, true); when(switchDomain.isHealthCheckEnabled()).thenReturn(true); when(distroMapper.responsible(client.getResponsibleId())).thenReturn(true); + when(upgradeJudgement.isUseGrpcFeatures()).thenReturn(true); ClientBeatCheckTaskV2 beatCheckTask = new ClientBeatCheckTaskV2(client); taskWrapper = new HealthCheckTaskInterceptWrapper(beatCheckTask); } @@ -163,7 +169,7 @@ public class HealthCheckTaskInterceptWrapperTest { Service service = Service.newService(NAMESPACE, GROUP_NAME, SERVICE_NAME); InstanceMetadata metadata = new InstanceMetadata(); metadata.getExtendData().put(PreservedMetadataKeys.HEART_BEAT_TIMEOUT, 1000L); - when(namingMetadataManager.getInstanceMetadata(service, instance.getInstanceId())).thenReturn(Optional.of(metadata)); + when(namingMetadataManager.getInstanceMetadata(service, instance.getMetadataId())).thenReturn(Optional.of(metadata)); when(globalConfig.isExpireInstance()).thenReturn(true); TimeUnit.SECONDS.sleep(1); taskWrapper.run(); diff --git a/naming/src/test/java/com/alibaba/nacos/naming/push/v2/NamingSubscriberServiceV2ImplTest.java b/naming/src/test/java/com/alibaba/nacos/naming/push/v2/NamingSubscriberServiceV2ImplTest.java index 86218a4ef..c4a85bade 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/push/v2/NamingSubscriberServiceV2ImplTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/push/v2/NamingSubscriberServiceV2ImplTest.java @@ -85,6 +85,7 @@ public class NamingSubscriberServiceV2ImplTest { new Subscriber("1.1.1.1:1111", "Test", "unknown", "1.1.1.1", "N", service.getGroupedServiceName(), 0)); when(client.getSubscriber(service1)).thenReturn( new Subscriber("1.1.1.1:1111", "Test", "unknown", "1.1.1.1", "N", service1.getGroupedServiceName(), 0)); + when(upgradeJudgement.isUseGrpcFeatures()).thenReturn(true); } @Test diff --git a/naming/src/test/java/com/alibaba/nacos/naming/raft/RaftStoreTest.java b/naming/src/test/java/com/alibaba/nacos/naming/raft/RaftStoreTest.java index e5d937d83..a6ff01ed6 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/raft/RaftStoreTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/raft/RaftStoreTest.java @@ -19,14 +19,18 @@ package com.alibaba.nacos.naming.raft; import com.alibaba.nacos.naming.BaseTest; import com.alibaba.nacos.naming.consistency.Datum; import com.alibaba.nacos.naming.consistency.KeyBuilder; +import com.alibaba.nacos.naming.consistency.persistent.ClusterVersionJudgement; import com.alibaba.nacos.naming.consistency.persistent.raft.RaftCore; import com.alibaba.nacos.naming.consistency.persistent.raft.RaftStore; import com.alibaba.nacos.naming.core.Instance; import com.alibaba.nacos.naming.core.Instances; import org.junit.Assert; +import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; +import org.mockito.Mock; import org.mockito.Spy; +import org.springframework.test.util.ReflectionTestUtils; public class RaftStoreTest extends BaseTest { @@ -37,6 +41,14 @@ public class RaftStoreTest extends BaseTest { @Spy public RaftStore raftStore; + @Mock + private ClusterVersionJudgement versionJudgement; + + @Before + public void setUp() { + ReflectionTestUtils.setField(raftCore, "versionJudgement", versionJudgement); + } + @Test public void wrietDatum() throws Exception { Datum datum = new Datum<>();