Remove Operators for V1.

This commit is contained in:
KomachiSion 2022-08-26 11:42:12 +08:00
parent 9819820b14
commit 2477080e1d
17 changed files with 19 additions and 1590 deletions

View File

@ -26,11 +26,9 @@ import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.common.utils.StringUtils; import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.core.utils.WebUtils; import com.alibaba.nacos.core.utils.WebUtils;
import com.alibaba.nacos.naming.core.CatalogService; import com.alibaba.nacos.naming.core.CatalogService;
import com.alibaba.nacos.naming.core.CatalogServiceV1Impl;
import com.alibaba.nacos.naming.core.CatalogServiceV2Impl; import com.alibaba.nacos.naming.core.CatalogServiceV2Impl;
import com.alibaba.nacos.naming.core.Service; import com.alibaba.nacos.naming.core.Service;
import com.alibaba.nacos.naming.core.ServiceManager; import com.alibaba.nacos.naming.core.ServiceManager;
import com.alibaba.nacos.naming.core.v2.upgrade.UpgradeJudgement;
import com.alibaba.nacos.naming.healthcheck.HealthCheckTask; import com.alibaba.nacos.naming.healthcheck.HealthCheckTask;
import com.alibaba.nacos.naming.misc.UtilsAndCommons; import com.alibaba.nacos.naming.misc.UtilsAndCommons;
import com.alibaba.nacos.plugin.auth.constant.ActionTypes; import com.alibaba.nacos.plugin.auth.constant.ActionTypes;
@ -58,15 +56,9 @@ public class CatalogController {
@Autowired @Autowired
protected ServiceManager serviceManager; protected ServiceManager serviceManager;
@Autowired
private CatalogServiceV1Impl catalogServiceV1;
@Autowired @Autowired
private CatalogServiceV2Impl catalogServiceV2; private CatalogServiceV2Impl catalogServiceV2;
@Autowired
private UpgradeJudgement upgradeJudgement;
/** /**
* Get service detail. * Get service detail.
* *
@ -192,6 +184,6 @@ public class CatalogController {
} }
private CatalogService judgeCatalogService() { private CatalogService judgeCatalogService() {
return upgradeJudgement.isUseGrpcFeatures() ? catalogServiceV2 : catalogServiceV1; return catalogServiceV2;
} }
} }

View File

@ -26,10 +26,8 @@ import com.alibaba.nacos.common.utils.NumberUtils;
import com.alibaba.nacos.common.utils.StringUtils; import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.core.utils.WebUtils; import com.alibaba.nacos.core.utils.WebUtils;
import com.alibaba.nacos.naming.core.ClusterOperator; import com.alibaba.nacos.naming.core.ClusterOperator;
import com.alibaba.nacos.naming.core.ClusterOperatorV1Impl;
import com.alibaba.nacos.naming.core.ClusterOperatorV2Impl; import com.alibaba.nacos.naming.core.ClusterOperatorV2Impl;
import com.alibaba.nacos.naming.core.v2.metadata.ClusterMetadata; import com.alibaba.nacos.naming.core.v2.metadata.ClusterMetadata;
import com.alibaba.nacos.naming.core.v2.upgrade.UpgradeJudgement;
import com.alibaba.nacos.naming.misc.UtilsAndCommons; import com.alibaba.nacos.naming.misc.UtilsAndCommons;
import com.alibaba.nacos.plugin.auth.constant.ActionTypes; import com.alibaba.nacos.plugin.auth.constant.ActionTypes;
import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.PutMapping;
@ -47,16 +45,9 @@ import javax.servlet.http.HttpServletRequest;
@RequestMapping(UtilsAndCommons.NACOS_NAMING_CONTEXT + UtilsAndCommons.NACOS_NAMING_CLUSTER_CONTEXT) @RequestMapping(UtilsAndCommons.NACOS_NAMING_CONTEXT + UtilsAndCommons.NACOS_NAMING_CLUSTER_CONTEXT)
public class ClusterController { public class ClusterController {
private final UpgradeJudgement upgradeJudgement;
private final ClusterOperatorV1Impl clusterOperatorV1;
private final ClusterOperatorV2Impl clusterOperatorV2; private final ClusterOperatorV2Impl clusterOperatorV2;
public ClusterController(UpgradeJudgement upgradeJudgement, ClusterOperatorV1Impl clusterOperatorV1, public ClusterController(ClusterOperatorV2Impl clusterOperatorV2) {
ClusterOperatorV2Impl clusterOperatorV2) {
this.upgradeJudgement = upgradeJudgement;
this.clusterOperatorV1 = clusterOperatorV1;
this.clusterOperatorV2 = clusterOperatorV2; this.clusterOperatorV2 = clusterOperatorV2;
} }
@ -89,6 +80,6 @@ public class ClusterController {
} }
private ClusterOperator judgeClusterOperator() { private ClusterOperator judgeClusterOperator() {
return upgradeJudgement.isUseGrpcFeatures() ? clusterOperatorV2 : clusterOperatorV1; return clusterOperatorV2;
} }
} }

View File

@ -27,9 +27,7 @@ import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.common.utils.StringUtils; import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.core.utils.WebUtils; import com.alibaba.nacos.core.utils.WebUtils;
import com.alibaba.nacos.naming.core.HealthOperator; import com.alibaba.nacos.naming.core.HealthOperator;
import com.alibaba.nacos.naming.core.HealthOperatorV1Impl;
import com.alibaba.nacos.naming.core.HealthOperatorV2Impl; import com.alibaba.nacos.naming.core.HealthOperatorV2Impl;
import com.alibaba.nacos.naming.core.v2.upgrade.UpgradeJudgement;
import com.alibaba.nacos.naming.misc.Loggers; import com.alibaba.nacos.naming.misc.Loggers;
import com.alibaba.nacos.naming.misc.UtilsAndCommons; import com.alibaba.nacos.naming.misc.UtilsAndCommons;
import com.alibaba.nacos.naming.monitor.MetricsMonitor; import com.alibaba.nacos.naming.monitor.MetricsMonitor;
@ -65,15 +63,9 @@ import static com.alibaba.nacos.naming.constants.RequestConstant.VALID_KEY;
@RequestMapping(UtilsAndCommons.NACOS_NAMING_CONTEXT + UtilsAndCommons.NACOS_NAMING_HEALTH_CONTEXT) @RequestMapping(UtilsAndCommons.NACOS_NAMING_CONTEXT + UtilsAndCommons.NACOS_NAMING_HEALTH_CONTEXT)
public class HealthController { public class HealthController {
@Autowired
private HealthOperatorV1Impl healthOperatorV1;
@Autowired @Autowired
private HealthOperatorV2Impl healthOperatorV2; private HealthOperatorV2Impl healthOperatorV2;
@Autowired
private UpgradeJudgement upgradeJudgement;
/** /**
* Just a health check. * Just a health check.
* *
@ -137,6 +129,6 @@ public class HealthController {
} }
private HealthOperator getHealthOperator() { private HealthOperator getHealthOperator() {
return upgradeJudgement.isUseGrpcFeatures() ? healthOperatorV2 : healthOperatorV1; return healthOperatorV2;
} }
} }

View File

@ -33,9 +33,7 @@ import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.core.utils.WebUtils; import com.alibaba.nacos.core.utils.WebUtils;
import com.alibaba.nacos.naming.core.InstanceOperator; import com.alibaba.nacos.naming.core.InstanceOperator;
import com.alibaba.nacos.naming.core.InstanceOperatorClientImpl; import com.alibaba.nacos.naming.core.InstanceOperatorClientImpl;
import com.alibaba.nacos.naming.core.InstanceOperatorServiceImpl;
import com.alibaba.nacos.naming.core.InstancePatchObject; import com.alibaba.nacos.naming.core.InstancePatchObject;
import com.alibaba.nacos.naming.core.v2.upgrade.UpgradeJudgement;
import com.alibaba.nacos.naming.healthcheck.RsInfo; import com.alibaba.nacos.naming.healthcheck.RsInfo;
import com.alibaba.nacos.naming.misc.Loggers; import com.alibaba.nacos.naming.misc.Loggers;
import com.alibaba.nacos.naming.misc.SwitchDomain; import com.alibaba.nacos.naming.misc.SwitchDomain;
@ -85,12 +83,6 @@ public class InstanceController {
@Autowired @Autowired
private InstanceOperatorClientImpl instanceServiceV2; private InstanceOperatorClientImpl instanceServiceV2;
@Autowired
private InstanceOperatorServiceImpl instanceServiceV1;
@Autowired
private UpgradeJudgement upgradeJudgement;
private static final String METADATA = "metadata"; private static final String METADATA = "metadata";
public InstanceController() { public InstanceController() {
@ -119,9 +111,9 @@ public class InstanceController {
.setDefaultInstanceEphemeral(switchDomain.isDefaultInstanceEphemeral()).setRequest(request).build(); .setDefaultInstanceEphemeral(switchDomain.isDefaultInstanceEphemeral()).setRequest(request).build();
getInstanceOperator().registerInstance(namespaceId, serviceName, instance); getInstanceOperator().registerInstance(namespaceId, serviceName, instance);
NotifyCenter.publishEvent(new RegisterInstanceTraceEvent(System.currentTimeMillis(), "", NotifyCenter.publishEvent(new RegisterInstanceTraceEvent(System.currentTimeMillis(), "", false, namespaceId,
false, namespaceId, NamingUtils.getGroupName(serviceName), NamingUtils.getServiceName(serviceName), NamingUtils.getGroupName(serviceName), NamingUtils.getServiceName(serviceName), instance.getIp(),
instance.getIp(), instance.getPort())); instance.getPort()));
return "ok"; return "ok";
} }
@ -143,8 +135,8 @@ public class InstanceController {
NamingUtils.checkServiceNameFormat(serviceName); NamingUtils.checkServiceNameFormat(serviceName);
getInstanceOperator().removeInstance(namespaceId, serviceName, instance); getInstanceOperator().removeInstance(namespaceId, serviceName, instance);
NotifyCenter.publishEvent(new DeregisterInstanceTraceEvent(System.currentTimeMillis(), "", NotifyCenter.publishEvent(new DeregisterInstanceTraceEvent(System.currentTimeMillis(), "", false,
false, DeregisterInstanceReason.REQUEST, namespaceId, NamingUtils.getGroupName(serviceName), DeregisterInstanceReason.REQUEST, namespaceId, NamingUtils.getGroupName(serviceName),
NamingUtils.getServiceName(serviceName), instance.getIp(), instance.getPort())); NamingUtils.getServiceName(serviceName), instance.getIp(), instance.getPort()));
return "ok"; return "ok";
} }
@ -324,7 +316,7 @@ public class InstanceController {
int udpPort = Integer.parseInt(WebUtils.optional(request, "udpPort", "0")); int udpPort = Integer.parseInt(WebUtils.optional(request, "udpPort", "0"));
boolean healthyOnly = Boolean.parseBoolean(WebUtils.optional(request, "healthyOnly", "false")); boolean healthyOnly = Boolean.parseBoolean(WebUtils.optional(request, "healthyOnly", "false"));
String app = WebUtils.optional(request, "app", StringUtils.EMPTY); String app = WebUtils.optional(request, "app", StringUtils.EMPTY);
Subscriber subscriber = new Subscriber(clientIP + ":" + udpPort, agent, app, clientIP, namespaceId, serviceName, Subscriber subscriber = new Subscriber(clientIP + ":" + udpPort, agent, app, clientIP, namespaceId, serviceName,
udpPort, clusters); udpPort, clusters);
return getInstanceOperator().listInstance(namespaceId, serviceName, subscriber, clusters, healthyOnly); return getInstanceOperator().listInstance(namespaceId, serviceName, subscriber, clusters, healthyOnly);
@ -447,6 +439,6 @@ public class InstanceController {
} }
private InstanceOperator getInstanceOperator() { private InstanceOperator getInstanceOperator() {
return upgradeJudgement.isUseGrpcFeatures() ? instanceServiceV2 : instanceServiceV1; return instanceServiceV2;
} }
} }

View File

@ -36,11 +36,9 @@ import com.alibaba.nacos.core.utils.WebUtils;
import com.alibaba.nacos.naming.core.Service; import com.alibaba.nacos.naming.core.Service;
import com.alibaba.nacos.naming.core.ServiceManager; import com.alibaba.nacos.naming.core.ServiceManager;
import com.alibaba.nacos.naming.core.ServiceOperator; import com.alibaba.nacos.naming.core.ServiceOperator;
import com.alibaba.nacos.naming.core.ServiceOperatorV1Impl;
import com.alibaba.nacos.naming.core.ServiceOperatorV2Impl; import com.alibaba.nacos.naming.core.ServiceOperatorV2Impl;
import com.alibaba.nacos.naming.core.SubscribeManager; import com.alibaba.nacos.naming.core.SubscribeManager;
import com.alibaba.nacos.naming.core.v2.metadata.ServiceMetadata; import com.alibaba.nacos.naming.core.v2.metadata.ServiceMetadata;
import com.alibaba.nacos.naming.core.v2.upgrade.UpgradeJudgement;
import com.alibaba.nacos.naming.misc.Loggers; import com.alibaba.nacos.naming.misc.Loggers;
import com.alibaba.nacos.naming.misc.UtilsAndCommons; import com.alibaba.nacos.naming.misc.UtilsAndCommons;
import com.alibaba.nacos.naming.pojo.Subscriber; import com.alibaba.nacos.naming.pojo.Subscriber;
@ -86,15 +84,9 @@ public class ServiceController {
@Autowired @Autowired
private SubscribeManager subscribeManager; private SubscribeManager subscribeManager;
@Autowired
private ServiceOperatorV1Impl serviceOperatorV1;
@Autowired @Autowired
private ServiceOperatorV2Impl serviceOperatorV2; private ServiceOperatorV2Impl serviceOperatorV2;
@Autowired
private UpgradeJudgement upgradeJudgement;
@Autowired @Autowired
private SelectorManager selectorManager; private SelectorManager selectorManager;
@ -122,8 +114,8 @@ public class ServiceController {
serviceMetadata.setExtendData(UtilsAndCommons.parseMetadata(metadata)); serviceMetadata.setExtendData(UtilsAndCommons.parseMetadata(metadata));
serviceMetadata.setEphemeral(false); serviceMetadata.setEphemeral(false);
getServiceOperator().create(namespaceId, serviceName, serviceMetadata); getServiceOperator().create(namespaceId, serviceName, serviceMetadata);
NotifyCenter.publishEvent(new RegisterServiceTraceEvent(System.currentTimeMillis(), NotifyCenter.publishEvent(new RegisterServiceTraceEvent(System.currentTimeMillis(), namespaceId,
namespaceId, NamingUtils.getGroupName(serviceName), NamingUtils.getServiceName(serviceName))); NamingUtils.getGroupName(serviceName), NamingUtils.getServiceName(serviceName)));
return "ok"; return "ok";
} }
@ -141,8 +133,8 @@ public class ServiceController {
@RequestParam String serviceName) throws Exception { @RequestParam String serviceName) throws Exception {
getServiceOperator().delete(namespaceId, serviceName); getServiceOperator().delete(namespaceId, serviceName);
NotifyCenter.publishEvent(new DeregisterServiceTraceEvent(System.currentTimeMillis(), NotifyCenter.publishEvent(
namespaceId, "", serviceName)); new DeregisterServiceTraceEvent(System.currentTimeMillis(), namespaceId, "", serviceName));
return "ok"; return "ok";
} }
@ -405,6 +397,6 @@ public class ServiceController {
} }
private ServiceOperator getServiceOperator() { private ServiceOperator getServiceOperator() {
return upgradeJudgement.isUseGrpcFeatures() ? serviceOperatorV2 : serviceOperatorV1; return serviceOperatorV2;
} }
} }

View File

@ -1,530 +0,0 @@
/*
* Copyright (c) 1999-2021 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.common.Constants;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.CommonParams;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import com.alibaba.nacos.api.naming.utils.NamingUtils;
import com.alibaba.nacos.api.selector.Selector;
import com.alibaba.nacos.auth.annotation.Secured;
import com.alibaba.nacos.common.utils.ConvertUtils;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.common.utils.NumberUtils;
import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.core.utils.WebUtils;
import com.alibaba.nacos.naming.core.InstanceOperator;
import com.alibaba.nacos.naming.core.InstanceOperatorClientImpl;
import com.alibaba.nacos.naming.core.InstanceOperatorServiceImpl;
import com.alibaba.nacos.naming.core.ServiceManager;
import com.alibaba.nacos.naming.core.ServiceOperator;
import com.alibaba.nacos.naming.core.ServiceOperatorV1Impl;
import com.alibaba.nacos.naming.core.ServiceOperatorV2Impl;
import com.alibaba.nacos.naming.core.v2.index.ServiceStorage;
import com.alibaba.nacos.naming.core.v2.metadata.ServiceMetadata;
import com.alibaba.nacos.naming.core.v2.upgrade.UpgradeJudgement;
import com.alibaba.nacos.naming.core.v2.upgrade.doublewrite.delay.DoubleWriteDelayTaskEngine;
import com.alibaba.nacos.naming.misc.SwitchDomain;
import com.alibaba.nacos.naming.misc.UtilsAndCommons;
import com.alibaba.nacos.naming.monitor.MetricsMonitor;
import com.alibaba.nacos.naming.pojo.Subscriber;
import com.alibaba.nacos.naming.pojo.instance.HttpRequestInstanceBuilder;
import com.alibaba.nacos.naming.selector.NoneSelector;
import com.alibaba.nacos.naming.selector.SelectorManager;
import com.alibaba.nacos.naming.utils.ServiceUtil;
import com.alibaba.nacos.naming.web.CanDistro;
import com.alibaba.nacos.plugin.auth.constant.ActionTypes;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import static com.alibaba.nacos.api.common.Constants.DEFAULT_GROUP;
import static com.alibaba.nacos.api.common.Constants.SERVICE_INFO_SPLITER;
import static com.alibaba.nacos.naming.misc.UtilsAndCommons.NAMESPACE_SERVICE_CONNECTOR;
/**
* Some API for v2 data ops when upgrading to v2.
*
* <p>Helping to resolve some unexpected problems when upgrading.
*
* @author gengtuo.ygt on 2021/5/14
* @deprecated will be removed at 2.1.x
*/
@RestController
@RequestMapping(UtilsAndCommons.NACOS_NAMING_CONTEXT + "/upgrade/ops")
public class UpgradeOpsController {
private final SwitchDomain switchDomain;
private final ServiceManager serviceManager;
private final ServiceOperatorV1Impl serviceOperatorV1;
private final ServiceOperatorV2Impl serviceOperatorV2;
private final InstanceOperatorServiceImpl instanceServiceV1;
private final InstanceOperatorClientImpl instanceServiceV2;
private final ServiceStorage serviceStorage;
private final DoubleWriteDelayTaskEngine doubleWriteDelayTaskEngine;
private final UpgradeJudgement upgradeJudgement;
@Autowired
private SelectorManager selectorManager;
public UpgradeOpsController(SwitchDomain switchDomain, ServiceManager serviceManager,
ServiceOperatorV1Impl serviceOperatorV1, ServiceOperatorV2Impl serviceOperatorV2,
InstanceOperatorServiceImpl instanceServiceV1, InstanceOperatorClientImpl instanceServiceV2,
ServiceStorage serviceStorage, DoubleWriteDelayTaskEngine doubleWriteDelayTaskEngine,
UpgradeJudgement upgradeJudgement) {
this.switchDomain = switchDomain;
this.serviceManager = serviceManager;
this.serviceOperatorV1 = serviceOperatorV1;
this.serviceOperatorV2 = serviceOperatorV2;
this.instanceServiceV1 = instanceServiceV1;
this.instanceServiceV2 = instanceServiceV2;
this.serviceStorage = serviceStorage;
this.doubleWriteDelayTaskEngine = doubleWriteDelayTaskEngine;
this.upgradeJudgement = upgradeJudgement;
}
/**
* Get metrics information for upgrading view.
*
* @param json return json format
* @return metrics about services and instances
*/
@GetMapping("/metrics")
public String metrics(@RequestParam(required = false, defaultValue = "false") boolean json) throws NacosException {
ObjectNode result = getMetrics();
if (json) {
return JacksonUtils.toJson(result);
} else {
StringBuilder sb = new StringBuilder();
Iterator<Map.Entry<String, JsonNode>> fields = result.fields();
fields.forEachRemaining(e -> {
sb.append(String.format("%-30s = ", e.getKey()));
JsonNode value = e.getValue();
if (value.isIntegralNumber()) {
sb.append(String.format("%5d", value.longValue()));
} else if (value.isFloatingPointNumber()) {
sb.append(String.format("%.3f", value.doubleValue()));
} else if (value.isTextual()) {
sb.append(value.textValue());
} else {
sb.append(value.toString());
}
sb.append('\n');
});
return sb.toString();
}
}
private ObjectNode getMetrics() throws NacosException {
ObjectNode result = JacksonUtils.createEmptyJsonNode();
Set<String> serviceNamesV2 = new HashSet<>();
Set<String> persistentServiceNamesV2 = new HashSet<>();
Set<String> ephemeralServiceNamesV2 = new HashSet<>();
int persistentInstanceCountV2 = 0;
int ephemeralInstanceCountV2 = 0;
Set<String> allNamespaces = com.alibaba.nacos.naming.core.v2.ServiceManager.getInstance().getAllNamespaces();
for (String ns : allNamespaces) {
Set<com.alibaba.nacos.naming.core.v2.pojo.Service> services = com.alibaba.nacos.naming.core.v2.ServiceManager
.getInstance().getSingletons(ns);
for (com.alibaba.nacos.naming.core.v2.pojo.Service service : services) {
String nameWithNs =
service.getNamespace() + NAMESPACE_SERVICE_CONNECTOR + service.getGroupedServiceName();
serviceNamesV2.add(nameWithNs);
if (service.isEphemeral()) {
ephemeralServiceNamesV2.add(nameWithNs);
} else {
persistentServiceNamesV2.add(nameWithNs);
}
ServiceInfo data = serviceStorage.getPushData(service);
for (com.alibaba.nacos.api.naming.pojo.Instance instance : data.getHosts()) {
if (instance.isEphemeral()) {
ephemeralInstanceCountV2 += 1;
} else {
persistentInstanceCountV2 += 1;
}
}
}
}
result.put("upgraded", upgradeJudgement.isUseGrpcFeatures());
result.put("isAll20XVersion", upgradeJudgement.isAll20XVersion());
result.put("isDoubleWriteEnabled", switchDomain.isDoubleWriteEnabled());
result.put("doubleWriteDelayTaskCount", doubleWriteDelayTaskEngine.size());
result.put("serviceCountV1", serviceManager.getServiceCount());
result.put("instanceCountV1", serviceManager.getInstanceCount());
result.put("serviceCountV2", MetricsMonitor.getDomCountMonitor().get());
result.put("instanceCountV2", MetricsMonitor.getIpCountMonitor().get());
result.put("subscribeCountV2", MetricsMonitor.getSubscriberCount().get());
result.put("responsibleServiceCountV1", serviceManager.getResponsibleServiceCount());
result.put("responsibleInstanceCountV1", serviceManager.getResponsibleInstanceCount());
result.put("ephemeralServiceCountV2", ephemeralServiceNamesV2.size());
result.put("persistentServiceCountV2", persistentServiceNamesV2.size());
result.put("ephemeralInstanceCountV2", ephemeralInstanceCountV2);
result.put("persistentInstanceCountV2", persistentInstanceCountV2);
Set<String> serviceNamesV1 = serviceManager.getAllServiceNames().entrySet().stream()
.flatMap(e -> e.getValue().stream().map(name -> {
if (!name.contains(SERVICE_INFO_SPLITER)) {
name = NamingUtils.getGroupedName(name, DEFAULT_GROUP);
}
return e.getKey() + NAMESPACE_SERVICE_CONNECTOR + name;
})).collect(Collectors.toSet());
result.put("service.V1.not.in.V2",
String.join("\n", (Collection<String>) CollectionUtils.subtract(serviceNamesV1, serviceNamesV2)));
result.put("service.V2.not.in.V1",
String.join("\n", (Collection<String>) CollectionUtils.subtract(serviceNamesV2, serviceNamesV1)));
return result;
}
/**
* Create a new service. This API will create a persistence service.
*
* @param namespaceId namespace id
* @param serviceName service name
* @param protectThreshold protect threshold
* @param metadata service metadata
* @param selector selector
* @return 'ok' if success
* @throws Exception exception
*/
@PostMapping("/service")
@Secured(action = ActionTypes.WRITE)
public String createService(@RequestParam(defaultValue = "v2", required = false) String ver,
HttpServletRequest request, @RequestParam(defaultValue = Constants.DEFAULT_NAMESPACE_ID) String namespaceId,
@RequestParam String serviceName,
@RequestParam(required = false, defaultValue = "0.0F") float protectThreshold,
@RequestParam(defaultValue = StringUtils.EMPTY) String metadata,
@RequestParam(defaultValue = StringUtils.EMPTY) String selector) throws Exception {
ServiceMetadata serviceMetadata = new ServiceMetadata();
serviceMetadata.setProtectThreshold(protectThreshold);
serviceMetadata.setSelector(parseSelector(selector));
serviceMetadata.setExtendData(UtilsAndCommons.parseMetadata(metadata));
boolean ephemeral = ConvertUtils.toBoolean(
WebUtils.optional(request, "ephemeral", String.valueOf(switchDomain.isDefaultInstanceEphemeral())));
serviceMetadata.setEphemeral(ephemeral);
getServiceOperator(ver).create(namespaceId, serviceName, serviceMetadata);
return "ok";
}
/**
* Remove service.
*
* @param namespaceId namespace
* @param serviceName service name
* @return 'ok' if success
* @throws Exception exception
*/
@DeleteMapping("/service")
@Secured(action = ActionTypes.WRITE)
public String removeService(@RequestParam(defaultValue = "v2", required = false) String ver,
@RequestParam(defaultValue = Constants.DEFAULT_NAMESPACE_ID) String namespaceId,
@RequestParam String serviceName) throws Exception {
getServiceOperator(ver).delete(namespaceId, serviceName);
return "ok";
}
private ServiceOperator getServiceOperator(String ver) {
return "v2".equals(ver) ? serviceOperatorV2 : serviceOperatorV1;
}
/**
* Get detail of service.
*
* @param namespaceId namespace
* @param serviceName service name
* @return detail information of service
* @throws NacosException nacos exception
*/
@GetMapping("/service")
@Secured(action = ActionTypes.READ)
public ObjectNode detailService(@RequestParam(defaultValue = "v2", required = false) String ver,
@RequestParam(defaultValue = Constants.DEFAULT_NAMESPACE_ID) String namespaceId,
@RequestParam String serviceName) throws NacosException {
return getServiceOperator(ver).queryService(namespaceId, serviceName);
}
/**
* List all service names.
*
* @param request http request
* @return all service names
* @throws Exception exception
*/
@GetMapping("/service/list")
@Secured(action = ActionTypes.READ)
public ObjectNode listService(@RequestParam(defaultValue = "v2", required = false) String ver,
HttpServletRequest request) throws Exception {
final int pageNo = NumberUtils.toInt(WebUtils.required(request, "pageNo"));
final int pageSize = NumberUtils.toInt(WebUtils.required(request, "pageSize"));
String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID, Constants.DEFAULT_NAMESPACE_ID);
String groupName = WebUtils.optional(request, CommonParams.GROUP_NAME, Constants.DEFAULT_GROUP);
String selectorString = WebUtils.optional(request, "selector", StringUtils.EMPTY);
ObjectNode result = JacksonUtils.createEmptyJsonNode();
Collection<String> serviceNameList = getServiceOperator(ver)
.listService(namespaceId, groupName, selectorString);
result.put("count", serviceNameList.size());
result.replace("doms",
JacksonUtils.transferToJsonNode(ServiceUtil.pageServiceName(pageNo, pageSize, serviceNameList)));
return result;
}
/**
* Update service.
*
* @param request http request
* @return 'ok' if success
* @throws Exception exception
*/
@PutMapping("/service")
@Secured(action = ActionTypes.WRITE)
public String updateService(@RequestParam(defaultValue = "v2", required = false) String ver,
HttpServletRequest request) throws Exception {
String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID, Constants.DEFAULT_NAMESPACE_ID);
String serviceName = WebUtils.required(request, CommonParams.SERVICE_NAME);
ServiceMetadata serviceMetadata = new ServiceMetadata();
serviceMetadata.setProtectThreshold(NumberUtils.toFloat(WebUtils.required(request, "protectThreshold")));
serviceMetadata.setExtendData(
UtilsAndCommons.parseMetadata(WebUtils.optional(request, "metadata", StringUtils.EMPTY)));
serviceMetadata.setSelector(parseSelector(WebUtils.optional(request, "selector", StringUtils.EMPTY)));
com.alibaba.nacos.naming.core.v2.pojo.Service service = com.alibaba.nacos.naming.core.v2.pojo.Service
.newService(namespaceId, NamingUtils.getGroupName(serviceName),
NamingUtils.getServiceName(serviceName));
getServiceOperator(ver).update(service, serviceMetadata);
return "ok";
}
/**
* Search service names.
*
* @param namespaceId namespace
* @param expr search pattern
* @param responsibleOnly whether only search responsible service
* @return search result
*/
@RequestMapping("/service/names")
@Secured(action = ActionTypes.READ)
public ObjectNode searchService(@RequestParam(defaultValue = "v2", required = false) String ver,
@RequestParam(defaultValue = StringUtils.EMPTY) String namespaceId,
@RequestParam(defaultValue = StringUtils.EMPTY) String expr,
@RequestParam(required = false) boolean responsibleOnly) throws NacosException {
Map<String, Collection<String>> serviceNameMap = new HashMap<>(16);
int totalCount = 0;
ServiceOperator serviceOperator = getServiceOperator(ver);
if (StringUtils.isNotBlank(namespaceId)) {
Collection<String> names = serviceOperator.searchServiceName(namespaceId, expr, responsibleOnly);
serviceNameMap.put(namespaceId, names);
totalCount = names.size();
} else {
for (String each : serviceOperator.listAllNamespace()) {
Collection<String> names = serviceOperator.searchServiceName(each, expr, responsibleOnly);
serviceNameMap.put(each, names);
totalCount += names.size();
}
}
ObjectNode result = JacksonUtils.createEmptyJsonNode();
result.replace("services", JacksonUtils.transferToJsonNode(serviceNameMap));
result.put("count", totalCount);
return result;
}
private Selector parseSelector(String selectorJsonString) throws Exception {
if (StringUtils.isBlank(selectorJsonString)) {
return new NoneSelector();
}
JsonNode selectorJson = JacksonUtils.toObj(URLDecoder.decode(selectorJsonString, "UTF-8"));
String type = Optional.ofNullable(selectorJson.get("type"))
.orElseThrow(() -> new NacosException(NacosException.INVALID_PARAM, "not match any type of selector!"))
.asText();
String expression = Optional.ofNullable(selectorJson.get("expression")).map(JsonNode::asText).orElse(null);
Selector selector = selectorManager.parseSelector(type, expression);
if (Objects.isNull(selector)) {
throw new NacosException(NacosException.INVALID_PARAM, "not match any type of selector!");
}
return selector;
}
/**
* Register new instance.
*
* @param request http request
* @return 'ok' if success
* @throws Exception any error during register
*/
@CanDistro
@PostMapping("/instance")
@Secured(action = ActionTypes.WRITE)
public String registerInstance(@RequestParam(defaultValue = "v2", required = false) String ver,
HttpServletRequest request) throws Exception {
final String namespaceId = WebUtils
.optional(request, CommonParams.NAMESPACE_ID, Constants.DEFAULT_NAMESPACE_ID);
final String serviceName = WebUtils.required(request, CommonParams.SERVICE_NAME);
NamingUtils.checkServiceNameFormat(serviceName);
final Instance instance = HttpRequestInstanceBuilder.newBuilder()
.setDefaultInstanceEphemeral(switchDomain.isDefaultInstanceEphemeral()).setRequest(request).build();
getInstanceOperator(ver).registerInstance(namespaceId, serviceName, instance);
return "ok";
}
/**
* Deregister instances.
*
* @param request http request
* @return 'ok' if success
* @throws Exception any error during deregister
*/
@CanDistro
@DeleteMapping("/instance")
@Secured(action = ActionTypes.WRITE)
public String deregisterInstance(@RequestParam(defaultValue = "v2", required = false) String ver,
HttpServletRequest request) throws Exception {
Instance instance = HttpRequestInstanceBuilder.newBuilder()
.setDefaultInstanceEphemeral(switchDomain.isDefaultInstanceEphemeral()).setRequest(request).build();
String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID, Constants.DEFAULT_NAMESPACE_ID);
String serviceName = WebUtils.required(request, CommonParams.SERVICE_NAME);
NamingUtils.checkServiceNameFormat(serviceName);
getInstanceOperator(ver).removeInstance(namespaceId, serviceName, instance);
return "ok";
}
/**
* Update instance.
*
* @param request http request
* @return 'ok' if success
* @throws Exception any error during update
*/
@CanDistro
@PutMapping("/instance")
@Secured(action = ActionTypes.WRITE)
public String updateInstance(@RequestParam(defaultValue = "v2", required = false) String ver,
HttpServletRequest request) throws Exception {
String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID, Constants.DEFAULT_NAMESPACE_ID);
String serviceName = WebUtils.required(request, CommonParams.SERVICE_NAME);
NamingUtils.checkServiceNameFormat(serviceName);
Instance instance = HttpRequestInstanceBuilder.newBuilder()
.setDefaultInstanceEphemeral(switchDomain.isDefaultInstanceEphemeral()).setRequest(request).build();
getInstanceOperator(ver).updateInstance(namespaceId, serviceName, instance);
return "ok";
}
/**
* Get all instance of input service.
*
* @param request http request
* @return list of instance
* @throws Exception any error during list
*/
@GetMapping("/instance/list")
@Secured(action = ActionTypes.READ)
public Object listInstance(@RequestParam(defaultValue = "v2", required = false) String ver,
HttpServletRequest request) throws Exception {
String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID, Constants.DEFAULT_NAMESPACE_ID);
String serviceName = WebUtils.required(request, CommonParams.SERVICE_NAME);
NamingUtils.checkServiceNameFormat(serviceName);
String agent = WebUtils.getUserAgent(request);
String clusters = WebUtils.optional(request, "clusters", StringUtils.EMPTY);
String clientIP = WebUtils.optional(request, "clientIP", StringUtils.EMPTY);
int udpPort = Integer.parseInt(WebUtils.optional(request, "udpPort", "0"));
boolean healthyOnly = Boolean.parseBoolean(WebUtils.optional(request, "healthyOnly", "false"));
boolean isCheck = Boolean.parseBoolean(WebUtils.optional(request, "isCheck", "false"));
String app = WebUtils.optional(request, "app", StringUtils.EMPTY);
String env = WebUtils.optional(request, "env", StringUtils.EMPTY);
String tenant = WebUtils.optional(request, "tid", StringUtils.EMPTY);
Subscriber subscriber = new Subscriber(clientIP + ":" + udpPort, agent, app, clientIP, namespaceId, serviceName,
udpPort, clusters);
return getInstanceOperator(ver).listInstance(namespaceId, serviceName, subscriber, clusters, healthyOnly);
}
/**
* Get detail information of specified instance.
*
* @param request http request
* @return detail information of instance
* @throws Exception any error during get
*/
@GetMapping("/instance")
@Secured(action = ActionTypes.READ)
public ObjectNode detailInstance(@RequestParam(defaultValue = "v2", required = false) String ver,
HttpServletRequest request) throws Exception {
String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID, Constants.DEFAULT_NAMESPACE_ID);
String serviceName = WebUtils.required(request, CommonParams.SERVICE_NAME);
NamingUtils.checkServiceNameFormat(serviceName);
String cluster = WebUtils.optional(request, CommonParams.CLUSTER_NAME, UtilsAndCommons.DEFAULT_CLUSTER_NAME);
String ip = WebUtils.required(request, "ip");
int port = Integer.parseInt(WebUtils.required(request, "port"));
com.alibaba.nacos.api.naming.pojo.Instance instance = getInstanceOperator(ver)
.getInstance(namespaceId, serviceName, cluster, ip, port);
ObjectNode result = JacksonUtils.createEmptyJsonNode();
result.put("service", serviceName);
result.put("ip", ip);
result.put("port", port);
result.put("clusterName", cluster);
result.put("weight", instance.getWeight());
result.put("healthy", instance.isHealthy());
result.put("instanceId", instance.getInstanceId());
result.set("metadata", JacksonUtils.transferToJsonNode(instance.getMetadata()));
return result;
}
private InstanceOperator getInstanceOperator(String ver) {
return "v2".equals(ver) ? instanceServiceV2 : instanceServiceV1;
}
}

View File

@ -1,178 +0,0 @@
/*
* Copyright 1999-2020 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.naming.core;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.utils.NamingUtils;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.naming.constants.FieldsConstants;
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.pojo.ServiceView;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.commons.collections.CollectionUtils;
import com.alibaba.nacos.common.utils.StringUtils;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* Catalog service for v1.x .
*
* @author xiweng.yy
*/
@Component
public class CatalogServiceV1Impl implements CatalogService {
private final ServiceManager serviceManager;
public CatalogServiceV1Impl(ServiceManager serviceManager) {
this.serviceManager = serviceManager;
}
@Override
public Object getServiceDetail(String namespaceId, String groupName, String serviceName) throws NacosException {
Service detailedService = serviceManager
.getService(namespaceId, NamingUtils.getGroupedName(serviceName, groupName));
serviceManager.checkServiceIsNull(detailedService, namespaceId, serviceName);
ObjectNode serviceObject = JacksonUtils.createEmptyJsonNode();
serviceObject.put(FieldsConstants.NAME, serviceName);
serviceObject.put(FieldsConstants.PROTECT_THRESHOLD, detailedService.getProtectThreshold());
serviceObject.put(FieldsConstants.GROUP_NAME, groupName);
serviceObject.replace(FieldsConstants.SELECTOR, JacksonUtils.transferToJsonNode(detailedService.getSelector()));
serviceObject.replace(FieldsConstants.METADATA, JacksonUtils.transferToJsonNode(detailedService.getMetadata()));
ObjectNode detailView = JacksonUtils.createEmptyJsonNode();
detailView.replace(FieldsConstants.SERVICE, serviceObject);
detailView.replace(FieldsConstants.CLUSTERS,
JacksonUtils.transferToJsonNode(detailedService.getClusterMap().values()));
return detailView;
}
@Override
public List<? extends Instance> listInstances(String namespaceId, String groupName, String serviceName,
String clusterName) throws NacosException {
Service service = serviceManager.getService(namespaceId, NamingUtils.getGroupedName(serviceName, groupName));
serviceManager.checkServiceIsNull(service, namespaceId, serviceName);
if (!service.getClusterMap().containsKey(clusterName)) {
throw new NacosException(NacosException.NOT_FOUND, "cluster " + clusterName + " is not found!");
}
return service.getClusterMap().get(clusterName).allIPs();
}
@Override
public Object pageListService(String namespaceId, String groupName, String serviceName, int pageNo, int pageSize,
String instancePattern, boolean ignoreEmptyService) throws NacosException {
String param = StringUtils.isBlank(serviceName) && StringUtils.isBlank(groupName) ? StringUtils.EMPTY
: NamingUtils.getGroupedNameOptional(serviceName, groupName);
ObjectNode result = JacksonUtils.createEmptyJsonNode();
List<Service> services = new ArrayList<>();
final int total = serviceManager
.getPagedService(namespaceId, pageNo - 1, pageSize, param, instancePattern, services,
ignoreEmptyService);
if (CollectionUtils.isEmpty(services)) {
result.replace(FieldsConstants.SERVICE_LIST, JacksonUtils.transferToJsonNode(Collections.emptyList()));
result.put(FieldsConstants.COUNT, 0);
return result;
}
List<ServiceView> serviceViews = new LinkedList<>();
for (Service each : services) {
ServiceView serviceView = new ServiceView();
serviceView.setName(NamingUtils.getServiceName(each.getName()));
serviceView.setGroupName(NamingUtils.getGroupName(each.getName()));
serviceView.setClusterCount(each.getClusterMap().size());
serviceView.setIpCount(each.allIPs().size());
serviceView.setHealthyInstanceCount(each.healthyInstanceCount());
serviceView.setTriggerFlag(each.triggerFlag() ? "true" : "false");
serviceViews.add(serviceView);
}
result.set(FieldsConstants.SERVICE_LIST, JacksonUtils.transferToJsonNode(serviceViews));
result.put(FieldsConstants.COUNT, total);
return result;
}
@Override
public Object pageListServiceDetail(String namespaceId, String groupName, String serviceName, int pageNo,
int pageSize) throws NacosException {
String param = StringUtils.isBlank(serviceName) && StringUtils.isBlank(groupName) ? StringUtils.EMPTY
: NamingUtils.getGroupedNameOptional(serviceName, groupName);
List<ServiceDetailInfo> serviceDetailInfoList = new ArrayList<>();
List<Service> services = new ArrayList<>(8);
serviceManager.getPagedService(namespaceId, pageNo, pageSize, param, StringUtils.EMPTY, services, false);
for (Service each : services) {
ServiceDetailInfo serviceDetailInfo = new ServiceDetailInfo();
serviceDetailInfo.setServiceName(NamingUtils.getServiceName(each.getName()));
serviceDetailInfo.setGroupName(NamingUtils.getGroupName(each.getName()));
serviceDetailInfo.setMetadata(each.getMetadata());
Map<String, ClusterInfo> clusterInfoMap = getStringClusterInfoMap(each);
serviceDetailInfo.setClusterMap(clusterInfoMap);
serviceDetailInfoList.add(serviceDetailInfo);
}
return serviceDetailInfoList;
}
private Map<String, ClusterInfo> getStringClusterInfoMap(Service service) {
Map<String, ClusterInfo> clusterInfoMap = new HashMap<>(8);
service.getClusterMap().forEach((clusterName, cluster) -> {
ClusterInfo clusterInfo = new ClusterInfo();
List<IpAddressInfo> ipAddressInfos = getIpAddressInfos(cluster.allIPs());
clusterInfo.setHosts(ipAddressInfos);
clusterInfoMap.put(clusterName, clusterInfo);
});
return clusterInfoMap;
}
private List<IpAddressInfo> getIpAddressInfos(List<com.alibaba.nacos.naming.core.Instance> instances) {
List<IpAddressInfo> ipAddressInfos = new ArrayList<>();
instances.forEach((ipAddress) -> {
IpAddressInfo ipAddressInfo = new IpAddressInfo();
ipAddressInfo.setIp(ipAddress.getIp());
ipAddressInfo.setPort(ipAddress.getPort());
ipAddressInfo.setMetadata(ipAddress.getMetadata());
ipAddressInfo.setValid(ipAddress.isHealthy());
ipAddressInfo.setWeight(ipAddress.getWeight());
ipAddressInfo.setEnabled(ipAddress.isEnabled());
ipAddressInfos.add(ipAddressInfo);
});
return ipAddressInfos;
}
}

View File

@ -1,62 +0,0 @@
/*
* Copyright 1999-2020 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.naming.core;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.naming.core.v2.metadata.ClusterMetadata;
import com.alibaba.nacos.naming.misc.Loggers;
/**
* Implementation of cluster operator for v1.x.
*
* @author xiweng.yy
*/
@org.springframework.stereotype.Service
public class ClusterOperatorV1Impl implements ClusterOperator {
private final ServiceManager serviceManager;
public ClusterOperatorV1Impl(ServiceManager serviceManager) {
this.serviceManager = serviceManager;
}
@Override
public void updateClusterMetadata(String namespaceId, String serviceName, String clusterName,
ClusterMetadata clusterMetadata) throws NacosException {
Service service = serviceManager.getService(namespaceId, serviceName);
serviceManager.checkServiceIsNull(service, namespaceId, serviceName);
Cluster cluster = service.getClusterMap().get(clusterName);
if (cluster == null) {
Loggers.SRV_LOG.warn("[UPDATE-CLUSTER] cluster not exist, will create it: {}, service: {}", clusterName,
serviceName);
cluster = new Cluster(clusterName, service);
}
cluster.setDefCkport(clusterMetadata.getHealthyCheckPort());
cluster.setUseIPPort4Check(clusterMetadata.isUseInstancePortForCheck());
cluster.setHealthChecker(clusterMetadata.getHealthChecker());
cluster.setMetadata(clusterMetadata.getExtendData());
cluster.init();
service.getClusterMap().put(clusterName, cluster);
service.setLastModifiedMillis(System.currentTimeMillis());
service.recalculateChecksum();
service.validate();
serviceManager.addOrReplaceService(service);
}
}

View File

@ -1,65 +0,0 @@
/*
* Copyright 1999-2020 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.naming.core;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.pojo.healthcheck.HealthCheckType;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.alibaba.nacos.naming.misc.Loggers;
import com.alibaba.nacos.naming.push.UdpPushService;
import org.springframework.stereotype.Component;
/**
* Health operator implementation for v1.x.
*
* @author xiweng.yy
*/
@Component
public class HealthOperatorV1Impl implements HealthOperator {
private final ServiceManager serviceManager;
private final UdpPushService pushService;
public HealthOperatorV1Impl(ServiceManager serviceManager, UdpPushService pushService) {
this.serviceManager = serviceManager;
this.pushService = pushService;
}
@Override
public void updateHealthStatusForPersistentInstance(String namespace, String fullServiceName, String clusterName,
String ip, int port, boolean healthy) throws NacosException {
Service service = serviceManager.getService(namespace, fullServiceName);
// Only health check "none" need update health status with api
if (HealthCheckType.NONE.name().equals(service.getClusterMap().get(clusterName).getHealthChecker().getType())) {
for (Instance instance : service.allIPs(CollectionUtils.list(clusterName))) {
if (instance.getIp().equals(ip) && instance.getPort() == port) {
instance.setHealthy(healthy);
Loggers.EVT_LOG
.info((healthy ? "[IP-ENABLED]" : "[IP-DISABLED]") + " ips: " + instance.getIp() + ":"
+ instance.getPort() + "@" + instance.getClusterName() + ", service: "
+ fullServiceName + ", msg: update thought HealthController api");
pushService.serviceChanged(service);
break;
}
}
} else {
throw new NacosException(NacosException.INVALID_PARAM,
"health check is still working, service: " + fullServiceName);
}
}
}

View File

@ -1,375 +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 com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingResponseCode;
import com.alibaba.nacos.api.naming.PreservedMetadataKeys;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.naming.core.v2.upgrade.doublewrite.execute.InstanceUpgradeHelper;
import com.alibaba.nacos.naming.healthcheck.RsInfo;
import com.alibaba.nacos.naming.misc.Loggers;
import com.alibaba.nacos.naming.misc.SwitchDomain;
import com.alibaba.nacos.naming.pojo.InstanceOperationContext;
import com.alibaba.nacos.naming.pojo.InstanceOperationInfo;
import com.alibaba.nacos.naming.pojo.Subscriber;
import com.alibaba.nacos.naming.pojo.instance.BeatInfoInstanceBuilder;
import com.alibaba.nacos.naming.push.UdpPushService;
import com.alibaba.nacos.naming.push.v1.ClientInfo;
import com.alibaba.nacos.naming.push.v1.DataSource;
import com.alibaba.nacos.naming.push.v1.NamingSubscriberServiceV1Impl;
import com.alibaba.nacos.naming.push.v1.PushClient;
import com.alibaba.nacos.naming.selector.SelectorManager;
import com.alibaba.nacos.naming.utils.InstanceUtil;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Component;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.alibaba.nacos.naming.misc.UtilsAndCommons.EPHEMERAL;
import static com.alibaba.nacos.naming.misc.UtilsAndCommons.PERSIST;
import static com.alibaba.nacos.naming.misc.UtilsAndCommons.UPDATE_INSTANCE_METADATA_ACTION_REMOVE;
import static com.alibaba.nacos.naming.misc.UtilsAndCommons.UPDATE_INSTANCE_METADATA_ACTION_UPDATE;
/**
* Implementation of {@link InstanceOperator} by service for v1.x.
*
* @author xiweng.yy
*/
@Component
public class InstanceOperatorServiceImpl implements InstanceOperator {
private final ServiceManager serviceManager;
private final SwitchDomain switchDomain;
private final UdpPushService pushService;
private final NamingSubscriberServiceV1Impl subscriberServiceV1;
private final InstanceUpgradeHelper instanceUpgradeHelper;
private final SelectorManager selectorManager;
private DataSource pushDataSource = new DataSource() {
@Override
public String getData(PushClient client) {
ServiceInfo result = new ServiceInfo(client.getServiceName(), client.getClusters());
try {
Subscriber subscriber = new Subscriber(client.getAddrStr(), client.getAgent(), client.getApp(),
client.getIp(), client.getNamespaceId(), client.getServiceName(), client.getPort(),
client.getClusters());
result = listInstance(client.getNamespaceId(), client.getServiceName(), subscriber,
client.getClusters(), false);
} catch (Exception e) {
Loggers.SRV_LOG.warn("PUSH-SERVICE: service is not modified", e);
}
// overdrive the cache millis to push mode
result.setCacheMillis(switchDomain.getPushCacheMillis(client.getServiceName()));
return JacksonUtils.toJson(result);
}
};
public InstanceOperatorServiceImpl(ServiceManager serviceManager, SwitchDomain switchDomain,
UdpPushService pushService, NamingSubscriberServiceV1Impl subscriberServiceV1,
InstanceUpgradeHelper instanceUpgradeHelper, SelectorManager selectorManager) {
this.serviceManager = serviceManager;
this.switchDomain = switchDomain;
this.pushService = pushService;
this.subscriberServiceV1 = subscriberServiceV1;
this.instanceUpgradeHelper = instanceUpgradeHelper;
this.selectorManager = selectorManager;
}
@Override
public void registerInstance(String namespaceId, String serviceName, Instance instance) throws NacosException {
com.alibaba.nacos.naming.core.Instance coreInstance = parseInstance(instance);
serviceManager.registerInstance(namespaceId, serviceName, coreInstance);
}
@Override
public void removeInstance(String namespaceId, String serviceName, Instance instance) throws NacosException {
com.alibaba.nacos.naming.core.Instance coreInstance = parseInstance(instance);
Service service = serviceManager.getService(namespaceId, serviceName);
if (service == null) {
Loggers.SRV_LOG.warn("remove instance from non-exist service: {}", serviceName);
return;
}
serviceManager.removeInstance(namespaceId, serviceName, instance.isEphemeral(), coreInstance);
}
@Override
public void updateInstance(String namespaceId, String serviceName, Instance instance) throws NacosException {
com.alibaba.nacos.naming.core.Instance coreInstance = parseInstance(instance);
serviceManager.updateInstance(namespaceId, serviceName, coreInstance);
}
@Override
public void patchInstance(String namespaceId, String serviceName, InstancePatchObject patchObject)
throws NacosException {
com.alibaba.nacos.naming.core.Instance instance = serviceManager
.getInstance(namespaceId, serviceName, patchObject.getCluster(), patchObject.getIp(),
patchObject.getPort());
if (instance == null) {
throw new NacosException(NacosException.INVALID_PARAM, "instance not found");
}
if (null != patchObject.getMetadata()) {
instance.setMetadata(patchObject.getMetadata());
}
if (null != patchObject.getApp()) {
instance.setApp(patchObject.getApp());
}
if (null != patchObject.getEnabled()) {
instance.setEnabled(patchObject.getEnabled());
}
if (null != patchObject.getHealthy()) {
instance.setHealthy(patchObject.getHealthy());
}
instance.setLastBeat(System.currentTimeMillis());
instance.validate();
serviceManager.updateInstance(namespaceId, serviceName, instance);
}
@Override
public ServiceInfo listInstance(String namespaceId, String serviceName, Subscriber subscriber, String cluster,
boolean healthOnly) throws Exception {
ClientInfo clientInfo = new ClientInfo(subscriber.getAgent());
String clientIP = subscriber.getIp();
ServiceInfo result = new ServiceInfo(serviceName, cluster);
Service service = serviceManager.getService(namespaceId, serviceName);
long cacheMillis = switchDomain.getDefaultCacheMillis();
// now try to enable the push
try {
if (subscriber.getPort() > 0 && pushService.canEnablePush(subscriber.getAgent())) {
subscriberServiceV1.addClient(namespaceId, serviceName, cluster, subscriber.getAgent(),
new InetSocketAddress(clientIP, subscriber.getPort()), pushDataSource, StringUtils.EMPTY,
StringUtils.EMPTY);
cacheMillis = switchDomain.getPushCacheMillis(serviceName);
}
} catch (Exception e) {
Loggers.SRV_LOG.error("[NACOS-API] failed to added push client {}, {}:{}", clientInfo, clientIP,
subscriber.getPort(), e);
cacheMillis = switchDomain.getDefaultCacheMillis();
}
if (service == null) {
if (Loggers.SRV_LOG.isDebugEnabled()) {
Loggers.SRV_LOG.debug("no instance to serve for service: {}", serviceName);
}
result.setCacheMillis(cacheMillis);
return result;
}
checkIfDisabled(service);
List<com.alibaba.nacos.naming.core.Instance> srvedIps = service
.srvIPs(Arrays.asList(StringUtils.split(cluster, StringUtils.COMMA)));
// filter ips using selector:
if (service.getSelector() != null && StringUtils.isNotBlank(clientIP)) {
srvedIps = selectorManager.select(service.getSelector(), clientIP, srvedIps);
}
if (CollectionUtils.isEmpty(srvedIps)) {
if (Loggers.SRV_LOG.isDebugEnabled()) {
Loggers.SRV_LOG.debug("no instance to serve for service: {}", serviceName);
}
result.setCacheMillis(cacheMillis);
result.setLastRefTime(System.currentTimeMillis());
result.setChecksum(service.getChecksum());
return result;
}
long total = 0;
Map<Boolean, List<com.alibaba.nacos.naming.core.Instance>> ipMap = new HashMap<>(2);
ipMap.put(Boolean.TRUE, new ArrayList<>());
ipMap.put(Boolean.FALSE, new ArrayList<>());
for (com.alibaba.nacos.naming.core.Instance ip : srvedIps) {
// remove disabled instance:
if (!ip.isEnabled()) {
continue;
}
ipMap.get(ip.isHealthy()).add(ip);
total += 1;
}
double threshold = service.getProtectThreshold();
List<Instance> hosts;
if ((float) ipMap.get(Boolean.TRUE).size() / total <= threshold) {
Loggers.SRV_LOG.warn("protect threshold reached, return all ips, service: {}", result.getName());
result.setReachProtectionThreshold(true);
hosts = Stream.of(Boolean.TRUE, Boolean.FALSE).map(ipMap::get).flatMap(Collection::stream)
.map(InstanceUtil::deepCopy)
// set all to `healthy` state to protect
.peek(instance -> instance.setHealthy(true)).collect(Collectors.toCollection(LinkedList::new));
} else {
result.setReachProtectionThreshold(false);
hosts = new LinkedList<>(ipMap.get(Boolean.TRUE));
if (!healthOnly) {
hosts.addAll(ipMap.get(Boolean.FALSE));
}
}
result.setHosts(hosts);
result.setCacheMillis(cacheMillis);
result.setLastRefTime(System.currentTimeMillis());
result.setChecksum(service.getChecksum());
return result;
}
@Override
public Instance getInstance(String namespaceId, String serviceName, String cluster, String ip, int port)
throws NacosException {
Service service = serviceManager.getService(namespaceId, serviceName);
serviceManager.checkServiceIsNull(service, namespaceId, serviceName);
List<String> clusters = new ArrayList<>();
clusters.add(cluster);
List<com.alibaba.nacos.naming.core.Instance> ips = service.allIPs(clusters);
if (ips == null || ips.isEmpty()) {
throw new NacosException(NacosException.NOT_FOUND,
"no ips found for cluster " + cluster + " in service " + serviceName);
}
for (com.alibaba.nacos.naming.core.Instance each : ips) {
if (each.getIp().equals(ip) && each.getPort() == port) {
return each;
}
}
throw new NacosException(NacosException.NOT_FOUND, "no matched ip found!");
}
private void checkIfDisabled(Service service) throws Exception {
if (!service.getEnabled()) {
throw new Exception("service is disabled now.");
}
}
@Override
public int handleBeat(String namespaceId, String serviceName, String ip, int port, String cluster,
RsInfo clientBeat, BeatInfoInstanceBuilder builder) throws NacosException {
com.alibaba.nacos.naming.core.Instance instance = serviceManager
.getInstance(namespaceId, serviceName, cluster, ip, port);
if (instance == null) {
if (clientBeat == null) {
return NamingResponseCode.RESOURCE_NOT_FOUND;
}
Loggers.SRV_LOG.warn("[CLIENT-BEAT] The instance has been removed for health mechanism, "
+ "perform data compensation operations, beat: {}, serviceName: {}", clientBeat, serviceName);
instance = parseInstance(builder.setBeatInfo(clientBeat).setServiceName(serviceName).build());
serviceManager.registerInstance(namespaceId, serviceName, instance);
}
Service service = serviceManager.getService(namespaceId, serviceName);
serviceManager.checkServiceIsNull(service, namespaceId, serviceName);
if (clientBeat == null) {
clientBeat = new RsInfo();
clientBeat.setIp(ip);
clientBeat.setPort(port);
clientBeat.setCluster(cluster);
}
service.processClientBeat(clientBeat);
return NamingResponseCode.OK;
}
@Override
public long getHeartBeatInterval(String namespaceId, String serviceName, String ip, int port, String cluster) {
com.alibaba.nacos.naming.core.Instance instance = serviceManager
.getInstance(namespaceId, serviceName, cluster, ip, port);
if (null != instance && instance.containsMetadata(PreservedMetadataKeys.HEART_BEAT_INTERVAL)) {
return instance.getInstanceHeartBeatInterval();
}
return switchDomain.getClientBeatInterval();
}
@Override
public List<? extends Instance> listAllInstances(String namespaceId, String serviceName) throws NacosException {
Service service = serviceManager.getService(namespaceId, serviceName);
serviceManager.checkServiceIsNull(service, namespaceId, serviceName);
return service.allIPs();
}
@Override
public List<String> batchUpdateMetadata(String namespaceId, InstanceOperationInfo instanceOperationInfo,
Map<String, String> metadata) {
return batchOperate(namespaceId, instanceOperationInfo, metadata, UPDATE_INSTANCE_METADATA_ACTION_UPDATE);
}
@Override
public List<String> batchDeleteMetadata(String namespaceId, InstanceOperationInfo instanceOperationInfo,
Map<String, String> metadata) throws NacosException {
return batchOperate(namespaceId, instanceOperationInfo, metadata, UPDATE_INSTANCE_METADATA_ACTION_REMOVE);
}
private List<String> batchOperate(String namespaceId, InstanceOperationInfo instanceOperationInfo,
Map<String, String> metadata, String updateInstanceMetadataAction) {
List<String> result = new LinkedList<>();
for (com.alibaba.nacos.naming.core.Instance each : batchOperateMetadata(namespaceId, instanceOperationInfo,
metadata, updateInstanceMetadataAction)) {
result.add(each.getDatumKey() + ":" + (each.isEphemeral() ? EPHEMERAL : PERSIST));
}
return result;
}
private List<com.alibaba.nacos.naming.core.Instance> batchOperateMetadata(String namespace,
InstanceOperationInfo instanceOperationInfo, Map<String, String> metadata, String action) {
Function<InstanceOperationContext, List<com.alibaba.nacos.naming.core.Instance>> operateFunction = instanceOperationContext -> {
try {
return serviceManager.updateMetadata(instanceOperationContext.getNamespace(),
instanceOperationContext.getServiceName(), instanceOperationContext.getEphemeral(), action,
instanceOperationContext.getAll(), instanceOperationContext.getInstances(), metadata);
} catch (NacosException e) {
Loggers.SRV_LOG.warn("UPDATE-METADATA: updateMetadata failed", e);
}
return new ArrayList<>();
};
return serviceManager.batchOperate(namespace, instanceOperationInfo, operateFunction);
}
private com.alibaba.nacos.naming.core.Instance parseInstance(Instance apiInstance) throws NacosException {
com.alibaba.nacos.naming.core.Instance result = instanceUpgradeHelper.toV1(apiInstance);
result.setApp(apiInstance.getMetadata().getOrDefault("app", "DEFAULT"));
result.validate();
return result;
}
}

View File

@ -1,157 +0,0 @@
/*
* Copyright 1999-2020 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.naming.core;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.utils.NamingUtils;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.naming.constants.FieldsConstants;
import com.alibaba.nacos.naming.core.v2.metadata.ServiceMetadata;
import com.alibaba.nacos.naming.core.v2.pojo.Service;
import com.alibaba.nacos.naming.utils.ServiceUtil;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.springframework.stereotype.Component;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
/**
* Implementation of service operator for v1.x.
*
* @author xiweng.yy
*/
@Component
public class ServiceOperatorV1Impl implements ServiceOperator {
private final ServiceManager serviceManager;
private final DistroMapper distroMapper;
public ServiceOperatorV1Impl(ServiceManager serviceManager, DistroMapper distroMapper) {
this.serviceManager = serviceManager;
this.distroMapper = distroMapper;
}
@Override
public void create(String namespaceId, String serviceName, ServiceMetadata metadata) throws NacosException {
if (serviceManager.getService(namespaceId, serviceName) != null) {
throw new IllegalArgumentException("specified service already exists, serviceName : " + serviceName);
}
com.alibaba.nacos.naming.core.Service service = new com.alibaba.nacos.naming.core.Service(serviceName);
service.setProtectThreshold(metadata.getProtectThreshold());
service.setEnabled(true);
service.setMetadata(metadata.getExtendData());
service.setSelector(metadata.getSelector());
service.setNamespaceId(namespaceId);
service.setGroupName(NamingUtils.getGroupName(serviceName));
// now valid the service. if failed, exception will be thrown
service.setLastModifiedMillis(System.currentTimeMillis());
service.recalculateChecksum();
service.validate();
serviceManager.addOrReplaceService(service);
}
@Override
public void update(Service service, ServiceMetadata metadata) throws NacosException {
String namespaceId = service.getNamespace();
String serviceName = service.getGroupedServiceName();
com.alibaba.nacos.naming.core.Service serviceV1 = serviceManager.getService(namespaceId, serviceName);
serviceManager.checkServiceIsNull(serviceV1, namespaceId, serviceName);
serviceV1.setProtectThreshold(metadata.getProtectThreshold());
serviceV1.setSelector(metadata.getSelector());
serviceV1.setMetadata(metadata.getExtendData());
serviceV1.setLastModifiedMillis(System.currentTimeMillis());
serviceV1.recalculateChecksum();
serviceV1.validate();
serviceManager.addOrReplaceService(serviceV1);
}
@Override
public void delete(String namespaceId, String serviceName) throws NacosException {
serviceManager.easyRemoveService(namespaceId, serviceName);
}
@Override
public ObjectNode queryService(String namespaceId, String serviceName) throws NacosException {
com.alibaba.nacos.naming.core.Service service = serviceManager.getService(namespaceId, serviceName);
serviceManager.checkServiceIsNull(service, namespaceId, serviceName);
ObjectNode res = JacksonUtils.createEmptyJsonNode();
res.put(FieldsConstants.NAME, NamingUtils.getServiceName(serviceName));
res.put(FieldsConstants.NAME_SPACE_ID, service.getNamespaceId());
res.put(FieldsConstants.PROTECT_THRESHOLD, service.getProtectThreshold());
res.replace(FieldsConstants.METADATA, JacksonUtils.transferToJsonNode(service.getMetadata()));
res.replace(FieldsConstants.SELECTOR, JacksonUtils.transferToJsonNode(service.getSelector()));
res.put(FieldsConstants.GROUP_NAME, NamingUtils.getGroupName(serviceName));
ArrayNode clusters = JacksonUtils.createEmptyArrayNode();
for (Cluster cluster : service.getClusterMap().values()) {
ObjectNode clusterJson = JacksonUtils.createEmptyJsonNode();
clusterJson.put(FieldsConstants.NAME, cluster.getName());
clusterJson.replace(FieldsConstants.HEALTH_CHECKER,
JacksonUtils.transferToJsonNode(cluster.getHealthChecker()));
clusterJson.replace(FieldsConstants.METADATA, JacksonUtils.transferToJsonNode(cluster.getMetadata()));
clusters.add(clusterJson);
}
res.replace(FieldsConstants.CLUSTERS, clusters);
return res;
}
@Override
public Collection<String> listService(String namespaceId, String groupName, String selector) throws NacosException {
Map<String, com.alibaba.nacos.naming.core.Service> serviceMap = serviceManager.chooseServiceMap(namespaceId);
if (serviceMap == null || serviceMap.isEmpty()) {
return Collections.emptyList();
}
serviceMap = ServiceUtil.selectServiceWithGroupName(serviceMap, groupName);
serviceMap = ServiceUtil.selectServiceBySelector(serviceMap, selector);
if (!Constants.ALL_PATTERN.equals(groupName)) {
serviceMap.entrySet()
.removeIf(entry -> !entry.getKey().startsWith(groupName + Constants.SERVICE_INFO_SPLITER));
}
return serviceMap.keySet();
}
@Override
public Collection<String> listAllNamespace() {
return serviceManager.getAllNamespaces();
}
@Override
public Collection<String> searchServiceName(String namespaceId, String expr, boolean responsibleOnly)
throws NacosException {
List<com.alibaba.nacos.naming.core.Service> services = serviceManager
.searchServices(namespaceId, Constants.ANY_PATTERN + expr + Constants.ANY_PATTERN);
Collection<String> result = new HashSet<>();
for (com.alibaba.nacos.naming.core.Service each : services) {
if (!responsibleOnly || distroMapper.responsible(each.getName())) {
result.add(NamingUtils.getServiceName(each.getName()));
}
}
return result;
}
}

View File

@ -19,7 +19,6 @@ package com.alibaba.nacos.naming.controllers;
import com.alibaba.nacos.api.common.Constants; import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.CommonParams; import com.alibaba.nacos.api.naming.CommonParams;
import com.alibaba.nacos.naming.core.CatalogServiceV1Impl;
import com.alibaba.nacos.naming.core.Cluster; import com.alibaba.nacos.naming.core.Cluster;
import com.alibaba.nacos.naming.core.Instance; import com.alibaba.nacos.naming.core.Instance;
import com.alibaba.nacos.naming.core.Service; import com.alibaba.nacos.naming.core.Service;
@ -55,8 +54,6 @@ public class CatalogControllerTest {
@Mock @Mock
protected UpgradeJudgement upgradeJudgement; protected UpgradeJudgement upgradeJudgement;
private CatalogServiceV1Impl catalogServiceV1;
private CatalogController catalogController; private CatalogController catalogController;
private Service service; private Service service;
@ -69,10 +66,8 @@ public class CatalogControllerTest {
@Before @Before
public void setUp() throws NoSuchFieldException, IllegalAccessException, NacosException { public void setUp() throws NoSuchFieldException, IllegalAccessException, NacosException {
catalogController = new CatalogController(); catalogController = new CatalogController();
catalogServiceV1 = new CatalogServiceV1Impl(serviceManager);
ReflectionTestUtils.setField(catalogController, "serviceManager", serviceManager); ReflectionTestUtils.setField(catalogController, "serviceManager", serviceManager);
ReflectionTestUtils.setField(catalogController, "upgradeJudgement", upgradeJudgement); ReflectionTestUtils.setField(catalogController, "upgradeJudgement", upgradeJudgement);
ReflectionTestUtils.setField(catalogController, "catalogServiceV1", catalogServiceV1);
service = new Service(TEST_SERVICE_NAME); service = new Service(TEST_SERVICE_NAME);
service.setNamespaceId(Constants.DEFAULT_NAMESPACE_ID); service.setNamespaceId(Constants.DEFAULT_NAMESPACE_ID);
service.setProtectThreshold(12.34f); service.setProtectThreshold(12.34f);
@ -150,7 +145,8 @@ public class CatalogControllerTest {
@Test @Test
public void testRt4Service() { public void testRt4Service() {
MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter(CommonParams.SERVICE_NAME, TEST_GROUP_NAME + Constants.SERVICE_INFO_SPLITER + TEST_SERVICE_NAME); request.addParameter(CommonParams.SERVICE_NAME,
TEST_GROUP_NAME + Constants.SERVICE_INFO_SPLITER + TEST_SERVICE_NAME);
try { try {
ObjectNode objectNode = catalogController.rt4Service(request); ObjectNode objectNode = catalogController.rt4Service(request);
String result = objectNode.toString(); String result = objectNode.toString();

View File

@ -20,7 +20,6 @@ import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.naming.BaseTest; import com.alibaba.nacos.naming.BaseTest;
import com.alibaba.nacos.naming.core.Cluster; import com.alibaba.nacos.naming.core.Cluster;
import com.alibaba.nacos.naming.core.ClusterOperatorV1Impl;
import com.alibaba.nacos.naming.core.Service; import com.alibaba.nacos.naming.core.Service;
import com.alibaba.nacos.naming.misc.UtilsAndCommons; import com.alibaba.nacos.naming.misc.UtilsAndCommons;
import org.junit.Assert; import org.junit.Assert;
@ -52,9 +51,6 @@ public class ClusterControllerTest extends BaseTest {
@InjectMocks @InjectMocks
private ClusterController clusterController; private ClusterController clusterController;
@InjectMocks
private ClusterOperatorV1Impl clusterOperatorV1;
private MockMvc mockmvc; private MockMvc mockmvc;
@Before @Before
@ -64,7 +60,6 @@ public class ClusterControllerTest extends BaseTest {
mockInjectDistroMapper(); mockInjectDistroMapper();
mockmvc = MockMvcBuilders.standaloneSetup(clusterController).build(); mockmvc = MockMvcBuilders.standaloneSetup(clusterController).build();
ReflectionTestUtils.setField(clusterController, "upgradeJudgement", upgradeJudgement); ReflectionTestUtils.setField(clusterController, "upgradeJudgement", upgradeJudgement);
ReflectionTestUtils.setField(clusterController, "clusterOperatorV1", clusterOperatorV1);
try { try {
doCallRealMethod().when(serviceManager).checkServiceIsNull(eq(null), anyString(), anyString()); doCallRealMethod().when(serviceManager).checkServiceIsNull(eq(null), anyString(), anyString());
} catch (NacosException e) { } catch (NacosException e) {

View File

@ -20,7 +20,6 @@ package com.alibaba.nacos.naming.controllers;
import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.CommonParams; import com.alibaba.nacos.api.naming.CommonParams;
import com.alibaba.nacos.naming.constants.RequestConstant; import com.alibaba.nacos.naming.constants.RequestConstant;
import com.alibaba.nacos.naming.core.HealthOperatorV1Impl;
import com.alibaba.nacos.naming.core.HealthOperatorV2Impl; import com.alibaba.nacos.naming.core.HealthOperatorV2Impl;
import com.alibaba.nacos.naming.core.v2.upgrade.UpgradeJudgement; import com.alibaba.nacos.naming.core.v2.upgrade.UpgradeJudgement;
import com.alibaba.nacos.sys.env.EnvUtil; import com.alibaba.nacos.sys.env.EnvUtil;
@ -48,9 +47,6 @@ public class HealthControllerTest {
@InjectMocks @InjectMocks
private HealthController healthController; private HealthController healthController;
@Mock
private HealthOperatorV1Impl healthOperatorV1;
@Mock @Mock
private HealthOperatorV2Impl healthOperatorV2; private HealthOperatorV2Impl healthOperatorV2;
@ -75,7 +71,7 @@ public class HealthControllerTest {
servletRequest.addParameter(RequestConstant.IP_KEY, "1.1.1.1"); servletRequest.addParameter(RequestConstant.IP_KEY, "1.1.1.1");
servletRequest.addParameter(RequestConstant.PORT_KEY, "8848"); servletRequest.addParameter(RequestConstant.PORT_KEY, "8848");
servletRequest.addParameter(RequestConstant.HEALTHY_KEY, "true"); servletRequest.addParameter(RequestConstant.HEALTHY_KEY, "true");
Mockito.when(upgradeJudgement.isUseGrpcFeatures()).thenReturn(true); Mockito.when(upgradeJudgement.isUseGrpcFeatures()).thenReturn(true);
try { try {

View File

@ -23,7 +23,6 @@ import com.alibaba.nacos.naming.BaseTest;
import com.alibaba.nacos.naming.consistency.persistent.raft.RaftPeerSet; import com.alibaba.nacos.naming.consistency.persistent.raft.RaftPeerSet;
import com.alibaba.nacos.naming.core.Cluster; import com.alibaba.nacos.naming.core.Cluster;
import com.alibaba.nacos.naming.core.Instance; import com.alibaba.nacos.naming.core.Instance;
import com.alibaba.nacos.naming.core.InstanceOperatorServiceImpl;
import com.alibaba.nacos.naming.core.Service; import com.alibaba.nacos.naming.core.Service;
import com.alibaba.nacos.naming.core.v2.upgrade.doublewrite.delay.DoubleWriteEventListener; import com.alibaba.nacos.naming.core.v2.upgrade.doublewrite.delay.DoubleWriteEventListener;
import com.alibaba.nacos.naming.core.v2.upgrade.doublewrite.execute.InstanceUpgradeHelper; import com.alibaba.nacos.naming.core.v2.upgrade.doublewrite.execute.InstanceUpgradeHelper;
@ -66,9 +65,6 @@ public class InstanceControllerTest extends BaseTest {
@InjectMocks @InjectMocks
private InstanceController instanceController; private InstanceController instanceController;
@InjectMocks
private InstanceOperatorServiceImpl instanceOperatorService;
@Mock @Mock
private DoubleWriteEventListener doubleWriteEventListener; private DoubleWriteEventListener doubleWriteEventListener;
@ -85,7 +81,6 @@ public class InstanceControllerTest extends BaseTest {
super.before(); super.before();
mockInjectPushServer(); mockInjectPushServer();
ReflectionTestUtils.setField(instanceController, "upgradeJudgement", upgradeJudgement); ReflectionTestUtils.setField(instanceController, "upgradeJudgement", upgradeJudgement);
ReflectionTestUtils.setField(instanceController, "instanceServiceV1", instanceOperatorService);
when(context.getBean(DoubleWriteEventListener.class)).thenReturn(doubleWriteEventListener); when(context.getBean(DoubleWriteEventListener.class)).thenReturn(doubleWriteEventListener);
when(instanceUpgradeHelper.toV1(any())).thenReturn(new Instance("1.1.1.1", 9999)); when(instanceUpgradeHelper.toV1(any())).thenReturn(new Instance("1.1.1.1", 9999));
mockmvc = MockMvcBuilders.standaloneSetup(instanceController).build(); mockmvc = MockMvcBuilders.standaloneSetup(instanceController).build();

View File

@ -1,80 +0,0 @@
/*
* Copyright 1999-2021 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 com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.pojo.healthcheck.AbstractHealthChecker;
import com.alibaba.nacos.naming.push.UdpPushService;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* {@link HealthOperatorV1Impl} unit tests.
*
* @author chenglu
* @date 2021-08-03 22:19
*/
@RunWith(MockitoJUnitRunner.class)
public class HealthOperatorV1ImplTest {
private HealthOperatorV1Impl healthOperatorV1;
@Mock
private ServiceManager serviceManager;
@Mock
private UdpPushService pushService;
@Before
public void setUp() {
healthOperatorV1 = new HealthOperatorV1Impl(serviceManager, pushService);
}
@Test
public void testUpdateHealthStatusForPersistentInstance() {
try {
Service service = new Service();
Map<String, Cluster> clusterMap = new HashMap<>(2);
Cluster cluster = Mockito.mock(Cluster.class);
clusterMap.put("C", cluster);
service.setClusterMap(clusterMap);
Instance instance = new Instance();
instance.setIp("1.1.1.1");
instance.setPort(8080);
Mockito.when(cluster.allIPs()).thenReturn(Collections.singletonList(instance));
Mockito.when(cluster.getHealthChecker()).thenReturn(new AbstractHealthChecker.None());
Mockito.when(serviceManager.getService(Mockito.anyString(), Mockito.anyString())).thenReturn(service);
healthOperatorV1.updateHealthStatusForPersistentInstance("A", "B", "C", "1.1.1.1", 8080, true);
} catch (NacosException e) {
e.printStackTrace();
Assert.fail(e.getMessage());
}
}
}

View File

@ -1,65 +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 com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.utils.NamingUtils;
import com.alibaba.nacos.naming.BaseTest;
import com.alibaba.nacos.naming.consistency.ConsistencyService;
import com.alibaba.nacos.naming.core.v2.metadata.ServiceMetadata;
import com.alibaba.nacos.naming.core.v2.pojo.Service;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.test.util.ReflectionTestUtils;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class ServiceOperatorV1ImplTest extends BaseTest {
private ServiceOperatorV1Impl serviceOperatorV1Impl;
@InjectMocks
private ServiceManager serviceManager;
@InjectMocks
private DistroMapper distroMapper;
@Mock
private ConsistencyService consistencyService;
@Before
public void setUp() {
ReflectionTestUtils.setField(serviceManager, "consistencyService", consistencyService);
serviceOperatorV1Impl = new ServiceOperatorV1Impl(serviceManager, distroMapper);
}
@Test
public void testUpdate() throws NacosException {
String serviceName = "DEFAULT_GROUP@@order-service";
serviceManager.createEmptyService(TEST_NAMESPACE, serviceName, true);
com.alibaba.nacos.naming.core.v2.pojo.Service service = Service
.newService(TEST_NAMESPACE, NamingUtils.getGroupName(serviceName),
NamingUtils.getServiceName(serviceName));
ServiceMetadata metadata = new ServiceMetadata();
metadata.setProtectThreshold(0.1F);
serviceOperatorV1Impl.update(service, metadata);
assertThat(serviceManager.getService(TEST_NAMESPACE, serviceName).getProtectThreshold(), is(0.1F));
}
}