Search in sources :

Example 56 with ServiceInfo

use of com.alibaba.nacos.api.naming.pojo.ServiceInfo in project nacos by alibaba.

the class InstanceOperatorServiceImpl method listInstance.

@Override
public ServiceInfo listInstance(String namespaceId, String serviceName, Subscriber subscriber, String cluster, boolean healthOnly) throws Exception {
    ClientInfo clientInfo = new ClientInfo(subscriber.getAgent());
    String clientIP = subscriber.getIp();
    ServiceInfo result = new ServiceInfo(serviceName, cluster);
    Service service = serviceManager.getService(namespaceId, serviceName);
    long cacheMillis = switchDomain.getDefaultCacheMillis();
    // now try to enable the push
    try {
        if (subscriber.getPort() > 0 && pushService.canEnablePush(subscriber.getAgent())) {
            subscriberServiceV1.addClient(namespaceId, serviceName, cluster, subscriber.getAgent(), new InetSocketAddress(clientIP, subscriber.getPort()), pushDataSource, StringUtils.EMPTY, StringUtils.EMPTY);
            cacheMillis = switchDomain.getPushCacheMillis(serviceName);
        }
    } catch (Exception e) {
        Loggers.SRV_LOG.error("[NACOS-API] failed to added push client {}, {}:{}", clientInfo, clientIP, subscriber.getPort(), e);
        cacheMillis = switchDomain.getDefaultCacheMillis();
    }
    if (service == null) {
        if (Loggers.SRV_LOG.isDebugEnabled()) {
            Loggers.SRV_LOG.debug("no instance to serve for service: {}", serviceName);
        }
        result.setCacheMillis(cacheMillis);
        return result;
    }
    checkIfDisabled(service);
    List<com.alibaba.nacos.naming.core.Instance> srvedIps = service.srvIPs(Arrays.asList(StringUtils.split(cluster, StringUtils.COMMA)));
    // filter ips using selector:
    if (service.getSelector() != null && StringUtils.isNotBlank(clientIP)) {
        srvedIps = selectorManager.select(service.getSelector(), clientIP, srvedIps);
    }
    if (CollectionUtils.isEmpty(srvedIps)) {
        if (Loggers.SRV_LOG.isDebugEnabled()) {
            Loggers.SRV_LOG.debug("no instance to serve for service: {}", serviceName);
        }
        result.setCacheMillis(cacheMillis);
        result.setLastRefTime(System.currentTimeMillis());
        result.setChecksum(service.getChecksum());
        return result;
    }
    long total = 0;
    Map<Boolean, List<com.alibaba.nacos.naming.core.Instance>> ipMap = new HashMap<>(2);
    ipMap.put(Boolean.TRUE, new ArrayList<>());
    ipMap.put(Boolean.FALSE, new ArrayList<>());
    for (com.alibaba.nacos.naming.core.Instance ip : srvedIps) {
        // remove disabled instance:
        if (!ip.isEnabled()) {
            continue;
        }
        ipMap.get(ip.isHealthy()).add(ip);
        total += 1;
    }
    double threshold = service.getProtectThreshold();
    List<Instance> hosts;
    if ((float) ipMap.get(Boolean.TRUE).size() / total <= threshold) {
        Loggers.SRV_LOG.warn("protect threshold reached, return all ips, service: {}", result.getName());
        result.setReachProtectionThreshold(true);
        hosts = Stream.of(Boolean.TRUE, Boolean.FALSE).map(ipMap::get).flatMap(Collection::stream).map(InstanceUtil::deepCopy).peek(instance -> instance.setHealthy(true)).collect(Collectors.toCollection(LinkedList::new));
    } else {
        result.setReachProtectionThreshold(false);
        hosts = new LinkedList<>(ipMap.get(Boolean.TRUE));
        if (!healthOnly) {
            hosts.addAll(ipMap.get(Boolean.FALSE));
        }
    }
    result.setHosts(hosts);
    result.setCacheMillis(cacheMillis);
    result.setLastRefTime(System.currentTimeMillis());
    result.setChecksum(service.getChecksum());
    return result;
}
Also used : Instance(com.alibaba.nacos.api.naming.pojo.Instance) HashMap(java.util.HashMap) InetSocketAddress(java.net.InetSocketAddress) ServiceInfo(com.alibaba.nacos.api.naming.pojo.ServiceInfo) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) List(java.util.List) UdpPushService(com.alibaba.nacos.naming.push.UdpPushService) NacosException(com.alibaba.nacos.api.exception.NacosException) LinkedList(java.util.LinkedList) Collection(java.util.Collection) ClientInfo(com.alibaba.nacos.naming.push.v1.ClientInfo)

Example 57 with ServiceInfo

use of com.alibaba.nacos.api.naming.pojo.ServiceInfo in project nacos by alibaba.

the class ServiceQueryRequestHandler method handle.

@Override
@Secured(action = ActionTypes.READ)
public QueryServiceResponse handle(ServiceQueryRequest request, RequestMeta meta) throws NacosException {
    String namespaceId = request.getNamespace();
    String groupName = request.getGroupName();
    String serviceName = request.getServiceName();
    Service service = Service.newService(namespaceId, groupName, serviceName);
    String cluster = null == request.getCluster() ? "" : request.getCluster();
    boolean healthyOnly = request.isHealthyOnly();
    ServiceInfo result = serviceStorage.getData(service);
    ServiceMetadata serviceMetadata = metadataManager.getServiceMetadata(service).orElse(null);
    result = ServiceUtil.selectInstancesWithHealthyProtection(result, serviceMetadata, cluster, healthyOnly, true, meta.getClientIp());
    return QueryServiceResponse.buildSuccessResponse(result);
}
Also used : ServiceInfo(com.alibaba.nacos.api.naming.pojo.ServiceInfo) Service(com.alibaba.nacos.naming.core.v2.pojo.Service) ServiceMetadata(com.alibaba.nacos.naming.core.v2.metadata.ServiceMetadata) Secured(com.alibaba.nacos.auth.annotation.Secured)

Example 58 with ServiceInfo

use of com.alibaba.nacos.api.naming.pojo.ServiceInfo in project nacos by alibaba.

the class SubscribeServiceRequestHandler method handle.

@Override
@Secured(action = ActionTypes.READ)
public SubscribeServiceResponse handle(SubscribeServiceRequest request, RequestMeta meta) throws NacosException {
    String namespaceId = request.getNamespace();
    String serviceName = request.getServiceName();
    String groupName = request.getGroupName();
    String app = request.getHeader("app", "unknown");
    String groupedServiceName = NamingUtils.getGroupedName(serviceName, groupName);
    Service service = Service.newService(namespaceId, groupName, serviceName, true);
    Subscriber subscriber = new Subscriber(meta.getClientIp(), meta.getClientVersion(), app, meta.getClientIp(), namespaceId, groupedServiceName, 0, request.getClusters());
    ServiceInfo serviceInfo = ServiceUtil.selectInstancesWithHealthyProtection(serviceStorage.getData(service), metadataManager.getServiceMetadata(service).orElse(null), subscriber);
    if (request.isSubscribe()) {
        clientOperationService.subscribeService(service, subscriber, meta.getConnectionId());
    } else {
        clientOperationService.unsubscribeService(service, subscriber, meta.getConnectionId());
    }
    return new SubscribeServiceResponse(ResponseCode.SUCCESS.getCode(), "success", serviceInfo);
}
Also used : ServiceInfo(com.alibaba.nacos.api.naming.pojo.ServiceInfo) Subscriber(com.alibaba.nacos.naming.pojo.Subscriber) Service(com.alibaba.nacos.naming.core.v2.pojo.Service) SubscribeServiceResponse(com.alibaba.nacos.api.naming.remote.response.SubscribeServiceResponse) Secured(com.alibaba.nacos.auth.annotation.Secured)

Example 59 with ServiceInfo

use of com.alibaba.nacos.api.naming.pojo.ServiceInfo 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 60 with ServiceInfo

use of com.alibaba.nacos.api.naming.pojo.ServiceInfo in project nacos by alibaba.

the class CatalogServiceV2ImplTest method testPageListService.

@Test
public void testPageListService() {
    try {
        ServiceInfo serviceInfo = new ServiceInfo();
        serviceInfo.setHosts(Collections.singletonList(new Instance()));
        Mockito.when(serviceStorage.getData(Mockito.any())).thenReturn(serviceInfo);
        ServiceMetadata metadata = new ServiceMetadata();
        metadata.setProtectThreshold(0.75F);
        Mockito.when(metadataManager.getServiceMetadata(Mockito.any())).thenReturn(Optional.of(metadata));
        ObjectNode obj = (ObjectNode) catalogServiceV2Impl.pageListService("A", "B", "C", 1, 10, null, false);
        Assert.assertEquals(1, obj.get(FieldsConstants.COUNT).asInt());
    } catch (NacosException e) {
        e.printStackTrace();
        Assert.fail(e.getMessage());
    }
}
Also used : ServiceInfo(com.alibaba.nacos.api.naming.pojo.ServiceInfo) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) Instance(com.alibaba.nacos.api.naming.pojo.Instance) ServiceMetadata(com.alibaba.nacos.naming.core.v2.metadata.ServiceMetadata) NacosException(com.alibaba.nacos.api.exception.NacosException) Test(org.junit.Test)

Aggregations

ServiceInfo (com.alibaba.nacos.api.naming.pojo.ServiceInfo)74 Test (org.junit.Test)44 Instance (com.alibaba.nacos.api.naming.pojo.Instance)29 ArrayList (java.util.ArrayList)17 ServiceMetadata (com.alibaba.nacos.naming.core.v2.metadata.ServiceMetadata)12 Properties (java.util.Properties)10 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)9 NacosException (com.alibaba.nacos.api.exception.NacosException)8 ServiceInfoHolder (com.alibaba.nacos.client.naming.cache.ServiceInfoHolder)8 Before (org.junit.Before)8 Service (com.alibaba.nacos.naming.core.v2.pojo.Service)7 Field (java.lang.reflect.Field)6 HashSet (java.util.HashSet)5 EventListener (com.alibaba.nacos.api.naming.listener.EventListener)4 SubscribeServiceResponse (com.alibaba.nacos.api.naming.remote.response.SubscribeServiceResponse)4 PushDataWrapper (com.alibaba.nacos.naming.push.v2.PushDataWrapper)4 HashMap (java.util.HashMap)4 QueryServiceResponse (com.alibaba.nacos.api.naming.remote.response.QueryServiceResponse)3 Secured (com.alibaba.nacos.auth.annotation.Secured)3 InstancesChangeNotifier (com.alibaba.nacos.client.naming.event.InstancesChangeNotifier)3