com.orbitz.consul.model.agent.Registration Java Examples

The following examples show how to use com.orbitz.consul.model.agent.Registration. 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: ServiceAdvertizer.java    From pragmatic-microservices-lab with MIT License 6 votes vote down vote up
public void advertize(ServiceAdvertisement advertisement, ScheduledExecutorService scheduler) {
	Config config = ConfigProvider.getConfig();
	String serviceAddress = getAddressFromAdvert(advertisement, config);
	Integer servicePort = getPortFromAdvert(advertisement, config);
	Registration service = ImmutableRegistration.builder().id(idFromAdvert(advertisement))
			.name(advertisement.getName()).address(serviceAddress).port(servicePort)
			.check(Registration.RegCheck.ttl(3L)) // registers with a TTL of 3 seconds
			.meta(Collections.singletonMap(ConsulClient.KEY_CTX_ROOT, advertisement.getContextRoot())).build();
	try {
		ConsulClient.build().agentClient().register(service);
	} catch (RuntimeException e) {
		Logger.getLogger(this.getClass().getName()).log(Level.WARNING, "Is consul running?", e);
	}
	// keep refreshing the status within the TTL
	scheduler.scheduleAtFixedRate(() -> refreshAdvertisement(advertisement), 2, 2, TimeUnit.SECONDS);
}
 
Example #2
Source File: TcpHealthCheckBuilder.java    From hazelcast-consul-discovery-spi with Apache License 2.0 6 votes vote down vote up
@Override
public RegCheck buildRegistrationCheck(Map<String, Object> registratorConfig, Address localAddress) {
	
	RegCheck regCheck = null;
	
	try {
		/**
		 * Deal with health check tcp
		 */
		String healthCheckTcp = (String)registratorConfig.get(CONFIG_PROP_HEALTH_CHECK_TCP);
		
		if (healthCheckTcp != null && !healthCheckTcp.trim().isEmpty()) {
			
			healthCheckTcp = healthCheckTcp.replaceAll(TCP_TEMPLATE_MYIP, localAddress.getInetAddress().getHostAddress())
					  						 .replaceAll(TCP_TEMPLATE_MYPORT, String.valueOf(localAddress.getPort()));
			
			Long healthCheckTcpIntervalSeconds = Long.valueOf((Integer)registratorConfig.get(CONFIG_PROP_HEALTH_CHECK_TCP_INTERVAL_SECONDS));
			regCheck = Registration.RegCheck.tcp(healthCheckTcp, healthCheckTcpIntervalSeconds);
		}
		
	} catch(Exception e) {
		logger.severe("Unexpected error occured trying to build TCP health check : " + e.getMessage(), e);
	}
	
	return regCheck;
}
 
Example #3
Source File: ConsulCoordinator.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@Override
public void registerRemote(RemoteInstance remoteInstance) throws ServiceRegisterException {
    if (needUsingInternalAddr()) {
        remoteInstance = new RemoteInstance(new Address(config.getInternalComHost(), config.getInternalComPort(), true));
    }

    AgentClient agentClient = client.agentClient();

    this.selfAddress = remoteInstance.getAddress();
    TelemetryRelatedContext.INSTANCE.setId(selfAddress.toString());

    Registration registration = ImmutableRegistration.builder()
                                                     .id(remoteInstance.getAddress().toString())
                                                     .name(serviceName)
                                                     .address(remoteInstance.getAddress().getHost())
                                                     .port(remoteInstance.getAddress().getPort())
                                                     .check(Registration.RegCheck.grpc(remoteInstance.getAddress()
                                                                                                     .getHost() + ":" + remoteInstance
                                                         .getAddress()
                                                         .getPort(), 5)) // registers with a TTL of 5 seconds
                                                     .build();

    agentClient.register(registration);
}
 
Example #4
Source File: HttpHealthCheckBuilder.java    From hazelcast-consul-discovery-spi with Apache License 2.0 5 votes vote down vote up
@Override
public RegCheck buildRegistrationCheck( Map<String, Object> registratorConfig, Address localAddress) {
	
	RegCheck regCheck = null;
	
	try{
		/**
		 * Deal with health check http
		 */
		String healthCheckHttp = (String)registratorConfig.get(CONFIG_PROP_HEALTH_CHECK_HTTP);
		
		if (healthCheckHttp != null && !healthCheckHttp.trim().isEmpty()) {
			
			healthCheckHttp = healthCheckHttp.replaceAll(HTTP_TEMPLATE_MYIP, localAddress.getInetAddress().getHostAddress())
					  						 .replaceAll(HTTP_TEMPLATE_MYPORT, String.valueOf(localAddress.getPort()));
			
			Long healthCheckHttpIntervalSeconds = Long.valueOf((Integer)registratorConfig.get(CONFIG_PROP_HEALTH_CHECK_HTTP_INTERVAL_SECONDS));
			regCheck = Registration.RegCheck.http(healthCheckHttp, healthCheckHttpIntervalSeconds);
		}
	
	}catch(Exception e){
		logger.severe("Unexpected error occured trying to build HTTP health check : " + e.getMessage(), e);

	}
	
	return regCheck;
}
 
Example #5
Source File: DiscoveryAgentActor.java    From docker-nginx-consul with MIT License 5 votes vote down vote up
public DiscoveryAgentActor(AppConfiguration configuration){
  this.configuration = configuration;
  this.SCHEDULED_WORK_DELAY =  new FiniteDuration(configuration.serviceDiscoveryConfiguration.healthCheckTimeout, TimeUnit.SECONDS);

  // todo: terminate system if error occur while connecting to consul
  // get consul connection
  this.consul = Consul
      .builder()
      .withHostAndPort(
          HostAndPort.fromParts(
              configuration.serviceDiscoveryConfiguration.host,
              configuration.serviceDiscoveryConfiguration.port)
      )
      .build();

  // get agent
  agentClient = consul.agentClient();
  // set registration config
  Registration service = ImmutableRegistration.builder()
      .id(configuration.appId)
      .name(configuration.serviceName)
      .port(configuration.port)
      .address(configuration.host)
      .check(Registration.RegCheck.ttl(configuration.serviceDiscoveryConfiguration.healthCheckTimeout))
      .tags(Collections.singletonList("tag1"))
      .meta(Collections.singletonMap("version", "1.0"))
      .build();

  // register service
  agentClient.register(service);
  // check in with Consul, serviceId required only.  client will prepend "service:" for service level checks.
  // Note that you need to continually check in before the TTL expires, otherwise your service's state will be marked as "critical".
}
 
Example #6
Source File: ConsulCoordinatorTest.java    From skywalking with Apache License 2.0 5 votes vote down vote up
private void verifyRegistration(Address remoteAddress, Registration registration) {
    assertNotNull(registration);
    assertEquals(SERVICE_NAME, registration.getName());
    assertEquals(remoteAddress.getHost() + "_" + remoteAddress.getPort(), registration.getId());
    assertTrue(registration.getAddress().isPresent());
    assertEquals(remoteAddress.getHost(), registration.getAddress().get());
    assertTrue(registration.getPort().isPresent());
    assertEquals(remoteAddress.getPort(), registration.getPort().get().intValue());
    assertTrue(registration.getCheck().isPresent());
    Registration.RegCheck regCheck = registration.getCheck().get();
    assertTrue(regCheck.getGrpc().isPresent());
    assertEquals(remoteAddress.getHost() + ":" + remoteAddress.getPort(), regCheck.getGrpc().get());
}
 
Example #7
Source File: ITClusterModuleConsulProviderFunctionalTest.java    From skywalking with Apache License 2.0 4 votes vote down vote up
private ClusterModuleConsulProvider createProvider(String serviceName, String internalComHost,
    int internalComPort) throws Exception {
    ClusterModuleConsulProvider provider = new ClusterModuleConsulProvider();

    ClusterModuleConsulConfig config = (ClusterModuleConsulConfig) provider.createConfigBeanIfAbsent();

    config.setHostPort(consulAddress);
    config.setServiceName(serviceName);

    if (!StringUtil.isEmpty(internalComHost)) {
        config.setInternalComHost(internalComHost);
    }

    if (internalComPort > 0) {
        config.setInternalComPort(internalComPort);
    }

    provider.prepare();
    provider.start();
    provider.notifyAfterCompleted();

    ConsulCoordinator consulCoordinator = (ConsulCoordinator) provider.getService(ClusterRegister.class);

    // ignore health check
    ClusterRegister register = remoteInstance -> {
        if (needUsingInternalAddr(config)) {
            remoteInstance = new RemoteInstance(new Address(config.getInternalComHost(), config.getInternalComPort(), true));
        }

        Consul client = Whitebox.getInternalState(consulCoordinator, "client");
        AgentClient agentClient = client.agentClient();
        Whitebox.setInternalState(consulCoordinator, "selfAddress", remoteInstance.getAddress());
        TelemetryRelatedContext.INSTANCE.setId(remoteInstance.getAddress().toString());
        Registration registration = ImmutableRegistration.builder()
                                                         .id(remoteInstance.getAddress().toString())
                                                         .name(serviceName)
                                                         .address(remoteInstance.getAddress().getHost())
                                                         .port(remoteInstance.getAddress().getPort())
                                                         .build();

        agentClient.register(registration);
    };

    provider.registerServiceImplementation(ClusterRegister.class, register);
    return provider;
}
 
Example #8
Source File: ConsulCoordinatorTest.java    From skywalking with Apache License 2.0 4 votes vote down vote up
private void registerRemote(Address address) {
    coordinator.registerRemote(new RemoteInstance(address));
    Registration registration = afterRegister();
    verifyRegistration(address, registration);
}
 
Example #9
Source File: ConsulCoordinatorTest.java    From skywalking with Apache License 2.0 4 votes vote down vote up
private Registration afterRegister() {
    ArgumentCaptor<Registration> argumentCaptor = ArgumentCaptor.forClass(Registration.class);
    verify(agentClient).register(argumentCaptor.capture());
    return argumentCaptor.getValue();
}
 
Example #10
Source File: ConsulIntegrationTest.java    From wildfly-camel with Apache License 2.0 4 votes vote down vote up
@Test
public void testServiceDiscovery() throws Exception {
    final AgentClient client = getConsul().agentClient();
    try {
        registrations = new ArrayList<>(3);

        for (int i = 0; i < 3; i++) {
            Registration r = ImmutableRegistration.builder()
                .id("service-" + i)
                .name("my-service")
                .address("127.0.0.1")
                .addTags("a-tag")
                .addTags("key1=value1")
                .addTags("key2=value2")
                .port(9000 + i)
                .build();

            client.register(r);
            registrations.add(r);
        }

        ConsulConfiguration configuration = new ConsulConfiguration();
        configuration.setUrl(consulUrl);
        ServiceDiscovery discovery = new ConsulServiceDiscovery(configuration);

        List<ServiceDefinition> services = discovery.getServices("my-service");
        assertNotNull(services);
        assertEquals(3, services.size());

        for (ServiceDefinition service : services) {
            assertFalse(service.getMetadata().isEmpty());
            assertTrue(service.getMetadata().containsKey("service.name"));
            assertTrue(service.getMetadata().containsKey("service.id"));
            assertTrue(service.getMetadata().containsKey("service.node"));
            assertTrue(service.getMetadata().containsKey("a-tag"));
            assertTrue(service.getMetadata().containsKey("key1"));
            assertTrue(service.getMetadata().containsKey("key2"));
        }
    } finally {
        if (registrations != null && client != null) {
            registrations.forEach(r -> client.deregister(r.getId()));
        }
    }
}
 
Example #11
Source File: ScriptHealthCheckBuilder.java    From hazelcast-consul-discovery-spi with Apache License 2.0 3 votes vote down vote up
@Override
public RegCheck buildRegistrationCheck(Map<String, Object> registratorConfig, Address localAddress) {
	
	RegCheck regCheck = null;
	
	try{
		/**
		 * Deal with health check script
		 */
		String rawScript = (String)registratorConfig.get(CONFIG_PROP_HEALTH_CHECK_SCRIPT);
		
		if (rawScript != null && !rawScript.trim().isEmpty()) {
			
			Long healthCheckScriptIntervalSeconds = Long.valueOf((Integer)registratorConfig.get(CONFIG_PROP_HEALTH_CHECK_SCRIPT_INTERVAL_SECONDS));
			String healthCheckScript = rawScript.replaceAll(HEALTH_SCRIPT_TEMPLATE_MYIP, localAddress.getInetAddress().getHostAddress())
											    .replaceAll(HEALTH_SCRIPT_TEMPLATE_MYPORT, String.valueOf(localAddress.getPort()));
		
			regCheck = Registration.RegCheck.args(Arrays.asList(healthCheckScript.split(" ")), healthCheckScriptIntervalSeconds);
		}
	
	}catch(Exception e){
		logger.severe("Unexpected error occured trying to build HTTP health check : " + e.getMessage(), e);
	}
	
	return regCheck;
	
	
	
}