Search in sources :

Example 1 with Instance

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

the class ClientBeatProcessor method run.

@Override
public void run() {
    Service service = this.service;
    if (Loggers.EVT_LOG.isDebugEnabled()) {
        Loggers.EVT_LOG.debug("[CLIENT-BEAT] processing beat: {}", rsInfo.toString());
    }
    String ip = rsInfo.getIp();
    String clusterName = rsInfo.getCluster();
    int port = rsInfo.getPort();
    Cluster cluster = service.getClusterMap().get(clusterName);
    List<Instance> instances = cluster.allIPs(true);
    for (Instance instance : instances) {
        if (instance.getIp().equals(ip) && instance.getPort() == port) {
            if (Loggers.EVT_LOG.isDebugEnabled()) {
                Loggers.EVT_LOG.debug("[CLIENT-BEAT] refresh beat: {}", rsInfo.toString());
            }
            instance.setLastBeat(System.currentTimeMillis());
            if (!instance.isMarked() && !instance.isHealthy()) {
                instance.setHealthy(true);
                Loggers.EVT_LOG.info("service: {} {POS} {IP-ENABLED} valid: {}:{}@{}, region: {}, msg: client beat ok", cluster.getService().getName(), ip, port, cluster.getName(), UtilsAndCommons.LOCALHOST_SITE);
                getPushService().serviceChanged(service);
            }
        }
    }
}
Also used : Instance(com.alibaba.nacos.naming.core.Instance) UdpPushService(com.alibaba.nacos.naming.push.UdpPushService) Service(com.alibaba.nacos.naming.core.Service) Cluster(com.alibaba.nacos.naming.core.Cluster)

Example 2 with Instance

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

the class RaftStore method readDatum.

private synchronized Datum readDatum(File file, String namespaceId) throws IOException {
    if (!KeyBuilder.isDatumCacheFile(file.getName())) {
        return null;
    }
    ByteBuffer buffer;
    try (FileChannel fc = new FileInputStream(file).getChannel()) {
        buffer = ByteBuffer.allocate((int) file.length());
        fc.read(buffer);
        String json = new String(buffer.array(), StandardCharsets.UTF_8);
        if (StringUtils.isBlank(json)) {
            return null;
        }
        final String fileName = file.getName();
        if (KeyBuilder.matchSwitchKey(fileName)) {
            return JacksonUtils.toObj(json, new TypeReference<Datum<SwitchDomain>>() {
            });
        }
        if (KeyBuilder.matchServiceMetaKey(fileName)) {
            Datum<Service> serviceDatum;
            try {
                serviceDatum = JacksonUtils.toObj(json.replace("\\", ""), new TypeReference<Datum<Service>>() {
                });
            } catch (Exception e) {
                JsonNode jsonObject = JacksonUtils.toObj(json);
                serviceDatum = new Datum<>();
                serviceDatum.timestamp.set(jsonObject.get("timestamp").asLong());
                serviceDatum.key = jsonObject.get("key").asText();
                serviceDatum.value = JacksonUtils.toObj(jsonObject.get("value").toString(), Service.class);
            }
            if (StringUtils.isBlank(serviceDatum.value.getGroupName())) {
                serviceDatum.value.setGroupName(Constants.DEFAULT_GROUP);
            }
            if (!serviceDatum.value.getName().contains(Constants.SERVICE_INFO_SPLITER)) {
                serviceDatum.value.setName(Constants.DEFAULT_GROUP + Constants.SERVICE_INFO_SPLITER + serviceDatum.value.getName());
            }
            return serviceDatum;
        }
        if (KeyBuilder.matchInstanceListKey(fileName)) {
            Datum<Instances> instancesDatum;
            try {
                instancesDatum = JacksonUtils.toObj(json, new TypeReference<Datum<Instances>>() {
                });
            } catch (Exception e) {
                JsonNode jsonObject = JacksonUtils.toObj(json);
                instancesDatum = new Datum<>();
                instancesDatum.timestamp.set(jsonObject.get("timestamp").asLong());
                String key = jsonObject.get("key").asText();
                String serviceName = KeyBuilder.getServiceName(key);
                key = key.substring(0, key.indexOf(serviceName)) + Constants.DEFAULT_GROUP + Constants.SERVICE_INFO_SPLITER + serviceName;
                instancesDatum.key = key;
                instancesDatum.value = new Instances();
                instancesDatum.value.setInstanceList(JacksonUtils.toObj(jsonObject.get("value").toString(), new TypeReference<List<Instance>>() {
                }));
                if (!instancesDatum.value.getInstanceList().isEmpty()) {
                    for (Instance instance : instancesDatum.value.getInstanceList()) {
                        instance.setEphemeral(false);
                    }
                }
            }
            return instancesDatum;
        }
        return JacksonUtils.toObj(json, Datum.class);
    } catch (Exception e) {
        Loggers.RAFT.warn("waning: failed to deserialize key: {}", file.getName());
        throw e;
    }
}
Also used : Datum(com.alibaba.nacos.naming.consistency.Datum) Instance(com.alibaba.nacos.naming.core.Instance) FileChannel(java.nio.channels.FileChannel) Service(com.alibaba.nacos.naming.core.Service) JsonNode(com.fasterxml.jackson.databind.JsonNode) ByteBuffer(java.nio.ByteBuffer) FileInputStream(java.io.FileInputStream) NacosException(com.alibaba.nacos.api.exception.NacosException) IOException(java.io.IOException) Instances(com.alibaba.nacos.naming.core.Instances) List(java.util.List) TypeReference(com.fasterxml.jackson.core.type.TypeReference)

Example 3 with Instance

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

the class NamingHttpClientProxy_ITCase method testSyncData.

@Test
public void testSyncData() throws NacosException, InterruptedException {
    // write data to DataStore
    String groupedName = NamingUtils.getGroupedName(serviceName, groupName);
    Instances instances = new Instances();
    Instance instance = new Instance();
    instance.setIp("1.2.3.4");
    instance.setPort(8888);
    instance.setEphemeral(true);
    instance.setServiceName(groupedName);
    List<Instance> instanceList = new ArrayList<Instance>(1);
    instanceList.add(instance);
    instances.setInstanceList(instanceList);
    String key = KeyBuilder.buildInstanceListKey(namespaceId, instance.getServiceName(), true);
    Datum<Instances> datum = new Datum<>();
    datum.value = instances;
    datum.key = key;
    datum.timestamp.incrementAndGet();
    this.dataStore.put(key, datum);
    // sync data to server
    Map<String, Datum> dataMap = dataStore.getDataMap();
    byte[] content = serializer.serialize(dataMap);
    boolean result = NamingProxy.syncData(content, "localhost:" + port);
    if (!result) {
        Assert.fail("NamingProxy.syncData error");
    }
    // query instance by api
    List<com.alibaba.nacos.api.naming.pojo.Instance> allInstances = namingService.getAllInstances(serviceName, false);
    for (int i = 0; i < 3 && allInstances.isEmpty(); i++) {
        // wait for async op
        TimeUnit.SECONDS.sleep(100);
        allInstances = namingService.getAllInstances(serviceName, false);
    }
    if (allInstances.isEmpty()) {
        Assert.fail("instance is empty");
    }
    com.alibaba.nacos.api.naming.pojo.Instance dst = allInstances.get(0);
    Assert.assertEquals(instance.getIp(), dst.getIp());
    Assert.assertEquals(instance.getPort(), dst.getPort());
    Assert.assertEquals(instance.getServiceName(), dst.getServiceName());
}
Also used : Datum(com.alibaba.nacos.naming.consistency.Datum) Instance(com.alibaba.nacos.naming.core.Instance) ArrayList(java.util.ArrayList) Instances(com.alibaba.nacos.naming.core.Instances) Test(org.junit.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest)

Example 4 with Instance

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

the class InstanceControllerTest method before.

@Before
public void before() {
    super.before();
    mockInjectPushServer();
    ReflectionTestUtils.setField(instanceController, "upgradeJudgement", upgradeJudgement);
    ReflectionTestUtils.setField(instanceController, "instanceServiceV1", instanceOperatorService);
    when(context.getBean(DoubleWriteEventListener.class)).thenReturn(doubleWriteEventListener);
    when(instanceUpgradeHelper.toV1(any())).thenReturn(new Instance("1.1.1.1", 9999));
    mockmvc = MockMvcBuilders.standaloneSetup(instanceController).build();
}
Also used : Instance(com.alibaba.nacos.naming.core.Instance) Before(org.junit.Before)

Example 5 with Instance

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

the class InstanceControllerTest method batchUpdateMetadata.

@Test
public void batchUpdateMetadata() throws Exception {
    Instance instance = new Instance("1.1.1.1", 8080, TEST_CLUSTER_NAME);
    instance.setServiceName(TEST_SERVICE_NAME);
    Map<String, String> metadata = new HashMap<>();
    metadata.put("key1", "value1");
    instance.setMetadata(metadata);
    Instance instance2 = new Instance("2.2.2.2", 8080, TEST_CLUSTER_NAME);
    instance2.setServiceName(TEST_SERVICE_NAME);
    List<Instance> instanceList = new LinkedList<>();
    instanceList.add(instance);
    instanceList.add(instance2);
    when(serviceManager.batchOperate(ArgumentMatchers.anyString(), ArgumentMatchers.any(InstanceOperationInfo.class), ArgumentMatchers.any(Function.class))).thenReturn(instanceList);
    MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.put(UtilsAndCommons.NACOS_NAMING_CONTEXT + "/instance/metadata/batch").param("namespace", "public").param("serviceName", TEST_SERVICE_NAME).param("instances", "[{\"ip\":\"1.1.1.1\",\"port\": \"8080\",\"ephemeral\":\"true\",\"clusterName\":\"test-cluster\"}," + "{\"ip\":\"2.2.2.2\",\"port\":\"8080\",\"ephemeral\":\"true\",\"clusterName\":\"test-cluster\"}]").param("metadata", "{\"age\":\"20\",\"name\":\"horizon\"}");
    String actualValue = mockmvc.perform(builder).andReturn().getResponse().getContentAsString();
    JsonNode result = JacksonUtils.toObj(actualValue);
    JsonNode updated = result.get("updated");
    Assert.assertEquals(updated.size(), 2);
    Assert.assertTrue(updated.get(0).asText().contains("1.1.1.1"));
    Assert.assertTrue(updated.get(0).asText().contains("8080"));
    Assert.assertTrue(updated.get(0).asText().contains(TEST_CLUSTER_NAME));
    Assert.assertTrue(updated.get(0).asText().contains("ephemeral"));
    Assert.assertTrue(updated.get(1).asText().contains("2.2.2.2"));
    Assert.assertTrue(updated.get(1).asText().contains("8080"));
    Assert.assertTrue(updated.get(1).asText().contains(TEST_CLUSTER_NAME));
    Assert.assertTrue(updated.get(1).asText().contains("ephemeral"));
}
Also used : Function(java.util.function.Function) Instance(com.alibaba.nacos.naming.core.Instance) HashMap(java.util.HashMap) InstanceOperationInfo(com.alibaba.nacos.naming.pojo.InstanceOperationInfo) MockHttpServletRequestBuilder(org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder) JsonNode(com.fasterxml.jackson.databind.JsonNode) LinkedList(java.util.LinkedList) Test(org.junit.Test) BaseTest(com.alibaba.nacos.naming.BaseTest)

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