com.codahale.metrics.health.HealthCheck.Result Java Examples

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: DashboardHealthCheck.java    From SeaCloudsPlatform with Apache License 2.0 6 votes vote down vote up
@Override
protected Result check() throws Exception {
    LOG.warn("This is NOT an integration test. The current Healthcheck only checks if all the endpoints are reachable");

    if(!portIsOpen(deployer.getHost(), deployer.getPort())){
        return Result.unhealthy("The Deployer endpoint is not ready");
    }


    if(!portIsOpen(grafana.getHost(), grafana.getPort())){
        return Result.unhealthy("The Monitor endpoint is not ready");
    }

    if(!portIsOpen(sla.getHost(), sla.getPort())) {
        return Result.unhealthy("The SLA endpoint is not ready");
    }

    if(!portIsOpen(planner.getHost(), planner.getPort())){
        return Result.unhealthy("The Planner endpoint is not ready");
    }

    return Result.healthy();
}
 
Example #2
Source File: HealthCheckCacheManager.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected void doStart() throws Exception {
  cache = CacheBuilder.newBuilder().build(cacheLoader());
  jobService.startUsing();
  metricsWritingJob = jobService.schedule(() -> {
    registry.getNames().forEach(k -> {
      Result oldResult = cache.getUnchecked(k);
      cache.refresh(k);
      // Refresh is lazy and doesn't refresh until the next request so force it to refresh.
      Result newResult = cache.getUnchecked(k);
      if(oldResult.isHealthy() != newResult.isHealthy()) {
        log.info("Health check status changed from {} to {} for {}", oldResult.isHealthy(), newResult.isHealthy(), k);
      }
    });
  }, refreshInterval);
}
 
Example #3
Source File: DbcpConnectionPoolHealthCheckTest.java    From moneta with Apache License 2.0 6 votes vote down vote up
@Test
public void testBasic() throws Exception {
	Assert.assertTrue(healthCheck.execute().equals(Result.healthy()));
	Assert.assertTrue(connectionPool.getNumActive()==0);
	
	poolableConnectionFactory.setValidationQuery("crap");		
	Result testResult = healthCheck.execute();
	Assert.assertTrue(!testResult.isHealthy());
	Assert.assertTrue(testResult.getMessage() != null);
	Assert.assertTrue(testResult.getMessage().contains("validation error"));
	poolableConnectionFactory.setValidationQuery(VALIDATION_SQL);
	
	healthCheck.setMaxWaitingConnections(-1);
	testResult = healthCheck.execute();
	Assert.assertTrue(!testResult.isHealthy());
	Assert.assertTrue(testResult.getMessage() != null);
	Assert.assertTrue(testResult.getMessage().contains("Overloaded connection pool"));
	Assert.assertTrue(healthCheck.getMaxWaitingConnections() == -1);
}
 
Example #4
Source File: StatusResourceDoc.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @since 3.20
 */
@GET
@ApiOperation("Health check endpoint that returns the results of the system status checks")
@ApiResponses({
    @ApiResponse(code = 200, message = "The system status check results", response = Result.class, responseContainer = "Map")
})
SortedMap<String, Result> getSystemStatusChecks();
 
Example #5
Source File: AvailableCpuHealthCheckTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testCheck_plentyOfCores() {
  Runtime runtime = mock(Runtime.class);
  when(runtime.availableProcessors()).thenReturn(86);
  underTest.setRuntime(runtime);
  Result result = underTest.check();
  assertThat(result.isHealthy(), is(true));
  assertThat(result.getMessage(), is("The host system is allocating a maximum of 86 cores to the application."));
}
 
Example #6
Source File: StatusResource.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @since 3.20
 */
@GET
@Path("/check")
@Timed
@RequiresAuthentication
@RequiresPermissions("nexus:metrics:read")
@Override
public SortedMap<String, Result> getSystemStatusChecks() {
  return registry.runHealthChecks();
}
 
Example #7
Source File: AvailableCpuHealthCheckTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testCheck_notEnoughCores() {
  Runtime runtime = mock(Runtime.class);
  when(runtime.availableProcessors()).thenReturn(1);
  underTest.setRuntime(runtime);
  Result result = underTest.check();
  assertThat(result.isHealthy(), is(false));
  assertThat(result.getMessage(), is("The host system is allocating a maximum of 1 cores to the application." +
      " A minimum of " + AvailableCpuHealthCheck.MIN_RECOMMENDED_CPU_COUNT + " is recommended."));
}
 
Example #8
Source File: DefaultUserHealthCheckTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void checkIsHealthyWhenRealmIsDisabled() {
  when(realmManager.isRealmEnabled(AuthenticatingRealmImpl.NAME)).thenReturn(false);

  Result result = defaultUserHealthCheck.check();

  assertThat(result.isHealthy(), is(true));
}
 
Example #9
Source File: DefaultUserHealthCheckTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void checkIsHealthyWhenRealmIsEnabled() {
  Realm realm = mock(Realm.class);
  when(realmManager.isRealmEnabled(AuthenticatingRealmImpl.NAME)).thenReturn(true);
  when(realmSecurityManager.getRealms()).thenReturn(singleton(realm));
  when(realm.getName()).thenReturn(AuthenticatingRealmImpl.NAME);
  when(realm.getAuthenticationInfo(any(UsernamePasswordToken.class))).thenThrow(AuthenticationException.class);

  Result result = defaultUserHealthCheck.check();

  assertThat(result.isHealthy(), is(true));
}
 
Example #10
Source File: DefaultUserHealthCheckTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void checkIsUnhealthy() {
  Realm realm = mock(Realm.class);
  when(realmManager.isRealmEnabled(AuthenticatingRealmImpl.NAME)).thenReturn(true);
  when(realmSecurityManager.getRealms()).thenReturn(singleton(realm));
  when(realm.getName()).thenReturn(AuthenticatingRealmImpl.NAME);
  when(realm.getAuthenticationInfo(any(UsernamePasswordToken.class))).thenReturn(mock(AuthenticationInfo.class));

  Result result = defaultUserHealthCheck.check();

  assertThat(result.isHealthy(), is(false));
  assertThat(result.getMessage(), is(DefaultUserHealthCheck.ERROR_MESSAGE));
}
 
Example #11
Source File: HealthCheckCacheManager.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private CacheLoader<String, Result> cacheLoader() {
  return new CacheLoader<String, Result>()
  {
    @Override
    public Result load(final String s) {
      return registry.runHealthCheck(s);
    }
  };
}
 
Example #12
Source File: TemplateHealthCheck.java    From karamel with Apache License 2.0 5 votes vote down vote up
@Override
protected Result check() throws Exception {
  final String saying = String.format(template, "TEST");
  if (!saying.contains("TEST")) {
    return Result.unhealthy("template doesn't include a name");
  }
  return Result.healthy();
}
 
Example #13
Source File: DropwizardArmeriaApplicationTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void testPingHealthCheck() {
    final HealthCheck ping = new PingCheck();

    final Result res = ping.execute();

    assertThat(res.isHealthy()).isTrue();
    assertThat(res.getMessage()).isEqualTo("pong");
}
 
Example #14
Source File: MesosDriverHealthCheckTest.java    From incubator-myriad with Apache License 2.0 5 votes vote down vote up
@Test
public void testCheckHealthyResult() throws Exception {
  HealthCheckTestTuple tuple = getTestStack();
  MyriadDriverManager manager = tuple.getManager();
  MesosDriverHealthCheck checker = tuple.getChecker();
  manager.startDriver(); 
  assertEquals(Result.healthy(), checker.check());
  manager.stopDriver(false);
}
 
Example #15
Source File: MesosDriverHealthCheckTest.java    From incubator-myriad with Apache License 2.0 5 votes vote down vote up
@Test
public void testCheckStoppedDriverUnhealthyResult() throws Exception {
  HealthCheckTestTuple tuple = getTestStack();
  MyriadDriverManager manager = tuple.getManager();
  MesosDriverHealthCheck checker = tuple.getChecker();
  manager.startDriver(); 
  manager.stopDriver(false);
  assertEquals(Result.unhealthy("Driver status: DRIVER_STOPPED"), checker.check());
}
 
Example #16
Source File: MesosDriverHealthCheckTest.java    From incubator-myriad with Apache License 2.0 5 votes vote down vote up
@Test
public void testCheckAbortedDriverUnhealthyResult() throws Exception {
  HealthCheckTestTuple tuple = getTestStack();
  MyriadDriverManager manager = tuple.getManager();
  MesosDriverHealthCheck checker = tuple.getChecker();
  manager.startDriver(); 
  manager.abortDriver();
  assertEquals(Result.unhealthy("Driver status: DRIVER_ABORTED"), checker.check());
}
 
Example #17
Source File: DashboardTestApplication.java    From SeaCloudsPlatform with Apache License 2.0 5 votes vote down vote up
@Override
public void run(DashboardTestConfiguration configuration, Environment environment) throws Exception {
    // Generating  HTTP Clients
    Client jerseyClient = new JerseyClientBuilder(environment).using(configuration.getJerseyClientConfiguration())
            .build(getName());

    // Configuring HealthChecks
    environment.healthChecks().register(getName(), new HealthCheck() {
        @Override
        protected Result check() throws Exception {
            return Result.healthy();
        }
    });
}
 
Example #18
Source File: JStormHealthReporter.java    From jstorm with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    StormClusterState clusterState = workerData.getZkCluster();
    String topologyId = workerData.getTopologyId();

    Map<Integer, HealthCheckRegistry> taskHealthCheckMap = JStormHealthCheck.getTaskhealthcheckmap();
    int cnt = 0;
    for (Map.Entry<Integer, HealthCheckRegistry> entry : taskHealthCheckMap.entrySet()) {
        Integer taskId = entry.getKey();
        Map<String, Result> results = entry.getValue().runHealthChecks();

        for (Map.Entry<String, Result> result : results.entrySet()) {
            if (!result.getValue().isHealthy()) {
                try {
                    clusterState.report_task_error(topologyId, taskId, result.getValue().getMessage(),
                            ErrorConstants.WARN, ErrorConstants.CODE_QUEUE_FULL, ErrorConstants.DURATION_SECS_QUEUE_FULL);
                    cnt++;
                } catch (Exception e) {
                    LOG.error("Failed to update health data in ZK for topo-{} task-{}.", topologyId, taskId, e);
                }
            }
        }
    }

    if (cnt > 0) {
        LOG.info("Successfully updated {} health data to ZK for topology:{}", cnt, topologyId);
    }
}
 
Example #19
Source File: DefaultRoleHealthCheckTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testCheck_isConfiguredIsEnabledRoleMissing() throws Exception {
  when(realmManager.isRealmEnabled(DefaultRoleRealm.NAME)).thenReturn(true);
  when(defaultRoleRealm.getRole()).thenReturn("test-role");

  Result result = underTest.check();
  assertThat(result.isHealthy(), is(false));
}
 
Example #20
Source File: DefaultRoleHealthCheckTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testCheck_isConfiguredIsEnabledRoleAvailable() throws Exception {
  when(realmManager.isRealmEnabled(DefaultRoleRealm.NAME)).thenReturn(true);
  when(defaultRoleRealm.getRole()).thenReturn("test-role");

  Role role = mock(Role.class);
  when(role.getRoleId()).thenReturn("test-role");
  when(securitySystem.listRoles(DEFAULT_SOURCE)).thenReturn(singleton(role));

  Result result = underTest.check();
  assertThat(result.isHealthy(), is(true));
}
 
Example #21
Source File: DefaultRoleHealthCheckTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testCheck_notConfiguredIsEnabled() throws Exception {
  when(realmManager.isRealmEnabled(DefaultRoleRealm.NAME)).thenReturn(true);

  Result result = underTest.check();
  assertThat(result.isHealthy(), is(false));
}
 
Example #22
Source File: CustomHandlers.java    From StubbornJava with MIT License 5 votes vote down vote up
public static void health(HttpServerExchange exchange) {
    SortedMap<String, Result> results = HealthChecks.getHealthCheckRegistry().runHealthChecks();
    boolean unhealthy = results.values().stream().anyMatch(result -> !result.isHealthy());

    if (unhealthy) {
        /*
         *  Set a 500 status code also. A lot of systems / dev ops tools can
         *  easily test status codes but are not set up to parse JSON.
         *  Let's keep it simple for everyone.
         */
        exchange.setStatusCode(500);
    }
    Exchange.body().sendJson(exchange, results);
}
 
Example #23
Source File: ConsulHealthCheckTest.java    From dropwizard-consul with Apache License 2.0 5 votes vote down vote up
@Test
public void testCheckUnhealthy() throws Exception {
  doThrow(new ConsulException("error")).when(agent).ping();
  final Result actual = healthCheck.check();
  verify(agent).ping();
  assertThat(actual.isHealthy()).isFalse();
}
 
Example #24
Source File: RtlSdrStatusDaoTest.java    From r2cloud with Apache License 2.0 5 votes vote down vote up
@Test
public void testUnknown() {
	rtlTestServer.mockTest("No supported\n");
	rtlTestServer.mockPpm("No supported\n");
	createExecuteNowRtlSdrDao();

	Map<String, Result> status = metrics.getHealthRegistry().runHealthChecks();
	assertError(status.get("rtldongle"));
	assertPpm(0);
}
 
Example #25
Source File: CustomHandlers.java    From StubbornJava with MIT License 5 votes vote down vote up
public static void health(HttpServerExchange exchange) {
    SortedMap<String, Result> results = HealthChecks.getHealthCheckRegistry().runHealthChecks();
    boolean unhealthy = results.values().stream().anyMatch(result -> !result.isHealthy());

    if (unhealthy) {
        /*
         *  Set a 500 status code also. A lot of systems / dev ops tools can
         *  easily test status codes but are not set up to parse JSON.
         *  Let's keep it simple for everyone.
         */
        exchange.setStatusCode(500);
    }
    Exchange.body().sendJson(exchange, results);
}
 
Example #26
Source File: RtlSdrStatusDaoTest.java    From r2cloud with Apache License 2.0 5 votes vote down vote up
@Test
public void testUnknownOutput() {
	rtlTestServer.mockTest(UUID.randomUUID().toString() + "\n");
	createExecuteNowRtlSdrDao();

	Map<String, Result> status = metrics.getHealthRegistry().runHealthChecks();
	assertUnknown(status.get("rtldongle"));
}
 
Example #27
Source File: RtlSdrStatusDaoTest.java    From r2cloud with Apache License 2.0 5 votes vote down vote up
@Test
public void testSuccess() {
	rtlTestServer.mockDefault();

	createExecuteNowRtlSdrDao();

	Map<String, Result> status = metrics.getHealthRegistry().runHealthChecks();
	assertHealthy(status.get("rtltest"));
	assertHealthy(status.get("rtldongle"));
	assertPpm(53);
}
 
Example #28
Source File: ResultUtil.java    From r2cloud with Apache License 2.0 4 votes vote down vote up
public static Result healthy() {
	ResultBuilder builder = Result.builder();
	builder.healthy().withDetail(FIELD_NAME, Status.SUCCESS);
	return builder.build();
}
 
Example #29
Source File: ResultUtil.java    From r2cloud with Apache License 2.0 4 votes vote down vote up
public static Result unknown() {
	ResultBuilder builder = Result.builder();
	builder.healthy().withDetail(FIELD_NAME, Status.UNKNOWN);
	return builder.build();
}
 
Example #30
Source File: KafkaHealthCheckTest.java    From monasca-common with Apache License 2.0 4 votes vote down vote up
public void shouldCheckHealth() throws Exception {
  Result result = new KafkaHealthCheck(config).check();
  if (!result.isHealthy() && result.getClass() != null)
    fail(result.getMessage(), result.getError());
  assertTrue(result.isHealthy(), result.getMessage());
}