CLUSTER: Communication between servers in a cluster.
+ *
+ *
+ * @author stone-98
+ * @date 2023/12/23
+ */
+public enum CommunicationType {
+ /**
+ * Communication between SDK and servers.
+ */
+ SDK("sdk"),
+ /**
+ * Communication between servers in a cluster.
+ */
+ CLUSTER("cluster");
+
+ private final String type;
+
+ CommunicationType(String type) {
+ this.type = type;
+ }
+
+ public String getType() {
+ return type;
+ }
+}
+
diff --git a/common/src/main/java/com/alibaba/nacos/common/remote/client/RpcClientFactory.java b/common/src/main/java/com/alibaba/nacos/common/remote/client/RpcClientFactory.java
index 6d850568e3c..5b7c5a4c96c 100644
--- a/common/src/main/java/com/alibaba/nacos/common/remote/client/RpcClientFactory.java
+++ b/common/src/main/java/com/alibaba/nacos/common/remote/client/RpcClientFactory.java
@@ -76,7 +76,7 @@ public static RpcClient createClient(String clientName, ConnectionType connectio
}
public static RpcClient createClient(String clientName, ConnectionType connectionType, Map labels,
- RpcClientTlsConfig tlsConfig) {
+ RpcSdkClientTlsConfig tlsConfig) {
return createClient(clientName, connectionType, null, null, labels, tlsConfig);
}
@@ -97,7 +97,7 @@ public static RpcClient createClient(String clientName, ConnectionType connectio
* @return rpc client.
*/
public static RpcClient createClient(String clientName, ConnectionType connectionType, Integer threadPoolCoreSize,
- Integer threadPoolMaxSize, Map labels, RpcClientTlsConfig tlsConfig) {
+ Integer threadPoolMaxSize, Map labels, RpcSdkClientTlsConfig tlsConfig) {
if (!ConnectionType.GRPC.equals(connectionType)) {
throw new UnsupportedOperationException("unsupported connection type :" + connectionType.getType());
@@ -110,30 +110,41 @@ public static RpcClient createClient(String clientName, ConnectionType connectio
}
/**
- * create a rpc client.
+ * Creates an RPC client for cluster communication with default thread pool settings.
*
- * @param clientName client name.
- * @param connectionType client type.
- * @return rpc client.
+ * @param clientName The name of the client.
+ * @param connectionType The type of client connection.
+ * @param labels Additional labels for RPC-related attributes.
+ * @return An RPC client for cluster communication.
*/
public static RpcClient createClusterClient(String clientName, ConnectionType connectionType,
Map labels) {
return createClusterClient(clientName, connectionType, null, null, labels);
}
+ /**
+ * Creates an RPC client for cluster communication with TLS configuration.
+ *
+ * @param clientName The name of the client.
+ * @param connectionType The type of client connection.
+ * @param labels Additional labels for RPC-related attributes.
+ * @param tlsConfig TLS configuration for secure communication.
+ * @return An RPC client for cluster communication with TLS configuration.
+ */
public static RpcClient createClusterClient(String clientName, ConnectionType connectionType,
- Map labels, RpcClientTlsConfig tlsConfig) {
+ Map labels, RpcClusterClientTlsConfig tlsConfig) {
return createClusterClient(clientName, connectionType, null, null, labels, tlsConfig);
}
/**
- * create a rpc client.
+ * Creates an RPC client for cluster communication with custom thread pool settings.
*
- * @param clientName client name.
- * @param connectionType client type.
- * @param threadPoolCoreSize grpc thread pool core size
- * @param threadPoolMaxSize grpc thread pool max size
- * @return rpc client.
+ * @param clientName The name of the client.
+ * @param connectionType The type of client connection.
+ * @param threadPoolCoreSize The core size of the gRPC thread pool.
+ * @param threadPoolMaxSize The maximum size of the gRPC thread pool.
+ * @param labels Additional labels for RPC-related attributes.
+ * @return An RPC client for cluster communication with custom thread pool settings.
*/
public static RpcClient createClusterClient(String clientName, ConnectionType connectionType,
Integer threadPoolCoreSize, Integer threadPoolMaxSize, Map labels) {
@@ -151,10 +162,9 @@ public static RpcClient createClusterClient(String clientName, ConnectionType co
* @param tlsConfig tlsConfig.
* @return
*/
-
public static RpcClient createClusterClient(String clientName, ConnectionType connectionType,
Integer threadPoolCoreSize, Integer threadPoolMaxSize, Map labels,
- RpcClientTlsConfig tlsConfig) {
+ RpcClusterClientTlsConfig tlsConfig) {
if (!ConnectionType.GRPC.equals(connectionType)) {
throw new UnsupportedOperationException("unsupported connection type :" + connectionType.getType());
}
diff --git a/common/src/main/java/com/alibaba/nacos/common/remote/client/RpcClusterClientTlsConfig.java b/common/src/main/java/com/alibaba/nacos/common/remote/client/RpcClusterClientTlsConfig.java
new file mode 100644
index 00000000000..cccf9949ada
--- /dev/null
+++ b/common/src/main/java/com/alibaba/nacos/common/remote/client/RpcClusterClientTlsConfig.java
@@ -0,0 +1,105 @@
+/*
+ * Copyright 1999-2023 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.alibaba.nacos.common.remote.client;
+
+import com.alibaba.nacos.common.remote.TlsConfig;
+import com.alibaba.nacos.common.utils.StringUtils;
+
+/**
+ * RPC Cluster Client TLS Configuration for Nacos.
+ *
+ * This class extends the {@link TlsConfig} class and provides a convenient way to create a configuration instance
+ * specifically for the RPC (Remote Procedure Call) cluster client in Nacos.
+ *
+ *
+ * To configure RPC cluster client TLS settings, you can use the following system properties:
+ *
+ *
+ *
{@code nacos.remote.cluster.client.rpc.tls.enable}: Enable or disable TLS. Default is {@code false}.
+ *
{@code nacos.remote.cluster.client.rpc.tls.Provider}: Specify the SSL provider.
+ *
{@code nacos.remote.cluster.client.rpc.tls.mutualAuth}: Enable or disable mutual authentication. Default is {@code false}.
+ *
{@code nacos.remote.cluster.client.rpc.tls.protocols}: Specify the TLS protocols.
+ *
{@code nacos.remote.cluster.client.rpc.tls.ciphers}: Specify the TLS ciphers.
+ *
{@code nacos.remote.cluster.client.rpc.tls.certChainFile}: Specify the path to the certificate chain file.
+ *
{@code nacos.remote.cluster.client.rpc.tls.certPrivateKey}: Specify the path to the certificate private key file.
+ *
{@code nacos.remote.cluster.client.rpc.tls.certPrivateKeyPassword}: Specify the password for the certificate private key.
+ *
{@code nacos.remote.cluster.client.rpc.tls.trustCollectionCertFile}: Specify the path to the trust collection chain file.
+ *
{@code nacos.remote.cluster.client.rpc.tls.trustAll}: Enable or disable trusting all certificates. Default is {@code false}.
+ *
+ *
+ * @author stone-98
+ * @date 2023/12/20
+ */
+public class RpcClusterClientTlsConfig extends TlsConfig {
+
+ /**
+ * Creates a new instance of {@link RpcClusterClientTlsConfig} by loading TLS configuration from system properties.
+ *
+ * @return A new instance of {@link RpcClusterClientTlsConfig} with loaded TLS configuration.
+ */
+ public static RpcClusterClientTlsConfig createConfig() {
+ RpcClusterClientTlsConfig tlsConfig = new RpcClusterClientTlsConfig();
+ tlsConfig.setEnableTls(Boolean.getBoolean(RpcConstants.RPC_CLUSTER_CLIENT_TLS_ENABLE));
+ if (!Boolean.getBoolean(RpcConstants.RPC_CLUSTER_CLIENT_TLS_ENABLE)) {
+ return tlsConfig;
+ }
+
+ String sslProvider = System.getProperty(RpcConstants.RPC_CLUSTER_CLIENT_TLS_PROVIDER);
+ if (StringUtils.isNotBlank(sslProvider)) {
+ tlsConfig.setSslProvider(sslProvider);
+ }
+
+ boolean mutualAuth = Boolean.getBoolean(RpcConstants.RPC_CLUSTER_CLIENT_MUTUAL_AUTH);
+ tlsConfig.setMutualAuthEnable(mutualAuth);
+
+ String protocols = System.getProperty(RpcConstants.RPC_CLUSTER_CLIENT_TLS_PROTOCOLS);
+ if (StringUtils.isNotBlank(protocols)) {
+ tlsConfig.setProtocols(protocols);
+ }
+
+ String ciphers = System.getProperty(RpcConstants.RPC_CLUSTER_CLIENT_TLS_CIPHERS);
+ if (StringUtils.isNotBlank(ciphers)) {
+ tlsConfig.setCiphers(ciphers);
+ }
+
+ String certChain = System.getProperty(RpcConstants.RPC_CLUSTER_CLIENT_TLS_CERT_CHAIN_PATH);
+ if (StringUtils.isNotBlank(ciphers)) {
+ tlsConfig.setCertChainFile(certChain);
+ }
+
+ String certPrivateKey = System.getProperty(RpcConstants.RPC_CLUSTER_CLIENT_TLS_CERT_KEY);
+ if (StringUtils.isNotBlank(certPrivateKey)) {
+ tlsConfig.setCertPrivateKey(certPrivateKey);
+ }
+
+ String certPrivateKeyPassword = System.getProperty(RpcConstants.RPC_CLUSTER_CLIENT_TLS_TRUST_PWD);
+ if (StringUtils.isNotBlank(certPrivateKeyPassword)) {
+ tlsConfig.setCertPrivateKeyPassword(certPrivateKeyPassword);
+ }
+
+ String trustCollectionCertFile = System.getProperty(
+ RpcConstants.RPC_CLUSTER_CLIENT_TLS_TRUST_COLLECTION_CHAIN_PATH);
+ if (StringUtils.isNotBlank(trustCollectionCertFile)) {
+ tlsConfig.setTrustCollectionCertFile(trustCollectionCertFile);
+ }
+
+ boolean trustAll = Boolean.getBoolean(RpcConstants.RPC_CLUSTER_CLIENT_TLS_TRUST_ALL);
+ tlsConfig.setTrustAll(trustAll);
+
+ return tlsConfig;
+ }
+}
diff --git a/common/src/main/java/com/alibaba/nacos/common/remote/client/RpcConstants.java b/common/src/main/java/com/alibaba/nacos/common/remote/client/RpcConstants.java
index 0b0f40762b6..eb7320a21be 100644
--- a/common/src/main/java/com/alibaba/nacos/common/remote/client/RpcConstants.java
+++ b/common/src/main/java/com/alibaba/nacos/common/remote/client/RpcConstants.java
@@ -35,62 +35,202 @@ public class RpcConstants {
public static final String NACOS_CLIENT_RPC = "nacos.remote.client.rpc";
+ public static final String NACOS_CLUSTER_CLIENT_RPC = "nacos.remote.cluster.client.rpc";
+
@RpcConfigLabel
- public static final String RPC_CLIENT_TLS_ENABLE = NACOS_CLIENT_RPC + ".tls.enable";
+ public static final String RPC_CLIENT_TLS_ENABLE = getConfigKey(RpcConfigSuffix.TLS_ENABLE);
@RpcConfigLabel
- public static final String RPC_CLIENT_TLS_PROVIDER = NACOS_CLIENT_RPC + ".tls.provider";
+ public static final String RPC_CLIENT_TLS_PROVIDER = getConfigKey(RpcConfigSuffix.TLS_PROVIDER);
@RpcConfigLabel
- public static final String RPC_CLIENT_MUTUAL_AUTH = NACOS_CLIENT_RPC + ".tls.mutualAuth";
+ public static final String RPC_CLIENT_MUTUAL_AUTH = getConfigKey(RpcConfigSuffix.MUTUAL_AUTH);
@RpcConfigLabel
- public static final String RPC_CLIENT_TLS_PROTOCOLS = NACOS_CLIENT_RPC + ".tls.protocols";
+ public static final String RPC_CLIENT_TLS_PROTOCOLS = getConfigKey(RpcConfigSuffix.TLS_PROTOCOLS);
@RpcConfigLabel
- public static final String RPC_CLIENT_TLS_CIPHERS = NACOS_CLIENT_RPC + ".tls.ciphers";
+ public static final String RPC_CLIENT_TLS_CIPHERS = getConfigKey(RpcConfigSuffix.TLS_CIPHERS);
@RpcConfigLabel
- public static final String RPC_CLIENT_TLS_CERT_CHAIN_PATH = NACOS_CLIENT_RPC + ".tls.certChainFile";
+ public static final String RPC_CLIENT_TLS_CERT_CHAIN_PATH = getConfigKey(RpcConfigSuffix.TLS_CERT_CHAIN_PATH);
@RpcConfigLabel
- public static final String RPC_CLIENT_TLS_CERT_KEY = NACOS_CLIENT_RPC + ".tls.certPrivateKey";
+ public static final String RPC_CLIENT_TLS_CERT_KEY = getConfigKey(RpcConfigSuffix.TLS_CERT_KEY);
@RpcConfigLabel
- public static final String RPC_CLIENT_TLS_TRUST_PWD = NACOS_CLIENT_RPC + ".tls.certPrivateKeyPassword";
+ public static final String RPC_CLIENT_TLS_TRUST_PWD = getConfigKey(RpcConfigSuffix.TLS_TRUST_PWD);
@RpcConfigLabel
- public static final String RPC_CLIENT_TLS_TRUST_COLLECTION_CHAIN_PATH =
- NACOS_CLIENT_RPC + ".tls.trustCollectionChainPath";
+ public static final String RPC_CLIENT_TLS_TRUST_COLLECTION_CHAIN_PATH = getConfigKey(
+ RpcConfigSuffix.TLS_TRUST_COLLECTION_CHAIN_PATH);
@RpcConfigLabel
- public static final String RPC_CLIENT_TLS_TRUST_ALL = NACOS_CLIENT_RPC + ".tls.trustAll";
+ public static final String RPC_CLIENT_TLS_TRUST_ALL = getConfigKey(RpcConfigSuffix.TLS_TRUST_ALL);
private static final Set CONFIG_NAMES = new HashSet<>();
- @Documented
- @Target(ElementType.FIELD)
- @Retention(RetentionPolicy.RUNTIME)
- protected @interface RpcConfigLabel {
+ @RpcClusterConfigLabel
+ public static final String RPC_CLUSTER_CLIENT_TLS_ENABLE = getClusterConfigKey(RpcConfigSuffix.TLS_ENABLE);
- }
+ @RpcClusterConfigLabel
+ public static final String RPC_CLUSTER_CLIENT_TLS_PROVIDER = getClusterConfigKey(RpcConfigSuffix.TLS_PROVIDER);
+
+ @RpcClusterConfigLabel
+ public static final String RPC_CLUSTER_CLIENT_MUTUAL_AUTH = getClusterConfigKey(RpcConfigSuffix.MUTUAL_AUTH);
+
+ @RpcClusterConfigLabel
+ public static final String RPC_CLUSTER_CLIENT_TLS_PROTOCOLS = getClusterConfigKey(RpcConfigSuffix.TLS_PROTOCOLS);
+
+ @RpcClusterConfigLabel
+ public static final String RPC_CLUSTER_CLIENT_TLS_CIPHERS = getClusterConfigKey(RpcConfigSuffix.TLS_CIPHERS);
+
+ @RpcClusterConfigLabel
+ public static final String RPC_CLUSTER_CLIENT_TLS_CERT_CHAIN_PATH = getClusterConfigKey(
+ RpcConfigSuffix.TLS_CERT_CHAIN_PATH);
+
+ @RpcClusterConfigLabel
+ public static final String RPC_CLUSTER_CLIENT_TLS_CERT_KEY = getClusterConfigKey(RpcConfigSuffix.TLS_CERT_KEY);
+
+ @RpcClusterConfigLabel
+ public static final String RPC_CLUSTER_CLIENT_TLS_TRUST_PWD = getClusterConfigKey(RpcConfigSuffix.TLS_TRUST_PWD);
+
+ @RpcClusterConfigLabel
+ public static final String RPC_CLUSTER_CLIENT_TLS_TRUST_COLLECTION_CHAIN_PATH = getClusterConfigKey(
+ RpcConfigSuffix.TLS_TRUST_COLLECTION_CHAIN_PATH);
+
+ @RpcClusterConfigLabel
+ public static final String RPC_CLUSTER_CLIENT_TLS_TRUST_ALL = getClusterConfigKey(RpcConfigSuffix.TLS_TRUST_ALL);
+
+ private static final Set CLUSTER_CONFIG_NAMES = new HashSet<>();
static {
Class clazz = RpcConstants.class;
Field[] declaredFields = clazz.getDeclaredFields();
for (Field declaredField : declaredFields) {
declaredField.setAccessible(true);
- if (declaredField.getType().equals(String.class) && null != declaredField
- .getAnnotation(RpcConfigLabel.class)) {
+ if (!declaredField.getType().equals(String.class)) {
+ continue;
+ }
+ if (null != declaredField.getAnnotation(RpcConfigLabel.class)) {
try {
CONFIG_NAMES.add((String) declaredField.get(null));
} catch (IllegalAccessException ignored) {
}
+ } else if (null != declaredField.getAnnotation(RpcClusterConfigLabel.class)) {
+ try {
+ CLUSTER_CONFIG_NAMES.add((String) declaredField.get(null));
+ } catch (IllegalAccessException ignored) {
+ }
}
}
}
+ public static String getConfigKey(RpcConfigSuffix configSuffix) {
+ return NACOS_CLIENT_RPC + configSuffix.getSuffix();
+ }
+
+ public static String getClusterConfigKey(RpcConfigSuffix configSuffix) {
+ return NACOS_CLUSTER_CLIENT_RPC + configSuffix.getSuffix();
+ }
+
+ /**
+ * Enumeration of common suffixes for RPC configuration properties. Each enum constant represents a specific
+ * configuration attribute suffix. This allows for the construction of complete configuration property keys.
+ */
+ public enum RpcConfigSuffix {
+
+ /**
+ * Suffix for 'tls.enable' configuration property.
+ */
+ TLS_ENABLE(".tls.enable"),
+
+ /**
+ * Suffix for 'tls.provider' configuration property.
+ */
+ TLS_PROVIDER(".tls.provider"),
+
+ /**
+ * Suffix for 'tls.mutualAuth' configuration property.
+ */
+ MUTUAL_AUTH(".tls.mutualAuth"),
+
+ /**
+ * Suffix for 'tls.protocols' configuration property.
+ */
+ TLS_PROTOCOLS(".tls.protocols"),
+
+ /**
+ * Suffix for 'tls.ciphers' configuration property.
+ */
+ TLS_CIPHERS(".tls.ciphers"),
+
+ /**
+ * Suffix for 'tls.certChainFile' configuration property.
+ */
+ TLS_CERT_CHAIN_PATH(".tls.certChainFile"),
+
+ /**
+ * Suffix for 'tls.certPrivateKey' configuration property.
+ */
+ TLS_CERT_KEY(".tls.certPrivateKey"),
+
+ /**
+ * Suffix for 'tls.certPrivateKeyPassword' configuration property.
+ */
+ TLS_TRUST_PWD(".tls.certPrivateKeyPassword"),
+
+ /**
+ * Suffix for 'tls.trustCollectionChainPath' configuration property.
+ */
+ TLS_TRUST_COLLECTION_CHAIN_PATH(".tls.trustCollectionChainPath"),
+
+ /**
+ * Suffix for 'tls.trustAll' configuration property.
+ */
+ TLS_TRUST_ALL(".tls.trustAll");
+
+ private final String suffix;
+
+ /**
+ * Constructor for RpcConfigSuffix enumeration.
+ *
+ * @param suffix The configuration attribute suffix.
+ */
+ RpcConfigSuffix(String suffix) {
+ this.suffix = suffix;
+ }
+
+ /**
+ * Retrieve the configuration attribute suffix.
+ *
+ * @return The configuration attribute suffix.
+ */
+ public String getSuffix() {
+ return suffix;
+ }
+ }
+
+
+ @Documented
+ @Target(ElementType.FIELD)
+ @Retention(RetentionPolicy.RUNTIME)
+ protected @interface RpcConfigLabel {
+
+ }
+
+ @Documented
+ @Target(ElementType.FIELD)
+ @Retention(RetentionPolicy.RUNTIME)
+ protected @interface RpcClusterConfigLabel {
+
+ }
+
public static Set getRpcParams() {
return Collections.unmodifiableSet(CONFIG_NAMES);
}
+
+ public static Set getClusterRpcParams() {
+ return Collections.unmodifiableSet(CLUSTER_CONFIG_NAMES);
+ }
}
diff --git a/common/src/main/java/com/alibaba/nacos/common/remote/client/RpcClientTlsConfig.java b/common/src/main/java/com/alibaba/nacos/common/remote/client/RpcSdkClientTlsConfig.java
similarity index 75%
rename from common/src/main/java/com/alibaba/nacos/common/remote/client/RpcClientTlsConfig.java
rename to common/src/main/java/com/alibaba/nacos/common/remote/client/RpcSdkClientTlsConfig.java
index 61b847e98ac..e72d69c0651 100644
--- a/common/src/main/java/com/alibaba/nacos/common/remote/client/RpcClientTlsConfig.java
+++ b/common/src/main/java/com/alibaba/nacos/common/remote/client/RpcSdkClientTlsConfig.java
@@ -25,61 +25,57 @@
*
* @author githubcheng2978
*/
-public class RpcClientTlsConfig extends TlsConfig {
-
+public class RpcSdkClientTlsConfig extends TlsConfig {
+
/**
- * get tls config from properties.
- * @param properties Properties.
+ * get tls config from properties.
+ *
+ * @param properties Properties.
* @return tls of config.
*/
- public static RpcClientTlsConfig properties(Properties properties) {
- RpcClientTlsConfig tlsConfig = new RpcClientTlsConfig();
+ public static RpcSdkClientTlsConfig properties(Properties properties) {
+ RpcSdkClientTlsConfig tlsConfig = new RpcSdkClientTlsConfig();
if (properties.containsKey(RpcConstants.RPC_CLIENT_TLS_ENABLE)) {
- tlsConfig.setEnableTls(Boolean.parseBoolean(
- properties.getProperty(RpcConstants.RPC_CLIENT_TLS_ENABLE)));
- }
-
- if (properties.containsKey(RpcConstants.RPC_CLIENT_TLS_PROVIDER)) {
- tlsConfig.setSslProvider(properties.getProperty(RpcConstants.RPC_CLIENT_TLS_PROVIDER));
+ tlsConfig.setEnableTls(Boolean.parseBoolean(properties.getProperty(RpcConstants.RPC_CLIENT_TLS_ENABLE)));
}
-
+
if (properties.containsKey(RpcConstants.RPC_CLIENT_MUTUAL_AUTH)) {
- tlsConfig.setMutualAuthEnable(Boolean.parseBoolean(
- properties.getProperty(RpcConstants.RPC_CLIENT_MUTUAL_AUTH)));
+ tlsConfig.setMutualAuthEnable(
+ Boolean.parseBoolean(properties.getProperty(RpcConstants.RPC_CLIENT_MUTUAL_AUTH)));
}
-
+
if (properties.containsKey(RpcConstants.RPC_CLIENT_TLS_PROTOCOLS)) {
tlsConfig.setProtocols(properties.getProperty(RpcConstants.RPC_CLIENT_TLS_PROTOCOLS));
}
-
+
if (properties.containsKey(RpcConstants.RPC_CLIENT_TLS_CIPHERS)) {
tlsConfig.setCiphers(properties.getProperty(RpcConstants.RPC_CLIENT_TLS_CIPHERS));
}
-
+
if (properties.containsKey(RpcConstants.RPC_CLIENT_TLS_TRUST_COLLECTION_CHAIN_PATH)) {
- tlsConfig.setTrustCollectionCertFile(properties.getProperty(RpcConstants.RPC_CLIENT_TLS_TRUST_COLLECTION_CHAIN_PATH));
+ tlsConfig.setTrustCollectionCertFile(
+ properties.getProperty(RpcConstants.RPC_CLIENT_TLS_TRUST_COLLECTION_CHAIN_PATH));
}
-
+
if (properties.containsKey(RpcConstants.RPC_CLIENT_TLS_CERT_CHAIN_PATH)) {
tlsConfig.setCertChainFile(properties.getProperty(RpcConstants.RPC_CLIENT_TLS_CERT_CHAIN_PATH));
}
-
+
if (properties.containsKey(RpcConstants.RPC_CLIENT_TLS_CERT_KEY)) {
tlsConfig.setCertPrivateKey(properties.getProperty(RpcConstants.RPC_CLIENT_TLS_CERT_KEY));
}
-
+
if (properties.containsKey(RpcConstants.RPC_CLIENT_TLS_TRUST_ALL)) {
tlsConfig.setTrustAll(Boolean.parseBoolean(properties.getProperty(RpcConstants.RPC_CLIENT_TLS_TRUST_ALL)));
}
-
+
if (properties.containsKey(RpcConstants.RPC_CLIENT_TLS_TRUST_PWD)) {
tlsConfig.setCertPrivateKeyPassword(properties.getProperty(RpcConstants.RPC_CLIENT_TLS_TRUST_PWD));
}
-
+
if (properties.containsKey(RpcConstants.RPC_CLIENT_TLS_PROVIDER)) {
tlsConfig.setSslProvider(properties.getProperty(RpcConstants.RPC_CLIENT_TLS_PROVIDER));
}
return tlsConfig;
}
-
}
diff --git a/common/src/main/java/com/alibaba/nacos/common/remote/client/grpc/DefaultGrpcClientConfig.java b/common/src/main/java/com/alibaba/nacos/common/remote/client/grpc/DefaultGrpcClientConfig.java
index cf6ac4787e5..72188dae1a4 100644
--- a/common/src/main/java/com/alibaba/nacos/common/remote/client/grpc/DefaultGrpcClientConfig.java
+++ b/common/src/main/java/com/alibaba/nacos/common/remote/client/grpc/DefaultGrpcClientConfig.java
@@ -16,7 +16,8 @@
package com.alibaba.nacos.common.remote.client.grpc;
-import com.alibaba.nacos.common.remote.client.RpcClientTlsConfig;
+import com.alibaba.nacos.common.remote.TlsConfig;
+import com.alibaba.nacos.common.remote.client.RpcSdkClientTlsConfig;
import com.alibaba.nacos.common.utils.ThreadUtils;
import java.util.HashMap;
@@ -32,39 +33,39 @@
*/
public class DefaultGrpcClientConfig implements GrpcClientConfig {
- private String name;
+ private final String name;
- private int retryTimes;
+ private final int retryTimes;
- private long timeOutMills;
+ private final long timeOutMills;
- private long connectionKeepAlive;
+ private final long connectionKeepAlive;
- private long channelKeepAliveTimeout;
+ private final long channelKeepAliveTimeout;
- private long threadPoolKeepAlive;
+ private final long threadPoolKeepAlive;
- private int threadPoolCoreSize;
+ private final int threadPoolCoreSize;
- private int threadPoolMaxSize;
+ private final int threadPoolMaxSize;
- private long serverCheckTimeOut;
+ private final long serverCheckTimeOut;
- private int threadPoolQueueSize;
+ private final int threadPoolQueueSize;
- private int maxInboundMessageSize;
+ private final int maxInboundMessageSize;
- private int channelKeepAlive;
+ private final int channelKeepAlive;
- private int healthCheckRetryTimes;
+ private final int healthCheckRetryTimes;
- private long healthCheckTimeOut;
+ private final long healthCheckTimeOut;
- private long capabilityNegotiationTimeout;
+ private final long capabilityNegotiationTimeout;
- private Map labels;
+ private final Map labels;
- private RpcClientTlsConfig tlsConfig = new RpcClientTlsConfig();
+ private TlsConfig tlsConfig = new TlsConfig();
/**
* constructor.
@@ -173,11 +174,11 @@ public long channelKeepAliveTimeout() {
}
@Override
- public RpcClientTlsConfig tlsConfig() {
+ public TlsConfig tlsConfig() {
return tlsConfig;
}
- public void setTlsConfig(RpcClientTlsConfig tlsConfig) {
+ public void setTlsConfig(TlsConfig tlsConfig) {
this.tlsConfig = tlsConfig;
}
@@ -237,9 +238,9 @@ public static class Builder {
private long capabilityNegotiationTimeout = 5000L;
- private Map labels = new HashMap<>();
+ private final Map labels = new HashMap<>();
- private RpcClientTlsConfig tlsConfig = new RpcClientTlsConfig();
+ private TlsConfig tlsConfig = new TlsConfig();
private Builder() {
}
@@ -261,53 +262,53 @@ public Builder fromProperties(Properties properties) {
this.timeOutMills = Long.parseLong(properties.getProperty(GrpcConstants.GRPC_TIMEOUT_MILLS));
}
if (properties.containsKey(GrpcConstants.GRPC_CONNECT_KEEP_ALIVE_TIME)) {
- this.connectionKeepAlive = Long
- .parseLong(properties.getProperty(GrpcConstants.GRPC_CONNECT_KEEP_ALIVE_TIME));
+ this.connectionKeepAlive = Long.parseLong(
+ properties.getProperty(GrpcConstants.GRPC_CONNECT_KEEP_ALIVE_TIME));
}
if (properties.containsKey(GrpcConstants.GRPC_THREADPOOL_KEEPALIVETIME)) {
- this.threadPoolKeepAlive = Long
- .parseLong(properties.getProperty(GrpcConstants.GRPC_THREADPOOL_KEEPALIVETIME));
+ this.threadPoolKeepAlive = Long.parseLong(
+ properties.getProperty(GrpcConstants.GRPC_THREADPOOL_KEEPALIVETIME));
}
if (properties.containsKey(GrpcConstants.GRPC_THREADPOOL_CORE_SIZE)) {
- this.threadPoolCoreSize = Integer
- .parseInt(properties.getProperty(GrpcConstants.GRPC_THREADPOOL_CORE_SIZE));
+ this.threadPoolCoreSize = Integer.parseInt(
+ properties.getProperty(GrpcConstants.GRPC_THREADPOOL_CORE_SIZE));
}
if (properties.containsKey(GrpcConstants.GRPC_THREADPOOL_MAX_SIZE)) {
- this.threadPoolMaxSize = Integer
- .parseInt(properties.getProperty(GrpcConstants.GRPC_THREADPOOL_MAX_SIZE));
+ this.threadPoolMaxSize = Integer.parseInt(
+ properties.getProperty(GrpcConstants.GRPC_THREADPOOL_MAX_SIZE));
}
if (properties.containsKey(GrpcConstants.GRPC_SERVER_CHECK_TIMEOUT)) {
- this.serverCheckTimeOut = Long
- .parseLong(properties.getProperty(GrpcConstants.GRPC_SERVER_CHECK_TIMEOUT));
+ this.serverCheckTimeOut = Long.parseLong(
+ properties.getProperty(GrpcConstants.GRPC_SERVER_CHECK_TIMEOUT));
}
if (properties.containsKey(GrpcConstants.GRPC_QUEUESIZE)) {
this.threadPoolQueueSize = Integer.parseInt(properties.getProperty(GrpcConstants.GRPC_QUEUESIZE));
}
if (properties.containsKey(GrpcConstants.GRPC_MAX_INBOUND_MESSAGE_SIZE)) {
- this.maxInboundMessageSize = Integer
- .parseInt(properties.getProperty(GrpcConstants.GRPC_MAX_INBOUND_MESSAGE_SIZE));
+ this.maxInboundMessageSize = Integer.parseInt(
+ properties.getProperty(GrpcConstants.GRPC_MAX_INBOUND_MESSAGE_SIZE));
}
if (properties.containsKey(GrpcConstants.GRPC_CHANNEL_KEEP_ALIVE_TIME)) {
- this.channelKeepAlive = Integer
- .parseInt(properties.getProperty(GrpcConstants.GRPC_CHANNEL_KEEP_ALIVE_TIME));
+ this.channelKeepAlive = Integer.parseInt(
+ properties.getProperty(GrpcConstants.GRPC_CHANNEL_KEEP_ALIVE_TIME));
}
if (properties.containsKey(GrpcConstants.GRPC_CHANNEL_CAPABILITY_NEGOTIATION_TIMEOUT)) {
- this.capabilityNegotiationTimeout = Integer
- .parseInt(properties.getProperty(GrpcConstants.GRPC_CHANNEL_CAPABILITY_NEGOTIATION_TIMEOUT));
+ this.capabilityNegotiationTimeout = Integer.parseInt(
+ properties.getProperty(GrpcConstants.GRPC_CHANNEL_CAPABILITY_NEGOTIATION_TIMEOUT));
}
if (properties.containsKey(GrpcConstants.GRPC_HEALTHCHECK_RETRY_TIMES)) {
- this.healthCheckRetryTimes = Integer
- .parseInt(properties.getProperty(GrpcConstants.GRPC_HEALTHCHECK_RETRY_TIMES));
+ this.healthCheckRetryTimes = Integer.parseInt(
+ properties.getProperty(GrpcConstants.GRPC_HEALTHCHECK_RETRY_TIMES));
}
if (properties.containsKey(GrpcConstants.GRPC_HEALTHCHECK_TIMEOUT)) {
- this.healthCheckTimeOut = Long
- .parseLong(properties.getProperty(GrpcConstants.GRPC_HEALTHCHECK_TIMEOUT));
+ this.healthCheckTimeOut = Long.parseLong(
+ properties.getProperty(GrpcConstants.GRPC_HEALTHCHECK_TIMEOUT));
}
if (properties.containsKey(GrpcConstants.GRPC_CHANNEL_KEEP_ALIVE_TIMEOUT)) {
- this.channelKeepAliveTimeout = Integer
- .parseInt(properties.getProperty(GrpcConstants.GRPC_CHANNEL_KEEP_ALIVE_TIMEOUT));
+ this.channelKeepAliveTimeout = Integer.parseInt(
+ properties.getProperty(GrpcConstants.GRPC_CHANNEL_KEEP_ALIVE_TIMEOUT));
}
- this.tlsConfig = RpcClientTlsConfig.properties(properties);
+ this.tlsConfig = RpcSdkClientTlsConfig.properties(properties);
return this;
}
@@ -449,7 +450,7 @@ public Builder setLabels(Map labels) {
* @param tlsConfig tls of client.
* @return
*/
- public Builder setTlsConfig(RpcClientTlsConfig tlsConfig) {
+ public Builder setTlsConfig(TlsConfig tlsConfig) {
this.tlsConfig = tlsConfig;
return this;
}
diff --git a/common/src/main/java/com/alibaba/nacos/common/remote/client/grpc/GrpcClient.java b/common/src/main/java/com/alibaba/nacos/common/remote/client/grpc/GrpcClient.java
index 25d213cb951..ff81cc2322f 100644
--- a/common/src/main/java/com/alibaba/nacos/common/remote/client/grpc/GrpcClient.java
+++ b/common/src/main/java/com/alibaba/nacos/common/remote/client/grpc/GrpcClient.java
@@ -33,10 +33,10 @@
import com.alibaba.nacos.common.ability.discover.NacosAbilityManagerHolder;
import com.alibaba.nacos.common.packagescan.resource.Resource;
import com.alibaba.nacos.common.remote.ConnectionType;
+import com.alibaba.nacos.common.remote.TlsConfig;
import com.alibaba.nacos.common.remote.client.Connection;
import com.alibaba.nacos.common.remote.client.RpcClient;
import com.alibaba.nacos.common.remote.client.RpcClientStatus;
-import com.alibaba.nacos.common.remote.client.RpcClientTlsConfig;
import com.alibaba.nacos.common.remote.client.ServerListFactory;
import com.alibaba.nacos.common.remote.client.ServerRequestHandler;
import com.alibaba.nacos.common.utils.JacksonUtils;
@@ -163,7 +163,7 @@ public GrpcClient(String name, Integer threadPoolCoreSize, Integer threadPoolMax
}
public GrpcClient(String name, Integer threadPoolCoreSize, Integer threadPoolMaxSize, Map labels,
- RpcClientTlsConfig tlsConfig) {
+ TlsConfig tlsConfig) {
this(DefaultGrpcClientConfig.newBuilder().setName(name).setThreadPoolCoreSize(threadPoolCoreSize)
.setTlsConfig(tlsConfig).setThreadPoolMaxSize(threadPoolMaxSize).setLabels(labels).build());
}
@@ -209,8 +209,8 @@ protected RequestGrpc.RequestFutureStub createNewChannelStub(ManagedChannel mana
private ManagedChannel createNewManagedChannel(String serverIp, int serverPort) {
LOGGER.info("grpc client connection server:{} ip,serverPort:{},grpcTslConfig:{}", serverIp, serverPort,
JacksonUtils.toJson(clientConfig.tlsConfig()));
- ManagedChannelBuilder> managedChannelBuilder = buildChannel(serverIp, serverPort, buildSslContext())
- .executor(grpcExecutor).compressorRegistry(CompressorRegistry.getDefaultInstance())
+ ManagedChannelBuilder> managedChannelBuilder = buildChannel(serverIp, serverPort, buildSslContext()).executor(
+ grpcExecutor).compressorRegistry(CompressorRegistry.getDefaultInstance())
.decompressorRegistry(DecompressorRegistry.getDefaultInstance())
.maxInboundMessageSize(clientConfig.maxInboundMessageSize())
.keepAliveTime(clientConfig.channelKeepAlive(), TimeUnit.MILLISECONDS)
@@ -288,8 +288,8 @@ public void onNext(Payload payload) {
} catch (Exception e) {
LoggerUtils.printIfErrorEnabled(LOGGER, "[{}]Handle server request exception: {}",
grpcConn.getConnectionId(), payload.toString(), e.getMessage());
- Response errResponse = ErrorResponse
- .build(NacosException.CLIENT_ERROR, "Handle server request error");
+ Response errResponse = ErrorResponse.build(NacosException.CLIENT_ERROR,
+ "Handle server request error");
errResponse.setRequestId(request.getRequestId());
sendResponse(errResponse);
}
@@ -374,8 +374,8 @@ public Connection connectToServer(ServerInfo serverInfo) {
ServerCheckResponse serverCheckResponse = (ServerCheckResponse) response;
connectionId = serverCheckResponse.getConnectionId();
- BiRequestStreamGrpc.BiRequestStreamStub biRequestStreamStub = BiRequestStreamGrpc
- .newStub(newChannelStubTemp.getChannel());
+ BiRequestStreamGrpc.BiRequestStreamStub biRequestStreamStub = BiRequestStreamGrpc.newStub(
+ newChannelStubTemp.getChannel());
GrpcConnection grpcConn = new GrpcConnection(serverInfo, grpcExecutor);
grpcConn.setConnectionId(connectionId);
// if not supported, it will be false
@@ -398,8 +398,8 @@ public Connection connectToServer(ServerInfo serverInfo) {
conSetupRequest.setClientVersion(VersionUtils.getFullClientVersion());
conSetupRequest.setLabels(super.getLabels());
// set ability table
- conSetupRequest
- .setAbilityTable(NacosAbilityManagerHolder.getInstance().getCurrentNodeAbilities(abilityMode()));
+ conSetupRequest.setAbilityTable(
+ NacosAbilityManagerHolder.getInstance().getCurrentNodeAbilities(abilityMode()));
conSetupRequest.setTenant(super.getTenant());
grpcConn.sendRequest(conSetupRequest);
// wait for response
@@ -531,44 +531,9 @@ public boolean check(Connection connection) {
}
}
- /**
- * Setup response handler.
- */
- class SetupRequestHandler implements ServerRequestHandler {
-
- private final RecAbilityContext abilityContext;
-
- public SetupRequestHandler(RecAbilityContext abilityContext) {
- this.abilityContext = abilityContext;
- }
-
- @Override
- public Response requestReply(Request request, Connection connection) {
- // if finish setup
- if (request instanceof SetupAckRequest) {
- SetupAckRequest setupAckRequest = (SetupAckRequest) request;
- // remove and count down
- recAbilityContext
- .release(Optional.ofNullable(setupAckRequest.getAbilityTable()).orElse(new HashMap<>(0)));
- return new SetupAckResponse();
- }
- return null;
- }
- }
-
- private ManagedChannelBuilder buildChannel(String serverIp, int port, Optional sslContext) {
- if (sslContext.isPresent()) {
- return NettyChannelBuilder.forAddress(serverIp, port).negotiationType(NegotiationType.TLS)
- .sslContext(sslContext.get());
-
- } else {
- return ManagedChannelBuilder.forAddress(serverIp, port).usePlaintext();
- }
- }
-
private Optional buildSslContext() {
- RpcClientTlsConfig tlsConfig = clientConfig.tlsConfig();
+ TlsConfig tlsConfig = clientConfig.tlsConfig();
if (!tlsConfig.getEnableTls()) {
return Optional.empty();
}
@@ -595,8 +560,8 @@ private Optional buildSslContext() {
}
if (tlsConfig.getMutualAuthEnable()) {
- if (StringUtils.isBlank(tlsConfig.getCertChainFile()) || StringUtils
- .isBlank(tlsConfig.getCertPrivateKey())) {
+ if (StringUtils.isBlank(tlsConfig.getCertChainFile()) || StringUtils.isBlank(
+ tlsConfig.getCertPrivateKey())) {
throw new IllegalArgumentException("client certChainFile or certPrivateKey must be not null");
}
Resource certChainFile = resourceLoader.getResource(tlsConfig.getCertChainFile());
@@ -609,6 +574,41 @@ private Optional buildSslContext() {
throw new RuntimeException("Unable to build SslContext", e);
}
}
+
+ private ManagedChannelBuilder buildChannel(String serverIp, int port, Optional sslContext) {
+ if (sslContext.isPresent()) {
+ return NettyChannelBuilder.forAddress(serverIp, port).negotiationType(NegotiationType.TLS)
+ .sslContext(sslContext.get());
+
+ } else {
+ return ManagedChannelBuilder.forAddress(serverIp, port).usePlaintext();
+ }
+ }
+
+ /**
+ * Setup response handler.
+ */
+ class SetupRequestHandler implements ServerRequestHandler {
+
+ private final RecAbilityContext abilityContext;
+
+ public SetupRequestHandler(RecAbilityContext abilityContext) {
+ this.abilityContext = abilityContext;
+ }
+
+ @Override
+ public Response requestReply(Request request, Connection connection) {
+ // if finish setup
+ if (request instanceof SetupAckRequest) {
+ SetupAckRequest setupAckRequest = (SetupAckRequest) request;
+ // remove and count down
+ recAbilityContext.release(
+ Optional.ofNullable(setupAckRequest.getAbilityTable()).orElse(new HashMap<>(0)));
+ return new SetupAckResponse();
+ }
+ return null;
+ }
+ }
}
diff --git a/common/src/main/java/com/alibaba/nacos/common/remote/client/grpc/GrpcClientConfig.java b/common/src/main/java/com/alibaba/nacos/common/remote/client/grpc/GrpcClientConfig.java
index 1c1b4003bad..42b8199a7ae 100644
--- a/common/src/main/java/com/alibaba/nacos/common/remote/client/grpc/GrpcClientConfig.java
+++ b/common/src/main/java/com/alibaba/nacos/common/remote/client/grpc/GrpcClientConfig.java
@@ -16,8 +16,8 @@
package com.alibaba.nacos.common.remote.client.grpc;
+import com.alibaba.nacos.common.remote.TlsConfig;
import com.alibaba.nacos.common.remote.client.RpcClientConfig;
-import com.alibaba.nacos.common.remote.client.RpcClientTlsConfig;
/**
* GrpcCleint config. Use to collect and init Grpc client configuration.
@@ -81,26 +81,26 @@ public interface GrpcClientConfig extends RpcClientConfig {
* @return channelKeepAliveTimeout.
*/
long channelKeepAliveTimeout();
-
+
/**
- * getTlsConfig.
+ * getTlsConfig.
*
* @return TlsConfig.
*/
- RpcClientTlsConfig tlsConfig();
-
+ TlsConfig tlsConfig();
+
/**
- *Set TlsConfig.
+ * Set TlsConfig.
*
* @param tlsConfig tlsConfig of client.
*/
- void setTlsConfig(RpcClientTlsConfig tlsConfig);
-
+ void setTlsConfig(TlsConfig tlsConfig);
+
/**
* get timeout of connection setup(TimeUnit.MILLISECONDS).
*
* @return timeout of connection setup
*/
long capabilityNegotiationTimeout();
-
+
}
diff --git a/common/src/main/java/com/alibaba/nacos/common/remote/client/grpc/GrpcClusterClient.java b/common/src/main/java/com/alibaba/nacos/common/remote/client/grpc/GrpcClusterClient.java
index 7749f69b6f6..63b9e6f7775 100644
--- a/common/src/main/java/com/alibaba/nacos/common/remote/client/grpc/GrpcClusterClient.java
+++ b/common/src/main/java/com/alibaba/nacos/common/remote/client/grpc/GrpcClusterClient.java
@@ -18,7 +18,7 @@
import com.alibaba.nacos.api.ability.constant.AbilityMode;
import com.alibaba.nacos.api.common.Constants;
-import com.alibaba.nacos.common.remote.client.RpcClientTlsConfig;
+import com.alibaba.nacos.common.remote.client.RpcClusterClientTlsConfig;
import java.util.Map;
import java.util.Properties;
@@ -67,20 +67,20 @@ public GrpcClusterClient(Properties properties) {
* @param labels .
*/
public GrpcClusterClient(String name, Integer threadPoolCoreSize, Integer threadPoolMaxSize,
- Map labels) {
+ Map labels) {
this(name, threadPoolCoreSize, threadPoolMaxSize, labels, null);
}
-
+
public GrpcClusterClient(String name, Integer threadPoolCoreSize, Integer threadPoolMaxSize,
- Map labels, RpcClientTlsConfig tlsConfig) {
+ Map labels, RpcClusterClientTlsConfig tlsConfig) {
super(name, threadPoolCoreSize, threadPoolMaxSize, labels, tlsConfig);
}
-
+
@Override
protected AbilityMode abilityMode() {
return AbilityMode.CLUSTER_CLIENT;
}
-
+
@Override
public int rpcPortOffset() {
return Integer.parseInt(System.getProperty(GrpcConstants.NACOS_SERVER_GRPC_PORT_OFFSET_KEY,
diff --git a/common/src/main/java/com/alibaba/nacos/common/remote/client/grpc/GrpcSdkClient.java b/common/src/main/java/com/alibaba/nacos/common/remote/client/grpc/GrpcSdkClient.java
index 0ede2af6de6..aaab00aa222 100644
--- a/common/src/main/java/com/alibaba/nacos/common/remote/client/grpc/GrpcSdkClient.java
+++ b/common/src/main/java/com/alibaba/nacos/common/remote/client/grpc/GrpcSdkClient.java
@@ -18,7 +18,7 @@
import com.alibaba.nacos.api.ability.constant.AbilityMode;
import com.alibaba.nacos.api.common.Constants;
-import com.alibaba.nacos.common.remote.client.RpcClientTlsConfig;
+import com.alibaba.nacos.common.remote.client.RpcSdkClientTlsConfig;
import java.util.Map;
import java.util.Properties;
@@ -57,20 +57,21 @@ public GrpcSdkClient(Properties properties) {
* @param threadPoolMaxSize .
* @param labels .
*/
- public GrpcSdkClient(String name, Integer threadPoolCoreSize, Integer threadPoolMaxSize, Map labels) {
+ public GrpcSdkClient(String name, Integer threadPoolCoreSize, Integer threadPoolMaxSize,
+ Map labels) {
this(name, threadPoolCoreSize, threadPoolMaxSize, labels, null);
}
-
+
public GrpcSdkClient(String name, Integer threadPoolCoreSize, Integer threadPoolMaxSize, Map labels,
- RpcClientTlsConfig tlsConfig) {
+ RpcSdkClientTlsConfig tlsConfig) {
super(name, threadPoolCoreSize, threadPoolMaxSize, labels, tlsConfig);
}
-
+
@Override
protected AbilityMode abilityMode() {
return AbilityMode.SDK_CLIENT;
}
-
+
/**
* constructor.
*
@@ -86,4 +87,4 @@ public int rpcPortOffset() {
String.valueOf(Constants.SDK_GRPC_PORT_DEFAULT_OFFSET)));
}
-}
\ No newline at end of file
+}
diff --git a/common/src/test/java/com/alibaba/nacos/common/remote/client/RpcClientFactoryTest.java b/common/src/test/java/com/alibaba/nacos/common/remote/client/RpcClientFactoryTest.java
index 1857a707c6e..1bdebc76f88 100644
--- a/common/src/test/java/com/alibaba/nacos/common/remote/client/RpcClientFactoryTest.java
+++ b/common/src/test/java/com/alibaba/nacos/common/remote/client/RpcClientFactoryTest.java
@@ -48,7 +48,10 @@ public class RpcClientFactoryTest {
RpcClient rpcClient;
@Mock(lenient = true)
- RpcClientTlsConfig tlsConfig;
+ RpcClusterClientTlsConfig clusterClientTlsConfig;
+
+ @Mock(lenient = true)
+ RpcSdkClientTlsConfig rpcClientTlsConfig;
@BeforeClass
public static void setUpBeforeClass() throws NoSuchFieldException, IllegalAccessException {
@@ -166,9 +169,9 @@ public void testCreatedClusterClientWhenConnectionTypeNotMappingThenThrowExcepti
@Test
public void testCreateClusterClientTsl() {
- Mockito.when(tlsConfig.getEnableTls()).thenReturn(true);
+ Mockito.when(clusterClientTlsConfig.getEnableTls()).thenReturn(true);
RpcClient client = RpcClientFactory.createClusterClient("testClient", ConnectionType.GRPC,
- Collections.singletonMap("labelKey", "labelValue"), tlsConfig);
+ Collections.singletonMap("labelKey", "labelValue"), clusterClientTlsConfig);
Map labesMap = new HashMap<>();
labesMap.put("labelKey", "labelValue");
labesMap.put("tls.enable", "true");
@@ -180,9 +183,9 @@ public void testCreateClusterClientTsl() {
@Test
public void testCreateClientTsl() {
- Mockito.when(tlsConfig.getEnableTls()).thenReturn(true);
+ Mockito.when(rpcClientTlsConfig.getEnableTls()).thenReturn(true);
RpcClient client = RpcClientFactory.createClient("testClient", ConnectionType.GRPC,
- Collections.singletonMap("labelKey", "labelValue"), tlsConfig);
+ Collections.singletonMap("labelKey", "labelValue"), rpcClientTlsConfig);
Map labesMap = new HashMap<>();
labesMap.put("labelKey", "labelValue");
labesMap.put("tls.enable", "true");
@@ -191,4 +194,4 @@ public void testCreateClientTsl() {
Assert.assertEquals("testClient",
CollectionUtils.getOnlyElement(RpcClientFactory.getAllClientEntries()).getKey());
}
-}
\ No newline at end of file
+}
diff --git a/common/src/test/java/com/alibaba/nacos/common/remote/client/RpcClientTlsConfigTest.java b/common/src/test/java/com/alibaba/nacos/common/remote/client/RpcClientTlsConfigTest.java
index f0e6b59ba02..367bb16808b 100644
--- a/common/src/test/java/com/alibaba/nacos/common/remote/client/RpcClientTlsConfigTest.java
+++ b/common/src/test/java/com/alibaba/nacos/common/remote/client/RpcClientTlsConfigTest.java
@@ -29,7 +29,7 @@ public class RpcClientTlsConfigTest {
public void testEnableTls() {
Properties properties = new Properties();
properties.setProperty(RpcConstants.RPC_CLIENT_TLS_ENABLE, "true");
- RpcClientTlsConfig tlsConfig = RpcClientTlsConfig.properties(properties);
+ RpcSdkClientTlsConfig tlsConfig = RpcSdkClientTlsConfig.properties(properties);
assertTrue(tlsConfig.getEnableTls());
}
@@ -37,7 +37,7 @@ public void testEnableTls() {
public void testSslProvider() {
Properties properties = new Properties();
properties.setProperty(RpcConstants.RPC_CLIENT_TLS_PROVIDER, "provider");
- RpcClientTlsConfig tlsConfig = RpcClientTlsConfig.properties(properties);
+ RpcSdkClientTlsConfig tlsConfig = RpcSdkClientTlsConfig.properties(properties);
assertEquals("provider", tlsConfig.getSslProvider());
}
@@ -45,7 +45,7 @@ public void testSslProvider() {
public void testMutualAuthEnable() {
Properties properties = new Properties();
properties.setProperty(RpcConstants.RPC_CLIENT_MUTUAL_AUTH, "true");
- RpcClientTlsConfig tlsConfig = RpcClientTlsConfig.properties(properties);
+ RpcSdkClientTlsConfig tlsConfig = RpcSdkClientTlsConfig.properties(properties);
assertTrue(tlsConfig.getMutualAuthEnable());
}
@@ -53,7 +53,7 @@ public void testMutualAuthEnable() {
public void testProtocols() {
Properties properties = new Properties();
properties.setProperty(RpcConstants.RPC_CLIENT_TLS_PROTOCOLS, "protocols");
- RpcClientTlsConfig tlsConfig = RpcClientTlsConfig.properties(properties);
+ RpcSdkClientTlsConfig tlsConfig = RpcSdkClientTlsConfig.properties(properties);
assertEquals("protocols", tlsConfig.getProtocols());
}
@@ -61,7 +61,7 @@ public void testProtocols() {
public void testCiphers() {
Properties properties = new Properties();
properties.setProperty(RpcConstants.RPC_CLIENT_TLS_CIPHERS, "ciphers");
- RpcClientTlsConfig tlsConfig = RpcClientTlsConfig.properties(properties);
+ RpcSdkClientTlsConfig tlsConfig = RpcSdkClientTlsConfig.properties(properties);
assertEquals("ciphers", tlsConfig.getCiphers());
}
@@ -69,7 +69,7 @@ public void testCiphers() {
public void testTrustCollectionCertFile() {
Properties properties = new Properties();
properties.setProperty(RpcConstants.RPC_CLIENT_TLS_TRUST_COLLECTION_CHAIN_PATH, "trustCollectionCertFile");
- RpcClientTlsConfig tlsConfig = RpcClientTlsConfig.properties(properties);
+ RpcSdkClientTlsConfig tlsConfig = RpcSdkClientTlsConfig.properties(properties);
assertEquals("trustCollectionCertFile", tlsConfig.getTrustCollectionCertFile());
}
@@ -77,7 +77,7 @@ public void testTrustCollectionCertFile() {
public void testCertChainFile() {
Properties properties = new Properties();
properties.setProperty(RpcConstants.RPC_CLIENT_TLS_CERT_CHAIN_PATH, "certChainFile");
- RpcClientTlsConfig tlsConfig = RpcClientTlsConfig.properties(properties);
+ RpcSdkClientTlsConfig tlsConfig = RpcSdkClientTlsConfig.properties(properties);
assertEquals("certChainFile", tlsConfig.getCertChainFile());
}
@@ -85,7 +85,7 @@ public void testCertChainFile() {
public void testCertPrivateKey() {
Properties properties = new Properties();
properties.setProperty(RpcConstants.RPC_CLIENT_TLS_CERT_KEY, "certPrivateKey");
- RpcClientTlsConfig tlsConfig = RpcClientTlsConfig.properties(properties);
+ RpcSdkClientTlsConfig tlsConfig = RpcSdkClientTlsConfig.properties(properties);
assertEquals("certPrivateKey", tlsConfig.getCertPrivateKey());
}
@@ -93,7 +93,7 @@ public void testCertPrivateKey() {
public void testTrustAll() {
Properties properties = new Properties();
properties.setProperty(RpcConstants.RPC_CLIENT_TLS_TRUST_ALL, "true");
- RpcClientTlsConfig tlsConfig = RpcClientTlsConfig.properties(properties);
+ RpcSdkClientTlsConfig tlsConfig = RpcSdkClientTlsConfig.properties(properties);
assertTrue(tlsConfig.getTrustAll());
}
@@ -101,7 +101,7 @@ public void testTrustAll() {
public void testCertPrivateKeyPassword() {
Properties properties = new Properties();
properties.setProperty(RpcConstants.RPC_CLIENT_TLS_TRUST_PWD, "trustPwd");
- RpcClientTlsConfig tlsConfig = RpcClientTlsConfig.properties(properties);
+ RpcSdkClientTlsConfig tlsConfig = RpcSdkClientTlsConfig.properties(properties);
assertEquals("trustPwd", tlsConfig.getCertPrivateKeyPassword());
}
-}
\ No newline at end of file
+}
diff --git a/common/src/test/java/com/alibaba/nacos/common/remote/client/RpcClusterClientTlsConfigTest.java b/common/src/test/java/com/alibaba/nacos/common/remote/client/RpcClusterClientTlsConfigTest.java
new file mode 100644
index 00000000000..f71382fcd22
--- /dev/null
+++ b/common/src/test/java/com/alibaba/nacos/common/remote/client/RpcClusterClientTlsConfigTest.java
@@ -0,0 +1,105 @@
+/*
+ * Copyright 1999-2023 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.alibaba.nacos.common.remote.client;
+
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+public class RpcClusterClientTlsConfigTest {
+
+ @Test
+ public void testEnableTls() {
+ System.setProperty(RpcConstants.RPC_CLUSTER_CLIENT_TLS_ENABLE, "true");
+ RpcClusterClientTlsConfig tlsConfig = RpcClusterClientTlsConfig.createConfig();
+ assertTrue(tlsConfig.getEnableTls());
+ }
+
+ @Test
+ public void testSslProvider() {
+ System.setProperty(RpcConstants.RPC_CLUSTER_CLIENT_TLS_ENABLE, "true");
+ System.setProperty(RpcConstants.RPC_CLUSTER_CLIENT_TLS_PROVIDER, "provider");
+ RpcClusterClientTlsConfig tlsConfig = RpcClusterClientTlsConfig.createConfig();
+ assertEquals("provider", tlsConfig.getSslProvider());
+ }
+
+ @Test
+ public void testMutualAuthEnable() {
+ System.setProperty(RpcConstants.RPC_CLUSTER_CLIENT_TLS_ENABLE, "true");
+ System.setProperty(RpcConstants.RPC_CLUSTER_CLIENT_MUTUAL_AUTH, "true");
+ RpcClusterClientTlsConfig tlsConfig = RpcClusterClientTlsConfig.createConfig();
+ assertTrue(tlsConfig.getMutualAuthEnable());
+ }
+
+ @Test
+ public void testProtocols() {
+ System.setProperty(RpcConstants.RPC_CLUSTER_CLIENT_TLS_ENABLE, "true");
+ System.setProperty(RpcConstants.RPC_CLUSTER_CLIENT_TLS_PROTOCOLS, "protocols");
+ RpcClusterClientTlsConfig tlsConfig = RpcClusterClientTlsConfig.createConfig();
+ assertEquals("protocols", tlsConfig.getProtocols());
+ }
+
+ @Test
+ public void testCiphers() {
+ System.setProperty(RpcConstants.RPC_CLUSTER_CLIENT_TLS_ENABLE, "true");
+ System.setProperty(RpcConstants.RPC_CLUSTER_CLIENT_TLS_CIPHERS, "ciphers");
+ RpcClusterClientTlsConfig tlsConfig = RpcClusterClientTlsConfig.createConfig();
+ assertEquals("ciphers", tlsConfig.getCiphers());
+ }
+
+ @Test
+ public void testTrustCollectionCertFile() {
+ System.setProperty(RpcConstants.RPC_CLUSTER_CLIENT_TLS_ENABLE, "true");
+ System.setProperty(RpcConstants.RPC_CLUSTER_CLIENT_TLS_TRUST_COLLECTION_CHAIN_PATH, "trustCollectionCertFile");
+ RpcClusterClientTlsConfig tlsConfig = RpcClusterClientTlsConfig.createConfig();
+ assertEquals("trustCollectionCertFile", tlsConfig.getTrustCollectionCertFile());
+ }
+
+ @Test
+ public void testCertChainFile() {
+ System.setProperty(RpcConstants.RPC_CLUSTER_CLIENT_TLS_ENABLE, "true");
+ System.setProperty(RpcConstants.RPC_CLUSTER_CLIENT_TLS_CERT_CHAIN_PATH, "certChainFile");
+ RpcClusterClientTlsConfig tlsConfig = RpcClusterClientTlsConfig.createConfig();
+ assertEquals("certChainFile", tlsConfig.getCertChainFile());
+ }
+
+ @Test
+ public void testCertPrivateKey() {
+ System.setProperty(RpcConstants.RPC_CLUSTER_CLIENT_TLS_ENABLE, "true");
+ System.setProperty(RpcConstants.RPC_CLUSTER_CLIENT_TLS_CERT_KEY, "certPrivateKey");
+ RpcClusterClientTlsConfig tlsConfig = RpcClusterClientTlsConfig.createConfig();
+ assertEquals("certPrivateKey", tlsConfig.getCertPrivateKey());
+ }
+
+ @Test
+ public void testTrustAll() {
+ System.setProperty(RpcConstants.RPC_CLUSTER_CLIENT_TLS_ENABLE, "true");
+ System.setProperty(RpcConstants.RPC_CLUSTER_CLIENT_TLS_TRUST_ALL, "true");
+ RpcClusterClientTlsConfig tlsConfig = RpcClusterClientTlsConfig.createConfig();
+ assertTrue(tlsConfig.getTrustAll());
+ }
+
+ @Test
+ public void testCertPrivateKeyPassword() {
+ System.setProperty(RpcConstants.RPC_CLUSTER_CLIENT_TLS_ENABLE, "true");
+ System.setProperty(RpcConstants.RPC_CLUSTER_CLIENT_TLS_TRUST_PWD, "trustPwd");
+ RpcClusterClientTlsConfig tlsConfig = RpcClusterClientTlsConfig.createConfig();
+ assertEquals("trustPwd", tlsConfig.getCertPrivateKeyPassword());
+ }
+}
+
diff --git a/common/src/test/java/com/alibaba/nacos/common/remote/client/RpcConstantsTest.java b/common/src/test/java/com/alibaba/nacos/common/remote/client/RpcConstantsTest.java
index 6d4a88400f5..0e82b09c0ba 100644
--- a/common/src/test/java/com/alibaba/nacos/common/remote/client/RpcConstantsTest.java
+++ b/common/src/test/java/com/alibaba/nacos/common/remote/client/RpcConstantsTest.java
@@ -26,8 +26,7 @@ public class RpcConstantsTest {
@Test
public void testGetRpcParams() {
- Class clazz = RpcConstants.class;
- Field[] declaredFields = clazz.getDeclaredFields();
+ Field[] declaredFields = RpcConstants.class.getDeclaredFields();
int i = 0;
for (Field declaredField : declaredFields) {
declaredField.setAccessible(true);
@@ -38,4 +37,18 @@ public void testGetRpcParams() {
}
assertEquals(i, RpcConstants.getRpcParams().size());
}
+
+ @Test
+ public void testGetClusterRpcParams() {
+ Field[] declaredFields = RpcConstants.class.getDeclaredFields();
+ int i = 0;
+ for (Field declaredField : declaredFields) {
+ declaredField.setAccessible(true);
+ if (declaredField.getType().equals(String.class) && null != declaredField.getAnnotation(
+ RpcConstants.RpcClusterConfigLabel.class)) {
+ i++;
+ }
+ }
+ assertEquals(i, RpcConstants.getClusterRpcParams().size());
+ }
}
diff --git a/common/src/test/java/com/alibaba/nacos/common/remote/client/grpc/DefaultGrpcClientConfigTest.java b/common/src/test/java/com/alibaba/nacos/common/remote/client/grpc/DefaultGrpcClientConfigTest.java
index 718bab454e5..1fee49da6a5 100644
--- a/common/src/test/java/com/alibaba/nacos/common/remote/client/grpc/DefaultGrpcClientConfigTest.java
+++ b/common/src/test/java/com/alibaba/nacos/common/remote/client/grpc/DefaultGrpcClientConfigTest.java
@@ -16,7 +16,7 @@
package com.alibaba.nacos.common.remote.client.grpc;
-import com.alibaba.nacos.common.remote.client.RpcClientTlsConfig;
+import com.alibaba.nacos.common.remote.client.RpcSdkClientTlsConfig;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -255,7 +255,7 @@ public void testSetLabels() {
@Test
public void testSetTlsConfig() {
- RpcClientTlsConfig tlsConfig = new RpcClientTlsConfig();
+ RpcSdkClientTlsConfig tlsConfig = new RpcSdkClientTlsConfig();
DefaultGrpcClientConfig.Builder builder = DefaultGrpcClientConfig.newBuilder();
builder.setTlsConfig(tlsConfig);
DefaultGrpcClientConfig config = (DefaultGrpcClientConfig) builder.build();
@@ -264,7 +264,7 @@ public void testSetTlsConfig() {
@Test
public void testSetTlsConfigDirectly() {
- RpcClientTlsConfig tlsConfig = new RpcClientTlsConfig();
+ RpcSdkClientTlsConfig tlsConfig = new RpcSdkClientTlsConfig();
DefaultGrpcClientConfig.Builder builder = DefaultGrpcClientConfig.newBuilder();
DefaultGrpcClientConfig config = (DefaultGrpcClientConfig) builder.build();
config.setTlsConfig(tlsConfig);
diff --git a/common/src/test/java/com/alibaba/nacos/common/remote/client/grpc/GrpcClientTest.java b/common/src/test/java/com/alibaba/nacos/common/remote/client/grpc/GrpcClientTest.java
index 28b89e8c4f8..b33ca62c0e0 100644
--- a/common/src/test/java/com/alibaba/nacos/common/remote/client/grpc/GrpcClientTest.java
+++ b/common/src/test/java/com/alibaba/nacos/common/remote/client/grpc/GrpcClientTest.java
@@ -31,7 +31,7 @@
import com.alibaba.nacos.common.remote.client.Connection;
import com.alibaba.nacos.common.remote.client.RpcClient;
import com.alibaba.nacos.common.remote.client.RpcClientStatus;
-import com.alibaba.nacos.common.remote.client.RpcClientTlsConfig;
+import com.alibaba.nacos.common.remote.client.RpcSdkClientTlsConfig;
import com.alibaba.nacos.common.remote.client.ServerListFactory;
import com.google.common.util.concurrent.ListenableFuture;
import io.grpc.Channel;
@@ -76,7 +76,7 @@ public class GrpcClientTest {
protected GrpcClient grpcClient;
@Mock
- RpcClientTlsConfig tlsConfig;
+ RpcSdkClientTlsConfig tlsConfig;
protected RpcClient.ServerInfo serverInfo;
@@ -176,8 +176,8 @@ public void testBindRequestStreamOnNextSetupAckRequest()
BiRequestStreamGrpc.BiRequestStreamStub stub = mock(BiRequestStreamGrpc.BiRequestStreamStub.class);
GrpcConnection grpcConnection = mock(GrpcConnection.class);
when(stub.requestBiStream(any())).thenAnswer((Answer>) invocationOnMock -> {
- ((StreamObserver) invocationOnMock.getArgument(0))
- .onNext(GrpcUtils.convert(new SetupAckRequest()));
+ ((StreamObserver) invocationOnMock.getArgument(0)).onNext(
+ GrpcUtils.convert(new SetupAckRequest()));
return null;
});
setCurrentConnection(grpcConnection, grpcClient);
@@ -191,8 +191,8 @@ public void testBindRequestStreamOnNextOtherRequest()
BiRequestStreamGrpc.BiRequestStreamStub stub = mock(BiRequestStreamGrpc.BiRequestStreamStub.class);
GrpcConnection grpcConnection = mock(GrpcConnection.class);
when(stub.requestBiStream(any())).thenAnswer((Answer>) invocationOnMock -> {
- ((StreamObserver) invocationOnMock.getArgument(0))
- .onNext(GrpcUtils.convert(new ConnectResetRequest()));
+ ((StreamObserver) invocationOnMock.getArgument(0)).onNext(
+ GrpcUtils.convert(new ConnectResetRequest()));
return null;
});
grpcClient.registerServerRequestHandler((request, connection) -> {
@@ -212,8 +212,8 @@ public void testBindRequestStreamOnNextNoRequest()
BiRequestStreamGrpc.BiRequestStreamStub stub = mock(BiRequestStreamGrpc.BiRequestStreamStub.class);
GrpcConnection grpcConnection = mock(GrpcConnection.class);
when(stub.requestBiStream(any())).thenAnswer((Answer>) invocationOnMock -> {
- ((StreamObserver) invocationOnMock.getArgument(0))
- .onNext(GrpcUtils.convert(new ConnectResetRequest()));
+ ((StreamObserver) invocationOnMock.getArgument(0)).onNext(
+ GrpcUtils.convert(new ConnectResetRequest()));
return null;
});
grpcClient.registerServerRequestHandler((request, connection) -> null);
@@ -228,8 +228,8 @@ public void testBindRequestStreamOnNextHandleException()
BiRequestStreamGrpc.BiRequestStreamStub stub = mock(BiRequestStreamGrpc.BiRequestStreamStub.class);
GrpcConnection grpcConnection = mock(GrpcConnection.class);
when(stub.requestBiStream(any())).thenAnswer((Answer>) invocationOnMock -> {
- ((StreamObserver) invocationOnMock.getArgument(0))
- .onNext(GrpcUtils.convert(new ConnectResetRequest()));
+ ((StreamObserver) invocationOnMock.getArgument(0)).onNext(
+ GrpcUtils.convert(new ConnectResetRequest()));
return null;
});
grpcClient.registerServerRequestHandler((request, connection) -> {
@@ -325,9 +325,8 @@ public void testBindRequestStreamOnCompletedFromNotRunning()
private void invokeBindRequestStream(GrpcClient grpcClient, BiRequestStreamGrpc.BiRequestStreamStub stub,
GrpcConnection grpcConnection)
throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
- Method bindRequestStreamMethod = GrpcClient.class
- .getDeclaredMethod("bindRequestStream", BiRequestStreamGrpc.BiRequestStreamStub.class,
- GrpcConnection.class);
+ Method bindRequestStreamMethod = GrpcClient.class.getDeclaredMethod("bindRequestStream",
+ BiRequestStreamGrpc.BiRequestStreamStub.class, GrpcConnection.class);
bindRequestStreamMethod.setAccessible(true);
bindRequestStreamMethod.invoke(grpcClient, stub, grpcConnection);
}
diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/ExceptionUtilTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/ExceptionUtilTest.java
index 087a8f1fc83..2a8cf2d5120 100644
--- a/common/src/test/java/com/alibaba/nacos/common/utils/ExceptionUtilTest.java
+++ b/common/src/test/java/com/alibaba/nacos/common/utils/ExceptionUtilTest.java
@@ -52,8 +52,8 @@ public void testGetStackTrace() {
assertEquals("", ExceptionUtil.getStackTrace(null));
String stackTrace = ExceptionUtil.getStackTrace(nacosRuntimeException);
assertTrue(stackTrace.contains(
- "com.alibaba.nacos.api.exception.runtime.NacosRuntimeException: errCode: 500, errMsg: Test \n"));
+ "com.alibaba.nacos.api.exception.runtime.NacosRuntimeException: errCode: 500, errMsg: Test"));
assertTrue(stackTrace.contains("at "));
- assertTrue(stackTrace.contains("Caused by: java.lang.RuntimeException: I'm caused exception.\n"));
+ assertTrue(stackTrace.contains("Caused by: java.lang.RuntimeException: I'm caused exception."));
}
-}
\ No newline at end of file
+}
diff --git a/core/src/main/java/com/alibaba/nacos/core/cluster/remote/ClusterRpcClientProxy.java b/core/src/main/java/com/alibaba/nacos/core/cluster/remote/ClusterRpcClientProxy.java
index ac6f8b9af3d..224bfbd7c99 100644
--- a/core/src/main/java/com/alibaba/nacos/core/cluster/remote/ClusterRpcClientProxy.java
+++ b/core/src/main/java/com/alibaba/nacos/core/cluster/remote/ClusterRpcClientProxy.java
@@ -25,6 +25,7 @@
import com.alibaba.nacos.common.remote.ConnectionType;
import com.alibaba.nacos.common.remote.client.RpcClient;
import com.alibaba.nacos.common.remote.client.RpcClientFactory;
+import com.alibaba.nacos.common.remote.client.RpcClusterClientTlsConfig;
import com.alibaba.nacos.common.remote.client.ServerListFactory;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.alibaba.nacos.core.cluster.Member;
@@ -152,10 +153,9 @@ public List getServerList() {
* Using {@link EnvUtil#getAvailableProcessors(int)} to build cluster clients' grpc thread pool.
*/
private RpcClient buildRpcClient(ConnectionType type, Map labels, String memberClientKey) {
- RpcClient clusterClient = RpcClientFactory
- .createClusterClient(memberClientKey, type, EnvUtil.getAvailableProcessors(2),
- EnvUtil.getAvailableProcessors(8), labels);
- return clusterClient;
+ RpcClusterClientTlsConfig config = RpcClusterClientTlsConfig.createConfig();
+ return RpcClientFactory.createClusterClient(memberClientKey, type, EnvUtil.getAvailableProcessors(2),
+ EnvUtil.getAvailableProcessors(8), labels, config);
}
/**
diff --git a/core/src/main/java/com/alibaba/nacos/core/remote/BaseRpcServer.java b/core/src/main/java/com/alibaba/nacos/core/remote/BaseRpcServer.java
index 3b5fe849a8f..3ec0fe28674 100644
--- a/core/src/main/java/com/alibaba/nacos/core/remote/BaseRpcServer.java
+++ b/core/src/main/java/com/alibaba/nacos/core/remote/BaseRpcServer.java
@@ -47,8 +47,12 @@ public void start() throws Exception {
startServer();
- if (RpcServerSslContextRefresherHolder.getInstance() != null) {
- RpcServerSslContextRefresherHolder.getInstance().refresh(this);
+ if (RpcServerSslContextRefresherHolder.getSdkInstance() != null) {
+ RpcServerSslContextRefresherHolder.getSdkInstance().refresh(this);
+ }
+
+ if (RpcServerSslContextRefresherHolder.getClusterInstance() != null) {
+ RpcServerSslContextRefresherHolder.getClusterInstance().refresh(this);
}
Loggers.REMOTE.info("Nacos {} Rpc server started at port {}", serverName, getServicePort());
@@ -75,8 +79,8 @@ public void start() throws Exception {
* Reload protocol context if necessary.
*
*
- * protocol like:
- *
Tls
+ * protocol like:
+ *
Tls
*
*/
public abstract void reloadProtocolContext();
diff --git a/core/src/main/java/com/alibaba/nacos/core/remote/grpc/BaseGrpcServer.java b/core/src/main/java/com/alibaba/nacos/core/remote/grpc/BaseGrpcServer.java
index 5749a52d8cb..837924191ea 100644
--- a/core/src/main/java/com/alibaba/nacos/core/remote/grpc/BaseGrpcServer.java
+++ b/core/src/main/java/com/alibaba/nacos/core/remote/grpc/BaseGrpcServer.java
@@ -20,6 +20,7 @@
import com.alibaba.nacos.common.remote.ConnectionType;
import com.alibaba.nacos.core.remote.BaseRpcServer;
import com.alibaba.nacos.core.remote.ConnectionManager;
+import com.alibaba.nacos.core.remote.grpc.negotiator.NacosGrpcProtocolNegotiator;
import com.alibaba.nacos.core.utils.Loggers;
import com.alibaba.nacos.sys.env.EnvUtil;
import io.grpc.CompressorRegistry;
@@ -53,6 +54,11 @@
*/
public abstract class BaseGrpcServer extends BaseRpcServer {
+ /**
+ * The ProtocolNegotiator instance used for communication.
+ */
+ protected NacosGrpcProtocolNegotiator protocolNegotiator;
+
private Server server;
@Autowired
@@ -115,6 +121,15 @@ protected Optional newProtocolNeg
* reload protocol negotiator If necessary.
*/
public void reloadProtocolNegotiator() {
+ if (protocolNegotiator != null) {
+ try {
+ protocolNegotiator.reloadNegotiator();
+ } catch (Throwable throwable) {
+ Loggers.REMOTE.info("Nacos {} Rpc server reload negotiator fail at port {}.",
+ this.getClass().getSimpleName(), getServicePort());
+ throw throwable;
+ }
+ }
}
protected long getPermitKeepAliveTime() {
@@ -130,8 +145,8 @@ protected long getKeepAliveTimeout() {
}
protected int getMaxInboundMessageSize() {
- Integer property = EnvUtil
- .getProperty(GrpcServerConstants.GrpcConfig.MAX_INBOUND_MSG_SIZE_PROPERTY, Integer.class);
+ Integer property = EnvUtil.getProperty(GrpcServerConstants.GrpcConfig.MAX_INBOUND_MSG_SIZE_PROPERTY,
+ Integer.class);
if (property != null) {
return property;
}
@@ -152,8 +167,8 @@ private void addServices(MutableHandlerRegistry handlerRegistry, ServerIntercept
// unary common call register.
final MethodDescriptor unaryPayloadMethod = MethodDescriptor.newBuilder()
- .setType(MethodDescriptor.MethodType.UNARY).setFullMethodName(MethodDescriptor
- .generateFullMethodName(GrpcServerConstants.REQUEST_SERVICE_NAME,
+ .setType(MethodDescriptor.MethodType.UNARY).setFullMethodName(
+ MethodDescriptor.generateFullMethodName(GrpcServerConstants.REQUEST_SERVICE_NAME,
GrpcServerConstants.REQUEST_METHOD_NAME))
.setRequestMarshaller(ProtoUtils.marshaller(Payload.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Payload.getDefaultInstance())).build();
@@ -161,9 +176,8 @@ private void addServices(MutableHandlerRegistry handlerRegistry, ServerIntercept
final ServerCallHandler payloadHandler = ServerCalls.asyncUnaryCall(
(request, responseObserver) -> grpcCommonRequestAcceptor.request(request, responseObserver));
- final ServerServiceDefinition serviceDefOfUnaryPayload = ServerServiceDefinition
- .builder(GrpcServerConstants.REQUEST_SERVICE_NAME).addMethod(unaryPayloadMethod, payloadHandler)
- .build();
+ final ServerServiceDefinition serviceDefOfUnaryPayload = ServerServiceDefinition.builder(
+ GrpcServerConstants.REQUEST_SERVICE_NAME).addMethod(unaryPayloadMethod, payloadHandler).build();
handlerRegistry.addService(ServerInterceptors.intercept(serviceDefOfUnaryPayload, serverInterceptor));
// bi stream register.
@@ -171,15 +185,14 @@ private void addServices(MutableHandlerRegistry handlerRegistry, ServerIntercept
(responseObserver) -> grpcBiStreamRequestAcceptor.requestBiStream(responseObserver));
final MethodDescriptor biStreamMethod = MethodDescriptor.newBuilder()
- .setType(MethodDescriptor.MethodType.BIDI_STREAMING).setFullMethodName(MethodDescriptor
- .generateFullMethodName(GrpcServerConstants.REQUEST_BI_STREAM_SERVICE_NAME,
+ .setType(MethodDescriptor.MethodType.BIDI_STREAMING).setFullMethodName(
+ MethodDescriptor.generateFullMethodName(GrpcServerConstants.REQUEST_BI_STREAM_SERVICE_NAME,
GrpcServerConstants.REQUEST_BI_STREAM_METHOD_NAME))
.setRequestMarshaller(ProtoUtils.marshaller(Payload.newBuilder().build()))
.setResponseMarshaller(ProtoUtils.marshaller(Payload.getDefaultInstance())).build();
- final ServerServiceDefinition serviceDefOfBiStream = ServerServiceDefinition
- .builder(GrpcServerConstants.REQUEST_BI_STREAM_SERVICE_NAME).addMethod(biStreamMethod, biStreamHandler)
- .build();
+ final ServerServiceDefinition serviceDefOfBiStream = ServerServiceDefinition.builder(
+ GrpcServerConstants.REQUEST_BI_STREAM_SERVICE_NAME).addMethod(biStreamMethod, biStreamHandler).build();
handlerRegistry.addService(ServerInterceptors.intercept(serviceDefOfBiStream, serverInterceptor));
}
diff --git a/core/src/main/java/com/alibaba/nacos/core/remote/grpc/GrpcClusterServer.java b/core/src/main/java/com/alibaba/nacos/core/remote/grpc/GrpcClusterServer.java
index f37c4c46b37..1a52b48afdf 100644
--- a/core/src/main/java/com/alibaba/nacos/core/remote/grpc/GrpcClusterServer.java
+++ b/core/src/main/java/com/alibaba/nacos/core/remote/grpc/GrpcClusterServer.java
@@ -17,19 +17,23 @@
package com.alibaba.nacos.core.remote.grpc;
import com.alibaba.nacos.api.common.Constants;
+import com.alibaba.nacos.common.remote.CommunicationType;
import com.alibaba.nacos.core.remote.grpc.filter.NacosGrpcServerTransportFilter;
import com.alibaba.nacos.core.remote.grpc.filter.NacosGrpcServerTransportFilterServiceLoader;
import com.alibaba.nacos.core.remote.grpc.interceptor.NacosGrpcServerInterceptor;
import com.alibaba.nacos.core.remote.grpc.interceptor.NacosGrpcServerInterceptorServiceLoader;
+import com.alibaba.nacos.core.remote.grpc.negotiator.tls.ProtocolNegotiatorBuilderManager;
import com.alibaba.nacos.core.utils.GlobalExecutor;
import com.alibaba.nacos.core.utils.Loggers;
import com.alibaba.nacos.sys.env.EnvUtil;
import io.grpc.ServerInterceptor;
import io.grpc.ServerTransportFilter;
+import io.grpc.netty.shaded.io.grpc.netty.InternalProtocolNegotiator;
import org.springframework.stereotype.Service;
import java.util.LinkedList;
import java.util.List;
+import java.util.Optional;
import java.util.concurrent.ThreadPoolExecutor;
/**
@@ -56,8 +60,8 @@ public ThreadPoolExecutor getRpcExecutor() {
@Override
protected long getKeepAliveTime() {
- Long property = EnvUtil
- .getProperty(GrpcServerConstants.GrpcConfig.CLUSTER_KEEP_ALIVE_TIME_PROPERTY, Long.class);
+ Long property = EnvUtil.getProperty(GrpcServerConstants.GrpcConfig.CLUSTER_KEEP_ALIVE_TIME_PROPERTY,
+ Long.class);
if (property != null) {
return property;
}
@@ -66,14 +70,21 @@ protected long getKeepAliveTime() {
@Override
protected long getKeepAliveTimeout() {
- Long property = EnvUtil
- .getProperty(GrpcServerConstants.GrpcConfig.CLUSTER_KEEP_ALIVE_TIMEOUT_PROPERTY, Long.class);
+ Long property = EnvUtil.getProperty(GrpcServerConstants.GrpcConfig.CLUSTER_KEEP_ALIVE_TIMEOUT_PROPERTY,
+ Long.class);
if (property != null) {
return property;
}
return super.getKeepAliveTimeout();
}
+ @Override
+ protected Optional newProtocolNegotiator() {
+ protocolNegotiator = ProtocolNegotiatorBuilderManager.getInstance()
+ .buildGrpcProtocolNegotiator(CommunicationType.CLUSTER);
+ return Optional.ofNullable(protocolNegotiator);
+ }
+
@Override
protected long getPermitKeepAliveTime() {
Long property = EnvUtil.getProperty(GrpcServerConstants.GrpcConfig.CLUSTER_PERMIT_KEEP_ALIVE_TIME, Long.class);
@@ -85,8 +96,8 @@ protected long getPermitKeepAliveTime() {
@Override
protected int getMaxInboundMessageSize() {
- Integer property = EnvUtil
- .getProperty(GrpcServerConstants.GrpcConfig.CLUSTER_MAX_INBOUND_MSG_SIZE_PROPERTY, Integer.class);
+ Integer property = EnvUtil.getProperty(GrpcServerConstants.GrpcConfig.CLUSTER_MAX_INBOUND_MSG_SIZE_PROPERTY,
+ Integer.class);
if (property != null) {
return property;
}
@@ -104,8 +115,8 @@ protected int getMaxInboundMessageSize() {
protected List getSeverInterceptors() {
List result = new LinkedList<>();
result.addAll(super.getSeverInterceptors());
- result.addAll(NacosGrpcServerInterceptorServiceLoader
- .loadServerInterceptors(NacosGrpcServerInterceptor.CLUSTER_INTERCEPTOR));
+ result.addAll(NacosGrpcServerInterceptorServiceLoader.loadServerInterceptors(
+ NacosGrpcServerInterceptor.CLUSTER_INTERCEPTOR));
return result;
}
@@ -113,8 +124,8 @@ protected List getSeverInterceptors() {
protected List getServerTransportFilters() {
List result = new LinkedList<>();
result.addAll(super.getServerTransportFilters());
- result.addAll(NacosGrpcServerTransportFilterServiceLoader
- .loadServerTransportFilters(NacosGrpcServerTransportFilter.CLUSTER_FILTER));
+ result.addAll(NacosGrpcServerTransportFilterServiceLoader.loadServerTransportFilters(
+ NacosGrpcServerTransportFilter.CLUSTER_FILTER));
return result;
}
}
diff --git a/core/src/main/java/com/alibaba/nacos/core/remote/grpc/GrpcSdkServer.java b/core/src/main/java/com/alibaba/nacos/core/remote/grpc/GrpcSdkServer.java
index 6e9e58fb8ab..a06afe9d45e 100644
--- a/core/src/main/java/com/alibaba/nacos/core/remote/grpc/GrpcSdkServer.java
+++ b/core/src/main/java/com/alibaba/nacos/core/remote/grpc/GrpcSdkServer.java
@@ -17,12 +17,12 @@
package com.alibaba.nacos.core.remote.grpc;
import com.alibaba.nacos.api.common.Constants;
+import com.alibaba.nacos.common.remote.CommunicationType;
import com.alibaba.nacos.core.remote.grpc.filter.NacosGrpcServerTransportFilter;
import com.alibaba.nacos.core.remote.grpc.filter.NacosGrpcServerTransportFilterServiceLoader;
import com.alibaba.nacos.core.remote.grpc.interceptor.NacosGrpcServerInterceptor;
import com.alibaba.nacos.core.remote.grpc.interceptor.NacosGrpcServerInterceptorServiceLoader;
-import com.alibaba.nacos.core.remote.grpc.negotiator.NacosGrpcProtocolNegotiator;
-import com.alibaba.nacos.core.remote.grpc.negotiator.ProtocolNegotiatorBuilderSingleton;
+import com.alibaba.nacos.core.remote.grpc.negotiator.tls.ProtocolNegotiatorBuilderManager;
import com.alibaba.nacos.core.utils.GlobalExecutor;
import com.alibaba.nacos.core.utils.Loggers;
import com.alibaba.nacos.sys.env.EnvUtil;
@@ -45,8 +45,6 @@
@Service
public class GrpcSdkServer extends BaseGrpcServer {
- private NacosGrpcProtocolNegotiator protocolNegotiator;
-
@Override
public int rpcPortOffset() {
return Constants.SDK_GRPC_PORT_DEFAULT_OFFSET;
@@ -78,8 +76,8 @@ protected long getKeepAliveTimeout() {
@Override
protected int getMaxInboundMessageSize() {
- Integer property = EnvUtil
- .getProperty(GrpcServerConstants.GrpcConfig.SDK_MAX_INBOUND_MSG_SIZE_PROPERTY, Integer.class);
+ Integer property = EnvUtil.getProperty(GrpcServerConstants.GrpcConfig.SDK_MAX_INBOUND_MSG_SIZE_PROPERTY,
+ Integer.class);
if (property != null) {
return property;
}
@@ -106,7 +104,8 @@ protected long getPermitKeepAliveTime() {
@Override
protected Optional newProtocolNegotiator() {
- protocolNegotiator = ProtocolNegotiatorBuilderSingleton.getSingleton().build();
+ protocolNegotiator = ProtocolNegotiatorBuilderManager.getInstance()
+ .buildGrpcProtocolNegotiator(CommunicationType.SDK);
return Optional.ofNullable(protocolNegotiator);
}
@@ -114,8 +113,8 @@ protected Optional newProtocolNeg
protected List getSeverInterceptors() {
List result = new LinkedList<>();
result.addAll(super.getSeverInterceptors());
- result.addAll(NacosGrpcServerInterceptorServiceLoader
- .loadServerInterceptors(NacosGrpcServerInterceptor.SDK_INTERCEPTOR));
+ result.addAll(NacosGrpcServerInterceptorServiceLoader.loadServerInterceptors(
+ NacosGrpcServerInterceptor.SDK_INTERCEPTOR));
return result;
}
@@ -123,24 +122,9 @@ protected List getSeverInterceptors() {
protected List getServerTransportFilters() {
List result = new LinkedList<>();
result.addAll(super.getServerTransportFilters());
- result.addAll(NacosGrpcServerTransportFilterServiceLoader
- .loadServerTransportFilters(NacosGrpcServerTransportFilter.SDK_FILTER));
+ result.addAll(NacosGrpcServerTransportFilterServiceLoader.loadServerTransportFilters(
+ NacosGrpcServerTransportFilter.SDK_FILTER));
return result;
}
- /**
- * reload ssl context.
- */
- public void reloadProtocolNegotiator() {
- if (protocolNegotiator != null) {
- try {
- protocolNegotiator.reloadNegotiator();
- } catch (Throwable throwable) {
- Loggers.REMOTE
- .info("Nacos {} Rpc server reload negotiator fail at port {}.", this.getClass().getSimpleName(),
- getServicePort());
- throw throwable;
- }
- }
- }
}
diff --git a/core/src/main/java/com/alibaba/nacos/core/remote/grpc/negotiator/ProtocolNegotiatorBuilderSingleton.java b/core/src/main/java/com/alibaba/nacos/core/remote/grpc/negotiator/ProtocolNegotiatorBuilderSingleton.java
deleted file mode 100644
index 9d30d3676ca..00000000000
--- a/core/src/main/java/com/alibaba/nacos/core/remote/grpc/negotiator/ProtocolNegotiatorBuilderSingleton.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Copyright 1999-2023 Alibaba Group Holding Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.alibaba.nacos.core.remote.grpc.negotiator;
-
-import com.alibaba.nacos.common.spi.NacosServiceLoader;
-import com.alibaba.nacos.core.remote.grpc.negotiator.tls.DefaultTlsProtocolNegotiatorBuilder;
-import com.alibaba.nacos.core.utils.Loggers;
-import com.alibaba.nacos.sys.env.EnvUtil;
-
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-import static com.alibaba.nacos.core.remote.grpc.negotiator.tls.DefaultTlsProtocolNegotiatorBuilder.TYPE_DEFAULT_TLS;
-
-/**
- * Protocol Negotiator Builder Singleton.
- *
- * @author xiweng.yy
- */
-public class ProtocolNegotiatorBuilderSingleton implements ProtocolNegotiatorBuilder {
-
- private static final String TYPE_PROPERTY_KEY = "nacos.remote.server.rpc.protocol.negotiator.type";
-
- private static final ProtocolNegotiatorBuilderSingleton SINGLETON = new ProtocolNegotiatorBuilderSingleton();
-
- private final Map builderMap;
-
- private String actualType;
-
- private ProtocolNegotiatorBuilderSingleton() {
- actualType = EnvUtil.getProperty(TYPE_PROPERTY_KEY, TYPE_DEFAULT_TLS);
- builderMap = new ConcurrentHashMap<>();
- loadAllBuilders();
- }
-
- private void loadAllBuilders() {
- try {
- for (ProtocolNegotiatorBuilder each : NacosServiceLoader.load(ProtocolNegotiatorBuilder.class)) {
- builderMap.put(each.type(), each);
- Loggers.REMOTE.info("Load ProtocolNegotiatorBuilder {} for type {}", each.getClass().getCanonicalName(),
- each.type());
- }
- } catch (Exception e) {
- Loggers.REMOTE.warn("Load ProtocolNegotiatorBuilder failed, use default ProtocolNegotiatorBuilder", e);
- builderMap.put(TYPE_DEFAULT_TLS, new DefaultTlsProtocolNegotiatorBuilder());
- actualType = TYPE_DEFAULT_TLS;
- }
- }
-
- public static ProtocolNegotiatorBuilderSingleton getSingleton() {
- return SINGLETON;
- }
-
- @Override
- public NacosGrpcProtocolNegotiator build() {
- ProtocolNegotiatorBuilder actualBuilder = builderMap.get(actualType);
- if (null == actualBuilder) {
- Loggers.REMOTE.warn("Not found ProtocolNegotiatorBuilder for type {}, will use default", actualType);
- return builderMap.get(TYPE_DEFAULT_TLS).build();
- }
- return actualBuilder.build();
- }
-
- @Override
- public String type() {
- return actualType;
- }
-}
diff --git a/core/src/main/java/com/alibaba/nacos/core/remote/grpc/negotiator/tls/ClusterDefaultTlsProtocolNegotiatorBuilder.java b/core/src/main/java/com/alibaba/nacos/core/remote/grpc/negotiator/tls/ClusterDefaultTlsProtocolNegotiatorBuilder.java
new file mode 100644
index 00000000000..75de17fae0e
--- /dev/null
+++ b/core/src/main/java/com/alibaba/nacos/core/remote/grpc/negotiator/tls/ClusterDefaultTlsProtocolNegotiatorBuilder.java
@@ -0,0 +1,89 @@
+/*
+ * Copyright 1999-2023 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.alibaba.nacos.core.remote.grpc.negotiator.tls;
+
+import com.alibaba.nacos.core.remote.grpc.negotiator.NacosGrpcProtocolNegotiator;
+import com.alibaba.nacos.core.remote.grpc.negotiator.ProtocolNegotiatorBuilder;
+import com.alibaba.nacos.core.remote.tls.RpcClusterServerTlsConfig;
+import com.alibaba.nacos.core.remote.tls.RpcServerTlsConfig;
+import io.grpc.netty.shaded.io.netty.handler.ssl.SslContext;
+
+/**
+ * The {@code ClusterDefaultTlsProtocolNegotiatorBuilder} class is an implementation of the
+ * {@link ProtocolNegotiatorBuilder} interface for constructing a ProtocolNegotiator specifically for cluster-to-cluster
+ * communication with TLS encryption.
+ *
+ *
It defines the type as {@code CLUSTER_DEFAULT_TLS} and supports communication types for clusters.
+ *
+ *
+ *
The {@code build()} method constructs and returns a {@link NacosGrpcProtocolNegotiator} instance based on the
+ * configuration provided by the {@link RpcClusterServerTlsConfig} class. If TLS encryption is enabled, it creates an
+ * {@link OptionalTlsProtocolNegotiator} with the corresponding SSL context and configuration; otherwise, it returns
+ * null.
+ *
+ *
+ *
The {@code type()} method returns the unique identifier {@code CLUSTER_TYPE_DEFAULT_TLS} for this negotiator
+ * builder.
+ *