com.codahale.metrics.health.HealthCheck Java Examples

The following examples show how to use com.codahale.metrics.health.HealthCheck. 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: ExampleApplication.java    From okta-auth-java with Apache License 2.0 6 votes vote down vote up
@Override
public void run(final ExampleConfiguration configuration, final Environment environment) {
    // example health check
    environment.healthChecks().register("example", new HealthCheck() {
        @Override
        protected HealthCheck.Result check() {
            // Everything is in memory, so we are always healthy ;)
            return Result.healthy();
        }
    });

    environment.servlets().addFilter("csrf", new OverlySimpleCsrfFilter())
            .addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), false, "/*");

    configureShiro(environment);

    configureJersey(environment.jersey());
}
 
Example #2
Source File: JobManager.java    From jobson with Apache License 2.0 6 votes vote down vote up
public Map<String, HealthCheck> getHealthChecks() {
    return Collections.singletonMap(
            JOB_MANAGER_JOB_QUEUE_OVERFLOW_HEALTHCHECK,
            new HealthCheck() {
                @Override
                protected Result check() throws Exception {
                    final int queueSize = jobQueue.size();
                    if (queueSize < JOB_MANAGER_MAX_JOB_QUEUE_OVERFLOW_THRESHOLD) {
                        return Result.healthy(format("Queue contains %s entries", queueSize));
                    } else {
                        return Result.unhealthy(format(
                                "%s entries in job queue: this exceeds the warning threshold (%s)",
                                queueSize,
                                JOB_MANAGER_MAX_JOB_QUEUE_OVERFLOW_THRESHOLD));
                    }
                }
            });
}
 
Example #3
Source File: JobManagerTest.java    From jobson with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetHealthChecksReturnsAHealthCheckForJobQueueOverflowing() {
    final CancelablePromise<JobExecutionResult> executorPromise = new SimpleCancelablePromise<>();
    final JobManager jobManager = createManagerWith(MockJobExecutor.thatUses(executorPromise));
    final Map<String, HealthCheck> healthChecks = jobManager.getHealthChecks();

    assertThat(healthChecks).containsKeys(JOB_MANAGER_JOB_QUEUE_OVERFLOW_HEALTHCHECK);
    assertThat(healthChecks.get(JOB_MANAGER_JOB_QUEUE_OVERFLOW_HEALTHCHECK)).isNotNull();

    final HealthCheck jobQueueHealthCheck = healthChecks.get(JOB_MANAGER_JOB_QUEUE_OVERFLOW_HEALTHCHECK);

    assertThat(jobQueueHealthCheck.execute().isHealthy());

    for(int i = 0; i < JOB_MANAGER_MAX_JOB_QUEUE_OVERFLOW_THRESHOLD * 2; i++) {
        // These won't finish because we never resolve the promise
        jobManager.submit(STANDARD_VALID_REQUEST);
    }

    assertThat(jobQueueHealthCheck.execute().isHealthy()).isFalse();
}
 
Example #4
Source File: HealthChecksServer.java    From StubbornJava with MIT License 6 votes vote down vote up
public static void main(String[] args) {
    /*
     *  Init connection pools. They auto register their own health checks.
     */
    ConnectionPools.getProcessing();
    ConnectionPools.getTransactional();

    // Assume some global HttpClient.
    OkHttpClient client = new OkHttpClient.Builder().build();

    HttpUrl passingPath = HttpUrl.parse("http://localhost:8080/ping");
    HealthCheck passing = new ExternalServiceHealthCheck(client, passingPath);
    HealthChecks.getHealthCheckRegistry().register("ping", passing);

    // Since this route doesn't exist it will respond with 404 and should fail the check.
    HttpUrl failingPath = HttpUrl.parse("http://localhost:8080/failingPath");
    HealthCheck failing = new ExternalServiceHealthCheck(client, failingPath);
    HealthChecks.getHealthCheckRegistry().register("shouldFail", failing);

    // Once again pull in a bunch of common middleware.
    SimpleServer server = SimpleServer.simpleServer(Middleware.common(ROUTES));
    server.start();
}
 
Example #5
Source File: CasBlobStoreTest.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, 3);  // app, ugc, media
}
 
Example #6
Source File: CasDatabusTest.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, 3);  // app, ugc, databus
}
 
Example #7
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 #8
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 #9
Source File: ClusterManager.java    From foxtrot with Apache License 2.0 6 votes vote down vote up
@Inject
public ClusterManager(HazelcastConnection connection, List<HealthCheck> healthChecks, ServerFactory serverFactory) throws IOException {
    this.hazelcastConnection = connection;
    this.healthChecks = healthChecks;
    MapConfig mapConfig = new MapConfig(MAP_NAME);
    mapConfig.setTimeToLiveSeconds(MAP_REFRESH_TIME + 2); //Reduce jitter
    mapConfig.setBackupCount(1);
    mapConfig.setAsyncBackupCount(2);
    mapConfig.setEvictionPolicy(EvictionPolicy.NONE);
    hazelcastConnection.getHazelcastConfig()
            .getMapConfigs()
            .put(MAP_NAME, mapConfig);
    String hostname = Inet4Address.getLocalHost()
            .getCanonicalHostName();
    //Auto detect marathon environment and query for host environment variable
    if(!Strings.isNullOrEmpty(System.getenv("HOST")))
        hostname = System.getenv("HOST");
    Preconditions.checkNotNull(hostname, "Could not retrieve hostname, cannot proceed");
    int port = ServerUtils.port(serverFactory);
    //Auto detect marathon environment and query for host environment variable
    if(!Strings.isNullOrEmpty(System.getenv("PORT_" + port)))
        port = Integer.parseInt(System.getenv("PORT_" + port));
    executor = Executors.newScheduledThreadPool(1);
    clusterMember = new ClusterMember(hostname, port);
}
 
Example #10
Source File: HealthCheckMetrics.java    From watcher with Apache License 2.0 6 votes vote down vote up
@Override
public Object watch(Map<String, Object> params) {
	Object key = checkNotNull(params).get(Constants.KEY);
	if (key == null) {
		SortedMap<String, HealthCheck.Result> healthChecks = healthCheckRegistry.runHealthChecks();
		boolean isAllOk = true;
		for (HealthCheck.Result singleResult : healthChecks.values()) {
			if (!singleResult.isHealthy()) {
				isAllOk = false;
				break;
			}
		}
		Map<String, Object> result = Maps.newHashMap();
		result.put("healthy", isAllOk);
		result.put("healthChecks", healthChecks);
		return result;
	} else {
		if (!healthCheckRegistry.getNames().contains(key.toString())) {
			return Collections.emptyMap();
		}
		return healthCheckRegistry.runHealthCheck(key.toString());
	}
}
 
Example #11
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 #12
Source File: TenacityCircuitBreakerHealthCheckTest.java    From tenacity with Apache License 2.0 6 votes vote down vote up
@Test
public void multipleUnhealthyWhenThereIsAnOpenCircuitBreaker() {
    final ImmutableList<TenacityPropertyKey> keys = ImmutableList.<TenacityPropertyKey>of(
            DependencyKey.EXISTENT_HEALTHCHECK, DependencyKey.ANOTHER_EXISTENT_HEALTHCHECK);
    final HealthCheck healthCheck = new TenacityCircuitBreakerHealthCheck(keys);

    assertThat(CircuitBreakers.all(keys)).isEmpty();
    tryToOpenCircuitBreaker(DependencyKey.EXISTENT_HEALTHCHECK);
    tryToOpenCircuitBreaker(DependencyKey.ANOTHER_EXISTENT_HEALTHCHECK);
    assertThat(CircuitBreakers.all(keys))
            .contains(CircuitBreaker.open(DependencyKey.EXISTENT_HEALTHCHECK),
                    CircuitBreaker.open(DependencyKey.ANOTHER_EXISTENT_HEALTHCHECK));

    assertThat(healthCheck.execute())
            .isEqualToComparingOnlyGivenFields(HealthCheck.Result.unhealthy(""), "healthy");
}
 
Example #13
Source File: CodahaleHealthCheck.java    From attic-polygene-java with Apache License 2.0 6 votes vote down vote up
static HealthCheck.Result unwrap( Result result )
{
    String message = result.getMessage();
    if( result.isHealthy() )
    {
        if( message != null )
        {
            return HealthCheck.Result.healthy( message );
        }
        return HealthCheck.Result.healthy();
    }
    Throwable error = result.getException();
    if( error != null )
    {
        return HealthCheck.Result.unhealthy( error );
    }
    return HealthCheck.Result.unhealthy( message );
}
 
Example #14
Source File: DropwizardModule.java    From dropwizard-guicier with Apache License 2.0 6 votes vote down vote up
@Override
public void configure(final Binder binder) {
  binder.bindListener(Matchers.any(), new ProvisionListener() {
    @Override
    public <T> void onProvision(ProvisionInvocation<T> provision) {
      Object obj = provision.provision();

      if (obj instanceof Managed) {
        handle((Managed) obj);
      }

      if (obj instanceof Task) {
        handle((Task) obj);
      }

      if (obj instanceof HealthCheck) {
        handle((HealthCheck) obj);
      }

      if (obj instanceof ServerLifecycleListener) {
        handle((ServerLifecycleListener) obj);
      }
    }
  });
}
 
Example #15
Source File: MacroBaseServer.java    From macrobase with Apache License 2.0 6 votes vote down vote up
@Override
public void run(MacroBaseConf configuration,
                Environment environment) throws Exception {
    configuration.loadSystemProperties();
    environment.jersey().register(new AnalyzeResource(configuration));
    environment.jersey().register(new SchemaResource(configuration));
    environment.jersey().register(new RowSetResource(configuration));
    environment.jersey().register(new FormattedRowSetResource(configuration));
    environment.jersey().register(new MultipleRowSetResource(configuration));

    environment.healthChecks().register("basic", new HealthCheck() {
        @Override
        protected Result check() throws Exception {
            return null;
        }
    });

    environment.jersey().setUrlPattern("/api/*");
}
 
Example #16
Source File: MyApp.java    From dropwizard-websockets with MIT License 6 votes vote down vote up
@Override
public void run(Configuration configuration, Environment environment) throws InvalidKeySpecException, NoSuchAlgorithmException, ServletException, DeploymentException {
    environment.lifecycle().addLifeCycleListener(new AbstractLifeCycle.AbstractLifeCycleListener() {

        @Override
        public void lifeCycleStarted(LifeCycle event) {
            cdl.countDown();
        }
    });
    environment.jersey().register(new MyResource());
    environment.healthChecks().register("alive", new HealthCheck() {
        @Override
        protected HealthCheck.Result check() throws Exception {
            return HealthCheck.Result.healthy();
        }
    });

    // Using ServerEndpointConfig lets you inject objects to the websocket endpoint:
    final ServerEndpointConfig config = ServerEndpointConfig.Builder.create(EchoServer.class, "/extends-ws").build();
    // config.getUserProperties().put(Environment.class.getName(), environment);
    // Then you can get it from the Session object
    // - obj = session.getUserProperties().get("objectName");            
    websocketBundle.addEndpoint(config);
}
 
Example #17
Source File: Application.java    From xrpc with Apache License 2.0 5 votes vote down vote up
public static void configure(Server server) {
  // Add handlers for /people routes
  server.addRoutes(new PeopleRoutes());

  // Add a service specific health check
  server.addHealthCheck(
      "simple",
      new HealthCheck() {
        @Override
        protected Result check() {
          System.out.println("Health Check Ran");
          return Result.healthy();
        }
      });
}
 
Example #18
Source File: FilesystemJobSpecDAO.java    From jobson with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, HealthCheck> getHealthChecks() {
    return singletonMap(
            FILESYSTEM_SPECS_DAO_DISK_SPACE_HEALTHCHECK,
            new DiskSpaceHealthCheck(
                    jobSpecsDir.toFile(),
                    FILESYSTEM_SPECS_DAO_DISK_SPACE_WARNING_THRESHOLD_IN_BYTES));
}
 
Example #19
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 #20
Source File: RDFConnectionHealthCheckTest.java    From trellis with Apache License 2.0 5 votes vote down vote up
@Test
void testIsConnected() {
    final Dataset dataset = rdf.createDataset();
    final RDFConnection rdfConnection = connect(wrap(toJena(dataset)));
    final HealthCheck check = new RDFConnectionHealthCheck(rdfConnection);
    assertTrue(check.execute().isHealthy(), "RDFConnection isn't healthy!");
}
 
Example #21
Source File: RDFConnectionHealthCheckTest.java    From trellis with Apache License 2.0 5 votes vote down vote up
@Test
void testNonConnected() {
    final Dataset dataset = rdf.createDataset();
    final RDFConnection rdfConnection = connect(wrap(toJena(dataset)));
    rdfConnection.close();
    final HealthCheck check = new RDFConnectionHealthCheck(rdfConnection);
    assertFalse(check.execute().isHealthy(), "Closed RDFConnection doesn't report as unhealthy!");
}
 
Example #22
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 #23
Source File: AWSDatabaseHolder.java    From billow with Apache License 2.0 5 votes vote down vote up
public HealthCheck.Result healthy() {
    final long ageInMs = current.getAgeInMs();
    if (ageInMs < maxAgeInMs)
        return HealthCheck.Result.healthy();
    else
        return HealthCheck.Result.unhealthy("DB too old: " + ageInMs + " ms");
}
 
Example #24
Source File: TestCassandraHealthCheck.java    From emodb with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testHealthCheckCaching() 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 health checks to return a different host
    operationResult = createPositiveOperationResult("host2");
    resultSet = createPositiveResultSet("host2");
    when(_astyanaxStatement.execute()).thenReturn(operationResult);
    when(_cqlSession.execute(_queryString)).thenReturn(resultSet);

    // Move time forward 4.9 seconds to ensure the cached result is still returned
    when(_clock.millis()).thenReturn(now = now + 4900L);
    result = _healthCheck.execute();
    assertTrue(result.isHealthy());
    // Since the cached value should have been returned the old hosts should still be included in the message
    assertTrue(result.getMessage().contains("host1"));
    assertFalse(result.getMessage().contains("host2"));

    // Move time forward another 0.1 seconds for a total of 5.
    when(_clock.millis()).thenReturn(now + 100L);
    // Now the health check should perform the ping queries again
    result = _healthCheck.execute();
    assertTrue(result.isHealthy());
    assertTrue(result.getMessage().contains("host2"));
    assertFalse(result.getMessage().contains("host1"));
}
 
Example #25
Source File: OxdServerApplication.java    From oxd with Apache License 2.0 5 votes vote down vote up
@Override
public void run(OxdServerConfiguration configuration, Environment environment) {
    ServerLauncher.configureServices(configuration);
    TracingUtil.configureGlobalTracer(configuration, "oxd-server");
    environment.healthChecks().register("dummy", new HealthCheck() {
        @Override
        protected Result check() {
            return Result.healthy();
        }
    });
    environment.jersey().register(RolesAllowedDynamicFeature.class);
    environment.jersey().register(RestResource.class);
}
 
Example #26
Source File: HealthCheckMetrics.java    From watcher with Apache License 2.0 5 votes vote down vote up
public HealthCheckMetrics() {
	ExtensionLoader extensionLoader = new ExtensionLoader();
	HealthCheckRepository healthCheckRepository = new HealthCheckRepository();
	extensionLoader.load(healthCheckRepository, HealthCheck.class);
	for (HealthCheck healthCheck : healthCheckRepository.set()) {
		healthCheckRegistry.register(getHealthCheckerName(healthCheck), healthCheck);
	}
}
 
Example #27
Source File: HealthCheckMetrics.java    From watcher with Apache License 2.0 5 votes vote down vote up
private String getHealthCheckerName(HealthCheck healthCheck) {
	String simpleName = healthCheck.getClass().getSimpleName();
	int idx = simpleName.lastIndexOf("HealthCheck");
	if (idx < 0) {
		return simpleName;
	} else {
		return simpleName.substring(0, idx);
	}
}
 
Example #28
Source File: HealthCheckProducerMethodBean.java    From metrics-cdi with Apache License 2.0 5 votes vote down vote up
@Produces
@Named("not_registered_healthcheck")
HealthCheck anInjectedCheck(HealthCheckRegistry registry, InjectionPoint ip) {
    HealthCheck check3 = new HealthCheck() {
        @Override
        protected Result check() {
            return Result.healthy("check3");
        }
    };
    registry.register("check3", check3);
    return check3;
}
 
Example #29
Source File: FoxtrotModule.java    From foxtrot with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure() {
    bind(TableMetadataManager.class)
            .to(DistributedTableMetadataManager.class);
    bind(DataStore.class)
            .to(HBaseDataStore.class);
    bind(QueryStore.class)
            .to(ElasticsearchQueryStore.class);
    bind(FqlStoreService.class)
            .to(FqlStoreServiceImpl.class);
    bind(CacheFactory.class)
            .to(DistributedCacheFactory.class);
    bind(InternalEventBus.class)
            .to(GuavaInternalEventBus.class);
    bind(InternalEventBusConsumer.class)
            .to(AlertingSystemEventConsumer.class);
    bind(ConsolePersistence.class)
            .to(ElasticsearchConsolePersistence.class);
    bind(EmailSubjectBuilder.class)
            .to(StrSubstitutorEmailSubjectBuilder.class);
    bind(EmailBodyBuilder.class)
            .to(StrSubstitutorEmailBodyBuilder.class);
    bind(TableManager.class)
            .to(FoxtrotTableManager.class);
    bind(new TypeLiteral<List<HealthCheck>>() {
    }).toProvider(HealthcheckListProvider.class);
}
 
Example #30
Source File: StatusResourceTest.java    From keywhiz with Apache License 2.0 5 votes vote down vote up
@Test
public void testStatusWarn() throws Exception {
  TreeMap<String, HealthCheck.Result> map = new TreeMap<>();
  map.put("test", HealthCheck.Result.unhealthy("failing"));

  when(registry.runHealthChecks()).thenReturn(map);
  Response r = status.get();
  assertThat(r.getStatus()).isEqualTo(500);
}