Remove Instance.java.

This commit is contained in:
KomachiSion 2022-08-29 16:44:47 +08:00
parent 77b3391e10
commit 48695dab16
7 changed files with 7 additions and 569 deletions

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);
}

View File

@ -22,12 +22,12 @@ 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.common.utils.StringUtils;
import com.alibaba.nacos.naming.core.ClusterOperator;
import com.alibaba.nacos.naming.core.Instance;
import com.alibaba.nacos.naming.core.InstanceOperator;
import com.alibaba.nacos.naming.core.v2.ServiceManager;
import com.alibaba.nacos.naming.core.v2.metadata.ClusterMetadata;

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;

View File

@ -1,377 +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.naming.core;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.common.utils.InternetAddressUtil;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.naming.healthcheck.HealthCheckStatus;
import com.alibaba.nacos.naming.misc.Loggers;
import com.alibaba.nacos.naming.misc.UtilsAndCommons;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.alibaba.nacos.common.utils.NumberUtils;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
/**
* IP under service.
*
* @author nkorange
*/
@JsonInclude(Include.NON_NULL)
public class Instance extends com.alibaba.nacos.api.naming.pojo.Instance implements Comparable {
private static final long serialVersionUID = -6527721638428975306L;
private volatile long lastBeat = System.currentTimeMillis();
@JsonIgnore
private volatile boolean mockValid = false;
private volatile boolean marked = false;
private String tenant;
private String app;
private static final String SPLITER = "_";
public Instance() {
}
public boolean isMockValid() {
return mockValid;
}
public void setMockValid(boolean mockValid) {
this.mockValid = mockValid;
}
public long getLastBeat() {
return lastBeat;
}
public void setLastBeat(long lastBeat) {
this.lastBeat = lastBeat;
}
public Instance(String ip, int port) {
this.setIp(ip);
this.setPort(port);
this.setClusterName(UtilsAndCommons.DEFAULT_CLUSTER_NAME);
}
public Instance(String ip, int port, String clusterName) {
this.setIp(ip.trim());
this.setPort(port);
this.setClusterName(clusterName);
}
public Instance(String ip, int port, String clusterName, String tenant, String app) {
this.setIp(ip.trim());
this.setPort(port);
this.setClusterName(clusterName);
this.tenant = tenant;
this.app = app;
}
/**
* Create {@link Instance} from encoding string.
*
* @param config instance encoding string
* @return new Instance
*/
public static Instance fromString(String config) {
String[] ipAddressAttributes = config.split(SPLITER);
if (ipAddressAttributes.length < 1) {
return null;
}
String provider = ipAddressAttributes[0];
String[] providerAddr;
try {
providerAddr = InternetAddressUtil.splitIPPortStr(provider);
} catch (Exception ex) {
return null;
}
int port = 0;
if (providerAddr.length == InternetAddressUtil.SPLIT_IP_PORT_RESULT_LENGTH && NumberUtils
.isDigits(providerAddr[1])) {
port = Integer.parseInt(providerAddr[1]);
}
Instance instance = new Instance(providerAddr[0], port);
// 7 possible formats of config:
// ip:port
// ip:port_weight
// ip:port_weight_cluster
// ip:port_weight_valid
// ip:port_weight_valid_cluster
// ip:port_weight_valid_marked
// ip:port_weight_valid_marked_cluster
int minimumLength = 1;
if (ipAddressAttributes.length > minimumLength) {
// determine 'weight':
instance.setWeight(NumberUtils.toDouble(ipAddressAttributes[minimumLength], 1));
}
minimumLength++;
if (ipAddressAttributes.length > minimumLength) {
// determine 'valid':
if (Boolean.TRUE.toString().equals(ipAddressAttributes[minimumLength]) || Boolean.FALSE.toString()
.equals(ipAddressAttributes[minimumLength])) {
instance.setHealthy(Boolean.parseBoolean(ipAddressAttributes[minimumLength]));
}
// determine 'cluster':
if (!Boolean.TRUE.toString().equals(ipAddressAttributes[ipAddressAttributes.length - 1]) && !Boolean.FALSE
.toString().equals(ipAddressAttributes[ipAddressAttributes.length - 1])) {
instance.setClusterName(ipAddressAttributes[ipAddressAttributes.length - 1]);
}
}
minimumLength++;
if (ipAddressAttributes.length > minimumLength) {
// determine 'marked':
if (Boolean.TRUE.toString().equals(ipAddressAttributes[minimumLength]) || Boolean.FALSE.toString()
.equals(ipAddressAttributes[minimumLength])) {
instance.setMarked(Boolean.parseBoolean(ipAddressAttributes[minimumLength]));
}
}
return instance;
}
public String toIpAddr() {
return getIp() + ":" + getPort();
}
@Override
public String toString() {
return getDatumKey() + SPLITER + getWeight() + SPLITER + isHealthy() + SPLITER + marked + SPLITER
+ getClusterName();
}
/**
* Serialize to Json.
*
* @return json string
*/
public String toJson() {
return JacksonUtils.toJson(this);
}
/**
* Create {@link Instance} from json string.
*
* @param json json string
* @return new Instance
*/
public static Instance fromJson(String json) {
Instance ip;
try {
ip = JacksonUtils.toObj(json, Instance.class);
} catch (Exception e) {
ip = fromString(json);
}
if (ip == null) {
throw new IllegalArgumentException("malformed ip config: " + json);
}
if (ip.getWeight() > com.alibaba.nacos.naming.constants.Constants.MAX_WEIGHT_VALUE) {
ip.setWeight(com.alibaba.nacos.naming.constants.Constants.MAX_WEIGHT_VALUE);
}
if (ip.getWeight() < com.alibaba.nacos.naming.constants.Constants.MIN_POSITIVE_WEIGHT_VALUE
&& ip.getWeight() > com.alibaba.nacos.naming.constants.Constants.MIN_WEIGHT_VALUE) {
ip.setWeight(com.alibaba.nacos.naming.constants.Constants.MIN_POSITIVE_WEIGHT_VALUE);
} else if (ip.getWeight() < com.alibaba.nacos.naming.constants.Constants.MIN_WEIGHT_VALUE) {
ip.setWeight(0.0D);
}
try {
ip.validate();
} catch (NacosException e) {
throw new IllegalArgumentException("malformed ip config: " + json);
}
return ip;
}
@Override
public boolean equals(Object obj) {
if (null == obj || obj.getClass() != getClass()) {
return false;
}
if (obj == this) {
return true;
}
Instance other = (Instance) obj;
// 0 means wild
return getIp().equals(other.getIp()) && (getPort() == other.getPort() || getPort() == 0)
&& this.isEphemeral() == other.isEphemeral();
}
@JsonIgnore
public String getDatumKey() {
if (getPort() > 0) {
return getIp() + ":" + getPort() + ":" + UtilsAndCommons.LOCALHOST_SITE + ":" + getClusterName();
} else {
return getIp() + ":" + UtilsAndCommons.LOCALHOST_SITE + ":" + getClusterName();
}
}
@JsonIgnore
public String getDefaultKey() {
if (getPort() > 0) {
return getIp() + ":" + getPort() + ":" + UtilsAndCommons.UNKNOWN_SITE;
} else {
return getIp() + ":" + UtilsAndCommons.UNKNOWN_SITE;
}
}
@Override
public int hashCode() {
return getIp().hashCode();
}
public void setBeingChecked(boolean isBeingChecked) {
HealthCheckStatus.get(this).isBeingChecked.set(isBeingChecked);
}
public boolean markChecking() {
return HealthCheckStatus.get(this).isBeingChecked.compareAndSet(false, true);
}
@JsonIgnore
public long getCheckRt() {
return HealthCheckStatus.get(this).checkRt;
}
@JsonIgnore
public AtomicInteger getOkCount() {
return HealthCheckStatus.get(this).checkOkCount;
}
@JsonIgnore
public AtomicInteger getFailCount() {
return HealthCheckStatus.get(this).checkFailCount;
}
@JsonIgnore
public void setCheckRt(long checkRt) {
HealthCheckStatus.get(this).checkRt = checkRt;
}
public boolean isMarked() {
return marked;
}
public void setMarked(boolean marked) {
this.marked = marked;
}
public String getApp() {
return app;
}
public void setApp(String app) {
this.app = app;
}
public String getTenant() {
return tenant;
}
public void setTenant(String tenant) {
this.tenant = tenant;
}
public String generateInstanceId() {
return getIp() + "#" + getPort() + "#" + getClusterName() + "#" + getServiceName();
}
/**
* Generate instance id.
*
* @param currentInstanceIds current instance ids
* @return new instance id
*/
public String generateInstanceId(Set<String> currentInstanceIds) {
String instanceIdGenerator = getInstanceIdGenerator();
if (Constants.SNOWFLAKE_INSTANCE_ID_GENERATOR.equalsIgnoreCase(instanceIdGenerator)) {
return generateSnowflakeInstanceId(currentInstanceIds);
} else {
return generateInstanceId();
}
}
private String generateSnowflakeInstanceId(Set<String> currentInstanceIds) {
int id = 0;
while (currentInstanceIds.contains(String.valueOf(id))) {
id++;
}
String idStr = String.valueOf(id);
currentInstanceIds.add(idStr);
return idStr;
}
/**
* Judge whether this instance is validate.
*
* @throws NacosException if instance is not validate
*/
public void validate() throws NacosException {
if (!InternetAddressUtil.isIP(getIp())) {
throw new NacosException(NacosException.INVALID_PARAM,
"instance format invalid: Your IP address is spelled incorrectly");
}
if (getWeight() > com.alibaba.nacos.naming.constants.Constants.MAX_WEIGHT_VALUE
|| getWeight() < com.alibaba.nacos.naming.constants.Constants.MIN_WEIGHT_VALUE) {
throw new NacosException(NacosException.INVALID_PARAM, "instance format invalid: The weights range from "
+ com.alibaba.nacos.naming.constants.Constants.MIN_WEIGHT_VALUE + " to "
+ com.alibaba.nacos.naming.constants.Constants.MAX_WEIGHT_VALUE);
}
}
@Override
public int compareTo(Object o) {
if (!(o instanceof Instance)) {
Loggers.SRV_LOG.error("[INSTANCE-COMPARE] Object is not an instance of IPAdress, object: {}", o.getClass());
throw new IllegalArgumentException("Object is not an instance of IPAdress,object: " + o.getClass());
}
Instance instance = (Instance) o;
String ipKey = instance.toString();
return this.toString().compareTo(ipKey);
}
}

View File

@ -16,12 +16,7 @@
package com.alibaba.nacos.naming.healthcheck;
import com.alibaba.nacos.naming.core.Instance;
import com.alibaba.nacos.naming.misc.Loggers;
import java.io.Serializable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
@ -41,44 +36,4 @@ public class HealthCheckStatus implements Serializable {
public AtomicInteger checkOkCount = new AtomicInteger(0);
public long checkRt = -1L;
private static ConcurrentMap<String, HealthCheckStatus> statusMap = new ConcurrentHashMap<>();
public static void reset(Instance instance) {
statusMap.put(buildKey(instance), new HealthCheckStatus());
}
/**
* Get health check status of instance.
*
* @param instance instance
* @return health check status
*/
public static HealthCheckStatus get(Instance instance) {
String key = buildKey(instance);
if (!statusMap.containsKey(key)) {
statusMap.putIfAbsent(key, new HealthCheckStatus());
}
return statusMap.get(key);
}
public static void remv(Instance instance) {
statusMap.remove(buildKey(instance));
}
private static String buildKey(Instance instance) {
try {
String clusterName = instance.getClusterName();
String serviceName = instance.getServiceName();
String datumKey = instance.getDatumKey();
return serviceName + ":" + clusterName + ":" + datumKey;
} catch (Throwable e) {
Loggers.SRV_LOG.error("[BUILD-KEY] Exception while set rt, ip {}, error: {}", instance.toJson(), e);
}
return instance.getDefaultKey();
}
}

View File

@ -18,6 +18,7 @@
package com.alibaba.nacos.naming.core;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.healthcheck.HealthCheckType;
import com.alibaba.nacos.naming.core.v2.client.impl.ConnectionBasedClient;
import com.alibaba.nacos.naming.core.v2.client.manager.ClientManagerDelegate;
@ -72,7 +73,7 @@ public class HealthOperatorV2ImplTest {
instance.setPort(8080);
Mockito.when(cluster.getHealthyCheckType()).thenReturn(HealthCheckType.NONE.name());
Mockito.when(metadataManager.getServiceMetadata(Mockito.any())).thenReturn(Optional.of(metadata));
ConnectionBasedClient client = Mockito.mock(ConnectionBasedClient.class);
Mockito.when(clientManager.getClient(Mockito.anyString())).thenReturn(client);

View File

@ -1,141 +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.naming.core;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.naming.healthcheck.RsInfo;
import org.junit.Before;
import org.junit.Test;
import java.util.Map;
import java.util.HashMap;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
public class InstanceTest {
private Instance instance;
@Before
public void before() {
instance = new Instance();
}
@Test
public void updateIp() {
instance.setIp("1.1.1.1");
instance.setPort(1234);
instance.setWeight(5);
assertEquals("1.1.1.1", instance.getIp());
assertEquals(1234, instance.getPort());
assertEquals(5, instance.getWeight(), 0.001);
}
@Test
public void testToJsonWithAllParam() {
instance = new Instance("1.1.1.1", 1234, "TEST", "TENANT", "APP");
String actual = instance.toJson();
assertTrue(actual.contains("\"app\":\"APP\""));
assertTrue(actual.contains("\"clusterName\":\"TEST\""));
assertTrue(actual.contains("\"enabled\":true"));
assertTrue(actual.contains("\"ephemeral\":true"));
assertTrue(actual.contains("\"healthy\":true"));
assertTrue(actual.contains("\"instanceHeartBeatInterval\":5000"));
assertTrue(actual.contains("\"instanceHeartBeatTimeOut\":15000"));
assertTrue(actual.contains("\"instanceIdGenerator\":\"simple\""));
assertTrue(actual.contains("\"ip\":\"1.1.1.1\""));
assertTrue(actual.contains("\"ipDeleteTimeout\":30000"));
assertTrue(actual.contains("\"lastBeat\":" + instance.getLastBeat()));
assertTrue(actual.contains("\"marked\":false"));
assertTrue(actual.contains("\"metadata\":{}"));
assertTrue(actual.contains("\"port\":1234"));
assertTrue(actual.contains("\"tenant\":\"TENANT\""));
assertTrue(actual.contains("\"weight\":1.0"));
assertFalse(actual.contains("\"mockValid\""));
assertFalse(actual.contains("\"failCount\""));
}
@Test
public void testToJsonWithoutTenantAndApp() {
instance = new Instance("1.1.1.1", 1234, "TEST");
String actual = instance.toJson();
System.out.println(actual);
assertTrue(actual.contains("\"clusterName\":\"TEST\""));
assertTrue(actual.contains("\"enabled\":true"));
assertTrue(actual.contains("\"ephemeral\":true"));
assertTrue(actual.contains("\"healthy\":true"));
assertTrue(actual.contains("\"instanceHeartBeatInterval\":5000"));
assertTrue(actual.contains("\"instanceHeartBeatTimeOut\":15000"));
assertTrue(actual.contains("\"instanceIdGenerator\":\"simple\""));
assertTrue(actual.contains("\"ip\":\"1.1.1.1\""));
assertTrue(actual.contains("\"ipDeleteTimeout\":30000"));
assertTrue(actual.contains("\"lastBeat\":" + instance.getLastBeat()));
assertTrue(actual.contains("\"marked\":false"));
assertTrue(actual.contains("\"metadata\":{}"));
assertTrue(actual.contains("\"port\":1234"));
assertTrue(actual.contains("\"weight\":1.0"));
assertFalse(actual.contains("\"app\""));
assertFalse(actual.contains("\"tenant\":"));
assertFalse(actual.contains("\"mockValid\""));
assertFalse(actual.contains("\"failCount\""));
}
@Test
@SuppressWarnings("checkstyle:linelength")
public void testFromJsonByJson() {
instance = Instance.fromJson(
"{\"clusterName\":\"TEST\",\"enabled\":true,\"ephemeral\":true,\"healthy\":true,\"instanceHeartBeatInterval\":5000,\"instanceHeartBeatTimeOut\":15000,\"instanceIdGenerator\":\"simple\",\"ip\":\"1.1.1.1\",\"ipDeleteTimeout\":30000,\"lastBeat\":1590043805463,\"marked\":false,\"metadata\":{},\"port\":1234,\"weight\":1.0}\n");
assertEquals("1.1.1.1", instance.getIp());
assertEquals(1234, instance.getPort());
assertEquals("TEST", instance.getClusterName());
assertNull(instance.getApp());
assertNull(instance.getTenant());
}
@Test
public void testFromJsonByNoJson() {
instance = Instance.fromJson("2.2.2.2:8888_2_TEST1");
assertEquals("2.2.2.2", instance.getIp());
assertEquals(8888, instance.getPort());
assertEquals(2, instance.getWeight(), 0.001);
assertEquals("TEST1", instance.getClusterName());
}
@Test
public void rsInfo() throws Exception {
RsInfo info = new RsInfo();
Map<String, String> metadata = new HashMap<>();
metadata.put("version", "2222");
info.setMetadata(metadata);
System.out.println(JacksonUtils.toJson(info));
String json = JacksonUtils.toJson(info);
RsInfo info1 = JacksonUtils.toObj(json, RsInfo.class);
System.out.println(info1);
}
@Test(expected = NacosException.class)
public void testIpValidate() throws NacosException {
Instance instance1 = new Instance("192.168.1.3d", 8080);
instance1.validate();
}
}