From 1a6fa9e69cfbf35769d793f187aed124736bb97a Mon Sep 17 00:00:00 2001 From: pbting <314226532@qq.com> Date: Wed, 13 Feb 2019 15:42:41 +0800 Subject: [PATCH 01/12] support ans --- .../alibaba/nacos/api/PropertyKeyConst.java | 24 +- .../nacos/client/identify/Constants.java | 28 +- .../client/identify/CredentialWatcher.java | 364 ++++----- .../nacos/client/identify/Credentials.java | 75 +- .../nacos/client/naming/CredentialsValue.java | 49 ++ .../client/naming/NacosNamingService.java | 495 +++++++------ .../alibaba/nacos/client/naming/SignUtil.java | 68 ++ .../nacos/client/naming/net/HttpClient.java | 276 +++---- .../nacos/client/naming/net/NamingProxy.java | 690 ++++++++++-------- .../client/naming/utils/UtilAndComs.java | 38 +- 10 files changed, 1203 insertions(+), 904 deletions(-) create mode 100644 client/src/main/java/com/alibaba/nacos/client/naming/CredentialsValue.java create mode 100644 client/src/main/java/com/alibaba/nacos/client/naming/SignUtil.java diff --git a/api/src/main/java/com/alibaba/nacos/api/PropertyKeyConst.java b/api/src/main/java/com/alibaba/nacos/api/PropertyKeyConst.java index a0095c04a..2922e66d0 100644 --- a/api/src/main/java/com/alibaba/nacos/api/PropertyKeyConst.java +++ b/api/src/main/java/com/alibaba/nacos/api/PropertyKeyConst.java @@ -22,24 +22,26 @@ package com.alibaba.nacos.api; */ public class PropertyKeyConst { - public final static String ENDPOINT = "endpoint"; + public final static String WEB_CONTEXT = "webContext"; - public final static String NAMESPACE = "namespace"; + public final static String ENDPOINT = "endpoint"; - public final static String ACCESS_KEY = "accessKey"; + public final static String NAMESPACE = "namespace"; - public final static String SECRET_KEY = "secretKey"; + public final static String ACCESS_KEY = "accessKey"; - public final static String SERVER_ADDR = "serverAddr"; + public final static String SECRET_KEY = "secretKey"; - public final static String CONTEXT_PATH = "contextPath"; + public final static String SERVER_ADDR = "serverAddr"; - public final static String CLUSTER_NAME = "clusterName"; + public final static String CONTEXT_PATH = "contextPath"; - public final static String ENCODE = "encode"; + public final static String CLUSTER_NAME = "clusterName"; - public final static String NAMING_LOAD_CACHE_AT_START = "namingLoadCacheAtStart"; - public final static String NAMING_CLIENT_BEAT_THREAD_COUNT = "namingClientBeatThreadCount"; - public final static String NAMING_POLLING_THREAD_COUNT = "namingPollingThreadCount"; + public final static String ENCODE = "encode"; + + public final static String NAMING_LOAD_CACHE_AT_START = "namingLoadCacheAtStart"; + public final static String NAMING_CLIENT_BEAT_THREAD_COUNT = "namingClientBeatThreadCount"; + public final static String NAMING_POLLING_THREAD_COUNT = "namingPollingThreadCount"; } diff --git a/client/src/main/java/com/alibaba/nacos/client/identify/Constants.java b/client/src/main/java/com/alibaba/nacos/client/identify/Constants.java index 339103f0c..6d87da6d6 100644 --- a/client/src/main/java/com/alibaba/nacos/client/identify/Constants.java +++ b/client/src/main/java/com/alibaba/nacos/client/identify/Constants.java @@ -21,26 +21,32 @@ package com.alibaba.nacos.client.identify; * @author Nacos */ public class Constants { - public static final String ACCESS_KEY = "accessKey"; + public static final String ACCESS_KEY = "accessKey"; - public static final String SECRET_KEY = "secretKey"; + public static final String SECRET_KEY = "secretKey"; - public static final String PROPERTIES_FILENAME = "spas.properties"; + public static final String TENANT_ID = "tenantId"; - public static final String CREDENTIAL_PATH = "/home/admin/.spas_key/"; + public static final String PROPERTIES_FILENAME = "spas.properties"; - public static final String CREDENTIAL_DEFAULT = "default"; + public static final String CREDENTIAL_PATH = "/home/admin/.spas_key/"; - public static final String DOCKER_CREDENTIAL_PATH = "/etc/instanceInfo"; + public static final String CREDENTIAL_DEFAULT = "default"; - public static final String DOCKER_ACCESS_KEY = "env_spas_accessKey"; + public static final String DOCKER_CREDENTIAL_PATH = "/etc/instanceInfo"; - public static final String DOCKER_SECRET_KEY = "env_spas_secretKey"; + public static final String DOCKER_ACCESS_KEY = "env_spas_accessKey"; - public static final String ENV_ACCESS_KEY = "spas_accessKey"; + public static final String DOCKER_SECRET_KEY = "env_spas_secretKey"; - public static final String ENV_SECRET_KEY = "spas_secretKey"; + public static final String DOCKER_TENANT_ID = "ebv_spas_tenantId"; - public static final String NO_APP_NAME = ""; + 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 = ""; } diff --git a/client/src/main/java/com/alibaba/nacos/client/identify/CredentialWatcher.java b/client/src/main/java/com/alibaba/nacos/client/identify/CredentialWatcher.java index 4da1f9886..9b6cc10fe 100644 --- a/client/src/main/java/com/alibaba/nacos/client/identify/CredentialWatcher.java +++ b/client/src/main/java/com/alibaba/nacos/client/identify/CredentialWatcher.java @@ -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); + } } diff --git a/client/src/main/java/com/alibaba/nacos/client/identify/Credentials.java b/client/src/main/java/com/alibaba/nacos/client/identify/Credentials.java index a271561da..76a9be249 100644 --- a/client/src/main/java/com/alibaba/nacos/client/identify/Credentials.java +++ b/client/src/main/java/com/alibaba/nacos/client/identify/Credentials.java @@ -22,45 +22,56 @@ package com.alibaba.nacos.client.identify; */ public class Credentials implements SpasCredential { - private volatile String accessKey; + private volatile String accessKey; - private volatile String secretKey; + private volatile String secretKey; - public Credentials(String accessKey, String secretKey) { - this.accessKey = accessKey; - this.secretKey = secretKey; - } + private volatile String tenantId; - public Credentials() { - this(null, null); - } + public Credentials(String accessKey, String secretKey, String tenantId) { + this.accessKey = accessKey; + this.secretKey = secretKey; + this.tenantId = tenantId; + } - public String getAccessKey() { - return accessKey; - } + public Credentials() { + this(null, null, null); + } - public void setAccessKey(String accessKey) { - this.accessKey = accessKey; - } + public String getAccessKey() { + return accessKey; + } - public String getSecretKey() { - return secretKey; - } + public void setAccessKey(String accessKey) { + this.accessKey = accessKey; + } - public void setSecretKey(String secretKey) { - this.secretKey = secretKey; - } + public String getSecretKey() { + return secretKey; + } - public boolean valid() { - return accessKey != null && !accessKey.isEmpty() && secretKey != null && !secretKey.isEmpty(); - } + public void setSecretKey(String secretKey) { + this.secretKey = secretKey; + } - 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))); - } + 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(); + } + + 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))); + } } diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/CredentialsValue.java b/client/src/main/java/com/alibaba/nacos/client/naming/CredentialsValue.java new file mode 100644 index 000000000..6abacf7e9 --- /dev/null +++ b/client/src/main/java/com/alibaba/nacos/client/naming/CredentialsValue.java @@ -0,0 +1,49 @@ +/* + * 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; + +/** + * @author pbting + * @date 2019-01-22 10:21 PM + */ +public class CredentialsValue { + private volatile String accessKey; + private volatile String secretKey; + + public CredentialsValue() { + } + + public CredentialsValue(String accessKey, String secretKey) { + this.accessKey = accessKey; + this.secretKey = secretKey; + } + + public String getAccessKey() { + return this.accessKey; + } + + public void setAccessKey(String accessKey) { + this.accessKey = accessKey; + } + + public String getSecretKey() { + return this.secretKey; + } + + public void setSecretKey(String secretKey) { + this.secretKey = secretKey; + } +} diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/NacosNamingService.java b/client/src/main/java/com/alibaba/nacos/client/naming/NacosNamingService.java index 74e73007d..6a9b583d7 100644 --- a/client/src/main/java/com/alibaba/nacos/client/naming/NacosNamingService.java +++ b/client/src/main/java/com/alibaba/nacos/client/naming/NacosNamingService.java @@ -48,293 +48,338 @@ import java.util.Properties; @SuppressWarnings("PMD.ServiceOrDaoClassShouldEndWithImplRule") public class NacosNamingService implements NamingService { - /** - * Each Naming instance should have different namespace. - */ - private String namespace; + /** + * Each Naming instance should have different namespace. + */ + private String namespace; - private String endpoint; + private String endpoint; - private String serverList; + private String serverList; - private String cacheDir; + private String cacheDir; - private String logName; + private String logName; - private HostReactor hostReactor; + private HostReactor hostReactor; - private BeatReactor beatReactor; + private BeatReactor beatReactor; - private EventDispatcher eventDispatcher; + private EventDispatcher eventDispatcher; - private NamingProxy serverProxy; + private NamingProxy serverProxy; - private void init() { + private void init() { - namespace = System.getProperty(PropertyKeyConst.NAMESPACE); + namespace = System.getProperty(PropertyKeyConst.NAMESPACE); - if (StringUtils.isEmpty(namespace)) { - namespace = UtilAndComs.DEFAULT_NAMESPACE_ID; - } + if (StringUtils.isEmpty(namespace)) { + namespace = UtilAndComs.DEFAULT_NAMESPACE_ID; + } - logName = System.getProperty(UtilAndComs.NACOS_NAMING_LOG_NAME); - if (StringUtils.isEmpty(logName)) { - logName = "naming.log"; - } + logName = System.getProperty(UtilAndComs.NACOS_NAMING_LOG_NAME); + if (StringUtils.isEmpty(logName)) { + logName = "naming.log"; + } - String logLevel = System.getProperty(UtilAndComs.NACOS_NAMING_LOG_LEVEL); - if (StringUtils.isEmpty(logLevel)) { - logLevel = "INFO"; - } + String logLevel = System.getProperty(UtilAndComs.NACOS_NAMING_LOG_LEVEL); + if (StringUtils.isEmpty(logLevel)) { + logLevel = "INFO"; + } - LogUtils.setLogLevel(logLevel); + LogUtils.setLogLevel(logLevel); - cacheDir = System.getProperty("com.alibaba.nacos.naming.cache.dir"); - if (StringUtils.isEmpty(cacheDir)) { - cacheDir = System.getProperty("user.home") + "/nacos/naming/" + namespace; - } - } + cacheDir = System.getProperty("com.alibaba.nacos.naming.cache.dir"); + if (StringUtils.isEmpty(cacheDir)) { + cacheDir = System.getProperty("user.home") + "/nacos/naming/" + namespace; + } + } - public NacosNamingService(String serverList) { + public NacosNamingService(String serverList) { - this.serverList = serverList; - init(); - eventDispatcher = new EventDispatcher(); - serverProxy = new NamingProxy(namespace, endpoint, serverList); - beatReactor = new BeatReactor(serverProxy); - hostReactor = new HostReactor(eventDispatcher, serverProxy, cacheDir); - } + this.serverList = serverList; + init(); + eventDispatcher = new EventDispatcher(); + serverProxy = new NamingProxy(namespace, endpoint, serverList); + beatReactor = new BeatReactor(serverProxy); + hostReactor = new HostReactor(eventDispatcher, serverProxy, cacheDir); + } - public NacosNamingService(Properties properties) { + public NacosNamingService(Properties properties) { - init(); + init(); - serverList = properties.getProperty(PropertyKeyConst.SERVER_ADDR); + serverList = properties.getProperty(PropertyKeyConst.SERVER_ADDR); - if (StringUtils.isNotEmpty(properties.getProperty(PropertyKeyConst.NAMESPACE))) { - namespace = properties.getProperty(PropertyKeyConst.NAMESPACE); - } + if (StringUtils.isNotEmpty(properties.getProperty(PropertyKeyConst.NAMESPACE))) { + namespace = properties.getProperty(PropertyKeyConst.NAMESPACE); + } - if (StringUtils.isNotEmpty(properties.getProperty(UtilAndComs.NACOS_NAMING_LOG_NAME))) { - logName = 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"); - } + if (StringUtils.isNotEmpty(properties.getProperty(PropertyKeyConst.ENDPOINT))) { + endpoint = properties.getProperty(PropertyKeyConst.ENDPOINT) + ":" + + properties.getProperty("address.server.port", "8080"); + } - cacheDir = System.getProperty("user.home") + "/nacos/naming/" + namespace; + if (StringUtils + .isNotEmpty(properties.getProperty(PropertyKeyConst.WEB_CONTEXT))) { + String tmpWebContext = properties.getProperty(PropertyKeyConst.WEB_CONTEXT); + UtilAndComs.WEB_CONTEXT = tmpWebContext.indexOf("/") > -1 ? tmpWebContext + : "/" + tmpWebContext; - boolean loadCacheAtStart = false; - if (StringUtils.isNotEmpty(properties.getProperty(PropertyKeyConst.NAMING_LOAD_CACHE_AT_START))) { - loadCacheAtStart = BooleanUtils.toBoolean( - properties.getProperty(PropertyKeyConst.NAMING_LOAD_CACHE_AT_START)); - } + UtilAndComs.NACOS_URL_BASE = UtilAndComs.WEB_CONTEXT + "/v1/ns"; + UtilAndComs.NACOS_URL_INSTANCE = UtilAndComs.NACOS_URL_BASE + "/instance"; + } - int clientBeatThreadCount = NumberUtils.toInt(properties.getProperty(PropertyKeyConst.NAMING_CLIENT_BEAT_THREAD_COUNT), - UtilAndComs.DEFAULT_CLIENT_BEAT_THREAD_COUNT); + cacheDir = System.getProperty("user.home") + "/nacos/naming/" + namespace; - int pollingThreadCount = NumberUtils.toInt(properties.getProperty(PropertyKeyConst.NAMING_POLLING_THREAD_COUNT), - UtilAndComs.DEFAULT_POLLING_THREAD_COUNT); + boolean loadCacheAtStart = false; + if (StringUtils.isNotEmpty( + properties.getProperty(PropertyKeyConst.NAMING_LOAD_CACHE_AT_START))) { + loadCacheAtStart = BooleanUtils.toBoolean( + properties.getProperty(PropertyKeyConst.NAMING_LOAD_CACHE_AT_START)); + } - eventDispatcher = new EventDispatcher(); - serverProxy = new NamingProxy(namespace, endpoint, serverList); - beatReactor = new BeatReactor(serverProxy, clientBeatThreadCount); - hostReactor = new HostReactor(eventDispatcher, serverProxy, cacheDir, loadCacheAtStart, pollingThreadCount); + 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), + UtilAndComs.DEFAULT_POLLING_THREAD_COUNT); - @Override - public void registerInstance(String serviceName, String ip, int port) throws NacosException { - registerInstance(serviceName, ip, port, Constants.NAMING_DEFAULT_CLUSTER_NAME); - } + eventDispatcher = new EventDispatcher(); + serverProxy = new NamingProxy(namespace, endpoint, serverList); + beatReactor = new BeatReactor(serverProxy, clientBeatThreadCount); + hostReactor = new HostReactor(eventDispatcher, serverProxy, cacheDir, + loadCacheAtStart, pollingThreadCount); - @Override - public void registerInstance(String serviceName, String ip, int port, String clusterName) throws NacosException { - Instance instance = new Instance(); - instance.setIp(ip); - instance.setPort(port); - instance.setWeight(1.0); - instance.setClusterName(clusterName); + } - registerInstance(serviceName, instance); - } + @Override + 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, Instance instance) throws NacosException { + @Override + public void registerInstance(String serviceName, String ip, int port, + String clusterName) throws NacosException { + Instance instance = new Instance(); + instance.setIp(ip); + instance.setPort(port); + instance.setWeight(1.0); + instance.setClusterName(clusterName); - BeatInfo beatInfo = new BeatInfo(); - beatInfo.setServiceName(serviceName); - beatInfo.setIp(instance.getIp()); - beatInfo.setPort(instance.getPort()); - beatInfo.setCluster(instance.getClusterName()); - beatInfo.setWeight(instance.getWeight()); - beatInfo.setMetadata(instance.getMetadata()); - beatInfo.setScheduled(false); + registerInstance(serviceName, instance); + } - beatReactor.addBeatInfo(serviceName, beatInfo); + @Override + public void registerInstance(String serviceName, Instance instance) + throws NacosException { - serverProxy.registerService(serviceName, instance); - } + BeatInfo beatInfo = new BeatInfo(); + beatInfo.setServiceName(serviceName); + beatInfo.setIp(instance.getIp()); + beatInfo.setPort(instance.getPort()); + beatInfo.setCluster(instance.getClusterName()); + beatInfo.setWeight(instance.getWeight()); + beatInfo.setMetadata(instance.getMetadata()); + beatInfo.setScheduled(false); - @Override - public void deregisterInstance(String serviceName, String ip, int port) throws NacosException { - deregisterInstance(serviceName, ip, port, Constants.NAMING_DEFAULT_CLUSTER_NAME); - } + beatReactor.addBeatInfo(serviceName, beatInfo); - @Override - public void deregisterInstance(String serviceName, String ip, int port, String clusterName) throws NacosException { - beatReactor.removeBeatInfo(serviceName, ip, port); - serverProxy.deregisterService(serviceName, ip, port, clusterName); - } + serverProxy.registerService(serviceName, instance); + } - @Override - public List getAllInstances(String serviceName) throws NacosException { - return getAllInstances(serviceName, new ArrayList()); - } + @Override + public void deregisterInstance(String serviceName, String ip, int port) + throws NacosException { + deregisterInstance(serviceName, ip, port, Constants.NAMING_DEFAULT_CLUSTER_NAME); + } - @Override - public List getAllInstances(String serviceName, boolean subscribe) throws NacosException { - return getAllInstances(serviceName, new ArrayList(), subscribe); - } + @Override + public void deregisterInstance(String serviceName, String ip, int port, + String clusterName) throws NacosException { + beatReactor.removeBeatInfo(serviceName, ip, port); + serverProxy.deregisterService(serviceName, ip, port, clusterName); + } - @Override - public List getAllInstances(String serviceName, List clusters) throws NacosException { - return getAllInstances(serviceName, clusters, true); - } + @Override + public List getAllInstances(String serviceName) throws NacosException { + return getAllInstances(serviceName, new ArrayList()); + } - @Override - public List getAllInstances(String serviceName, List clusters, boolean subscribe) throws NacosException { + @Override + public List getAllInstances(String serviceName, boolean subscribe) + throws NacosException { + return getAllInstances(serviceName, new ArrayList(), subscribe); + } - ServiceInfo serviceInfo; - if (subscribe) { - serviceInfo = hostReactor.getServiceInfo(serviceName, StringUtils.join(clusters, ",")); - } else { - serviceInfo = hostReactor.getServiceInfoDirectlyFromServer(serviceName, StringUtils.join(clusters, ",")); - } - List list; - if (serviceInfo == null || CollectionUtils.isEmpty(list = serviceInfo.getHosts())) { - return new ArrayList(); - } - return list; - } + @Override + public List getAllInstances(String serviceName, List clusters) + throws NacosException { + return getAllInstances(serviceName, clusters, true); + } - @Override - public List selectInstances(String serviceName, boolean healthy) throws NacosException { - return selectInstances(serviceName, new ArrayList(), healthy); - } + @Override + public List getAllInstances(String serviceName, List clusters, + boolean subscribe) throws NacosException { - @Override - public List selectInstances(String serviceName, boolean healthy, boolean subscribe) throws NacosException { - return selectInstances(serviceName, new ArrayList(), healthy, subscribe); - } + ServiceInfo serviceInfo; + if (subscribe) { + serviceInfo = hostReactor.getServiceInfo(serviceName, + StringUtils.join(clusters, ",")); + } + else { + serviceInfo = hostReactor.getServiceInfoDirectlyFromServer(serviceName, + StringUtils.join(clusters, ",")); + } + List list; + if (serviceInfo == null + || CollectionUtils.isEmpty(list = serviceInfo.getHosts())) { + return new ArrayList(); + } + return list; + } - @Override - public List selectInstances(String serviceName, List clusters, boolean healthy) - throws NacosException { - return selectInstances(serviceName, clusters, healthy, true); - } + @Override + public List selectInstances(String serviceName, boolean healthy) + throws NacosException { + return selectInstances(serviceName, new ArrayList(), healthy); + } - @Override - public List selectInstances(String serviceName, List clusters, boolean healthy, - boolean subscribe) throws NacosException { - ServiceInfo serviceInfo; - if (subscribe) { - serviceInfo = hostReactor.getServiceInfo(serviceName, StringUtils.join(clusters, ",")); - } else { - serviceInfo = hostReactor.getServiceInfoDirectlyFromServer(serviceName, StringUtils.join(clusters, ",")); - } - return selectInstances(serviceInfo, healthy); - } + @Override + public List selectInstances(String serviceName, boolean healthy, + boolean subscribe) throws NacosException { + return selectInstances(serviceName, new ArrayList(), healthy, subscribe); + } - @Override - public Instance selectOneHealthyInstance(String serviceName) throws NacosException { - return selectOneHealthyInstance(serviceName, new ArrayList()); - } + @Override + public List selectInstances(String serviceName, List clusters, + boolean healthy) throws NacosException { + return selectInstances(serviceName, clusters, healthy, true); + } - @Override - public Instance selectOneHealthyInstance(String serviceName, boolean subscribe) throws NacosException { - return selectOneHealthyInstance(serviceName, new ArrayList(), subscribe); - } + @Override + public List selectInstances(String serviceName, List clusters, + boolean healthy, boolean subscribe) throws NacosException { + ServiceInfo serviceInfo; + if (subscribe) { + serviceInfo = hostReactor.getServiceInfo(serviceName, + StringUtils.join(clusters, ",")); + } + else { + serviceInfo = hostReactor.getServiceInfoDirectlyFromServer(serviceName, + StringUtils.join(clusters, ",")); + } + return selectInstances(serviceInfo, healthy); + } - @Override - public Instance selectOneHealthyInstance(String serviceName, List clusters) throws NacosException { - return selectOneHealthyInstance(serviceName, clusters, true); - } + @Override + public Instance selectOneHealthyInstance(String serviceName) throws NacosException { + return selectOneHealthyInstance(serviceName, new ArrayList()); + } - @Override - public Instance selectOneHealthyInstance(String serviceName, List clusters, boolean subscribe) throws NacosException { + @Override + public Instance selectOneHealthyInstance(String serviceName, boolean subscribe) + throws NacosException { + return selectOneHealthyInstance(serviceName, new ArrayList(), subscribe); + } - if (subscribe) { - return Balancer.RandomByWeight.selectHost( - hostReactor.getServiceInfo(serviceName, StringUtils.join(clusters, ","))); - } else { - return Balancer.RandomByWeight.selectHost( - hostReactor.getServiceInfoDirectlyFromServer(serviceName, StringUtils.join(clusters, ","))); - } - } + @Override + public Instance selectOneHealthyInstance(String serviceName, List clusters) + throws NacosException { + return selectOneHealthyInstance(serviceName, clusters, true); + } - @Override - public void subscribe(String service, EventListener listener) { - eventDispatcher.addListener(hostReactor.getServiceInfo(service, StringUtils.EMPTY), StringUtils.EMPTY, - listener); - } + @Override + public Instance selectOneHealthyInstance(String serviceName, List clusters, + boolean subscribe) throws NacosException { - @Override - public void subscribe(String service, List clusters, EventListener listener) { - eventDispatcher.addListener(hostReactor.getServiceInfo(service, StringUtils.join(clusters, ",")), - StringUtils.join(clusters, ","), listener); - } + if (subscribe) { + return Balancer.RandomByWeight.selectHost(hostReactor + .getServiceInfo(serviceName, StringUtils.join(clusters, ","))); + } + else { + return Balancer.RandomByWeight + .selectHost(hostReactor.getServiceInfoDirectlyFromServer(serviceName, + StringUtils.join(clusters, ","))); + } + } - @Override - public void unsubscribe(String service, EventListener listener) { - eventDispatcher.removeListener(service, StringUtils.EMPTY, listener); - } + @Override + public void subscribe(String service, EventListener listener) { + eventDispatcher.addListener( + hostReactor.getServiceInfo(service, StringUtils.EMPTY), StringUtils.EMPTY, + listener); + } - @Override - public void unsubscribe(String service, List clusters, EventListener listener) { - eventDispatcher.removeListener(service, StringUtils.join(clusters, ","), listener); - } + @Override + public void subscribe(String service, List clusters, EventListener listener) { + eventDispatcher.addListener( + hostReactor.getServiceInfo(service, StringUtils.join(clusters, ",")), + StringUtils.join(clusters, ","), listener); + } - @Override - public ListView getServicesOfServer(int pageNo, int pageSize) throws NacosException { - return serverProxy.getServiceList(pageNo, pageSize); - } + @Override + public void unsubscribe(String service, EventListener listener) { + eventDispatcher.removeListener(service, StringUtils.EMPTY, listener); + } - @Override - public ListView getServicesOfServer(int pageNo, int pageSize, AbstractSelector selector) throws NacosException { - return serverProxy.getServiceList(pageNo, pageSize, selector); - } + @Override + public void unsubscribe(String service, List clusters, + EventListener listener) { + eventDispatcher.removeListener(service, StringUtils.join(clusters, ","), + listener); + } - @Override - public List getSubscribeServices() { - return eventDispatcher.getSubscribeServices(); - } + @Override + public ListView getServicesOfServer(int pageNo, int pageSize) + throws NacosException { + return serverProxy.getServiceList(pageNo, pageSize); + } - @Override - public String getServerStatus() { - return serverProxy.serverHealthy() ? "UP" : "DOWN"; - } + @Override + public ListView getServicesOfServer(int pageNo, int pageSize, + AbstractSelector selector) throws NacosException { + return serverProxy.getServiceList(pageNo, pageSize, selector); + } - private List selectInstances(ServiceInfo serviceInfo, boolean healthy) { - List list; - if (serviceInfo == null || CollectionUtils.isEmpty(list = serviceInfo.getHosts())) { - return new ArrayList(); - } + @Override + public List getSubscribeServices() { + return eventDispatcher.getSubscribeServices(); + } - Iterator iterator = list.iterator(); - while (iterator.hasNext()) { - Instance instance = iterator.next(); - if (healthy != instance.isHealthy() || !instance.isEnabled() || instance.getWeight() <= 0) { - iterator.remove(); - } - } + @Override + public String getServerStatus() { + return serverProxy.serverHealthy() ? "UP" : "DOWN"; + } - return list; - } + private List selectInstances(ServiceInfo serviceInfo, boolean healthy) { + List list; + if (serviceInfo == null + || CollectionUtils.isEmpty(list = serviceInfo.getHosts())) { + return new ArrayList(); + } - public BeatReactor getBeatReactor() { - return beatReactor; - } + Iterator iterator = list.iterator(); + while (iterator.hasNext()) { + Instance instance = iterator.next(); + if (healthy != instance.isHealthy() || !instance.isEnabled() + || instance.getWeight() <= 0) { + iterator.remove(); + } + } + + return list; + } + + public BeatReactor getBeatReactor() { + return beatReactor; + } } diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/SignUtil.java b/client/src/main/java/com/alibaba/nacos/client/naming/SignUtil.java new file mode 100644 index 000000000..a44b4c433 --- /dev/null +++ b/client/src/main/java/com/alibaba/nacos/client/naming/SignUtil.java @@ -0,0 +1,68 @@ +/* + * 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() { + } + } +} diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/net/HttpClient.java b/client/src/main/java/com/alibaba/nacos/client/naming/net/HttpClient.java index fad93fe3d..70d75cf2e 100644 --- a/client/src/main/java/com/alibaba/nacos/client/naming/net/HttpClient.java +++ b/client/src/main/java/com/alibaba/nacos/client/naming/net/HttpClient.java @@ -35,159 +35,187 @@ 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"); - static { - // limit max redirection - System.setProperty("http.maxRedirects", "5"); - } + private static final String POST = "POST"; + private static final String PUT = "PUT"; - public static String getPrefix() { - if (ENABLE_HTTPS) { - return "https://"; - } + static { + // limit max redirection + System.setProperty("http.maxRedirects", "5"); + } - return "http://"; + public static String getPrefix() { + if (ENABLE_HTTPS) { + return "https://"; + } - } + return "http://"; - public static HttpResult httpGet(String url, List headers, Map paramValues, String encoding) { - return request(url, headers, paramValues, encoding, "GET"); - } + } - public static HttpResult request(String url, List headers, Map paramValues, String encoding, String method) { - HttpURLConnection conn = null; - try { - String encodedContent = encodingParams(paramValues, encoding); - url += (null == encodedContent) ? "" : ("?" + encodedContent); + public static HttpResult httpGet(String url, List headers, + Map paramValues, String encoding) { + return request(url, headers, paramValues, encoding, "GET"); + } - conn = (HttpURLConnection) new URL(url).openConnection(); + public static HttpResult request(String url, List headers, + Map paramValues, String encoding, String method) { + HttpURLConnection conn = null; + try { + String encodedContent = encodingParams(paramValues, encoding); + url += (null == encodedContent) ? "" : ("?" + encodedContent); - conn.setConnectTimeout(CON_TIME_OUT_MILLIS); - conn.setReadTimeout(TIME_OUT_MILLIS); - conn.setRequestMethod(method); - setHeaders(conn, headers, encoding); - 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()); - } - } catch (Exception e1) { - LogUtils.LOG.error("NA", "failed to request ", e1); - //ignore - } + conn = (HttpURLConnection) new URL(url).openConnection(); - LogUtils.LOG.error("NA", "failed to request ", e); + setHeaders(conn, headers, encoding); + conn.setConnectTimeout(CON_TIME_OUT_MILLIS); + conn.setReadTimeout(TIME_OUT_MILLIS); + conn.setRequestMethod(method); + 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()); + } + } + catch (Exception e1) { + LogUtils.LOG.error("NA", "failed to request ", e1); + // ignore + } - return new HttpResult(500, e.toString(), Collections.emptyMap()); - } finally { - if (conn != null) { - conn.disconnect(); - } - } - } + LogUtils.LOG.error("NA", "failed to request ", e); - private static HttpResult getResult(HttpURLConnection conn) throws IOException { - int respCode = conn.getResponseCode(); + return new HttpResult(500, e.toString(), + Collections.emptyMap()); + } + finally { + if (conn != null) { + conn.disconnect(); + } + } + } - InputStream inputStream; - if (HttpURLConnection.HTTP_OK == respCode - || HttpURLConnection.HTTP_NOT_MODIFIED == respCode) { - inputStream = conn.getInputStream(); - } else { - inputStream = conn.getErrorStream(); - } + private static HttpResult getResult(HttpURLConnection conn) throws IOException { + int respCode = conn.getResponseCode(); - Map respHeaders = new HashMap(conn.getHeaderFields().size()); - for (Map.Entry> entry : conn.getHeaderFields().entrySet()) { - respHeaders.put(entry.getKey(), entry.getValue().get(0)); - } + InputStream inputStream; + if (HttpURLConnection.HTTP_OK == respCode + || HttpURLConnection.HTTP_NOT_MODIFIED == respCode) { + inputStream = conn.getInputStream(); + } + else { + inputStream = conn.getErrorStream(); + } - String encodingGzip = "gzip"; + Map respHeaders = new HashMap( + conn.getHeaderFields().size()); + for (Map.Entry> entry : conn.getHeaderFields().entrySet()) { + respHeaders.put(entry.getKey(), entry.getValue().get(0)); + } - if (encodingGzip.equals(respHeaders.get(HttpHeaders.CONTENT_ENCODING))) { - inputStream = new GZIPInputStream(inputStream); - } + String encodingGzip = "gzip"; - return new HttpResult(respCode, IoUtils.toString(inputStream, getCharset(conn)), respHeaders); - } + if (encodingGzip.equals(respHeaders.get(HttpHeaders.CONTENT_ENCODING))) { + inputStream = new GZIPInputStream(inputStream); + } - private static String getCharset(HttpURLConnection conn) { - String contentType = conn.getContentType(); - if (StringUtils.isEmpty(contentType)) { - return "UTF-8"; - } + return new HttpResult(respCode, IoUtils.toString(inputStream, getCharset(conn)), + respHeaders); + } - String[] values = contentType.split(";"); - if (values.length == 0) { - return "UTF-8"; - } + private static String getCharset(HttpURLConnection conn) { + String contentType = conn.getContentType(); + if (StringUtils.isEmpty(contentType)) { + return "UTF-8"; + } - String charset = "UTF-8"; - for (String value : values) { - value = value.trim(); + String[] values = contentType.split(";"); + if (values.length == 0) { + return "UTF-8"; + } - if (value.toLowerCase().startsWith("charset=")) { - charset = value.substring("charset=".length()); - } - } + String charset = "UTF-8"; + for (String value : values) { + value = value.trim(); - return charset; - } + if (value.toLowerCase().startsWith("charset=")) { + charset = value.substring("charset=".length()); + } + } - private static void setHeaders(HttpURLConnection conn, List headers, String encoding) { - if (null != headers) { - for (Iterator iter = headers.iterator(); iter.hasNext(); ) { - conn.addRequestProperty(iter.next(), iter.next()); - } - } + return charset; + } - conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" - + encoding); - conn.addRequestProperty("Accept-Charset", encoding); - } + private static void setHeaders(HttpURLConnection conn, List headers, + String encoding) { + if (null != headers) { + for (Iterator iter = headers.iterator(); iter.hasNext();) { + conn.addRequestProperty(iter.next(), iter.next()); + } + } - private static String encodingParams(Map params, String encoding) - throws UnsupportedEncodingException { - StringBuilder sb = new StringBuilder(); - if (null == params || params.isEmpty()) { - return null; - } + conn.addRequestProperty("Content-Type", + "application/x-www-form-urlencoded;charset=" + encoding); + conn.addRequestProperty("Accept-Charset", encoding); + } - params.put("encoding", encoding); + private static String encodingParams(Map params, String encoding) + throws UnsupportedEncodingException { + if (null == params) { + return null; + } + params.put("encoding", encoding); + StringBuilder sb = new StringBuilder(); - for (Map.Entry entry : params.entrySet()) { - if (StringUtils.isEmpty(entry.getValue())) { - continue; - } + for (Map.Entry entry : params.entrySet()) { + if (StringUtils.isEmpty(entry.getValue())) { + continue; + } - sb.append(entry.getKey()).append("="); - sb.append(URLEncoder.encode(entry.getValue(), encoding)); - sb.append("&"); - } + sb.append(entry.getKey()).append("="); + sb.append(URLEncoder.encode(entry.getValue(), encoding)); + sb.append("&"); + } - return sb.toString(); - } + if (sb.length() > 0) { + sb = sb.deleteCharAt(sb.length() - 1); + } + return sb.toString(); + } - public static class HttpResult { - final public int code; - final public String content; - final private Map respHeaders; + public static class HttpResult { + final public int code; + final public String content; + final private Map respHeaders; - public HttpResult(int code, String content, Map respHeaders) { - this.code = code; - this.content = content; - this.respHeaders = respHeaders; - } + public HttpResult(int code, String content, Map respHeaders) { + this.code = code; + this.content = content; + this.respHeaders = respHeaders; + } - public String getHeader(String name) { - return respHeaders.get(name); - } - } + public String getHeader(String name) { + return respHeaders.get(name); + } + } } diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/net/NamingProxy.java b/client/src/main/java/com/alibaba/nacos/client/naming/net/NamingProxy.java index 95ad44643..6c09c0f53 100644 --- a/client/src/main/java/com/alibaba/nacos/client/naming/net/NamingProxy.java +++ b/client/src/main/java/com/alibaba/nacos/client/naming/net/NamingProxy.java @@ -25,7 +25,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; @@ -45,340 +47,398 @@ import java.util.concurrent.TimeUnit; */ public class NamingProxy { - private static final int DEFAULT_SERVER_PORT = 8848; + private static final int DEFAULT_SERVER_PORT = 8848; - private String namespaceId; + private String namespaceId; - private String endpoint; + private String endpoint; - private String nacosDomain; + private String nacosDomain; - private List serverList; + private List serverList; - private List serversFromEndpoint = new ArrayList(); + private List serversFromEndpoint = new ArrayList(); - private long lastSrvRefTime = 0L; + private long lastSrvRefTime = 0L; - private long vipSrvRefInterMillis = TimeUnit.SECONDS.toMillis(30); + private long vipSrvRefInterMillis = TimeUnit.SECONDS.toMillis(30); - private ScheduledExecutorService executorService; + private CredentialService credentialService = CredentialService.getInstance(); - public NamingProxy(String namespaceId, String endpoint, String serverList) { + private ScheduledExecutorService executorService; - this.namespaceId = namespaceId; - this.endpoint = endpoint; - if (StringUtils.isNotEmpty(serverList)) { - this.serverList = Arrays.asList(serverList.split(",")); - if (this.serverList.size() == 1) { - this.nacosDomain = serverList; - } - } + public NamingProxy(String namespaceId, String endpoint, String serverList) { - executorService = new ScheduledThreadPoolExecutor(1, new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - Thread t = new Thread(r); - t.setName("com.alibaba.nacos.client.naming.serverlist.updater"); - t.setDaemon(true); - return t; - } - }); + this.namespaceId = namespaceId; + this.endpoint = endpoint; + if (StringUtils.isNotEmpty(serverList)) { + this.serverList = Arrays.asList(serverList.split(",")); + if (this.serverList.size() == 1) { + this.nacosDomain = serverList; + } + } - executorService.scheduleWithFixedDelay(new Runnable() { - @Override - public void run() { - refreshSrvIfNeed(); - } - }, 0, vipSrvRefInterMillis, TimeUnit.MILLISECONDS); + executorService = new ScheduledThreadPoolExecutor(1, new ThreadFactory() { + @Override + public Thread newThread(Runnable r) { + Thread t = new Thread(r); + t.setName("com.alibaba.nacos.client.naming.serverlist.updater"); + t.setDaemon(true); + return t; + } + }); - refreshSrvIfNeed(); - } + executorService.scheduleWithFixedDelay(new Runnable() { + @Override + public void run() { + refreshSrvIfNeed(); + } + }, 0, vipSrvRefInterMillis, TimeUnit.MILLISECONDS); + + refreshSrvIfNeed(); + } + + public List getServerListFromEndpoint() { + + try { + String urlString = "http://" + endpoint + "/nacos/serverlist"; + + List headers = Arrays.asList("Client-Version", UtilAndComs.VERSION, + "Accept-Encoding", "gzip,deflate,sdch", "Connection", "Keep-Alive", + "RequestId", UuidUtils.generateUuid()); + + 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); + } + + String content = result.content; + List list = new ArrayList(); + for (String line : IoUtils.readLines(new StringReader(content))) { + if (!line.trim().isEmpty()) { + list.add(line.trim()); + } + } + + return list; + + } + catch (Exception e) { + e.printStackTrace(); + } + + return null; + } + + private void refreshSrvIfNeed() { + try { + + if (!CollectionUtils.isEmpty(serverList)) { + LogUtils.LOG.debug("server list provided by user: " + serverList); + return; + } + + if (System.currentTimeMillis() - lastSrvRefTime < vipSrvRefInterMillis) { + return; + } + + List list = getServerListFromEndpoint(); + + if (CollectionUtils.isEmpty(list)) { + throw new Exception("Can not acquire Nacos list"); + } + + if (!CollectionUtils.isEqualCollection(list, serversFromEndpoint)) { + LogUtils.LOG.info("SERVER-LIST", "server list is updated: " + list); + } + + serversFromEndpoint = list; + lastSrvRefTime = System.currentTimeMillis(); + } + catch (Throwable e) { + LogUtils.LOG.warn("failed to update server list", e); + } + } + + public void registerService(String serviceName, Instance instance) + throws NacosException { + + LogUtils.LOG.info("REGISTER-SERVICE", + "{} registering service {} with instance: {}", namespaceId, serviceName, + instance); + + final Map params = new HashMap(8); + params.put(Constants.REQUEST_PARAM_NAMESPACE_ID, namespaceId); + params.put("ip", instance.getIp()); + params.put("port", String.valueOf(instance.getPort())); + params.put("weight", String.valueOf(instance.getWeight())); + params.put("enable", String.valueOf(instance.isEnabled())); + params.put("healthy", String.valueOf(instance.isHealthy())); + params.put("metadata", JSON.toJSONString(instance.getMetadata())); + params.put("serviceName", serviceName); + params.put("clusterName", instance.getClusterName()); + + reqAPI(UtilAndComs.NACOS_URL_INSTANCE, params, HttpMethod.POST); + + } + + private void checkTenant(Map params) { + String tenantId = credentialService.getCredential().getTenantId(); + if (tenantId == null || tenantId.trim().length() == 0) { + return; + } + + 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 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 params = new HashMap(8); + params.put(Constants.REQUEST_PARAM_NAMESPACE_ID, namespaceId); + params.put("ip", ip); + params.put("port", String.valueOf(port)); + params.put("serviceName", serviceName); + params.put("cluster", cluster); + + reqAPI(UtilAndComs.NACOS_URL_INSTANCE, params, HttpMethod.DELETE); + } + + public String queryList(String serviceName, String clusters, int udpPort, + boolean healthyOnly) throws NacosException { + + final Map params = new HashMap(8); + params.put(Constants.REQUEST_PARAM_NAMESPACE_ID, namespaceId); + params.put("serviceName", serviceName); + params.put("clusters", clusters); + params.put("udpPort", String.valueOf(udpPort)); + params.put("clientIP", NetUtils.localIP()); + params.put("healthyOnly", String.valueOf(healthyOnly)); + + 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()); + Map params = new HashMap(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); + 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); + } + return 0L; + } + + public boolean serverHealthy() { + + try { + reqAPI(UtilAndComs.NACOS_URL_BASE + "/api/hello", + new HashMap(2)); + } + catch (Exception e) { + return false; + } + + return true; + } + + public ListView getServiceList(int pageNo, int pageSize) + throws NacosException { + return getServiceList(pageNo, pageSize, null); + } + + public ListView getServiceList(int pageNo, int pageSize, + AbstractSelector selector) throws NacosException { + + Map params = new HashMap(4); + params.put("pageNo", String.valueOf(pageNo)); + params.put("pageSize", String.valueOf(pageSize)); + params.put(Constants.REQUEST_PARAM_NAMESPACE_ID, namespaceId); + + if (selector != null) { + switch (SelectorType.valueOf(selector.getType())) { + case none: + break; + case label: + ExpressionSelector expressionSelector = (ExpressionSelector) selector; + params.put("selector", JSON.toJSONString(expressionSelector)); + break; + default: + break; + } + } + + String result = reqAPI(UtilAndComs.NACOS_URL_BASE + "/service/list", params); + + JSONObject json = JSON.parseObject(result); + ListView listView = new ListView(); + listView.setCount(json.getInteger("count")); + listView.setData(JSON.parseObject(json.getString("doms"), + new TypeReference>() { + })); + + return listView; + } + + public String reqAPI(String api, Map params) throws NacosException { + + List snapshot = serversFromEndpoint; + if (!CollectionUtils.isEmpty(serverList)) { + snapshot = serverList; + } + + return reqAPI(api, params, snapshot); + } + + public String reqAPI(String api, Map params, String method) + throws NacosException { + + List snapshot = serversFromEndpoint; + if (!CollectionUtils.isEmpty(serverList)) { + snapshot = serverList; + } + + return reqAPI(api, params, snapshot, method); + } + + public String callServer(String api, Map params, String curServer) + throws NacosException { + return callServer(api, params, curServer, HttpMethod.GET); + } + + public String callServer(String api, Map params, String curServer, + String method) throws NacosException { + long start = System.currentTimeMillis(); + long end = 0; + + List headers = Arrays.asList("Client-Version", UtilAndComs.VERSION, + "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; + } + + url = HttpClient.getPrefix() + curServer + api; + + HttpClient.HttpResult result = HttpClient.request(url, headers, params, + UtilAndComs.ENCODING, method); + end = System.currentTimeMillis(); + + MetricsMonitor.getNamingRequestMonitor(method, url, String.valueOf(result.code)) + .record(end - start, TimeUnit.MILLISECONDS); + + if (HttpURLConnection.HTTP_OK == result.code) { + return result.content; + } + + if (HttpURLConnection.HTTP_NOT_MODIFIED == result.code) { + return StringUtils.EMPTY; + } + + 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); + } + + public String reqAPI(String api, Map params, List servers) { + return reqAPI(api, params, servers, HttpMethod.GET); + } + + public String reqAPI(String api, Map params, List 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"); + } + + if (servers != null && !servers.isEmpty()) { - public List getServerListFromEndpoint() { + Random random = new Random(System.currentTimeMillis()); + int index = random.nextInt(servers.size()); - try { - String urlString = "http://" + endpoint + "/nacos/serverlist"; + for (int i = 0; i < servers.size(); i++) { + String server = servers.get(index); + try { + return callServer(api, params, server, method); + } + catch (Exception e) { + LogUtils.LOG.error("NA", + "req api:" + api + " failed, server(" + server, e); + } - List headers = Arrays.asList("Client-Version", UtilAndComs.VERSION, - "Accept-Encoding", "gzip,deflate,sdch", - "Connection", "Keep-Alive", - "RequestId", UuidUtils.generateUuid()); + index = (index + 1) % servers.size(); + } - 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 IllegalStateException("failed to req API:" + api + + " after all servers(" + servers + ") tried"); + } - String content = result.content; - List list = new ArrayList(); - for (String line : IoUtils.readLines(new StringReader(content))) { - if (!line.trim().isEmpty()) { - list.add(line.trim()); - } - } - - return list; - - } catch (Exception e) { - e.printStackTrace(); - } - - return null; - } - - private void refreshSrvIfNeed() { - try { - - if (!CollectionUtils.isEmpty(serverList)) { - LogUtils.LOG.debug("server list provided by user: " + serverList); - return; - } - - if (System.currentTimeMillis() - lastSrvRefTime < vipSrvRefInterMillis) { - return; - } - - List list = getServerListFromEndpoint(); - - if (CollectionUtils.isEmpty(list)) { - throw new Exception("Can not acquire Nacos list"); - } - - if (!CollectionUtils.isEqualCollection(list, serversFromEndpoint)) { - LogUtils.LOG.info("SERVER-LIST", "server list is updated: " + list); - } - - serversFromEndpoint = list; - lastSrvRefTime = System.currentTimeMillis(); - } catch (Throwable e) { - LogUtils.LOG.warn("failed to update server list", e); - } - } - - public void registerService(String serviceName, Instance instance) throws NacosException { - - LogUtils.LOG.info("REGISTER-SERVICE", "{} registering service {} with instance: {}", - namespaceId, serviceName, instance); - - final Map params = new HashMap(8); - params.put(Constants.REQUEST_PARAM_NAMESPACE_ID, namespaceId); - params.put("ip", instance.getIp()); - params.put("port", String.valueOf(instance.getPort())); - params.put("weight", String.valueOf(instance.getWeight())); - params.put("enable", String.valueOf(instance.isEnabled())); - params.put("healthy", String.valueOf(instance.isHealthy())); - params.put("metadata", JSON.toJSONString(instance.getMetadata())); - params.put("serviceName", serviceName); - params.put("clusterName", instance.getClusterName()); - - reqAPI(UtilAndComs.NACOS_URL_INSTANCE, params, HttpMethod.POST); - - } - - 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 params = new HashMap(8); - params.put(Constants.REQUEST_PARAM_NAMESPACE_ID, namespaceId); - params.put("ip", ip); - params.put("port", String.valueOf(port)); - params.put("serviceName", serviceName); - params.put("cluster", cluster); - - reqAPI(UtilAndComs.NACOS_URL_INSTANCE, params, HttpMethod.DELETE); - } - - public String queryList(String serviceName, String clusters, int udpPort, boolean healthyOnly) throws NacosException { - - final Map params = new HashMap(8); - params.put(Constants.REQUEST_PARAM_NAMESPACE_ID, namespaceId); - params.put("serviceName", serviceName); - params.put("clusters", clusters); - params.put("udpPort", String.valueOf(udpPort)); - params.put("clientIP", NetUtils.localIP()); - params.put("healthyOnly", String.valueOf(healthyOnly)); - - 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()); - Map params = new HashMap(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); - 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); - } - return 0L; - } - - public boolean serverHealthy() { - - try { - reqAPI(UtilAndComs.NACOS_URL_BASE + "/api/hello", new HashMap(2)); - } catch (Exception e) { - return false; - } - - return true; - } - - public ListView getServiceList(int pageNo, int pageSize) throws NacosException { - return getServiceList(pageNo, pageSize, null); - } - - public ListView getServiceList(int pageNo, int pageSize, AbstractSelector selector) throws NacosException { - - Map params = new HashMap(4); - params.put("pageNo", String.valueOf(pageNo)); - params.put("pageSize", String.valueOf(pageSize)); - params.put(Constants.REQUEST_PARAM_NAMESPACE_ID, namespaceId); - - if (selector != null) { - switch (SelectorType.valueOf(selector.getType())) { - case none: - break; - case label: - ExpressionSelector expressionSelector = (ExpressionSelector) selector; - params.put("selector", JSON.toJSONString(expressionSelector)); - break; - default: - break; - } - } - - String result = reqAPI(UtilAndComs.NACOS_URL_BASE + "/service/list", params); - - JSONObject json = JSON.parseObject(result); - ListView listView = new ListView(); - listView.setCount(json.getInteger("count")); - listView.setData(JSON.parseObject(json.getString("doms"), new TypeReference>() { - })); + 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); + } + } - return listView; - } + throw new IllegalStateException("failed to req API:/api/" + api + + " after all servers(" + servers + ") tried"); - public String reqAPI(String api, Map params) throws NacosException { + } - - List snapshot = serversFromEndpoint; - if (!CollectionUtils.isEmpty(serverList)) { - snapshot = serverList; - } - - return reqAPI(api, params, snapshot); - } - - public String reqAPI(String api, Map params, String method) throws NacosException { - - List snapshot = serversFromEndpoint; - if (!CollectionUtils.isEmpty(serverList)) { - snapshot = serverList; - } - - return reqAPI(api, params, snapshot, method); - } - - public String callServer(String api, Map params, String curServer) throws NacosException { - return callServer(api, params, curServer, HttpMethod.GET); - } - - public String callServer(String api, Map params, String curServer, String method) - throws NacosException { - long start = System.currentTimeMillis(); - long end = 0; - - List headers = Arrays.asList("Client-Version", UtilAndComs.VERSION, - "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; - } - - url = HttpClient.getPrefix() + curServer + api; - - HttpClient.HttpResult result = HttpClient.request(url, headers, params, UtilAndComs.ENCODING, method); - end = System.currentTimeMillis(); - - MetricsMonitor.getNamingRequestMonitor(method, url, String.valueOf(result.code)) - .record(end - start, TimeUnit.MILLISECONDS); - - if (HttpURLConnection.HTTP_OK == result.code) { - return result.content; - } - - if (HttpURLConnection.HTTP_NOT_MODIFIED == result.code) { - return StringUtils.EMPTY; - } - - 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); - } - - public String reqAPI(String api, Map params, List servers) { - return reqAPI(api, params, servers, HttpMethod.GET); - } - - public String reqAPI(String api, Map params, List servers, String method) { - - params.put(Constants.REQUEST_PARAM_NAMESPACE_ID, getNamespaceId()); - - if (CollectionUtils.isEmpty(servers) && StringUtils.isEmpty(nacosDomain)) { - throw new IllegalArgumentException("no server available"); - } - - if (servers != null && !servers.isEmpty()) { - - Random random = new Random(System.currentTimeMillis()); - int index = random.nextInt(servers.size()); - - for (int i = 0; i < servers.size(); i++) { - String server = servers.get(index); - try { - return callServer(api, params, server, method); - } catch (Exception 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"); - } - - 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); - } - } - - throw new IllegalStateException("failed to req API:/api/" + api + " after all servers(" + servers + ") tried"); - - } - - public String getNamespaceId() { - return namespaceId; - } + public String getNamespaceId() { + return namespaceId; + } } diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/utils/UtilAndComs.java b/client/src/main/java/com/alibaba/nacos/client/naming/utils/UtilAndComs.java index efa0773db..b8f7892d6 100644 --- a/client/src/main/java/com/alibaba/nacos/client/naming/utils/UtilAndComs.java +++ b/client/src/main/java/com/alibaba/nacos/client/naming/utils/UtilAndComs.java @@ -20,35 +20,39 @@ package com.alibaba.nacos.client.naming.utils; */ public class UtilAndComs { - public static final String VERSION = "Nacos-Java-Client:v0.2.1"; + public static String WEB_CONTEXT = "/nacos"; - public static final String ENCODING = "UTF-8"; + public static String NACOS_URL_BASE = WEB_CONTEXT + "/v1/ns"; - public static final String ENV_LIST_KEY = "envList"; + public static String NACOS_URL_INSTANCE = NACOS_URL_BASE + "/instance"; - public static final String ALL_IPS = "000--00-ALL_IPS--00--000"; + public static final String VERSION = "Nacos-Java-Client:v0.2.1"; - public static final String FAILOVER_SWITCH = "00-00---000-VIPSRV_FAILOVER_SWITCH-000---00-00"; + public static final String ENCODING = "UTF-8"; - public static final String NACOS_URL_BASE = "/nacos/v1/ns"; + public static final String ENV_LIST_KEY = "envList"; - public static final String NACOS_URL_INSTANCE = NACOS_URL_BASE + "/instance"; + public static final String ALL_IPS = "000--00-ALL_IPS--00--000"; - public static final String DEFAULT_NAMESPACE_ID = "public"; + public static final String FAILOVER_SWITCH = "00-00---000-VIPSRV_FAILOVER_SWITCH-000---00-00"; - public static final int REQUEST_DOMAIN_RETRY_COUNT = 3; + public static final String DEFAULT_NAMESPACE_ID = "public"; - public static final String DEFAULT_NAMING_ID = "default"; + public static final int REQUEST_DOMAIN_RETRY_COUNT = 3; - public static final String NACOS_NAMING_LOG_NAME = "com.alibaba.nacos.naming.log.filename"; + public static final String DEFAULT_NAMING_ID = "default"; - public static final String NACOS_NAMING_LOG_LEVEL = "com.alibaba.nacos.naming.log.level"; + public static final String NACOS_NAMING_LOG_NAME = "com.alibaba.nacos.naming.log.filename"; - public static final String SERVER_ADDR_IP_SPLITER = ":"; + public static final String NACOS_NAMING_LOG_LEVEL = "com.alibaba.nacos.naming.log.level"; - public static final int DEFAULT_CLIENT_BEAT_THREAD_COUNT = Runtime.getRuntime().availableProcessors() > 1 ? - Runtime.getRuntime().availableProcessors() / 2 : 1; + public static final String SERVER_ADDR_IP_SPLITER = ":"; - public static final int DEFAULT_POLLING_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; } From e9bbe492bbd0e789972d587dd137e5af566cafec Mon Sep 17 00:00:00 2001 From: pbting <314226532@qq.com> Date: Wed, 13 Feb 2019 16:12:16 +0800 Subject: [PATCH 02/12] code format with idea --- .../alibaba/nacos/api/PropertyKeyConst.java | 24 +- .../nacos/client/identify/Constants.java | 28 +- .../nacos/client/identify/Credentials.java | 80 ++--- .../nacos/client/naming/CredentialsValue.java | 49 --- .../alibaba/nacos/client/naming/SignUtil.java | 66 ++-- .../nacos/client/naming/net/HttpClient.java | 300 +++++++++--------- .../client/naming/utils/UtilAndComs.java | 40 +-- 7 files changed, 266 insertions(+), 321 deletions(-) delete mode 100644 client/src/main/java/com/alibaba/nacos/client/naming/CredentialsValue.java diff --git a/api/src/main/java/com/alibaba/nacos/api/PropertyKeyConst.java b/api/src/main/java/com/alibaba/nacos/api/PropertyKeyConst.java index 2922e66d0..1344b2c1a 100644 --- a/api/src/main/java/com/alibaba/nacos/api/PropertyKeyConst.java +++ b/api/src/main/java/com/alibaba/nacos/api/PropertyKeyConst.java @@ -22,26 +22,26 @@ package com.alibaba.nacos.api; */ public class PropertyKeyConst { - public final static String WEB_CONTEXT = "webContext"; + public final static String WEB_CONTEXT = "webContext"; - public final static String ENDPOINT = "endpoint"; + public final static String ENDPOINT = "endpoint"; - public final static String NAMESPACE = "namespace"; + public final static String NAMESPACE = "namespace"; - public final static String ACCESS_KEY = "accessKey"; + public final static String ACCESS_KEY = "accessKey"; - public final static String SECRET_KEY = "secretKey"; + public final static String SECRET_KEY = "secretKey"; - public final static String SERVER_ADDR = "serverAddr"; + public final static String SERVER_ADDR = "serverAddr"; - public final static String CONTEXT_PATH = "contextPath"; + public final static String CONTEXT_PATH = "contextPath"; - public final static String CLUSTER_NAME = "clusterName"; + public final static String CLUSTER_NAME = "clusterName"; - public final static String ENCODE = "encode"; + public final static String ENCODE = "encode"; - public final static String NAMING_LOAD_CACHE_AT_START = "namingLoadCacheAtStart"; - public final static String NAMING_CLIENT_BEAT_THREAD_COUNT = "namingClientBeatThreadCount"; - public final static String NAMING_POLLING_THREAD_COUNT = "namingPollingThreadCount"; + public final static String NAMING_LOAD_CACHE_AT_START = "namingLoadCacheAtStart"; + public final static String NAMING_CLIENT_BEAT_THREAD_COUNT = "namingClientBeatThreadCount"; + public final static String NAMING_POLLING_THREAD_COUNT = "namingPollingThreadCount"; } diff --git a/client/src/main/java/com/alibaba/nacos/client/identify/Constants.java b/client/src/main/java/com/alibaba/nacos/client/identify/Constants.java index 6d87da6d6..a94110720 100644 --- a/client/src/main/java/com/alibaba/nacos/client/identify/Constants.java +++ b/client/src/main/java/com/alibaba/nacos/client/identify/Constants.java @@ -21,32 +21,32 @@ package com.alibaba.nacos.client.identify; * @author Nacos */ public class Constants { - public static final String ACCESS_KEY = "accessKey"; + public static final String ACCESS_KEY = "accessKey"; - public static final String SECRET_KEY = "secretKey"; + public static final String SECRET_KEY = "secretKey"; - public static final String TENANT_ID = "tenantId"; + public static final String TENANT_ID = "tenantId"; - public static final String PROPERTIES_FILENAME = "spas.properties"; + public static final String PROPERTIES_FILENAME = "spas.properties"; - public static final String CREDENTIAL_PATH = "/home/admin/.spas_key/"; + public static final String CREDENTIAL_PATH = "/home/admin/.spas_key/"; - public static final String CREDENTIAL_DEFAULT = "default"; + public static final String CREDENTIAL_DEFAULT = "default"; - public static final String DOCKER_CREDENTIAL_PATH = "/etc/instanceInfo"; + public static final String DOCKER_CREDENTIAL_PATH = "/etc/instanceInfo"; - public static final String DOCKER_ACCESS_KEY = "env_spas_accessKey"; + public static final String DOCKER_ACCESS_KEY = "env_spas_accessKey"; - public static final String DOCKER_SECRET_KEY = "env_spas_secretKey"; + public static final String DOCKER_SECRET_KEY = "env_spas_secretKey"; - public static final String DOCKER_TENANT_ID = "ebv_spas_tenantId"; + public static final String DOCKER_TENANT_ID = "ebv_spas_tenantId"; - public static final String ENV_ACCESS_KEY = "spas_accessKey"; + public static final String ENV_ACCESS_KEY = "spas_accessKey"; - public static final String ENV_SECRET_KEY = "spas_secretKey"; + public static final String ENV_SECRET_KEY = "spas_secretKey"; - public static final String ENV_TENANT_ID = "tenant.id"; + public static final String ENV_TENANT_ID = "tenant.id"; - public static final String NO_APP_NAME = ""; + public static final String NO_APP_NAME = ""; } diff --git a/client/src/main/java/com/alibaba/nacos/client/identify/Credentials.java b/client/src/main/java/com/alibaba/nacos/client/identify/Credentials.java index 76a9be249..36f698c95 100644 --- a/client/src/main/java/com/alibaba/nacos/client/identify/Credentials.java +++ b/client/src/main/java/com/alibaba/nacos/client/identify/Credentials.java @@ -22,56 +22,56 @@ package com.alibaba.nacos.client.identify; */ public class Credentials implements SpasCredential { - private volatile String accessKey; + private volatile String accessKey; - private volatile String secretKey; + private volatile String secretKey; - private volatile String tenantId; + private volatile String tenantId; - public Credentials(String accessKey, String secretKey, String tenantId) { - this.accessKey = accessKey; - this.secretKey = secretKey; - this.tenantId = tenantId; - } + public Credentials(String accessKey, String secretKey, String tenantId) { + this.accessKey = accessKey; + this.secretKey = secretKey; + this.tenantId = tenantId; + } - public Credentials() { - this(null, null, null); - } + public Credentials() { + this(null, null, null); + } - public String getAccessKey() { - return accessKey; - } + public String getAccessKey() { + return accessKey; + } - public void setAccessKey(String accessKey) { - this.accessKey = accessKey; - } + public void setAccessKey(String accessKey) { + this.accessKey = accessKey; + } - public String getSecretKey() { - return secretKey; - } + public String getSecretKey() { + return secretKey; + } - public void setSecretKey(String secretKey) { - this.secretKey = secretKey; - } + public void setSecretKey(String secretKey) { + this.secretKey = secretKey; + } - public String getTenantId() { - return tenantId; - } + public String getTenantId() { + return tenantId; + } - public void setTenantId(String tenantId) { - this.tenantId = tenantId; - } + public void setTenantId(String tenantId) { + this.tenantId = tenantId; + } - public boolean valid() { - return accessKey != null && !accessKey.isEmpty() && secretKey != null - && !secretKey.isEmpty(); - } + public boolean valid() { + 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))); - } + 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))); + } } diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/CredentialsValue.java b/client/src/main/java/com/alibaba/nacos/client/naming/CredentialsValue.java deleted file mode 100644 index 6abacf7e9..000000000 --- a/client/src/main/java/com/alibaba/nacos/client/naming/CredentialsValue.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * 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; - -/** - * @author pbting - * @date 2019-01-22 10:21 PM - */ -public class CredentialsValue { - private volatile String accessKey; - private volatile String secretKey; - - public CredentialsValue() { - } - - public CredentialsValue(String accessKey, String secretKey) { - this.accessKey = accessKey; - this.secretKey = secretKey; - } - - public String getAccessKey() { - return this.accessKey; - } - - public void setAccessKey(String accessKey) { - this.accessKey = accessKey; - } - - public String getSecretKey() { - return this.secretKey; - } - - public void setSecretKey(String secretKey) { - this.secretKey = secretKey; - } -} diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/SignUtil.java b/client/src/main/java/com/alibaba/nacos/client/naming/SignUtil.java index a44b4c433..59a44090a 100644 --- a/client/src/main/java/com/alibaba/nacos/client/naming/SignUtil.java +++ b/client/src/main/java/com/alibaba/nacos/client/naming/SignUtil.java @@ -26,43 +26,41 @@ import java.nio.charset.Charset; * @date 2019-01-22 10:20 PM */ public class SignUtil { - public static final Charset UTF8 = Charset.forName("UTF-8"); + public static final Charset UTF8 = Charset.forName("UTF-8"); - public SignUtil() { - } + 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); - } - } + 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); - } - } + 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; + public static enum SigningAlgorithm { + // Hmac SHA1 algorithm + HmacSHA1; - private SigningAlgorithm() { - } - } + private SigningAlgorithm() { + } + } } diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/net/HttpClient.java b/client/src/main/java/com/alibaba/nacos/client/naming/net/HttpClient.java index 70d75cf2e..a66c40551 100644 --- a/client/src/main/java/com/alibaba/nacos/client/naming/net/HttpClient.java +++ b/client/src/main/java/com/alibaba/nacos/client/naming/net/HttpClient.java @@ -35,187 +35,183 @@ 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"; + private static final String POST = "POST"; + private static final String PUT = "PUT"; - static { - // limit max redirection - System.setProperty("http.maxRedirects", "5"); - } + static { + // limit max redirection + System.setProperty("http.maxRedirects", "5"); + } - public static String getPrefix() { - if (ENABLE_HTTPS) { - return "https://"; - } + public static String getPrefix() { + if (ENABLE_HTTPS) { + return "https://"; + } - return "http://"; + return "http://"; - } + } - public static HttpResult httpGet(String url, List headers, - Map paramValues, String encoding) { - return request(url, headers, paramValues, encoding, "GET"); - } + public static HttpResult httpGet(String url, List headers, + Map paramValues, String encoding) { + return request(url, headers, paramValues, encoding, "GET"); + } - public static HttpResult request(String url, List headers, - Map paramValues, String encoding, String method) { - HttpURLConnection conn = null; - try { - String encodedContent = encodingParams(paramValues, encoding); - url += (null == encodedContent) ? "" : ("?" + encodedContent); + public static HttpResult request(String url, List headers, + Map paramValues, String encoding, String method) { + HttpURLConnection conn = null; + try { + String encodedContent = encodingParams(paramValues, encoding); + url += (null == encodedContent) ? "" : ("?" + encodedContent); - conn = (HttpURLConnection) new URL(url).openConnection(); + conn = (HttpURLConnection) new URL(url).openConnection(); - setHeaders(conn, headers, encoding); - conn.setConnectTimeout(CON_TIME_OUT_MILLIS); - conn.setReadTimeout(TIME_OUT_MILLIS); - conn.setRequestMethod(method); - 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()); - } - } - catch (Exception e1) { - LogUtils.LOG.error("NA", "failed to request ", e1); - // ignore - } + setHeaders(conn, headers, encoding); + conn.setConnectTimeout(CON_TIME_OUT_MILLIS); + conn.setReadTimeout(TIME_OUT_MILLIS); + conn.setRequestMethod(method); + 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()); + } + } catch (Exception e1) { + LogUtils.LOG.error("NA", "failed to request ", e1); + // ignore + } - LogUtils.LOG.error("NA", "failed to request ", e); + LogUtils.LOG.error("NA", "failed to request ", e); - return new HttpResult(500, e.toString(), - Collections.emptyMap()); - } - finally { - if (conn != null) { - conn.disconnect(); - } - } - } + return new HttpResult(500, e.toString(), + Collections.emptyMap()); + } finally { + if (conn != null) { + conn.disconnect(); + } + } + } - private static HttpResult getResult(HttpURLConnection conn) throws IOException { - int respCode = conn.getResponseCode(); + private static HttpResult getResult(HttpURLConnection conn) throws IOException { + int respCode = conn.getResponseCode(); - InputStream inputStream; - if (HttpURLConnection.HTTP_OK == respCode - || HttpURLConnection.HTTP_NOT_MODIFIED == respCode) { - inputStream = conn.getInputStream(); - } - else { - inputStream = conn.getErrorStream(); - } + InputStream inputStream; + if (HttpURLConnection.HTTP_OK == respCode + || HttpURLConnection.HTTP_NOT_MODIFIED == respCode) { + inputStream = conn.getInputStream(); + } else { + inputStream = conn.getErrorStream(); + } - Map respHeaders = new HashMap( - conn.getHeaderFields().size()); - for (Map.Entry> entry : conn.getHeaderFields().entrySet()) { - respHeaders.put(entry.getKey(), entry.getValue().get(0)); - } + Map respHeaders = new HashMap( + conn.getHeaderFields().size()); + for (Map.Entry> entry : conn.getHeaderFields().entrySet()) { + respHeaders.put(entry.getKey(), entry.getValue().get(0)); + } - String encodingGzip = "gzip"; + String encodingGzip = "gzip"; - if (encodingGzip.equals(respHeaders.get(HttpHeaders.CONTENT_ENCODING))) { - inputStream = new GZIPInputStream(inputStream); - } + if (encodingGzip.equals(respHeaders.get(HttpHeaders.CONTENT_ENCODING))) { + 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) { - String contentType = conn.getContentType(); - if (StringUtils.isEmpty(contentType)) { - return "UTF-8"; - } + private static String getCharset(HttpURLConnection conn) { + String contentType = conn.getContentType(); + if (StringUtils.isEmpty(contentType)) { + return "UTF-8"; + } - String[] values = contentType.split(";"); - if (values.length == 0) { - return "UTF-8"; - } + String[] values = contentType.split(";"); + if (values.length == 0) { + return "UTF-8"; + } - String charset = "UTF-8"; - for (String value : values) { - value = value.trim(); + String charset = "UTF-8"; + for (String value : values) { + value = value.trim(); - if (value.toLowerCase().startsWith("charset=")) { - charset = value.substring("charset=".length()); - } - } + if (value.toLowerCase().startsWith("charset=")) { + charset = value.substring("charset=".length()); + } + } - return charset; - } + return charset; + } - private static void setHeaders(HttpURLConnection conn, List headers, - String encoding) { - if (null != headers) { - for (Iterator iter = headers.iterator(); iter.hasNext();) { - conn.addRequestProperty(iter.next(), iter.next()); - } - } + private static void setHeaders(HttpURLConnection conn, List headers, + String encoding) { + if (null != headers) { + for (Iterator iter = headers.iterator(); iter.hasNext(); ) { + conn.addRequestProperty(iter.next(), iter.next()); + } + } - conn.addRequestProperty("Content-Type", - "application/x-www-form-urlencoded;charset=" + encoding); - conn.addRequestProperty("Accept-Charset", encoding); - } + conn.addRequestProperty("Content-Type", + "application/x-www-form-urlencoded;charset=" + encoding); + conn.addRequestProperty("Accept-Charset", encoding); + } - private static String encodingParams(Map params, String encoding) - throws UnsupportedEncodingException { - if (null == params) { - return null; - } - params.put("encoding", encoding); - StringBuilder sb = new StringBuilder(); + private static String encodingParams(Map params, String encoding) + throws UnsupportedEncodingException { + if (null == params) { + return null; + } + params.put("encoding", encoding); + StringBuilder sb = new StringBuilder(); - for (Map.Entry entry : params.entrySet()) { - if (StringUtils.isEmpty(entry.getValue())) { - continue; - } + for (Map.Entry entry : params.entrySet()) { + if (StringUtils.isEmpty(entry.getValue())) { + continue; + } - sb.append(entry.getKey()).append("="); - sb.append(URLEncoder.encode(entry.getValue(), encoding)); - sb.append("&"); - } + sb.append(entry.getKey()).append("="); + sb.append(URLEncoder.encode(entry.getValue(), encoding)); + sb.append("&"); + } - if (sb.length() > 0) { - sb = sb.deleteCharAt(sb.length() - 1); - } - return sb.toString(); - } + if (sb.length() > 0) { + sb = sb.deleteCharAt(sb.length() - 1); + } + return sb.toString(); + } - public static class HttpResult { - final public int code; - final public String content; - final private Map respHeaders; + public static class HttpResult { + final public int code; + final public String content; + final private Map respHeaders; - public HttpResult(int code, String content, Map respHeaders) { - this.code = code; - this.content = content; - this.respHeaders = respHeaders; - } + public HttpResult(int code, String content, Map respHeaders) { + this.code = code; + this.content = content; + this.respHeaders = respHeaders; + } - public String getHeader(String name) { - return respHeaders.get(name); - } - } + public String getHeader(String name) { + return respHeaders.get(name); + } + } } diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/utils/UtilAndComs.java b/client/src/main/java/com/alibaba/nacos/client/naming/utils/UtilAndComs.java index b8f7892d6..036e2d69b 100644 --- a/client/src/main/java/com/alibaba/nacos/client/naming/utils/UtilAndComs.java +++ b/client/src/main/java/com/alibaba/nacos/client/naming/utils/UtilAndComs.java @@ -20,39 +20,39 @@ package com.alibaba.nacos.client.naming.utils; */ public class UtilAndComs { - public static String WEB_CONTEXT = "/nacos"; + public static String WEB_CONTEXT = "/nacos"; - public static String NACOS_URL_BASE = WEB_CONTEXT + "/v1/ns"; + public static String NACOS_URL_BASE = WEB_CONTEXT + "/v1/ns"; - public static String NACOS_URL_INSTANCE = NACOS_URL_BASE + "/instance"; + 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 VERSION = "Nacos-Java-Client:v0.2.1"; - 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"; - public static final String ALL_IPS = "000--00-ALL_IPS--00--000"; + public static final String ALL_IPS = "000--00-ALL_IPS--00--000"; - public static final String FAILOVER_SWITCH = "00-00---000-VIPSRV_FAILOVER_SWITCH-000---00-00"; + public static final String FAILOVER_SWITCH = "00-00---000-VIPSRV_FAILOVER_SWITCH-000---00-00"; - public static final String DEFAULT_NAMESPACE_ID = "public"; + public static final String DEFAULT_NAMESPACE_ID = "public"; - public static final int REQUEST_DOMAIN_RETRY_COUNT = 3; + public static final int REQUEST_DOMAIN_RETRY_COUNT = 3; - public static final String DEFAULT_NAMING_ID = "default"; + public static final String DEFAULT_NAMING_ID = "default"; - public static final String NACOS_NAMING_LOG_NAME = "com.alibaba.nacos.naming.log.filename"; + public static final String NACOS_NAMING_LOG_NAME = "com.alibaba.nacos.naming.log.filename"; - public static final String NACOS_NAMING_LOG_LEVEL = "com.alibaba.nacos.naming.log.level"; + public static final String NACOS_NAMING_LOG_LEVEL = "com.alibaba.nacos.naming.log.level"; - public static final String SERVER_ADDR_IP_SPLITER = ":"; + 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; } From 15e0f3084943eaf93978a13b21c56b6947f66d7b Mon Sep 17 00:00:00 2001 From: pbting <314226532@qq.com> Date: Thu, 14 Feb 2019 18:00:01 +0800 Subject: [PATCH 03/12] fix #367 --- api/pom.xml | 2 +- .../alibaba/nacos/api/PropertyKeyConst.java | 2 + client/pom.xml | 2 +- .../client/naming/NacosNamingService.java | 621 +++++++-------- .../nacos/client/naming/net/NamingProxy.java | 752 +++++++++--------- cmdb/pom.xml | 2 +- common/pom.xml | 2 +- config/pom.xml | 2 +- console/pom.xml | 2 +- core/pom.xml | 2 +- distribution/pom.xml | 2 +- example/pom.xml | 2 +- naming/pom.xml | 2 +- pom.xml | 3 +- test/pom.xml | 2 +- 15 files changed, 705 insertions(+), 695 deletions(-) diff --git a/api/pom.xml b/api/pom.xml index 1845bc0f4..087585e06 100644 --- a/api/pom.xml +++ b/api/pom.xml @@ -16,7 +16,7 @@ com.alibaba.nacos nacos-all - 0.8.0-SNAPSHOT + 0.8.1-SNAPSHOT 4.0.0 diff --git a/api/src/main/java/com/alibaba/nacos/api/PropertyKeyConst.java b/api/src/main/java/com/alibaba/nacos/api/PropertyKeyConst.java index 1344b2c1a..2b689cd31 100644 --- a/api/src/main/java/com/alibaba/nacos/api/PropertyKeyConst.java +++ b/api/src/main/java/com/alibaba/nacos/api/PropertyKeyConst.java @@ -22,6 +22,8 @@ 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"; diff --git a/client/pom.xml b/client/pom.xml index 1bf49a0f1..1c91f29f1 100644 --- a/client/pom.xml +++ b/client/pom.xml @@ -16,7 +16,7 @@ com.alibaba.nacos nacos-all - 0.8.0-SNAPSHOT + 0.8.1-SNAPSHOT ../pom.xml diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/NacosNamingService.java b/client/src/main/java/com/alibaba/nacos/client/naming/NacosNamingService.java index 6a9b583d7..905c557a6 100644 --- a/client/src/main/java/com/alibaba/nacos/client/naming/NacosNamingService.java +++ b/client/src/main/java/com/alibaba/nacos/client/naming/NacosNamingService.java @@ -48,338 +48,339 @@ import java.util.Properties; @SuppressWarnings("PMD.ServiceOrDaoClassShouldEndWithImplRule") public class NacosNamingService implements NamingService { - /** - * Each Naming instance should have different namespace. - */ - private String namespace; + /** + * Each Naming instance should have different namespace. + */ + private String namespace; - private String endpoint; + private String endpoint; - private String serverList; + private String serverList; - private String cacheDir; + private String cacheDir; - private String logName; + private String logName; - private HostReactor hostReactor; + private HostReactor hostReactor; - private BeatReactor beatReactor; + private BeatReactor beatReactor; - private EventDispatcher eventDispatcher; + private EventDispatcher eventDispatcher; - private NamingProxy serverProxy; + private NamingProxy serverProxy; - private void init() { + private void init() { - namespace = System.getProperty(PropertyKeyConst.NAMESPACE); + namespace = System.getProperty(PropertyKeyConst.NAMESPACE); - if (StringUtils.isEmpty(namespace)) { - namespace = UtilAndComs.DEFAULT_NAMESPACE_ID; - } + if (StringUtils.isEmpty(namespace)) { + namespace = UtilAndComs.DEFAULT_NAMESPACE_ID; + } - logName = System.getProperty(UtilAndComs.NACOS_NAMING_LOG_NAME); - if (StringUtils.isEmpty(logName)) { - logName = "naming.log"; - } + logName = System.getProperty(UtilAndComs.NACOS_NAMING_LOG_NAME); + if (StringUtils.isEmpty(logName)) { + logName = "naming.log"; + } - String logLevel = System.getProperty(UtilAndComs.NACOS_NAMING_LOG_LEVEL); - if (StringUtils.isEmpty(logLevel)) { - logLevel = "INFO"; - } + String logLevel = System.getProperty(UtilAndComs.NACOS_NAMING_LOG_LEVEL); + if (StringUtils.isEmpty(logLevel)) { + logLevel = "INFO"; + } - LogUtils.setLogLevel(logLevel); + LogUtils.setLogLevel(logLevel); - cacheDir = System.getProperty("com.alibaba.nacos.naming.cache.dir"); - if (StringUtils.isEmpty(cacheDir)) { - cacheDir = System.getProperty("user.home") + "/nacos/naming/" + namespace; - } - } + cacheDir = System.getProperty("com.alibaba.nacos.naming.cache.dir"); + if (StringUtils.isEmpty(cacheDir)) { + cacheDir = System.getProperty("user.home") + "/nacos/naming/" + namespace; + } + } - public NacosNamingService(String serverList) { + public NacosNamingService(String serverList) { - this.serverList = serverList; - init(); - eventDispatcher = new EventDispatcher(); - serverProxy = new NamingProxy(namespace, endpoint, serverList); - beatReactor = new BeatReactor(serverProxy); - hostReactor = new HostReactor(eventDispatcher, serverProxy, cacheDir); - } + this.serverList = serverList; + init(); + eventDispatcher = new EventDispatcher(); + serverProxy = new NamingProxy(namespace, endpoint, serverList); + beatReactor = new BeatReactor(serverProxy); + hostReactor = new HostReactor(eventDispatcher, serverProxy, cacheDir); + } - public NacosNamingService(Properties properties) { + public NacosNamingService(Properties properties) { - init(); + init(); - serverList = properties.getProperty(PropertyKeyConst.SERVER_ADDR); + serverList = properties.getProperty(PropertyKeyConst.SERVER_ADDR); - if (StringUtils.isNotEmpty(properties.getProperty(PropertyKeyConst.NAMESPACE))) { - namespace = properties.getProperty(PropertyKeyConst.NAMESPACE); - } + if (StringUtils.isNotEmpty(properties.getProperty(PropertyKeyConst.NAMESPACE))) { + namespace = properties.getProperty(PropertyKeyConst.NAMESPACE); + } - if (StringUtils - .isNotEmpty(properties.getProperty(UtilAndComs.NACOS_NAMING_LOG_NAME))) { - logName = 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"); - } - - if (StringUtils - .isNotEmpty(properties.getProperty(PropertyKeyConst.WEB_CONTEXT))) { - String tmpWebContext = properties.getProperty(PropertyKeyConst.WEB_CONTEXT); - UtilAndComs.WEB_CONTEXT = tmpWebContext.indexOf("/") > -1 ? tmpWebContext - : "/" + tmpWebContext; + if (StringUtils.isNotEmpty(properties.getProperty(PropertyKeyConst.ENDPOINT))) { + endpoint = properties.getProperty(PropertyKeyConst.ENDPOINT) + ":" + + properties.getProperty("address.server.port", "8080"); + } - UtilAndComs.NACOS_URL_BASE = UtilAndComs.WEB_CONTEXT + "/v1/ns"; - UtilAndComs.NACOS_URL_INSTANCE = UtilAndComs.NACOS_URL_BASE + "/instance"; - } - - cacheDir = System.getProperty("user.home") + "/nacos/naming/" + namespace; - - boolean loadCacheAtStart = false; - 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), - UtilAndComs.DEFAULT_CLIENT_BEAT_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); - - } - - @Override - 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 { - Instance instance = new Instance(); - instance.setIp(ip); - instance.setPort(port); - instance.setWeight(1.0); - instance.setClusterName(clusterName); - - registerInstance(serviceName, instance); - } - - @Override - public void registerInstance(String serviceName, Instance instance) - throws NacosException { - - BeatInfo beatInfo = new BeatInfo(); - beatInfo.setServiceName(serviceName); - beatInfo.setIp(instance.getIp()); - beatInfo.setPort(instance.getPort()); - beatInfo.setCluster(instance.getClusterName()); - beatInfo.setWeight(instance.getWeight()); - beatInfo.setMetadata(instance.getMetadata()); - beatInfo.setScheduled(false); - - beatReactor.addBeatInfo(serviceName, beatInfo); - - serverProxy.registerService(serviceName, instance); - } - - @Override - 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 { - beatReactor.removeBeatInfo(serviceName, ip, port); - serverProxy.deregisterService(serviceName, ip, port, clusterName); - } - - @Override - public List getAllInstances(String serviceName) throws NacosException { - return getAllInstances(serviceName, new ArrayList()); - } - - @Override - public List getAllInstances(String serviceName, boolean subscribe) - throws NacosException { - return getAllInstances(serviceName, new ArrayList(), subscribe); - } - - @Override - public List getAllInstances(String serviceName, List clusters) - throws NacosException { - return getAllInstances(serviceName, clusters, true); - } - - @Override - public List getAllInstances(String serviceName, List clusters, - boolean subscribe) throws NacosException { - - ServiceInfo serviceInfo; - if (subscribe) { - serviceInfo = hostReactor.getServiceInfo(serviceName, - StringUtils.join(clusters, ",")); - } - else { - serviceInfo = hostReactor.getServiceInfoDirectlyFromServer(serviceName, - StringUtils.join(clusters, ",")); - } - List list; - if (serviceInfo == null - || CollectionUtils.isEmpty(list = serviceInfo.getHosts())) { - return new ArrayList(); - } - return list; - } - - @Override - public List selectInstances(String serviceName, boolean healthy) - throws NacosException { - return selectInstances(serviceName, new ArrayList(), healthy); - } - - @Override - public List selectInstances(String serviceName, boolean healthy, - boolean subscribe) throws NacosException { - return selectInstances(serviceName, new ArrayList(), healthy, subscribe); - } - - @Override - public List selectInstances(String serviceName, List clusters, - boolean healthy) throws NacosException { - return selectInstances(serviceName, clusters, healthy, true); - } - - @Override - public List selectInstances(String serviceName, List clusters, - boolean healthy, boolean subscribe) throws NacosException { - ServiceInfo serviceInfo; - if (subscribe) { - serviceInfo = hostReactor.getServiceInfo(serviceName, - StringUtils.join(clusters, ",")); - } - else { - serviceInfo = hostReactor.getServiceInfoDirectlyFromServer(serviceName, - StringUtils.join(clusters, ",")); - } - return selectInstances(serviceInfo, healthy); - } - - @Override - public Instance selectOneHealthyInstance(String serviceName) throws NacosException { - return selectOneHealthyInstance(serviceName, new ArrayList()); - } - - @Override - public Instance selectOneHealthyInstance(String serviceName, boolean subscribe) - throws NacosException { - return selectOneHealthyInstance(serviceName, new ArrayList(), subscribe); - } - - @Override - public Instance selectOneHealthyInstance(String serviceName, List clusters) - throws NacosException { - return selectOneHealthyInstance(serviceName, clusters, true); - } - - @Override - public Instance selectOneHealthyInstance(String serviceName, List clusters, - boolean subscribe) throws NacosException { - - if (subscribe) { - return Balancer.RandomByWeight.selectHost(hostReactor - .getServiceInfo(serviceName, StringUtils.join(clusters, ","))); - } - else { - 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, - listener); - } - - @Override - public void subscribe(String service, List clusters, EventListener listener) { - eventDispatcher.addListener( - hostReactor.getServiceInfo(service, StringUtils.join(clusters, ",")), - StringUtils.join(clusters, ","), listener); - } - - @Override - public void unsubscribe(String service, EventListener listener) { - eventDispatcher.removeListener(service, StringUtils.EMPTY, listener); - } - - @Override - public void unsubscribe(String service, List clusters, - EventListener listener) { - eventDispatcher.removeListener(service, StringUtils.join(clusters, ","), - listener); - } - - @Override - public ListView getServicesOfServer(int pageNo, int pageSize) - throws NacosException { - return serverProxy.getServiceList(pageNo, pageSize); - } - - @Override - public ListView getServicesOfServer(int pageNo, int pageSize, - AbstractSelector selector) throws NacosException { - return serverProxy.getServiceList(pageNo, pageSize, selector); - } - - @Override - public List getSubscribeServices() { - return eventDispatcher.getSubscribeServices(); - } - - @Override - public String getServerStatus() { - return serverProxy.serverHealthy() ? "UP" : "DOWN"; - } - - private List selectInstances(ServiceInfo serviceInfo, boolean healthy) { - List list; - if (serviceInfo == null - || CollectionUtils.isEmpty(list = serviceInfo.getHosts())) { - return new ArrayList(); - } - - Iterator iterator = list.iterator(); - while (iterator.hasNext()) { - Instance instance = iterator.next(); - if (healthy != instance.isHealthy() || !instance.isEnabled() - || instance.getWeight() <= 0) { - iterator.remove(); - } - } - - return list; - } - - public BeatReactor getBeatReactor() { - return beatReactor; - } + initWebRootContext(); + + cacheDir = System.getProperty("user.home") + "/nacos/naming/" + namespace; + + boolean loadCacheAtStart = false; + 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), + UtilAndComs.DEFAULT_CLIENT_BEAT_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); + + } + + 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 { + registerInstance(serviceName, ip, port, Constants.NAMING_DEFAULT_CLUSTER_NAME); + } + + @Override + public void registerInstance(String serviceName, String ip, int port, + String clusterName) throws NacosException { + Instance instance = new Instance(); + instance.setIp(ip); + instance.setPort(port); + instance.setWeight(1.0); + instance.setClusterName(clusterName); + + registerInstance(serviceName, instance); + } + + @Override + public void registerInstance(String serviceName, Instance instance) + throws NacosException { + + BeatInfo beatInfo = new BeatInfo(); + beatInfo.setServiceName(serviceName); + beatInfo.setIp(instance.getIp()); + beatInfo.setPort(instance.getPort()); + beatInfo.setCluster(instance.getClusterName()); + beatInfo.setWeight(instance.getWeight()); + beatInfo.setMetadata(instance.getMetadata()); + beatInfo.setScheduled(false); + + beatReactor.addBeatInfo(serviceName, beatInfo); + + serverProxy.registerService(serviceName, instance); + } + + @Override + 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 { + beatReactor.removeBeatInfo(serviceName, ip, port); + serverProxy.deregisterService(serviceName, ip, port, clusterName); + } + + @Override + public List getAllInstances(String serviceName) throws NacosException { + return getAllInstances(serviceName, new ArrayList()); + } + + @Override + public List getAllInstances(String serviceName, boolean subscribe) + throws NacosException { + return getAllInstances(serviceName, new ArrayList(), subscribe); + } + + @Override + public List getAllInstances(String serviceName, List clusters) + throws NacosException { + return getAllInstances(serviceName, clusters, true); + } + + @Override + public List getAllInstances(String serviceName, List clusters, + boolean subscribe) throws NacosException { + + ServiceInfo serviceInfo; + if (subscribe) { + serviceInfo = hostReactor.getServiceInfo(serviceName, + StringUtils.join(clusters, ",")); + } else { + serviceInfo = hostReactor.getServiceInfoDirectlyFromServer(serviceName, + StringUtils.join(clusters, ",")); + } + List list; + if (serviceInfo == null + || CollectionUtils.isEmpty(list = serviceInfo.getHosts())) { + return new ArrayList(); + } + return list; + } + + @Override + public List selectInstances(String serviceName, boolean healthy) + throws NacosException { + return selectInstances(serviceName, new ArrayList(), healthy); + } + + @Override + public List selectInstances(String serviceName, boolean healthy, + boolean subscribe) throws NacosException { + return selectInstances(serviceName, new ArrayList(), healthy, subscribe); + } + + @Override + public List selectInstances(String serviceName, List clusters, + boolean healthy) throws NacosException { + return selectInstances(serviceName, clusters, healthy, true); + } + + @Override + public List selectInstances(String serviceName, List clusters, + boolean healthy, boolean subscribe) throws NacosException { + ServiceInfo serviceInfo; + if (subscribe) { + serviceInfo = hostReactor.getServiceInfo(serviceName, + StringUtils.join(clusters, ",")); + } else { + serviceInfo = hostReactor.getServiceInfoDirectlyFromServer(serviceName, + StringUtils.join(clusters, ",")); + } + return selectInstances(serviceInfo, healthy); + } + + @Override + public Instance selectOneHealthyInstance(String serviceName) throws NacosException { + return selectOneHealthyInstance(serviceName, new ArrayList()); + } + + @Override + public Instance selectOneHealthyInstance(String serviceName, boolean subscribe) + throws NacosException { + return selectOneHealthyInstance(serviceName, new ArrayList(), subscribe); + } + + @Override + public Instance selectOneHealthyInstance(String serviceName, List clusters) + throws NacosException { + return selectOneHealthyInstance(serviceName, clusters, true); + } + + @Override + public Instance selectOneHealthyInstance(String serviceName, List clusters, + boolean subscribe) throws NacosException { + + if (subscribe) { + return Balancer.RandomByWeight.selectHost(hostReactor + .getServiceInfo(serviceName, StringUtils.join(clusters, ","))); + } else { + 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, + listener); + } + + @Override + public void subscribe(String service, List clusters, EventListener listener) { + eventDispatcher.addListener( + hostReactor.getServiceInfo(service, StringUtils.join(clusters, ",")), + StringUtils.join(clusters, ","), listener); + } + + @Override + public void unsubscribe(String service, EventListener listener) { + eventDispatcher.removeListener(service, StringUtils.EMPTY, listener); + } + + @Override + public void unsubscribe(String service, List clusters, + EventListener listener) { + eventDispatcher.removeListener(service, StringUtils.join(clusters, ","), + listener); + } + + @Override + public ListView getServicesOfServer(int pageNo, int pageSize) + throws NacosException { + return serverProxy.getServiceList(pageNo, pageSize); + } + + @Override + public ListView getServicesOfServer(int pageNo, int pageSize, + AbstractSelector selector) throws NacosException { + return serverProxy.getServiceList(pageNo, pageSize, selector); + } + + @Override + public List getSubscribeServices() { + return eventDispatcher.getSubscribeServices(); + } + + @Override + public String getServerStatus() { + return serverProxy.serverHealthy() ? "UP" : "DOWN"; + } + + private List selectInstances(ServiceInfo serviceInfo, boolean healthy) { + List list; + if (serviceInfo == null + || CollectionUtils.isEmpty(list = serviceInfo.getHosts())) { + return new ArrayList(); + } + + Iterator iterator = list.iterator(); + while (iterator.hasNext()) { + Instance instance = iterator.next(); + if (healthy != instance.isHealthy() || !instance.isEnabled() + || instance.getWeight() <= 0) { + iterator.remove(); + } + } + + return list; + } + + public BeatReactor getBeatReactor() { + return beatReactor; + } } diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/net/NamingProxy.java b/client/src/main/java/com/alibaba/nacos/client/naming/net/NamingProxy.java index 6c09c0f53..a3f0c30e1 100644 --- a/client/src/main/java/com/alibaba/nacos/client/naming/net/NamingProxy.java +++ b/client/src/main/java/com/alibaba/nacos/client/naming/net/NamingProxy.java @@ -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; @@ -47,398 +48,403 @@ import java.util.concurrent.TimeUnit; */ public class NamingProxy { - private static final int DEFAULT_SERVER_PORT = 8848; + private static final int DEFAULT_SERVER_PORT = 8848; - private String namespaceId; + private int serverPort = DEFAULT_SERVER_PORT; - private String endpoint; + private String namespaceId; - private String nacosDomain; + private String endpoint; - private List serverList; + private String nacosDomain; - private List serversFromEndpoint = new ArrayList(); + private List serverList; - private long lastSrvRefTime = 0L; + private List serversFromEndpoint = new ArrayList(); - private long vipSrvRefInterMillis = TimeUnit.SECONDS.toMillis(30); + private long lastSrvRefTime = 0L; - private CredentialService credentialService = CredentialService.getInstance(); + private long vipSrvRefInterMillis = TimeUnit.SECONDS.toMillis(30); - private ScheduledExecutorService executorService; + private CredentialService credentialService = CredentialService.getInstance(); - public NamingProxy(String namespaceId, String endpoint, String serverList) { + private ScheduledExecutorService executorService; - this.namespaceId = namespaceId; - this.endpoint = endpoint; - if (StringUtils.isNotEmpty(serverList)) { - this.serverList = Arrays.asList(serverList.split(",")); - if (this.serverList.size() == 1) { - this.nacosDomain = serverList; - } - } + public NamingProxy(String namespaceId, String endpoint, String serverList) { - executorService = new ScheduledThreadPoolExecutor(1, new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - Thread t = new Thread(r); - t.setName("com.alibaba.nacos.client.naming.serverlist.updater"); - t.setDaemon(true); - return t; - } - }); + this.namespaceId = namespaceId; + this.endpoint = endpoint; - executorService.scheduleWithFixedDelay(new Runnable() { - @Override - public void run() { - refreshSrvIfNeed(); - } - }, 0, vipSrvRefInterMillis, TimeUnit.MILLISECONDS); - - refreshSrvIfNeed(); - } - - public List getServerListFromEndpoint() { - - try { - String urlString = "http://" + endpoint + "/nacos/serverlist"; - - List headers = Arrays.asList("Client-Version", UtilAndComs.VERSION, - "Accept-Encoding", "gzip,deflate,sdch", "Connection", "Keep-Alive", - "RequestId", UuidUtils.generateUuid()); - - 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); - } - - String content = result.content; - List list = new ArrayList(); - for (String line : IoUtils.readLines(new StringReader(content))) { - if (!line.trim().isEmpty()) { - list.add(line.trim()); - } - } - - return list; - - } - catch (Exception e) { - e.printStackTrace(); - } - - return null; - } - - private void refreshSrvIfNeed() { - try { - - if (!CollectionUtils.isEmpty(serverList)) { - LogUtils.LOG.debug("server list provided by user: " + serverList); - return; - } - - if (System.currentTimeMillis() - lastSrvRefTime < vipSrvRefInterMillis) { - return; - } - - List list = getServerListFromEndpoint(); - - if (CollectionUtils.isEmpty(list)) { - throw new Exception("Can not acquire Nacos list"); - } - - if (!CollectionUtils.isEqualCollection(list, serversFromEndpoint)) { - LogUtils.LOG.info("SERVER-LIST", "server list is updated: " + list); - } - - serversFromEndpoint = list; - lastSrvRefTime = System.currentTimeMillis(); - } - catch (Throwable e) { - LogUtils.LOG.warn("failed to update server list", e); - } - } - - public void registerService(String serviceName, Instance instance) - throws NacosException { - - LogUtils.LOG.info("REGISTER-SERVICE", - "{} registering service {} with instance: {}", namespaceId, serviceName, - instance); - - final Map params = new HashMap(8); - params.put(Constants.REQUEST_PARAM_NAMESPACE_ID, namespaceId); - params.put("ip", instance.getIp()); - params.put("port", String.valueOf(instance.getPort())); - params.put("weight", String.valueOf(instance.getWeight())); - params.put("enable", String.valueOf(instance.isEnabled())); - params.put("healthy", String.valueOf(instance.isHealthy())); - params.put("metadata", JSON.toJSONString(instance.getMetadata())); - params.put("serviceName", serviceName); - params.put("clusterName", instance.getClusterName()); - - reqAPI(UtilAndComs.NACOS_URL_INSTANCE, params, HttpMethod.POST); - - } - - private void checkTenant(Map params) { - String tenantId = credentialService.getCredential().getTenantId(); - if (tenantId == null || tenantId.trim().length() == 0) { - return; - } - - 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 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 params = new HashMap(8); - params.put(Constants.REQUEST_PARAM_NAMESPACE_ID, namespaceId); - params.put("ip", ip); - params.put("port", String.valueOf(port)); - params.put("serviceName", serviceName); - params.put("cluster", cluster); - - reqAPI(UtilAndComs.NACOS_URL_INSTANCE, params, HttpMethod.DELETE); - } - - public String queryList(String serviceName, String clusters, int udpPort, - boolean healthyOnly) throws NacosException { - - final Map params = new HashMap(8); - params.put(Constants.REQUEST_PARAM_NAMESPACE_ID, namespaceId); - params.put("serviceName", serviceName); - params.put("clusters", clusters); - params.put("udpPort", String.valueOf(udpPort)); - params.put("clientIP", NetUtils.localIP()); - params.put("healthyOnly", String.valueOf(healthyOnly)); - - 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()); - Map params = new HashMap(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); - 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); - } - return 0L; - } - - public boolean serverHealthy() { - - try { - reqAPI(UtilAndComs.NACOS_URL_BASE + "/api/hello", - new HashMap(2)); - } - catch (Exception e) { - return false; - } - - return true; - } - - public ListView getServiceList(int pageNo, int pageSize) - throws NacosException { - return getServiceList(pageNo, pageSize, null); - } - - public ListView getServiceList(int pageNo, int pageSize, - AbstractSelector selector) throws NacosException { - - Map params = new HashMap(4); - params.put("pageNo", String.valueOf(pageNo)); - params.put("pageSize", String.valueOf(pageSize)); - params.put(Constants.REQUEST_PARAM_NAMESPACE_ID, namespaceId); - - if (selector != null) { - switch (SelectorType.valueOf(selector.getType())) { - case none: - break; - case label: - ExpressionSelector expressionSelector = (ExpressionSelector) selector; - params.put("selector", JSON.toJSONString(expressionSelector)); - break; - default: - break; - } - } - - String result = reqAPI(UtilAndComs.NACOS_URL_BASE + "/service/list", params); - - JSONObject json = JSON.parseObject(result); - ListView listView = new ListView(); - listView.setCount(json.getInteger("count")); - listView.setData(JSON.parseObject(json.getString("doms"), - new TypeReference>() { - })); - - return listView; - } - - public String reqAPI(String api, Map params) throws NacosException { - - List snapshot = serversFromEndpoint; - if (!CollectionUtils.isEmpty(serverList)) { - snapshot = serverList; - } - - return reqAPI(api, params, snapshot); - } - - public String reqAPI(String api, Map params, String method) - throws NacosException { - - List snapshot = serversFromEndpoint; - if (!CollectionUtils.isEmpty(serverList)) { - snapshot = serverList; - } - - return reqAPI(api, params, snapshot, method); - } - - public String callServer(String api, Map params, String curServer) - throws NacosException { - return callServer(api, params, curServer, HttpMethod.GET); - } - - public String callServer(String api, Map params, String curServer, - String method) throws NacosException { - long start = System.currentTimeMillis(); - long end = 0; - - List headers = Arrays.asList("Client-Version", UtilAndComs.VERSION, - "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; - } - - url = HttpClient.getPrefix() + curServer + api; - - HttpClient.HttpResult result = HttpClient.request(url, headers, params, - UtilAndComs.ENCODING, method); - end = System.currentTimeMillis(); - - MetricsMonitor.getNamingRequestMonitor(method, url, String.valueOf(result.code)) - .record(end - start, TimeUnit.MILLISECONDS); - - if (HttpURLConnection.HTTP_OK == result.code) { - return result.content; - } - - if (HttpURLConnection.HTTP_NOT_MODIFIED == result.code) { - return StringUtils.EMPTY; - } - - 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); - } - - public String reqAPI(String api, Map params, List servers) { - return reqAPI(api, params, servers, HttpMethod.GET); - } - - public String reqAPI(String api, Map params, List 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"); - } - - if (servers != null && !servers.isEmpty()) { + if (StringUtils.isNotEmpty(serverList)) { + this.serverList = Arrays.asList(serverList.split(",")); + if (this.serverList.size() == 1) { + this.nacosDomain = serverList; + } + } - Random random = new Random(System.currentTimeMillis()); - int index = random.nextInt(servers.size()); + String serverPort = System.getProperties().getProperty(PropertyKeyConst.SERVER_PORT); + if (StringUtils.isNotEmpty(serverPort)) { + this.serverPort = Integer.valueOf(serverPort.trim()); + } - for (int i = 0; i < servers.size(); i++) { - String server = servers.get(index); - try { - return callServer(api, params, server, method); - } - catch (Exception e) { - LogUtils.LOG.error("NA", - "req api:" + api + " failed, server(" + server, e); - } + executorService = new ScheduledThreadPoolExecutor(1, new ThreadFactory() { + @Override + public Thread newThread(Runnable r) { + Thread t = new Thread(r); + t.setName("com.alibaba.nacos.client.naming.serverlist.updater"); + t.setDaemon(true); + return t; + } + }); - index = (index + 1) % servers.size(); - } + executorService.scheduleWithFixedDelay(new Runnable() { + @Override + public void run() { + refreshSrvIfNeed(); + } + }, 0, vipSrvRefInterMillis, TimeUnit.MILLISECONDS); - throw new IllegalStateException("failed to req API:" + api - + " after all servers(" + servers + ") tried"); - } + refreshSrvIfNeed(); + } - 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); - } - } + public void setServerPort(int serverPort) { + this.serverPort = serverPort; + } - throw new IllegalStateException("failed to req API:/api/" + api - + " after all servers(" + servers + ") tried"); + public List getServerListFromEndpoint() { + + try { + String urlString = "http://" + endpoint + "/nacos/serverlist"; + + List headers = Arrays.asList("Client-Version", UtilAndComs.VERSION, + "Accept-Encoding", "gzip,deflate,sdch", "Connection", "Keep-Alive", + "RequestId", UuidUtils.generateUuid()); + + 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); + } + + String content = result.content; + List list = new ArrayList(); + for (String line : IoUtils.readLines(new StringReader(content))) { + if (!line.trim().isEmpty()) { + list.add(line.trim()); + } + } + + return list; + + } catch (Exception e) { + e.printStackTrace(); + } + + return null; + } + + private void refreshSrvIfNeed() { + try { + + if (!CollectionUtils.isEmpty(serverList)) { + LogUtils.LOG.debug("server list provided by user: " + serverList); + return; + } + + if (System.currentTimeMillis() - lastSrvRefTime < vipSrvRefInterMillis) { + return; + } + + List list = getServerListFromEndpoint(); + + if (CollectionUtils.isEmpty(list)) { + throw new Exception("Can not acquire Nacos list"); + } + + if (!CollectionUtils.isEqualCollection(list, serversFromEndpoint)) { + LogUtils.LOG.info("SERVER-LIST", "server list is updated: " + list); + } + + serversFromEndpoint = list; + lastSrvRefTime = System.currentTimeMillis(); + } catch (Throwable e) { + LogUtils.LOG.warn("failed to update server list", e); + } + } + + public void registerService(String serviceName, Instance instance) + throws NacosException { + + LogUtils.LOG.info("REGISTER-SERVICE", + "{} registering service {} with instance: {}", namespaceId, serviceName, + instance); + + final Map params = new HashMap(8); + params.put(Constants.REQUEST_PARAM_NAMESPACE_ID, namespaceId); + params.put("ip", instance.getIp()); + params.put("port", String.valueOf(instance.getPort())); + params.put("weight", String.valueOf(instance.getWeight())); + params.put("enable", String.valueOf(instance.isEnabled())); + params.put("healthy", String.valueOf(instance.isHealthy())); + params.put("metadata", JSON.toJSONString(instance.getMetadata())); + params.put("serviceName", serviceName); + params.put("clusterName", instance.getClusterName()); + + reqAPI(UtilAndComs.NACOS_URL_INSTANCE, params, HttpMethod.POST); + + } + + private void checkTenant(Map params) { + String tenantId = credentialService.getCredential().getTenantId(); + if (tenantId == null || tenantId.trim().length() == 0) { + return; + } + + 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 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 params = new HashMap(8); + params.put(Constants.REQUEST_PARAM_NAMESPACE_ID, namespaceId); + params.put("ip", ip); + params.put("port", String.valueOf(port)); + params.put("serviceName", serviceName); + params.put("cluster", cluster); + + reqAPI(UtilAndComs.NACOS_URL_INSTANCE, params, HttpMethod.DELETE); + } + + public String queryList(String serviceName, String clusters, int udpPort, + boolean healthyOnly) throws NacosException { + + final Map params = new HashMap(8); + params.put(Constants.REQUEST_PARAM_NAMESPACE_ID, namespaceId); + params.put("serviceName", serviceName); + params.put("clusters", clusters); + params.put("udpPort", String.valueOf(udpPort)); + params.put("clientIP", NetUtils.localIP()); + params.put("healthyOnly", String.valueOf(healthyOnly)); + + 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()); + Map params = new HashMap(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); + 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); + } + return 0L; + } + + public boolean serverHealthy() { + + try { + reqAPI(UtilAndComs.NACOS_URL_BASE + "/api/hello", + new HashMap(2)); + } catch (Exception e) { + return false; + } + + return true; + } + + public ListView getServiceList(int pageNo, int pageSize) + throws NacosException { + return getServiceList(pageNo, pageSize, null); + } + + public ListView getServiceList(int pageNo, int pageSize, + AbstractSelector selector) throws NacosException { + + Map params = new HashMap(4); + params.put("pageNo", String.valueOf(pageNo)); + params.put("pageSize", String.valueOf(pageSize)); + params.put(Constants.REQUEST_PARAM_NAMESPACE_ID, namespaceId); + + if (selector != null) { + switch (SelectorType.valueOf(selector.getType())) { + case none: + break; + case label: + ExpressionSelector expressionSelector = (ExpressionSelector) selector; + params.put("selector", JSON.toJSONString(expressionSelector)); + break; + default: + break; + } + } + + String result = reqAPI(UtilAndComs.NACOS_URL_BASE + "/service/list", params); + + JSONObject json = JSON.parseObject(result); + ListView listView = new ListView(); + listView.setCount(json.getInteger("count")); + listView.setData(JSON.parseObject(json.getString("doms"), + new TypeReference>() { + })); + + return listView; + } + + public String reqAPI(String api, Map params) throws NacosException { + + List snapshot = serversFromEndpoint; + if (!CollectionUtils.isEmpty(serverList)) { + snapshot = serverList; + } + + return reqAPI(api, params, snapshot); + } + + public String reqAPI(String api, Map params, String method) + throws NacosException { + + List snapshot = serversFromEndpoint; + if (!CollectionUtils.isEmpty(serverList)) { + snapshot = serverList; + } + + return reqAPI(api, params, snapshot, method); + } + + public String callServer(String api, Map params, String curServer) + throws NacosException { + return callServer(api, params, curServer, HttpMethod.GET); + } + + public String callServer(String api, Map params, String curServer, + String method) throws NacosException { + long start = System.currentTimeMillis(); + long end = 0; + + List headers = Arrays.asList("Client-Version", UtilAndComs.VERSION, + "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 + + serverPort; + } + + url = HttpClient.getPrefix() + curServer + api; + + HttpClient.HttpResult result = HttpClient.request(url, headers, params, + UtilAndComs.ENCODING, method); + end = System.currentTimeMillis(); + + MetricsMonitor.getNamingRequestMonitor(method, url, String.valueOf(result.code)) + .record(end - start, TimeUnit.MILLISECONDS); + + if (HttpURLConnection.HTTP_OK == result.code) { + return result.content; + } + + if (HttpURLConnection.HTTP_NOT_MODIFIED == result.code) { + return StringUtils.EMPTY; + } + + 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); + } + + public String reqAPI(String api, Map params, List servers) { + return reqAPI(api, params, servers, HttpMethod.GET); + } + + public String reqAPI(String api, Map params, List 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"); + } - } + if (servers != null && !servers.isEmpty()) { - public String getNamespaceId() { - return namespaceId; - } + Random random = new Random(System.currentTimeMillis()); + int index = random.nextInt(servers.size()); + + for (int i = 0; i < servers.size(); i++) { + String server = servers.get(index); + try { + return callServer(api, params, server, method); + } catch (Exception 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"); + } + + 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); + } + } + + throw new IllegalStateException("failed to req API:/api/" + api + + " after all servers(" + servers + ") tried"); + + } + + public String getNamespaceId() { + return namespaceId; + } } diff --git a/cmdb/pom.xml b/cmdb/pom.xml index 102cbe3e0..296525236 100644 --- a/cmdb/pom.xml +++ b/cmdb/pom.xml @@ -18,7 +18,7 @@ nacos-all com.alibaba.nacos - 0.8.0-SNAPSHOT + 0.8.1-SNAPSHOT ../pom.xml 4.0.0 diff --git a/common/pom.xml b/common/pom.xml index f90047d07..26a060ede 100644 --- a/common/pom.xml +++ b/common/pom.xml @@ -18,7 +18,7 @@ com.alibaba.nacos nacos-all - 0.8.0-SNAPSHOT + 0.8.1-SNAPSHOT ../pom.xml 4.0.0 diff --git a/config/pom.xml b/config/pom.xml index cdc571f91..1bd258b13 100644 --- a/config/pom.xml +++ b/config/pom.xml @@ -17,7 +17,7 @@ com.alibaba.nacos nacos-all - 0.8.0-SNAPSHOT + 0.8.1-SNAPSHOT 4.0.0 diff --git a/console/pom.xml b/console/pom.xml index 64e3e13d3..aa22c6427 100644 --- a/console/pom.xml +++ b/console/pom.xml @@ -18,7 +18,7 @@ com.alibaba.nacos nacos-all - 0.8.0-SNAPSHOT + 0.8.1-SNAPSHOT nacos-console diff --git a/core/pom.xml b/core/pom.xml index 92bc6f271..4f1b6e50e 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -18,7 +18,7 @@ com.alibaba.nacos nacos-all - 0.8.0-SNAPSHOT + 0.8.1-SNAPSHOT ../pom.xml diff --git a/distribution/pom.xml b/distribution/pom.xml index 5baca6981..6730bc2e1 100644 --- a/distribution/pom.xml +++ b/distribution/pom.xml @@ -18,7 +18,7 @@ com.alibaba.nacos nacos-all - 0.8.0-SNAPSHOT + 0.8.1-SNAPSHOT ../pom.xml diff --git a/example/pom.xml b/example/pom.xml index d377f76e5..efd6f6bb0 100644 --- a/example/pom.xml +++ b/example/pom.xml @@ -18,7 +18,7 @@ com.alibaba.nacos nacos-all - 0.8.0-SNAPSHOT + 0.8.1-SNAPSHOT ../pom.xml diff --git a/naming/pom.xml b/naming/pom.xml index 4a1eb8388..c97192ff6 100644 --- a/naming/pom.xml +++ b/naming/pom.xml @@ -18,7 +18,7 @@ com.alibaba.nacos nacos-all - 0.8.0-SNAPSHOT + 0.8.1-SNAPSHOT ../pom.xml diff --git a/pom.xml b/pom.xml index f25e46102..61c8211ed 100644 --- a/pom.xml +++ b/pom.xml @@ -21,7 +21,7 @@ 2018 com.alibaba.nacos nacos-all - 0.8.0-SNAPSHOT + 0.8.1-SNAPSHOT pom Alibaba NACOS ${project.version} @@ -742,5 +742,6 @@ + diff --git a/test/pom.xml b/test/pom.xml index 3d9792707..bbc26eea7 100644 --- a/test/pom.xml +++ b/test/pom.xml @@ -17,7 +17,7 @@ com.alibaba.nacos nacos-all - 0.8.0-SNAPSHOT + 0.8.1-SNAPSHOT ../pom.xml 4.0.0 From 451863fe338b574323af60f153f2c68f24ed2b6a Mon Sep 17 00:00:00 2001 From: nkorange Date: Fri, 15 Feb 2019 11:54:10 +0800 Subject: [PATCH 04/12] Update version to 0.8.1 --- api/pom.xml | 2 +- client/pom.xml | 2 +- cmdb/pom.xml | 2 +- common/pom.xml | 2 +- config/pom.xml | 2 +- console/pom.xml | 2 +- core/pom.xml | 2 +- distribution/pom.xml | 2 +- example/pom.xml | 2 +- naming/pom.xml | 2 +- pom.xml | 2 +- test/pom.xml | 2 +- 12 files changed, 12 insertions(+), 12 deletions(-) diff --git a/api/pom.xml b/api/pom.xml index 087585e06..e6bdf1cbc 100644 --- a/api/pom.xml +++ b/api/pom.xml @@ -16,7 +16,7 @@ com.alibaba.nacos nacos-all - 0.8.1-SNAPSHOT + 0.8.1 4.0.0 diff --git a/client/pom.xml b/client/pom.xml index 1c91f29f1..985aea31f 100644 --- a/client/pom.xml +++ b/client/pom.xml @@ -16,7 +16,7 @@ com.alibaba.nacos nacos-all - 0.8.1-SNAPSHOT + 0.8.1 ../pom.xml diff --git a/cmdb/pom.xml b/cmdb/pom.xml index 296525236..5d9559847 100644 --- a/cmdb/pom.xml +++ b/cmdb/pom.xml @@ -18,7 +18,7 @@ nacos-all com.alibaba.nacos - 0.8.1-SNAPSHOT + 0.8.1 ../pom.xml 4.0.0 diff --git a/common/pom.xml b/common/pom.xml index 26a060ede..df2b4235d 100644 --- a/common/pom.xml +++ b/common/pom.xml @@ -18,7 +18,7 @@ com.alibaba.nacos nacos-all - 0.8.1-SNAPSHOT + 0.8.1 ../pom.xml 4.0.0 diff --git a/config/pom.xml b/config/pom.xml index 1bd258b13..69d4fcc42 100644 --- a/config/pom.xml +++ b/config/pom.xml @@ -17,7 +17,7 @@ com.alibaba.nacos nacos-all - 0.8.1-SNAPSHOT + 0.8.1 4.0.0 diff --git a/console/pom.xml b/console/pom.xml index aa22c6427..98c747899 100644 --- a/console/pom.xml +++ b/console/pom.xml @@ -18,7 +18,7 @@ com.alibaba.nacos nacos-all - 0.8.1-SNAPSHOT + 0.8.1 nacos-console diff --git a/core/pom.xml b/core/pom.xml index 4f1b6e50e..791a42bed 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -18,7 +18,7 @@ com.alibaba.nacos nacos-all - 0.8.1-SNAPSHOT + 0.8.1 ../pom.xml diff --git a/distribution/pom.xml b/distribution/pom.xml index 6730bc2e1..f0f45cfb6 100644 --- a/distribution/pom.xml +++ b/distribution/pom.xml @@ -18,7 +18,7 @@ com.alibaba.nacos nacos-all - 0.8.1-SNAPSHOT + 0.8.1 ../pom.xml diff --git a/example/pom.xml b/example/pom.xml index efd6f6bb0..f2e2f093f 100644 --- a/example/pom.xml +++ b/example/pom.xml @@ -18,7 +18,7 @@ com.alibaba.nacos nacos-all - 0.8.1-SNAPSHOT + 0.8.1 ../pom.xml diff --git a/naming/pom.xml b/naming/pom.xml index c97192ff6..cc71eafa4 100644 --- a/naming/pom.xml +++ b/naming/pom.xml @@ -18,7 +18,7 @@ com.alibaba.nacos nacos-all - 0.8.1-SNAPSHOT + 0.8.1 ../pom.xml diff --git a/pom.xml b/pom.xml index 61c8211ed..cc10b6c53 100644 --- a/pom.xml +++ b/pom.xml @@ -21,7 +21,7 @@ 2018 com.alibaba.nacos nacos-all - 0.8.1-SNAPSHOT + 0.8.1 pom Alibaba NACOS ${project.version} diff --git a/test/pom.xml b/test/pom.xml index bbc26eea7..b1cfa4e20 100644 --- a/test/pom.xml +++ b/test/pom.xml @@ -17,7 +17,7 @@ com.alibaba.nacos nacos-all - 0.8.1-SNAPSHOT + 0.8.1 ../pom.xml 4.0.0 From b3ee9698fac319660334f96a6929e2e53e896c6b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=97=E5=B0=91?= <314226532@qq.com> Date: Fri, 22 Feb 2019 17:06:02 +0800 Subject: [PATCH 05/12] #817 --- api/pom.xml | 2 +- .../alibaba/nacos/api/PropertyKeyConst.java | 4 --- .../nacos/api/SystemPropertyKeyConst.java | 31 +++++++++++++++++++ client/pom.xml | 2 +- .../client/naming/NacosNamingService.java | 3 +- .../nacos/client/naming/net/NamingProxy.java | 8 +++-- cmdb/pom.xml | 2 +- common/pom.xml | 2 +- config/pom.xml | 2 +- console/pom.xml | 2 +- core/pom.xml | 2 +- distribution/pom.xml | 2 +- example/pom.xml | 2 +- naming/pom.xml | 2 +- pom.xml | 2 +- test/pom.xml | 2 +- 16 files changed, 50 insertions(+), 20 deletions(-) create mode 100644 api/src/main/java/com/alibaba/nacos/api/SystemPropertyKeyConst.java diff --git a/api/pom.xml b/api/pom.xml index e6bdf1cbc..84ac061a2 100644 --- a/api/pom.xml +++ b/api/pom.xml @@ -16,7 +16,7 @@ com.alibaba.nacos nacos-all - 0.8.1 + 0.8.2 4.0.0 diff --git a/api/src/main/java/com/alibaba/nacos/api/PropertyKeyConst.java b/api/src/main/java/com/alibaba/nacos/api/PropertyKeyConst.java index 2b689cd31..a0095c04a 100644 --- a/api/src/main/java/com/alibaba/nacos/api/PropertyKeyConst.java +++ b/api/src/main/java/com/alibaba/nacos/api/PropertyKeyConst.java @@ -22,10 +22,6 @@ 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"; diff --git a/api/src/main/java/com/alibaba/nacos/api/SystemPropertyKeyConst.java b/api/src/main/java/com/alibaba/nacos/api/SystemPropertyKeyConst.java new file mode 100644 index 000000000..f74d5d7c8 --- /dev/null +++ b/api/src/main/java/com/alibaba/nacos/api/SystemPropertyKeyConst.java @@ -0,0 +1,31 @@ +/* + * 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.api; + +/** + * Properties that are preferred to which in {@link PropertyKeyConst} + * + * @author pbting + * @date 2019-02-22 3:38 PM + */ +public interface SystemPropertyKeyConst { + + String NAMING_SERVER_PORT = "nacos.naming.exposed.port"; + + String NAMING_WEB_CONTEXT = "nacos.naming.web.context"; + + String NACOS_NAMING_MODE = "nacos.naming.mode"; +} diff --git a/client/pom.xml b/client/pom.xml index 985aea31f..0e0906fb5 100644 --- a/client/pom.xml +++ b/client/pom.xml @@ -16,7 +16,7 @@ com.alibaba.nacos nacos-all - 0.8.1 + 0.8.2 ../pom.xml diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/NacosNamingService.java b/client/src/main/java/com/alibaba/nacos/client/naming/NacosNamingService.java index 905c557a6..14fbd8953 100644 --- a/client/src/main/java/com/alibaba/nacos/client/naming/NacosNamingService.java +++ b/client/src/main/java/com/alibaba/nacos/client/naming/NacosNamingService.java @@ -16,6 +16,7 @@ package com.alibaba.nacos.client.naming; import com.alibaba.nacos.api.PropertyKeyConst; +import com.alibaba.nacos.api.SystemPropertyKeyConst; import com.alibaba.nacos.api.common.Constants; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.NamingService; @@ -154,7 +155,7 @@ public class NacosNamingService implements NamingService { private void initWebRootContext() { // support the web context with ali-yun if the app deploy by EDAS - String webContext = System.getProperties().getProperty(PropertyKeyConst.WEB_CONTEXT); + String webContext = System.getProperties().getProperty(SystemPropertyKeyConst.NAMING_WEB_CONTEXT); if (StringUtils.isNotEmpty(webContext)) { UtilAndComs.WEB_CONTEXT = webContext.indexOf("/") > -1 ? webContext : "/" + webContext; diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/net/NamingProxy.java b/client/src/main/java/com/alibaba/nacos/client/naming/net/NamingProxy.java index a3f0c30e1..5fac17a96 100644 --- a/client/src/main/java/com/alibaba/nacos/client/naming/net/NamingProxy.java +++ b/client/src/main/java/com/alibaba/nacos/client/naming/net/NamingProxy.java @@ -18,7 +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.SystemPropertyKeyConst; import com.alibaba.nacos.api.common.Constants; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.pojo.Instance; @@ -82,7 +82,7 @@ public class NamingProxy { } } - String serverPort = System.getProperties().getProperty(PropertyKeyConst.SERVER_PORT); + String serverPort = System.getProperties().getProperty(SystemPropertyKeyConst.NAMING_SERVER_PORT); if (StringUtils.isNotEmpty(serverPort)) { this.serverPort = Integer.valueOf(serverPort.trim()); } @@ -116,9 +116,11 @@ public class NamingProxy { try { String urlString = "http://" + endpoint + "/nacos/serverlist"; + String nacosNamingMode = System.getProperty(SystemPropertyKeyConst.NACOS_NAMING_MODE, "Naming"); + List headers = Arrays.asList("Client-Version", UtilAndComs.VERSION, "Accept-Encoding", "gzip,deflate,sdch", "Connection", "Keep-Alive", - "RequestId", UuidUtils.generateUuid()); + "RequestId", UuidUtils.generateUuid(), "Request-Module", nacosNamingMode); HttpClient.HttpResult result = HttpClient.httpGet(urlString, headers, null, UtilAndComs.ENCODING); diff --git a/cmdb/pom.xml b/cmdb/pom.xml index 5d9559847..86c4ad234 100644 --- a/cmdb/pom.xml +++ b/cmdb/pom.xml @@ -18,7 +18,7 @@ nacos-all com.alibaba.nacos - 0.8.1 + 0.8.2 ../pom.xml 4.0.0 diff --git a/common/pom.xml b/common/pom.xml index df2b4235d..452a50aad 100644 --- a/common/pom.xml +++ b/common/pom.xml @@ -18,7 +18,7 @@ com.alibaba.nacos nacos-all - 0.8.1 + 0.8.2 ../pom.xml 4.0.0 diff --git a/config/pom.xml b/config/pom.xml index 69d4fcc42..c6a8ba969 100644 --- a/config/pom.xml +++ b/config/pom.xml @@ -17,7 +17,7 @@ com.alibaba.nacos nacos-all - 0.8.1 + 0.8.2 4.0.0 diff --git a/console/pom.xml b/console/pom.xml index 98c747899..69b131510 100644 --- a/console/pom.xml +++ b/console/pom.xml @@ -18,7 +18,7 @@ com.alibaba.nacos nacos-all - 0.8.1 + 0.8.2 nacos-console diff --git a/core/pom.xml b/core/pom.xml index 791a42bed..d85d662ac 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -18,7 +18,7 @@ com.alibaba.nacos nacos-all - 0.8.1 + 0.8.2 ../pom.xml diff --git a/distribution/pom.xml b/distribution/pom.xml index f0f45cfb6..8e160bf28 100644 --- a/distribution/pom.xml +++ b/distribution/pom.xml @@ -18,7 +18,7 @@ com.alibaba.nacos nacos-all - 0.8.1 + 0.8.2 ../pom.xml diff --git a/example/pom.xml b/example/pom.xml index f2e2f093f..447aa45c6 100644 --- a/example/pom.xml +++ b/example/pom.xml @@ -18,7 +18,7 @@ com.alibaba.nacos nacos-all - 0.8.1 + 0.8.2 ../pom.xml diff --git a/naming/pom.xml b/naming/pom.xml index cc71eafa4..e5a4da900 100644 --- a/naming/pom.xml +++ b/naming/pom.xml @@ -18,7 +18,7 @@ com.alibaba.nacos nacos-all - 0.8.1 + 0.8.2 ../pom.xml diff --git a/pom.xml b/pom.xml index cc10b6c53..072bfc237 100644 --- a/pom.xml +++ b/pom.xml @@ -21,7 +21,7 @@ 2018 com.alibaba.nacos nacos-all - 0.8.1 + 0.8.2 pom Alibaba NACOS ${project.version} diff --git a/test/pom.xml b/test/pom.xml index b1cfa4e20..dbfd8baf8 100644 --- a/test/pom.xml +++ b/test/pom.xml @@ -17,7 +17,7 @@ com.alibaba.nacos nacos-all - 0.8.1 + 0.8.2 ../pom.xml 4.0.0 From e916431d65886546b39fe2172fcac47ac97d4b0e Mon Sep 17 00:00:00 2001 From: pbting <314226532@qq.com> Date: Fri, 22 Feb 2019 17:43:28 +0800 Subject: [PATCH 06/12] Update SystemPropertyKeyConst.java --- .../main/java/com/alibaba/nacos/api/SystemPropertyKeyConst.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/api/src/main/java/com/alibaba/nacos/api/SystemPropertyKeyConst.java b/api/src/main/java/com/alibaba/nacos/api/SystemPropertyKeyConst.java index f74d5d7c8..4b41e6c8a 100644 --- a/api/src/main/java/com/alibaba/nacos/api/SystemPropertyKeyConst.java +++ b/api/src/main/java/com/alibaba/nacos/api/SystemPropertyKeyConst.java @@ -27,5 +27,5 @@ public interface SystemPropertyKeyConst { String NAMING_WEB_CONTEXT = "nacos.naming.web.context"; - String NACOS_NAMING_MODE = "nacos.naming.mode"; + String NACOS_NAMING_REQUEST_MODULE = "nacos.naming.request.module"; } From f5d27829013a824196fd015e62c83e1cd57e2fc2 Mon Sep 17 00:00:00 2001 From: pbting <314226532@qq.com> Date: Fri, 22 Feb 2019 17:43:54 +0800 Subject: [PATCH 07/12] Update NamingProxy.java --- .../java/com/alibaba/nacos/client/naming/net/NamingProxy.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/net/NamingProxy.java b/client/src/main/java/com/alibaba/nacos/client/naming/net/NamingProxy.java index 5fac17a96..8c09966e0 100644 --- a/client/src/main/java/com/alibaba/nacos/client/naming/net/NamingProxy.java +++ b/client/src/main/java/com/alibaba/nacos/client/naming/net/NamingProxy.java @@ -116,7 +116,7 @@ public class NamingProxy { try { String urlString = "http://" + endpoint + "/nacos/serverlist"; - String nacosNamingMode = System.getProperty(SystemPropertyKeyConst.NACOS_NAMING_MODE, "Naming"); + String nacosNamingMode = System.getProperty(SystemPropertyKeyConst.NACOS_NAMING_REQUEST_MODULE, "Naming"); List headers = Arrays.asList("Client-Version", UtilAndComs.VERSION, "Accept-Encoding", "gzip,deflate,sdch", "Connection", "Keep-Alive", From df15d56018bec1f1e852c5a966f64b2f07d022e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=97=E5=B0=91?= <314226532@qq.com> Date: Mon, 4 Mar 2019 17:09:09 +0800 Subject: [PATCH 08/12] constract error message will transfor to pararent construct --- .../java/com/alibaba/nacos/api/exception/NacosException.java | 1 + 1 file changed, 1 insertion(+) diff --git a/api/src/main/java/com/alibaba/nacos/api/exception/NacosException.java b/api/src/main/java/com/alibaba/nacos/api/exception/NacosException.java index 1bbd56dc9..aab756e60 100644 --- a/api/src/main/java/com/alibaba/nacos/api/exception/NacosException.java +++ b/api/src/main/java/com/alibaba/nacos/api/exception/NacosException.java @@ -35,6 +35,7 @@ public class NacosException extends Exception { } public NacosException(int errCode, String errMsg) { + super(errMsg); this.errCode = errCode; this.errMsg = errMsg; } From 1869bea58f007211a9082239c02b5161693c3ac9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=97=E5=B0=91?= <314226532@qq.com> Date: Mon, 4 Mar 2019 18:50:35 +0800 Subject: [PATCH 09/12] format log --- .../nacos/client/identify/CredentialWatcher.java | 15 ++++++++------- .../nacos/client/naming/net/NamingProxy.java | 14 +++++++------- 2 files changed, 15 insertions(+), 14 deletions(-) diff --git a/client/src/main/java/com/alibaba/nacos/client/identify/CredentialWatcher.java b/client/src/main/java/com/alibaba/nacos/client/identify/CredentialWatcher.java index 83050aea3..e0258de52 100644 --- a/client/src/main/java/com/alibaba/nacos/client/identify/CredentialWatcher.java +++ b/client/src/main/java/com/alibaba/nacos/client/identify/CredentialWatcher.java @@ -109,12 +109,13 @@ public class CredentialWatcher { : appName); } else { if (logWarn) { - SpasLogger.info(appName, "Defined credential file: -D" + "spas.identity" + "=" + propertyPath); + SpasLogger.info("[{}] Defined credential file: -Dspas.identity={}", appName, propertyPath); } } } else { if (logWarn) { - SpasLogger.info(appName, "Load credential file from classpath: " + Constants.PROPERTIES_FILENAME); + SpasLogger.info("[{}] Load credential file from classpath: {}", appName, + Constants.PROPERTIES_FILENAME); } } } @@ -155,7 +156,7 @@ public class CredentialWatcher { try { properties.load(propertiesIS); } catch (IOException e) { - SpasLogger.error("26", "Unable to load credential file, appName:" + appName + SpasLogger.error("[26] Unable to load credential file, appName:" + appName + "Unable to load credential file " + propertyPath, e); propertyPath = null; return; @@ -163,13 +164,13 @@ public class CredentialWatcher { try { propertiesIS.close(); } catch (IOException e) { - SpasLogger.error("27", "Unable to close credential file, appName:" + appName + 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); + SpasLogger.info("[{}] Load credential file {}", appName, propertyPath); } if (!Constants.DOCKER_CREDENTIAL_PATH.equals(propertyPath)) { @@ -209,8 +210,8 @@ public class CredentialWatcher { 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); + SpasLogger.warn("[1] Credential file missing required property {} Credential file missing {} or {}", + appName, Constants.ACCESS_KEY, Constants.SECRET_KEY); propertyPath = null; // return; } diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/net/NamingProxy.java b/client/src/main/java/com/alibaba/nacos/client/naming/net/NamingProxy.java index c829405fb..f9ab6b49a 100644 --- a/client/src/main/java/com/alibaba/nacos/client/naming/net/NamingProxy.java +++ b/client/src/main/java/com/alibaba/nacos/client/naming/net/NamingProxy.java @@ -156,7 +156,7 @@ public class NamingProxy { } if (!CollectionUtils.isEqualCollection(list, serversFromEndpoint)) { - NAMING_LOGGER.info("SERVER-LIST", "server list is updated: " + list); + NAMING_LOGGER.info("[SERVER-LIST] server list is updated: " + list); } serversFromEndpoint = list; @@ -168,7 +168,7 @@ public class NamingProxy { public void registerService(String serviceName, Instance instance) throws NacosException { - NAMING_LOGGER.info("REGISTER-SERVICE", "{} registering service {} with instance: {}", + NAMING_LOGGER.info("[REGISTER-SERVICE] {} registering service {} with instance: {}", namespaceId, serviceName, instance); final Map params = new HashMap(8); @@ -188,7 +188,7 @@ public class NamingProxy { public void deregisterService(String serviceName, String ip, int port, String cluster) throws NacosException { - NAMING_LOGGER.info("DEREGISTER-SERVICE", "{} deregistering service {} with instance: {}:{}@{}", + NAMING_LOGGER.info("[DEREGISTER-SERVICE] {} deregistering service {} with instance: {}:{}@{}", namespaceId, serviceName, ip, port, cluster); final Map params = new HashMap(8); @@ -217,7 +217,7 @@ public class NamingProxy { public long sendBeat(BeatInfo beatInfo) { try { - NAMING_LOGGER.info("BEAT", "{} sending beat to server: {}", namespaceId, beatInfo.toString()); + NAMING_LOGGER.info("[BEAT] {} sending beat to server: {}", namespaceId, beatInfo.toString()); Map params = new HashMap(4); params.put("beat", JSON.toJSONString(beatInfo)); params.put(Constants.REQUEST_PARAM_NAMESPACE_ID, namespaceId); @@ -334,7 +334,7 @@ public class NamingProxy { return StringUtils.EMPTY; } - NAMING_LOGGER.error("CALL-SERVER", "failed to req API:" + HttpClient.getPrefix() + curServer + NAMING_LOGGER.error("[CALL-SERVER] failed to req API:" + HttpClient.getPrefix() + curServer + api + ". code:" + result.code + " msg: " + result.content); @@ -365,7 +365,7 @@ public class NamingProxy { try { return callServer(api, params, server, method); } catch (Exception e) { - NAMING_LOGGER.error("NA", "req api:" + api + " failed, server(" + server, e); + NAMING_LOGGER.error("[NA] req api:" + api + " failed, server(" + server, e); } index = (index + 1) % servers.size(); @@ -378,7 +378,7 @@ public class NamingProxy { try { return callServer(api, params, nacosDomain); } catch (Exception e) { - NAMING_LOGGER.error("NA", "req api:" + api + " failed, server(" + nacosDomain, e); + NAMING_LOGGER.error("[NA] req api:" + api + " failed, server(" + nacosDomain, e); } } From 0774cb23d48d37d674fc606fd5b4707c6767677b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=97=E5=B0=91?= <314226532@qq.com> Date: Mon, 4 Mar 2019 19:15:04 +0800 Subject: [PATCH 10/12] format log --- .../alibaba/nacos/client/identify/CredentialWatcher.java | 4 ++-- .../com/alibaba/nacos/client/naming/net/HttpClient.java | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/client/src/main/java/com/alibaba/nacos/client/identify/CredentialWatcher.java b/client/src/main/java/com/alibaba/nacos/client/identify/CredentialWatcher.java index e0258de52..47c39b6e3 100644 --- a/client/src/main/java/com/alibaba/nacos/client/identify/CredentialWatcher.java +++ b/client/src/main/java/com/alibaba/nacos/client/identify/CredentialWatcher.java @@ -31,7 +31,7 @@ import java.util.TimerTask; * @author Nacos */ public class CredentialWatcher { - static final public Logger SpasLogger = LogUtils.logger(CredentialWatcher.class); + private static final Logger SpasLogger = LogUtils.logger(CredentialWatcher.class); private static final long REFRESH_INTERVAL = 10 * 1000; private CredentialService serviceInstance; @@ -147,7 +147,7 @@ public class CredentialWatcher { secretKey = System.getenv(Constants.ENV_SECRET_KEY); if (accessKey == null && secretKey == null) { if (logWarn) { - SpasLogger.info(appName, "No credential found"); + SpasLogger.info("{} No credential found", appName); } return; } diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/net/HttpClient.java b/client/src/main/java/com/alibaba/nacos/client/naming/net/HttpClient.java index f98fcdd8f..4386d5631 100644 --- a/client/src/main/java/com/alibaba/nacos/client/naming/net/HttpClient.java +++ b/client/src/main/java/com/alibaba/nacos/client/naming/net/HttpClient.java @@ -92,7 +92,7 @@ public class HttpClient { try { if (conn != null) { NAMING_LOGGER.warn("failed to request " + conn.getURL() + " from " - + InetAddress.getByName(conn.getURL().getHost()).getHostAddress()); + + InetAddress.getByName(conn.getURL().getHost()).getHostAddress()); } } catch (Exception e1) { NAMING_LOGGER.error("[NA] failed to request ", e1); @@ -114,7 +114,7 @@ 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(); @@ -165,12 +165,12 @@ public class HttpClient { } conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" - + encoding); + + encoding); conn.addRequestProperty("Accept-Charset", encoding); } private static String encodingParams(Map params, String encoding) - throws UnsupportedEncodingException { + throws UnsupportedEncodingException { if (null == params || params.isEmpty()) { return null; } From a05be5f97be12d7a8638d3d5cacff22f6a0623ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=97=E5=B0=91?= <314226532@qq.com> Date: Mon, 4 Mar 2019 19:23:11 +0800 Subject: [PATCH 11/12] log format --- .../java/com/alibaba/nacos/client/naming/net/NamingProxy.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/net/NamingProxy.java b/client/src/main/java/com/alibaba/nacos/client/naming/net/NamingProxy.java index f9ab6b49a..c7f8a3c25 100644 --- a/client/src/main/java/com/alibaba/nacos/client/naming/net/NamingProxy.java +++ b/client/src/main/java/com/alibaba/nacos/client/naming/net/NamingProxy.java @@ -229,7 +229,7 @@ public class NamingProxy { return jsonObject.getLong("clientBeatInterval"); } } catch (Exception e) { - NAMING_LOGGER.error("CLIENT-BEAT", "failed to send beat: " + JSON.toJSONString(beatInfo), e); + NAMING_LOGGER.error("[CLIENT-BEAT] failed to send beat: " + JSON.toJSONString(beatInfo), e); } return 0L; } From a9ff49692f2316ebce9a639a3c85de04c06750f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=97=E5=B0=91?= <314226532@qq.com> Date: Tue, 5 Mar 2019 10:08:28 +0800 Subject: [PATCH 12/12] Optimize code design --- .../client/config/impl/ServerListManager.java | 8 ++--- .../client/naming/NacosNamingService.java | 30 +++++++++---------- .../nacos/client/utils/TemplateUtils.java | 12 ++++++++ 3 files changed, 28 insertions(+), 22 deletions(-) diff --git a/client/src/main/java/com/alibaba/nacos/client/config/impl/ServerListManager.java b/client/src/main/java/com/alibaba/nacos/client/config/impl/ServerListManager.java index eefdd3368..838af5183 100644 --- a/client/src/main/java/com/alibaba/nacos/client/config/impl/ServerListManager.java +++ b/client/src/main/java/com/alibaba/nacos/client/config/impl/ServerListManager.java @@ -20,11 +20,7 @@ import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.client.config.impl.EventDispatcher.ServerlistChangeEvent; import com.alibaba.nacos.client.config.impl.HttpSimpleClient.HttpResult; import com.alibaba.nacos.client.config.utils.IOUtils; -import com.alibaba.nacos.client.utils.TemplateUtils; -import com.alibaba.nacos.client.utils.EnvUtil; -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.*; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.slf4j.Logger; @@ -171,7 +167,7 @@ public class ServerListManager { private String initEndpoint(String endpointTmp) { String endpointPortTmp = System.getenv(PropertyKeyConst.SystemEnv.ALIBABA_ALIWARE_ENDPOINT_PORT); - if (StringUtils.isNotEmpty(endpointPortTmp)) { + if (StringUtils.isNotBlank(endpointPortTmp)) { endpointPort = Integer.parseInt(endpointPortTmp); } diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/NacosNamingService.java b/client/src/main/java/com/alibaba/nacos/client/naming/NacosNamingService.java index 3ebda5f2f..0b5266efa 100644 --- a/client/src/main/java/com/alibaba/nacos/client/naming/NacosNamingService.java +++ b/client/src/main/java/com/alibaba/nacos/client/naming/NacosNamingService.java @@ -97,11 +97,11 @@ public class NacosNamingService implements NamingService { eventDispatcher = new EventDispatcher(); serverProxy = new NamingProxy(namespace, endpoint, serverList); serverProxy.setProperties(properties); - beatReactor = new BeatReactor(serverProxy, clientBeatThreadCount(properties)); - hostReactor = new HostReactor(eventDispatcher, serverProxy, cacheDir, isLoadCacheAtStart(properties), pollingThreadCount(properties)); + beatReactor = new BeatReactor(serverProxy, initClientBeatThreadCount(properties)); + hostReactor = new HostReactor(eventDispatcher, serverProxy, cacheDir, isLoadCacheAtStart(properties), initPollingThreadCount(properties)); } - private int clientBeatThreadCount(Properties properties) { + private int initClientBeatThreadCount(Properties properties) { if (properties == null) { return UtilAndComs.DEFAULT_CLIENT_BEAT_THREAD_COUNT; @@ -113,7 +113,7 @@ public class NacosNamingService implements NamingService { return clientBeatThreadCount; } - private int pollingThreadCount(Properties properties) { + private int initPollingThreadCount(Properties properties) { if (properties == null) { return UtilAndComs.DEFAULT_POLLING_THREAD_COUNT; @@ -234,19 +234,17 @@ public class NacosNamingService implements NamingService { private void initWebRootContext() { // support the web context with ali-yun if the app deploy by EDAS - String webContext = System.getProperty(SystemPropertyKeyConst.NAMING_WEB_CONTEXT); - boolean isSetting = false; - if (StringUtils.isNotEmpty(webContext)) { - UtilAndComs.WEB_CONTEXT = webContext.indexOf("/") > -1 ? webContext - : "/" + webContext; + 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; - isSetting = true; - } - - if (isSetting) { - UtilAndComs.NACOS_URL_BASE = UtilAndComs.WEB_CONTEXT + "/v1/ns"; - UtilAndComs.NACOS_URL_INSTANCE = UtilAndComs.NACOS_URL_BASE + "/instance"; - } + UtilAndComs.NACOS_URL_BASE = UtilAndComs.WEB_CONTEXT + "/v1/ns"; + UtilAndComs.NACOS_URL_INSTANCE = UtilAndComs.NACOS_URL_BASE + "/instance"; + } + }); } @Override diff --git a/client/src/main/java/com/alibaba/nacos/client/utils/TemplateUtils.java b/client/src/main/java/com/alibaba/nacos/client/utils/TemplateUtils.java index 890fd5d66..7e2384473 100644 --- a/client/src/main/java/com/alibaba/nacos/client/utils/TemplateUtils.java +++ b/client/src/main/java/com/alibaba/nacos/client/utils/TemplateUtils.java @@ -23,6 +23,18 @@ import java.util.concurrent.Callable; */ public class TemplateUtils { + public static final void stringNotEmptyAndThenExecute(String source, Runnable runnable) { + + if (StringUtils.isNotEmpty(source)) { + + try { + runnable.run(); + } catch (Exception e) { + LogUtils.NAMING_LOGGER.error("string empty and then execute cause an exception.", e); + } + } + } + public static final String stringEmptyAndThenExecute(String source, Callable callable) { if (StringUtils.isEmpty(source)) {