com.netflix.runtime.health.api.HealthCheckStatus Java Examples

The following examples show how to use com.netflix.runtime.health.api.HealthCheckStatus. 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: HealthLocalMasterReadinessResolverTest.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    when(healthcheck.check()).thenAnswer(invocation -> {
        CompletableFuture<HealthCheckStatus> future = new CompletableFuture<>();
        if (simulatedError != null) {
            future.completeExceptionally(new RuntimeException("simulated error"));
        } else if (currentHealthStatus != null) {
            future.complete(currentHealthStatus);
        } // else never complete
        invocationCounter++;
        return future;
    });

    this.resolver = new HealthLocalMasterReadinessResolver(
            healthcheck,
            REFRESH_SCHEDULER_DESCRIPTOR.toBuilder()
                    .withInterval(Duration.ofMillis(1))
                    .withTimeout(Duration.ofMillis(1))
                    .build(),
            titusRuntime,
            Schedulers.parallel()
    );
}
 
Example #2
Source File: SimpleHealthCheckAggregator.java    From runtime-health with Apache License 2.0 6 votes vote down vote up
protected HealthCheckStatus getStatusFromCallbacks(final List<HealthIndicatorCallbackImpl> callbacks) {
    List<Health> healths = new ArrayList<>();
    List<Health> suppressedHealths = new ArrayList<>();  
    boolean isHealthy = callbacks.stream()
	    .map(callback -> {
	    	Health health = Health.from(callback.getHealthOrTimeout())
	    			.withDetail(Health.NAME_KEY, callback.getIndicator().getName()).build();
	    	if(callback.isSuppressed()) {
	    	    suppressedHealths.add(health);
	    	    return Health.healthy().build();
	    	} else {
	    	    healths.add(health);
	    	    return health;
	    	}
	    })
	    .map(health -> health.isHealthy())
	    .reduce(true, (a,b) -> a && b); 
    return HealthCheckStatus.create(isHealthy, healths, suppressedHealths);
}
 
Example #3
Source File: HealthStatusServlet.java    From runtime-health with Apache License 2.0 6 votes vote down vote up
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws IOException, ServletException {
    HealthCheckStatus health;
    try {
        if(matcher != null ) {
            health = this.healthCheckAggregator.check(matcher).get();
        } else {
            health = this.healthCheckAggregator.check().get();
        }
    } catch (Exception e) {
        throw new ServletException(e);
    }
    
    if(health.isHealthy()) {
        resp.setStatus(200);
    }
    else {
        resp.setStatus(500);
    }
    String content = health.toString();
    resp.setContentLength(content.length());
    resp.setContentType("text/plain");
    resp.getWriter().print(content);
}
 
Example #4
Source File: HealthModuleTest.java    From runtime-health with Apache License 2.0 6 votes vote down vote up
@Test
public void testMultipleInstancesOfHealthModuleInstalled() throws InterruptedException, ExecutionException {
    LifecycleInjector injector = InjectorBuilder.fromModules(new HealthModule() {
        @Override
        protected void configureHealth() {
            bindAdditionalHealthIndicator().toInstance(healthy);
        }
    }, new HealthModule() {
        @Override
        protected void configureHealth() {
            bindAdditionalHealthIndicator().toInstance(unhealthy);
        }
    }, new ArchaiusModule()).createInjector();
    HealthCheckAggregator aggregator = injector.getInstance(HealthCheckAggregator.class);
    assertNotNull(aggregator);
    HealthCheckStatus healthCheckStatus = aggregator.check().get();
    assertFalse(healthCheckStatus.isHealthy());
    assertEquals(2, healthCheckStatus.getHealthResults().size());
}
 
Example #5
Source File: HealthServiceImplTest.java    From conductor with Apache License 2.0 6 votes vote down vote up
@Test
public void healthException() throws Exception {
    // Generate a unique in-process server name.
    String serverName = InProcessServerBuilder.generateName();
    HealthCheckAggregator hca = mock(HealthCheckAggregator.class);
    CompletableFuture<HealthCheckStatus> hcsf = mock(CompletableFuture.class);
    when(hcsf.get()).thenThrow(InterruptedException.class);
    when(hca.check()).thenReturn(hcsf);
    HealthServiceImpl healthyService = new HealthServiceImpl(hca);

    addService(serverName, healthyService);
    HealthGrpc.HealthBlockingStub blockingStub = HealthGrpc.newBlockingStub(
            // Create a client channel and register for automatic graceful shutdown.
            grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()));

    thrown.expect(StatusRuntimeException.class);
    thrown.expect(hasProperty("status", is(Status.INTERNAL)));
    blockingStub.check(HealthCheckRequest.newBuilder().build());

}
 
Example #6
Source File: HealthServiceImplTest.java    From conductor with Apache License 2.0 6 votes vote down vote up
@Test
public void healthNotServing() throws Exception {
    // Generate a unique in-process server name.
    String serverName = InProcessServerBuilder.generateName();
    HealthCheckAggregator hca = mock(HealthCheckAggregator.class);
    CompletableFuture<HealthCheckStatus> hcsf = mock(CompletableFuture.class);
    HealthCheckStatus hcs = mock(HealthCheckStatus.class);
    when(hcs.isHealthy()).thenReturn(false);
    when(hcsf.get()).thenReturn(hcs);
    when(hca.check()).thenReturn(hcsf);
    HealthServiceImpl healthyService = new HealthServiceImpl(hca);

    addService(serverName, healthyService);
    HealthGrpc.HealthBlockingStub blockingStub = HealthGrpc.newBlockingStub(
            // Create a client channel and register for automatic graceful shutdown.
            grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()));


    HealthCheckResponse reply = blockingStub.check(HealthCheckRequest.newBuilder().build());

    assertEquals(HealthCheckResponse.ServingStatus.NOT_SERVING, reply.getStatus());
}
 
Example #7
Source File: HealthServiceImplTest.java    From conductor with Apache License 2.0 6 votes vote down vote up
@Test
public void healthServing() throws Exception {
    // Generate a unique in-process server name.
    String serverName = InProcessServerBuilder.generateName();
    HealthCheckAggregator hca = mock(HealthCheckAggregator.class);
    CompletableFuture<HealthCheckStatus> hcsf = mock(CompletableFuture.class);
    HealthCheckStatus hcs = mock(HealthCheckStatus.class);
    when(hcs.isHealthy()).thenReturn(true);
    when(hcsf.get()).thenReturn(hcs);
    when(hca.check()).thenReturn(hcsf);
    HealthServiceImpl healthyService = new HealthServiceImpl(hca);

    addService(serverName, healthyService);
    HealthGrpc.HealthBlockingStub blockingStub = HealthGrpc.newBlockingStub(
            // Create a client channel and register for automatic graceful shutdown.
            grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()));


    HealthCheckResponse reply = blockingStub.check(HealthCheckRequest.newBuilder().build());

    assertEquals(HealthCheckResponse.ServingStatus.SERVING, reply.getStatus());
}
 
Example #8
Source File: HealthCheckResource.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
@GET
public Response doCheck() throws Exception {
    HealthCheckStatus healthCheckStatus = healthCheck.check().get(2, TimeUnit.SECONDS);
    if (healthCheckStatus.isHealthy()) {
        return Response.ok(healthCheckStatus).build();
    } else {
        return Response.serverError().entity(healthCheckStatus).build();
    }
}
 
Example #9
Source File: SimpleHealthCheckAggregatorEventsTest.java    From runtime-health with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 1000)
public void testChangingHealthSendsFirstEventWhenNoListeners() throws Exception {
    SimpleHealthCheckAggregator aggregator = new SimpleHealthCheckAggregator(Collections.emptyList(), 100, TimeUnit.SECONDS,dispatcher);
    HealthCheckStatus aggregatedHealth = aggregator.check().get();
    assertTrue(aggregatedHealth.isHealthy());
    assertEquals(0, aggregatedHealth.getHealthResults().size());
    Thread.sleep(10);
    Mockito.verify(dispatcher, Mockito.times(1)).publishEvent(Mockito.any());
}
 
Example #10
Source File: SimpleHealthCheckAggregatorTest.java    From runtime-health with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 1000)
public void testIncludeFilterIncludesAndExcludes() throws Exception {
    aggregator = new SimpleHealthCheckAggregator(Arrays.asList(healthy, unhealthy, nonResponsive), 10, TimeUnit.MILLISECONDS);

    HealthCheckStatus aggregatedHealth = aggregator
            .check(IndicatorMatchers
                    .includes(healthy.getName(), unhealthy.getName())
                    .excludes(unhealthy.getName())
                    .build()).get();
    assertTrue(aggregatedHealth.isHealthy());
    assertEquals(1, aggregatedHealth.getHealthResults().size());
    assertEquals(2, aggregatedHealth.getSuppressedHealthResults().size());
    assertThat(aggregatedHealth.getHealthResults()).extracting(h -> h.getDetails().get("className")).isNotNull();
}
 
Example #11
Source File: SimpleHealthCheckAggregatorTest.java    From runtime-health with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 1000)
public void testIncludeFilterIncludes() throws Exception {
    aggregator = new SimpleHealthCheckAggregator(Arrays.asList(healthy, unhealthy, nonResponsive), 10, TimeUnit.MILLISECONDS);

    HealthCheckStatus aggregatedHealth = aggregator
            .check(IndicatorMatchers.includes(healthy.getName()).build()).get();
    assertTrue(aggregatedHealth.isHealthy());
    assertEquals(1, aggregatedHealth.getHealthResults().size());
    assertEquals(2, aggregatedHealth.getSuppressedHealthResults().size());
    assertThat(aggregatedHealth.getHealthResults()).extracting(h -> h.getDetails().get("className")).isNotNull();
}
 
Example #12
Source File: SimpleHealthCheckAggregatorTest.java    From runtime-health with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 1000)
public void testIncludeFilterExcludes() throws Exception {
    aggregator = new SimpleHealthCheckAggregator(Arrays.asList(healthy, unhealthy), 10, TimeUnit.MILLISECONDS);

    HealthCheckStatus aggregatedHealth = aggregator
            .check(IndicatorMatchers.excludes(unhealthy.getName()).build()).get();
    assertTrue(aggregatedHealth.isHealthy());
    assertEquals(1, aggregatedHealth.getHealthResults().size());
    assertEquals(1, aggregatedHealth.getSuppressedHealthResults().size());
    assertThat(aggregatedHealth.getHealthResults()).extracting(h -> h.getDetails().get("className")).isNotNull();
}
 
Example #13
Source File: SimpleHealthCheckAggregatorTest.java    From runtime-health with Apache License 2.0 5 votes vote down vote up
@Test(timeout=1000)
public void testClassNameAdded() throws Exception {
	aggregator = new SimpleHealthCheckAggregator(Arrays.asList(healthy,unhealthy,nonResponsive), 10, TimeUnit.MILLISECONDS);
	HealthCheckStatus aggregatedHealth = aggregator.check().get();
	assertFalse(aggregatedHealth.isHealthy());
	assertEquals(3, aggregatedHealth.getHealthResults().size());
	assertEquals(0, aggregatedHealth.getSuppressedHealthResults().size());
	assertThat(aggregatedHealth.getHealthResults()).extracting(h->h.getDetails().get("className")).isNotNull();
}
 
Example #14
Source File: SimpleHealthCheckAggregatorTest.java    From runtime-health with Apache License 2.0 5 votes vote down vote up
@Test(timeout=1000)
public void testWithDetails() throws Exception {
	aggregator = new SimpleHealthCheckAggregator(Arrays.asList( 
			(callback)->callback.inform(Health.healthy().withDetail("foo", "bar").build()),
			(callback)->callback.inform(Health.unhealthy(new RuntimeException("Boom")).build())), 1, TimeUnit.SECONDS);
	HealthCheckStatus aggregatedHealth = aggregator.check().get();
	assertFalse(aggregatedHealth.isHealthy());
	assertEquals(2, aggregatedHealth.getHealthResults().size());
	assertEquals(0, aggregatedHealth.getSuppressedHealthResults().size());
	List<Health> indicators = aggregator.check().get().getHealthResults();
	assertThat(indicators).flatExtracting(s->s.getDetails().keySet()).contains("foo", "error");
	assertThat(indicators).flatExtracting(s->s.getDetails().values()).contains("bar", "java.lang.RuntimeException: Boom");
}
 
Example #15
Source File: SimpleHealthCheckAggregatorTest.java    From runtime-health with Apache License 2.0 5 votes vote down vote up
@Test(timeout=1000)
public void testOneHealthyAndOneNonResponsive() throws Exception {
	aggregator = new SimpleHealthCheckAggregator(Arrays.asList(healthy,nonResponsive), 50, TimeUnit.MILLISECONDS);
	HealthCheckStatus aggregatedHealth = aggregator.check().get();
	assertFalse(aggregatedHealth.isHealthy());
	assertEquals(2, aggregatedHealth.getHealthResults().size());
	assertEquals(0, aggregatedHealth.getSuppressedHealthResults().size());
	Health failed = aggregatedHealth.getHealthResults().stream().filter(h->!h.isHealthy()).findFirst().get();
	assertNotNull(failed);
	assertTrue(failed.getErrorMessage().isPresent());
	assertEquals("java.util.concurrent.TimeoutException: Timed out waiting for response", failed.getErrorMessage().get());
}
 
Example #16
Source File: SimpleHealthCheckAggregatorTest.java    From runtime-health with Apache License 2.0 5 votes vote down vote up
@Test(timeout=1000)
public void testOneHealthyAndOneExceptional() throws Exception {
	aggregator = new SimpleHealthCheckAggregator(Arrays.asList(healthy,exceptional), 1, TimeUnit.SECONDS);
	HealthCheckStatus aggregatedHealth = aggregator.check().get();
	assertFalse(aggregatedHealth.isHealthy());
	assertEquals(2, aggregatedHealth.getHealthResults().size());
	assertEquals(0, aggregatedHealth.getSuppressedHealthResults().size());
}
 
Example #17
Source File: SimpleHealthCheckAggregatorEventsTest.java    From runtime-health with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 1000)
public void testChangingHealthSendsEvent() throws Exception {
    SimpleHealthCheckAggregator aggregator = new SimpleHealthCheckAggregator(Arrays.asList(changing), 100, TimeUnit.SECONDS,dispatcher);
    HealthCheckStatus aggregatedHealth = aggregator.check().get();
    assertTrue(aggregatedHealth.isHealthy());
    assertEquals(1, aggregatedHealth.getHealthResults().size());
    Thread.sleep(10);
    Mockito.verify(dispatcher, Mockito.times(1)).publishEvent(Mockito.any());
    aggregator.check().get();
    Thread.sleep(10);
    Mockito.verify(dispatcher, Mockito.times(2)).publishEvent(Mockito.any());
    aggregator.check().get();
    Thread.sleep(10);
    Mockito.verifyNoMoreInteractions(dispatcher);
}
 
Example #18
Source File: SimpleHealthCheckAggregatorTest.java    From runtime-health with Apache License 2.0 5 votes vote down vote up
@Test(timeout=1000)
public void testAllUnheathy() throws Exception {
	aggregator = new SimpleHealthCheckAggregator(Arrays.asList(unhealthy,unhealthy), 1, TimeUnit.SECONDS);
	HealthCheckStatus aggregatedHealth = aggregator.check().get();
	assertFalse(aggregatedHealth.isHealthy());
	assertEquals(2, aggregatedHealth.getHealthResults().size());
	assertEquals(0, aggregatedHealth.getSuppressedHealthResults().size());
}
 
Example #19
Source File: SimpleHealthCheckAggregatorTest.java    From runtime-health with Apache License 2.0 5 votes vote down vote up
@Test(timeout=1000)
public void testOneUnheathy() throws Exception {
	aggregator = new SimpleHealthCheckAggregator(Arrays.asList(healthy,unhealthy), 1, TimeUnit.SECONDS);
	HealthCheckStatus aggregatedHealth = aggregator.check().get();
	assertFalse(aggregatedHealth.isHealthy());
	assertEquals(2, aggregatedHealth.getHealthResults().size());
	assertEquals(0, aggregatedHealth.getSuppressedHealthResults().size());
}
 
Example #20
Source File: SimpleHealthCheckAggregatorTest.java    From runtime-health with Apache License 2.0 5 votes vote down vote up
@Test(timeout=1000)
public void testAllHealthy() throws Exception {
	aggregator = new SimpleHealthCheckAggregator(Arrays.asList(healthy,healthy), 1, TimeUnit.SECONDS);
	HealthCheckStatus aggregatedHealth = aggregator.check().get();
	assertTrue(aggregatedHealth.isHealthy());
	assertEquals(2, aggregatedHealth.getHealthResults().size());
	assertEquals(0, aggregatedHealth.getSuppressedHealthResults().size());
}
 
Example #21
Source File: SimpleHealthCheckAggregatorTest.java    From runtime-health with Apache License 2.0 5 votes vote down vote up
@Test(timeout=1000)
public void testEmptyListIsHealthy() throws Exception {
	aggregator = new SimpleHealthCheckAggregator(new ArrayList<>(), 1, TimeUnit.SECONDS);
	HealthCheckStatus aggregatedHealth = aggregator.check().get();
	assertTrue(aggregatedHealth.isHealthy());
	assertEquals(0, aggregatedHealth.getHealthResults().size());
	assertEquals(0, aggregatedHealth.getSuppressedHealthResults().size());
}
 
Example #22
Source File: DefaultCachingHealthCheckAggregatorTest.java    From runtime-health with Apache License 2.0 5 votes vote down vote up
@Test(timeout=1000)
public void testCachedIndicatorNameNotHidden() throws Exception {
    DefaultCachingHealthCheckAggregator aggregator = new DefaultCachingHealthCheckAggregator(
            Arrays.asList(new TestHealthIndicator()), 1, TimeUnit.SECONDS, 1, TimeUnit.SECONDS, null);
    HealthCheckStatus aggregatedHealth = aggregator.check().get();
    assertTrue(aggregatedHealth.isHealthy());
    assertEquals(1, aggregatedHealth.getHealthResults().size());
    assertEquals(TestHealthIndicator.class.getName(), aggregatedHealth.getHealthResults().get(0).getDetails().get("className"));
}
 
Example #23
Source File: SimpleHealthCheckAggregator.java    From runtime-health with Apache License 2.0 5 votes vote down vote up
protected CompletableFuture<HealthCheckStatus> doWithFuture(CompletableFuture<HealthCheckStatus> future) {
    return future.whenComplete((status, error) -> {
        if (status.getHealthResults().stream().filter(s -> s.getErrorMessage().orElse("").contains(TimeoutException.class.getName())).count() > 0) {
            registry.ifPresent(r -> r.counter("runtime.health", "status", "TIMEOUT").increment());
        } else {
            registry.ifPresent(r -> r.counter("runtime.health", "status", status.isHealthy() ? "HEALTHY" : "UNHEALTHY").increment());
        }
        LOG.debug("Health Status: {}", status);
    });
}
 
Example #24
Source File: HealthAggregatorEurekaHealthCheckHandler.java    From runtime-health with Apache License 2.0 5 votes vote down vote up
private InstanceStatus getInstanceStatusForHealth(HealthCheckStatus health) {
    if (health.isHealthy()) {
        return InstanceStatus.UP;
    } else {
        return InstanceStatus.DOWN;
    }
}
 
Example #25
Source File: HealthModuleTest.java    From runtime-health with Apache License 2.0 5 votes vote down vote up
@Test
public void testConfiguringIndicatorsByExtendingHealthModule() throws InterruptedException, ExecutionException {
    LifecycleInjector injector = InjectorBuilder.fromModules(new HealthModule() {
        @Override
        protected void configureHealth() {
            bindAdditionalHealthIndicator().toInstance(healthy);
        }
    }, new ArchaiusModule()).createInjector();
    HealthCheckAggregator aggregator = injector.getInstance(HealthCheckAggregator.class);
    assertNotNull(aggregator);
    HealthCheckStatus healthCheckStatus = aggregator.check().get();
    assertTrue(healthCheckStatus.isHealthy());
    assertEquals(1, healthCheckStatus.getHealthResults().size());
}
 
Example #26
Source File: HealthModuleTest.java    From runtime-health with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoIndicators() throws InterruptedException, ExecutionException {
    LifecycleInjector injector = InjectorBuilder.fromModules(new HealthModule(), new ArchaiusModule()).createInjector();
    HealthCheckAggregator aggregator = injector.getInstance(HealthCheckAggregator.class);
    assertNotNull(aggregator);
    HealthCheckStatus healthCheckStatus = aggregator.check().get();
    assertTrue(healthCheckStatus.isHealthy());
    assertEquals(0, healthCheckStatus.getHealthResults().size());
}
 
Example #27
Source File: SimpleHealthCheckAggregator.java    From runtime-health with Apache License 2.0 4 votes vote down vote up
public CompletableFuture<HealthCheckStatus> check(IndicatorMatcher matcher) {
    final List<HealthIndicatorCallbackImpl> callbacks = new ArrayList<>(indicators.size());
    final CompletableFuture<HealthCheckStatus> future = new CompletableFuture<HealthCheckStatus>();
    final AtomicInteger counter = new AtomicInteger(indicators.size());
    
    if (eventDispatcher != null) {
        future.whenComplete((h, e) -> {
            if (h != null && previousHealth.compareAndSet(!h.isHealthy(), h.isHealthy())) {
                eventDispatcher.publishEvent(new HealthCheckStatusChangedEvent(h));
            }
        });
    }
    
    List<CompletableFuture<?>> futures = indicators.stream().map(indicator -> {

        HealthIndicatorCallbackImpl callback = new HealthIndicatorCallbackImpl(indicator, !matcher.matches(indicator)) {
            @Override
            public void inform(Health status) {
                setHealth(status);
                if (counter.decrementAndGet() == 0) {
                    future.complete(getStatusFromCallbacks(callbacks));
                }
            }
        };

        callbacks.add(callback);
  
        return CompletableFuture.runAsync(() -> {
            try {
                indicator.check(callback);
            } catch (Exception ex) {
                callback.inform(Health.unhealthy(ex).build());
            }
        }, healthCheckExecutor);
        
    }).collect(Collectors.toList());
            
    if(indicators.size() == 0) {
    	future.complete(HealthCheckStatus.create(true, Collections.emptyList()));
    }
    
    if (maxWaitTime != 0 && units != null) {
        scheduledExecutor.schedule(new Runnable() {
            @Override
            public void run() {
                future.complete(getStatusFromCallbacks(callbacks));
                CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])).cancel(true);
            }
        }, maxWaitTime, units);
    }

    return doWithFuture(future);
}
 
Example #28
Source File: SimpleHealthCheckAggregator.java    From runtime-health with Apache License 2.0 4 votes vote down vote up
@Override
public CompletableFuture<HealthCheckStatus> check() {
    return check(IndicatorMatchers.build());
}
 
Example #29
Source File: HealthCheckStatusChangedEvent.java    From runtime-health with Apache License 2.0 4 votes vote down vote up
public HealthCheckStatus getHealth() {
    return health;
}
 
Example #30
Source File: HealthCheckStatusChangedEvent.java    From runtime-health with Apache License 2.0 4 votes vote down vote up
public HealthCheckStatusChangedEvent(HealthCheckStatus health) {
    this.health = health;
}