Merge pull request #766 from pbting/0.8.0-poc-support-ans
0.8.0 poc support ans
This commit is contained in:
commit
7d1519e25d
@ -16,7 +16,7 @@
|
||||
<parent>
|
||||
<groupId>com.alibaba.nacos</groupId>
|
||||
<artifactId>nacos-all</artifactId>
|
||||
<version>0.8.0</version>
|
||||
<version>0.8.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
@ -22,6 +22,10 @@ package com.alibaba.nacos.api;
|
||||
*/
|
||||
public class PropertyKeyConst {
|
||||
|
||||
public final static String SERVER_PORT = "serverPort";
|
||||
|
||||
public final static String WEB_CONTEXT = "webContext";
|
||||
|
||||
public final static String ENDPOINT = "endpoint";
|
||||
|
||||
public final static String NAMESPACE = "namespace";
|
||||
|
@ -16,7 +16,7 @@
|
||||
<parent>
|
||||
<groupId>com.alibaba.nacos</groupId>
|
||||
<artifactId>nacos-all</artifactId>
|
||||
<version>0.8.0</version>
|
||||
<version>0.8.1-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
|
@ -25,6 +25,8 @@ public class Constants {
|
||||
|
||||
public static final String SECRET_KEY = "secretKey";
|
||||
|
||||
public static final String TENANT_ID = "tenantId";
|
||||
|
||||
public static final String PROPERTIES_FILENAME = "spas.properties";
|
||||
|
||||
public static final String CREDENTIAL_PATH = "/home/admin/.spas_key/";
|
||||
@ -37,10 +39,14 @@ public class Constants {
|
||||
|
||||
public static final String DOCKER_SECRET_KEY = "env_spas_secretKey";
|
||||
|
||||
public static final String DOCKER_TENANT_ID = "ebv_spas_tenantId";
|
||||
|
||||
public static final String ENV_ACCESS_KEY = "spas_accessKey";
|
||||
|
||||
public static final String ENV_SECRET_KEY = "spas_secretKey";
|
||||
|
||||
public static final String ENV_TENANT_ID = "tenant.id";
|
||||
|
||||
public static final String NO_APP_NAME = "";
|
||||
|
||||
}
|
||||
|
@ -15,198 +15,224 @@
|
||||
*/
|
||||
package com.alibaba.nacos.client.identify;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import com.alibaba.nacos.client.config.utils.LogUtils;
|
||||
import com.alibaba.nacos.client.logger.Logger;
|
||||
import com.alibaba.nacos.client.utils.StringUtils;
|
||||
|
||||
import java.io.*;
|
||||
import java.net.URL;
|
||||
import java.util.Properties;
|
||||
import java.util.Timer;
|
||||
import java.util.TimerTask;
|
||||
|
||||
import com.alibaba.nacos.client.config.utils.LogUtils;
|
||||
import com.alibaba.nacos.client.logger.Logger;
|
||||
import com.alibaba.nacos.client.utils.StringUtils;
|
||||
|
||||
/**
|
||||
* Credential Watcher
|
||||
*
|
||||
* @author Nacos
|
||||
*/
|
||||
public class CredentialWatcher {
|
||||
static final public Logger SpasLogger = LogUtils.logger(CredentialWatcher.class);
|
||||
private static final long REFRESH_INTERVAL = 10 * 1000;
|
||||
static final public Logger SpasLogger = LogUtils.logger(CredentialWatcher.class);
|
||||
private static final long REFRESH_INTERVAL = 10 * 1000;
|
||||
|
||||
private CredentialService serviceInstance;
|
||||
private String appName;
|
||||
private String propertyPath;
|
||||
private TimerTask watcher;
|
||||
private boolean stopped;
|
||||
private CredentialService serviceInstance;
|
||||
private String appName;
|
||||
private String propertyPath;
|
||||
private TimerTask watcher;
|
||||
private boolean stopped;
|
||||
|
||||
@SuppressWarnings("PMD.AvoidUseTimerRule")
|
||||
public CredentialWatcher(String appName, CredentialService serviceInstance) {
|
||||
this.appName = appName;
|
||||
this.serviceInstance = serviceInstance;
|
||||
loadCredential(true);
|
||||
watcher = new TimerTask() {
|
||||
private Timer timer = new Timer(true);
|
||||
private long modified = 0;
|
||||
@SuppressWarnings("PMD.AvoidUseTimerRule")
|
||||
public CredentialWatcher(String appName, CredentialService serviceInstance) {
|
||||
this.appName = appName;
|
||||
this.serviceInstance = serviceInstance;
|
||||
loadCredential(true);
|
||||
watcher = new TimerTask() {
|
||||
private Timer timer = new Timer(true);
|
||||
private long modified = 0;
|
||||
|
||||
{
|
||||
timer.schedule(this, REFRESH_INTERVAL, REFRESH_INTERVAL);
|
||||
}
|
||||
{
|
||||
timer.schedule(this, REFRESH_INTERVAL, REFRESH_INTERVAL);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
synchronized (this) {
|
||||
if (stopped) {
|
||||
return;
|
||||
}
|
||||
boolean reload = false;
|
||||
if (propertyPath == null) {
|
||||
reload = true;
|
||||
} else {
|
||||
File file = new File(propertyPath);
|
||||
long lastModified = file.lastModified();
|
||||
if (modified != lastModified) {
|
||||
reload = true;
|
||||
modified = lastModified;
|
||||
}
|
||||
}
|
||||
if (reload) {
|
||||
loadCredential(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
@Override
|
||||
public void run() {
|
||||
synchronized (this) {
|
||||
if (stopped) {
|
||||
return;
|
||||
}
|
||||
boolean reload = false;
|
||||
if (propertyPath == null) {
|
||||
reload = true;
|
||||
}
|
||||
else {
|
||||
File file = new File(propertyPath);
|
||||
long lastModified = file.lastModified();
|
||||
if (modified != lastModified) {
|
||||
reload = true;
|
||||
modified = lastModified;
|
||||
}
|
||||
}
|
||||
if (reload) {
|
||||
loadCredential(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
if (stopped) {
|
||||
return;
|
||||
}
|
||||
if (watcher != null) {
|
||||
synchronized (watcher) {
|
||||
watcher.cancel();
|
||||
stopped = true;
|
||||
}
|
||||
}
|
||||
SpasLogger.info(appName, this.getClass().getSimpleName() + " is stopped");
|
||||
}
|
||||
public void stop() {
|
||||
if (stopped) {
|
||||
return;
|
||||
}
|
||||
if (watcher != null) {
|
||||
synchronized (watcher) {
|
||||
watcher.cancel();
|
||||
stopped = true;
|
||||
}
|
||||
}
|
||||
SpasLogger.info(appName, this.getClass().getSimpleName() + " is stopped");
|
||||
}
|
||||
|
||||
private void loadCredential(boolean init) {
|
||||
boolean logWarn = init;
|
||||
if (propertyPath == null) {
|
||||
URL url = ClassLoader.getSystemResource(Constants.PROPERTIES_FILENAME);
|
||||
if (url != null) {
|
||||
propertyPath = url.getPath();
|
||||
}
|
||||
if (propertyPath == null || propertyPath.isEmpty()) {
|
||||
private void loadCredential(boolean init) {
|
||||
boolean logWarn = init;
|
||||
if (propertyPath == null) {
|
||||
URL url = ClassLoader.getSystemResource(Constants.PROPERTIES_FILENAME);
|
||||
if (url != null) {
|
||||
propertyPath = url.getPath();
|
||||
}
|
||||
if (propertyPath == null || propertyPath.isEmpty()) {
|
||||
|
||||
String value = System.getProperty("spas.identity");
|
||||
if (StringUtils.isNotEmpty(value)) {
|
||||
propertyPath = value;
|
||||
}
|
||||
if (propertyPath == null || propertyPath.isEmpty()) {
|
||||
propertyPath = Constants.CREDENTIAL_PATH + (appName == null ? Constants.CREDENTIAL_DEFAULT
|
||||
: appName);
|
||||
} else {
|
||||
if (logWarn) {
|
||||
SpasLogger.info(appName, "Defined credential file: -D" + "spas.identity" + "=" + propertyPath);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (logWarn) {
|
||||
SpasLogger.info(appName, "Load credential file from classpath: " + Constants.PROPERTIES_FILENAME);
|
||||
}
|
||||
}
|
||||
}
|
||||
String value = System.getProperty("spas.identity");
|
||||
if (StringUtils.isNotEmpty(value)) {
|
||||
propertyPath = value;
|
||||
}
|
||||
if (propertyPath == null || propertyPath.isEmpty()) {
|
||||
propertyPath = Constants.CREDENTIAL_PATH
|
||||
+ (appName == null ? Constants.CREDENTIAL_DEFAULT : appName);
|
||||
}
|
||||
else {
|
||||
if (logWarn) {
|
||||
SpasLogger.info(appName, "Defined credential file: -D"
|
||||
+ "spas.identity" + "=" + propertyPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (logWarn) {
|
||||
SpasLogger.info(appName, "Load credential file from classpath: "
|
||||
+ Constants.PROPERTIES_FILENAME);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
InputStream propertiesIS = null;
|
||||
do {
|
||||
try {
|
||||
propertiesIS = new FileInputStream(propertyPath);
|
||||
} catch (FileNotFoundException e) {
|
||||
if (appName != null && !appName.equals(Constants.CREDENTIAL_DEFAULT) && propertyPath.equals(
|
||||
Constants.CREDENTIAL_PATH + appName)) {
|
||||
propertyPath = Constants.CREDENTIAL_PATH + Constants.CREDENTIAL_DEFAULT;
|
||||
continue;
|
||||
}
|
||||
if (!Constants.DOCKER_CREDENTIAL_PATH.equals(propertyPath)) {
|
||||
propertyPath = Constants.DOCKER_CREDENTIAL_PATH;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
break;
|
||||
} while (true);
|
||||
InputStream propertiesIS = null;
|
||||
do {
|
||||
try {
|
||||
propertiesIS = new FileInputStream(propertyPath);
|
||||
}
|
||||
catch (FileNotFoundException e) {
|
||||
if (appName != null && !appName.equals(Constants.CREDENTIAL_DEFAULT)
|
||||
&& propertyPath.equals(Constants.CREDENTIAL_PATH + appName)) {
|
||||
propertyPath = Constants.CREDENTIAL_PATH
|
||||
+ Constants.CREDENTIAL_DEFAULT;
|
||||
continue;
|
||||
}
|
||||
if (!Constants.DOCKER_CREDENTIAL_PATH.equals(propertyPath)) {
|
||||
propertyPath = Constants.DOCKER_CREDENTIAL_PATH;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
while (true);
|
||||
|
||||
String accessKey = null;
|
||||
String secretKey = null;
|
||||
if (propertiesIS == null) {
|
||||
propertyPath = null;
|
||||
accessKey = System.getenv(Constants.ENV_ACCESS_KEY);
|
||||
secretKey = System.getenv(Constants.ENV_SECRET_KEY);
|
||||
if (accessKey == null && secretKey == null) {
|
||||
if (logWarn) {
|
||||
SpasLogger.info(appName, "No credential found");
|
||||
}
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
Properties properties = new Properties();
|
||||
try {
|
||||
properties.load(propertiesIS);
|
||||
} catch (IOException e) {
|
||||
SpasLogger.error("26", "Unable to load credential file, appName:" + appName
|
||||
+ "Unable to load credential file " + propertyPath, e);
|
||||
propertyPath = null;
|
||||
return;
|
||||
} finally {
|
||||
try {
|
||||
propertiesIS.close();
|
||||
} catch (IOException e) {
|
||||
SpasLogger.error("27", "Unable to close credential file, appName:" + appName
|
||||
+ "Unable to close credential file " + propertyPath, e);
|
||||
}
|
||||
}
|
||||
String accessKey = null;
|
||||
String secretKey = null;
|
||||
String tenantId = "";
|
||||
if (propertiesIS == null) {
|
||||
propertyPath = null;
|
||||
accessKey = System.getenv(Constants.ENV_ACCESS_KEY);
|
||||
secretKey = System.getenv(Constants.ENV_SECRET_KEY);
|
||||
tenantId = System.getenv(Constants.ENV_TENANT_ID);
|
||||
if (accessKey == null && secretKey == null) {
|
||||
if (logWarn) {
|
||||
SpasLogger.info(appName, "No credential found");
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
else {
|
||||
Properties properties = new Properties();
|
||||
try {
|
||||
properties.load(propertiesIS);
|
||||
}
|
||||
catch (IOException e) {
|
||||
SpasLogger.error("26", "Unable to load credential file, appName:"
|
||||
+ appName + "Unable to load credential file " + propertyPath, e);
|
||||
propertyPath = null;
|
||||
return;
|
||||
}
|
||||
finally {
|
||||
try {
|
||||
propertiesIS.close();
|
||||
}
|
||||
catch (IOException e) {
|
||||
SpasLogger.error("27",
|
||||
"Unable to close credential file, appName:" + appName
|
||||
+ "Unable to close credential file " + propertyPath,
|
||||
e);
|
||||
}
|
||||
}
|
||||
|
||||
if (logWarn) {
|
||||
SpasLogger.info(appName, "Load credential file " + propertyPath);
|
||||
}
|
||||
if (logWarn) {
|
||||
SpasLogger.info(appName, "Load credential file " + propertyPath);
|
||||
}
|
||||
|
||||
if (!Constants.DOCKER_CREDENTIAL_PATH.equals(propertyPath)) {
|
||||
if (properties.containsKey(Constants.ACCESS_KEY)) {
|
||||
accessKey = properties.getProperty(Constants.ACCESS_KEY);
|
||||
}
|
||||
if (properties.containsKey(Constants.SECRET_KEY)) {
|
||||
secretKey = properties.getProperty(Constants.SECRET_KEY);
|
||||
}
|
||||
} else {
|
||||
if (properties.containsKey(Constants.DOCKER_ACCESS_KEY)) {
|
||||
accessKey = properties.getProperty(Constants.DOCKER_ACCESS_KEY);
|
||||
}
|
||||
if (properties.containsKey(Constants.DOCKER_SECRET_KEY)) {
|
||||
secretKey = properties.getProperty(Constants.DOCKER_SECRET_KEY);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!Constants.DOCKER_CREDENTIAL_PATH.equals(propertyPath)) {
|
||||
if (properties.containsKey(Constants.ACCESS_KEY)) {
|
||||
accessKey = properties.getProperty(Constants.ACCESS_KEY);
|
||||
}
|
||||
if (properties.containsKey(Constants.SECRET_KEY)) {
|
||||
secretKey = properties.getProperty(Constants.SECRET_KEY);
|
||||
}
|
||||
if (properties.containsKey(Constants.TENANT_ID)) {
|
||||
tenantId = properties.getProperty(Constants.TENANT_ID);
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (properties.containsKey(Constants.DOCKER_ACCESS_KEY)) {
|
||||
accessKey = properties.getProperty(Constants.DOCKER_ACCESS_KEY);
|
||||
}
|
||||
if (properties.containsKey(Constants.DOCKER_SECRET_KEY)) {
|
||||
secretKey = properties.getProperty(Constants.DOCKER_SECRET_KEY);
|
||||
}
|
||||
|
||||
if (accessKey != null) {
|
||||
accessKey = accessKey.trim();
|
||||
}
|
||||
if (secretKey != null) {
|
||||
secretKey = secretKey.trim();
|
||||
}
|
||||
if (properties.containsKey(Constants.DOCKER_TENANT_ID)) {
|
||||
tenantId = properties.getProperty(Constants.DOCKER_TENANT_ID);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Credentials credential = new Credentials(accessKey, secretKey);
|
||||
if (!credential.valid()) {
|
||||
SpasLogger.warn("1", "Credential file missing required property" + appName + "Credential file missing "
|
||||
+ Constants.ACCESS_KEY + " or " + Constants.SECRET_KEY);
|
||||
propertyPath = null;
|
||||
// return;
|
||||
}
|
||||
if (accessKey != null) {
|
||||
accessKey = accessKey.trim();
|
||||
}
|
||||
if (secretKey != null) {
|
||||
secretKey = secretKey.trim();
|
||||
}
|
||||
|
||||
serviceInstance.setCredential(credential);
|
||||
}
|
||||
if (tenantId != null) {
|
||||
tenantId = tenantId.trim();
|
||||
}
|
||||
|
||||
Credentials credential = new Credentials(accessKey, secretKey, tenantId);
|
||||
if (!credential.valid()) {
|
||||
SpasLogger.warn("1",
|
||||
"Credential file missing required property" + appName
|
||||
+ "Credential file missing " + Constants.ACCESS_KEY + " or "
|
||||
+ Constants.SECRET_KEY);
|
||||
propertyPath = null;
|
||||
// return;
|
||||
}
|
||||
|
||||
serviceInstance.setCredential(credential);
|
||||
}
|
||||
}
|
||||
|
@ -26,13 +26,16 @@ public class Credentials implements SpasCredential {
|
||||
|
||||
private volatile String secretKey;
|
||||
|
||||
public Credentials(String accessKey, String secretKey) {
|
||||
private volatile String tenantId;
|
||||
|
||||
public Credentials(String accessKey, String secretKey, String tenantId) {
|
||||
this.accessKey = accessKey;
|
||||
this.secretKey = secretKey;
|
||||
this.tenantId = tenantId;
|
||||
}
|
||||
|
||||
public Credentials() {
|
||||
this(null, null);
|
||||
this(null, null, null);
|
||||
}
|
||||
|
||||
public String getAccessKey() {
|
||||
@ -51,16 +54,24 @@ public class Credentials implements SpasCredential {
|
||||
this.secretKey = secretKey;
|
||||
}
|
||||
|
||||
public String getTenantId() {
|
||||
return tenantId;
|
||||
}
|
||||
|
||||
public void setTenantId(String tenantId) {
|
||||
this.tenantId = tenantId;
|
||||
}
|
||||
|
||||
public boolean valid() {
|
||||
return accessKey != null && !accessKey.isEmpty() && secretKey != null && !secretKey.isEmpty();
|
||||
return accessKey != null && !accessKey.isEmpty() && secretKey != null
|
||||
&& !secretKey.isEmpty();
|
||||
}
|
||||
|
||||
public boolean identical(Credentials other) {
|
||||
return this == other ||
|
||||
(other != null &&
|
||||
(accessKey == null && other.accessKey == null || accessKey != null && accessKey.equals(other.accessKey))
|
||||
&&
|
||||
(secretKey == null && other.secretKey == null || secretKey != null && secretKey.equals(
|
||||
other.secretKey)));
|
||||
return this == other || (other != null
|
||||
&& (accessKey == null && other.accessKey == null
|
||||
|| accessKey != null && accessKey.equals(other.accessKey))
|
||||
&& (secretKey == null && other.secretKey == null
|
||||
|| secretKey != null && secretKey.equals(other.secretKey)));
|
||||
}
|
||||
}
|
||||
|
@ -115,43 +115,64 @@ public class NacosNamingService implements NamingService {
|
||||
namespace = properties.getProperty(PropertyKeyConst.NAMESPACE);
|
||||
}
|
||||
|
||||
if (StringUtils.isNotEmpty(properties.getProperty(UtilAndComs.NACOS_NAMING_LOG_NAME))) {
|
||||
if (StringUtils
|
||||
.isNotEmpty(properties.getProperty(UtilAndComs.NACOS_NAMING_LOG_NAME))) {
|
||||
logName = properties.getProperty(UtilAndComs.NACOS_NAMING_LOG_NAME);
|
||||
}
|
||||
|
||||
if (StringUtils.isNotEmpty(properties.getProperty(PropertyKeyConst.ENDPOINT))) {
|
||||
endpoint = properties.getProperty(PropertyKeyConst.ENDPOINT) + ":" +
|
||||
properties.getProperty("address.server.port", "8080");
|
||||
endpoint = properties.getProperty(PropertyKeyConst.ENDPOINT) + ":"
|
||||
+ properties.getProperty("address.server.port", "8080");
|
||||
}
|
||||
|
||||
initWebRootContext();
|
||||
|
||||
cacheDir = System.getProperty("user.home") + "/nacos/naming/" + namespace;
|
||||
|
||||
boolean loadCacheAtStart = false;
|
||||
if (StringUtils.isNotEmpty(properties.getProperty(PropertyKeyConst.NAMING_LOAD_CACHE_AT_START))) {
|
||||
if (StringUtils.isNotEmpty(
|
||||
properties.getProperty(PropertyKeyConst.NAMING_LOAD_CACHE_AT_START))) {
|
||||
loadCacheAtStart = BooleanUtils.toBoolean(
|
||||
properties.getProperty(PropertyKeyConst.NAMING_LOAD_CACHE_AT_START));
|
||||
}
|
||||
|
||||
int clientBeatThreadCount = NumberUtils.toInt(properties.getProperty(PropertyKeyConst.NAMING_CLIENT_BEAT_THREAD_COUNT),
|
||||
int clientBeatThreadCount = NumberUtils.toInt(
|
||||
properties.getProperty(PropertyKeyConst.NAMING_CLIENT_BEAT_THREAD_COUNT),
|
||||
UtilAndComs.DEFAULT_CLIENT_BEAT_THREAD_COUNT);
|
||||
|
||||
int pollingThreadCount = NumberUtils.toInt(properties.getProperty(PropertyKeyConst.NAMING_POLLING_THREAD_COUNT),
|
||||
int pollingThreadCount = NumberUtils.toInt(
|
||||
properties.getProperty(PropertyKeyConst.NAMING_POLLING_THREAD_COUNT),
|
||||
UtilAndComs.DEFAULT_POLLING_THREAD_COUNT);
|
||||
|
||||
eventDispatcher = new EventDispatcher();
|
||||
serverProxy = new NamingProxy(namespace, endpoint, serverList);
|
||||
beatReactor = new BeatReactor(serverProxy, clientBeatThreadCount);
|
||||
hostReactor = new HostReactor(eventDispatcher, serverProxy, cacheDir, loadCacheAtStart, pollingThreadCount);
|
||||
hostReactor = new HostReactor(eventDispatcher, serverProxy, cacheDir,
|
||||
loadCacheAtStart, pollingThreadCount);
|
||||
|
||||
}
|
||||
|
||||
private void initWebRootContext() {
|
||||
// support the web context with ali-yun if the app deploy by EDAS
|
||||
String webContext = System.getProperties().getProperty(PropertyKeyConst.WEB_CONTEXT);
|
||||
if (StringUtils.isNotEmpty(webContext)) {
|
||||
UtilAndComs.WEB_CONTEXT = webContext.indexOf("/") > -1 ? webContext
|
||||
: "/" + webContext;
|
||||
}
|
||||
|
||||
UtilAndComs.NACOS_URL_BASE = UtilAndComs.WEB_CONTEXT + "/v1/ns";
|
||||
UtilAndComs.NACOS_URL_INSTANCE = UtilAndComs.NACOS_URL_BASE + "/instance";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerInstance(String serviceName, String ip, int port) throws NacosException {
|
||||
public void registerInstance(String serviceName, String ip, int port)
|
||||
throws NacosException {
|
||||
registerInstance(serviceName, ip, port, Constants.NAMING_DEFAULT_CLUSTER_NAME);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerInstance(String serviceName, String ip, int port, String clusterName) throws NacosException {
|
||||
public void registerInstance(String serviceName, String ip, int port,
|
||||
String clusterName) throws NacosException {
|
||||
Instance instance = new Instance();
|
||||
instance.setIp(ip);
|
||||
instance.setPort(port);
|
||||
@ -162,7 +183,8 @@ public class NacosNamingService implements NamingService {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerInstance(String serviceName, Instance instance) throws NacosException {
|
||||
public void registerInstance(String serviceName, Instance instance)
|
||||
throws NacosException {
|
||||
|
||||
BeatInfo beatInfo = new BeatInfo();
|
||||
beatInfo.setServiceName(serviceName);
|
||||
@ -179,12 +201,14 @@ public class NacosNamingService implements NamingService {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deregisterInstance(String serviceName, String ip, int port) throws NacosException {
|
||||
public void deregisterInstance(String serviceName, String ip, int port)
|
||||
throws NacosException {
|
||||
deregisterInstance(serviceName, ip, port, Constants.NAMING_DEFAULT_CLUSTER_NAME);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deregisterInstance(String serviceName, String ip, int port, String clusterName) throws NacosException {
|
||||
public void deregisterInstance(String serviceName, String ip, int port,
|
||||
String clusterName) throws NacosException {
|
||||
beatReactor.removeBeatInfo(serviceName, ip, port);
|
||||
serverProxy.deregisterService(serviceName, ip, port, clusterName);
|
||||
}
|
||||
@ -195,55 +219,65 @@ public class NacosNamingService implements NamingService {
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Instance> getAllInstances(String serviceName, boolean subscribe) throws NacosException {
|
||||
public List<Instance> getAllInstances(String serviceName, boolean subscribe)
|
||||
throws NacosException {
|
||||
return getAllInstances(serviceName, new ArrayList<String>(), subscribe);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Instance> getAllInstances(String serviceName, List<String> clusters) throws NacosException {
|
||||
public List<Instance> getAllInstances(String serviceName, List<String> clusters)
|
||||
throws NacosException {
|
||||
return getAllInstances(serviceName, clusters, true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Instance> getAllInstances(String serviceName, List<String> clusters, boolean subscribe) throws NacosException {
|
||||
public List<Instance> getAllInstances(String serviceName, List<String> clusters,
|
||||
boolean subscribe) throws NacosException {
|
||||
|
||||
ServiceInfo serviceInfo;
|
||||
if (subscribe) {
|
||||
serviceInfo = hostReactor.getServiceInfo(serviceName, StringUtils.join(clusters, ","));
|
||||
serviceInfo = hostReactor.getServiceInfo(serviceName,
|
||||
StringUtils.join(clusters, ","));
|
||||
} else {
|
||||
serviceInfo = hostReactor.getServiceInfoDirectlyFromServer(serviceName, StringUtils.join(clusters, ","));
|
||||
serviceInfo = hostReactor.getServiceInfoDirectlyFromServer(serviceName,
|
||||
StringUtils.join(clusters, ","));
|
||||
}
|
||||
List<Instance> list;
|
||||
if (serviceInfo == null || CollectionUtils.isEmpty(list = serviceInfo.getHosts())) {
|
||||
if (serviceInfo == null
|
||||
|| CollectionUtils.isEmpty(list = serviceInfo.getHosts())) {
|
||||
return new ArrayList<Instance>();
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Instance> selectInstances(String serviceName, boolean healthy) throws NacosException {
|
||||
public List<Instance> selectInstances(String serviceName, boolean healthy)
|
||||
throws NacosException {
|
||||
return selectInstances(serviceName, new ArrayList<String>(), healthy);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Instance> selectInstances(String serviceName, boolean healthy, boolean subscribe) throws NacosException {
|
||||
public List<Instance> selectInstances(String serviceName, boolean healthy,
|
||||
boolean subscribe) throws NacosException {
|
||||
return selectInstances(serviceName, new ArrayList<String>(), healthy, subscribe);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Instance> selectInstances(String serviceName, List<String> clusters, boolean healthy)
|
||||
throws NacosException {
|
||||
public List<Instance> selectInstances(String serviceName, List<String> clusters,
|
||||
boolean healthy) throws NacosException {
|
||||
return selectInstances(serviceName, clusters, healthy, true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Instance> selectInstances(String serviceName, List<String> clusters, boolean healthy,
|
||||
boolean subscribe) throws NacosException {
|
||||
public List<Instance> selectInstances(String serviceName, List<String> clusters,
|
||||
boolean healthy, boolean subscribe) throws NacosException {
|
||||
ServiceInfo serviceInfo;
|
||||
if (subscribe) {
|
||||
serviceInfo = hostReactor.getServiceInfo(serviceName, StringUtils.join(clusters, ","));
|
||||
serviceInfo = hostReactor.getServiceInfo(serviceName,
|
||||
StringUtils.join(clusters, ","));
|
||||
} else {
|
||||
serviceInfo = hostReactor.getServiceInfoDirectlyFromServer(serviceName, StringUtils.join(clusters, ","));
|
||||
serviceInfo = hostReactor.getServiceInfoDirectlyFromServer(serviceName,
|
||||
StringUtils.join(clusters, ","));
|
||||
}
|
||||
return selectInstances(serviceInfo, healthy);
|
||||
}
|
||||
@ -254,36 +288,42 @@ public class NacosNamingService implements NamingService {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Instance selectOneHealthyInstance(String serviceName, boolean subscribe) throws NacosException {
|
||||
public Instance selectOneHealthyInstance(String serviceName, boolean subscribe)
|
||||
throws NacosException {
|
||||
return selectOneHealthyInstance(serviceName, new ArrayList<String>(), subscribe);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Instance selectOneHealthyInstance(String serviceName, List<String> clusters) throws NacosException {
|
||||
public Instance selectOneHealthyInstance(String serviceName, List<String> clusters)
|
||||
throws NacosException {
|
||||
return selectOneHealthyInstance(serviceName, clusters, true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Instance selectOneHealthyInstance(String serviceName, List<String> clusters, boolean subscribe) throws NacosException {
|
||||
public Instance selectOneHealthyInstance(String serviceName, List<String> clusters,
|
||||
boolean subscribe) throws NacosException {
|
||||
|
||||
if (subscribe) {
|
||||
return Balancer.RandomByWeight.selectHost(
|
||||
hostReactor.getServiceInfo(serviceName, StringUtils.join(clusters, ",")));
|
||||
return Balancer.RandomByWeight.selectHost(hostReactor
|
||||
.getServiceInfo(serviceName, StringUtils.join(clusters, ",")));
|
||||
} else {
|
||||
return Balancer.RandomByWeight.selectHost(
|
||||
hostReactor.getServiceInfoDirectlyFromServer(serviceName, StringUtils.join(clusters, ",")));
|
||||
return Balancer.RandomByWeight
|
||||
.selectHost(hostReactor.getServiceInfoDirectlyFromServer(serviceName,
|
||||
StringUtils.join(clusters, ",")));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void subscribe(String service, EventListener listener) {
|
||||
eventDispatcher.addListener(hostReactor.getServiceInfo(service, StringUtils.EMPTY), StringUtils.EMPTY,
|
||||
eventDispatcher.addListener(
|
||||
hostReactor.getServiceInfo(service, StringUtils.EMPTY), StringUtils.EMPTY,
|
||||
listener);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void subscribe(String service, List<String> clusters, EventListener listener) {
|
||||
eventDispatcher.addListener(hostReactor.getServiceInfo(service, StringUtils.join(clusters, ",")),
|
||||
eventDispatcher.addListener(
|
||||
hostReactor.getServiceInfo(service, StringUtils.join(clusters, ",")),
|
||||
StringUtils.join(clusters, ","), listener);
|
||||
}
|
||||
|
||||
@ -293,17 +333,21 @@ public class NacosNamingService implements NamingService {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void unsubscribe(String service, List<String> clusters, EventListener listener) {
|
||||
eventDispatcher.removeListener(service, StringUtils.join(clusters, ","), listener);
|
||||
public void unsubscribe(String service, List<String> clusters,
|
||||
EventListener listener) {
|
||||
eventDispatcher.removeListener(service, StringUtils.join(clusters, ","),
|
||||
listener);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ListView<String> getServicesOfServer(int pageNo, int pageSize) throws NacosException {
|
||||
public ListView<String> getServicesOfServer(int pageNo, int pageSize)
|
||||
throws NacosException {
|
||||
return serverProxy.getServiceList(pageNo, pageSize);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ListView<String> getServicesOfServer(int pageNo, int pageSize, AbstractSelector selector) throws NacosException {
|
||||
public ListView<String> getServicesOfServer(int pageNo, int pageSize,
|
||||
AbstractSelector selector) throws NacosException {
|
||||
return serverProxy.getServiceList(pageNo, pageSize, selector);
|
||||
}
|
||||
|
||||
@ -319,14 +363,16 @@ public class NacosNamingService implements NamingService {
|
||||
|
||||
private List<Instance> selectInstances(ServiceInfo serviceInfo, boolean healthy) {
|
||||
List<Instance> list;
|
||||
if (serviceInfo == null || CollectionUtils.isEmpty(list = serviceInfo.getHosts())) {
|
||||
if (serviceInfo == null
|
||||
|| CollectionUtils.isEmpty(list = serviceInfo.getHosts())) {
|
||||
return new ArrayList<Instance>();
|
||||
}
|
||||
|
||||
Iterator<Instance> iterator = list.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
Instance instance = iterator.next();
|
||||
if (healthy != instance.isHealthy() || !instance.isEnabled() || instance.getWeight() <= 0) {
|
||||
if (healthy != instance.isHealthy() || !instance.isEnabled()
|
||||
|| instance.getWeight() <= 0) {
|
||||
iterator.remove();
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,66 @@
|
||||
/*
|
||||
* Copyright (C) 2019 the original author or authors.
|
||||
*
|
||||
* 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.client.identify.Base64;
|
||||
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.nio.charset.Charset;
|
||||
|
||||
/**
|
||||
* @author pbting
|
||||
* @date 2019-01-22 10:20 PM
|
||||
*/
|
||||
public class SignUtil {
|
||||
public static final Charset UTF8 = Charset.forName("UTF-8");
|
||||
|
||||
public SignUtil() {
|
||||
}
|
||||
|
||||
public static String sign(String data, String key) throws Exception {
|
||||
try {
|
||||
byte[] signature = sign(data.getBytes(UTF8), key.getBytes(UTF8),
|
||||
SignUtil.SigningAlgorithm.HmacSHA1);
|
||||
return new String(Base64.encodeBase64(signature));
|
||||
} catch (Exception var3) {
|
||||
throw new Exception(
|
||||
"Unable to calculate a request signature: " + var3.getMessage(),
|
||||
var3);
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] sign(byte[] data, byte[] key,
|
||||
SignUtil.SigningAlgorithm algorithm) throws Exception {
|
||||
try {
|
||||
Mac mac = Mac.getInstance(algorithm.toString());
|
||||
mac.init(new SecretKeySpec(key, algorithm.toString()));
|
||||
return mac.doFinal(data);
|
||||
} catch (Exception var4) {
|
||||
throw new Exception(
|
||||
"Unable to calculate a request signature: " + var4.getMessage(),
|
||||
var4);
|
||||
}
|
||||
}
|
||||
|
||||
public static enum SigningAlgorithm {
|
||||
// Hmac SHA1 algorithm
|
||||
HmacSHA1;
|
||||
|
||||
private SigningAlgorithm() {
|
||||
}
|
||||
}
|
||||
}
|
@ -35,9 +35,15 @@ import java.util.zip.GZIPInputStream;
|
||||
*/
|
||||
public class HttpClient {
|
||||
|
||||
public static final int TIME_OUT_MILLIS = Integer.getInteger("com.alibaba.nacos.client.naming.ctimeout", 50000);
|
||||
public static final int CON_TIME_OUT_MILLIS = Integer.getInteger("com.alibaba.nacos.client.naming.ctimeout", 3000);
|
||||
private static final boolean ENABLE_HTTPS = Boolean.getBoolean("com.alibaba.nacos.client.naming.tls.enable");
|
||||
public static final int TIME_OUT_MILLIS = Integer
|
||||
.getInteger("com.alibaba.nacos.client.naming.ctimeout", 50000);
|
||||
public static final int CON_TIME_OUT_MILLIS = Integer
|
||||
.getInteger("com.alibaba.nacos.client.naming.ctimeout", 3000);
|
||||
private static final boolean ENABLE_HTTPS = Boolean
|
||||
.getBoolean("com.alibaba.nacos.client.naming.tls.enable");
|
||||
|
||||
private static final String POST = "POST";
|
||||
private static final String PUT = "PUT";
|
||||
|
||||
static {
|
||||
// limit max redirection
|
||||
@ -53,11 +59,13 @@ public class HttpClient {
|
||||
|
||||
}
|
||||
|
||||
public static HttpResult httpGet(String url, List<String> headers, Map<String, String> paramValues, String encoding) {
|
||||
public static HttpResult httpGet(String url, List<String> headers,
|
||||
Map<String, String> paramValues, String encoding) {
|
||||
return request(url, headers, paramValues, encoding, "GET");
|
||||
}
|
||||
|
||||
public static HttpResult request(String url, List<String> headers, Map<String, String> paramValues, String encoding, String method) {
|
||||
public static HttpResult request(String url, List<String> headers,
|
||||
Map<String, String> paramValues, String encoding, String method) {
|
||||
HttpURLConnection conn = null;
|
||||
try {
|
||||
String encodedContent = encodingParams(paramValues, encoding);
|
||||
@ -65,27 +73,38 @@ public class HttpClient {
|
||||
|
||||
conn = (HttpURLConnection) new URL(url).openConnection();
|
||||
|
||||
setHeaders(conn, headers, encoding);
|
||||
conn.setConnectTimeout(CON_TIME_OUT_MILLIS);
|
||||
conn.setReadTimeout(TIME_OUT_MILLIS);
|
||||
conn.setRequestMethod(method);
|
||||
setHeaders(conn, headers, encoding);
|
||||
conn.setDoOutput(true);
|
||||
if (POST.equals(method) || PUT.equals(method)) {
|
||||
// fix: apache http nio framework must set some content to request body
|
||||
byte[] b = encodedContent.getBytes();
|
||||
conn.setRequestProperty("Content-Length", String.valueOf(b.length));
|
||||
conn.getOutputStream().write(b, 0, b.length);
|
||||
conn.getOutputStream().flush();
|
||||
conn.getOutputStream().close();
|
||||
}
|
||||
conn.connect();
|
||||
LogUtils.LOG.debug("Request from server: " + url);
|
||||
return getResult(conn);
|
||||
} catch (Exception e) {
|
||||
try {
|
||||
if (conn != null) {
|
||||
LogUtils.LOG.warn("failed to request " + conn.getURL() + " from "
|
||||
+ InetAddress.getByName(conn.getURL().getHost()).getHostAddress());
|
||||
LogUtils.LOG.warn(
|
||||
"failed to request " + conn.getURL() + " from " + InetAddress
|
||||
.getByName(conn.getURL().getHost()).getHostAddress());
|
||||
}
|
||||
} catch (Exception e1) {
|
||||
LogUtils.LOG.error("NA", "failed to request ", e1);
|
||||
//ignore
|
||||
// ignore
|
||||
}
|
||||
|
||||
LogUtils.LOG.error("NA", "failed to request ", e);
|
||||
|
||||
return new HttpResult(500, e.toString(), Collections.<String, String>emptyMap());
|
||||
return new HttpResult(500, e.toString(),
|
||||
Collections.<String, String>emptyMap());
|
||||
} finally {
|
||||
if (conn != null) {
|
||||
conn.disconnect();
|
||||
@ -98,13 +117,14 @@ public class HttpClient {
|
||||
|
||||
InputStream inputStream;
|
||||
if (HttpURLConnection.HTTP_OK == respCode
|
||||
|| HttpURLConnection.HTTP_NOT_MODIFIED == respCode) {
|
||||
|| HttpURLConnection.HTTP_NOT_MODIFIED == respCode) {
|
||||
inputStream = conn.getInputStream();
|
||||
} else {
|
||||
inputStream = conn.getErrorStream();
|
||||
}
|
||||
|
||||
Map<String, String> respHeaders = new HashMap<String, String>(conn.getHeaderFields().size());
|
||||
Map<String, String> respHeaders = new HashMap<String, String>(
|
||||
conn.getHeaderFields().size());
|
||||
for (Map.Entry<String, List<String>> entry : conn.getHeaderFields().entrySet()) {
|
||||
respHeaders.put(entry.getKey(), entry.getValue().get(0));
|
||||
}
|
||||
@ -115,7 +135,8 @@ public class HttpClient {
|
||||
inputStream = new GZIPInputStream(inputStream);
|
||||
}
|
||||
|
||||
return new HttpResult(respCode, IoUtils.toString(inputStream, getCharset(conn)), respHeaders);
|
||||
return new HttpResult(respCode, IoUtils.toString(inputStream, getCharset(conn)),
|
||||
respHeaders);
|
||||
}
|
||||
|
||||
private static String getCharset(HttpURLConnection conn) {
|
||||
@ -141,26 +162,26 @@ public class HttpClient {
|
||||
return charset;
|
||||
}
|
||||
|
||||
private static void setHeaders(HttpURLConnection conn, List<String> headers, String encoding) {
|
||||
private static void setHeaders(HttpURLConnection conn, List<String> headers,
|
||||
String encoding) {
|
||||
if (null != headers) {
|
||||
for (Iterator<String> iter = headers.iterator(); iter.hasNext(); ) {
|
||||
conn.addRequestProperty(iter.next(), iter.next());
|
||||
}
|
||||
}
|
||||
|
||||
conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset="
|
||||
+ encoding);
|
||||
conn.addRequestProperty("Content-Type",
|
||||
"application/x-www-form-urlencoded;charset=" + encoding);
|
||||
conn.addRequestProperty("Accept-Charset", encoding);
|
||||
}
|
||||
|
||||
private static String encodingParams(Map<String, String> params, String encoding)
|
||||
throws UnsupportedEncodingException {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
if (null == params || params.isEmpty()) {
|
||||
throws UnsupportedEncodingException {
|
||||
if (null == params) {
|
||||
return null;
|
||||
}
|
||||
|
||||
params.put("encoding", encoding);
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
for (Map.Entry<String, String> entry : params.entrySet()) {
|
||||
if (StringUtils.isEmpty(entry.getValue())) {
|
||||
@ -172,6 +193,9 @@ public class HttpClient {
|
||||
sb.append("&");
|
||||
}
|
||||
|
||||
if (sb.length() > 0) {
|
||||
sb = sb.deleteCharAt(sb.length() - 1);
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
|
@ -18,6 +18,7 @@ package com.alibaba.nacos.client.naming.net;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.alibaba.fastjson.TypeReference;
|
||||
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.pojo.Instance;
|
||||
@ -25,7 +26,9 @@ import com.alibaba.nacos.api.naming.pojo.ListView;
|
||||
import com.alibaba.nacos.api.selector.AbstractSelector;
|
||||
import com.alibaba.nacos.api.selector.ExpressionSelector;
|
||||
import com.alibaba.nacos.api.selector.SelectorType;
|
||||
import com.alibaba.nacos.client.identify.CredentialService;
|
||||
import com.alibaba.nacos.client.monitor.MetricsMonitor;
|
||||
import com.alibaba.nacos.client.naming.SignUtil;
|
||||
import com.alibaba.nacos.client.naming.beat.BeatInfo;
|
||||
import com.alibaba.nacos.client.naming.utils.*;
|
||||
import com.alibaba.nacos.common.util.HttpMethod;
|
||||
@ -47,6 +50,8 @@ public class NamingProxy {
|
||||
|
||||
private static final int DEFAULT_SERVER_PORT = 8848;
|
||||
|
||||
private int serverPort = DEFAULT_SERVER_PORT;
|
||||
|
||||
private String namespaceId;
|
||||
|
||||
private String endpoint;
|
||||
@ -61,12 +66,15 @@ public class NamingProxy {
|
||||
|
||||
private long vipSrvRefInterMillis = TimeUnit.SECONDS.toMillis(30);
|
||||
|
||||
private CredentialService credentialService = CredentialService.getInstance();
|
||||
|
||||
private ScheduledExecutorService executorService;
|
||||
|
||||
public NamingProxy(String namespaceId, String endpoint, String serverList) {
|
||||
|
||||
this.namespaceId = namespaceId;
|
||||
this.endpoint = endpoint;
|
||||
|
||||
if (StringUtils.isNotEmpty(serverList)) {
|
||||
this.serverList = Arrays.asList(serverList.split(","));
|
||||
if (this.serverList.size() == 1) {
|
||||
@ -74,6 +82,11 @@ public class NamingProxy {
|
||||
}
|
||||
}
|
||||
|
||||
String serverPort = System.getProperties().getProperty(PropertyKeyConst.SERVER_PORT);
|
||||
if (StringUtils.isNotEmpty(serverPort)) {
|
||||
this.serverPort = Integer.valueOf(serverPort.trim());
|
||||
}
|
||||
|
||||
executorService = new ScheduledThreadPoolExecutor(1, new ThreadFactory() {
|
||||
@Override
|
||||
public Thread newThread(Runnable r) {
|
||||
@ -94,20 +107,24 @@ public class NamingProxy {
|
||||
refreshSrvIfNeed();
|
||||
}
|
||||
|
||||
public void setServerPort(int serverPort) {
|
||||
this.serverPort = serverPort;
|
||||
}
|
||||
|
||||
public List<String> getServerListFromEndpoint() {
|
||||
|
||||
try {
|
||||
String urlString = "http://" + endpoint + "/nacos/serverlist";
|
||||
|
||||
List<String> headers = Arrays.asList("Client-Version", UtilAndComs.VERSION,
|
||||
"Accept-Encoding", "gzip,deflate,sdch",
|
||||
"Connection", "Keep-Alive",
|
||||
"Accept-Encoding", "gzip,deflate,sdch", "Connection", "Keep-Alive",
|
||||
"RequestId", UuidUtils.generateUuid());
|
||||
|
||||
HttpClient.HttpResult result = HttpClient.httpGet(urlString, headers, null, UtilAndComs.ENCODING);
|
||||
HttpClient.HttpResult result = HttpClient.httpGet(urlString, headers, null,
|
||||
UtilAndComs.ENCODING);
|
||||
if (HttpURLConnection.HTTP_OK != result.code) {
|
||||
throw new IOException("Error while requesting: " + urlString + "'. Server returned: "
|
||||
+ result.code);
|
||||
throw new IOException("Error while requesting: " + urlString
|
||||
+ "'. Server returned: " + result.code);
|
||||
}
|
||||
|
||||
String content = result.content;
|
||||
@ -156,10 +173,12 @@ public class NamingProxy {
|
||||
}
|
||||
}
|
||||
|
||||
public void registerService(String serviceName, Instance instance) throws NacosException {
|
||||
public void registerService(String serviceName, Instance instance)
|
||||
throws NacosException {
|
||||
|
||||
LogUtils.LOG.info("REGISTER-SERVICE", "{} registering service {} with instance: {}",
|
||||
namespaceId, serviceName, instance);
|
||||
LogUtils.LOG.info("REGISTER-SERVICE",
|
||||
"{} registering service {} with instance: {}", namespaceId, serviceName,
|
||||
instance);
|
||||
|
||||
final Map<String, String> params = new HashMap<String, String>(8);
|
||||
params.put(Constants.REQUEST_PARAM_NAMESPACE_ID, namespaceId);
|
||||
@ -176,10 +195,41 @@ public class NamingProxy {
|
||||
|
||||
}
|
||||
|
||||
public void deregisterService(String serviceName, String ip, int port, String cluster) throws NacosException {
|
||||
private void checkTenant(Map<String, String> params) {
|
||||
String tenantId = credentialService.getCredential().getTenantId();
|
||||
if (tenantId == null || tenantId.trim().length() == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
LogUtils.LOG.info("DEREGISTER-SERVICE", "{} deregistering service {} with instance: {}:{}@{}",
|
||||
namespaceId, serviceName, ip, port, cluster);
|
||||
try {
|
||||
String tenantApp = System.getProperty("project.name");
|
||||
String tenantAk = credentialService.getCredential().getAccessKey();
|
||||
String tenantSK = credentialService.getCredential().getSecretKey();
|
||||
String signData = getSignData(params);
|
||||
String signature = SignUtil.sign(signData, tenantSK);
|
||||
params.put("signature", signature);
|
||||
params.put("data", signData);
|
||||
params.put("ak", tenantAk);
|
||||
params.put("app", tenantApp);
|
||||
params.put(Constants.REQUEST_PARAM_NAMESPACE_ID, tenantId);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private static String getSignData(Map<String, String> params) {
|
||||
String data = "";
|
||||
return params.containsKey("dom")
|
||||
? System.currentTimeMillis() + "@@" + (String) params.get("dom")
|
||||
: String.valueOf(System.currentTimeMillis());
|
||||
}
|
||||
|
||||
public void deregisterService(String serviceName, String ip, int port, String cluster)
|
||||
throws NacosException {
|
||||
|
||||
LogUtils.LOG.info("DEREGISTER-SERVICE",
|
||||
"{} deregistering service {} with instance: {}:{}@{}", namespaceId,
|
||||
serviceName, ip, port, cluster);
|
||||
|
||||
final Map<String, String> params = new HashMap<String, String>(8);
|
||||
params.put(Constants.REQUEST_PARAM_NAMESPACE_ID, namespaceId);
|
||||
@ -191,7 +241,8 @@ public class NamingProxy {
|
||||
reqAPI(UtilAndComs.NACOS_URL_INSTANCE, params, HttpMethod.DELETE);
|
||||
}
|
||||
|
||||
public String queryList(String serviceName, String clusters, int udpPort, boolean healthyOnly) throws NacosException {
|
||||
public String queryList(String serviceName, String clusters, int udpPort,
|
||||
boolean healthyOnly) throws NacosException {
|
||||
|
||||
final Map<String, String> params = new HashMap<String, String>(8);
|
||||
params.put(Constants.REQUEST_PARAM_NAMESPACE_ID, namespaceId);
|
||||
@ -201,24 +252,28 @@ public class NamingProxy {
|
||||
params.put("clientIP", NetUtils.localIP());
|
||||
params.put("healthyOnly", String.valueOf(healthyOnly));
|
||||
|
||||
return reqAPI(UtilAndComs.NACOS_URL_BASE + "/instance/list", params, HttpMethod.GET);
|
||||
return reqAPI(UtilAndComs.NACOS_URL_BASE + "/instance/list", params,
|
||||
HttpMethod.GET);
|
||||
}
|
||||
|
||||
public long sendBeat(BeatInfo beatInfo) {
|
||||
try {
|
||||
LogUtils.LOG.info("BEAT", "{} sending beat to server: {}", namespaceId, beatInfo.toString());
|
||||
LogUtils.LOG.info("BEAT", "{} sending beat to server: {}", namespaceId,
|
||||
beatInfo.toString());
|
||||
Map<String, String> params = new HashMap<String, String>(4);
|
||||
params.put("beat", JSON.toJSONString(beatInfo));
|
||||
params.put(Constants.REQUEST_PARAM_NAMESPACE_ID, namespaceId);
|
||||
params.put("serviceName", beatInfo.getServiceName());
|
||||
String result = reqAPI(UtilAndComs.NACOS_URL_BASE + "/instance/beat", params, HttpMethod.PUT);
|
||||
String result = reqAPI(UtilAndComs.NACOS_URL_BASE + "/instance/beat", params,
|
||||
HttpMethod.PUT);
|
||||
JSONObject jsonObject = JSON.parseObject(result);
|
||||
|
||||
if (jsonObject != null) {
|
||||
return jsonObject.getLong("clientBeatInterval");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LogUtils.LOG.error("CLIENT-BEAT", "failed to send beat: " + JSON.toJSONString(beatInfo), e);
|
||||
LogUtils.LOG.error("CLIENT-BEAT",
|
||||
"failed to send beat: " + JSON.toJSONString(beatInfo), e);
|
||||
}
|
||||
return 0L;
|
||||
}
|
||||
@ -226,7 +281,8 @@ public class NamingProxy {
|
||||
public boolean serverHealthy() {
|
||||
|
||||
try {
|
||||
reqAPI(UtilAndComs.NACOS_URL_BASE + "/api/hello", new HashMap<String, String>(2));
|
||||
reqAPI(UtilAndComs.NACOS_URL_BASE + "/api/hello",
|
||||
new HashMap<String, String>(2));
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
@ -234,11 +290,13 @@ public class NamingProxy {
|
||||
return true;
|
||||
}
|
||||
|
||||
public ListView<String> getServiceList(int pageNo, int pageSize) throws NacosException {
|
||||
public ListView<String> getServiceList(int pageNo, int pageSize)
|
||||
throws NacosException {
|
||||
return getServiceList(pageNo, pageSize, null);
|
||||
}
|
||||
|
||||
public ListView<String> getServiceList(int pageNo, int pageSize, AbstractSelector selector) throws NacosException {
|
||||
public ListView<String> getServiceList(int pageNo, int pageSize,
|
||||
AbstractSelector selector) throws NacosException {
|
||||
|
||||
Map<String, String> params = new HashMap<String, String>(4);
|
||||
params.put("pageNo", String.valueOf(pageNo));
|
||||
@ -263,15 +321,15 @@ public class NamingProxy {
|
||||
JSONObject json = JSON.parseObject(result);
|
||||
ListView<String> listView = new ListView<String>();
|
||||
listView.setCount(json.getInteger("count"));
|
||||
listView.setData(JSON.parseObject(json.getString("doms"), new TypeReference<List<String>>() {
|
||||
}));
|
||||
listView.setData(JSON.parseObject(json.getString("doms"),
|
||||
new TypeReference<List<String>>() {
|
||||
}));
|
||||
|
||||
return listView;
|
||||
}
|
||||
|
||||
public String reqAPI(String api, Map<String, String> params) throws NacosException {
|
||||
|
||||
|
||||
List<String> snapshot = serversFromEndpoint;
|
||||
if (!CollectionUtils.isEmpty(serverList)) {
|
||||
snapshot = serverList;
|
||||
@ -280,7 +338,8 @@ public class NamingProxy {
|
||||
return reqAPI(api, params, snapshot);
|
||||
}
|
||||
|
||||
public String reqAPI(String api, Map<String, String> params, String method) throws NacosException {
|
||||
public String reqAPI(String api, Map<String, String> params, String method)
|
||||
throws NacosException {
|
||||
|
||||
List<String> snapshot = serversFromEndpoint;
|
||||
if (!CollectionUtils.isEmpty(serverList)) {
|
||||
@ -290,29 +349,31 @@ public class NamingProxy {
|
||||
return reqAPI(api, params, snapshot, method);
|
||||
}
|
||||
|
||||
public String callServer(String api, Map<String, String> params, String curServer) throws NacosException {
|
||||
public String callServer(String api, Map<String, String> params, String curServer)
|
||||
throws NacosException {
|
||||
return callServer(api, params, curServer, HttpMethod.GET);
|
||||
}
|
||||
|
||||
public String callServer(String api, Map<String, String> params, String curServer, String method)
|
||||
throws NacosException {
|
||||
public String callServer(String api, Map<String, String> params, String curServer,
|
||||
String method) throws NacosException {
|
||||
long start = System.currentTimeMillis();
|
||||
long end = 0;
|
||||
|
||||
List<String> headers = Arrays.asList("Client-Version", UtilAndComs.VERSION,
|
||||
"Accept-Encoding", "gzip,deflate,sdch",
|
||||
"Connection", "Keep-Alive",
|
||||
"Accept-Encoding", "gzip,deflate,sdch", "Connection", "Keep-Alive",
|
||||
"RequestId", UuidUtils.generateUuid());
|
||||
|
||||
String url;
|
||||
|
||||
if (!curServer.contains(UtilAndComs.SERVER_ADDR_IP_SPLITER)) {
|
||||
curServer = curServer + UtilAndComs.SERVER_ADDR_IP_SPLITER + DEFAULT_SERVER_PORT;
|
||||
curServer = curServer + UtilAndComs.SERVER_ADDR_IP_SPLITER
|
||||
+ serverPort;
|
||||
}
|
||||
|
||||
url = HttpClient.getPrefix() + curServer + api;
|
||||
|
||||
HttpClient.HttpResult result = HttpClient.request(url, headers, params, UtilAndComs.ENCODING, method);
|
||||
HttpClient.HttpResult result = HttpClient.request(url, headers, params,
|
||||
UtilAndComs.ENCODING, method);
|
||||
end = System.currentTimeMillis();
|
||||
|
||||
MetricsMonitor.getNamingRequestMonitor(method, url, String.valueOf(result.code))
|
||||
@ -326,22 +387,23 @@ public class NamingProxy {
|
||||
return StringUtils.EMPTY;
|
||||
}
|
||||
|
||||
LogUtils.LOG.error("CALL-SERVER", "failed to req API:" + HttpClient.getPrefix() + curServer
|
||||
+ api + ". code:"
|
||||
+ result.code + " msg: " + result.content);
|
||||
LogUtils.LOG.error("CALL-SERVER", "failed to req API:" + HttpClient.getPrefix()
|
||||
+ curServer + api + ". code:" + result.code + " msg: " + result.content);
|
||||
|
||||
throw new NacosException(NacosException.SERVER_ERROR, "failed to req API:" + HttpClient.getPrefix() + curServer
|
||||
+ api + ". code:"
|
||||
+ result.code + " msg: " + result.content);
|
||||
throw new NacosException(NacosException.SERVER_ERROR,
|
||||
"failed to req API:" + HttpClient.getPrefix() + curServer + api
|
||||
+ ". code:" + result.code + " msg: " + result.content);
|
||||
}
|
||||
|
||||
public String reqAPI(String api, Map<String, String> params, List<String> servers) {
|
||||
return reqAPI(api, params, servers, HttpMethod.GET);
|
||||
}
|
||||
|
||||
public String reqAPI(String api, Map<String, String> params, List<String> servers, String method) {
|
||||
public String reqAPI(String api, Map<String, String> params, List<String> servers,
|
||||
String method) {
|
||||
|
||||
params.put(Constants.REQUEST_PARAM_NAMESPACE_ID, getNamespaceId());
|
||||
checkTenant(params);
|
||||
|
||||
if (CollectionUtils.isEmpty(servers) && StringUtils.isEmpty(nacosDomain)) {
|
||||
throw new IllegalArgumentException("no server available");
|
||||
@ -357,24 +419,28 @@ public class NamingProxy {
|
||||
try {
|
||||
return callServer(api, params, server, method);
|
||||
} catch (Exception e) {
|
||||
LogUtils.LOG.error("NA", "req api:" + api + " failed, server(" + server, e);
|
||||
LogUtils.LOG.error("NA",
|
||||
"req api:" + api + " failed, server(" + server, e);
|
||||
}
|
||||
|
||||
index = (index + 1) % servers.size();
|
||||
}
|
||||
|
||||
throw new IllegalStateException("failed to req API:" + api + " after all servers(" + servers + ") tried");
|
||||
throw new IllegalStateException("failed to req API:" + api
|
||||
+ " after all servers(" + servers + ") tried");
|
||||
}
|
||||
|
||||
for (int i = 0; i < UtilAndComs.REQUEST_DOMAIN_RETRY_COUNT; i++) {
|
||||
try {
|
||||
return callServer(api, params, nacosDomain);
|
||||
} catch (Exception e) {
|
||||
LogUtils.LOG.error("NA", "req api:" + api + " failed, server(" + nacosDomain, e);
|
||||
LogUtils.LOG.error("NA",
|
||||
"req api:" + api + " failed, server(" + nacosDomain, e);
|
||||
}
|
||||
}
|
||||
|
||||
throw new IllegalStateException("failed to req API:/api/" + api + " after all servers(" + servers + ") tried");
|
||||
throw new IllegalStateException("failed to req API:/api/" + api
|
||||
+ " after all servers(" + servers + ") tried");
|
||||
|
||||
}
|
||||
|
||||
|
@ -20,6 +20,12 @@ package com.alibaba.nacos.client.naming.utils;
|
||||
*/
|
||||
public class UtilAndComs {
|
||||
|
||||
public static String WEB_CONTEXT = "/nacos";
|
||||
|
||||
public static String NACOS_URL_BASE = WEB_CONTEXT + "/v1/ns";
|
||||
|
||||
public static String NACOS_URL_INSTANCE = NACOS_URL_BASE + "/instance";
|
||||
|
||||
public static final String VERSION = "Nacos-Java-Client:v0.2.1";
|
||||
|
||||
public static final String ENCODING = "UTF-8";
|
||||
@ -30,10 +36,6 @@ public class UtilAndComs {
|
||||
|
||||
public static final String FAILOVER_SWITCH = "00-00---000-VIPSRV_FAILOVER_SWITCH-000---00-00";
|
||||
|
||||
public static final String NACOS_URL_BASE = "/nacos/v1/ns";
|
||||
|
||||
public static final String NACOS_URL_INSTANCE = NACOS_URL_BASE + "/instance";
|
||||
|
||||
public static final String DEFAULT_NAMESPACE_ID = "public";
|
||||
|
||||
public static final int REQUEST_DOMAIN_RETRY_COUNT = 3;
|
||||
@ -46,9 +48,11 @@ public class UtilAndComs {
|
||||
|
||||
public static final String SERVER_ADDR_IP_SPLITER = ":";
|
||||
|
||||
public static final int DEFAULT_CLIENT_BEAT_THREAD_COUNT = Runtime.getRuntime().availableProcessors() > 1 ?
|
||||
Runtime.getRuntime().availableProcessors() / 2 : 1;
|
||||
public static final int DEFAULT_CLIENT_BEAT_THREAD_COUNT = Runtime.getRuntime()
|
||||
.availableProcessors() > 1 ? Runtime.getRuntime().availableProcessors() / 2
|
||||
: 1;
|
||||
|
||||
public static final int DEFAULT_POLLING_THREAD_COUNT = Runtime.getRuntime().availableProcessors() > 1 ?
|
||||
Runtime.getRuntime().availableProcessors() / 2 : 1;
|
||||
public static final int DEFAULT_POLLING_THREAD_COUNT = Runtime.getRuntime()
|
||||
.availableProcessors() > 1 ? Runtime.getRuntime().availableProcessors() / 2
|
||||
: 1;
|
||||
}
|
||||
|
@ -18,7 +18,7 @@
|
||||
<parent>
|
||||
<artifactId>nacos-all</artifactId>
|
||||
<groupId>com.alibaba.nacos</groupId>
|
||||
<version>0.8.0</version>
|
||||
<version>0.8.1-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
@ -18,7 +18,7 @@
|
||||
<parent>
|
||||
<groupId>com.alibaba.nacos</groupId>
|
||||
<artifactId>nacos-all</artifactId>
|
||||
<version>0.8.0</version>
|
||||
<version>0.8.1-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
@ -17,7 +17,7 @@
|
||||
<parent>
|
||||
<groupId>com.alibaba.nacos</groupId>
|
||||
<artifactId>nacos-all</artifactId>
|
||||
<version>0.8.0</version>
|
||||
<version>0.8.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
@ -18,7 +18,7 @@
|
||||
<parent>
|
||||
<groupId>com.alibaba.nacos</groupId>
|
||||
<artifactId>nacos-all</artifactId>
|
||||
<version>0.8.0</version>
|
||||
<version>0.8.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
<artifactId>nacos-console</artifactId>
|
||||
<!--<packaging>war</packaging>-->
|
||||
|
@ -18,7 +18,7 @@
|
||||
<parent>
|
||||
<groupId>com.alibaba.nacos</groupId>
|
||||
<artifactId>nacos-all</artifactId>
|
||||
<version>0.8.0</version>
|
||||
<version>0.8.1-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
|
@ -18,7 +18,7 @@
|
||||
<parent>
|
||||
<groupId>com.alibaba.nacos</groupId>
|
||||
<artifactId>nacos-all</artifactId>
|
||||
<version>0.8.0</version>
|
||||
<version>0.8.1-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
|
@ -18,7 +18,7 @@
|
||||
<parent>
|
||||
<groupId>com.alibaba.nacos</groupId>
|
||||
<artifactId>nacos-all</artifactId>
|
||||
<version>0.8.0</version>
|
||||
<version>0.8.1-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
|
@ -18,7 +18,7 @@
|
||||
<parent>
|
||||
<groupId>com.alibaba.nacos</groupId>
|
||||
<artifactId>nacos-all</artifactId>
|
||||
<version>0.8.0</version>
|
||||
<version>0.8.1-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
|
3
pom.xml
3
pom.xml
@ -21,7 +21,7 @@
|
||||
<inceptionYear>2018</inceptionYear>
|
||||
<groupId>com.alibaba.nacos</groupId>
|
||||
<artifactId>nacos-all</artifactId>
|
||||
<version>0.8.0</version>
|
||||
<version>0.8.1-SNAPSHOT</version>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<name>Alibaba NACOS ${project.version}</name>
|
||||
@ -742,5 +742,6 @@
|
||||
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
</project>
|
||||
|
||||
|
@ -17,7 +17,7 @@
|
||||
<parent>
|
||||
<groupId>com.alibaba.nacos</groupId>
|
||||
<artifactId>nacos-all</artifactId>
|
||||
<version>0.8.0</version>
|
||||
<version>0.8.1-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
Loading…
Reference in New Issue
Block a user