同步远程develop分支

This commit is contained in:
yongchao9 2019-06-05 20:43:12 +08:00
parent 3c971e9c45
commit c1ac93aee8
72 changed files with 11134 additions and 1853 deletions

View File

@ -20,6 +20,8 @@ import java.util.Properties;
import com.alibaba.nacos.api.config.ConfigFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingMaintainFactory;
import com.alibaba.nacos.api.naming.NamingMaintainService;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
@ -74,4 +76,26 @@ public class NacosFactory {
return NamingFactory.createNamingService(properties);
}
/**
* Create maintain service
*
* @param serverAddr
* @return NamingMaintainService
* @throws NacosException Exception
*/
public static NamingMaintainService createMaintainService(String serverAddr) throws NacosException {
return NamingMaintainFactory.createMaintainService(serverAddr);
}
/**
* Create maintain service
*
* @param properties
* @return NamingMaintainService
* @throws NacosException Exception
*/
public static NamingMaintainService createMaintainService(Properties properties) throws NacosException {
return NamingMaintainFactory.createMaintainService(properties);
}
}

View File

@ -103,6 +103,8 @@ public class Constants {
public static final int FLOW_CONTROL_INTERVAL = 1000;
public static final float DEFAULT_PROTECT_THRESHOLD = 0.0F;
public static final String LINE_SEPARATOR = Character.toString((char)1);
public static final String WORD_SEPARATOR = Character.toString((char)2);

View File

@ -0,0 +1,52 @@
/*
* 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.api.naming;
import com.alibaba.nacos.api.exception.NacosException;
import java.lang.reflect.Constructor;
import java.util.Properties;
/**
* @author liaochuntao
* @since 1.0.1
*/
public class NamingMaintainFactory {
public static NamingMaintainService createMaintainService(String serverList) throws NacosException {
try {
Class<?> driverImplClass = Class.forName("com.alibaba.nacos.client.naming.NacosNamingMaintainService");
Constructor constructor = driverImplClass.getConstructor(String.class);
NamingMaintainService vendorImpl = (NamingMaintainService)constructor.newInstance(serverList);
return vendorImpl;
} catch (Throwable e) {
throw new NacosException(-400, e.getMessage());
}
}
public static NamingMaintainService createMaintainService(Properties properties) throws NacosException {
try {
Class<?> driverImplClass = Class.forName("com.alibaba.nacos.client.naming.NacosNamingMaintainService");
Constructor constructor = driverImplClass.getConstructor(Properties.class);
NamingMaintainService vendorImpl = (NamingMaintainService)constructor.newInstance(properties);
return vendorImpl;
} catch (Throwable e) {
throw new NacosException(-400, e.getMessage());
}
}
}

View File

@ -0,0 +1,168 @@
/*
* 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.api.naming;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.Service;
import com.alibaba.nacos.api.selector.AbstractSelector;
import java.util.Map;
/**
* Operations related to Nacos
*
* @author liaochuntao
* @since 1.0.1
*/
public interface NamingMaintainService {
/**
* update instance info
*
* @param serviceName
* @param instance
* @throws NacosException
*/
void updateInstance(String serviceName, Instance instance) throws NacosException;
/**
* update instance info
*
* @param serviceName
* @param groupName
* @param instance
* @throws NacosException
*/
void updateInstance(String serviceName, String groupName, Instance instance) throws NacosException;
/**
* query service
*
* @param serviceName
* @return
* @throws NacosException
*/
Service queryService(String serviceName) throws NacosException;
/**
* query service
*
* @param serviceName
* @param groupName
* @return
* @throws NacosException
*/
Service queryService(String serviceName, String groupName) throws NacosException;
/**
* create service to Nacos
*
* @param serviceName name of service
* @throws NacosException
*/
void createService(String serviceName) throws NacosException;
/**
* create service to Nacos
*
* @param serviceName name of service
* @param groupName group of service
* @throws NacosException
*/
void createService(String serviceName, String groupName) throws NacosException;
/**
* create service to Nacos
*
* @param serviceName name of service
* @param groupName group of service
* @param protectThreshold protectThreshold of service
* @throws NacosException
*/
void createService(String serviceName, String groupName, float protectThreshold) throws NacosException;
/**
* create service to Nacos
*
* @param serviceName name of service
* @param groupName group of service
* @param protectThreshold protectThreshold of service
* @param expression expression of selector
* @throws NacosException
*/
void createService(String serviceName, String groupName, float protectThreshold, String expression) throws NacosException;
/**
* create service to Nacos
*
* @param service name of service
* @param selector selector
* @throws NacosException
*/
void createService(Service service, AbstractSelector selector) throws NacosException;
/**
* delete service from Nacos
*
* @param serviceName name of service
* @return if delete service success return true
* @throws NacosException
*/
boolean deleteService(String serviceName) throws NacosException;
/**
* delete service from Nacos
*
* @param serviceName name of service
* @param groupName group of service
* @return if delete service success return true
* @throws NacosException
*/
boolean deleteService(String serviceName, String groupName) throws NacosException;
/**
* update service to Nacos
*
* @param serviceName name of service
* @param groupName group of service
* @param protectThreshold protectThreshold of service
* @throws NacosException
*/
void updateService(String serviceName, String groupName, float protectThreshold) throws NacosException;
/**
* update service to Nacos
*
* @param serviceName name of service
* @param groupName group of service
* @param protectThreshold protectThreshold of service
* @param metadata metadata of service
* @throws NacosException
*/
void updateService(String serviceName, String groupName, float protectThreshold, Map<String, String> metadata) throws NacosException;
/**
* update service to Nacos with selector
*
* @param service {@link Service} pojo of service
* @param selector {@link AbstractSelector} pojo of selector
* @throws NacosException
*/
void updateService(Service service, AbstractSelector selector) throws NacosException;
}

View File

@ -19,10 +19,12 @@ import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.listener.EventListener;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.ListView;
import com.alibaba.nacos.api.naming.pojo.Service;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import com.alibaba.nacos.api.selector.AbstractSelector;
import java.util.List;
import java.util.Map;
/**
* Naming Service

View File

@ -28,6 +28,10 @@ public class NamingEvent implements Event {
private String serviceName;
private String groupName;
private String clusters;
private List<Instance> instances;
public NamingEvent(String serviceName, List<Instance> instances) {
@ -35,6 +39,13 @@ public class NamingEvent implements Event {
this.instances = instances;
}
public NamingEvent(String serviceName, String groupName, String clusters, List<Instance> instances) {
this.serviceName = serviceName;
this.groupName = groupName;
this.clusters = clusters;
this.instances = instances;
}
public String getServiceName() {
return serviceName;
}
@ -50,4 +61,20 @@ public class NamingEvent implements Event {
public void setInstances(List<Instance> instances) {
this.instances = instances;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public String getClusters() {
return clusters;
}
public void setClusters(String clusters) {
this.clusters = clusters;
}
}

View File

@ -16,6 +16,7 @@
package com.alibaba.nacos.api.naming.pojo;
import com.alibaba.fastjson.annotation.JSONField;
import com.alibaba.fastjson.serializer.SerializeWriter;
import com.alibaba.nacos.api.common.Constants;
import org.apache.commons.lang3.StringUtils;
@ -45,8 +46,16 @@ public abstract class AbstractHealthChecker implements Cloneable {
* @return Another instance with exactly the same fields.
* @throws CloneNotSupportedException
*/
@Override
public abstract AbstractHealthChecker clone() throws CloneNotSupportedException;
/**
* used to JsonAdapter
*/
public void jsonAdapterCallback(SerializeWriter writer){
// do nothing
}
public static class None extends AbstractHealthChecker {
public static final String TYPE = "NONE";
@ -116,6 +125,17 @@ public abstract class AbstractHealthChecker implements Cloneable {
return headerMap;
}
/**
* used to JsonAdapter
*
* @param writer
*/
@Override
public void jsonAdapterCallback(SerializeWriter writer) {
writer.writeFieldValue(',', "path", getPath());
writer.writeFieldValue(',', "headers", getHeaders());
}
@Override
public int hashCode() {
return Objects.hash(path, headers, expectedResponseCode);
@ -215,6 +235,18 @@ public abstract class AbstractHealthChecker implements Cloneable {
this.pwd = pwd;
}
/**
* used to JsonAdapter
*
* @param writer
*/
@Override
public void jsonAdapterCallback(SerializeWriter writer) {
writer.writeFieldValue(',', "user", getUser());
writer.writeFieldValue(',', "pwd", getPwd());
writer.writeFieldValue(',', "cmd", getCmd());
}
@Override
public int hashCode() {
return Objects.hash(user, pwd, cmd);

View File

@ -101,4 +101,15 @@ public class Service {
public void addMetadata(String key, String value) {
this.metadata.put(key, value);
}
@Override
public String toString() {
return "Service{" +
"name='" + name + '\'' +
", protectThreshold=" + protectThreshold +
", appName='" + appName + '\'' +
", groupName='" + groupName + '\'' +
", metadata=" + metadata +
'}';
}
}

View File

@ -0,0 +1,28 @@
/*
* 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.api.selector;
/**
* @author liaochuntao
* @since 1.0.1
*/
public class NoneSelector extends AbstractSelector {
public NoneSelector() {
this.setType(SelectorType.none.name());
}
}

View File

@ -274,7 +274,7 @@ public class CacheData {
*/
private volatile boolean isUseLocalConfig = false;
/**
* last motify time
* last modify time
*/
private volatile long localConfigLastModified;
private volatile String content;

View File

@ -16,31 +16,19 @@
package com.alibaba.nacos.client.logging.log4j2;
import com.alibaba.nacos.client.logging.AbstractNacosLogging;
import com.alibaba.nacos.client.utils.StringUtils;
import com.alibaba.nacos.common.util.ClassUtils;
import com.alibaba.nacos.common.util.ResourceUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.Appender;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.AbstractConfiguration;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.ConfigurationFactory;
import org.apache.logging.log4j.core.config.ConfigurationSource;
import org.apache.logging.log4j.core.config.composite.CompositeConfiguration;
import org.apache.logging.log4j.core.lookup.Interpolator;
import org.apache.logging.log4j.core.lookup.StrSubstitutor;
import org.apache.logging.log4j.util.PropertiesUtil;
import org.apache.logging.log4j.core.config.LoggerConfig;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static org.apache.logging.log4j.core.config.ConfigurationFactory.CONFIGURATION_FILE_PROPERTY;
import java.util.Map;
/**
* Support for Log4j version 2.7 or higher
@ -54,50 +42,32 @@ public class Log4J2NacosLogging extends AbstractNacosLogging {
private static final String FILE_PROTOCOL = "file";
private static final String YAML_PARSER_CLASS_NAME = "com.fasterxml.jackson.dataformat.yaml.YAMLParser";
private static final String NACOS_LOGGER_PREFIX = "com.alibaba.nacos";
private static final String JSON_PARSER_CLASS_NAME = "com.fasterxml.jackson.databind.ObjectMapper";
private final StrSubstitutor strSubstitutor = new StrSubstitutor(new Interpolator());
private Set<String> locationList = new HashSet<String>();
public Log4J2NacosLogging() {
String location = getLocation(NACOS_LOG4J2_LOCATION);
if (!StringUtils.isBlank(location)) {
locationList.add(location);
}
}
private String location = getLocation(NACOS_LOG4J2_LOCATION);
@Override
public void loadConfiguration() {
if (locationList.isEmpty()) {
return;
final LoggerContext loggerContext = (LoggerContext)LogManager.getContext(false);
final Configuration contextConfiguration = loggerContext.getConfiguration();
// load and start nacos configuration
Configuration configuration = loadConfiguration(loggerContext, location);
configuration.start();
// append loggers and appenders to contextConfiguration
Map<String, Appender> appenders = configuration.getAppenders();
for (Appender appender: appenders.values()) {
contextConfiguration.addAppender(appender);
}
List<String> configList = findConfig(getCurrentlySupportedConfigLocations());
if (configList != null) {
locationList.addAll(configList);
}
final List<AbstractConfiguration> configurations = new ArrayList<AbstractConfiguration>();
LoggerContext loggerContext = (LoggerContext)LogManager.getContext(false);
for (String location : locationList) {
try {
Configuration configuration = loadConfiguration(loggerContext, location);
if (configuration instanceof AbstractConfiguration) {
configurations.add((AbstractConfiguration)configuration);
}
} catch (Exception e) {
throw new IllegalStateException(
"Could not initialize Log4J2 Nacos logging from " + location, e);
Map<String, LoggerConfig> loggers = configuration.getLoggers();
for (String name : loggers.keySet()) {
if (name.startsWith(NACOS_LOGGER_PREFIX)) {
contextConfiguration.addLogger(name, loggers.get(name));
}
}
// since log4j 2.6
CompositeConfiguration compositeConfiguration = new CompositeConfiguration(configurations);
loggerContext.start(compositeConfiguration);
loggerContext.updateLoggers();
}
private Configuration loadConfiguration(LoggerContext loggerContext, String location) {
@ -119,43 +89,4 @@ public class Log4J2NacosLogging extends AbstractNacosLogging {
}
return new ConfigurationSource(stream, url);
}
private String[] getCurrentlySupportedConfigLocations() {
List<String> supportedConfigLocations = new ArrayList<String>();
if (ClassUtils.isPresent(YAML_PARSER_CLASS_NAME)) {
Collections.addAll(supportedConfigLocations, "log4j2.yaml", "log4j2.yml", "log4j2-test.yaml",
"log4j2-test.yml");
}
if (ClassUtils.isPresent(JSON_PARSER_CLASS_NAME)) {
Collections.addAll(supportedConfigLocations, "log4j2.json", "log4j2.jsn", "log4j2-test.json",
"log4j2-test.jsn");
}
supportedConfigLocations.add("log4j2.xml");
supportedConfigLocations.add("log4j2-test.xml");
return supportedConfigLocations.toArray(new String[supportedConfigLocations.size()]);
}
private List<String> findConfig(String[] locations) {
final String configLocationStr = this.strSubstitutor.replace(PropertiesUtil.getProperties()
.getStringProperty(CONFIGURATION_FILE_PROPERTY));
if (configLocationStr != null) {
return Arrays.asList(configLocationStr.split(","));
}
for (String location : locations) {
ClassLoader defaultClassLoader = ClassUtils.getDefaultClassLoader();
if (defaultClassLoader != null && defaultClassLoader.getResource(location) != null) {
List<String> list = new ArrayList<String>();
list.add("classpath:" + location);
return list;
}
}
return null;
}
}

View File

@ -0,0 +1,174 @@
/*
* 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.client.naming;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingMaintainService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.Service;
import com.alibaba.nacos.api.selector.AbstractSelector;
import com.alibaba.nacos.api.selector.ExpressionSelector;
import com.alibaba.nacos.api.selector.NoneSelector;
import com.alibaba.nacos.client.naming.net.NamingProxy;
import com.alibaba.nacos.client.naming.utils.InitUtils;
import com.alibaba.nacos.client.utils.StringUtils;
import java.util.Map;
import java.util.Properties;
/**
* @author liaochuntao
* @since 1.0.1
*/
@SuppressWarnings("PMD.ServiceOrDaoClassShouldEndWithImplRule")
public class NacosNamingMaintainService implements NamingMaintainService {
private String namespace;
private String endpoint;
private String serverList;
private NamingProxy serverProxy;
public NacosNamingMaintainService(String serverList) {
Properties properties = new Properties();
properties.setProperty(PropertyKeyConst.SERVER_ADDR, serverList);
init(properties);
}
public NacosNamingMaintainService(Properties properties) {
init(properties);
}
private void init(Properties properties) {
namespace = InitUtils.initNamespace(properties);
initServerAddr(properties);
InitUtils.initWebRootContext();
serverProxy = new NamingProxy(namespace, endpoint, serverList);
serverProxy.setProperties(properties);
}
private void initServerAddr(Properties properties) {
serverList = properties.getProperty(PropertyKeyConst.SERVER_ADDR);
endpoint = InitUtils.initEndpoint(properties);
if (StringUtils.isNotEmpty(endpoint)) {
serverList = "";
}
}
@Override
public void updateInstance(String serviceName, Instance instance) throws NacosException {
updateInstance(serviceName, Constants.DEFAULT_GROUP, instance);
}
@Override
public void updateInstance(String serviceName, String groupName, Instance instance) throws NacosException {
serverProxy.updateInstance(serviceName, groupName, instance);
}
@Override
public Service queryService(String serviceName) throws NacosException {
return queryService(serviceName, Constants.DEFAULT_GROUP);
}
@Override
public Service queryService(String serviceName, String groupName) throws NacosException {
return serverProxy.queryService(serviceName, groupName);
}
@Override
public void createService(String serviceName) throws NacosException {
createService(serviceName, Constants.DEFAULT_GROUP);
}
@Override
public void createService(String serviceName, String groupName) throws NacosException {
createService(serviceName, groupName, Constants.DEFAULT_PROTECT_THRESHOLD);
}
@Override
public void createService(String serviceName, String groupName, float protectThreshold) throws NacosException {
NoneSelector selector = new NoneSelector();
Service service = new Service();
service.setName(serviceName);
service.setGroupName(groupName);
service.setProtectThreshold(protectThreshold);
createService(service, selector);
}
@Override
public void createService(String serviceName, String groupName, float protectThreshold, String expression) throws NacosException {
Service service = new Service();
service.setName(serviceName);
service.setGroupName(groupName);
service.setProtectThreshold(protectThreshold);
ExpressionSelector selector = new ExpressionSelector();
selector.setExpression(expression);
createService(service, selector);
}
@Override
public void createService(Service service, AbstractSelector selector) throws NacosException {
serverProxy.createService(service, selector);
}
@Override
public boolean deleteService(String serviceName) throws NacosException {
return deleteService(serviceName, Constants.DEFAULT_GROUP);
}
@Override
public boolean deleteService(String serviceName, String groupName) throws NacosException {
return serverProxy.deleteService(serviceName, groupName);
}
@Override
public void updateService(String serviceName, String groupName, float protectThreshold) throws NacosException {
Service service = new Service();
service.setName(serviceName);
service.setGroupName(groupName);
service.setProtectThreshold(protectThreshold);
updateService(service, new NoneSelector());
}
@Override
public void updateService(String serviceName, String groupName, float protectThreshold, Map<String, String> metadata) throws NacosException {
Service service = new Service();
service.setName(serviceName);
service.setGroupName(groupName);
service.setProtectThreshold(protectThreshold);
service.setMetadata(metadata);
updateService(service, new NoneSelector());
}
@Override
public void updateService(Service service, AbstractSelector selector) throws NacosException {
serverProxy.updateService(service, selector);
}
}

View File

@ -16,7 +16,6 @@
package com.alibaba.nacos.client.naming;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.SystemPropertyKeyConst;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
@ -26,7 +25,6 @@ import com.alibaba.nacos.api.naming.pojo.ListView;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import com.alibaba.nacos.api.naming.utils.NamingUtils;
import com.alibaba.nacos.api.selector.AbstractSelector;
import com.alibaba.nacos.client.identify.CredentialService;
import com.alibaba.nacos.client.naming.beat.BeatInfo;
import com.alibaba.nacos.client.naming.beat.BeatReactor;
import com.alibaba.nacos.client.naming.core.Balancer;
@ -34,19 +32,13 @@ import com.alibaba.nacos.client.naming.core.EventDispatcher;
import com.alibaba.nacos.client.naming.core.HostReactor;
import com.alibaba.nacos.client.naming.net.NamingProxy;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.alibaba.nacos.client.naming.utils.InitUtils;
import com.alibaba.nacos.client.naming.utils.UtilAndComs;
import com.alibaba.nacos.client.utils.LogUtils;
import com.alibaba.nacos.client.utils.ParamUtil;
import com.alibaba.nacos.client.utils.StringUtils;
import com.alibaba.nacos.client.utils.TemplateUtils;
import com.alibaba.nacos.client.utils.*;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.math.NumberUtils;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.Callable;
import java.util.*;
/**
* @author nkorange
@ -87,10 +79,9 @@ public class NacosNamingService implements NamingService {
}
private void init(Properties properties) {
serverList = properties.getProperty(PropertyKeyConst.SERVER_ADDR);
initNamespace(properties);
initEndpoint(properties);
initWebRootContext();
namespace = InitUtils.initNamespace(properties);
initServerAddr(properties);
InitUtils.initWebRootContext();
initCacheDir();
initLogName(properties);
@ -130,6 +121,14 @@ public class NacosNamingService implements NamingService {
return loadCacheAtStart;
}
private void initServerAddr(Properties properties) {
serverList = properties.getProperty(PropertyKeyConst.SERVER_ADDR);
endpoint = InitUtils.initEndpoint(properties);
if (StringUtils.isNotEmpty(endpoint)) {
serverList = "";
}
}
private void initLogName(Properties properties) {
logName = System.getProperty(UtilAndComs.NACOS_NAMING_LOG_NAME);
if (StringUtils.isEmpty(logName)) {
@ -149,104 +148,6 @@ public class NacosNamingService implements NamingService {
}
}
private void initEndpoint(final Properties properties) {
if (properties == null) {
return;
}
//这里通过 dubbo/sca 侧来初始化默认传入的是 true
boolean isUseEndpointParsingRule = Boolean.valueOf(properties.getProperty(PropertyKeyConst.IS_USE_ENDPOINT_PARSING_RULE, ParamUtil.USE_ENDPOINT_PARSING_RULE_DEFAULT_VALUE));
String endpointUrl;
if (isUseEndpointParsingRule) {
endpointUrl = ParamUtil.parsingEndpointRule(properties.getProperty(PropertyKeyConst.ENDPOINT));
if (com.alibaba.nacos.client.utils.StringUtils.isNotBlank(endpointUrl)) {
serverList = "";
}
} else {
endpointUrl = properties.getProperty(PropertyKeyConst.ENDPOINT);
}
if (StringUtils.isBlank(endpointUrl)) {
return;
}
String endpointPort = TemplateUtils.stringEmptyAndThenExecute(System.getenv(PropertyKeyConst.SystemEnv.ALIBABA_ALIWARE_ENDPOINT_PORT), new Callable<String>() {
@Override
public String call() {
return properties.getProperty(PropertyKeyConst.ENDPOINT_PORT);
}
});
endpointPort = TemplateUtils.stringEmptyAndThenExecute(endpointPort, new Callable<String>() {
@Override
public String call() {
return "8080";
}
});
endpoint = endpointUrl + ":" + endpointPort;
}
private void initNamespace(Properties properties) {
String tmpNamespace = null;
tmpNamespace = TemplateUtils.stringEmptyAndThenExecute(tmpNamespace, new Callable<String>() {
@Override
public String call() {
String namespace = System.getProperty(PropertyKeyConst.NAMESPACE);
LogUtils.NAMING_LOGGER.info("initializer namespace from System Property :" + namespace);
return namespace;
}
});
tmpNamespace = TemplateUtils.stringEmptyAndThenExecute(tmpNamespace, new Callable<String>() {
@Override
public String call() {
String namespace = System.getenv(PropertyKeyConst.SystemEnv.ALIBABA_ALIWARE_NAMESPACE);
LogUtils.NAMING_LOGGER.info("initializer namespace from System Environment :" + namespace);
return namespace;
}
});
tmpNamespace = TemplateUtils.stringEmptyAndThenExecute(tmpNamespace, new Callable<String>() {
@Override
public String call() {
String namespace = CredentialService.getInstance().getCredential().getTenantId();
LogUtils.NAMING_LOGGER.info("initializer namespace from Credential Module " + namespace);
return namespace;
}
});
if (StringUtils.isEmpty(tmpNamespace) && properties != null) {
tmpNamespace = properties.getProperty(PropertyKeyConst.NAMESPACE);
}
tmpNamespace = TemplateUtils.stringEmptyAndThenExecute(tmpNamespace, new Callable<String>() {
@Override
public String call() {
return UtilAndComs.DEFAULT_NAMESPACE_ID;
}
});
namespace = tmpNamespace;
}
private void initWebRootContext() {
// support the web context with ali-yun if the app deploy by EDAS
final String webContext = System.getProperty(SystemPropertyKeyConst.NAMING_WEB_CONTEXT);
TemplateUtils.stringNotEmptyAndThenExecute(webContext, new Runnable() {
@Override
public void run() {
UtilAndComs.WEB_CONTEXT = webContext.indexOf("/") > -1 ? webContext
: "/" + webContext;
UtilAndComs.NACOS_URL_BASE = UtilAndComs.WEB_CONTEXT + "/v1/ns";
UtilAndComs.NACOS_URL_INSTANCE = UtilAndComs.NACOS_URL_BASE + "/instance";
}
});
}
@Override
public void registerInstance(String serviceName, String ip, int port) throws NacosException {
registerInstance(serviceName, ip, port, Constants.DEFAULT_CLUSTER_NAME);

View File

@ -125,7 +125,7 @@ public class EventDispatcher {
if (!CollectionUtils.isEmpty(listeners)) {
for (EventListener listener : listeners) {
List<Instance> hosts = Collections.unmodifiableList(serviceInfo.getHosts());
listener.onEvent(new NamingEvent(serviceInfo.getName(), hosts));
listener.onEvent(new NamingEvent(serviceInfo.getName(), serviceInfo.getGroupName(), serviceInfo.getClusters(), hosts));
}
}

View File

@ -24,6 +24,7 @@ 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.ListView;
import com.alibaba.nacos.api.naming.pojo.Service;
import com.alibaba.nacos.api.selector.AbstractSelector;
import com.alibaba.nacos.api.selector.ExpressionSelector;
import com.alibaba.nacos.api.selector.SelectorType;
@ -170,7 +171,7 @@ public class NamingProxy {
NAMING_LOGGER.info("[REGISTER-SERVICE] {} registering service {} with instance: {}",
namespaceId, serviceName, instance);
final Map<String, String> params = new HashMap<String, String>(8);
final Map<String, String> params = new HashMap<String, String>(9);
params.put(CommonParams.NAMESPACE_ID, namespaceId);
params.put(CommonParams.SERVICE_NAME, serviceName);
params.put(CommonParams.GROUP_NAME, groupName);
@ -203,6 +204,84 @@ public class NamingProxy {
reqAPI(UtilAndComs.NACOS_URL_INSTANCE, params, HttpMethod.DELETE);
}
public void updateInstance(String serviceName, String groupName, Instance instance) throws NacosException {
NAMING_LOGGER.info("[UPDATE-SERVICE] {} update service {} with instance: {}",
namespaceId, serviceName, instance);
final Map<String, String> params = new HashMap<String, String>(8);
params.put(CommonParams.NAMESPACE_ID, namespaceId);
params.put(CommonParams.SERVICE_NAME, serviceName);
params.put(CommonParams.GROUP_NAME, groupName);
params.put(CommonParams.CLUSTER_NAME, instance.getClusterName());
params.put("ip", instance.getIp());
params.put("port", String.valueOf(instance.getPort()));
params.put("weight", String.valueOf(instance.getWeight()));
params.put("ephemeral", String.valueOf(instance.isEphemeral()));
params.put("metadata", JSON.toJSONString(instance.getMetadata()));
reqAPI(UtilAndComs.NACOS_URL_INSTANCE, params, HttpMethod.PUT);
}
public Service queryService(String serviceName, String groupName) throws NacosException {
NAMING_LOGGER.info("[QUERY-SERVICE] {} query service : {}, {}",
namespaceId, serviceName, groupName);
final Map<String, String> params = new HashMap<String, String>(3);
params.put(CommonParams.NAMESPACE_ID, namespaceId);
params.put(CommonParams.SERVICE_NAME, serviceName);
params.put(CommonParams.GROUP_NAME, groupName);
String result = reqAPI(UtilAndComs.NACOS_URL_SERVICE, params, HttpMethod.GET);
JSONObject jsonObject = JSON.parseObject(result);
return jsonObject.toJavaObject(Service.class);
}
public void createService(Service service, AbstractSelector selector) throws NacosException {
NAMING_LOGGER.info("[CREATE-SERVICE] {} creating service : {}",
namespaceId, service);
final Map<String, String> params = new HashMap<String, String>(6);
params.put(CommonParams.NAMESPACE_ID, namespaceId);
params.put(CommonParams.SERVICE_NAME, service.getName());
params.put(CommonParams.GROUP_NAME, service.getGroupName());
params.put("protectThreshold", String.valueOf(service.getProtectThreshold()));
params.put("metadata", JSON.toJSONString(service.getMetadata()));
params.put("selector", JSON.toJSONString(selector));
reqAPI(UtilAndComs.NACOS_URL_SERVICE, params, HttpMethod.POST);
}
public boolean deleteService(String serviceName, String groupName) throws NacosException {
NAMING_LOGGER.info("[DELETE-SERVICE] {} deleting service : {} with groupName : {}",
namespaceId, serviceName, groupName);
final Map<String, String> params = new HashMap<String, String>(6);
params.put(CommonParams.NAMESPACE_ID, namespaceId);
params.put(CommonParams.SERVICE_NAME, serviceName);
params.put(CommonParams.GROUP_NAME, groupName);
String result = reqAPI(UtilAndComs.NACOS_URL_SERVICE, params, HttpMethod.DELETE);
NAMING_LOGGER.info(result);
return "ok".equals(result);
}
public void updateService(Service service, AbstractSelector selector) throws NacosException {
NAMING_LOGGER.info("[UPDATE-SERVICE] {} updating service : {}",
namespaceId, service);
final Map<String, String> params = new HashMap<String, String>(6);
params.put(CommonParams.NAMESPACE_ID, namespaceId);
params.put(CommonParams.SERVICE_NAME, service.getName());
params.put(CommonParams.GROUP_NAME, service.getGroupName());
params.put("protectThreshold", String.valueOf(service.getProtectThreshold()));
params.put("metadata", JSON.toJSONString(service.getMetadata()));
params.put("selector", JSON.toJSONString(selector));
reqAPI(UtilAndComs.NACOS_URL_SERVICE, params, HttpMethod.PUT);
}
public String queryList(String serviceName, String clusters, int udpPort, boolean healthyOnly)
throws NacosException {

View File

@ -0,0 +1,135 @@
/*
* 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.client.naming.utils;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.SystemPropertyKeyConst;
import com.alibaba.nacos.client.identify.CredentialService;
import com.alibaba.nacos.client.naming.utils.UtilAndComs;
import com.alibaba.nacos.client.utils.LogUtils;
import com.alibaba.nacos.client.utils.ParamUtil;
import com.alibaba.nacos.client.utils.StringUtils;
import com.alibaba.nacos.client.utils.TemplateUtils;
import java.util.Properties;
import java.util.concurrent.Callable;
/**
* @author liaochuntao
*/
public class InitUtils {
public static final String initNamespace(Properties properties) {
String tmpNamespace = null;
tmpNamespace = TemplateUtils.stringEmptyAndThenExecute(tmpNamespace, new Callable<String>() {
@Override
public String call() {
String namespace = System.getProperty(PropertyKeyConst.NAMESPACE);
LogUtils.NAMING_LOGGER.info("initializer namespace from System Property :" + namespace);
return namespace;
}
});
tmpNamespace = TemplateUtils.stringEmptyAndThenExecute(tmpNamespace, new Callable<String>() {
@Override
public String call() {
String namespace = System.getenv(PropertyKeyConst.SystemEnv.ALIBABA_ALIWARE_NAMESPACE);
LogUtils.NAMING_LOGGER.info("initializer namespace from System Environment :" + namespace);
return namespace;
}
});
tmpNamespace = TemplateUtils.stringEmptyAndThenExecute(tmpNamespace, new Callable<String>() {
@Override
public String call() {
String namespace = CredentialService.getInstance().getCredential().getTenantId();
LogUtils.NAMING_LOGGER.info("initializer namespace from Credential Module " + namespace);
return namespace;
}
});
if (com.alibaba.nacos.client.utils.StringUtils.isEmpty(tmpNamespace) && properties != null) {
tmpNamespace = properties.getProperty(PropertyKeyConst.NAMESPACE);
}
tmpNamespace = TemplateUtils.stringEmptyAndThenExecute(tmpNamespace, new Callable<String>() {
@Override
public String call() {
return UtilAndComs.DEFAULT_NAMESPACE_ID;
}
});
return tmpNamespace;
}
public static final void initWebRootContext() {
// support the web context with ali-yun if the app deploy by EDAS
final String webContext = System.getProperty(SystemPropertyKeyConst.NAMING_WEB_CONTEXT);
TemplateUtils.stringNotEmptyAndThenExecute(webContext, new Runnable() {
@Override
public void run() {
UtilAndComs.WEB_CONTEXT = webContext.indexOf("/") > -1 ? webContext
: "/" + webContext;
UtilAndComs.NACOS_URL_BASE = UtilAndComs.WEB_CONTEXT + "/v1/ns";
UtilAndComs.NACOS_URL_INSTANCE = UtilAndComs.NACOS_URL_BASE + "/instance";
}
});
}
public static final String initEndpoint(final Properties properties) {
if (properties == null) {
return "";
}
// 是否开启域名解析规则
boolean isUseEndpointParsingRule = Boolean.valueOf(properties.getProperty(PropertyKeyConst.IS_USE_ENDPOINT_PARSING_RULE, ParamUtil.USE_ENDPOINT_PARSING_RULE_DEFAULT_VALUE));
String endpointUrl;
if (isUseEndpointParsingRule) {
// 获取设置的域名信息
endpointUrl = ParamUtil.parsingEndpointRule(properties.getProperty(PropertyKeyConst.ENDPOINT));
if (com.alibaba.nacos.client.utils.StringUtils.isNotBlank(endpointUrl)) {
return "";
}
} else {
endpointUrl = properties.getProperty(PropertyKeyConst.ENDPOINT);
}
if (StringUtils.isBlank(endpointUrl)) {
return "";
}
String endpointPort = TemplateUtils.stringEmptyAndThenExecute(System.getenv(PropertyKeyConst.SystemEnv.ALIBABA_ALIWARE_ENDPOINT_PORT), new Callable<String>() {
@Override
public String call() {
return properties.getProperty(PropertyKeyConst.ENDPOINT_PORT);
}
});
endpointPort = TemplateUtils.stringEmptyAndThenExecute(endpointPort, new Callable<String>() {
@Override
public String call() {
return "8080";
}
});
return endpointUrl + ":" + endpointPort;
}
}

View File

@ -28,6 +28,8 @@ public class UtilAndComs {
public static String NACOS_URL_INSTANCE = NACOS_URL_BASE + "/instance";
public static String NACOS_URL_SERVICE = NACOS_URL_BASE + "/service";
public static final String ENCODING = "UTF-8";
public static final String ENV_LIST_KEY = "envList";

View File

@ -45,5 +45,8 @@
additivity="false">
<AppenderRef ref="NAMING_LOG_FILE"/>
</Logger>
<Root level="INFO">
<AppenderRef ref="CONFIG_LOG_FILE"/>
</Root>
</Loggers>
</Configuration>

View File

@ -0,0 +1,62 @@
package com.alibaba.nacos.client;
import com.alibaba.nacos.client.utils.StringUtils;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collection;
import static org.junit.Assert.*;
import static com.alibaba.nacos.client.utils.StringUtils.*;
public class StringUtilsTest {
@Test
public void testisNotBlank() {
assertTrue(isNotBlank("foo"));
assertFalse(isNotBlank(" "));
assertFalse(isNotBlank(null));
}
@Test
public void testIsNotEmpty() {
assertFalse(isNotEmpty(""));
assertTrue(isNotEmpty("foo"));
}
@Test
public void testDefaultIfEmpty() {
assertEquals("foo", defaultIfEmpty("", "foo"));
assertEquals("bar", defaultIfEmpty("bar", "foo"));
}
@Test
public void testEquals() {
assertTrue(StringUtils.equals("foo", "foo"));
assertFalse(StringUtils.equals("bar", "foo"));
assertFalse(StringUtils.equals(" ", "foo"));
assertFalse(StringUtils.equals("foo", null));
}
@Test
public void testSubstringBetween() {
assertNull(substringBetween(null, null, null));
assertNull(substringBetween("", "foo", ""));
assertNull(substringBetween("foo", "bar", "baz"));
assertEquals("", substringBetween("foo", "foo", ""));
}
@Test
public void testJoin() {
assertNull(join(null, ""));
Collection collection = new ArrayList();
collection.add("foo");
collection.add("bar");
assertEquals("foo,bar", join(collection, ","));
}
}

View File

@ -0,0 +1,48 @@
package com.alibaba.nacos.client.naming;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Service;
import com.alibaba.nacos.api.selector.ExpressionSelector;
import com.alibaba.nacos.api.selector.NoneSelector;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import static com.alibaba.nacos.client.utils.LogUtils.NAMING_LOGGER;
public class NacosNamingServiceTest {
private NamingService nameService;
@Before
public void before() throws NacosException {
Properties properties = new Properties();
properties.put(PropertyKeyConst.SERVER_ADDR, "11.160.165.126:8848");
nameService = NacosFactory.createNamingService(properties);
}
@Test
public void deleteService() {
}
@Test
public void updateService() {
}
@Test
public void registerInstance() throws NacosException {
nameService.registerInstance("nacos-api", "127.0.0.1", 8009);
}
}

View File

@ -1,60 +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.common.util;
/**
* @author <a href="mailto:huangxiaoyu1018@gmail.com">hxy1991</a>
* @since 0.9.0
*/
public class ClassUtils {
public static ClassLoader getDefaultClassLoader() {
try {
return Thread.currentThread().getContextClassLoader();
} catch (Throwable t) {
// ignore
}
ClassLoader classLoader = ClassUtils.class.getClassLoader();
if (classLoader != null) {
return classLoader;
}
try {
return ClassLoader.getSystemClassLoader();
} catch (Throwable t) {
// ignore
}
return null;
}
public static boolean isPresent(String className) {
ClassLoader defaultClassLoader = getDefaultClassLoader();
try {
if (defaultClassLoader != null) {
defaultClassLoader.loadClass(className);
} else {
Class.forName(className);
}
return true;
} catch (Throwable t) {
return false;
}
}
}

View File

@ -100,7 +100,7 @@ public class DumpService {
log.warn("clearConfigHistory start");
if (ServerListService.isFirstIp()) {
try {
Timestamp startTime = getBeforeStamp(TimeUtils.getCurrentTime(), 24 * 30);
Timestamp startTime = getBeforeStamp(TimeUtils.getCurrentTime(), 24 * getRetentionDays());
int totalCount = persistService.findConfigHistoryCountByTime(startTime);
if (totalCount > 0) {
int pageSize = 1000;
@ -278,6 +278,25 @@ public class DumpService {
return isQuickStart;
}
private int getRetentionDays() {
String val = env.getProperty("nacos.config.retention.days");
if (null == val) {
return retentionDays;
}
int tmp = 0;
try {
tmp = Integer.parseInt(val);
if (tmp > 0) {
retentionDays = tmp;
}
} catch (NumberFormatException nfe) {
fatalLog.error("read nacos.config.retention.days wrong", nfe);
}
return retentionDays;
}
public void dump(String dataId, String group, String tenant, String tag, long lastModified, String handleIp) {
dump(dataId, group, tenant, tag, lastModified, handleIp, false);
}
@ -400,4 +419,5 @@ public class DumpService {
Boolean isQuickStart = false;
private int retentionDays = 30;
}

View File

@ -0,0 +1,24 @@
package com.alibaba.nacos.config.server.service.dump;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import static org.junit.Assert.*;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@WebAppConfiguration
public class DumpServiceTest {
@Autowired
DumpService service;
@Test
public void init() {
service.init();
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

View File

@ -104,6 +104,7 @@
<version>2.1.1.RELEASE</version>
<configuration>
<mainClass>com.alibaba.nacos.Nacos</mainClass>
<layout>ZIP</layout>
</configuration>
<executions>
<execution>

View File

@ -468,7 +468,7 @@ class NewConfig extends React.Component {
message: locale.moreAdvanced,
},
{
max: 127,
maxLength: 127,
message: locale.groupNotEmpty,
},
{ validator: this.validateChart.bind(this) },

View File

@ -67,7 +67,7 @@ class EditInstanceDialog extends React.Component {
port,
ephemeral,
weight,
enable: enabled,
enabled,
metadata: replaceEnter(METADATA_SEPARATOR)(metadataText),
},
dataType: 'text',

View File

@ -26,6 +26,7 @@ class InstanceTable extends React.Component {
locale: PropTypes.object,
clusterName: PropTypes.string,
serviceName: PropTypes.string,
groupName: PropTypes.string,
};
constructor(props) {
@ -52,7 +53,7 @@ class InstanceTable extends React.Component {
}
getInstanceList() {
const { clusterName, serviceName } = this.props;
const { clusterName, serviceName, groupName } = this.props;
if (!clusterName) return;
const { pageSize, pageNum } = this.state;
request({
@ -60,6 +61,7 @@ class InstanceTable extends React.Component {
data: {
serviceName,
clusterName,
groupName,
pageSize,
pageNo: pageNum,
},
@ -87,7 +89,7 @@ class InstanceTable extends React.Component {
port,
ephemeral,
weight,
enable: !enabled,
enabled: !enabled,
metadata: JSON.stringify(metadata),
},
dataType: 'text',

View File

@ -93,7 +93,7 @@ class ServiceDetail extends React.Component {
render() {
const { locale = {} } = this.props;
const { serviceName, loading, service = {}, clusters } = this.state;
const { serviceName, groupName, loading, service = {}, clusters } = this.state;
const { metadata = {}, selector = {} } = service;
const metadataText = processMetaData(METADATA_ENTER)(metadata);
return (
@ -169,7 +169,11 @@ class ServiceDetail extends React.Component {
</Button>
}
>
<InstanceTable clusterName={cluster.name} serviceName={serviceName} />
<InstanceTable
clusterName={cluster.name}
serviceName={serviceName}
groupName={groupName}
/>
</Card>
))}
</Loading>

File diff suppressed because it is too large Load Diff

View File

@ -14,7 +14,7 @@ rem limitations under the License.
if not exist "%JAVA_HOME%\bin\java.exe" echo Please set the JAVA_HOME variable in your environment, We need java(x64)! jdk8 or later is better! & EXIT /B 1
set "JAVA=%JAVA_HOME%\bin\java.exe"
setlocal
setlocal enabledelayedexpansion
set BASE_DIR=%~dp0
rem added double quotation marks to avoid the issue caused by the folder names containing spaces.
@ -24,20 +24,45 @@ set BASE_DIR="%BASE_DIR:~0,-5%"
set DEFAULT_SEARCH_LOCATIONS="classpath:/,classpath:/config/,file:./,file:./config/"
set CUSTOM_SEARCH_LOCATIONS=%DEFAULT_SEARCH_LOCATIONS%,file:%BASE_DIR%/conf/
set MODE="standalone"
set FUNCTION_MODE="all"
set MODE_INDEX=-1
set FUNCTION_MODE_INDEX=-1
set i=0
for %%a in (%*) do (
if "%%a" == "-m" ( set /a MODE_INDEX=!i!+1 )
if "%%a" == "-f" ( set /a FUNCTION_MODE_INDEX=!i!+1 )
set /a i+=1
)
if not "%2" == "cluster" (
set i=0
for %%a in (%*) do (
if %MODE_INDEX% == !i! ( set MODE="%%a" )
if %FUNCTION_MODE_INDEX% == !i! ( set FUNCTION_MODE="%%a" )
set /a i+=1
)
if %MODE% == "standalone" (
set "JAVA_OPT=%JAVA_OPT% -Xms512m -Xmx512m -Xmn256m"
set "JAVA_OPT=%JAVA_OPT% -Dnacos.standalone=true"
) else (
) else (
set "JAVA_OPT=%JAVA_OPT% -server -Xms2g -Xmx2g -Xmn1g -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=320m"
set "JAVA_OPT=%JAVA_OPT% -XX:-OmitStackTraceInFastThrow XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=%BASE_DIR%\logs\java_heapdump.hprof"
set "JAVA_OPT=%JAVA_OPT% -XX:-UseLargePages"
)
)
set "JAVA_OPT=%JAVA_OPT% -Xbootclasspath/a:%BASE_DIR%\plugins\cmdb"
if %FUNCTION_MODE% == "config" (
set "JAVA_OPT=%JAVA_OPT% -Dnacos.functionMode=config"
)
if %FUNCTION_MODE% == "naming" (
set "JAVA_OPT=%JAVA_OPT% -Dnacos.functionMode=naming"
)
set "JAVA_OPT=%JAVA_OPT% -Xbootclasspath/a:%BASE_DIR%\plugins\cmdb:%BASE_DIR%\plugins\mysql"
set "JAVA_OPT=%JAVA_OPT% -Dnacos.home=%BASE_DIR%"
set "JAVA_OPT=%JAVA_OPT% -jar %BASE_DIR%\target\nacos-server.jar"
set "JAVA_OPT=%JAVA_OPT% -Dloader.path=%BASE_DIR%/plugins/health -jar %BASE_DIR%\target\nacos-server.jar"
set "JAVA_OPT=%JAVA_OPT% --spring.config.location=%CUSTOM_SEARCH_LOCATIONS%"
set "JAVA_OPT=%JAVA_OPT% --logging.config=%BASE_DIR%/conf/nacos-logback.xml"

View File

@ -102,7 +102,7 @@ else
fi
JAVA_OPT="${JAVA_OPT} -Dnacos.home=${BASE_DIR}"
JAVA_OPT="${JAVA_OPT} -jar ${BASE_DIR}/target/nacos-server.jar"
JAVA_OPT="${JAVA_OPT} -Dloader.path=${BASE_DIR}/plugins/health -jar ${BASE_DIR}/target/nacos-server.jar"
JAVA_OPT="${JAVA_OPT} ${JAVA_OPT_EXT}"
JAVA_OPT="${JAVA_OPT} --spring.config.location=${CUSTOM_SEARCH_LOCATIONS}"
JAVA_OPT="${JAVA_OPT} --logging.config=${BASE_DIR}/conf/nacos-logback.xml"

View File

@ -17,7 +17,6 @@ package com.alibaba.nacos.naming.consistency.ephemeral.distro;
import com.alibaba.nacos.naming.cluster.ServerListManager;
import com.alibaba.nacos.naming.cluster.servers.Server;
import com.alibaba.nacos.naming.cluster.servers.ServerChangeListener;
import com.alibaba.nacos.naming.cluster.transport.Serializer;
import com.alibaba.nacos.naming.consistency.Datum;
import com.alibaba.nacos.naming.consistency.KeyBuilder;
@ -43,7 +42,7 @@ import java.util.concurrent.ConcurrentHashMap;
*/
@Component
@DependsOn("serverListManager")
public class DataSyncer implements ServerChangeListener {
public class DataSyncer {
@Autowired
private DataStore dataStore;
@ -62,11 +61,8 @@ public class DataSyncer implements ServerChangeListener {
private Map<String, String> taskMap = new ConcurrentHashMap<>();
private List<Server> servers;
@PostConstruct
public void init() {
serverListManager.listen(this);
startTimedSync();
}
@ -97,7 +93,7 @@ public class DataSyncer implements ServerChangeListener {
public void run() {
try {
if (servers == null || servers.isEmpty()) {
if (getServers() == null || getServers().isEmpty()) {
Loggers.SRV_LOG.warn("try to sync data but server list is empty.");
return;
}
@ -148,7 +144,7 @@ public class DataSyncer implements ServerChangeListener {
Server server = new Server();
server.setIp(syncTask.getTargetServer().split(":")[0]);
server.setServePort(Integer.parseInt(syncTask.getTargetServer().split(":")[1]));
if (!servers.contains(server)) {
if (!getServers().contains(server)) {
// if server is no longer in healthy server list, ignore this task:
return;
}
@ -167,6 +163,11 @@ public class DataSyncer implements ServerChangeListener {
public void run() {
try {
if (Loggers.EPHEMERAL.isDebugEnabled()) {
Loggers.EPHEMERAL.debug("server list is: {}", getServers());
}
// send local timestamps to other servers:
Map<String, String> keyChecksums = new HashMap<>(64);
for (String key : dataStore.keys()) {
@ -185,7 +186,7 @@ public class DataSyncer implements ServerChangeListener {
Loggers.EPHEMERAL.debug("sync checksums: {}", keyChecksums);
}
for (Server member : servers) {
for (Server member : getServers()) {
if (NetUtils.localServer().equals(member.getKey())) {
continue;
}
@ -198,20 +199,10 @@ public class DataSyncer implements ServerChangeListener {
}
public List<Server> getServers() {
return servers;
return serverListManager.getHealthyServers();
}
public String buildKey(String key, String targetServer) {
return key + UtilsAndCommons.CACHE_KEY_SPLITER + targetServer;
}
@Override
public void onChangeServerList(List<Server> latestMembers) {
}
@Override
public void onChangeHealthyServerList(List<Server> healthServers) {
servers = healthServers;
}
}

View File

@ -58,13 +58,12 @@ public class CatalogController {
@RequestMapping(value = "/service")
public JSONObject serviceDetail(HttpServletRequest request) throws Exception {
String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID,
Constants.DEFAULT_NAMESPACE_ID);
String serviceName = WebUtils.required(request, CommonParams.SERVICE_NAME);
com.alibaba.nacos.naming.core.Service detailedService = serviceManager.getService(namespaceId, serviceName);
Service detailedService = serviceManager.getService(namespaceId, serviceName);
if (detailedService == null) {
throw new NacosException(NacosException.NOT_FOUND, "serivce " + serviceName + " is not found!");
throw new NacosException(NacosException.NOT_FOUND, "service " + serviceName + " is not found!");
}
JSONObject detailView = new JSONObject();
@ -80,7 +79,7 @@ public class CatalogController {
List<Cluster> clusters = new ArrayList<>();
for (Cluster cluster : detailedService.getClusterMap().values()) {
for (com.alibaba.nacos.naming.core.Cluster cluster : detailedService.getClusterMap().values()) {
Cluster clusterView = new Cluster();
clusterView.setName(cluster.getName());
clusterView.setHealthChecker(cluster.getHealthChecker());
@ -88,7 +87,7 @@ public class CatalogController {
clusterView.setUseIPPort4Check(cluster.isUseIPPort4Check());
clusterView.setDefaultPort(cluster.getDefaultPort());
clusterView.setDefaultCheckPort(cluster.getDefaultCheckPort());
clusterView.setServiceName(serviceName);
clusterView.setServiceName(cluster.getService().getName());
clusters.add(clusterView);
}
@ -141,7 +140,7 @@ public class CatalogController {
}
@RequestMapping(value = "/services", method = RequestMethod.GET)
public Object listDetail(HttpServletRequest request) throws Exception {
public Object listDetail(HttpServletRequest request) {
boolean withInstances = Boolean.parseBoolean(WebUtils.optional(request, "withInstances", "true"));
@ -248,7 +247,7 @@ public class CatalogController {
return ipAddressInfos;
}
private JSONObject serviceList(HttpServletRequest request) throws Exception {
private JSONObject serviceList(HttpServletRequest request) {
String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID,
Constants.DEFAULT_NAMESPACE_ID);

View File

@ -25,6 +25,7 @@ import com.alibaba.nacos.naming.core.Cluster;
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.HealthCheckType;
import com.alibaba.nacos.naming.misc.Loggers;
import com.alibaba.nacos.naming.misc.UtilsAndCommons;
import org.apache.commons.lang3.BooleanUtils;
@ -67,9 +68,7 @@ public class ClusterController {
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();
cluster.setName(clusterName);
cluster.setService(service);
cluster = new Cluster(clusterName, service);
}
cluster.setDefCkport(NumberUtils.toInt(checkPort));
@ -77,23 +76,12 @@ public class ClusterController {
JSONObject healthCheckObj = JSON.parseObject(healthChecker);
AbstractHealthChecker abstractHealthChecker;
switch (healthCheckObj.getString("type")) {
case AbstractHealthChecker.Tcp.TYPE:
abstractHealthChecker = JSON.parseObject(healthChecker, AbstractHealthChecker.Tcp.class);
break;
case AbstractHealthChecker.Http.TYPE:
abstractHealthChecker = JSON.parseObject(healthChecker, AbstractHealthChecker.Http.class);
break;
case AbstractHealthChecker.Mysql.TYPE:
abstractHealthChecker = JSON.parseObject(healthChecker, AbstractHealthChecker.Mysql.class);
break;
case AbstractHealthChecker.None.TYPE:
abstractHealthChecker = JSON.parseObject(healthChecker, AbstractHealthChecker.None.class);
break;
default:
throw new NacosException(NacosException.INVALID_PARAM, "unknown health check type:" + healthChecker);
String type = healthCheckObj.getString("type");
Class<AbstractHealthChecker> healthCheckClass = HealthCheckType.ofHealthCheckerClass(type);
if(healthCheckClass == null){
throw new NacosException(NacosException.INVALID_PARAM, "unknown health check type:" + healthChecker);
}
abstractHealthChecker = JSON.parseObject(healthChecker, healthCheckClass);
cluster.setHealthChecker(abstractHealthChecker);
cluster.setMetadata(UtilsAndCommons.parseMetadata(metadata));
@ -107,4 +95,5 @@ public class ClusterController {
return "ok";
}
}

View File

@ -18,6 +18,7 @@ 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.api.naming.pojo.AbstractHealthChecker;
import com.alibaba.nacos.core.utils.WebUtils;
import com.alibaba.nacos.naming.boot.RunningConfig;
import com.alibaba.nacos.naming.core.DistroMapper;
@ -32,11 +33,16 @@ import com.alibaba.nacos.naming.web.CanDistro;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Health status related operation controller
@ -110,4 +116,20 @@ public class HealthController {
return "ok";
}
@ResponseBody
@RequestMapping(value = "checkers", method = RequestMethod.GET)
public ResponseEntity checkers() {
List<Class> classes = HealthCheckType.getLoadedHealthCheckerClasses();
Map<String, AbstractHealthChecker> checkerMap = new HashMap<>(8);
for (Class clazz : classes) {
try {
AbstractHealthChecker checker = (AbstractHealthChecker) clazz.newInstance();
checkerMap.put(checker.getType(), checker);
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
}
return ResponseEntity.ok(checkerMap);
}
}

View File

@ -339,7 +339,15 @@ public class InstanceController {
cluster = WebUtils.optional(request, "cluster", UtilsAndCommons.DEFAULT_CLUSTER_NAME);
}
boolean healthy = BooleanUtils.toBoolean(WebUtils.optional(request, "healthy", "true"));
boolean enabled = BooleanUtils.toBoolean(WebUtils.optional(request, "enable", "true"));
String enabledString = WebUtils.optional(request, "enabled", StringUtils.EMPTY);
boolean enabled;
if (StringUtils.isBlank(enabledString)) {
enabled = BooleanUtils.toBoolean(WebUtils.optional(request, "enable", "true"));
} else {
enabled = BooleanUtils.toBoolean(enabledString);
}
boolean ephemeral = BooleanUtils.toBoolean(WebUtils.optional(request, "ephemeral",
String.valueOf(switchDomain.isDefaultInstanceEphemeral())));
@ -469,6 +477,12 @@ public class InstanceController {
}
for (Instance instance : ips) {
// remove disabled instance:
if (!instance.isEnabled()) {
continue;
}
JSONObject ipObj = new JSONObject();
ipObj.put("ip", instance.getIp());

View File

@ -20,15 +20,18 @@ import com.alibaba.nacos.naming.healthcheck.HealthCheckReactor;
import com.alibaba.nacos.naming.healthcheck.HealthCheckStatus;
import com.alibaba.nacos.naming.healthcheck.HealthCheckTask;
import com.alibaba.nacos.naming.misc.Loggers;
import com.alibaba.nacos.naming.misc.UtilsAndCommons;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.springframework.util.Assert;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author nkorange
* @author jifengnan 2019-04-26
*/
public class Cluster extends com.alibaba.nacos.api.naming.pojo.Cluster implements Cloneable {
@ -62,8 +65,19 @@ public class Cluster extends com.alibaba.nacos.api.naming.pojo.Cluster implement
public Cluster() {
}
public Cluster(String clusterName) {
/**
* Create a cluster.
* <p>the cluster name cannot be null, and only the arabic numerals, letters and endashes are allowed.
*
* @param clusterName the cluster name
* @param service the service to which the current cluster belongs
* @throws IllegalArgumentException the service is null, or the cluster name is null, or the cluster name is illegal
* @author jifengnan 2019-04-26
* @since 1.0.1
*/
public Cluster(String clusterName, Service service) {
this.setName(clusterName);
this.service = service;
validate();
}
@ -113,19 +127,50 @@ public class Cluster extends com.alibaba.nacos.api.naming.pojo.Cluster implement
return service;
}
/**
* Replace the service for the current cluster.
* <p>Deprecated because the service shouldn't be replaced.
* (the service fields can be changed, but the service A shouldn't be replaced to service B).
* If the service of a cluster is required to replace, actually, a new cluster is required.
*
* @param service the new service
*/
@Deprecated
public void setService(Service service) {
this.service = service;
this.setServiceName(service.getName());
}
/**
* this method has been deprecated, the service name shouldn't be changed.
*
* @param serviceName the service name
* @author jifengnan 2019-04-26
* @since 1.0.1
*/
@Deprecated
@Override
public void setServiceName(String serviceName) {
super.setServiceName(serviceName);
}
/**
* Get the service name of the current cluster.
* <p>Note that the returned service name is not the name which set by {@link #setServiceName(String)},
* but the name of the service to which the current cluster belongs.
*
* @return the service name of the current cluster.
*/
@Override
public String getServiceName() {
return service.getName();
}
@Override
public Cluster clone() throws CloneNotSupportedException {
super.clone();
Cluster cluster = new Cluster();
Cluster cluster = new Cluster(this.getName(), service);
cluster.setHealthChecker(getHealthChecker().clone());
cluster.setService(getService());
cluster.persistentInstances = new HashSet<Instance>();
cluster.persistentInstances = new HashSet<>();
cluster.checkTask = null;
cluster.metadata = new HashMap<>(metadata);
return cluster;
@ -263,16 +308,28 @@ public class Cluster extends com.alibaba.nacos.api.naming.pojo.Cluster implement
@Override
public int hashCode() {
return Objects.hash(getName());
return new HashCodeBuilder(17, 37)
.append(getName())
.append(service)
.toHashCode();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Cluster)) {
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
return getName().equals(((Cluster) obj).getName());
Cluster cluster = (Cluster) o;
return new EqualsBuilder()
.append(getName(), cluster.getName())
.append(service, cluster.service)
.isEquals();
}
public int getDefCkport() {
@ -330,7 +387,15 @@ public class Cluster extends com.alibaba.nacos.api.naming.pojo.Cluster implement
return persistentInstances.contains(ip) || ephemeralInstances.contains(ip);
}
/**
* validate the current cluster.
* <p>the cluster name cannot be null, and only the arabic numerals, letters and endashes are allowed.
*
* @throws IllegalArgumentException the service is null, or the cluster name is null, or the cluster name is illegal
*/
public void validate() {
Assert.notNull(getName(), "cluster name cannot be null");
Assert.notNull(service, "service cannot be null");
if (!getName().matches(CLUSTER_NAME_SYNTAX)) {
throw new IllegalArgumentException("cluster name can only have these characters: 0-9a-zA-Z-, current: " + getName());
}

View File

@ -51,6 +51,9 @@ public class Instance extends com.alibaba.nacos.api.naming.pojo.Instance impleme
public static final Pattern IP_PATTERN
= Pattern.compile("(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}):?(\\d{1,5})?");
public static final Pattern ONLY_DIGIT_AND_DOT
= Pattern.compile("(\\d|\\.)+");
public static final String SPLITER = "_";
public Instance() {
@ -296,10 +299,11 @@ public class Instance extends com.alibaba.nacos.api.naming.pojo.Instance impleme
}
public boolean validate() {
Matcher matcher = IP_PATTERN.matcher(getIp() + ":" + getPort());
if (!matcher.matches()) {
return false;
if (onlyContainsDigitAndDot()) {
Matcher matcher = IP_PATTERN.matcher(getIp() + ":" + getPort());
if (!matcher.matches()) {
return false;
}
}
if (getWeight() > MAX_WEIGHT_VALUE || getWeight() < MIN_WEIGHT_VALUE) {
@ -309,6 +313,11 @@ public class Instance extends com.alibaba.nacos.api.naming.pojo.Instance impleme
return true;
}
private boolean onlyContainsDigitAndDot() {
Matcher matcher = ONLY_DIGIT_AND_DOT.matcher(getIp());
return matcher.matches();
}
@Override
public int compareTo(Object o) {
if (!(o instanceof Instance)) {

View File

@ -215,8 +215,7 @@ public class Service extends com.alibaba.nacos.api.naming.pojo.Service implement
if (!clusterMap.containsKey(instance.getClusterName())) {
Loggers.SRV_LOG.warn("cluster: {} not found, ip: {}, will create new cluster with default configuration.",
instance.getClusterName(), instance.toJSON());
Cluster cluster = new Cluster(instance.getClusterName());
cluster.setService(this);
Cluster cluster = new Cluster(instance.getClusterName(), this);
cluster.init();
getClusterMap().put(instance.getClusterName(), cluster);
}

View File

@ -20,6 +20,7 @@ import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
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.naming.cluster.ServerListManager;
import com.alibaba.nacos.naming.cluster.servers.Server;
import com.alibaba.nacos.naming.consistency.ConsistencyService;
@ -357,7 +358,7 @@ public class ServiceManager implements RecordListener<Service> {
service = new Service();
service.setName(serviceName);
service.setNamespaceId(namespaceId);
service.setGroupName(Constants.DEFAULT_GROUP);
service.setGroupName(NamingUtils.getGroupName(serviceName));
// now validate the service. if failed, exception will be thrown
service.setLastModifiedMillis(System.currentTimeMillis());
service.recalculateChecksum();
@ -485,8 +486,7 @@ public class ServiceManager implements RecordListener<Service> {
for (Instance instance : ips) {
if (!service.getClusterMap().containsKey(instance.getClusterName())) {
Cluster cluster = new Cluster(instance.getClusterName());
cluster.setService(service);
Cluster cluster = new Cluster(instance.getClusterName(), service);
cluster.init();
service.getClusterMap().put(instance.getClusterName(), cluster);
Loggers.SRV_LOG.warn("cluster: {} not found, ip: {}, will create new cluster with default configuration.",

View File

@ -77,8 +77,8 @@ public class ClientBeatCheckTask implements Runnable {
if (!instance.isMarked()) {
if (instance.isHealthy()) {
instance.setHealthy(false);
Loggers.EVT_LOG.info("{POS} {IP-DISABLED} valid: {}:{}@{}, region: {}, msg: client timeout after {}, last beat: {}",
instance.getIp(), instance.getPort(), instance.getClusterName(),
Loggers.EVT_LOG.info("{POS} {IP-DISABLED} valid: {}:{}@{}@{}, region: {}, msg: client timeout after {}, last beat: {}",
instance.getIp(), instance.getPort(), instance.getClusterName(), service.getName(),
UtilsAndCommons.LOCALHOST_SITE, ClientBeatProcessor.CLIENT_BEAT_TIMEOUT, instance.getLastBeat());
getPushService().serviceChanged(service.getNamespaceId(), service.getName());
}

View File

@ -15,48 +15,45 @@
*/
package com.alibaba.nacos.naming.healthcheck;
import com.alibaba.nacos.naming.healthcheck.extend.HealthCheckExtendProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @author nacos
*/
@Component("healthCheckDelegate")
public class HealthCheckProcessorDelegate implements HealthCheckProcessor {
@Autowired
private HttpHealthCheckProcessor httpProcessor;
private Map<String, HealthCheckProcessor> healthCheckProcessorMap
= new HashMap<>();
public HealthCheckProcessorDelegate(HealthCheckExtendProvider provider) {
provider.init();
}
@Autowired
private TcpSuperSenseProcessor tcpProcessor;
@Autowired
private MysqlHealthCheckProcessor mysqlProcessor;
@Autowired
private NoneHealthCheckProcessor noneProcessor;
public void addProcessor(Collection<HealthCheckProcessor> processors){
healthCheckProcessorMap.putAll(processors.stream()
.filter(processor -> processor.getType() != null)
.collect(Collectors.toMap(HealthCheckProcessor::getType, processor -> processor)));
}
@Override
public void process(HealthCheckTask task) {
String type = task.getCluster().getHealthChecker().getType();
if (type.equals(httpProcessor.getType())) {
httpProcessor.process(task);
return;
HealthCheckProcessor processor = healthCheckProcessorMap.get(type);
if(processor == null){
processor = healthCheckProcessorMap.get("none");
}
if (type.equals(tcpProcessor.getType())) {
tcpProcessor.process(task);
return;
}
if (type.equals(mysqlProcessor.getType())) {
mysqlProcessor.process(task);
return;
}
noneProcessor.process(task);
processor.process(task);
}
@Override

View File

@ -15,6 +15,13 @@
*/
package com.alibaba.nacos.naming.healthcheck;
import com.alibaba.nacos.api.naming.pojo.AbstractHealthChecker;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author nkorange
*/
@ -22,17 +29,54 @@ public enum HealthCheckType {
/**
* TCP type
*/
TCP,
TCP("tcp", AbstractHealthChecker.Tcp.class),
/**
* HTTP type
*/
HTTP,
HTTP("http", AbstractHealthChecker.Http.class),
/**
* MySQL type
*/
MYSQL,
MYSQL("mysql", AbstractHealthChecker.Mysql.class),
/**
* No check
*/
NONE
NONE("none", AbstractHealthChecker.None.class);
private String name;
private Class healthCheckerClass;
private static Map<String, Class> EXTEND =
new ConcurrentHashMap<>();
HealthCheckType(String name, Class healthCheckerClass) {
this.name = name;
this.healthCheckerClass = healthCheckerClass;
}
public static void registerHealthChecker(String type, Class healthCheckerClass){
EXTEND.putIfAbsent(type, healthCheckerClass);
}
public static Class ofHealthCheckerClass(String type){
HealthCheckType enumType;
try {
enumType = valueOf(type);
}catch (Exception e){
return EXTEND.get(type);
}
return enumType.healthCheckerClass;
}
public static List<Class> getLoadedHealthCheckerClasses(){
List<Class> all = new ArrayList<>();
for(HealthCheckType type : values()){
all.add(type.healthCheckerClass);
}
for(Map.Entry<String, Class> entry : EXTEND.entrySet()){
all.add(entry.getValue());
}
return all;
}
}

View File

@ -42,25 +42,16 @@ public class JsonAdapter implements ObjectDeserializer, ObjectSerializer {
return INSTANCE;
}
@SuppressWarnings("unchecked")
@Override
public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
JSONObject jsonObj = (JSONObject) parser.parse();
String checkType = jsonObj.getString("type");
if (StringUtils.equals(checkType, AbstractHealthChecker.Http.TYPE)) {
return (T) JSON.parseObject(jsonObj.toJSONString(), AbstractHealthChecker.Http.class);
}
Class target = HealthCheckType.ofHealthCheckerClass(checkType);
if (StringUtils.equals(checkType, AbstractHealthChecker.Tcp.TYPE)) {
return (T) JSON.parseObject(jsonObj.toJSONString(), AbstractHealthChecker.Tcp.class);
}
if (StringUtils.equals(checkType, AbstractHealthChecker.None.TYPE)) {
return (T) JSON.parseObject(jsonObj.toJSONString(), AbstractHealthChecker.None.class);
}
if (StringUtils.equals(checkType, AbstractHealthChecker.Mysql.TYPE)) {
return (T) JSON.parseObject(jsonObj.toJSONString(), AbstractHealthChecker.Mysql.class);
if(target != null){
return (T) JSON.parseObject(jsonObj.toJSONString(), target);
}
return null;
@ -83,21 +74,6 @@ public class JsonAdapter implements ObjectDeserializer, ObjectSerializer {
writer.writeFieldValue(',', "type", config.getType());
if (StringUtils.equals(config.getType(), HealthCheckType.HTTP.name())) {
AbstractHealthChecker.Http httpCheckConfig = (AbstractHealthChecker.Http) config;
writer.writeFieldValue(',', "path", httpCheckConfig.getPath());
writer.writeFieldValue(',', "headers", httpCheckConfig.getHeaders());
}
if (StringUtils.equals(config.getType(), HealthCheckType.TCP.name())) {
// nothing sepcial to handle
}
if (StringUtils.equals(config.getType(), HealthCheckType.MYSQL.name())) {
AbstractHealthChecker.Mysql mysqlCheckConfig = (AbstractHealthChecker.Mysql) config;
writer.writeFieldValue(',', "user", mysqlCheckConfig.getUser());
writer.writeFieldValue(',', "pwd", mysqlCheckConfig.getPwd());
writer.writeFieldValue(',', "cmd", mysqlCheckConfig.getCmd());
}
config.jsonAdapterCallback(writer);
}
}

View File

@ -0,0 +1,109 @@
/*
* 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.healthcheck.extend;
import com.alibaba.nacos.api.naming.pojo.AbstractHealthChecker;
import com.alibaba.nacos.naming.healthcheck.HealthCheckProcessor;
import com.alibaba.nacos.naming.healthcheck.HealthCheckType;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.config.SingletonBeanRegistry;
import org.springframework.stereotype.Component;
import java.util.HashSet;
import java.util.Iterator;
import java.util.ServiceLoader;
import java.util.Set;
/**
* @author XCXCXCXCX
*/
@Component
public class HealthCheckExtendProvider implements BeanFactoryAware {
private static final Logger LOGGER = LoggerFactory.getLogger(HealthCheckExtendProvider.class);
private ServiceLoader<HealthCheckProcessor> processorLoader
= ServiceLoader.load(HealthCheckProcessor.class);
private ServiceLoader<AbstractHealthChecker> checkerLoader
= ServiceLoader.load(AbstractHealthChecker.class);
private SingletonBeanRegistry registry;
public void init(){
loadExtend();
}
private void loadExtend() {
Iterator<HealthCheckProcessor> processorIt = processorLoader.iterator();
Iterator<AbstractHealthChecker> healthCheckerIt = checkerLoader.iterator();
Set<String> origin = new HashSet<>();
for(HealthCheckType type : HealthCheckType.values()){
origin.add(type.name());
}
Set<String> processorType = new HashSet<>();
Set<String> healthCheckerType = new HashSet<>();
processorType.addAll(origin);
healthCheckerType.addAll(origin);
while(processorIt.hasNext()){
HealthCheckProcessor processor = processorIt.next();
String type = processor.getType();
if(processorType.contains(type)){
throw new RuntimeException("More than one processor of the same type was found : [type=\"" + type + "\"]");
}
processorType.add(type);
registry.registerSingleton(lowerFirstChar(processor.getClass().getSimpleName()), processor);
}
while(healthCheckerIt.hasNext()){
AbstractHealthChecker checker = healthCheckerIt.next();
String type = checker.getType();
if(healthCheckerType.contains(type)){
throw new RuntimeException("More than one healthChecker of the same type was found : [type=\"" + type + "\"]");
}
healthCheckerType.add(type);
HealthCheckType.registerHealthChecker(checker.getType(), checker.getClass());
}
if(!processorType.equals(healthCheckerType)){
throw new RuntimeException("An unmatched processor and healthChecker are detected in the extension package.");
}
if(processorType.size() > origin.size()){
processorType.removeAll(origin);
LOGGER.debug("init health plugin : types=" + processorType);
}
}
private String lowerFirstChar(String simpleName) {
if(StringUtils.isBlank(simpleName)){
throw new IllegalArgumentException("can't find extend processor class name");
}
return String.valueOf(simpleName.charAt(0)).toLowerCase() + simpleName.substring(1);
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
if(beanFactory instanceof SingletonBeanRegistry){
this.registry = (SingletonBeanRegistry) beanFactory;
}
}
}

View File

@ -61,7 +61,7 @@ public class ServerStatusSynchronizer implements Synchronizer {
}
});
} catch (Exception e) {
Loggers.SRV_LOG.warn("[STATUS-SYNCHRONIZE] failed to request serverStatus, remote server: " + serverIP, e);
Loggers.SRV_LOG.warn("[STATUS-SYNCHRONIZE] failed to request serverStatus, remote server: {}", serverIP, e);
}
}

View File

@ -36,6 +36,7 @@ import static com.alibaba.nacos.core.utils.SystemUtils.NACOS_HOME;
/**
* @author nacos
* @author jifengnan
*/
public class UtilsAndCommons {
@ -239,23 +240,25 @@ public class UtilsAndCommons {
}
/**
* 根据指定的字符串计算出一个0{@code upperLimit}不含之间的数字本方法会试图让不同的字符串较均匀的分布在0到{@code upperLimit}之间
* (Provide a number between 0(include) and {@code upperLimit}(exclude) for the given {@code string}, the number will be nearly uniform distribution.)
* Provide a number between 0(inclusive) and {@code upperLimit}(exclusive) for the given {@code string},
* the number will be nearly uniform distribution.
* <p>
* <p>
* 举个例子假设有N个提供相同服务的服务器地址被存在一个数组中为了实现负载均衡可以根据调用者的名字决定使用哪个服务器
* (e.g. Assume there's an array which contains some IP of the servers provide the same service, the caller name can be used to choose the server to achieve load balance.)
*
* e.g. Assume there's an array which contains some IP of the servers provide the same service,
* the caller name can be used to choose the server to achieve load balance.
* <blockquote><pre>
* String[] serverIps = new String[10];
* int index = shakeUp("callerName", serverIps.length);
* String targetServerIp = serverIps[index];
* </pre></blockquote>
*
* @param string 字符串如果为null会固定返回0 (a string. the number 0 will be returned if it's null)
* @param upperLimit 返回值的上限必须为正整数(>0) (the upper limit of the returned number, must be a positive integer, which means > 0)
* @return 0到upperLimit不含之间的一个数字 (a number between 0(include) and upperLimit(exclude))
* @param string a string. the number 0 will be returned if it's null
* @param upperLimit the upper limit of the returned number, must be a positive integer, which means > 0
* @return a number between 0(inclusive) and upperLimit(exclusive)
* @throws IllegalArgumentException if the upper limit equals or less than 0
* @since 1.0.0
* @author jifengnan
*/
public static int shakeUp(String string, int upperLimit) {
if (upperLimit < 1) {

View File

@ -15,8 +15,6 @@
*/
package com.alibaba.nacos.naming.selector;
import com.alibaba.nacos.api.selector.AbstractSelector;
import com.alibaba.nacos.api.selector.SelectorType;
import com.alibaba.nacos.naming.core.Instance;
import java.util.List;
@ -27,11 +25,7 @@ import java.util.List;
* @author nkorange
* @since 0.7.0
*/
public class NoneSelector extends AbstractSelector implements Selector {
public NoneSelector() {
this.setType(SelectorType.none.name());
}
public class NoneSelector extends com.alibaba.nacos.api.selector.NoneSelector implements Selector {
@Override
public List<Instance> select(String consumer, List<Instance> providers) {

View File

@ -17,6 +17,7 @@ package com.alibaba.nacos.naming.web;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.naming.CommonParams;
import com.alibaba.nacos.naming.boot.SpringContext;
import com.alibaba.nacos.naming.core.DistroMapper;
import com.alibaba.nacos.naming.misc.HttpClient;
import com.alibaba.nacos.naming.misc.Loggers;
@ -97,6 +98,16 @@ public class DistroFilter implements Filter {
// proxy request to other server if necessary:
if (method.isAnnotationPresent(CanDistro.class) && !distroMapper.responsible(groupedServiceName)) {
String userAgent = req.getHeader("User-Agent");
if (StringUtils.isNotBlank(userAgent) && userAgent.contains(UtilsAndCommons.NACOS_SERVER_HEADER)) {
// This request is sent from peer server, should not be redirected again:
Loggers.SRV_LOG.error("receive invalid redirect request from peer {}", req.getRemoteAddr());
resp.sendError(HttpServletResponse.SC_BAD_REQUEST,
"receive invalid redirect request from peer " + req.getRemoteAddr());
return;
}
List<String> headerList = new ArrayList<>(16);
Enumeration<String> headers = req.getHeaderNames();
while (headers.hasMoreElements()) {

View File

@ -15,15 +15,26 @@
*/
package com.alibaba.nacos.naming;
import com.alibaba.nacos.naming.boot.SpringContext;
import com.alibaba.nacos.naming.consistency.persistent.raft.RaftCore;
import com.alibaba.nacos.naming.consistency.persistent.raft.RaftPeer;
import com.alibaba.nacos.naming.consistency.persistent.raft.RaftPeerSet;
import com.alibaba.nacos.naming.core.DistroMapper;
import com.alibaba.nacos.naming.core.ServiceManager;
import com.alibaba.nacos.naming.healthcheck.HealthCheckProcessorDelegate;
import com.alibaba.nacos.naming.misc.NetUtils;
import com.alibaba.nacos.naming.misc.SwitchDomain;
import com.alibaba.nacos.naming.push.PushService;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.ExpectedException;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
import org.springframework.context.ApplicationContext;
import static org.mockito.Mockito.doReturn;
/**
* @author nkorange
@ -39,6 +50,9 @@ public class BaseTest {
@Mock
public RaftCore raftCore;
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Before
public void before() {
MockitoAnnotations.initMocks(this);
@ -49,5 +63,27 @@ public class BaseTest {
Mockito.when(peerSet.local()).thenReturn(peer);
Mockito.when(peerSet.getLeader()).thenReturn(peer);
Mockito.when(peerSet.isLeader(NetUtils.localServer())).thenReturn(true);
new SpringContext().setApplicationContext(context);
doReturn(distroMapper).when(context).getBean(DistroMapper.class);
doReturn(switchDomain).when(context).getBean(SwitchDomain.class);
doReturn(delegate).when(context).getBean(HealthCheckProcessorDelegate.class);
doReturn(pushService).when(context).getBean(PushService.class);
}
protected static final String TEST_CLUSTER_NAME = "test-cluster";
protected static final String TEST_SERVICE_NAME = "test-service";
protected static final String TEST_GROUP_NAME = "test-group-name";
protected static final String TEST_NAMESPACE = "test-namespace";
@Spy
protected ApplicationContext context;
@Mock
protected DistroMapper distroMapper;
@Spy
protected SwitchDomain switchDomain;
@Mock
protected HealthCheckProcessorDelegate delegate;
@Mock
protected PushService pushService;
}

View File

@ -16,6 +16,7 @@
package com.alibaba.nacos.naming.consistency.ephemeral.distro;
import com.alibaba.nacos.naming.misc.GlobalConfig;
import com.alibaba.nacos.naming.misc.Loggers;
import org.junit.Before;
import org.junit.Test;
import org.springframework.test.util.ReflectionTestUtils;

View File

@ -0,0 +1,98 @@
/*
* 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.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.naming.core.Cluster;
import com.alibaba.nacos.naming.core.Service;
import com.alibaba.nacos.naming.core.ServiceManager;
import com.alibaba.nacos.naming.misc.UtilsAndCommons;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
/**
* @author jifengnan 2019-04-29
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class CatalogControllerTest {
@Autowired
private MockMvc mockmvc;
@MockBean
private ServiceManager serviceManager;
@Test
public void testServiceDetail() throws Exception {
Service service = new Service(TEST_SERVICE_NAME);
service.setNamespaceId(Constants.DEFAULT_NAMESPACE_ID);
service.setProtectThreshold(12.34f);
service.setGroupName(TEST_GROUP_NAME);
Cluster cluster = new Cluster(TEST_CLUSTER_NAME, service);
cluster.setDefaultPort(1);
service.addCluster(cluster);
when(serviceManager.getService(anyString(), anyString())).thenReturn(service);
String result1 = mockmvc.perform(get(UtilsAndCommons.NACOS_NAMING_CONTEXT + "/catalog/service")
.param(CommonParams.NAMESPACE_ID, Constants.DEFAULT_NAMESPACE_ID)
.param(CommonParams.SERVICE_NAME, TEST_SERVICE_NAME)
.param(CommonParams.GROUP_NAME, TEST_GROUP_NAME))
.andReturn().getResponse().getContentAsString();
JSONObject result = JSONObject.parseObject(result1);
JSONObject serviceResult = (JSONObject) result.get("service");
Assert.assertEquals(TEST_SERVICE_NAME, serviceResult.get("name"));
Assert.assertEquals(12.34, Float.parseFloat(serviceResult.get("protectThreshold").toString()), 0.01);
Assert.assertEquals(TEST_GROUP_NAME, serviceResult.get("groupName"));
JSONArray clusterResults = (JSONArray) result.get("clusters");
Assert.assertEquals(1, clusterResults.size());
JSONObject clusterResult = (JSONObject) clusterResults.get(0);
Assert.assertEquals(TEST_CLUSTER_NAME, clusterResult.get("name"));
Assert.assertEquals(1, Integer.parseInt(clusterResult.get("defaultPort").toString()));
Assert.assertTrue(Boolean.parseBoolean(clusterResult.get("useIPPort4Check").toString()));
Assert.assertEquals(TEST_SERVICE_NAME, clusterResult.get("serviceName"));
Assert.assertEquals(80, Integer.parseInt(clusterResult.get("defaultCheckPort").toString()));
}
@Test
public void testServiceDetailNotFound() throws Exception {
String result = mockmvc.perform(get(UtilsAndCommons.NACOS_NAMING_CONTEXT + "/catalog/service")
.param(CommonParams.NAMESPACE_ID, Constants.DEFAULT_NAMESPACE_ID)
.param(CommonParams.SERVICE_NAME, TEST_SERVICE_NAME)).andReturn().getResponse().getContentAsString();
Assert.assertTrue(result.contains("test-service is not found!"));
}
private static final String TEST_CLUSTER_NAME = "test-cluster";
private static final String TEST_SERVICE_NAME = "test-service";
private static final String TEST_GROUP_NAME = "test-group-name";
}

View File

@ -0,0 +1,113 @@
/*
* 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.common.Constants;
import com.alibaba.nacos.naming.BaseTest;
import com.alibaba.nacos.naming.core.Cluster;
import com.alibaba.nacos.naming.core.Service;
import com.alibaba.nacos.naming.exception.NacosException;
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.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 static org.hamcrest.CoreMatchers.isA;
import static org.mockito.Mockito.when;
/**
* @author jifengnan 2019-04-29
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MockServletContext.class)
@WebAppConfiguration
public class ClusterControllerTest extends BaseTest {
@InjectMocks
private ClusterController clusterController;
private MockMvc mockmvc;
@Before
public void before() {
super.before();
mockmvc = MockMvcBuilders.standaloneSetup(clusterController).build();
}
@Test
public void testUpdate() throws Exception {
Service service = new Service(TEST_SERVICE_NAME);
service.setNamespaceId("test-namespace");
when(serviceManager.getService(Constants.DEFAULT_NAMESPACE_ID, TEST_SERVICE_NAME)).thenReturn(service);
MockHttpServletRequestBuilder builder =
MockMvcRequestBuilders.put(UtilsAndCommons.NACOS_NAMING_CONTEXT + "/cluster")
.param("clusterName", TEST_CLUSTER_NAME)
.param("serviceName", TEST_SERVICE_NAME)
.param("healthChecker", "{\"type\":\"HTTP\"}")
.param("checkPort", "1")
.param("useInstancePort4Check", "true");
Assert.assertEquals("ok", mockmvc.perform(builder).andReturn().getResponse().getContentAsString());
Cluster expectedCluster = new Cluster(TEST_CLUSTER_NAME, service);
Cluster actualCluster = service.getClusterMap().get(TEST_CLUSTER_NAME);
Assert.assertEquals(expectedCluster, actualCluster);
Assert.assertEquals(1, actualCluster.getDefCkport());
Assert.assertTrue(actualCluster.isUseIPPort4Check());
}
@Test
public void testUpdateNoService() throws Exception {
expectedException.expectCause(isA(NacosException.class));
expectedException.expectMessage("service not found:test-service-not-found");
MockHttpServletRequestBuilder builder =
MockMvcRequestBuilders.put(UtilsAndCommons.NACOS_NAMING_CONTEXT + "/cluster")
.param("clusterName", TEST_CLUSTER_NAME)
.param("serviceName", "test-service-not-found")
.param("healthChecker", "{\"type\":\"HTTP\"}")
.param("checkPort", "1")
.param("useInstancePort4Check", "true");
mockmvc.perform(builder);
}
@Test
public void testUpdateInvalidType() throws Exception {
expectedException.expectCause(isA(NacosException.class));
expectedException.expectMessage("unknown health check type:{\"type\":\"123\"}");
Service service = new Service(TEST_SERVICE_NAME);
service.setNamespaceId(Constants.DEFAULT_NAMESPACE_ID);
when(serviceManager.getService(Constants.DEFAULT_NAMESPACE_ID, TEST_SERVICE_NAME)).thenReturn(service);
MockHttpServletRequestBuilder builder =
MockMvcRequestBuilders.put(UtilsAndCommons.NACOS_NAMING_CONTEXT + "/cluster")
.param("clusterName", TEST_CLUSTER_NAME)
.param("serviceName", TEST_SERVICE_NAME)
.param("healthChecker", "{\"type\":\"123\"}")
.param("checkPort", "1")
.param("useInstancePort4Check", "true");
mockmvc.perform(builder);
}
}

View File

@ -71,27 +71,25 @@ public class InstanceControllerTest extends BaseTest {
public void registerInstance() throws Exception {
Service service = new Service();
service.setName("nacos.test.1");
service.setName(TEST_SERVICE_NAME);
Cluster cluster = new Cluster();
cluster.setName(UtilsAndCommons.DEFAULT_CLUSTER_NAME);
cluster.setService(service);
Cluster cluster = new Cluster(UtilsAndCommons.DEFAULT_CLUSTER_NAME, service);
service.addCluster(cluster);
Instance instance = new Instance();
instance.setIp("1.1.1.1");
instance.setPort(9999);
List<Instance> ipList = new ArrayList<Instance>();
List<Instance> ipList = new ArrayList<>();
ipList.add(instance);
service.updateIPs(ipList, false);
Mockito.when(serviceManager.getService(Constants.DEFAULT_NAMESPACE_ID, "nacos.test.1")).thenReturn(service);
Mockito.when(serviceManager.getService(Constants.DEFAULT_NAMESPACE_ID, TEST_SERVICE_NAME)).thenReturn(service);
MockHttpServletRequestBuilder builder =
MockMvcRequestBuilders.put("/naming/instance")
.param("serviceName", "nacos.test.1")
.param("ip", "1.1.1.1")
.param("port", "9999");
MockMvcRequestBuilders.put(UtilsAndCommons.NACOS_NAMING_CONTEXT + "/instance")
.param("serviceName", TEST_SERVICE_NAME)
.param("ip", "1.1.1.1")
.param("port", "9999");
String actualValue = mockmvc.perform(builder).andReturn().getResponse().getContentAsString();
Assert.assertEquals("ok", actualValue);
@ -101,11 +99,11 @@ public class InstanceControllerTest extends BaseTest {
public void deregisterInstance() throws Exception {
MockHttpServletRequestBuilder builder =
MockMvcRequestBuilders.delete("/naming/instance")
.param("serviceName", "nacos.test.1")
.param("ip", "1.1.1.1")
.param("port", "9999")
.param("clusterName", UtilsAndCommons.DEFAULT_CLUSTER_NAME);
MockMvcRequestBuilders.delete(UtilsAndCommons.NACOS_NAMING_CONTEXT + "/instance")
.param("serviceName", TEST_SERVICE_NAME)
.param("ip", "1.1.1.1")
.param("port", "9999")
.param("clusterName", UtilsAndCommons.DEFAULT_CLUSTER_NAME);
String actualValue = mockmvc.perform(builder).andReturn().getResponse().getContentAsString();
Assert.assertEquals("ok", actualValue);
@ -115,34 +113,32 @@ public class InstanceControllerTest extends BaseTest {
public void getInstances() throws Exception {
Service service = new Service();
service.setName("nacos.test.1");
service.setName(TEST_SERVICE_NAME);
Cluster cluster = new Cluster();
cluster.setName(UtilsAndCommons.DEFAULT_CLUSTER_NAME);
cluster.setService(service);
Cluster cluster = new Cluster(UtilsAndCommons.DEFAULT_CLUSTER_NAME, service);
service.addCluster(cluster);
Instance instance = new Instance();
instance.setIp("10.10.10.10");
instance.setPort(8888);
instance.setWeight(2.0);
List<Instance> ipList = new ArrayList<Instance>();
instance.setServiceName(TEST_SERVICE_NAME);
List<Instance> ipList = new ArrayList<>();
ipList.add(instance);
service.updateIPs(ipList, false);
Mockito.when(serviceManager.getService(Constants.DEFAULT_NAMESPACE_ID, "nacos.test.1")).thenReturn(service);
Mockito.when(serviceManager.getService(Constants.DEFAULT_NAMESPACE_ID, TEST_SERVICE_NAME)).thenReturn(service);
MockHttpServletRequestBuilder builder =
MockMvcRequestBuilders.get("/v1/ns/instances")
.param("serviceName", "nacos.test.1");
MockMvcRequestBuilders.get(UtilsAndCommons.NACOS_NAMING_CONTEXT + "/instance/list")
.param("serviceName", TEST_SERVICE_NAME);
MockHttpServletResponse response = mockmvc.perform(builder).andReturn().getResponse();
String actualValue = response.getContentAsString();
JSONObject result = JSON.parseObject(actualValue);
Assert.assertEquals("nacos.test.1", result.getString("serviceName"));
Assert.assertEquals(TEST_SERVICE_NAME, result.getString("name"));
JSONArray hosts = result.getJSONArray("hosts");
Assert.assertTrue(hosts != null);
Assert.assertNotNull(hosts);
Assert.assertEquals(hosts.size(), 1);

View File

@ -36,9 +36,7 @@ public class ClusterTest {
Service service = new Service();
service.setName("nacos.service.1");
cluster = new Cluster();
cluster.setName("nacos-cluster-1");
cluster.setService(service);
cluster = new Cluster("nacos-cluster-1", service);
cluster.setDefCkport(80);
cluster.setDefIPPort(8080);
}
@ -46,8 +44,10 @@ public class ClusterTest {
@Test
public void updateCluster() {
Service service = new Service();
service.setName("nacos.service.2");
Cluster newCluster = new Cluster();
Cluster newCluster = new Cluster("nacos-cluster-1", service);
newCluster.setDefCkport(8888);
newCluster.setDefIPPort(9999);
AbstractHealthChecker.Http healthCheckConfig = new AbstractHealthChecker.Http();
@ -56,17 +56,12 @@ public class ClusterTest {
healthCheckConfig.setHeaders("Client-Version:nacos-test-1");
newCluster.setHealthChecker(healthCheckConfig);
Service service = new Service();
service.setName("nacos.service.2");
newCluster.setService(service);
cluster.update(newCluster);
Assert.assertEquals(8888, cluster.getDefCkport());
Assert.assertEquals(9999, cluster.getDefIPPort());
Assert.assertTrue(cluster.getHealthChecker() instanceof AbstractHealthChecker.Http);
AbstractHealthChecker.Http httpHealthCheck = (AbstractHealthChecker.Http)(cluster.getHealthChecker());
AbstractHealthChecker.Http httpHealthCheck = (AbstractHealthChecker.Http) (cluster.getHealthChecker());
Assert.assertEquals("/nacos-path-1", httpHealthCheck.getPath());
Assert.assertEquals(500, httpHealthCheck.getExpectedResponseCode());
Assert.assertEquals("Client-Version:nacos-test-1", httpHealthCheck.getHeaders());
@ -83,7 +78,7 @@ public class ClusterTest {
instance2.setIp("1.1.1.1");
instance2.setPort(2345);
List<Instance> list = new ArrayList<Instance>();
List<Instance> list = new ArrayList<>();
list.add(instance1);
list.add(instance2);
@ -97,4 +92,25 @@ public class ClusterTest {
Assert.assertEquals("1.1.1.1", ips.get(1).getIp());
Assert.assertEquals(2345, ips.get(1).getPort());
}
@Test
public void testValidate() {
Service service = new Service("nacos.service.2");
cluster = new Cluster("nacos-cluster-1", service);
cluster.validate();
}
@Test(expected = IllegalArgumentException.class)
public void testValidateClusterNameNull() {
Service service = new Service("nacos.service.2");
cluster = new Cluster(null, service);
cluster.validate();
}
@Test(expected = IllegalArgumentException.class)
public void testValidateServiceNull() {
cluster = new Cluster("nacos-cluster-1", null);
cluster.validate();
}
}

View File

@ -15,31 +15,45 @@
*/
package com.alibaba.nacos.naming.core;
import com.alibaba.nacos.naming.boot.SpringContext;
import com.alibaba.nacos.naming.healthcheck.HealthCheckProcessorDelegate;
import com.alibaba.nacos.naming.misc.SwitchDomain;
import com.alibaba.nacos.naming.misc.UtilsAndCommons;
import com.alibaba.nacos.naming.push.PushService;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
import org.springframework.context.ApplicationContext;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.mockito.Mockito.doReturn;
/**
* @author nkorange
*/
public class DomainTest {
private Service service;
@Spy
protected ApplicationContext context;
@Mock
protected PushService pushService;
@Before
public void before() {
MockitoAnnotations.initMocks(this);
service = new Service();
service.setName("nacos.service.1");
Cluster cluster = new Cluster();
cluster.setName(UtilsAndCommons.DEFAULT_CLUSTER_NAME);
cluster.setService(service);
Cluster cluster = new Cluster(UtilsAndCommons.DEFAULT_CLUSTER_NAME, service);
service.addCluster(cluster);
new SpringContext().setApplicationContext(context);
doReturn(pushService).when(context).getBean(PushService.class);
}
@Test
@ -48,9 +62,7 @@ public class DomainTest {
Service newDomain = new Service();
newDomain.setName("nacos.service.1");
newDomain.setProtectThreshold(0.7f);
Cluster cluster = new Cluster();
cluster.setName(UtilsAndCommons.DEFAULT_CLUSTER_NAME);
cluster.setService(newDomain);
Cluster cluster = new Cluster(UtilsAndCommons.DEFAULT_CLUSTER_NAME, newDomain);
newDomain.addCluster(cluster);
service.update(newDomain);
@ -60,8 +72,7 @@ public class DomainTest {
@Test
public void addCluster() {
Cluster cluster = new Cluster();
cluster.setName("nacos-cluster-1");
Cluster cluster = new Cluster("nacos-cluster-1", service);
service.addCluster(cluster);

View File

@ -17,47 +17,52 @@ package com.alibaba.nacos.naming.core;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.naming.BaseTest;
import com.alibaba.nacos.naming.misc.UtilsAndCommons;
import com.alibaba.nacos.naming.consistency.ephemeral.distro.DistroConsistencyServiceImpl;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
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.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import java.util.List;
/**
* @author nkorange
* @author jifengnan 2019-05-18
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MockServletContext.class)
@WebAppConfiguration
public class DomainsManagerTest extends BaseTest {
@Before
public void before() {
super.before();
serviceManager = new ServiceManager();
}
@Spy
@InjectMocks
private ServiceManager manager;
@Mock
private DistroConsistencyServiceImpl consistencyService;
@Test
public void easyRemoveDom() throws Exception {
serviceManager.easyRemoveService(Constants.DEFAULT_NAMESPACE_ID, "nacos.test.1");
Service service = new Service(TEST_SERVICE_NAME);
service.setNamespaceId(TEST_NAMESPACE);
manager.putService(service);
manager.easyRemoveService(TEST_NAMESPACE, TEST_SERVICE_NAME);
}
@Test
public void searchDom() throws Exception {
Service service = new Service();
service.setName("nacos.test.1");
public void easyRemoveDomNotExist() throws Exception {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("specified service not exist, serviceName : " + TEST_SERVICE_NAME);
manager.easyRemoveService(Constants.DEFAULT_NAMESPACE_ID, TEST_SERVICE_NAME);
}
serviceManager.chooseServiceMap(Constants.DEFAULT_NAMESPACE_ID).put("nacos.test.1", service);
@Test
public void searchDom() {
Service service = new Service(TEST_SERVICE_NAME);
service.setNamespaceId(TEST_NAMESPACE);
manager.putService(service);
List<Service> list = serviceManager.searchServices(Constants.DEFAULT_NAMESPACE_ID, "nacos.test.*");
List<Service> list = manager.searchServices(TEST_NAMESPACE, "test.*");
Assert.assertNotNull(list);
Assert.assertEquals(1, list.size());
Assert.assertEquals("nacos.test.1", list.get(0).getName());
Assert.assertEquals(TEST_SERVICE_NAME, list.get(0).getName());
}
}

View File

@ -0,0 +1,87 @@
/*
* 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.naming.BaseTest;
import com.alibaba.nacos.naming.consistency.ConsistencyService;
import com.alibaba.nacos.naming.consistency.Datum;
import com.alibaba.nacos.naming.consistency.KeyBuilder;
import com.alibaba.nacos.naming.misc.UtilsAndCommons;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Spy;
import org.springframework.test.util.ReflectionTestUtils;
import java.util.List;
import static org.mockito.Mockito.when;
/**
* @author jifengnan 2019-04-29
*/
public class ServiceManagerTest extends BaseTest {
@Spy
private ServiceManager serviceManager;
@Mock
private ConsistencyService consistencyService;
@Before
public void before() {
super.before();
}
@Test
public void testUpdateIpAddresses() throws Exception {
ReflectionTestUtils.setField(serviceManager, "consistencyService", consistencyService);
Service service = new Service(TEST_SERVICE_NAME);
service.setNamespaceId(TEST_NAMESPACE);
Instance instance = new Instance("1.1.1.1", 1);
instance.setClusterName(TEST_CLUSTER_NAME);
List<Instance> instanceList = serviceManager.updateIpAddresses(service, UtilsAndCommons.UPDATE_INSTANCE_ACTION_ADD, true, instance);
Assert.assertEquals(1, instanceList.size());
Assert.assertEquals(instance, instanceList.get(0));
Assert.assertEquals(1, service.getClusterMap().size());
Assert.assertEquals(new Cluster(instance.getClusterName(), service), service.getClusterMap().get(TEST_CLUSTER_NAME));
Datum datam = new Datum();
datam.key = KeyBuilder.buildInstanceListKey(TEST_NAMESPACE, TEST_SERVICE_NAME, true);
Instances instances = new Instances();
instanceList.add(new Instance("2.2.2.2", 2));
instances.setInstanceList(instanceList);
datam.value = instances;
when(consistencyService.get(KeyBuilder.buildInstanceListKey(TEST_NAMESPACE, TEST_SERVICE_NAME, true))).thenReturn(datam);
service.getClusterMap().get(TEST_CLUSTER_NAME).updateIPs(instanceList, true);
instanceList = serviceManager.updateIpAddresses(service, UtilsAndCommons.UPDATE_INSTANCE_ACTION_REMOVE, true, instance);
Assert.assertEquals(1, instanceList.size());
Assert.assertEquals(new Instance("2.2.2.2", 2), instanceList.get(0));
Assert.assertEquals(1, service.getClusterMap().size());
Assert.assertEquals(new Cluster(instance.getClusterName(), service), service.getClusterMap().get(TEST_CLUSTER_NAME));
}
@Test
public void testUpdateIpAddressesNoInstance() throws Exception {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("ip list can not be empty, service: test-service, ip list: []");
ReflectionTestUtils.setField(serviceManager, "consistencyService", consistencyService);
Service service = new Service(TEST_SERVICE_NAME);
service.setNamespaceId(TEST_NAMESPACE);
serviceManager.updateIpAddresses(service, UtilsAndCommons.UPDATE_INSTANCE_ACTION_ADD, true);
}
}

View File

@ -0,0 +1,58 @@
/*
* 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.naming.BaseTest;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Spy;
import java.util.ArrayList;
import java.util.List;
/**
* @author jifengnan 2019-04-28
*/
public class ServiceTest extends BaseTest {
@Spy
private Service service;
@Before
public void before() {
super.before();
}
@Test
public void testUpdateIPs() {
service.setName("test-service");
List<Instance> instances = new ArrayList<>();
Instance instance = new Instance("1.1.1.1", 1, "test-instance1");
instances.add(instance);
service.updateIPs(instances, true);
Assert.assertEquals(instances, service.allIPs(true));
instances = new ArrayList<>();
instance = new Instance();
instance.setIp("2.2.2.2");
instance.setPort(2);
instances.add(instance);
instances.add(null);
service.updateIPs(instances, true);
instances.remove(null);
Assert.assertEquals(instances, service.allIPs(true));
}
}

View File

@ -36,9 +36,6 @@ public class UtilsAndCommonsTest {
MockEnvironment environment = new MockEnvironment();
Assert.assertEquals(DEFAULT_NACOS_NAMING_CONTEXT, environment.resolvePlaceholders(NACOS_NAMING_CONTEXT));
Assert.assertEquals("/nacos/v1/ns", DEFAULT_NACOS_NAMING_CONTEXT);
}
@Test(expected = IllegalArgumentException.class)

View File

@ -15,39 +15,49 @@
*/
package com.alibaba.nacos.naming.raft;
import com.alibaba.nacos.naming.BaseTest;
import com.alibaba.nacos.naming.consistency.Datum;
import com.alibaba.nacos.naming.consistency.KeyBuilder;
import com.alibaba.nacos.naming.consistency.persistent.raft.RaftCore;
import com.alibaba.nacos.naming.consistency.persistent.raft.RaftStore;
import com.alibaba.nacos.naming.core.Instance;
import com.alibaba.nacos.naming.core.Instances;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.InjectMocks;
import org.mockito.Spy;
/**
* @author nkorange
* @author jifengnan 2019-05-18
*/
public class RaftStoreTest {
public class RaftStoreTest extends BaseTest {
@Mock
@InjectMocks
@Spy
public RaftCore raftCore;
@Mock
@Spy
public RaftStore raftStore;
@Test
public void wrietDatum() throws Exception {
Datum datum = new Datum();
datum.key = "1.2.3.4";
Datum<Instances> datum = new Datum<>();
String key = KeyBuilder.buildInstanceListKey(TEST_NAMESPACE, TEST_SERVICE_NAME, false);
datum.key = key;
datum.timestamp.getAndIncrement();
datum.value = new Instances();
Instance instance = new Instance("1.1.1.1", 1, TEST_CLUSTER_NAME);
datum.value.getInstanceList().add(instance);
instance = new Instance("2.2.2.2", 2, TEST_CLUSTER_NAME);
datum.value.getInstanceList().add(instance);
raftStore.write(datum);
raftCore.init();
Datum result = raftCore.getDatum(key);
raftCore.loadDatum("1.2.3.4");
Datum result = raftCore.getDatum("1.2.3.4");
Assert.assertNotNull(result);
Assert.assertEquals("value1", result.value);
Assert.assertEquals(key, result.key);
Assert.assertEquals(1, result.timestamp.intValue());
Assert.assertEquals(datum.value.toString(), result.value.toString());
}
}

View File

@ -404,9 +404,6 @@
<includes>
<include>**/*ITCase.java</include>
</includes>
<excludes>
<exclude>**/RestAPI_ITCase.java</exclude>
</excludes>
</configuration>
<executions>
<execution>
@ -682,13 +679,13 @@
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.8</version>
<version>2.9.9</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
<version>2.9.9</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>

View File

@ -24,7 +24,6 @@ import com.alibaba.nacos.client.naming.beat.BeatInfo;
import com.alibaba.nacos.naming.NamingApp;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
@ -78,7 +77,6 @@ public class AutoDeregisterInstance_ITCase {
* @throws Exception
*/
@Test
@Ignore
public void autoDregDomClustersTest() throws Exception {
String serviceName = randomDomainName();
@ -116,7 +114,6 @@ public class AutoDeregisterInstance_ITCase {
* @throws Exception
*/
@Test
@Ignore
public void autoDregDomTest() throws Exception {
String serviceName = randomDomainName();
@ -139,8 +136,6 @@ public class AutoDeregisterInstance_ITCase {
instances = naming.getAllInstances(serviceName);
Assert.assertEquals(1, instances.size());
}

View File

@ -0,0 +1,672 @@
/*
* 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.test.naming;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import org.junit.Ignore;
import org.springframework.http.HttpMethod;
import com.alibaba.nacos.naming.NamingApp;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.MultiValueMap;
import org.springframework.web.util.UriComponentsBuilder;
import static com.alibaba.nacos.client.naming.net.HttpClient.request;
import static com.alibaba.nacos.test.naming.NamingBase.*;
import static com.alibaba.nacos.test.naming.NamingBase.randomDomainName;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = NamingApp.class, properties = {"server.servlet.context-path=/nacos",
"server.port=7001"},
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Ignore
public class Cmdb_ITCase {
private NamingService naming;
private URL base;
public static final long TIME_OUT = 3000;
@Autowired
private TestRestTemplate restTemplate;
@LocalServerPort
private int port;
@Before
public void setUp() throws Exception {
String url = String.format("http://%s:%s", TEST_IP_4_DOM_1, port);
this.base = new URL(url);
if (naming == null) {
naming = NamingFactory.createNamingService(TEST_IP_4_DOM_1 + ":" + port);
}
}
@After
public void cleanup() throws Exception {
}
/**
* @TCDescription : cmdb注册的label,同机房优先
* @throws Exception
*/
@Test
public void cmdb_getInstanceList_1() throws Exception {
String serviceName = randomDomainName();
System.out.println(serviceName);
namingServiceCreate(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP);
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "11.11.11.11", String.valueOf(TEST_PORT_4_DOM_1), "c1");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "22.22.22.22", String.valueOf(TEST_PORT_4_DOM_1), "c1");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "33.33.33.33", String.valueOf(TEST_PORT_4_DOM_1), "c2");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "44.44.44.44", String.valueOf(TEST_PORT_4_DOM_1), "c2");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "55.55.55.55", String.valueOf(TEST_PORT_4_DOM_1), "c1");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "66.66.66.66", String.valueOf(TEST_PORT_4_DOM_1), "c1");
String serviceName2 = randomDomainName();
namingServiceCreate(serviceName2, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP);
instanceRegister(serviceName2, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "77.77.77.77", String.valueOf(TEST_PORT_4_DOM_1), "c2");
instanceRegister(serviceName2, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "88.88.88.88", String.valueOf(TEST_PORT_4_DOM_1), "c2");
TimeUnit.SECONDS.sleep(5L);
JSONObject json = new JSONObject();
json.put("type", "label");
json.put("expression", "CONSUMER.label.label1 = PROVIDER.label.label1");
ResponseEntity<String> httpResult = request("/nacos/v1/ns/service",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("protectThreshold", "0")
.appendParam("selector", json.toJSONString())
.done(),
String.class,
HttpMethod.PUT);
Assert.assertEquals(HttpURLConnection.HTTP_OK, httpResult.getStatusCodeValue());
httpResult = request("/nacos/v1/ns/instance/list",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("clientIP", "11.11.11.11")
.done(),
String.class,
HttpMethod.GET);
Assert.assertEquals(HttpURLConnection.HTTP_OK, httpResult.getStatusCodeValue());
json = JSON.parseObject(httpResult.getBody());
Assert.assertEquals(1, json.getJSONArray("hosts").size());
}
/**
* @TCDescription : cmdb未注册的label,获取所有的instance
* @throws Exception
*/
@Test
public void cmdb_getInstanceList_2() throws Exception {
String serviceName = randomDomainName();
namingServiceCreate(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP);
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "11.11.11.11", String.valueOf(TEST_PORT_4_DOM_1), "c1");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "22.22.22.22", String.valueOf(TEST_PORT_4_DOM_1), "c1");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "33.33.33.33", String.valueOf(TEST_PORT_4_DOM_1), "c2");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "44.44.44.44", String.valueOf(TEST_PORT_4_DOM_1), "c2");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "55.55.55.55", String.valueOf(TEST_PORT_4_DOM_1), "c1");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "66.66.66.66", String.valueOf(TEST_PORT_4_DOM_1), "c1");
String serviceName2 = randomDomainName();
namingServiceCreate(serviceName2, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP);
instanceRegister(serviceName2, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "77.77.77.77", String.valueOf(TEST_PORT_4_DOM_1), "c2");
instanceRegister(serviceName2, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "88.88.88.88", String.valueOf(TEST_PORT_4_DOM_1), "c2");
TimeUnit.SECONDS.sleep(10);
JSONObject json = new JSONObject();
json.put("type", "label");
json.put("expression", "CONSUMER.label.label1 = PROVIDER.label.label1");
ResponseEntity<String> httpResult = request("/nacos/v1/ns/service",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("protectThreshold", "0")
.appendParam("selector", json.toJSONString())
.done(),
String.class,
HttpMethod.PUT);
Assert.assertEquals(HttpURLConnection.HTTP_OK, httpResult.getStatusCodeValue());
httpResult = request("/nacos/v1/ns/instance/list",
Params.newParams()
.appendParam("serviceName", serviceName)
.done(),
String.class,
HttpMethod.GET);
Assert.assertEquals(HttpURLConnection.HTTP_OK, httpResult.getStatusCodeValue());
json = JSON.parseObject(httpResult.getBody());
Assert.assertEquals(6, json.getJSONArray("hosts").size());
}
/**
* @TCDescription : cmdb规则不同,根据IP获取优先的instance
* @throws Exception
*/
@Test
public void cmdb_getInstanceList_3() throws Exception {
String serviceName = randomDomainName();
namingServiceCreate(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP);
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "11.11.11.11", String.valueOf(TEST_PORT_4_DOM_1), "c1");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "22.22.22.22", String.valueOf(TEST_PORT_4_DOM_1), "c1");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "33.33.33.33", String.valueOf(TEST_PORT_4_DOM_1), "c2");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "44.44.44.44", String.valueOf(TEST_PORT_4_DOM_1), "c2");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "55.55.55.55", String.valueOf(TEST_PORT_4_DOM_1), "c1");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "66.66.66.66", String.valueOf(TEST_PORT_4_DOM_1), "c1");
String serviceName2 = randomDomainName();
namingServiceCreate(serviceName2, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP);
instanceRegister(serviceName2, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "77.77.77.77", String.valueOf(TEST_PORT_4_DOM_1), "c2");
instanceRegister(serviceName2, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "88.88.88.88", String.valueOf(TEST_PORT_4_DOM_1), "c2");
TimeUnit.SECONDS.sleep(10);
JSONObject json = new JSONObject();
json.put("type", "label");
json.put("expression", "CONSUMER.label.label1 = PROVIDER.label.label1 & CONSUMER.label.label2 = PROVIDER.label.label2");
ResponseEntity<String> httpResult = request("/nacos/v1/ns/service",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("protectThreshold", "0")
.appendParam("selector", json.toJSONString())
.done(),
String.class,
HttpMethod.PUT);
Assert.assertEquals(HttpURLConnection.HTTP_OK, httpResult.getStatusCodeValue());
httpResult = request("/nacos/v1/ns/instance/list",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("clientIP", "66.66.66.66")
.done(),
String.class,
HttpMethod.GET);
Assert.assertEquals(HttpURLConnection.HTTP_OK, httpResult.getStatusCodeValue());
json = JSON.parseObject(httpResult.getBody());
System.out.println("instance list = " + json);
Assert.assertEquals(2, json.getJSONArray("hosts").size());
}
/**
* @TCDescription : cmdb规则不同,对不同的serviceName的不影响
* @throws Exception
*/
@Test
public void cmdb_getInstanceList_4() throws Exception {
String serviceName = randomDomainName();
String serviceName2 = randomDomainName();
System.out.println(serviceName);
namingServiceCreate(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP);
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "11.11.11.11", String.valueOf(TEST_PORT_4_DOM_1), "c1");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "22.22.22.22", String.valueOf(TEST_PORT_4_DOM_1), "c1");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "33.33.33.33", String.valueOf(TEST_PORT_4_DOM_1), "c2");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "44.44.44.44", String.valueOf(TEST_PORT_4_DOM_1), "c2");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "55.55.55.55", String.valueOf(TEST_PORT_4_DOM_1), "c1");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "66.66.66.66", String.valueOf(TEST_PORT_4_DOM_1), "c1");
namingServiceCreate(serviceName2, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP);
instanceRegister(serviceName2, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "77.77.77.77", String.valueOf(TEST_PORT_4_DOM_1), "c2");
instanceRegister(serviceName2, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "88.88.88.88", String.valueOf(TEST_PORT_4_DOM_1), "c2");
TimeUnit.SECONDS.sleep(10);
JSONObject json = new JSONObject();
json.put("type", "label");
json.put("expression", "CONSUMER.label.label1 = PROVIDER.label.label1 & CONSUMER.label.label2 = PROVIDER.label.label2");
ResponseEntity<String> httpResult = request("/nacos/v1/ns/service",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("protectThreshold", "0")
.appendParam("selector", json.toJSONString())
.done(),
String.class,
HttpMethod.PUT);
Assert.assertEquals(HttpURLConnection.HTTP_OK, httpResult.getStatusCodeValue());
httpResult = request( "/nacos/v1/ns/service",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam( "namespaceId", Constants.DEFAULT_NAMESPACE_ID)
.done(),
String.class,
HttpMethod.GET);
System.out.println("service list = " + JSON.parseObject(httpResult.getBody()));
httpResult = request("/nacos/v1/ns/instance/list",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("clientIP", "66.66.66.66")
.done(),
String.class,
HttpMethod.GET);
Assert.assertEquals(HttpURLConnection.HTTP_OK, httpResult.getStatusCodeValue());
json = JSON.parseObject(httpResult.getBody());
System.out.println("instance list = " + json);
Assert.assertEquals(2, json.getJSONArray("hosts").size());
}
/**
* @TCDescription : cmdb规则不同,根据IP获取优先的instance,对不同的serviceName的不影响
* @throws Exception
*/
@Test
public void cmdb_getInstanceList_5() throws Exception {
String serviceName = randomDomainName();
String serviceName2 = randomDomainName();
System.out.println(serviceName);
namingServiceCreate(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP);
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "11.11.11.11", String.valueOf(TEST_PORT_4_DOM_1), "c1");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "22.22.22.22", String.valueOf(TEST_PORT_4_DOM_1), "c1");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "33.33.33.33", String.valueOf(TEST_PORT_4_DOM_1), "c2");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "44.44.44.44", String.valueOf(TEST_PORT_4_DOM_1), "c2");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "55.55.55.55", String.valueOf(TEST_PORT_4_DOM_1), "c1");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "66.66.66.66", String.valueOf(TEST_PORT_4_DOM_1), "c1");
namingServiceCreate(serviceName2, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP);
instanceRegister(serviceName2, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "77.77.77.77", String.valueOf(TEST_PORT_4_DOM_1), "c2");
instanceRegister(serviceName2, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "88.88.88.88", String.valueOf(TEST_PORT_4_DOM_1), "c2");
TimeUnit.SECONDS.sleep(10);
JSONObject json = new JSONObject();
json.put("type", "label");
json.put("expression", "CONSUMER.label.label1 = PROVIDER.label.label1 & CONSUMER.label.label2 = PROVIDER.label.label2");
ResponseEntity<String> httpResult = request("/nacos/v1/ns/service",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("protectThreshold", "0")
.appendParam("selector", json.toJSONString())
.done(),
String.class,
HttpMethod.PUT);
Assert.assertEquals(HttpURLConnection.HTTP_OK, httpResult.getStatusCodeValue());
httpResult = request("/nacos/v1/ns/instance/list",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("clientIP", "77.77.77.77")
.done(),
String.class,
HttpMethod.GET);
Assert.assertEquals(HttpURLConnection.HTTP_OK, httpResult.getStatusCodeValue());
json = JSON.parseObject(httpResult.getBody());
System.out.println("instance list = " + json);
Assert.assertEquals(6, json.getJSONArray("hosts").size());
}
/**
* @TCDescription : cmdb规则不同,selector为空时
* @throws Exception
*/
@Test
public void cmdb_getInstanceList_6() throws Exception {
String serviceName = randomDomainName();
String serviceName2 = randomDomainName();
System.out.println(serviceName);
namingServiceCreate(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP);
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "11.11.11.11", String.valueOf(TEST_PORT_4_DOM_1), "c1");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "22.22.22.22", String.valueOf(TEST_PORT_4_DOM_1), "c1");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "33.33.33.33", String.valueOf(TEST_PORT_4_DOM_1), "c2");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "44.44.44.44", String.valueOf(TEST_PORT_4_DOM_1), "c2");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "55.55.55.55", String.valueOf(TEST_PORT_4_DOM_1), "c1");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "66.66.66.66", String.valueOf(TEST_PORT_4_DOM_1), "c1");
namingServiceCreate(serviceName2, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP);
instanceRegister(serviceName2, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "77.77.77.77", String.valueOf(TEST_PORT_4_DOM_1), "c2");
instanceRegister(serviceName2, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "88.88.88.88", String.valueOf(TEST_PORT_4_DOM_1), "c2");
TimeUnit.SECONDS.sleep(10);
JSONObject json = new JSONObject();
json.put("type", "label");
json.put("expression", "CONSUMER.label.label1 = PROVIDER.label.label1 & CONSUMER.label.label2 = PROVIDER.label.label2");
ResponseEntity<String> httpResult = request("/nacos/v1/ns/service",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("protectThreshold", "0")
.appendParam("selector", json.toJSONString())
.done(),
String.class,
HttpMethod.PUT);
Assert.assertEquals(HttpURLConnection.HTTP_OK, httpResult.getStatusCodeValue());
httpResult = request("/nacos/v1/ns/instance/list",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("clientIP", "11.11.11.11")
.done(),
String.class,
HttpMethod.GET);
Assert.assertEquals(HttpURLConnection.HTTP_OK, httpResult.getStatusCodeValue());
json = JSON.parseObject(httpResult.getBody());
System.out.println("instance list = " + json);
Assert.assertEquals(1, json.getJSONArray("hosts").size());
}
/**
* @TCDescription : cmdb规则不同,selector规则改变
* @throws Exception
*/
@Test
public void cmdb_getInstanceList_7() throws Exception {
String serviceName = randomDomainName();
String serviceName2 = randomDomainName();
System.out.println(serviceName);
namingServiceCreate(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP);
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "11.11.11.11", String.valueOf(TEST_PORT_4_DOM_1), "c1");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "22.22.22.22", String.valueOf(TEST_PORT_4_DOM_1), "c1");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "33.33.33.33", String.valueOf(TEST_PORT_4_DOM_1), "c2");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "44.44.44.44", String.valueOf(TEST_PORT_4_DOM_1), "c2");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "55.55.55.55", String.valueOf(TEST_PORT_4_DOM_1), "c1");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "66.66.66.66", String.valueOf(TEST_PORT_4_DOM_1), "c1");
namingServiceCreate(serviceName2, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP);
instanceRegister(serviceName2, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "77.77.77.77", String.valueOf(TEST_PORT_4_DOM_1), "c2");
instanceRegister(serviceName2, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "88.88.88.88", String.valueOf(TEST_PORT_4_DOM_1), "c2");
TimeUnit.SECONDS.sleep(10);
JSONObject json = new JSONObject();
json.put("type", "label");
json.put("expression", "CONSUMER.label.label1 = PROVIDER.label.label1 & CONSUMER.label.label2 = PROVIDER.label.label2");
List<String> params = Arrays.asList("serviceName", serviceName, "protectThreshold", "0", "selector", json.toString());
ResponseEntity<String> httpResult = request("/nacos/v1/ns/service",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("protectThreshold", "0")
.appendParam("selector", json.toJSONString())
.done(),
String.class,
HttpMethod.PUT);
Assert.assertEquals(HttpURLConnection.HTTP_OK, httpResult.getStatusCodeValue());
httpResult = request("/nacos/v1/ns/instance/list",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("clientIP", "11.11.11.11")
.done(),
String.class,
HttpMethod.GET);
Assert.assertEquals(HttpURLConnection.HTTP_OK, httpResult.getStatusCodeValue());
json = JSON.parseObject(httpResult.getBody());
System.out.println("instance list = " + json);
Assert.assertEquals(1, json.getJSONArray("hosts").size());
httpResult = request("/nacos/v1/ns/service",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("protectThreshold", "0")
.appendParam("selector", "")
.done(),
String.class,
HttpMethod.PUT);
Assert.assertEquals(HttpURLConnection.HTTP_OK, httpResult.getStatusCodeValue());
httpResult = request("/nacos/v1/ns/instance/list",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("clientIP", "11.11.11.11")
.done(),
String.class,
HttpMethod.GET);
Assert.assertEquals(HttpURLConnection.HTTP_OK, httpResult.getStatusCodeValue());
json = JSON.parseObject(httpResult.getBody());
System.out.println("instance list = " + json);
Assert.assertEquals(6, json.getJSONArray("hosts").size());
}
/**
* @TCDescription : cmdb规则不同,expression为空
* @throws Exception
*/
@Test
public void cmdb_getInstanceList_8() throws Exception {
String serviceName = randomDomainName();
String serviceName2 = randomDomainName();
System.out.println(serviceName);
namingServiceCreate(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP);
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "11.11.11.11", String.valueOf(TEST_PORT_4_DOM_1), "c1");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "22.22.22.22", String.valueOf(TEST_PORT_4_DOM_1), "c1");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "33.33.33.33", String.valueOf(TEST_PORT_4_DOM_1), "c2");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "44.44.44.44", String.valueOf(TEST_PORT_4_DOM_1), "c2");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "55.55.55.55", String.valueOf(TEST_PORT_4_DOM_1), "c1");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "66.66.66.66", String.valueOf(TEST_PORT_4_DOM_1), "c1");
namingServiceCreate(serviceName2, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP);
instanceRegister(serviceName2, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "77.77.77.77", String.valueOf(TEST_PORT_4_DOM_1), "c2");
instanceRegister(serviceName2, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "88.88.88.88", String.valueOf(TEST_PORT_4_DOM_1), "c2");
TimeUnit.SECONDS.sleep(10);
JSONObject json = new JSONObject();
json.put("type", "label");
json.put("expression", "");
ResponseEntity<String> httpResult = request("/nacos/v1/ns/service",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("protectThreshold", "0")
.appendParam("selector", json.toJSONString())
.done(),
String.class,
HttpMethod.PUT);
Assert.assertEquals(HttpURLConnection.HTTP_OK, httpResult.getStatusCodeValue());
httpResult = request("/nacos/v1/ns/instance/list",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("clientIP", "11.11.11.11")
.done(),
String.class,
HttpMethod.GET);
Assert.assertEquals(HttpURLConnection.HTTP_OK, httpResult.getStatusCodeValue());
json = JSON.parseObject(httpResult.getBody());
System.out.println("instance list = " + json);
Assert.assertEquals(6, json.getJSONArray("hosts").size());
}
/**
* @TCDescription : cmdb规则不同,expression为null,获取所有的instance
* @throws Exception
*/
@Test
public void cmdb_getInstanceList_9() throws Exception {
String serviceName = randomDomainName();
String serviceName2 = randomDomainName();
System.out.println(serviceName);
namingServiceCreate(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP);
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "11.11.11.11", String.valueOf(TEST_PORT_4_DOM_1), "c1");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "22.22.22.22", String.valueOf(TEST_PORT_4_DOM_1), "c1");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "33.33.33.33", String.valueOf(TEST_PORT_4_DOM_1), "c2");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "44.44.44.44", String.valueOf(TEST_PORT_4_DOM_1), "c2");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "55.55.55.55", String.valueOf(TEST_PORT_4_DOM_1), "c1");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "66.66.66.66", String.valueOf(TEST_PORT_4_DOM_1), "c1");
namingServiceCreate(serviceName2, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP);
instanceRegister(serviceName2, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "77.77.77.77", String.valueOf(TEST_PORT_4_DOM_1), "c2");
instanceRegister(serviceName2, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "88.88.88.88", String.valueOf(TEST_PORT_4_DOM_1), "c2");
TimeUnit.SECONDS.sleep(10);
JSONObject json = new JSONObject();
json.put("type", "label");
json.put("expression", "");
ResponseEntity<String> httpResult = request("/nacos/v1/ns/service",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("protectThreshold", "0")
.appendParam("selector", json.toJSONString())
.done(),
String.class,
HttpMethod.PUT);
Assert.assertEquals(HttpURLConnection.HTTP_OK, httpResult.getStatusCodeValue());
httpResult = request("/nacos/v1/ns/instance/list",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("clientIP", "11.11.11.11")
.done(),
String.class,
HttpMethod.GET);
Assert.assertEquals(HttpURLConnection.HTTP_OK, httpResult.getStatusCodeValue());
json = JSON.parseObject(httpResult.getBody());
System.out.println("instance list = " + json);
Assert.assertEquals(6, json.getJSONArray("hosts").size());
}
/**
* @TCDescription : cmdb规则不同,type为label填写异常
* @throws Exception
*/
@Test
public void cmdb_getInstanceList_10() throws Exception {
String serviceName = randomDomainName();
String serviceName2 = randomDomainName();
System.out.println(serviceName);
namingServiceCreate(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP);
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "11.11.11.11", String.valueOf(TEST_PORT_4_DOM_1), "c1");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "22.22.22.22", String.valueOf(TEST_PORT_4_DOM_1), "c1");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "33.33.33.33", String.valueOf(TEST_PORT_4_DOM_1), "c2");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "44.44.44.44", String.valueOf(TEST_PORT_4_DOM_1), "c2");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "55.55.55.55", String.valueOf(TEST_PORT_4_DOM_1), "c1");
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "66.66.66.66", String.valueOf(TEST_PORT_4_DOM_1), "c1");
namingServiceCreate(serviceName2, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP);
instanceRegister(serviceName2, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "77.77.77.77", String.valueOf(TEST_PORT_4_DOM_1), "c2");
instanceRegister(serviceName2, Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "88.88.88.88", String.valueOf(TEST_PORT_4_DOM_1), "c2");
TimeUnit.SECONDS.sleep(10);
JSONObject json = new JSONObject();
json.put("type", "label1");
json.put("expression", "CONSUMER.label.label1 = PROVIDER.label.label1 & CONSUMER.label.label2 = PROVIDER.label.label2");
ResponseEntity<String> httpResult = request("/nacos/v1/ns/service",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("protectThreshold", "0")
.appendParam("selector", json.toJSONString())
.done(),
String.class,
HttpMethod.PUT);
Assert.assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, httpResult.getStatusCodeValue());
}
public void instanceRegister(String serviceName, String namespace, String groupName, String ip, String port, String clusterName) throws
IOException {
ResponseEntity<String> httpResult = request( "/nacos/v1/ns/instance",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("ip", ip)
.appendParam("port", port)
.appendParam("namespaceId", namespace)
.appendParam("groupName", groupName)
.appendParam("clusterName", clusterName)
.appendParam("ephemeral", "false")
.done(),
String.class,
HttpMethod.POST);
Assert.assertEquals(HttpURLConnection.HTTP_OK, httpResult.getStatusCodeValue());
}
public void namingServiceCreate(String serviceName, String namespace) throws IOException {
namingServiceCreate(serviceName, namespace, Constants.DEFAULT_GROUP);
}
public void namingServiceCreate(String serviceName, String namespace, String groupName) throws IOException {
List<String> listParams = Arrays.asList("serviceName", serviceName, "protectThreshold", "0.3", "namespaceId", namespace, "groupName", groupName);
ResponseEntity<String> httpResult = request("/nacos/v1/ns/service",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("protectThreshold", "0.3")
.appendParam( "namespaceId", namespace)
.appendParam("groupName", groupName)
.done(),
String.class,
HttpMethod.POST);
Assert.assertEquals(HttpURLConnection.HTTP_OK, httpResult.getStatusCodeValue());
}
private <T> ResponseEntity<T> request(String path, MultiValueMap<String, String> params, Class<T> clazz) {
return request(path, params, clazz, org.springframework.http.HttpMethod.GET);
}
private <T> ResponseEntity<T> request(String path, MultiValueMap<String, String> params, Class<T> clazz, org.springframework.http.HttpMethod httpMethod) {
HttpHeaders headers = new HttpHeaders();
HttpEntity<?> entity = new HttpEntity<T>(headers);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(this.base.toString() + path)
.queryParams(params);
return this.restTemplate.exchange(
builder.toUriString(), httpMethod, entity, clazz);
}
}

View File

@ -0,0 +1,151 @@
/*
* 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.test.naming;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingMaintainFactory;
import com.alibaba.nacos.api.naming.NamingMaintainService;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.Service;
import com.alibaba.nacos.api.selector.ExpressionSelector;
import com.alibaba.nacos.api.selector.NoneSelector;
import com.alibaba.nacos.naming.NamingApp;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import static com.alibaba.nacos.test.naming.NamingBase.randomDomainName;
/**
* @author liaochuntao
* @date 2019-05-07 10:13
**/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = NamingApp.class, properties = {"server.servlet.context-path=/nacos"},
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class NamingMaintainService_ITCase {
private NamingMaintainService namingMaintainService;
private NamingService namingService;
private Instance instance;
private String serviceName;
@LocalServerPort
private int port;
@Before
public void init() throws Exception {
NamingBase.prepareServer(port);
if (namingMaintainService == null) {
TimeUnit.SECONDS.sleep(10);
namingMaintainService = NamingMaintainFactory.createMaintainService("127.0.0.1" + ":" + port);
}
if (namingService == null) {
TimeUnit.SECONDS.sleep(10);
namingService = NamingFactory.createNamingService("127.0.0.1" + ":" + port);
}
instance = new Instance();
instance.setIp("127.0.0.1");
instance.setPort(8081);
instance.setWeight(2);
instance.setClusterName(Constants.DEFAULT_CLUSTER_NAME);
Map<String, String> map = new HashMap<String, String>();
map.put("netType", "external");
map.put("version", "1.0");
instance.setMetadata(map);
serviceName = randomDomainName();
}
@Test
public void updateInstance() throws NacosException {
Map<String, String> map = new HashMap<String, String>();
map.put("netType", "external-update");
map.put("version", "2.0");
namingService.registerInstance(serviceName, instance);
instance.setMetadata(map);
namingMaintainService.updateInstance(serviceName, instance);
List<Instance> instances = namingService.getAllInstances(serviceName, true);
Assert.assertEquals(instances.size(), 1);
System.out.println(instances.get(0));
}
@Test
public void createAndUpdateService() throws NacosException {
// register service
Service preService = new Service();
preService.setName(serviceName);
preService.setGroupName(Constants.DEFAULT_GROUP);
preService.setProtectThreshold(1.0f);
Map<String, String> metadata = new HashMap<String, String>();
metadata.put(serviceName, "this is a register metadata");
preService.setMetadata(metadata);
ExpressionSelector selector = new ExpressionSelector();
selector.setExpression("CONSUMER.label.A=PROVIDER.label.A &CONSUMER.label.B=PROVIDER.label.B");
System.out.println("service info : " + preService);
namingMaintainService.createService(preService, selector);
Service remoteService = namingMaintainService.queryService(serviceName);
System.out.println("remote service info : " + remoteService);
Assert.assertEquals(preService.toString(), remoteService.toString());
// update service
Service nowService = new Service();
nowService.setName(serviceName);
nowService.setGroupName(Constants.DEFAULT_GROUP);
nowService.setProtectThreshold(1.0f);
metadata.clear();
metadata.put(serviceName, "this is a update metadata");
nowService.setMetadata(metadata);
namingMaintainService.updateService(nowService, new NoneSelector());
remoteService = namingMaintainService.queryService(serviceName);
System.out.println("remote service info : " + remoteService);
Assert.assertEquals(nowService.toString(), remoteService.toString());
}
@Test
public void deleteService() throws NacosException {
Service preService = new Service();
preService.setName(serviceName);
System.out.println("service info : " + preService);
namingMaintainService.createService(preService, new NoneSelector());
Assert.assertTrue(namingMaintainService.deleteService(serviceName));
}
}

View File

@ -23,7 +23,6 @@ import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.naming.NamingApp;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
@ -71,28 +70,21 @@ public class RegisterInstance_ITCase {
}
@Test
@Ignore
public void regService() throws NacosException, InterruptedException {
Properties properties = new Properties();
properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1:8848");
properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1:" + port);
properties.put(PropertyKeyConst.NAMESPACE, "t3");
naming = NamingFactory.createNamingService(properties);
TimeUnit.SECONDS.sleep(10);
String serviceName = "dungu.test.10";
naming.registerInstance(serviceName, "127.0.0.1", 80, "c1");
naming.registerInstance(serviceName, "127.0.0.2", 80, "c2");
Thread.sleep(100000000L);
}
List<Instance> instances = naming.getAllInstances(serviceName);
@Test
@Ignore
public void deregService() throws NacosException, InterruptedException {
String serviceName = "dungu.test.98";
System.out.println(naming.getAllInstances(serviceName));
// Thread.sleep(100000000L);
Assert.assertEquals(2, instances.size());
}
/**
@ -180,7 +172,6 @@ public class RegisterInstance_ITCase {
* @throws Exception
*/
@Test
@Ignore
public void regDomNotHealth() throws Exception {
String serviceName = randomDomainName();
System.out.println(serviceName);
@ -192,8 +183,7 @@ public class RegisterInstance_ITCase {
List<Instance> instances = naming.selectInstances(serviceName, false);
Assert.assertEquals(instances.size(), 1);
Assert.assertEquals(instances.get(0).isHealthy(), false);
Assert.assertEquals(0, instances.size());
}
@Test

View File

@ -15,13 +15,12 @@
*/
package com.alibaba.nacos.test.naming;
import java.net.URL;
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.naming.NamingApp;
import com.alibaba.nacos.naming.misc.UtilsAndCommons;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
@ -39,10 +38,6 @@ import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.MultiValueMap;
import org.springframework.web.util.UriComponentsBuilder;
import java.net.URL;
import static org.junit.Assert.assertTrue;
/**
* @author nkorange
*/
@ -64,427 +59,18 @@ public class RestAPI_ITCase {
public void setUp() throws Exception {
String url = String.format("http://localhost:%d/", port);
this.base = new URL(url);
prepareData();
//prepareData();
}
@After
public void cleanup() throws Exception {
removeData();
}
@Test
public void dom() throws Exception {
ResponseEntity<String> response = request("/nacos/v1/ns/api/dom",
Params.newParams().appendParam("dom", NamingBase.TEST_DOM_1).done(), String.class);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
JSONObject json = JSON.parseObject(response.getBody());
Assert.assertEquals(NamingBase.TEST_DOM_1, json.getString("name"));
}
@Test
public void domCount() throws Exception {
ResponseEntity<String> response = request("/nacos/v1/ns/api/domCount",
Params.newParams().done(), String.class);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
}
@Test
public void rt4Dom() throws Exception {
ResponseEntity<String> response = request("/nacos/v1/ns/api/rt4Dom",
Params.newParams().appendParam("dom", NamingBase.TEST_DOM_1).done(), String.class);
assertTrue(response.getStatusCode().is2xxSuccessful());
}
@Test
public void ip4Dom2() throws Exception {
ResponseEntity<String> response = request("/nacos/v1/ns/api/ip4Dom2",
Params.newParams().appendParam("dom", NamingBase.TEST_DOM_1).done(), String.class);
assertTrue(response.getStatusCode().is2xxSuccessful());
JSONObject json = JSON.parseObject(response.getBody());
Assert.assertNotNull(json.getJSONArray("ips"));
Assert.assertEquals(1, json.getJSONArray("ips").size());
Assert.assertEquals(NamingBase.TEST_IP_4_DOM_1 + ":" + NamingBase.TEST_PORT_4_DOM_1,
json.getJSONArray("ips").getString(0).split("_")[0]);
}
@Test
public void ip4Dom() throws Exception {
ResponseEntity<String> response = request("/nacos/v1/ns/api/ip4Dom",
Params.newParams().appendParam("dom", NamingBase.TEST_DOM_1).done(), String.class);
assertTrue(response.getStatusCode().is2xxSuccessful());
JSONObject json = JSON.parseObject(response.getBody());
Assert.assertNotNull(json.getJSONArray("ips"));
Assert.assertEquals(1, json.getJSONArray("ips").size());
Assert.assertEquals(NamingBase.TEST_IP_4_DOM_1, json.getJSONArray("ips").getJSONObject(0).getString("ip"));
Assert.assertEquals(NamingBase.TEST_PORT_4_DOM_1, json.getJSONArray("ips").getJSONObject(0).getString("port"));
}
@Test
public void replaceDom() throws Exception {
ResponseEntity<String> response = request("/nacos/v1/ns/api/replaceDom",
Params.newParams()
.appendParam("dom", NamingBase.TEST_DOM_1)
.appendParam("token", NamingBase.TEST_TOKEN_4_DOM_1)
.appendParam("protectThreshold", "0.5")
.appendParam("enableHealthCheck", "false")
.appendParam("cktype", "HTTP")
.appendParam("ipPort4Check", "false")
.appendParam("path", "/hello")
.appendParam("headers", "1.1.1.1")
.appendParam("defCkport", "8080")
.appendParam("defIPPort", "8888")
.done(), String.class);
assertTrue(response.getStatusCode().is2xxSuccessful());
response = request("/nacos/naming/api/dom",
Params.newParams().appendParam("dom", NamingBase.TEST_DOM_1).done(), String.class);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
JSONObject json = JSON.parseObject(response.getBody());
Assert.assertEquals(NamingBase.TEST_DOM_1, json.getString("name"));
Assert.assertEquals("0.5", json.getString("protectThreshold"));
Assert.assertEquals(NamingBase.TEST_TOKEN_4_DOM_1, json.getString("token"));
Assert.assertEquals("false", json.getString("enableHealthCheck"));
JSONArray clusters = json.getJSONArray("clusters");
Assert.assertNotNull(clusters);
Assert.assertEquals(1, clusters.size());
Assert.assertEquals(false, clusters.getJSONObject(0).getBooleanValue("useIPPort4Check"));
Assert.assertEquals(8888, clusters.getJSONObject(0).getIntValue("defIPPort"));
Assert.assertEquals(8080, clusters.getJSONObject(0).getIntValue("defCkport"));
}
@Test
public void regAndDeregService() throws Exception {
ResponseEntity<String> response = request("/nacos/v1/ns/api/regService",
Params.newParams()
.appendParam("dom", NamingBase.TEST_DOM_2)
.appendParam("app", "test1")
.appendParam("ip", NamingBase.TEST_IP_4_DOM_2)
.appendParam("port", NamingBase.TEST_PORT_4_DOM_2)
.appendParam("cluster", "DEFAULT")
.appendParam("token", NamingBase.TETS_TOKEN_4_DOM_2)
.done(), String.class);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
response = request("/nacos/v1/ns/api/deRegService",
Params.newParams()
.appendParam("dom", NamingBase.TEST_DOM_2)
.appendParam("ip", NamingBase.TEST_IP_4_DOM_2)
.appendParam("port", NamingBase.TEST_PORT_4_DOM_2)
.appendParam("cluster", "DEFAULT")
.appendParam("token", NamingBase.TETS_TOKEN_4_DOM_2)
.done(), String.class);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
}
@Test
public void updateDom() throws Exception {
ResponseEntity<String> response = request("/nacos/v1/ns/api/updateDom",
Params.newParams()
.appendParam("dom", NamingBase.TEST_DOM_1)
.appendParam("token", NamingBase.TEST_TOKEN_4_DOM_1)
.appendParam("protectThreshold", "0.8")
.appendParam("enableHealthCheck", "false")
.appendParam("cktype", "TCP")
.appendParam("ipPort4Check", "false")
.appendParam("defCkPort", "10000")
.appendParam("defIPPort", "20000")
.done(), String.class);
assertTrue(response.getStatusCode().is2xxSuccessful());
response = request("/nacos/v1/ns/api/dom",
Params.newParams().appendParam("dom", NamingBase.TEST_DOM_1).done(), String.class);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
JSONObject json = JSON.parseObject(response.getBody());
Assert.assertEquals(NamingBase.TEST_DOM_1, json.getString("name"));
Assert.assertEquals("0.8", json.getString("protectThreshold"));
Assert.assertEquals("false", json.getString("enableHealthCheck"));
JSONArray clusters = json.getJSONArray("clusters");
Assert.assertNotNull(clusters);
Assert.assertEquals(1, clusters.size());
Assert.assertEquals(false, clusters.getJSONObject(0).getBooleanValue("useIPPort4Check"));
Assert.assertEquals(20000, clusters.getJSONObject(0).getIntValue("defIPPort"));
Assert.assertEquals(10000, clusters.getJSONObject(0).getIntValue("defCkport"));
}
@Test
public void hello() throws Exception {
ResponseEntity<String> response = request("/nacos/v1/ns/api/hello",
Params.newParams().done(), String.class);
assertTrue(response.getStatusCode().is2xxSuccessful());
}
@Test
public void replaceIP4Dom() throws Exception {
ResponseEntity<String> response = request("/nacos/v1/ns/api/replaceIP4Dom",
Params.newParams()
.appendParam("dom", NamingBase.TEST_DOM_1)
.appendParam("cluster", "DEFAULT")
.appendParam("ipList", NamingBase.TEST_IP_4_DOM_1 + ":" + NamingBase.TEST_PORT2_4_DOM_1)
.appendParam("token", NamingBase.TEST_TOKEN_4_DOM_1)
.done(), String.class);
assertTrue(response.getStatusCode().is2xxSuccessful());
response = request("/nacos/v1/ns/api/ip4Dom2",
Params.newParams().appendParam("dom", NamingBase.TEST_DOM_1).done(), String.class);
assertTrue(response.getStatusCode().is2xxSuccessful());
JSONObject json = JSON.parseObject(response.getBody());
Assert.assertNotNull(json.getJSONArray("ips"));
Assert.assertEquals(1, json.getJSONArray("ips").size());
Assert.assertEquals(NamingBase.TEST_IP_4_DOM_1 + ":" + NamingBase.TEST_PORT2_4_DOM_1,
json.getJSONArray("ips").getString(0).split("_")[0]);
}
@Test
public void remvIP4Dom() throws Exception {
ResponseEntity<String> response = request("/nacos/v1/ns/api/addIP4Dom",
Params.newParams()
.appendParam("dom", NamingBase.TEST_DOM_1)
.appendParam("ipList", NamingBase.TEST_IP_4_DOM_1 + ":" + NamingBase.TEST_PORT2_4_DOM_1)
.appendParam("token", NamingBase.TEST_TOKEN_4_DOM_1).done(),
String.class);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
response = request("/nacos/v1/ns/api/remvIP4Dom",
Params.newParams()
.appendParam("dom", NamingBase.TEST_DOM_1)
.appendParam("ipList", NamingBase.TEST_IP_4_DOM_1 + ":" + NamingBase.TEST_PORT2_4_DOM_1)
.appendParam("token", NamingBase.TEST_TOKEN_4_DOM_1).done(),
String.class);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
}
@Test
public void updateSwitch() throws Exception {
ResponseEntity<String> response = request("/nacos/v1/ns/api/updateSwitch",
Params.newParams()
.appendParam("entry", "distroThreshold")
.appendParam("distroThreshold", "0.3")
.appendParam("token", "xy").done(),
String.class);
assertTrue(response.getStatusCode().is2xxSuccessful());
response = request("/nacos/v1/ns/api/updateSwitch",
Params.newParams()
.appendParam("entry", "enableAllDomNameCache")
.appendParam("enableAllDomNameCache", "false")
.appendParam("token", "xy").done(),
String.class);
assertTrue(response.getStatusCode().is2xxSuccessful());
response = request("/nacos/v1/ns/api/updateSwitch",
Params.newParams()
.appendParam("entry", "incrementalList")
.appendParam("incrementalList", "1.com,2.com")
.appendParam("action", "update")
.appendParam("token", "xy").done(),
String.class);
assertTrue(response.getStatusCode().is2xxSuccessful());
response = request("/nacos/v1/ns/api/updateSwitch",
Params.newParams()
.appendParam("entry", "healthCheckWhiteList")
.appendParam("healthCheckWhiteList", "1.com,2.com")
.appendParam("action", "update")
.appendParam("token", "xy").done(),
String.class);
assertTrue(response.getStatusCode().is2xxSuccessful());
response = request("/nacos/v1/ns/api/updateSwitch",
Params.newParams()
.appendParam("entry", "clientBeatInterval")
.appendParam("clientBeatInterval", "5000")
.appendParam("token", "xy").done(),
String.class);
assertTrue(response.getStatusCode().is2xxSuccessful());
response = request("/nacos/v1/ns/api/updateSwitch",
Params.newParams()
.appendParam("entry", "pushVersion")
.appendParam("type", "java")
.appendParam("version", "4.0.0")
.appendParam("token", "xy").done(),
String.class);
assertTrue(response.getStatusCode().is2xxSuccessful());
response = request("/nacos/v1/ns/api/updateSwitch",
Params.newParams()
.appendParam("entry", "pushCacheMillis")
.appendParam("millis", "30000")
.appendParam("token", "xy").done(),
String.class);
assertTrue(response.getStatusCode().is2xxSuccessful());
response = request("/nacos/v1/ns/api/updateSwitch",
Params.newParams()
.appendParam("entry", "defaultCacheMillis")
.appendParam("millis", "3000")
.appendParam("token", "xy").done(),
String.class);
assertTrue(response.getStatusCode().is2xxSuccessful());
response = request("/nacos/v1/ns/api/switches",
Params.newParams().done(),
String.class);
assertTrue(response.getStatusCode().is2xxSuccessful());
JSONObject switches = JSON.parseObject(response.getBody());
System.out.println(switches);
Assert.assertEquals("0.3", switches.getString("distroThreshold"));
Assert.assertEquals("false", switches.getString("allDomNameCache"));
Assert.assertTrue(switches.getJSONArray("incrementalList").contains("1.com"));
Assert.assertTrue(switches.getJSONArray("incrementalList").contains("2.com"));
Assert.assertTrue(switches.getJSONArray("healthCheckWhiteList").contains("1.com"));
Assert.assertTrue(switches.getJSONArray("healthCheckWhiteList").contains("2.com"));
Assert.assertEquals("5000", switches.getString("clientBeatInterval"));
Assert.assertEquals("4.0.0", switches.getString("pushJavaVersion"));
Assert.assertEquals("30000", switches.getString("defaultPushCacheMillis"));
Assert.assertEquals("3000", switches.getString("defaultCacheMillis"));
}
@Test
public void allDomNames() throws Exception {
ResponseEntity<String> response = request("/nacos/v1/ns/api/allDomNames",
Params.newParams().done(),
String.class);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
JSONObject json = JSON.parseObject(response.getBody());
Assert.assertEquals(json.getIntValue("count"), json.getJSONArray("doms").size());
}
@Test
public void searchDom() throws Exception {
ResponseEntity<String> response = request("/nacos/v1/ns/api/searchDom",
Params.newParams()
.appendParam("expr", "nacos")
.done(),
String.class);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
JSONObject json = JSON.parseObject(response.getBody());
Assert.assertTrue(json.getJSONArray("doms").size() > 0);
}
@Test
public void addCluster4Dom() throws Exception {
ResponseEntity<String> response = request("/nacos/v1/ns/api/addCluster4Dom",
Params.newParams()
.appendParam("dom", NamingBase.TEST_DOM_1)
.appendParam("token", NamingBase.TEST_TOKEN_4_DOM_1)
.appendParam("clusterName", NamingBase.TEST_NEW_CLUSTER_4_DOM_1)
.appendParam("cktype", "TCP")
.appendParam("defIPPort", "1111")
.appendParam("defCkport", "2222")
.done(),
String.class);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
response = request("/nacos/v1/ns/api/dom",
Params.newParams().appendParam("dom", NamingBase.TEST_DOM_1).done(), String.class);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Assert.assertTrue(response.getBody().contains(NamingBase.TEST_NEW_CLUSTER_4_DOM_1));
JSONObject json = JSON.parseObject(response.getBody());
Assert.assertEquals(NamingBase.TEST_DOM_1, json.getString("name"));
JSONArray clusters = json.getJSONArray("clusters");
Assert.assertEquals(2, clusters.size());
for (int i=0; i<2; i++) {
JSONObject cluster = clusters.getJSONObject(i);
if (cluster.getString("name").equals(NamingBase.TEST_NEW_CLUSTER_4_DOM_1)) {
Assert.assertEquals("1111", cluster.getString("defIPPort"));
Assert.assertEquals("2222", cluster.getString("defCkport"));
}
}
}
@Test
public void distroStatus() throws Exception {
ResponseEntity<String> response = request("/nacos/v1/ns/api/distroStatus",
Params.newParams()
.done(),
String.class);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
//removeData();
}
@Test
public void metrics() throws Exception {
ResponseEntity<String> response = request("/nacos/v1/ns/api/metrics",
ResponseEntity<String> response = request("/nacos/v1/ns/operator/metrics",
Params.newParams()
.done(),
String.class);
@ -492,56 +78,10 @@ public class RestAPI_ITCase {
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
JSONObject json = JSON.parseObject(response.getBody());
Assert.assertTrue(json.getIntValue("domCount") > 0);
Assert.assertTrue(json.getIntValue("ipCount") > 0);
Assert.assertTrue(json.getIntValue("responsibleDomCount") > 0);
Assert.assertTrue(json.getIntValue("responsibleIPCount") > 0);
}
@Test
public void updateClusterConf() throws Exception {
// TODO
}
@Test
public void reCalculateCheckSum4Dom() throws Exception {
ResponseEntity<String> response = request("/nacos/v1/ns/api/reCalculateCheckSum4Dom",
Params.newParams()
.appendParam(CommonParams.NAMESPACE_ID, Constants.DEFAULT_NAMESPACE_ID)
.appendParam("dom", NamingBase.TEST_DOM_1)
.done(),
String.class);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
}
@Test
public void getResponsibleServer4Dom() throws Exception {
ResponseEntity<String> response = request("/nacos/v1/ns/api/getResponsibleServer4Dom",
Params.newParams()
.appendParam("dom", NamingBase.TEST_DOM_1)
.done(),
String.class);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
}
@Test
public void domServeStatus() throws Exception {
ResponseEntity<String> response = request("/nacos/v1/ns/api/domServeStatus",
Params.newParams()
.appendParam("dom", NamingBase.TEST_DOM_1)
.done(),
String.class);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
JSONObject json = JSON.parseObject(response.getBody());
Assert.assertTrue(json.getBooleanValue("success"));
Assert.assertTrue(json.getJSONObject("data").getJSONArray("ips").size() > 0);
Assert.assertTrue(json.getIntValue("serviceCount") > 0);
Assert.assertTrue(json.getIntValue("instanceCount") > 0);
Assert.assertTrue(json.getIntValue("responsibleServiceCount") > 0);
Assert.assertTrue(json.getIntValue("responsibleInstanceCount") > 0);
}
/**
@ -555,9 +95,10 @@ public class RestAPI_ITCase {
ResponseEntity<String> response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("protectThreshold", "0.3")
.done(),
String.class,
HttpMethod.PUT);
HttpMethod.POST);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Assert.assertEquals("ok", response.getBody());
@ -575,9 +116,10 @@ public class RestAPI_ITCase {
ResponseEntity<String> response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("protectThreshold", "0.3")
.done(),
String.class,
HttpMethod.PUT);
HttpMethod.POST);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Assert.assertEquals("ok", response.getBody());
@ -585,6 +127,7 @@ public class RestAPI_ITCase {
response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("protectThreshold", "0.3")
.done(),
String.class);
@ -621,9 +164,10 @@ public class RestAPI_ITCase {
response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("protectThreshold", "0.3")
.done(),
String.class,
HttpMethod.PUT);
HttpMethod.POST);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Assert.assertEquals("ok", response.getBody());
@ -653,9 +197,10 @@ public class RestAPI_ITCase {
ResponseEntity<String> response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("protectThreshold", "0.6")
.done(),
String.class,
HttpMethod.PUT);
HttpMethod.POST);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Assert.assertEquals("ok", response.getBody());
@ -664,10 +209,10 @@ public class RestAPI_ITCase {
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("healthCheckMode", "server")
.appendParam("protectThreshold", "3")
.appendParam("protectThreshold", "0.3")
.done(),
String.class,
HttpMethod.POST);
HttpMethod.PUT);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Assert.assertEquals("ok", response.getBody());
@ -682,7 +227,7 @@ public class RestAPI_ITCase {
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
JSONObject json = JSON.parseObject(response.getBody());
System.out.println(json);
Assert.assertEquals(3.0f, json.getFloatValue("protectThreshold"), 0.0f);
Assert.assertEquals(0.3f, json.getFloatValue("protectThreshold"), 0.0f);
namingServiceDelete(serviceName);
}
@ -692,6 +237,7 @@ public class RestAPI_ITCase {
ResponseEntity<String> response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("protectThreshold", "0.3")
.done(),
String.class,
HttpMethod.DELETE);

View File

@ -24,7 +24,6 @@ import com.alibaba.nacos.api.selector.ExpressionSelector;
import com.alibaba.nacos.naming.NamingApp;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
@ -76,7 +75,6 @@ public class SelectInstances_ITCase {
* @throws Exception
*/
@Test
@Ignore
public void selectHealthyInstances() throws Exception {
String serviceName = randomDomainName();
naming.registerInstance(serviceName, "127.0.0.1", TEST_PORT);
@ -86,8 +84,7 @@ public class SelectInstances_ITCase {
List<Instance> instances = naming.selectInstances(serviceName, true);
Assert.assertEquals(1, instances.size());
Assert.assertEquals(2, instances.size());
Instance instanceNotH = null;
List<Instance> instancesGet = naming.getAllInstances(serviceName);
@ -108,7 +105,6 @@ public class SelectInstances_ITCase {
* @throws Exception
*/
@Test
@Ignore
public void selectUnhealthyInstances() throws Exception {
String serviceName = randomDomainName();
naming.registerInstance(serviceName, "1.1.1.1", TEST_PORT);
@ -118,7 +114,7 @@ public class SelectInstances_ITCase {
List<Instance> instances = naming.selectInstances(serviceName, false);
TimeUnit.SECONDS.sleep(2);
Assert.assertEquals(2, instances.size());
Assert.assertEquals(0, instances.size());
List<Instance> instancesGet = naming.getAllInstances(serviceName);
@ -131,7 +127,6 @@ public class SelectInstances_ITCase {
* @throws Exception
*/
@Test
@Ignore
public void selectHealthyInstancesClusters() throws Exception {
String serviceName = randomDomainName();
naming.registerInstance(serviceName, "127.0.0.1", TEST_PORT, "c1");
@ -153,7 +148,6 @@ public class SelectInstances_ITCase {
* @throws Exception
*/
@Test
@Ignore
public void selectUnhealthyInstancesClusters() throws Exception {
String serviceName = randomDomainName();
naming.registerInstance(serviceName, "1.1.1.1", TEST_PORT, "c1");
@ -162,7 +156,7 @@ public class SelectInstances_ITCase {
TimeUnit.SECONDS.sleep(8);
List<Instance> instances = naming.selectInstances(serviceName, Arrays.asList("c1", "c2"), false);
TimeUnit.SECONDS.sleep(2);
Assert.assertEquals(instances.size(), 2);
Assert.assertEquals(0, instances.size());
List<Instance> instancesGet = naming.getAllInstances(serviceName);