From 0e0900bfa9ec8b6c2cdc499c06d63a366a2879bb Mon Sep 17 00:00:00 2001 From: nkorange Date: Thu, 24 Jan 2019 16:56:51 +0800 Subject: [PATCH] #677 Add ephemeral instance implementation --- .../nacos/api/naming/pojo/Instance.java | 22 +- .../nacos/api/naming/pojo/Service.java | 11 +- .../alibaba/nacos/naming/acl/AuthChecker.java | 6 +- .../consistency/ConsistencyService.java | 2 +- .../naming/consistency/DataListener.java | 6 +- .../DelegateConsistencyServiceImpl.java | 2 +- .../nacos/naming/consistency/KeyBuilder.java | 23 +- .../PartitionConsistencyServiceImpl.java | 2 +- .../raft/RaftConsistencyServiceImpl.java | 4 +- .../consistency/persistent/raft/RaftCore.java | 16 +- .../persistent/raft/RaftStore.java | 4 +- .../naming/controllers/CatalogController.java | 183 +++++++------- .../naming/controllers/ClusterController.java | 5 +- .../naming/controllers/HealthController.java | 24 +- .../controllers/InstanceController.java | 159 ++++++------ .../controllers/OperatorController.java | 13 +- .../controllers/PartitionController.java | 15 ++ .../naming/controllers/RaftController.java | 2 +- .../naming/controllers/ServiceController.java | 134 ++-------- .../alibaba/nacos/naming/core/Cluster.java | 150 ++++------- .../nacos/naming/core/DistroMapper.java | 4 +- .../com/alibaba/nacos/naming/core/Domain.java | 132 ---------- .../core/{IpAddress.java => Instance.java} | 41 ++- ...VirtualClusterDomain.java => Service.java} | 210 ++++------------ .../nacos/naming/core/ServiceManager.java | 237 +++++++++--------- .../healthcheck/ClientBeatCheckTask.java | 49 ++-- .../healthcheck/ClientBeatProcessor.java | 32 +-- .../naming/healthcheck/HealthCheckCommon.java | 38 ++- .../naming/healthcheck/HealthCheckStatus.java | 10 +- .../naming/healthcheck/HealthCheckTask.java | 7 +- .../healthcheck/HttpHealthCheckProcessor.java | 16 +- .../MysqlHealthCheckProcessor.java | 16 +- .../healthcheck/TcpSuperSenseProcessor.java | 26 +- .../naming/misc/DomainStatusSynchronizer.java | 13 +- .../nacos/naming/misc/NamingProxy.java | 37 ++- .../nacos/naming/misc/SwitchDomain.java | 9 +- .../nacos/naming/misc/UtilsAndCommons.java | 42 ++-- .../nacos/naming/selector/LabelSelector.java | 16 +- .../nacos/naming/selector/NoneSelector.java | 4 +- .../nacos/naming/selector/Selector.java | 4 +- .../nacos/naming/view/ServiceDetailView.java | 2 +- .../controllers/InstanceControllerTest.java | 30 +-- .../nacos/naming/core/ClusterTest.java | 24 +- .../alibaba/nacos/naming/core/DomainTest.java | 25 +- .../nacos/naming/core/DomainsManagerTest.java | 4 +- .../{IpAddressTest.java => InstanceTest.java} | 28 +-- .../nacos/naming/web/APICommandsTest.java | 130 ---------- 47 files changed, 770 insertions(+), 1199 deletions(-) delete mode 100644 naming/src/main/java/com/alibaba/nacos/naming/core/Domain.java rename naming/src/main/java/com/alibaba/nacos/naming/core/{IpAddress.java => Instance.java} (87%) rename naming/src/main/java/com/alibaba/nacos/naming/core/{VirtualClusterDomain.java => Service.java} (71%) rename naming/src/test/java/com/alibaba/nacos/naming/core/{IpAddressTest.java => InstanceTest.java} (67%) delete mode 100644 naming/src/test/java/com/alibaba/nacos/naming/web/APICommandsTest.java diff --git a/api/src/main/java/com/alibaba/nacos/api/naming/pojo/Instance.java b/api/src/main/java/com/alibaba/nacos/api/naming/pojo/Instance.java index fcc840adea8..b19a78c4782 100644 --- a/api/src/main/java/com/alibaba/nacos/api/naming/pojo/Instance.java +++ b/api/src/main/java/com/alibaba/nacos/api/naming/pojo/Instance.java @@ -24,7 +24,7 @@ /** * Instance * - * @author dungu.zpf + * @author nkorange */ public class Instance { @@ -54,8 +54,18 @@ public class Instance { @JSONField(name = "valid") private boolean healthy = true; + /** + * If instance is enabled to accept request + */ private boolean enabled = true; + /** + * If instance is ephemeral + * + * @since 1.0.0 + */ + private boolean ephemeral = true; + /** * cluster information of instance */ @@ -147,6 +157,14 @@ public void setEnabled(boolean enabled) { this.enabled = enabled; } + public boolean isEphemeral() { + return ephemeral; + } + + public void setEphemeral(boolean ephemeral) { + this.ephemeral = ephemeral; + } + @Override public String toString() { return JSON.toJSONString(this); @@ -162,7 +180,7 @@ public boolean equals(Object obj) { return false; } - Instance host = (Instance)obj; + Instance host = (Instance) obj; return strEquals(toString(), host.toString()); } diff --git a/api/src/main/java/com/alibaba/nacos/api/naming/pojo/Service.java b/api/src/main/java/com/alibaba/nacos/api/naming/pojo/Service.java index 098270d8cd4..07a06c2b474 100644 --- a/api/src/main/java/com/alibaba/nacos/api/naming/pojo/Service.java +++ b/api/src/main/java/com/alibaba/nacos/api/naming/pojo/Service.java @@ -59,6 +59,9 @@ public class Service { private Map metadata = new HashMap(); + public Service() { + } + public Service(String name) { this.name = name; } @@ -114,12 +117,4 @@ public void setMetadata(Map metadata) { public void addMetadata(String key, String value) { this.metadata.put(key, value); } - - public AbstractSelector getSelector() { - return selector; - } - - public void setSelector(AbstractSelector selector) { - this.selector = selector; - } } diff --git a/naming/src/main/java/com/alibaba/nacos/naming/acl/AuthChecker.java b/naming/src/main/java/com/alibaba/nacos/naming/acl/AuthChecker.java index c33647b0f22..bcc3beb1d9d 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/acl/AuthChecker.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/acl/AuthChecker.java @@ -15,9 +15,9 @@ */ package com.alibaba.nacos.naming.acl; -import com.alibaba.nacos.api.common.Constants; +import com.alibaba.nacos.api.naming.CommonParams; import com.alibaba.nacos.core.utils.WebUtils; -import com.alibaba.nacos.naming.core.Domain; +import com.alibaba.nacos.naming.core.Service; import com.alibaba.nacos.naming.core.ServiceManager; import com.alibaba.nacos.naming.misc.SwitchDomain; import com.alibaba.nacos.naming.misc.UtilsAndCommons; @@ -72,7 +72,7 @@ public void doAuth(Map params, HttpServletRequest req) throws dom = WebUtils.optional(req, "tag", ""); } - Domain domObj = serviceManager.getService(namespaceId, dom); + Service domObj = serviceManager.getService(namespaceId, dom); if (domObj == null) { if (!req.getRequestURI().equals(UtilsAndCommons.NACOS_NAMING_CONTEXT + UtilsAndCommons.API_SET_ALL_WEIGHTS)) { diff --git a/naming/src/main/java/com/alibaba/nacos/naming/consistency/ConsistencyService.java b/naming/src/main/java/com/alibaba/nacos/naming/consistency/ConsistencyService.java index 8bd96ab8431..e0ad5a57d40 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/consistency/ConsistencyService.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/consistency/ConsistencyService.java @@ -56,7 +56,7 @@ public interface ConsistencyService { * @return data related to the key * @throws NacosException */ - Object get(String key) throws NacosException; + Datum get(String key) throws NacosException; /** * Listen for changes of a data diff --git a/naming/src/main/java/com/alibaba/nacos/naming/consistency/DataListener.java b/naming/src/main/java/com/alibaba/nacos/naming/consistency/DataListener.java index 30b4b49ceac..70a250d7136 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/consistency/DataListener.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/consistency/DataListener.java @@ -20,7 +20,7 @@ * * @author nacos */ -public interface DataListener { +public interface DataListener { /** * Determine if the listener was registered with this key @@ -45,12 +45,12 @@ public interface DataListener { * @param value data of the key * @throws Exception */ - void onChange(String key, Object value) throws Exception; + void onChange(String key, T value) throws Exception; /** * Action to do if data of target key has been removed * - * @param key target key + * @param key target key * @throws Exception */ void onDelete(String key) throws Exception; diff --git a/naming/src/main/java/com/alibaba/nacos/naming/consistency/DelegateConsistencyServiceImpl.java b/naming/src/main/java/com/alibaba/nacos/naming/consistency/DelegateConsistencyServiceImpl.java index 93edfaf51a3..96204856120 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/consistency/DelegateConsistencyServiceImpl.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/consistency/DelegateConsistencyServiceImpl.java @@ -47,7 +47,7 @@ public void remove(String key) throws NacosException { } @Override - public Object get(String key) throws NacosException { + public Datum get(String key) throws NacosException { return persistentConsistencyService.get(key); } diff --git a/naming/src/main/java/com/alibaba/nacos/naming/consistency/KeyBuilder.java b/naming/src/main/java/com/alibaba/nacos/naming/consistency/KeyBuilder.java index 37d6be7800d..b6f14b5b1fd 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/consistency/KeyBuilder.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/consistency/KeyBuilder.java @@ -17,6 +17,7 @@ /** * @author nkorange + * @since 1.0.0 */ public class KeyBuilder { @@ -25,18 +26,26 @@ public class KeyBuilder { private static final String PERSISTENT_KEY_PREFIX = "persistent"; private static final String INSTANCE_LIST_KEY_PREFIX = "instanceList"; - public static String buildEphemeralInstanceListKey(String namespaceId, String serviceName, String clusterName) { - return namespaceId + KEY_CONNECTOR + PERSISTENT_KEY_PREFIX + KEY_CONNECTOR + INSTANCE_LIST_KEY_PREFIX + KEY_CONNECTOR - + serviceName + KEY_CONNECTOR + clusterName; + public static String buildEphemeralInstanceListKey(String namespaceId, String serviceName) { + return namespaceId + KEY_CONNECTOR + + serviceName + KEY_CONNECTOR + EPHEMERAL_KEY_PREFIX + KEY_CONNECTOR + INSTANCE_LIST_KEY_PREFIX; } - public static String buildPersistentInstanceListKey(String namespaceId, String serviceName, String clusterName) { - return namespaceId + KEY_CONNECTOR + EPHEMERAL_KEY_PREFIX + KEY_CONNECTOR + INSTANCE_LIST_KEY_PREFIX + KEY_CONNECTOR - + serviceName + KEY_CONNECTOR + clusterName; + public static String buildPersistentInstanceListKey(String namespaceId, String serviceName) { + return namespaceId + KEY_CONNECTOR + + serviceName + KEY_CONNECTOR + PERSISTENT_KEY_PREFIX + KEY_CONNECTOR + INSTANCE_LIST_KEY_PREFIX; } + public static String buildInstanceListKey(String namespaceId, String serviceName, boolean ephemeral) { + if (ephemeral) { + return buildEphemeralInstanceListKey(namespaceId, serviceName); + } + return buildPersistentInstanceListKey(namespaceId, serviceName); + } + + public static boolean matchEphemeralInstanceListKey(String key) { - return key.contains(KEY_CONNECTOR + EPHEMERAL_KEY_PREFIX + KEY_CONNECTOR + INSTANCE_LIST_KEY_PREFIX + KEY_CONNECTOR); + return key.endsWith(KEY_CONNECTOR + EPHEMERAL_KEY_PREFIX + KEY_CONNECTOR + INSTANCE_LIST_KEY_PREFIX); } public static boolean matchInstanceListKey(String key) { diff --git a/naming/src/main/java/com/alibaba/nacos/naming/consistency/ephemeral/partition/PartitionConsistencyServiceImpl.java b/naming/src/main/java/com/alibaba/nacos/naming/consistency/ephemeral/partition/PartitionConsistencyServiceImpl.java index 2b37fb30e5f..5f8902a6de8 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/consistency/ephemeral/partition/PartitionConsistencyServiceImpl.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/consistency/ephemeral/partition/PartitionConsistencyServiceImpl.java @@ -76,7 +76,7 @@ public void remove(String key) throws NacosException { } @Override - public Object get(String key) throws NacosException { + public Datum get(String key) throws NacosException { return dataStore.get(key); } diff --git a/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/raft/RaftConsistencyServiceImpl.java b/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/raft/RaftConsistencyServiceImpl.java index 986b104c102..b3a945ab656 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/raft/RaftConsistencyServiceImpl.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/raft/RaftConsistencyServiceImpl.java @@ -23,7 +23,7 @@ public class RaftConsistencyServiceImpl implements PersistentConsistencyService @Override public void put(String key, Object value) throws NacosException { try { - raftCore.signalPublish(key, (String) value); + raftCore.signalPublish(key, value); } catch (Exception e) { Loggers.RAFT.error("Raft put failed.", e); throw new NacosException(NacosException.SERVER_ERROR, "Raft put failed, key:" + key + ", value:" + value); @@ -41,7 +41,7 @@ public void remove(String key) throws NacosException { } @Override - public Object get(String key) throws NacosException { + public Datum get(String key) throws NacosException { return raftCore.getDatum(key); } diff --git a/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/raft/RaftCore.java b/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/raft/RaftCore.java index d490128bca8..7b3e53ff358 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/raft/RaftCore.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/raft/RaftCore.java @@ -90,7 +90,7 @@ public Thread newThread(Runnable r) { private volatile Map> listeners = new ConcurrentHashMap<>(); - private volatile ConcurrentMap datums = new ConcurrentHashMap(); + private volatile ConcurrentMap> datums = new ConcurrentHashMap<>(); @Autowired private RaftPeerSet peers; @@ -115,10 +115,10 @@ public void init() throws Exception { long start = System.currentTimeMillis(); - ConcurrentMap datumMap = raftStore.loadDatums(); + ConcurrentMap> datumMap = raftStore.loadDatums(); if (datumMap != null && !datumMap.isEmpty()) { datums = datumMap; - for (Map.Entry entry : datumMap.entrySet()) { + for (Map.Entry> entry : datumMap.entrySet()) { notifier.addTask(entry.getValue(), ApplyAction.CHANGE); } } @@ -147,7 +147,7 @@ public Map> getListeners() { return listeners; } - public void signalPublish(String key, String value) throws Exception { + public void signalPublish(String key, T value) throws Exception { if (!isLeader()) { JSONObject params = new JSONObject(); @@ -163,7 +163,7 @@ public void signalPublish(String key, String value) throws Exception { try { OPERATE_LOCK.lock(); long start = System.currentTimeMillis(); - final Datum datum = new Datum(); + final Datum datum = new Datum<>(); datum.key = key; datum.value = value; if (getDatum(key) == null) { @@ -264,7 +264,7 @@ public Integer onCompleted(Response response) throws Exception { } } - public void onPublish(Datum datum, RaftPeer source) throws Exception { + public void onPublish(Datum datum, RaftPeer source) throws Exception { RaftPeer local = peers.local(); if (StringUtils.isBlank((String) datum.value)) { Loggers.RAFT.warn("received empty datum"); @@ -614,7 +614,7 @@ public RaftPeer receivedBeat(JSONObject beat) throws Exception { Map receivedKeysMap = new HashMap(datums.size()); - for (Map.Entry entry : datums.entrySet()) { + for (Map.Entry> entry : datums.entrySet()) { receivedKeysMap.put(entry.getKey(), 0); } @@ -829,7 +829,7 @@ public static String buildURL(String ip, String api) { return "http://" + ip + RunningConfig.getContextPath() + api; } - public Datum getDatum(String key) { + public Datum getDatum(String key) { return datums.get(key); } diff --git a/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/raft/RaftStore.java b/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/raft/RaftStore.java index e383979463d..4cbc62c1f6f 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/raft/RaftStore.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/raft/RaftStore.java @@ -60,9 +60,9 @@ public class RaftStore { CACHE_DIR = BASE_DIR + File.separator + "data"; } - public synchronized ConcurrentHashMap loadDatums() throws Exception { + public synchronized ConcurrentHashMap> loadDatums() throws Exception { - ConcurrentHashMap datums = new ConcurrentHashMap<>(32); + ConcurrentHashMap> datums = new ConcurrentHashMap<>(32); Datum datum; long start = System.currentTimeMillis(); for (File cache : listCaches()) { diff --git a/naming/src/main/java/com/alibaba/nacos/naming/controllers/CatalogController.java b/naming/src/main/java/com/alibaba/nacos/naming/controllers/CatalogController.java index 400eb2bcb9c..5048511f288 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/controllers/CatalogController.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/controllers/CatalogController.java @@ -17,25 +17,18 @@ import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; -import com.alibaba.nacos.api.common.Constants; import com.alibaba.nacos.api.naming.CommonParams; import com.alibaba.nacos.api.naming.pojo.Cluster; -import com.alibaba.nacos.api.naming.pojo.Instance; -import com.alibaba.nacos.api.naming.pojo.Service; -import com.alibaba.nacos.api.selector.SelectorType; import com.alibaba.nacos.core.utils.WebUtils; -import com.alibaba.nacos.naming.core.Domain; -import com.alibaba.nacos.naming.core.IpAddress; +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.VirtualClusterDomain; import com.alibaba.nacos.naming.exception.NacosException; -import com.alibaba.nacos.naming.healthcheck.HealthCheckMode; +import com.alibaba.nacos.naming.healthcheck.HealthCheckTask; import com.alibaba.nacos.naming.misc.UtilsAndCommons; import com.alibaba.nacos.naming.pojo.ClusterInfo; import com.alibaba.nacos.naming.pojo.IpAddressInfo; import com.alibaba.nacos.naming.pojo.ServiceDetailInfo; -import com.alibaba.nacos.naming.selector.LabelSelector; -import com.alibaba.nacos.naming.selector.NoneSelector; import com.alibaba.nacos.naming.view.ServiceDetailView; import com.alibaba.nacos.naming.view.ServiceView; import org.apache.commons.collections.CollectionUtils; @@ -47,21 +40,17 @@ import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; +import java.util.*; /** * @author nkorange */ @RestController - @RequestMapping(UtilsAndCommons.NACOS_NAMING_CONTEXT + UtilsAndCommons.NACOS_NAMING_CATALOG_CONTEXT) public class CatalogController { @Autowired - protected ServiceManager domainsManager; + protected ServiceManager serviceManager; @RequestMapping(value = "/serviceList") public JSONObject serviceList(HttpServletRequest request) throws Exception { @@ -74,8 +63,8 @@ public JSONObject serviceList(HttpServletRequest request) throws Exception { int pageSize = Integer.parseInt(WebUtils.required(request, "pgSize")); String keyword = WebUtils.optional(request, "keyword", StringUtils.EMPTY); - List doms = new ArrayList<>(); - int total = domainsManager.getPagedDom(namespaceId, page - 1, pageSize, keyword, doms); + List doms = new ArrayList<>(); + int total = serviceManager.getPagedDom(namespaceId, page - 1, pageSize, keyword, doms); if (CollectionUtils.isEmpty(doms)) { result.put("serviceList", Collections.emptyList()); @@ -84,17 +73,16 @@ public JSONObject serviceList(HttpServletRequest request) throws Exception { } JSONArray domArray = new JSONArray(); - for (Domain dom : doms) { - VirtualClusterDomain vDomain = (VirtualClusterDomain) dom; + for (Service dom : doms) { ServiceView serviceView = new ServiceView(); - serviceView.setName(vDomain.getName()); - serviceView.setClusterCount(vDomain.getClusterMap().size()); - serviceView.setIpCount(vDomain.allIPs().size()); + serviceView.setName(dom.getName()); + serviceView.setClusterCount(dom.getClusterMap().size()); + serviceView.setIpCount(dom.allIPs().size()); // FIXME should be optimized: int validCount = 0; - for (IpAddress ipAddress : vDomain.allIPs()) { - if (ipAddress.isValid()) { + for (Instance instance : dom.allIPs()) { + if (instance.isValid()) { validCount++; } } @@ -116,37 +104,14 @@ public ServiceDetailView serviceDetail(HttpServletRequest request) throws Except String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID, UtilsAndCommons.getDefaultNamespaceId()); String serviceName = WebUtils.required(request, "serviceName"); - VirtualClusterDomain domain = domainsManager.getService(namespaceId, serviceName); + Service domain = serviceManager.getService(namespaceId, serviceName); if (domain == null) { throw new NacosException(NacosException.NOT_FOUND, "serivce " + serviceName + " is not found!"); } ServiceDetailView detailView = new ServiceDetailView(); - Service service = new Service(serviceName); - service.setName(serviceName); - service.setProtectThreshold(domain.getProtectThreshold()); - service.setHealthCheckMode(HealthCheckMode.none.name()); - if (domain.getEnableHealthCheck()) { - service.setHealthCheckMode(HealthCheckMode.server.name()); - } - if (domain.getEnableClientBeat()) { - service.setHealthCheckMode(HealthCheckMode.client.name()); - } - service.setMetadata(domain.getMetadata()); - - switch (SelectorType.valueOf(domain.getSelector().getType())) { - case label: - service.setSelector((LabelSelector) domain.getSelector()); - break; - case none: - case unknown: - default: - service.setSelector((NoneSelector) domain.getSelector()); - break; - } - - detailView.setService(service); + detailView.setService(domain); List clusters = new ArrayList<>(); @@ -177,7 +142,7 @@ public JSONObject instanceList(HttpServletRequest request) throws Exception { int page = Integer.parseInt(WebUtils.required(request, "startPg")); int pageSize = Integer.parseInt(WebUtils.required(request, "pgSize")); - VirtualClusterDomain domain = domainsManager.getService(namespaceId, serviceName); + Service domain = serviceManager.getService(namespaceId, serviceName); if (domain == null) { throw new NacosException(NacosException.NOT_FOUND, "serivce " + serviceName + " is not found!"); } @@ -186,20 +151,7 @@ public JSONObject instanceList(HttpServletRequest request) throws Exception { throw new NacosException(NacosException.NOT_FOUND, "cluster " + clusterName + " is not found!"); } - List instances = new ArrayList<>(); - - for (IpAddress ipAddress : domain.getClusterMap().get(clusterName).allIPs()) { - Instance instance = new Instance(); - instance.setIp(ipAddress.getIp()); - instance.setMetadata(ipAddress.getMetadata()); - instance.setHealthy(ipAddress.isValid()); - instance.setPort(ipAddress.getPort()); - instance.setInstanceId(ipAddress.getInstanceId()); - instance.setWeight(ipAddress.getWeight()); - instance.setEnabled(ipAddress.isEnabled()); - - instances.add(instance); - } + List instances = domain.getClusterMap().get(clusterName).allIPs(); int start = (page - 1) * pageSize; int end = page * pageSize; @@ -230,39 +182,98 @@ public List listDetail(HttpServletRequest request) { UtilsAndCommons.getDefaultNamespaceId()); List serviceDetailInfoList = new ArrayList<>(); - domainsManager - .getDomMap(namespaceId) - .forEach( - (serviceName, domain) -> { - - if (domain instanceof VirtualClusterDomain) { + serviceManager + .getDomMap(namespaceId) + .forEach( + (serviceName, service) -> { - VirtualClusterDomain virtualClusterDomain = (VirtualClusterDomain) domain; - ServiceDetailInfo serviceDetailInfo = new ServiceDetailInfo(); - serviceDetailInfo.setServiceName(serviceName); - serviceDetailInfo.setMetadata(virtualClusterDomain.getMetadata()); + ServiceDetailInfo serviceDetailInfo = new ServiceDetailInfo(); + serviceDetailInfo.setServiceName(serviceName); + serviceDetailInfo.setMetadata(service.getMetadata()); - Map clusterInfoMap = getStringClusterInfoMap(virtualClusterDomain); - serviceDetailInfo.setClusterMap(clusterInfoMap); + Map clusterInfoMap = getStringClusterInfoMap(service); + serviceDetailInfo.setClusterMap(clusterInfoMap); - serviceDetailInfoList.add(serviceDetailInfo); - } - }); + serviceDetailInfoList.add(serviceDetailInfo); + }); return serviceDetailInfoList; } + @RequestMapping("/rt4Dom") + public JSONObject rt4Dom(HttpServletRequest request) { + + String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID, + UtilsAndCommons.getDefaultNamespaceId()); + String dom = WebUtils.required(request, "dom"); + + Service domObj = serviceManager.getService(namespaceId, dom); + if (domObj == null) { + throw new IllegalArgumentException("request dom doesn't exist"); + } + + JSONObject result = new JSONObject(); + + JSONArray clusters = new JSONArray(); + for (Map.Entry entry : domObj.getClusterMap().entrySet()) { + JSONObject packet = new JSONObject(); + HealthCheckTask task = entry.getValue().getHealthCheckTask(); + + packet.put("name", entry.getKey()); + packet.put("checkRTBest", task.getCheckRTBest()); + packet.put("checkRTWorst", task.getCheckRTWorst()); + packet.put("checkRTNormalized", task.getCheckRTNormalized()); + + clusters.add(packet); + } + result.put("clusters", clusters); + + return result; + } + + @RequestMapping("/getDomsByIP") + public JSONObject getDomsByIP(HttpServletRequest request) { + String ip = WebUtils.required(request, "ip"); + + Set doms = new HashSet(); + Map> serviceNameMap = serviceManager.getAllDomNames(); + + for (String namespaceId : serviceNameMap.keySet()) { + for (String serviceName : serviceNameMap.get(namespaceId)) { + Service service = serviceManager.getService(namespaceId, serviceName); + List instances = service.allIPs(); + for (Instance instance : instances) { + if (ip.contains(":")) { + if (StringUtils.equals(instance.getIp() + ":" + instance.getPort(), ip)) { + doms.add(namespaceId + UtilsAndCommons.SERVICE_GROUP_CONNECTOR + service.getName()); + } + } else { + if (StringUtils.equals(instance.getIp(), ip)) { + doms.add(namespaceId + UtilsAndCommons.SERVICE_GROUP_CONNECTOR + service.getName()); + } + } + } + } + } + + JSONObject result = new JSONObject(); + + result.put("doms", doms); + + return result; + } + /** * getStringClusterInfoMap * - * @param virtualClusterDomain + * @param service * @return */ - private Map getStringClusterInfoMap(VirtualClusterDomain virtualClusterDomain) { + private Map getStringClusterInfoMap(Service service) { Map clusterInfoMap = new HashedMap(); - virtualClusterDomain.getClusterMap().forEach((clusterName, cluster) -> { + service.getClusterMap().forEach((clusterName, cluster) -> { ClusterInfo clusterInfo = new ClusterInfo(); List ipAddressInfos = getIpAddressInfos(cluster.allIPs()); @@ -276,13 +287,13 @@ private Map getStringClusterInfoMap(VirtualClusterDomain vi /** * getIpAddressInfos * - * @param ipAddresses + * @param instances * @return */ - private List getIpAddressInfos(List ipAddresses) { + private List getIpAddressInfos(List instances) { List ipAddressInfos = new ArrayList<>(); - ipAddresses.forEach((ipAddress) -> { + instances.forEach((ipAddress) -> { IpAddressInfo ipAddressInfo = new IpAddressInfo(); ipAddressInfo.setIp(ipAddress.getIp()); diff --git a/naming/src/main/java/com/alibaba/nacos/naming/controllers/ClusterController.java b/naming/src/main/java/com/alibaba/nacos/naming/controllers/ClusterController.java index cd0788dcf88..4aada031fa6 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/controllers/ClusterController.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/controllers/ClusterController.java @@ -17,13 +17,12 @@ import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; -import com.alibaba.nacos.api.common.Constants; import com.alibaba.nacos.api.naming.CommonParams; import com.alibaba.nacos.api.naming.pojo.AbstractHealthChecker; import com.alibaba.nacos.core.utils.WebUtils; import com.alibaba.nacos.naming.core.Cluster; import com.alibaba.nacos.naming.core.ServiceManager; -import com.alibaba.nacos.naming.core.VirtualClusterDomain; +import com.alibaba.nacos.naming.core.Service; import com.alibaba.nacos.naming.exception.NacosException; import com.alibaba.nacos.naming.misc.Loggers; import com.alibaba.nacos.naming.misc.UtilsAndCommons; @@ -59,7 +58,7 @@ public String update(HttpServletRequest request) throws Exception { String checkPort = WebUtils.required(request, "checkPort"); String useInstancePort4Check = WebUtils.required(request, "useInstancePort4Check"); - VirtualClusterDomain domain = domainsManager.getService(namespaceId, serviceName); + Service domain = domainsManager.getService(namespaceId, serviceName); if (domain == null) { throw new NacosException(NacosException.INVALID_PARAM, "service not found:" + serviceName); } diff --git a/naming/src/main/java/com/alibaba/nacos/naming/controllers/HealthController.java b/naming/src/main/java/com/alibaba/nacos/naming/controllers/HealthController.java index b5f01cac39f..8fb51fdf747 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/controllers/HealthController.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/controllers/HealthController.java @@ -16,14 +16,14 @@ package com.alibaba.nacos.naming.controllers; import com.alibaba.fastjson.JSONObject; -import com.alibaba.nacos.api.common.Constants; import com.alibaba.nacos.api.naming.CommonParams; import com.alibaba.nacos.core.utils.WebUtils; import com.alibaba.nacos.naming.boot.RunningConfig; import com.alibaba.nacos.naming.core.DistroMapper; -import com.alibaba.nacos.naming.core.IpAddress; +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.VirtualClusterDomain; +import com.alibaba.nacos.naming.healthcheck.HealthCheckMode; import com.alibaba.nacos.naming.misc.HttpClient; import com.alibaba.nacos.naming.misc.Loggers; import com.alibaba.nacos.naming.misc.UtilsAndCommons; @@ -60,14 +60,14 @@ public class HealthController { private PushService pushService; @RequestMapping("/server") - public JSONObject hello(HttpServletRequest request) { + public JSONObject server(HttpServletRequest request) { JSONObject result = new JSONObject(); result.put("msg", "Hello! I am Nacos-Naming and healthy! total services: raft " + serviceManager.getDomCount() + ", local port:" + RunningConfig.getServerPort()); return result; } - @RequestMapping(method = {RequestMethod.POST, RequestMethod.PUT}) + @RequestMapping(value = "", method = RequestMethod.PUT) public String update(HttpServletRequest request) throws Exception { String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID, @@ -100,16 +100,16 @@ public String update(HttpServletRequest request) throws Exception { throw new IllegalArgumentException("failed to proxy health update to " + server + ", dom: " + dom); } } else { - VirtualClusterDomain virtualClusterDomain = serviceManager.getService(namespaceId, dom); + Service service = serviceManager.getService(namespaceId, dom); // Only health check "none" need update health status with api - if (!virtualClusterDomain.getEnableHealthCheck() && !virtualClusterDomain.getEnableClientBeat()) { - for (IpAddress ipAddress : virtualClusterDomain.allIPs(Lists.newArrayList(clusterName))) { - if (ipAddress.getIp().equals(ip) && ipAddress.getPort() == port) { - ipAddress.setValid(valid); + if (service.getHealthCheckMode().equals(HealthCheckMode.none.name())) { + for (Instance instance : service.allIPs(Lists.newArrayList(clusterName))) { + if (instance.getIp().equals(ip) && instance.getPort() == port) { + instance.setValid(valid); Loggers.EVT_LOG.info((valid ? "[IP-ENABLED]" : "[IP-DISABLED]") + " ips: " - + ipAddress.getIp() + ":" + ipAddress.getPort() + "@" + ipAddress.getClusterName() + + instance.getIp() + ":" + instance.getPort() + "@" + instance.getClusterName() + ", dom: " + dom + ", msg: update thought HealthController api"); - pushService.domChanged(namespaceId, virtualClusterDomain.getName()); + pushService.domChanged(namespaceId, service.getName()); break; } } diff --git a/naming/src/main/java/com/alibaba/nacos/naming/controllers/InstanceController.java b/naming/src/main/java/com/alibaba/nacos/naming/controllers/InstanceController.java index 1f4c190ac2e..f830ba567a0 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/controllers/InstanceController.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/controllers/InstanceController.java @@ -18,14 +18,13 @@ import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; -import com.alibaba.nacos.api.common.Constants; import com.alibaba.nacos.api.naming.CommonParams; import com.alibaba.nacos.core.utils.WebUtils; import com.alibaba.nacos.naming.boot.RunningConfig; import com.alibaba.nacos.naming.core.DistroMapper; -import com.alibaba.nacos.naming.core.IpAddress; +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.VirtualClusterDomain; import com.alibaba.nacos.naming.exception.NacosException; import com.alibaba.nacos.naming.healthcheck.RsInfo; import com.alibaba.nacos.naming.misc.HttpClient; @@ -34,7 +33,6 @@ import com.alibaba.nacos.naming.misc.UtilsAndCommons; import com.alibaba.nacos.naming.push.DataSource; import com.alibaba.nacos.naming.push.PushService; -import com.alibaba.nacos.naming.web.OverrideParameterRequestWrapper; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.StringUtils; @@ -104,33 +102,22 @@ public String getData(PushService.PushClient client) throws Exception { @RequestMapping(value = "/instance", method = RequestMethod.POST) public String register(HttpServletRequest request) throws Exception { - - OverrideParameterRequestWrapper requestWrapper = OverrideParameterRequestWrapper.buildRequest(request); - - String serviceJson = WebUtils.optional(request, "service", StringUtils.EMPTY); - - // set service info: - if (StringUtils.isNotEmpty(serviceJson)) { - JSONObject service = JSON.parseObject(serviceJson); - requestWrapper.addParameter("serviceName", service.getString("name")); - } - - return regService(requestWrapper); + return regService(request); } @RequestMapping(value = "/instance", method = RequestMethod.DELETE) public String deregister(HttpServletRequest request) throws Exception { - IpAddress ipAddress = getIPAddress(request); + Instance instance = getIPAddress(request); String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID, UtilsAndCommons.getDefaultNamespaceId()); String serviceName = WebUtils.required(request, CommonParams.SERVICE_NAME); - VirtualClusterDomain virtualClusterDomain = serviceManager.getService(namespaceId, serviceName); - if (virtualClusterDomain == null) { + Service service = serviceManager.getService(namespaceId, serviceName); + if (service == null) { return "ok"; } - serviceManager.removeInstance(namespaceId, serviceName, ipAddress); + serviceManager.removeInstance(namespaceId, serviceName, instance.isEphemeral(), instance); return "ok"; } @@ -141,7 +128,7 @@ public String update(HttpServletRequest request) throws Exception { } @RequestMapping(value = {"/instances", "/instance/list"}, method = RequestMethod.GET) - public JSONObject queryList(HttpServletRequest request) throws Exception { + public JSONObject list(HttpServletRequest request) throws Exception { String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID, UtilsAndCommons.getDefaultNamespaceId()); @@ -164,7 +151,7 @@ public JSONObject queryList(HttpServletRequest request) throws Exception { } @RequestMapping(value = "/instance", method = RequestMethod.GET) - public JSONObject queryDetail(HttpServletRequest request) throws Exception { + public JSONObject detail(HttpServletRequest request) throws Exception { String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID, UtilsAndCommons.getDefaultNamespaceId()); @@ -173,7 +160,7 @@ public JSONObject queryDetail(HttpServletRequest request) throws Exception { String ip = WebUtils.required(request, "ip"); int port = Integer.parseInt(WebUtils.required(request, "port")); - VirtualClusterDomain domain = serviceManager.getService(namespaceId, serviceName); + Service domain = serviceManager.getService(namespaceId, serviceName); if (domain == null) { throw new NacosException(NacosException.NOT_FOUND, "no dom " + serviceName + " found!"); } @@ -181,22 +168,22 @@ public JSONObject queryDetail(HttpServletRequest request) throws Exception { List clusters = new ArrayList<>(); clusters.add(cluster); - List ips = domain.allIPs(clusters); + List ips = domain.allIPs(clusters); if (ips == null || ips.isEmpty()) { throw new IllegalStateException("no ips found for cluster " + cluster + " in dom " + serviceName); } - for (IpAddress ipAddress : ips) { - if (ipAddress.getIp().equals(ip) && ipAddress.getPort() == port) { + for (Instance instance : ips) { + if (instance.getIp().equals(ip) && instance.getPort() == port) { JSONObject result = new JSONObject(); result.put("service", serviceName); result.put("ip", ip); result.put("port", port); result.put("clusterName", cluster); - result.put("weight", ipAddress.getWeight()); - result.put("healthy", ipAddress.isValid()); - result.put("metadata", ipAddress.getMetadata()); - result.put("instanceId", ipAddress.generateInstanceId()); + result.put("weight", instance.getWeight()); + result.put("healthy", instance.isValid()); + result.put("metadata", instance.getMetadata()); + result.put("instanceId", instance.generateInstanceId()); return result; } } @@ -205,7 +192,7 @@ public JSONObject queryDetail(HttpServletRequest request) throws Exception { } @RequestMapping(value = "/instance/beat", method = RequestMethod.PUT) - public JSONObject sendBeat(HttpServletRequest request) throws Exception { + public JSONObject beat(HttpServletRequest request) throws Exception { String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID, UtilsAndCommons.getDefaultNamespaceId()); String beat = WebUtils.required(request, "beat"); @@ -228,24 +215,24 @@ public JSONObject sendBeat(HttpServletRequest request) throws Exception { Loggers.DEBUG_LOG.debug("[CLIENT-BEAT] full arguments: beat: {}, serviceName: {}", clientBeat, serviceName); } - IpAddress ipAddress = serviceManager.getInstance(namespaceId, serviceName, clientBeat.getCluster(), clientBeat.getIp(), + Instance instance = serviceManager.getInstance(namespaceId, serviceName, clientBeat.getCluster(), clientBeat.getIp(), clientBeat.getPort()); - if (ipAddress == null) { - ipAddress = new IpAddress(); - ipAddress.setPort(clientBeat.getPort()); - ipAddress.setIp(clientBeat.getIp()); - ipAddress.setWeight(clientBeat.getWeight()); - ipAddress.setMetadata(clientBeat.getMetadata()); - ipAddress.setClusterName(clusterName); - ipAddress.setServiceName(serviceName); - ipAddress.setInstanceId(ipAddress.generateInstanceId()); - serviceManager.registerInstance(namespaceId, serviceName, clusterName, ipAddress); + if (instance == null) { + instance = new Instance(); + instance.setPort(clientBeat.getPort()); + instance.setIp(clientBeat.getIp()); + instance.setWeight(clientBeat.getWeight()); + instance.setMetadata(clientBeat.getMetadata()); + instance.setClusterName(clusterName); + instance.setServiceName(serviceName); + instance.setInstanceId(instance.generateInstanceId()); + serviceManager.registerInstance(namespaceId, serviceName, clusterName, instance); } - VirtualClusterDomain virtualClusterDomain = (VirtualClusterDomain) serviceManager.getService(namespaceId, serviceName); + Service service = (Service) serviceManager.getService(namespaceId, serviceName); - if (virtualClusterDomain == null) { + if (service == null) { throw new NacosException(NacosException.SERVER_ERROR, "service not found: " + serviceName + "@" + namespaceId); } @@ -271,7 +258,7 @@ public JSONObject sendBeat(HttpServletRequest request) throws Exception { throw new IllegalArgumentException("failed to proxy client beat to" + server + ", beat: " + beat); } } else { - virtualClusterDomain.processClientBeat(clientBeat); + service.processClientBeat(clientBeat); } JSONObject result = new JSONObject(); @@ -282,25 +269,34 @@ public JSONObject sendBeat(HttpServletRequest request) throws Exception { } - @RequestMapping("/ip4Dom2") - public JSONObject ip4Dom2(HttpServletRequest request) throws NacosException { + @RequestMapping("/listWithHealthStatus") + public JSONObject listWithHealthStatus(HttpServletRequest request) throws NacosException { - String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID, - UtilsAndCommons.getDefaultNamespaceId()); - String domName = WebUtils.required(request, "dom"); + String key = WebUtils.required(request, "key"); + + String domName; + String namespaceId; + + if (key.contains(UtilsAndCommons.SERVICE_GROUP_CONNECTOR)) { + namespaceId = key.split(UtilsAndCommons.SERVICE_GROUP_CONNECTOR)[0]; + domName = key.split(UtilsAndCommons.SERVICE_GROUP_CONNECTOR)[1]; + } else { + namespaceId = UtilsAndCommons.getDefaultNamespaceId(); + domName = key; + } - VirtualClusterDomain dom = serviceManager.getService(namespaceId, domName); + Service dom = serviceManager.getService(namespaceId, domName); if (dom == null) { throw new NacosException(NacosException.NOT_FOUND, "dom: " + domName + " not found."); } - List ips = dom.allIPs(); + List ips = dom.allIPs(); JSONObject result = new JSONObject(); JSONArray ipArray = new JSONArray(); - for (IpAddress ip : ips) { + for (Instance ip : ips) { ipArray.add(ip.toIPAddr() + "_" + ip.isValid()); } @@ -317,42 +313,41 @@ private String regService(HttpServletRequest request) throws Exception { String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID, UtilsAndCommons.getDefaultNamespaceId()); - IpAddress ipAddress = getIPAddress(request); - ipAddress.setApp(app); - ipAddress.setServiceName(serviceName); - ipAddress.setInstanceId(ipAddress.generateInstanceId()); - ipAddress.setLastBeat(System.currentTimeMillis()); + Instance instance = getIPAddress(request); + instance.setApp(app); + instance.setServiceName(serviceName); + instance.setInstanceId(instance.generateInstanceId()); + instance.setLastBeat(System.currentTimeMillis()); if (StringUtils.isNotEmpty(metadata)) { - ipAddress.setMetadata(UtilsAndCommons.parseMetadata(metadata)); + instance.setMetadata(UtilsAndCommons.parseMetadata(metadata)); } - serviceManager.registerInstance(namespaceId, serviceName, clusterName, ipAddress); + serviceManager.registerInstance(namespaceId, serviceName, clusterName, instance); return "ok"; } - private IpAddress getIPAddress(HttpServletRequest request) { + private Instance getIPAddress(HttpServletRequest request) { String ip = WebUtils.required(request, "ip"); String port = WebUtils.required(request, "port"); String weight = WebUtils.optional(request, "weight", "1"); - String cluster = WebUtils.optional(request, "cluster", StringUtils.EMPTY); - if (StringUtils.isEmpty(cluster)) { - cluster = WebUtils.optional(request, "clusterName", UtilsAndCommons.DEFAULT_CLUSTER_NAME); - } + String cluster = WebUtils.optional(request, "clusterName", UtilsAndCommons.DEFAULT_CLUSTER_NAME); boolean enabled = BooleanUtils.toBoolean(WebUtils.optional(request, "enable", "true")); + boolean ephemeral = BooleanUtils.toBoolean(WebUtils.optional(request, "ephemeral", "true")); - IpAddress ipAddress = new IpAddress(); - ipAddress.setPort(Integer.parseInt(port)); - ipAddress.setIp(ip); - ipAddress.setWeight(Double.parseDouble(weight)); - ipAddress.setClusterName(cluster); - ipAddress.setEnabled(enabled); + Instance instance = new Instance(); + instance.setPort(Integer.parseInt(port)); + instance.setIp(ip); + instance.setWeight(Double.parseDouble(weight)); + instance.setClusterName(cluster); + instance.setEnabled(enabled); + instance.setEphemeral(ephemeral); - return ipAddress; + return instance; } - public void checkIfDisabled(VirtualClusterDomain domObj) throws Exception { + public void checkIfDisabled(Service domObj) throws Exception { if (!domObj.getEnabled()) { throw new Exception("domain is disabled now."); } @@ -362,7 +357,7 @@ public JSONObject doSrvIPXT(String namespaceId, String dom, String agent, String String env, boolean isCheck, String app, String tid, boolean healthyOnly) throws Exception { JSONObject result = new JSONObject(); - VirtualClusterDomain domObj = (VirtualClusterDomain) serviceManager.getService(namespaceId, dom); + Service domObj = (Service) serviceManager.getService(namespaceId, dom); if (domObj == null) { throw new NacosException(NacosException.NOT_FOUND, "dom not found: " + dom); @@ -389,7 +384,7 @@ public JSONObject doSrvIPXT(String namespaceId, String dom, String agent, String cacheMillis = switchDomain.getDefaultCacheMillis(); } - List srvedIPs; + List srvedIPs; srvedIPs = domObj.srvIPs(clientIP, Arrays.asList(StringUtils.split(clusters, ","))); @@ -404,11 +399,11 @@ public JSONObject doSrvIPXT(String namespaceId, String dom, String agent, String Loggers.SRV_LOG.debug(msg); } - Map> ipMap = new HashMap<>(2); - ipMap.put(Boolean.TRUE, new ArrayList()); - ipMap.put(Boolean.FALSE, new ArrayList()); + Map> ipMap = new HashMap<>(2); + ipMap.put(Boolean.TRUE, new ArrayList()); + ipMap.put(Boolean.FALSE, new ArrayList()); - for (IpAddress ip : srvedIPs) { + for (Instance ip : srvedIPs) { ipMap.get(ip.isValid()).add(ip); } @@ -438,14 +433,14 @@ public JSONObject doSrvIPXT(String namespaceId, String dom, String agent, String JSONArray hosts = new JSONArray(); - for (Map.Entry> entry : ipMap.entrySet()) { - List ips = entry.getValue(); + for (Map.Entry> entry : ipMap.entrySet()) { + List ips = entry.getValue(); if (healthyOnly && !entry.getKey()) { continue; } - for (IpAddress ip : ips) { + for (Instance ip : ips) { JSONObject ipObj = new JSONObject(); ipObj.put("ip", ip.getIp()); diff --git a/naming/src/main/java/com/alibaba/nacos/naming/controllers/OperatorController.java b/naming/src/main/java/com/alibaba/nacos/naming/controllers/OperatorController.java index 5e2276767b7..1f49b819fb7 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/controllers/OperatorController.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/controllers/OperatorController.java @@ -18,13 +18,12 @@ import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; -import com.alibaba.nacos.api.common.Constants; import com.alibaba.nacos.api.naming.CommonParams; import com.alibaba.nacos.common.util.SystemUtils; import com.alibaba.nacos.core.utils.WebUtils; import com.alibaba.nacos.naming.core.DistroMapper; +import com.alibaba.nacos.naming.core.Service; import com.alibaba.nacos.naming.core.ServiceManager; -import com.alibaba.nacos.naming.core.VirtualClusterDomain; import com.alibaba.nacos.naming.misc.SwitchDomain; import com.alibaba.nacos.naming.misc.SwitchEntry; import com.alibaba.nacos.naming.misc.SwitchManager; @@ -41,6 +40,8 @@ import java.util.List; /** + * Operation for operators + * * @author nkorange */ @RestController @@ -146,9 +147,9 @@ public JSONObject getResponsibleServer4Dom(HttpServletRequest request) { String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID, UtilsAndCommons.getDefaultNamespaceId()); String dom = WebUtils.required(request, "dom"); - VirtualClusterDomain virtualClusterDomain = serviceManager.getService(namespaceId, dom); + Service service = serviceManager.getService(namespaceId, dom); - if (virtualClusterDomain == null) { + if (service == null) { throw new IllegalArgumentException("dom not found"); } @@ -173,9 +174,9 @@ public JSONObject responsible(HttpServletRequest request) { String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID, UtilsAndCommons.getDefaultNamespaceId()); String dom = WebUtils.required(request, "dom"); - VirtualClusterDomain virtualClusterDomain = (VirtualClusterDomain) serviceManager.getService(namespaceId, dom); + Service service = (Service) serviceManager.getService(namespaceId, dom); - if (virtualClusterDomain == null) { + if (service == null) { throw new IllegalArgumentException("dom not found"); } diff --git a/naming/src/main/java/com/alibaba/nacos/naming/controllers/PartitionController.java b/naming/src/main/java/com/alibaba/nacos/naming/controllers/PartitionController.java index f3de0d8284c..0c33b8b2e1c 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/controllers/PartitionController.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/controllers/PartitionController.java @@ -1,3 +1,18 @@ +/* + * Copyright 1999-2018 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.controllers; import com.alibaba.nacos.api.naming.pojo.Instance; diff --git a/naming/src/main/java/com/alibaba/nacos/naming/controllers/RaftController.java b/naming/src/main/java/com/alibaba/nacos/naming/controllers/RaftController.java index 76c26ea80db..0bfbe417057 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/controllers/RaftController.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/controllers/RaftController.java @@ -129,7 +129,7 @@ public String publish(HttpServletRequest request, HttpServletResponse response) value = URLDecoder.decode(value, "UTF-8"); JSONObject json = JSON.parseObject(value); - raftConsistencyService.put(json.getString("key"), json.getString("value")); + raftConsistencyService.put(json.getString("key"), json.getString("value"), String.class); return "ok"; } diff --git a/naming/src/main/java/com/alibaba/nacos/naming/controllers/ServiceController.java b/naming/src/main/java/com/alibaba/nacos/naming/controllers/ServiceController.java index a093399dbfd..b07fccd973e 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/controllers/ServiceController.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/controllers/ServiceController.java @@ -18,15 +18,15 @@ import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; -import com.alibaba.nacos.api.common.Constants; import com.alibaba.nacos.api.naming.CommonParams; import com.alibaba.nacos.api.selector.SelectorType; import com.alibaba.nacos.core.utils.WebUtils; import com.alibaba.nacos.naming.cluster.ServerListManager; -import com.alibaba.nacos.naming.core.*; +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.ServiceManager; import com.alibaba.nacos.naming.exception.NacosException; -import com.alibaba.nacos.naming.healthcheck.HealthCheckMode; -import com.alibaba.nacos.naming.healthcheck.HealthCheckTask; import com.alibaba.nacos.naming.misc.Loggers; import com.alibaba.nacos.naming.misc.SwitchDomain; import com.alibaba.nacos.naming.misc.UtilsAndCommons; @@ -86,12 +86,11 @@ public String create(HttpServletRequest request) throws Exception { metadataMap = UtilsAndCommons.parseMetadata(metadata); } - VirtualClusterDomain domObj = new VirtualClusterDomain(); + Service domObj = new Service(); domObj.setName(serviceName); domObj.setProtectThreshold(protectThreshold); - domObj.setEnableHealthCheck(HealthCheckMode.server.name().equals(healthCheckMode.toLowerCase())); + domObj.setHealthCheckMode(healthCheckMode.toLowerCase()); domObj.setEnabled(true); - domObj.setEnableClientBeat(HealthCheckMode.client.name().equals(healthCheckMode.toLowerCase())); domObj.setMetadata(metadataMap); domObj.setSelector(parseSelector(selector)); domObj.setNamespaceId(namespaceId); @@ -113,7 +112,7 @@ public String remove(HttpServletRequest request) throws Exception { UtilsAndCommons.getDefaultNamespaceId()); String serviceName = WebUtils.required(request, CommonParams.SERVICE_NAME); - VirtualClusterDomain service = serviceManager.getService(namespaceId, serviceName); + Service service = serviceManager.getService(namespaceId, serviceName); if (service == null) { throw new IllegalArgumentException("specified service not exist, serviceName : " + serviceName); } @@ -134,7 +133,7 @@ public JSONObject detail(HttpServletRequest request) throws Exception { UtilsAndCommons.getDefaultNamespaceId()); String serviceName = WebUtils.required(request, CommonParams.SERVICE_NAME); - VirtualClusterDomain domain = serviceManager.getService(namespaceId, serviceName); + Service domain = serviceManager.getService(namespaceId, serviceName); if (domain == null) { throw new NacosException(NacosException.NOT_FOUND, "serivce " + serviceName + " is not found!"); } @@ -143,19 +142,8 @@ public JSONObject detail(HttpServletRequest request) throws Exception { res.put("name", serviceName); res.put("namespaceId", domain.getNamespaceId()); res.put("protectThreshold", domain.getProtectThreshold()); - - res.put("healthCheckMode", HealthCheckMode.none.name()); - - if (domain.getEnableHealthCheck()) { - res.put("healthCheckMode", HealthCheckMode.server.name()); - } - - if (domain.getEnableClientBeat()) { - res.put("healthCheckMode", HealthCheckMode.client.name()); - } - + res.put("healthCheckMode", domain.getHealthCheckMode()); res.put("metadata", domain.getMetadata()); - res.put("selector", domain.getSelector()); return res; @@ -238,27 +226,14 @@ public String update(HttpServletRequest request) throws Exception { String metadata = WebUtils.optional(request, "metadata", StringUtils.EMPTY); String selector = WebUtils.optional(request, "selector", StringUtils.EMPTY); - VirtualClusterDomain domain = serviceManager.getService(namespaceId, serviceName); + Service domain = serviceManager.getService(namespaceId, serviceName); if (domain == null) { throw new NacosException(NacosException.INVALID_PARAM, "service " + serviceName + " not found!"); } domain.setProtectThreshold(protectThreshold); - if (HealthCheckMode.server.name().equals(healthCheckMode)) { - domain.setEnableHealthCheck(true); - domain.setEnableClientBeat(false); - } - - if (HealthCheckMode.client.name().equals(healthCheckMode)) { - domain.setEnableClientBeat(true); - domain.setEnableHealthCheck(false); - } - - if (HealthCheckMode.none.name().equals(healthCheckMode)) { - domain.setEnableClientBeat(false); - domain.setEnableHealthCheck(false); - } + domain.setHealthCheckMode(healthCheckMode); Map metadataMap = UtilsAndCommons.parseMetadata(metadata); domain.setMetadata(metadataMap); @@ -274,69 +249,6 @@ public String update(HttpServletRequest request) throws Exception { return "ok"; } - @RequestMapping("/rt4Dom") - public JSONObject rt4Dom(HttpServletRequest request) { - - String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID, - UtilsAndCommons.getDefaultNamespaceId()); - String dom = WebUtils.required(request, "dom"); - - VirtualClusterDomain domObj = serviceManager.getService(namespaceId, dom); - if (domObj == null) { - throw new IllegalArgumentException("request dom doesn't exist"); - } - - JSONObject result = new JSONObject(); - - JSONArray clusters = new JSONArray(); - for (Map.Entry entry : domObj.getClusterMap().entrySet()) { - JSONObject packet = new JSONObject(); - HealthCheckTask task = entry.getValue().getHealthCheckTask(); - - packet.put("name", entry.getKey()); - packet.put("checkRTBest", task.getCheckRTBest()); - packet.put("checkRTWorst", task.getCheckRTWorst()); - packet.put("checkRTNormalized", task.getCheckRTNormalized()); - - clusters.add(packet); - } - result.put("clusters", clusters); - - return result; - } - - @RequestMapping("/getDomsByIP") - public JSONObject getDomsByIP(HttpServletRequest request) { - String ip = WebUtils.required(request, "ip"); - - Set doms = new HashSet(); - Map> domMap = serviceManager.getAllDomNames(); - - for (String namespaceId : domMap.keySet()) { - for (String dom : domMap.get(namespaceId)) { - Domain domObj = serviceManager.getService(namespaceId, dom); - List ipObjs = domObj.allIPs(); - for (IpAddress ipObj : ipObjs) { - if (ip.contains(":")) { - if (StringUtils.equals(ipObj.getIp() + ":" + ipObj.getPort(), ip)) { - doms.add(namespaceId + UtilsAndCommons.SERVICE_GROUP_CONNECTOR + domObj.getName()); - } - } else { - if (StringUtils.equals(ipObj.getIp(), ip)) { - doms.add(namespaceId + UtilsAndCommons.SERVICE_GROUP_CONNECTOR + domObj.getName()); - } - } - } - } - } - - JSONObject result = new JSONObject(); - - result.put("doms", doms); - - return result; - } - @RequestMapping("/allDomNames") public JSONObject allDomNames(HttpServletRequest request) throws Exception { @@ -371,7 +283,7 @@ public JSONObject searchDom(HttpServletRequest request) { UtilsAndCommons.getDefaultNamespaceId()); String expr = WebUtils.required(request, "expr"); - List doms + List doms = serviceManager.searchDomains(namespaceId, ".*" + expr + ".*"); if (CollectionUtils.isEmpty(doms)) { @@ -380,7 +292,7 @@ public JSONObject searchDom(HttpServletRequest request) { } JSONArray domArray = new JSONArray(); - for (Domain dom : doms) { + for (Service dom : doms) { domArray.add(dom.getName()); } @@ -389,8 +301,8 @@ public JSONObject searchDom(HttpServletRequest request) { return result; } - @RequestMapping("/domStatus") - public String domStatus(HttpServletRequest request) { + @RequestMapping("/serviceStatus") + public String serviceStatus(HttpServletRequest request) { //format: dom1@@checksum@@@dom2@@checksum String domsStatusString = WebUtils.required(request, "domsStatus"); String serverIP = WebUtils.optional(request, "clientIP", ""); @@ -412,7 +324,7 @@ public String domStatus(HttpServletRequest request) { } String dom = entry.getKey(); String checksum = entry.getValue(); - Domain domain = serviceManager.getService(checksums.namespaceId, dom); + Service domain = serviceManager.getService(checksums.namespaceId, dom); if (domain == null) { continue; @@ -441,17 +353,17 @@ public JSONObject checksum(HttpServletRequest request) { String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID, UtilsAndCommons.getDefaultNamespaceId()); String serviceName = WebUtils.required(request, "serviceName"); - VirtualClusterDomain virtualClusterDomain = serviceManager.getService(namespaceId, serviceName); + Service service = serviceManager.getService(namespaceId, serviceName); - if (virtualClusterDomain == null) { + if (service == null) { throw new IllegalArgumentException("serviceName not found: " + serviceName); } - virtualClusterDomain.recalculateChecksum(); + service.recalculateChecksum(); JSONObject result = new JSONObject(); - result.put("checksum", virtualClusterDomain.getChecksum()); + result.put("checksum", service.getChecksum()); return result; } @@ -460,11 +372,11 @@ private List filterInstanceMetadata(String namespaceId, List ser List filteredServices = new ArrayList<>(); for (String service : serivces) { - VirtualClusterDomain serviceObj = serviceManager.getService(namespaceId, service); + Service serviceObj = serviceManager.getService(namespaceId, service); if (serviceObj == null) { continue; } - for (IpAddress address : serviceObj.allIPs()) { + for (Instance address : serviceObj.allIPs()) { if (address.getMetadata() != null && value.equals(address.getMetadata().get(key))) { filteredServices.add(service); break; @@ -478,7 +390,7 @@ private List filterServiceMetadata(String namespaceId, List seri List filteredServices = new ArrayList<>(); for (String service : serivces) { - VirtualClusterDomain serviceObj = serviceManager.getService(namespaceId, service); + Service serviceObj = serviceManager.getService(namespaceId, service); if (serviceObj == null) { continue; } diff --git a/naming/src/main/java/com/alibaba/nacos/naming/core/Cluster.java b/naming/src/main/java/com/alibaba/nacos/naming/core/Cluster.java index 8aadfb16dab..45719bb8465 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/core/Cluster.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/core/Cluster.java @@ -48,9 +48,6 @@ public class Cluster extends com.alibaba.nacos.api.naming.pojo.Cluster implement private int defIPPort = -1; - @JSONField(name = "nodegroup") - private String legacySyncConfig; - @JSONField(name = "healthChecker") private AbstractHealthChecker healthChecker = new AbstractHealthChecker.Tcp(); @@ -58,10 +55,13 @@ public class Cluster extends com.alibaba.nacos.api.naming.pojo.Cluster implement private HealthCheckTask checkTask; @JSONField(serialize = false) - private Set raftIPs = new HashSet(); + private Set persistentInstances = new HashSet<>(); + + @JSONField(serialize = false) + private Set ephemeralInstances = new HashSet<>(); @JSONField(serialize = false) - private Domain dom; + private Service dom; private Map ipContains = new ConcurrentHashMap<>(); @@ -86,30 +86,11 @@ public void setDefIPPort(int defIPPort) { this.defIPPort = defIPPort; } - public List allIPs() { - return new ArrayList(chooseIPs()); - } - - public List allIPs(String tenant) { - - List list = new ArrayList<>(); - for (IpAddress ipAddress : chooseIPs()) { - if (ipAddress.getTenant().equals(tenant)) { - list.add(ipAddress); - } - } - return list; - } - - public List allIPs(String tenant, String app) { - - List list = new ArrayList<>(); - for (IpAddress ipAddress : chooseIPs()) { - if (ipAddress.getTenant().equals(tenant) && ipAddress.getApp().equals(app)) { - list.add(ipAddress); - } - } - return list; + public List allIPs() { + List allInstances = new ArrayList<>(); + allInstances.addAll(persistentInstances); + allInstances.addAll(ephemeralInstances); + return allInstances; } public void init() { @@ -121,34 +102,18 @@ public void destroy() { checkTask.setCancelled(true); } - public void addIP(IpAddress ip) { - chooseIPs().add(ip); - } - - public void removeIP(IpAddress ip) { - chooseIPs().remove(ip); - } - public HealthCheckTask getHealthCheckTask() { return checkTask; } - public Domain getDom() { + public Service getDom() { return dom; } - public void setDom(Domain dom) { + public void setDom(Service dom) { this.dom = dom; } - public String getLegacySyncConfig() { - return legacySyncConfig; - } - - public void setLegacySyncConfig(String nodegroup) { - this.legacySyncConfig = nodegroup; - } - @Override public Cluster clone() throws CloneNotSupportedException { super.clone(); @@ -156,23 +121,23 @@ public Cluster clone() throws CloneNotSupportedException { cluster.setHealthChecker(healthChecker.clone()); cluster.setDom(getDom()); - cluster.raftIPs = new HashSet(); + cluster.persistentInstances = new HashSet(); cluster.checkTask = null; cluster.metadata = new HashMap<>(metadata); return cluster; } - public void updateIPs(List ips) { - HashMap oldIPMap = new HashMap<>(raftIPs.size()); + public void updateIPs(List ips) { + HashMap oldIPMap = new HashMap<>(persistentInstances.size()); - for (IpAddress ip : this.raftIPs) { + for (Instance ip : this.persistentInstances) { oldIPMap.put(ip.getDatumKey(), ip); } - List updatedIPs = updatedIPs(ips, oldIPMap.values()); + List updatedIPs = updatedIPs(ips, oldIPMap.values()); if (updatedIPs.size() > 0) { - for (IpAddress ip : updatedIPs) { - IpAddress oldIP = oldIPMap.get(ip.getDatumKey()); + for (Instance ip : updatedIPs) { + Instance oldIP = oldIPMap.get(ip.getDatumKey()); // do not update the ip validation status of updated ips // because the checker has the most precise result @@ -194,75 +159,68 @@ public void updateIPs(List ips) { } } - List newIPs = subtract(ips, oldIPMap.values()); + List newIPs = subtract(ips, oldIPMap.values()); if (newIPs.size() > 0) { Loggers.EVT_LOG.info("{} {SYNC} {IP-NEW} cluster: {}, new ips size: {}, content: {}", getDom().getName(), getName(), newIPs.size(), newIPs.toString()); - for (IpAddress ip : newIPs) { + for (Instance ip : newIPs) { HealthCheckStatus.reset(ip); } } - List deadIPs = subtract(oldIPMap.values(), ips); + List deadIPs = subtract(oldIPMap.values(), ips); if (deadIPs.size() > 0) { Loggers.EVT_LOG.info("{} {SYNC} {IP-DEAD} cluster: {}, dead ips size: {}, content: {}", getDom().getName(), getName(), deadIPs.size(), deadIPs.toString()); - for (IpAddress ip : deadIPs) { + for (Instance ip : deadIPs) { HealthCheckStatus.remv(ip); } } - this.raftIPs = new HashSet(ips); - - StringBuilder stringBuilder = new StringBuilder(); - for (IpAddress ipAddress : raftIPs) { - stringBuilder.append(ipAddress.toIPAddr()).append(ipAddress.isValid()); - } + this.persistentInstances = new HashSet<>(ips); ipContains.clear(); - for (IpAddress ipAddress : raftIPs) { - ipContains.put(ipAddress.toIPAddr(), true); + for (Instance instance : persistentInstances) { + ipContains.put(instance.toIPAddr(), true); } } - public List updatedIPs(Collection a, Collection b) { + public List updatedIPs(Collection a, Collection b) { - List intersects = (List) CollectionUtils.intersection(a, b); - Map stringIPAddressMap = new ConcurrentHashMap<>(intersects.size()); + List intersects = (List) CollectionUtils.intersection(a, b); + Map stringIPAddressMap = new ConcurrentHashMap<>(intersects.size()); - for (IpAddress ipAddress : intersects) { - stringIPAddressMap.put(ipAddress.getIp() + ":" + ipAddress.getPort(), ipAddress); + for (Instance instance : intersects) { + stringIPAddressMap.put(instance.getIp() + ":" + instance.getPort(), instance); } Map intersectMap = new ConcurrentHashMap<>(a.size() + b.size()); - Map ipAddressMap = new ConcurrentHashMap<>(a.size()); - Map ipAddressMap1 = new ConcurrentHashMap<>(b.size()); - Map ipAddressMap2 = new ConcurrentHashMap<>(a.size()); + Map instanceMap = new ConcurrentHashMap<>(a.size()); + Map instanceMap1 = new ConcurrentHashMap<>(a.size()); - for (IpAddress ipAddress : b) { - if (stringIPAddressMap.containsKey(ipAddress.getIp() + ":" + ipAddress.getPort())) { - intersectMap.put(ipAddress.toString(), 1); + for (Instance instance : b) { + if (stringIPAddressMap.containsKey(instance.getIp() + ":" + instance.getPort())) { + intersectMap.put(instance.toString(), 1); } - ipAddressMap1.put(ipAddress.toString(), ipAddress); } - for (IpAddress ipAddress : a) { - if (stringIPAddressMap.containsKey(ipAddress.getIp() + ":" + ipAddress.getPort())) { + for (Instance instance : a) { + if (stringIPAddressMap.containsKey(instance.getIp() + ":" + instance.getPort())) { - if (intersectMap.containsKey(ipAddress.toString())) { - intersectMap.put(ipAddress.toString(), 2); + if (intersectMap.containsKey(instance.toString())) { + intersectMap.put(instance.toString(), 2); } else { - intersectMap.put(ipAddress.toString(), 1); + intersectMap.put(instance.toString(), 1); } } - ipAddressMap2.put(ipAddress.toString(), ipAddress); + instanceMap1.put(instance.toString(), instance); } @@ -271,24 +229,24 @@ public List updatedIPs(Collection a, Collection Integer value = entry.getValue(); if (value == 1) { - if (ipAddressMap2.containsKey(key)) { - ipAddressMap.put(key, ipAddressMap2.get(key)); + if (instanceMap1.containsKey(key)) { + instanceMap.put(key, instanceMap1.get(key)); } } } - return new ArrayList<>(ipAddressMap.values()); + return new ArrayList<>(instanceMap.values()); } - public List subtract(Collection a, Collection b) { - Map mapa = new HashMap<>(b.size()); - for (IpAddress o : b) { + public List subtract(Collection a, Collection b) { + Map mapa = new HashMap<>(b.size()); + for (Instance o : b) { mapa.put(o.getIp() + ":" + o.getPort(), o); } - List result = new ArrayList(); + List result = new ArrayList(); - for (IpAddress o : a) { + for (Instance o : a) { if (!mapa.containsKey(o.getIp() + ":" + o.getPort())) { result.add(o); } @@ -297,10 +255,6 @@ public List subtract(Collection a, Collection b return result; } - public Set chooseIPs() { - return raftIPs; - } - @Override public int hashCode() { return Objects.hash(getName()); @@ -384,11 +338,11 @@ public void setSitegroup(String sitegroup) { this.sitegroup = sitegroup; } - public boolean contains(IpAddress ip) { + public boolean contains(Instance ip) { return ipContains.containsKey(ip.toIPAddr()); } - public void valid() { + public void validate() { if (!getName().matches(CLUSTER_NAME_SYNTAX)) { throw new IllegalArgumentException("cluster name can only have these characters: 0-9a-zA-Z-, current: " + getName()); } diff --git a/naming/src/main/java/com/alibaba/nacos/naming/core/DistroMapper.java b/naming/src/main/java/com/alibaba/nacos/naming/core/DistroMapper.java index 28ec8aeda9f..ee3e672c0fa 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/core/DistroMapper.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/core/DistroMapper.java @@ -285,11 +285,11 @@ public synchronized void onReceiveServerStatus(String configInfo) { } } - public boolean responsible(Cluster cluster, IpAddress ipAddress) { + public boolean responsible(Cluster cluster, Instance instance) { return switchDomain.isHealthCheckEnabled(cluster.getServiceName()) && !cluster.getHealthCheckTask().isCancelled() && responsible(cluster.getServiceName()) - && cluster.contains(ipAddress); + && cluster.contains(instance); } public boolean responsible(String dom) { diff --git a/naming/src/main/java/com/alibaba/nacos/naming/core/Domain.java b/naming/src/main/java/com/alibaba/nacos/naming/core/Domain.java deleted file mode 100644 index 6c93416304c..00000000000 --- a/naming/src/main/java/com/alibaba/nacos/naming/core/Domain.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright 1999-2018 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.core; - -import java.util.List; - -/** - * @author nkorange - */ -public interface Domain { - /** - * Get name of domain - * - * @return Name of domain - */ - String getName(); - - /** - * Set name of domain - * - * @param name Domain name - */ - void setName(String name); - - /** - * Get token of domain - * - * @return Token of domain - */ - String getToken(); - - /** - * Set token of domain - * - * @param token Domain token - */ - void setToken(String token); - - /** - * Get domain owners - * - * @return Domain owners - */ - List getOwners(); - - /** - * Set domain owners - * - * @param owners Domain owners - */ - void setOwners(List owners); - - /** - * Initiation of domain - */ - void init(); - - /** - * Domain destruction - * - * @throws Exception - */ - void destroy() throws Exception; - - /** - * Get whole list IP of domain - * - * @return Whole list IP of domain - */ - List allIPs(); - - /** - * Get servable IP list of domain. - * - * @param clientIP Request IP of client - * @return Servable IP list of domain. - */ - List srvIPs(String clientIP); - - /** - * get JSON serialization of domain - * - * @return JSON representation of domain - */ - String toJSON(); - - /** - * Set protect threshold of domain - * - * @param protectThreshold Protect threshold - */ - void setProtectThreshold(float protectThreshold); - - /** - * Get protect threshold of domain - * - * @return Protect threshold of domain - */ - float getProtectThreshold(); - - /** - * Replace domain using properties of 'dom' - * - * @param dom New domain - */ - void update(Domain dom); - - /** - * Get checksum of domain - * - * @return Checksum of domain - */ - String getChecksum(); - - /** - * Refresh checksum of domain - */ - void recalculateChecksum(); -} diff --git a/naming/src/main/java/com/alibaba/nacos/naming/core/IpAddress.java b/naming/src/main/java/com/alibaba/nacos/naming/core/Instance.java similarity index 87% rename from naming/src/main/java/com/alibaba/nacos/naming/core/IpAddress.java rename to naming/src/main/java/com/alibaba/nacos/naming/core/Instance.java index 25c7b770ef4..402fc0612a9 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/core/IpAddress.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/core/Instance.java @@ -17,7 +17,6 @@ import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; -import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.naming.healthcheck.HealthCheckStatus; import com.alibaba.nacos.naming.misc.Loggers; import com.alibaba.nacos.naming.misc.UtilsAndCommons; @@ -28,11 +27,11 @@ import java.util.regex.Pattern; /** - * IP under domain + * IP under service * * @author nkorange */ -public class IpAddress extends Instance implements Comparable { +public class Instance extends com.alibaba.nacos.api.naming.pojo.Instance implements Comparable { private static final double MAX_WEIGHT_VALUE = 10000.0D; private static final double MIN_POSTIVE_WEIGHT_VALUE = 0.01D; @@ -54,7 +53,7 @@ public class IpAddress extends Instance implements Comparable { public static final String SPLITER = "_"; - public IpAddress() { + public Instance() { } public boolean isMockValid() { @@ -73,19 +72,19 @@ public void setLastBeat(long lastBeat) { this.lastBeat = lastBeat; } - public IpAddress(String ip, int port) { + public Instance(String ip, int port) { this.setIp(ip); this.setPort(port); this.setClusterName(UtilsAndCommons.DEFAULT_CLUSTER_NAME); } - public IpAddress(String ip, int port, String clusterName) { + public Instance(String ip, int port, String clusterName) { this.setIp(ip.trim()); this.setPort(port); this.setClusterName(clusterName); } - public IpAddress(String ip, int port, String clusterName, String tenant, String app) { + public Instance(String ip, int port, String clusterName, String tenant, String app) { this.setIp(ip.trim()); this.setPort(port); this.setClusterName(clusterName); @@ -93,7 +92,7 @@ public IpAddress(String ip, int port, String clusterName, String tenant, String this.app = app; } - public static IpAddress fromString(String config) { + public static Instance fromString(String config) { String[] ipAddressAttributes = config.split(SPLITER); if (ipAddressAttributes.length < 1) { return null; @@ -112,7 +111,7 @@ public static IpAddress fromString(String config) { port = Integer.parseInt(matcher.group(expectedGroupCount)); } - IpAddress ipAddress = new IpAddress(matcher.group(1), port); + Instance instance = new Instance(matcher.group(1), port); // 7 possible formats of config: // ip:port @@ -126,7 +125,7 @@ public static IpAddress fromString(String config) { if (ipAddressAttributes.length > minimumLength) { // determine 'weight': - ipAddress.setWeight(NumberUtils.toDouble(ipAddressAttributes[minimumLength], 1)); + instance.setWeight(NumberUtils.toDouble(ipAddressAttributes[minimumLength], 1)); } minimumLength++; @@ -135,13 +134,13 @@ public static IpAddress fromString(String config) { // determine 'valid': if (Boolean.TRUE.toString().equals(ipAddressAttributes[minimumLength]) || Boolean.FALSE.toString().equals(ipAddressAttributes[minimumLength])) { - ipAddress.setValid(Boolean.parseBoolean(ipAddressAttributes[minimumLength])); + instance.setValid(Boolean.parseBoolean(ipAddressAttributes[minimumLength])); } // determine 'cluster': if (!Boolean.TRUE.toString().equals(ipAddressAttributes[ipAddressAttributes.length - 1]) && !Boolean.FALSE.toString().equals(ipAddressAttributes[ipAddressAttributes.length - 1])) { - ipAddress.setClusterName(ipAddressAttributes[ipAddressAttributes.length - 1]); + instance.setClusterName(ipAddressAttributes[ipAddressAttributes.length - 1]); } } @@ -151,11 +150,11 @@ public static IpAddress fromString(String config) { // determine 'marked': if (Boolean.TRUE.toString().equals(ipAddressAttributes[minimumLength]) || Boolean.FALSE.toString().equals(ipAddressAttributes[minimumLength])) { - ipAddress.setMarked(Boolean.parseBoolean(ipAddressAttributes[minimumLength])); + instance.setMarked(Boolean.parseBoolean(ipAddressAttributes[minimumLength])); } } - return ipAddress; + return instance; } public String toIPAddr() { @@ -172,11 +171,11 @@ public String toJSON() { } - public static IpAddress fromJSON(String json) { - IpAddress ip; + public static Instance fromJSON(String json) { + Instance ip; try { - ip = JSON.parseObject(json, IpAddress.class); + ip = JSON.parseObject(json, Instance.class); } catch (Exception e) { ip = fromString(json); } @@ -205,7 +204,7 @@ public boolean equals(Object obj) { if (obj == this) { return true; } - IpAddress other = (IpAddress) obj; + Instance other = (Instance) obj; // 0 means wild return getIp().equals(other.getIp()) && (getPort() == other.getPort() || getPort() == 0); @@ -300,13 +299,13 @@ public String generateInstanceId() { @Override public int compareTo(Object o) { - if (!(o instanceof IpAddress)) { + if (!(o instanceof Instance)) { Loggers.SRV_LOG.error("[IPADDRESS-COMPARE] Object is not an instance of IPAdress, object: {}", o.getClass()); throw new IllegalArgumentException("Object is not an instance of IPAdress,object: " + o.getClass()); } - IpAddress ipAddress = (IpAddress) o; - String ipKey = ipAddress.toString(); + Instance instance = (Instance) o; + String ipKey = instance.toString(); return this.toString().compareTo(ipKey); } diff --git a/naming/src/main/java/com/alibaba/nacos/naming/core/VirtualClusterDomain.java b/naming/src/main/java/com/alibaba/nacos/naming/core/Service.java similarity index 71% rename from naming/src/main/java/com/alibaba/nacos/naming/core/VirtualClusterDomain.java rename to naming/src/main/java/com/alibaba/nacos/naming/core/Service.java index 7842703dbb4..e64ed6704bf 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/core/VirtualClusterDomain.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/core/Service.java @@ -38,30 +38,31 @@ import java.nio.charset.Charset; import java.security.MessageDigest; import java.util.*; -import java.util.concurrent.ConcurrentHashMap; /** + * Service of Nacos + *

+ * We introduce a 'service --> cluster --> instance' model, so service stores a list of clusters, which contains + * a list of instances. + *

+ * Typically we put some common properties between instances to service level. + * * @author nkorange */ -public class VirtualClusterDomain implements Domain, DataListener { +public class Service extends com.alibaba.nacos.api.naming.pojo.Service implements DataListener> { private static final String DOMAIN_NAME_SYNTAX = "[0-9a-zA-Z\\.:_-]+"; - public static final int MINIMUM_IP_DELETE_TIMEOUT = 60 * 1000; - @JSONField(serialize = false) private ClientBeatProcessor clientBeatProcessor = new ClientBeatProcessor(); @JSONField(serialize = false) private ClientBeatCheckTask clientBeatCheckTask = new ClientBeatCheckTask(this); - private String name; private String token; private List owners = new ArrayList<>(); private Boolean resetWeight = false; - private Boolean enableHealthCheck = true; private Boolean enabled = true; - private Boolean enableClientBeat = false; private Selector selector = new NoneSelector(); private String namespaceId; @@ -72,16 +73,10 @@ public class VirtualClusterDomain implements Domain, DataListener { private volatile long lastModifiedMillis = 0L; - private boolean useSpecifiedURL = false; - - private float protectThreshold = 0.0F; - private volatile String checksum; private Map clusterMap = new HashMap(); - private Map metadata = new ConcurrentHashMap<>(); - @JSONField(serialize = false) public PushService getPushService() { return SpringContext.getAppContext().getBean(PushService.class); @@ -96,19 +91,11 @@ public void setIpDeleteTimeout(long ipDeleteTimeout) { } public void processClientBeat(final RsInfo rsInfo) { - clientBeatProcessor.setDomain(this); + clientBeatProcessor.setService(this); clientBeatProcessor.setRsInfo(rsInfo); HealthCheckReactor.scheduleNow(clientBeatProcessor); } - public Boolean getEnableClientBeat() { - return enableClientBeat; - } - - public void setEnableClientBeat(Boolean enableClientBeat) { - this.enableClientBeat = enableClientBeat; - } - public Boolean getEnabled() { return enabled; } @@ -117,13 +104,6 @@ public void setEnabled(Boolean enabled) { this.enabled = enabled; } - public Boolean getEnableHealthCheck() { - return enableHealthCheck; - } - - public void setEnableHealthCheck(Boolean enableHealthCheck) { - this.enableHealthCheck = enableHealthCheck; - } public long getLastModifiedMillis() { return lastModifiedMillis; @@ -141,14 +121,6 @@ public void setResetWeight(Boolean resetWeight) { this.resetWeight = resetWeight; } - public Map getMetadata() { - return metadata; - } - - public void setMetadata(Map metadata) { - this.metadata = metadata; - } - public Selector getSelector() { return selector; } @@ -159,28 +131,20 @@ public void setSelector(Selector selector) { @Override public boolean interests(String key) { - return StringUtils.equals(key, UtilsAndCommons.IPADDRESS_DATA_ID_PRE + namespaceId + UtilsAndCommons.SERVICE_GROUP_CONNECTOR + name); + return StringUtils.equals(key, UtilsAndCommons.IPADDRESS_DATA_ID_PRE + namespaceId + UtilsAndCommons.SERVICE_GROUP_CONNECTOR + getName()); } @Override public boolean matchUnlistenKey(String key) { - return StringUtils.equals(key, UtilsAndCommons.IPADDRESS_DATA_ID_PRE + namespaceId + UtilsAndCommons.SERVICE_GROUP_CONNECTOR + name); + return StringUtils.equals(key, UtilsAndCommons.IPADDRESS_DATA_ID_PRE + namespaceId + UtilsAndCommons.SERVICE_GROUP_CONNECTOR + getName()); } @Override - public void onChange(String key, Object value) throws Exception { - - if (StringUtils.isEmpty((String) value)) { - Loggers.SRV_LOG.warn("[NACOS-DOM] received empty iplist config for dom: {}", name); - return; - } + public void onChange(String key, List value) throws Exception { Loggers.RAFT.info("[NACOS-RAFT] datum is changed, key: {}, value: {}", key, value); - List ips = JSON.parseObject((String) value, new TypeReference>() { - }); - - for (IpAddress ip : ips) { + for (Instance ip : value) { if (ip.getWeight() > 10000.0D) { ip.setWeight(10000.0D); @@ -191,7 +155,7 @@ public void onChange(String key, Object value) throws Exception { } } - updateIPs(ips); + updateIPs(value); recalculateChecksum(); } @@ -201,18 +165,18 @@ public void onDelete(String key) throws Exception { // ignore } - public void updateIPs(List ips) { + public void updateIPs(List ips) { if (CollectionUtils.isEmpty(ips) && allIPs().size() > 1) { return; } - Map> ipMap = new HashMap>(clusterMap.size()); + Map> ipMap = new HashMap>(clusterMap.size()); for (String clusterName : clusterMap.keySet()) { - ipMap.put(clusterName, new ArrayList()); + ipMap.put(clusterName, new ArrayList()); } - for (IpAddress ip : ips) { + for (Instance ip : ips) { try { if (ip == null) { Loggers.SRV_LOG.error("[NACOS-DOM] received malformed ip: null"); @@ -229,9 +193,9 @@ public void updateIPs(List ips) { continue; } - List clusterIPs = ipMap.get(ip.getClusterName()); + List clusterIPs = ipMap.get(ip.getClusterName()); if (clusterIPs == null) { - clusterIPs = new LinkedList(); + clusterIPs = new LinkedList(); ipMap.put(ip.getClusterName(), clusterIPs); } @@ -241,24 +205,23 @@ public void updateIPs(List ips) { } } - for (Map.Entry> entry : ipMap.entrySet()) { + for (Map.Entry> entry : ipMap.entrySet()) { //make every ip mine - List entryIPs = entry.getValue(); + List entryIPs = entry.getValue(); clusterMap.get(entry.getKey()).updateIPs(entryIPs); } setLastModifiedMillis(System.currentTimeMillis()); - getPushService().domChanged(namespaceId, name); + getPushService().domChanged(namespaceId, getName()); StringBuilder stringBuilder = new StringBuilder(); - for (IpAddress ipAddress : allIPs()) { - stringBuilder.append(ipAddress.toIPAddr()).append("_").append(ipAddress.isValid()).append(","); + for (Instance instance : allIPs()) { + stringBuilder.append(instance.toIPAddr()).append("_").append(instance.isValid()).append(","); } Loggers.EVT_LOG.info("[IP-UPDATED] dom: {}, ips: {}", getName(), stringBuilder.toString()); } - @Override public void init() { HealthCheckReactor.scheduleCheck(clientBeatCheckTask); @@ -268,7 +231,6 @@ public void init() { } } - @Override public void destroy() throws Exception { for (Map.Entry entry : clusterMap.entrySet()) { entry.getValue().destroy(); @@ -276,9 +238,8 @@ public void destroy() throws Exception { HealthCheckReactor.cancelCheck(clientBeatCheckTask); } - @Override - public List allIPs() { - List allIPs = new ArrayList(); + public List allIPs() { + List allIPs = new ArrayList(); for (Map.Entry entry : clusterMap.entrySet()) { allIPs.addAll(entry.getValue().allIPs()); } @@ -286,23 +247,8 @@ public List allIPs() { return allIPs; } - public List allIPs(String tenant, String app) { - - List allIPs = new ArrayList(); - for (Map.Entry entry : clusterMap.entrySet()) { - - if (StringUtils.isEmpty(app)) { - allIPs.addAll(entry.getValue().allIPs(tenant)); - } else { - allIPs.addAll(entry.getValue().allIPs(tenant, app)); - } - } - - return allIPs; - } - - public List allIPs(List clusters) { - List allIPs = new ArrayList(); + public List allIPs(List clusters) { + List allIPs = new ArrayList(); for (String cluster : clusters) { Cluster clusterObj = clusterMap.get(cluster); if (clusterObj == null) { @@ -315,13 +261,12 @@ public List allIPs(List clusters) { return allIPs; } - @Override - public List srvIPs(String clientIP) { + public List srvIPs(String clientIP) { return srvIPs(clientIP, Collections.EMPTY_LIST); } - public List srvIPs(String clientIP, List clusters) { - List ips; + public List srvIPs(String clientIP, List clusters) { + List ips; if (CollectionUtils.isEmpty(clusters)) { clusters = new ArrayList<>(); @@ -330,9 +275,9 @@ public List srvIPs(String clientIP, List clusters) { return allIPs(clusters); } - public static VirtualClusterDomain fromJSON(String json) { + public static Service fromJSON(String json) { try { - VirtualClusterDomain vDom = JSON.parseObject(json, VirtualClusterDomain.class); + Service vDom = JSON.parseObject(json, Service.class); for (Cluster cluster : vDom.clusterMap.values()) { cluster.setDom(vDom); } @@ -344,7 +289,6 @@ public static VirtualClusterDomain fromJSON(String json) { } } - @Override public String toJSON() { return JSON.toJSONString(this); } @@ -352,14 +296,14 @@ public String toJSON() { @JSONField(serialize = false) public String getDomString() { Map domain = new HashMap(10); - VirtualClusterDomain vDom = this; + Service vDom = this; domain.put("name", vDom.getName()); - List ips = vDom.allIPs(); + List ips = vDom.allIPs(); int invalidIPCount = 0; int ipCount = 0; - for (IpAddress ip : ips) { + for (Instance ip : ips) { if (!ip.isValid()) { invalidIPCount++; } @@ -397,44 +341,27 @@ public String getDomString() { return JSON.toJSONString(domain); } - @Override - public String getName() { - return name; - } - @Override public void setName(String name) { if (!name.matches(DOMAIN_NAME_SYNTAX)) { throw new IllegalArgumentException("dom name can only have these characters: 0-9a-zA-Z.:_-; current: " + name); } - this.name = name; + super.setName(name); } - public boolean isUseSpecifiedURL() { - return useSpecifiedURL; - } - - public void setUseSpecifiedURL(boolean isUseSpecifiedURL) { - this.useSpecifiedURL = isUseSpecifiedURL; - } - - @Override public String getToken() { return token; } - @Override public void setToken(String token) { this.token = token; } - @Override public List getOwners() { return owners; } - @Override public void setOwners(List owners) { this.owners = owners; } @@ -455,63 +382,46 @@ public void setNamespaceId(String namespaceId) { this.namespaceId = namespaceId; } - @Override - public void update(Domain dom) { - if (!(dom instanceof VirtualClusterDomain)) { - return; - } + public void update(Service vDom) { - VirtualClusterDomain vDom = (VirtualClusterDomain) dom; if (!StringUtils.equals(token, vDom.getToken())) { - Loggers.SRV_LOG.info("[DOM-UPDATE] dom: {}, token: {} -> {}", name, token, vDom.getToken()); + Loggers.SRV_LOG.info("[DOM-UPDATE] dom: {}, token: {} -> {}", getName(), token, vDom.getToken()); token = vDom.getToken(); } if (!ListUtils.isEqualList(owners, vDom.getOwners())) { - Loggers.SRV_LOG.info("[DOM-UPDATE] dom: {}, owners: {} -> {}", name, owners, vDom.getOwners()); + Loggers.SRV_LOG.info("[DOM-UPDATE] dom: {}, owners: {} -> {}", getName(), owners, vDom.getOwners()); owners = vDom.getOwners(); } - if (protectThreshold != vDom.getProtectThreshold()) { - Loggers.SRV_LOG.info("[DOM-UPDATE] dom: {}, protectThreshold: {} -> {}", name, protectThreshold, vDom.getProtectThreshold()); - protectThreshold = vDom.getProtectThreshold(); - } - - if (useSpecifiedURL != vDom.isUseSpecifiedURL()) { - Loggers.SRV_LOG.info("[DOM-UPDATE] dom: {}, useSpecifiedURL: {} -> {}", name, useSpecifiedURL, vDom.isUseSpecifiedURL()); - useSpecifiedURL = vDom.isUseSpecifiedURL(); + if (getProtectThreshold() != vDom.getProtectThreshold()) { + Loggers.SRV_LOG.info("[DOM-UPDATE] dom: {}, protectThreshold: {} -> {}", getName(), getProtectThreshold(), vDom.getProtectThreshold()); + setProtectThreshold(vDom.getProtectThreshold()); } if (resetWeight != vDom.getResetWeight().booleanValue()) { - Loggers.SRV_LOG.info("[DOM-UPDATE] dom: {}, resetWeight: {} -> {}", name, resetWeight, vDom.getResetWeight()); + Loggers.SRV_LOG.info("[DOM-UPDATE] dom: {}, resetWeight: {} -> {}", getName(), resetWeight, vDom.getResetWeight()); resetWeight = vDom.getResetWeight(); } - if (enableHealthCheck != vDom.getEnableHealthCheck().booleanValue()) { - Loggers.SRV_LOG.info("[DOM-UPDATE] dom: {}, enableHealthCheck: {} -> {}", name, enableHealthCheck, vDom.getEnableHealthCheck()); - enableHealthCheck = vDom.getEnableHealthCheck(); - } - - if (enableClientBeat != vDom.getEnableClientBeat().booleanValue()) { - Loggers.SRV_LOG.info("[DOM-UPDATE] dom: {}, enableClientBeat: {} -> {}", name, enableClientBeat, vDom.getEnableClientBeat()); - enableClientBeat = vDom.getEnableClientBeat(); + if (getHealthCheckMode().equals(vDom.getHealthCheckMode())) { + Loggers.SRV_LOG.info("[DOM-UPDATE] dom: {}, healthCheckMode: {} -> {}", getName(), getHealthCheckMode(), vDom.getHealthCheckMode()); } if (enabled != vDom.getEnabled().booleanValue()) { - Loggers.SRV_LOG.info("[DOM-UPDATE] dom: {}, enabled: {} -> {}", name, enabled, vDom.getEnabled()); + Loggers.SRV_LOG.info("[DOM-UPDATE] dom: {}, enabled: {} -> {}", getName(), enabled, vDom.getEnabled()); enabled = vDom.getEnabled(); } selector = vDom.getSelector(); - metadata = vDom.getMetadata(); + setMetadata(vDom.getMetadata()); updateOrAddCluster(vDom.getClusterMap().values()); remvDeadClusters(this, vDom); recalculateChecksum(); } - @Override public String getChecksum() { if (StringUtils.isEmpty(checksum)) { recalculateChecksum(); @@ -521,7 +431,7 @@ public String getChecksum() { } public synchronized void recalculateChecksum() { - List ips = allIPs(); + List ips = allIPs(); StringBuilder ipsString = new StringBuilder(); ipsString.append(getDomString()); @@ -532,7 +442,7 @@ public synchronized void recalculateChecksum() { Collections.sort(ips); } - for (IpAddress ip : ips) { + for (Instance ip : ips) { String string = ip.getIp() + ":" + ip.getPort() + "_" + ip.getWeight() + "_" + ip.isValid() + "_" + ip.getClusterName(); ipsString.append(string); @@ -568,7 +478,7 @@ private void updateOrAddCluster(Collection clusters) { } } - private void remvDeadClusters(VirtualClusterDomain oldDom, VirtualClusterDomain newDom) { + private void remvDeadClusters(Service oldDom, Service newDom) { Collection oldClusters = oldDom.getClusterMap().values(); Collection newClusters = newDom.getClusterMap().values(); List deadClusters = (List) CollectionUtils.subtract(oldClusters, newClusters); @@ -579,23 +489,13 @@ private void remvDeadClusters(VirtualClusterDomain oldDom, VirtualClusterDomain } } - @Override - public float getProtectThreshold() { - return protectThreshold; - } - - @Override - public void setProtectThreshold(float protectThreshold) { - this.protectThreshold = protectThreshold; - } - public void addCluster(Cluster cluster) { clusterMap.put(cluster.getName(), cluster); } public void valid() { - if (!name.matches(DOMAIN_NAME_SYNTAX)) { - throw new IllegalArgumentException("dom name can only have these characters: 0-9a-zA-Z-._:, current: " + name); + if (!getName().matches(DOMAIN_NAME_SYNTAX)) { + throw new IllegalArgumentException("dom name can only have these characters: 0-9a-zA-Z-._:, current: " + getName()); } Map> map = new HashMap<>(clusterMap.size()); @@ -610,7 +510,7 @@ public void valid() { } list.add(cluster.getName()); - cluster.valid(); + cluster.validate(); } for (Map.Entry> entry : map.entrySet()) { diff --git a/naming/src/main/java/com/alibaba/nacos/naming/core/ServiceManager.java b/naming/src/main/java/com/alibaba/nacos/naming/core/ServiceManager.java index 4a6da9f479a..a5d309e67d5 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/core/ServiceManager.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/core/ServiceManager.java @@ -25,7 +25,7 @@ import com.alibaba.nacos.naming.consistency.ConsistencyService; import com.alibaba.nacos.naming.consistency.DataListener; import com.alibaba.nacos.naming.consistency.Datum; -import com.alibaba.nacos.api.common.Constants; +import com.alibaba.nacos.naming.consistency.KeyBuilder; import com.alibaba.nacos.naming.misc.*; import com.alibaba.nacos.naming.push.PushService; import org.apache.commons.lang3.ArrayUtils; @@ -47,12 +47,12 @@ */ @Component @DependsOn("nacosApplicationContext") -public class ServiceManager implements DataListener { +public class ServiceManager implements DataListener { /** * Map> */ - private Map> serviceMap = new ConcurrentHashMap<>(); + private Map> serviceMap = new ConcurrentHashMap<>(); private LinkedBlockingDeque toBeUpdatedDomsQueue = new LinkedBlockingDeque<>(1024 * 1024); @@ -113,7 +113,7 @@ public void init() { } } - public Map chooseDomMap(String namespaceId) { + public Map chooseDomMap(String namespaceId) { return serviceMap.get(namespaceId); } @@ -141,37 +141,32 @@ public boolean matchUnlistenKey(String key) { } @Override - public void onChange(String key, Object value) throws Exception { + public void onChange(String key, Service service) throws Exception { try { - if (StringUtils.isEmpty((String)value)) { + if (service == null) { Loggers.SRV_LOG.warn("received empty push from raft, key: {}", key); return; } - VirtualClusterDomain dom = VirtualClusterDomain.fromJSON((String)value); - if (dom == null) { - throw new IllegalStateException("dom parsing failed, json: " + value); + if (StringUtils.isBlank(service.getNamespaceId())) { + service.setNamespaceId(UtilsAndCommons.getDefaultNamespaceId()); } - if (StringUtils.isBlank(dom.getNamespaceId())) { - dom.setNamespaceId(UtilsAndCommons.getDefaultNamespaceId()); - } - - Loggers.RAFT.info("[RAFT-NOTIFIER] datum is changed, key: {}, value: {}", key, value); + Loggers.RAFT.info("[RAFT-NOTIFIER] datum is changed, key: {}, value: {}", key, service); - Domain oldDom = getService(dom.getNamespaceId(), dom.getName()); + Service oldDom = getService(service.getNamespaceId(), service.getName()); if (oldDom != null) { - oldDom.update(dom); + oldDom.update(service); } else { - addLockIfAbsent(UtilsAndCommons.assembleFullServiceName(dom.getNamespaceId(), dom.getName())); - putDomain(dom); - dom.init(); - consistencyService.listen(UtilsAndCommons.getIPListStoreKey(dom), dom); - Loggers.SRV_LOG.info("[NEW-DOM-RAFT] {}", dom.toJSON()); + addLockIfAbsent(UtilsAndCommons.assembleFullServiceName(service.getNamespaceId(), service.getName())); + putDomain(service); + service.init(); + consistencyService.listen(UtilsAndCommons.getIPListStoreKey(service), service); + Loggers.SRV_LOG.info("[NEW-DOM-RAFT] {}", service.toJSON()); } - wakeUp(UtilsAndCommons.assembleFullServiceName(dom.getNamespaceId(), dom.getName())); + wakeUp(UtilsAndCommons.assembleFullServiceName(service.getNamespaceId(), service.getName())); } catch (Throwable e) { Loggers.SRV_LOG.error("[NACOS-DOM] error while processing dom update", e); @@ -183,7 +178,7 @@ public void onDelete(String key) throws Exception { String domKey = StringUtils.removeStart(key, UtilsAndCommons.DOMAINS_DATA_ID_PRE); String namespace = domKey.split(UtilsAndCommons.SERVICE_GROUP_CONNECTOR)[0]; String name = domKey.split(UtilsAndCommons.SERVICE_GROUP_CONNECTOR)[1]; - VirtualClusterDomain dom = chooseDomMap(namespace).remove(name); + Service dom = chooseDomMap(namespace).remove(name); Loggers.RAFT.info("[RAFT-NOTIFIER] datum is deleted, key: {}", key); if (dom != null) { @@ -263,32 +258,32 @@ public void updatedDom2(String namespaceId, String domName, String serverIP) { ipsMap.put(strings[0], strings[1]); } - VirtualClusterDomain raftVirtualClusterDomain = (VirtualClusterDomain) getService(namespaceId, domName); + Service raftService = (Service) getService(namespaceId, domName); - if (raftVirtualClusterDomain == null) { + if (raftService == null) { return; } - List ipAddresses = raftVirtualClusterDomain.allIPs(); - for (IpAddress ipAddress : ipAddresses) { + List instances = raftService.allIPs(); + for (Instance instance : instances) { - Boolean valid = Boolean.parseBoolean(ipsMap.get(ipAddress.toIPAddr())); - if (valid != ipAddress.isValid()) { - ipAddress.setValid(valid); + Boolean valid = Boolean.parseBoolean(ipsMap.get(instance.toIPAddr())); + if (valid != instance.isValid()) { + instance.setValid(valid); Loggers.EVT_LOG.info("{} {SYNC} IP-{} : {}@{}", - domName, (ipAddress.isValid() ? "ENABLED" : "DISABLED"), - ipAddress.getIp(), ipAddress.getPort(), ipAddress.getClusterName()); + domName, (instance.isValid() ? "ENABLED" : "DISABLED"), + instance.getIp(), instance.getPort(), instance.getClusterName()); } } - pushService.domChanged(raftVirtualClusterDomain.getNamespaceId(), raftVirtualClusterDomain.getName()); + pushService.domChanged(raftService.getNamespaceId(), raftService.getName()); StringBuilder stringBuilder = new StringBuilder(); - List allIps = raftVirtualClusterDomain.allIPs(); - for (IpAddress ipAddress : allIps) { - stringBuilder.append(ipAddress.toIPAddr()).append("_").append(ipAddress.isValid()).append(","); + List allIps = raftService.allIPs(); + for (Instance instance : allIps) { + stringBuilder.append(instance.toIPAddr()).append("_").append(instance.isValid()).append(","); } - Loggers.EVT_LOG.info("[IP-UPDATED] dom: {}, ips: {}", raftVirtualClusterDomain.getName(), stringBuilder.toString()); + Loggers.EVT_LOG.info("[IP-UPDATED] dom: {}, ips: {}", raftService.getName(), stringBuilder.toString()); } @@ -312,12 +307,12 @@ public List getAllDomNamesList(String namespaceId) { return new ArrayList<>(chooseDomMap(namespaceId).keySet()); } - public Map> getResponsibleDoms() { - Map> result = new HashMap<>(16); + public Map> getResponsibleDoms() { + Map> result = new HashMap<>(16); for (String namespaceId : serviceMap.keySet()) { result.put(namespaceId, new HashSet<>()); - for (Map.Entry entry : serviceMap.get(namespaceId).entrySet()) { - Domain domain = entry.getValue(); + for (Map.Entry entry : serviceMap.get(namespaceId).entrySet()) { + Service domain = entry.getValue(); if (distroMapper.responsible(entry.getKey())) { result.get(namespaceId).add(domain); } @@ -329,7 +324,7 @@ public Map> getResponsibleDoms() { public int getResponsibleDomCount() { int domCount = 0; for (String namespaceId : serviceMap.keySet()) { - for (Map.Entry entry : serviceMap.get(namespaceId).entrySet()) { + for (Map.Entry entry : serviceMap.get(namespaceId).entrySet()) { if (distroMapper.responsible(entry.getKey())) { domCount++; } @@ -339,10 +334,10 @@ public int getResponsibleDomCount() { } public int getResponsibleIPCount() { - Map> responsibleDoms = getResponsibleDoms(); + Map> responsibleDoms = getResponsibleDoms(); int count = 0; for (String namespaceId : responsibleDoms.keySet()) { - for (Domain domain : responsibleDoms.get(namespaceId)) { + for (Service domain : responsibleDoms.get(namespaceId)) { count += domain.allIPs().size(); } } @@ -351,33 +346,33 @@ public int getResponsibleIPCount() { } public void easyRemoveDom(String namespaceId, String serviceName) throws Exception { - Domain dom = getService(namespaceId, serviceName); + Service dom = getService(namespaceId, serviceName); consistencyService.remove(UtilsAndCommons.getDomStoreKey(dom)); } - public void addOrReplaceService(VirtualClusterDomain newDom) throws Exception { - consistencyService.put(UtilsAndCommons.getDomStoreKey(newDom), JSON.toJSONString(newDom)); + public void addOrReplaceService(Service newDom) throws Exception { + consistencyService.put(UtilsAndCommons.getDomStoreKey(newDom), JSON.toJSONString(newDom), String.class); } /** * Register an instance to a service. *

- * This method create service or cluster silently if they don't exist. + * This method creates service or cluster silently if they don't exist. * * @param namespaceId id of namespace * @param serviceName service name * @param instance instance to register * @throws Exception any error occurred in the process */ - public void registerInstance(String namespaceId, String serviceName, String clusterName, IpAddress instance) throws Exception { + public void registerInstance(String namespaceId, String serviceName, String clusterName, Instance instance) throws Exception { - VirtualClusterDomain service = getService(namespaceId, serviceName); + Service service = getService(namespaceId, serviceName); boolean serviceUpdated = false; if (service == null) { - service = new VirtualClusterDomain(); + service = new Service(); service.setName(serviceName); service.setNamespaceId(namespaceId); - // now valid the dom. if failed, exception will be thrown + // now validate the dom. if failed, exception will be thrown service.setLastModifiedMillis(System.currentTimeMillis()); service.recalculateChecksum(); service.valid(); @@ -416,37 +411,46 @@ public void registerInstance(String namespaceId, String serviceName, String clus lock.unlock(); } } - addInstance(namespaceId, serviceName, clusterName, instance); + + if (service.allIPs().contains(instance)) { + throw new NacosException(NacosException.INVALID_PARAM, "instance already exist: " + instance); + } + + addInstance(namespaceId, serviceName, clusterName, instance.isEphemeral(), instance); } - public void addInstance(String namespaceId, String serviceName, String clusterName, IpAddress... ips) throws NacosException { + public void addInstance(String namespaceId, String serviceName, String clusterName, boolean ephemeral, Instance... ips) throws NacosException { String key = UtilsAndCommons.getIPListStoreKey(getService(namespaceId, serviceName)); - VirtualClusterDomain dom = getService(namespaceId, serviceName); + key = KeyBuilder.buildInstanceListKey(namespaceId, serviceName, ephemeral); - Map ipAddressMap = addIpAddresses(dom, ips); + Service dom = getService(namespaceId, serviceName); + + Map ipAddressMap = addIpAddresses(dom, ephemeral, ips); String value = JSON.toJSONString(ipAddressMap.values()); - consistencyService.put(key, value); + consistencyService.put(key, value, String.class); } - public void removeInstance(String namespaceId, String serviceName, IpAddress... ips) throws NacosException { + public void removeInstance(String namespaceId, String serviceName, boolean ephemeral, Instance... ips) throws NacosException { String key = UtilsAndCommons.getIPListStoreKey(getService(namespaceId, serviceName)); - VirtualClusterDomain dom = getService(namespaceId, serviceName); + key = KeyBuilder.buildInstanceListKey(namespaceId, serviceName, ephemeral); + + Service dom = getService(namespaceId, serviceName); - Map ipAddressMap = substractIpAddresses(dom, ips); + Map ipAddressMap = substractIpAddresses(dom, ephemeral, ips); String value = JSON.toJSONString(ipAddressMap.values()); - consistencyService.put(key, value); + consistencyService.put(key, value, String.class); } - public IpAddress getInstance(String namespaceId, String serviceName, String cluster, String ip, int port) { - VirtualClusterDomain service = (VirtualClusterDomain) getService(namespaceId, serviceName); + public Instance getInstance(String namespaceId, String serviceName, String cluster, String ip, int port) { + Service service = getService(namespaceId, serviceName); if (service == null) { return null; } @@ -454,23 +458,26 @@ public IpAddress getInstance(String namespaceId, String serviceName, String clus List clusters = new ArrayList<>(); clusters.add(cluster); - List ips = service.allIPs(clusters); + List ips = service.allIPs(clusters); if (ips == null || ips.isEmpty()) { throw new IllegalStateException("no ips found for cluster " + cluster + " in dom " + serviceName); } - for (IpAddress ipAddress : ips) { - if (ipAddress.getIp().equals(ip) && ipAddress.getPort() == port) { - return ipAddress; + for (Instance instance : ips) { + if (instance.getIp().equals(ip) && instance.getPort() == port) { + return instance; } } return null; } - public Map updateIpAddresses(VirtualClusterDomain dom, String action, IpAddress... ips) throws NacosException { + public Map updateIpAddresses(Service dom, String action, boolean ephemeral, Instance... ips) throws NacosException { + + + Datum datum1 = consistencyService.get(KeyBuilder.buildInstanceListKey(dom.getNamespaceId(), dom.getName(), ephemeral), + String.class); - Datum datum1 = (Datum) consistencyService.get(UtilsAndCommons.getIPListStoreKey(dom)); String oldJson = StringUtils.EMPTY; // TODO support ephemeral instances: @@ -478,88 +485,88 @@ public Map updateIpAddresses(VirtualClusterDomain dom, String oldJson = (String) datum1.value; } - List ipAddresses; - List currentIPs = dom.allIPs(); - Map map = new ConcurrentHashMap(currentIPs.size()); + List instances; + List currentIPs = dom.allIPs(); + Map map = new ConcurrentHashMap<>(currentIPs.size()); - for (IpAddress ipAddress : currentIPs) { - map.put(ipAddress.toIPAddr(), ipAddress); + for (Instance instance : currentIPs) { + map.put(instance.toIPAddr(), instance); } - ipAddresses = setValid(oldJson, map); + instances = setValid(oldJson, map); - Map ipAddressMap = new HashMap(ipAddresses.size()); + Map instanceMap = new HashMap<>(instances.size()); - for (IpAddress ipAddress : ipAddresses) { - ipAddressMap.put(ipAddress.getDatumKey(), ipAddress); + for (Instance instance : instances) { + instanceMap.put(instance.getDatumKey(), instance); } - for (IpAddress ipAddress : ips) { - if (!dom.getClusterMap().containsKey(ipAddress.getClusterName())) { - Cluster cluster = new Cluster(ipAddress.getClusterName()); + for (Instance instance : ips) { + if (!dom.getClusterMap().containsKey(instance.getClusterName())) { + Cluster cluster = new Cluster(instance.getClusterName()); cluster.setDom(dom); - dom.getClusterMap().put(ipAddress.getClusterName(), cluster); + dom.getClusterMap().put(instance.getClusterName(), cluster); Loggers.SRV_LOG.warn("cluster: {} not found, ip: {}, will create new cluster with default configuration.", - ipAddress.getClusterName(), ipAddress.toJSON()); + instance.getClusterName(), instance.toJSON()); } if (UtilsAndCommons.UPDATE_INSTANCE_ACTION_REMOVE.equals(action)) { - ipAddressMap.remove(ipAddress.getDatumKey()); + instanceMap.remove(instance.getDatumKey()); } else { - ipAddressMap.put(ipAddress.getDatumKey(), ipAddress); + instanceMap.put(instance.getDatumKey(), instance); } } - if (ipAddressMap.size() <= 0 && UtilsAndCommons.UPDATE_INSTANCE_ACTION_ADD.equals(action)) { + if (instanceMap.size() <= 0 && UtilsAndCommons.UPDATE_INSTANCE_ACTION_ADD.equals(action)) { throw new IllegalArgumentException("ip list can not be empty, dom: " + dom.getName() + ", ip list: " - + JSON.toJSONString(ipAddressMap.values())); + + JSON.toJSONString(instanceMap.values())); } - return ipAddressMap; + return instanceMap; } - public Map substractIpAddresses(VirtualClusterDomain dom, IpAddress... ips) throws NacosException { - return updateIpAddresses(dom, UtilsAndCommons.UPDATE_INSTANCE_ACTION_REMOVE, ips); + public Map substractIpAddresses(Service dom, boolean ephemeral, Instance... ips) throws NacosException { + return updateIpAddresses(dom, UtilsAndCommons.UPDATE_INSTANCE_ACTION_REMOVE, ephemeral, ips); } - public Map addIpAddresses(VirtualClusterDomain dom, IpAddress... ips) throws NacosException { - return updateIpAddresses(dom, UtilsAndCommons.UPDATE_INSTANCE_ACTION_ADD, ips); + public Map addIpAddresses(Service dom, boolean ephemeral, Instance... ips) throws NacosException { + return updateIpAddresses(dom, UtilsAndCommons.UPDATE_INSTANCE_ACTION_ADD, ephemeral, ips); } - private List setValid(String oldJson, Map map) { - List ipAddresses = new ArrayList<>(); + private List setValid(String oldJson, Map map) { + List instances = new ArrayList<>(); if (StringUtils.isNotEmpty(oldJson)) { try { - ipAddresses = JSON.parseObject(oldJson, new TypeReference>() { + instances = JSON.parseObject(oldJson, new TypeReference>() { }); - for (IpAddress ipAddress : ipAddresses) { - IpAddress ipAddress1 = map.get(ipAddress.toIPAddr()); - if (ipAddress1 != null) { - ipAddress.setValid(ipAddress1.isValid()); - ipAddress.setLastBeat(ipAddress1.getLastBeat()); + for (Instance instance : instances) { + Instance instance1 = map.get(instance.toIPAddr()); + if (instance1 != null) { + instance.setValid(instance1.isValid()); + instance.setLastBeat(instance1.getLastBeat()); } } } catch (Throwable throwable) { Loggers.RAFT.error("error while processing json: " + oldJson, throwable); } finally { - if (ipAddresses == null) { - ipAddresses = new ArrayList<>(); + if (instances == null) { + instances = new ArrayList<>(); } } } - return ipAddresses; + return instances; } - public VirtualClusterDomain getService(String namespaceId, String domName) { + public Service getService(String namespaceId, String domName) { if (serviceMap.get(namespaceId) == null) { return null; } return chooseDomMap(namespaceId).get(domName); } - public void putDomain(VirtualClusterDomain domain) { + public void putDomain(Service domain) { if (!serviceMap.containsKey(domain.getNamespaceId())) { serviceMap.put(domain.getNamespaceId(), new ConcurrentHashMap<>(16)); } @@ -567,10 +574,10 @@ public void putDomain(VirtualClusterDomain domain) { } - public List searchDomains(String namespaceId, String regex) { - List result = new ArrayList<>(); - for (Map.Entry entry : chooseDomMap(namespaceId).entrySet()) { - VirtualClusterDomain dom = entry.getValue(); + public List searchDomains(String namespaceId, String regex) { + List result = new ArrayList<>(); + for (Map.Entry entry : chooseDomMap(namespaceId).entrySet()) { + Service dom = entry.getValue(); String key = dom.getName() + ":" + ArrayUtils.toString(dom.getOwners()); if (key.matches(regex)) { result.add(dom); @@ -591,20 +598,20 @@ public int getDomCount() { public int getInstanceCount() { int total = 0; for (String namespaceId : serviceMap.keySet()) { - for (Domain domain : serviceMap.get(namespaceId).values()) { + for (Service domain : serviceMap.get(namespaceId).values()) { total += domain.allIPs().size(); } } return total; } - public Map getDomMap(String namespaceId) { + public Map getDomMap(String namespaceId) { return serviceMap.get(namespaceId); } - public int getPagedDom(String namespaceId, int startPage, int pageSize, String keyword, List domainList) { + public int getPagedDom(String namespaceId, int startPage, int pageSize, String keyword, List domainList) { - List matchList; + List matchList; if (chooseDomMap(namespaceId) == null) { return 0; @@ -613,7 +620,7 @@ public int getPagedDom(String namespaceId, int startPage, int pageSize, String k if (StringUtils.isNotBlank(keyword)) { matchList = searchDomains(namespaceId, ".*" + keyword + ".*"); } else { - matchList = new ArrayList(chooseDomMap(namespaceId).values()); + matchList = new ArrayList(chooseDomMap(namespaceId).values()); } if (pageSize >= matchList.size()) { @@ -682,7 +689,7 @@ public void run() { continue; } - Domain domain = getService(namespaceId, domName); + Service domain = getService(namespaceId, domName); if (domain == null) { continue; diff --git a/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/ClientBeatCheckTask.java b/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/ClientBeatCheckTask.java index 24d4623cc2d..728e077ba29 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/ClientBeatCheckTask.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/ClientBeatCheckTask.java @@ -20,8 +20,8 @@ import com.alibaba.nacos.naming.boot.RunningConfig; import com.alibaba.nacos.naming.boot.SpringContext; import com.alibaba.nacos.naming.core.DistroMapper; -import com.alibaba.nacos.naming.core.IpAddress; -import com.alibaba.nacos.naming.core.VirtualClusterDomain; +import com.alibaba.nacos.naming.core.Instance; +import com.alibaba.nacos.naming.core.Service; import com.alibaba.nacos.naming.misc.HttpClient; import com.alibaba.nacos.naming.misc.Loggers; import com.alibaba.nacos.naming.misc.NamingProxy; @@ -36,9 +36,9 @@ */ public class ClientBeatCheckTask implements Runnable { - private VirtualClusterDomain domain; + private Service domain; - public ClientBeatCheckTask(VirtualClusterDomain domain) { + public ClientBeatCheckTask(Service domain) { this.domain = domain; } @@ -60,29 +60,30 @@ public String taskKey() { @Override public void run() { try { - if (!domain.getEnableClientBeat() || !getDistroMapper().responsible(domain.getName())) { + if (!domain.getHealthCheckMode().equals(HealthCheckMode.client.name()) || + !getDistroMapper().responsible(domain.getName())) { return; } - List ipAddresses = domain.allIPs(); + List instances = domain.allIPs(); - for (IpAddress ipAddress : ipAddresses) { - if (System.currentTimeMillis() - ipAddress.getLastBeat() > ClientBeatProcessor.CLIENT_BEAT_TIMEOUT) { - if (!ipAddress.isMarked()) { - if (ipAddress.isValid()) { - ipAddress.setValid(false); + for (Instance instance : instances) { + if (System.currentTimeMillis() - instance.getLastBeat() > ClientBeatProcessor.CLIENT_BEAT_TIMEOUT) { + if (!instance.isMarked()) { + if (instance.isValid()) { + instance.setValid(false); Loggers.EVT_LOG.info("{POS} {IP-DISABLED} valid: {}:{}@{}, region: {}, msg: client timeout after {}, last beat: {}", - ipAddress.getIp(), ipAddress.getPort(), ipAddress.getClusterName(), - UtilsAndCommons.LOCALHOST_SITE, ClientBeatProcessor.CLIENT_BEAT_TIMEOUT, ipAddress.getLastBeat()); + instance.getIp(), instance.getPort(), instance.getClusterName(), + UtilsAndCommons.LOCALHOST_SITE, ClientBeatProcessor.CLIENT_BEAT_TIMEOUT, instance.getLastBeat()); getPushService().domChanged(domain.getNamespaceId(), domain.getName()); } } } - if (System.currentTimeMillis() - ipAddress.getLastBeat() > domain.getIpDeleteTimeout()) { + if (System.currentTimeMillis() - instance.getLastBeat() > domain.getIpDeleteTimeout()) { // delete ip - Loggers.SRV_LOG.info("[AUTO-DELETE-IP] dom: {}, ip: {}", domain.getName(), JSON.toJSONString(ipAddress)); - deleteIP(ipAddress); + Loggers.SRV_LOG.info("[AUTO-DELETE-IP] dom: {}, ip: {}", domain.getName(), JSON.toJSONString(instance)); + deleteIP(instance); } } } catch (Exception e) { @@ -91,15 +92,15 @@ public void run() { } - private void deleteIP(IpAddress ipAddress) { + private void deleteIP(Instance instance) { try { - String ipList = ipAddress.getIp() + ":" + ipAddress.getPort() + "_" - + ipAddress.getWeight() + "_" + ipAddress.getClusterName(); + String ipList = instance.getIp() + ":" + instance.getPort() + "_" + + instance.getWeight() + "_" + instance.getClusterName(); NamingProxy.Request request = NamingProxy.Request.newRequest(); - request.appendParam("ip", ipAddress.getIp()) - .appendParam("port", String.valueOf(ipAddress.getPort())) - .appendParam("clusterName", ipAddress.getClusterName()) + request.appendParam("ip", instance.getIp()) + .appendParam("port", String.valueOf(instance.getPort())) + .appendParam("clusterName", instance.getClusterName()) .appendParam("serviceName", domain.getName()) .appendParam("namespaceId", domain.getNamespaceId()); @@ -108,10 +109,10 @@ private void deleteIP(IpAddress ipAddress) { HttpClient.HttpResult result = HttpClient.httpGet(url, null, null); if (result.code != HttpURLConnection.HTTP_OK) { Loggers.SRV_LOG.error("[IP-DEAD] failed to delete ip automatically, ip: {}, caused {}, resp code: {}", - ipAddress.toJSON(), result.content, result.code); + instance.toJSON(), result.content, result.code); } } catch (Exception e) { - Loggers.SRV_LOG.error("[IP-DEAD] failed to delete ip automatically, ip: {}, error: {}", ipAddress.toJSON(), e); + Loggers.SRV_LOG.error("[IP-DEAD] failed to delete ip automatically, ip: {}, error: {}", instance.toJSON(), e); } } diff --git a/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/ClientBeatProcessor.java b/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/ClientBeatProcessor.java index 0251791c57a..d7964028916 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/ClientBeatProcessor.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/ClientBeatProcessor.java @@ -32,7 +32,7 @@ public class ClientBeatProcessor implements Runnable { public static final long CLIENT_BEAT_TIMEOUT = TimeUnit.SECONDS.toMillis(15); private RsInfo rsInfo; - private Domain domain; + private Service service; @JSONField(serialize = false) public PushService getPushService() { @@ -47,12 +47,12 @@ public void setRsInfo(RsInfo rsInfo) { this.rsInfo = rsInfo; } - public Domain getDomain() { - return domain; + public Service getService() { + return service; } - public void setDomain(Domain domain) { - this.domain = domain; + public void setService(Service service) { + this.service = service; } public String getType() { @@ -60,8 +60,8 @@ public String getType() { } public void process() { - VirtualClusterDomain virtualClusterDomain = (VirtualClusterDomain) domain; - if (!virtualClusterDomain.getEnableClientBeat()) { + Service service = this.service; + if (!service.getHealthCheckMode().equals(HealthCheckMode.client.name())) { return; } @@ -70,19 +70,19 @@ public void process() { String ip = rsInfo.getIp(); String clusterName = rsInfo.getCluster(); int port = rsInfo.getPort(); - Cluster cluster = virtualClusterDomain.getClusterMap().get(clusterName); - List ipAddresses = cluster.allIPs(); + Cluster cluster = service.getClusterMap().get(clusterName); + List instances = cluster.allIPs(); - for (IpAddress ipAddress: ipAddresses) { - if (ipAddress.getIp().equals(ip) && ipAddress.getPort() == port) { + for (Instance instance : instances) { + if (instance.getIp().equals(ip) && instance.getPort() == port) { Loggers.EVT_LOG.debug("[CLIENT-BEAT] refresh beat: {}", rsInfo.toString()); - ipAddress.setLastBeat(System.currentTimeMillis()); - if (!ipAddress.isMarked()) { - if (!ipAddress.isValid()) { - ipAddress.setValid(true); + instance.setLastBeat(System.currentTimeMillis()); + if (!instance.isMarked()) { + if (!instance.isValid()) { + instance.setValid(true); Loggers.EVT_LOG.info("dom: {} {POS} {IP-ENABLED} valid: {}:{}@{}, region: {}, msg: client beat ok", cluster.getDom().getName(), ip, port, cluster.getName(), UtilsAndCommons.LOCALHOST_SITE); - getPushService().domChanged(virtualClusterDomain.getNamespaceId(), domain.getName()); + getPushService().domChanged(service.getNamespaceId(), this.service.getName()); } } } diff --git a/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/HealthCheckCommon.java b/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/HealthCheckCommon.java index 875dbf62b61..79081083d03 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/HealthCheckCommon.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/HealthCheckCommon.java @@ -21,8 +21,8 @@ import com.alibaba.nacos.naming.cluster.members.Member; import com.alibaba.nacos.naming.core.Cluster; import com.alibaba.nacos.naming.core.DistroMapper; -import com.alibaba.nacos.naming.core.IpAddress; -import com.alibaba.nacos.naming.core.VirtualClusterDomain; +import com.alibaba.nacos.naming.core.Instance; +import com.alibaba.nacos.naming.core.Service; import com.alibaba.nacos.naming.misc.*; import com.alibaba.nacos.naming.push.PushService; import org.springframework.beans.factory.annotation.Autowired; @@ -108,12 +108,8 @@ public void run() { }, 500, TimeUnit.MILLISECONDS); } - public boolean isHealthCheckEnabled(VirtualClusterDomain virtualClusterDomain) { - if (virtualClusterDomain.getEnableClientBeat()) { - return false; - } - - return virtualClusterDomain.getEnableHealthCheck(); + public boolean isHealthCheckEnabled(Service service) { + return service.getHealthCheckMode().equals(HealthCheckMode.server.name()); } public void reEvaluateCheckRT(long checkRT, HealthCheckTask task, SwitchDomain.HealthParams params) { @@ -140,7 +136,7 @@ public void reEvaluateCheckRT(long checkRT, HealthCheckTask task, SwitchDomain.H task.setCheckRTNormalized(checkRT); } - public void checkOK(IpAddress ip, HealthCheckTask task, String msg) { + public void checkOK(Instance ip, HealthCheckTask task, String msg) { Cluster cluster = task.getCluster(); try { @@ -150,7 +146,7 @@ public void checkOK(IpAddress ip, HealthCheckTask task, String msg) { ip.setValid(true); ip.setMockValid(true); - VirtualClusterDomain vDom = (VirtualClusterDomain) cluster.getDom(); + Service vDom = (Service) cluster.getDom(); vDom.setLastModifiedMillis(System.currentTimeMillis()); pushService.domChanged(vDom.getNamespaceId(), vDom.getName()); @@ -178,7 +174,7 @@ public void checkOK(IpAddress ip, HealthCheckTask task, String msg) { ip.setBeingChecked(false); } - public void checkFail(IpAddress ip, HealthCheckTask task, String msg) { + public void checkFail(Instance ip, HealthCheckTask task, String msg) { Cluster cluster = task.getCluster(); try { @@ -188,7 +184,7 @@ public void checkFail(IpAddress ip, HealthCheckTask task, String msg) { ip.setValid(false); ip.setMockValid(false); - VirtualClusterDomain vDom = (VirtualClusterDomain) cluster.getDom(); + Service vDom = (Service) cluster.getDom(); vDom.setLastModifiedMillis(System.currentTimeMillis()); addResult(new HealthCheckResult(vDom.getName(), ip)); @@ -215,7 +211,7 @@ public void checkFail(IpAddress ip, HealthCheckTask task, String msg) { ip.setBeingChecked(false); } - public void checkFailNow(IpAddress ip, HealthCheckTask task, String msg) { + public void checkFailNow(Instance ip, HealthCheckTask task, String msg) { Cluster cluster = task.getCluster(); try { if (ip.isValid() || ip.isMockValid()) { @@ -223,7 +219,7 @@ public void checkFailNow(IpAddress ip, HealthCheckTask task, String msg) { ip.setValid(false); ip.setMockValid(false); - VirtualClusterDomain vDom = (VirtualClusterDomain) cluster.getDom(); + Service vDom = (Service) cluster.getDom(); vDom.setLastModifiedMillis(System.currentTimeMillis()); pushService.domChanged(vDom.getNamespaceId(), vDom.getName()); @@ -261,11 +257,11 @@ private void addResult(HealthCheckResult result) { static class HealthCheckResult { private String dom; - private IpAddress ipAddress; + private Instance instance; - public HealthCheckResult(String dom, IpAddress ipAddress) { + public HealthCheckResult(String dom, Instance instance) { this.dom = dom; - this.ipAddress = ipAddress; + this.instance = instance; } public String getDom() { @@ -276,12 +272,12 @@ public void setDom(String dom) { this.dom = dom; } - public IpAddress getIpAddress() { - return ipAddress; + public Instance getInstance() { + return instance; } - public void setIpAddress(IpAddress ipAddress) { - this.ipAddress = ipAddress; + public void setInstance(Instance instance) { + this.instance = instance; } } } diff --git a/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/HealthCheckStatus.java b/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/HealthCheckStatus.java index ee05688fb4f..6f9f0447bf8 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/HealthCheckStatus.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/HealthCheckStatus.java @@ -16,7 +16,7 @@ package com.alibaba.nacos.naming.healthcheck; -import com.alibaba.nacos.naming.core.IpAddress; +import com.alibaba.nacos.naming.core.Instance; import com.alibaba.nacos.naming.misc.Loggers; import java.util.concurrent.ConcurrentHashMap; @@ -36,11 +36,11 @@ public class HealthCheckStatus { private static ConcurrentMap statusMap = new ConcurrentHashMap(); - public static void reset(IpAddress ip) { + public static void reset(Instance ip) { statusMap.put(buildKey(ip), new HealthCheckStatus()); } - public static HealthCheckStatus get(IpAddress ip) { + public static HealthCheckStatus get(Instance ip) { String key = buildKey(ip); if (!statusMap.containsKey(key)) { @@ -50,11 +50,11 @@ public static HealthCheckStatus get(IpAddress ip) { return statusMap.get(key); } - public static void remv(IpAddress ip) { + public static void remv(Instance ip) { statusMap.remove(buildKey(ip)); } - private static String buildKey(IpAddress ip) { + private static String buildKey(Instance ip) { try { String clusterName = ip.getClusterName(); diff --git a/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/HealthCheckTask.java b/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/HealthCheckTask.java index faa5a8bd521..6cd24e105b5 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/HealthCheckTask.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/HealthCheckTask.java @@ -19,14 +19,11 @@ import com.alibaba.nacos.naming.boot.SpringContext; import com.alibaba.nacos.naming.core.Cluster; import com.alibaba.nacos.naming.core.DistroMapper; -import com.alibaba.nacos.naming.core.VirtualClusterDomain; +import com.alibaba.nacos.naming.core.Service; import com.alibaba.nacos.naming.misc.Loggers; import com.alibaba.nacos.naming.misc.SwitchDomain; -import com.alibaba.nacos.naming.push.PushService; import org.apache.commons.lang3.RandomUtils; -import java.util.Random; - /** * @author nacos */ @@ -95,7 +92,7 @@ public void run() { this.setCheckRTLastLast(this.getCheckRTLast()); Cluster cluster = this.getCluster(); - if (((VirtualClusterDomain) cluster.getDom()).getEnableHealthCheck()) { + if ((cluster.getDom()).getHealthCheckMode().equals(HealthCheckMode.server.name())) { Loggers.CHECK_RT.info("{}:{}@{}->normalized: {}, worst: {}, best: {}, last: {}, diff: {}", cluster.getDom().getName(), cluster.getName(), cluster.getHealthChecker().getType(), this.getCheckRTNormalized(), this.getCheckRTWorst(), this.getCheckRTBest(), diff --git a/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/HttpHealthCheckProcessor.java b/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/HttpHealthCheckProcessor.java index 8ca504d58fc..8b42ef3dcd4 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/HttpHealthCheckProcessor.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/HttpHealthCheckProcessor.java @@ -17,8 +17,8 @@ import com.alibaba.nacos.api.naming.pojo.AbstractHealthChecker; import com.alibaba.nacos.naming.core.Cluster; -import com.alibaba.nacos.naming.core.IpAddress; -import com.alibaba.nacos.naming.core.VirtualClusterDomain; +import com.alibaba.nacos.naming.core.Instance; +import com.alibaba.nacos.naming.core.Service; import com.alibaba.nacos.naming.misc.SwitchDomain; import com.alibaba.nacos.naming.monitor.MetricsMonitor; import com.ning.http.client.AsyncCompletionHandler; @@ -85,20 +85,20 @@ public String getType() { @Override public void process(HealthCheckTask task) { - List ips = task.getCluster().allIPs(); + List ips = task.getCluster().allIPs(); if (CollectionUtils.isEmpty(ips)) { return; } - VirtualClusterDomain virtualClusterDomain = (VirtualClusterDomain) task.getCluster().getDom(); + Service service = (Service) task.getCluster().getDom(); - if (!switchDomain.isHealthCheckEnabled() || !virtualClusterDomain.getEnableHealthCheck()) { + if (!switchDomain.isHealthCheckEnabled() || !service.getHealthCheckMode().equals(HealthCheckMode.server.name())) { return; } Cluster cluster = task.getCluster(); - for (IpAddress ip : ips) { + for (Instance ip : ips) { try { if (ip.isMarked()) { @@ -144,12 +144,12 @@ public void process(HealthCheckTask task) { } private class HttpHealthCheckCallback extends AsyncCompletionHandler { - private IpAddress ip; + private Instance ip; private HealthCheckTask task; private long startTime = System.currentTimeMillis(); - public HttpHealthCheckCallback(IpAddress ip, HealthCheckTask task) { + public HttpHealthCheckCallback(Instance ip, HealthCheckTask task) { this.ip = ip; this.task = task; } diff --git a/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/MysqlHealthCheckProcessor.java b/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/MysqlHealthCheckProcessor.java index 70e97585a15..e76db1205ad 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/MysqlHealthCheckProcessor.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/MysqlHealthCheckProcessor.java @@ -17,8 +17,8 @@ import com.alibaba.nacos.api.naming.pojo.AbstractHealthChecker; import com.alibaba.nacos.naming.core.Cluster; -import com.alibaba.nacos.naming.core.IpAddress; -import com.alibaba.nacos.naming.core.VirtualClusterDomain; +import com.alibaba.nacos.naming.core.Instance; +import com.alibaba.nacos.naming.core.Service; import com.alibaba.nacos.naming.misc.Loggers; import com.alibaba.nacos.naming.misc.SwitchDomain; import com.alibaba.nacos.naming.monitor.MetricsMonitor; @@ -89,20 +89,20 @@ public String getType() { @Override public void process(HealthCheckTask task) { - List ips = task.getCluster().allIPs(); + List ips = task.getCluster().allIPs(); SRV_LOG.debug("mysql check, ips:" + ips); if (CollectionUtils.isEmpty(ips)) { return; } - VirtualClusterDomain virtualClusterDomain = (VirtualClusterDomain) task.getCluster().getDom(); + Service service = (Service) task.getCluster().getDom(); - if (!healthCheckCommon.isHealthCheckEnabled(virtualClusterDomain)) { + if (!healthCheckCommon.isHealthCheckEnabled(service)) { return; } - for (IpAddress ip : ips) { + for (Instance ip : ips) { try { if (ip.isMarked()) { @@ -131,11 +131,11 @@ public void process(HealthCheckTask task) { } private class MysqlCheckTask implements Runnable { - private IpAddress ip; + private Instance ip; private HealthCheckTask task; private long startTime = System.currentTimeMillis(); - public MysqlCheckTask(IpAddress ip, HealthCheckTask task) { + public MysqlCheckTask(Instance ip, HealthCheckTask task) { this.ip = ip; this.task = task; } diff --git a/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/TcpSuperSenseProcessor.java b/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/TcpSuperSenseProcessor.java index ca84f5d4cbf..35722d370f3 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/TcpSuperSenseProcessor.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/TcpSuperSenseProcessor.java @@ -16,8 +16,8 @@ package com.alibaba.nacos.naming.healthcheck; import com.alibaba.nacos.naming.core.Cluster; -import com.alibaba.nacos.naming.core.IpAddress; -import com.alibaba.nacos.naming.core.VirtualClusterDomain; +import com.alibaba.nacos.naming.core.Instance; +import com.alibaba.nacos.naming.core.Service; import com.alibaba.nacos.naming.misc.Loggers; import com.alibaba.nacos.naming.monitor.MetricsMonitor; import com.alibaba.nacos.naming.misc.SwitchDomain; @@ -106,18 +106,18 @@ public TcpSuperSenseProcessor() { @Override public void process(HealthCheckTask task) { - List ips = task.getCluster().allIPs(); + List ips = task.getCluster().allIPs(); if (CollectionUtils.isEmpty(ips)) { return; } - VirtualClusterDomain virtualClusterDomain = (VirtualClusterDomain) task.getCluster().getDom(); + Service service = (Service) task.getCluster().getDom(); - if (!healthCheckCommon.isHealthCheckEnabled(virtualClusterDomain)) { + if (!healthCheckCommon.isHealthCheckEnabled(service)) { return; } - for (IpAddress ip : ips) { + for (Instance ip : ips) { if (ip.isMarked()) { if (SRV_LOG.isDebugEnabled()) { @@ -238,13 +238,13 @@ public void run() { } private class Beat { - IpAddress ip; + Instance ip; HealthCheckTask task; long startTime = System.currentTimeMillis(); - Beat(IpAddress ip, HealthCheckTask task) { + Beat(Instance ip, HealthCheckTask task) { this.ip = ip; this.task = task; } @@ -257,7 +257,7 @@ public long getStartTime() { return startTime; } - public IpAddress getIp() { + public Instance getIp() { return ip; } @@ -378,13 +378,13 @@ public Void call() { SocketChannel channel = null; try { - IpAddress ipAddress = beat.getIp(); + Instance instance = beat.getIp(); Cluster cluster = beat.getTask().getCluster(); BeatKey beatKey = keyMap.get(beat.toString()); if (beatKey != null && beatKey.key.isValid()) { if (System.currentTimeMillis() - beatKey.birthTime < TCP_KEEP_ALIVE_MILLIS) { - ipAddress.setBeingChecked(false); + instance.setBeingChecked(false); return null; } @@ -400,8 +400,8 @@ public Void call() { channel.socket().setKeepAlive(true); channel.socket().setTcpNoDelay(true); - int port = cluster.isUseIPPort4Check() ? ipAddress.getPort() : cluster.getDefCkport(); - channel.connect(new InetSocketAddress(ipAddress.getIp(), port)); + int port = cluster.isUseIPPort4Check() ? instance.getPort() : cluster.getDefCkport(); + channel.connect(new InetSocketAddress(instance.getIp(), port)); SelectionKey key = channel.register(selector, SelectionKey.OP_CONNECT | SelectionKey.OP_READ); diff --git a/naming/src/main/java/com/alibaba/nacos/naming/misc/DomainStatusSynchronizer.java b/naming/src/main/java/com/alibaba/nacos/naming/misc/DomainStatusSynchronizer.java index 9c8e3f4eacc..8a63c868181 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/misc/DomainStatusSynchronizer.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/misc/DomainStatusSynchronizer.java @@ -41,11 +41,11 @@ public void send(final String serverIP, Message msg) { String url = "http://" + serverIP + ":" + RunningConfig.getServerPort() + RunningConfig.getContextPath() + - UtilsAndCommons.NACOS_NAMING_CONTEXT + "/api/domStatus"; + UtilsAndCommons.NACOS_NAMING_CONTEXT + "/service/serviceStatus"; if (serverIP.contains(UtilsAndCommons.CLUSTER_CONF_IP_SPLITER)) { url = "http://" + serverIP + RunningConfig.getContextPath() + - UtilsAndCommons.NACOS_NAMING_CONTEXT + "/api/domStatus"; + UtilsAndCommons.NACOS_NAMING_CONTEXT + "/service/serviceStatus"; } try { @@ -53,7 +53,7 @@ public void send(final String serverIP, Message msg) { @Override public Integer onCompleted(Response response) throws Exception { if (response.getStatusCode() != HttpURLConnection.HTTP_OK) { - Loggers.SRV_LOG.warn("[STATUS-SYNCHRONIZE] failed to request domStatus, remote server: {}", serverIP); + Loggers.SRV_LOG.warn("[STATUS-SYNCHRONIZE] failed to request serviceStatus, remote server: {}", serverIP); return 1; } @@ -61,7 +61,7 @@ public Integer onCompleted(Response response) throws Exception { } }); } catch (Exception e) { - Loggers.SRV_LOG.warn("[STATUS-SYNCHRONIZE] failed to request domStatus, remote server: " + serverIP, e); + Loggers.SRV_LOG.warn("[STATUS-SYNCHRONIZE] failed to request serviceStatus, remote server: " + serverIP, e); } } @@ -74,12 +74,13 @@ public Message get(String serverIP, String key) { Map params = new HashMap<>(10); - params.put("dom", key); + params.put("key", key); String result; try { Loggers.SRV_LOG.info("[STATUS-SYNCHRONIZE] sync dom status from: {}, dom: {}", serverIP, key); - result = NamingProxy.reqAPI("ip4Dom2", params, serverIP, false); + result = NamingProxy.reqAPI(RunningConfig.getContextPath() + + UtilsAndCommons.NACOS_NAMING_CONTEXT + "/instance/" + "listWithHealthStatus", params, serverIP); } catch (Exception e) { Loggers.SRV_LOG.warn("[STATUS-SYNCHRONIZE] Failed to get domain status from " + serverIP, e); return null; diff --git a/naming/src/main/java/com/alibaba/nacos/naming/misc/NamingProxy.java b/naming/src/main/java/com/alibaba/nacos/naming/misc/NamingProxy.java index 715768a4b5c..685838ccdce 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/misc/NamingProxy.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/misc/NamingProxy.java @@ -20,7 +20,6 @@ import com.ning.http.client.AsyncCompletionHandler; import com.ning.http.client.Response; import org.apache.commons.lang3.StringUtils; -import org.springframework.http.HttpMethod; import java.io.IOException; import java.net.HttpURLConnection; @@ -119,6 +118,42 @@ public static boolean syncData(byte[] data, String curServer) throws Exception { return false; } + public static String reqAPI(String api, Map params, String curServer) throws Exception { + try { + List headers = Arrays.asList("Client-Version", UtilsAndCommons.SERVER_VERSION, + "Accept-Encoding", "gzip,deflate,sdch", + "Connection", "Keep-Alive", + "Content-Encoding", "gzip"); + + + HttpClient.HttpResult result; + + if (!curServer.contains(UtilsAndCommons.CLUSTER_CONF_IP_SPLITER)) { + curServer = curServer + UtilsAndCommons.CLUSTER_CONF_IP_SPLITER + RunningConfig.getServerPort(); + } + + + result = HttpClient.httpGet("http://" + curServer + api, headers, params); + + + if (HttpURLConnection.HTTP_OK == result.code) { + return result.content; + } + + if (HttpURLConnection.HTTP_NOT_MODIFIED == result.code) { + return StringUtils.EMPTY; + } + + throw new IOException("failed to req API:" + "http://" + curServer + + RunningConfig.getContextPath() + + UtilsAndCommons.NACOS_NAMING_CONTEXT + "/api/" + api + ". code:" + + result.code + " msg: " + result.content); + } catch (Exception e) { + Loggers.SRV_LOG.warn("NamingProxy", e); + } + return StringUtils.EMPTY; + } + public static String reqAPI(String api, Map params, String curServer, boolean isPost) throws Exception { try { List headers = Arrays.asList("Client-Version", UtilsAndCommons.SERVER_VERSION, diff --git a/naming/src/main/java/com/alibaba/nacos/naming/misc/SwitchDomain.java b/naming/src/main/java/com/alibaba/nacos/naming/misc/SwitchDomain.java index 004a1efc339..766d7f2dc13 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/misc/SwitchDomain.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/misc/SwitchDomain.java @@ -15,15 +15,11 @@ */ package com.alibaba.nacos.naming.misc; -import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.nacos.naming.consistency.DataListener; -import com.alibaba.nacos.naming.core.Domain; -import com.alibaba.nacos.naming.core.IpAddress; import com.alibaba.nacos.naming.healthcheck.HealthCheckMode; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Component; -import sun.reflect.generics.reflectiveObjects.NotImplementedException; import java.util.*; import java.util.concurrent.TimeUnit; @@ -32,7 +28,7 @@ * @author nacos */ @Component -public class SwitchDomain implements DataListener { +public class SwitchDomain implements DataListener { public String name = UtilsAndCommons.SWITCH_DOMAIN_NAME; @@ -172,8 +168,7 @@ public boolean matchUnlistenKey(String key) { } @Override - public void onChange(String key, Object value) throws Exception { - SwitchDomain domain = JSON.parseObject((String)value, SwitchDomain.class); + public void onChange(String key, SwitchDomain domain) throws Exception { update(domain); } diff --git a/naming/src/main/java/com/alibaba/nacos/naming/misc/UtilsAndCommons.java b/naming/src/main/java/com/alibaba/nacos/naming/misc/UtilsAndCommons.java index 282e15515be..5d4a13e095a 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/misc/UtilsAndCommons.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/misc/UtilsAndCommons.java @@ -21,8 +21,7 @@ import com.alibaba.fastjson.serializer.SerializeConfig; import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.nacos.api.naming.pojo.AbstractHealthChecker; -import com.alibaba.nacos.naming.core.Domain; -import com.alibaba.nacos.naming.core.VirtualClusterDomain; +import com.alibaba.nacos.naming.core.Service; import com.alibaba.nacos.naming.exception.NacosException; import com.alibaba.nacos.naming.healthcheck.JsonAdapter; import com.alibaba.nacos.naming.selector.Selector; @@ -144,14 +143,14 @@ public class UtilsAndCommons { static { // custom serializer and deserializer for fast-json SerializeConfig.getGlobalInstance() - .put(AbstractHealthChecker.class, JsonAdapter.getInstance()); + .put(AbstractHealthChecker.class, JsonAdapter.getInstance()); ParserConfig.getGlobalInstance() - .putDeserializer(AbstractHealthChecker.class, JsonAdapter.getInstance()); + .putDeserializer(AbstractHealthChecker.class, JsonAdapter.getInstance()); SerializeConfig.getGlobalInstance() - .put(Selector.class, SelectorJsonAdapter.getInstance()); + .put(Selector.class, SelectorJsonAdapter.getInstance()); ParserConfig.getGlobalInstance() - .putDeserializer(Selector.class, SelectorJsonAdapter.getInstance()); + .putDeserializer(Selector.class, SelectorJsonAdapter.getInstance()); // write null values, otherwise will cause compatibility issues JSON.DEFAULT_GENERATE_FEATURE |= SerializerFeature.WriteNullStringAsEmpty.getMask(); @@ -161,7 +160,7 @@ public class UtilsAndCommons { JSON.DEFAULT_GENERATE_FEATURE |= SerializerFeature.WriteNullNumberAsZero.getMask(); DOMAIN_SYNCHRONIZATION_EXECUTOR - = new ScheduledThreadPoolExecutor(1, new ThreadFactory() { + = new ScheduledThreadPoolExecutor(1, new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); @@ -172,7 +171,7 @@ public Thread newThread(Runnable r) { }); DOMAIN_UPDATE_EXECUTOR - = new ScheduledThreadPoolExecutor(1, new ThreadFactory() { + = new ScheduledThreadPoolExecutor(1, new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); @@ -183,7 +182,7 @@ public Thread newThread(Runnable r) { }); INIT_CONFIG_EXECUTOR - = new ScheduledThreadPoolExecutor(1, new ThreadFactory() { + = new ScheduledThreadPoolExecutor(1, new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); @@ -194,7 +193,7 @@ public Thread newThread(Runnable r) { }); SERVER_STATUS_EXECUTOR - = new ScheduledThreadPoolExecutor(1, new ThreadFactory() { + = new ScheduledThreadPoolExecutor(1, new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); @@ -205,7 +204,7 @@ public Thread newThread(Runnable r) { }); RAFT_PUBLISH_EXECUTOR - = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(), new ThreadFactory() { + = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(), new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); @@ -230,20 +229,14 @@ public static String getAllExceptionMsg(Throwable e) { } - public static String getIPListStoreKey(Domain dom) { - if (dom instanceof VirtualClusterDomain) { - return UtilsAndCommons.IPADDRESS_DATA_ID_PRE + ((VirtualClusterDomain) dom).getNamespaceId() + - UtilsAndCommons.SERVICE_GROUP_CONNECTOR + dom.getName(); - } - return UtilsAndCommons.IPADDRESS_DATA_ID_PRE + dom.getName(); + public static String getIPListStoreKey(Service dom) { + return UtilsAndCommons.IPADDRESS_DATA_ID_PRE + dom.getNamespaceId() + + UtilsAndCommons.SERVICE_GROUP_CONNECTOR + dom.getName(); } - public static String getDomStoreKey(Domain dom) { - if (dom instanceof VirtualClusterDomain) { - return UtilsAndCommons.DOMAINS_DATA_ID_PRE + ((VirtualClusterDomain) dom).getNamespaceId() + - UtilsAndCommons.SERVICE_GROUP_CONNECTOR + dom.getName(); - } - return UtilsAndCommons.DOMAINS_DATA_ID_PRE + dom.getName(); + public static String getDomStoreKey(Service dom) { + return UtilsAndCommons.DOMAINS_DATA_ID_PRE + dom.getNamespaceId() + + UtilsAndCommons.SERVICE_GROUP_CONNECTOR + dom.getName(); } public static String getSwitchDomainKey() { @@ -259,7 +252,8 @@ public static Map parseMetadata(String metadata) throws NacosExc } try { - metadataMap = JSON.parseObject(metadata, new TypeReference>(){}); + metadataMap = JSON.parseObject(metadata, new TypeReference>() { + }); } catch (Exception e) { String[] datas = metadata.split(","); if (datas.length > 0) { diff --git a/naming/src/main/java/com/alibaba/nacos/naming/selector/LabelSelector.java b/naming/src/main/java/com/alibaba/nacos/naming/selector/LabelSelector.java index 210607ae1cf..2de16945816 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/selector/LabelSelector.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/selector/LabelSelector.java @@ -21,7 +21,7 @@ import com.alibaba.nacos.api.selector.SelectorType; import com.alibaba.nacos.cmdb.service.CmdbReader; import com.alibaba.nacos.naming.boot.SpringContext; -import com.alibaba.nacos.naming.core.IpAddress; +import com.alibaba.nacos.naming.core.Instance; import com.alibaba.nacos.naming.exception.NacosException; import org.apache.commons.lang3.StringUtils; @@ -103,14 +103,14 @@ public static Set parseExpression(String expression) throws NacosExcepti @Override - public List select(String consumer, List providers) { + public List select(String consumer, List providers) { if (labels.isEmpty()) { return providers; } - List ipAddressList = new ArrayList<>(); - for (IpAddress ipAddress : providers) { + List instanceList = new ArrayList<>(); + for (Instance instance : providers) { boolean matched = true; for (String labelName : getLabels()) { @@ -119,21 +119,21 @@ public List select(String consumer, List providers) { if (StringUtils.isNotBlank(consumerLabelValue) && !StringUtils.equals(consumerLabelValue, - cmdbReader.queryLabel(ipAddress.getIp(), PreservedEntityTypes.ip.name(), labelName))) { + cmdbReader.queryLabel(instance.getIp(), PreservedEntityTypes.ip.name(), labelName))) { matched = false; break; } } if (matched) { - ipAddressList.add(ipAddress); + instanceList.add(instance); } } - if (ipAddressList.isEmpty()) { + if (instanceList.isEmpty()) { return providers; } - return ipAddressList; + return instanceList; } /** diff --git a/naming/src/main/java/com/alibaba/nacos/naming/selector/NoneSelector.java b/naming/src/main/java/com/alibaba/nacos/naming/selector/NoneSelector.java index dc4a8bb7667..40d5a7b8832 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/selector/NoneSelector.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/selector/NoneSelector.java @@ -16,7 +16,7 @@ package com.alibaba.nacos.naming.selector; import com.alibaba.nacos.api.selector.SelectorType; -import com.alibaba.nacos.naming.core.IpAddress; +import com.alibaba.nacos.naming.core.Instance; import java.util.List; @@ -33,7 +33,7 @@ public NoneSelector() { } @Override - public List select(String consumer, List providers) { + public List select(String consumer, List providers) { return providers; } } diff --git a/naming/src/main/java/com/alibaba/nacos/naming/selector/Selector.java b/naming/src/main/java/com/alibaba/nacos/naming/selector/Selector.java index 0e874d1c647..13e29eacbb7 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/selector/Selector.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/selector/Selector.java @@ -15,7 +15,7 @@ */ package com.alibaba.nacos.naming.selector; -import com.alibaba.nacos.naming.core.IpAddress; +import com.alibaba.nacos.naming.core.Instance; import java.util.List; @@ -52,5 +52,5 @@ public interface Selector { * @param providers candidate provider addresses * @return selected provider addresses */ - List select(String consumer, List providers); + List select(String consumer, List providers); } diff --git a/naming/src/main/java/com/alibaba/nacos/naming/view/ServiceDetailView.java b/naming/src/main/java/com/alibaba/nacos/naming/view/ServiceDetailView.java index 9640e4f723d..b936ec29628 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/view/ServiceDetailView.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/view/ServiceDetailView.java @@ -17,7 +17,7 @@ import com.alibaba.fastjson.JSON; import com.alibaba.nacos.api.naming.pojo.Cluster; -import com.alibaba.nacos.api.naming.pojo.Service; +import com.alibaba.nacos.naming.core.Service; import java.util.List; 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 f457ddf97f5..cec53e50d9e 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 @@ -21,8 +21,8 @@ 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.IpAddress; -import com.alibaba.nacos.naming.core.VirtualClusterDomain; +import com.alibaba.nacos.naming.core.Instance; +import com.alibaba.nacos.naming.core.Service; import com.alibaba.nacos.naming.misc.UtilsAndCommons; import org.junit.Assert; import org.junit.Before; @@ -70,7 +70,7 @@ public void before() { @Test public void registerInstance() throws Exception { - VirtualClusterDomain domain = new VirtualClusterDomain(); + Service domain = new Service(); domain.setName("nacos.test.1"); Cluster cluster = new Cluster(); @@ -78,11 +78,11 @@ public void registerInstance() throws Exception { cluster.setDom(domain); domain.addCluster(cluster); - IpAddress ipAddress = new IpAddress(); - ipAddress.setIp("1.1.1.1"); - ipAddress.setPort(9999); - List ipList = new ArrayList(); - ipList.add(ipAddress); + Instance instance = new Instance(); + instance.setIp("1.1.1.1"); + instance.setPort(9999); + List ipList = new ArrayList(); + ipList.add(instance); domain.updateIPs(ipList); Mockito.when(domainsManager.getService(UtilsAndCommons.getDefaultNamespaceId(), "nacos.test.1")).thenReturn(domain); @@ -118,7 +118,7 @@ public void deregisterInstance() throws Exception { @Test public void getInstances() throws Exception { - VirtualClusterDomain domain = new VirtualClusterDomain(); + Service domain = new Service(); domain.setName("nacos.test.1"); Cluster cluster = new Cluster(); @@ -126,12 +126,12 @@ public void getInstances() throws Exception { cluster.setDom(domain); domain.addCluster(cluster); - IpAddress ipAddress = new IpAddress(); - ipAddress.setIp("10.10.10.10"); - ipAddress.setPort(8888); - ipAddress.setWeight(2.0); - List ipList = new ArrayList(); - ipList.add(ipAddress); + Instance instance = new Instance(); + instance.setIp("10.10.10.10"); + instance.setPort(8888); + instance.setWeight(2.0); + List ipList = new ArrayList(); + ipList.add(instance); domain.updateIPs(ipList); Mockito.when(domainsManager.getService(UtilsAndCommons.getDefaultNamespaceId(), "nacos.test.1")).thenReturn(domain); diff --git a/naming/src/test/java/com/alibaba/nacos/naming/core/ClusterTest.java b/naming/src/test/java/com/alibaba/nacos/naming/core/ClusterTest.java index 63862ae1f7d..b82bb8ef888 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/core/ClusterTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/core/ClusterTest.java @@ -33,7 +33,7 @@ public class ClusterTest { @Before public void before() { - VirtualClusterDomain domain = new VirtualClusterDomain(); + Service domain = new Service(); domain.setName("nacos.domain.1"); cluster = new Cluster(); @@ -56,7 +56,7 @@ public void updateCluster() { healthCheckConfig.setHeaders("Client-Version:nacos-test-1"); newCluster.setHealthChecker(healthCheckConfig); - VirtualClusterDomain domain = new VirtualClusterDomain(); + Service domain = new Service(); domain.setName("nacos.domain.2"); newCluster.setDom(domain); @@ -75,21 +75,21 @@ public void updateCluster() { @Test public void updateIps() { - IpAddress ipAddress1 = new IpAddress(); - ipAddress1.setIp("1.1.1.1"); - ipAddress1.setPort(1234); + Instance instance1 = new Instance(); + instance1.setIp("1.1.1.1"); + instance1.setPort(1234); - IpAddress ipAddress2 = new IpAddress(); - ipAddress2.setIp("1.1.1.1"); - ipAddress2.setPort(2345); + Instance instance2 = new Instance(); + instance2.setIp("1.1.1.1"); + instance2.setPort(2345); - List list = new ArrayList(); - list.add(ipAddress1); - list.add(ipAddress2); + List list = new ArrayList(); + list.add(instance1); + list.add(instance2); cluster.updateIPs(list); - List ips = cluster.allIPs(); + List ips = cluster.allIPs(); Assert.assertNotNull(ips); Assert.assertEquals(2, ips.size()); Assert.assertEquals("1.1.1.1", ips.get(0).getIp()); 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 714d42570d8..4d1a83dda49 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 @@ -16,6 +16,7 @@ package com.alibaba.nacos.naming.core; import com.alibaba.fastjson.JSON; +import com.alibaba.nacos.naming.healthcheck.HealthCheckMode; import com.alibaba.nacos.naming.misc.UtilsAndCommons; import org.junit.Assert; import org.junit.Before; @@ -30,11 +31,11 @@ */ public class DomainTest { - private VirtualClusterDomain domain; + private Service domain; @Before public void before() { - domain = new VirtualClusterDomain(); + domain = new Service(); domain.setName("nacos.domain.1"); Cluster cluster = new Cluster(); cluster.setName(UtilsAndCommons.DEFAULT_CLUSTER_NAME); @@ -45,10 +46,9 @@ public void before() { @Test public void updateDomain() { - VirtualClusterDomain newDomain = new VirtualClusterDomain(); + Service newDomain = new Service(); newDomain.setName("nacos.domain.1"); - newDomain.setEnableClientBeat(false); - newDomain.setEnableHealthCheck(false); + newDomain.setHealthCheckMode(HealthCheckMode.client.name()); newDomain.setProtectThreshold(0.7f); Cluster cluster = new Cluster(); cluster.setName(UtilsAndCommons.DEFAULT_CLUSTER_NAME); @@ -57,8 +57,7 @@ public void updateDomain() { domain.update(newDomain); - Assert.assertEquals(false, domain.getEnableClientBeat()); - Assert.assertEquals(false, domain.getEnableHealthCheck()); + Assert.assertEquals(HealthCheckMode.client.name(), domain.getHealthCheckMode()); Assert.assertEquals(0.7f, domain.getProtectThreshold(), 0.0001f); } @@ -78,15 +77,15 @@ public void addCluster() { @Test public void updateIps() throws Exception { - IpAddress ipAddress = new IpAddress(); - ipAddress.setIp("1.1.1.1"); - ipAddress.setPort(1234); - List list = new ArrayList(); - list.add(ipAddress); + Instance instance = new Instance(); + instance.setIp("1.1.1.1"); + instance.setPort(1234); + List list = new ArrayList(); + list.add(instance); domain.onChange("iplist", JSON.toJSONString(list)); - List ips = domain.allIPs(); + List ips = domain.allIPs(); Assert.assertNotNull(ips); Assert.assertEquals(1, ips.size()); 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 c4f03bf77da..98237940474 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 @@ -51,12 +51,12 @@ public void easyRemoveDom() throws Exception { @Test public void searchDom() throws Exception { - VirtualClusterDomain domain = new VirtualClusterDomain(); + Service domain = new Service(); domain.setName("nacos.test.1"); domainsManager.chooseDomMap(UtilsAndCommons.getDefaultNamespaceId()).put("nacos.test.1", domain); - List list = domainsManager.searchDomains(UtilsAndCommons.getDefaultNamespaceId(), "nacos.test.*"); + List list = domainsManager.searchDomains(UtilsAndCommons.getDefaultNamespaceId(), "nacos.test.*"); Assert.assertNotNull(list); Assert.assertEquals(1, list.size()); Assert.assertEquals("nacos.test.1", list.get(0).getName()); diff --git a/naming/src/test/java/com/alibaba/nacos/naming/core/IpAddressTest.java b/naming/src/test/java/com/alibaba/nacos/naming/core/InstanceTest.java similarity index 67% rename from naming/src/test/java/com/alibaba/nacos/naming/core/IpAddressTest.java rename to naming/src/test/java/com/alibaba/nacos/naming/core/InstanceTest.java index 3dae31c805a..cca8416331a 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/core/IpAddressTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/core/InstanceTest.java @@ -27,33 +27,33 @@ /** * @author nkorange */ -public class IpAddressTest { +public class InstanceTest { - private IpAddress ipAddress; + private Instance instance; @Before public void before() { - ipAddress = new IpAddress(); + instance = new Instance(); } @Test public void updateIp() { - ipAddress.setIp("1.1.1.1"); - ipAddress.setPort(1234); - ipAddress.setWeight(5); + instance.setIp("1.1.1.1"); + instance.setPort(1234); + instance.setWeight(5); - Assert.assertEquals("1.1.1.1", ipAddress.getIp()); - Assert.assertEquals(1234, ipAddress.getPort()); - Assert.assertEquals(5, ipAddress.getWeight(), 0.001); + Assert.assertEquals("1.1.1.1", instance.getIp()); + Assert.assertEquals(1234, instance.getPort()); + Assert.assertEquals(5, instance.getWeight(), 0.001); } @Test public void fromJson() { - ipAddress = IpAddress.fromJSON("2.2.2.2:8888_2_TEST1"); - Assert.assertEquals("2.2.2.2", ipAddress.getIp()); - Assert.assertEquals(8888, ipAddress.getPort()); - Assert.assertEquals(2, ipAddress.getWeight(), 0.001); - Assert.assertEquals("TEST1", ipAddress.getClusterName()); + instance = Instance.fromJSON("2.2.2.2:8888_2_TEST1"); + Assert.assertEquals("2.2.2.2", instance.getIp()); + Assert.assertEquals(8888, instance.getPort()); + Assert.assertEquals(2, instance.getWeight(), 0.001); + Assert.assertEquals("TEST1", instance.getClusterName()); } @Test diff --git a/naming/src/test/java/com/alibaba/nacos/naming/web/APICommandsTest.java b/naming/src/test/java/com/alibaba/nacos/naming/web/APICommandsTest.java deleted file mode 100644 index 809a59d3649..00000000000 --- a/naming/src/test/java/com/alibaba/nacos/naming/web/APICommandsTest.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright 1999-2018 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. - */ -/** - * Alipay.com Inc. - * Copyright (c) 2004-2018 All Rights Reserved. - */ - -package com.alibaba.nacos.naming.web; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.alibaba.nacos.naming.core.Cluster; -import com.alibaba.nacos.naming.core.IpAddress; -import com.alibaba.nacos.naming.core.ServiceManager; -import com.alibaba.nacos.naming.core.VirtualClusterDomain; -import com.alibaba.nacos.naming.misc.UtilsAndCommons; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -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.web.servlet.MockMvc; -import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; -import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; - -import java.util.ArrayList; -import java.util.List; - -/** - * - * @author en.xuze@alipay.com - * @version $Id: APICommandsTest.java, v 0.1 2018年5月14日 下午4:31:13 en.xuze@alipay.com Exp $ - */ -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = MockServletContext.class) -@WebAppConfiguration -public class APICommandsTest { - - @InjectMocks - private ApiCommands apiCommands; - @Mock - private ServiceManager domainsManager; - private MockMvc mockmvc; - - @Before - public void before() { - MockitoAnnotations.initMocks(this); - mockmvc = MockMvcBuilders.standaloneSetup(apiCommands).build(); - } - - @Test - public void testDomCount() throws Exception { - int mockValue = 5; - JSONObject expectedResult = new JSONObject(); - expectedResult.put("count", mockValue); - Mockito.when(domainsManager.getDomCount()).thenReturn(mockValue); - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/naming/api/domCount"); - String actualValue = mockmvc.perform(builder).andReturn().getResponse().getContentAsString(); - Assert.assertTrue("UnitTest:APICommands.domCount failure!", expectedResult.toString().equals(actualValue)); - } - - @Test - public void dom() throws Exception { - VirtualClusterDomain domain = new VirtualClusterDomain(); - domain.setName("nacos.domain.1"); - Mockito.when(domainsManager.getService(UtilsAndCommons.getDefaultNamespaceId(), "nacos.domain.1")).thenReturn(domain); - - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/naming/api/dom") - .param("dom", "nacos.domain.1"); - String actualValue = mockmvc.perform(builder).andReturn().getResponse().getContentAsString(); - Assert.assertNotNull(actualValue); - JSONObject json = JSON.parseObject(actualValue); - Assert.assertNotNull(json); - Assert.assertEquals("nacos.domain.1",json.getString("name")); - } - - @Test - public void ip4Dom() throws Exception { - - VirtualClusterDomain domain = new VirtualClusterDomain(); - domain.setName("nacos.domain.1"); - Cluster cluster = new Cluster(); - cluster.setName(UtilsAndCommons.DEFAULT_CLUSTER_NAME); - cluster.setDom(domain); - domain.addCluster(cluster); - IpAddress ipAddress = new IpAddress(); - ipAddress.setIp("1.1.1.1"); - ipAddress.setPort(1234); - List list = new ArrayList(); - list.add(ipAddress); - - domain.onChange("iplist", JSON.toJSONString(list)); - - Mockito.when(domainsManager.getService(UtilsAndCommons.getDefaultNamespaceId(), "nacos.domain.1")).thenReturn(domain); - - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/naming/api/ip4Dom") - .param("dom", "nacos.domain.1"); - String actualValue = mockmvc.perform(builder).andReturn().getResponse().getContentAsString(); - Assert.assertNotNull(actualValue); - JSONObject json = JSON.parseObject(actualValue); - Assert.assertNotNull(json); - JSONArray ips = json.getJSONArray("ips"); - Assert.assertNotNull(ips); - Assert.assertEquals(1, ips.size()); - Assert.assertEquals("1.1.1.1", ips.getJSONObject(0).getString("ip")); - Assert.assertEquals(1234, ips.getJSONObject(0).getIntValue("port")); - } -}