com.orbitz.consul.model.health.ServiceHealth Java Examples

The following examples show how to use com.orbitz.consul.model.health.ServiceHealth. 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: ConsulServerList.java    From dropwizard-consul with Apache License 2.0 6 votes vote down vote up
/**
 * Build a {@link Server} instance from a Consul {@link ServiceHealth} instance. If the service
 * has an address defined, use that as the server host, otherwise default to using the node
 * address.
 *
 * @param service Consul service health record
 * @return Ribbon Server instance
 */
private Server buildServer(final ServiceHealth service) {
  @Nullable final String scheme = service.getService().getMeta().get("scheme");
  final int port = service.getService().getPort();

  final String address;
  if (!Strings.isNullOrEmpty(service.getService().getAddress())) {
    address = service.getService().getAddress();
  } else {
    address = service.getNode().getAddress();
  }

  final Server server = new Server(scheme, address, port);
  server.setZone(service.getNode().getDatacenter().orElse(Server.UNKNOWN_ZONE));
  server.setReadyToServe(true);

  return server;
}
 
Example #2
Source File: ServiceCacheListener.java    From thorntail with Apache License 2.0 6 votes vote down vote up
@Override
public void notify(Map<ServiceHealthKey, ServiceHealth> newValues) {
    Set<Registration> previousEntries = topologyManager.registrationsForService(this.name);

    Set<Registration> newEntries = newValues.values().stream()
            .map(e -> new Registration("consul",
                                       this.name,
                                       e.getService().getAddress(),
                                       e.getService().getPort())
                    .addTags(e.getService().getTags())
            )
            .collect(Collectors.toSet());

    previousEntries.stream()
            .filter(e -> !newEntries.contains(e))
            .forEach(e -> {
                this.topologyManager.unregister(e);
            });

    newEntries.stream()
            .filter(e -> !previousEntries.contains(e))
            .forEach(e -> {
                this.topologyManager.register(e);
            });
}
 
Example #3
Source File: PropertyConfig.java    From kafka-topic-exporter with Apache License 2.0 6 votes vote down vote up
ArrayList<String> getBootStrapServersFromConsul(String consulServer, String consulKafkaServicename) {
    ArrayList<String> bootstrapServers = null;
    LOG.info("CONSUL: Consul server used: [" + consulServer + "]");
    LOG.info("CONSUL: Consul service retrieved: [" + consulKafkaServicename + "]");
    try {
        Consul consul = Consul.builder().withUrl(consulServer).build();
        HealthClient healthClient = consul.healthClient();

        // discover only "passing" nodes
        List<ServiceHealth> nodes = healthClient.getHealthyServiceInstances(consulKafkaServicename).getResponse();
        for (ServiceHealth kafkaNode : nodes) {
            String address = kafkaNode.getService().getAddress();
            String port = kafkaNode.getService().getPort() + "";
            if (bootstrapServers == null) {
                bootstrapServers = new ArrayList<String>();
            }
            bootstrapServers.add(address + ":" + port);
        }
    } catch (Exception e){
        LOG.error("CONSUL: " + e.toString());
    }
    LOG.info("CONSUL: Kafka services found through Consul server: " + (bootstrapServers==null?"None available":bootstrapServers.toString()));
    return bootstrapServers;
}
 
Example #4
Source File: ServiceCacheListener.java    From ARCHIVE-wildfly-swarm with Apache License 2.0 6 votes vote down vote up
@Override
public void notify(Map<HostAndPort, ServiceHealth> newValues) {
    Set<Registration> previousEntries = topologyManager.registrationsForService(this.name);

    Set<Registration> newEntries = newValues.values().stream()
            .map(e -> new Registration("consul",
                    this.name,
                    e.getService().getAddress(),
                    e.getService().getPort())
                    .addTags(e.getService().getTags())
            )
            .collect(Collectors.toSet());

    previousEntries.stream()
            .filter(e -> !newEntries.contains(e))
            .forEach(e -> {
                this.topologyManager.unregister(e);
            });

    newEntries.stream()
            .filter(e -> !previousEntries.contains(e))
            .forEach(e -> {
                this.topologyManager.register(e);
            });
}
 
Example #5
Source File: ConsulCoordinator.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@Override
public List<RemoteInstance> queryRemoteNodes() {
    HealthClient healthClient = client.healthClient();

    // Discover only "passing" nodes
    List<ServiceHealth> nodes = healthClient.getHealthyServiceInstances(serviceName).getResponse();

    List<RemoteInstance> remoteInstances = new ArrayList<>();
    if (CollectionUtils.isNotEmpty(nodes)) {
        nodes.forEach(node -> {
            if (!Strings.isNullOrEmpty(node.getService().getAddress())) {
                Address address = new Address(node.getService().getAddress(), node.getService().getPort(), false);
                if (address.equals(selfAddress)) {
                    address.setSelf(true);
                }
                remoteInstances.add(new RemoteInstance(address));
            }
        });
    }
    return remoteInstances;
}
 
Example #6
Source File: ConsulDiscoveryConfigSource.java    From pragmatic-microservices-lab with MIT License 5 votes vote down vote up
@Override
public String getValue(String propertyName) {
    if (propertyName.startsWith(CONFIG_DISCOVERY_SERVICE_PREFIX)) {
        Consul consul = ConsulClient.build();
        String[] serviceNameAndProp = propertyName.split("\\.");
        if (serviceNameAndProp.length == 4) {
            String serviceName = serviceNameAndProp[2];
            String serviceProp = serviceNameAndProp[3];
            if (serviceProp.equals("url")) {
                // propertyName is "discovery.service.NAME.url"
                // result is a url that doesn't end with / and optionally includes context root
                List<ServiceHealth> services = consul.healthClient()
                        .getHealthyServiceInstances(serviceName).getResponse();
                if (!services.isEmpty()) {
                    int randomIndex = new Random().nextInt(services.size());
                    Service selectedService = services.get(randomIndex).getService();
                    String contextRoot = selectedService.getMeta().getOrDefault(ConsulClient.KEY_CTX_ROOT, "");
                    if ( !contextRoot.isEmpty() && !contextRoot.startsWith("/")) {
                        contextRoot = "/" + contextRoot;
                    }
                    StringBuilder resultBuilder = new StringBuilder();
                    resultBuilder = resultBuilder.append("http://").append(selectedService.getAddress())
                            .append(":").append(selectedService.getPort())
                            .append(contextRoot);
                    return resultBuilder.toString();
                }
            }
        }
    }
    return null;
}
 
Example #7
Source File: ConsulDiscoveryService.java    From jim-framework with Apache License 2.0 5 votes vote down vote up
@Override
public List<RpcURL> getUrls(String registryHost,int registryPort) {
    List<RpcURL> urls= Lists.newArrayList();
    Consul consul = this.buildConsul(registryHost,registryPort);
    HealthClient client = consul.healthClient();
    String name = CONSUL_NAME;
    ConsulResponse object= client.getAllServiceInstances(name);
    List<ImmutableServiceHealth> serviceHealths=(List<ImmutableServiceHealth>)object.getResponse();
    for(ImmutableServiceHealth serviceHealth:serviceHealths){
        RpcURL url=new RpcURL();
        url.setHost(serviceHealth.getService().getAddress());
        url.setPort(serviceHealth.getService().getPort());
        urls.add(url);
    }

    try {
        ServiceHealthCache serviceHealthCache = ServiceHealthCache.newCache(client, name);
        serviceHealthCache.addListener(new ConsulCache.Listener<ServiceHealthKey, ServiceHealth>() {
            @Override
            public void notify(Map<ServiceHealthKey, ServiceHealth> map) {
                logger.info("serviceHealthCache.addListener notify");
                RpcClientInvokerCache.clear();

            }
        });
        serviceHealthCache.start();
    } catch (Exception e) {
        logger.info("serviceHealthCache.start error:",e);
    }
    return urls;
}
 
Example #8
Source File: ConsulCoordinatorTest.java    From skywalking with Apache License 2.0 5 votes vote down vote up
private ServiceHealth mockSelfService() {
    ServiceHealth serviceHealth = mock(ServiceHealth.class);
    Service service = mock(Service.class);

    when(service.getAddress()).thenReturn(selfRemoteAddress.getHost());
    when(service.getPort()).thenReturn(selfRemoteAddress.getPort());

    when(serviceHealth.getService()).thenReturn(service);

    return serviceHealth;
}
 
Example #9
Source File: ConsulCoordinatorTest.java    From skywalking with Apache License 2.0 5 votes vote down vote up
private ServiceHealth mockNotSelfService() {
    ServiceHealth serviceHealth = mock(ServiceHealth.class);
    Service service = mock(Service.class);

    when(service.getAddress()).thenReturn(remoteAddress.getHost());
    when(service.getPort()).thenReturn(remoteAddress.getPort());

    when(serviceHealth.getService()).thenReturn(service);

    return serviceHealth;
}
 
Example #10
Source File: ConsulCoordinatorTest.java    From skywalking with Apache License 2.0 5 votes vote down vote up
private List<ServiceHealth> mockHealth() {
    List<ServiceHealth> result = new LinkedList<>();
    result.add(mockSelfService());
    result.add(mockNotSelfService());
    result.add(mockNullServiceAddress());
    return result;
}
 
Example #11
Source File: ConsulCoordinatorTest.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Test
public void queryRemoteNodesWithNullSelf() {
    List<ServiceHealth> serviceHealths = mockHealth();
    when(consulResponse.getResponse()).thenReturn(serviceHealths);
    List<RemoteInstance> remoteInstances = coordinator.queryRemoteNodes();
    // filter empty address
    assertEquals(2, remoteInstances.size());
}
 
Example #12
Source File: ConsulCoordinatorTest.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Test
public void queryRemoteNodes() {
    registerSelfRemote();
    List<ServiceHealth> serviceHealths = mockHealth();
    when(consulResponse.getResponse()).thenReturn(serviceHealths);
    List<RemoteInstance> remoteInstances = coordinator.queryRemoteNodes();
    assertEquals(2, remoteInstances.size());

    RemoteInstance selfInstance = remoteInstances.get(0);
    velidate(selfRemoteAddress, selfInstance);

    RemoteInstance notSelfInstance = remoteInstances.get(1);
    velidate(remoteAddress, notSelfInstance);
}
 
Example #13
Source File: ConsulTests.java    From nano-framework with Apache License 2.0 4 votes vote down vote up
@Test
public void findAvailableServicesTest() {
    injects();
    final List<ServiceHealth> nodes = healthClient.getHealthyServiceInstances("DataService").getResponse();
    Assert.assertTrue(CollectionUtils.isEmpty(nodes));
}
 
Example #14
Source File: ConsulDiscoveryStrategy.java    From hazelcast-consul-discovery-spi with Apache License 2.0 4 votes vote down vote up
@Override
public Iterable<DiscoveryNode> discoverNodes() {
	
	List<DiscoveryNode> toReturn = new ArrayList<DiscoveryNode>();
	
	try {
		// discover healthy nodes only? (and its NOT the first invocation...)
		if (this.consulHealthyOnly && discoverNodesInvoked) {
			
			List<ServiceHealth> nodes = consulHealthClient.getHealthyServiceInstances(consulServiceName, ConsulUtility.getAclToken(this.consulAclToken)).getResponse();
			
			for (ServiceHealth node : nodes) {
				toReturn.add(new SimpleDiscoveryNode(
								new Address(node.getService().getAddress(),node.getService().getPort())));
				getLogger().info("Discovered healthy node: " + node.getService().getAddress()+":"+node.getService().getPort());
			}
			
		// discover all services, regardless of health or this is the first invocation
		} else {
			
			ConsulResponse<List<CatalogService>> response = this.consulCatalogClient.getService(consulServiceName, ConsulUtility.getAclToken(this.consulAclToken));
			
			for (CatalogService service : response.getResponse()) {
				
				String discoveredAddress = null;
				String rawServiceAddress = service.getServiceAddress();
				String rawAddress = service.getAddress();
				
				if (rawServiceAddress != null && !rawServiceAddress.trim().isEmpty()) {
				    discoveredAddress = rawServiceAddress;
					
				} else if (rawAddress != null && !rawAddress.trim().isEmpty()) {
				    getLogger().warning("discoverNodes() ServiceAddress was null/blank! " +
						     "for service: " + service.getServiceName() + 
						     " falling back to Address value");
				    discoveredAddress = rawAddress;
					
				} else {
				    getLogger().warning("discoverNodes() could not discover an address, " +
						     "both ServiceAddress and Address were null/blank! " +
						     "for service: " + service.getServiceName());
				}
				
				toReturn.add(new SimpleDiscoveryNode(
						new Address(discoveredAddress, service.getServicePort())));
				getLogger().info("Discovered healthy node: " + discoveredAddress+":"+service.getServicePort());
			}
		}
		
	} catch(Exception e) {
		getLogger().severe("discoverNodes() unexpected error: " + e.getMessage(),e);
	}

	// flag we were invoked
	discoverNodesInvoked = true;
	
	return toReturn;
}
 
Example #15
Source File: HealthyConsulServiceDiscoverer.java    From dropwizard-consul with Apache License 2.0 4 votes vote down vote up
@Override
public Collection<ServiceHealth> discover(final Consul consul) {
  return consul.healthClient().getHealthyServiceInstances(service).getResponse();
}
 
Example #16
Source File: HelloWorldResource.java    From dropwizard-consul with Apache License 2.0 4 votes vote down vote up
@GET
@Timed
@Path("/consul/{service}")
public List<ServiceHealth> getHealthyServiceInstances(@PathParam("service") String service) {
  return consul.healthClient().getHealthyServiceInstances(service).getResponse();
}
 
Example #17
Source File: ConsulCoordinatorTest.java    From skywalking with Apache License 2.0 3 votes vote down vote up
private ServiceHealth mockNullServiceAddress() {
    ServiceHealth serviceHealth = mock(ServiceHealth.class);
    Service service = mock(Service.class);

    when(serviceHealth.getService()).thenReturn(service);

    when(service.getAddress()).thenReturn("");

    return serviceHealth;
}
 
Example #18
Source File: ConsulServerList.java    From dropwizard-consul with Apache License 2.0 2 votes vote down vote up
/**
 * Converts a list of {@link ServiceHealth} objects into {@link Server} objects
 *
 * @param services list of healthy service instances
 * @return list of server instances
 */
private List<Server> buildServerList(final Collection<ServiceHealth> services) {
  return services.stream().map(this::buildServer).collect(Collectors.toList());
}
 
Example #19
Source File: ConsulServiceDiscoverer.java    From dropwizard-consul with Apache License 2.0 votes vote down vote up
Collection<ServiceHealth> discover(Consul consul);