com.ecwid.consul.v1.Response Java Examples

The following examples show how to use com.ecwid.consul.v1.Response. 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: ConsulPropertySource.java    From spring-cloud-consul with Apache License 2.0 6 votes vote down vote up
public void init() {
	if (!this.context.endsWith("/")) {
		this.context = this.context + "/";
	}

	Response<List<GetValue>> response = this.source.getKVValues(this.context,
			this.configProperties.getAclToken(), QueryParams.DEFAULT);

	this.initialIndex = response.getConsulIndex();

	final List<GetValue> values = response.getValue();
	ConsulConfigProperties.Format format = this.configProperties.getFormat();
	switch (format) {
	case KEY_VALUE:
		parsePropertiesInKeyValueFormat(values);
		break;
	case PROPERTIES:
	case YAML:
		parsePropertiesWithNonKeyValueFormat(values, format);
	}
}
 
Example #2
Source File: ConsulAutoServiceRegistrationCustomizedInstanceGroupTests.java    From spring-cloud-consul with Apache License 2.0 6 votes vote down vote up
@Test
@Ignore // FIXME: 3.0.0
public void contextLoads() {
	Response<Map<String, Service>> response = this.consul.getAgentServices();
	Map<String, Service> services = response.getValue();
	Service service = services.get("myTestService1-WithGroup");
	assertThat(service).as("service was null").isNotNull();
	assertThat(service.getPort().intValue()).as("service port is 0").isNotEqualTo(0);
	assertThat(service.getId()).as("service id was wrong")
			.isEqualTo("myTestService1-WithGroup");
	assertThat(service.getTags().contains("group=test")).as("service group was wrong")
			.isTrue();

	// ConsulServerList serverList = new ConsulServerList(this.consul,
	// this.properties);
	// DefaultClientConfigImpl config = new DefaultClientConfigImpl();
	// config.setClientName("myTestService-WithGroup");
	// serverList.initWithNiwsConfig(config);
	//
	// List<ConsulServer> servers = serverList.getInitialListOfServers();
	// assertThat(servers.size()).as("servers was wrong size").isEqualTo(1);
	// assertThat(servers.get(0).getMetaInfo().getServerGroup())
	// .as("service group was wrong").isEqualTo("test");
}
 
Example #3
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 #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: AlphaConsulAutoConfiguration.java    From servicecomb-pack with Apache License 2.0 6 votes vote down vote up
/**
 * Update grpc port of consul tags after Conusl Registered
 * */
@EventListener
public void listenInstanceRegisteredEvent(InstanceRegisteredEvent instanceRegisteredEvent){
  if(alphaServerPort == 0){
    if(instanceRegisteredEvent.getConfig() instanceof ConsulDiscoveryProperties){
      ConsulDiscoveryProperties properties = (ConsulDiscoveryProperties)instanceRegisteredEvent.getConfig();
      this.consuleInstanceId = formatConsulInstanceId(properties.getInstanceId());
      Response<List<CatalogService>> services = consulClient.getCatalogService(serviceName,null);
      if(services.getValue() != null){
        services.getValue().stream().filter(service ->
            service.getServiceId().equalsIgnoreCase(this.consuleInstanceId)).forEach(service -> {

          NewService newservice =  new NewService();
          newservice.setName(service.getServiceName());
          newservice.setId(service.getServiceId());
          newservice.setAddress(service.getAddress());
          newservice.setPort(service.getServicePort());
          List<String> tags = service.getServiceTags();
          tags.remove("alpha-server-port=0");
          tags.add("alpha-server-port="+actualAlphaServerPort);
          newservice.setTags(tags);
          consulClient.agentServiceRegister(newservice);
        });
      }
    }
  }
}
 
Example #6
Source File: SessionConsulClient.java    From consul-api with Apache License 2.0 6 votes vote down vote up
@Override
public Response<Session> renewSession(String session, QueryParams queryParams, String token) {
	UrlParameters tokenParam = token != null ? new SingleUrlParameters("token", token) : null;
	HttpResponse httpResponse = rawClient.makePutRequest("/v1/session/renew/" + session, "", queryParams, tokenParam);

	if (httpResponse.getStatusCode() == 200) {
		List<Session> value = GsonFactory.getGson().fromJson(httpResponse.getContent(), new TypeToken<List<Session>>() {
		}.getType());

		if (value.size() == 1) {
			return new Response<Session>(value.get(0), httpResponse);
		} else {
			throw new ConsulException("Strange response (list size=" + value.size() + ")");
		}
	} else {
		throw new OperationException(httpResponse);
	}
}
 
Example #7
Source File: ConsulEndpoint.java    From spring-cloud-consul with Apache License 2.0 6 votes vote down vote up
@ReadOperation
public ConsulData invoke() {
	ConsulData data = new ConsulData();
	// data.setKeyValues(kvClient.getKeyValueRecurse());
	Response<Map<String, Service>> agentServices = this.consul.getAgentServices();
	data.setAgentServices(agentServices.getValue());

	Response<Map<String, List<String>>> catalogServices = this.consul
			.getCatalogServices(CatalogServicesRequest.newBuilder()
					.setQueryParams(QueryParams.DEFAULT).build());

	for (String serviceId : catalogServices.getValue().keySet()) {
		Response<List<CatalogService>> response = this.consul
				.getCatalogService(serviceId, CatalogServiceRequest.newBuilder()
						.setQueryParams(QueryParams.DEFAULT).build());
		data.getCatalogServices().put(serviceId, response.getValue());
	}

	Response<List<Node>> catalogNodes = this.consul
			.getCatalogNodes(CatalogNodesRequest.newBuilder()
					.setQueryParams(QueryParams.DEFAULT).build());
	data.setCatalogNodes(catalogNodes.getValue());

	return data;
}
 
Example #8
Source File: SessionConsulClient.java    From consul-api with Apache License 2.0 5 votes vote down vote up
@Override
public Response<String> sessionCreate(NewSession newSession, QueryParams queryParams, String token) {
	UrlParameters tokenParam = token != null ? new SingleUrlParameters("token", token) : null;

	String json = GsonFactory.getGson().toJson(newSession);
	HttpResponse httpResponse = rawClient.makePutRequest("/v1/session/create", json, queryParams, tokenParam);

	if (httpResponse.getStatusCode() == 200) {
		Map<String, String> value = GsonFactory.getGson().fromJson(httpResponse.getContent(), new TypeToken<Map<String, String>>() {
		}.getType());
		return new Response<String>(value.get("ID"), httpResponse);
	} else {
		throw new OperationException(httpResponse);
	}
}
 
Example #9
Source File: ConsulAutoServiceRegistrationNonWebTests.java    From spring-cloud-consul with Apache License 2.0 5 votes vote down vote up
@Test
public void contextLoads() {
	assertThat(this.autoServiceRegistration)
			.as("ConsulAutoServiceRegistration was created").isNotNull();

	Response<Map<String, Service>> response = this.consul.getAgentServices();
	Map<String, Service> services = response.getValue();
	Service service = services.get("consulNonWebTest");
	assertThat(service).as("service was registered").isNull(); // no port to listen,
																// hence no
	// registration
}
 
Example #10
Source File: AgentConsulClient.java    From consul-api with Apache License 2.0 5 votes vote down vote up
@Override
public Response<Void> agentJoin(String address, boolean wan) {
	UrlParameters wanParams = wan ? new SingleUrlParameters("wan", "1") : null;
	HttpResponse httpResponse = rawClient.makePutRequest("/v1/agent/join/" + address, "", wanParams);

	if (httpResponse.getStatusCode() == 200) {
		return new Response<Void>(null, httpResponse);
	} else {
		throw new OperationException(httpResponse);
	}
}
 
Example #11
Source File: ConsulCatalogWatch.java    From spring-cloud-consul with Apache License 2.0 5 votes vote down vote up
@Timed("consul.watch-catalog-services")
public void catalogServicesWatch() {
	try {
		long index = -1;
		if (this.catalogServicesIndex.get() != null) {
			index = this.catalogServicesIndex.get().longValue();
		}

		CatalogServicesRequest request = CatalogServicesRequest.newBuilder()
				.setQueryParams(new QueryParams(
						this.properties.getCatalogServicesWatchTimeout(), index))
				.setToken(this.properties.getAclToken()).build();
		Response<Map<String, List<String>>> response = this.consul
				.getCatalogServices(request);
		Long consulIndex = response.getConsulIndex();
		if (consulIndex != null) {
			this.catalogServicesIndex.set(BigInteger.valueOf(consulIndex));
		}

		if (log.isTraceEnabled()) {
			log.trace("Received services update from consul: " + response.getValue()
					+ ", index: " + consulIndex);
		}
		this.publisher.publishEvent(new HeartbeatEvent(this, consulIndex));
	}
	catch (Exception e) {
		log.error("Error watching Consul CatalogServices", e);
	}
}
 
Example #12
Source File: AgentConsulClient.java    From consul-api with Apache License 2.0 5 votes vote down vote up
@Override
public Response<Void> agentServiceDeregister(String serviceId, String token) {
	UrlParameters tokenParam = token != null ? new SingleUrlParameters("token", token) : null;

	HttpResponse httpResponse = rawClient.makePutRequest("/v1/agent/service/deregister/" + serviceId, "", tokenParam);

	if (httpResponse.getStatusCode() == 200) {
		return new Response<Void>(null, httpResponse);
	} else {
		throw new OperationException(httpResponse);
	}
}
 
Example #13
Source File: CoordinateConsulClient.java    From consul-api with Apache License 2.0 5 votes vote down vote up
@Override
public Response<List<Datacenter>> getDatacenters() {
	HttpResponse httpResponse = rawClient.makeGetRequest("/v1/coordinate/datacenters");

	if (httpResponse.getStatusCode() == 200) {
		List<Datacenter> value = GsonFactory.getGson().fromJson(httpResponse.getContent(), new TypeToken<List<Datacenter>>() {
		}.getType());
		return new Response<List<Datacenter>>(value, httpResponse);
	} else {
		throw new OperationException(httpResponse);
	}
}
 
Example #14
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 #15
Source File: CatalogConsulClientTest.java    From consul-api with Apache License 2.0 5 votes vote down vote up
@Test
void testGetCatalogNodes() {
	CatalogNodesRequest request = CatalogNodesRequest.newBuilder().build();
	Response<List<Node>> response = consulClient.getCatalogNodes(request);

	// We should find only one node – this
	assertEquals(1, response.getValue().size());
}
 
Example #16
Source File: EventConsulClient.java    From consul-api with Apache License 2.0 5 votes vote down vote up
@Override
public Response<List<Event>> eventList(EventListRequest eventListRequest) {
	HttpResponse httpResponse = rawClient.makeGetRequest("/v1/event/list", eventListRequest.asUrlParameters());

	if (httpResponse.getStatusCode() == 200) {
		List<Event> value = GsonFactory.getGson().fromJson(httpResponse.getContent(), new TypeToken<List<Event>>() {
		}.getType());
		return new Response<List<Event>>(value, httpResponse);
	} else {
		throw new OperationException(httpResponse);
	}
}
 
Example #17
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 #18
Source File: ConsulClient.java    From saluki with Apache License 2.0 5 votes vote down vote up
public ConsulServiceResp lookupHealthService(String serviceName, long lastConsulIndex) {
    QueryParams queryParams = new QueryParams(ConsulConstants.CONSUL_BLOCK_TIME_SECONDS, lastConsulIndex);
    Response<List<HealthService>> orgResponse = client.getHealthServices(serviceName, true, queryParams);
    if (orgResponse != null && orgResponse.getValue() != null && !orgResponse.getValue().isEmpty()) {
        List<HealthService> HealthServices = orgResponse.getValue();
        List<ConsulService> ConsulServcies = Lists.newArrayList();
        for (HealthService orgService : HealthServices) {
            Service org = orgService.getService();
            ConsulService newService = ConsulService.newSalukiService()//
                                                    .withAddress(org.getAddress())//
                                                    .withName(org.getService())//
                                                    .withId(org.getId())//
                                                    .withPort(org.getPort().toString())//
                                                    .withTags(org.getTags())//
                                                    .build();
            ConsulServcies.add(newService);
        }
        if (!ConsulServcies.isEmpty()) {
            ConsulServiceResp response = ConsulServiceResp.newResponse()//
                                                          .withValue(ConsulServcies)//
                                                          .withConsulIndex(orgResponse.getConsulIndex())//
                                                          .withConsulLastContact(orgResponse.getConsulLastContact())//
                                                          .withConsulKnowLeader(orgResponse.isConsulKnownLeader())//
                                                          .build();
            return response;
        }
    }
    return null;
}
 
Example #19
Source File: AgentConsulClient.java    From consul-api with Apache License 2.0 5 votes vote down vote up
@Override
public Response<Void> agentForceLeave(String node) {
	HttpResponse httpResponse = rawClient.makePutRequest("/v1/agent/force-leave/" + node, "");

	if (httpResponse.getStatusCode() == 200) {
		return new Response<Void>(null, httpResponse);
	} else {
		throw new OperationException(httpResponse);
	}
}
 
Example #20
Source File: AgentConsulClient.java    From consul-api with Apache License 2.0 5 votes vote down vote up
@Override
public Response<Map<String, Service>> getAgentServices() {
	HttpResponse httpResponse = rawClient.makeGetRequest("/v1/agent/services");

	if (httpResponse.getStatusCode() == 200) {
		Map<String, Service> agentServices = GsonFactory.getGson().fromJson(httpResponse.getContent(),
				new TypeToken<Map<String, Service>>() {
				}.getType());
		return new Response<Map<String, Service>>(agentServices, httpResponse);
	} else {
		throw new OperationException(httpResponse);
	}
}
 
Example #21
Source File: HealthConsulClient.java    From consul-api with Apache License 2.0 5 votes vote down vote up
@Override
public Response<List<Check>> getHealthChecksForService(String serviceName, HealthChecksForServiceRequest healthChecksForServiceRequest) {
	HttpResponse httpResponse = rawClient.makeGetRequest("/v1/health/checks/" + serviceName, healthChecksForServiceRequest.asUrlParameters());

	if (httpResponse.getStatusCode() == 200) {
		List<Check> value = GsonFactory.getGson().fromJson(httpResponse.getContent(), new TypeToken<List<Check>>() {
		}.getType());
		return new Response<List<Check>>(value, httpResponse);
	} else {
		throw new OperationException(httpResponse);
	}
}
 
Example #22
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 #23
Source File: HealthConsulClient.java    From consul-api with Apache License 2.0 5 votes vote down vote up
@Override
public Response<List<Check>> getHealthChecksForService(String serviceName, QueryParams queryParams) {
	HealthChecksForServiceRequest request = HealthChecksForServiceRequest.newBuilder()
			.setQueryParams(queryParams)
			.build();

	return getHealthChecksForService(serviceName, request);
}
 
Example #24
Source File: TtlSchedulerTests.java    From spring-cloud-consul with Apache License 2.0 5 votes vote down vote up
private Check getCheckForService(String serviceId) {
	Response<List<Check>> checkResponse = this.consul
			.getHealthChecksForService(serviceId, HealthChecksForServiceRequest
					.newBuilder().setQueryParams(QueryParams.DEFAULT).build());
	if (checkResponse.getValue().size() > 0) {
		return checkResponse.getValue().get(0);
	}
	return null;
}
 
Example #25
Source File: AclConsulClient.java    From consul-api with Apache License 2.0 5 votes vote down vote up
@Override
public Response<Void> aclUpdate(UpdateAcl updateAcl, String token) {
	UrlParameters tokenParams = token != null ? new SingleUrlParameters("token", token) : null;
	String json = GsonFactory.getGson().toJson(updateAcl);
	HttpResponse httpResponse = rawClient.makePutRequest("/v1/acl/update", json, tokenParams);

	if (httpResponse.getStatusCode() == 200) {
		return new Response<Void>(null, httpResponse);
	} else {
		throw new OperationException(httpResponse);
	}
}
 
Example #26
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 #27
Source File: AgentConsulClient.java    From consul-api with Apache License 2.0 5 votes vote down vote up
@Override
public Response<Void> agentCheckFail(String checkId, String note, String token) {
	UrlParameters noteParameter = note != null ? new SingleUrlParameters("note", note) : null;
	UrlParameters tokenParameter = token != null ? new SingleUrlParameters("token", token) : null;

	HttpResponse httpResponse = rawClient.makePutRequest("/v1/agent/check/fail/" + checkId, "", noteParameter, tokenParameter);

	if (httpResponse.getStatusCode() == 200) {
		return new Response<Void>(null, httpResponse);
	} else {
		throw new OperationException(httpResponse);
	}
}
 
Example #28
Source File: ConsulAutoServiceRegistrationDefaultPortTests.java    From spring-cloud-consul with Apache License 2.0 5 votes vote down vote up
@Test
public void contextLoads() {
	Response<Map<String, Service>> response = this.consul.getAgentServices();
	Map<String, Service> services = response.getValue();
	Service service = services.get("myTestService2-DD");
	assertThat(service).as("service was null").isNotNull();
	assertThat(service.getPort().intValue()).as("service port is 0").isNotEqualTo(0);
}
 
Example #29
Source File: ConsulDiscoveryClient.java    From spring-cloud-consul with Apache License 2.0 5 votes vote down vote up
public List<ServiceInstance> getAllInstances() {
	List<ServiceInstance> instances = new ArrayList<>();

	Response<Map<String, List<String>>> services = this.client
			.getCatalogServices(CatalogServicesRequest.newBuilder()
					.setQueryParams(QueryParams.DEFAULT).build());
	for (String serviceId : services.getValue().keySet()) {
		addInstancesToList(instances, serviceId, QueryParams.DEFAULT);
	}
	return instances;
}
 
Example #30
Source File: ConsulSendingHandler.java    From spring-cloud-consul with Apache License 2.0 5 votes vote down vote up
@Override
protected void handleMessageInternal(Message<?> message) {
	if (this.logger.isTraceEnabled()) {
		this.logger.trace("Publishing message" + message);
	}

	Object payload = message.getPayload();
	// TODO: support headers
	// TODO: support consul event filters: NodeFilter, ServiceFilter, TagFilter
	Response<Event> event = this.consul.eventFire(this.eventName, (String) payload,
			new EventParams(), QueryParams.DEFAULT);
	// TODO: return event?
	// return null;
}