Java Code Examples for com.codahale.metrics.health.HealthCheck#Result

The following examples show how to use com.codahale.metrics.health.HealthCheck#Result . 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: HealthServlet.java    From chassis with Apache License 2.0 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	if (healthCheckRegistry != null) {
        for (Map.Entry<String, HealthCheck.Result> entry : healthCheckRegistry.runHealthChecks().entrySet()) {
            if (!entry.getValue().isHealthy()) {
            	resp.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            	resp.getWriter().write(entry.getKey());
            }
        }
        resp.setStatus(HttpServletResponse.SC_OK);
    	resp.getWriter().write("OK");
    } else {
    	resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
    	resp.getWriter().write("No health check registry");
    }
}
 
Example 2
Source File: HealthCheckResourceTest.java    From pay-publicapi with MIT License 6 votes vote down vote up
@Test
public void checkHealthCheck_isUnHealthy() throws JsonProcessingException {
    SortedMap<String,HealthCheck.Result> map = new TreeMap<>();
    map.put("ping", HealthCheck.Result.unhealthy("application is unavailable"));
    map.put("deadlocks", HealthCheck.Result.unhealthy("no new threads available"));

    when(healthCheckRegistry.runHealthChecks()).thenReturn(map);

    Response response = resource.healthCheck();

    assertThat(response.getStatus(), is(503));

    ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
    String body = ow.writeValueAsString(response.getEntity());
    JsonAssert.with(body)
            .assertThat("$.*", hasSize(2))
            .assertThat("$.ping.healthy", is(false))
            .assertThat("$.deadlocks.healthy", is(false));
}
 
Example 3
Source File: HealthCheckHandler.java    From pippo with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RouteContext routeContext) {
    Response response = routeContext.getResponse().noCache().text();

    SortedMap<String, HealthCheck.Result> healthChecks = healthCheckRegistry.runHealthChecks();
    if (healthChecks.isEmpty()) {
        response.notImplemented().send("The health checks are empty");
    } else {
        boolean notHealthy = healthChecks.values().stream().anyMatch(hc -> !hc.isHealthy());
        if (notHealthy) {
            response.internalError().send("The health is bad");
        } else {
            response.ok().send("The health is good");
        }
    }
}
 
Example 4
Source File: CasDataStoreTest.java    From emodb with Apache License 2.0 6 votes vote down vote up
@Test
public void testHealthCheck() throws Exception {
    ArgumentCaptor<HealthCheck> captor = ArgumentCaptor.forClass(HealthCheck.class);
    verify(_healthChecks, atLeastOnce()).addHealthCheck(Matchers.anyString(), captor.capture());
    List<HealthCheck> healthChecks = captor.getAllValues();

    int numCassandraHealthChecks = 0;
    for (HealthCheck healthCheck : healthChecks) {
        if (healthCheck instanceof CassandraHealthCheck) {
            HealthCheck.Result result = healthCheck.execute();
            assertTrue(result.isHealthy(), result.getMessage());
            numCassandraHealthChecks++;
        }
    }
    assertEquals(numCassandraHealthChecks, 2);  // app, ugc
}
 
Example 5
Source File: HealthCheckResource.java    From pay-publicapi with MIT License 5 votes vote down vote up
private Map<String, Map<String, Boolean>> getResponse(SortedMap<String, HealthCheck.Result> results) {
    Map<String, Map<String, Boolean>> response = new HashMap<>();
    for (SortedMap.Entry<String, HealthCheck.Result> entry : results.entrySet() ) {
        response.put(entry.getKey(), ImmutableMap.of(HEALTHY, entry.getValue().isHealthy()));
    }
    return response;
}
 
Example 6
Source File: ActuatorHealthIndicator.java    From moneta with Apache License 2.0 5 votes vote down vote up
public Health health() {
	
	Map<String, HealthCheck.Result> resultMap = healthCheckRegistry.runHealthChecks();
	HealthCheck.Result result;
	for (String checkName: resultMap.keySet()) {
		result = resultMap.get(checkName);
		if ( !result.isHealthy()) {
			return Health.down().withDetail(checkName, result.toString()).build();
		}
	}
	
	return Health.up().build();
}
 
Example 7
Source File: JooqHealthCheckTest.java    From keywhiz with Apache License 2.0 5 votes vote down vote up
@Test
public void reportsUnhealthy() throws Exception {
  Connection connection;
  try (Connection c = dataSource.getConnection()) {
    connection = c;
  }
  when(managedDataSource.getConnection()).thenReturn(connection);
  JooqHealthCheck healthCheck = new JooqHealthCheck(managedDataSource, RETURN_UNHEALTHY);
  HealthCheck.Result result = healthCheck.check();

  assertThat(result.isHealthy()).isFalse();
  assertThat(result.getMessage()).isEqualTo("Unhealthy connection to database.");
}
 
Example 8
Source File: CodahaleHealthCheck.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
static Result wrap( HealthCheck.Result result )
{
    if( result.isHealthy() )
    {
        return Result.healthOk();
    }
    String message = result.getMessage();
    Throwable error = result.getError();
    if( error != null )
    {
        return Result.exception( message, error );
    }
    return Result.unhealthy( message );
}
 
Example 9
Source File: TestCassandraHealthCheck.java    From emodb with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
@Test
public void testNegativeHealthCheck() throws Exception {
    when(_astyanaxStatement.execute()).thenThrow(new OperationException("simulated cassandra exception"));
    when(_clock.millis()).thenReturn(1478789200000L);

    HealthCheck.Result result = _healthCheck.execute();
    assertFalse(result.isHealthy());
    assertTrue(result.getError() instanceof OperationException);
}
 
Example 10
Source File: HealthCheckMethodProducerTest.java    From metrics-cdi with Apache License 2.0 5 votes vote down vote up
@Test
@InSequence(2)
public void healthChecksRegistered() {
    assertThat("HealthChecks are not registered correctly", registry.getNames(),
        containsInRelativeOrder("check1", "check2"));

    SortedMap<String, HealthCheck.Result> results = registry.runHealthChecks();

    assertThat("check1 did not execute", results, hasKey("check1"));
    assertThat("check1 did not pass", results.get("check1").isHealthy(), is(true));

    assertThat("check2 did not execute", results, hasKey("check2"));
    assertThat("check2 did not fail", results.get("check2").isHealthy(), is(false));
}
 
Example 11
Source File: PartitionAwareServiceFactory.java    From emodb with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isHealthy(ServiceEndPoint endPoint) {
    if (isSelf(endPoint)) {
        Map<String, HealthCheck.Result> results = _healthCheckRegistry.runHealthChecks();
        return Iterables.all(results.values(), new Predicate<HealthCheck.Result>() {
            @Override
            public boolean apply(HealthCheck.Result result) {
                return result.isHealthy();
            }
        });
    }
    return _delegate.isHealthy(endPoint);
}
 
Example 12
Source File: ReconciledCheck.java    From dcos-cassandra-service with Apache License 2.0 5 votes vote down vote up
protected HealthCheck.Result check() throws Exception {

        if (reconciler.isReconciled()) {
            return HealthCheck.Result.healthy("Framework reconciled");
        }
        return HealthCheck.Result.unhealthy("Reconciliation in progress");
    }
 
Example 13
Source File: HealthCheckTableFormatter.java    From verify-service-provider with MIT License 5 votes vote down vote up
private static String extractHealthCheckItemRows(String healthCheckName, HealthCheck.Result healthCheckResult) {
    String healthCheckNameLine = healthCheckName + ":" + lineSeparator();
    String healthyStatusLine = "|     healthy: " + healthCheckResult.isHealthy();
    String messageLine = Optional.ofNullable(healthCheckResult.getMessage())
        .map(message -> lineSeparator() + "|     message: " + message)
        .orElse("");

    return healthCheckNameLine +
        healthyStatusLine +
        messageLine;
}
 
Example 14
Source File: HealthResource.java    From airpal with Apache License 2.0 5 votes vote down vote up
private static boolean isAllHealthy(Map<String, HealthCheck.Result> results) {
    for (HealthCheck.Result result : results.values()) {
        if (!result.isHealthy()) {
            return false;
        }
    }
    return true;
}
 
Example 15
Source File: Subjects.java    From droptools with Apache License 2.0 4 votes vote down vote up
public static HealthCheckResultSubject assertThat(HealthCheck.Result result) {
    return HealthCheckResultSubject.assertThat(result);
}
 
Example 16
Source File: TotalHealthCheckGauge.java    From helios with Apache License 2.0 4 votes vote down vote up
@Override
public Integer getValue() {
  final SortedMap<String, HealthCheck.Result> results = registry.runHealthChecks();
  return results.values().stream().allMatch(HealthCheck.Result::isHealthy) ? 1 : 0;
}
 
Example 17
Source File: TestCassandraHealthCheck.java    From emodb with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings({"ThrowableResultOfMethodCallIgnored", "unchecked"})
@Test(timeOut = 15000L)
public void testConcurrentHealthChecks() throws Exception {
    // Perform one positive health check to get it cached.
    OperationResult operationResult = createPositiveOperationResult("host1");
    ResultSet resultSet = createPositiveResultSet("host1");
    when(_astyanaxStatement.execute()).thenReturn(operationResult);
    when(_cqlSession.execute(_queryString)).thenReturn(resultSet);

    long now = 1478789200000L;
    when(_clock.millis()).thenReturn(now);

    HealthCheck.Result result = _healthCheck.execute();
    assertTrue(result.isHealthy());
    assertTrue(result.getMessage().contains("host1"));

    // Change the CQL health check to block for a controlled amount of time

    final CountDownLatch cqlBlocked = new CountDownLatch(1);
    final CountDownLatch raiseConnectionException = new CountDownLatch(1);

    when(_cqlSession.execute(_queryString)).thenAnswer(new Answer<ResultSet>() {
        @Override
        public ResultSet answer(InvocationOnMock invocationOnMock) throws Throwable {
            // Let the main thread know we are blocked
            cqlBlocked.countDown();
            // Wait for the main thread to give the signal to raise the connection exception
            raiseConnectionException.await();
            // Raise the exception
            throw new OperationException("simulated cassandra exception");
        }
    });

    // Move time forward 5 seconds to ensure the cached value isn't being returned.
    when(_clock.millis()).thenReturn(now = now + TimeUnit.SECONDS.toMillis(5));

    ExecutorService service = Executors.newFixedThreadPool(1);
    try {
        // In a new thread perform a health check
        Future<HealthCheck.Result> blockedThreadResult = service.submit(() -> _healthCheck.execute());
        // Wait for the thread's CQL call to be blocked
        assertTrue(cqlBlocked.await(5, TimeUnit.SECONDS), "Thread taking too long to make CQL call");

        // Make a call to the health check.  It should return immediately with the old healthy value
        result = _healthCheck.execute();
        assertTrue(result.isHealthy());
        assertTrue(result.getMessage().contains("host1"));

        // Move time forward 29 seconds and check again
        when(_clock.millis()).thenReturn(now = now + TimeUnit.SECONDS.toMillis(29));
        result = _healthCheck.execute();
        assertTrue(result.isHealthy());
        assertTrue(result.getMessage().contains("host1"));

        // Now move time forward one more second for a total of 30.   At this point this health check should return
        // unhealthy because the other health check is taking too long.
        when(_clock.millis()).thenReturn(now + TimeUnit.SECONDS.toMillis(1));
        Stopwatch stopWatch = Stopwatch.createStarted();
        result = _healthCheck.execute();
        stopWatch.stop();
        // Health check shouldn't have taken long
        assertTrue(stopWatch.elapsed(TimeUnit.SECONDS) < 1, "Heath check should not have been blocked");
        assertFalse(result.isHealthy());
        assertEquals(result.getMessage(), "Asynchronous health check update is taking too long");

        // Unblock the thread's health check and let it finish
        raiseConnectionException.countDown();

        result = blockedThreadResult.get(2, TimeUnit.SECONDS);
        assertFalse(result.isHealthy());
        assertTrue(result.getError() instanceof OperationException);

    } catch (Exception e) {
        // Always ensure the thread completes
        raiseConnectionException.countDown();
        service.shutdownNow();
    }
}
 
Example 18
Source File: HealthCheckGauge.java    From helios with Apache License 2.0 4 votes vote down vote up
@Override
public Integer getValue() {
  final HealthCheck.Result result = registry.runHealthCheck(name);
  return result.isHealthy() ? 1 : 0;
}
 
Example 19
Source File: StatusResource.java    From keywhiz with Apache License 2.0 4 votes vote down vote up
public SortedMap<String, HealthCheck.Result> getResults() {
  return results;
}
 
Example 20
Source File: HealthCheckIntegrationTest.java    From tutorials with MIT License 4 votes vote down vote up
@Test
public void whenUseHealthCheck_thenHealthChecked() {
    HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry();

    healthCheckRegistry.register("db", new DatabaseHealthCheck());
    healthCheckRegistry.register("uc", new UserCenterHealthCheck());

    assertThat(healthCheckRegistry.getNames().size(), equalTo(2));

    Map<String, HealthCheck.Result> results = healthCheckRegistry.runHealthChecks();

    assertFalse(results.isEmpty());

    results.forEach((k, v) -> assertTrue(v.isHealthy()));

    healthCheckRegistry.unregister("uc");

    assertThat(healthCheckRegistry.getNames().size(), equalTo(1));
}