类com.codahale.metrics.health.HealthCheck源码实例Demo

下面列出了怎么用com.codahale.metrics.health.HealthCheck的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: okta-auth-java   文件: ExampleApplication.java
@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());
}
 
源代码2 项目: jobson   文件: JobManager.java
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));
                    }
                }
            });
}
 
源代码3 项目: jobson   文件: JobManagerTest.java
@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();
}
 
源代码4 项目: StubbornJava   文件: HealthChecksServer.java
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();
}
 
源代码5 项目: emodb   文件: CasBlobStoreTest.java
@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
}
 
源代码6 项目: emodb   文件: CasDatabusTest.java
@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
}
 
源代码7 项目: emodb   文件: CasDataStoreTest.java
@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
}
 
源代码8 项目: pippo   文件: HealthCheckHandler.java
@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");
        }
    }
}
 
源代码9 项目: foxtrot   文件: ClusterManager.java
@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);
}
 
源代码10 项目: watcher   文件: HealthCheckMetrics.java
@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());
	}
}
 
源代码11 项目: pay-publicapi   文件: HealthCheckResourceTest.java
@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");
}
 
源代码13 项目: attic-polygene-java   文件: CodahaleHealthCheck.java
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 );
}
 
源代码14 项目: dropwizard-guicier   文件: DropwizardModule.java
@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);
      }
    }
  });
}
 
源代码15 项目: macrobase   文件: MacroBaseServer.java
@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/*");
}
 
源代码16 项目: dropwizard-websockets   文件: MyApp.java
@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);
}
 
源代码17 项目: xrpc   文件: Application.java
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();
        }
      });
}
 
源代码18 项目: jobson   文件: FilesystemJobSpecDAO.java
@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;
}
 
源代码20 项目: trellis   文件: RDFConnectionHealthCheckTest.java
@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!");
}
 
源代码21 项目: trellis   文件: RDFConnectionHealthCheckTest.java
@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!");
}
 
源代码22 项目: dcos-cassandra-service   文件: ReconciledCheck.java
protected HealthCheck.Result check() throws Exception {

        if (reconciler.isReconciled()) {
            return HealthCheck.Result.healthy("Framework reconciled");
        }
        return HealthCheck.Result.unhealthy("Reconciliation in progress");
    }
 
源代码23 项目: billow   文件: AWSDatabaseHolder.java
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");
}
 
源代码24 项目: emodb   文件: TestCassandraHealthCheck.java
@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"));
}
 
源代码25 项目: oxd   文件: OxdServerApplication.java
@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);
}
 
源代码26 项目: watcher   文件: HealthCheckMetrics.java
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);
	}
}
 
源代码27 项目: watcher   文件: HealthCheckMetrics.java
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;
}
 
源代码29 项目: foxtrot   文件: FoxtrotModule.java
@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);
}
 
源代码30 项目: keywhiz   文件: StatusResourceTest.java
@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);
}
 
 类所在包
 同包方法