下面列出了怎么用com.codahale.metrics.health.HealthCheck的API类实例代码及写法,或者点击链接到github查看源代码。
@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());
}
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));
}
}
});
}
@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();
}
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();
}
@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
}
@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
}
@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
}
@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");
}
}
}
@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);
}
@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());
}
}
@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));
}
@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");
}
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 );
}
@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);
}
}
});
}
@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/*");
}
@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);
}
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();
}
});
}
@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));
}
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;
}
@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!");
}
@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!");
}
protected HealthCheck.Result check() throws Exception {
if (reconciler.isReconciled()) {
return HealthCheck.Result.healthy("Framework reconciled");
}
return HealthCheck.Result.unhealthy("Reconciliation in progress");
}
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");
}
@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"));
}
@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);
}
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);
}
}
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);
}
}
@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;
}
@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);
}
@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);
}