Java Code Examples for com.ecwid.consul.v1.agent.model.NewService

The following examples show how to use com.ecwid.consul.v1.agent.model.NewService. These examples are extracted from open source projects. 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
@Override
public ConsulRegistration convert(ServiceDefinition source) {
    NewService service = new NewService();
    service.setName(source.getName());
    service.setId(source.getId());
    service.setAddress(properties.getServiceRegistry().getServiceHost());
    service.setPort(source.getPort());

    service.setTags(
        source.getMetadata().entrySet().stream()
            .map(e -> e.getKey() + "=" + e.getValue())
            .collect(Collectors.toList())
    );

    return new ConsulRegistration(service, null) {
        @Override
        public boolean isSecure() {
            return service.getPort() == 443 || Objects.equals("https", source.getMetadata().get(ServiceDefinition.SERVICE_META_PROTOCOL));
        }
    };
}
 
Example 2
Source Project: nacos-sync   Source File: NacosSyncToConsulServiceImpl.java    License: Apache License 2.0 7 votes vote down vote up
public NewService buildSyncInstance(Instance instance, TaskDO taskDO) {
    NewService newService = new NewService();
    newService.setAddress(instance.getIp());
    newService.setPort(instance.getPort());
    newService.setName(taskDO.getServiceName());
    newService.setId(instance.getInstanceId());
    List<String> tags = Lists.newArrayList();
    tags.addAll(instance.getMetadata().entrySet().stream()
        .map(entry -> String.join("=", entry.getKey(), entry.getValue())).collect(Collectors.toList()));
    tags.add(String.join("=", SkyWalkerConstants.DEST_CLUSTERID_KEY, taskDO.getDestClusterId()));
    tags.add(String.join("=", SkyWalkerConstants.SYNC_SOURCE_KEY,
        skyWalkerCacheServices.getClusterType(taskDO.getSourceClusterId()).getCode()));
    tags.add(String.join("=", SkyWalkerConstants.SOURCE_CLUSTERID_KEY, taskDO.getSourceClusterId()));
    newService.setTags(tags);
    return newService;
}
 
Example 3
Source Project: sofa-rpc   Source File: ConsulRegistry.java    License: Apache License 2.0 7 votes vote down vote up
private void registerConsulService(NewService service) {
    consulClient.agentServiceRegister(service);
    if (service.getCheck().getTtl() != null) {
        ScheduledFuture<?> scheduledFuture =
                heartbeatExecutor.scheduleAtFixedRate(
                        () -> checkPass(service),
                        0, properties.getHeartbeatInterval(), TimeUnit.MILLISECONDS);

        // multiple heartbeat use the same service id, remove and cancel the old one, or still use it?
        ScheduledFuture oldFuture = heartbeatFutures.remove(service.getId());
        if (oldFuture != null) {
            oldFuture.cancel(true);
        }
        heartbeatFutures.put(service.getId(), scheduledFuture);
    }
}
 
Example 4
Source Project: sofa-rpc   Source File: ConsulRegistry.java    License: Apache License 2.0 7 votes vote down vote up
private List<NewService> buildNewServices(ProviderConfig<?> config) {
    List<ServerConfig> servers = config.getServer();
    if (CommonUtils.isEmpty(servers)) {
        return Collections.emptyList();
    }
    return servers.stream().map(server -> {
        NewService service = new NewService();
        service.setId(buildServiceId(config, server));
        service.setName(buildServiceName(config));

        String host = getServerHost(server);
        int port = server.getPort();
        service.setAddress(host);
        service.setPort(port);

        Map<String, String> metaData = RegistryUtils.convertProviderToMap(config, server).entrySet().stream()
                .filter(e -> ConsulUtils.isValidMetaKey(e.getKey()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
        service.setMeta(metaData);
        service.setTags(Collections.singletonList(buildUniqueName(config, server.getProtocol())));

        service.setCheck(buildCheck(host, port));
        return service;
    }).collect(Collectors.toList());
}
 
Example 5
Source Project: dubbo3   Source File: ConsulRegistry.java    License: Apache License 2.0 7 votes vote down vote up
@Override
protected void doRegister(URL url) {
    NewService dubboService = new NewService();
    dubboService.setTags(Arrays.asList("dubbo"));
    dubboService.setAddress(url.toFullString());
    dubboService.setPort(url.getPort());
    dubboService.setId(convertConsulSerivceId(url));
    dubboService.setName(url.getServiceInterface());
    //set health checker
    String dubboHTTPCheckURL = System.getProperty("DUBBO_HTTP_CHECK_URL");
    if (dubboHTTPCheckURL == null) {
        dubboHTTPCheckURL = System.getenv("DUBBO_HTTP_CHECK_URL");
    }
    if (dubboHTTPCheckURL != null) {
        NewService.Check check = new NewService.Check();
        check.setHttp(dubboHTTPCheckURL);
        check.setInterval("15s");
        check.setTimeout("3s");
        dubboService.setCheck(check);
    }
    consulClient.agentServiceRegister(dubboService);
}
 
Example 6
@Override
public void registerStubs() {
	Map<StubConfiguration, Integer> activeStubs = this.stubRunning.runStubs()
			.validNamesAndPorts();
	for (Map.Entry<StubConfiguration, Integer> entry : activeStubs.entrySet()) {
		NewService newService = newService(entry.getKey(), entry.getValue());
		this.services.add(newService);
		try {
			this.consulClient.agentServiceRegister(newService);
			if (log.isDebugEnabled()) {
				log.debug("Successfully registered stub ["
						+ entry.getKey().toColonSeparatedDependencyNotation()
						+ "] in Service Discovery");
			}
		}
		catch (Exception e) {
			log.warn("Exception occurred while trying to register a stub ["
					+ entry.getKey().toColonSeparatedDependencyNotation()
					+ "] in Service Discovery", e);
		}
	}
}
 
Example 7
@BeforeClass
public static void beforeClass() {

	assumeTrue(CanConnect.to(new InetSocketAddress(CONSUL_HOST, CONSUL_PORT)));

	ConsulClient client = new ConsulClient();

	Response<List<CatalogService>> response = client.getCatalogService("vault",
			QueryParams.DEFAULT);

	if (response.getValue().isEmpty()) {

		NewService service = new NewService();
		service.setAddress("localhost");
		service.setPort(8200);
		service.setId("vault");
		service.setName("vault");

		client.agentServiceRegister(service);
	}
}
 
Example 8
public static void setCheck(NewService service,
		AutoServiceRegistrationProperties autoServiceRegistrationProperties,
		ConsulDiscoveryProperties properties, ApplicationContext context,
		HeartbeatProperties heartbeatProperties) {
	if (properties.isRegisterHealthCheck() && service.getCheck() == null) {
		Integer checkPort;
		if (shouldRegisterManagement(autoServiceRegistrationProperties, properties,
				context)) {
			checkPort = getManagementPort(properties, context);
		}
		else {
			checkPort = service.getPort();
		}
		Assert.notNull(checkPort, "checkPort may not be null");
		service.setCheck(createCheck(checkPort, heartbeatProperties, properties));
	}
}
 
Example 9
public static ConsulAutoRegistration managementRegistration(
		AutoServiceRegistrationProperties autoServiceRegistrationProperties,
		ConsulDiscoveryProperties properties, ApplicationContext context,
		List<ConsulManagementRegistrationCustomizer> managementRegistrationCustomizers,
		HeartbeatProperties heartbeatProperties) {
	NewService management = new NewService();
	management.setId(getManagementServiceId(properties, context));
	management.setAddress(properties.getHostname());
	management
			.setName(getManagementServiceName(properties, context.getEnvironment()));
	management.setPort(getManagementPort(properties, context));
	management.setTags(properties.getManagementTags());
	management.setEnableTagOverride(properties.getManagementEnableTagOverride());
	management.setMeta(properties.getManagementMetadata());
	if (properties.isRegisterHealthCheck()) {
		management.setCheck(createCheck(getManagementPort(properties, context),
				heartbeatProperties, properties));
	}
	ConsulAutoRegistration registration = new ConsulAutoRegistration(management,
			autoServiceRegistrationProperties, properties, context,
			heartbeatProperties, managementRegistrationCustomizers);
	managementCustomize(managementRegistrationCustomizers, registration);
	return registration;
}
 
Example 10
Source Project: spring-cloud-consul   Source File: ConsulServiceRegistry.java    License: Apache License 2.0 7 votes vote down vote up
@Override
public void register(ConsulRegistration reg) {
	log.info("Registering service with consul: " + reg.getService());
	try {
		this.client.agentServiceRegister(reg.getService(),
				this.properties.getAclToken());
		NewService service = reg.getService();
		if (this.heartbeatProperties.isEnabled() && this.ttlScheduler != null
				&& service.getCheck() != null
				&& service.getCheck().getTtl() != null) {
			this.ttlScheduler.add(reg.getInstanceId());
		}
	}
	catch (ConsulException e) {
		if (this.properties.isFailFast()) {
			log.error("Error registering service with consul: " + reg.getService(),
					e);
			ReflectionUtils.rethrowRuntimeException(e);
		}
		log.warn("Failfast is false. Error registering service with consul: "
				+ reg.getService(), e);
	}
}
 
Example 11
@Test
public void contextLoads() {
	NewService service = this.registration.getService();
	assertThat(service).as("service was null").isNotNull();
	assertThat(service.getPort()).as("service port is 0").isGreaterThan(0);

	NewService.Check check = service.getCheck();
	assertThat(check).as("check was null").isNotNull();

	String httpCheck = String.format("%s://%s:%s%s", this.properties.getScheme(),
			this.properties.getHostname(), this.properties.getPort(),
			this.properties.getHealthCheckPath());
	assertThat(check.getHttp()).as("http check was wrong").isEqualTo(httpCheck);

	// unable to call consul api to get health check details
}
 
Example 12
Source Project: brpc-java   Source File: ConsulNamingService.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void doRegister(RegisterInfo registerInfo)  {
    NewService newService = getConsulNewService(registerInfo);
    client.agentServiceRegister(newService);
    instanceIds.add("service:" + newService.getId());
    log.info("register success to {}", url);
}
 
Example 13
Source Project: brpc-java   Source File: ConsulNamingService.java    License: Apache License 2.0 6 votes vote down vote up
private NewService getConsulNewService(RegisterInfo registerInfo) {
    NewService newService = new NewService();
    newService.setName(registerInfo.getServiceId());
    newService.setId(generateInstanceId(registerInfo));
    newService.setAddress(registerInfo.getHost());
    newService.setPort(registerInfo.getPort());
    newService.setTags(Arrays.asList(ConsulConstants.CONSUL_SERVICE_TAG));

    NewService.Check check = new NewService.Check();
    check.setTtl(this.consulInterval + "s");
    check.setDeregisterCriticalServiceAfter("3m");
    newService.setCheck(check);

    return newService;
}
 
Example 14
Source Project: sofa-rpc   Source File: ConsulRegistry.java    License: Apache License 2.0 6 votes vote down vote up
private void checkPass(NewService service) {
    try {
        consulClient.agentCheckPass("service:" + service.getId(), "TTL check passing by SOFA RPC");
    } catch (Exception e) {
        LOGGER.error(LogCodes.getLog(LogCodes.ERROR_CHECK_PASS ,"Consul"), e);
    }
}
 
Example 15
public SidecarConsulAutoRegistration(NewService service,
		AutoServiceRegistrationProperties autoServiceRegistrationProperties,
		ConsulDiscoveryProperties properties, ApplicationContext context,
		HeartbeatProperties heartbeatProperties,
		List<ConsulManagementRegistrationCustomizer> managementRegistrationCustomizers) {
	super(service, autoServiceRegistrationProperties, properties, context,
			heartbeatProperties, managementRegistrationCustomizers);
}
 
Example 16
/**
 * Set port on Non-Web Application.
 * @param consulRegistration {@link ConsulRegistration}
 */
private void setPort(ConsulAutoRegistration consulRegistration) {
	int port = consulRegistration.getPort();
	NewService newService = consulRegistration.getService();
	if (newService.getPort() == null) {
		newService.setPort(port);
	}
}
 
Example 17
private void attachURLsIntoMetadata(ConsulRegistration consulRegistration) {
	NewService newService = consulRegistration.getService();
	Map<String, String> serviceMetadata = dubboServiceMetadataRepository
			.getDubboMetadataServiceMetadata();
	if (!isEmpty(serviceMetadata)) {
		List<String> tags = newService.getTags();
		for (Map.Entry<String, String> entry : serviceMetadata.entrySet()) {
			tags.add(entry.getKey() + "=" + entry.getValue());
		}
	}
}
 
Example 18
Source Project: saluki   Source File: ConsulService.java    License: Apache License 2.0 6 votes vote down vote up
public NewService getNewService() {
    NewService consulService = new NewService();
    consulService.setName(this.name);
    consulService.setId(this.id);
    consulService.setAddress(this.address);
    consulService.setPort(this.port);
    consulService.setTags(unmodifiableList(new ArrayList<>(this.tags)));
    NewService.Check check = new NewService.Check();
    check.setTtl(this.interval + "s");
    check.setDeregisterCriticalServiceAfter("3m");
    consulService.setCheck(check);
    return consulService;
}
 
Example 19
Source Project: dubbox   Source File: ConsulRegistry.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void doRegister(URL url) {
	NewService newService = createServiceDef(url, this.ttl);
	try {
		this.consulClient.agentServiceRegister(newService);
	} catch (Exception e) {
		throw new RpcException(
				"Failed to register " + url + " to Consul " + getUrl() + ", cause: " + e.getMessage(), e);
	}
}
 
Example 20
Source Project: dubbox   Source File: ConsulRegistry.java    License: Apache License 2.0 6 votes vote down vote up
private NewService createServiceDef(URL url, long ttl) {
	NewService newService = new NewService();
	newService.setId(toCategoryPath(url));
	newService.setName(url.getServiceInterface());
	newService.setAddress(URL.encode(url.toFullString()));
	newService.setPort(url.getPort());
	String version = makeVersionTag(url);
	newService.setTags(Collections.singletonList(version));
	int ttlInSeconds = (int) ttl / 1000;
	NewService.Check check = new NewService.Check();
	check.setTtl(ttlInSeconds + "s");
	newService.setCheck(check);
	return newService;
}
 
Example 21
/**
 * 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 22
private ConsulRegistration getRegistration(GRpcServerInitializedEvent event) {
    ApplicationContext applicationContext = event.getApplicationContext();


    ConsulDiscoveryProperties consulProperties = applicationContext.getBean(ConsulDiscoveryProperties.class);
    GRpcServerProperties gRpcServerProperties = event.getApplicationContext().getBean(GRpcServerProperties.class);

    NewService grpcService = new NewService();
    grpcService.setPort(event.getServer().getPort());
    if (!consulProperties.isPreferAgentAddress()) {
        grpcService.setAddress(consulProperties.getHostname());
    }
    String appName = "grpc-" + ConsulAutoRegistration.getAppName(consulProperties, applicationContext.getEnvironment());
    grpcService.setName(ConsulAutoRegistration.normalizeForDns(appName));
    grpcService.setId("grpc-" + ConsulAutoRegistration.getInstanceId(consulProperties, applicationContext));
    grpcService.setTags(ConsulAutoRegistration.createTags(consulProperties)
            .stream()
            .filter(t->!t.startsWith("secure="))
            .collect(Collectors.toList())
    );


    if(consulProperties.isRegisterHealthCheck()) {
        GRpcConsulHealthCheck health = GRpcConsulHealthCheck.builder()
                .socketAddr(consulProperties.getHostname() + ":" + event.getServer().getPort())
                .grpcUseTlc(Objects.nonNull(gRpcServerProperties.getSecurity()))
                .interval(consulProperties.getHealthCheckInterval())
                .timeout(consulProperties.getHealthCheckTimeout())
                .build();

        health.setDeregisterCriticalServiceAfter(consulProperties.getHealthCheckCriticalTimeout());

        grpcService.setCheck(health);
    }



    return new ConsulRegistration(grpcService, consulProperties);
}
 
Example 23
Source Project: dyno   Source File: ConsulHostsSupplierTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAwsHosts() throws JSONException {
    List<String> tags = new ArrayList<>();
    tags.add("cloud=aws");
    tags.add("availability-zone=us-east-1b");
    tags.add("datacenter=us-east-1");

    NewService service = new NewService();
    service.setName(APPLICATION_NAME);
    service.setTags(tags);

    consulClient.agentServiceRegister(service);

    NewCheck check = new NewCheck();
    check.setName(APPLICATION_NAME);
    check.setScript("true");
    check.setTtl("1m");
    check.setInterval("30s");

    consulClient.agentCheckRegister(check);

    consulClient.agentCheckPass(APPLICATION_NAME);

    ConsulHostsSupplier hostSupplier = new ConsulHostsSupplier(APPLICATION_NAME, consulClient);

    assertEquals(hostSupplier.getApplicationName(), APPLICATION_NAME);

    List<Host> hosts = hostSupplier.getHosts();

    assertEquals(hosts.size(), 1);

    Host host = hosts.get(0);

    assertEquals(host.getRack(), "us-east-1b");
    assertEquals(host.getDatacenter(), "us-east-1");
    assertEquals(host.getHostName(), "127.0.0.1");
    assertEquals(host.getIpAddress(), "127.0.0.1");
    assertTrue(host.isUp());
}
 
Example 24
Source Project: dyno   Source File: ConsulHostsSupplierTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testOtherCloudProviderHosts() throws JSONException {
    List<String> tags = new ArrayList<>();
    tags.add("cloud=kubernetes");
    tags.add("rack=rack1");
    tags.add("datacenter=dc1");

    NewService service = new NewService();
    service.setName(APPLICATION_NAME);
    service.setTags(tags);

    consulClient.agentServiceRegister(service);

    NewCheck check = new NewCheck();
    check.setName(APPLICATION_NAME);
    check.setScript("true");
    check.setTtl("1m");
    check.setInterval("30s");

    consulClient.agentCheckRegister(check);

    consulClient.agentCheckPass(APPLICATION_NAME);

    ConsulHostsSupplier hostSupplier = new ConsulHostsSupplier(APPLICATION_NAME, consulClient);

    assertEquals(hostSupplier.getApplicationName(), APPLICATION_NAME);

    List<Host> hosts = hostSupplier.getHosts();

    assertEquals(hosts.size(), 1);

    Host host = hosts.get(0);

    assertEquals(host.getRack(), "rack1");
    assertEquals(host.getDatacenter(), "dc1");
    assertEquals(host.getHostName(), "127.0.0.1");
    assertEquals(host.getIpAddress(), "127.0.0.1");
    assertTrue(host.isUp());
}
 
Example 25
Source Project: consul-api   Source File: ConsulClientTest.java    License: Apache License 2.0 6 votes vote down vote up
private void serviceRegisterTest(ConsulClient consulClient) {
    NewService newService = new NewService();
    String serviceName = "abc";
    newService.setName(serviceName);
    consulClient.agentServiceRegister(newService);

    Response<Map<String, Service>> agentServicesResponse = consulClient.getAgentServices();
    Map<String, Service> services = agentServicesResponse.getValue();
    assertThat(services, IsMapContaining.hasKey(serviceName));
}
 
Example 26
@Deprecated
public ConsulAutoRegistration(NewService service,
		AutoServiceRegistrationProperties autoServiceRegistrationProperties,
		ConsulDiscoveryProperties properties, ApplicationContext context,
		HeartbeatProperties heartbeatProperties) {
	this(service, autoServiceRegistrationProperties, properties, context,
			heartbeatProperties, Collections.emptyList());
}
 
Example 27
public ConsulAutoRegistration(NewService service,
		AutoServiceRegistrationProperties autoServiceRegistrationProperties,
		ConsulDiscoveryProperties properties, ApplicationContext context,
		HeartbeatProperties heartbeatProperties,
		List<ConsulManagementRegistrationCustomizer> managementRegistrationCustomizers) {
	super(service, properties);
	this.autoServiceRegistrationProperties = autoServiceRegistrationProperties;
	this.context = context;
	this.heartbeatProperties = heartbeatProperties;
	this.managementRegistrationCustomizers = managementRegistrationCustomizers;
}
 
Example 28
public static NewService.Check createCheck(Integer port,
		HeartbeatProperties ttlConfig, ConsulDiscoveryProperties properties) {
	NewService.Check check = new NewService.Check();
	if (StringUtils.hasText(properties.getHealthCheckCriticalTimeout())) {
		check.setDeregisterCriticalServiceAfter(
				properties.getHealthCheckCriticalTimeout());
	}
	if (ttlConfig.isEnabled()) {
		// FIXME 3.0.0
		// https://github.com/spring-cloud/spring-cloud-consul/issues/614
		check.setTtl(ttlConfig.getTtl().getSeconds() + "s");
		return check;
	}

	Assert.notNull(port, "createCheck port must not be null");
	Assert.isTrue(port > 0, "createCheck port must be greater than 0");

	if (properties.getHealthCheckUrl() != null) {
		check.setHttp(properties.getHealthCheckUrl());
	}
	else {
		check.setHttp(String.format("%s://%s:%s%s", properties.getScheme(),
				properties.getHostname(), port, properties.getHealthCheckPath()));
	}
	check.setHeader(properties.getHealthCheckHeaders());
	check.setInterval(properties.getHealthCheckInterval());
	check.setTimeout(properties.getHealthCheckTimeout());
	check.setTlsSkipVerify(properties.getHealthCheckTlsSkipVerify());
	return check;
}
 
Example 29
@Test
public void contextLoads() {
	NewService service = this.registration.getService();
	assertThat(service).as("service was null").isNotNull();

	NewService.Check check = service.getCheck();
	assertThat(service.getId()).as("id is null").isNotNull();
	assertThat(service.getId()).as("id no include hostname").contains("testhostname");
	assertThat(service.getId()).as("service id was wrong")
			.isEqualTo(this.registration.getInstanceId());

}
 
Example 30
@Test
public void contextLoads() {
	NewService service = this.registration.getService();
	assertThat(service).as("service was null").isNotNull();

	NewService.Check check = service.getCheck();
	assertThat(check).as("check was null").isNotNull();
	assertThat(check.getHeader()).as("header is null").isNotNull();
	assertThat(check.getHeader()).as("header is empty").isNotEmpty();
	assertThat(check.getHeader().get("X-Config-Token").get(0))
			.as("expected header value not found").isEqualTo("ACCESSTOKEN");

	// unable to call consul api to get health check details
}