Merge pull request #10126 from alibaba/develop

Merge from develop.
This commit is contained in:
杨翊 SionYang 2023-03-17 18:20:52 +08:00 committed by GitHub
commit cb0422ed74
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
398 changed files with 12960 additions and 3454 deletions

View File

@ -1,7 +1,7 @@
# This workflow will build a Java project with Maven
# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven
name: Continuous Integration
name: "Continuous Integration"
on:
push:
@ -13,34 +13,37 @@ permissions:
contents: read # to fetch code (actions/checkout)
jobs:
unix:
ci:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest]
java: [8]
steps:
- name: Cache Maven Repos
- name: "Cache Maven Repos"
uses: actions/cache@v3
with:
path: ~/.m2/repository
key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
restore-keys: |
${{ runner.os }}-maven-
- uses: actions/checkout@v3
- name: Set up JDK ${{ matrix.java }}
- name: "Checkout"
uses: actions/checkout@v3
- name: "Set up JDK ${{ matrix.java }}"
uses: actions/setup-java@v3
with:
java-version: ${{ matrix.java }}
distribution: 'zulu'
architecture: x64
- name: Check with Maven
run: mvn -B clean package apache-rat:check findbugs:findbugs -Dmaven.test.skip=true
- name: Build with Maven
run: mvn -Prelease-nacos -Dmaven.test.skip=true clean install -U
- name: Test With Maven
run: mvn -Prelease-nacos clean test -DtrimStackTrace=false
- name: Codecov
- name: "Print maven version"
run: mvn -version
- name: "Check with Maven"
run: mvn -B clean package apache-rat:check findbugs:findbugs -DskipTests -e -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn
- name: "Build with Maven"
run: mvn -Prelease-nacos -DskipTests clean install -U -e -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn
- name: "Test With Maven"
run: mvn -Prelease-nacos clean test -DtrimStackTrace=false -e -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn
- name: "Codecov"
uses: codecov/codecov-action@v3.1.0
with:
files: ./address/target/site/jacoco/jacoco.xml,./api/target/site/jacoco/jacoco.xml,./auth/target/site/jacoco/jacoco.xml,./client/target/site/jacoco/jacoco.xml,./common/target/site/jacoco/jacoco.xml,./consistency/target/site/jacoco/jacoco.xml,./console/target/site/jacoco/jacoco.xml,./core/target/site/jacoco/jacoco.xml,./naming/target/site/jacoco/jacoco.xml,./plugin-default-impl/target/site/jacoco/jacoco.xml,./plugin/auth/target/site/jacoco/jacoco.xml,./plugin/encryption/target/site/jacoco/jacoco.xml,./sys/target/site/jacoco/jacoco.xml

View File

@ -1,7 +1,7 @@
# This workflow will build a Java project with Maven
# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven
name: Integration Test
name: "Integration Test"
on:
push:
@ -13,33 +13,36 @@ permissions:
contents: read # to fetch code (actions/checkout)
jobs:
unix:
test:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest]
java: [8, 8.0.192, 11, 11.0.3]
steps:
- name: Cache Maven Repos
- name: "Cache Maven Repos"
uses: actions/cache@v3
with:
path: ~/.m2/repository
key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
restore-keys: |
${{ runner.os }}-maven-
- uses: actions/checkout@v3
- name: Set up JDK ${{ matrix.java }}
- name: "Checkout"
uses: actions/checkout@v3
- name: "Set up JDK ${{ matrix.java }}"
uses: actions/setup-java@v3
with:
java-version: ${{ matrix.java }}
distribution: 'zulu'
architecture: x64
- name: Test Config
run: mvn clean package -Pcit-test
- name: Clean Env
run: mvn clean -Premove-test-data
- name: Test Naming
run: mvn clean package -Pnit-test
- name: Clean Env
run: mvn clean -Premove-test-data
- name: "Print maven version"
run: mvn -version
- name: "Test Config"
run: mvn clean package -Pcit-test -e -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn
- name: "Clean Env"
run: mvn clean -Premove-test-data -e -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn
- name: "Test Naming"
run: mvn clean package -Pnit-test -e -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn
- name: "Clean Env"
run: mvn clean -Premove-test-data -e -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn

View File

@ -5,6 +5,7 @@
[![Gitter](https://badges.gitter.im/alibaba/nacos.svg)](https://gitter.im/alibaba/nacos?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) [![License](https://img.shields.io/badge/license-Apache%202-4EB1BA.svg)](https://www.apache.org/licenses/LICENSE-2.0.html)
[![Gitter](https://travis-ci.org/alibaba/nacos.svg?branch=master)](https://travis-ci.org/alibaba/nacos)
[![](https://img.shields.io/badge/Nacos-Check%20Your%20Contribution-orange)](https://opensource.alibaba.com/contribution_leaderboard/details?projectValue=nacos)
-------
@ -118,9 +119,9 @@ Contributors are welcomed to join Nacos project. Please check [CONTRIBUTING](./C
* users-nacos@googlegroups.com: Nacos usage general discussion.
* dev-nacos@googlegroups.com: Nacos developer discussion (APIs, feature design, etc).
* commits-nacos@googlegroups.com: Commits notice, very high frequency.
* Join us from DingDing(Group 1: 21708933(full), Group 2: 30438813).
* Join us from DingDing(Group 1: 21708933(full), Group 2: 30438813(full), Group 3: 31222241(full), Group 4: 12810027056).
![Nacos](https://nacos.io/img/nacos_dingding.jpg)
![Nacos](https://img.alicdn.com/imgextra/i1/O1CN01ULSVXu1DRbANwVC6r_!!6000000000213-2-tps-666-884.png)
## Enterprise Service
If you need Nacos enterprise service support, or purchase cloud product services, you can join the discussion by scanning the following DingTalk group. It can also be directly activated and used through the microservice engine (MSE) provided by Alibaba Cloud.

View File

@ -1,6 +1,6 @@
# How to report bugs
If any part of the Nacos project has bugs or documentation mistakes, please let us know by [opening an issue][Nacos-issue]. We treat bugs and mistakes very seriously and believe no issue is too small, anyOne is implement. Before creating a bug report, please check that an issue reporting the same problem does not already exist.
If any part of the Nacos project has bugs or documentation mistakes, please let us know by [opening an issue][Nacos-issue]. We treat bugs and mistakes very seriously and believe no issue is too small, anyone is implement. Before creating a bug report, please check that an issue reporting the same problem does not already exist.
To make the bug report accurate and easy to understand, please try to create bug reports that are:

View File

@ -27,13 +27,7 @@
<packaging>jar</packaging>
<name>nacos-address ${project.version}</name>
<url>http://nacos.io</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<url>https://nacos.io</url>
<dependencies>
<dependency>

View File

@ -28,7 +28,7 @@
<packaging>jar</packaging>
<name>nacos-api ${project.version}</name>
<url>http://nacos.io</url>
<url>https://nacos.io</url>
<build>
<plugins>
<!-- reuse when you need to update grpc model -->
@ -50,22 +50,9 @@
</execution>
</executions>
</plugin>-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
@ -105,11 +92,6 @@
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>protoc-gen-grpc-java</artifactId>
<type>pom</type>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>

View File

@ -75,7 +75,7 @@ public class Result<T> implements Serializable {
* @return Result
*/
public static Result<String> failure(String message) {
return Result.failure(ErrorCode.SERVER_ERROR, message);
return new Result<>(ErrorCode.SERVER_ERROR.getCode(), message);
}
/**

View File

@ -25,6 +25,7 @@ import com.fasterxml.jackson.annotation.JsonInclude.Include;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
/**
* Instance.
@ -209,7 +210,7 @@ public class Instance implements Serializable {
}
private static boolean strEquals(final String str1, final String str2) {
return str1 == null ? str2 == null : str1.equals(str2);
return Objects.equals(str1, str2);
}
public long getInstanceHeartBeatInterval() {

View File

@ -24,7 +24,6 @@ import com.fasterxml.jackson.annotation.JsonInclude.Include;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
@ -36,15 +35,22 @@ import java.util.List;
@JsonInclude(Include.NON_NULL)
public class ServiceInfo {
/**
* file name pattern: groupName@@name@clusters.
*/
private static final int GROUP_POSITION = 0;
private static final int SERVICE_POSITION = 1;
private static final int CLUSTER_POSITION = 2;
private static final int FILE_NAME_PARTS = 3;
@JsonIgnore
private String jsonFromServer = EMPTY;
private static final String EMPTY = "";
private static final String ALL_IPS = "000--00-ALL_IPS--00--000";
public static final String SPLITER = "@@";
private static final String DEFAULT_CHARSET = "UTF-8";
private String name;
@ -80,20 +86,15 @@ public class ServiceInfo {
* There is only one form of the key:groupName@@name@clusters. This constructor used by DiskCache.read(String) and
* FailoverReactor.FailoverFileReader,you should know that 'groupName' must not be null,and 'clusters' can be null.
*/
public ServiceInfo(String key) {
int maxIndex = 2;
int clusterIndex = 2;
int serviceNameIndex = 1;
int groupIndex = 0;
public ServiceInfo(final String key) {
String[] keys = key.split(Constants.SERVICE_INFO_SPLITER);
if (keys.length >= maxIndex + 1) {
this.groupName = keys[groupIndex];
this.name = keys[serviceNameIndex];
this.clusters = keys[clusterIndex];
} else if (keys.length == maxIndex) {
this.groupName = keys[groupIndex];
this.name = keys[serviceNameIndex];
if (keys.length >= FILE_NAME_PARTS) {
this.groupName = keys[GROUP_POSITION];
this.name = keys[SERVICE_POSITION];
this.clusters = keys[CLUSTER_POSITION];
} else if (keys.length == CLUSTER_POSITION) {
this.groupName = keys[GROUP_POSITION];
this.name = keys[SERVICE_POSITION];
} else {
//defensive programming
throw new IllegalArgumentException("Can't parse out 'groupName',but it must not be null!");
@ -231,8 +232,7 @@ public class ServiceInfo {
String serviceName = getGroupedServiceName();
try {
serviceName = URLEncoder.encode(serviceName, DEFAULT_CHARSET);
} catch (UnsupportedEncodingException e) {
//do nothing
} catch (UnsupportedEncodingException ignored) {
}
return getKey(serviceName, clusters);
}
@ -251,19 +251,8 @@ public class ServiceInfo {
* @param key key of service info
* @return new service info
*/
public static ServiceInfo fromKey(String key) {
ServiceInfo serviceInfo = new ServiceInfo();
int maxSegCount = 3;
String[] segs = key.split(Constants.SERVICE_INFO_SPLITER);
if (segs.length == maxSegCount - 1) {
serviceInfo.setGroupName(segs[0]);
serviceInfo.setName(segs[1]);
} else if (segs.length == maxSegCount) {
serviceInfo.setGroupName(segs[0]);
serviceInfo.setName(segs[1]);
serviceInfo.setClusters(segs[2]);
}
return serviceInfo;
public static ServiceInfo fromKey(final String key) {
return new ServiceInfo(key);
}
@Override
@ -283,18 +272,10 @@ public class ServiceInfo {
return str == null || str.length() == 0;
}
private static boolean isEmpty(Collection coll) {
return (coll == null || coll.isEmpty());
}
private static boolean strEquals(String str1, String str2) {
return str1 == null ? str2 == null : str1.equals(str2);
}
public boolean isReachProtectionThreshold() {
return reachProtectionThreshold;
}
public void setReachProtectionThreshold(boolean reachProtectionThreshold) {
this.reachProtectionThreshold = reachProtectionThreshold;
}

View File

@ -21,10 +21,10 @@ import com.alibaba.nacos.api.naming.pojo.healthcheck.AbstractHealthChecker;
import com.alibaba.nacos.api.utils.StringUtils;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.util.Objects;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
/**
* Implementation of health checker for HTTP.
@ -100,10 +100,6 @@ public class Http extends AbstractHealthChecker {
final Http other = (Http) obj;
if (!StringUtils.equals(type, other.getType())) {
return false;
}
if (!StringUtils.equals(path, other.getPath())) {
return false;
}

View File

@ -34,6 +34,11 @@ public class ServerRemoteAbility implements Serializable {
*/
private boolean supportRemoteConnection;
/**
* if support grpc report.
*/
private boolean grpcReportEnabled = true;
public boolean isSupportRemoteConnection() {
return this.supportRemoteConnection;
}
@ -42,6 +47,14 @@ public class ServerRemoteAbility implements Serializable {
this.supportRemoteConnection = supportRemoteConnection;
}
public boolean isGrpcReportEnabled() {
return grpcReportEnabled;
}
public void setGrpcReportEnabled(boolean grpcReportEnabled) {
this.grpcReportEnabled = grpcReportEnabled;
}
@Override
public boolean equals(Object o) {
if (this == o) {
@ -51,11 +64,11 @@ public class ServerRemoteAbility implements Serializable {
return false;
}
ServerRemoteAbility that = (ServerRemoteAbility) o;
return supportRemoteConnection == that.supportRemoteConnection;
return supportRemoteConnection == that.supportRemoteConnection && grpcReportEnabled == that.grpcReportEnabled;
}
@Override
public int hashCode() {
return Objects.hash(supportRemoteConnection);
return Objects.hash(supportRemoteConnection, grpcReportEnabled);
}
}

View File

@ -0,0 +1,57 @@
#
# Copyright 1999-2021 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.
#
#
com.alibaba.nacos.api.remote.request.ClientDetectionRequest
com.alibaba.nacos.api.remote.request.ConnectionSetupRequest
com.alibaba.nacos.api.remote.request.ConnectResetRequest
com.alibaba.nacos.api.remote.request.HealthCheckRequest
com.alibaba.nacos.api.remote.request.PushAckRequest
com.alibaba.nacos.api.remote.request.ServerCheckRequest
com.alibaba.nacos.api.remote.request.ServerLoaderInfoRequest
com.alibaba.nacos.api.remote.request.ServerReloadRequest
com.alibaba.nacos.api.remote.response.ClientDetectionResponse
com.alibaba.nacos.api.remote.response.ConnectResetResponse
com.alibaba.nacos.api.remote.response.ErrorResponse
com.alibaba.nacos.api.remote.response.HealthCheckResponse
com.alibaba.nacos.api.remote.response.ServerCheckResponse
com.alibaba.nacos.api.remote.response.ServerLoaderInfoResponse
com.alibaba.nacos.api.remote.response.ServerReloadResponse
com.alibaba.nacos.api.config.remote.request.ClientConfigMetricRequest
com.alibaba.nacos.api.config.remote.request.ConfigBatchListenRequest
com.alibaba.nacos.api.config.remote.request.ConfigChangeNotifyRequest
com.alibaba.nacos.api.config.remote.request.ConfigPublishRequest
com.alibaba.nacos.api.config.remote.request.ConfigQueryRequest
com.alibaba.nacos.api.config.remote.request.ConfigRemoveRequest
com.alibaba.nacos.api.config.remote.response.ClientConfigMetricResponse
com.alibaba.nacos.api.config.remote.response.ConfigChangeBatchListenResponse
com.alibaba.nacos.api.config.remote.response.ConfigChangeNotifyResponse
com.alibaba.nacos.api.config.remote.response.ConfigPublishResponse
com.alibaba.nacos.api.config.remote.response.ConfigQueryResponse
com.alibaba.nacos.api.config.remote.response.ConfigRemoveResponse
com.alibaba.nacos.api.config.remote.request.cluster.ConfigChangeClusterSyncRequest
com.alibaba.nacos.api.config.remote.response.cluster.ConfigChangeClusterSyncResponse
com.alibaba.nacos.api.naming.remote.request.BatchInstanceRequest
com.alibaba.nacos.api.naming.remote.request.InstanceRequest
com.alibaba.nacos.api.naming.remote.request.NotifySubscriberRequest
com.alibaba.nacos.api.naming.remote.request.ServiceListRequest
com.alibaba.nacos.api.naming.remote.request.ServiceQueryRequest
com.alibaba.nacos.api.naming.remote.request.SubscribeServiceRequest
com.alibaba.nacos.api.naming.remote.response.BatchInstanceResponse
com.alibaba.nacos.api.naming.remote.response.InstanceResponse
com.alibaba.nacos.api.naming.remote.response.NotifySubscriberResponse
com.alibaba.nacos.api.naming.remote.response.QueryServiceResponse
com.alibaba.nacos.api.naming.remote.response.ServiceListResponse
com.alibaba.nacos.api.naming.remote.response.SubscribeServiceResponse

View File

@ -0,0 +1,59 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.ability;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class ClientAbilitiesTest {
private static ObjectMapper mapper;
@BeforeClass
public static void setUp() throws Exception {
mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
@Test
public void testSerialize() throws JsonProcessingException {
ClientAbilities abilities = new ClientAbilities();
String json = mapper.writeValueAsString(abilities);
assertTrue(json.contains("\"remoteAbility\":{"));
assertTrue(json.contains("\"configAbility\":{"));
assertTrue(json.contains("\"namingAbility\":{"));
}
@Test
public void testDeserialize() throws JsonProcessingException {
String json = "{\"remoteAbility\":{\"supportRemoteConnection\":false},"
+ "\"configAbility\":{\"supportRemoteMetrics\":false},\"namingAbility\":{\"supportDeltaPush\":false,"
+ "\"supportRemoteMetric\":false}}";
ClientAbilities abilities = mapper.readValue(json, ClientAbilities.class);
assertNotNull(abilities.getRemoteAbility());
assertNotNull(abilities.getNamingAbility());
assertNotNull(abilities.getConfigAbility());
}
}

View File

@ -0,0 +1,83 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.ability;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class ServerAbilitiesTest {
private static ObjectMapper mapper;
private ServerAbilities serverAbilities;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
@Before
public void setUp() throws Exception {
serverAbilities = new ServerAbilities();
}
@Test
public void testSerialize() throws JsonProcessingException {
serverAbilities = new ServerAbilities();
String json = mapper.writeValueAsString(serverAbilities);
assertTrue(json.contains("\"remoteAbility\":{"));
assertTrue(json.contains("\"configAbility\":{"));
assertTrue(json.contains("\"namingAbility\":{"));
}
@Test
public void testDeserialize() throws JsonProcessingException {
String json = "{\"remoteAbility\":{\"supportRemoteConnection\":false},"
+ "\"configAbility\":{\"supportRemoteMetrics\":false},\"namingAbility\":{\"supportDeltaPush\":false,"
+ "\"supportRemoteMetric\":false}}";
ServerAbilities abilities = mapper.readValue(json, ServerAbilities.class);
assertNotNull(abilities.getRemoteAbility());
assertNotNull(abilities.getNamingAbility());
assertNotNull(abilities.getConfigAbility());
}
@Test
public void testEqualsAndHashCode() {
assertEquals(serverAbilities, serverAbilities);
assertEquals(serverAbilities.hashCode(), serverAbilities.hashCode());
assertNotEquals(serverAbilities, null);
assertNotEquals(serverAbilities, new ClientAbilities());
ServerAbilities test = new ServerAbilities();
assertEquals(serverAbilities, test);
assertEquals(serverAbilities.hashCode(), test.hashCode());
test.setRemoteAbility(null);
assertNotEquals(serverAbilities, test);
assertNotEquals(serverAbilities.hashCode(), test.hashCode());
}
}

View File

@ -0,0 +1,55 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.config.ability;
import com.alibaba.nacos.api.remote.ability.ClientRemoteAbility;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class ClientRemoteAbilityTest {
private static ObjectMapper mapper;
@BeforeClass
public static void setUp() throws Exception {
mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
@Test
public void testSerialize() throws JsonProcessingException {
ClientRemoteAbility abilities = new ClientRemoteAbility();
String json = mapper.writeValueAsString(abilities);
assertEquals("{\"supportRemoteConnection\":false}", json);
}
@Test
public void testDeserialize() throws JsonProcessingException {
String json = "{\"supportRemoteConnection\":true}";
ClientRemoteAbility abilities = mapper.readValue(json, ClientRemoteAbility.class);
assertTrue(abilities.isSupportRemoteConnection());
}
}

View File

@ -0,0 +1,83 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.config.ability;
import com.alibaba.nacos.api.ability.ClientAbilities;
import com.alibaba.nacos.api.remote.ability.ServerRemoteAbility;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
public class ServerRemoteAbilityTest {
private static ObjectMapper mapper;
private ServerRemoteAbility serverAbilities;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
@Before
public void setUp() throws Exception {
serverAbilities = new ServerRemoteAbility();
}
@Test
public void testSerialize() throws JsonProcessingException {
serverAbilities = new ServerRemoteAbility();
String json = mapper.writeValueAsString(serverAbilities);
assertEquals("{\"supportRemoteConnection\":false,\"grpcReportEnabled\":true}", json);
}
@Test
public void testDeserialize() throws JsonProcessingException {
String json = "{\"supportRemoteConnection\":true,\"grpcReportEnabled\":true}";
ServerRemoteAbility abilities = mapper.readValue(json, ServerRemoteAbility.class);
assertTrue(abilities.isSupportRemoteConnection());
assertTrue(abilities.isGrpcReportEnabled());
}
@Test
public void testEqualsAndHashCode() {
assertEquals(serverAbilities, serverAbilities);
assertEquals(serverAbilities.hashCode(), serverAbilities.hashCode());
assertNotEquals(serverAbilities, null);
assertNotEquals(serverAbilities, new ClientAbilities());
ServerRemoteAbility test = new ServerRemoteAbility();
assertEquals(serverAbilities, test);
assertEquals(serverAbilities.hashCode(), test.hashCode());
test.setSupportRemoteConnection(true);
assertNotEquals(serverAbilities, test);
assertNotEquals(serverAbilities.hashCode(), test.hashCode());
test.setSupportRemoteConnection(false);
test.setGrpcReportEnabled(false);
assertNotEquals(serverAbilities, test);
assertNotEquals(serverAbilities.hashCode(), test.hashCode());
}
}

View File

@ -0,0 +1,71 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.model.v2;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class ResultTest {
@Test
public void testSuccessEmptyResult() {
Result<String> result = Result.success();
assertNull(result.getData());
assertEquals(ErrorCode.SUCCESS.getCode(), result.getCode());
assertEquals(ErrorCode.SUCCESS.getMsg(), result.getMessage());
}
@Test
public void testSuccessWithData() {
Result<String> result = Result.success("test");
assertEquals("test", result.getData());
assertEquals(ErrorCode.SUCCESS.getCode(), result.getCode());
assertEquals(ErrorCode.SUCCESS.getMsg(), result.getMessage());
}
@Test
public void testFailureMessageResult() {
Result<String> result = Result.failure("test");
assertNull(result.getData());
assertEquals(ErrorCode.SERVER_ERROR.getCode(), result.getCode());
assertEquals("test", result.getMessage());
}
@Test
public void testFailureWithoutData() {
Result<String> result = Result.failure(ErrorCode.DATA_ACCESS_ERROR);
assertNull(result.getData());
assertEquals(ErrorCode.DATA_ACCESS_ERROR.getCode(), result.getCode());
assertEquals(ErrorCode.DATA_ACCESS_ERROR.getMsg(), result.getMessage());
}
@Test
public void testFailureWithData() {
Result<String> result = Result.failure(ErrorCode.DATA_ACCESS_ERROR, "error");
assertEquals("error", result.getData());
assertEquals(ErrorCode.DATA_ACCESS_ERROR.getCode(), result.getCode());
assertEquals(ErrorCode.DATA_ACCESS_ERROR.getMsg(), result.getMessage());
}
@Test
public void testToString() {
Result<String> result = Result.success("test");
assertEquals("Result{errorCode=0, message='success', data=test}", result.toString());
}
}

View File

@ -0,0 +1,36 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.naming.ability;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class ClientNamingAbilityTest {
@Test
public void testGetAndSet() {
ClientNamingAbility ability = new ClientNamingAbility();
assertFalse(ability.isSupportDeltaPush());
assertFalse(ability.isSupportRemoteMetric());
ability.setSupportDeltaPush(true);
ability.setSupportRemoteMetric(true);
assertTrue(ability.isSupportDeltaPush());
assertTrue(ability.isSupportRemoteMetric());
}
}

View File

@ -26,6 +26,7 @@ import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
public class ServerNamingAbilityTest {
@ -57,4 +58,29 @@ public class ServerNamingAbilityTest {
actual.setSupportJraft(true);
assertEquals(expected, actual);
}
@Test
public void testEqualsForOneObject() {
ServerNamingAbility ability = new ServerNamingAbility();
assertTrue(ability.equals(ability));
}
@Test
public void testEqualsForOtherAbility() {
ServerNamingAbility ability = new ServerNamingAbility();
assertFalse(ability.equals(new ClientNamingAbility()));
}
@Test
public void testHashCode() throws JsonProcessingException {
ServerNamingAbility expected = new ServerNamingAbility();
expected.setSupportJraft(true);
String serializeJson = jacksonMapper.writeValueAsString(expected);
ServerNamingAbility actual = jacksonMapper.readValue(serializeJson, ServerNamingAbility.class);
assertEquals(expected, actual);
actual = new ServerNamingAbility();
assertNotEquals(expected, actual);
actual.setSupportJraft(true);
assertEquals(expected.hashCode(), actual.hashCode());
}
}

View File

@ -0,0 +1,77 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.naming.listener;
import org.junit.Before;
import org.junit.Test;
import java.util.Collections;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
public class NamingEventTest {
private MockNamingEventListener eventListener;
@Before
public void setUp() throws Exception {
eventListener = new MockNamingEventListener();
}
@Test
public void testNamingEventWithSimpleConstructor() {
NamingEvent event = new NamingEvent("serviceName", Collections.EMPTY_LIST);
assertEquals("serviceName", event.getServiceName());
assertNull(event.getGroupName());
assertNull(event.getClusters());
assertTrue(event.getInstances().isEmpty());
eventListener.onEvent(event);
assertNull(event.getServiceName());
assertNull(event.getGroupName());
assertNull(event.getClusters());
assertNull(event.getInstances());
}
@Test
public void testNamingEventWithFullConstructor() {
NamingEvent event = new NamingEvent("serviceName", "group", "clusters", Collections.EMPTY_LIST);
assertEquals("serviceName", event.getServiceName());
assertEquals("group", event.getGroupName());
assertEquals("clusters", event.getClusters());
assertTrue(event.getInstances().isEmpty());
eventListener.onEvent(event);
assertNull(event.getServiceName());
assertNull(event.getGroupName());
assertNull(event.getClusters());
assertNull(event.getInstances());
}
private static class MockNamingEventListener extends AbstractEventListener {
@Override
public void onEvent(Event event) {
assertNull(getExecutor());
NamingEvent namingEvent = (NamingEvent) event;
namingEvent.setServiceName(null);
namingEvent.setGroupName(null);
namingEvent.setClusters(null);
namingEvent.setInstances(null);
}
}
}

View File

@ -0,0 +1,109 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.naming.pojo;
import com.alibaba.nacos.api.naming.pojo.healthcheck.impl.Http;
import com.alibaba.nacos.api.naming.pojo.healthcheck.impl.Tcp;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.Collections;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
public class ClusterTest {
private static ObjectMapper mapper;
@BeforeClass
public static void setUp() throws Exception {
mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
@Test
public void testSetAndGet() {
Cluster actual = new Cluster();
assertNull(actual.getName());
assertNull(actual.getServiceName());
assertEquals(Tcp.TYPE, actual.getHealthChecker().getType());
assertEquals(80, actual.getDefaultPort());
assertEquals(80, actual.getDefaultCheckPort());
assertTrue(actual.isUseIPPort4Check());
assertTrue(actual.getMetadata().isEmpty());
actual.setName("cluster");
actual.setServiceName("group@@service");
actual.setHealthChecker(new Http());
actual.setDefaultPort(81);
actual.setDefaultCheckPort(82);
actual.setUseIPPort4Check(false);
actual.setMetadata(Collections.singletonMap("a", "a"));
assertEquals("cluster", actual.getName());
assertEquals("group@@service", actual.getServiceName());
assertEquals(Http.TYPE, actual.getHealthChecker().getType());
assertEquals(81, actual.getDefaultPort());
assertEquals(82, actual.getDefaultCheckPort());
assertFalse(actual.isUseIPPort4Check());
assertFalse(actual.getMetadata().isEmpty());
assertTrue(actual.getMetadata().containsKey("a"));
assertEquals("a", actual.getMetadata().get("a"));
}
@Test
public void testJsonSerialize() throws JsonProcessingException {
Cluster actual = new Cluster("cluster");
actual.setServiceName("group@@service");
actual.setHealthChecker(new Http());
actual.setDefaultPort(81);
actual.setDefaultCheckPort(82);
actual.setUseIPPort4Check(false);
actual.setMetadata(Collections.singletonMap("a", "a"));
String json = mapper.writeValueAsString(actual);
assertTrue(json.contains("\"serviceName\":\"group@@service\""));
assertTrue(json.contains("\"name\":\"cluster\""));
assertTrue(json.contains("\"type\":\"HTTP\""));
assertTrue(json.contains("\"defaultPort\":81"));
assertTrue(json.contains("\"defaultCheckPort\":82"));
assertTrue(json.contains("\"useIPPort4Check\":false"));
assertTrue(json.contains("\"metadata\":{\"a\":\"a\"}"));
}
@Test
public void testJsonDeserialize() throws JsonProcessingException {
String json = "{\"serviceName\":\"group@@service\",\"name\":\"cluster\","
+ "\"healthChecker\":{\"type\":\"HTTP\",\"path\":\"\",\"headers\":\"\",\"expectedResponseCode\":200},"
+ "\"defaultPort\":81,\"defaultCheckPort\":82,\"useIPPort4Check\":false,\"metadata\":{\"a\":\"a\"}}";
Cluster actual = mapper.readValue(json, Cluster.class);
assertEquals("cluster", actual.getName());
assertEquals("group@@service", actual.getServiceName());
assertEquals(Http.TYPE, actual.getHealthChecker().getType());
assertEquals(81, actual.getDefaultPort());
assertEquals(82, actual.getDefaultCheckPort());
assertFalse(actual.isUseIPPort4Check());
assertFalse(actual.getMetadata().isEmpty());
assertTrue(actual.getMetadata().containsKey("a"));
assertEquals("a", actual.getMetadata().get("a"));
}
}

View File

@ -16,15 +16,154 @@
package com.alibaba.nacos.api.naming.pojo;
import junit.framework.TestCase;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.naming.PreservedMetadataKeys;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.BeforeClass;
import org.junit.Test;
public class InstanceTest extends TestCase {
import java.util.Collections;
import java.util.HashMap;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
public class InstanceTest {
private static ObjectMapper mapper;
@BeforeClass
public static void setUp() throws Exception {
mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
@Test
public void testSetAndGet() {
Instance instance = new Instance();
assertNull(instance.getInstanceId());
assertNull(instance.getIp());
assertEquals(0, instance.getPort());
assertEquals(1.0D, instance.getWeight(), 0.1);
assertTrue(instance.isHealthy());
assertTrue(instance.isEnabled());
assertTrue(instance.isEphemeral());
assertNull(instance.getClusterName());
assertNull(instance.getServiceName());
assertTrue(instance.getMetadata().isEmpty());
setInstance(instance);
checkInstance(instance);
}
@Test
public void testJsonSerialize() throws JsonProcessingException {
Instance instance = new Instance();
setInstance(instance);
String actual = mapper.writeValueAsString(instance);
assertTrue(actual.contains("\"instanceId\":\"id\""));
assertTrue(actual.contains("\"ip\":\"1.1.1.1\""));
assertTrue(actual.contains("\"port\":1000"));
assertTrue(actual.contains("\"weight\":100.0"));
assertTrue(actual.contains("\"healthy\":false"));
assertTrue(actual.contains("\"enabled\":false"));
assertTrue(actual.contains("\"ephemeral\":false"));
assertTrue(actual.contains("\"clusterName\":\"cluster\""));
assertTrue(actual.contains("\"serviceName\":\"group@@serviceName\""));
assertTrue(actual.contains("\"metadata\":{\"a\":\"b\"}"));
assertTrue(actual.contains("\"instanceHeartBeatInterval\":5000"));
assertTrue(actual.contains("\"instanceHeartBeatTimeOut\":15000"));
assertTrue(actual.contains("\"ipDeleteTimeout\":30000"));
}
@Test
public void testJsonDeserialize() throws JsonProcessingException {
String json = "{\"instanceId\":\"id\",\"ip\":\"1.1.1.1\",\"port\":1000,\"weight\":100.0,\"healthy\":false,"
+ "\"enabled\":false,\"ephemeral\":false,\"clusterName\":\"cluster\","
+ "\"serviceName\":\"group@@serviceName\",\"metadata\":{\"a\":\"b\"},\"instanceHeartBeatInterval\":5000,"
+ "\"instanceHeartBeatTimeOut\":15000,\"ipDeleteTimeout\":30000}";
Instance instance = mapper.readValue(json, Instance.class);
checkInstance(instance);
}
@Test
public void testCheckClusterNameFormat() {
Instance instance = new Instance();
instance.setClusterName("demo");
assertEquals("demo", instance.getClusterName());
}
@Test
public void testToInetAddr() {
Instance instance = new Instance();
setInstance(instance);
assertEquals("1.1.1.1:1000", instance.toInetAddr());
}
@Test
public void testContainsMetadata() {
Instance instance = new Instance();
assertFalse(instance.containsMetadata("a"));
instance.setMetadata(null);
assertFalse(instance.containsMetadata("a"));
instance.addMetadata("a", "b");
assertTrue(instance.containsMetadata("a"));
}
@Test
public void testGetInstanceIdGenerator() {
Instance instance = new Instance();
assertEquals(Constants.DEFAULT_INSTANCE_ID_GENERATOR, instance.getInstanceIdGenerator());
instance.addMetadata(PreservedMetadataKeys.INSTANCE_ID_GENERATOR, "test");
assertEquals("test", instance.getInstanceIdGenerator());
}
@Test
public void testEquals() {
Instance actual = new Instance();
setInstance(actual);
actual.setMetadata(new HashMap<>());
actual.addMetadata("a", "b");
assertFalse(actual.equals(new Object()));
Instance expected = new Instance();
setInstance(expected);
expected.setMetadata(new HashMap<>());
expected.addMetadata("a", "b");
assertTrue(actual.equals(expected));
expected.addMetadata("a", "c");
assertFalse(actual.equals(expected));
}
private void setInstance(Instance instance) {
instance.setInstanceId("id");
instance.setIp("1.1.1.1");
instance.setPort(1000);
instance.setWeight(100);
instance.setHealthy(false);
instance.setEnabled(false);
instance.setEphemeral(false);
instance.setClusterName("cluster");
instance.setServiceName("group@@serviceName");
instance.setMetadata(Collections.singletonMap("a", "b"));
}
private void checkInstance(Instance instance) {
assertEquals("id", instance.getInstanceId());
assertEquals("1.1.1.1", instance.getIp());
assertEquals(1000, instance.getPort());
assertEquals(100D, instance.getWeight(), 0.1);
assertFalse(instance.isHealthy());
assertFalse(instance.isEnabled());
assertFalse(instance.isEphemeral());
assertEquals("cluster", instance.getClusterName());
assertEquals("group@@serviceName", instance.getServiceName());
assertFalse(instance.getMetadata().isEmpty());
assertTrue(instance.containsMetadata("a"));
assertEquals("b", instance.getMetadata().get("a"));
}
}

View File

@ -0,0 +1,53 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.naming.pojo;
import org.junit.Test;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class ListViewTest {
@Test
public void testToString() {
List<String> data = new LinkedList<>();
data.add("1");
data.add("2");
data.add("3");
ListView<String> listView = new ListView<>();
listView.setData(data);
listView.setCount(data.size());
String actual = listView.toString();
assertEquals("ListView{data=[1, 2, 3], count=3}", actual);
}
@Test
public void testSetAndGet() {
ListView<String> listView = new ListView<>();
assertEquals(0, listView.getCount());
assertNull(listView.getData());
listView.setCount(1);
listView.setData(Collections.singletonList("1"));
assertEquals(1, listView.getCount());
assertEquals(1, listView.getData().size());
}
}

View File

@ -16,6 +16,7 @@
package com.alibaba.nacos.api.naming.pojo;
import com.alibaba.nacos.api.utils.StringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
@ -25,6 +26,9 @@ import org.junit.Test;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@ -65,11 +69,13 @@ public class ServiceInfoTest {
+ "\"lastRefTime\":0,\"checksum\":\"\",\"allIPs\":false,\"valid\":true,\"groupName\":\"\"}";
ServiceInfo actual = mapper.readValue(example, ServiceInfo.class);
assertEquals("G@@testName", actual.getName());
assertEquals(0, actual.ipCount());
assertEquals("testClusters", actual.getClusters());
assertEquals("", actual.getChecksum());
assertEquals("", actual.getGroupName());
assertEquals(1000, actual.getCacheMillis());
assertEquals(0, actual.getLastRefTime());
assertTrue(actual.expired());
assertTrue(actual.getHosts().isEmpty());
assertTrue(actual.isValid());
assertFalse(actual.isAllIPs());
@ -79,6 +85,7 @@ public class ServiceInfoTest {
public void testGetKey() {
String key = serviceInfo.getKey();
assertEquals("G@@testName@@testClusters", key);
assertEquals("G@@testName@@testClusters", serviceInfo.toString());
}
@Test
@ -102,4 +109,67 @@ public class ServiceInfoTest {
assertEquals(key1, s1.getKey());
assertEquals(key2, s2.getKey());
}
@Test(expected = IllegalArgumentException.class)
public void testServiceInfoConstructorWithError() {
String key1 = "name";
ServiceInfo s1 = new ServiceInfo(key1);
}
@Test
public void testValidateForAllIps() {
serviceInfo.setAllIPs(true);
assertTrue(serviceInfo.validate());
}
@Test
public void testValidateForNullHosts() {
serviceInfo.setHosts(null);
assertFalse(serviceInfo.validate());
}
@Test
public void testValidateForEmptyHosts() {
serviceInfo.setHosts(Collections.EMPTY_LIST);
assertFalse(serviceInfo.validate());
}
@Test
public void testValidateForUnhealthyHosts() {
Instance instance = new Instance();
instance.setHealthy(false);
serviceInfo.addHost(instance);
assertFalse(serviceInfo.validate());
}
@Test
public void testValidateForBothUnhealthyAndHealthyHosts() {
List<Instance> instanceList = new LinkedList<>();
Instance instance = new Instance();
instanceList.add(instance);
instance = new Instance();
instance.setHealthy(false);
instanceList.add(instance);
serviceInfo.addAllHosts(instanceList);
assertTrue(serviceInfo.validate());
}
@Test
public void testFromKey() {
String key1 = "group@@name";
String key2 = "group@@name@@c2";
ServiceInfo s1 = ServiceInfo.fromKey(key1);
ServiceInfo s2 = ServiceInfo.fromKey(key2);
assertEquals(key1, s1.getKey());
assertEquals(key2, s2.getKey());
}
@Test
public void testSetAndGet() throws JsonProcessingException {
serviceInfo.setReachProtectionThreshold(true);
serviceInfo.setJsonFromServer(mapper.writeValueAsString(serviceInfo));
ServiceInfo actual = mapper.readValue(serviceInfo.getJsonFromServer(), ServiceInfo.class);
assertEquals(StringUtils.EMPTY, actual.getJsonFromServer());
assertTrue(actual.isReachProtectionThreshold());
}
}

View File

@ -0,0 +1,62 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.naming.pojo;
import org.junit.Test;
import java.util.Collections;
import java.util.HashMap;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
public class ServiceTest {
@Test
public void testSetAndGet() {
Service service = new Service();
assertNull(service.getName());
assertNull(service.getAppName());
assertNull(service.getGroupName());
assertEquals(0.0f, service.getProtectThreshold(), 0.1);
assertTrue(service.getMetadata().isEmpty());
service.setName("service");
service.setGroupName("group");
service.setAppName("app");
service.setProtectThreshold(1.0f);
HashMap<String, String> metadata = new HashMap<>();
service.setMetadata(metadata);
service.addMetadata("a", "b");
assertEquals("service", service.getName());
assertEquals("app", service.getAppName());
assertEquals("group", service.getGroupName());
assertEquals(1.0f, service.getProtectThreshold(), 0.1);
assertEquals(1, service.getMetadata().size());
assertEquals("b", service.getMetadata().get("a"));
}
@Test
public void testToString() {
Service service = new Service("service");
service.setGroupName("group");
service.setAppName("app");
service.setProtectThreshold(1.0f);
service.setMetadata(Collections.singletonMap("a", "b"));
assertEquals("Service{name='service', protectThreshold=1.0, appName='app', groupName='group', metadata={a=b}}", service.toString());
}
}

View File

@ -19,7 +19,11 @@ package com.alibaba.nacos.api.naming.pojo.builder;
import com.alibaba.nacos.api.naming.pojo.Instance;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
@ -67,6 +71,24 @@ public class InstanceBuilderTest {
assertThat(actual.getMetadata().get(META_KEY), is(META_VALUE));
}
@Test
public void testBuildInstanceWithoutNewMetadata() {
InstanceBuilder builder = InstanceBuilder.newBuilder();
Map<String, String> metadata = new HashMap<>();
metadata.put("test", "test");
Instance actual = builder.setMetadata(metadata).build();
assertNull(actual.getServiceName());
assertNull(actual.getClusterName());
assertNull(actual.getInstanceId());
assertNull(actual.getIp());
assertThat(actual.getPort(), is(0));
assertThat(actual.getWeight(), is(1.0));
assertTrue(actual.isHealthy());
assertTrue(actual.isEnabled());
assertTrue(actual.isEphemeral());
assertEquals(1, actual.getMetadata().size());
}
@Test
public void testBuildEmptyInstance() {
InstanceBuilder builder = InstanceBuilder.newBuilder();

View File

@ -54,4 +54,10 @@ public class AbstractHealthCheckerTest {
assertEquals("", actual.getTestValue());
assertEquals(TestChecker.TYPE, actual.getType());
}
@Test
public void testClone() throws CloneNotSupportedException {
AbstractHealthChecker none = new AbstractHealthChecker.None().clone();
assertEquals(AbstractHealthChecker.None.class, none.getClass());
}
}

View File

@ -0,0 +1,56 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.naming.pojo.healthcheck;
import com.alibaba.nacos.api.naming.pojo.healthcheck.impl.Http;
import com.alibaba.nacos.api.naming.pojo.healthcheck.impl.Mysql;
import com.alibaba.nacos.api.naming.pojo.healthcheck.impl.Tcp;
import org.junit.Test;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class HealthCheckTypeTest {
@Test
public void testOfHealthCheckerClassForBuildInType() {
assertEquals(Tcp.class, HealthCheckType.ofHealthCheckerClass("TCP"));
assertEquals(Http.class, HealthCheckType.ofHealthCheckerClass("HTTP"));
assertEquals(Mysql.class, HealthCheckType.ofHealthCheckerClass("MYSQL"));
assertEquals(AbstractHealthChecker.None.class, HealthCheckType.ofHealthCheckerClass("NONE"));
}
@Test
public void testOfHealthCheckerClassForExtendType() {
HealthCheckType.registerHealthChecker(TestChecker.TYPE, TestChecker.class);
assertEquals(TestChecker.class, HealthCheckType.ofHealthCheckerClass(TestChecker.TYPE));
}
@Test
public void testOfHealthCheckerClassForNonExistType() {
assertNull(HealthCheckType.ofHealthCheckerClass("non-exist"));
}
@Test
public void testGetLoadedHealthCheckerClasses() {
HealthCheckType.registerHealthChecker(TestChecker.TYPE, TestChecker.class);
List<Class<? extends AbstractHealthChecker>> actual = HealthCheckType.getLoadedHealthCheckerClasses();
assertEquals(5, actual.size());
}
}

View File

@ -16,18 +16,21 @@
package com.alibaba.nacos.api.naming.pojo.healthcheck;
import com.alibaba.nacos.api.exception.runtime.NacosDeserializationException;
import com.alibaba.nacos.api.exception.runtime.NacosSerializationException;
import com.alibaba.nacos.api.naming.pojo.healthcheck.impl.Tcp;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class HealthCheckerFactoryTest {
@BeforeClass
public static void beforeClass() {
HealthCheckerFactory.registerSubType(TestChecker.class, TestChecker.TYPE);
HealthCheckerFactory.registerSubType(new TestChecker());
}
@Test
@ -57,4 +60,74 @@ public class HealthCheckerFactoryTest {
AbstractHealthChecker actual = HealthCheckerFactory.deserialize(tcpString);
assertEquals(TestChecker.class, actual.getClass());
}
@Test
public void testSerializeNoRegister() {
NoRegisterHealthChecker noRegister = new NoRegisterHealthChecker();
assertFalse(HealthCheckerFactory.serialize(noRegister).contains("no register"));
}
@Test
public void testDeserializeNoRegister() {
String tcpString = "{\"type\":\"no register\",\"testValue\":null}";
AbstractHealthChecker actual = HealthCheckerFactory.deserialize(tcpString);
assertEquals(AbstractHealthChecker.None.class, actual.getClass());
}
@Test(expected = NacosSerializationException.class)
public void testSerializeFailure() {
SelfDependHealthChecker selfDependHealthChecker = new SelfDependHealthChecker();
System.out.println(HealthCheckerFactory.serialize(selfDependHealthChecker));
}
@Test(expected = NacosDeserializationException.class)
public void testDeserializeFailure() {
String errorString = "{\"type\"=\"TCP\"}";
System.out.println(HealthCheckerFactory.deserialize(errorString));
}
@Test
public void testCreateNoneHealthChecker() {
assertEquals(AbstractHealthChecker.None.class, HealthCheckerFactory.createNoneHealthChecker().getClass());
}
private static class NoRegisterHealthChecker extends AbstractHealthChecker {
private static final long serialVersionUID = 9020783491111797559L;
private String testValue;
protected NoRegisterHealthChecker() {
super("no register");
}
public String getTestValue() {
return testValue;
}
public void setTestValue(String testValue) {
this.testValue = testValue;
}
@Override
public AbstractHealthChecker clone() throws CloneNotSupportedException {
return null;
}
}
private static class SelfDependHealthChecker extends AbstractHealthChecker {
private static final long serialVersionUID = 876677992848225965L;
public SelfDependHealthChecker self = this;
protected SelfDependHealthChecker() {
super("self depend");
}
@Override
public AbstractHealthChecker clone() throws CloneNotSupportedException {
return null;
}
}
}

View File

@ -76,4 +76,25 @@ public class HttpTest {
assertEquals("x:a|y:", actual.getHeaders());
assertEquals(Http.TYPE, actual.getType());
}
@Test
public void testClone() throws CloneNotSupportedException {
Http cloned = http.clone();
assertEquals(http.hashCode(), cloned.hashCode());
assertTrue(http.equals(cloned));
}
@Test
public void testNotEquals() throws CloneNotSupportedException {
assertFalse(http.equals(new Tcp()));
Http cloned = http.clone();
cloned.setPath("aaa");
assertFalse(http.equals(cloned));
cloned = http.clone();
cloned.setHeaders("aaa");
assertFalse(http.equals(cloned));
cloned = http.clone();
cloned.setExpectedResponseCode(500);
assertFalse(http.equals(cloned));
}
}

View File

@ -24,6 +24,7 @@ import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class MysqlTest {
@ -59,4 +60,25 @@ public class MysqlTest {
assertEquals("user", actual.getUser());
assertEquals(Mysql.TYPE, actual.getType());
}
@Test
public void testClone() throws CloneNotSupportedException {
Mysql cloned = mysql.clone();
assertEquals(mysql.hashCode(), cloned.hashCode());
assertTrue(mysql.equals(cloned));
}
@Test
public void testNotEquals() throws CloneNotSupportedException {
assertFalse(mysql.equals(new Tcp()));
Mysql cloned = mysql.clone();
cloned.setUser("aaa");
assertFalse(mysql.equals(cloned));
cloned = mysql.clone();
cloned.setPwd("aaa");
assertFalse(mysql.equals(cloned));
cloned = mysql.clone();
cloned.setCmd("aaa");
assertFalse(mysql.equals(cloned));
}
}

View File

@ -0,0 +1,33 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.naming.pojo.healthcheck.impl;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class TcpTest {
@Test
public void testClone() throws CloneNotSupportedException {
Tcp original = new Tcp();
Tcp cloned = original.clone();
assertEquals(original.hashCode(), cloned.hashCode());
assertTrue(original.equals(cloned));
}
}

View File

@ -0,0 +1,64 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.naming.remote.request;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.BeforeClass;
import static com.alibaba.nacos.api.common.Constants.Naming.NAMING_MODULE;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public abstract class BasedNamingRequestTest {
protected static final String SERVICE = "service";
protected static final String GROUP = "group";
protected static final String NAMESPACE = "namespace";
protected static ObjectMapper mapper;
@BeforeClass
public static void setUp() throws Exception {
mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
protected void injectNamingRequestBasedInfo(AbstractNamingRequest request) {
request.setServiceName(SERVICE);
request.setGroupName(GROUP);
request.setNamespace(NAMESPACE);
}
protected void checkNamingRequestBasedInfo(AbstractNamingRequest request) {
assertEquals(SERVICE, request.getServiceName());
assertEquals(GROUP, request.getGroupName());
assertEquals(NAMESPACE, request.getNamespace());
assertEquals(NAMING_MODULE, request.getModule());
}
protected void checkSerializeBasedInfo(String json) {
assertTrue(json.contains("\"serviceName\":\"" + SERVICE + "\""));
assertTrue(json.contains("\"groupName\":\"" + GROUP + "\""));
assertTrue(json.contains("\"namespace\":\"" + NAMESPACE + "\""));
assertTrue(json.contains("\"module\":\"" + NAMING_MODULE + "\""));
}
}

View File

@ -0,0 +1,54 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.naming.remote.request;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.remote.NamingRemoteConstants;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.junit.Test;
import java.util.Collections;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class BatchInstanceRequestTest extends BasedNamingRequestTest {
@Test
public void testSerialize() throws JsonProcessingException {
BatchInstanceRequest request = new BatchInstanceRequest(NAMESPACE, SERVICE, GROUP,
NamingRemoteConstants.BATCH_REGISTER_INSTANCE, Collections.singletonList(new Instance()));
String json = mapper.writeValueAsString(request);
checkSerializeBasedInfo(json);
assertTrue(json.contains("\"type\":\"" + NamingRemoteConstants.BATCH_REGISTER_INSTANCE + "\""));
assertTrue(json.contains("\"instances\":[{"));
}
@Test
public void testDeserialize() throws JsonProcessingException {
String json = "{\"headers\":{},\"namespace\":\"namespace\",\"serviceName\":\"service\",\"groupName\":\"group\","
+ "\"type\":\"batchRegisterInstance\",\"instances\":[{\"port\":0,\"weight\":1.0,\"healthy\":true,"
+ "\"enabled\":true,\"ephemeral\":true,\"metadata\":{},\"instanceIdGenerator\":\"simple\","
+ "\"instanceHeartBeatInterval\":5000,\"instanceHeartBeatTimeOut\":15000,\"ipDeleteTimeout\":30000}],"
+ "\"module\":\"naming\"}";
BatchInstanceRequest actual = mapper.readValue(json, BatchInstanceRequest.class);
checkNamingRequestBasedInfo(actual);
assertEquals(NamingRemoteConstants.BATCH_REGISTER_INSTANCE, actual.getType());
assertEquals(1, actual.getInstances().size());
assertEquals(new Instance(), actual.getInstances().get(0));
}
}

View File

@ -0,0 +1,51 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.naming.remote.request;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.remote.NamingRemoteConstants;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class InstanceRequestTest extends BasedNamingRequestTest {
@Test
public void testSerialize() throws JsonProcessingException {
InstanceRequest request = new InstanceRequest(NAMESPACE, SERVICE, GROUP,
NamingRemoteConstants.REGISTER_INSTANCE, new Instance());
String json = mapper.writeValueAsString(request);
checkSerializeBasedInfo(json);
assertTrue(json.contains("\"type\":\"" + NamingRemoteConstants.REGISTER_INSTANCE + "\""));
assertTrue(json.contains("\"instance\":{"));
}
@Test
public void testDeserialize() throws JsonProcessingException {
String json = "{\"headers\":{},\"namespace\":\"namespace\",\"serviceName\":\"service\",\"groupName\":\"group\","
+ "\"type\":\"deregisterInstance\",\"instance\":{\"port\":0,\"weight\":1.0,\"healthy\":true,"
+ "\"enabled\":true,\"ephemeral\":true,\"metadata\":{},\"instanceIdGenerator\":\"simple\","
+ "\"instanceHeartBeatInterval\":5000,\"instanceHeartBeatTimeOut\":15000,\"ipDeleteTimeout\":30000},"
+ "\"module\":\"naming\"}";
InstanceRequest actual = mapper.readValue(json, InstanceRequest.class);
checkNamingRequestBasedInfo(actual);
assertEquals(NamingRemoteConstants.DE_REGISTER_INSTANCE, actual.getType());
assertEquals(new Instance(), actual.getInstance());
}
}

View File

@ -0,0 +1,84 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.naming.remote.request;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.BeforeClass;
import org.junit.Test;
import static com.alibaba.nacos.api.common.Constants.Naming.NAMING_MODULE;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class NotifySubscriberRequestTest {
private static final String SERVICE = "service";
private static final String GROUP = "group";
private static final String NAMESPACE = "namespace";
private static ObjectMapper mapper;
@BeforeClass
public static void setUp() throws Exception {
mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
@Test
public void testSerialize() throws JsonProcessingException {
ServiceInfo serviceInfo = new ServiceInfo(GROUP + "@@" + SERVICE);
NotifySubscriberRequest request = NotifySubscriberRequest.buildNotifySubscriberRequest(serviceInfo);
request.setServiceName(SERVICE);
request.setGroupName(GROUP);
request.setNamespace(NAMESPACE);
String json = mapper.writeValueAsString(request);
checkSerializeBasedInfo(json);
assertTrue(json.contains("\"serviceInfo\":{"));
}
@Test
public void testDeserialize() throws JsonProcessingException {
String json = "{\"headers\":{},\"namespace\":\"namespace\",\"serviceName\":\"service\",\"groupName\":\"group\","
+ "\"serviceInfo\":{\"name\":\"service\",\"groupName\":\"group\",\"cacheMillis\":1000,\"hosts\":[],"
+ "\"lastRefTime\":0,\"checksum\":\"\",\"allIPs\":false,\"reachProtectionThreshold\":false,"
+ "\"valid\":true},\"module\":\"naming\"}";
NotifySubscriberRequest actual = mapper.readValue(json, NotifySubscriberRequest.class);
checkRequestBasedInfo(actual);
assertEquals(GROUP + "@@" + SERVICE, actual.getServiceInfo().getKey());
}
private void checkRequestBasedInfo(NotifySubscriberRequest request) {
assertEquals(SERVICE, request.getServiceName());
assertEquals(GROUP, request.getGroupName());
assertEquals(NAMESPACE, request.getNamespace());
assertEquals(NAMING_MODULE, request.getModule());
}
private void checkSerializeBasedInfo(String json) {
assertTrue(json.contains("\"serviceName\":\"" + SERVICE + "\""));
assertTrue(json.contains("\"groupName\":\"" + GROUP + "\""));
assertTrue(json.contains("\"namespace\":\"" + NAMESPACE + "\""));
assertTrue(json.contains("\"module\":\"" + NAMING_MODULE + "\""));
}
}

View File

@ -0,0 +1,53 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.naming.remote.request;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.junit.Test;
import static com.alibaba.nacos.api.common.Constants.Naming.NAMING_MODULE;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class ServiceListRequestTest extends BasedNamingRequestTest {
@Test
public void testSerialize() throws JsonProcessingException {
ServiceListRequest request = new ServiceListRequest(NAMESPACE, GROUP, 1, 10);
request.setSelector("label");
String json = mapper.writeValueAsString(request);
assertTrue(json.contains("\"groupName\":\"" + GROUP + "\""));
assertTrue(json.contains("\"namespace\":\"" + NAMESPACE + "\""));
assertTrue(json.contains("\"module\":\"" + NAMING_MODULE + "\""));
assertTrue(json.contains("\"selector\":\"label\""));
assertTrue(json.contains("\"pageNo\":1"));
assertTrue(json.contains("\"pageSize\":10"));
}
@Test
public void testDeserialize() throws JsonProcessingException {
String json = "{\"headers\":{},\"namespace\":\"namespace\",\"serviceName\":\"\",\"groupName\":\"group\","
+ "\"pageNo\":1,\"pageSize\":10,\"selector\":\"label\",\"module\":\"naming\"}";
ServiceListRequest actual = mapper.readValue(json, ServiceListRequest.class);
assertEquals(GROUP, actual.getGroupName());
assertEquals(NAMESPACE, actual.getNamespace());
assertEquals(NAMING_MODULE, actual.getModule());
assertEquals(1, actual.getPageNo());
assertEquals(10, actual.getPageSize());
assertEquals("label", actual.getSelector());
}
}

View File

@ -0,0 +1,49 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.naming.remote.request;
import com.alibaba.nacos.api.common.Constants;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class ServiceQueryRequestTest extends BasedNamingRequestTest {
@Test
public void testSerialize() throws JsonProcessingException {
ServiceQueryRequest request = new ServiceQueryRequest(NAMESPACE, SERVICE, GROUP);
request.setCluster(Constants.DEFAULT_CLUSTER_NAME);
String json = mapper.writeValueAsString(request);
checkSerializeBasedInfo(json);
assertTrue(json.contains("\"cluster\":\"" + Constants.DEFAULT_CLUSTER_NAME + "\""));
assertTrue(json.contains("\"healthyOnly\":false"));
assertTrue(json.contains("\"udpPort\":0"));
}
@Test
public void testDeserialize() throws JsonProcessingException {
String json = "{\"headers\":{},\"namespace\":\"namespace\",\"serviceName\":\"service\",\"groupName\":\"group\","
+ "\"cluster\":\"DEFAULT\",\"healthyOnly\":true,\"udpPort\":0,\"module\":\"naming\"}";
ServiceQueryRequest actual = mapper.readValue(json, ServiceQueryRequest.class);
checkNamingRequestBasedInfo(actual);
assertEquals(Constants.DEFAULT_CLUSTER_NAME, actual.getCluster());
assertTrue(actual.isHealthyOnly());
assertEquals(0, actual.getUdpPort());
}
}

View File

@ -0,0 +1,46 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.naming.remote.request;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class SubscribeServiceRequestTest extends BasedNamingRequestTest {
@Test
public void testSerialize() throws JsonProcessingException {
SubscribeServiceRequest request = new SubscribeServiceRequest(NAMESPACE, GROUP, SERVICE, "", true);
String json = mapper.writeValueAsString(request);
checkSerializeBasedInfo(json);
assertTrue(json.contains("\"clusters\":\"\""));
assertTrue(json.contains("\"subscribe\":true"));
}
@Test
public void testDeserialize() throws JsonProcessingException {
String json = "{\"headers\":{},\"namespace\":\"namespace\",\"serviceName\":\"service\",\"groupName\":\"group\","
+ "\"subscribe\":false,\"clusters\":\"aa,bb\",\"module\":\"naming\"}";
SubscribeServiceRequest actual = mapper.readValue(json, SubscribeServiceRequest.class);
checkNamingRequestBasedInfo(actual);
assertEquals("aa,bb", actual.getClusters());
assertFalse(actual.isSubscribe());
}
}

View File

@ -0,0 +1,54 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.naming.remote.response;
import com.alibaba.nacos.api.naming.remote.NamingRemoteConstants;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class BatchInstanceResponseTest {
protected static ObjectMapper mapper;
@BeforeClass
public static void setUp() throws Exception {
mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
@Test
public void testSerialize() throws JsonProcessingException {
BatchInstanceResponse response = new BatchInstanceResponse(NamingRemoteConstants.REGISTER_INSTANCE);
String json = mapper.writeValueAsString(response);
assertTrue(json.contains("\"type\":\"" + NamingRemoteConstants.REGISTER_INSTANCE + "\""));
}
@Test
public void testDeserialize() throws JsonProcessingException {
String json = "{\"resultCode\":200,\"errorCode\":0,\"type\":\"registerInstance\",\"success\":true}";
BatchInstanceResponse response = mapper.readValue(json, BatchInstanceResponse.class);
assertEquals(NamingRemoteConstants.REGISTER_INSTANCE, response.getType());
}
}

View File

@ -0,0 +1,54 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.naming.remote.response;
import com.alibaba.nacos.api.naming.remote.NamingRemoteConstants;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class InstanceResponseTest {
protected static ObjectMapper mapper;
@BeforeClass
public static void setUp() throws Exception {
mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
@Test
public void testSerialize() throws JsonProcessingException {
InstanceResponse response = new InstanceResponse(NamingRemoteConstants.REGISTER_INSTANCE);
String json = mapper.writeValueAsString(response);
assertTrue(json.contains("\"type\":\"" + NamingRemoteConstants.REGISTER_INSTANCE + "\""));
}
@Test
public void testDeserialize() throws JsonProcessingException {
String json = "{\"resultCode\":200,\"errorCode\":0,\"type\":\"deregisterInstance\",\"success\":true}";
InstanceResponse response = mapper.readValue(json, InstanceResponse.class);
assertEquals(NamingRemoteConstants.DE_REGISTER_INSTANCE, response.getType());
}
}

View File

@ -0,0 +1,70 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.naming.remote.response;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class QueryServiceResponseTest {
protected static ObjectMapper mapper;
@BeforeClass
public static void setUp() throws Exception {
mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
@Test
public void testSerializeSuccessResponse() throws JsonProcessingException {
QueryServiceResponse response = QueryServiceResponse.buildSuccessResponse(new ServiceInfo());
String json = mapper.writeValueAsString(response);
assertTrue(json.contains("\"serviceInfo\":{"));
assertTrue(json.contains("\"resultCode\":200"));
assertTrue(json.contains("\"errorCode\":0"));
assertTrue(json.contains("\"success\":true"));
}
@Test
public void testSerializeFailResponse() throws JsonProcessingException {
QueryServiceResponse response = QueryServiceResponse.buildFailResponse("test");
String json = mapper.writeValueAsString(response);
assertTrue(json.contains("\"resultCode\":500"));
assertTrue(json.contains("\"errorCode\":0"));
assertTrue(json.contains("\"message\":\"test\""));
assertTrue(json.contains("\"success\":false"));
}
@Test
public void testDeserialize() throws JsonProcessingException {
String json = "{\"resultCode\":200,\"errorCode\":0,\"serviceInfo\":{\"cacheMillis\":1000,\"hosts\":[],"
+ "\"lastRefTime\":0,\"checksum\":\"\",\"allIPs\":false,\"reachProtectionThreshold\":false,"
+ "\"valid\":true},\"success\":true}";
QueryServiceResponse response = mapper.readValue(json, QueryServiceResponse.class);
assertNotNull(response.getServiceInfo());
}
}

View File

@ -0,0 +1,72 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.naming.remote.response;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.Collections;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class ServiceListResponseTest {
protected static ObjectMapper mapper;
@BeforeClass
public static void setUp() throws Exception {
mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
@Test
public void testSerializeSuccessResponse() throws JsonProcessingException {
ServiceListResponse response = ServiceListResponse.buildSuccessResponse(10, Collections.singletonList("a"));
String json = mapper.writeValueAsString(response);
assertTrue(json.contains("\"count\":10"));
assertTrue(json.contains("\"serviceNames\":[\"a\"]"));
assertTrue(json.contains("\"resultCode\":200"));
assertTrue(json.contains("\"errorCode\":0"));
assertTrue(json.contains("\"success\":true"));
}
@Test
public void testSerializeFailResponse() throws JsonProcessingException {
ServiceListResponse response = ServiceListResponse.buildFailResponse("test");
String json = mapper.writeValueAsString(response);
assertTrue(json.contains("\"resultCode\":500"));
assertTrue(json.contains("\"errorCode\":500"));
assertTrue(json.contains("\"message\":\"test\""));
assertTrue(json.contains("\"success\":false"));
}
@Test
public void testDeserialize() throws JsonProcessingException {
String json = "{\"resultCode\":200,\"errorCode\":0,\"count\":10,\"serviceNames\":[\"a\"],\"success\":true}";
ServiceListResponse response = mapper.readValue(json, ServiceListResponse.class);
assertEquals(10, response.getCount());
assertEquals(1, response.getServiceNames().size());
assertEquals("a", response.getServiceNames().get(0));
}
}

View File

@ -0,0 +1,70 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.naming.remote.response;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class SubscribeServiceResponseTest {
protected static ObjectMapper mapper;
@BeforeClass
public static void setUp() throws Exception {
mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
@Test
public void testSerializeSuccessResponse() throws JsonProcessingException {
SubscribeServiceResponse response = new SubscribeServiceResponse(200, null, new ServiceInfo());
String json = mapper.writeValueAsString(response);
assertTrue(json.contains("\"serviceInfo\":{"));
assertTrue(json.contains("\"resultCode\":200"));
assertTrue(json.contains("\"errorCode\":0"));
assertTrue(json.contains("\"success\":true"));
}
@Test
public void testSerializeFailResponse() throws JsonProcessingException {
SubscribeServiceResponse response = new SubscribeServiceResponse(500, "test", null);
String json = mapper.writeValueAsString(response);
assertTrue(json.contains("\"resultCode\":500"));
assertTrue(json.contains("\"errorCode\":0"));
assertTrue(json.contains("\"message\":\"test\""));
assertTrue(json.contains("\"success\":false"));
}
@Test
public void testDeserialize() throws JsonProcessingException {
String json = "{\"resultCode\":200,\"errorCode\":0,\"serviceInfo\":{\"cacheMillis\":1000,\"hosts\":[],"
+ "\"lastRefTime\":0,\"checksum\":\"\",\"allIPs\":false,\"reachProtectionThreshold\":false,"
+ "\"valid\":true},\"success\":true}";
SubscribeServiceResponse response = mapper.readValue(json, SubscribeServiceResponse.class);
assertNotNull(response.getServiceInfo());
}
}

View File

@ -16,6 +16,7 @@
package com.alibaba.nacos.api.naming.utils;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.PreservedMetadataKeys;
import com.alibaba.nacos.api.naming.pojo.Instance;
@ -33,6 +34,79 @@ import static org.junit.Assert.assertTrue;
public class NamingUtilsTest {
@Test
public void testGetGroupedName() {
assertEquals("group@@serviceName", NamingUtils.getGroupedName("serviceName", "group"));
}
@Test(expected = IllegalArgumentException.class)
public void testGetGroupedNameWithoutGroup() {
NamingUtils.getGroupedName("serviceName", "");
}
@Test(expected = IllegalArgumentException.class)
public void testGetGroupedNameWithoutServiceName() {
NamingUtils.getGroupedName("", "group");
}
@Test
public void testGetServiceName() {
String validServiceName = "group@@serviceName";
assertEquals("serviceName", NamingUtils.getServiceName(validServiceName));
}
@Test
public void testGetServiceNameWithoutGroup() {
String serviceName = "serviceName";
assertEquals(serviceName, NamingUtils.getServiceName(serviceName));
}
@Test
public void testGetServiceNameWithEmpty() {
assertEquals(StringUtils.EMPTY, NamingUtils.getServiceName(null));
}
@Test
public void testGetGroupName() {
String validServiceName = "group@@serviceName";
assertEquals("group", NamingUtils.getGroupName(validServiceName));
}
@Test
public void testGetGroupNameWithoutGroup() {
String serviceName = "serviceName";
assertEquals(Constants.DEFAULT_GROUP, NamingUtils.getGroupName(serviceName));
}
@Test
public void testGetGroupNameWithEmpty() {
assertEquals(StringUtils.EMPTY, NamingUtils.getGroupName(null));
}
@Test
public void testCheckServiceNameFormat() {
String validServiceName = "group@@serviceName";
NamingUtils.checkServiceNameFormat(validServiceName);
}
@Test(expected = IllegalArgumentException.class)
public void testCheckServiceNameFormatWithoutGroupAndService() {
String validServiceName = "@@";
NamingUtils.checkServiceNameFormat(validServiceName);
}
@Test(expected = IllegalArgumentException.class)
public void testCheckServiceNameFormatWithoutGroup() {
String validServiceName = "@@service";
NamingUtils.checkServiceNameFormat(validServiceName);
}
@Test(expected = IllegalArgumentException.class)
public void testCheckServiceNameFormatWithoutService() {
String validServiceName = "group@@";
NamingUtils.checkServiceNameFormat(validServiceName);
}
@Test
public void testGetGroupedNameOptional() {
String onlyGroupName = NamingUtils.getGroupedNameOptional(StringUtils.EMPTY, "groupA");

View File

@ -0,0 +1,54 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.remote.ability;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class ClientRemoteAbilityTest {
private static ObjectMapper mapper;
@BeforeClass
public static void setUp() throws Exception {
mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
@Test
public void testSerialize() throws JsonProcessingException {
ClientRemoteAbility abilities = new ClientRemoteAbility();
String json = mapper.writeValueAsString(abilities);
assertEquals("{\"supportRemoteConnection\":false}", json);
}
@Test
public void testDeserialize() throws JsonProcessingException {
String json = "{\"supportRemoteConnection\":true}";
ClientRemoteAbility abilities = mapper.readValue(json, ClientRemoteAbility.class);
assertTrue(abilities.isSupportRemoteConnection());
}
}

View File

@ -0,0 +1,82 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.remote.ability;
import com.alibaba.nacos.api.ability.ClientAbilities;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
public class ServerRemoteAbilityTest {
private static ObjectMapper mapper;
private ServerRemoteAbility serverAbilities;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
@Before
public void setUp() throws Exception {
serverAbilities = new ServerRemoteAbility();
}
@Test
public void testSerialize() throws JsonProcessingException {
serverAbilities = new ServerRemoteAbility();
String json = mapper.writeValueAsString(serverAbilities);
assertEquals("{\"supportRemoteConnection\":false,\"grpcReportEnabled\":true}", json);
}
@Test
public void testDeserialize() throws JsonProcessingException {
String json = "{\"supportRemoteConnection\":true,\"grpcReportEnabled\":true}";
ServerRemoteAbility abilities = mapper.readValue(json, ServerRemoteAbility.class);
assertTrue(abilities.isSupportRemoteConnection());
assertTrue(abilities.isGrpcReportEnabled());
}
@Test
public void testEqualsAndHashCode() {
assertEquals(serverAbilities, serverAbilities);
assertEquals(serverAbilities.hashCode(), serverAbilities.hashCode());
assertNotEquals(serverAbilities, null);
assertNotEquals(serverAbilities, new ClientAbilities());
ServerRemoteAbility test = new ServerRemoteAbility();
assertEquals(serverAbilities, test);
assertEquals(serverAbilities.hashCode(), test.hashCode());
test.setSupportRemoteConnection(true);
assertNotEquals(serverAbilities, test);
assertNotEquals(serverAbilities.hashCode(), test.hashCode());
test.setSupportRemoteConnection(false);
test.setGrpcReportEnabled(false);
assertNotEquals(serverAbilities, test);
assertNotEquals(serverAbilities.hashCode(), test.hashCode());
}
}

View File

@ -54,6 +54,7 @@ public class NetUtilsTest {
System.setProperty("com.alibaba.nacos.client.local.preferHostname", "true");
assertEquals(hostname, NetUtils.localIP());
assertEquals(hostname, NetUtils.localIP());
}
}

View File

@ -0,0 +1,109 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.utils;
import org.junit.Assert;
import org.junit.Test;
public class StringUtilsTest {
@Test
public void testIsEmpty() {
Assert.assertTrue(StringUtils.isEmpty(null));
Assert.assertTrue(StringUtils.isEmpty(""));
Assert.assertFalse(StringUtils.isEmpty(" "));
Assert.assertFalse(StringUtils.isEmpty("bob"));
Assert.assertFalse(StringUtils.isEmpty(" bob "));
}
@Test
public void testIsBlank() {
Assert.assertTrue(StringUtils.isBlank(null));
Assert.assertTrue(StringUtils.isBlank(""));
Assert.assertTrue(StringUtils.isBlank(" "));
Assert.assertFalse(StringUtils.isBlank("bob"));
Assert.assertFalse(StringUtils.isBlank(" bob "));
}
@Test
public void testTrim() {
Assert.assertNull(StringUtils.trim(null));
Assert.assertEquals(StringUtils.EMPTY, StringUtils.trim(""));
Assert.assertEquals(StringUtils.EMPTY, StringUtils.trim(" "));
Assert.assertEquals("abc", StringUtils.trim("abc"));
Assert.assertEquals("abc", StringUtils.trim(" abc "));
}
@Test
public void testEquals() {
Assert.assertTrue(StringUtils.equals(null, null));
Assert.assertFalse(StringUtils.equals(null, "abc"));
Assert.assertFalse(StringUtils.equals("abc", null));
Assert.assertTrue(StringUtils.equals("abc", "abc"));
Assert.assertFalse(StringUtils.equals("abc", "ABC"));
Assert.assertTrue(StringUtils.equals(new StringBuilder("abc"), "abc"));
Assert.assertFalse(StringUtils.equals(new StringBuilder("ABC"), "abc"));
}
@Test
public void testRegionMatchesEqualsCaseSensitive() {
Assert.assertTrue(StringUtils.regionMatches("abc", false, 0, "xabc", 1, 3));
}
@Test
public void testRegionMatchesEqualsCaseInsensitive() {
Assert.assertTrue(StringUtils.regionMatches("abc", true, 0, "xabc", 1, 3));
Assert.assertTrue(StringUtils.regionMatches("abc", true, 0, "xAbc", 1, 3));
}
@Test
public void testRegionMatchesNotEqualsCaseSensitive() {
Assert.assertFalse(StringUtils.regionMatches("abc", false, 0, "xAbc", 1, 3));
Assert.assertFalse(StringUtils.regionMatches("abc", false, 0, "xCbc", 1, 3));
}
@Test
public void testRegionMatchesNotEqualsCaseInsensitive() {
Assert.assertFalse(StringUtils.regionMatches("abc", true, 0, "xCab", 1, 3));
}
@Test
public void testRegionMatchesEqualsCaseSensitiveForNonString() {
Assert.assertTrue(StringUtils.regionMatches(new StringBuilder("abc"), false, 0, "xabc", 1, 3));
}
@Test
public void testRegionMatchesEqualsCaseInsensitiveForNonString() {
Assert.assertTrue(StringUtils.regionMatches(new StringBuilder("abc"), true, 0, "xabc", 1, 3));
Assert.assertTrue(StringUtils.regionMatches(new StringBuilder("abc"), true, 0, "xAbc", 1, 3));
}
@Test
public void testRegionMatchesNotEqualsCaseSensitiveForNonString() {
Assert.assertFalse(StringUtils.regionMatches(new StringBuilder("abc"), false, 0, "xAbc", 1, 3));
Assert.assertFalse(StringUtils.regionMatches(new StringBuilder("abc"), false, 0, "xCbc", 1, 3));
}
@Test
public void testRegionMatchesNotEqualsCaseInsensitiveForNonString() {
Assert.assertFalse(StringUtils.regionMatches(new StringBuilder("abc"), true, 0, "xCab", 1, 3));
}
}

View File

@ -29,11 +29,7 @@
<artifactId>nacos-auth</artifactId>
<packaging>jar</packaging>
<name>nacos-auth ${project.version}</name>
<url>http://nacos.io</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<url>https://nacos.io</url>
<dependencies>
<dependency>
@ -60,17 +56,4 @@
<artifactId>tomcat-embed-core</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -16,12 +16,14 @@
package com.alibaba.nacos.auth.config;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.common.JustForTest;
import com.alibaba.nacos.common.event.ServerConfigChangeEvent;
import com.alibaba.nacos.common.notify.Event;
import com.alibaba.nacos.common.notify.NotifyCenter;
import com.alibaba.nacos.common.notify.listener.Subscriber;
import com.alibaba.nacos.common.utils.ConvertUtils;
import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.plugin.auth.constant.Constants;
import com.alibaba.nacos.sys.env.EnvUtil;
import com.alibaba.nacos.sys.utils.PropertiesUtil;
@ -30,6 +32,7 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
@ -80,6 +83,24 @@ public class AuthConfigs extends Subscriber<ServerConfigChangeEvent> {
refreshPluginProperties();
}
/**
* Validate auth config.
*
* @throws NacosException If the config is not valid.
*/
@PostConstruct
public void validate() throws NacosException {
if (!authEnabled) {
return;
}
if (StringUtils.isEmpty(nacosAuthSystemType)) {
throw new NacosException(AuthErrorCode.INVALID_TYPE.getCode(), AuthErrorCode.INVALID_TYPE.getMsg());
}
if (StringUtils.isEmpty(serverIdentityKey) || StringUtils.isEmpty(serverIdentityValue)) {
throw new NacosException(AuthErrorCode.EMPTY_IDENTITY.getCode(), AuthErrorCode.EMPTY_IDENTITY.getMsg());
}
}
private void refreshPluginProperties() {
try {
Map<String, Properties> newProperties = new HashMap<>(1);

View File

@ -0,0 +1,51 @@
/*
* Copyright 1999-2021 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.auth.config;
/**
* Auth relative error codes, start with 5000X.
*
* @author xiweng.yy
*/
public enum AuthErrorCode {
/**
* invalid auth type.
*/
INVALID_TYPE(50001,
"Invalid auth type, Please set `nacos.core.auth.system.type`, detail: https://nacos.io/zh-cn/docs/v2/plugin/auth-plugin.html"),
EMPTY_IDENTITY(50002,
"Empty identity, Please set `nacos.core.auth.server.identity.key` and `nacos.core.auth.server.identity.value`, detail: https://nacos.io/zh-cn/docs/v2/guide/user/auth.html");
private final Integer code;
private final String msg;
public Integer getCode() {
return code;
}
public String getMsg() {
return msg;
}
AuthErrorCode(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
}

View File

@ -29,11 +29,7 @@
<packaging>jar</packaging>
<name>nacos-client ${project.version}</name>
<url>http://nacos.io</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<url>https://nacos.io</url>
<dependencies>
@ -125,156 +121,160 @@
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.4</version>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<keepDependenciesWithProvidedScope>false</keepDependenciesWithProvidedScope>
<promoteTransitiveDependencies>true</promoteTransitiveDependencies>
<createDependencyReducedPom>false</createDependencyReducedPom>
<minimizeJar>true</minimizeJar>
<createSourcesJar>true</createSourcesJar>
<shadeSourcesContent>true</shadeSourcesContent>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
<filter>
<artifact>io.grpc:grpc-netty-shaded</artifact>
<excludes>
<exclude>
META-INF/native/*.*
</exclude>
</excludes>
</filter>
<filter>
<artifact>com.google.*:*</artifact>
<excludes>
<exclude>
google/**/*.proto
</exclude>
</excludes>
</filter>
<filter>
<artifact>com.alibaba.nacos:nacos-api</artifact>
<includes>
<include>
com/alibaba/nacos/api/**/**
</include>
<include>
META-INF/**/*.*
</include>
</includes>
</filter>
</filters>
<artifactSet>
<includes>
<include>com.alibaba.nacos:nacos-api</include>
<include>com.alibaba.nacos:nacos-common</include>
<include>org.conscrypt:conscrypt-openjdk</include>
<include>org.mortbay.jetty.alpn:alpn-boot</include>
<include>org.eclipse.jetty.npn:npn-api</include>
<include>org.reflections:reflections</include>
<include>com.google.guava:guava</include>
<include>io.grpc:*</include>
<include>io.opencensus:*</include>
<include>org.javassist:*</include>
<include>io.perfmark:perfmark-api</include>
<include>com.google.*:*</include>
<include>javax.annotation:javax.annotation-api</include>
<include>org.checkerframework:*</include>
<include>org.codehaus.mojo:*</include>
</includes>
</artifactSet>
<relocations>
<relocation>
<pattern>io.grpc</pattern>
<shadedPattern>com.alibaba.nacos.shaded.io.grpc</shadedPattern>
<excludes>
<exclude>io.grpc.netty.shaded.io.grpc.netty.*</exclude>
</excludes>
</relocation>
<relocation>
<pattern>io.grpc.netty.shaded.io.grpc.netty</pattern>
<shadedPattern>com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.grpc.netty
</shadedPattern>
<includes>
<include>io.grpc.netty.shaded.io.grpc.netty.*</include>
</includes>
</relocation>
<relocation>
<pattern>com.google</pattern>
<shadedPattern>com.alibaba.nacos.shaded.com.google</shadedPattern>
</relocation>
<relocation>
<pattern>javax.annotation</pattern>
<shadedPattern>com.alibaba.nacos.shaded.javax.annotation</shadedPattern>
</relocation>
<relocation>
<pattern>io.perfmark</pattern>
<shadedPattern>com.alibaba.nacos.shaded.io.perfmark</shadedPattern>
</relocation>
<relocation>
<pattern>io.opencensus</pattern>
<shadedPattern>com.alibaba.nacos.shaded.io.opencensus</shadedPattern>
</relocation>
<relocation>
<pattern>org.codehaus</pattern>
<shadedPattern>com.alibaba.nacos.shaded.org.codehaus</shadedPattern>
</relocation>
<relocation>
<pattern>org.checkerframework</pattern>
<shadedPattern>com.alibaba.nacos.shaded.org.checkerframework</shadedPattern>
</relocation>
<relocation>
<pattern>android.annotation</pattern>
<shadedPattern>com.alibaba.nacos.shaded.android.annotation</shadedPattern>
</relocation>
<relocation>
<pattern>org.example</pattern>
<shadedPattern>com.alibaba.nacos.shaded.org.example</shadedPattern>
</relocation>
</relocations>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"/>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
</build>
<profiles>
<profile>
<id>release-sign-artifacts</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.4</version>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<keepDependenciesWithProvidedScope>false</keepDependenciesWithProvidedScope>
<promoteTransitiveDependencies>true</promoteTransitiveDependencies>
<createDependencyReducedPom>false</createDependencyReducedPom>
<minimizeJar>true</minimizeJar>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
<filter>
<artifact>io.grpc:grpc-netty-shaded</artifact>
<excludes>
<exclude>
META-INF/native/*.*
</exclude>
</excludes>
</filter>
<filter>
<artifact>com.alibaba.nacos:nacos-api</artifact>
<includes>
<include>
com/alibaba/nacos/api/**/**
</include>
</includes>
</filter>
</filters>
<createSourcesJar>true</createSourcesJar>
<shadeSourcesContent>true</shadeSourcesContent>
<artifactSet>
<includes>
<include>com.alibaba.nacos:nacos-api</include>
<include>com.alibaba.nacos:nacos-common</include>
<include>org.conscrypt:conscrypt-openjdk</include>
<include>org.mortbay.jetty.alpn:alpn-boot</include>
<include>org.eclipse.jetty.npn:npn-api</include>
<include>org.reflections:reflections</include>
<include>com.google.guava:guava</include>
<include>io.grpc:*</include>
<include>io.opencensus:*</include>
<include>org.javassist:*</include>
<include>io.perfmark:perfmark-api</include>
<include>com.google.*:*</include>
<include>javax.annotation:javax.annotation-api</include>
<include>org.checkerframework:*</include>
<include>org.codehaus.mojo:*</include>
</includes>
</artifactSet>
<relocations>
<relocation>
<pattern>io.grpc</pattern>
<shadedPattern>com.alibaba.nacos.shaded.io.grpc</shadedPattern>
<excludes>
<exclude>io.grpc.netty.shaded.io.grpc.netty.*</exclude>
</excludes>
</relocation>
<relocation>
<pattern>io.grpc.netty.shaded.io.grpc.netty</pattern>
<shadedPattern>com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.grpc.netty
</shadedPattern>
<includes>
<include>io.grpc.netty.shaded.io.grpc.netty.*</include>
</includes>
</relocation>
<relocation>
<pattern>com.google</pattern>
<shadedPattern>com.alibaba.nacos.shaded.com.google</shadedPattern>
</relocation>
<relocation>
<pattern>javax.annotation</pattern>
<shadedPattern>com.alibaba.nacos.shaded.javax.annotation</shadedPattern>
</relocation>
<relocation>
<pattern>io.perfmark</pattern>
<shadedPattern>com.alibaba.nacos.shaded.io.perfmark</shadedPattern>
</relocation>
<relocation>
<pattern>io.opencensus</pattern>
<shadedPattern>com.alibaba.nacos.shaded.io.opencensus</shadedPattern>
</relocation>
<relocation>
<pattern>org.codehaus</pattern>
<shadedPattern>com.alibaba.nacos.shaded.org.codehaus</shadedPattern>
</relocation>
<relocation>
<pattern>org.checkerframework</pattern>
<shadedPattern>com.alibaba.nacos.shaded.org.checkerframework</shadedPattern>
</relocation>
<relocation>
<pattern>android.annotation</pattern>
<shadedPattern>com.alibaba.nacos.shaded.android.annotation</shadedPattern>
</relocation>
<relocation>
<pattern>org.example</pattern>
<shadedPattern>com.alibaba.nacos.shaded.org.example</shadedPattern>
</relocation>
</relocations>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"/>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
@ -299,138 +299,7 @@
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.4</version>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<keepDependenciesWithProvidedScope>false</keepDependenciesWithProvidedScope>
<promoteTransitiveDependencies>true</promoteTransitiveDependencies>
<createDependencyReducedPom>false</createDependencyReducedPom>
<minimizeJar>true</minimizeJar>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
<filter>
<artifact>io.grpc:grpc-netty-shaded</artifact>
<excludes>
<exclude>
META-INF/native/*.*
</exclude>
</excludes>
</filter>
<filter>
<artifact>com.alibaba.nacos:nacos-api</artifact>
<includes>
<include>
com/alibaba/nacos/api/**/**
</include>
</includes>
</filter>
</filters>
<createSourcesJar>true</createSourcesJar>
<shadeSourcesContent>true</shadeSourcesContent>
<artifactSet>
<includes>
<include>com.alibaba.nacos:nacos-api</include>
<include>com.alibaba.nacos:nacos-common</include>
<include>org.conscrypt:conscrypt-openjdk</include>
<include>org.mortbay.jetty.alpn:alpn-boot</include>
<include>org.eclipse.jetty.npn:npn-api</include>
<include>org.reflections:reflections</include>
<include>com.google.guava:guava</include>
<include>io.grpc:*</include>
<include>io.opencensus:*</include>
<include>org.javassist:*</include>
<include>io.perfmark:perfmark-api</include>
<include>com.google.*:*</include>
<include>javax.annotation:javax.annotation-api</include>
<include>org.checkerframework:*</include>
<include>org.codehaus.mojo:*</include>
</includes>
</artifactSet>
<relocations>
<relocation>
<pattern>io.grpc</pattern>
<shadedPattern>com.alibaba.nacos.shaded.io.grpc</shadedPattern>
<excludes>
<exclude>io.grpc.netty.shaded.io.grpc.netty.*</exclude>
</excludes>
</relocation>
<relocation>
<pattern>io.grpc.netty.shaded.io.grpc.netty</pattern>
<shadedPattern>com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.grpc.netty
</shadedPattern>
<includes>
<include>io.grpc.netty.shaded.io.grpc.netty.*</include>
</includes>
</relocation>
<relocation>
<pattern>com.google</pattern>
<shadedPattern>com.alibaba.nacos.shaded.com.google</shadedPattern>
</relocation>
<relocation>
<pattern>javax.annotation</pattern>
<shadedPattern>com.alibaba.nacos.shaded.javax.annotation</shadedPattern>
</relocation>
<relocation>
<pattern>io.perfmark</pattern>
<shadedPattern>com.alibaba.nacos.shaded.io.perfmark</shadedPattern>
</relocation>
<relocation>
<pattern>io.opencensus</pattern>
<shadedPattern>com.alibaba.nacos.shaded.io.opencensus</shadedPattern>
</relocation>
<relocation>
<pattern>org.codehaus</pattern>
<shadedPattern>com.alibaba.nacos.shaded.org.codehaus</shadedPattern>
</relocation>
<relocation>
<pattern>org.checkerframework</pattern>
<shadedPattern>com.alibaba.nacos.shaded.org.checkerframework</shadedPattern>
</relocation>
<relocation>
<pattern>android.annotation</pattern>
<shadedPattern>com.alibaba.nacos.shaded.android.annotation</shadedPattern>
</relocation>
<relocation>
<pattern>org.example</pattern>
<shadedPattern>com.alibaba.nacos.shaded.org.example</shadedPattern>
</relocation>
</relocations>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"/>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>

View File

@ -19,14 +19,16 @@ package com.alibaba.nacos.client.auth.impl.process;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.client.auth.impl.NacosAuthLoginConstant;
import com.alibaba.nacos.plugin.auth.api.LoginIdentityContext;
import com.alibaba.nacos.client.utils.ContextPathUtil;
import com.alibaba.nacos.client.utils.ParamUtil;
import com.alibaba.nacos.common.http.HttpRestResult;
import com.alibaba.nacos.common.http.client.NacosRestTemplate;
import com.alibaba.nacos.common.http.param.Header;
import com.alibaba.nacos.common.http.param.Query;
import com.alibaba.nacos.common.utils.InternetAddressUtil;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.plugin.auth.api.LoginIdentityContext;
import com.fasterxml.jackson.databind.JsonNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -36,6 +38,7 @@ import java.util.Map;
import java.util.Properties;
import static com.alibaba.nacos.client.naming.utils.UtilAndComs.webContext;
import static com.alibaba.nacos.common.constant.RequestUrlConstants.HTTPS_PREFIX;
import static com.alibaba.nacos.common.constant.RequestUrlConstants.HTTP_PREFIX;
/**
@ -58,34 +61,39 @@ public class HttpLoginProcessor implements LoginProcessor {
@Override
public LoginIdentityContext getResponse(Properties properties) {
String contextPath = ContextPathUtil
.normalizeContextPath(properties.getProperty(PropertyKeyConst.CONTEXT_PATH, webContext));
String contextPath = ContextPathUtil.normalizeContextPath(
properties.getProperty(PropertyKeyConst.CONTEXT_PATH, webContext));
String server = properties.getProperty(NacosAuthLoginConstant.SERVER, StringUtils.EMPTY);
String url = HTTP_PREFIX + server + contextPath + LOGIN_URL;
if (server.contains(Constants.HTTP_PREFIX)) {
url = server + contextPath + LOGIN_URL;
if (!server.startsWith(HTTPS_PREFIX) && !server.startsWith(HTTP_PREFIX)) {
if (!InternetAddressUtil.containsPort(server)) {
server = server + InternetAddressUtil.IP_PORT_SPLITER + ParamUtil.getDefaultServerPort();
}
server = HTTP_PREFIX + server;
}
String url = server + contextPath + LOGIN_URL;
Map<String, String> params = new HashMap<>(2);
Map<String, String> bodyMap = new HashMap<>(2);
params.put(PropertyKeyConst.USERNAME, properties.getProperty(PropertyKeyConst.USERNAME, StringUtils.EMPTY));
bodyMap.put(PropertyKeyConst.PASSWORD, properties.getProperty(PropertyKeyConst.PASSWORD, StringUtils.EMPTY));
try {
HttpRestResult<String> restResult = nacosRestTemplate
.postForm(url, Header.EMPTY, Query.newInstance().initParams(params), bodyMap, String.class);
HttpRestResult<String> restResult = nacosRestTemplate.postForm(url, Header.EMPTY,
Query.newInstance().initParams(params), bodyMap, String.class);
if (!restResult.ok()) {
SECURITY_LOGGER.error("login failed: {}", JacksonUtils.toJson(restResult));
return null;
}
JsonNode obj = JacksonUtils.toObj(restResult.getData());
LoginIdentityContext loginIdentityContext = new LoginIdentityContext();
if (obj.has(Constants.ACCESS_TOKEN)) {
loginIdentityContext
.setParameter(NacosAuthLoginConstant.ACCESSTOKEN, obj.get(Constants.ACCESS_TOKEN).asText());
loginIdentityContext.setParameter(NacosAuthLoginConstant.TOKENTTL, obj.get(Constants.TOKEN_TTL).asText());
loginIdentityContext.setParameter(NacosAuthLoginConstant.ACCESSTOKEN,
obj.get(Constants.ACCESS_TOKEN).asText());
loginIdentityContext.setParameter(NacosAuthLoginConstant.TOKENTTL,
obj.get(Constants.TOKEN_TTL).asText());
} else {
SECURITY_LOGGER.info("[NacosClientAuthServiceImpl] ACCESS_TOKEN is empty from response");
}

View File

@ -27,6 +27,8 @@ public class IdentifyConstants {
public static final String SECRET_KEY = "secretKey";
public static final String SECURITY_TOKEN_HEADER = "Spas-SecurityToken";
public static final String TENANT_ID = "tenantId";
public static final String PROPERTIES_FILENAME = "spas.properties";

View File

@ -0,0 +1,98 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.client.auth.ram.identify;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException;
import com.alibaba.nacos.client.config.impl.ConfigHttpClientManager;
import com.alibaba.nacos.client.utils.LogUtils;
import com.alibaba.nacos.common.http.HttpRestResult;
import com.alibaba.nacos.common.http.param.Header;
import com.alibaba.nacos.common.http.param.Query;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import org.slf4j.Logger;
/**
* Sts credential holder.
*
* @author xiweng.yy
*/
public class StsCredentialHolder {
private static final Logger LOGGER = LogUtils.logger(StsCredentialHolder.class);
private static final StsCredentialHolder INSTANCE = new StsCredentialHolder();
private StsCredential stsCredential;
private StsCredentialHolder() {
}
public static StsCredentialHolder getInstance() {
return INSTANCE;
}
/**
* Get Sts Credential.
*
* @return StsCredential
*/
public StsCredential getStsCredential() {
boolean cacheSecurityCredentials = StsConfig.getInstance().isCacheSecurityCredentials();
if (cacheSecurityCredentials && stsCredential != null) {
long currentTime = System.currentTimeMillis();
long expirationTime = stsCredential.getExpiration().getTime();
int timeToRefreshInMillisecond = StsConfig.getInstance().getTimeToRefreshInMillisecond();
if (expirationTime - currentTime > timeToRefreshInMillisecond) {
return stsCredential;
}
}
String stsResponse = getStsResponse();
stsCredential = JacksonUtils.toObj(stsResponse, new TypeReference<StsCredential>() {
});
LOGGER.info("[getSTSCredential] code:{}, accessKeyId:{}, lastUpdated:{}, expiration:{}",
stsCredential.getCode(), stsCredential.getAccessKeyId(), stsCredential.getLastUpdated(),
stsCredential.getExpiration());
return stsCredential;
}
private static String getStsResponse() {
String securityCredentials = StsConfig.getInstance().getSecurityCredentials();
if (securityCredentials != null) {
return securityCredentials;
}
String securityCredentialsUrl = StsConfig.getInstance().getSecurityCredentialsUrl();
try {
HttpRestResult<String> result = ConfigHttpClientManager.getInstance().getNacosRestTemplate()
.get(securityCredentialsUrl, Header.EMPTY, Query.EMPTY, String.class);
if (!result.ok()) {
LOGGER.error(
"can not get security credentials, securityCredentialsUrl: {}, responseCode: {}, response: {}",
securityCredentialsUrl, result.getCode(), result.getMessage());
throw new NacosRuntimeException(NacosException.SERVER_ERROR,
"can not get security credentials, responseCode: " + result.getCode() + ", response: " + result
.getMessage());
}
return result.getData();
} catch (Exception e) {
LOGGER.error("can not get security credentials", e);
throw new NacosRuntimeException(NacosException.SERVER_ERROR, e);
}
}
}

View File

@ -16,23 +16,15 @@
package com.alibaba.nacos.client.auth.ram.injector;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException;
import com.alibaba.nacos.plugin.auth.api.LoginIdentityContext;
import com.alibaba.nacos.client.auth.ram.RamContext;
import com.alibaba.nacos.plugin.auth.api.RequestResource;
import com.alibaba.nacos.client.config.impl.ConfigHttpClientManager;
import com.alibaba.nacos.client.auth.ram.utils.SpasAdapter;
import com.alibaba.nacos.client.auth.ram.identify.IdentifyConstants;
import com.alibaba.nacos.client.auth.ram.identify.StsConfig;
import com.alibaba.nacos.client.auth.ram.identify.StsCredential;
import com.alibaba.nacos.client.utils.LogUtils;
import com.alibaba.nacos.common.http.HttpRestResult;
import com.alibaba.nacos.common.http.param.Header;
import com.alibaba.nacos.common.http.param.Query;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.client.auth.ram.identify.StsCredentialHolder;
import com.alibaba.nacos.client.auth.ram.utils.SpasAdapter;
import com.alibaba.nacos.common.utils.StringUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import org.slf4j.Logger;
import com.alibaba.nacos.plugin.auth.api.LoginIdentityContext;
import com.alibaba.nacos.plugin.auth.api.RequestResource;
import java.util.Map;
@ -43,26 +35,20 @@ import java.util.Map;
*/
public class ConfigResourceInjector extends AbstractResourceInjector {
private static final Logger LOGGER = LogUtils.logger(ConfigResourceInjector.class);
private static final String SECURITY_TOKEN_HEADER = "Spas-SecurityToken";
private static final String ACCESS_KEY_HEADER = "Spas-AccessKey";
private static final String DEFAULT_RESOURCE = "";
private StsCredential stsCredential;
@Override
public void doInject(RequestResource resource, RamContext context, LoginIdentityContext result) {
String accessKey = context.getAccessKey();
String secretKey = context.getSecretKey();
// STS 临时凭证鉴权的优先级高于 AK/SK 鉴权
if (StsConfig.getInstance().isStsOn()) {
StsCredential stsCredential = getStsCredential();
StsCredential stsCredential = StsCredentialHolder.getInstance().getStsCredential();
accessKey = stsCredential.getAccessKeyId();
secretKey = stsCredential.getAccessKeySecret();
result.setParameter(SECURITY_TOKEN_HEADER, stsCredential.getSecurityToken());
result.setParameter(IdentifyConstants.SECURITY_TOKEN_HEADER, stsCredential.getSecurityToken());
}
if (StringUtils.isNotEmpty(accessKey) && StringUtils.isNotBlank(secretKey)) {
@ -73,50 +59,6 @@ public class ConfigResourceInjector extends AbstractResourceInjector {
result.setParameters(signHeaders);
}
private StsCredential getStsCredential() {
boolean cacheSecurityCredentials = StsConfig.getInstance().isCacheSecurityCredentials();
if (cacheSecurityCredentials && stsCredential != null) {
long currentTime = System.currentTimeMillis();
long expirationTime = stsCredential.getExpiration().getTime();
int timeToRefreshInMillisecond = StsConfig.getInstance().getTimeToRefreshInMillisecond();
if (expirationTime - currentTime > timeToRefreshInMillisecond) {
return stsCredential;
}
}
String stsResponse = getStsResponse();
stsCredential = JacksonUtils.toObj(stsResponse, new TypeReference<StsCredential>() {
});
LOGGER.info("[getSTSCredential] code:{}, accessKeyId:{}, lastUpdated:{}, expiration:{}",
stsCredential.getCode(), stsCredential.getAccessKeyId(), stsCredential.getLastUpdated(),
stsCredential.getExpiration());
return stsCredential;
}
private static String getStsResponse() {
String securityCredentials = StsConfig.getInstance().getSecurityCredentials();
if (securityCredentials != null) {
return securityCredentials;
}
String securityCredentialsUrl = StsConfig.getInstance().getSecurityCredentialsUrl();
try {
HttpRestResult<String> result = ConfigHttpClientManager.getInstance().getNacosRestTemplate()
.get(securityCredentialsUrl, Header.EMPTY, Query.EMPTY, String.class);
if (!result.ok()) {
LOGGER.error(
"can not get security credentials, securityCredentialsUrl: {}, responseCode: {}, response: {}",
securityCredentialsUrl, result.getCode(), result.getMessage());
throw new NacosRuntimeException(NacosException.SERVER_ERROR,
"can not get security credentials, responseCode: " + result.getCode() + ", response: " + result
.getMessage());
}
return result.getData();
} catch (Exception e) {
LOGGER.error("can not get security credentials", e);
throw new NacosRuntimeException(NacosException.SERVER_ERROR, e);
}
}
private String getResource(String tenant, String group) {
if (StringUtils.isNotBlank(tenant) && StringUtils.isNotBlank(group)) {
return tenant + "+" + group;

View File

@ -18,6 +18,10 @@ package com.alibaba.nacos.client.auth.ram.injector;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.naming.utils.NamingUtils;
import com.alibaba.nacos.client.auth.ram.identify.IdentifyConstants;
import com.alibaba.nacos.client.auth.ram.identify.StsConfig;
import com.alibaba.nacos.client.auth.ram.identify.StsCredential;
import com.alibaba.nacos.client.auth.ram.identify.StsCredentialHolder;
import com.alibaba.nacos.plugin.auth.api.LoginIdentityContext;
import com.alibaba.nacos.client.auth.ram.RamContext;
import com.alibaba.nacos.plugin.auth.api.RequestResource;
@ -43,11 +47,20 @@ public class NamingResourceInjector extends AbstractResourceInjector {
public void doInject(RequestResource resource, RamContext context, LoginIdentityContext result) {
if (context.validate()) {
try {
String accessKey = context.getAccessKey();
String secretKey = context.getSecretKey();
// STS 临时凭证鉴权的优先级高于 AK/SK 鉴权
if (StsConfig.getInstance().isStsOn()) {
StsCredential stsCredential = StsCredentialHolder.getInstance().getStsCredential();
accessKey = stsCredential.getAccessKeyId();
secretKey = stsCredential.getAccessKeySecret();
result.setParameter(IdentifyConstants.SECURITY_TOKEN_HEADER, stsCredential.getSecurityToken());
}
String signData = getSignData(getGroupedServiceName(resource));
String signature = SignUtil.sign(signData, context.getSecretKey());
String signature = SignUtil.sign(signData, secretKey);
result.setParameter(SIGNATURE_FILED, signature);
result.setParameter(DATA_FILED, signData);
result.setParameter(AK_FILED, context.getAccessKey());
result.setParameter(AK_FILED, accessKey);
} catch (Exception e) {
NAMING_LOGGER.error("inject ak/sk failed.", e);
}

View File

@ -38,6 +38,7 @@ import com.alibaba.nacos.api.remote.RemoteConstants;
import com.alibaba.nacos.api.remote.request.Request;
import com.alibaba.nacos.api.remote.response.Response;
import com.alibaba.nacos.client.env.NacosClientProperties;
import com.alibaba.nacos.common.remote.client.RpcClientTlsConfig;
import com.alibaba.nacos.plugin.auth.api.RequestResource;
import com.alibaba.nacos.client.config.common.GroupKey;
import com.alibaba.nacos.client.config.filter.impl.ConfigFilterChainManager;
@ -115,13 +116,11 @@ public class ClientWorker implements Closeable {
private final ConfigFilterChainManager configFilterChainManager;
private boolean isHealthServer = true;
private String uuid = UUID.randomUUID().toString();
private long timeout;
private ConfigTransportClient agent;
private ConfigRpcTransportClient agent;
private int taskPenaltyTime;
@ -294,8 +293,8 @@ public class ClientWorker implements Closeable {
*/
public boolean publishConfig(String dataId, String group, String tenant, String appName, String tag, String betaIps,
String content, String encryptedDataKey, String casMd5, String type) throws NacosException {
return agent
.publishConfig(dataId, group, tenant, appName, tag, betaIps, content, encryptedDataKey, casMd5, type);
return agent.publishConfig(dataId, group, tenant, appName, tag, betaIps, content, encryptedDataKey, casMd5,
type);
}
/**
@ -417,8 +416,8 @@ public class ClientWorker implements Closeable {
agent = new ConfigRpcTransportClient(properties, serverListManager);
int count = ThreadUtils.getSuitableThreadCount(THREAD_MULTIPLE);
ScheduledExecutorService executorService = Executors
.newScheduledThreadPool(Math.max(count, MIN_THREAD_NUM), r -> {
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(Math.max(count, MIN_THREAD_NUM),
r -> {
Thread t = new Thread(r);
t.setName("com.alibaba.nacos.client.Worker");
t.setDaemon(true);
@ -463,11 +462,11 @@ public class ClientWorker implements Closeable {
timeout = Math.max(ConvertUtils.toInt(properties.getProperty(PropertyKeyConst.CONFIG_LONG_POLL_TIMEOUT),
Constants.CONFIG_LONG_POLL_TIMEOUT), Constants.MIN_CONFIG_LONG_POLL_TIMEOUT);
taskPenaltyTime = ConvertUtils
.toInt(properties.getProperty(PropertyKeyConst.CONFIG_RETRY_TIME), Constants.CONFIG_RETRY_TIME);
taskPenaltyTime = ConvertUtils.toInt(properties.getProperty(PropertyKeyConst.CONFIG_RETRY_TIME),
Constants.CONFIG_RETRY_TIME);
this.enableRemoteSyncConfig = Boolean
.parseBoolean(properties.getProperty(PropertyKeyConst.ENABLE_REMOTE_SYNC_CONFIG));
this.enableRemoteSyncConfig = Boolean.parseBoolean(
properties.getProperty(PropertyKeyConst.ENABLE_REMOTE_SYNC_CONFIG));
}
private Map<String, Object> getMetrics(List<ClientConfigMetricRequest.MetricsKey> metricsKeys) {
@ -501,8 +500,8 @@ public class ClientWorker implements Closeable {
}
if (ClientConfigMetricRequest.MetricsKey.SNAPSHOT_DATA.equals(metricsKey.getType())) {
String[] configStr = GroupKey.parseKey(metricsKey.getKey());
String snapshot = LocalConfigInfoProcessor
.getSnapshot(this.agent.getName(), configStr[0], configStr[1], configStr[2]);
String snapshot = LocalConfigInfoProcessor.getSnapshot(this.agent.getName(), configStr[0], configStr[1],
configStr[2]);
values.putIfAbsent(metricsKey,
snapshot == null ? null : snapshot + ":" + MD5Utils.md5Hex(snapshot, ENCODE));
}
@ -520,12 +519,14 @@ public class ClientWorker implements Closeable {
LOGGER.info("{} do shutdown stop", className);
}
/**
* check if it has any connectable server endpoint.
*
* @return true: that means has atleast one connected rpc client. flase: that means does not have any connected rpc
* client.
*/
public boolean isHealthServer() {
return isHealthServer;
}
private void setHealthServer(boolean isHealthServer) {
this.isHealthServer = isHealthServer;
return agent.isHealthServer();
}
public class ConfigRpcTransportClient extends ConfigTransportClient {
@ -605,9 +606,8 @@ public class ClientWorker implements Closeable {
LOGGER.info("[{}] [server-push] config changed. dataId={}, group={},tenant={}",
rpcClientInner.getName(), configChangeNotifyRequest.getDataId(),
configChangeNotifyRequest.getGroup(), configChangeNotifyRequest.getTenant());
String groupKey = GroupKey
.getKeyTenant(configChangeNotifyRequest.getDataId(), configChangeNotifyRequest.getGroup(),
configChangeNotifyRequest.getTenant());
String groupKey = GroupKey.getKeyTenant(configChangeNotifyRequest.getDataId(),
configChangeNotifyRequest.getGroup(), configChangeNotifyRequest.getTenant());
CacheData cacheData = cacheMap.get().get(groupKey);
if (cacheData != null) {
@ -791,11 +791,10 @@ public class ClientWorker implements Closeable {
//handle changed keys,notify listener
if (!CollectionUtils.isEmpty(configChangeBatchListenResponse.getChangedConfigs())) {
hasChangedKeys = true;
for (ConfigChangeBatchListenResponse.ConfigContext changeConfig : configChangeBatchListenResponse
.getChangedConfigs()) {
String changeKey = GroupKey
.getKeyTenant(changeConfig.getDataId(), changeConfig.getGroup(),
changeConfig.getTenant());
for (ConfigChangeBatchListenResponse.ConfigContext changeConfig
: configChangeBatchListenResponse.getChangedConfigs()) {
String changeKey = GroupKey.getKeyTenant(changeConfig.getDataId(),
changeConfig.getGroup(), changeConfig.getTenant());
changeKeys.add(changeKey);
refreshContentAndCheck(changeKey);
}
@ -804,8 +803,8 @@ public class ClientWorker implements Closeable {
//handler content configs
for (CacheData cacheData : listenCaches) {
String groupKey = GroupKey
.getKeyTenant(cacheData.dataId, cacheData.group, cacheData.getTenant());
String groupKey = GroupKey.getKeyTenant(cacheData.dataId, cacheData.group,
cacheData.getTenant());
if (!changeKeys.contains(groupKey)) {
//sync:cache data md5 = server md5 && cache data md5 = all listeners md5.
synchronized (cacheData) {
@ -850,8 +849,8 @@ public class ClientWorker implements Closeable {
for (CacheData cacheData : removeListenCaches) {
synchronized (cacheData) {
if (cacheData.isDiscard()) {
ClientWorker.this
.removeCache(cacheData.dataId, cacheData.group, cacheData.tenant);
ClientWorker.this.removeCache(cacheData.dataId, cacheData.group,
cacheData.tenant);
}
}
}
@ -879,13 +878,12 @@ public class ClientWorker implements Closeable {
private RpcClient ensureRpcClient(String taskId) throws NacosException {
synchronized (ClientWorker.this) {
Map<String, String> labels = getLabels();
Map<String, String> newLabels = new HashMap<>(labels);
newLabels.put("taskId", taskId);
RpcClient rpcClient = RpcClientFactory
.createClient(uuid + "_config-" + taskId, getConnectionType(), newLabels);
RpcClient rpcClient = RpcClientFactory.createClient(uuid + "_config-" + taskId, getConnectionType(),
newLabels, RpcClientTlsConfig.properties(this.properties));
if (rpcClient.isWaitInitiated()) {
initRpcClientHandler(rpcClient);
rpcClient.setTenant(getTenant());
@ -966,8 +964,8 @@ public class ClientWorker implements Closeable {
}
configResponse.setConfigType(configType);
String encryptedDataKey = response.getEncryptedDataKey();
LocalEncryptedDataKeyProcessor
.saveEncryptDataKeySnapshot(agent.getName(), dataId, group, tenant, encryptedDataKey);
LocalEncryptedDataKeyProcessor.saveEncryptDataKeySnapshot(agent.getName(), dataId, group, tenant,
encryptedDataKey);
configResponse.setEncryptedDataKey(encryptedDataKey);
return configResponse;
} else if (response.getErrorCode() == ConfigQueryResponse.CONFIG_NOT_FOUND) {
@ -1075,6 +1073,20 @@ public class ClientWorker implements Closeable {
ConfigRemoveResponse response = (ConfigRemoveResponse) requestProxy(getOneRunningClient(), request);
return response.isSuccess();
}
/**
* check server is health.
*
* @return
*/
public boolean isHealthServer() {
try {
return getOneRunningClient().isRunning();
} catch (NacosException e) {
LOGGER.warn("check server status failed. error={}", e);
return false;
}
}
}
public String getAgentName() {

View File

@ -23,7 +23,6 @@ import com.alibaba.nacos.common.spi.NacosServiceLoader;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
@ -44,11 +43,8 @@ public class ConfigChangeHandler {
this.parserList = new LinkedList<>();
Collection<ConfigChangeParser> loader = NacosServiceLoader.load(ConfigChangeParser.class);
Iterator<ConfigChangeParser> itr = loader.iterator();
while (itr.hasNext()) {
this.parserList.add(itr.next());
}
this.parserList.addAll(loader);
this.parserList.add(new PropertiesChangeParser());
this.parserList.add(new YmlChangeParser());
}

View File

@ -40,8 +40,6 @@ public class LocalConfigInfoProcessor {
private static final Logger LOGGER = LogUtils.logger(LocalConfigInfoProcessor.class);
public static final String LOCAL_FILEROOT_PATH;
public static final String LOCAL_SNAPSHOT_PATH;
private static final String SUFFIX = "_nacos";
@ -59,12 +57,9 @@ public class LocalConfigInfoProcessor {
private static final String SNAPSHOT_FILE_CHILD_2 = "snapshot-tenant";
static {
LOCAL_FILEROOT_PATH = NacosClientProperties.PROTOTYPE.getProperty("JM.LOG.PATH",
NacosClientProperties.PROTOTYPE.getProperty("user.home")) + File.separator + "nacos" + File.separator
+ "config";
LOCAL_SNAPSHOT_PATH = NacosClientProperties.PROTOTYPE.getProperty("JM.SNAPSHOT.PATH",
NacosClientProperties.PROTOTYPE.getProperty("user.home")) + File.separator + "nacos" + File.separator
+ "config";
LOCAL_SNAPSHOT_PATH = NacosClientProperties.PROTOTYPE.getProperty(com.alibaba.nacos.client.constant.Constants.SysEnv.JM_SNAPSHOT_PATH,
NacosClientProperties.PROTOTYPE.getProperty(com.alibaba.nacos.client.constant.Constants.SysEnv.USER_HOME)) + File.separator
+ "nacos" + File.separator + "config";
LOGGER.info("LOCAL_SNAPSHOT_PATH:{}", LOCAL_SNAPSHOT_PATH);
}

View File

@ -20,9 +20,11 @@ import com.alibaba.nacos.api.config.ConfigChangeItem;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException;
import com.alibaba.nacos.common.utils.StringUtils;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.ConstructorException;
import org.yaml.snakeyaml.composer.ComposerException;
import org.yaml.snakeyaml.constructor.SafeConstructor;
import org.yaml.snakeyaml.error.MarkedYAMLException;
import java.util.Collection;
import java.util.Collections;
@ -50,7 +52,7 @@ public class YmlChangeParser extends AbstractConfigChangeParser {
Map<String, Object> oldMap = Collections.emptyMap();
Map<String, Object> newMap = Collections.emptyMap();
try {
Yaml yaml = new Yaml(new SafeConstructor());
Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions()));
if (StringUtils.isNotBlank(oldContent)) {
oldMap = yaml.load(oldContent);
oldMap = getFlattenedMap(oldMap);
@ -59,15 +61,15 @@ public class YmlChangeParser extends AbstractConfigChangeParser {
newMap = yaml.load(newContent);
newMap = getFlattenedMap(newMap);
}
} catch (ConstructorException e) {
} catch (MarkedYAMLException e) {
handleYamlException(e);
}
return filterChangeData(oldMap, newMap);
}
private void handleYamlException(ConstructorException e) {
if (e.getMessage().startsWith(INVALID_CONSTRUCTOR_ERROR_INFO)) {
private void handleYamlException(MarkedYAMLException e) {
if (e.getMessage().startsWith(INVALID_CONSTRUCTOR_ERROR_INFO) || e instanceof ComposerException) {
throw new NacosRuntimeException(NacosException.INVALID_PARAM,
"AbstractConfigChangeListener only support basic java data type for yaml. If you want to listen "
+ "key changes for custom classes, please use `Listener` to listener whole yaml configuration and parse it by yourself.",

View File

@ -54,6 +54,15 @@ public interface NacosClientProperties {
*/
String getProperty(String key, String defaultValue);
/**
* get property from special property source.
* @param source source type
* @see SourceType
* @param key special key
* @return string value or null.
*/
String getPropertyFrom(SourceType source, String key);
/**
* get boolean, if the value can not be got by the special key, the null will be returned.
*

View File

@ -22,20 +22,17 @@ import com.alibaba.nacos.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Properties;
import java.util.stream.Collectors;
/**
* Searchable NacosClientProperties.
* the SearchableProperties that it can be specified search order by
* nacos.env.first
* Searchable NacosClientProperties. the SearchableProperties that it can be specified search order by nacos.env.first
*
* @author onewe
*/
class SearchableProperties implements NacosClientProperties {
@ -48,11 +45,42 @@ class SearchableProperties implements NacosClientProperties {
private static final DefaultSettingPropertySource DEFAULT_SETTING_PROPERTY_SOURCE = new DefaultSettingPropertySource();
private static final List<SourceType> DEFAULT_ORDER = Arrays.asList(SourceType.PROPERTIES, SourceType.JVM,
SourceType.ENV, SourceType.DEFAULT_SETTING);
private static final List<SourceType> SEARCH_ORDER;
private static final CompositeConverter CONVERTER = new CompositeConverter();
static {
List<SourceType> initOrder = Arrays.asList(SourceType.PROPERTIES, SourceType.JVM, SourceType.ENV,
SourceType.DEFAULT_SETTING);
String firstEnv = JVM_ARGS_PROPERTY_SOURCE.getProperty(Constants.SysEnv.NACOS_ENV_FIRST);
if (StringUtils.isBlank(firstEnv)) {
firstEnv = SYSTEM_ENV_PROPERTY_SOURCE.getProperty(Constants.SysEnv.NACOS_ENV_FIRST);
}
if (StringUtils.isNotBlank(firstEnv)) {
try {
final SourceType sourceType = SourceType.valueOf(firstEnv.toUpperCase());
if (!sourceType.equals(SourceType.PROPERTIES) && !sourceType.equals(SourceType.DEFAULT_SETTING)) {
final int index = initOrder.indexOf(sourceType);
final SourceType replacedSourceType = initOrder.set(0, sourceType);
initOrder.set(index, replacedSourceType);
}
} catch (Exception e) {
LOGGER.warn("first source type parse error, it will be used default order!", e);
}
}
SEARCH_ORDER = initOrder;
StringBuilder orderInfo = new StringBuilder("properties search order:");
for (int i = 0; i < SEARCH_ORDER.size(); i++) {
orderInfo.append(SEARCH_ORDER.get(i).toString());
if (i < SEARCH_ORDER.size() - 1) {
orderInfo.append("->");
}
}
LOGGER.debug(orderInfo.toString());
}
static final SearchableProperties INSTANCE = new SearchableProperties();
private final List<AbstractPropertySource> propertySources;
@ -65,8 +93,8 @@ class SearchableProperties implements NacosClientProperties {
private SearchableProperties(PropertiesPropertySource propertiesPropertySource) {
this.propertiesPropertySource = propertiesPropertySource;
this.propertySources = build(propertiesPropertySource,
JVM_ARGS_PROPERTY_SOURCE, SYSTEM_ENV_PROPERTY_SOURCE, DEFAULT_SETTING_PROPERTY_SOURCE);
this.propertySources = build(propertiesPropertySource, JVM_ARGS_PROPERTY_SOURCE, SYSTEM_ENV_PROPERTY_SOURCE,
DEFAULT_SETTING_PROPERTY_SOURCE);
}
@Override
@ -79,6 +107,25 @@ class SearchableProperties implements NacosClientProperties {
return this.search(key, String.class).orElse(defaultValue);
}
@Override
public String getPropertyFrom(SourceType source, String key) {
if (source == null) {
return this.getProperty(key);
}
switch (source) {
case JVM:
return JVM_ARGS_PROPERTY_SOURCE.getProperty(key);
case ENV:
return SYSTEM_ENV_PROPERTY_SOURCE.getProperty(key);
case PROPERTIES:
return this.propertiesPropertySource.getProperty(key);
case DEFAULT_SETTING:
return DEFAULT_SETTING_PROPERTY_SOURCE.getProperty(key);
default:
return this.getProperty(key);
}
}
@Override
public Boolean getBoolean(String key) {
return getBoolean(key, null);
@ -122,8 +169,7 @@ class SearchableProperties implements NacosClientProperties {
@Override
public Properties asProperties() {
Properties properties = new Properties();
final ListIterator<AbstractPropertySource> iterator = propertySources.listIterator(
propertySources.size());
final ListIterator<AbstractPropertySource> iterator = propertySources.listIterator(propertySources.size());
while (iterator.hasPrevious()) {
final AbstractPropertySource previous = iterator.previous();
properties.putAll(previous.asProperties());
@ -166,60 +212,9 @@ class SearchableProperties implements NacosClientProperties {
}
private List<AbstractPropertySource> build(AbstractPropertySource... propertySources) {
String firstEnv = JVM_ARGS_PROPERTY_SOURCE.getProperty(Constants.SysEnv.NACOS_ENV_FIRST);
if (StringUtils.isBlank(firstEnv)) {
firstEnv = SYSTEM_ENV_PROPERTY_SOURCE.getProperty(Constants.SysEnv.NACOS_ENV_FIRST);
}
if (StringUtils.isBlank(firstEnv)) {
return sortPropertySourceDefaultOrder(propertySources);
}
try {
final SourceType sourceType = SourceType.valueOf(firstEnv.toUpperCase());
if (SourceType.DEFAULT_SETTING.equals(sourceType) || SourceType.PROPERTIES.equals(sourceType)) {
return sortPropertySourceDefaultOrder(propertySources);
}
return sortPropertySource(sourceType, propertySources);
} catch (Exception e) {
LOGGER.error("first source type parse error, it will be used default order!", e);
return sortPropertySourceDefaultOrder(propertySources);
}
}
private List<AbstractPropertySource> sortPropertySourceDefaultOrder(
AbstractPropertySource... propertySources) {
final Map<SourceType, AbstractPropertySource> sourceMap = Arrays.stream(propertySources)
.collect(Collectors.toMap(AbstractPropertySource::getType, propertySource -> propertySource));
final List<AbstractPropertySource> collect = DEFAULT_ORDER.stream().map(sourceMap::get)
.collect(Collectors.toList());
LOGGER.info("properties search order:PROPERTIES->JVM->ENV->DEFAULT_SETTING");
return collect;
}
private List<AbstractPropertySource> sortPropertySource(SourceType firstType,
AbstractPropertySource... propertySources) {
List<SourceType> tempList = new ArrayList<>(4);
tempList.add(firstType);
final Map<SourceType, AbstractPropertySource> sourceMap = Arrays.stream(propertySources)
.collect(Collectors.toMap(AbstractPropertySource::getType, propertySource -> propertySource));
final List<AbstractPropertySource> collect = DEFAULT_ORDER.stream()
.filter(sourceType -> !sourceType.equals(firstType)).collect(() -> tempList, List::add, List::addAll)
.stream().map(sourceMap::get).filter(Objects::nonNull).collect(Collectors.toList());
StringBuilder orderInfo = new StringBuilder("properties search order:");
for (int i = 0; i < collect.size(); i++) {
final AbstractPropertySource abstractPropertySource = collect.get(i);
orderInfo.append(abstractPropertySource.getType().toString());
if (i < collect.size() - 1) {
orderInfo.append("->");
}
}
LOGGER.info(orderInfo.toString());
return collect;
return SEARCH_ORDER.stream().map(sourceMap::get).collect(Collectors.toList());
}
@Override

View File

@ -16,7 +16,11 @@
package com.alibaba.nacos.client.env;
enum SourceType {
/**
* properties source type enum.
* @author onewe
*/
public enum SourceType {
/**
* get value from properties.
*/

View File

@ -16,13 +16,10 @@
package com.alibaba.nacos.client.logging;
import com.alibaba.nacos.client.constant.Constants;
import com.alibaba.nacos.client.env.NacosClientProperties;
import com.alibaba.nacos.common.utils.ConvertUtils;
import com.alibaba.nacos.common.utils.StringUtils;
import java.io.File;
/**
* Abstract nacos logging.
*
@ -35,16 +32,6 @@ public abstract class AbstractNacosLogging {
private static final String NACOS_LOGGING_DEFAULT_CONFIG_ENABLED_PROPERTY = "nacos.logging.default.config.enabled";
private static final String NACOS_LOGGING_PATH_DIR = "logs";
static {
String loggingPath = NacosClientProperties.PROTOTYPE.getProperty(Constants.SysEnv.JM_LOG_PATH);
if (StringUtils.isBlank(loggingPath)) {
String userHome = NacosClientProperties.PROTOTYPE.getProperty(Constants.SysEnv.USER_HOME);
NacosClientProperties.PROTOTYPE.setProperty(Constants.SysEnv.JM_LOG_PATH, userHome + File.separator + NACOS_LOGGING_PATH_DIR);
}
}
protected String getLocation(String defaultLocation) {
String location = NacosClientProperties.PROTOTYPE.getProperty(NACOS_LOGGING_CONFIG_PROPERTY);
if (StringUtils.isBlank(location)) {

View File

@ -22,8 +22,12 @@ import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.spi.LoggerContextListener;
import ch.qos.logback.core.CoreConstants;
import com.alibaba.nacos.client.logging.AbstractNacosLogging;
import com.alibaba.nacos.common.log.NacosLogbackConfigurator;
import com.alibaba.nacos.common.spi.NacosServiceLoader;
import com.alibaba.nacos.common.utils.ResourceUtils;
import org.slf4j.impl.StaticLoggerBinder;
import org.slf4j.LoggerFactory;
import java.util.Collection;
import java.util.stream.Collectors;
/**
* Support for Logback version 1.0.8 or higher
@ -37,6 +41,19 @@ public class LogbackNacosLogging extends AbstractNacosLogging {
private static final String NACOS_LOGBACK_LOCATION = "classpath:nacos-logback.xml";
private Integer userVersion = 2;
/**
* logback use 'ch.qos.logback.core.model.Model' since 1.3.0, set logback version during initialization.
*/
public LogbackNacosLogging() {
try {
Class.forName("ch.qos.logback.core.model.Model");
} catch (ClassNotFoundException e) {
userVersion = 1;
}
}
@Override
public void loadConfiguration() {
LoggerContext loggerContext = loadConfigurationOnStart();
@ -57,10 +74,13 @@ public class LogbackNacosLogging extends AbstractNacosLogging {
private LoggerContext loadConfigurationOnStart() {
String location = getLocation(NACOS_LOGBACK_LOCATION);
try {
LoggerContext loggerContext = (LoggerContext) StaticLoggerBinder.getSingleton().getLoggerFactory();
NacosJoranConfigurator configurator = new NacosJoranConfigurator();
configurator.setContext(loggerContext);
configurator.doNacosConfigure(ResourceUtils.getResourceUrl(location));
LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
Collection<NacosLogbackConfigurator> nacosLogbackConfigurators = NacosServiceLoader.load(
NacosLogbackConfigurator.class);
NacosLogbackConfigurator nacosLogbackConfigurator = nacosLogbackConfigurators.stream()
.filter(c -> c.getVersion() == userVersion).collect(Collectors.toList()).get(0);
nacosLogbackConfigurator.setContext(loggerContext);
nacosLogbackConfigurator.configure(ResourceUtils.getResourceUrl(location));
return loggerContext;
} catch (Exception e) {
throw new IllegalStateException("Could not initialize Logback Nacos logging from " + location, e);

View File

@ -0,0 +1,33 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.client.logging.logback;
import com.alibaba.nacos.client.env.NacosClientProperties;
import com.alibaba.nacos.common.log.NacosLogbackProperties;
/**
* adapter to higher version of logback (>= 1.4.5).
*
* @author hujun
*/
public class NacosClientLogbackProperties implements NacosLogbackProperties {
@Override
public String getValue(String source, String defaultValue) {
return NacosClientProperties.PROTOTYPE.getProperty(source, defaultValue);
}
}

View File

@ -17,11 +17,12 @@
package com.alibaba.nacos.client.logging.logback;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.Context;
import ch.qos.logback.core.joran.event.SaxEvent;
import ch.qos.logback.core.joran.spi.ElementSelector;
import ch.qos.logback.core.joran.spi.JoranException;
import ch.qos.logback.core.joran.spi.RuleStore;
import com.alibaba.nacos.common.log.NacosLogbackConfigurator;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
@ -34,7 +35,7 @@ import java.util.List;
* @author <a href="mailto:hujun3@xiaomi.com">hujun</a>
* @see <a href="https://github.com/alibaba/nacos/issues/6999">#6999</a>
*/
public class NacosJoranConfigurator extends JoranConfigurator {
public class NacosLogbackConfiguratorAdapterV1 extends JoranConfigurator implements NacosLogbackConfigurator {
/**
* ensure that Nacos configuration does not affect user configuration savepoints.
@ -51,13 +52,24 @@ public class NacosJoranConfigurator extends JoranConfigurator {
rs.addRule(new ElementSelector("configuration/nacosClientProperty"), new NacosClientPropertyAction());
}
@Override
public int getVersion() {
return 1;
}
@Override
public void setContext(Object loggerContext) {
super.setContext((Context) loggerContext);
}
/**
* ensure that Nacos configuration does not affect user configuration scanning url.
*
* @param url config url
* @throws JoranException e
* @throws Exception e
*/
public void doNacosConfigure(URL url) throws JoranException {
@Override
public void configure(URL url) throws Exception {
InputStream in = null;
try {
URLConnection urlConnection = url.openConnection();

View File

@ -103,16 +103,7 @@ public class NacosNamingService implements NamingService {
}
private void initLogName(NacosClientProperties properties) {
logName = properties.getProperty(UtilAndComs.NACOS_NAMING_LOG_NAME);
if (StringUtils.isEmpty(logName)) {
if (StringUtils
.isNotEmpty(properties.getProperty(UtilAndComs.NACOS_NAMING_LOG_NAME))) {
logName = properties.getProperty(UtilAndComs.NACOS_NAMING_LOG_NAME);
} else {
logName = DEFAULT_NAMING_LOG_FILE_PATH;
}
}
logName = properties.getProperty(UtilAndComs.NACOS_NAMING_LOG_NAME, DEFAULT_NAMING_LOG_FILE_PATH);
}
@Override

View File

@ -31,7 +31,10 @@ import com.alibaba.nacos.common.utils.ThreadUtils;
import java.io.BufferedReader;
import java.io.File;
import java.io.StringReader;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
@ -142,7 +145,7 @@ public class FailoverReactor implements Closeable {
@Override
public void run() {
try {
File switchFile = new File(failoverDir + UtilAndComs.FAILOVER_SWITCH);
File switchFile = Paths.get(failoverDir, UtilAndComs.FAILOVER_SWITCH).toFile();
if (!switchFile.exists()) {
switchParams.put(FAILOVER_MODE_PARAM, Boolean.FALSE.toString());
NAMING_LOGGER.debug("failover switch is not found, {}", switchFile.getName());
@ -208,11 +211,12 @@ public class FailoverReactor implements Closeable {
continue;
}
ServiceInfo dom = new ServiceInfo(file.getName());
ServiceInfo dom = null;
try {
String dataString = ConcurrentDiskUtil
.getFileContent(file, Charset.defaultCharset().toString());
dom = new ServiceInfo(URLDecoder.decode(file.getName(), StandardCharsets.UTF_8.name()));
String dataString = ConcurrentDiskUtil.getFileContent(file,
Charset.defaultCharset().toString());
reader = new BufferedReader(new StringReader(dataString));
String json;
@ -235,7 +239,7 @@ public class FailoverReactor implements Closeable {
//ignore
}
}
if (!CollectionUtils.isEmpty(dom.getHosts())) {
if (dom != null && !CollectionUtils.isEmpty(dom.getHosts())) {
domMap.put(dom.getKey(), dom);
}
}

View File

@ -53,6 +53,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.ServerListFactory;
import com.alibaba.nacos.common.remote.client.RpcClientTlsConfig;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.alibaba.nacos.common.utils.JacksonUtils;
@ -92,7 +93,7 @@ public class NamingGrpcClientProxy extends AbstractNamingClientProxy {
Map<String, String> labels = new HashMap<>();
labels.put(RemoteConstants.LABEL_SOURCE, RemoteConstants.LABEL_SOURCE_SDK);
labels.put(RemoteConstants.LABEL_MODULE, RemoteConstants.LABEL_MODULE_NAMING);
this.rpcClient = RpcClientFactory.createClient(uuid, ConnectionType.GRPC, labels);
this.rpcClient = RpcClientFactory.createClient(uuid, ConnectionType.GRPC, labels, RpcClientTlsConfig.properties(properties.asProperties()));
this.redoService = new NamingGrpcRedoService(this);
start(serverListFactory, serviceInfoHolder);
}
@ -153,7 +154,7 @@ public class NamingGrpcClientProxy extends AbstractNamingClientProxy {
instances));
}
String combinedServiceName = NamingUtils.getGroupedName(serviceName, groupName);
InstanceRedoData instanceRedoData = redoService.getRegisteredInstancesBykey(combinedServiceName);
InstanceRedoData instanceRedoData = redoService.getRegisteredInstancesByKey(combinedServiceName);
if (!(instanceRedoData instanceof BatchInstanceRedoData)) {
throw new NacosException(NacosException.INVALID_PARAM, String.format(
"[Batch deRegistration] batch deRegister is not BatchInstanceRedoData type , instances: %s,",
@ -231,7 +232,7 @@ public class NamingGrpcClientProxy extends AbstractNamingClientProxy {
InstanceRequest request = new InstanceRequest(namespaceId, serviceName, groupName,
NamingRemoteConstants.DE_REGISTER_INSTANCE, instance);
requestToServer(request, Response.class);
redoService.removeInstanceForRedo(serviceName, groupName);
redoService.instanceDeregistered(serviceName, groupName);
}
@Override

View File

@ -132,7 +132,7 @@ public class NamingGrpcRedoService implements ConnectionEventListener {
synchronized (registeredInstances) {
InstanceRedoData redoData = registeredInstances.get(key);
if (null != redoData) {
redoData.setRegistered(true);
redoData.registered();
}
}
}
@ -149,6 +149,23 @@ public class NamingGrpcRedoService implements ConnectionEventListener {
InstanceRedoData redoData = registeredInstances.get(key);
if (null != redoData) {
redoData.setUnregistering(true);
redoData.setExpectedRegistered(false);
}
}
}
/**
* Instance deregister finished, mark unregistered status.
*
* @param serviceName service name
* @param groupName group name
*/
public void instanceDeregistered(String serviceName, String groupName) {
String key = NamingUtils.getGroupedName(serviceName, groupName);
synchronized (registeredInstances) {
InstanceRedoData redoData = registeredInstances.get(key);
if (null != redoData) {
redoData.unregistered();
}
}
}
@ -160,8 +177,12 @@ public class NamingGrpcRedoService implements ConnectionEventListener {
* @param groupName group name
*/
public void removeInstanceForRedo(String serviceName, String groupName) {
String key = NamingUtils.getGroupedName(serviceName, groupName);
synchronized (registeredInstances) {
registeredInstances.remove(NamingUtils.getGroupedName(serviceName, groupName));
InstanceRedoData redoData = registeredInstances.get(key);
if (null != redoData && !redoData.isExpectedRegistered()) {
registeredInstances.remove(key);
}
}
}
@ -227,6 +248,7 @@ public class NamingGrpcRedoService implements ConnectionEventListener {
SubscriberRedoData redoData = subscribes.get(key);
if (null != redoData) {
redoData.setUnregistering(true);
redoData.setExpectedRegistered(false);
}
}
}
@ -255,8 +277,12 @@ public class NamingGrpcRedoService implements ConnectionEventListener {
* @param cluster cluster
*/
public void removeSubscriberForRedo(String serviceName, String groupName, String cluster) {
String key = ServiceInfo.getKey(NamingUtils.getGroupedName(serviceName, groupName), cluster);
synchronized (subscribes) {
subscribes.remove(ServiceInfo.getKey(NamingUtils.getGroupedName(serviceName, groupName), cluster));
SubscriberRedoData redoData = subscribes.get(key);
if (null != redoData && !redoData.isExpectedRegistered()) {
subscribes.remove(key);
}
}
}
@ -281,7 +307,7 @@ public class NamingGrpcRedoService implements ConnectionEventListener {
* get Cache service.
* @return cache service
*/
public InstanceRedoData getRegisteredInstancesBykey(String combinedServiceName) {
public InstanceRedoData getRegisteredInstancesByKey(String combinedServiceName) {
return registeredInstances.get(combinedServiceName);
}

View File

@ -19,6 +19,7 @@ package com.alibaba.nacos.client.naming.remote.gprc.redo.data;
import com.alibaba.nacos.api.naming.pojo.Instance;
import java.util.List;
import java.util.Objects;
/**
* batch instance redo service.
@ -54,4 +55,24 @@ public class BatchInstanceRedoData extends InstanceRedoData {
result.setInstances(instances);
return result;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof BatchInstanceRedoData)) {
return false;
}
if (!super.equals(o)) {
return false;
}
BatchInstanceRedoData redoData = (BatchInstanceRedoData) o;
return Objects.equals(instances, redoData.instances);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), instances);
}
}

View File

@ -30,6 +30,16 @@ public abstract class RedoData<T> {
private final String groupName;
/**
* Expected states for finally.
*
* <ul>
* <li>{@code true} meas the cached data expect registered to server finally.</li>
* <li>{@code false} means unregistered from server.</li>
* </ul>
*/
private volatile boolean expectedRegistered;
/**
* If {@code true} means cached data has been registered to server successfully.
*/
@ -45,6 +55,7 @@ public abstract class RedoData<T> {
protected RedoData(String serviceName, String groupName) {
this.serviceName = serviceName;
this.groupName = groupName;
this.expectedRegistered = true;
}
public String getServiceName() {
@ -55,18 +66,26 @@ public abstract class RedoData<T> {
return groupName;
}
public void setExpectedRegistered(boolean registered) {
this.expectedRegistered = registered;
}
public boolean isExpectedRegistered() {
return expectedRegistered;
}
public boolean isRegistered() {
return registered;
}
public void setRegistered(boolean registered) {
this.registered = registered;
}
public boolean isUnregistering() {
return unregistering;
}
public void setRegistered(boolean registered) {
this.registered = registered;
}
public void setUnregistering(boolean unregistering) {
this.unregistering = unregistering;
}
@ -79,8 +98,22 @@ public abstract class RedoData<T> {
this.data = data;
}
public void registered() {
this.registered = true;
this.unregistering = false;
}
public void unregistered() {
this.registered = false;
this.unregistering = true;
}
public boolean isNeedRedo() {
return !RedoType.NONE.equals(getRedoType());
}
/**
* Get redo type for current redo data.
* Get redo type for current redo data without expected state.
*
* <ul>
* <li>{@code registered=true} & {@code unregistering=false} means data has registered, so redo should not do anything.</li>
@ -93,20 +126,16 @@ public abstract class RedoData<T> {
*/
public RedoType getRedoType() {
if (isRegistered() && !isUnregistering()) {
return RedoType.NONE;
return expectedRegistered ? RedoType.NONE : RedoType.UNREGISTER;
} else if (isRegistered() && isUnregistering()) {
return RedoType.UNREGISTER;
} else if (!isRegistered() && !isUnregistering()) {
return RedoType.REGISTER;
} else {
return RedoType.REMOVE;
return expectedRegistered ? RedoType.REGISTER : RedoType.REMOVE;
}
}
public boolean isNeedRedo() {
return !RedoType.NONE.equals(getRedoType());
}
public enum RedoType {
/**
@ -129,7 +158,7 @@ public abstract class RedoData<T> {
*/
REMOVE;
}
@Override
public boolean equals(Object o) {
if (this == o) {
@ -139,10 +168,11 @@ public abstract class RedoData<T> {
return false;
}
RedoData<?> redoData = (RedoData<?>) o;
return registered == redoData.registered && unregistering == redoData.unregistering
&& serviceName.equals(redoData.serviceName) && groupName.equals(redoData.groupName) && data.equals(redoData.data);
return registered == redoData.registered && unregistering == redoData.unregistering && serviceName
.equals(redoData.serviceName) && groupName.equals(redoData.groupName) && Objects
.equals(data, redoData.data);
}
@Override
public int hashCode() {
return Objects.hash(serviceName, groupName, registered, unregistering, data);

View File

@ -23,6 +23,7 @@ import com.alibaba.nacos.api.selector.ExpressionSelector;
import com.alibaba.nacos.api.selector.NoneSelector;
import com.alibaba.nacos.api.selector.SelectorType;
import com.alibaba.nacos.client.env.NacosClientProperties;
import com.alibaba.nacos.client.env.SourceType;
import com.alibaba.nacos.client.utils.ContextPathUtil;
import com.alibaba.nacos.client.utils.LogUtils;
import com.alibaba.nacos.client.utils.ParamUtil;
@ -58,21 +59,21 @@ public class InitUtils {
if (Boolean.parseBoolean(isUseCloudNamespaceParsing)) {
tmpNamespace = TenantUtil.getUserTenantForAns();
LogUtils.NAMING_LOGGER.info("initializer namespace from System Property : {}", tmpNamespace);
LogUtils.NAMING_LOGGER.info("initializer namespace from ans.namespace attribute : {}", tmpNamespace);
tmpNamespace = TemplateUtils.stringEmptyAndThenExecute(tmpNamespace, () -> {
String namespace = properties.getProperty(PropertyKeyConst.SystemEnv.ALIBABA_ALIWARE_NAMESPACE);
LogUtils.NAMING_LOGGER.info("initializer namespace from System Environment :" + namespace);
LogUtils.NAMING_LOGGER.info("initializer namespace from ALIBABA_ALIWARE_NAMESPACE attribute :" + namespace);
return namespace;
});
}
tmpNamespace = TemplateUtils.stringEmptyAndThenExecute(tmpNamespace, () -> {
String namespace = properties.getProperty(PropertyKeyConst.NAMESPACE);
LogUtils.NAMING_LOGGER.info("initializer namespace from System Property :" + namespace);
String namespace = properties.getPropertyFrom(SourceType.JVM, PropertyKeyConst.NAMESPACE);
LogUtils.NAMING_LOGGER.info("initializer namespace from namespace attribute :" + namespace);
return namespace;
});
if (StringUtils.isEmpty(tmpNamespace)) {
tmpNamespace = properties.getProperty(PropertyKeyConst.NAMESPACE);
}

View File

@ -1,46 +0,0 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.client.remote;
import com.alibaba.nacos.common.remote.PayloadPackageProvider;
import java.util.HashSet;
import java.util.Set;
/**
* client package provider.
*
* @author hujun
*/
public class ClientPayloadPackageProvider implements PayloadPackageProvider {
private final Set<String> scanPackage = new HashSet<>();
{
scanPackage.add("com.alibaba.nacos.api.naming.remote.request");
scanPackage.add("com.alibaba.nacos.api.remote.request");
scanPackage.add("com.alibaba.nacos.api.config.remote.request");
scanPackage.add("com.alibaba.nacos.api.naming.remote.response");
scanPackage.add("com.alibaba.nacos.api.config.remote.response");
scanPackage.add("com.alibaba.nacos.api.remote.response");
}
@Override
public Set<String> getScanPackage() {
return scanPackage;
}
}

View File

@ -223,7 +223,7 @@ public class ParamUtil {
}
String endpointUrlSource = TemplateUtils
.stringBlankAndThenExecute(NacosClientProperties.PROTOTYPE.getProperty(endpointUrl, System.getenv(endpointUrl)),
.stringBlankAndThenExecute(NacosClientProperties.PROTOTYPE.getProperty(endpointUrl),
() -> NacosClientProperties.PROTOTYPE.getProperty(PropertyKeyConst.SystemEnv.ALIBABA_ALIWARE_ENDPOINT_URL));
if (StringUtils.isBlank(endpointUrlSource)) {

View File

@ -15,4 +15,4 @@
#
#
com.alibaba.nacos.common.remote.MockPayloadPackageProvider
com.alibaba.nacos.client.logging.logback.NacosLogbackConfiguratorAdapterV1

View File

@ -15,4 +15,4 @@
#
#
com.alibaba.nacos.config.server.remote.ConfigPayloadPackageProvider
com.alibaba.nacos.client.logging.logback.NacosClientLogbackProperties

View File

@ -1,18 +0,0 @@
#
# Copyright 1999-2021 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.
#
#
com.alibaba.nacos.client.remote.ClientPayloadPackageProvider

View File

@ -16,9 +16,13 @@
-->
<Configuration status="WARN">
<Properties>
<Property name="userHome" value="${nacosClientProperty:user.home}"/>
<Property name="logPath" value="${nacosClientProperty:JM.LOG.PATH:-${userHome}/logs}"/>
</Properties>
<Appenders>
<RollingFile name="CONFIG_LOG_FILE" fileName="${nacosClientProperty:JM.LOG.PATH}/nacos/config.log"
filePattern="${nacosClientProperty:JM.LOG.PATH}/nacos/config.log.%d{yyyy-MM-dd}.%i">
<RollingFile name="CONFIG_LOG_FILE" fileName="${logPath}/nacos/config.log"
filePattern="${logPath}/nacos/config.log.%d{yyyy-MM-dd}.%i">
<PatternLayout>
<Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %p [%-5t:%c{2}] %m%n</Pattern>
</PatternLayout>
@ -29,15 +33,19 @@
</Policies>
<DefaultRolloverStrategy max="${nacosClientProperty:JM.LOG.RETAIN.COUNT:-7}">
<Delete basePath="${nacosClientProperty:JM.LOG.PATH}/nacos" maxDepth="1" testMode="${nacosClientProperty:JM.LOG.RETAIN.DURATION.OFF:-true}">
<Delete basePath="${logPath}/nacos" maxDepth="1" testMode="${nacosClientProperty:JM.LOG.RETAIN.DURATION.OFF:-true}">
<IfFileName glob="config.log.*.*" />
<IfLastModified age="${nacosClientProperty:JM.LOG.RETAIN.DURATION:-P180D}" />
</Delete>
</DefaultRolloverStrategy>
</RollingFile>
<RollingFile name="REMOTE_LOG_FILE" fileName="${nacosClientProperty:JM.LOG.PATH}/nacos/remote.log"
filePattern="${nacosClientProperty:JM.LOG.PATH}/nacos/remote.log.%d{yyyy-MM-dd}.%i">
<Async name="ASYNC_CONFIG" bufferSize="1024" blocking="false">
<AppenderRef ref="CONFIG_LOG_FILE"/>
</Async>
<RollingFile name="REMOTE_LOG_FILE" fileName="${logPath}/nacos/remote.log"
filePattern="${logPath}/nacos/remote.log.%d{yyyy-MM-dd}.%i">
<PatternLayout>
<Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %p [%-5t:%c{2}] %m%n</Pattern>
</PatternLayout>
@ -48,15 +56,19 @@
</Policies>
<DefaultRolloverStrategy max="${nacosClientProperty:JM.LOG.RETAIN.COUNT:-7}">
<Delete basePath="${nacosClientProperty:JM.LOG.PATH}/nacos" maxDepth="1" testMode="${nacosClientProperty:JM.LOG.RETAIN.DURATION.OFF:-true}">
<Delete basePath="${logPath}/nacos" maxDepth="1" testMode="${nacosClientProperty:JM.LOG.RETAIN.DURATION.OFF:-true}">
<IfFileName glob="remote.log.*.*" />
<IfLastModified age="${nacosClientProperty:JM.LOG.RETAIN.DURATION:-P180D}" />
</Delete>
</DefaultRolloverStrategy>
</RollingFile>
<Async name="ASYNC_REMOTE" bufferSize="1024" blocking="false">
<AppenderRef ref="REMOTE_LOG_FILE"/>
</Async>
<RollingFile name="NAMING_LOG_FILE" fileName="${nacosClientProperty:JM.LOG.PATH}/nacos/naming.log"
filePattern="${nacosClientProperty:JM.LOG.PATH}/nacos/naming.log.%d{yyyy-MM-dd}.%i">
<RollingFile name="NAMING_LOG_FILE" fileName="${logPath}/nacos/naming.log"
filePattern="${logPath}/nacos/naming.log.%d{yyyy-MM-dd}.%i">
<PatternLayout>
<Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %p [%-5t:%c{2}] %m%n</Pattern>
</PatternLayout>
@ -67,37 +79,38 @@
</Policies>
<DefaultRolloverStrategy max="${nacosClientProperty:JM.LOG.RETAIN.COUNT:-7}">
<Delete basePath="${nacosClientProperty:JM.LOG.PATH}/nacos" maxDepth="1" testMode="${nacosClientProperty:JM.LOG.RETAIN.DURATION.OFF:-true}">
<Delete basePath="${logPath}/nacos" maxDepth="1" testMode="${nacosClientProperty:JM.LOG.RETAIN.DURATION.OFF:-true}">
<IfFileName glob="naming.log.*.*" />
<IfLastModified age="${nacosClientProperty:JM.LOG.RETAIN.DURATION:-P180D}" />
</Delete>
</DefaultRolloverStrategy>
</RollingFile>
<Async name="ASYNC_NAMING" bufferSize="1024" blocking="false">
<AppenderRef ref="NAMING_LOG_FILE"/>
</Async>
</Appenders>
<Loggers>
<Logger name="com.alibaba.nacos.client" level="${nacosClientProperty:com.alibaba.nacos.config.log.level:-info}"
additivity="false">
<AppenderRef ref="CONFIG_LOG_FILE"/>
<AppenderRef ref="ASYNC_CONFIG"/>
</Logger>
<Logger name="com.alibaba.nacos.common.remote.client" level="${nacosClientProperty:com.alibaba.nacos.config.log.level:-info}"
additivity="false">
<AppenderRef ref="REMOTE_LOG_FILE"/>
<AppenderRef ref="ASYNC_REMOTE"/>
</Logger>
<Logger name="com.alibaba.nacos.client.config" level="${nacosClientProperty:com.alibaba.nacos.config.log.level:-info}"
additivity="false">
<AppenderRef ref="CONFIG_LOG_FILE"/>
<AppenderRef ref="ASYNC_CONFIG"/>
</Logger>
<Logger name="com.alibaba.nacos.client.naming" level="${nacosClientProperty:com.alibaba.nacos.naming.log.level:-info}"
additivity="false">
<AppenderRef ref="NAMING_LOG_FILE"/>
<AppenderRef ref="ASYNC_NAMING"/>
</Logger>
<Root level="INFO">
<AppenderRef ref="CONFIG_LOG_FILE"/>
</Root>
</Loggers>
</Configuration>

View File

@ -16,7 +16,7 @@
-->
<configuration debug="false" scan="false" packagingData="true">
<nacosClientProperty scope="context" name="logPath" source="JM.LOG.PATH"/>
<nacosClientProperty scope="context" name="logPath" source="JM.LOG.PATH" defaultValue="${user.home}/logs"/>
<nacosClientProperty scope="context" name="logRetainCount" source="JM.LOG.RETAIN.COUNT" defaultValue="7"/>
<nacosClientProperty scope="context" name="logFileSize" source="JM.LOG.FILE.SIZE" defaultValue="10MB"/>
<nacosClientProperty scope="context" name="nacosConfigLogLevel" source="com.alibaba.nacos.config.log.level" defaultValue="info"/>
@ -39,6 +39,13 @@
</encoder>
</appender>
<appender name="ASYNC-CONFIG" class="ch.qos.logback.classic.AsyncAppender">
<discardingThreshold>0</discardingThreshold>
<queueSize>1024</queueSize>
<neverBlock>true</neverBlock>
<appender-ref ref="CONFIG_LOG_FILE"/>
</appender>
<appender name="NAMING_LOG_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${logPath}/nacos/naming.log</file>
@ -56,6 +63,13 @@
</encoder>
</appender>
<appender name="ASYNC-NAMING" class="ch.qos.logback.classic.AsyncAppender">
<discardingThreshold>0</discardingThreshold>
<queueSize>1024</queueSize>
<neverBlock>true</neverBlock>
<appender-ref ref="NAMING_LOG_FILE"/>
</appender>
<appender name="REMOTE_LOG_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${logPath}/nacos/remote.log</file>
@ -73,31 +87,37 @@
</encoder>
</appender>
<appender name="ASYNC-REMOTE" class="ch.qos.logback.classic.AsyncAppender">
<discardingThreshold>0</discardingThreshold>
<queueSize>1024</queueSize>
<neverBlock>true</neverBlock>
<appender-ref ref="REMOTE_LOG_FILE"/>
</appender>
<logger name="com.alibaba.nacos.client" level="${nacosConfigLogLevel}"
additivity="false">
<appender-ref ref="CONFIG_LOG_FILE"/>
<appender-ref ref="ASYNC-CONFIG"/>
</logger>
<Logger name="com.alibaba.nacos.common.remote.client" level="${nacosConfigLogLevel}"
additivity="false">
<appender-ref ref="REMOTE_LOG_FILE"/>
<appender-ref ref="ASYNC-REMOTE"/>
</Logger>
<Logger name="com.alibaba.nacos.shaded.io.grpc" level="${nacosConfigLogLevel}"
additivity="false">
<appender-ref ref="REMOTE_LOG_FILE"/>
<appender-ref ref="ASYNC-REMOTE"/>
</Logger>
<logger name="com.alibaba.nacos.client.config" level="${nacosConfigLogLevel}"
additivity="false">
<appender-ref ref="CONFIG_LOG_FILE"/>
<appender-ref ref="ASYNC-CONFIG"/>
</logger>
<logger name="com.alibaba.nacos.client.naming" level="${nacosConfigLogLevel}"
additivity="false">
<appender-ref ref="NAMING_LOG_FILE"/>
<appender-ref ref="ASYNC-NAMING"/>
</logger>
</configuration>

View File

@ -0,0 +1,134 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.client.auth.ram.identify;
import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException;
import com.alibaba.nacos.client.config.impl.ConfigHttpClientManager;
import com.alibaba.nacos.common.http.client.NacosRestTemplate;
import com.alibaba.nacos.common.http.client.request.HttpClientRequest;
import com.alibaba.nacos.common.http.client.response.HttpClientResponse;
import com.alibaba.nacos.common.http.param.Header;
import com.alibaba.nacos.common.utils.JacksonUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.io.ByteArrayInputStream;
import java.lang.reflect.Field;
import java.util.Date;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class StsCredentialHolderTest {
private String securityCredentialsUrl;
private HttpClientRequest httpClient;
@Mock
private HttpClientRequest mockRest;
@Before
public void setUp() throws Exception {
securityCredentialsUrl = StsConfig.getInstance().getSecurityCredentialsUrl();
StsConfig.getInstance().setSecurityCredentialsUrl("url");
Field field = NacosRestTemplate.class.getDeclaredField("requestClient");
field.setAccessible(true);
httpClient = (HttpClientRequest) field.get(ConfigHttpClientManager.getInstance().getNacosRestTemplate());
field.set(ConfigHttpClientManager.getInstance().getNacosRestTemplate(), mockRest);
}
@After
public void tearDown() throws Exception {
StsConfig.getInstance().setSecurityCredentials(null);
StsConfig.getInstance().setSecurityCredentialsUrl(securityCredentialsUrl);
Field field = NacosRestTemplate.class.getDeclaredField("requestClient");
field.setAccessible(true);
field.set(ConfigHttpClientManager.getInstance().getNacosRestTemplate(), httpClient);
clearForSts();
}
private void clearForSts() throws NoSuchFieldException, IllegalAccessException {
StsConfig.getInstance().setSecurityCredentialsUrl(null);
Field field = StsCredentialHolder.class.getDeclaredField("stsCredential");
field.setAccessible(true);
field.set(StsCredentialHolder.getInstance(), null);
}
@Test
public void testGetStsCredentialFromCache() throws NoSuchFieldException, IllegalAccessException {
StsCredential stsCredential = buildMockStsCredential();
setStsCredential(stsCredential);
assertEquals(stsCredential, StsCredentialHolder.getInstance().getStsCredential());
}
private void setStsCredential(StsCredential stsCredential) throws NoSuchFieldException, IllegalAccessException {
Field field = StsCredentialHolder.class.getDeclaredField("stsCredential");
field.setAccessible(true);
field.set(StsCredentialHolder.getInstance(), stsCredential);
}
@Test
public void testGetStsCredentialFromStringCache() throws NoSuchFieldException, IllegalAccessException {
StsCredential stsCredential = buildMockStsCredential();
StsConfig.getInstance().setSecurityCredentials(JacksonUtils.toJson(stsCredential));
assertEquals(stsCredential.toString(), StsCredentialHolder.getInstance().getStsCredential().toString());
}
@Test
public void testGetStsCredentialFromRequest() throws Exception {
StsCredential stsCredential = buildMockStsCredential();
HttpClientResponse response = mock(HttpClientResponse.class);
when(response.getStatusCode()).thenReturn(200);
when(response.getHeaders()).thenReturn(Header.newInstance());
when(response.getBody()).thenReturn(new ByteArrayInputStream(JacksonUtils.toJsonBytes(stsCredential)));
when(mockRest.execute(any(), any(), any())).thenReturn(response);
assertEquals(stsCredential.toString(), StsCredentialHolder.getInstance().getStsCredential().toString());
}
@Test(expected = NacosRuntimeException.class)
public void testGetStsCredentialFromRequestFailure() throws Exception {
HttpClientResponse response = mock(HttpClientResponse.class);
when(response.getStatusCode()).thenReturn(500);
when(response.getHeaders()).thenReturn(Header.newInstance());
when(response.getBody()).thenReturn(new ByteArrayInputStream(new byte[0]));
when(mockRest.execute(any(), any(), any())).thenReturn(response);
StsCredentialHolder.getInstance().getStsCredential();
}
@Test(expected = NacosRuntimeException.class)
public void testGetStsCredentialFromRequestException() throws Exception {
when(mockRest.execute(any(), any(), any())).thenThrow(new RuntimeException("test"));
StsCredentialHolder.getInstance().getStsCredential();
}
private StsCredential buildMockStsCredential() {
StsCredential stsCredential = new StsCredential();
stsCredential.setAccessKeyId("test-sts-ak");
stsCredential.setAccessKeySecret("test-sts-sk");
stsCredential.setSecurityToken("test-sts-token");
stsCredential.setExpiration(new Date(System.currentTimeMillis() + 1000000));
return stsCredential;
}
}

View File

@ -17,16 +17,22 @@
package com.alibaba.nacos.client.auth.ram.injector;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.plugin.auth.api.LoginIdentityContext;
import com.alibaba.nacos.client.auth.ram.RamContext;
import com.alibaba.nacos.plugin.auth.api.RequestResource;
import com.alibaba.nacos.client.auth.ram.identify.IdentifyConstants;
import com.alibaba.nacos.client.auth.ram.identify.StsConfig;
import com.alibaba.nacos.client.auth.ram.identify.StsCredential;
import com.alibaba.nacos.client.auth.ram.identify.StsCredentialHolder;
import com.alibaba.nacos.plugin.auth.api.LoginIdentityContext;
import com.alibaba.nacos.plugin.auth.api.RequestResource;
import com.alibaba.nacos.plugin.auth.constant.SignType;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.lang.reflect.Field;
import java.util.Date;
public class ConfigResourceInjectorTest {
private ConfigResourceInjector configResourceInjector;
@ -39,6 +45,8 @@ public class ConfigResourceInjectorTest {
private String cachedSecurityCredentials;
private StsCredential stsCredential;
@Before
public void setUp() throws Exception {
configResourceInjector = new ConfigResourceInjector();
@ -53,16 +61,18 @@ public class ConfigResourceInjectorTest {
cachedSecurityCredentials = StsConfig.getInstance().getSecurityCredentials();
StsConfig.getInstance().setSecurityCredentialsUrl("");
StsConfig.getInstance().setSecurityCredentials("");
stsCredential = new StsCredential();
}
@After
public void tearDown() {
public void tearDown() throws NoSuchFieldException, IllegalAccessException {
StsConfig.getInstance().setSecurityCredentialsUrl(cachedSecurityCredentialsUrl);
StsConfig.getInstance().setSecurityCredentials(cachedSecurityCredentials);
clearForSts();
}
@Test
public void testDoInject() throws Exception {
public void testDoInjectWithFullResource() throws Exception {
LoginIdentityContext actual = new LoginIdentityContext();
configResourceInjector.doInject(resource, ramContext, actual);
Assert.assertEquals(3, actual.getAllKey().size());
@ -70,4 +80,67 @@ public class ConfigResourceInjectorTest {
Assert.assertTrue(actual.getAllKey().contains("Timestamp"));
Assert.assertTrue(actual.getAllKey().contains("Spas-Signature"));
}
@Test
public void testDoInjectWithTenant() throws Exception {
resource.setGroup("");
LoginIdentityContext actual = new LoginIdentityContext();
configResourceInjector.doInject(resource, ramContext, actual);
Assert.assertEquals(3, actual.getAllKey().size());
Assert.assertEquals(PropertyKeyConst.ACCESS_KEY, actual.getParameter("Spas-AccessKey"));
Assert.assertTrue(actual.getAllKey().contains("Timestamp"));
Assert.assertTrue(actual.getAllKey().contains("Spas-Signature"));
}
@Test
public void testDoInjectWithGroup() throws Exception {
resource.setNamespace("");
LoginIdentityContext actual = new LoginIdentityContext();
configResourceInjector.doInject(resource, ramContext, actual);
Assert.assertEquals(3, actual.getAllKey().size());
Assert.assertEquals(PropertyKeyConst.ACCESS_KEY, actual.getParameter("Spas-AccessKey"));
Assert.assertTrue(actual.getAllKey().contains("Timestamp"));
Assert.assertTrue(actual.getAllKey().contains("Spas-Signature"));
}
@Test
public void testDoInjectWithoutResource() throws Exception {
resource = new RequestResource();
LoginIdentityContext actual = new LoginIdentityContext();
configResourceInjector.doInject(resource, ramContext, actual);
Assert.assertEquals(3, actual.getAllKey().size());
Assert.assertEquals(PropertyKeyConst.ACCESS_KEY, actual.getParameter("Spas-AccessKey"));
Assert.assertTrue(actual.getAllKey().contains("Timestamp"));
Assert.assertTrue(actual.getAllKey().contains("Spas-Signature"));
}
@Test
public void testDoInjectForSts() throws NoSuchFieldException, IllegalAccessException {
prepareForSts();
LoginIdentityContext actual = new LoginIdentityContext();
configResourceInjector.doInject(resource, ramContext, actual);
Assert.assertEquals(4, actual.getAllKey().size());
Assert.assertEquals("test-sts-ak", actual.getParameter("Spas-AccessKey"));
Assert.assertTrue(actual.getAllKey().contains("Timestamp"));
Assert.assertTrue(actual.getAllKey().contains("Spas-Signature"));
Assert.assertTrue(actual.getAllKey().contains(IdentifyConstants.SECURITY_TOKEN_HEADER));
}
private void prepareForSts() throws NoSuchFieldException, IllegalAccessException {
StsConfig.getInstance().setSecurityCredentialsUrl("test");
Field field = StsCredentialHolder.class.getDeclaredField("stsCredential");
field.setAccessible(true);
field.set(StsCredentialHolder.getInstance(), stsCredential);
stsCredential.setAccessKeyId("test-sts-ak");
stsCredential.setAccessKeySecret("test-sts-sk");
stsCredential.setSecurityToken("test-sts-token");
stsCredential.setExpiration(new Date(System.currentTimeMillis() + 1000000));
}
private void clearForSts() throws NoSuchFieldException, IllegalAccessException {
StsConfig.getInstance().setSecurityCredentialsUrl(null);
Field field = StsCredentialHolder.class.getDeclaredField("stsCredential");
field.setAccessible(true);
field.set(StsCredentialHolder.getInstance(), null);
}
}

View File

@ -17,14 +17,21 @@
package com.alibaba.nacos.client.auth.ram.injector;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.plugin.auth.api.LoginIdentityContext;
import com.alibaba.nacos.client.auth.ram.RamContext;
import com.alibaba.nacos.plugin.auth.api.RequestResource;
import com.alibaba.nacos.client.auth.ram.identify.StsConfig;
import com.alibaba.nacos.client.auth.ram.identify.StsCredential;
import com.alibaba.nacos.client.auth.ram.identify.StsCredentialHolder;
import com.alibaba.nacos.client.auth.ram.utils.SignUtil;
import com.alibaba.nacos.plugin.auth.api.LoginIdentityContext;
import com.alibaba.nacos.plugin.auth.api.RequestResource;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.lang.reflect.Field;
import java.util.Date;
public class NamingResourceInjectorTest {
private NamingResourceInjector namingResourceInjector;
@ -33,12 +40,32 @@ public class NamingResourceInjectorTest {
private RequestResource resource;
private StsCredential stsCredential;
@Before
public void setUp() throws Exception {
namingResourceInjector = new NamingResourceInjector();
ramContext = new RamContext();
ramContext.setAccessKey(PropertyKeyConst.ACCESS_KEY);
ramContext.setSecretKey(PropertyKeyConst.SECRET_KEY);
stsCredential = new StsCredential();
}
@After
public void tearDown() throws NoSuchFieldException, IllegalAccessException {
clearForSts();
}
@Test
public void testDoInjectWithEmpty() throws Exception {
resource = RequestResource.namingBuilder().setResource("").build();
LoginIdentityContext actual = new LoginIdentityContext();
namingResourceInjector.doInject(resource, ramContext, actual);
String expectSign = SignUtil.sign(actual.getParameter("data"), PropertyKeyConst.SECRET_KEY);
Assert.assertEquals(3, actual.getAllKey().size());
Assert.assertEquals(PropertyKeyConst.ACCESS_KEY, actual.getParameter("ak"));
Assert.assertTrue(Long.parseLong(actual.getParameter("data")) - System.currentTimeMillis() < 100);
Assert.assertEquals(expectSign, actual.getParameter("signature"));
}
@Test
@ -46,10 +73,10 @@ public class NamingResourceInjectorTest {
resource = RequestResource.namingBuilder().setResource("test@@aaa").setGroup("group").build();
LoginIdentityContext actual = new LoginIdentityContext();
namingResourceInjector.doInject(resource, ramContext, actual);
String expectSign = SignUtil.sign(actual.getParameter("data"), PropertyKeyConst.SECRET_KEY);
Assert.assertEquals(3, actual.getAllKey().size());
Assert.assertEquals(PropertyKeyConst.ACCESS_KEY, actual.getParameter("ak"));
Assert.assertTrue(actual.getParameter("data").endsWith("@@test@@aaa"));
String expectSign = SignUtil.sign(actual.getParameter("data"), PropertyKeyConst.SECRET_KEY);
Assert.assertEquals(expectSign, actual.getParameter("signature"));
}
@ -58,10 +85,64 @@ public class NamingResourceInjectorTest {
resource = RequestResource.namingBuilder().setResource("aaa").setGroup("group").build();
LoginIdentityContext actual = new LoginIdentityContext();
namingResourceInjector.doInject(resource, ramContext, actual);
Assert.assertTrue(actual.getParameter("data").endsWith("@@group@@aaa"));
Assert.assertEquals(3, actual.getAllKey().size());
Assert.assertEquals(PropertyKeyConst.ACCESS_KEY, actual.getParameter("ak"));
Assert.assertTrue(actual.getParameter("data").endsWith("@@group@@aaa"));
String expectSign = SignUtil.sign(actual.getParameter("data"), PropertyKeyConst.SECRET_KEY);
Assert.assertEquals(expectSign, actual.getParameter("signature"));
}
@Test
public void testDoInjectWithGroupForSts() throws Exception {
prepareForSts();
resource = RequestResource.namingBuilder().setResource("test@@aaa").setGroup("group").build();
LoginIdentityContext actual = new LoginIdentityContext();
namingResourceInjector.doInject(resource, ramContext, actual);
String expectSign = SignUtil.sign(actual.getParameter("data"), "test-sts-sk");
Assert.assertEquals(4, actual.getAllKey().size());
Assert.assertEquals("test-sts-ak", actual.getParameter("ak"));
Assert.assertTrue(actual.getParameter("data").endsWith("@@test@@aaa"));
Assert.assertEquals(expectSign, actual.getParameter("signature"));
}
@Test
public void testDoInjectWithoutGroupForSts() throws Exception {
prepareForSts();
resource = RequestResource.namingBuilder().setResource("aaa").setGroup("group").build();
LoginIdentityContext actual = new LoginIdentityContext();
namingResourceInjector.doInject(resource, ramContext, actual);
String expectSign = SignUtil.sign(actual.getParameter("data"), "test-sts-sk");
Assert.assertEquals(4, actual.getAllKey().size());
Assert.assertEquals("test-sts-ak", actual.getParameter("ak"));
Assert.assertTrue(actual.getParameter("data").endsWith("@@group@@aaa"));
Assert.assertEquals(expectSign, actual.getParameter("signature"));
}
@Test
public void testDoInjectForStsWithException() throws Exception {
prepareForSts();
stsCredential.setExpiration(new Date());
resource = RequestResource.namingBuilder().setResource("aaa").setGroup("group").build();
LoginIdentityContext actual = new LoginIdentityContext();
namingResourceInjector.doInject(resource, ramContext, actual);
Assert.assertEquals(0, actual.getAllKey().size());
}
private void prepareForSts() throws NoSuchFieldException, IllegalAccessException {
StsConfig.getInstance().setSecurityCredentialsUrl("test");
Field field = StsCredentialHolder.class.getDeclaredField("stsCredential");
field.setAccessible(true);
field.set(StsCredentialHolder.getInstance(), stsCredential);
stsCredential.setAccessKeyId("test-sts-ak");
stsCredential.setAccessKeySecret("test-sts-sk");
stsCredential.setSecurityToken("test-sts-token");
stsCredential.setExpiration(new Date(System.currentTimeMillis() + 1000000));
}
private void clearForSts() throws NoSuchFieldException, IllegalAccessException {
StsConfig.getInstance().setSecurityCredentialsUrl(null);
Field field = StsCredentialHolder.class.getDeclaredField("stsCredential");
field.setAccessible(true);
field.set(StsCredentialHolder.getInstance(), null);
}
}

View File

@ -182,8 +182,27 @@ public class ClientWorkerTest {
Assert.assertTrue(o.executor.isShutdown());
agent1.setAccessible(false);
Assert.assertTrue(clientWorker.isHealthServer());
Assert.assertEquals(null, clientWorker.getAgentName());
}
@Test
public void testIsHealthServer() throws NacosException, NoSuchFieldException, IllegalAccessException {
Properties prop = new Properties();
ConfigFilterChainManager filter = new ConfigFilterChainManager(new Properties());
ServerListManager agent = Mockito.mock(ServerListManager.class);
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(prop);
ClientWorker clientWorker = new ClientWorker(filter, agent, nacosClientProperties);
ClientWorker.ConfigRpcTransportClient client = Mockito.mock(ClientWorker.ConfigRpcTransportClient.class);
Mockito.when(client.isHealthServer()).thenReturn(Boolean.TRUE);
Field declaredField = ClientWorker.class.getDeclaredField("agent");
declaredField.setAccessible(true);
declaredField.set(clientWorker, client);
Assert.assertEquals(true, clientWorker.isHealthServer());
Mockito.when(client.isHealthServer()).thenReturn(Boolean.FALSE);
Assert.assertEquals(false, clientWorker.isHealthServer());
}
}

View File

@ -305,4 +305,22 @@ public class NacosClientPropertiesTest {
}
@Test
public void testGetPropertyFrom() {
System.setProperty("nacos.home.default.test", "/home/jvm_args");
NacosClientProperties.PROTOTYPE.setProperty("nacos.home.default.test", "/home/properties_args");
Assert.assertEquals(NacosClientProperties.PROTOTYPE.getPropertyFrom(SourceType.JVM, "nacos.home.default.test"),
"/home/jvm_args");
Assert.assertEquals(
NacosClientProperties.PROTOTYPE.getPropertyFrom(SourceType.DEFAULT_SETTING, "nacos.home.default.test"),
"/home/default_setting");
Assert.assertEquals(
NacosClientProperties.PROTOTYPE.getPropertyFrom(SourceType.PROPERTIES, "nacos.home.default.test"),
"/home/properties_args");
Assert.assertEquals(
NacosClientProperties.PROTOTYPE.getPropertyFrom(null, "nacos.home.default.test"),
NacosClientProperties.PROTOTYPE.getProperty("nacos.home.default.test"));
}
}

View File

@ -78,8 +78,9 @@ public class AbstractNamingClientProxyTest {
Map<String, String> mockIdentityContext = new HashMap<>();
String serviceName = "aaa";
mockIdentityContext.put("ak", ak);
mockIdentityContext.put("data", System.currentTimeMillis() + "@@" + serviceName);
mockIdentityContext.put("signature", SignUtil.sign(System.currentTimeMillis() + "@@" + serviceName, sk));
String data = System.currentTimeMillis() + "@@" + serviceName;
mockIdentityContext.put("data", data);
mockIdentityContext.put("signature", SignUtil.sign(data, sk));
when(sc.getIdentityContext(any(RequestResource.class))).thenReturn(mockIdentityContext);
AbstractNamingClientProxy proxy = new MockNamingClientProxy(sc);
Map<String, String> spasHeaders = proxy.getSecurityHeaders("", "", serviceName);

View File

@ -66,6 +66,7 @@ import org.mockito.junit.MockitoJUnitRunner;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ -74,6 +75,8 @@ import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.times;
@ -223,6 +226,66 @@ public class NamingGrpcClientProxyTest {
}));
}
@Test(expected = NacosException.class)
public void testBatchDeregisterServiceWithEmptyInstances() throws NacosException {
client.batchDeregisterService(SERVICE_NAME, GROUP_NAME, Collections.EMPTY_LIST);
}
@Test(expected = NacosException.class)
public void testBatchDeregisterServiceWithoutCacheData() throws NacosException {
List<Instance> instanceList = new ArrayList<>();
instance.setHealthy(true);
instanceList.add(instance);
client.batchDeregisterService(SERVICE_NAME, GROUP_NAME, instanceList);
}
@Test(expected = NacosException.class)
public void testBatchDeregisterServiceNotBatchData() throws NacosException {
client.registerService(SERVICE_NAME, GROUP_NAME, instance);
List<Instance> instanceList = new ArrayList<>();
instance.setHealthy(true);
instanceList.add(instance);
client.batchDeregisterService(SERVICE_NAME, GROUP_NAME, instanceList);
}
@Test(expected = NacosException.class)
public void testBatchDeregisterServiceWithEmptyBatchData() throws NacosException {
try {
client.batchRegisterService(SERVICE_NAME, GROUP_NAME, Collections.EMPTY_LIST);
} catch (Exception ignored) {
}
List<Instance> instanceList = new ArrayList<>();
instance.setHealthy(true);
instanceList.add(instance);
client.batchDeregisterService(SERVICE_NAME, GROUP_NAME, instanceList);
}
@Test
public void testBatchDeregisterService() throws NacosException {
try {
List<Instance> instanceList = new ArrayList<>();
instance.setHealthy(true);
instanceList.add(instance);
instanceList.add(new Instance());
client.batchRegisterService(SERVICE_NAME, GROUP_NAME, instanceList);
} catch (Exception ignored) {
}
response = new BatchInstanceResponse();
when(this.rpcClient.request(any())).thenReturn(response);
List<Instance> instanceList = new ArrayList<>();
instance.setHealthy(true);
instanceList.add(instance);
client.batchDeregisterService(SERVICE_NAME, GROUP_NAME, instanceList);
verify(this.rpcClient, times(1)).request(argThat(request -> {
if (request instanceof BatchInstanceRequest) {
BatchInstanceRequest request1 = (BatchInstanceRequest) request;
request1.setRequestId("1");
return request1.getInstances().size() == 1 && request1.getType().equals(NamingRemoteConstants.BATCH_REGISTER_INSTANCE);
}
return false;
}));
}
@Test
public void testUpdateInstance() throws Exception {
//TODO thrown.expect(UnsupportedOperationException.class);
@ -256,7 +319,7 @@ public class NamingGrpcClientProxyTest {
@Test
public void testDeleteService() throws Exception {
//TODO thrown.expect(UnsupportedOperationException.class);
Assert.assertFalse(client.deleteService(SERVICE_NAME, GROUP_NAME));
assertFalse(client.deleteService(SERVICE_NAME, GROUP_NAME));
}
@Test
@ -310,6 +373,17 @@ public class NamingGrpcClientProxyTest {
}));
}
@Test
public void testIsSubscribed() throws NacosException {
SubscribeServiceResponse res = new SubscribeServiceResponse();
ServiceInfo info = new ServiceInfo(GROUP_NAME + "@@" + SERVICE_NAME + "@@" + CLUSTERS);
res.setServiceInfo(info);
when(this.rpcClient.request(any())).thenReturn(res);
assertFalse(client.isSubscribed(SERVICE_NAME, GROUP_NAME, CLUSTERS));
client.subscribe(SERVICE_NAME, GROUP_NAME, CLUSTERS);
assertTrue(client.isSubscribed(SERVICE_NAME, GROUP_NAME, CLUSTERS));
}
@Test
public void testServerHealthy() {
when(this.rpcClient.isRunning()).thenReturn(true);

View File

@ -101,6 +101,7 @@ public class NamingGrpcRedoServiceTest {
assertEquals(instance, actual.get());
assertFalse(actual.isRegistered());
assertFalse(actual.isUnregistering());
assertTrue(actual.isExpectedRegistered());
}
@Test
@ -136,6 +137,17 @@ public class NamingGrpcRedoServiceTest {
redoService.instanceDeregister(SERVICE, GROUP);
InstanceRedoData actual = registeredInstances.entrySet().iterator().next().getValue();
assertTrue(actual.isUnregistering());
assertFalse(actual.isExpectedRegistered());
}
@Test
public void testInstanceDeregistered() {
ConcurrentMap<String, InstanceRedoData> registeredInstances = getInstanceRedoDataMap();
redoService.cacheInstanceForRedo(SERVICE, GROUP, new Instance());
redoService.instanceDeregistered(SERVICE, GROUP);
InstanceRedoData actual = registeredInstances.entrySet().iterator().next().getValue();
assertFalse(actual.isRegistered());
assertTrue(actual.isUnregistering());
}
@Test
@ -144,6 +156,7 @@ public class NamingGrpcRedoServiceTest {
assertTrue(registeredInstances.isEmpty());
redoService.cacheInstanceForRedo(SERVICE, GROUP, new Instance());
assertFalse(registeredInstances.isEmpty());
redoService.instanceDeregister(SERVICE, GROUP);
redoService.removeInstanceForRedo(SERVICE, GROUP);
assertTrue(registeredInstances.isEmpty());
}
@ -195,12 +208,21 @@ public class NamingGrpcRedoServiceTest {
assertTrue(actual.isUnregistering());
}
@Test
public void testIsSubscriberRegistered() {
assertFalse(redoService.isSubscriberRegistered(SERVICE, GROUP, CLUSTER));
redoService.cacheSubscriberForRedo(SERVICE, GROUP, CLUSTER);
redoService.subscriberRegistered(SERVICE, GROUP, CLUSTER);
assertTrue(redoService.isSubscriberRegistered(SERVICE, GROUP, CLUSTER));
}
@Test
public void testRemoveSubscriberForRedo() {
ConcurrentMap<String, SubscriberRedoData> subscribes = getSubscriberRedoDataMap();
assertTrue(subscribes.isEmpty());
redoService.cacheSubscriberForRedo(SERVICE, GROUP, CLUSTER);
assertFalse(subscribes.isEmpty());
redoService.subscriberDeregister(SERVICE, GROUP, CLUSTER);
redoService.removeSubscriberForRedo(SERVICE, GROUP, CLUSTER);
assertTrue(subscribes.isEmpty());
}

View File

@ -62,7 +62,7 @@ public class RedoScheduledTaskTest {
@Test
public void testRunRedoRegisterInstance() throws NacosException {
Set<InstanceRedoData> mockData = generateMockInstanceData(false, false);
Set<InstanceRedoData> mockData = generateMockInstanceData(false, false, true);
when(redoService.findInstanceRedoData()).thenReturn(mockData);
redoTask.run();
verify(clientProxy).doRegisterService(SERVICE, GROUP, INSTANCE);
@ -70,7 +70,7 @@ public class RedoScheduledTaskTest {
@Test
public void testRunRedoDeregisterInstance() throws NacosException {
Set<InstanceRedoData> mockData = generateMockInstanceData(true, true);
Set<InstanceRedoData> mockData = generateMockInstanceData(true, true, false);
when(redoService.findInstanceRedoData()).thenReturn(mockData);
redoTask.run();
verify(clientProxy).doDeregisterService(SERVICE, GROUP, INSTANCE);
@ -78,7 +78,7 @@ public class RedoScheduledTaskTest {
@Test
public void testRunRedoRemoveInstanceRedoData() throws NacosException {
Set<InstanceRedoData> mockData = generateMockInstanceData(false, true);
Set<InstanceRedoData> mockData = generateMockInstanceData(false, true, false);
when(redoService.findInstanceRedoData()).thenReturn(mockData);
redoTask.run();
verify(redoService).removeInstanceForRedo(SERVICE, GROUP);
@ -87,16 +87,17 @@ public class RedoScheduledTaskTest {
@Test
public void testRunRedoRegisterInstanceWithClientDisabled() throws NacosException {
when(clientProxy.isEnable()).thenReturn(false);
Set<InstanceRedoData> mockData = generateMockInstanceData(false, false);
Set<InstanceRedoData> mockData = generateMockInstanceData(false, false, true);
when(redoService.findInstanceRedoData()).thenReturn(mockData);
redoTask.run();
verify(clientProxy, never()).doRegisterService(SERVICE, GROUP, INSTANCE);
}
private Set<InstanceRedoData> generateMockInstanceData(boolean registered, boolean unregistering) {
private Set<InstanceRedoData> generateMockInstanceData(boolean registered, boolean unregistering, boolean expectedRegistered) {
InstanceRedoData redoData = InstanceRedoData.build(SERVICE, GROUP, INSTANCE);
redoData.setRegistered(registered);
redoData.setUnregistering(unregistering);
redoData.setExpectedRegistered(expectedRegistered);
Set<InstanceRedoData> result = new HashSet<>();
result.add(redoData);
return result;
@ -104,7 +105,7 @@ public class RedoScheduledTaskTest {
@Test
public void testRunRedoRegisterSubscriber() throws NacosException {
Set<SubscriberRedoData> mockData = generateMockSubscriberData(false, false);
Set<SubscriberRedoData> mockData = generateMockSubscriberData(false, false, true);
when(redoService.findSubscriberRedoData()).thenReturn(mockData);
redoTask.run();
verify(clientProxy).doSubscribe(SERVICE, GROUP, CLUSTER);
@ -112,7 +113,7 @@ public class RedoScheduledTaskTest {
@Test
public void testRunRedoDeregisterSubscriber() throws NacosException {
Set<SubscriberRedoData> mockData = generateMockSubscriberData(true, true);
Set<SubscriberRedoData> mockData = generateMockSubscriberData(true, true, false);
when(redoService.findSubscriberRedoData()).thenReturn(mockData);
redoTask.run();
verify(clientProxy).doUnsubscribe(SERVICE, GROUP, CLUSTER);
@ -120,7 +121,7 @@ public class RedoScheduledTaskTest {
@Test
public void testRunRedoRemoveSubscriberRedoData() throws NacosException {
Set<SubscriberRedoData> mockData = generateMockSubscriberData(false, true);
Set<SubscriberRedoData> mockData = generateMockSubscriberData(false, true, false);
when(redoService.findSubscriberRedoData()).thenReturn(mockData);
redoTask.run();
verify(redoService).removeSubscriberForRedo(SERVICE, GROUP, CLUSTER);
@ -129,16 +130,17 @@ public class RedoScheduledTaskTest {
@Test
public void testRunRedoRegisterSubscriberWithClientDisabled() throws NacosException {
when(clientProxy.isEnable()).thenReturn(false);
Set<SubscriberRedoData> mockData = generateMockSubscriberData(false, false);
Set<SubscriberRedoData> mockData = generateMockSubscriberData(false, false, true);
when(redoService.findSubscriberRedoData()).thenReturn(mockData);
redoTask.run();
verify(clientProxy, never()).doSubscribe(SERVICE, GROUP, CLUSTER);
}
private Set<SubscriberRedoData> generateMockSubscriberData(boolean registered, boolean unregistering) {
private Set<SubscriberRedoData> generateMockSubscriberData(boolean registered, boolean unregistering, boolean expectedRegistered) {
SubscriberRedoData redoData = SubscriberRedoData.build(SERVICE, GROUP, CLUSTER);
redoData.setRegistered(registered);
redoData.setUnregistering(unregistering);
redoData.setExpectedRegistered(expectedRegistered);
Set<SubscriberRedoData> result = new HashSet<>();
result.add(redoData);
return result;

View File

@ -0,0 +1,56 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.client.naming.remote.gprc.redo.data;
import com.alibaba.nacos.api.naming.pojo.Instance;
import org.junit.Test;
import java.util.Collections;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
public class BatchInstanceRedoDataTest {
@Test
@SuppressWarnings("all")
public void testEquals() {
BatchInstanceRedoData redoData1 = new BatchInstanceRedoData("a", "b");
redoData1.setInstances(Collections.singletonList(new Instance()));
BatchInstanceRedoData redoData2 = new BatchInstanceRedoData("a", "b");
redoData2.setInstances(Collections.singletonList(new Instance()));
assertTrue(redoData1.equals(redoData1));
assertTrue(redoData1.equals(redoData2));
redoData2.getInstances().get(0).setIp("1.1.1.1");
assertFalse(redoData1.equals(null));
assertFalse(redoData1.equals(redoData2));
assertFalse(redoData1.equals(redoData2));
}
@Test
public void testHashCode() {
BatchInstanceRedoData redoData1 = new BatchInstanceRedoData("a", "b");
redoData1.setInstances(Collections.singletonList(new Instance()));
BatchInstanceRedoData redoData2 = new BatchInstanceRedoData("a", "b");
redoData2.setInstances(Collections.singletonList(new Instance()));
assertEquals(redoData1.hashCode(), redoData2.hashCode());
redoData2.getInstances().get(0).setIp("1.1.1.1");
assertNotEquals(redoData1.hashCode(), redoData2.hashCode());
}
}

View File

@ -1,18 +0,0 @@
#
# Copyright 1999-2021 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.
#
#
com.alibaba.nacos.client.remote.ClientPayloadPackageProvider

View File

@ -30,13 +30,7 @@
<packaging>jar</packaging>
<name>nacos-cmdb ${project.version}</name>
<url>http://nacos.io</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<url>https://nacos.io</url>
<dependencies>
<dependency>

View File

@ -30,11 +30,7 @@
<packaging>jar</packaging>
<name>nacos-common ${project.version}</name>
<url>http://nacos.io</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<url>https://nacos.io</url>
<dependencies>
<dependency>
@ -68,16 +64,6 @@
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>

View File

@ -63,7 +63,7 @@ public abstract class AbstractHttpClientFactory implements HttpClientFactory {
private static final String ASYNC_THREAD_NAME = "nacos-http-async-client";
private static final String AYNC_IO_REACTOR_NAME = ASYNC_THREAD_NAME + "#I/O Reactor";
private static final String ASYNC_IO_REACTOR_NAME = ASYNC_THREAD_NAME + "#I/O Reactor";
@Override
public NacosRestTemplate createNacosRestTemplate() {
@ -82,8 +82,10 @@ public abstract class AbstractHttpClientFactory implements HttpClientFactory {
@Override
public NacosAsyncRestTemplate createNacosAsyncRestTemplate() {
final HttpClientConfig originalRequestConfig = buildHttpClientConfig();
final DefaultConnectingIOReactor ioreactor = getIoReactor(AYNC_IO_REACTOR_NAME);
final DefaultConnectingIOReactor ioreactor = getIoReactor(ASYNC_IO_REACTOR_NAME);
final RequestConfig defaultConfig = getRequestConfig();
final NHttpClientConnectionManager connectionManager = getConnectionManager(originalRequestConfig, ioreactor);
monitorAndExtension(connectionManager);
return new NacosAsyncRestTemplate(assignLogger(), new DefaultAsyncHttpClientRequest(
HttpAsyncClients.custom().addInterceptorLast(new RequestContent(true))
.setThreadFactory(new NameThreadFactory(ASYNC_THREAD_NAME))
@ -91,7 +93,7 @@ public abstract class AbstractHttpClientFactory implements HttpClientFactory {
.setMaxConnTotal(originalRequestConfig.getMaxConnTotal())
.setMaxConnPerRoute(originalRequestConfig.getMaxConnPerRoute())
.setUserAgent(originalRequestConfig.getUserAgent())
.setConnectionManager(getConnectionManager(originalRequestConfig, ioreactor)).build(),
.setConnectionManager(connectionManager).build(),
ioreactor, defaultConfig));
}
@ -218,4 +220,10 @@ public abstract class AbstractHttpClientFactory implements HttpClientFactory {
* @return Logger
*/
protected abstract Logger assignLogger();
/**
* add some monitor and do some extension. default empty implementation, implemented by subclass
*/
protected void monitorAndExtension(NHttpClientConnectionManager connectionManager) {
}
}

View File

@ -0,0 +1,45 @@
/*
* Copyright 1999-2022 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.log;
import java.net.URL;
/**
* logback configurator interface,different version can adapter this.
* @author hujun
*/
public interface NacosLogbackConfigurator {
/**
* config logback.
* @param resourceUrl resourceUrl
* @throws Exception exception
*/
void configure(URL resourceUrl) throws Exception;
/**
* logback configurator will be sorted by version.
* @return version
*/
int getVersion();
/**
* set loggerContext.
* @param loggerContext loggerContext
*/
void setContext(Object loggerContext);
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
* Copyright 1999-2022 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.
@ -14,21 +14,19 @@
* limitations under the License.
*/
package com.alibaba.nacos.naming.cluster.remote.request;
import com.alibaba.nacos.api.remote.request.Request;
package com.alibaba.nacos.common.log;
/**
* Cluster request.
*
* @author xiweng.yy
* nacos logback properties.
* @author hujun
*/
public abstract class AbstractClusterRequest extends Request {
private static final String CLUSTER = "cluster";
@Override
public String getModule() {
return CLUSTER;
}
public interface NacosLogbackProperties {
/**
* get value.
*
* @param source source
* @param defaultValue defaultValue
* @return value
*/
String getValue(String source, String defaultValue);
}

View File

@ -17,16 +17,14 @@
package com.alibaba.nacos.common.remote;
import com.alibaba.nacos.api.remote.Payload;
import com.alibaba.nacos.common.packagescan.DefaultPackageScan;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.Set;
/**
* payload regitry,Define basic scan behavior request and response.
* payload registry,Define basic scan behavior request and response.
*
* @author liuzunfei
* @author hujun
@ -47,18 +45,9 @@ public class PayloadRegistry {
if (initialized) {
return;
}
ServiceLoader<PayloadPackageProvider> payloadPackages = ServiceLoader.load(PayloadPackageProvider.class);
Set<String> result = new HashSet<>();
for (PayloadPackageProvider payloadPackage : payloadPackages) {
result.addAll(payloadPackage.getScanPackage());
}
for (String pkg : result) {
DefaultPackageScan packageScan = new DefaultPackageScan();
Set<Class<Payload>> subTypesResponse = packageScan.getSubTypesOf(pkg, Payload.class);
for (Class<?> clazz : subTypesResponse) {
register(clazz.getSimpleName(), clazz);
}
ServiceLoader<Payload> payloads = ServiceLoader.load(Payload.class);
for (Payload payload : payloads) {
register(payload.getClass().getSimpleName(), payload.getClass());
}
initialized = true;
}

Some files were not shown because too many files have changed in this diff Show More