com.ecwid.consul.v1.health.model.HealthService Java Examples

The following examples show how to use com.ecwid.consul.v1.health.model.HealthService. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HealthServiceInformer.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
private void watchHealthService() {
    try {
        HealthServicesRequest request = HealthServicesRequest.newBuilder()
                .setTag(tag)
                .setQueryParams(new QueryParams(properties.getWatchTimeout(), currentData.getConsulIndex()))
                .setPassing(true)
                .build();
        Response<List<HealthService>> response = consulClient.getHealthServices(serviceName, request);
        if (response.getConsulIndex().equals(currentData.getConsulIndex())) {
            return;
        }
        this.currentData = response;
        ProviderGroup providerGroup = new ProviderGroup(currentProviders());
        listeners.stream().filter(Objects::nonNull).forEach(l -> l.updateProviders(providerGroup));
    } catch (Exception e) {
        LOGGER.error(LogCodes.getLog(LogCodes.ERROR_WATCH_HEALTH ,"Consul"), e);
    }
}
 
Example #2
Source File: ConsulDiscoveryClient.java    From spring-cloud-consul with Apache License 2.0 6 votes vote down vote up
private void addInstancesToList(List<ServiceInstance> instances, String serviceId,
		QueryParams queryParams) {

	HealthServicesRequest request = HealthServicesRequest.newBuilder()
			.setTag(this.properties.getDefaultQueryTag())
			.setPassing(this.properties.isQueryPassing()).setQueryParams(queryParams)
			.setToken(this.properties.getAclToken()).build();
	Response<List<HealthService>> services = this.client.getHealthServices(serviceId,
			request);

	for (HealthService service : services.getValue()) {
		String host = findHost(service);

		Map<String, String> metadata = service.getService().getMeta();
		if (metadata == null) {
			metadata = new LinkedHashMap<>();
		}
		boolean secure = false;
		if (metadata.containsKey("secure")) {
			secure = Boolean.parseBoolean(metadata.get("secure"));
		}
		instances.add(new DefaultServiceInstance(service.getService().getId(),
				serviceId, host, service.getService().getPort(), secure, metadata));
	}
}
 
Example #3
Source File: ConsulSyncToNacosServiceImpl.java    From nacos-sync with Apache License 2.0 6 votes vote down vote up
@Override
public boolean sync(TaskDO taskDO) {
    try {
        ConsulClient consulClient = consulServerHolder.get(taskDO.getSourceClusterId(), null);
        NamingService destNamingService = nacosServerHolder.get(taskDO.getDestClusterId(), null);
        Response<List<HealthService>> response =
            consulClient.getHealthServices(taskDO.getServiceName(), true, QueryParams.DEFAULT);
        List<HealthService> healthServiceList = response.getValue();
        Set<String> instanceKeys = new HashSet<>();
        overrideAllInstance(taskDO, destNamingService, healthServiceList, instanceKeys);
        cleanAllOldInstance(taskDO, destNamingService, instanceKeys);
        specialSyncEventBus.subscribe(taskDO, this::sync);
    } catch (Exception e) {
        log.error("Sync task from consul to nacos was failed, taskId:{}", taskDO.getTaskId(), e);
        metricsManager.recordError(MetricsStatisticsType.SYNC_ERROR);
        return false;
    }
    return true;
}
 
Example #4
Source File: ConsulSyncToNacosServiceImplTest.java    From nacos-sync with Apache License 2.0 6 votes vote down vote up
public void mockSync(TaskDO taskDO) throws Exception {
    Instance instance = mock(Instance.class);
    Map<String, String> metadata = Maps.newHashMap();
    metadata.put(SkyWalkerConstants.SOURCE_CLUSTERID_KEY, TEST_SOURCE_CLUSTER_ID);
    HealthService healthServiceUp = buildHealthService(TEST_INSTANCE_ADDRESS, 8080, Maps.newHashMap());
    HealthService healthServiceDown = buildHealthService(TEST_INSTANCE_ADDRESS, 8081, metadata);
    List<HealthService> healthServiceList = Lists.newArrayList(healthServiceUp,healthServiceDown);
    RawResponse rawResponse = new RawResponse(200,null,null,1000L,true,100L);
    Response<List<HealthService>> response = new Response<>(healthServiceList,rawResponse);
    when(taskDO.getTaskId()).thenReturn(TEST_TASK_ID);
    when(taskDO.getSourceClusterId()).thenReturn(TEST_SOURCE_CLUSTER_ID);
    when(taskDO.getDestClusterId()).thenReturn(TEST_DEST_CLUSTER_ID);
    doReturn(destNamingService).when(nacosServerHolder).get(anyString(), any());
    doReturn(consulClient).when(consulServerHolder).get(anyString(), any());
    doReturn(response).when(consulClient).getHealthServices(anyString(),anyBoolean(), any());
    List<Instance> allInstances = Lists.newArrayList(instance);
    doReturn(allInstances).when(destNamingService).getAllInstances(anyString());
    doReturn(ClusterTypeEnum.EUREKA).when(skyWalkerCacheServices).getClusterType(any());

}
 
Example #5
Source File: ConsulNamingService.java    From brpc-java with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    while (!stopWatch) {
        Response<List<HealthService>> response = lookupHealthService(serviceName, lastConsulIndex);
        Long currentIndex = response.getConsulIndex();
        if (currentIndex != null && currentIndex > lastConsulIndex) {
            List<ServiceInstance> currentInstances = convert(response);
            Collection<ServiceInstance> addList = CollectionUtils.subtract(
                    currentInstances, lastInstances);
            Collection<ServiceInstance> deleteList = CollectionUtils.subtract(
                    lastInstances, currentInstances);
            listener.notify(addList, deleteList);
            lastInstances = currentInstances;
            lastConsulIndex = currentIndex;
        }
    }
}
 
Example #6
Source File: ConsulNamingService.java    From brpc-java with Apache License 2.0 6 votes vote down vote up
@Override
public List<ServiceInstance> lookup(SubscribeInfo subscribeInfo) {
    try {
        Response<List<HealthService>> consulServices = lookupHealthService(
                subscribeInfo.getServiceId(), -1);
        List<ServiceInstance> instances = convert(consulServices);
        log.info("lookup {} instances from consul", instances.size());
        return instances;
    } catch (Exception ex) {
        log.warn("lookup endpoint list failed from {}, msg={}",
                url, ex.getMessage());
        if (!subscribeInfo.isIgnoreFailOfNamingService()) {
            throw new RpcException("lookup endpoint list failed from consul failed", ex);
        } else {
            return new ArrayList<ServiceInstance>();
        }
    }
}
 
Example #7
Source File: ConsulRegistry.java    From dubbox with Apache License 2.0 5 votes vote down vote up
private void doNotify(URL url, Collection<NotifyListener> listeners) {
	List<URL> result = new ArrayList<URL>();
	String consumerService = url.getServiceInterface();
	try {
		Response<List<HealthService>> response = this.consulClient.getHealthServices(consumerService, true, QueryParams.DEFAULT);
		List<HealthService> healthServices = (List<HealthService>) response.getValue();
		Iterator<HealthService> iterator = healthServices.iterator();
		while (iterator.hasNext()) {
			HealthService healthService = (HealthService) iterator.next();
			HealthService.Service service = healthService.getService();
			List<URL> urls = new ArrayList<URL>();
			String serviceURL = URL.decode(service.getAddress());
			URL u = URL.valueOf(serviceURL);
			if (UrlUtils.isMatch(url, u)) {
				urls.add(u);
			}
			result.addAll(urls);
			if (logger.isInfoEnabled()) {
				logger.info("Consul notify:  = " + urls);
			}
		}
		if (result == null || result.size() == 0) {
			return;
		}
		for (NotifyListener listener : listeners) {
			notify(url, listener, result);
		}
	} catch (OperationException e) {
		throw e;
	}
}
 
Example #8
Source File: NotifyListenerConsulWrapper.java    From dubbo3 with Apache License 2.0 5 votes vote down vote up
public List<URL> getProviderUrls(String serviceName) {
    List<URL> urls = new ArrayList<>();
    Response<List<HealthService>> healthServices = consulClient.getHealthServices(serviceName, true, null);
    for (HealthService healthService : healthServices.getValue()) {
        urls.add(URL.valueOf(healthService.getService().getAddress()));
    }
    return urls;
}
 
Example #9
Source File: ConsulRegistrationTest.java    From grpc-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
@Test
public void contextLoads() throws ExecutionException, InterruptedException {
    final String serviceId = "grpc-grpc-demo";
    final ConsulClient consulClient = new ConsulClient("localhost", Integer.parseInt(System.getProperty("spring.cloud.consul.port")));


    List<ServiceInstance> instances = discoveryClient.getInstances(serviceId);
    assertFalse(instances.isEmpty());

    ServiceInstance serviceInstance = instances.get(0);
    ManagedChannel channel = ManagedChannelBuilder.forAddress(serviceInstance.getHost(), serviceInstance.getPort())
            .usePlaintext()
            .build();

    final GreeterGrpc.GreeterFutureStub greeterFutureStub = GreeterGrpc.newFutureStub(channel);
    final GreeterOuterClass.HelloRequest helloRequest =GreeterOuterClass.HelloRequest.newBuilder().setName("Bob").build();
    final String reply = greeterFutureStub.sayHello(helloRequest).get().getMessage();
    assertNotNull("Replay should not be null",reply);

    boolean isHealthy = false;
    for(int i=0;i<5; ++i){
        final List<HealthService> healthServices = consulClient.getHealthServices(serviceId, true, QueryParams.DEFAULT).getValue();
        isHealthy =healthServices
                .stream()
                .flatMap(h->h.getChecks().stream())
                .anyMatch(c-> Check.CheckStatus.PASSING.equals(c.getStatus())&& c.getCheckId().contains(serviceId));
        if(isHealthy){
            break;
        }else{
            Thread.sleep(Duration.ofSeconds(10).toMillis());
        }
    }
    assertTrue(isHealthy);
    applicationContext.stop();
}
 
Example #10
Source File: ConsulConnection.java    From garmadon with Apache License 2.0 5 votes vote down vote up
/**
 * Fetches healthy garmadon forwarder end points from consul.
 */
private List<HealthService> getHealthyEndPoints() {
    ConsulClient client = new ConsulClient("localhost");

    HealthServicesRequest request = HealthServicesRequest.newBuilder()
            .setPassing(true)
            .setQueryParams(QueryParams.DEFAULT)
            .build();
    Response<List<HealthService>> healthyServices = client.getHealthServices(serviceName, request);

    return healthyServices.getValue();
}
 
Example #11
Source File: ConsulHelper.java    From dyno with Apache License 2.0 5 votes vote down vote up
public static String findHost(HealthService healthService) {
    HealthService.Service service = healthService.getService();
    HealthService.Node node = healthService.getNode();

    if (StringUtils.isNotBlank(service.getAddress())) {
        return service.getAddress();
    } else if (StringUtils.isNotBlank(node.getAddress())) {
        return node.getAddress();
    }
    return node.getNode();
}
 
Example #12
Source File: HealthConsulClient.java    From consul-api with Apache License 2.0 5 votes vote down vote up
@Override
public Response<List<com.ecwid.consul.v1.health.model.HealthService>> getHealthServices(String serviceName, String[] tags, boolean onlyPassing, QueryParams queryParams, String token) {
	HealthServicesRequest request = HealthServicesRequest.newBuilder()
			.setTags(tags)
			.setPassing(onlyPassing)
			.setQueryParams(queryParams)
			.setToken(token)
			.build();

	return getHealthServices(serviceName, request);
}
 
Example #13
Source File: HealthConsulClient.java    From consul-api with Apache License 2.0 5 votes vote down vote up
@Override
public Response<List<HealthService>> getHealthServices(String serviceName, HealthServicesRequest healthServicesRequest) {
	HttpResponse httpResponse = rawClient.makeGetRequest("/v1/health/service/" + serviceName, healthServicesRequest.asUrlParameters());

	if (httpResponse.getStatusCode() == 200) {
		List<com.ecwid.consul.v1.health.model.HealthService> value = GsonFactory.getGson().fromJson(httpResponse.getContent(),
				new TypeToken<List<com.ecwid.consul.v1.health.model.HealthService>>() {
				}.getType());
		return new Response<List<com.ecwid.consul.v1.health.model.HealthService>>(value, httpResponse);
	} else {
		throw new OperationException(httpResponse);
	}
}
 
Example #14
Source File: ConsulServerUtils.java    From spring-cloud-consul with Apache License 2.0 5 votes vote down vote up
public static String findHost(HealthService healthService) {
	HealthService.Service service = healthService.getService();
	HealthService.Node node = healthService.getNode();

	if (StringUtils.hasText(service.getAddress())) {
		return fixIPv6Address(service.getAddress());
	}
	else if (StringUtils.hasText(node.getAddress())) {
		return fixIPv6Address(node.getAddress());
	}
	return node.getNode();
}
 
Example #15
Source File: ConsulReactiveDiscoveryClient.java    From spring-cloud-consul with Apache License 2.0 5 votes vote down vote up
@Override
public Flux<ServiceInstance> getInstances(String serviceId) {
	return Flux.defer(() -> {
		List<ServiceInstance> instances = new ArrayList<>();
		for (HealthService healthService : getHealthServices(serviceId)) {
			instances.add(mapToServiceInstance(healthService, serviceId));
		}
		return Flux.fromIterable(instances);
	}).onErrorResume(exception -> {
		logger.error("Error getting instances from Consul.", exception);
		return Flux.empty();
	}).subscribeOn(Schedulers.boundedElastic());
}
 
Example #16
Source File: ConsulReactiveDiscoveryClient.java    From spring-cloud-consul with Apache License 2.0 5 votes vote down vote up
private List<HealthService> getHealthServices(String serviceId) {
	HealthServicesRequest request = HealthServicesRequest.newBuilder()
			.setTag(this.properties.getDefaultQueryTag())
			.setPassing(this.properties.isQueryPassing())
			.setQueryParams(QueryParams.DEFAULT)
			.setToken(this.properties.getAclToken()).build();

	Response<List<HealthService>> services = client.getHealthServices(serviceId,
			request);
	return services == null ? Collections.emptyList() : services.getValue();
}
 
Example #17
Source File: ConsulReactiveDiscoveryClient.java    From spring-cloud-consul with Apache License 2.0 5 votes vote down vote up
private ServiceInstance mapToServiceInstance(HealthService service,
		String serviceId) {
	String host = findHost(service);
	Map<String, String> metadata = service.getService().getMeta();
	if (metadata == null) {
		metadata = new LinkedHashMap<>();
	}
	boolean secure = false;
	if (metadata.containsKey("secure")) {
		secure = Boolean.parseBoolean(metadata.get("secure"));
	}
	return new DefaultServiceInstance(service.getService().getId(), serviceId, host,
			service.getService().getPort(), secure, metadata);
}
 
Example #18
Source File: ConsulReactiveDiscoveryClientTests.java    From spring-cloud-consul with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnFluxOfServiceInstances() {
	configureCommonProperties();
	Response<List<HealthService>> response = consulInstancesResponse();
	when(consulClient.getHealthServices(eq("existing-service"),
			any(HealthServicesRequest.class))).thenReturn(response);
	Flux<ServiceInstance> instances = client.getInstances("existing-service");
	StepVerifier.create(instances).expectNextCount(1).expectComplete().verify();
	verify(properties).getAclToken();
	verify(properties).getDefaultQueryTag();
	verify(properties).isQueryPassing();
	verify(consulClient).getHealthServices(eq("existing-service"), any());
}
 
Example #19
Source File: ConsulReactiveDiscoveryClientTests.java    From spring-cloud-consul with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnFluxOfServiceInstancesWithAclToken() {
	configureCommonProperties();
	when(properties.getAclToken()).thenReturn("aclToken");
	Response<List<HealthService>> response = consulInstancesResponse();
	when(consulClient.getHealthServices(eq("existing-service"),
			any(HealthServicesRequest.class))).thenReturn(response);
	Flux<ServiceInstance> instances = client.getInstances("existing-service");
	StepVerifier.create(instances).expectNextCount(1).expectComplete().verify();
	verify(properties, times(1)).getAclToken();
	verify(properties).getDefaultQueryTag();
	verify(properties).isQueryPassing();
	verify(consulClient).getHealthServices(eq("existing-service"), any());
}
 
Example #20
Source File: ConsulReactiveDiscoveryClientTests.java    From spring-cloud-consul with Apache License 2.0 5 votes vote down vote up
private Response<List<HealthService>> consulInstancesResponse() {
	HealthService healthService = mock(HealthService.class);
	HealthService.Service service = mock(HealthService.Service.class);

	when(healthService.getService()).thenReturn(service);
	when(service.getAddress()).thenReturn("localhost");
	when(service.getPort()).thenReturn(443);
	lenient().when(service.getTags()).thenReturn(singletonList("secure=true"));

	return new Response<>(singletonList(healthService), 0L, true,
			System.currentTimeMillis());
}
 
Example #21
Source File: ConsulConnection.java    From garmadon with Apache License 2.0 5 votes vote down vote up
/**
 * Choose randomly a healthy garmadon forwarder and connect to it via a FixedConnection.
 */
@Override
public void establishConnection() {
    for (; ; ) {
        List<HealthService> nodes = getHealthyEndPoints();

        HealthService electedNode = nodes.get(ThreadLocalRandom.current().nextInt(nodes.size()));

        String host = electedNode.getNode().getAddress();
        Integer port = electedNode.getService().getPort();

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("will use forwarder at " + host + ":" + port);
        }

        if (underlying != null) {
            underlying.close();
        }

        underlying = new FixedConnection(host, port);

        boolean connected = underlying.establishConnectionOnce();
        if (connected) {
            return;
        }
    }
}
 
Example #22
Source File: ConsulServerContext.java    From pampas with Apache License 2.0 5 votes vote down vote up
private static String findHost(HealthService healthService) {
    HealthService.Service service = healthService.getService();
    HealthService.Node node = healthService.getNode();

    if (StringUtils.isNotBlank(service.getAddress())) {
        return service.getAddress();
    } else if (StringUtils.isNotBlank(node.getAddress())) {
        return node.getAddress();
    }
    return node.getNode();
}
 
Example #23
Source File: ConsulServerContext.java    From pampas with Apache License 2.0 5 votes vote down vote up
public boolean isPassingChecks(HealthService service) {
    for (Check check : service.getChecks()) {
        if (check.getStatus() != Check.CheckStatus.PASSING) {
            return false;
        }
    }
    return true;
}
 
Example #24
Source File: HiveDriverConsul.java    From garmadon with Apache License 2.0 5 votes vote down vote up
/**
 * Fetches healthy service nodes
 */
private List<HealthService> getHealthyEndPoints(String serviceName) {
    ConsulClient client = new ConsulClient("localhost");

    HealthServicesRequest request = HealthServicesRequest.newBuilder()
        .setPassing(true)
        .setQueryParams(QueryParams.DEFAULT)
        .build();
    Response<List<HealthService>> healthyServices = client.getHealthServices(serviceName, request);

    return healthyServices.getValue();
}
 
Example #25
Source File: HiveDriverConsul.java    From garmadon with Apache License 2.0 5 votes vote down vote up
/**
 * Fetches one of the healthy node
 */
private String getEndPoint(String url) throws SQLException {
    String serviceName = url.split("/")[0];
    List<HealthService> nodes = getHealthyEndPoints(serviceName);
    if (nodes.size() == 0) throw new SQLException("No nodes are available for service: " + serviceName);
    HealthService electedNode = nodes.get(ThreadLocalRandom.current().nextInt(nodes.size()));

    String host = electedNode.getNode().getAddress();
    String port = String.valueOf(electedNode.getService().getPort());

    String hiveJdbcConf = url.replace(serviceName, "");
    return "jdbc:hive2://" + host + ":" + port + hiveJdbcConf;
}
 
Example #26
Source File: NacosSyncToConsulServiceImpl.java    From nacos-sync with Apache License 2.0 5 votes vote down vote up
@Override
public boolean delete(TaskDO taskDO) {
    try {

        NamingService sourceNamingService =
            nacosServerHolder.get(taskDO.getSourceClusterId(), taskDO.getGroupName());
        ConsulClient consulClient = consulServerHolder.get(taskDO.getDestClusterId(), taskDO.getGroupName());

        sourceNamingService.unsubscribe(taskDO.getServiceName(), nacosListenerMap.get(taskDO.getTaskId()));

        // 删除目标集群中同步的实例列表
        Response<List<HealthService>> serviceResponse =
            consulClient.getHealthServices(taskDO.getServiceName(), true, QueryParams.DEFAULT);
        List<HealthService> healthServices = serviceResponse.getValue();
        for (HealthService healthService : healthServices) {

            if (needDelete(ConsulUtils.transferMetadata(healthService.getService().getTags()), taskDO)) {
                consulClient.agentServiceDeregister(healthService.getService().getId());
            }
        }
    } catch (Exception e) {
        log.error("delete a task from nacos to nacos was failed, taskId:{}", taskDO.getTaskId(), e);
        metricsManager.recordError(MetricsStatisticsType.DELETE_ERROR);
        return false;
    }
    return true;
}
 
Example #27
Source File: ConsulSyncToNacosServiceImpl.java    From nacos-sync with Apache License 2.0 5 votes vote down vote up
private void overrideAllInstance(TaskDO taskDO, NamingService destNamingService,
    List<HealthService> healthServiceList, Set<String> instanceKeys) throws NacosException {
    for (HealthService healthService : healthServiceList) {
        if (needSync(ConsulUtils.transferMetadata(healthService.getService().getTags()))) {
            destNamingService.registerInstance(taskDO.getServiceName(),
                buildSyncInstance(healthService, taskDO));
            instanceKeys.add(composeInstanceKey(healthService.getService().getAddress(),
                healthService.getService().getPort()));
        }
    }
}
 
Example #28
Source File: ConsulSyncToNacosServiceImpl.java    From nacos-sync with Apache License 2.0 5 votes vote down vote up
private Instance buildSyncInstance(HealthService instance, TaskDO taskDO) {
    Instance temp = new Instance();
    temp.setIp(instance.getService().getAddress());
    temp.setPort(instance.getService().getPort());
    Map<String, String> metaData = new HashMap<>(ConsulUtils.transferMetadata(instance.getService().getTags()));
    metaData.put(SkyWalkerConstants.DEST_CLUSTERID_KEY, taskDO.getDestClusterId());
    metaData.put(SkyWalkerConstants.SYNC_SOURCE_KEY,
        skyWalkerCacheServices.getClusterType(taskDO.getSourceClusterId()).getCode());
    metaData.put(SkyWalkerConstants.SOURCE_CLUSTERID_KEY, taskDO.getSourceClusterId());
    temp.setMetadata(metaData);
    return temp;
}
 
Example #29
Source File: ConsulSyncToNacosServiceImplTest.java    From nacos-sync with Apache License 2.0 5 votes vote down vote up
private HealthService buildHealthService(String address,int port,Map<String,String> metadata) {
    HealthService healthService = new HealthService();
    HealthService.Node node = new HealthService.Node();
    node.setMeta(metadata);
    HealthService.Service service = new HealthService.Service();
    service.setAddress(address);
    service.setPort(port);
    healthService.setNode(node);
    healthService.setService(service);

    return healthService;
}
 
Example #30
Source File: ConsulNamingService.java    From brpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public void doSubscribe(SubscribeInfo subscribeInfo, NotifyListener listener) {
    final String serviceName = subscribeInfo.getServiceId();
    Response<List<HealthService>> response = lookupHealthService(serviceName, -1);
    List<ServiceInstance> instances = convert(response);
    log.info("lookup {} instances from consul", instances.size());
    WatchTask watchTask = new WatchTask(serviceName, instances, response.getConsulIndex(), listener);
    watchExecutor.submit(watchTask);
    watchTaskMap.putIfAbsent(subscribeInfo, watchTask);
}