Merge branch 'develop' into hotfix_jackson_vulnerability

This commit is contained in:
Fury Zhu 2019-05-24 19:35:36 +08:00 committed by GitHub
commit d5b5dbb85e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
68 changed files with 3557 additions and 1853 deletions

View File

@ -32,8 +32,8 @@
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<configuration> <configuration>
<source>6</source> <source>7</source>
<target>6</target> <target>7</target>
</configuration> </configuration>
</plugin> </plugin>
</plugins> </plugins>

View File

@ -20,6 +20,8 @@ import java.util.Properties;
import com.alibaba.nacos.api.config.ConfigFactory; import com.alibaba.nacos.api.config.ConfigFactory;
import com.alibaba.nacos.api.config.ConfigService; import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException; 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.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.NamingService;
@ -74,4 +76,26 @@ public class NacosFactory {
return NamingFactory.createNamingService(properties); 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 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 LINE_SEPARATOR = Character.toString((char)1);
public static final String WORD_SEPARATOR = Character.toString((char)2); 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.listener.EventListener;
import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.ListView; 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.naming.pojo.ServiceInfo;
import com.alibaba.nacos.api.selector.AbstractSelector; import com.alibaba.nacos.api.selector.AbstractSelector;
import java.util.List; import java.util.List;
import java.util.Map;
/** /**
* Naming Service * Naming Service

View File

@ -28,6 +28,10 @@ public class NamingEvent implements Event {
private String serviceName; private String serviceName;
private String groupName;
private String clusters;
private List<Instance> instances; private List<Instance> instances;
public NamingEvent(String serviceName, List<Instance> instances) { public NamingEvent(String serviceName, List<Instance> instances) {
@ -35,6 +39,13 @@ public class NamingEvent implements Event {
this.instances = instances; 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() { public String getServiceName() {
return serviceName; return serviceName;
} }
@ -50,4 +61,20 @@ public class NamingEvent implements Event {
public void setInstances(List<Instance> instances) { public void setInstances(List<Instance> instances) {
this.instances = 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; package com.alibaba.nacos.api.naming.pojo;
import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.annotation.JSONField;
import com.alibaba.fastjson.serializer.SerializeWriter;
import com.alibaba.nacos.api.common.Constants; import com.alibaba.nacos.api.common.Constants;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
@ -45,8 +46,16 @@ public abstract class AbstractHealthChecker implements Cloneable {
* @return Another instance with exactly the same fields. * @return Another instance with exactly the same fields.
* @throws CloneNotSupportedException * @throws CloneNotSupportedException
*/ */
@Override
public abstract AbstractHealthChecker clone() throws CloneNotSupportedException; public abstract AbstractHealthChecker clone() throws CloneNotSupportedException;
/**
* used to JsonAdapter
*/
public void jsonAdapterCallback(SerializeWriter writer){
// do nothing
}
public static class None extends AbstractHealthChecker { public static class None extends AbstractHealthChecker {
public static final String TYPE = "NONE"; public static final String TYPE = "NONE";
@ -116,6 +125,17 @@ public abstract class AbstractHealthChecker implements Cloneable {
return headerMap; return headerMap;
} }
/**
* used to JsonAdapter
*
* @param writer
*/
@Override
public void jsonAdapterCallback(SerializeWriter writer) {
writer.writeFieldValue(',', "path", getPath());
writer.writeFieldValue(',', "headers", getHeaders());
}
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hash(path, headers, expectedResponseCode); return Objects.hash(path, headers, expectedResponseCode);
@ -215,6 +235,18 @@ public abstract class AbstractHealthChecker implements Cloneable {
this.pwd = pwd; 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 @Override
public int hashCode() { public int hashCode() {
return Objects.hash(user, pwd, cmd); return Objects.hash(user, pwd, cmd);

View File

@ -101,4 +101,15 @@ public class Service {
public void addMetadata(String key, String value) { public void addMetadata(String key, String value) {
this.metadata.put(key, 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; private volatile boolean isUseLocalConfig = false;
/** /**
* last motify time * last modify time
*/ */
private volatile long localConfigLastModified; private volatile long localConfigLastModified;
private volatile String content; private volatile String content;

View File

@ -16,31 +16,19 @@
package com.alibaba.nacos.client.logging.log4j2; package com.alibaba.nacos.client.logging.log4j2;
import com.alibaba.nacos.client.logging.AbstractNacosLogging; 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 com.alibaba.nacos.common.util.ResourceUtils;
import org.apache.logging.log4j.LogManager; 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.LoggerContext;
import org.apache.logging.log4j.core.config.AbstractConfiguration;
import org.apache.logging.log4j.core.config.Configuration; import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.ConfigurationFactory; import org.apache.logging.log4j.core.config.ConfigurationFactory;
import org.apache.logging.log4j.core.config.ConfigurationSource; import org.apache.logging.log4j.core.config.ConfigurationSource;
import org.apache.logging.log4j.core.config.composite.CompositeConfiguration; import org.apache.logging.log4j.core.config.LoggerConfig;
import org.apache.logging.log4j.core.lookup.Interpolator;
import org.apache.logging.log4j.core.lookup.StrSubstitutor;
import org.apache.logging.log4j.util.PropertiesUtil;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.net.URL; import java.net.URL;
import java.util.ArrayList; import java.util.Map;
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;
/** /**
* Support for Log4j version 2.7 or higher * 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 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 String location = getLocation(NACOS_LOG4J2_LOCATION);
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);
}
}
@Override @Override
public void loadConfiguration() { public void loadConfiguration() {
if (locationList.isEmpty()) { final LoggerContext loggerContext = (LoggerContext)LogManager.getContext(false);
return; 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);
} }
Map<String, LoggerConfig> loggers = configuration.getLoggers();
List<String> configList = findConfig(getCurrentlySupportedConfigLocations()); for (String name : loggers.keySet()) {
if (configList != null) { if (name.startsWith(NACOS_LOGGER_PREFIX)) {
locationList.addAll(configList); contextConfiguration.addLogger(name, loggers.get(name));
}
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);
} }
} }
// since log4j 2.6 loggerContext.updateLoggers();
CompositeConfiguration compositeConfiguration = new CompositeConfiguration(configurations);
loggerContext.start(compositeConfiguration);
} }
private Configuration loadConfiguration(LoggerContext loggerContext, String location) { private Configuration loadConfiguration(LoggerContext loggerContext, String location) {
@ -119,43 +89,4 @@ public class Log4J2NacosLogging extends AbstractNacosLogging {
} }
return new ConfigurationSource(stream, url); 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; package com.alibaba.nacos.client.naming;
import com.alibaba.nacos.api.PropertyKeyConst; import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.SystemPropertyKeyConst;
import com.alibaba.nacos.api.common.Constants; import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService; 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.pojo.ServiceInfo;
import com.alibaba.nacos.api.naming.utils.NamingUtils; import com.alibaba.nacos.api.naming.utils.NamingUtils;
import com.alibaba.nacos.api.selector.AbstractSelector; 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.BeatInfo;
import com.alibaba.nacos.client.naming.beat.BeatReactor; import com.alibaba.nacos.client.naming.beat.BeatReactor;
import com.alibaba.nacos.client.naming.core.Balancer; 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.core.HostReactor;
import com.alibaba.nacos.client.naming.net.NamingProxy; import com.alibaba.nacos.client.naming.net.NamingProxy;
import com.alibaba.nacos.client.naming.utils.CollectionUtils; 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.naming.utils.UtilAndComs;
import com.alibaba.nacos.client.utils.LogUtils; import com.alibaba.nacos.client.utils.*;
import com.alibaba.nacos.client.utils.ParamUtil;
import com.alibaba.nacos.client.utils.StringUtils;
import com.alibaba.nacos.client.utils.TemplateUtils;
import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.math.NumberUtils; import org.apache.commons.lang3.math.NumberUtils;
import java.util.ArrayList; import java.util.*;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.Callable;
/** /**
* @author nkorange * @author nkorange
@ -87,10 +79,9 @@ public class NacosNamingService implements NamingService {
} }
private void init(Properties properties) { private void init(Properties properties) {
serverList = properties.getProperty(PropertyKeyConst.SERVER_ADDR); namespace = InitUtils.initNamespace(properties);
initNamespace(properties); initServerAddr(properties);
initEndpoint(properties); InitUtils.initWebRootContext();
initWebRootContext();
initCacheDir(); initCacheDir();
initLogName(properties); initLogName(properties);
@ -130,6 +121,14 @@ public class NacosNamingService implements NamingService {
return loadCacheAtStart; 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) { private void initLogName(Properties properties) {
logName = System.getProperty(UtilAndComs.NACOS_NAMING_LOG_NAME); logName = System.getProperty(UtilAndComs.NACOS_NAMING_LOG_NAME);
if (StringUtils.isEmpty(logName)) { 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 @Override
public void registerInstance(String serviceName, String ip, int port) throws NacosException { public void registerInstance(String serviceName, String ip, int port) throws NacosException {
registerInstance(serviceName, ip, port, Constants.DEFAULT_CLUSTER_NAME); registerInstance(serviceName, ip, port, Constants.DEFAULT_CLUSTER_NAME);

View File

@ -125,7 +125,7 @@ public class EventDispatcher {
if (!CollectionUtils.isEmpty(listeners)) { if (!CollectionUtils.isEmpty(listeners)) {
for (EventListener listener : listeners) { for (EventListener listener : listeners) {
List<Instance> hosts = Collections.unmodifiableList(serviceInfo.getHosts()); 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.CommonParams;
import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.ListView; 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.AbstractSelector;
import com.alibaba.nacos.api.selector.ExpressionSelector; import com.alibaba.nacos.api.selector.ExpressionSelector;
import com.alibaba.nacos.api.selector.SelectorType; import com.alibaba.nacos.api.selector.SelectorType;
@ -170,7 +171,7 @@ public class NamingProxy {
NAMING_LOGGER.info("[REGISTER-SERVICE] {} registering service {} with instance: {}", NAMING_LOGGER.info("[REGISTER-SERVICE] {} registering service {} with instance: {}",
namespaceId, serviceName, 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.NAMESPACE_ID, namespaceId);
params.put(CommonParams.SERVICE_NAME, serviceName); params.put(CommonParams.SERVICE_NAME, serviceName);
params.put(CommonParams.GROUP_NAME, groupName); params.put(CommonParams.GROUP_NAME, groupName);
@ -203,6 +204,84 @@ public class NamingProxy {
reqAPI(UtilAndComs.NACOS_URL_INSTANCE, params, HttpMethod.DELETE); 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) public String queryList(String serviceName, String clusters, int udpPort, boolean healthyOnly)
throws NacosException { 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_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 ENCODING = "UTF-8";
public static final String ENV_LIST_KEY = "envList"; public static final String ENV_LIST_KEY = "envList";

View File

@ -45,5 +45,8 @@
additivity="false"> additivity="false">
<AppenderRef ref="NAMING_LOG_FILE"/> <AppenderRef ref="NAMING_LOG_FILE"/>
</Logger> </Logger>
<Root level="INFO">
<AppenderRef ref="CONFIG_LOG_FILE"/>
</Root>
</Loggers> </Loggers>
</Configuration> </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"); log.warn("clearConfigHistory start");
if (ServerListService.isFirstIp()) { if (ServerListService.isFirstIp()) {
try { try {
Timestamp startTime = getBeforeStamp(TimeUtils.getCurrentTime(), 24 * 30); Timestamp startTime = getBeforeStamp(TimeUtils.getCurrentTime(), 24 * getRetentionDays());
int totalCount = persistService.findConfigHistoryCountByTime(startTime); int totalCount = persistService.findConfigHistoryCountByTime(startTime);
if (totalCount > 0) { if (totalCount > 0) {
int pageSize = 1000; int pageSize = 1000;
@ -278,6 +278,25 @@ public class DumpService {
return isQuickStart; 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) { public void dump(String dataId, String group, String tenant, String tag, long lastModified, String handleIp) {
dump(dataId, group, tenant, tag, lastModified, handleIp, false); dump(dataId, group, tenant, tag, lastModified, handleIp, false);
} }
@ -400,4 +419,5 @@ public class DumpService {
Boolean isQuickStart = false; 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();
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

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 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" set "JAVA=%JAVA_HOME%\bin\java.exe"
setlocal setlocal enabledelayedexpansion
set BASE_DIR=%~dp0 set BASE_DIR=%~dp0
rem added double quotation marks to avoid the issue caused by the folder names containing spaces. 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 DEFAULT_SEARCH_LOCATIONS="classpath:/,classpath:/config/,file:./,file:./config/"
set CUSTOM_SEARCH_LOCATIONS=%DEFAULT_SEARCH_LOCATIONS%,file:%BASE_DIR%/conf/ 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% -Xms512m -Xmx512m -Xmn256m"
set "JAVA_OPT=%JAVA_OPT% -Dnacos.standalone=true" 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% -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:-OmitStackTraceInFastThrow XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=%BASE_DIR%\logs\java_heapdump.hprof"
set "JAVA_OPT=%JAVA_OPT% -XX:-UseLargePages" set "JAVA_OPT=%JAVA_OPT% -XX:-UseLargePages"
) )
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% -Xbootclasspath/a:%BASE_DIR%\plugins\cmdb:%BASE_DIR%\plugins\mysql"
set "JAVA_OPT=%JAVA_OPT% -Dnacos.home=%BASE_DIR%" 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% --spring.config.location=%CUSTOM_SEARCH_LOCATIONS%"
set "JAVA_OPT=%JAVA_OPT% --logging.config=%BASE_DIR%/conf/nacos-logback.xml" set "JAVA_OPT=%JAVA_OPT% --logging.config=%BASE_DIR%/conf/nacos-logback.xml"

View File

@ -102,7 +102,7 @@ else
fi fi
JAVA_OPT="${JAVA_OPT} -Dnacos.home=${BASE_DIR}" 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} ${JAVA_OPT_EXT}"
JAVA_OPT="${JAVA_OPT} --spring.config.location=${CUSTOM_SEARCH_LOCATIONS}" JAVA_OPT="${JAVA_OPT} --spring.config.location=${CUSTOM_SEARCH_LOCATIONS}"
JAVA_OPT="${JAVA_OPT} --logging.config=${BASE_DIR}/conf/nacos-logback.xml" JAVA_OPT="${JAVA_OPT} --logging.config=${BASE_DIR}/conf/nacos-logback.xml"

View File

@ -58,13 +58,12 @@ public class CatalogController {
@RequestMapping(value = "/service") @RequestMapping(value = "/service")
public JSONObject serviceDetail(HttpServletRequest request) throws Exception { public JSONObject serviceDetail(HttpServletRequest request) throws Exception {
String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID, String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID,
Constants.DEFAULT_NAMESPACE_ID); Constants.DEFAULT_NAMESPACE_ID);
String serviceName = WebUtils.required(request, CommonParams.SERVICE_NAME); 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) { 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(); JSONObject detailView = new JSONObject();
@ -80,7 +79,7 @@ public class CatalogController {
List<Cluster> clusters = new ArrayList<>(); 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(); Cluster clusterView = new Cluster();
clusterView.setName(cluster.getName()); clusterView.setName(cluster.getName());
clusterView.setHealthChecker(cluster.getHealthChecker()); clusterView.setHealthChecker(cluster.getHealthChecker());
@ -88,7 +87,7 @@ public class CatalogController {
clusterView.setUseIPPort4Check(cluster.isUseIPPort4Check()); clusterView.setUseIPPort4Check(cluster.isUseIPPort4Check());
clusterView.setDefaultPort(cluster.getDefaultPort()); clusterView.setDefaultPort(cluster.getDefaultPort());
clusterView.setDefaultCheckPort(cluster.getDefaultCheckPort()); clusterView.setDefaultCheckPort(cluster.getDefaultCheckPort());
clusterView.setServiceName(serviceName); clusterView.setServiceName(cluster.getService().getName());
clusters.add(clusterView); clusters.add(clusterView);
} }
@ -141,7 +140,7 @@ public class CatalogController {
} }
@RequestMapping(value = "/services", method = RequestMethod.GET) @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")); boolean withInstances = Boolean.parseBoolean(WebUtils.optional(request, "withInstances", "true"));
@ -248,7 +247,7 @@ public class CatalogController {
return ipAddressInfos; return ipAddressInfos;
} }
private JSONObject serviceList(HttpServletRequest request) throws Exception { private JSONObject serviceList(HttpServletRequest request) {
String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID, String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID,
Constants.DEFAULT_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.Service;
import com.alibaba.nacos.naming.core.ServiceManager; import com.alibaba.nacos.naming.core.ServiceManager;
import com.alibaba.nacos.naming.exception.NacosException; 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.Loggers;
import com.alibaba.nacos.naming.misc.UtilsAndCommons; import com.alibaba.nacos.naming.misc.UtilsAndCommons;
import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.BooleanUtils;
@ -67,9 +68,7 @@ public class ClusterController {
Cluster cluster = service.getClusterMap().get(clusterName); Cluster cluster = service.getClusterMap().get(clusterName);
if (cluster == null) { if (cluster == null) {
Loggers.SRV_LOG.warn("[UPDATE-CLUSTER] cluster not exist, will create it: {}, service: {}", clusterName, serviceName); Loggers.SRV_LOG.warn("[UPDATE-CLUSTER] cluster not exist, will create it: {}, service: {}", clusterName, serviceName);
cluster = new Cluster(); cluster = new Cluster(clusterName, service);
cluster.setName(clusterName);
cluster.setService(service);
} }
cluster.setDefCkport(NumberUtils.toInt(checkPort)); cluster.setDefCkport(NumberUtils.toInt(checkPort));
@ -77,23 +76,12 @@ public class ClusterController {
JSONObject healthCheckObj = JSON.parseObject(healthChecker); JSONObject healthCheckObj = JSON.parseObject(healthChecker);
AbstractHealthChecker abstractHealthChecker; AbstractHealthChecker abstractHealthChecker;
String type = healthCheckObj.getString("type");
switch (healthCheckObj.getString("type")) { Class<AbstractHealthChecker> healthCheckClass = HealthCheckType.ofHealthCheckerClass(type);
case AbstractHealthChecker.Tcp.TYPE: if(healthCheckClass == null){
abstractHealthChecker = JSON.parseObject(healthChecker, AbstractHealthChecker.Tcp.class); throw new NacosException(NacosException.INVALID_PARAM, "unknown health check type:" + healthChecker);
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);
} }
abstractHealthChecker = JSON.parseObject(healthChecker, healthCheckClass);
cluster.setHealthChecker(abstractHealthChecker); cluster.setHealthChecker(abstractHealthChecker);
cluster.setMetadata(UtilsAndCommons.parseMetadata(metadata)); cluster.setMetadata(UtilsAndCommons.parseMetadata(metadata));
@ -107,4 +95,5 @@ public class ClusterController {
return "ok"; return "ok";
} }
} }

View File

@ -18,6 +18,7 @@ package com.alibaba.nacos.naming.controllers;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.common.Constants; import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.naming.CommonParams; 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.core.utils.WebUtils;
import com.alibaba.nacos.naming.boot.RunningConfig; import com.alibaba.nacos.naming.boot.RunningConfig;
import com.alibaba.nacos.naming.core.DistroMapper; 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 com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired; 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.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/** /**
* Health status related operation controller * Health status related operation controller
@ -110,4 +116,20 @@ public class HealthController {
return "ok"; 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); cluster = WebUtils.optional(request, "cluster", UtilsAndCommons.DEFAULT_CLUSTER_NAME);
} }
boolean healthy = BooleanUtils.toBoolean(WebUtils.optional(request, "healthy", "true")); 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", boolean ephemeral = BooleanUtils.toBoolean(WebUtils.optional(request, "ephemeral",
String.valueOf(switchDomain.isDefaultInstanceEphemeral()))); String.valueOf(switchDomain.isDefaultInstanceEphemeral())));
@ -469,6 +477,12 @@ public class InstanceController {
} }
for (Instance instance : ips) { for (Instance instance : ips) {
// remove disabled instance:
if (!instance.isEnabled()) {
continue;
}
JSONObject ipObj = new JSONObject(); JSONObject ipObj = new JSONObject();
ipObj.put("ip", instance.getIp()); 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.HealthCheckStatus;
import com.alibaba.nacos.naming.healthcheck.HealthCheckTask; import com.alibaba.nacos.naming.healthcheck.HealthCheckTask;
import com.alibaba.nacos.naming.misc.Loggers; import com.alibaba.nacos.naming.misc.Loggers;
import com.alibaba.nacos.naming.misc.UtilsAndCommons;
import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils; 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.*;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
/** /**
* @author nkorange * @author nkorange
* @author jifengnan 2019-04-26
*/ */
public class Cluster extends com.alibaba.nacos.api.naming.pojo.Cluster implements Cloneable { 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() {
} }
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.setName(clusterName);
this.service = service;
validate(); validate();
} }
@ -113,19 +127,50 @@ public class Cluster extends com.alibaba.nacos.api.naming.pojo.Cluster implement
return service; 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) { public void setService(Service service) {
this.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 @Override
public Cluster clone() throws CloneNotSupportedException { public Cluster clone() throws CloneNotSupportedException {
super.clone(); super.clone();
Cluster cluster = new Cluster(); Cluster cluster = new Cluster(this.getName(), service);
cluster.setHealthChecker(getHealthChecker().clone()); cluster.setHealthChecker(getHealthChecker().clone());
cluster.setService(getService()); cluster.persistentInstances = new HashSet<>();
cluster.persistentInstances = new HashSet<Instance>();
cluster.checkTask = null; cluster.checkTask = null;
cluster.metadata = new HashMap<>(metadata); cluster.metadata = new HashMap<>(metadata);
return cluster; return cluster;
@ -263,16 +308,28 @@ public class Cluster extends com.alibaba.nacos.api.naming.pojo.Cluster implement
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hash(getName()); return new HashCodeBuilder(17, 37)
.append(getName())
.append(service)
.toHashCode();
} }
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object o) {
if (!(obj instanceof Cluster)) { if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false; 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() { 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); 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() { public void validate() {
Assert.notNull(getName(), "cluster name cannot be null");
Assert.notNull(service, "service cannot be null");
if (!getName().matches(CLUSTER_NAME_SYNTAX)) { if (!getName().matches(CLUSTER_NAME_SYNTAX)) {
throw new IllegalArgumentException("cluster name can only have these characters: 0-9a-zA-Z-, current: " + getName()); 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 public static final Pattern IP_PATTERN
= Pattern.compile("(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}):?(\\d{1,5})?"); = 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 static final String SPLITER = "_";
public Instance() { public Instance() {
@ -296,10 +299,11 @@ public class Instance extends com.alibaba.nacos.api.naming.pojo.Instance impleme
} }
public boolean validate() { public boolean validate() {
if (onlyContainsDigitAndDot()) {
Matcher matcher = IP_PATTERN.matcher(getIp() + ":" + getPort()); Matcher matcher = IP_PATTERN.matcher(getIp() + ":" + getPort());
if (!matcher.matches()) { if (!matcher.matches()) {
return false; return false;
}
} }
if (getWeight() > MAX_WEIGHT_VALUE || getWeight() < MIN_WEIGHT_VALUE) { 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; return true;
} }
private boolean onlyContainsDigitAndDot() {
Matcher matcher = ONLY_DIGIT_AND_DOT.matcher(getIp());
return matcher.matches();
}
@Override @Override
public int compareTo(Object o) { public int compareTo(Object o) {
if (!(o instanceof Instance)) { 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())) { if (!clusterMap.containsKey(instance.getClusterName())) {
Loggers.SRV_LOG.warn("cluster: {} not found, ip: {}, will create new cluster with default configuration.", Loggers.SRV_LOG.warn("cluster: {} not found, ip: {}, will create new cluster with default configuration.",
instance.getClusterName(), instance.toJSON()); instance.getClusterName(), instance.toJSON());
Cluster cluster = new Cluster(instance.getClusterName()); Cluster cluster = new Cluster(instance.getClusterName(), this);
cluster.setService(this);
cluster.init(); cluster.init();
getClusterMap().put(instance.getClusterName(), cluster); getClusterMap().put(instance.getClusterName(), cluster);
} }

View File

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

View File

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

View File

@ -15,6 +15,13 @@
*/ */
package com.alibaba.nacos.naming.healthcheck; 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 * @author nkorange
*/ */
@ -22,17 +29,54 @@ public enum HealthCheckType {
/** /**
* TCP type * TCP type
*/ */
TCP, TCP("tcp", AbstractHealthChecker.Tcp.class),
/** /**
* HTTP type * HTTP type
*/ */
HTTP, HTTP("http", AbstractHealthChecker.Http.class),
/** /**
* MySQL type * MySQL type
*/ */
MYSQL, MYSQL("mysql", AbstractHealthChecker.Mysql.class),
/** /**
* No check * 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; return INSTANCE;
} }
@SuppressWarnings("unchecked")
@Override @Override
public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
JSONObject jsonObj = (JSONObject) parser.parse(); JSONObject jsonObj = (JSONObject) parser.parse();
String checkType = jsonObj.getString("type"); String checkType = jsonObj.getString("type");
if (StringUtils.equals(checkType, AbstractHealthChecker.Http.TYPE)) { Class target = HealthCheckType.ofHealthCheckerClass(checkType);
return (T) JSON.parseObject(jsonObj.toJSONString(), AbstractHealthChecker.Http.class);
}
if (StringUtils.equals(checkType, AbstractHealthChecker.Tcp.TYPE)) { if(target != null){
return (T) JSON.parseObject(jsonObj.toJSONString(), AbstractHealthChecker.Tcp.class); return (T) JSON.parseObject(jsonObj.toJSONString(), target);
}
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);
} }
return null; return null;
@ -83,21 +74,6 @@ public class JsonAdapter implements ObjectDeserializer, ObjectSerializer {
writer.writeFieldValue(',', "type", config.getType()); writer.writeFieldValue(',', "type", config.getType());
if (StringUtils.equals(config.getType(), HealthCheckType.HTTP.name())) { config.jsonAdapterCallback(writer);
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());
}
} }
} }

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

@ -36,6 +36,7 @@ import static com.alibaba.nacos.core.utils.SystemUtils.NACOS_HOME;
/** /**
* @author nacos * @author nacos
* @author jifengnan
*/ */
public class UtilsAndCommons { public class UtilsAndCommons {
@ -239,23 +240,25 @@ public class UtilsAndCommons {
} }
/** /**
* 根据指定的字符串计算出一个0{@code upperLimit}不含之间的数字本方法会试图让不同的字符串较均匀的分布在0到{@code upperLimit}之间 * Provide a number between 0(inclusive) and {@code upperLimit}(exclusive) for the given {@code string},
* (Provide a number between 0(include) and {@code upperLimit}(exclude) for the given {@code string}, the number will be nearly uniform distribution.) * the number will be nearly uniform distribution.
* <p> * <p>
* <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> * <blockquote><pre>
* String[] serverIps = new String[10]; * String[] serverIps = new String[10];
* int index = shakeUp("callerName", serverIps.length); * int index = shakeUp("callerName", serverIps.length);
* String targetServerIp = serverIps[index]; * String targetServerIp = serverIps[index];
* </pre></blockquote> * </pre></blockquote>
* *
* @param string 字符串如果为null会固定返回0 (a string. the number 0 will be returned if it's null) * @param string 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) * @param upperLimit 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)) * @return a number between 0(inclusive) and upperLimit(exclusive)
* @throws IllegalArgumentException if the upper limit equals or less than 0 * @throws IllegalArgumentException if the upper limit equals or less than 0
* @since 1.0.0 * @since 1.0.0
* @author jifengnan
*/ */
public static int shakeUp(String string, int upperLimit) { public static int shakeUp(String string, int upperLimit) {
if (upperLimit < 1) { if (upperLimit < 1) {

View File

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

View File

@ -15,15 +15,26 @@
*/ */
package com.alibaba.nacos.naming; 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.RaftCore;
import com.alibaba.nacos.naming.consistency.persistent.raft.RaftPeer; import com.alibaba.nacos.naming.consistency.persistent.raft.RaftPeer;
import com.alibaba.nacos.naming.consistency.persistent.raft.RaftPeerSet; import com.alibaba.nacos.naming.consistency.persistent.raft.RaftPeerSet;
import com.alibaba.nacos.naming.core.DistroMapper;
import com.alibaba.nacos.naming.core.ServiceManager; import com.alibaba.nacos.naming.core.ServiceManager;
import com.alibaba.nacos.naming.healthcheck.HealthCheckProcessorDelegate;
import com.alibaba.nacos.naming.misc.NetUtils; 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.Before;
import org.junit.Rule;
import org.junit.rules.ExpectedException;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
import org.springframework.context.ApplicationContext;
import static org.mockito.Mockito.doReturn;
/** /**
* @author nkorange * @author nkorange
@ -39,6 +50,9 @@ public class BaseTest {
@Mock @Mock
public RaftCore raftCore; public RaftCore raftCore;
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Before @Before
public void before() { public void before() {
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
@ -49,5 +63,27 @@ public class BaseTest {
Mockito.when(peerSet.local()).thenReturn(peer); Mockito.when(peerSet.local()).thenReturn(peer);
Mockito.when(peerSet.getLeader()).thenReturn(peer); Mockito.when(peerSet.getLeader()).thenReturn(peer);
Mockito.when(peerSet.isLeader(NetUtils.localServer())).thenReturn(true); 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; package com.alibaba.nacos.naming.consistency.ephemeral.distro;
import com.alibaba.nacos.naming.misc.GlobalConfig; import com.alibaba.nacos.naming.misc.GlobalConfig;
import com.alibaba.nacos.naming.misc.Loggers;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.springframework.test.util.ReflectionTestUtils; 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 { public void registerInstance() throws Exception {
Service service = new Service(); Service service = new Service();
service.setName("nacos.test.1"); service.setName(TEST_SERVICE_NAME);
Cluster cluster = new Cluster(); Cluster cluster = new Cluster(UtilsAndCommons.DEFAULT_CLUSTER_NAME, service);
cluster.setName(UtilsAndCommons.DEFAULT_CLUSTER_NAME);
cluster.setService(service);
service.addCluster(cluster); service.addCluster(cluster);
Instance instance = new Instance(); Instance instance = new Instance();
instance.setIp("1.1.1.1"); instance.setIp("1.1.1.1");
instance.setPort(9999); instance.setPort(9999);
List<Instance> ipList = new ArrayList<Instance>(); List<Instance> ipList = new ArrayList<>();
ipList.add(instance); ipList.add(instance);
service.updateIPs(ipList, false); 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 = MockHttpServletRequestBuilder builder =
MockMvcRequestBuilders.put("/naming/instance") MockMvcRequestBuilders.put(UtilsAndCommons.NACOS_NAMING_CONTEXT + "/instance")
.param("serviceName", "nacos.test.1") .param("serviceName", TEST_SERVICE_NAME)
.param("ip", "1.1.1.1") .param("ip", "1.1.1.1")
.param("port", "9999"); .param("port", "9999");
String actualValue = mockmvc.perform(builder).andReturn().getResponse().getContentAsString(); String actualValue = mockmvc.perform(builder).andReturn().getResponse().getContentAsString();
Assert.assertEquals("ok", actualValue); Assert.assertEquals("ok", actualValue);
@ -101,11 +99,11 @@ public class InstanceControllerTest extends BaseTest {
public void deregisterInstance() throws Exception { public void deregisterInstance() throws Exception {
MockHttpServletRequestBuilder builder = MockHttpServletRequestBuilder builder =
MockMvcRequestBuilders.delete("/naming/instance") MockMvcRequestBuilders.delete(UtilsAndCommons.NACOS_NAMING_CONTEXT + "/instance")
.param("serviceName", "nacos.test.1") .param("serviceName", TEST_SERVICE_NAME)
.param("ip", "1.1.1.1") .param("ip", "1.1.1.1")
.param("port", "9999") .param("port", "9999")
.param("clusterName", UtilsAndCommons.DEFAULT_CLUSTER_NAME); .param("clusterName", UtilsAndCommons.DEFAULT_CLUSTER_NAME);
String actualValue = mockmvc.perform(builder).andReturn().getResponse().getContentAsString(); String actualValue = mockmvc.perform(builder).andReturn().getResponse().getContentAsString();
Assert.assertEquals("ok", actualValue); Assert.assertEquals("ok", actualValue);
@ -115,34 +113,32 @@ public class InstanceControllerTest extends BaseTest {
public void getInstances() throws Exception { public void getInstances() throws Exception {
Service service = new Service(); Service service = new Service();
service.setName("nacos.test.1"); service.setName(TEST_SERVICE_NAME);
Cluster cluster = new Cluster(); Cluster cluster = new Cluster(UtilsAndCommons.DEFAULT_CLUSTER_NAME, service);
cluster.setName(UtilsAndCommons.DEFAULT_CLUSTER_NAME);
cluster.setService(service);
service.addCluster(cluster); service.addCluster(cluster);
Instance instance = new Instance(); Instance instance = new Instance();
instance.setIp("10.10.10.10"); instance.setIp("10.10.10.10");
instance.setPort(8888); instance.setPort(8888);
instance.setWeight(2.0); instance.setWeight(2.0);
List<Instance> ipList = new ArrayList<Instance>(); instance.setServiceName(TEST_SERVICE_NAME);
List<Instance> ipList = new ArrayList<>();
ipList.add(instance); ipList.add(instance);
service.updateIPs(ipList, false); 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 = MockHttpServletRequestBuilder builder =
MockMvcRequestBuilders.get("/v1/ns/instances") MockMvcRequestBuilders.get(UtilsAndCommons.NACOS_NAMING_CONTEXT + "/instance/list")
.param("serviceName", "nacos.test.1"); .param("serviceName", TEST_SERVICE_NAME);
MockHttpServletResponse response = mockmvc.perform(builder).andReturn().getResponse(); MockHttpServletResponse response = mockmvc.perform(builder).andReturn().getResponse();
String actualValue = response.getContentAsString(); String actualValue = response.getContentAsString();
JSONObject result = JSON.parseObject(actualValue); 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"); JSONArray hosts = result.getJSONArray("hosts");
Assert.assertTrue(hosts != null);
Assert.assertNotNull(hosts); Assert.assertNotNull(hosts);
Assert.assertEquals(hosts.size(), 1); Assert.assertEquals(hosts.size(), 1);

View File

@ -36,9 +36,7 @@ public class ClusterTest {
Service service = new Service(); Service service = new Service();
service.setName("nacos.service.1"); service.setName("nacos.service.1");
cluster = new Cluster(); cluster = new Cluster("nacos-cluster-1", service);
cluster.setName("nacos-cluster-1");
cluster.setService(service);
cluster.setDefCkport(80); cluster.setDefCkport(80);
cluster.setDefIPPort(8080); cluster.setDefIPPort(8080);
} }
@ -46,8 +44,10 @@ public class ClusterTest {
@Test @Test
public void updateCluster() { 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.setDefCkport(8888);
newCluster.setDefIPPort(9999); newCluster.setDefIPPort(9999);
AbstractHealthChecker.Http healthCheckConfig = new AbstractHealthChecker.Http(); AbstractHealthChecker.Http healthCheckConfig = new AbstractHealthChecker.Http();
@ -56,17 +56,12 @@ public class ClusterTest {
healthCheckConfig.setHeaders("Client-Version:nacos-test-1"); healthCheckConfig.setHeaders("Client-Version:nacos-test-1");
newCluster.setHealthChecker(healthCheckConfig); newCluster.setHealthChecker(healthCheckConfig);
Service service = new Service();
service.setName("nacos.service.2");
newCluster.setService(service);
cluster.update(newCluster); cluster.update(newCluster);
Assert.assertEquals(8888, cluster.getDefCkport()); Assert.assertEquals(8888, cluster.getDefCkport());
Assert.assertEquals(9999, cluster.getDefIPPort()); Assert.assertEquals(9999, cluster.getDefIPPort());
Assert.assertTrue(cluster.getHealthChecker() instanceof AbstractHealthChecker.Http); 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("/nacos-path-1", httpHealthCheck.getPath());
Assert.assertEquals(500, httpHealthCheck.getExpectedResponseCode()); Assert.assertEquals(500, httpHealthCheck.getExpectedResponseCode());
Assert.assertEquals("Client-Version:nacos-test-1", httpHealthCheck.getHeaders()); Assert.assertEquals("Client-Version:nacos-test-1", httpHealthCheck.getHeaders());
@ -83,7 +78,7 @@ public class ClusterTest {
instance2.setIp("1.1.1.1"); instance2.setIp("1.1.1.1");
instance2.setPort(2345); instance2.setPort(2345);
List<Instance> list = new ArrayList<Instance>(); List<Instance> list = new ArrayList<>();
list.add(instance1); list.add(instance1);
list.add(instance2); list.add(instance2);
@ -97,4 +92,25 @@ public class ClusterTest {
Assert.assertEquals("1.1.1.1", ips.get(1).getIp()); Assert.assertEquals("1.1.1.1", ips.get(1).getIp());
Assert.assertEquals(2345, ips.get(1).getPort()); 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; 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.misc.UtilsAndCommons;
import com.alibaba.nacos.naming.push.PushService;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; 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.ArrayList;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import static org.mockito.Mockito.doReturn;
/** /**
* @author nkorange * @author nkorange
*/ */
public class DomainTest { public class DomainTest {
private Service service; private Service service;
@Spy
protected ApplicationContext context;
@Mock
protected PushService pushService;
@Before @Before
public void before() { public void before() {
MockitoAnnotations.initMocks(this);
service = new Service(); service = new Service();
service.setName("nacos.service.1"); service.setName("nacos.service.1");
Cluster cluster = new Cluster(); Cluster cluster = new Cluster(UtilsAndCommons.DEFAULT_CLUSTER_NAME, service);
cluster.setName(UtilsAndCommons.DEFAULT_CLUSTER_NAME);
cluster.setService(service);
service.addCluster(cluster); service.addCluster(cluster);
new SpringContext().setApplicationContext(context);
doReturn(pushService).when(context).getBean(PushService.class);
} }
@Test @Test
@ -48,9 +62,7 @@ public class DomainTest {
Service newDomain = new Service(); Service newDomain = new Service();
newDomain.setName("nacos.service.1"); newDomain.setName("nacos.service.1");
newDomain.setProtectThreshold(0.7f); newDomain.setProtectThreshold(0.7f);
Cluster cluster = new Cluster(); Cluster cluster = new Cluster(UtilsAndCommons.DEFAULT_CLUSTER_NAME, newDomain);
cluster.setName(UtilsAndCommons.DEFAULT_CLUSTER_NAME);
cluster.setService(newDomain);
newDomain.addCluster(cluster); newDomain.addCluster(cluster);
service.update(newDomain); service.update(newDomain);
@ -60,8 +72,7 @@ public class DomainTest {
@Test @Test
public void addCluster() { public void addCluster() {
Cluster cluster = new Cluster(); Cluster cluster = new Cluster("nacos-cluster-1", service);
cluster.setName("nacos-cluster-1");
service.addCluster(cluster); 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.api.common.Constants;
import com.alibaba.nacos.naming.BaseTest; 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.Assert;
import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.mockito.InjectMocks;
import org.springframework.mock.web.MockServletContext; import org.mockito.Mock;
import org.springframework.test.context.ContextConfiguration; import org.mockito.Spy;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import java.util.List; import java.util.List;
/** /**
* @author nkorange * @author nkorange
* @author jifengnan 2019-05-18
*/ */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MockServletContext.class)
@WebAppConfiguration
public class DomainsManagerTest extends BaseTest { public class DomainsManagerTest extends BaseTest {
@Before @Spy
public void before() { @InjectMocks
super.before(); private ServiceManager manager;
serviceManager = new ServiceManager();
} @Mock
private DistroConsistencyServiceImpl consistencyService;
@Test @Test
public void easyRemoveDom() throws Exception { 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 @Test
public void searchDom() throws Exception { public void easyRemoveDomNotExist() throws Exception {
Service service = new Service(); expectedException.expect(IllegalArgumentException.class);
service.setName("nacos.test.1"); 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.assertNotNull(list);
Assert.assertEquals(1, list.size()); 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(); MockEnvironment environment = new MockEnvironment();
Assert.assertEquals(DEFAULT_NACOS_NAMING_CONTEXT, environment.resolvePlaceholders(NACOS_NAMING_CONTEXT)); Assert.assertEquals(DEFAULT_NACOS_NAMING_CONTEXT, environment.resolvePlaceholders(NACOS_NAMING_CONTEXT));
Assert.assertEquals("/nacos/v1/ns", DEFAULT_NACOS_NAMING_CONTEXT);
} }
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)

View File

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

View File

@ -404,9 +404,6 @@
<includes> <includes>
<include>**/*ITCase.java</include> <include>**/*ITCase.java</include>
</includes> </includes>
<excludes>
<exclude>**/RestAPI_ITCase.java</exclude>
</excludes>
</configuration> </configuration>
<executions> <executions>
<execution> <execution>

View File

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

View File

@ -15,13 +15,12 @@
*/ */
package com.alibaba.nacos.test.naming; package com.alibaba.nacos.test.naming;
import java.net.URL;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; 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.NamingApp;
import com.alibaba.nacos.naming.misc.UtilsAndCommons;
import org.junit.After; import org.junit.After;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
@ -39,10 +38,6 @@ import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.MultiValueMap; import org.springframework.util.MultiValueMap;
import org.springframework.web.util.UriComponentsBuilder; import org.springframework.web.util.UriComponentsBuilder;
import java.net.URL;
import static org.junit.Assert.assertTrue;
/** /**
* @author nkorange * @author nkorange
*/ */
@ -64,427 +59,18 @@ public class RestAPI_ITCase {
public void setUp() throws Exception { public void setUp() throws Exception {
String url = String.format("http://localhost:%d/", port); String url = String.format("http://localhost:%d/", port);
this.base = new URL(url); this.base = new URL(url);
prepareData(); //prepareData();
} }
@After @After
public void cleanup() throws Exception { public void cleanup() throws Exception {
removeData(); //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());
} }
@Test @Test
public void metrics() throws Exception { 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() Params.newParams()
.done(), .done(),
String.class); String.class);
@ -492,56 +78,10 @@ public class RestAPI_ITCase {
Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
JSONObject json = JSON.parseObject(response.getBody()); JSONObject json = JSON.parseObject(response.getBody());
Assert.assertTrue(json.getIntValue("domCount") > 0); Assert.assertTrue(json.getIntValue("serviceCount") > 0);
Assert.assertTrue(json.getIntValue("ipCount") > 0); Assert.assertTrue(json.getIntValue("instanceCount") > 0);
Assert.assertTrue(json.getIntValue("responsibleDomCount") > 0); Assert.assertTrue(json.getIntValue("responsibleServiceCount") > 0);
Assert.assertTrue(json.getIntValue("responsibleIPCount") > 0); Assert.assertTrue(json.getIntValue("responsibleInstanceCount") > 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);
} }
/** /**
@ -555,9 +95,10 @@ public class RestAPI_ITCase {
ResponseEntity<String> response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service", ResponseEntity<String> response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service",
Params.newParams() Params.newParams()
.appendParam("serviceName", serviceName) .appendParam("serviceName", serviceName)
.appendParam("protectThreshold", "0.3")
.done(), .done(),
String.class, String.class,
HttpMethod.PUT); HttpMethod.POST);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Assert.assertEquals("ok", response.getBody()); Assert.assertEquals("ok", response.getBody());
@ -575,9 +116,10 @@ public class RestAPI_ITCase {
ResponseEntity<String> response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service", ResponseEntity<String> response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service",
Params.newParams() Params.newParams()
.appendParam("serviceName", serviceName) .appendParam("serviceName", serviceName)
.appendParam("protectThreshold", "0.3")
.done(), .done(),
String.class, String.class,
HttpMethod.PUT); HttpMethod.POST);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Assert.assertEquals("ok", response.getBody()); Assert.assertEquals("ok", response.getBody());
@ -585,6 +127,7 @@ public class RestAPI_ITCase {
response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service", response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service",
Params.newParams() Params.newParams()
.appendParam("serviceName", serviceName) .appendParam("serviceName", serviceName)
.appendParam("protectThreshold", "0.3")
.done(), .done(),
String.class); String.class);
@ -621,9 +164,10 @@ public class RestAPI_ITCase {
response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service", response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service",
Params.newParams() Params.newParams()
.appendParam("serviceName", serviceName) .appendParam("serviceName", serviceName)
.appendParam("protectThreshold", "0.3")
.done(), .done(),
String.class, String.class,
HttpMethod.PUT); HttpMethod.POST);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Assert.assertEquals("ok", response.getBody()); Assert.assertEquals("ok", response.getBody());
@ -653,9 +197,10 @@ public class RestAPI_ITCase {
ResponseEntity<String> response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service", ResponseEntity<String> response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service",
Params.newParams() Params.newParams()
.appendParam("serviceName", serviceName) .appendParam("serviceName", serviceName)
.appendParam("protectThreshold", "0.6")
.done(), .done(),
String.class, String.class,
HttpMethod.PUT); HttpMethod.POST);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Assert.assertEquals("ok", response.getBody()); Assert.assertEquals("ok", response.getBody());
@ -664,10 +209,10 @@ public class RestAPI_ITCase {
Params.newParams() Params.newParams()
.appendParam("serviceName", serviceName) .appendParam("serviceName", serviceName)
.appendParam("healthCheckMode", "server") .appendParam("healthCheckMode", "server")
.appendParam("protectThreshold", "3") .appendParam("protectThreshold", "0.3")
.done(), .done(),
String.class, String.class,
HttpMethod.POST); HttpMethod.PUT);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Assert.assertEquals("ok", response.getBody()); Assert.assertEquals("ok", response.getBody());
@ -682,7 +227,7 @@ public class RestAPI_ITCase {
Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
JSONObject json = JSON.parseObject(response.getBody()); JSONObject json = JSON.parseObject(response.getBody());
System.out.println(json); System.out.println(json);
Assert.assertEquals(3.0f, json.getFloatValue("protectThreshold"), 0.0f); Assert.assertEquals(0.3f, json.getFloatValue("protectThreshold"), 0.0f);
namingServiceDelete(serviceName); namingServiceDelete(serviceName);
} }
@ -692,6 +237,7 @@ public class RestAPI_ITCase {
ResponseEntity<String> response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service", ResponseEntity<String> response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service",
Params.newParams() Params.newParams()
.appendParam("serviceName", serviceName) .appendParam("serviceName", serviceName)
.appendParam("protectThreshold", "0.3")
.done(), .done(),
String.class, String.class,
HttpMethod.DELETE); HttpMethod.DELETE);

View File

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