Merge pull request #9707 from alibaba/develop

Merge develop into master to release 2.2.0
This commit is contained in:
杨翊 SionYang 2022-12-14 14:14:14 +08:00 committed by GitHub
commit 38faeea58d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
671 changed files with 32653 additions and 48393 deletions

View File

@ -21,17 +21,19 @@ jobs:
java: [8]
steps:
- name: Cache Maven Repos
uses: actions/cache@v2
uses: actions/cache@v3
with:
path: ~/.m2/repository
key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
restore-keys: |
${{ runner.os }}-maven-
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: Set up JDK ${{ matrix.java }}
uses: actions/setup-java@v1
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

View File

@ -21,15 +21,15 @@ jobs:
java: [8, 8.0.192, 11, 11.0.3]
steps:
- name: Cache Maven Repos
uses: actions/cache@v2
uses: actions/cache@v3
with:
path: ~/.m2/repository
key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
restore-keys: |
${{ runner.os }}-maven-
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: Set up JDK ${{ matrix.java }}
uses: actions/setup-java@v2
uses: actions/setup-java@v3
with:
java-version: ${{ matrix.java }}
distribution: 'zulu'

View File

@ -18,8 +18,8 @@ package com.alibaba.nacos.address.component;
import com.alibaba.nacos.address.constant.AddressServerConstants;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.common.utils.InternetAddressUtil;
import com.alibaba.nacos.naming.core.Instance;
import com.alibaba.nacos.common.utils.StringUtils;
import org.springframework.stereotype.Component;
@ -76,9 +76,9 @@ public class AddressServerGeneratorManager {
instance.setPort(Integer.parseInt(ipAndPort[1]));
instance.setClusterName(clusterName);
instance.setServiceName(serviceName);
instance.setTenant(Constants.DEFAULT_NAMESPACE_ID);
instance.setApp(rawProductName);
instance.setEphemeral(false);
instance.getMetadata().put("app", rawProductName);
instance.getMetadata().put("tenant", Constants.DEFAULT_NAMESPACE_ID);
instanceList.add(instance);
}
@ -99,7 +99,7 @@ public class AddressServerGeneratorManager {
* @param instanceList a instance set will generate string response to client.
* @return the result of response to client
*/
public String generateResponseIps(List<Instance> instanceList) {
public String generateResponseIps(List<com.alibaba.nacos.api.naming.pojo.Instance> instanceList) {
StringBuilder ips = new StringBuilder();
instanceList.forEach(instance -> {

View File

@ -21,13 +21,19 @@ import com.alibaba.nacos.address.component.AddressServerManager;
import com.alibaba.nacos.address.constant.AddressServerConstants;
import com.alibaba.nacos.address.misc.Loggers;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.healthcheck.AbstractHealthChecker;
import com.alibaba.nacos.api.naming.utils.NamingUtils;
import com.alibaba.nacos.common.utils.InternetAddressUtil;
import com.alibaba.nacos.naming.core.Cluster;
import com.alibaba.nacos.naming.core.Instance;
import com.alibaba.nacos.naming.core.Service;
import com.alibaba.nacos.naming.core.ServiceManager;
import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.naming.core.ClusterOperator;
import com.alibaba.nacos.naming.core.InstanceOperator;
import com.alibaba.nacos.naming.core.v2.ServiceManager;
import com.alibaba.nacos.naming.core.v2.metadata.ClusterMetadata;
import com.alibaba.nacos.naming.core.v2.metadata.NamingMetadataManager;
import com.alibaba.nacos.naming.core.v2.metadata.ServiceMetadata;
import com.alibaba.nacos.naming.core.v2.pojo.Service;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
@ -36,6 +42,7 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Optional;
/**
* Address server cluster controller.
@ -47,15 +54,22 @@ import java.util.List;
@RequestMapping({AddressServerConstants.ADDRESS_SERVER_REQUEST_URL + "/nodes"})
public class AddressServerClusterController {
private final ServiceManager serviceManager;
private final InstanceOperator instanceOperator;
private final NamingMetadataManager metadataManager;
private final ClusterOperator clusterOperator;
private final AddressServerManager addressServerManager;
private final AddressServerGeneratorManager addressServerGeneratorManager;
public AddressServerClusterController(ServiceManager serviceManager, AddressServerManager addressServerManager,
public AddressServerClusterController(InstanceOperator instanceOperator, NamingMetadataManager metadataManager,
ClusterOperator clusterOperator, AddressServerManager addressServerManager,
AddressServerGeneratorManager addressServerGeneratorManager) {
this.serviceManager = serviceManager;
this.instanceOperator = instanceOperator;
this.metadataManager = metadataManager;
this.clusterOperator = clusterOperator;
this.addressServerManager = addressServerManager;
this.addressServerGeneratorManager = addressServerGeneratorManager;
}
@ -86,23 +100,13 @@ public class AddressServerClusterController {
try {
String serviceName = addressServerGeneratorManager.generateNacosServiceName(productName);
Cluster clusterObj = new Cluster();
clusterObj.setName(clusterName);
clusterObj.setHealthChecker(new AbstractHealthChecker.None());
serviceManager.createServiceIfAbsent(Constants.DEFAULT_NAMESPACE_ID, serviceName, false, clusterObj);
String[] ipArray = addressServerManager.splitIps(ips);
String checkResult = InternetAddressUtil.checkIPs(ipArray);
if (InternetAddressUtil.checkOK(checkResult)) {
List<Instance> instanceList = addressServerGeneratorManager
.generateInstancesByIps(serviceName, rawProductName, clusterName, ipArray);
for (Instance instance : instanceList) {
serviceManager.registerInstance(Constants.DEFAULT_NAMESPACE_ID, serviceName, instance);
}
Result result = registerCluster(serviceName, rawProductName, clusterName, ips);
if (InternetAddressUtil.checkOK(result.getCheckResult())) {
responseEntity = ResponseEntity
.ok("product=" + rawProductName + ",cluster=" + rawClusterName + "; put success with size="
+ instanceList.size());
+ result.getSize());
} else {
responseEntity = ResponseEntity.status(HttpStatus.BAD_REQUEST).body(checkResult);
responseEntity = ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result.getCheckResult());
}
} catch (Exception e) {
responseEntity = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
@ -111,6 +115,35 @@ public class AddressServerClusterController {
return responseEntity;
}
private Result registerCluster(String serviceName, String productName, String clusterName, String ips)
throws NacosException {
String serviceWithoutGroup = NamingUtils.getServiceName(serviceName);
String groupName = NamingUtils.getGroupName(serviceName);
Service service = Service.newService(Constants.DEFAULT_NAMESPACE_ID, groupName, serviceWithoutGroup, false);
service = ServiceManager.getInstance().getSingleton(service);
if (service.isEphemeral()) {
return new Result(
String.format("Service %s is ephemeral service, can't use as address server", serviceName), 0);
}
ServiceMetadata serviceMetadata = metadataManager.getServiceMetadata(service).orElse(new ServiceMetadata());
if (!serviceMetadata.getClusters().containsKey(clusterName)) {
ClusterMetadata metadata = new ClusterMetadata();
metadata.setHealthyCheckType(AbstractHealthChecker.None.TYPE);
metadata.setHealthChecker(new AbstractHealthChecker.None());
clusterOperator.updateClusterMetadata(Constants.DEFAULT_NAMESPACE_ID, serviceName, clusterName, metadata);
}
String[] ipArray = addressServerManager.splitIps(ips);
String checkResult = InternetAddressUtil.checkIPs(ipArray);
if (InternetAddressUtil.checkOK(checkResult)) {
List<Instance> instanceList = addressServerGeneratorManager
.generateInstancesByIps(serviceName, productName, clusterName, ipArray);
for (Instance instance : instanceList) {
instanceOperator.registerInstance(Constants.DEFAULT_NAMESPACE_ID, serviceName, instance);
}
}
return new Result(checkResult, ipArray.length);
}
/**
* Delete cluster.
*
@ -134,9 +167,12 @@ public class AddressServerClusterController {
try {
String serviceName = addressServerGeneratorManager.generateNacosServiceName(productName);
Service service = serviceManager.getService(Constants.DEFAULT_NAMESPACE_ID, serviceName);
String serviceWithoutGroup = NamingUtils.getServiceName(serviceName);
String groupName = NamingUtils.getGroupName(serviceName);
Optional<com.alibaba.nacos.naming.core.v2.pojo.Service> service = com.alibaba.nacos.naming.core.v2.ServiceManager
.getInstance().getSingletonIfExist(Constants.DEFAULT_NAMESPACE_ID, groupName, serviceWithoutGroup);
if (service == null) {
if (!service.isPresent()) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("product=" + rawProductName + " not found.");
}
if (StringUtils.isBlank(ips)) {
@ -149,8 +185,9 @@ public class AddressServerClusterController {
if (InternetAddressUtil.checkOK(checkResult)) {
List<Instance> instanceList = addressServerGeneratorManager
.generateInstancesByIps(serviceName, rawProductName, clusterName, ipArray);
serviceManager.removeInstance(Constants.DEFAULT_NAMESPACE_ID, serviceName, false,
instanceList.toArray(new Instance[0]));
for (Instance each : instanceList) {
instanceOperator.removeInstance(Constants.DEFAULT_NAMESPACE_ID, serviceName, each);
}
} else {
responseEntity = ResponseEntity.status(HttpStatus.BAD_REQUEST).body(checkResult);
}
@ -162,4 +199,23 @@ public class AddressServerClusterController {
return responseEntity;
}
private class Result {
private final String checkResult;
private final int size;
public Result(String checkResult, int size) {
this.checkResult = checkResult;
this.size = size;
}
public String getCheckResult() {
return checkResult;
}
public int getSize() {
return size;
}
}
}

View File

@ -18,9 +18,15 @@ package com.alibaba.nacos.address.controller;
import com.alibaba.nacos.address.component.AddressServerGeneratorManager;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.naming.core.Cluster;
import com.alibaba.nacos.naming.core.Service;
import com.alibaba.nacos.naming.core.ServiceManager;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import com.alibaba.nacos.api.naming.utils.NamingUtils;
import com.alibaba.nacos.naming.core.v2.ServiceManager;
import com.alibaba.nacos.naming.core.v2.index.ServiceStorage;
import com.alibaba.nacos.naming.core.v2.metadata.ClusterMetadata;
import com.alibaba.nacos.naming.core.v2.metadata.NamingMetadataManager;
import com.alibaba.nacos.naming.core.v2.metadata.ServiceMetadata;
import com.alibaba.nacos.naming.core.v2.pojo.Service;
import com.alibaba.nacos.naming.utils.ServiceUtil;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
@ -28,6 +34,8 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.Optional;
/**
* Server list controller.
*
@ -37,14 +45,17 @@ import org.springframework.web.bind.annotation.RestController;
@RestController
public class ServerListController {
private final ServiceManager serviceManager;
private final AddressServerGeneratorManager addressServerBuilderManager;
public ServerListController(ServiceManager serviceManager,
AddressServerGeneratorManager addressServerBuilderManager) {
this.serviceManager = serviceManager;
private final NamingMetadataManager metadataManager;
private final ServiceStorage serviceStorage;
public ServerListController(AddressServerGeneratorManager addressServerBuilderManager,
NamingMetadataManager metadataManager, ServiceStorage serviceStorage) {
this.addressServerBuilderManager = addressServerBuilderManager;
this.metadataManager = metadataManager;
this.serviceStorage = serviceStorage;
}
/**
@ -59,20 +70,22 @@ public class ServerListController {
String productName = addressServerBuilderManager.generateProductName(product);
String serviceName = addressServerBuilderManager.generateNacosServiceName(productName);
Service service = serviceManager.getService(Constants.DEFAULT_NAMESPACE_ID, serviceName);
if (service == null) {
String serviceWithoutGroup = NamingUtils.getServiceName(serviceName);
String groupName = NamingUtils.getGroupName(serviceName);
Optional<Service> service = ServiceManager.getInstance()
.getSingletonIfExist(Constants.DEFAULT_NAMESPACE_ID, groupName, serviceWithoutGroup);
if (!service.isPresent()) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("product=" + product + " not found.");
}
if (!service.getClusterMap().containsKey(cluster)) {
ClusterMetadata metadata = metadataManager.getServiceMetadata(service.get()).orElse(new ServiceMetadata())
.getClusters().get(cluster);
if (null == metadata) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body("product=" + product + ",cluster=" + cluster + " not found.");
}
Cluster clusterObj = service.getClusterMap().get(cluster);
ServiceInfo serviceInfo = serviceStorage.getData(service.get());
serviceInfo = ServiceUtil.selectInstances(serviceInfo, cluster, false);
return ResponseEntity.status(HttpStatus.OK)
.body(addressServerBuilderManager.generateResponseIps(clusterObj.allIPs(false)));
.body(addressServerBuilderManager.generateResponseIps(serviceInfo.getHosts()));
}
}

View File

@ -1,248 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.address;
import com.alibaba.nacos.common.codec.Base64;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.LinkedMultiValueMap;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT, properties = {
"spring.security.user.password=123456", "spring.security.user.name=user"})
public class AddressServerControllerTests {
private static final String PRODUCT_CONFIG = "config";
private static final String PRODUCT_NAMING = "naming";
private static final String HTTP_BASIC_INFO = getHttpBasicInfo();
@Autowired
private TestRestTemplate restTemplate;
@BeforeClass
public static void before() {
System.setProperty("nacos.standalone", "true");
System.setProperty("embeddedStorage", "true");
}
@AfterClass
public static void teardown() {
System.clearProperty("nacos.standalone");
System.clearProperty("embeddedStorage");
}
private static String getHttpBasicInfo() {
String userName = "user";
String password = "123456";
String info = userName + ":" + password;
final byte[] bytes = Base64.encodeBase64(info.getBytes(StandardCharsets.UTF_8));
return "Basic " + new String(bytes, StandardCharsets.UTF_8);
}
@Test
public void postClusterWithoutLogin() {
String ips = "127.0.0.100,127.0.0.102,127.0.0.104";
LinkedMultiValueMap<String, String> params = new LinkedMultiValueMap<>(1);
params.add("ips", ips);
final ResponseEntity<String> postClusterResponseEntity = restTemplate.exchange(
RequestEntity.post("/nacos/v1/as/nodes").body(params), String.class);
Assert.assertEquals(postClusterResponseEntity.getStatusCode(), HttpStatus.UNAUTHORIZED);
}
@Test
public void postCluster() throws InterruptedException {
String ips = "127.0.0.100,127.0.0.102,127.0.0.104";
LinkedMultiValueMap<String, String> params = new LinkedMultiValueMap<>(1);
params.add("ips", ips);
final ResponseEntity<String> postClusterResponseEntity = restTemplate.exchange(
RequestEntity.post("/nacos/v1/as/nodes").header(HttpHeaders.AUTHORIZATION, HTTP_BASIC_INFO)
.body(params), String.class);
Assert.assertNotNull(postClusterResponseEntity);
Assert.assertEquals(HttpStatus.OK.value(), postClusterResponseEntity.getStatusCodeValue());
TimeUnit.MILLISECONDS.sleep(500L);
final ResponseEntity<String> getClusterResponseEntity = restTemplate.exchange(
RequestEntity.get("/nacos/serverlist").build(), String.class);
Assert.assertNotNull(getClusterResponseEntity);
Assert.assertEquals(HttpStatus.OK.value(), getClusterResponseEntity.getStatusCodeValue());
}
@Test
public void deleteClusterWithoutLogin() {
LinkedMultiValueMap<String, String> params = new LinkedMultiValueMap<>(1);
params.add("ips", "127.0.0.104");
final ResponseEntity<String> postClusterResponseEntity = restTemplate.exchange(
RequestEntity.post("/nacos/v1/as/nodes").body(params), String.class);
Assert.assertEquals(postClusterResponseEntity.getStatusCode(), HttpStatus.UNAUTHORIZED);
}
@Test
public void deleteCluster() throws InterruptedException {
LinkedMultiValueMap<String, String> params = new LinkedMultiValueMap<>(1);
params.add("ips", "127.0.0.104");
final ResponseEntity<String> postClusterResponseEntity = restTemplate.exchange(
RequestEntity.post("/nacos/v1/as/nodes").header(HttpHeaders.AUTHORIZATION, HTTP_BASIC_INFO)
.body(params), String.class);
Assert.assertNotNull(postClusterResponseEntity);
Assert.assertEquals(HttpStatus.OK.value(), postClusterResponseEntity.getStatusCodeValue());
TimeUnit.MILLISECONDS.sleep(500L);
final ResponseEntity<String> deleteClusterResponseEntity = restTemplate.exchange(
RequestEntity.delete("/nacos/v1/as/nodes?ips={ips}", "127.0.0.104")
.header(HttpHeaders.AUTHORIZATION, HTTP_BASIC_INFO).build(), String.class);
Assert.assertNotNull(deleteClusterResponseEntity);
Assert.assertEquals(HttpStatus.OK.value(), deleteClusterResponseEntity.getStatusCodeValue());
}
@Test
public void postClusterWithProduct() throws InterruptedException {
LinkedMultiValueMap<String, String> params = new LinkedMultiValueMap<>(2);
String ips = "127.0.0.101,127.0.0.102,127.0.0.103";
params.add("ips", ips);
params.add("product", PRODUCT_CONFIG);
final ResponseEntity<String> postClusterResponseEntity = restTemplate.exchange(
RequestEntity.post("/nacos/v1/as/nodes").header(HttpHeaders.AUTHORIZATION, HTTP_BASIC_INFO)
.body(params), String.class);
Assert.assertNotNull(postClusterResponseEntity);
Assert.assertEquals(HttpStatus.OK.value(), postClusterResponseEntity.getStatusCodeValue());
TimeUnit.MILLISECONDS.sleep(500L);
final ResponseEntity<String> getClusterResponseEntity = restTemplate.exchange(
RequestEntity.get("/{product}/serverlist", PRODUCT_CONFIG).build(), String.class);
Assert.assertNotNull(getClusterResponseEntity);
Assert.assertEquals(HttpStatus.OK.value(), getClusterResponseEntity.getStatusCodeValue());
final String body = getClusterResponseEntity.getBody();
Assert.assertNotNull(body);
}
@Test
public void deleteClusterWithProduct() throws InterruptedException {
LinkedMultiValueMap<String, String> params = new LinkedMultiValueMap<>(1);
params.add("ips", "127.0.0.104");
params.add("product", PRODUCT_CONFIG);
final ResponseEntity<String> postClusterResponseEntity = restTemplate.exchange(
RequestEntity.post("/nacos/v1/as/nodes").header(HttpHeaders.AUTHORIZATION, HTTP_BASIC_INFO)
.body(params), String.class);
Assert.assertNotNull(postClusterResponseEntity);
Assert.assertEquals(HttpStatus.OK.value(), postClusterResponseEntity.getStatusCodeValue());
TimeUnit.MILLISECONDS.sleep(500L);
final ResponseEntity<String> deleteClusterResponseEntity = restTemplate.exchange(
RequestEntity.delete("/nacos/v1/as/nodes?product={product}&ips={ips}", PRODUCT_CONFIG, "127.0.0.104")
.header(HttpHeaders.AUTHORIZATION, HTTP_BASIC_INFO).build(), String.class);
Assert.assertNotNull(deleteClusterResponseEntity);
Assert.assertEquals(HttpStatus.OK.value(), deleteClusterResponseEntity.getStatusCodeValue());
}
@Test
public void postClusterWithProductAndCluster() throws InterruptedException {
LinkedMultiValueMap<String, String> params = new LinkedMultiValueMap<>(1);
String ips = "127.0.0.100,127.0.0.200,127.0.0.31";
params.add("ips", ips);
params.add("product", PRODUCT_NAMING);
params.add("cluster", "cluster01");
final ResponseEntity<String> postClusterResponseEntity = restTemplate.exchange(
RequestEntity.post("/nacos/v1/as/nodes").header(HttpHeaders.AUTHORIZATION, HTTP_BASIC_INFO)
.body(params), String.class);
Assert.assertNotNull(postClusterResponseEntity);
Assert.assertEquals(HttpStatus.OK.value(), postClusterResponseEntity.getStatusCodeValue());
TimeUnit.MILLISECONDS.sleep(500L);
final ResponseEntity<String> getClusterResponseEntity = restTemplate.exchange(
RequestEntity.get("/{product}/{cluster}", PRODUCT_NAMING, "cluster01").build(), String.class);
Assert.assertNotNull(getClusterResponseEntity);
Assert.assertEquals(HttpStatus.OK.value(), getClusterResponseEntity.getStatusCodeValue());
final String body = getClusterResponseEntity.getBody();
Assert.assertNotNull(body);
}
@Test
public void deleteClusterWithProductAndCluster() throws InterruptedException {
LinkedMultiValueMap<String, String> params = new LinkedMultiValueMap<>(1);
params.add("ips", "127.0.0.104");
params.add("product", PRODUCT_NAMING);
params.add("cluster", "cluster01");
final ResponseEntity<String> postClusterResponseEntity = restTemplate.exchange(
RequestEntity.post("/nacos/v1/as/nodes").header(HttpHeaders.AUTHORIZATION, HTTP_BASIC_INFO)
.body(params), String.class);
Assert.assertNotNull(postClusterResponseEntity);
Assert.assertEquals(HttpStatus.OK.value(), postClusterResponseEntity.getStatusCodeValue());
TimeUnit.MILLISECONDS.sleep(500L);
final ResponseEntity<String> deleteClusterResponseEntity = restTemplate.exchange(
RequestEntity.delete("/nacos/v1/as/nodes?product={product}&cluster={cluster}&ips={ips}", PRODUCT_NAMING,
"cluster01", "127.0.0.104").header(HttpHeaders.AUTHORIZATION, HTTP_BASIC_INFO).build(),
String.class);
Assert.assertNotNull(deleteClusterResponseEntity);
Assert.assertEquals(HttpStatus.OK.value(), deleteClusterResponseEntity.getStatusCodeValue());
}
}

View File

@ -17,7 +17,7 @@
package com.alibaba.nacos.address.component;
import com.alibaba.nacos.address.constant.AddressServerConstants;
import com.alibaba.nacos.naming.core.Instance;
import com.alibaba.nacos.api.naming.pojo.Instance;
import org.junit.Assert;
import org.junit.Test;
@ -67,7 +67,7 @@ public class AddressServerGeneratorManagerTest {
@Test
public void testGenerateResponseIps() {
final List<Instance> instanceList = new ArrayList<>();
final List<com.alibaba.nacos.api.naming.pojo.Instance> instanceList = new ArrayList<>();
Instance instance1 = new Instance();
instance1.setIp("192.168.3.1");
instance1.setPort(8848);

View File

@ -21,8 +21,12 @@ import com.alibaba.nacos.address.component.AddressServerManager;
import com.alibaba.nacos.address.constant.AddressServerConstants;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.naming.core.Service;
import com.alibaba.nacos.naming.core.ServiceManager;
import com.alibaba.nacos.naming.core.ClusterOperator;
import com.alibaba.nacos.naming.core.InstanceOperator;
import com.alibaba.nacos.naming.core.v2.ServiceManager;
import com.alibaba.nacos.naming.core.v2.metadata.NamingMetadataManager;
import com.alibaba.nacos.naming.core.v2.pojo.Service;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@ -40,124 +44,94 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
public class AddressServerClusterControllerTest {
@Mock
private ServiceManager serviceManager;
private InstanceOperator instanceOperator;
@Mock
private NamingMetadataManager metadataManager;
@Mock
private ClusterOperator clusterOperator;
private MockMvc mockMvc;
@Before
public void before() {
mockMvc = MockMvcBuilders.standaloneSetup(new AddressServerClusterController(serviceManager, new AddressServerManager(),
new AddressServerGeneratorManager())).build();
mockMvc = MockMvcBuilders.standaloneSetup(
new AddressServerClusterController(instanceOperator, metadataManager, clusterOperator,
new AddressServerManager(), new AddressServerGeneratorManager())).build();
Service service = Service
.newService(Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "nacos.as.default", false);
ServiceManager.getInstance().getSingleton(service);
}
@After
public void tearDown() {
Service service = Service
.newService(Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "nacos.as.default", false);
ServiceManager.getInstance().removeSingleton(service);
}
@Test
public void testPostCluster() throws Exception {
mockMvc.perform(post("/nacos/v1/as/nodes")
.param("product", "default")
.param("cluster", "serverList")
.param("ips", "192.168.3.1,192.168.3.2"))
.andExpect(status().isOk());
mockMvc.perform(post("/nacos/v1/as/nodes").param("product", "default").param("cluster", "serverList")
.param("ips", "192.168.3.1,192.168.3.2")).andExpect(status().isOk());
}
@Test
public void testPostClusterWithErrorIps() throws Exception {
mockMvc.perform(post("/nacos/v1/as/nodes")
.param("product", "default")
.param("cluster", "serverList")
.param("ips", "192.168.1"))
.andExpect(status().isBadRequest());
mockMvc.perform(post("/nacos/v1/as/nodes").param("product", "default").param("cluster", "serverList")
.param("ips", "192.168.1")).andExpect(status().isBadRequest());
}
@Test
public void testPostClusterThrowException() throws Exception {
Mockito.doThrow(new NacosException(500, "create service error")).when(serviceManager)
.createServiceIfAbsent(Mockito.eq(Constants.DEFAULT_NAMESPACE_ID), Mockito.eq(
Constants.DEFAULT_GROUP + AddressServerConstants.GROUP_SERVICE_NAME_SEP + "nacos.as.default"),
Mockito.eq(false), Mockito.any());
mockMvc.perform(post("/nacos/v1/as/nodes")
.param("product", "default")
.param("cluster", "serverList")
.param("ips", "192.168.1"))
.andExpect(status().isInternalServerError());
Mockito.doThrow(new NacosException(500, "create service error")).when(clusterOperator)
.updateClusterMetadata(Mockito.eq(Constants.DEFAULT_NAMESPACE_ID), Mockito.eq(
Constants.DEFAULT_GROUP + AddressServerConstants.GROUP_SERVICE_NAME_SEP + "nacos.as.default"),
Mockito.eq("serverList"), Mockito.any());
mockMvc.perform(post("/nacos/v1/as/nodes").param("product", "default").param("cluster", "serverList")
.param("ips", "192.168.1")).andExpect(status().isInternalServerError());
}
@Test
public void testDeleteCluster() throws Exception {
Mockito.when(serviceManager.getService(Mockito.eq(Constants.DEFAULT_NAMESPACE_ID),
Mockito.eq(Constants.DEFAULT_GROUP + AddressServerConstants.GROUP_SERVICE_NAME_SEP + "nacos.as.default")))
.thenReturn(new Service(Constants.DEFAULT_GROUP + AddressServerConstants.GROUP_SERVICE_NAME_SEP + "nacos.as.default"));
mockMvc.perform(delete("/nacos/v1/as/nodes")
.param("product", "default")
.param("cluster", "serverList")
.param("ips", "192.168.3.1,192.168.3.2")
).andExpect(status().isOk());
mockMvc.perform(delete("/nacos/v1/as/nodes").param("product", "default").param("cluster", "serverList")
.param("ips", "192.168.3.1,192.168.3.2")).andExpect(status().isOk());
}
@Test
public void testDeleteClusterCannotFindService() throws Exception {
mockMvc.perform(delete("/nacos/v1/as/nodes")
.param("product", "default")
.param("cluster", "serverList")
.param("ips", "192.168.3.1,192.168.3.2")
).andExpect(status().isNotFound());
tearDown();
mockMvc.perform(delete("/nacos/v1/as/nodes").param("product", "default").param("cluster", "serverList")
.param("ips", "192.168.3.1,192.168.3.2")).andExpect(status().isNotFound());
}
@Test
public void testDeleteClusterEmptyIps() throws Exception {
Mockito.when(serviceManager.getService(Mockito.eq(Constants.DEFAULT_NAMESPACE_ID),
Mockito.eq(Constants.DEFAULT_GROUP + AddressServerConstants.GROUP_SERVICE_NAME_SEP + "nacos.as.default")))
.thenReturn(new Service(Constants.DEFAULT_GROUP + AddressServerConstants.GROUP_SERVICE_NAME_SEP + "nacos.as.default"));
mockMvc.perform(delete("/nacos/v1/as/nodes")
.param("product", "default")
.param("cluster", "serverList")
.param("ips", "")
).andExpect(status().isBadRequest());
mockMvc.perform(delete("/nacos/v1/as/nodes").param("product", "default").param("cluster", "serverList")
.param("ips", "")).andExpect(status().isBadRequest());
}
@Test
public void testDeleteClusterErrorIps() throws Exception {
Mockito.when(serviceManager.getService(Mockito.eq(Constants.DEFAULT_NAMESPACE_ID),
Mockito.eq(Constants.DEFAULT_GROUP + AddressServerConstants.GROUP_SERVICE_NAME_SEP + "nacos.as.default")))
.thenReturn(new Service(Constants.DEFAULT_GROUP + AddressServerConstants.GROUP_SERVICE_NAME_SEP + "nacos.as.default"));
mockMvc.perform(delete("/nacos/v1/as/nodes")
.param("product", "default")
.param("cluster", "serverList")
.param("ips", "192.168.1")
).andExpect(status().isBadRequest());
mockMvc.perform(delete("/nacos/v1/as/nodes").param("product", "default").param("cluster", "serverList")
.param("ips", "192.168.1")).andExpect(status().isBadRequest());
}
@Test
public void testDeleteClusterThrowException() throws Exception {
Mockito.when(serviceManager.getService(Mockito.eq(Constants.DEFAULT_NAMESPACE_ID),
Mockito.eq(Constants.DEFAULT_GROUP + AddressServerConstants.GROUP_SERVICE_NAME_SEP + "nacos.as.default")))
.thenReturn(new Service(Constants.DEFAULT_GROUP + AddressServerConstants.GROUP_SERVICE_NAME_SEP + "nacos.as.default"));
Mockito.doThrow(new NacosException(500, "remove service error"))
.when(serviceManager)
.removeInstance(Mockito.eq(Constants.DEFAULT_NAMESPACE_ID),
Mockito.eq(Constants.DEFAULT_GROUP + AddressServerConstants.GROUP_SERVICE_NAME_SEP + "nacos.as.default"),
Mockito.eq(false),
Mockito.doThrow(new NacosException(500, "remove service error")).when(instanceOperator)
.removeInstance(Mockito.eq(Constants.DEFAULT_NAMESPACE_ID), Mockito.eq(
Constants.DEFAULT_GROUP + AddressServerConstants.GROUP_SERVICE_NAME_SEP + "nacos.as.default"),
Mockito.any());
mockMvc.perform(delete("/nacos/v1/as/nodes")
.param("product", "default")
.param("cluster", "serverList")
.param("ips", "192.168.3.1,192.168.3.2")
).andExpect(status().isInternalServerError());
mockMvc.perform(delete("/nacos/v1/as/nodes").param("product", "default").param("cluster", "serverList")
.param("ips", "192.168.3.1,192.168.3.2")).andExpect(status().isInternalServerError());
}
}

View File

@ -17,25 +17,29 @@
package com.alibaba.nacos.address.controller;
import com.alibaba.nacos.address.component.AddressServerGeneratorManager;
import com.alibaba.nacos.address.constant.AddressServerConstants;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.naming.core.Cluster;
import com.alibaba.nacos.naming.core.Instance;
import com.alibaba.nacos.naming.core.Service;
import com.alibaba.nacos.naming.core.ServiceManager;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import com.alibaba.nacos.naming.core.v2.ServiceManager;
import com.alibaba.nacos.naming.core.v2.index.ServiceStorage;
import com.alibaba.nacos.naming.core.v2.metadata.ClusterMetadata;
import com.alibaba.nacos.naming.core.v2.metadata.NamingMetadataManager;
import com.alibaba.nacos.naming.core.v2.metadata.ServiceMetadata;
import com.alibaba.nacos.naming.core.v2.pojo.Service;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ -43,68 +47,56 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
public class ServerListControllerTest {
@Mock
private ServiceManager serviceManager;
private NamingMetadataManager metadataManager;
@Mock
private ServiceStorage serviceStorage;
private Service service;
private MockMvc mockMvc;
@Before
public void before() {
this.mockMvc = MockMvcBuilders
.standaloneSetup(new ServerListController(serviceManager, new AddressServerGeneratorManager()))
.build();
this.mockMvc = MockMvcBuilders.standaloneSetup(
new ServerListController(new AddressServerGeneratorManager(), metadataManager, serviceStorage)).build();
service = Service
.newService(Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "nacos.as.default", false);
ServiceManager.getInstance().getSingleton(service);
}
@After
public void tearDown() {
ServiceManager.getInstance().removeSingleton(service);
}
@Test
public void testGetCluster() throws Exception {
final Service service = new Service(
Constants.DEFAULT_GROUP + AddressServerConstants.GROUP_SERVICE_NAME_SEP + "nacos.as.default");
Cluster cluster = new Cluster();
cluster.setName("serverList");
cluster.setService(service);
final HashMap<String, Cluster> clusterMap = new HashMap<>(1);
clusterMap.put("serverList", cluster);
service.setClusterMap(clusterMap);
final Service service = Service
.newService(Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "nacos.as.default", false);
ServiceMetadata serviceMetadata = new ServiceMetadata();
serviceMetadata.getClusters().put("serverList", new ClusterMetadata());
when(metadataManager.getServiceMetadata(service)).thenReturn(Optional.of(serviceMetadata));
List<Instance> list = new ArrayList<>(2);
list.add(new Instance("192.168.3.1", 8848));
list.add(new Instance("192.168.3.2", 8848));
cluster.updateIps(list, false);
Mockito.when(serviceManager.getService(Mockito.eq(Constants.DEFAULT_NAMESPACE_ID),
Mockito.eq(Constants.DEFAULT_GROUP + AddressServerConstants.GROUP_SERVICE_NAME_SEP + "nacos.as.default")))
.thenReturn(service);
mockMvc.perform(get("/nacos/serverList"))
.andExpect(status().isOk());
list.add(new Instance());
list.add(new Instance());
ServiceInfo serviceInfo = new ServiceInfo();
serviceInfo.setHosts(list);
when(serviceStorage.getData(service)).thenReturn(serviceInfo);
mockMvc.perform(get("/nacos/serverList")).andExpect(status().isOk());
}
@Test
public void testGetClusterCannotFindService() throws Exception {
mockMvc.perform(get("/default/serverList"))
.andExpect(status().isNotFound());
tearDown();
mockMvc.perform(get("/default/serverList")).andExpect(status().isNotFound());
}
@Test
public void testGetClusterCannotFindCluster() throws Exception {
final Service service = new Service(
Constants.DEFAULT_GROUP + AddressServerConstants.GROUP_SERVICE_NAME_SEP + "nacos.as.default");
final HashMap<String, Cluster> clusterMap = new HashMap<>(1);
service.setClusterMap(clusterMap);
Mockito.when(serviceManager.getService(Mockito.eq(Constants.DEFAULT_NAMESPACE_ID),
Mockito.eq(Constants.DEFAULT_GROUP + AddressServerConstants.GROUP_SERVICE_NAME_SEP + "nacos.as.default")))
.thenReturn(service);
mockMvc.perform(get("/nacos/serverList"))
.andExpect(status().isNotFound());
mockMvc.perform(get("/nacos/serverList")).andExpect(status().isNotFound());
}
}

View File

@ -77,8 +77,6 @@ public class PropertyKeyConst {
public static final String NAMING_ASYNC_QUERY_SUBSCRIBE_SERVICE = "namingAsyncQuerySubscribeService";
public static final String PUSH_RECEIVER_UDP_PORT = "push.receiver.udp.port";
/**
* Get the key value of some variable value from the system property.
*/

View File

@ -27,8 +27,6 @@ public interface SystemPropertyKeyConst {
String NAMING_SERVER_PORT = "nacos.naming.exposed.port";
String NAMING_WEB_CONTEXT = "nacos.naming.web.context";
/**
* In the cloud (Alibaba Cloud or other cloud vendors) environment, whether to enable namespace resolution in the
* cloud environment.

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,29 +14,23 @@
* limitations under the License.
*/
package com.alibaba.nacos.api.config.filter;
package com.alibaba.nacos.api.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Filter Config Interface.
*
* @author Nacos
* An annotation for Nacos API v2 Controller.
* @author dongyafei
* @date 2022/7/22
*/
@Deprecated
public interface IFilterConfig {
/**
* get filter name.
*
* @return filter name
*/
String getFilterName();
/**
* Get init param.
*
* @param name parameter name
* @return param
*/
Object getInitParameter(String name);
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface NacosApi {
}

View File

@ -249,8 +249,12 @@ public class Constants {
*/
public static class Exception {
public static final int DESERIALIZE_ERROR_CODE = 101;
public static final int SERIALIZE_ERROR_CODE = 100;
public static final int DESERIALIZE_ERROR_CODE = 101;
public static final int FIND_DATASOURCE_ERROR_CODE = 102;
public static final int FIND_TABLE_ERROR_CODE = 103;
}
}

View File

@ -62,13 +62,6 @@ public @interface NacosConfigurationProperties {
*/
String dataId();
/**
* set config type is yaml this method is deprecated, we support you use {@link #type()} to set config type.
*
* @return default value <code>false</code>
*/
@Deprecated boolean yaml() default false;
/**
* config style.
*

View File

@ -22,13 +22,5 @@ package com.alibaba.nacos.api.config.filter;
* @author luyanbo(RobberPhex)
*/
public abstract class AbstractConfigFilter implements IConfigFilter {
/**
* init.
*
* @param filterConfig Filter Config
*/
@Override
public void init(IFilterConfig filterConfig) {
}
}

View File

@ -30,14 +30,6 @@ import java.util.Properties;
*/
public interface IConfigFilter {
/**
* Init.
*
* @param filterConfig Filter Config
*/
@Deprecated
void init(IFilterConfig filterConfig);
/**
* Init.
*

View File

@ -0,0 +1,78 @@
/*
* 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.api.exception.api;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.model.v2.ErrorCode;
import com.alibaba.nacos.api.utils.StringUtils;
/** Exception for open API. <BR/>
* errCode -> HTTP status code inherited from {@link NacosException} <BR/>
* errMsg -> detail error message inherited from {@link NacosException} <BR/>
* detailErrCode -> error code for api v2.0 <BR/>
* errAbstract -> abstract error message for api v2.0
* @author dongyafei
* @date 2022/7/22
*/
public class NacosApiException extends NacosException {
/**
* serialVersionUID.
*/
private static final long serialVersionUID = 2245627968556056573L;
/**
* error code for api v2.0.
*/
private int detailErrCode;
/**
* abstract error description for api v2.0.
*/
private String errAbstract;
public NacosApiException() {
}
public NacosApiException(int statusCode, ErrorCode errorCode, Throwable throwable, String message) {
super(statusCode, message, throwable);
this.detailErrCode = errorCode.getCode();
this.errAbstract = errorCode.getMsg();
}
public NacosApiException(int statusCode, ErrorCode errorCode, String message) {
super(statusCode, message);
this.detailErrCode = errorCode.getCode();
this.errAbstract = errorCode.getMsg();
}
public int getDetailErrCode() {
return detailErrCode;
}
public String getErrAbstract() {
if (!StringUtils.isBlank(this.errAbstract)) {
return this.errAbstract;
}
return Constants.NULL;
}
public void setErrAbstract(String errAbstract) {
this.errAbstract = errAbstract;
}
}

View File

@ -0,0 +1,204 @@
/*
* 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.api.model.v2;
/**
* Response Error Code.
*
* @author dongyafei
* @date 2022/7/22
*/
public enum ErrorCode {
/**
* success.
*/
SUCCESS(0, "success"),
/**
* parameter missing.
*/
PARAMETER_MISSING(10000, "parameter missing"),
/**
* access denied.
*/
ACCESS_DENIED(10001, "access denied"),
/**
* data access error.
*/
DATA_ACCESS_ERROR(10002, "data access error"),
/**
* 'tenant' parameter error.
*/
TENANT_PARAM_ERROR(20001, "'tenant' parameter error"),
/**
* parameter validate error.
*/
PARAMETER_VALIDATE_ERROR(20002, "parameter validate error"),
/**
* MediaType Error.
*/
MEDIA_TYPE_ERROR(20003, "MediaType Error"),
/**
* resource not found.
*/
RESOURCE_NOT_FOUND(20004, "resource not found"),
/**
* resource conflict.
*/
RESOURCE_CONFLICT(20005, "resource conflict"),
/**
* config listener is null.
*/
CONFIG_LISTENER_IS_NULL(20006, "config listener is null"),
/**
* config listener error.
*/
CONFIG_LISTENER_ERROR(20007, "config listener error"),
/**
* invalid dataId.
*/
INVALID_DATA_ID(20008, "invalid dataId"),
/**
* parameter mismatch.
*/
PARAMETER_MISMATCH(20009, "parameter mismatch"),
/**
* service name error.
*/
SERVICE_NAME_ERROR(21000, "service name error"),
/**
* weight error.
*/
WEIGHT_ERROR(21001, "weight error"),
/**
* instance metadata error.
*/
INSTANCE_METADATA_ERROR(21002, "instance metadata error"),
/**
* instance not found.
*/
INSTANCE_NOT_FOUND(21003, "instance not found"),
/**
* instance error.
*/
INSTANCE_ERROR(21004, "instance error"),
/**
* service metadata error.
*/
SERVICE_METADATA_ERROR(21005, "service metadata error"),
/**
* selector error.
*/
SELECTOR_ERROR(21006, "selector error"),
/**
* service already exist.
*/
SERVICE_ALREADY_EXIST(21007, "service already exist"),
/**
* service not exist.
*/
SERVICE_NOT_EXIST(21008, "service not exist"),
/**
* service delete failure.
*/
SERVICE_DELETE_FAILURE(21009, "service delete failure"),
/**
* healthy param miss.
*/
HEALTHY_PARAM_MISS(21010, "healthy param miss"),
/**
* health check still running.
*/
HEALTH_CHECK_STILL_RUNNING(21011, "health check still running"),
/**
* illegal namespace.
*/
ILLEGAL_NAMESPACE(22000, "illegal namespace"),
/**
* namespace not exist.
*/
NAMESPACE_NOT_EXIST(22001, "namespace not exist"),
/**
* namespace already exist.
*/
NAMESPACE_ALREADY_EXIST(22002, "namespace already exist"),
/**
* illegal state.
*/
ILLEGAL_STATE(23000, "illegal state"),
/**
* node info error.
*/
NODE_INFO_ERROR(23001, "node info error"),
/**
* node down failure.
*/
NODE_DOWN_FAILURE(23001, "node down failure"),
/**
* server error.
*/
SERVER_ERROR(30000, "server error");
private final Integer code;
private final String msg;
public Integer getCode() {
return code;
}
public String getMsg() {
return msg;
}
ErrorCode(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
}

View File

@ -0,0 +1,115 @@
/*
* 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.api.model.v2;
import java.io.Serializable;
/**
* Response Result.
*
* @author dongyafei
* @date 2022/7/12
*/
public class Result<T> implements Serializable {
private static final long serialVersionUID = 6258345442767540526L;
private final Integer code;
private final String message;
private final T data;
public Result(Integer code, String message, T data) {
this.code = code;
this.message = message;
this.data = data;
}
public Result() {
this(null);
}
public Result(T data) {
this(ErrorCode.SUCCESS.getCode(), ErrorCode.SUCCESS.getMsg(), data);
}
public Result(Integer code, String message) {
this(code, message, null);
}
/**
* Success return with nothing.
* @param <T> data type
* @return Result
*/
public static <T> Result<T> success() {
return new Result<>();
}
/**
* Success return with data.
* @param <T> data type
* @return Result
*/
public static <T> Result<T> success(T data) {
return new Result<>(data);
}
/**
* Failed return with message and detail error information.
* @return Result
*/
public static Result<String> failure(String message) {
return Result.failure(ErrorCode.SERVER_ERROR, message);
}
/**
* Failed return with errorCode and message.
* @param <T> data type
* @return Result
*/
public static <T> Result<T> failure(ErrorCode errorCode) {
return new Result<>(errorCode.getCode(), errorCode.getMsg());
}
/**
* Failed return with errorCode, message and data.
* @param <T> data type
* @return Result
*/
public static <T> Result<T> failure(ErrorCode errorCode, T data) {
return new Result<>(errorCode.getCode(), errorCode.getMsg(), data);
}
@Override
public String toString() {
return "Result{" + "errorCode=" + code + ", message='" + message + '\'' + ", data=" + data + '}';
}
public Integer getCode() {
return code;
}
public String getMessage() {
return message;
}
public T getData() {
return data;
}
}

View File

@ -107,6 +107,17 @@ public interface NamingService {
*/
void batchRegisterInstance(String serviceName, String groupName, List<Instance> instances) throws NacosException;
/**
* batch deRegister instance to service with specified instance properties.
*
* @param serviceName name of service
* @param groupName group of service
* @param instances instances to deRegister
* @throws NacosException nacos exception
* @since 2.2.0
*/
void batchDeregisterInstance(String serviceName, String groupName, List<Instance> instances) throws NacosException;
/**
* deregister instance from a service.
*

View File

@ -18,6 +18,8 @@ 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.exception.api.NacosApiException;
import com.alibaba.nacos.api.model.v2.ErrorCode;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.utils.StringUtils;
@ -138,11 +140,11 @@ public class NamingUtils {
public static void checkInstanceIsLegal(Instance instance) throws NacosException {
if (instance.getInstanceHeartBeatTimeOut() < instance.getInstanceHeartBeatInterval()
|| instance.getIpDeleteTimeout() < instance.getInstanceHeartBeatInterval()) {
throw new NacosException(NacosException.INVALID_PARAM,
throw new NacosApiException(NacosException.INVALID_PARAM, ErrorCode.INSTANCE_ERROR,
"Instance 'heart beat interval' must less than 'heart beat timeout' and 'ip delete timeout'.");
}
if (!StringUtils.isEmpty(instance.getClusterName()) && !CLUSTER_NAME_PATTERN.matcher(instance.getClusterName()).matches()) {
throw new NacosException(NacosException.INVALID_PARAM,
throw new NacosApiException(NacosException.INVALID_PARAM, ErrorCode.INSTANCE_ERROR,
String.format("Instance 'clusterName' should be characters with only 0-9a-zA-Z-. (current: %s)",
instance.getClusterName()));
}
@ -155,7 +157,7 @@ public class NamingUtils {
*/
public static void checkInstanceIsEphemeral(Instance instance) throws NacosException {
if (!instance.isEphemeral()) {
throw new NacosException(NacosException.INVALID_PARAM,
throw new NacosApiException(NacosException.INVALID_PARAM, ErrorCode.INSTANCE_ERROR,
String.format("Batch registration does not allow persistent instance registration , Instance%s", instance));
}
}

View File

@ -17,6 +17,8 @@
package com.alibaba.nacos.api.remote;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;
/**
* rpc scheduler executor .
@ -33,7 +35,16 @@ public class RpcScheduledExecutor extends ScheduledThreadPoolExecutor {
"com.alibaba.nacos.remote.ServerCommonScheduler");
public RpcScheduledExecutor(int corePoolSize, final String threadName) {
super(corePoolSize, r -> new Thread(r, threadName));
super(corePoolSize, new ThreadFactory() {
private AtomicLong index = new AtomicLong();
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r, threadName + "." + index.getAndIncrement());
thread.setDaemon(true);
return thread;
}
});
}
}

View File

@ -30,14 +30,11 @@ import java.util.Enumeration;
* @author xuanyin.zy
*/
public class NetUtils {
@Deprecated
private static final String CLIENT_NAMING_LOCAL_IP_PROPERTY = "com.alibaba.nacos.client.naming.local.ip";
private static final String CLIENT_LOCAL_IP_PROPERTY = "com.alibaba.nacos.client.local.ip";
private static final String CLIENT_LOCAL_PREFER_HOSTNAME_PROPERTY = "com.alibaba.nacos.client.local.preferHostname";
private static final String LEGAL_LOCAL_IP_PROPERTY = "java.net.preferIPv6Addresses";
private static final String DEFAULT_SOLVE_FAILED_RETURN = "resolve_failed";
@ -53,23 +50,19 @@ public class NetUtils {
if (!StringUtils.isEmpty(localIp)) {
return localIp;
}
if (System.getProperties().containsKey(CLIENT_LOCAL_IP_PROPERTY)) {
return localIp = System.getProperty(CLIENT_LOCAL_IP_PROPERTY, getAddress());
}
String ip = System.getProperty(CLIENT_NAMING_LOCAL_IP_PROPERTY, getAddress());
return localIp = ip;
localIp = getAddress();
return localIp;
}
private static String getAddress() {
InetAddress inetAddress = findFirstNonLoopbackAddress();
if (inetAddress == null) {
return DEFAULT_SOLVE_FAILED_RETURN;
}
boolean preferHost = Boolean.parseBoolean(System.getProperty(CLIENT_LOCAL_PREFER_HOSTNAME_PROPERTY));
return preferHost ? inetAddress.getHostName() : inetAddress.getHostAddress();
}
@ -91,9 +84,8 @@ public class NetUtils {
for (Enumeration<InetAddress> addrs = ifc.getInetAddresses(); addrs.hasMoreElements(); ) {
InetAddress address = addrs.nextElement();
boolean isLegalIpVersion =
Boolean.parseBoolean(System.getProperty(LEGAL_LOCAL_IP_PROPERTY))
? address instanceof Inet6Address : address instanceof Inet4Address;
boolean isLegalIpVersion = Boolean.parseBoolean(System.getProperty(LEGAL_LOCAL_IP_PROPERTY))
? address instanceof Inet6Address : address instanceof Inet4Address;
if (isLegalIpVersion && !address.isLoopbackAddress()) {
result = address;
}

View File

@ -54,7 +54,7 @@ public class NamingUtilsTest {
NamingUtils.checkInstanceIsLegal(instance);
assertTrue(false);
} catch (Exception e) {
assertTrue(NacosException.class.equals(e.getClass()));
assertTrue(e instanceof NacosException);
assertEquals(
"Instance 'clusterName' should be characters with only 0-9a-zA-Z-. (current: cluster1,cluster2)",
e.getMessage());
@ -75,7 +75,7 @@ public class NamingUtilsTest {
NamingUtils.checkInstanceIsLegal(instance);
assertTrue(false);
} catch (Exception e) {
assertTrue(NacosException.class.equals(e.getClass()));
assertTrue(e instanceof NacosException);
assertEquals(
"Instance 'heart beat interval' must less than 'heart beat timeout' and 'ip delete timeout'.",
e.getMessage());
@ -98,7 +98,7 @@ public class NamingUtilsTest {
NamingUtils.batchCheckInstanceIsLegal(instanceList);
assertTrue(false);
} catch (Exception e) {
assertTrue(NacosException.class.equals(e.getClass()));
assertTrue(e instanceof NacosException);
assertEquals(
"Instance 'clusterName' should be characters with only 0-9a-zA-Z-. (current: cluster1,cluster2)",
e.getMessage());
@ -124,7 +124,7 @@ public class NamingUtilsTest {
NamingUtils.batchCheckInstanceIsLegal(instanceList);
assertTrue(false);
} catch (Exception e) {
assertTrue(NacosException.class.equals(e.getClass()));
assertTrue(e instanceof NacosException);
assertEquals(
"Instance 'heart beat interval' must less than 'heart beat timeout' and 'ip delete timeout'.",
e.getMessage());
@ -166,4 +166,4 @@ public class NamingUtilsTest {
String str2 = "123456";
assertTrue(NamingUtils.isNumber(str2));
}
}
}

View File

@ -34,7 +34,6 @@ public class NetUtilsTest {
field.setAccessible(true);
field.set(null, "");
System.clearProperty("com.alibaba.nacos.client.local.ip");
System.clearProperty("com.alibaba.nacos.client.naming.local.ip");
System.clearProperty("com.alibaba.nacos.client.local.preferHostname");
}
@ -45,12 +44,6 @@ public class NetUtilsTest {
assertEquals("10.2.8.8", NetUtils.localIP());
}
@Test
public void testCompatibleLocalIP() {
System.setProperty("com.alibaba.nacos.client.naming.local.ip", "10.2.7.8");
assertEquals("10.2.7.8", NetUtils.localIP());
}
@Test
public void testPreferHostname() throws Exception {
Class<?> clazz = Class.forName("com.alibaba.nacos.api.utils.NetUtils");
@ -63,4 +56,4 @@ public class NetUtilsTest {
assertEquals(hostname, NetUtils.localIP());
}
}
}

View File

@ -33,7 +33,7 @@ import java.util.HashMap;
import java.util.Map;
/**
* Auth Service for Http protocol.
* Auth Service for Grpc protocol.
*
* @author xiweng.yy
*/

View File

@ -16,6 +16,7 @@
package com.alibaba.nacos.client.auth.ram.identify;
import com.alibaba.nacos.client.env.NacosClientProperties;
import com.alibaba.nacos.client.utils.LogUtils;
import com.alibaba.nacos.common.utils.StringUtils;
import org.slf4j.Logger;
@ -43,7 +44,7 @@ public final class CredentialService implements SpasCredentialLoader {
private CredentialService(String appName) {
if (appName == null) {
String value = System.getProperty(IdentifyConstants.PROJECT_NAME_PROPERTY);
String value = NacosClientProperties.PROTOTYPE.getProperty(IdentifyConstants.PROJECT_NAME_PROPERTY);
if (StringUtils.isNotEmpty(value)) {
appName = value;
}
@ -126,25 +127,4 @@ public final class CredentialService implements SpasCredentialLoader {
public void registerCredentialListener(CredentialListener listener) {
this.listener = listener;
}
@Deprecated
public void setAccessKey(String accessKey) {
credentials.setAccessKey(accessKey);
}
@Deprecated
public void setSecretKey(String secretKey) {
credentials.setSecretKey(secretKey);
}
@Deprecated
public String getAccessKey() {
return credentials.getAccessKey();
}
@Deprecated
public String getSecretKey() {
return credentials.getSecretKey();
}
}

View File

@ -16,6 +16,7 @@
package com.alibaba.nacos.client.auth.ram.identify;
import com.alibaba.nacos.client.env.NacosClientProperties;
import com.alibaba.nacos.client.utils.LogUtils;
import com.alibaba.nacos.common.executor.ExecutorFactory;
import com.alibaba.nacos.common.executor.NameThreadFactory;
@ -113,7 +114,7 @@ public class CredentialWatcher {
}
if (propertyPath == null || propertyPath.isEmpty()) {
String value = System.getProperty("spas.identity");
String value = NacosClientProperties.PROTOTYPE.getProperty("spas.identity");
if (StringUtils.isNotEmpty(value)) {
propertyPath = value;
}
@ -157,8 +158,8 @@ public class CredentialWatcher {
String tenantId = null;
if (propertiesIS == null) {
propertyPath = null;
accessKey = System.getenv(IdentifyConstants.ENV_ACCESS_KEY);
secretKey = System.getenv(IdentifyConstants.ENV_SECRET_KEY);
accessKey = NacosClientProperties.PROTOTYPE.getProperty(IdentifyConstants.ENV_ACCESS_KEY);
secretKey = NacosClientProperties.PROTOTYPE.getProperty(IdentifyConstants.ENV_SECRET_KEY);
if (accessKey == null && secretKey == null) {
if (init) {
SPAS_LOGGER.info("{} No credential found", appName);

View File

@ -16,6 +16,7 @@
package com.alibaba.nacos.client.auth.ram.identify;
import com.alibaba.nacos.client.env.NacosClientProperties;
import com.alibaba.nacos.common.utils.StringUtils;
/**
@ -56,27 +57,27 @@ public class StsConfig {
}
private StsConfig() {
String ramRoleName = System.getProperty(IdentifyConstants.RAM_ROLE_NAME_PROPERTY);
String ramRoleName = NacosClientProperties.PROTOTYPE.getProperty(IdentifyConstants.RAM_ROLE_NAME_PROPERTY);
if (!StringUtils.isBlank(ramRoleName)) {
setRamRoleName(ramRoleName);
}
String timeToRefreshInMillisecond = System.getProperty(IdentifyConstants.REFRESH_TIME_PROPERTY);
String timeToRefreshInMillisecond = NacosClientProperties.PROTOTYPE.getProperty(IdentifyConstants.REFRESH_TIME_PROPERTY);
if (!StringUtils.isBlank(timeToRefreshInMillisecond)) {
setTimeToRefreshInMillisecond(Integer.parseInt(timeToRefreshInMillisecond));
}
String securityCredentials = System.getProperty(IdentifyConstants.SECURITY_PROPERTY);
String securityCredentials = NacosClientProperties.PROTOTYPE.getProperty(IdentifyConstants.SECURITY_PROPERTY);
if (!StringUtils.isBlank(securityCredentials)) {
setSecurityCredentials(securityCredentials);
}
String securityCredentialsUrl = System.getProperty(IdentifyConstants.SECURITY_URL_PROPERTY);
String securityCredentialsUrl = NacosClientProperties.PROTOTYPE.getProperty(IdentifyConstants.SECURITY_URL_PROPERTY);
if (!StringUtils.isBlank(securityCredentialsUrl)) {
setSecurityCredentialsUrl(securityCredentialsUrl);
}
String cacheSecurityCredentials = System.getProperty(IdentifyConstants.SECURITY_CACHE_PROPERTY);
String cacheSecurityCredentials = NacosClientProperties.PROTOTYPE.getProperty(IdentifyConstants.SECURITY_CACHE_PROPERTY);
if (!StringUtils.isBlank(cacheSecurityCredentials)) {
setCacheSecurityCredentials(Boolean.parseBoolean(cacheSecurityCredentials));
}

View File

@ -32,6 +32,7 @@ import com.alibaba.nacos.client.config.impl.LocalEncryptedDataKeyProcessor;
import com.alibaba.nacos.client.config.impl.ServerListManager;
import com.alibaba.nacos.client.config.utils.ContentUtils;
import com.alibaba.nacos.client.config.utils.ParamUtils;
import com.alibaba.nacos.client.env.NacosClientProperties;
import com.alibaba.nacos.client.utils.LogUtils;
import com.alibaba.nacos.client.utils.ParamUtil;
import com.alibaba.nacos.client.utils.ValidatorUtils;
@ -71,22 +72,23 @@ public class NacosConfigService implements ConfigService {
private final ConfigFilterChainManager configFilterChainManager;
public NacosConfigService(Properties properties) throws NacosException {
ValidatorUtils.checkInitParam(properties);
final NacosClientProperties clientProperties = NacosClientProperties.PROTOTYPE.derive(properties);
ValidatorUtils.checkInitParam(clientProperties);
initNamespace(properties);
this.configFilterChainManager = new ConfigFilterChainManager(properties);
ServerListManager serverListManager = new ServerListManager(properties);
initNamespace(clientProperties);
this.configFilterChainManager = new ConfigFilterChainManager(clientProperties.asProperties());
ServerListManager serverListManager = new ServerListManager(clientProperties);
serverListManager.start();
this.worker = new ClientWorker(this.configFilterChainManager, serverListManager, properties);
this.worker = new ClientWorker(this.configFilterChainManager, serverListManager, clientProperties);
// will be deleted in 2.0 later versions
agent = new ServerHttpAgent(serverListManager);
}
private void initNamespace(Properties properties) {
private void initNamespace(NacosClientProperties properties) {
namespace = ParamUtil.parseNamespace(properties);
properties.put(PropertyKeyConst.NAMESPACE, namespace);
properties.setProperty(PropertyKeyConst.NAMESPACE, namespace);
}
@Override

View File

@ -19,6 +19,7 @@ package com.alibaba.nacos.client.config.http;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.client.config.impl.ConfigHttpClientManager;
import com.alibaba.nacos.client.config.impl.ServerListManager;
import com.alibaba.nacos.client.env.NacosClientProperties;
import com.alibaba.nacos.client.utils.ContextPathUtil;
import com.alibaba.nacos.client.utils.LogUtils;
import com.alibaba.nacos.client.utils.ParamUtil;
@ -242,7 +243,7 @@ public class ServerHttpAgent implements HttpAgent {
}
public ServerHttpAgent(Properties properties) throws NacosException {
this.serverListMgr = new ServerListManager(properties);
this.serverListMgr = new ServerListManager(NacosClientProperties.PROTOTYPE.derive(properties));
}
@Override

View File

@ -25,6 +25,7 @@ import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.client.config.filter.impl.ConfigFilterChainManager;
import com.alibaba.nacos.client.config.filter.impl.ConfigResponse;
import com.alibaba.nacos.client.config.listener.impl.AbstractConfigChangeListener;
import com.alibaba.nacos.client.env.NacosClientProperties;
import com.alibaba.nacos.client.utils.LogUtils;
import com.alibaba.nacos.client.utils.TenantUtil;
import com.alibaba.nacos.common.utils.MD5Utils;
@ -62,7 +63,7 @@ public class CacheData {
static boolean initSnapshot;
static {
initSnapshot = Boolean.valueOf(System.getProperty("nacos.cache.data.init.snapshot", "true"));
initSnapshot = NacosClientProperties.PROTOTYPE.getBoolean("nacos.cache.data.init.snapshot", true);
LOGGER.info("nacos.cache.data.init.snapshot = {} ", initSnapshot);
}

View File

@ -37,6 +37,7 @@ import com.alibaba.nacos.api.exception.NacosException;
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.plugin.auth.api.RequestResource;
import com.alibaba.nacos.client.config.common.GroupKey;
import com.alibaba.nacos.client.config.filter.impl.ConfigFilterChainManager;
@ -75,7 +76,6 @@ import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
@ -410,7 +410,7 @@ public class ClientWorker implements Closeable {
@SuppressWarnings("PMD.ThreadPoolCreationRule")
public ClientWorker(final ConfigFilterChainManager configFilterChainManager, ServerListManager serverListManager,
final Properties properties) throws NacosException {
final NacosClientProperties properties) throws NacosException {
this.configFilterChainManager = configFilterChainManager;
init(properties);
@ -429,9 +429,10 @@ public class ClientWorker implements Closeable {
}
private void refreshContentAndCheck(String groupKey, boolean notify) {
private void refreshContentAndCheck(String groupKey) {
CacheData cache = cacheMap.get().get(groupKey);
if (cache != null) {
boolean notify = !cache.isInitializing();
refreshContentAndCheck(cache, notify);
}
}
@ -457,7 +458,7 @@ public class ClientWorker implements Closeable {
}
}
private void init(Properties properties) {
private void init(NacosClientProperties properties) {
timeout = Math.max(ConvertUtils.toInt(properties.getProperty(PropertyKeyConst.CONFIG_LONG_POLL_TIMEOUT),
Constants.CONFIG_LONG_POLL_TIMEOUT), Constants.MIN_CONFIG_LONG_POLL_TIMEOUT);
@ -540,7 +541,7 @@ public class ClientWorker implements Closeable {
*/
private static final long ALL_SYNC_INTERNAL = 5 * 60 * 1000L;
public ConfigRpcTransportClient(Properties properties, ServerListManager serverListManager) {
public ConfigRpcTransportClient(NacosClientProperties properties, ServerListManager serverListManager) {
super(properties, serverListManager);
}
@ -796,8 +797,7 @@ public class ClientWorker implements Closeable {
.getKeyTenant(changeConfig.getDataId(), changeConfig.getGroup(),
changeConfig.getTenant());
changeKeys.add(changeKey);
boolean isInitializing = cacheMap.get().get(changeKey).isInitializing();
refreshContentAndCheck(changeKey, !isInitializing);
refreshContentAndCheck(changeKey);
}
}

View File

@ -19,6 +19,7 @@ package com.alibaba.nacos.client.config.impl;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.client.env.NacosClientProperties;
import com.alibaba.nacos.plugin.auth.api.RequestResource;
import com.alibaba.nacos.client.config.filter.impl.ConfigResponse;
import com.alibaba.nacos.client.security.SecurityProxy;
@ -66,7 +67,7 @@ public abstract class ConfigTransportClient {
securityProxy.shutdown();
}
public ConfigTransportClient(Properties properties, ServerListManager serverListManager) {
public ConfigTransportClient(NacosClientProperties properties, ServerListManager serverListManager) {
String encodeTmp = properties.getProperty(PropertyKeyConst.ENCODE);
if (StringUtils.isBlank(encodeTmp)) {
@ -77,7 +78,7 @@ public abstract class ConfigTransportClient {
this.tenant = properties.getProperty(PropertyKeyConst.NAMESPACE);
this.serverListManager = serverListManager;
this.properties = properties;
this.properties = properties.asProperties();
this.securityProxy = new SecurityProxy(serverListManager.getServerUrls(),
ConfigHttpClientManager.getInstance().getNacosRestTemplate());
}

View File

@ -16,6 +16,7 @@
package com.alibaba.nacos.client.config.impl;
import com.alibaba.nacos.client.env.NacosClientProperties;
import com.alibaba.nacos.client.utils.LogUtils;
import com.alibaba.nacos.common.cache.Cache;
import com.alibaba.nacos.common.cache.builder.CacheBuilder;
@ -56,7 +57,7 @@ public class Limiter {
static {
try {
String limitTimeStr = System.getProperty(LIMIT_TIME_PROPERTY, String.valueOf(limit));
String limitTimeStr = NacosClientProperties.PROTOTYPE.getProperty(LIMIT_TIME_PROPERTY, String.valueOf(limit));
limit = Double.parseDouble(limitTimeStr);
LOGGER.info("limitTime:{}", limit);
} catch (Exception e) {

View File

@ -20,6 +20,7 @@ import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.client.config.utils.ConcurrentDiskUtil;
import com.alibaba.nacos.client.config.utils.JvmUtil;
import com.alibaba.nacos.client.config.utils.SnapShotSwitch;
import com.alibaba.nacos.client.env.NacosClientProperties;
import com.alibaba.nacos.client.utils.LogUtils;
import com.alibaba.nacos.common.utils.IoUtils;
import com.alibaba.nacos.common.utils.StringUtils;
@ -58,12 +59,12 @@ public class LocalConfigInfoProcessor {
private static final String SNAPSHOT_FILE_CHILD_2 = "snapshot-tenant";
static {
LOCAL_FILEROOT_PATH =
System.getProperty("JM.LOG.PATH", System.getProperty("user.home")) + File.separator + "nacos"
+ File.separator + "config";
LOCAL_SNAPSHOT_PATH =
System.getProperty("JM.SNAPSHOT.PATH", System.getProperty("user.home")) + File.separator + "nacos"
+ File.separator + "config";
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";
LOGGER.info("LOCAL_SNAPSHOT_PATH:{}", LOCAL_SNAPSHOT_PATH);
}

View File

@ -19,6 +19,7 @@ package com.alibaba.nacos.client.config.impl;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.SystemPropertyKeyConst;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.client.env.NacosClientProperties;
import com.alibaba.nacos.client.utils.ContextPathUtil;
import com.alibaba.nacos.client.utils.EnvUtil;
import com.alibaba.nacos.client.utils.LogUtils;
@ -165,7 +166,8 @@ public class ServerListManager implements Closeable {
this.isStarted = false;
Properties properties = new Properties();
properties.setProperty(PropertyKeyConst.ENDPOINT, endpoint);
this.endpoint = initEndpoint(properties);
final NacosClientProperties clientProperties = NacosClientProperties.PROTOTYPE.derive(properties);
this.endpoint = initEndpoint(clientProperties);
if (StringUtils.isBlank(endpoint)) {
throw new NacosException(NacosException.CLIENT_INVALID_PARAM, "endpoint is blank");
@ -176,10 +178,10 @@ public class ServerListManager implements Closeable {
}
this.name = initServerName(null);
initAddressServerUrl(properties);
initAddressServerUrl(clientProperties);
}
public ServerListManager(Properties properties) throws NacosException {
public ServerListManager(NacosClientProperties properties) throws NacosException {
this.isStarted = false;
this.serverAddrsStr = properties.getProperty(PropertyKeyConst.SERVER_ADDR);
String namespace = properties.getProperty(PropertyKeyConst.NAMESPACE);
@ -222,11 +224,11 @@ public class ServerListManager implements Closeable {
}
private String initServerName(Properties properties) {
private String initServerName(NacosClientProperties properties) {
String serverName;
//1.user define server name.
if (properties != null && properties.containsKey(PropertyKeyConst.SERVER_NAME)) {
serverName = properties.get(PropertyKeyConst.SERVER_NAME).toString();
serverName = properties.getProperty(PropertyKeyConst.SERVER_NAME);
} else {
// if fix url,use fix url join string.
if (isFixed) {
@ -245,7 +247,7 @@ public class ServerListManager implements Closeable {
return serverName;
}
private void initAddressServerUrl(Properties properties) {
private void initAddressServerUrl(NacosClientProperties properties) {
if (isFixed) {
return;
}
@ -259,7 +261,7 @@ public class ServerListManager implements Closeable {
}
if (properties != null && properties.containsKey(PropertyKeyConst.ENDPOINT_QUERY_PARAMS)) {
addressServerUrlTem
.append(hasQueryString ? "&" : "?" + properties.get(PropertyKeyConst.ENDPOINT_QUERY_PARAMS));
.append(hasQueryString ? "&" : "?" + properties.getProperty(PropertyKeyConst.ENDPOINT_QUERY_PARAMS));
}
@ -267,7 +269,7 @@ public class ServerListManager implements Closeable {
LOGGER.info("serverName = {}, address server url = {}", this.name, this.addressServerUrl);
}
private void initParam(Properties properties) {
private void initParam(NacosClientProperties properties) {
this.endpoint = initEndpoint(properties);
String contentPathTmp = properties.getProperty(PropertyKeyConst.CONTEXT_PATH);
@ -280,10 +282,10 @@ public class ServerListManager implements Closeable {
}
}
private String initEndpoint(final Properties properties) {
private String initEndpoint(final NacosClientProperties properties) {
String endpointPortTmp = TemplateUtils
.stringEmptyAndThenExecute(System.getenv(PropertyKeyConst.SystemEnv.ALIBABA_ALIWARE_ENDPOINT_PORT),
.stringEmptyAndThenExecute(properties.getProperty(PropertyKeyConst.SystemEnv.ALIBABA_ALIWARE_ENDPOINT_PORT),
() -> properties.getProperty(PropertyKeyConst.ENDPOINT_PORT));
if (StringUtils.isNotBlank(endpointPortTmp)) {
@ -294,7 +296,7 @@ public class ServerListManager implements Closeable {
// Whether to enable domain name resolution rules
String isUseEndpointRuleParsing = properties.getProperty(PropertyKeyConst.IS_USE_ENDPOINT_PARSING_RULE,
System.getProperty(SystemPropertyKeyConst.IS_USE_ENDPOINT_PARSING_RULE,
properties.getProperty(SystemPropertyKeyConst.IS_USE_ENDPOINT_PARSING_RULE,
String.valueOf(ParamUtil.USE_ENDPOINT_PARSING_RULE_DEFAULT_VALUE)));
if (Boolean.parseBoolean(isUseEndpointRuleParsing)) {
String endpointUrl = ParamUtil.parsingEndpointRule(endpointTmp);

View File

@ -16,6 +16,7 @@
package com.alibaba.nacos.client.config.utils;
import com.alibaba.nacos.client.env.NacosClientProperties;
import com.alibaba.nacos.client.utils.LogUtils;
import org.slf4j.Logger;
@ -46,7 +47,7 @@ public class JvmUtil {
private static final String DEFAULT_IS_MULTI_INSTANCE = "false";
static {
String multiDeploy = System.getProperty(IS_MULTI_INSTANCE_PROPERTY, DEFAULT_IS_MULTI_INSTANCE);
String multiDeploy = NacosClientProperties.PROTOTYPE.getProperty(IS_MULTI_INSTANCE_PROPERTY, DEFAULT_IS_MULTI_INSTANCE);
if (TRUE.equals(multiDeploy)) {
isMultiInstance = true;
}

View File

@ -17,6 +17,7 @@
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;
@ -37,15 +38,15 @@ public abstract class AbstractNacosLogging {
private static final String NACOS_LOGGING_PATH_DIR = "logs";
static {
String loggingPath = System.getProperty(Constants.SysEnv.JM_LOG_PATH);
String loggingPath = NacosClientProperties.PROTOTYPE.getProperty(Constants.SysEnv.JM_LOG_PATH);
if (StringUtils.isBlank(loggingPath)) {
String userHome = System.getProperty(Constants.SysEnv.USER_HOME);
System.setProperty(Constants.SysEnv.JM_LOG_PATH, userHome + File.separator + NACOS_LOGGING_PATH_DIR);
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 = System.getProperty(NACOS_LOGGING_CONFIG_PROPERTY);
String location = NacosClientProperties.PROTOTYPE.getProperty(NACOS_LOGGING_CONFIG_PROPERTY);
if (StringUtils.isBlank(location)) {
if (isDefaultConfigEnabled()) {
return defaultLocation;
@ -56,7 +57,7 @@ public abstract class AbstractNacosLogging {
}
private boolean isDefaultConfigEnabled() {
String property = System.getProperty(NACOS_LOGGING_DEFAULT_CONFIG_ENABLED_PROPERTY);
String property = NacosClientProperties.PROTOTYPE.getProperty(NACOS_LOGGING_DEFAULT_CONFIG_ENABLED_PROPERTY);
// The default value is true.
return property == null || ConvertUtils.toBoolean(property);
}

View File

@ -46,6 +46,8 @@ public class Log4J2NacosLogging extends AbstractNacosLogging {
private static final String NACOS_LOGGER_PREFIX = "com.alibaba.nacos";
private static final String NACOS_LOG4J2_PLUGIN_PACKAGE = "com.alibaba.nacos.client.logging.log4j2";
private final String location = getLocation(NACOS_LOG4J2_LOCATION);
@Override
@ -59,6 +61,7 @@ public class Log4J2NacosLogging extends AbstractNacosLogging {
// load and start nacos configuration
Configuration configuration = loadConfiguration(loggerContext, location);
configuration.getPluginPackages().add(NACOS_LOG4J2_PLUGIN_PACKAGE);
configuration.start();
// append loggers and appenders to contextConfiguration

View File

@ -0,0 +1,38 @@
/*
* 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.client.logging.log4j2;
import com.alibaba.nacos.client.env.NacosClientProperties;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.lookup.AbstractLookup;
import org.apache.logging.log4j.core.lookup.StrLookup;
/**
* support log4j2 read properties from NacosClientProperties.
* for example:
* <SizeBasedTriggeringPolicy size="${nacosClientProperty:JM.LOG.FILE.SIZE:-10MB}"/>
* @author onewe
*/
@Plugin(name = "nacosClientProperty", category = StrLookup.CATEGORY)
public class NacosClientPropertiesLookup extends AbstractLookup {
@Override
public String lookup(LogEvent event, String key) {
return NacosClientProperties.PROTOTYPE.getProperty(key);
}
}

View File

@ -0,0 +1,59 @@
/*
* 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.client.logging.logback;
import ch.qos.logback.core.joran.action.Action;
import ch.qos.logback.core.joran.action.ActionUtil;
import ch.qos.logback.core.joran.spi.ActionException;
import ch.qos.logback.core.joran.spi.InterpretationContext;
import ch.qos.logback.core.util.OptionHelper;
import com.alibaba.nacos.client.env.NacosClientProperties;
import org.xml.sax.Attributes;
/**
* support logback read properties from NacosClientProperties. just like springProperty.
* for example:
* <nacosClientProperty scope="context" name="logPath" source="system.log.path" defaultValue="/root" />
* @author onewe
*/
class NacosClientPropertyAction extends Action {
private static final String DEFAULT_VALUE_ATTRIBUTE = "defaultValue";
private static final String SOURCE_ATTRIBUTE = "source";
@Override
public void begin(InterpretationContext ic, String elementName, Attributes attributes) throws ActionException {
String name = attributes.getValue(NAME_ATTRIBUTE);
String source = attributes.getValue(SOURCE_ATTRIBUTE);
ActionUtil.Scope scope = ActionUtil.stringToScope(attributes.getValue(SCOPE_ATTRIBUTE));
String defaultValue = attributes.getValue(DEFAULT_VALUE_ATTRIBUTE);
if (OptionHelper.isEmpty(name)) {
addError("The \"name\" and \"source\" attributes of <nacosClientProperty> must be set");
}
ActionUtil.setProperty(ic, name, getValue(source, defaultValue), scope);
}
@Override
public void end(InterpretationContext ic, String name) throws ActionException {
}
private String getValue(String source, String defaultValue) {
return NacosClientProperties.PROTOTYPE.getProperty(source, defaultValue);
}
}

View File

@ -18,7 +18,9 @@ package com.alibaba.nacos.client.logging.logback;
import ch.qos.logback.classic.joran.JoranConfigurator;
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 java.io.IOException;
import java.io.InputStream;
@ -43,6 +45,12 @@ public class NacosJoranConfigurator extends JoranConfigurator {
public void registerSafeConfiguration(List<SaxEvent> eventList) {
}
@Override
public void addInstanceRules(RuleStore rs) {
super.addInstanceRules(rs);
rs.addRule(new ElementSelector("configuration/nacosClientProperty"), new NacosClientPropertyAction());
}
/**
* ensure that Nacos configuration does not affect user configuration scanning url.
*

View File

@ -25,6 +25,7 @@ import com.alibaba.nacos.api.naming.pojo.Service;
import com.alibaba.nacos.api.selector.AbstractSelector;
import com.alibaba.nacos.api.selector.ExpressionSelector;
import com.alibaba.nacos.api.selector.NoneSelector;
import com.alibaba.nacos.client.env.NacosClientProperties;
import com.alibaba.nacos.client.naming.core.ServerListManager;
import com.alibaba.nacos.client.naming.remote.http.NamingHttpClientManager;
import com.alibaba.nacos.client.naming.remote.http.NamingHttpClientProxy;
@ -72,15 +73,16 @@ public class NacosNamingMaintainService implements NamingMaintainService {
}
private void init(Properties properties) throws NacosException {
ValidatorUtils.checkInitParam(properties);
namespace = InitUtils.initNamespaceForNaming(properties);
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(properties);
ValidatorUtils.checkInitParam(nacosClientProperties);
namespace = InitUtils.initNamespaceForNaming(nacosClientProperties);
InitUtils.initSerialization();
InitUtils.initWebRootContext(properties);
serverListManager = new ServerListManager(properties, namespace);
InitUtils.initWebRootContext(nacosClientProperties);
serverListManager = new ServerListManager(nacosClientProperties, namespace);
securityProxy = new SecurityProxy(serverListManager.getServerList(),
NamingHttpClientManager.getInstance().getNacosRestTemplate());
initSecurityProxy(properties);
serverProxy = new NamingHttpClientProxy(namespace, securityProxy, serverListManager, properties, null);
serverProxy = new NamingHttpClientProxy(namespace, securityProxy, serverListManager, nacosClientProperties);
}
private void initSecurityProxy(Properties properties) {
@ -91,9 +93,10 @@ public class NacosNamingMaintainService implements NamingMaintainService {
return t;
});
this.securityProxy.login(properties);
this.executorService.scheduleWithFixedDelay(() -> securityProxy.login(properties), 0,
SECURITY_INFO_REFRESH_INTERVAL_MILLS, TimeUnit.MILLISECONDS);
this.executorService
.scheduleWithFixedDelay(() -> securityProxy.login(properties), 0, SECURITY_INFO_REFRESH_INTERVAL_MILLS,
TimeUnit.MILLISECONDS);
}
@Override

View File

@ -26,6 +26,7 @@ import com.alibaba.nacos.api.naming.pojo.ListView;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import com.alibaba.nacos.api.naming.utils.NamingUtils;
import com.alibaba.nacos.api.selector.AbstractSelector;
import com.alibaba.nacos.client.env.NacosClientProperties;
import com.alibaba.nacos.client.naming.cache.ServiceInfoHolder;
import com.alibaba.nacos.client.naming.core.Balancer;
import com.alibaba.nacos.client.naming.event.InstancesChangeEvent;
@ -85,25 +86,27 @@ public class NacosNamingService implements NamingService {
}
private void init(Properties properties) throws NacosException {
ValidatorUtils.checkInitParam(properties);
this.namespace = InitUtils.initNamespaceForNaming(properties);
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(properties);
ValidatorUtils.checkInitParam(nacosClientProperties);
this.namespace = InitUtils.initNamespaceForNaming(nacosClientProperties);
InitUtils.initSerialization();
InitUtils.initWebRootContext(properties);
initLogName(properties);
InitUtils.initWebRootContext(nacosClientProperties);
initLogName(nacosClientProperties);
this.notifierEventScope = UUID.randomUUID().toString();
this.changeNotifier = new InstancesChangeNotifier(this.notifierEventScope);
NotifyCenter.registerToPublisher(InstancesChangeEvent.class, 16384);
NotifyCenter.registerSubscriber(changeNotifier);
this.serviceInfoHolder = new ServiceInfoHolder(namespace, this.notifierEventScope, properties);
this.clientProxy = new NamingClientProxyDelegate(this.namespace, serviceInfoHolder, properties, changeNotifier);
this.serviceInfoHolder = new ServiceInfoHolder(namespace, this.notifierEventScope, nacosClientProperties);
this.clientProxy = new NamingClientProxyDelegate(this.namespace, serviceInfoHolder, nacosClientProperties, changeNotifier);
}
private void initLogName(Properties properties) {
logName = System.getProperty(UtilAndComs.NACOS_NAMING_LOG_NAME);
private void initLogName(NacosClientProperties properties) {
logName = properties.getProperty(UtilAndComs.NACOS_NAMING_LOG_NAME);
if (StringUtils.isEmpty(logName)) {
if (properties != null && StringUtils
if (StringUtils
.isNotEmpty(properties.getProperty(UtilAndComs.NACOS_NAMING_LOG_NAME))) {
logName = properties.getProperty(UtilAndComs.NACOS_NAMING_LOG_NAME);
} else {
@ -156,6 +159,13 @@ public class NacosNamingService implements NamingService {
clientProxy.batchRegisterService(serviceName, groupName, instances);
}
@Override
public void batchDeregisterInstance(String serviceName, String groupName, List<Instance> instances)
throws NacosException {
NamingUtils.batchCheckInstanceIsLegal(instances);
clientProxy.batchDeregisterService(serviceName, groupName, instances);
}
@Override
public void deregisterInstance(String serviceName, String ip, int port) throws NacosException {
deregisterInstance(serviceName, ip, port, Constants.DEFAULT_CLUSTER_NAME);

View File

@ -1,220 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.client.naming.beat;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.CommonParams;
import com.alibaba.nacos.api.naming.NamingResponseCode;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.utils.NamingUtils;
import com.alibaba.nacos.client.monitor.MetricsMonitor;
import com.alibaba.nacos.client.naming.remote.http.NamingHttpClientProxy;
import com.alibaba.nacos.client.naming.utils.UtilAndComs;
import com.alibaba.nacos.common.lifecycle.Closeable;
import com.alibaba.nacos.common.utils.ConvertUtils;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.common.utils.ThreadUtils;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import static com.alibaba.nacos.client.utils.LogUtils.NAMING_LOGGER;
/**
* Beat reactor.
*
* @author harold
*/
public class BeatReactor implements Closeable {
private static final String CLIENT_BEAT_INTERVAL_FIELD = "clientBeatInterval";
private final ScheduledExecutorService executorService;
private final NamingHttpClientProxy serverProxy;
private boolean lightBeatEnabled = false;
public final Map<String, BeatInfo> dom2Beat = new ConcurrentHashMap<>();
public BeatReactor(NamingHttpClientProxy serverProxy) {
this(serverProxy, null);
}
public BeatReactor(NamingHttpClientProxy serverProxy, Properties properties) {
this.serverProxy = serverProxy;
int threadCount = initClientBeatThreadCount(properties);
this.executorService = new ScheduledThreadPoolExecutor(threadCount, r -> {
Thread thread = new Thread(r);
thread.setDaemon(true);
thread.setName("com.alibaba.nacos.naming.beat.sender");
return thread;
});
}
private int initClientBeatThreadCount(Properties properties) {
if (properties == null) {
return UtilAndComs.DEFAULT_CLIENT_BEAT_THREAD_COUNT;
}
return ConvertUtils.toInt(properties.getProperty(PropertyKeyConst.NAMING_CLIENT_BEAT_THREAD_COUNT),
UtilAndComs.DEFAULT_CLIENT_BEAT_THREAD_COUNT);
}
/**
* Add beat information.
*
* @param serviceName service name
* @param beatInfo beat information
*/
public void addBeatInfo(String serviceName, BeatInfo beatInfo) {
NAMING_LOGGER.info("[BEAT] adding beat: {} to beat map.", beatInfo);
String key = buildKey(serviceName, beatInfo.getIp(), beatInfo.getPort());
BeatInfo existBeat;
//fix #1733
if ((existBeat = dom2Beat.remove(key)) != null) {
existBeat.setStopped(true);
}
dom2Beat.put(key, beatInfo);
executorService.schedule(new BeatTask(beatInfo), beatInfo.getPeriod(), TimeUnit.MILLISECONDS);
MetricsMonitor.getDom2BeatSizeMonitor().set(dom2Beat.size());
}
/**
* Remove beat information.
*
* @param serviceName service name
* @param ip ip of beat information
* @param port port of beat information
*/
public void removeBeatInfo(String serviceName, String ip, int port) {
NAMING_LOGGER.info("[BEAT] removing beat: {}:{}:{} from beat map.", serviceName, ip, port);
BeatInfo beatInfo = dom2Beat.remove(buildKey(serviceName, ip, port));
if (beatInfo == null) {
return;
}
beatInfo.setStopped(true);
MetricsMonitor.getDom2BeatSizeMonitor().set(dom2Beat.size());
}
/**
* Build new beat information.
*
* @param instance instance
* @return new beat information
*/
public BeatInfo buildBeatInfo(Instance instance) {
return buildBeatInfo(instance.getServiceName(), instance);
}
/**
* Build new beat information.
*
* @param groupedServiceName service name with group name, format: ${groupName}@@${serviceName}
* @param instance instance
* @return new beat information
*/
public BeatInfo buildBeatInfo(String groupedServiceName, Instance instance) {
BeatInfo beatInfo = new BeatInfo();
beatInfo.setServiceName(groupedServiceName);
beatInfo.setIp(instance.getIp());
beatInfo.setPort(instance.getPort());
beatInfo.setCluster(instance.getClusterName());
beatInfo.setWeight(instance.getWeight());
beatInfo.setMetadata(instance.getMetadata());
beatInfo.setScheduled(false);
beatInfo.setPeriod(instance.getInstanceHeartBeatInterval());
return beatInfo;
}
public String buildKey(String serviceName, String ip, int port) {
return serviceName + Constants.NAMING_INSTANCE_ID_SPLITTER + ip + Constants.NAMING_INSTANCE_ID_SPLITTER + port;
}
@Override
public void shutdown() throws NacosException {
String className = this.getClass().getName();
NAMING_LOGGER.info("{} do shutdown begin", className);
ThreadUtils.shutdownThreadPool(executorService, NAMING_LOGGER);
NAMING_LOGGER.info("{} do shutdown stop", className);
}
class BeatTask implements Runnable {
BeatInfo beatInfo;
public BeatTask(BeatInfo beatInfo) {
this.beatInfo = beatInfo;
}
@Override
public void run() {
if (beatInfo.isStopped()) {
return;
}
long nextTime = beatInfo.getPeriod();
try {
JsonNode result = serverProxy.sendBeat(beatInfo, BeatReactor.this.lightBeatEnabled);
long interval = result.get(CLIENT_BEAT_INTERVAL_FIELD).asLong();
boolean lightBeatEnabled = false;
if (result.has(CommonParams.LIGHT_BEAT_ENABLED)) {
lightBeatEnabled = result.get(CommonParams.LIGHT_BEAT_ENABLED).asBoolean();
}
BeatReactor.this.lightBeatEnabled = lightBeatEnabled;
if (interval > 0) {
nextTime = interval;
}
int code = NamingResponseCode.OK;
if (result.has(CommonParams.CODE)) {
code = result.get(CommonParams.CODE).asInt();
}
if (code == NamingResponseCode.RESOURCE_NOT_FOUND) {
Instance instance = new Instance();
instance.setPort(beatInfo.getPort());
instance.setIp(beatInfo.getIp());
instance.setWeight(beatInfo.getWeight());
instance.setMetadata(beatInfo.getMetadata());
instance.setClusterName(beatInfo.getCluster());
instance.setServiceName(beatInfo.getServiceName());
instance.setInstanceId(instance.getInstanceId());
instance.setEphemeral(true);
try {
serverProxy.registerService(beatInfo.getServiceName(),
NamingUtils.getGroupName(beatInfo.getServiceName()), instance);
} catch (Exception ignore) {
}
}
} catch (NacosException ex) {
NAMING_LOGGER.error("[CLIENT-BEAT] failed to send beat: {}, code: {}, msg: {}",
JacksonUtils.toJson(beatInfo), ex.getErrCode(), ex.getErrMsg());
} catch (Exception unknownEx) {
NAMING_LOGGER.error("[CLIENT-BEAT] failed to send beat: {}, unknown exception msg: {}",
JacksonUtils.toJson(beatInfo), unknownEx.getMessage(), unknownEx);
} finally {
executorService.schedule(new BeatTask(beatInfo), nextTime, TimeUnit.MILLISECONDS);
}
}
}
}

View File

@ -21,6 +21,7 @@ import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import com.alibaba.nacos.api.naming.utils.NamingUtils;
import com.alibaba.nacos.client.env.NacosClientProperties;
import com.alibaba.nacos.client.monitor.MetricsMonitor;
import com.alibaba.nacos.client.naming.backups.FailoverReactor;
import com.alibaba.nacos.client.naming.event.InstancesChangeEvent;
@ -36,7 +37,6 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
@ -68,7 +68,7 @@ public class ServiceInfoHolder implements Closeable {
private String notifierEventScope;
public ServiceInfoHolder(String namespace, String notifierEventScope, Properties properties) {
public ServiceInfoHolder(String namespace, String notifierEventScope, NacosClientProperties properties) {
initCacheDir(namespace, properties);
if (isLoadCacheAtStart(properties)) {
this.serviceInfoMap = new ConcurrentHashMap<>(DiskCache.read(this.cacheDir));
@ -80,8 +80,8 @@ public class ServiceInfoHolder implements Closeable {
this.notifierEventScope = notifierEventScope;
}
private void initCacheDir(String namespace, Properties properties) {
String jmSnapshotPath = System.getProperty(JM_SNAPSHOT_PATH_PROPERTY);
private void initCacheDir(String namespace, NacosClientProperties properties) {
String jmSnapshotPath = properties.getProperty(JM_SNAPSHOT_PATH_PROPERTY);
String namingCacheRegistryDir = "";
if (properties.getProperty(PropertyKeyConst.NAMING_CACHE_REGISTRY_DIR) != null) {
@ -92,12 +92,12 @@ public class ServiceInfoHolder implements Closeable {
cacheDir = jmSnapshotPath + File.separator + FILE_PATH_NACOS + namingCacheRegistryDir
+ File.separator + FILE_PATH_NAMING + File.separator + namespace;
} else {
cacheDir = System.getProperty(USER_HOME_PROPERTY) + File.separator + FILE_PATH_NACOS + namingCacheRegistryDir
cacheDir = properties.getProperty(USER_HOME_PROPERTY) + File.separator + FILE_PATH_NACOS + namingCacheRegistryDir
+ File.separator + FILE_PATH_NAMING + File.separator + namespace;
}
}
private boolean isLoadCacheAtStart(Properties properties) {
private boolean isLoadCacheAtStart(NacosClientProperties properties) {
boolean loadCacheAtStart = false;
if (properties != null && StringUtils
.isNotEmpty(properties.getProperty(PropertyKeyConst.NAMING_LOAD_CACHE_AT_START))) {
@ -107,7 +107,7 @@ public class ServiceInfoHolder implements Closeable {
return loadCacheAtStart;
}
private boolean isPushEmptyProtect(Properties properties) {
private boolean isPushEmptyProtect(NacosClientProperties properties) {
boolean pushEmptyProtection = false;
if (properties != null && StringUtils
.isNotEmpty(properties.getProperty(PropertyKeyConst.NAMING_PUSH_EMPTY_PROTECTION))) {

View File

@ -1,155 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.client.naming.core;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.client.naming.cache.ServiceInfoHolder;
import com.alibaba.nacos.common.lifecycle.Closeable;
import com.alibaba.nacos.common.utils.IoUtils;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.common.utils.ThreadUtils;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import static com.alibaba.nacos.client.utils.LogUtils.NAMING_LOGGER;
/**
* Push receiver.
*
* @author xuanyin
*/
public class PushReceiver implements Runnable, Closeable {
private static final Charset UTF_8 = StandardCharsets.UTF_8;
private static final int UDP_MSS = 64 * 1024;
private static final String PUSH_PACKAGE_TYPE_DOM = "dom";
private static final String PUSH_PACKAGE_TYPE_SERVICE = "service";
private static final String PUSH_PACKAGE_TYPE_DUMP = "dump";
private ScheduledExecutorService executorService;
private DatagramSocket udpSocket;
private ServiceInfoHolder serviceInfoHolder;
private volatile boolean closed = false;
public static String getPushReceiverUdpPort() {
return System.getenv(PropertyKeyConst.PUSH_RECEIVER_UDP_PORT);
}
public PushReceiver(ServiceInfoHolder serviceInfoHolder) {
try {
this.serviceInfoHolder = serviceInfoHolder;
String udpPort = getPushReceiverUdpPort();
if (StringUtils.isEmpty(udpPort)) {
this.udpSocket = new DatagramSocket();
} else {
this.udpSocket = new DatagramSocket(new InetSocketAddress(Integer.parseInt(udpPort)));
}
this.executorService = new ScheduledThreadPoolExecutor(1, r -> {
Thread thread = new Thread(r);
thread.setDaemon(true);
thread.setName("com.alibaba.nacos.naming.push.receiver");
return thread;
});
this.executorService.execute(this);
} catch (Exception e) {
NAMING_LOGGER.error("[NA] init udp socket failed", e);
}
}
@Override
public void run() {
while (!closed) {
try {
// byte[] is initialized with 0 full filled by default
byte[] buffer = new byte[UDP_MSS];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
udpSocket.receive(packet);
String json = new String(IoUtils.tryDecompress(packet.getData()), UTF_8).trim();
NAMING_LOGGER.info("received push data: " + json + " from " + packet.getAddress().toString());
PushPacket pushPacket = JacksonUtils.toObj(json, PushPacket.class);
String ack;
if (PUSH_PACKAGE_TYPE_DOM.equals(pushPacket.type) || PUSH_PACKAGE_TYPE_SERVICE.equals(pushPacket.type)) {
serviceInfoHolder.processServiceInfo(pushPacket.data);
// send ack to server
ack = "{\"type\": \"push-ack\"" + ", \"lastRefTime\":\"" + pushPacket.lastRefTime + "\", \"data\":"
+ "\"\"}";
} else if (PUSH_PACKAGE_TYPE_DUMP.equals(pushPacket.type)) {
// dump data to server
ack = "{\"type\": \"dump-ack\"" + ", \"lastRefTime\": \"" + pushPacket.lastRefTime + "\", \"data\":"
+ "\"" + StringUtils.escapeJavaScript(JacksonUtils.toJson(serviceInfoHolder.getServiceInfoMap()))
+ "\"}";
} else {
// do nothing send ack only
ack = "{\"type\": \"unknown-ack\"" + ", \"lastRefTime\":\"" + pushPacket.lastRefTime
+ "\", \"data\":" + "\"\"}";
}
udpSocket.send(new DatagramPacket(ack.getBytes(UTF_8), ack.getBytes(UTF_8).length,
packet.getSocketAddress()));
} catch (Exception e) {
if (closed) {
return;
}
NAMING_LOGGER.error("[NA] error while receiving push data", e);
}
}
}
@Override
public void shutdown() throws NacosException {
String className = this.getClass().getName();
NAMING_LOGGER.info("{} do shutdown begin", className);
ThreadUtils.shutdownThreadPool(executorService, NAMING_LOGGER);
closed = true;
udpSocket.close();
NAMING_LOGGER.info("{} do shutdown stop", className);
}
public static class PushPacket {
public String type;
public long lastRefTime;
public String data;
}
public int getUdpPort() {
return this.udpSocket.getLocalPort();
}
}

View File

@ -19,6 +19,7 @@ package com.alibaba.nacos.client.naming.core;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.exception.runtime.NacosLoadException;
import com.alibaba.nacos.client.env.NacosClientProperties;
import com.alibaba.nacos.client.naming.event.ServerListChangedEvent;
import com.alibaba.nacos.client.naming.remote.http.NamingHttpClientManager;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
@ -79,10 +80,10 @@ public class ServerListManager implements ServerListFactory, Closeable {
private long lastServerListRefreshTime = 0L;
public ServerListManager(Properties properties) {
this(properties, null);
this(NacosClientProperties.PROTOTYPE.derive(properties), null);
}
public ServerListManager(Properties properties, String namespace) {
public ServerListManager(NacosClientProperties properties, String namespace) {
this.namespace = namespace;
initServerAddr(properties);
if (!serverList.isEmpty()) {
@ -93,7 +94,7 @@ public class ServerListManager implements ServerListFactory, Closeable {
}
}
private void initServerAddr(Properties properties) {
private void initServerAddr(NacosClientProperties properties) {
this.endpoint = InitUtils.initEndpoint(properties);
if (StringUtils.isNotEmpty(endpoint)) {
this.serversFromEndpoint = getServerListFromEndpoint();

View File

@ -20,6 +20,7 @@ import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import com.alibaba.nacos.api.naming.utils.NamingUtils;
import com.alibaba.nacos.client.env.NacosClientProperties;
import com.alibaba.nacos.client.naming.cache.ServiceInfoHolder;
import com.alibaba.nacos.client.naming.event.InstancesChangeNotifier;
import com.alibaba.nacos.client.naming.remote.NamingClientProxy;
@ -32,7 +33,6 @@ import com.alibaba.nacos.common.utils.ThreadUtils;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
@ -63,7 +63,7 @@ public class ServiceInfoUpdateService implements Closeable {
private final boolean asyncQuerySubscribeService;
public ServiceInfoUpdateService(Properties properties, ServiceInfoHolder serviceInfoHolder,
public ServiceInfoUpdateService(NacosClientProperties properties, ServiceInfoHolder serviceInfoHolder,
NamingClientProxy namingClientProxy, InstancesChangeNotifier changeNotifier) {
this.asyncQuerySubscribeService = isAsyncQueryForSubscribeService(properties);
this.executor = new ScheduledThreadPoolExecutor(initPollingThreadCount(properties),
@ -73,14 +73,14 @@ public class ServiceInfoUpdateService implements Closeable {
this.changeNotifier = changeNotifier;
}
private boolean isAsyncQueryForSubscribeService(Properties properties) {
private boolean isAsyncQueryForSubscribeService(NacosClientProperties properties) {
if (properties == null || !properties.containsKey(PropertyKeyConst.NAMING_ASYNC_QUERY_SUBSCRIBE_SERVICE)) {
return true;
return false;
}
return ConvertUtils.toBoolean(properties.getProperty(PropertyKeyConst.NAMING_ASYNC_QUERY_SUBSCRIBE_SERVICE), true);
return ConvertUtils.toBoolean(properties.getProperty(PropertyKeyConst.NAMING_ASYNC_QUERY_SUBSCRIBE_SERVICE), false);
}
private int initPollingThreadCount(Properties properties) {
private int initPollingThreadCount(NacosClientProperties properties) {
if (properties == null) {
return UtilAndComs.DEFAULT_POLLING_THREAD_COUNT;
}

View File

@ -45,8 +45,6 @@ public class InstancesChangeNotifier extends Subscriber<InstancesChangeEvent> {
private final Map<String, ConcurrentHashSet<EventListener>> listenerMap = new ConcurrentHashMap<>();
private final Object lock = new Object();
@JustForTest
public InstancesChangeNotifier() {
this.eventScope = UUID.randomUUID().toString();
@ -66,16 +64,7 @@ public class InstancesChangeNotifier extends Subscriber<InstancesChangeEvent> {
*/
public void registerListener(String groupName, String serviceName, String clusters, EventListener listener) {
String key = ServiceInfo.getKey(NamingUtils.getGroupedName(serviceName, groupName), clusters);
ConcurrentHashSet<EventListener> eventListeners = listenerMap.get(key);
if (eventListeners == null) {
synchronized (lock) {
eventListeners = listenerMap.get(key);
if (eventListeners == null) {
eventListeners = new ConcurrentHashSet<>();
listenerMap.put(key, eventListeners);
}
}
}
ConcurrentHashSet<EventListener> eventListeners = listenerMap.computeIfAbsent(key, keyInner -> new ConcurrentHashSet<>());
eventListeners.add(listener);
}

View File

@ -25,7 +25,6 @@ import com.alibaba.nacos.api.selector.AbstractSelector;
import com.alibaba.nacos.common.lifecycle.Closeable;
import java.util.List;
import java.util.Set;
/**
* Naming Client Proxy.
@ -55,6 +54,17 @@ public interface NamingClientProxy extends Closeable {
*/
void batchRegisterService(String serviceName, String groupName, List<Instance> instances) throws NacosException;
/**
* Batch deRegister instance to service with specified instance properties.
*
* @param serviceName service name
* @param groupName group name
* @param instances deRegister instance
* @throws NacosException nacos exception
* @since 2.2.0
*/
void batchDeregisterService(String serviceName, String groupName, List<Instance> instances) throws NacosException;
/**
* Deregister instance from a service.
*
@ -86,8 +96,8 @@ public interface NamingClientProxy extends Closeable {
* @return service info
* @throws NacosException nacos exception
*/
ServiceInfo queryInstancesOfService(String serviceName, String groupName, String clusters, int udpPort, boolean healthyOnly)
throws NacosException;
ServiceInfo queryInstancesOfService(String serviceName, String groupName, String clusters, int udpPort,
boolean healthyOnly) throws NacosException;
/**
* Query Service.
@ -172,13 +182,6 @@ public interface NamingClientProxy extends Closeable {
*/
boolean isSubscribed(String serviceName, String groupName, String clusters) throws NacosException;
/**
* Update beat info.
*
* @param modifiedInstances modified instances
*/
void updateBeatInfo(Set<Instance> modifiedInstances);
/**
* Check Server healthy.
*

View File

@ -23,6 +23,7 @@ import com.alibaba.nacos.api.naming.pojo.Service;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import com.alibaba.nacos.api.naming.utils.NamingUtils;
import com.alibaba.nacos.api.selector.AbstractSelector;
import com.alibaba.nacos.client.env.NacosClientProperties;
import com.alibaba.nacos.client.naming.cache.ServiceInfoHolder;
import com.alibaba.nacos.client.naming.core.ServerListManager;
import com.alibaba.nacos.client.naming.core.ServiceInfoUpdateService;
@ -36,7 +37,6 @@ import com.alibaba.nacos.common.utils.ThreadUtils;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
@ -65,30 +65,32 @@ public class NamingClientProxyDelegate implements NamingClientProxy {
private ScheduledExecutorService executorService;
public NamingClientProxyDelegate(String namespace, ServiceInfoHolder serviceInfoHolder, Properties properties,
public NamingClientProxyDelegate(String namespace, ServiceInfoHolder serviceInfoHolder, NacosClientProperties properties,
InstancesChangeNotifier changeNotifier) throws NacosException {
this.serviceInfoUpdateService = new ServiceInfoUpdateService(properties, serviceInfoHolder, this,
changeNotifier);
this.serverListManager = new ServerListManager(properties, namespace);
this.serviceInfoHolder = serviceInfoHolder;
this.securityProxy = new SecurityProxy(this.serverListManager.getServerList(), NamingHttpClientManager.getInstance().getNacosRestTemplate());
this.securityProxy = new SecurityProxy(this.serverListManager.getServerList(),
NamingHttpClientManager.getInstance().getNacosRestTemplate());
initSecurityProxy(properties);
this.httpClientProxy = new NamingHttpClientProxy(namespace, securityProxy, serverListManager, properties,
serviceInfoHolder);
this.httpClientProxy = new NamingHttpClientProxy(namespace, securityProxy, serverListManager, properties);
this.grpcClientProxy = new NamingGrpcClientProxy(namespace, securityProxy, serverListManager, properties,
serviceInfoHolder);
}
private void initSecurityProxy(Properties properties) {
private void initSecurityProxy(NacosClientProperties properties) {
this.executorService = new ScheduledThreadPoolExecutor(1, r -> {
Thread t = new Thread(r);
t.setName("com.alibaba.nacos.client.naming.security");
t.setDaemon(true);
return t;
});
this.securityProxy.login(properties);
this.executorService.scheduleWithFixedDelay(() -> securityProxy.login(properties), 0,
SECURITY_INFO_REFRESH_INTERVAL_MILLS, TimeUnit.MILLISECONDS);
final Properties nacosClientPropertiesView = properties.asProperties();
this.securityProxy.login(nacosClientPropertiesView);
this.executorService
.scheduleWithFixedDelay(() -> securityProxy.login(nacosClientPropertiesView), 0, SECURITY_INFO_REFRESH_INTERVAL_MILLS,
TimeUnit.MILLISECONDS);
}
@Override
@ -107,6 +109,17 @@ public class NamingClientProxyDelegate implements NamingClientProxy {
NAMING_LOGGER.info("batchRegisterInstance instances: {} ,serviceName: {} finish.", instances, serviceName);
}
@Override
public void batchDeregisterService(String serviceName, String groupName, List<Instance> instances)
throws NacosException {
NAMING_LOGGER.info("batch DeregisterInstance instances: {} ,serviceName: {} begin.", instances, serviceName);
if (CollectionUtils.isEmpty(instances)) {
NAMING_LOGGER.warn("batch DeregisterInstance instances is Empty:{}", instances);
}
grpcClientProxy.batchDeregisterService(serviceName, groupName, instances);
NAMING_LOGGER.info("batch DeregisterInstance instances: {} ,serviceName: {} finish.", instances, serviceName);
}
@Override
public void deregisterService(String serviceName, String groupName, Instance instance) throws NacosException {
getExecuteClientProxy(instance).deregisterService(serviceName, groupName, instance);
@ -165,7 +178,8 @@ public class NamingClientProxyDelegate implements NamingClientProxy {
@Override
public void unsubscribe(String serviceName, String groupName, String clusters) throws NacosException {
NAMING_LOGGER.debug("[UNSUBSCRIBE-SERVICE] service:{}, group:{}, cluster:{} ", serviceName, groupName, clusters);
NAMING_LOGGER
.debug("[UNSUBSCRIBE-SERVICE] service:{}, group:{}, cluster:{} ", serviceName, groupName, clusters);
serviceInfoUpdateService.stopUpdateIfContain(serviceName, groupName, clusters);
grpcClientProxy.unsubscribe(serviceName, groupName, clusters);
}
@ -175,11 +189,6 @@ public class NamingClientProxyDelegate implements NamingClientProxy {
return grpcClientProxy.isSubscribed(serviceName, groupName, clusters);
}
@Override
public void updateBeatInfo(Set<Instance> modifiedInstances) {
httpClientProxy.updateBeatInfo(modifiedInstances);
}
@Override
public boolean serverHealthy() {
return grpcClientProxy.serverHealthy() || httpClientProxy.serverHealthy();

View File

@ -33,15 +33,19 @@ import com.alibaba.nacos.api.naming.remote.response.BatchInstanceResponse;
import com.alibaba.nacos.api.naming.remote.response.QueryServiceResponse;
import com.alibaba.nacos.api.naming.remote.response.ServiceListResponse;
import com.alibaba.nacos.api.naming.remote.response.SubscribeServiceResponse;
import com.alibaba.nacos.api.naming.utils.NamingUtils;
import com.alibaba.nacos.api.remote.RemoteConstants;
import com.alibaba.nacos.api.remote.response.Response;
import com.alibaba.nacos.api.remote.response.ResponseCode;
import com.alibaba.nacos.api.selector.AbstractSelector;
import com.alibaba.nacos.api.selector.SelectorType;
import com.alibaba.nacos.client.env.NacosClientProperties;
import com.alibaba.nacos.client.naming.cache.ServiceInfoHolder;
import com.alibaba.nacos.client.naming.event.ServerListChangedEvent;
import com.alibaba.nacos.client.naming.remote.AbstractNamingClientProxy;
import com.alibaba.nacos.client.naming.remote.gprc.redo.NamingGrpcRedoService;
import com.alibaba.nacos.client.naming.remote.gprc.redo.data.BatchInstanceRedoData;
import com.alibaba.nacos.client.naming.remote.gprc.redo.data.InstanceRedoData;
import com.alibaba.nacos.client.security.SecurityProxy;
import com.alibaba.nacos.common.notify.Event;
import com.alibaba.nacos.common.notify.NotifyCenter;
@ -49,14 +53,16 @@ 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.utils.CollectionUtils;
import com.alibaba.nacos.common.utils.JacksonUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Collectors;
import static com.alibaba.nacos.client.utils.LogUtils.NAMING_LOGGER;
@ -78,7 +84,7 @@ public class NamingGrpcClientProxy extends AbstractNamingClientProxy {
private final NamingGrpcRedoService redoService;
public NamingGrpcClientProxy(String namespaceId, SecurityProxy securityProxy, ServerListFactory serverListFactory,
Properties properties, ServiceInfoHolder serviceInfoHolder) throws NacosException {
NacosClientProperties properties, ServiceInfoHolder serviceInfoHolder) throws NacosException {
super(securityProxy);
this.namespaceId = namespaceId;
this.uuid = UUID.randomUUID().toString();
@ -124,6 +130,55 @@ public class NamingGrpcClientProxy extends AbstractNamingClientProxy {
doBatchRegisterService(serviceName, groupName, instances);
}
@Override
public void batchDeregisterService(String serviceName, String groupName, List<Instance> instances)
throws NacosException {
List<Instance> retainInstance = getRetainInstance(serviceName, groupName, instances);
batchRegisterService(serviceName, groupName, retainInstance);
}
/**
* Get instance list that need to be Retained.
*
* @param serviceName service name
* @param groupName group name
* @param instances instance list
* @return instance list that need to be deregistered.
*/
private List<Instance> getRetainInstance(String serviceName, String groupName, List<Instance> instances)
throws NacosException {
if (CollectionUtils.isEmpty(instances)) {
throw new NacosException(NacosException.INVALID_PARAM,
String.format("[Batch deRegistration] need deRegister instance is empty, instances: %s,",
instances));
}
String combinedServiceName = NamingUtils.getGroupedName(serviceName, groupName);
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,",
instances));
}
BatchInstanceRedoData batchInstanceRedoData = (BatchInstanceRedoData) instanceRedoData;
List<Instance> allInstance = batchInstanceRedoData.getInstances();
if (CollectionUtils.isEmpty(allInstance)) {
throw new NacosException(NacosException.INVALID_PARAM, String.format(
"[Batch deRegistration] not found all registerInstance , serviceName%s , groupName: %s",
serviceName, groupName));
}
Map<Instance, Instance> instanceMap = instances.stream()
.collect(Collectors.toMap(Function.identity(), Function.identity()));
List<Instance> retainInstances = new ArrayList<>();
for (Instance instance : allInstance) {
if (!instanceMap.containsKey(instance)) {
retainInstances.add(instance);
}
}
return retainInstances;
}
/**
* Execute batch register operation.
*
@ -260,7 +315,8 @@ public class NamingGrpcClientProxy extends AbstractNamingClientProxy {
@Override
public void unsubscribe(String serviceName, String groupName, String clusters) throws NacosException {
if (NAMING_LOGGER.isDebugEnabled()) {
NAMING_LOGGER.debug("[GRPC-UNSUBSCRIBE] service:{}, group:{}, cluster:{} ", serviceName, groupName, clusters);
NAMING_LOGGER
.debug("[GRPC-UNSUBSCRIBE] service:{}, group:{}, cluster:{} ", serviceName, groupName, clusters);
}
redoService.subscriberDeregister(serviceName, groupName, clusters);
doUnsubscribe(serviceName, groupName, clusters);
@ -286,10 +342,6 @@ public class NamingGrpcClientProxy extends AbstractNamingClientProxy {
redoService.removeSubscriberForRedo(serviceName, groupName, clusters);
}
@Override
public void updateBeatInfo(Set<Instance> modifiedInstances) {
}
@Override
public boolean serverHealthy() {
return rpcClient.isRunning();

View File

@ -39,8 +39,8 @@ public class NamingPushRequestHandler implements ServerRequestHandler {
@Override
public Response requestReply(Request request) {
if (request instanceof NotifySubscriberRequest) {
NotifySubscriberRequest notifyResponse = (NotifySubscriberRequest) request;
serviceInfoHolder.processServiceInfo(notifyResponse.getServiceInfo());
NotifySubscriberRequest notifyRequest = (NotifySubscriberRequest) request;
serviceInfoHolder.processServiceInfo(notifyRequest.getServiceInfo());
return new NotifySubscriberResponse();
}
return null;

View File

@ -277,6 +277,14 @@ public class NamingGrpcRedoService implements ConnectionEventListener {
return result;
}
/**
* get Cache service.
* @return cache service
*/
public InstanceRedoData getRegisteredInstancesBykey(String combinedServiceName) {
return registeredInstances.get(combinedServiceName);
}
/**
* Shutdown redo service.
*/

View File

@ -29,11 +29,8 @@ import com.alibaba.nacos.api.selector.AbstractSelector;
import com.alibaba.nacos.api.selector.ExpressionSelector;
import com.alibaba.nacos.api.selector.SelectorType;
import com.alibaba.nacos.api.utils.NetUtils;
import com.alibaba.nacos.client.env.NacosClientProperties;
import com.alibaba.nacos.client.monitor.MetricsMonitor;
import com.alibaba.nacos.client.naming.beat.BeatInfo;
import com.alibaba.nacos.client.naming.beat.BeatReactor;
import com.alibaba.nacos.client.naming.cache.ServiceInfoHolder;
import com.alibaba.nacos.client.naming.core.PushReceiver;
import com.alibaba.nacos.client.naming.core.ServerListManager;
import com.alibaba.nacos.client.naming.event.ServerListChangedEvent;
import com.alibaba.nacos.client.naming.remote.AbstractNamingClientProxy;
@ -59,9 +56,7 @@ import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.Set;
import static com.alibaba.nacos.client.utils.LogUtils.NAMING_LOGGER;
import static com.alibaba.nacos.common.constant.RequestUrlConstants.HTTPS_PREFIX;
@ -103,29 +98,23 @@ public class NamingHttpClientProxy extends AbstractNamingClientProxy {
private static final String CLIENT_IP_PARAM = "clientIP";
private static final String HEALTHY_ONLY_PARAM = "healthyOnly";
private static final String REGISTER_ENABLE_PARAM = "enable";
private final String namespaceId;
private final ServerListManager serverListManager;
private final BeatReactor beatReactor;
private final PushReceiver pushReceiver;
private final int maxRetry;
private int serverPort = DEFAULT_SERVER_PORT;
public NamingHttpClientProxy(String namespaceId, SecurityProxy securityProxy, ServerListManager serverListManager,
Properties properties, ServiceInfoHolder serviceInfoHolder) {
NacosClientProperties properties) {
super(securityProxy);
this.serverListManager = serverListManager;
this.setServerPort(DEFAULT_SERVER_PORT);
this.namespaceId = namespaceId;
this.beatReactor = new BeatReactor(this, properties);
this.pushReceiver = new PushReceiver(serviceInfoHolder);
this.maxRetry = ConvertUtils.toInt(properties.getProperty(PropertyKeyConst.NAMING_REQUEST_DOMAIN_RETRY_COUNT,
String.valueOf(UtilAndComs.REQUEST_DOMAIN_RETRY_COUNT)));
}
@ -142,13 +131,12 @@ public class NamingHttpClientProxy extends AbstractNamingClientProxy {
@Override
public void registerService(String serviceName, String groupName, Instance instance) throws NacosException {
NAMING_LOGGER.info("[REGISTER-SERVICE] {} registering service {} with instance: {}", namespaceId, serviceName,
instance);
String groupedServiceName = NamingUtils.getGroupedName(serviceName, groupName);
if (instance.isEphemeral()) {
BeatInfo beatInfo = beatReactor.buildBeatInfo(groupedServiceName, instance);
beatReactor.addBeatInfo(groupedServiceName, beatInfo);
throw new UnsupportedOperationException(
"Do not support register ephemeral instances by HTTP, please use gRPC replaced.");
}
final Map<String, String> params = new HashMap<>(32);
params.put(CommonParams.NAMESPACE_ID, namespaceId);
@ -162,14 +150,20 @@ public class NamingHttpClientProxy extends AbstractNamingClientProxy {
params.put(HEALTHY_PARAM, String.valueOf(instance.isHealthy()));
params.put(EPHEMERAL_PARAM, String.valueOf(instance.isEphemeral()));
params.put(META_PARAM, JacksonUtils.toJson(instance.getMetadata()));
reqApi(UtilAndComs.nacosUrlInstance, params, HttpMethod.POST);
}
@Override
public void batchRegisterService(String serviceName, String groupName, List<Instance> instances) {
throw new UnsupportedOperationException("Do not support persistent instances to perform batch registration methods.");
throw new UnsupportedOperationException(
"Do not support persistent instances to perform batch registration methods.");
}
@Override
public void batchDeregisterService(String serviceName, String groupName, List<Instance> instances)
throws NacosException {
throw new UnsupportedOperationException(
"Do not support persistent instances to perform batch de registration methods.");
}
@Override
@ -178,8 +172,7 @@ public class NamingHttpClientProxy extends AbstractNamingClientProxy {
.info("[DEREGISTER-SERVICE] {} deregistering service {} with instance: {}", namespaceId, serviceName,
instance);
if (instance.isEphemeral()) {
beatReactor.removeBeatInfo(NamingUtils.getGroupedName(serviceName, groupName), instance.getIp(),
instance.getPort());
return;
}
final Map<String, String> params = new HashMap<>(16);
params.put(CommonParams.NAMESPACE_ID, namespaceId);
@ -288,39 +281,11 @@ public class NamingHttpClientProxy extends AbstractNamingClientProxy {
reqApi(UtilAndComs.nacosUrlService, params, HttpMethod.PUT);
}
/**
* Send beat.
*
* @param beatInfo beat info
* @param lightBeatEnabled light beat
* @return beat result
* @throws NacosException nacos exception
*/
public JsonNode sendBeat(BeatInfo beatInfo, boolean lightBeatEnabled) throws NacosException {
if (NAMING_LOGGER.isDebugEnabled()) {
NAMING_LOGGER.debug("[BEAT] {} sending beat to server: {}", namespaceId, beatInfo.toString());
}
Map<String, String> params = new HashMap<>(16);
Map<String, String> bodyMap = new HashMap<>(2);
if (!lightBeatEnabled) {
bodyMap.put("beat", JacksonUtils.toJson(beatInfo));
}
params.put(CommonParams.NAMESPACE_ID, namespaceId);
params.put(CommonParams.SERVICE_NAME, beatInfo.getServiceName());
params.put(CommonParams.CLUSTER_NAME, beatInfo.getCluster());
params.put(IP_PARAM, beatInfo.getIp());
params.put(PORT_PARAM, String.valueOf(beatInfo.getPort()));
String result = reqApi(UtilAndComs.nacosUrlBase + "/instance/beat", params, bodyMap, HttpMethod.PUT);
return JacksonUtils.toObj(result);
}
@Override
public boolean serverHealthy() {
try {
String result = reqApi(UtilAndComs.nacosUrlBase + "/operator/metrics", new HashMap<>(8),
HttpMethod.GET);
String result = reqApi(UtilAndComs.nacosUrlBase + "/operator/metrics", new HashMap<>(8), HttpMethod.GET);
JsonNode json = JacksonUtils.toObj(result);
String serverStatus = json.get("status").asText();
return "UP".equals(serverStatus);
@ -365,7 +330,7 @@ public class NamingHttpClientProxy extends AbstractNamingClientProxy {
@Override
public ServiceInfo subscribe(String serviceName, String groupName, String clusters) throws NacosException {
return queryInstancesOfService(serviceName, groupName, clusters, pushReceiver.getUdpPort(), false);
throw new UnsupportedOperationException("Do not support subscribe service by UDP, please use gRPC replaced.");
}
@Override
@ -377,17 +342,6 @@ public class NamingHttpClientProxy extends AbstractNamingClientProxy {
return true;
}
@Override
public void updateBeatInfo(Set<Instance> modifiedInstances) {
for (Instance instance : modifiedInstances) {
String key = beatReactor.buildKey(instance.getServiceName(), instance.getIp(), instance.getPort());
if (beatReactor.dom2Beat.containsKey(key) && instance.isEphemeral()) {
BeatInfo beatInfo = beatReactor.buildBeatInfo(instance);
beatReactor.addBeatInfo(instance.getServiceName(), beatInfo);
}
}
}
public String reqApi(String api, Map<String, String> params, String method) throws NacosException {
return reqApi(api, params, Collections.EMPTY_MAP, method);
}
@ -432,7 +386,7 @@ public class NamingHttpClientProxy extends AbstractNamingClientProxy {
}
}
} else {
Random random = new Random(System.currentTimeMillis());
Random random = new Random();
int index = random.nextInt(servers.size());
for (int i = 0; i < servers.size(); i++) {
@ -491,7 +445,7 @@ public class NamingHttpClientProxy extends AbstractNamingClientProxy {
HttpRestResult<String> restResult = nacosRestTemplate
.exchangeForm(url, header, Query.newInstance().initParams(params), body, method, String.class);
end = System.currentTimeMillis();
MetricsMonitor.getNamingRequestMonitor(method, url, String.valueOf(restResult.getCode()))
.observe(end - start);
@ -518,21 +472,16 @@ public class NamingHttpClientProxy extends AbstractNamingClientProxy {
public void setServerPort(int serverPort) {
this.serverPort = serverPort;
String sp = System.getProperty(SystemPropertyKeyConst.NAMING_SERVER_PORT);
String sp = NacosClientProperties.PROTOTYPE.getProperty(SystemPropertyKeyConst.NAMING_SERVER_PORT);
if (StringUtils.isNotBlank(sp)) {
this.serverPort = Integer.parseInt(sp);
}
}
public BeatReactor getBeatReactor() {
return this.beatReactor;
}
@Override
public void shutdown() throws NacosException {
String className = this.getClass().getName();
NAMING_LOGGER.info("{} do shutdown begin", className);
beatReactor.shutdown();
NamingHttpClientManager.getInstance().shutdown();
NAMING_LOGGER.info("{} do shutdown stop", className);
}

View File

@ -69,6 +69,10 @@ public class Chooser<K, T> {
}
}
if (ref.weights.length == 0) {
throw new IllegalStateException("Cumulative Weight wrong , the array length is equal to 0.");
}
/* This should never happen, but it ensures we will return a correct
* object in case there is some floating point inequality problem
* wrt the cumulative probabilities. */
@ -117,7 +121,9 @@ public class Chooser<K, T> {
private double[] weights;
public Ref(List<Pair<T>> itemsWithWeight) {
this.itemsWithWeight = itemsWithWeight;
if (itemsWithWeight != null) {
this.itemsWithWeight = itemsWithWeight;
}
}
/**
@ -125,7 +131,7 @@ public class Chooser<K, T> {
*/
public void refresh() {
Double originWeightSum = (double) 0;
int size = 0;
for (Pair<T> item : itemsWithWeight) {
double weight = item.weight();
@ -142,9 +148,12 @@ public class Chooser<K, T> {
weight = 1.0D;
}
originWeightSum += weight;
size++;
}
double[] exactWeights = new double[items.size()];
weights = new double[size];
double exactWeight;
double randomRange = 0D;
int index = 0;
for (Pair<T> item : itemsWithWeight) {
double singleWeight = item.weight();
@ -152,14 +161,10 @@ public class Chooser<K, T> {
if (singleWeight <= 0) {
continue;
}
exactWeights[index++] = singleWeight / originWeightSum;
}
weights = new double[items.size()];
double randomRange = 0D;
for (int i = 0; i < index; i++) {
weights[i] = randomRange + exactWeights[i];
randomRange += exactWeights[i];
exactWeight = singleWeight / originWeightSum;
weights[index] = randomRange + exactWeight;
randomRange = weights[index++];
}
double doublePrecisionDelta = 0.0001;

View File

@ -22,6 +22,7 @@ import com.alibaba.nacos.api.common.Constants;
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.utils.ContextPathUtil;
import com.alibaba.nacos.client.utils.LogUtils;
import com.alibaba.nacos.client.utils.ParamUtil;
@ -30,8 +31,6 @@ import com.alibaba.nacos.client.utils.TenantUtil;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.common.utils.StringUtils;
import java.util.Properties;
/**
* Init utils.
*
@ -49,11 +48,11 @@ public class InitUtils {
* @param properties properties
* @return namespace
*/
public static String initNamespaceForNaming(Properties properties) {
public static String initNamespaceForNaming(NacosClientProperties properties) {
String tmpNamespace = null;
String isUseCloudNamespaceParsing = properties.getProperty(PropertyKeyConst.IS_USE_CLOUD_NAMESPACE_PARSING,
System.getProperty(SystemPropertyKeyConst.IS_USE_CLOUD_NAMESPACE_PARSING,
properties.getProperty(SystemPropertyKeyConst.IS_USE_CLOUD_NAMESPACE_PARSING,
String.valueOf(Constants.DEFAULT_USE_CLOUD_NAMESPACE_PARSING)));
if (Boolean.parseBoolean(isUseCloudNamespaceParsing)) {
@ -62,14 +61,14 @@ public class InitUtils {
LogUtils.NAMING_LOGGER.info("initializer namespace from System Property : {}", tmpNamespace);
tmpNamespace = TemplateUtils.stringEmptyAndThenExecute(tmpNamespace, () -> {
String namespace = System.getenv(PropertyKeyConst.SystemEnv.ALIBABA_ALIWARE_NAMESPACE);
String namespace = properties.getProperty(PropertyKeyConst.SystemEnv.ALIBABA_ALIWARE_NAMESPACE);
LogUtils.NAMING_LOGGER.info("initializer namespace from System Environment :" + namespace);
return namespace;
});
}
tmpNamespace = TemplateUtils.stringEmptyAndThenExecute(tmpNamespace, () -> {
String namespace = System.getProperty(PropertyKeyConst.NAMESPACE);
String namespace = properties.getProperty(PropertyKeyConst.NAMESPACE);
LogUtils.NAMING_LOGGER.info("initializer namespace from System Property :" + namespace);
return namespace;
});
@ -88,28 +87,13 @@ public class InitUtils {
* @param properties properties
* @since 1.4.1
*/
public static void initWebRootContext(Properties properties) {
public static void initWebRootContext(NacosClientProperties properties) {
final String webContext = properties.getProperty(PropertyKeyConst.CONTEXT_PATH);
TemplateUtils.stringNotEmptyAndThenExecute(webContext, () -> {
UtilAndComs.webContext = ContextPathUtil.normalizeContextPath(webContext);
UtilAndComs.nacosUrlBase = UtilAndComs.webContext + "/v1/ns";
UtilAndComs.nacosUrlInstance = UtilAndComs.nacosUrlBase + "/instance";
});
initWebRootContext();
}
/**
* Init web root context.
*/
@Deprecated
public static void initWebRootContext() {
// support the web context with ali-yun if the app deploy by EDAS
final String webContext = System.getProperty(SystemPropertyKeyConst.NAMING_WEB_CONTEXT);
TemplateUtils.stringNotEmptyAndThenExecute(webContext, () -> {
UtilAndComs.webContext = ContextPathUtil.normalizeContextPath(webContext);
UtilAndComs.nacosUrlBase = UtilAndComs.webContext + "/v1/ns";
UtilAndComs.nacosUrlInstance = UtilAndComs.nacosUrlBase + "/instance";
});
}
/**
@ -118,14 +102,14 @@ public class InitUtils {
* @param properties properties
* @return end point
*/
public static String initEndpoint(final Properties properties) {
public static String initEndpoint(final NacosClientProperties properties) {
if (properties == null) {
return "";
}
// Whether to enable domain name resolution rules
String isUseEndpointRuleParsing = properties.getProperty(PropertyKeyConst.IS_USE_ENDPOINT_PARSING_RULE,
System.getProperty(SystemPropertyKeyConst.IS_USE_ENDPOINT_PARSING_RULE,
properties.getProperty(SystemPropertyKeyConst.IS_USE_ENDPOINT_PARSING_RULE,
String.valueOf(ParamUtil.USE_ENDPOINT_PARSING_RULE_DEFAULT_VALUE)));
boolean isUseEndpointParsingRule = Boolean.parseBoolean(isUseEndpointRuleParsing);
@ -145,7 +129,7 @@ public class InitUtils {
}
String endpointPort = TemplateUtils
.stringEmptyAndThenExecute(System.getenv(PropertyKeyConst.SystemEnv.ALIBABA_ALIWARE_ENDPOINT_PORT),
.stringEmptyAndThenExecute(properties.getProperty(PropertyKeyConst.SystemEnv.ALIBABA_ALIWARE_ENDPOINT_PORT),
() -> properties.getProperty(PropertyKeyConst.ENDPOINT_PORT));
endpointPort = TemplateUtils.stringEmptyAndThenExecute(endpointPort, () -> DEFAULT_END_POINT_PORT);

View File

@ -17,7 +17,6 @@
package com.alibaba.nacos.client.naming.utils;
import com.alibaba.nacos.common.utils.ThreadUtils;
import com.alibaba.nacos.common.utils.VersionUtils;
/**
* Util and constants.
@ -26,10 +25,6 @@ import com.alibaba.nacos.common.utils.VersionUtils;
*/
public class UtilAndComs {
// using com.alibaba.nacos.common.utils.VersionUtils.getFullClientVersion instead.
@Deprecated
public static final String VERSION = VersionUtils.getFullClientVersion();
public static String webContext = "/nacos";
public static String nacosUrlBase = webContext + "/v1/ns";
@ -52,9 +47,6 @@ public class UtilAndComs {
public static final String NACOS_NAMING_LOG_LEVEL = "com.alibaba.nacos.naming.log.level";
public static final int DEFAULT_CLIENT_BEAT_THREAD_COUNT =
ThreadUtils.getSuitableThreadCount(1) > 1 ? ThreadUtils.getSuitableThreadCount(1) / 2 : 1;
public static final int DEFAULT_POLLING_THREAD_COUNT =
ThreadUtils.getSuitableThreadCount(1) > 1 ? ThreadUtils.getSuitableThreadCount(1) / 2 : 1;

View File

@ -17,6 +17,7 @@
package com.alibaba.nacos.client.utils;
import com.alibaba.nacos.client.constant.Constants;
import com.alibaba.nacos.client.env.NacosClientProperties;
import com.alibaba.nacos.common.utils.StringUtils;
import java.io.File;
@ -63,17 +64,17 @@ public class AppNameUtils {
}
private static String getAppNameByProjectName() {
return System.getProperty(Constants.SysEnv.PROJECT_NAME);
return NacosClientProperties.PROTOTYPE.getProperty(Constants.SysEnv.PROJECT_NAME);
}
private static String getAppNameByServerHome() {
String serverHome = null;
if (SERVER_JBOSS.equals(getServerType())) {
serverHome = System.getProperty(PARAM_MARKING_JBOSS);
serverHome = NacosClientProperties.PROTOTYPE.getProperty(PARAM_MARKING_JBOSS);
} else if (SERVER_JETTY.equals(getServerType())) {
serverHome = System.getProperty(PARAM_MARKING_JETTY);
serverHome = NacosClientProperties.PROTOTYPE.getProperty(PARAM_MARKING_JETTY);
} else if (SERVER_TOMCAT.equals(getServerType())) {
serverHome = System.getProperty(PARAM_MARKING_TOMCAT);
serverHome = NacosClientProperties.PROTOTYPE.getProperty(PARAM_MARKING_TOMCAT);
}
if (serverHome != null && serverHome.startsWith(LINUX_ADMIN_HOME)) {
@ -85,11 +86,11 @@ public class AppNameUtils {
private static String getServerType() {
String serverType;
if (System.getProperty(PARAM_MARKING_JBOSS) != null) {
if (NacosClientProperties.PROTOTYPE.getProperty(PARAM_MARKING_JBOSS) != null) {
serverType = SERVER_JBOSS;
} else if (System.getProperty(PARAM_MARKING_JETTY) != null) {
} else if (NacosClientProperties.PROTOTYPE.getProperty(PARAM_MARKING_JETTY) != null) {
serverType = SERVER_JETTY;
} else if (System.getProperty(PARAM_MARKING_TOMCAT) != null) {
} else if (NacosClientProperties.PROTOTYPE.getProperty(PARAM_MARKING_TOMCAT) != null) {
serverType = SERVER_TOMCAT;
} else {
serverType = SERVER_UNKNOWN;

View File

@ -19,11 +19,11 @@ package com.alibaba.nacos.client.utils;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.SystemPropertyKeyConst;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.client.env.NacosClientProperties;
import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.common.utils.VersionUtils;
import org.slf4j.Logger;
import java.util.Properties;
import java.util.regex.Pattern;
/**
@ -77,18 +77,18 @@ public class ParamUtil {
static {
// Client identity information
appKey = System.getProperty(NACOS_CLIENT_APP_KEY, BLANK_STR);
appKey = NacosClientProperties.PROTOTYPE.getProperty(NACOS_CLIENT_APP_KEY, BLANK_STR);
defaultContextPath = System.getProperty(NACOS_CLIENT_CONTEXTPATH_KEY, DEFAULT_NACOS_CLIENT_CONTEXTPATH);
defaultContextPath = NacosClientProperties.PROTOTYPE.getProperty(NACOS_CLIENT_CONTEXTPATH_KEY, DEFAULT_NACOS_CLIENT_CONTEXTPATH);
appName = AppNameUtils.getAppName();
serverPort = System.getProperty(NACOS_SERVER_PORT_KEY, DEFAULT_SERVER_PORT);
serverPort = NacosClientProperties.PROTOTYPE.getProperty(NACOS_SERVER_PORT_KEY, DEFAULT_SERVER_PORT);
LOGGER.info("[settings] [req-serv] nacos-server port:{}", serverPort);
String tmp = "1000";
try {
tmp = System.getProperty(NACOS_CONNECT_TIMEOUT_KEY, DEFAULT_NACOS_CONNECT_TIMEOUT);
tmp = NacosClientProperties.PROTOTYPE.getProperty(NACOS_CONNECT_TIMEOUT_KEY, DEFAULT_NACOS_CONNECT_TIMEOUT);
connectTimeout = Integer.parseInt(tmp);
} catch (NumberFormatException e) {
final String msg = "[http-client] invalid connect timeout:" + tmp;
@ -101,7 +101,7 @@ public class ParamUtil {
try {
perTaskConfigSize = Double
.parseDouble(System.getProperty(PER_TASK_CONFIG_SIZE_KEY, DEFAULT_PER_TASK_CONFIG_SIZE_KEY));
.parseDouble(NacosClientProperties.PROTOTYPE.getProperty(PER_TASK_CONFIG_SIZE_KEY, DEFAULT_PER_TASK_CONFIG_SIZE_KEY));
LOGGER.info("PER_TASK_CONFIG_SIZE: {}", perTaskConfigSize);
} catch (Throwable t) {
LOGGER.error("[PER_TASK_CONFIG_SIZE] PER_TASK_CONFIG_SIZE invalid", t);
@ -174,18 +174,18 @@ public class ParamUtil {
* @param properties properties
* @return namespace
*/
public static String parseNamespace(Properties properties) {
public static String parseNamespace(NacosClientProperties properties) {
String namespaceTmp = null;
String isUseCloudNamespaceParsing = properties.getProperty(PropertyKeyConst.IS_USE_CLOUD_NAMESPACE_PARSING,
System.getProperty(SystemPropertyKeyConst.IS_USE_CLOUD_NAMESPACE_PARSING,
properties.getProperty(SystemPropertyKeyConst.IS_USE_CLOUD_NAMESPACE_PARSING,
String.valueOf(Constants.DEFAULT_USE_CLOUD_NAMESPACE_PARSING)));
if (Boolean.parseBoolean(isUseCloudNamespaceParsing)) {
namespaceTmp = TenantUtil.getUserTenantForAcm();
namespaceTmp = TemplateUtils.stringBlankAndThenExecute(namespaceTmp, () -> {
String namespace = System.getenv(PropertyKeyConst.SystemEnv.ALIBABA_ALIWARE_NAMESPACE);
String namespace = properties.getProperty(PropertyKeyConst.SystemEnv.ALIBABA_ALIWARE_NAMESPACE);
return StringUtils.isNotBlank(namespace) ? namespace : StringUtils.EMPTY;
});
}
@ -206,7 +206,7 @@ public class ParamUtil {
// If entered in the configuration file, the priority in ENV will be given priority.
if (endpointUrl == null || !PATTERN.matcher(endpointUrl).find()) {
// skip retrieve from system property and retrieve directly from system env
String endpointUrlSource = System.getenv(PropertyKeyConst.SystemEnv.ALIBABA_ALIWARE_ENDPOINT_URL);
String endpointUrlSource = NacosClientProperties.PROTOTYPE.getProperty(PropertyKeyConst.SystemEnv.ALIBABA_ALIWARE_ENDPOINT_URL);
if (StringUtils.isNotBlank(endpointUrlSource)) {
endpointUrl = endpointUrlSource;
}
@ -223,8 +223,8 @@ public class ParamUtil {
}
String endpointUrlSource = TemplateUtils
.stringBlankAndThenExecute(System.getProperty(endpointUrl, System.getenv(endpointUrl)),
() -> System.getenv(PropertyKeyConst.SystemEnv.ALIBABA_ALIWARE_ENDPOINT_URL));
.stringBlankAndThenExecute(NacosClientProperties.PROTOTYPE.getProperty(endpointUrl, System.getenv(endpointUrl)),
() -> NacosClientProperties.PROTOTYPE.getProperty(PropertyKeyConst.SystemEnv.ALIBABA_ALIWARE_ENDPOINT_URL));
if (StringUtils.isBlank(endpointUrlSource)) {
if (StringUtils.isNotBlank(defaultEndpointUrl)) {

View File

@ -17,6 +17,7 @@
package com.alibaba.nacos.client.utils;
import com.alibaba.nacos.api.SystemPropertyKeyConst;
import com.alibaba.nacos.client.env.NacosClientProperties;
import com.alibaba.nacos.common.utils.StringUtils;
/**
@ -35,7 +36,7 @@ public class TenantUtil {
private static final String ACM_NAMESPACE_PROPERTY = "acm.namespace";
static {
USER_TENANT = System.getProperty(TENANT_ID, "");
USER_TENANT = NacosClientProperties.PROTOTYPE.getProperty(TENANT_ID, "");
}
/**
@ -51,7 +52,7 @@ public class TenantUtil {
String tmp = USER_TENANT;
if (StringUtils.isBlank(USER_TENANT)) {
tmp = System.getProperty(ACM_NAMESPACE_PROPERTY, DEFAULT_ACM_NAMESPACE);
tmp = NacosClientProperties.PROTOTYPE.getProperty(ACM_NAMESPACE_PROPERTY, DEFAULT_ACM_NAMESPACE);
}
return tmp;
@ -66,7 +67,7 @@ public class TenantUtil {
String tmp = USER_TENANT;
if (StringUtils.isBlank(USER_TENANT)) {
tmp = System.getProperty(SystemPropertyKeyConst.ANS_NAMESPACE);
tmp = NacosClientProperties.PROTOTYPE.getProperty(SystemPropertyKeyConst.ANS_NAMESPACE);
}
return tmp;
}

View File

@ -18,8 +18,8 @@ package com.alibaba.nacos.client.utils;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.client.env.NacosClientProperties;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@ -32,7 +32,7 @@ public final class ValidatorUtils {
private static final Pattern CONTEXT_PATH_MATCH = Pattern.compile("(\\/)\\1+");
public static void checkInitParam(Properties properties) throws NacosException {
public static void checkInitParam(NacosClientProperties properties) throws NacosException {
checkContextPath(properties.getProperty(PropertyKeyConst.CONTEXT_PATH));
}

View File

@ -17,59 +17,59 @@
<Configuration status="WARN">
<Appenders>
<RollingFile name="CONFIG_LOG_FILE" fileName="${sys:JM.LOG.PATH}/nacos/config.log"
filePattern="${sys:JM.LOG.PATH}/nacos/config.log.%d{yyyy-MM-dd}.%i">
<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">
<PatternLayout>
<Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %p [%-5t:%c{2}] %m%n</Pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy/>
<SizeBasedTriggeringPolicy size="${sys:JM.LOG.FILE.SIZE:-10MB}"/>
<SizeBasedTriggeringPolicy size="${nacosClientProperty:JM.LOG.FILE.SIZE:-10MB}"/>
</Policies>
<DefaultRolloverStrategy max="${sys:JM.LOG.RETAIN.COUNT:-7}">
<Delete basePath="${sys:JM.LOG.PATH}/nacos" maxDepth="1" testMode="${sys:JM.LOG.RETAIN.DURATION.OFF:-true}">
<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}">
<IfFileName glob="config.log.*.*" />
<IfLastModified age="${sys:JM.LOG.RETAIN.DURATION:-P180D}" />
<IfLastModified age="${nacosClientProperty:JM.LOG.RETAIN.DURATION:-P180D}" />
</Delete>
</DefaultRolloverStrategy>
</RollingFile>
<RollingFile name="REMOTE_LOG_FILE" fileName="${sys:JM.LOG.PATH}/nacos/remote.log"
filePattern="${sys:JM.LOG.PATH}/nacos/remote.log.%d{yyyy-MM-dd}.%i">
<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">
<PatternLayout>
<Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %p [%-5t:%c{2}] %m%n</Pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy/>
<SizeBasedTriggeringPolicy size="${sys:JM.LOG.FILE.SIZE:-10MB}"/>
<SizeBasedTriggeringPolicy size="${nacosClientProperty:JM.LOG.FILE.SIZE:-10MB}"/>
</Policies>
<DefaultRolloverStrategy max="${sys:JM.LOG.RETAIN.COUNT:-7}">
<Delete basePath="${sys:JM.LOG.PATH}/nacos" maxDepth="1" testMode="${sys:JM.LOG.RETAIN.DURATION.OFF:-true}">
<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}">
<IfFileName glob="remote.log.*.*" />
<IfLastModified age="${sys:JM.LOG.RETAIN.DURATION:-P180D}" />
<IfLastModified age="${nacosClientProperty:JM.LOG.RETAIN.DURATION:-P180D}" />
</Delete>
</DefaultRolloverStrategy>
</RollingFile>
<RollingFile name="NAMING_LOG_FILE" fileName="${sys:JM.LOG.PATH}/nacos/naming.log"
filePattern="${sys:JM.LOG.PATH}/nacos/naming.log.%d{yyyy-MM-dd}.%i">
<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">
<PatternLayout>
<Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %p [%-5t:%c{2}] %m%n</Pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy/>
<SizeBasedTriggeringPolicy size="${sys:JM.LOG.FILE.SIZE:-10MB}"/>
<SizeBasedTriggeringPolicy size="${nacosClientProperty:JM.LOG.FILE.SIZE:-10MB}"/>
</Policies>
<DefaultRolloverStrategy max="${sys:JM.LOG.RETAIN.COUNT:-7}">
<Delete basePath="${sys:JM.LOG.PATH}/nacos" maxDepth="1" testMode="${sys:JM.LOG.RETAIN.DURATION.OFF:-true}">
<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}">
<IfFileName glob="naming.log.*.*" />
<IfLastModified age="${sys:JM.LOG.RETAIN.DURATION:-P180D}" />
<IfLastModified age="${nacosClientProperty:JM.LOG.RETAIN.DURATION:-P180D}" />
</Delete>
</DefaultRolloverStrategy>
@ -77,22 +77,22 @@
</Appenders>
<Loggers>
<Logger name="com.alibaba.nacos.client" level="${sys:com.alibaba.nacos.config.log.level:-info}"
<Logger name="com.alibaba.nacos.client" level="${nacosClientProperty:com.alibaba.nacos.config.log.level:-info}"
additivity="false">
<AppenderRef ref="CONFIG_LOG_FILE"/>
</Logger>
<Logger name="com.alibaba.nacos.common.remote.client" level="${sys:com.alibaba.nacos.config.log.level:-info}"
<Logger name="com.alibaba.nacos.common.remote.client" level="${nacosClientProperty:com.alibaba.nacos.config.log.level:-info}"
additivity="false">
<AppenderRef ref="REMOTE_LOG_FILE"/>
</Logger>
<Logger name="com.alibaba.nacos.client.config" level="${sys:com.alibaba.nacos.config.log.level:-info}"
<Logger name="com.alibaba.nacos.client.config" level="${nacosClientProperty:com.alibaba.nacos.config.log.level:-info}"
additivity="false">
<AppenderRef ref="CONFIG_LOG_FILE"/>
</Logger>
<Logger name="com.alibaba.nacos.client.naming" level="${sys:com.alibaba.nacos.naming.log.level:-info}"
<Logger name="com.alibaba.nacos.client.naming" level="${nacosClientProperty:com.alibaba.nacos.naming.log.level:-info}"
additivity="false">
<AppenderRef ref="NAMING_LOG_FILE"/>
</Logger>

View File

@ -16,17 +16,22 @@
-->
<configuration debug="false" scan="false" packagingData="true">
<nacosClientProperty scope="context" name="logPath" source="JM.LOG.PATH"/>
<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"/>
<appender name="CONFIG_LOG_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${JM.LOG.PATH}/nacos/config.log</file>
<file>${logPath}/nacos/config.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
<fileNamePattern>${JM.LOG.PATH}/nacos/config.log.%i</fileNamePattern>
<maxIndex>${JM.LOG.RETAIN.COUNT:-7}</maxIndex>
<fileNamePattern>${logPath}/nacos/config.log.%i</fileNamePattern>
<maxIndex>${logRetainCount}</maxIndex>
</rollingPolicy>
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<maxFileSize>${JM.LOG.FILE.SIZE:-10MB}</maxFileSize>
<maxFileSize>${logFileSize}</maxFileSize>
</triggeringPolicy>
<encoder>
@ -35,15 +40,15 @@
</appender>
<appender name="NAMING_LOG_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${JM.LOG.PATH}/nacos/naming.log</file>
<file>${logPath}/nacos/naming.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
<fileNamePattern>${JM.LOG.PATH}/nacos/naming.log.%i</fileNamePattern>
<maxIndex>${JM.LOG.RETAIN.COUNT:-7}</maxIndex>
<fileNamePattern>${logPath}/nacos/naming.log.%i</fileNamePattern>
<maxIndex>${logRetainCount}</maxIndex>
</rollingPolicy>
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<maxFileSize>${JM.LOG.FILE.SIZE:-10MB}</maxFileSize>
<maxFileSize>${logFileSize}</maxFileSize>
</triggeringPolicy>
<encoder>
@ -52,15 +57,15 @@
</appender>
<appender name="REMOTE_LOG_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${JM.LOG.PATH}/nacos/remote.log</file>
<file>${logPath}/nacos/remote.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
<fileNamePattern>${JM.LOG.PATH}/nacos/remote.log.%i</fileNamePattern>
<maxIndex>${JM.LOG.RETAIN.COUNT:-7}</maxIndex>
<fileNamePattern>${logPath}/nacos/remote.log.%i</fileNamePattern>
<maxIndex>${logRetainCount}</maxIndex>
</rollingPolicy>
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<maxFileSize>${JM.LOG.FILE.SIZE:-10MB}</maxFileSize>
<maxFileSize>${logFileSize}</maxFileSize>
</triggeringPolicy>
<encoder>
@ -69,28 +74,28 @@
</appender>
<logger name="com.alibaba.nacos.client" level="${com.alibaba.nacos.config.log.level:-info}"
<logger name="com.alibaba.nacos.client" level="${nacosConfigLogLevel}"
additivity="false">
<appender-ref ref="CONFIG_LOG_FILE"/>
</logger>
<Logger name="com.alibaba.nacos.common.remote.client" level="${com.alibaba.nacos.log.level:-info}"
<Logger name="com.alibaba.nacos.common.remote.client" level="${nacosConfigLogLevel}"
additivity="false">
<appender-ref ref="REMOTE_LOG_FILE"/>
</Logger>
<Logger name="com.alibaba.nacos.shaded.io.grpc" level="${com.alibaba.nacos.log.level:-info}"
<Logger name="com.alibaba.nacos.shaded.io.grpc" level="${nacosConfigLogLevel}"
additivity="false">
<appender-ref ref="REMOTE_LOG_FILE"/>
</Logger>
<logger name="com.alibaba.nacos.client.config" level="${com.alibaba.nacos.config.log.level:-info}"
<logger name="com.alibaba.nacos.client.config" level="${nacosConfigLogLevel}"
additivity="false">
<appender-ref ref="CONFIG_LOG_FILE"/>
</logger>
<logger name="com.alibaba.nacos.client.naming" level="${com.alibaba.nacos.naming.log.level:-info}"
<logger name="com.alibaba.nacos.client.naming" level="${nacosConfigLogLevel}"
additivity="false">
<appender-ref ref="NAMING_LOG_FILE"/>
</logger>

View File

@ -1,36 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.client;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
public class AppTest extends TestCase {
public AppTest(String testName) {
super(testName);
}
public static Test suite() {
return new TestSuite(AppTest.class);
}
public void testApp() {
assertTrue(true);
}
}

View File

@ -1,67 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.client;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.common.utils.ThreadUtils;
import org.junit.Ignore;
import org.junit.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
@Ignore
public class NamingTest {
@Test
public void testServiceList() throws Exception {
Properties properties = new Properties();
properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1:8848");
properties.put(PropertyKeyConst.USERNAME, "nacos");
properties.put(PropertyKeyConst.PASSWORD, "nacos");
Instance instance = new Instance();
instance.setIp("1.1.1.1");
instance.setPort(800);
instance.setWeight(2);
Map<String, String> map = new HashMap<String, String>();
map.put("netType", "external");
map.put("version", "2.0");
instance.setMetadata(map);
NamingService namingService = NacosFactory.createNamingService(properties);
namingService.registerInstance("nacos.test.1", instance);
ThreadUtils.sleep(5000L);
List<Instance> list = namingService.getAllInstances("nacos.test.1");
System.out.println(list);
ThreadUtils.sleep(30000L);
// ExpressionSelector expressionSelector = new ExpressionSelector();
// expressionSelector.setExpression("INSTANCE.metadata.registerSource = 'dubbo'");
// ListView<String> serviceList = namingService.getServicesOfServer(1, 10, expressionSelector);
}
}

View File

@ -116,31 +116,4 @@ public class CredentialServiceTest extends TestCase {
Assert.assertEquals(expect, actual);
}
@Test
public void testGetAkAndSk() {
CredentialService credentialService1 = CredentialService.getInstance();
Credentials c = new Credentials();
c.setAccessKey("ak");
c.setSecretKey("sk");
credentialService1.setCredential(c);
Assert.assertEquals("ak", credentialService1.getAccessKey());
Assert.assertEquals("sk", credentialService1.getSecretKey());
}
@Test
public void testSetSecretKey() {
CredentialService credentialService1 = CredentialService.getInstance();
Credentials c = new Credentials();
c.setAccessKey("ak");
c.setSecretKey("sk");
credentialService1.setCredential(c);
credentialService1.setAccessKey("ak1");
credentialService1.setSecretKey("sk1");
Assert.assertEquals("ak1", credentialService1.getAccessKey());
Assert.assertEquals("sk1", credentialService1.getSecretKey());
}
}

View File

@ -24,6 +24,7 @@ import com.alibaba.nacos.client.config.impl.ClientWorker;
import com.alibaba.nacos.client.config.impl.ConfigTransportClient;
import com.alibaba.nacos.client.config.impl.LocalConfigInfoProcessor;
import com.alibaba.nacos.client.config.impl.ServerListManager;
import com.alibaba.nacos.client.env.NacosClientProperties;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
@ -101,7 +102,8 @@ public class NacosConfigServiceTest {
response.setContent(content);
response.setConfigType("bb");
Mockito.when(mockWoker.getServerConfig(dataId, group, "", timeout, false)).thenReturn(response);
Mockito.when(mockWoker.getAgent()).thenReturn(new ConfigTransportClient(new Properties(), new ServerListManager()) {
final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(new Properties());
Mockito.when(mockWoker.getAgent()).thenReturn(new ConfigTransportClient(properties, new ServerListManager()) {
@Override
public void startInternal() throws NacosException {
// NOOP

View File

@ -21,7 +21,6 @@ import com.alibaba.nacos.api.config.filter.IConfigFilter;
import com.alibaba.nacos.api.config.filter.IConfigFilterChain;
import com.alibaba.nacos.api.config.filter.IConfigRequest;
import com.alibaba.nacos.api.config.filter.IConfigResponse;
import com.alibaba.nacos.api.config.filter.IFilterConfig;
import com.alibaba.nacos.api.exception.NacosException;
import org.junit.Assert;
import org.junit.Test;
@ -43,11 +42,7 @@ public class ConfigFilterChainManagerTest {
this.name = name;
this.order = order;
}
@Override
public void init(IFilterConfig filterConfig) {
}
@Override
public void init(Properties properties) {
}
@ -135,4 +130,4 @@ public class ConfigFilterChainManagerTest {
Assert.assertEquals(2, configContext.getParameter("filterCount"));
}
}
}

View File

@ -20,7 +20,6 @@ import com.alibaba.nacos.api.config.filter.IConfigFilter;
import com.alibaba.nacos.api.config.filter.IConfigFilterChain;
import com.alibaba.nacos.api.config.filter.IConfigRequest;
import com.alibaba.nacos.api.config.filter.IConfigResponse;
import com.alibaba.nacos.api.config.filter.IFilterConfig;
import com.alibaba.nacos.api.exception.NacosException;
import java.util.Properties;
@ -29,11 +28,6 @@ public class DemoFilter1 implements IConfigFilter {
private static final String DEFAULT_NAME = DemoFilter1.class.getName();
@Override
public void init(IFilterConfig filterConfig) {
}
@Override
public void init(Properties properties) {

View File

@ -20,7 +20,6 @@ import com.alibaba.nacos.api.config.filter.IConfigFilter;
import com.alibaba.nacos.api.config.filter.IConfigFilterChain;
import com.alibaba.nacos.api.config.filter.IConfigRequest;
import com.alibaba.nacos.api.config.filter.IConfigResponse;
import com.alibaba.nacos.api.config.filter.IFilterConfig;
import com.alibaba.nacos.api.exception.NacosException;
import java.util.Properties;
@ -29,11 +28,6 @@ public class DemoFilter2 implements IConfigFilter {
private static final String DEFAULT_NAME = DemoFilter2.class.getName();
@Override
public void init(IFilterConfig filterConfig) {
}
@Override
public void init(Properties properties) {

View File

@ -20,6 +20,7 @@ import com.alibaba.nacos.api.config.listener.AbstractListener;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.client.config.filter.impl.ConfigFilterChainManager;
import com.alibaba.nacos.client.env.NacosClientProperties;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
@ -36,7 +37,9 @@ public class ClientWorkerTest {
Properties prop = new Properties();
ConfigFilterChainManager filter = new ConfigFilterChainManager(new Properties());
ServerListManager agent = Mockito.mock(ServerListManager.class);
ClientWorker clientWorker = new ClientWorker(filter, agent, prop);
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(prop);
ClientWorker clientWorker = new ClientWorker(filter, agent, nacosClientProperties);
Assert.assertNotNull(clientWorker);
}
@ -45,7 +48,9 @@ public class ClientWorkerTest {
Properties prop = new Properties();
ConfigFilterChainManager filter = new ConfigFilterChainManager(new Properties());
ServerListManager agent = Mockito.mock(ServerListManager.class);
ClientWorker clientWorker = new ClientWorker(filter, agent, prop);
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(prop);
ClientWorker clientWorker = new ClientWorker(filter, agent, nacosClientProperties);
String dataId = "a";
String group = "b";
@ -73,7 +78,9 @@ public class ClientWorkerTest {
Properties prop = new Properties();
ConfigFilterChainManager filter = new ConfigFilterChainManager(new Properties());
ServerListManager agent = Mockito.mock(ServerListManager.class);
ClientWorker clientWorker = new ClientWorker(filter, agent, prop);
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(prop);
ClientWorker clientWorker = new ClientWorker(filter, agent, nacosClientProperties);
Listener listener = new AbstractListener() {
@Override
@ -117,7 +124,9 @@ public class ClientWorkerTest {
Properties prop = new Properties();
ConfigFilterChainManager filter = new ConfigFilterChainManager(new Properties());
ServerListManager agent = Mockito.mock(ServerListManager.class);
ClientWorker clientWorker = new ClientWorker(filter, agent, prop);
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(prop);
ClientWorker clientWorker = new ClientWorker(filter, agent, nacosClientProperties);
ClientWorker.ConfigRpcTransportClient mockClient = Mockito.mock(ClientWorker.ConfigRpcTransportClient.class);
String dataId = "a";
@ -158,7 +167,9 @@ public class ClientWorkerTest {
Properties prop = new Properties();
ConfigFilterChainManager filter = new ConfigFilterChainManager(new Properties());
ServerListManager agent = Mockito.mock(ServerListManager.class);
ClientWorker clientWorker = new ClientWorker(filter, agent, prop);
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(prop);
ClientWorker clientWorker = new ClientWorker(filter, agent, nacosClientProperties);
String dataId = "a";
String group = "b";
String tenant = "c";

View File

@ -18,6 +18,7 @@ package com.alibaba.nacos.client.config.impl;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.client.env.NacosClientProperties;
import org.junit.Assert;
import org.junit.Test;
@ -57,7 +58,9 @@ public class ServerListManagerTest {
Properties properties = new Properties();
properties.put(PropertyKeyConst.CONTEXT_PATH, "aaa");
properties.put(PropertyKeyConst.ENDPOINT, "endpoint");
final ServerListManager mgr2 = new ServerListManager(properties);
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(properties);
final ServerListManager mgr2 = new ServerListManager(nacosClientProperties);
Assert.assertEquals("aaa", mgr2.getContentPath());
}
@ -66,7 +69,8 @@ public class ServerListManagerTest {
Properties properties = new Properties();
properties.put(PropertyKeyConst.CONTEXT_PATH, "aaa");
properties.put(PropertyKeyConst.SERVER_ADDR, "https://1.1.1.1:8848");
final ServerListManager mgr2 = new ServerListManager(properties);
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(properties);
final ServerListManager mgr2 = new ServerListManager(nacosClientProperties);
Assert.assertEquals("aaa", mgr2.getContentPath());
Assert.assertEquals("[https://1.1.1.1:8848]", mgr2.getServerUrls().toString());
}
@ -75,8 +79,9 @@ public class ServerListManagerTest {
Properties properties2 = new Properties();
properties2.put(PropertyKeyConst.CONTEXT_PATH, "aaa");
properties2.put(PropertyKeyConst.SERVER_ADDR, "1.1.1.1:8848");
final ServerListManager mgr3 = new ServerListManager(properties2);
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(properties2);
final ServerListManager mgr3 = new ServerListManager(nacosClientProperties);
Assert.assertEquals(1, mgr3.getServerUrls().size());
Assert.assertEquals("http://1.1.1.1:8848", mgr3.getServerUrls().get(0));
Assert.assertEquals("[http://1.1.1.1:8848]", mgr3.getUrlString());
@ -88,8 +93,9 @@ public class ServerListManagerTest {
Properties properties3 = new Properties();
properties3.put(PropertyKeyConst.CONTEXT_PATH, "aaa");
properties3.put(PropertyKeyConst.SERVER_ADDR, "1.1.1.1:8848,2.2.2.2:8848");
final ServerListManager mgr4 = new ServerListManager(properties3);
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(properties3);
final ServerListManager mgr4 = new ServerListManager(nacosClientProperties);
Assert.assertEquals(2, mgr4.getServerUrls().size());
Assert.assertEquals("http://1.1.1.1:8848", mgr4.getServerUrls().get(0));
Assert.assertEquals("http://2.2.2.2:8848", mgr4.getServerUrls().get(1));
@ -101,8 +107,9 @@ public class ServerListManagerTest {
Properties properties4 = new Properties();
properties4.put(PropertyKeyConst.CONTEXT_PATH, "aaa");
properties4.put(PropertyKeyConst.SERVER_ADDR, "1.1.1.1:8848;2.2.2.2:8848");
final ServerListManager mgr5 = new ServerListManager(properties4);
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(properties4);
final ServerListManager mgr5 = new ServerListManager(nacosClientProperties);
Assert.assertEquals(2, mgr5.getServerUrls().size());
Assert.assertEquals("http://1.1.1.1:8848", mgr5.getServerUrls().get(0));
Assert.assertEquals("http://2.2.2.2:8848", mgr5.getServerUrls().get(1));

View File

@ -0,0 +1,33 @@
/*
* 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.client.logging.log4j2;
import com.alibaba.nacos.client.env.NacosClientProperties;
import org.junit.Assert;
import org.junit.Test;
public class NacosClientPropertiesLookupTest {
@Test
public void testLookUp() {
NacosClientProperties.PROTOTYPE.setProperty("test.nacos.logging.lookup", "true");
NacosClientPropertiesLookup nacosClientPropertiesLookup = new NacosClientPropertiesLookup();
final String actual = nacosClientPropertiesLookup.lookup("test.nacos.logging.lookup");
Assert.assertEquals("true", actual);
}
}

View File

@ -0,0 +1,118 @@
/*
* 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.client.logging.logback;
import ch.qos.logback.core.Context;
import ch.qos.logback.core.ContextBase;
import ch.qos.logback.core.joran.spi.ActionException;
import ch.qos.logback.core.joran.spi.InterpretationContext;
import com.alibaba.nacos.client.env.NacosClientProperties;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import org.xml.sax.Attributes;
public class NacosClientPropertyActionTest {
@Test
public void testLookUpVar() throws ActionException {
NacosClientProperties.PROTOTYPE.setProperty("test.nacos.logging.action.lookup", "true");
Context context = new ContextBase();
final InterpretationContext interpretationContext = new InterpretationContext(context, null);
final Attributes mockAttr = Mockito.mock(AttributesForTest.class);
Mockito.when(mockAttr.getValue(Mockito.eq("name"))).thenReturn("logPath");
Mockito.when(mockAttr.getValue(Mockito.eq("source"))).thenReturn("test.nacos.logging.action.lookup");
Mockito.when(mockAttr.getValue(Mockito.eq("scope"))).thenReturn("context");
Mockito.when(mockAttr.getValue(Mockito.eq("defaultValue"))).thenReturn("/root");
NacosClientPropertyAction nacosClientPropertyAction = new NacosClientPropertyAction();
nacosClientPropertyAction.setContext(context);
nacosClientPropertyAction.begin(interpretationContext, "nacosClientProperty", mockAttr);
final String actual = context.getProperty("logPath");
Assert.assertEquals("true", actual);
}
static class AttributesForTest implements Attributes {
@Override
public int getLength() {
return 0;
}
@Override
public String getURI(int index) {
return null;
}
@Override
public String getLocalName(int index) {
return null;
}
@Override
public String getQName(int index) {
return null;
}
@Override
public int getIndex(String uri, String localName) {
return 0;
}
@Override
public int getIndex(String qName) {
return 0;
}
@Override
public String getType(int index) {
return null;
}
@Override
public String getType(String uri, String localName) {
return null;
}
@Override
public String getType(String qName) {
return null;
}
@Override
public String getValue(int index) {
return null;
}
@Override
public String getValue(String uri, String localName) {
return null;
}
@Override
public String getValue(String qName) {
return null;
}
}
}

View File

@ -116,6 +116,27 @@ public class NacosNamingServiceTest {
instances -> CollectionUtils.isEqualCollection(instanceList, instances)));
}
@Test
public void testBatchDeRegisterInstance() throws NacosException {
Instance instance = new Instance();
String serviceName = "service1";
String ip = "1.1.1.1";
int port = 10000;
instance.setServiceName(serviceName);
instance.setEphemeral(true);
instance.setPort(port);
instance.setIp(ip);
List<Instance> instanceList = new ArrayList<>();
instanceList.add(instance);
//when
try {
client.batchDeregisterInstance(serviceName, Constants.DEFAULT_GROUP, instanceList);
} catch (Exception e) {
Assert.assertTrue(e instanceof NacosException);
Assert.assertTrue(e.getMessage().contains("not found"));
}
}
@Test
public void testRegisterInstance2() throws NacosException {
//given

View File

@ -1,89 +0,0 @@
/*
*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.alibaba.nacos.client.naming.beat;
import org.junit.Assert;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
public class BeatInfoTest {
@Test
public void testGetterAndSetter() {
BeatInfo info = new BeatInfo();
String ip = "1.1.1.1";
info.setIp(ip);
int port = 10000;
info.setPort(port);
double weight = 1.0;
info.setWeight(weight);
String serviceName = "serviceName";
info.setServiceName(serviceName);
String cluster = "cluster1";
info.setCluster(cluster);
Map<String, String> meta = new HashMap<>();
meta.put("a", "b");
info.setMetadata(meta);
long period = 100;
info.setPeriod(period);
info.setScheduled(true);
info.setStopped(true);
Assert.assertEquals(ip, info.getIp());
Assert.assertEquals(port, info.getPort());
Assert.assertEquals(weight, info.getWeight(), 0.1);
Assert.assertEquals(serviceName, info.getServiceName());
Assert.assertEquals(meta, info.getMetadata());
Assert.assertEquals(period, info.getPeriod());
Assert.assertTrue(info.isScheduled());
Assert.assertTrue(info.isStopped());
}
@Test
public void testToString() {
BeatInfo info = new BeatInfo();
String ip = "1.1.1.1";
info.setIp(ip);
int port = 10000;
info.setPort(port);
double weight = 1.0;
info.setWeight(weight);
String serviceName = "serviceName";
info.setServiceName(serviceName);
String cluster = "cluster1";
info.setCluster(cluster);
Map<String, String> meta = new HashMap<>();
meta.put("a", "b");
info.setMetadata(meta);
long period = 100;
info.setPeriod(period);
info.setScheduled(true);
info.setStopped(true);
String expect = "BeatInfo{port=10000, ip='1.1.1.1', " + "weight=1.0, serviceName='serviceName',"
+ " cluster='cluster1', metadata={a=b}," + " scheduled=true, period=100, stopped=true}";
Assert.assertEquals(expect, info.toString());
}
}

View File

@ -1,315 +0,0 @@
/*
*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.alibaba.nacos.client.naming.beat;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.utils.NamingUtils;
import com.alibaba.nacos.client.naming.remote.http.NamingHttpClientProxy;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import org.mockito.Mockito;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
@Ignore("Nacos 2.0 do not need heart beat")
public class BeatReactorTest {
@Test
public void testConstruct() throws NoSuchFieldException, IllegalAccessException {
Properties properties = new Properties();
String threadSize = "10";
properties.put(PropertyKeyConst.NAMING_CLIENT_BEAT_THREAD_COUNT, threadSize);
NamingHttpClientProxy proxy = Mockito.mock(NamingHttpClientProxy.class);
BeatReactor beatReactor = new BeatReactor(proxy, properties);
Field field = BeatReactor.class.getDeclaredField("executorService");
field.setAccessible(true);
ScheduledThreadPoolExecutor scheduledExecutorService = (ScheduledThreadPoolExecutor) field.get(beatReactor);
Assert.assertEquals(Integer.valueOf(threadSize).intValue(), scheduledExecutorService.getCorePoolSize());
}
@Test
public void testAddBeatInfo() throws NacosException, InterruptedException {
BeatInfo beatInfo = new BeatInfo();
beatInfo.setServiceName("test");
beatInfo.setIp("11.11.11.11");
beatInfo.setPort(1234);
beatInfo.setCluster("clusterName");
beatInfo.setWeight(1);
beatInfo.setMetadata(new HashMap<String, String>());
beatInfo.setScheduled(false);
beatInfo.setPeriod(10L);
NamingHttpClientProxy proxy = Mockito.mock(NamingHttpClientProxy.class);
BeatReactor beatReactor = new BeatReactor(proxy);
String serviceName = "serviceName1";
beatReactor.addBeatInfo(serviceName, beatInfo);
TimeUnit.MILLISECONDS.sleep(15);
Mockito.verify(proxy, Mockito.times(1)).sendBeat(beatInfo, false);
}
@Test
public void testRemoveBeatInfo() throws InterruptedException, NacosException {
BeatInfo beatInfo = new BeatInfo();
beatInfo.setServiceName("test");
String ip = "11.11.11.11";
beatInfo.setIp(ip);
int port = 1234;
beatInfo.setPort(port);
beatInfo.setCluster("clusterName");
beatInfo.setWeight(1);
beatInfo.setMetadata(new HashMap<String, String>());
beatInfo.setScheduled(false);
beatInfo.setPeriod(10L);
NamingHttpClientProxy proxy = Mockito.mock(NamingHttpClientProxy.class);
BeatReactor beatReactor = new BeatReactor(proxy);
String serviceName = "serviceName1";
beatReactor.addBeatInfo(serviceName, beatInfo);
TimeUnit.MILLISECONDS.sleep(15);
Mockito.verify(proxy, Mockito.times(1)).sendBeat(beatInfo, false);
beatReactor.removeBeatInfo(serviceName, ip, port);
Assert.assertTrue(beatInfo.isStopped());
Mockito.verify(proxy, Mockito.times(1)).sendBeat(beatInfo, false);
TimeUnit.MILLISECONDS.sleep(10);
}
@Test
public void testBuildBeatInfo1() {
String ip = "11.11.11.11";
int port = 1234;
double weight = 1.0;
String serviceName = "service@@group1";
String clusterName = "cluster1";
Map<String, String> meta = new HashMap<>();
Instance instance = new Instance();
instance.setServiceName(serviceName);
instance.setIp(ip);
instance.setPort(port);
instance.setWeight(weight);
instance.setMetadata(meta);
instance.setClusterName(clusterName);
BeatInfo expectInfo = new BeatInfo();
expectInfo.setServiceName(serviceName);
expectInfo.setIp(ip);
expectInfo.setPort(port);
expectInfo.setCluster(clusterName);
expectInfo.setWeight(weight);
expectInfo.setMetadata(meta);
expectInfo.setScheduled(false);
expectInfo.setPeriod(Constants.DEFAULT_HEART_BEAT_INTERVAL);
NamingHttpClientProxy proxy = Mockito.mock(NamingHttpClientProxy.class);
BeatReactor beatReactor = new BeatReactor(proxy);
assertBeatInfoEquals(expectInfo, beatReactor.buildBeatInfo(instance));
}
@Test
public void testBuildBeatInfo2() {
String ip = "11.11.11.11";
int port = 1234;
double weight = 1.0;
String serviceName = "service";
String clusterName = "cluster1";
Map<String, String> meta = new HashMap<>();
Instance instance = new Instance();
instance.setServiceName(serviceName);
instance.setIp(ip);
instance.setPort(port);
instance.setWeight(weight);
instance.setMetadata(meta);
instance.setClusterName(clusterName);
String groupedService = "group1@@service";
BeatInfo expectInfo = new BeatInfo();
expectInfo.setServiceName(groupedService);
expectInfo.setIp(ip);
expectInfo.setPort(port);
expectInfo.setCluster(clusterName);
expectInfo.setWeight(weight);
expectInfo.setMetadata(meta);
expectInfo.setScheduled(false);
expectInfo.setPeriod(Constants.DEFAULT_HEART_BEAT_INTERVAL);
NamingHttpClientProxy proxy = Mockito.mock(NamingHttpClientProxy.class);
BeatReactor beatReactor = new BeatReactor(proxy);
assertBeatInfoEquals(expectInfo, beatReactor.buildBeatInfo(groupedService, instance));
}
void assertBeatInfoEquals(BeatInfo expect, BeatInfo actual) {
Assert.assertEquals(expect.getCluster(), actual.getCluster());
Assert.assertEquals(expect.getIp(), actual.getIp());
Assert.assertEquals(expect.getMetadata(), actual.getMetadata());
Assert.assertEquals(expect.getPeriod(), actual.getPeriod());
Assert.assertEquals(expect.getPort(), actual.getPort());
Assert.assertEquals(expect.getServiceName(), actual.getServiceName());
Assert.assertEquals(expect.getWeight(), actual.getWeight(), 0.1);
Assert.assertEquals(expect.isStopped(), actual.isStopped());
Assert.assertEquals(expect.isScheduled(), actual.isScheduled());
}
@Test
public void testBuildKey() {
String ip = "11.11.11.11";
int port = 1234;
String serviceName = "serviceName1";
NamingHttpClientProxy proxy = Mockito.mock(NamingHttpClientProxy.class);
BeatReactor beatReactor = new BeatReactor(proxy);
Assert.assertEquals(
serviceName + Constants.NAMING_INSTANCE_ID_SPLITTER + ip + Constants.NAMING_INSTANCE_ID_SPLITTER + port,
beatReactor.buildKey(serviceName, ip, port));
}
@Test
public void testShutdown() throws NacosException, NoSuchFieldException, IllegalAccessException {
NamingHttpClientProxy proxy = Mockito.mock(NamingHttpClientProxy.class);
BeatReactor beatReactor = new BeatReactor(proxy);
Field field = BeatReactor.class.getDeclaredField("executorService");
field.setAccessible(true);
ScheduledThreadPoolExecutor scheduledExecutorService = (ScheduledThreadPoolExecutor) field.get(beatReactor);
Assert.assertFalse(scheduledExecutorService.isShutdown());
beatReactor.shutdown();
Assert.assertTrue(scheduledExecutorService.isShutdown());
}
@Test
public void testLightBeatFromResponse() throws InterruptedException, NacosException, JsonProcessingException {
BeatInfo beatInfo = new BeatInfo();
beatInfo.setServiceName("test");
beatInfo.setIp("11.11.11.11");
beatInfo.setPort(1234);
beatInfo.setCluster("clusterName");
beatInfo.setWeight(1);
beatInfo.setMetadata(new HashMap<String, String>());
beatInfo.setScheduled(false);
beatInfo.setPeriod(10L);
NamingHttpClientProxy proxy = Mockito.mock(NamingHttpClientProxy.class);
String jsonString = "{\"lightBeatEnabled\":true,\"clientBeatInterval\":10}";
ObjectMapper mapper = new ObjectMapper();
JsonNode actualObj = mapper.readTree(jsonString);
Mockito.when(proxy.sendBeat(beatInfo, false)).thenReturn(actualObj);
BeatReactor beatReactor = new BeatReactor(proxy);
String serviceName = "serviceName1";
beatReactor.addBeatInfo(serviceName, beatInfo);
TimeUnit.MILLISECONDS.sleep(12);
Mockito.verify(proxy, Mockito.times(1)).sendBeat(beatInfo, false);
TimeUnit.MILLISECONDS.sleep(12);
Mockito.verify(proxy, Mockito.times(1)).sendBeat(beatInfo, false);
Mockito.verify(proxy, Mockito.times(1)).sendBeat(beatInfo, true);
}
@Test
public void testIntervalFromResponse() throws JsonProcessingException, NacosException, InterruptedException {
BeatInfo beatInfo = new BeatInfo();
beatInfo.setServiceName("test");
beatInfo.setIp("11.11.11.11");
beatInfo.setPort(1234);
beatInfo.setCluster("clusterName");
beatInfo.setWeight(1);
beatInfo.setMetadata(new HashMap<String, String>());
beatInfo.setScheduled(false);
beatInfo.setPeriod(10L);
NamingHttpClientProxy proxy = Mockito.mock(NamingHttpClientProxy.class);
String jsonString = "{\"clientBeatInterval\":20}";
ObjectMapper mapper = new ObjectMapper();
JsonNode actualObj = mapper.readTree(jsonString);
Mockito.when(proxy.sendBeat(beatInfo, false)).thenReturn(actualObj);
BeatReactor beatReactor = new BeatReactor(proxy);
String serviceName = "serviceName1";
beatReactor.addBeatInfo(serviceName, beatInfo);
TimeUnit.MILLISECONDS.sleep(12);
Mockito.verify(proxy, Mockito.times(1)).sendBeat(beatInfo, false);
TimeUnit.MILLISECONDS.sleep(20);
Mockito.verify(proxy, Mockito.times(2)).sendBeat(beatInfo, false);
}
@Test
public void testNotFoundFromResponse() throws JsonProcessingException, NacosException, InterruptedException {
BeatInfo beatInfo = new BeatInfo();
beatInfo.setServiceName("test");
beatInfo.setIp("11.11.11.11");
beatInfo.setPort(1234);
beatInfo.setCluster("clusterName");
beatInfo.setWeight(1);
beatInfo.setMetadata(new HashMap<String, String>());
beatInfo.setScheduled(false);
beatInfo.setPeriod(10L);
NamingHttpClientProxy proxy = Mockito.mock(NamingHttpClientProxy.class);
String jsonString = "{\"clientBeatInterval\":10,\"code\":20404}";
ObjectMapper mapper = new ObjectMapper();
JsonNode actualObj = mapper.readTree(jsonString);
Mockito.when(proxy.sendBeat(beatInfo, false)).thenReturn(actualObj);
Mockito.when(proxy.sendBeat(beatInfo, false)).thenReturn(actualObj);
BeatReactor beatReactor = new BeatReactor(proxy);
String serviceName = "serviceName1";
beatReactor.addBeatInfo(serviceName, beatInfo);
TimeUnit.MILLISECONDS.sleep(11);
Mockito.verify(proxy, Mockito.times(1)).sendBeat(beatInfo, false);
Instance instance = new Instance();
instance.setPort(beatInfo.getPort());
instance.setIp(beatInfo.getIp());
instance.setWeight(beatInfo.getWeight());
instance.setMetadata(beatInfo.getMetadata());
instance.setClusterName(beatInfo.getCluster());
instance.setServiceName(beatInfo.getServiceName());
instance.setInstanceId(null);
instance.setEphemeral(true);
Mockito.verify(proxy, Mockito.times(1))
.registerService(beatInfo.getServiceName(), NamingUtils.getGroupName(beatInfo.getServiceName()),
instance);
}
}

View File

@ -22,6 +22,7 @@ import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import com.alibaba.nacos.client.env.NacosClientProperties;
import com.alibaba.nacos.client.naming.backups.FailoverReactor;
import org.junit.Assert;
import org.junit.Test;
@ -37,7 +38,9 @@ public class ServiceInfoHolderTest {
@Test
public void testGetServiceInfoMap() throws NoSuchFieldException, IllegalAccessException {
Properties prop = new Properties();
ServiceInfoHolder holder = new ServiceInfoHolder("aa", "scope-001", prop);
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(prop);
ServiceInfoHolder holder = new ServiceInfoHolder("aa", "scope-001", nacosClientProperties);
Assert.assertEquals(0, holder.getServiceInfoMap().size());
Field fieldNotifierEventScope = ServiceInfoHolder.class.getDeclaredField("notifierEventScope");
fieldNotifierEventScope.setAccessible(true);
@ -55,7 +58,8 @@ public class ServiceInfoHolderTest {
info.setHosts(hosts);
Properties prop = new Properties();
ServiceInfoHolder holder = new ServiceInfoHolder("aa", "scope-001", prop);
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(prop);
ServiceInfoHolder holder = new ServiceInfoHolder("aa", "scope-001", nacosClientProperties);
ServiceInfo actual1 = holder.processServiceInfo(info);
Assert.assertEquals(info, actual1);
@ -83,7 +87,8 @@ public class ServiceInfoHolderTest {
@Test
public void testProcessServiceInfo2() {
Properties prop = new Properties();
ServiceInfoHolder holder = new ServiceInfoHolder("aa", "scope-001", prop);
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(prop);
ServiceInfoHolder holder = new ServiceInfoHolder("aa", "scope-001", nacosClientProperties);
String json = "{\"groupName\":\"a\",\"name\":\"b\",\"clusters\":\"c\"}";
ServiceInfo actual = holder.processServiceInfo(json);
@ -104,7 +109,8 @@ public class ServiceInfoHolderTest {
Properties prop = new Properties();
prop.setProperty(PropertyKeyConst.NAMING_PUSH_EMPTY_PROTECTION, "true");
ServiceInfoHolder holder = new ServiceInfoHolder("aa", "scope-001", prop);
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(prop);
ServiceInfoHolder holder = new ServiceInfoHolder("aa", "scope-001", nacosClientProperties);
holder.processServiceInfo(oldInfo);
ServiceInfo newInfo = new ServiceInfo("a@@b@@c");
@ -124,7 +130,8 @@ public class ServiceInfoHolderTest {
info.setHosts(hosts);
Properties prop = new Properties();
ServiceInfoHolder holder = new ServiceInfoHolder("aa", "scope-001", prop);
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(prop);
ServiceInfoHolder holder = new ServiceInfoHolder("aa", "scope-001", nacosClientProperties);
ServiceInfo expect = holder.processServiceInfo(info);
String serviceName = "b";
@ -139,7 +146,8 @@ public class ServiceInfoHolderTest {
@Test
public void testShutdown() throws NacosException, NoSuchFieldException, IllegalAccessException {
Properties prop = new Properties();
ServiceInfoHolder holder = new ServiceInfoHolder("aa", "scope-001", prop);
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(prop);
ServiceInfoHolder holder = new ServiceInfoHolder("aa", "scope-001", nacosClientProperties);
Field field = ServiceInfoHolder.class.getDeclaredField("failoverReactor");
field.setAccessible(true);
FailoverReactor reactor = (FailoverReactor) field.get(holder);

View File

@ -1,153 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.client.naming.core;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.client.naming.cache.ServiceInfoHolder;
import com.alibaba.nacos.common.utils.IoUtils;
import com.alibaba.nacos.common.utils.JacksonUtils;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
public class PushReceiverTest {
@Test
public void testTestRunDomAndService() throws InterruptedException, IOException {
ServiceInfoHolder holder = Mockito.mock(ServiceInfoHolder.class);
final PushReceiver pushReceiver = new PushReceiver(holder);
final ExecutorService executorService = Executors.newFixedThreadPool(1);
executorService.submit(new Runnable() {
@Override
public void run() {
pushReceiver.run();
}
});
TimeUnit.MILLISECONDS.sleep(10);
PushReceiver.PushPacket pack1 = new PushReceiver.PushPacket();
pack1.type = "dom";
pack1.data = "pack1";
pack1.lastRefTime = 1;
final String res1 = udpClientRun(pack1, pushReceiver);
Assert.assertEquals("{\"type\": \"push-ack\", \"lastRefTime\":\"1\", \"data\":\"\"}", res1);
verify(holder, times(1)).processServiceInfo(pack1.data);
PushReceiver.PushPacket pack2 = new PushReceiver.PushPacket();
pack2.type = "service";
pack2.data = "pack2";
pack2.lastRefTime = 2;
final String res2 = udpClientRun(pack2, pushReceiver);
Assert.assertEquals("{\"type\": \"push-ack\", \"lastRefTime\":\"2\", \"data\":\"\"}", res2);
verify(holder, times(1)).processServiceInfo(pack2.data);
}
private String udpClientRun(PushReceiver.PushPacket pack, PushReceiver pushReceiver) throws IOException {
final int udpPort = pushReceiver.getUdpPort();
String json = JacksonUtils.toJson(pack);
final byte[] bytes = IoUtils.tryCompress(json, "UTF-8");
final DatagramSocket datagramSocket = new DatagramSocket();
datagramSocket.send(new DatagramPacket(bytes, bytes.length, InetAddress.getByName("localhost"), udpPort));
byte[] buffer = new byte[20480];
final DatagramPacket datagramPacket = new DatagramPacket(buffer, buffer.length);
datagramSocket.receive(datagramPacket);
final byte[] data = datagramPacket.getData();
String res = new String(data, StandardCharsets.UTF_8);
return res.trim();
}
@Test
public void testTestRunWithDump() throws InterruptedException, IOException {
ServiceInfoHolder holder = Mockito.mock(ServiceInfoHolder.class);
final PushReceiver pushReceiver = new PushReceiver(holder);
final ExecutorService executorService = Executors.newFixedThreadPool(1);
executorService.submit(new Runnable() {
@Override
public void run() {
pushReceiver.run();
}
});
TimeUnit.MILLISECONDS.sleep(10);
PushReceiver.PushPacket pack1 = new PushReceiver.PushPacket();
pack1.type = "dump";
pack1.data = "pack1";
pack1.lastRefTime = 1;
final String res1 = udpClientRun(pack1, pushReceiver);
Assert.assertEquals("{\"type\": \"dump-ack\", \"lastRefTime\": \"1\", \"data\":\"{}\"}", res1);
verify(holder, times(1)).getServiceInfoMap();
}
@Test
public void testTestRunWithUnknown() throws InterruptedException, IOException {
ServiceInfoHolder holder = Mockito.mock(ServiceInfoHolder.class);
final PushReceiver pushReceiver = new PushReceiver(holder);
final ExecutorService executorService = Executors.newFixedThreadPool(1);
executorService.submit(new Runnable() {
@Override
public void run() {
pushReceiver.run();
}
});
TimeUnit.MILLISECONDS.sleep(10);
PushReceiver.PushPacket pack1 = new PushReceiver.PushPacket();
pack1.type = "unknown";
pack1.data = "pack1";
pack1.lastRefTime = 1;
final String res1 = udpClientRun(pack1, pushReceiver);
Assert.assertEquals("{\"type\": \"unknown-ack\", \"lastRefTime\":\"1\", \"data\":\"\"}", res1);
}
@Test
public void testShutdown() throws NacosException, NoSuchFieldException, IllegalAccessException {
ServiceInfoHolder holder = Mockito.mock(ServiceInfoHolder.class);
final PushReceiver pushReceiver = new PushReceiver(holder);
pushReceiver.shutdown();
final Field closed = PushReceiver.class.getDeclaredField("closed");
closed.setAccessible(true);
final boolean o = (boolean) closed.get(pushReceiver);
Assert.assertTrue(o);
}
@Test
public void testGetUdpPort() {
ServiceInfoHolder holder = Mockito.mock(ServiceInfoHolder.class);
final PushReceiver pushReceiver = new PushReceiver(holder);
final int udpPort = pushReceiver.getUdpPort();
System.out.println("udpPort = " + udpPort);
Assert.assertTrue(udpPort > 0);
}
}

View File

@ -18,6 +18,7 @@ package com.alibaba.nacos.client.naming.core;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import com.alibaba.nacos.client.env.NacosClientProperties;
import com.alibaba.nacos.client.naming.cache.ServiceInfoHolder;
import com.alibaba.nacos.client.naming.event.InstancesChangeNotifier;
import com.alibaba.nacos.client.naming.remote.NamingClientProxy;
@ -46,7 +47,10 @@ public class ServiceInfoUpdateServiceTest {
InstancesChangeNotifier notifyer = Mockito.mock(InstancesChangeNotifier.class);
Properties prop = new Properties();
final ServiceInfoUpdateService serviceInfoUpdateService = new ServiceInfoUpdateService(prop, holder, proxy,
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(prop);
nacosClientProperties.setProperty("namingAsyncQuerySubscribeService", "true");
final ServiceInfoUpdateService serviceInfoUpdateService = new ServiceInfoUpdateService(nacosClientProperties, holder, proxy,
notifyer);
serviceInfoUpdateService.scheduleUpdateIfAbsent("aa", "bb", "cc");
@ -71,7 +75,8 @@ public class ServiceInfoUpdateServiceTest {
Properties prop = new Properties();
ServiceInfoHolder holder = Mockito.mock(ServiceInfoHolder.class);
final ServiceInfoUpdateService serviceInfoUpdateService = new ServiceInfoUpdateService(prop, holder, proxy,
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(prop);
final ServiceInfoUpdateService serviceInfoUpdateService = new ServiceInfoUpdateService(nacosClientProperties, holder, proxy,
notifyer);
serviceInfoUpdateService.scheduleUpdateIfAbsent(serviceName, group, clusters);

View File

@ -26,11 +26,11 @@ import com.alibaba.nacos.api.naming.pojo.Service;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import com.alibaba.nacos.api.selector.AbstractSelector;
import com.alibaba.nacos.client.auth.ram.utils.SignUtil;
import com.alibaba.nacos.plugin.auth.api.RequestResource;
import com.alibaba.nacos.client.naming.event.ServerListChangedEvent;
import com.alibaba.nacos.client.security.SecurityProxy;
import com.alibaba.nacos.client.utils.AppNameUtils;
import com.alibaba.nacos.common.notify.Event;
import com.alibaba.nacos.plugin.auth.api.RequestResource;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
@ -40,7 +40,6 @@ import org.mockito.junit.MockitoJUnitRunner;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
@ -69,6 +68,7 @@ public class AbstractNamingClientProxyTest {
/**
* get security headers for ram.
*
* @throws Exception exception
*/
@Test
@ -102,13 +102,19 @@ public class AbstractNamingClientProxyTest {
public void registerService(String serviceName, String groupName, Instance instance) throws NacosException {
}
@Override
public void batchRegisterService(String serviceName, String groupName, List<Instance> instances)
throws NacosException {
}
@Override
public void batchDeregisterService(String serviceName, String groupName, List<Instance> instances)
throws NacosException {
}
@Override
public void deregisterService(String serviceName, String groupName, Instance instance) throws NacosException {
@ -166,11 +172,6 @@ public class AbstractNamingClientProxyTest {
return false;
}
@Override
public void updateBeatInfo(Set<Instance> modifiedInstances) {
}
@Override
public boolean serverHealthy() {
return false;

View File

@ -25,6 +25,7 @@ import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import com.alibaba.nacos.api.selector.AbstractSelector;
import com.alibaba.nacos.api.selector.ExpressionSelector;
import com.alibaba.nacos.api.selector.NoneSelector;
import com.alibaba.nacos.client.env.NacosClientProperties;
import com.alibaba.nacos.client.naming.cache.ServiceInfoHolder;
import com.alibaba.nacos.client.naming.event.InstancesChangeNotifier;
import com.alibaba.nacos.client.naming.remote.gprc.NamingGrpcClientProxy;
@ -35,10 +36,8 @@ import org.mockito.Mockito;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@ -52,8 +51,9 @@ public class NamingClientProxyDelegateTest {
ServiceInfoHolder holder = Mockito.mock(ServiceInfoHolder.class);
Properties props = new Properties();
props.setProperty("serverAddr", "localhost");
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(props);
InstancesChangeNotifier notifier = new InstancesChangeNotifier();
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, props, notifier);
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, nacosClientProperties, notifier);
NamingGrpcClientProxy mockGrpcClient = Mockito.mock(NamingGrpcClientProxy.class);
Field grpcClientProxyField = NamingClientProxyDelegate.class.getDeclaredField("grpcClientProxy");
grpcClientProxyField.setAccessible(true);
@ -78,7 +78,9 @@ public class NamingClientProxyDelegateTest {
Properties props = new Properties();
props.setProperty("serverAddr", "localhost");
InstancesChangeNotifier notifier = new InstancesChangeNotifier();
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, props, notifier);
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(props);
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, nacosClientProperties, notifier);
NamingGrpcClientProxy mockGrpcClient = Mockito.mock(NamingGrpcClientProxy.class);
Field grpcClientProxyField = NamingClientProxyDelegate.class.getDeclaredField("grpcClientProxy");
grpcClientProxyField.setAccessible(true);
@ -104,7 +106,9 @@ public class NamingClientProxyDelegateTest {
Properties props = new Properties();
props.setProperty("serverAddr", "localhost");
InstancesChangeNotifier notifier = new InstancesChangeNotifier();
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, props, notifier);
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(props);
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, nacosClientProperties, notifier);
NamingHttpClientProxy mockHttpClient = Mockito.mock(NamingHttpClientProxy.class);
Field mockHttpClientField = NamingClientProxyDelegate.class.getDeclaredField("httpClientProxy");
mockHttpClientField.setAccessible(true);
@ -130,7 +134,9 @@ public class NamingClientProxyDelegateTest {
Properties props = new Properties();
props.setProperty("serverAddr", "localhost");
InstancesChangeNotifier notifier = new InstancesChangeNotifier();
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, props, notifier);
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(props);
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, nacosClientProperties, notifier);
NamingGrpcClientProxy mockGrpcClient = Mockito.mock(NamingGrpcClientProxy.class);
Field grpcClientProxyField = NamingClientProxyDelegate.class.getDeclaredField("grpcClientProxy");
grpcClientProxyField.setAccessible(true);
@ -156,7 +162,9 @@ public class NamingClientProxyDelegateTest {
Properties props = new Properties();
props.setProperty("serverAddr", "localhost");
InstancesChangeNotifier notifier = new InstancesChangeNotifier();
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, props, notifier);
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(props);
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, nacosClientProperties, notifier);
NamingHttpClientProxy mockHttpClient = Mockito.mock(NamingHttpClientProxy.class);
Field mockHttpClientField = NamingClientProxyDelegate.class.getDeclaredField("httpClientProxy");
mockHttpClientField.setAccessible(true);
@ -182,7 +190,9 @@ public class NamingClientProxyDelegateTest {
Properties props = new Properties();
props.setProperty("serverAddr", "localhost");
InstancesChangeNotifier notifier = new InstancesChangeNotifier();
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, props, notifier);
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(props);
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, nacosClientProperties, notifier);
String serviceName = "service1";
String groupName = "group1";
Instance instance = new Instance();
@ -200,7 +210,9 @@ public class NamingClientProxyDelegateTest {
Properties props = new Properties();
props.setProperty("serverAddr", "localhost");
InstancesChangeNotifier notifier = new InstancesChangeNotifier();
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, props, notifier);
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(props);
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, nacosClientProperties, notifier);
NamingGrpcClientProxy mockGrpcClient = Mockito.mock(NamingGrpcClientProxy.class);
Field grpcClientProxyField = NamingClientProxyDelegate.class.getDeclaredField("grpcClientProxy");
grpcClientProxyField.setAccessible(true);
@ -220,7 +232,9 @@ public class NamingClientProxyDelegateTest {
Properties props = new Properties();
props.setProperty("serverAddr", "localhost");
InstancesChangeNotifier notifier = new InstancesChangeNotifier();
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, props, notifier);
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(props);
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, nacosClientProperties, notifier);
Service service = delegate.queryService("a", "b");
Assert.assertNull(service);
}
@ -232,7 +246,9 @@ public class NamingClientProxyDelegateTest {
Properties props = new Properties();
props.setProperty("serverAddr", "localhost");
InstancesChangeNotifier notifier = new InstancesChangeNotifier();
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, props, notifier);
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(props);
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, nacosClientProperties, notifier);
Service service = new Service();
try {
delegate.createService(service, new NoneSelector());
@ -248,7 +264,9 @@ public class NamingClientProxyDelegateTest {
Properties props = new Properties();
props.setProperty("serverAddr", "localhost");
InstancesChangeNotifier notifier = new InstancesChangeNotifier();
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, props, notifier);
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(props);
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, nacosClientProperties, notifier);
Assert.assertFalse(delegate.deleteService("service", "group1"));
}
@ -259,7 +277,9 @@ public class NamingClientProxyDelegateTest {
Properties props = new Properties();
props.setProperty("serverAddr", "localhost");
InstancesChangeNotifier notifier = new InstancesChangeNotifier();
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, props, notifier);
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(props);
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, nacosClientProperties, notifier);
Service service = new Service();
try {
delegate.updateService(service, new ExpressionSelector());
@ -275,7 +295,9 @@ public class NamingClientProxyDelegateTest {
Properties props = new Properties();
props.setProperty("serverAddr", "localhost");
InstancesChangeNotifier notifier = new InstancesChangeNotifier();
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, props, notifier);
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(props);
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, nacosClientProperties, notifier);
NamingGrpcClientProxy mockGrpcClient = Mockito.mock(NamingGrpcClientProxy.class);
Field grpcClientProxyField = NamingClientProxyDelegate.class.getDeclaredField("grpcClientProxy");
grpcClientProxyField.setAccessible(true);
@ -297,7 +319,9 @@ public class NamingClientProxyDelegateTest {
Properties props = new Properties();
props.setProperty("serverAddr", "localhost");
InstancesChangeNotifier notifier = new InstancesChangeNotifier();
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, props, notifier);
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(props);
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, nacosClientProperties, notifier);
NamingGrpcClientProxy mockGrpcClient = Mockito.mock(NamingGrpcClientProxy.class);
Field grpcClientProxyField = NamingClientProxyDelegate.class.getDeclaredField("grpcClientProxy");
grpcClientProxyField.setAccessible(true);
@ -326,7 +350,9 @@ public class NamingClientProxyDelegateTest {
Properties props = new Properties();
props.setProperty("serverAddr", "localhost");
InstancesChangeNotifier notifier = new InstancesChangeNotifier();
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, props, notifier);
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(props);
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, nacosClientProperties, notifier);
NamingGrpcClientProxy mockGrpcClient = Mockito.mock(NamingGrpcClientProxy.class);
Field grpcClientProxyField = NamingClientProxyDelegate.class.getDeclaredField("grpcClientProxy");
grpcClientProxyField.setAccessible(true);
@ -340,25 +366,6 @@ public class NamingClientProxyDelegateTest {
verify(mockGrpcClient, times(1)).unsubscribe(serviceName, groupName, clusters);
}
@Test
public void testUpdateBeatInfo() throws NacosException, NoSuchFieldException, IllegalAccessException {
String ns = "ns1";
ServiceInfoHolder holder = Mockito.mock(ServiceInfoHolder.class);
Properties props = new Properties();
props.setProperty("serverAddr", "localhost");
InstancesChangeNotifier notifier = new InstancesChangeNotifier();
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, props, notifier);
NamingHttpClientProxy mockHttpClient = Mockito.mock(NamingHttpClientProxy.class);
Field mockHttpClientField = NamingClientProxyDelegate.class.getDeclaredField("httpClientProxy");
mockHttpClientField.setAccessible(true);
mockHttpClientField.set(delegate, mockHttpClient);
//HTTP ONLY
Set<Instance> set = new HashSet<>();
delegate.updateBeatInfo(set);
verify(mockHttpClient, times(1)).updateBeatInfo(set);
}
@Test
public void testServerHealthy() throws IllegalAccessException, NacosException, NoSuchFieldException {
String ns = "ns1";
@ -366,7 +373,9 @@ public class NamingClientProxyDelegateTest {
Properties props = new Properties();
props.setProperty("serverAddr", "localhost");
InstancesChangeNotifier notifier = new InstancesChangeNotifier();
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, props, notifier);
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(props);
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, nacosClientProperties, notifier);
NamingGrpcClientProxy mockGrpcClient = Mockito.mock(NamingGrpcClientProxy.class);
Field grpcClientProxyField = NamingClientProxyDelegate.class.getDeclaredField("grpcClientProxy");
grpcClientProxyField.setAccessible(true);
@ -383,7 +392,9 @@ public class NamingClientProxyDelegateTest {
Properties props = new Properties();
props.setProperty("serverAddr", "localhost");
InstancesChangeNotifier notifier = new InstancesChangeNotifier();
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, props, notifier);
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(props);
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, nacosClientProperties, notifier);
NamingGrpcClientProxy mockGrpcClient = Mockito.mock(NamingGrpcClientProxy.class);
Field grpcClientProxyField = NamingClientProxyDelegate.class.getDeclaredField("grpcClientProxy");
grpcClientProxyField.setAccessible(true);
@ -391,4 +402,4 @@ public class NamingClientProxyDelegateTest {
delegate.shutdown();
verify(mockGrpcClient, times(1)).shutdown();
}
}
}

View File

@ -40,6 +40,7 @@ import com.alibaba.nacos.api.remote.response.ErrorResponse;
import com.alibaba.nacos.api.remote.response.Response;
import com.alibaba.nacos.api.selector.AbstractSelector;
import com.alibaba.nacos.api.selector.NoneSelector;
import com.alibaba.nacos.client.env.NacosClientProperties;
import com.alibaba.nacos.client.naming.cache.ServiceInfoHolder;
import com.alibaba.nacos.client.naming.event.ServerListChangedEvent;
import com.alibaba.nacos.client.naming.remote.gprc.redo.NamingGrpcRedoService;
@ -50,6 +51,8 @@ import com.alibaba.nacos.common.remote.client.Connection;
import com.alibaba.nacos.common.remote.client.RpcClient;
import com.alibaba.nacos.common.remote.client.RpcClientConfig;
import com.alibaba.nacos.common.remote.client.ServerListFactory;
import com.alibaba.nacos.common.remote.client.grpc.GrpcConstants;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
@ -64,7 +67,6 @@ import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
@ -119,14 +121,18 @@ public class NamingGrpcClientProxyTest {
@Before
public void setUp() throws NacosException, NoSuchFieldException, IllegalAccessException {
System.setProperty(GrpcConstants.GRPC_RETRY_TIMES, "1");
System.setProperty(GrpcConstants.GRPC_SERVER_CHECK_TIMEOUT, "1000");
List<String> serverList = Stream.of(ORIGIN_SERVER, "anotherServer").collect(Collectors.toList());
when(factory.getServerList()).thenReturn(serverList);
when(factory.genNextServer()).thenReturn(ORIGIN_SERVER);
prop = new Properties();
client = new NamingGrpcClientProxy(NAMESPACE_ID, proxy, factory, prop, holder);
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(prop);
client = new NamingGrpcClientProxy(NAMESPACE_ID, proxy, factory, nacosClientProperties, holder);
Field rpcClientField = NamingGrpcClientProxy.class.getDeclaredField("rpcClient");
rpcClientField.setAccessible(true);
((RpcClient) rpcClientField.get(client)).shutdown();
rpcClientField.set(client, this.rpcClient);
response = new InstanceResponse();
when(this.rpcClient.request(any())).thenReturn(response);
@ -136,6 +142,13 @@ public class NamingGrpcClientProxyTest {
instance.setPort(1111);
}
@After
public void tearDown() throws NacosException {
System.setProperty(GrpcConstants.GRPC_RETRY_TIMES, "3");
System.setProperty(GrpcConstants.GRPC_SERVER_CHECK_TIMEOUT, "3000");
client.shutdown();
}
@Test
public void testRegisterService() throws NacosException {
client.registerService(SERVICE_NAME, GROUP_NAME, instance);
@ -289,20 +302,14 @@ public class NamingGrpcClientProxyTest {
SubscribeServiceRequest request1 = (SubscribeServiceRequest) request;
// verify request fields
return !request1.isSubscribe() && SERVICE_NAME.equals(request1.getServiceName()) && GROUP_NAME.equals(
request1.getGroupName()) && CLUSTERS.equals(request1.getClusters()) && NAMESPACE_ID.equals(
request1.getNamespace());
return !request1.isSubscribe() && SERVICE_NAME.equals(request1.getServiceName()) && GROUP_NAME
.equals(request1.getGroupName()) && CLUSTERS.equals(request1.getClusters()) && NAMESPACE_ID
.equals(request1.getNamespace());
}
return false;
}));
}
@Test
public void testUpdateBeatInfo() {
//TODO thrown.expect(UnsupportedOperationException.class);
client.updateBeatInfo(new HashSet<>());
}
@Test
public void testServerHealthy() {
when(this.rpcClient.isRunning()).thenReturn(true);
@ -391,7 +398,7 @@ public class NamingGrpcClientProxyTest {
@Override
public void asyncRequest(Request request, RequestCallBack requestCallBack) throws NacosException {
}
@Override
@ -413,7 +420,7 @@ public class NamingGrpcClientProxyTest {
rpc.start();
int retry = 10;
while (!rpc.isRunning()) {
TimeUnit.SECONDS.sleep(1);
TimeUnit.MILLISECONDS.sleep(200);
if (--retry < 0) {
Assert.fail("rpc is not running");
}
@ -428,7 +435,7 @@ public class NamingGrpcClientProxyTest {
retry = 10;
while (ORIGIN_SERVER.equals(rpc.getCurrentServer().getServerIp())) {
TimeUnit.SECONDS.sleep(1);
TimeUnit.MILLISECONDS.sleep(200);
if (--retry < 0) {
Assert.fail("failed to auth switch server");
}

View File

@ -24,29 +24,30 @@ import com.alibaba.nacos.api.naming.pojo.ListView;
import com.alibaba.nacos.api.naming.pojo.Service;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import com.alibaba.nacos.api.selector.NoneSelector;
import com.alibaba.nacos.client.naming.beat.BeatInfo;
import com.alibaba.nacos.client.naming.beat.BeatReactor;
import com.alibaba.nacos.client.naming.cache.ServiceInfoHolder;
import com.alibaba.nacos.client.env.NacosClientProperties;
import com.alibaba.nacos.client.naming.core.ServerListManager;
import com.alibaba.nacos.client.naming.utils.UtilAndComs;
import com.alibaba.nacos.client.security.SecurityProxy;
import com.alibaba.nacos.common.http.HttpRestResult;
import com.alibaba.nacos.common.http.client.NacosRestTemplate;
import com.alibaba.nacos.common.utils.HttpMethod;
import com.alibaba.nacos.common.utils.ReflectUtils;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.endsWith;
@ -56,11 +57,35 @@ import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class NamingHttpClientProxyTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Mock
private SecurityProxy proxy;
@Mock
private ServerListManager mgr;
private Properties props;
private NamingHttpClientProxy clientProxy;
@Before
public void setUp() {
when(mgr.getServerList()).thenReturn(Arrays.asList("localhost"));
props = new Properties();
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(props);
clientProxy = new NamingHttpClientProxy("namespaceId", proxy, mgr, nacosClientProperties);
}
@After
public void tearDown() throws NacosException {
clientProxy.shutdown();
}
@Test
public void testRegisterService() throws Exception {
//given
@ -70,13 +95,6 @@ public class NamingHttpClientProxyTest {
a.setCode(200);
when(nacosRestTemplate.exchangeForm(any(), any(), any(), any(), any(), any())).thenReturn(a);
SecurityProxy proxy = mock(SecurityProxy.class);
ServerListManager mgr = mock(ServerListManager.class);
when(mgr.getServerList()).thenReturn(Arrays.asList("localhost"));
Properties props = new Properties();
ServiceInfoHolder holder = mock(ServiceInfoHolder.class);
NamingHttpClientProxy clientProxy = new NamingHttpClientProxy("namespaceId", proxy, mgr, props, holder);
final Field nacosRestTemplateField = NamingHttpClientProxy.class.getDeclaredField("nacosRestTemplate");
nacosRestTemplateField.setAccessible(true);
nacosRestTemplateField.set(clientProxy, nacosRestTemplate);
@ -84,6 +102,7 @@ public class NamingHttpClientProxyTest {
String serviceName = "service1";
String groupName = "group1";
Instance instance = new Instance();
instance.setEphemeral(false);
//when
clientProxy.registerService(serviceName, groupName, instance);
//then
@ -94,32 +113,25 @@ public class NamingHttpClientProxyTest {
public void testRegisterServiceThrowsNacosException() throws Exception {
thrown.expect(NacosException.class);
thrown.expectMessage("failed to req API");
NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class);
HttpRestResult<Object> a = new HttpRestResult<Object>();
a.setCode(503);
when(nacosRestTemplate.exchangeForm(any(), any(), any(), any(), any(), any())).thenReturn(a);
SecurityProxy proxy = mock(SecurityProxy.class);
ServerListManager mgr = mock(ServerListManager.class);
when(mgr.getServerList()).thenReturn(Arrays.asList("localhost"));
Properties props = new Properties();
ServiceInfoHolder holder = mock(ServiceInfoHolder.class);
NamingHttpClientProxy clientProxy = new NamingHttpClientProxy("namespaceId", proxy, mgr, props, holder);
final Field nacosRestTemplateField = NamingHttpClientProxy.class.getDeclaredField("nacosRestTemplate");
nacosRestTemplateField.setAccessible(true);
nacosRestTemplateField.set(clientProxy, nacosRestTemplate);
String serviceName = "service1";
String groupName = "group1";
Instance instance = new Instance();
instance.setEphemeral(false);
try {
clientProxy.registerService(serviceName, groupName, instance);
} catch (NacosException ex) {
// verify the `NacosException` is directly thrown
Assert.assertEquals(null, ex.getCause());
throw ex;
}
}
@ -135,19 +147,13 @@ public class NamingHttpClientProxyTest {
// makes exchangeForm failed with a NullPointerException
when(nacosRestTemplate.exchangeForm(any(), any(), any(), any(), any(), any())).thenReturn(null);
SecurityProxy proxy = mock(SecurityProxy.class);
ServerListManager mgr = mock(ServerListManager.class);
when(mgr.getServerList()).thenReturn(Arrays.asList("localhost"));
Properties props = new Properties();
ServiceInfoHolder holder = mock(ServiceInfoHolder.class);
NamingHttpClientProxy clientProxy = new NamingHttpClientProxy("namespaceId", proxy, mgr, props, holder);
final Field nacosRestTemplateField = NamingHttpClientProxy.class.getDeclaredField("nacosRestTemplate");
nacosRestTemplateField.setAccessible(true);
nacosRestTemplateField.set(clientProxy, nacosRestTemplate);
String serviceName = "service1";
String groupName = "group1";
Instance instance = new Instance();
instance.setEphemeral(false);
try {
clientProxy.registerService(serviceName, groupName, instance);
@ -169,13 +175,6 @@ public class NamingHttpClientProxyTest {
a.setCode(200);
when(nacosRestTemplate.exchangeForm(any(), any(), any(), any(), any(), any())).thenReturn(a);
SecurityProxy proxy = mock(SecurityProxy.class);
ServerListManager mgr = mock(ServerListManager.class);
when(mgr.getServerList()).thenReturn(Arrays.asList("localhost"));
Properties props = new Properties();
ServiceInfoHolder holder = mock(ServiceInfoHolder.class);
NamingHttpClientProxy clientProxy = new NamingHttpClientProxy("namespaceId", proxy, mgr, props, holder);
final Field nacosRestTemplateField = NamingHttpClientProxy.class.getDeclaredField("nacosRestTemplate");
nacosRestTemplateField.setAccessible(true);
nacosRestTemplateField.set(clientProxy, nacosRestTemplate);
@ -183,6 +182,7 @@ public class NamingHttpClientProxyTest {
String serviceName = "service1";
String groupName = "group1";
Instance instance = new Instance();
instance.setEphemeral(false);
//when
clientProxy.deregisterService(serviceName, groupName, instance);
//then
@ -198,13 +198,6 @@ public class NamingHttpClientProxyTest {
a.setCode(200);
when(nacosRestTemplate.exchangeForm(any(), any(), any(), any(), any(), any())).thenReturn(a);
SecurityProxy proxy = mock(SecurityProxy.class);
ServerListManager mgr = mock(ServerListManager.class);
when(mgr.getServerList()).thenReturn(Arrays.asList("localhost"));
Properties props = new Properties();
ServiceInfoHolder holder = mock(ServiceInfoHolder.class);
NamingHttpClientProxy clientProxy = new NamingHttpClientProxy("namespaceId", proxy, mgr, props, holder);
final Field nacosRestTemplateField = NamingHttpClientProxy.class.getDeclaredField("nacosRestTemplate");
nacosRestTemplateField.setAccessible(true);
nacosRestTemplateField.set(clientProxy, nacosRestTemplate);
@ -227,13 +220,6 @@ public class NamingHttpClientProxyTest {
a.setCode(200);
when(nacosRestTemplate.exchangeForm(any(), any(), any(), any(), any(), any())).thenReturn(a);
SecurityProxy proxy = mock(SecurityProxy.class);
ServerListManager mgr = mock(ServerListManager.class);
when(mgr.getServerList()).thenReturn(Arrays.asList("localhost"));
Properties props = new Properties();
ServiceInfoHolder holder = mock(ServiceInfoHolder.class);
NamingHttpClientProxy clientProxy = new NamingHttpClientProxy("namespaceId", proxy, mgr, props, holder);
final Field nacosRestTemplateField = NamingHttpClientProxy.class.getDeclaredField("nacosRestTemplate");
nacosRestTemplateField.setAccessible(true);
nacosRestTemplateField.set(clientProxy, nacosRestTemplate);
@ -258,13 +244,6 @@ public class NamingHttpClientProxyTest {
a.setCode(200);
when(nacosRestTemplate.exchangeForm(any(), any(), any(), any(), any(), any())).thenReturn(a);
SecurityProxy proxy = mock(SecurityProxy.class);
ServerListManager mgr = mock(ServerListManager.class);
when(mgr.getServerList()).thenReturn(Arrays.asList("localhost"));
Properties props = new Properties();
ServiceInfoHolder holder = mock(ServiceInfoHolder.class);
NamingHttpClientProxy clientProxy = new NamingHttpClientProxy("namespaceId", proxy, mgr, props, holder);
final Field nacosRestTemplateField = NamingHttpClientProxy.class.getDeclaredField("nacosRestTemplate");
nacosRestTemplateField.setAccessible(true);
nacosRestTemplateField.set(clientProxy, nacosRestTemplate);
@ -290,13 +269,6 @@ public class NamingHttpClientProxyTest {
a.setCode(200);
when(nacosRestTemplate.exchangeForm(any(), any(), any(), any(), any(), any())).thenReturn(a);
SecurityProxy proxy = mock(SecurityProxy.class);
ServerListManager mgr = mock(ServerListManager.class);
when(mgr.getServerList()).thenReturn(Arrays.asList("localhost"));
Properties props = new Properties();
ServiceInfoHolder holder = mock(ServiceInfoHolder.class);
NamingHttpClientProxy clientProxy = new NamingHttpClientProxy("namespaceId", proxy, mgr, props, holder);
final Field nacosRestTemplateField = NamingHttpClientProxy.class.getDeclaredField("nacosRestTemplate");
nacosRestTemplateField.setAccessible(true);
nacosRestTemplateField.set(clientProxy, nacosRestTemplate);
@ -317,13 +289,6 @@ public class NamingHttpClientProxyTest {
a.setCode(200);
when(nacosRestTemplate.exchangeForm(any(), any(), any(), any(), any(), any())).thenReturn(a);
SecurityProxy proxy = mock(SecurityProxy.class);
ServerListManager mgr = mock(ServerListManager.class);
when(mgr.getServerList()).thenReturn(Arrays.asList("localhost"));
Properties props = new Properties();
ServiceInfoHolder holder = mock(ServiceInfoHolder.class);
NamingHttpClientProxy clientProxy = new NamingHttpClientProxy("namespaceId", proxy, mgr, props, holder);
final Field nacosRestTemplateField = NamingHttpClientProxy.class.getDeclaredField("nacosRestTemplate");
nacosRestTemplateField.setAccessible(true);
nacosRestTemplateField.set(clientProxy, nacosRestTemplate);
@ -346,13 +311,6 @@ public class NamingHttpClientProxyTest {
a.setCode(200);
when(nacosRestTemplate.exchangeForm(any(), any(), any(), any(), any(), any())).thenReturn(a);
SecurityProxy proxy = mock(SecurityProxy.class);
ServerListManager mgr = mock(ServerListManager.class);
when(mgr.getServerList()).thenReturn(Arrays.asList("localhost"));
Properties props = new Properties();
ServiceInfoHolder holder = mock(ServiceInfoHolder.class);
NamingHttpClientProxy clientProxy = new NamingHttpClientProxy("namespaceId", proxy, mgr, props, holder);
final Field nacosRestTemplateField = NamingHttpClientProxy.class.getDeclaredField("nacosRestTemplate");
nacosRestTemplateField.setAccessible(true);
nacosRestTemplateField.set(clientProxy, nacosRestTemplate);
@ -367,35 +325,6 @@ public class NamingHttpClientProxyTest {
}
@Test
public void testSendBeat() throws Exception {
//given
NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class);
HttpRestResult<Object> a = new HttpRestResult<Object>();
a.setData("");
a.setCode(200);
when(nacosRestTemplate.exchangeForm(any(), any(), any(), any(), any(), any())).thenReturn(a);
SecurityProxy proxy = mock(SecurityProxy.class);
ServerListManager mgr = mock(ServerListManager.class);
when(mgr.getServerList()).thenReturn(Arrays.asList("localhost"));
Properties props = new Properties();
ServiceInfoHolder holder = mock(ServiceInfoHolder.class);
NamingHttpClientProxy clientProxy = new NamingHttpClientProxy("namespaceId", proxy, mgr, props, holder);
final Field nacosRestTemplateField = NamingHttpClientProxy.class.getDeclaredField("nacosRestTemplate");
nacosRestTemplateField.setAccessible(true);
nacosRestTemplateField.set(clientProxy, nacosRestTemplate);
BeatInfo beat = new BeatInfo();
//when
clientProxy.sendBeat(beat, true);
//then
verify(nacosRestTemplate, times(1))
.exchangeForm(endsWith("/instance/beat"), any(), any(), any(), eq(HttpMethod.PUT), any());
}
@Test
public void testServerHealthy() throws Exception {
//given
@ -405,13 +334,6 @@ public class NamingHttpClientProxyTest {
a.setCode(200);
when(nacosRestTemplate.exchangeForm(any(), any(), any(), any(), any(), any())).thenReturn(a);
SecurityProxy proxy = mock(SecurityProxy.class);
ServerListManager mgr = mock(ServerListManager.class);
when(mgr.getServerList()).thenReturn(Arrays.asList("localhost"));
Properties props = new Properties();
ServiceInfoHolder holder = mock(ServiceInfoHolder.class);
NamingHttpClientProxy clientProxy = new NamingHttpClientProxy("namespaceId", proxy, mgr, props, holder);
final Field nacosRestTemplateField = NamingHttpClientProxy.class.getDeclaredField("nacosRestTemplate");
nacosRestTemplateField.setAccessible(true);
nacosRestTemplateField.set(clientProxy, nacosRestTemplate);
@ -435,13 +357,6 @@ public class NamingHttpClientProxyTest {
a.setCode(200);
when(nacosRestTemplate.exchangeForm(any(), any(), any(), any(), any(), any())).thenReturn(a);
SecurityProxy proxy = mock(SecurityProxy.class);
ServerListManager mgr = mock(ServerListManager.class);
when(mgr.getServerList()).thenReturn(Arrays.asList("localhost"));
Properties props = new Properties();
ServiceInfoHolder holder = mock(ServiceInfoHolder.class);
NamingHttpClientProxy clientProxy = new NamingHttpClientProxy("namespaceId", proxy, mgr, props, holder);
final Field nacosRestTemplateField = NamingHttpClientProxy.class.getDeclaredField("nacosRestTemplate");
nacosRestTemplateField.setAccessible(true);
nacosRestTemplateField.set(clientProxy, nacosRestTemplate);
@ -457,58 +372,18 @@ public class NamingHttpClientProxyTest {
Assert.assertEquals("bbb", serviceList.getData().get(1));
}
@Test
@Test(expected = UnsupportedOperationException.class)
public void testSubscribe() throws Exception {
//given
NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class);
HttpRestResult<Object> a = new HttpRestResult<Object>();
a.setData("");
a.setCode(200);
when(nacosRestTemplate.exchangeForm(any(), any(), any(), any(), any(), any())).thenReturn(a);
SecurityProxy proxy = mock(SecurityProxy.class);
ServerListManager mgr = mock(ServerListManager.class);
when(mgr.getServerList()).thenReturn(Arrays.asList("localhost"));
Properties props = new Properties();
ServiceInfoHolder holder = mock(ServiceInfoHolder.class);
NamingHttpClientProxy clientProxy = new NamingHttpClientProxy("namespaceId", proxy, mgr, props, holder);
final Field nacosRestTemplateField = NamingHttpClientProxy.class.getDeclaredField("nacosRestTemplate");
nacosRestTemplateField.setAccessible(true);
nacosRestTemplateField.set(clientProxy, nacosRestTemplate);
String groupName = "group1";
String serviceName = "serviceName";
String clusters = "clusters";
//when
ServiceInfo serviceInfo = clientProxy.subscribe(serviceName, groupName, clusters);
//then
verify(nacosRestTemplate, times(1))
.exchangeForm(endsWith("/instance/list"), any(), any(), any(), eq(HttpMethod.GET), any());
Assert.assertEquals(groupName + "@@" + serviceName, serviceInfo.getName());
Assert.assertEquals(clusters, serviceInfo.getClusters());
}
@Test
public void testUnsubscribe() throws Exception {
//TODO thrown.expect(UnsupportedOperationException.class);
//given
NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class);
HttpRestResult<Object> a = new HttpRestResult<Object>();
a.setData("");
a.setCode(200);
when(nacosRestTemplate.exchangeForm(any(), any(), any(), any(), any(), any())).thenReturn(a);
SecurityProxy proxy = mock(SecurityProxy.class);
ServerListManager mgr = mock(ServerListManager.class);
when(mgr.getServerList()).thenReturn(Arrays.asList("localhost"));
Properties props = new Properties();
ServiceInfoHolder holder = mock(ServiceInfoHolder.class);
NamingHttpClientProxy clientProxy = new NamingHttpClientProxy("namespaceId", proxy, mgr, props, holder);
final Field nacosRestTemplateField = NamingHttpClientProxy.class.getDeclaredField("nacosRestTemplate");
nacosRestTemplateField.setAccessible(true);
nacosRestTemplateField.set(clientProxy, nacosRestTemplate);
String groupName = "group1";
String serviceName = "serviceName";
String clusters = "clusters";
@ -517,44 +392,6 @@ public class NamingHttpClientProxyTest {
clientProxy.unsubscribe(serviceName, groupName, clusters);
}
@Test
public void testUpdateBeatInfo() throws Exception {
//given
BeatReactor mockBeatReactor = mock(BeatReactor.class);
Field dom2Beat = BeatReactor.class.getDeclaredField("dom2Beat");
ConcurrentHashMap<String, BeatInfo> beatMap = new ConcurrentHashMap<>();
String beatServiceName = "service1#127.0.0.1#10000";
beatMap.put(beatServiceName, new BeatInfo());
dom2Beat.setAccessible(true);
dom2Beat.set(mockBeatReactor, beatMap);
SecurityProxy proxy = mock(SecurityProxy.class);
ServerListManager mgr = mock(ServerListManager.class);
when(mgr.getServerList()).thenReturn(Arrays.asList("localhost"));
Properties props = new Properties();
ServiceInfoHolder holder = mock(ServiceInfoHolder.class);
NamingHttpClientProxy clientProxy = new NamingHttpClientProxy("namespaceId", proxy, mgr, props, holder);
final Field mockBeatReactorField = NamingHttpClientProxy.class.getDeclaredField("beatReactor");
mockBeatReactorField.setAccessible(true);
mockBeatReactorField.set(clientProxy, mockBeatReactor);
Instance instance = new Instance();
instance.setInstanceId("id1");
instance.setIp("127.0.0.1");
instance.setPort(10000);
instance.setServiceName("service1");
instance.setClusterName("cluster1");
Set<Instance> beats = new HashSet<>();
beats.add(instance);
when(mockBeatReactor.buildKey("service1", "127.0.0.1", 10000)).thenReturn(beatServiceName);
//when
clientProxy.updateBeatInfo(beats);
//then
verify(mockBeatReactor, times(1)).addBeatInfo(eq("service1"), any());
}
@Test
public void testReqApi() throws Exception {
//given
@ -568,13 +405,6 @@ public class NamingHttpClientProxyTest {
return res;
});
SecurityProxy proxy = mock(SecurityProxy.class);
ServerListManager mgr = mock(ServerListManager.class);
when(mgr.getServerList()).thenReturn(Arrays.asList("localhost"));
ServiceInfoHolder holder = mock(ServiceInfoHolder.class);
NamingHttpClientProxy clientProxy = new NamingHttpClientProxy("namespaceId", proxy, mgr, new Properties(),
holder);
final Field nacosRestTemplateField = NamingHttpClientProxy.class.getDeclaredField("nacosRestTemplate");
nacosRestTemplateField.setAccessible(true);
nacosRestTemplateField.set(clientProxy, nacosRestTemplate);
@ -601,13 +431,6 @@ public class NamingHttpClientProxyTest {
return res;
});
SecurityProxy proxy = mock(SecurityProxy.class);
ServerListManager mgr = mock(ServerListManager.class);
when(mgr.getServerList()).thenReturn(Arrays.asList("localhost"));
ServiceInfoHolder holder = mock(ServiceInfoHolder.class);
NamingHttpClientProxy clientProxy = new NamingHttpClientProxy("namespaceId", proxy, mgr, new Properties(),
holder);
final Field nacosRestTemplateField = NamingHttpClientProxy.class.getDeclaredField("nacosRestTemplate");
nacosRestTemplateField.setAccessible(true);
nacosRestTemplateField.set(clientProxy, nacosRestTemplate);
@ -634,13 +457,6 @@ public class NamingHttpClientProxyTest {
return res;
});
SecurityProxy proxy = mock(SecurityProxy.class);
ServerListManager mgr = mock(ServerListManager.class);
when(mgr.getServerList()).thenReturn(Arrays.asList("localhost"));
ServiceInfoHolder holder = mock(ServiceInfoHolder.class);
NamingHttpClientProxy clientProxy = new NamingHttpClientProxy("namespaceId", proxy, mgr, new Properties(),
holder);
final Field nacosRestTemplateField = NamingHttpClientProxy.class.getDeclaredField("nacosRestTemplate");
nacosRestTemplateField.setAccessible(true);
nacosRestTemplateField.set(clientProxy, nacosRestTemplate);
@ -671,13 +487,6 @@ public class NamingHttpClientProxyTest {
return res;
});
SecurityProxy proxy = mock(SecurityProxy.class);
ServerListManager mgr = mock(ServerListManager.class);
when(mgr.getServerList()).thenReturn(Arrays.asList("localhost"));
ServiceInfoHolder holder = mock(ServiceInfoHolder.class);
NamingHttpClientProxy clientProxy = new NamingHttpClientProxy("namespaceId", proxy, mgr, new Properties(),
holder);
final Field nacosRestTemplateField = NamingHttpClientProxy.class.getDeclaredField("nacosRestTemplate");
nacosRestTemplateField.setAccessible(true);
nacosRestTemplateField.set(clientProxy, nacosRestTemplate);
@ -704,13 +513,6 @@ public class NamingHttpClientProxyTest {
return res;
});
SecurityProxy proxy = mock(SecurityProxy.class);
ServerListManager mgr = mock(ServerListManager.class);
when(mgr.getServerList()).thenReturn(Arrays.asList("localhost"));
ServiceInfoHolder holder = mock(ServiceInfoHolder.class);
NamingHttpClientProxy clientProxy = new NamingHttpClientProxy("namespaceId", proxy, mgr, new Properties(),
holder);
final Field nacosRestTemplateField = NamingHttpClientProxy.class.getDeclaredField("nacosRestTemplate");
nacosRestTemplateField.setAccessible(true);
nacosRestTemplateField.set(clientProxy, nacosRestTemplate);
@ -727,83 +529,16 @@ public class NamingHttpClientProxyTest {
@Test
public void testGetNamespaceId() {
//given
// NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class);
// HttpRestResult<Object> a = new HttpRestResult<Object>();
// a.setData("");
// a.setCode(200);
// when(nacosRestTemplate.exchangeForm(any(), any(), any(), any(), any(), any())).thenReturn(a);
SecurityProxy proxy = mock(SecurityProxy.class);
ServerListManager mgr = mock(ServerListManager.class);
when(mgr.getServerList()).thenReturn(Arrays.asList("localhost"));
Properties props = new Properties();
ServiceInfoHolder holder = mock(ServiceInfoHolder.class);
String namespaceId = "aaa";
NamingHttpClientProxy clientProxy = new NamingHttpClientProxy(namespaceId, proxy, mgr, props, holder);
// final Field nacosRestTemplateField = NamingHttpClientProxy.class.getDeclaredField("nacosRestTemplate");
// nacosRestTemplateField.setAccessible(true);
// nacosRestTemplateField.set(clientProxy, nacosRestTemplate);
//when
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(props);
NamingHttpClientProxy clientProxy = new NamingHttpClientProxy(namespaceId, proxy, mgr, nacosClientProperties);
String actualNamespaceId = clientProxy.getNamespaceId();
Assert.assertEquals(namespaceId, actualNamespaceId);
}
@Test
public void testSetServerPort() {
SecurityProxy proxy = mock(SecurityProxy.class);
ServerListManager mgr = mock(ServerListManager.class);
when(mgr.getServerList()).thenReturn(Arrays.asList("localhost"));
Properties props = new Properties();
ServiceInfoHolder holder = mock(ServiceInfoHolder.class);
String namespaceId = "aaa";
NamingHttpClientProxy clientProxy = new NamingHttpClientProxy(namespaceId, proxy, mgr, props, holder);
//when
clientProxy.setServerPort(1234);
Assert.assertEquals(1234, ReflectUtils.getFieldValue(clientProxy, "serverPort"));
}
@Test
public void testGetBeatReactor() throws Exception {
SecurityProxy proxy = mock(SecurityProxy.class);
ServerListManager mgr = mock(ServerListManager.class);
when(mgr.getServerList()).thenReturn(Arrays.asList("localhost"));
Properties props = new Properties();
ServiceInfoHolder holder = mock(ServiceInfoHolder.class);
String namespaceId = "aaa";
NamingHttpClientProxy clientProxy = new NamingHttpClientProxy(namespaceId, proxy, mgr, props, holder);
BeatReactor mockBeatReactor = mock(BeatReactor.class);
final Field mockBeatReactorField = NamingHttpClientProxy.class.getDeclaredField("beatReactor");
mockBeatReactorField.setAccessible(true);
mockBeatReactorField.set(clientProxy, mockBeatReactor);
//when
BeatReactor beatReactor = clientProxy.getBeatReactor();
//then
Assert.assertEquals(mockBeatReactor, beatReactor);
}
@Test
public void testShutdown() throws Exception {
SecurityProxy proxy = mock(SecurityProxy.class);
ServerListManager mgr = mock(ServerListManager.class);
when(mgr.getServerList()).thenReturn(Arrays.asList("localhost"));
Properties props = new Properties();
ServiceInfoHolder holder = mock(ServiceInfoHolder.class);
String namespaceId = "aaa";
NamingHttpClientProxy clientProxy = new NamingHttpClientProxy(namespaceId, proxy, mgr, props, holder);
BeatReactor mockBeatReactor = mock(BeatReactor.class);
final Field mockBeatReactorField = NamingHttpClientProxy.class.getDeclaredField("beatReactor");
mockBeatReactorField.setAccessible(true);
mockBeatReactorField.set(clientProxy, mockBeatReactor);
//when
clientProxy.shutdown();
//then
verify(mockBeatReactor, times(1)).shutdown();
}
}
}

View File

@ -18,18 +18,17 @@ package com.alibaba.nacos.client.naming.utils;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.SystemPropertyKeyConst;
import com.alibaba.nacos.client.env.NacosClientProperties;
import org.junit.Assert;
import org.junit.Test;
import java.util.Properties;
public class InitUtilsTest {
@Test
public void testInitWebRootContext() {
String ctx = "/aaa";
Properties properties = new Properties();
properties.put(PropertyKeyConst.CONTEXT_PATH, ctx);
final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive();
properties.setProperty(PropertyKeyConst.CONTEXT_PATH, ctx);
InitUtils.initWebRootContext(properties);
Assert.assertEquals(ctx, UtilAndComs.webContext);
Assert.assertEquals(ctx + "/v1/ns", UtilAndComs.nacosUrlBase);
@ -42,17 +41,17 @@ public class InitUtilsTest {
@Test
public void testInitNamespaceForNamingDefault() {
//DEFAULT
Properties prop = new Properties();
String ns = InitUtils.initNamespaceForNaming(prop);
final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive();
String ns = InitUtils.initNamespaceForNaming(properties);
Assert.assertEquals("public", ns);
}
@Test
public void testInitNamespaceForNamingFromProp() {
Properties prop = new Properties();
final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive();
String expect = "ns1";
prop.put(PropertyKeyConst.NAMESPACE, expect);
String ns = InitUtils.initNamespaceForNaming(prop);
properties.setProperty(PropertyKeyConst.NAMESPACE, expect);
String ns = InitUtils.initNamespaceForNaming(properties);
Assert.assertEquals(expect, ns);
}
@ -61,9 +60,8 @@ public class InitUtilsTest {
try {
String expect1 = "ns1";
System.setProperty(PropertyKeyConst.NAMESPACE, expect1);
Properties prop = new Properties();
prop.put(PropertyKeyConst.NAMESPACE, "cccccc");
String ns = InitUtils.initNamespaceForNaming(prop);
final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive();
String ns = InitUtils.initNamespaceForNaming(properties);
Assert.assertEquals(expect1, ns);
} finally {
System.clearProperty(PropertyKeyConst.NAMESPACE);
@ -77,11 +75,11 @@ public class InitUtilsTest {
public void testInitNamespaceForNamingFromCloud() {
try {
String expect1 = "ns1";
System.setProperty(PropertyKeyConst.IS_USE_CLOUD_NAMESPACE_PARSING, " true");
System.setProperty(PropertyKeyConst.IS_USE_CLOUD_NAMESPACE_PARSING, "true");
System.setProperty(SystemPropertyKeyConst.ANS_NAMESPACE, expect1);
Properties prop = new Properties();
prop.put(PropertyKeyConst.NAMESPACE, "cccccc");
String ns = InitUtils.initNamespaceForNaming(prop);
final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive();
properties.setProperty(PropertyKeyConst.NAMESPACE, "cccccc");
String ns = InitUtils.initNamespaceForNaming(properties);
Assert.assertEquals(expect1, ns);
} finally {
System.clearProperty(PropertyKeyConst.IS_USE_CLOUD_NAMESPACE_PARSING);
@ -92,12 +90,12 @@ public class InitUtilsTest {
@Test
public void testInitEndpoint() {
Properties prop = new Properties();
final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive();
String endpoint = "1.1.1.1";
String endpointPort = "1234";
prop.put(PropertyKeyConst.ENDPOINT, endpoint);
prop.put(PropertyKeyConst.ENDPOINT_PORT, endpointPort);
String actual = InitUtils.initEndpoint(prop);
properties.setProperty(PropertyKeyConst.ENDPOINT, endpoint);
properties.setProperty(PropertyKeyConst.ENDPOINT_PORT, endpointPort);
String actual = InitUtils.initEndpoint(properties);
Assert.assertEquals(endpoint + ":" + endpointPort, actual);
}
@ -105,10 +103,10 @@ public class InitUtilsTest {
public void testInitEndpointAns() {
try {
System.setProperty(PropertyKeyConst.IS_USE_ENDPOINT_PARSING_RULE, "true");
Properties prop = new Properties();
final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive();
String endpoint = "${key:test.com}";
prop.put(PropertyKeyConst.ENDPOINT, endpoint);
String actual = InitUtils.initEndpoint(prop);
properties.setProperty(PropertyKeyConst.ENDPOINT, endpoint);
String actual = InitUtils.initEndpoint(properties);
//defaultEndpointPort is "8080";
Assert.assertEquals("test.com:8080", actual);
} finally {

View File

@ -0,0 +1,118 @@
/*
*
* 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.utils;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.client.naming.utils.Chooser;
import com.alibaba.nacos.client.naming.utils.Pair;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import static org.junit.Assert.assertTrue;
public class ChooserTest {
//Test the correctness of Chooser, the weight of the final selected instance must be greater than 0
@Test
public void testChooser() {
List<Instance> hosts = getInstanceList();
Instance target = getRandomInstance(hosts);
assertTrue(hosts.contains(target) && target.getWeight() > 0);
}
private List<Instance> getInstanceList() {
List<Instance> list = new ArrayList<>();
int size = ThreadLocalRandom.current().nextInt(0, 1000);
for (int i = 0; i < size; i++) {
Instance instance = new Instance();
instance.setInstanceId(String.valueOf(i));
instance.setWeight(i);
list.add(instance);
}
return list;
}
// If there is only one instance whose weight is not zero, it will be selected
@Test
public void testOnlyOneInstanceWeightIsNotZero() {
List<Instance> hosts = getOneInstanceNotZeroList();
Instance target = getRandomInstance(hosts);
assertTrue(target.getWeight() > 0);
}
// getOneInstanceNotZeroList
private List<Instance> getOneInstanceNotZeroList() {
List<Instance> list = new ArrayList<>();
int size = ThreadLocalRandom.current().nextInt(0, 1000);
int notZeroIndex = ThreadLocalRandom.current().nextInt(0, size - 1);
for (int i = 0; i < size; i++) {
Instance instance = new Instance();
instance.setInstanceId(String.valueOf(i));
if (i == notZeroIndex) {
instance.setWeight(notZeroIndex + 1);
} else {
instance.setWeight(0);
}
list.add(instance);
}
return list;
}
// Throw an IllegalStateException when all instances have a weight of zero.
@Test
public void testInstanceWeightAllZero() {
List<Instance> hosts = getInstanceWeightAllZero();
try {
getRandomInstance(hosts);
} catch (Exception e) {
assertTrue(e instanceof IllegalStateException);
}
}
private List<Instance> getInstanceWeightAllZero() {
List<Instance> list = new ArrayList<>();
int size = ThreadLocalRandom.current().nextInt(0, 1000);
for (int i = 0; i < size; i++) {
Instance instance = new Instance();
instance.setInstanceId(String.valueOf(i));
instance.setWeight(0);
list.add(instance);
}
return list;
}
private Instance getRandomInstance(List<Instance> hosts) {
List<Pair<Instance>> hostsWithWeight = new ArrayList<>();
for (Instance host : hosts) {
if (host.isHealthy()) {
hostsWithWeight.add(new Pair<>(host, host.getWeight()));
}
}
Chooser<String, Instance> vipChooser = new Chooser<>("www.taobao.com", hostsWithWeight);
return vipChooser.randomWithWeight();
}
}

View File

@ -19,6 +19,7 @@
package com.alibaba.nacos.client.utils;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.client.env.NacosClientProperties;
import com.alibaba.nacos.common.utils.VersionUtils;
import org.junit.After;
import org.junit.Assert;
@ -147,7 +148,9 @@ public class ParamUtilTest {
String expect = "test";
Properties properties = new Properties();
properties.setProperty(PropertyKeyConst.NAMESPACE, expect);
String actual = ParamUtil.parseNamespace(properties);
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(properties);
String actual = ParamUtil.parseNamespace(nacosClientProperties);
Assert.assertEquals(expect, actual);
}

View File

@ -18,6 +18,7 @@ package com.alibaba.nacos.client.utils;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.client.env.NacosClientProperties;
import org.junit.Assert;
import org.junit.Test;
@ -66,7 +67,9 @@ public class ValidatorUtilsTest {
try {
Properties properties = new Properties();
properties.setProperty(PropertyKeyConst.CONTEXT_PATH, "test");
ValidatorUtils.checkInitParam(properties);
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(properties);
ValidatorUtils.checkInitParam(nacosClientProperties);
} catch (NacosException e) {
Assert.fail();
}

View File

@ -34,5 +34,7 @@ public interface HttpHeaderConsts {
String CONNECTION = "Requester";
String REQUEST_ID = "RequestId";
String REQUEST_MODULE = "Request-Module";
String APP_FILED = "app";
String CLIENT_IP = "clientIp";
}

View File

@ -16,6 +16,7 @@
package com.alibaba.nacos.common.http;
import com.alibaba.nacos.common.executor.NameThreadFactory;
import com.alibaba.nacos.common.http.client.NacosAsyncRestTemplate;
import com.alibaba.nacos.common.http.client.NacosRestTemplate;
import com.alibaba.nacos.common.http.client.request.DefaultAsyncHttpClientRequest;
@ -24,7 +25,9 @@ import com.alibaba.nacos.common.tls.SelfHostnameVerifier;
import com.alibaba.nacos.common.tls.TlsFileWatcher;
import com.alibaba.nacos.common.tls.TlsHelper;
import com.alibaba.nacos.common.tls.TlsSystemConfig;
import java.util.function.BiConsumer;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
@ -58,6 +61,10 @@ import java.security.NoSuchAlgorithmException;
*/
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";
@Override
public NacosRestTemplate createNacosRestTemplate() {
HttpClientConfig httpClientConfig = buildHttpClientConfig();
@ -75,68 +82,67 @@ public abstract class AbstractHttpClientFactory implements HttpClientFactory {
@Override
public NacosAsyncRestTemplate createNacosAsyncRestTemplate() {
final HttpClientConfig originalRequestConfig = buildHttpClientConfig();
final DefaultConnectingIOReactor ioreactor = getIoReactor();
final DefaultConnectingIOReactor ioreactor = getIoReactor(AYNC_IO_REACTOR_NAME);
final RequestConfig defaultConfig = getRequestConfig();
return new NacosAsyncRestTemplate(assignLogger(), new DefaultAsyncHttpClientRequest(
HttpAsyncClients.custom()
.addInterceptorLast(new RequestContent(true))
.setDefaultIOReactorConfig(getIoReactorConfig())
.setDefaultRequestConfig(defaultConfig)
HttpAsyncClients.custom().addInterceptorLast(new RequestContent(true))
.setThreadFactory(new NameThreadFactory(ASYNC_THREAD_NAME))
.setDefaultIOReactorConfig(getIoReactorConfig()).setDefaultRequestConfig(defaultConfig)
.setMaxConnTotal(originalRequestConfig.getMaxConnTotal())
.setMaxConnPerRoute(originalRequestConfig.getMaxConnPerRoute())
.setUserAgent(originalRequestConfig.getUserAgent())
.setConnectionManager(getConnectionManager(originalRequestConfig, ioreactor))
.build(), ioreactor, defaultConfig));
.setConnectionManager(getConnectionManager(originalRequestConfig, ioreactor)).build(),
ioreactor, defaultConfig));
}
private DefaultConnectingIOReactor getIoReactor() {
private DefaultConnectingIOReactor getIoReactor(String threadName) {
final DefaultConnectingIOReactor ioreactor;
try {
ioreactor = new DefaultConnectingIOReactor(getIoReactorConfig());
ioreactor = new DefaultConnectingIOReactor(getIoReactorConfig(), new NameThreadFactory(threadName));
} catch (IOReactorException e) {
assignLogger().error("[NHttpClientConnectionManager] Create DefaultConnectingIOReactor failed", e);
throw new IllegalStateException();
}
// if the handle return true, then the exception thrown by IOReactor will be ignore, and will not finish the IOReactor.
ioreactor.setExceptionHandler(new IOReactorExceptionHandler() {
@Override
public boolean handle(IOException ex) {
assignLogger().warn("[NHttpClientConnectionManager] handle IOException, ignore it.", ex);
return true;
}
@Override
public boolean handle(RuntimeException ex) {
assignLogger().warn("[NHttpClientConnectionManager] handle RuntimeException, ignore it.", ex);
return true;
}
});
return ioreactor;
}
/**
* create the {@link NHttpClientConnectionManager}, the code mainly from {@link HttpAsyncClientBuilder#build()}.
* we add the {@link IOReactorExceptionHandler} to handle the {@link IOException} and {@link RuntimeException}
* thrown by the {@link org.apache.http.impl.nio.reactor.BaseIOReactor} when process the event of Network.
* Using this way to avoid the {@link DefaultConnectingIOReactor} killed by unknown error of network.
* create the {@link NHttpClientConnectionManager}, the code mainly from {@link HttpAsyncClientBuilder#build()}. we
* add the {@link IOReactorExceptionHandler} to handle the {@link IOException} and {@link RuntimeException} thrown
* by the {@link org.apache.http.impl.nio.reactor.BaseIOReactor} when process the event of Network. Using this way
* to avoid the {@link DefaultConnectingIOReactor} killed by unknown error of network.
*
* @param originalRequestConfig request config.
* @param ioreactor I/O reactor.
* @param ioreactor I/O reactor.
* @return {@link NHttpClientConnectionManager}.
*/
private NHttpClientConnectionManager getConnectionManager(HttpClientConfig originalRequestConfig, DefaultConnectingIOReactor ioreactor) {
private NHttpClientConnectionManager getConnectionManager(HttpClientConfig originalRequestConfig,
DefaultConnectingIOReactor ioreactor) {
SSLContext sslcontext = SSLContexts.createDefault();
HostnameVerifier hostnameVerifier = new DefaultHostnameVerifier();
SchemeIOSessionStrategy sslStrategy = new SSLIOSessionStrategy(sslcontext, null, null, hostnameVerifier);
Registry<SchemeIOSessionStrategy> registry = RegistryBuilder.<SchemeIOSessionStrategy>create()
.register("http", NoopIOSessionStrategy.INSTANCE)
.register("https", sslStrategy)
.build();
final PoolingNHttpClientConnectionManager poolingmgr = new PoolingNHttpClientConnectionManager(ioreactor, registry);
.register("http", NoopIOSessionStrategy.INSTANCE).register("https", sslStrategy).build();
final PoolingNHttpClientConnectionManager poolingmgr = new PoolingNHttpClientConnectionManager(ioreactor,
registry);
int maxTotal = originalRequestConfig.getMaxConnTotal();
if (maxTotal > 0) {

View File

@ -38,8 +38,7 @@ public final class HttpClientBeanHolder {
private static final Map<String, NacosRestTemplate> SINGLETON_REST = new HashMap<>(10);
private static final Map<String, NacosAsyncRestTemplate> SINGLETON_ASYNC_REST = new HashMap<>(
10);
private static final Map<String, NacosAsyncRestTemplate> SINGLETON_ASYNC_REST = new HashMap<>(10);
private static final AtomicBoolean ALREADY_SHUTDOWN = new AtomicBoolean(false);
@ -101,11 +100,14 @@ public final class HttpClientBeanHolder {
return;
}
LOGGER.warn("[HttpClientBeanHolder] Start destroying common HttpClient");
try {
shutdown(DefaultHttpClientFactory.class.getName());
} catch (Exception ex) {
LOGGER.error("An exception occurred when the common HTTP client was closed : {}", ExceptionUtil.getStackTrace(ex));
LOGGER.error("An exception occurred when the common HTTP client was closed : {}",
ExceptionUtil.getStackTrace(ex));
}
LOGGER.warn("[HttpClientBeanHolder] Destruction of the end");
}

View File

@ -102,18 +102,12 @@ public class DefaultPublisher extends Thread implements EventPublisher {
int waitTimes = 60;
// To ensure that messages are not lost, enable EventHandler when
// waiting for the first Subscriber to register
for (; ; ) {
if (shutdown || hasSubscriber() || waitTimes <= 0) {
break;
}
while (!shutdown && !hasSubscriber() && waitTimes > 0) {
ThreadUtils.sleep(1000L);
waitTimes--;
}
for (; ; ) {
if (shutdown) {
break;
}
while (!shutdown) {
final Event event = queue.take();
receiveEvent(event);
UPDATER.compareAndSet(this, lastEventSequence, Math.max(lastEventSequence, event.sequence()));

View File

@ -30,9 +30,9 @@ import java.util.List;
public abstract class SmartSubscriber extends Subscriber {
/**
* Returns which event type are smartsubscriber interested in.
* Returns which event type are smart subscriber interested in.
*
* @return The interestd event types.
* @return The interested event types.
*/
public abstract List<Class<? extends Event>> subscribeTypes();

View File

@ -628,7 +628,7 @@ public abstract class RpcClient implements Closeable {
public Response request(Request request, long timeoutMills) throws NacosException {
int retryTimes = 0;
Response response;
Exception exceptionThrow = null;
Throwable exceptionThrow = null;
long start = System.currentTimeMillis();
while (retryTimes < rpcClientConfig.retryTimes() && System.currentTimeMillis() < timeoutMills + start) {
boolean waitReconnect = false;
@ -661,7 +661,7 @@ public abstract class RpcClient implements Closeable {
lastActiveTimeStamp = System.currentTimeMillis();
return response;
} catch (Exception e) {
} catch (Throwable e) {
if (waitReconnect) {
try {
// wait client to reconnect.
@ -701,8 +701,8 @@ public abstract class RpcClient implements Closeable {
*/
public void asyncRequest(Request request, RequestCallBack callback) throws NacosException {
int retryTimes = 0;
Exception exceptionToThrow = null;
Throwable exceptionToThrow = null;
long start = System.currentTimeMillis();
while (retryTimes < rpcClientConfig.retryTimes() && System.currentTimeMillis() < start + callback
.getTimeout()) {
@ -714,7 +714,7 @@ public abstract class RpcClient implements Closeable {
}
this.currentConnection.asyncRequest(request, callback);
return;
} catch (Exception e) {
} catch (Throwable e) {
if (waitReconnect) {
try {
// wait client to reconnect.

View File

@ -48,6 +48,8 @@ public final class TaskExecuteWorker implements NacosTaskProcessor, Closeable {
private final AtomicBoolean closed;
private final InnerWorker realWorker;
public TaskExecuteWorker(final String name, final int mod, final int total) {
this(name, mod, total, null);
}
@ -57,7 +59,8 @@ public final class TaskExecuteWorker implements NacosTaskProcessor, Closeable {
this.queue = new ArrayBlockingQueue<>(QUEUE_CAPACITY);
this.closed = new AtomicBoolean(false);
this.log = null == logger ? LoggerFactory.getLogger(TaskExecuteWorker.class) : logger;
new InnerWorker(name).start();
realWorker = new InnerWorker(this.name);
realWorker.start();
}
public String getName() {
@ -95,6 +98,7 @@ public final class TaskExecuteWorker implements NacosTaskProcessor, Closeable {
public void shutdown() throws NacosException {
queue.clear();
closed.compareAndSet(false, true);
realWorker.interrupt();
}
/**
@ -119,7 +123,7 @@ public final class TaskExecuteWorker implements NacosTaskProcessor, Closeable {
log.warn("task {} takes {}ms", task, duration);
}
} catch (Throwable e) {
log.error("[TASK-FAILED] " + e.toString(), e);
log.error("[TASK-FAILED] " + e, e);
}
}
}

View File

@ -24,7 +24,10 @@ import com.alibaba.nacos.common.notify.Event;
* @author yanda
*/
public class TraceEvent extends Event {
private String type;
private static final long serialVersionUID = -3065900892505697062L;
private final String type;
private final long eventTime;

View File

@ -103,7 +103,6 @@ public class TraceEventPublisher extends Thread implements ShardedEventPublisher
boolean success = this.queue.offer(event);
if (!success) {
LOGGER.warn("Trace Event Publish failed, event : {}, publish queue size : {}", event, currentEventSize());
return true;
}
return true;
}

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