Search in sources :

Example 16 with Instance

use of com.alibaba.nacos.naming.core.Instance in project nacos by alibaba.

the class ServiceUtil method doSelectInstances.

/**
 * Select instance of service info.
 *
 * @param serviceInfo original service info
 * @param cluster     cluster of instances
 * @param healthyOnly whether only select instance which healthy
 * @param enableOnly  whether only select instance which enabled
 * @param filter      do some other filter operation
 * @return new service info
 */
private static ServiceInfo doSelectInstances(ServiceInfo serviceInfo, String cluster, boolean healthyOnly, boolean enableOnly, InstancesFilter filter) {
    ServiceInfo result = new ServiceInfo();
    result.setName(serviceInfo.getName());
    result.setGroupName(serviceInfo.getGroupName());
    result.setCacheMillis(serviceInfo.getCacheMillis());
    result.setLastRefTime(System.currentTimeMillis());
    result.setClusters(cluster);
    result.setReachProtectionThreshold(false);
    Set<String> clusterSets = com.alibaba.nacos.common.utils.StringUtils.isNotBlank(cluster) ? new HashSet<>(Arrays.asList(cluster.split(","))) : new HashSet<>();
    long healthyCount = 0L;
    // The instance list won't be modified almost time.
    List<com.alibaba.nacos.api.naming.pojo.Instance> filteredInstances = new LinkedList<>();
    // The instance list of all filtered by cluster/enabled condition.
    List<com.alibaba.nacos.api.naming.pojo.Instance> allInstances = new LinkedList<>();
    for (com.alibaba.nacos.api.naming.pojo.Instance ip : serviceInfo.getHosts()) {
        if (checkCluster(clusterSets, ip) && checkEnabled(enableOnly, ip)) {
            if (!healthyOnly || ip.isHealthy()) {
                filteredInstances.add(ip);
            }
            if (ip.isHealthy()) {
                healthyCount += 1;
            }
            allInstances.add(ip);
        }
    }
    result.setHosts(filteredInstances);
    if (filter != null) {
        filter.doFilter(result, allInstances, healthyCount);
    }
    return result;
}
Also used : Instance(com.alibaba.nacos.naming.core.Instance) LinkedList(java.util.LinkedList) ServiceInfo(com.alibaba.nacos.api.naming.pojo.ServiceInfo)

Example 17 with Instance

use of com.alibaba.nacos.naming.core.Instance in project nacos by alibaba.

the class JacksonSerializerTest method testDeserializeMap.

@Test
@SuppressWarnings("checkstyle:linelength")
public void testDeserializeMap() {
    String example = "{\"datum\":{\"key\":\"instances\",\"value\":{\"instanceList\":[{\"ip\":\"1.1.1.1\",\"port\":1234,\"weight\":1.0,\"healthy\":true,\"enabled\":true,\"ephemeral\":true,\"clusterName\":\"cluster\",\"metadata\":{},\"lastBeat\":1590563397533,\"marked\":false,\"instanceIdGenerator\":\"simple\",\"instanceHeartBeatInterval\":5000,\"instanceHeartBeatTimeOut\":15000,\"ipDeleteTimeout\":30000}]},\"timestamp\":100000}}";
    Map<String, Datum<Instances>> actual = serializer.deserializeMap(ByteUtils.toBytes(example), Instances.class);
    assertEquals(actual.size(), 1);
    assertTrue(actual.containsKey("datum"));
    Datum<Instances> actualDatum = actual.get("datum");
    assertEquals("instances", actualDatum.key);
    assertEquals(100000L, actualDatum.timestamp.get());
    assertEquals(1, actualDatum.value.getInstanceList().size());
    Instance actualInstance = actualDatum.value.getInstanceList().get(0);
    assertEquals("1.1.1.1", actualInstance.getIp());
    assertEquals("cluster", actualInstance.getClusterName());
    assertEquals(1234, actualInstance.getPort());
}
Also used : Instances(com.alibaba.nacos.naming.core.Instances) Datum(com.alibaba.nacos.naming.consistency.Datum) Instance(com.alibaba.nacos.naming.core.Instance) Test(org.junit.Test)

Example 18 with Instance

use of com.alibaba.nacos.naming.core.Instance in project nacos by alibaba.

the class JacksonSerializerTest method setUp.

@Before
public void setUp() throws Exception {
    serializer = new JacksonSerializer();
    instances = new Instances();
    instances.getInstanceList().add(new Instance("1.1.1.1", 1234, "cluster"));
}
Also used : Instances(com.alibaba.nacos.naming.core.Instances) Instance(com.alibaba.nacos.naming.core.Instance) Before(org.junit.Before)

Example 19 with Instance

use of com.alibaba.nacos.naming.core.Instance in project nacos by alibaba.

the class ClientBeatCheckTask method run.

@Override
public void run() {
    try {
        // If upgrade to 2.0.X stop health check with v1
        if (ApplicationUtils.getBean(UpgradeJudgement.class).isUseGrpcFeatures()) {
            return;
        }
        if (!getDistroMapper().responsible(service.getName())) {
            return;
        }
        if (!getSwitchDomain().isHealthCheckEnabled()) {
            return;
        }
        List<Instance> instances = service.allIPs(true);
        // first set health status of instances:
        for (Instance instance : instances) {
            if (System.currentTimeMillis() - instance.getLastBeat() > instance.getInstanceHeartBeatTimeOut()) {
                if (!instance.isMarked()) {
                    if (instance.isHealthy()) {
                        instance.setHealthy(false);
                        Loggers.EVT_LOG.info("{POS} {IP-DISABLED} valid: {}:{}@{}@{}, region: {}, msg: client timeout after {}, last beat: {}", instance.getIp(), instance.getPort(), instance.getClusterName(), service.getName(), UtilsAndCommons.LOCALHOST_SITE, instance.getInstanceHeartBeatTimeOut(), instance.getLastBeat());
                        getPushService().serviceChanged(service);
                    }
                }
            }
        }
        if (!getGlobalConfig().isExpireInstance()) {
            return;
        }
        // then remove obsolete instances:
        for (Instance instance : instances) {
            if (instance.isMarked()) {
                continue;
            }
            if (System.currentTimeMillis() - instance.getLastBeat() > instance.getIpDeleteTimeout()) {
                // delete instance
                Loggers.SRV_LOG.info("[AUTO-DELETE-IP] service: {}, ip: {}", service.getName(), JacksonUtils.toJson(instance));
                deleteIp(instance);
            }
        }
    } catch (Exception e) {
        Loggers.SRV_LOG.warn("Exception while processing client beat time out.", e);
    }
}
Also used : Instance(com.alibaba.nacos.naming.core.Instance) UpgradeJudgement(com.alibaba.nacos.naming.core.v2.upgrade.UpgradeJudgement)

Example 20 with Instance

use of com.alibaba.nacos.naming.core.Instance in project nacos by alibaba.

the class HttpHealthCheckProcessor method process.

@Override
public void process(HealthCheckTask task) {
    List<Instance> ips = task.getCluster().allIPs(false);
    if (CollectionUtils.isEmpty(ips)) {
        return;
    }
    if (!switchDomain.isHealthCheckEnabled()) {
        return;
    }
    Cluster cluster = task.getCluster();
    for (Instance ip : ips) {
        try {
            if (ip.isMarked()) {
                if (SRV_LOG.isDebugEnabled()) {
                    SRV_LOG.debug("http check, ip is marked as to skip health check, ip: {}" + ip.getIp());
                }
                continue;
            }
            if (!ip.markChecking()) {
                SRV_LOG.warn("http check started before last one finished, service: {}:{}:{}", task.getCluster().getService().getName(), task.getCluster().getName(), ip.getIp());
                healthCheckCommon.reEvaluateCheckRT(task.getCheckRtNormalized() * 2, task, switchDomain.getHttpHealthParams());
                continue;
            }
            Http healthChecker = (Http) cluster.getHealthChecker();
            int ckPort = cluster.isUseIPPort4Check() ? ip.getPort() : cluster.getDefCkport();
            URL host = new URL(HTTP_PREFIX + ip.getIp() + ":" + ckPort);
            URL target = new URL(host, healthChecker.getPath());
            Map<String, String> customHeaders = healthChecker.getCustomHeaders();
            Header header = Header.newInstance();
            header.addAll(customHeaders);
            ASYNC_REST_TEMPLATE.get(target.toString(), header, Query.EMPTY, String.class, new HttpHealthCheckCallback(ip, task));
            MetricsMonitor.getHttpHealthCheckMonitor().incrementAndGet();
        } catch (Throwable e) {
            ip.setCheckRt(switchDomain.getHttpHealthParams().getMax());
            healthCheckCommon.checkFail(ip, task, "http:error:" + e.getMessage());
            healthCheckCommon.reEvaluateCheckRT(switchDomain.getHttpHealthParams().getMax(), task, switchDomain.getHttpHealthParams());
        }
    }
}
Also used : Header(com.alibaba.nacos.common.http.param.Header) Instance(com.alibaba.nacos.naming.core.Instance) Cluster(com.alibaba.nacos.naming.core.Cluster) Http(com.alibaba.nacos.api.naming.pojo.healthcheck.impl.Http) URL(java.net.URL)

Aggregations

Instance (com.alibaba.nacos.naming.core.Instance)26 Test (org.junit.Test)13 Instances (com.alibaba.nacos.naming.core.Instances)6 HashMap (java.util.HashMap)6 BaseTest (com.alibaba.nacos.naming.BaseTest)5 Cluster (com.alibaba.nacos.naming.core.Cluster)5 Service (com.alibaba.nacos.naming.core.Service)5 ArrayList (java.util.ArrayList)5 Datum (com.alibaba.nacos.naming.consistency.Datum)4 JsonNode (com.fasterxml.jackson.databind.JsonNode)4 MockHttpServletRequestBuilder (org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder)4 LinkedList (java.util.LinkedList)3 InstanceOperationInfo (com.alibaba.nacos.naming.pojo.InstanceOperationInfo)2 Function (java.util.function.Function)2 Before (org.junit.Before)2 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)2 NacosException (com.alibaba.nacos.api.exception.NacosException)1 ServiceInfo (com.alibaba.nacos.api.naming.pojo.ServiceInfo)1 AbstractHealthChecker (com.alibaba.nacos.api.naming.pojo.healthcheck.AbstractHealthChecker)1 Http (com.alibaba.nacos.api.naming.pojo.healthcheck.impl.Http)1