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