Java Code Examples for com.codahale.metrics.health.HealthCheckRegistry#register()

The following examples show how to use com.codahale.metrics.health.HealthCheckRegistry#register() . 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: MonetaSpringBootApplication.java    From moneta with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
	SpringApplication.run(MonetaSpringBootApplication.class, args);

	// Find and read application configuration
	MonetaConfiguration config = new MonetaConfiguration();

	// Install all health checks
	HealthCheckRegistry registry = new HealthCheckRegistry();
	for (String checkName : MonetaEnvironment.getConfiguration()
			.getHealthChecks()
			.keySet()) {
		registry.register(checkName, MonetaEnvironment.getConfiguration()
				.getHealthChecks()
				.get(checkName));
	}
	ActuatorHealthIndicator.setHealthCheckRegistry(registry);

	// Install metrics and JMX
	MetricRegistry metricRegistry = new MetricRegistry();
	final JmxReporter jmxReporter = JmxReporter.forRegistry(metricRegistry)
			.build();
	jmxReporter.start();
}
 
Example 2
Source File: Poseidon.java    From Poseidon with Apache License 2.0 6 votes vote down vote up
private ServletContextHandler getMetricsHandler() {
    MetricRegistry registry = Metrics.getRegistry();
    HealthCheckRegistry healthCheckRegistry = Metrics.getHealthCheckRegistry();
    healthCheckRegistry.register("rotation", new Rotation(configuration.getRotationStatusFilePath()));

    registry.registerAll(new GarbageCollectorMetricSet());
    registry.registerAll(new MemoryUsageGaugeSet());
    registry.registerAll(new ThreadStatesGaugeSet());
    registry.registerAll(new JvmAttributeGaugeSet());

    ServletContextHandler servletContextHandler = new ServletContextHandler();
    servletContextHandler.setContextPath("/__metrics");
    servletContextHandler.setAttribute(MetricsServlet.class.getCanonicalName() + ".registry", registry);
    servletContextHandler.setAttribute(HealthCheckServlet.class.getCanonicalName() + ".registry", healthCheckRegistry);
    servletContextHandler.addServlet(new ServletHolder(new AdminServlet()), "/*");

    return servletContextHandler;
}
 
Example 3
Source File: ChassisConfiguration.java    From chassis with Apache License 2.0 5 votes vote down vote up
/**
 * Initializes the health check registry
 *
 * @return health check registry bean
 */
@Bean
public HealthCheckRegistry healthCheckRegistry(ApplicationContext context, DiscoveryManager eureka) {
    final HealthCheckRegistry bean = new HealthCheckRegistry();

    // auto-register beans implementing health checks
    Map<String, HealthCheck> healthChecks = context.getBeansOfType(HealthCheck.class);
    for (HealthCheck check : healthChecks.values()) {
        bean.register(check.getClass().getName(), check);
    }

    // connect health checks into Eureka
    if (!disableEureka) {
        eureka.getDiscoveryClient().registerHealthCheckCallback(
                new HealthCheckCallback() {
                    @Override
                    public boolean isHealthy() {
                        for (Entry<String, HealthCheck.Result> entry : bean.runHealthChecks().entrySet()) {
                            if (!entry.getValue().isHealthy()) {
                                return false;
                            }
                        }
                        return true;
                    }
                });
    }

    return bean;
}
 
Example 4
Source File: MorphlineTest.java    From kite with Apache License 2.0 5 votes vote down vote up
@Test
public void testMorphlineContext() throws Exception {
  ExceptionHandler ex = new ExceptionHandler() {      
    @Override
    public void handleException(Throwable t, Record record) {
      throw new RuntimeException(t);        
    }
  };
  
  MetricRegistry metricRegistry = new MetricRegistry();
  metricRegistry.register("myCounter", new Counter());
  
  HealthCheckRegistry healthChecks = new HealthCheckRegistry();
  healthChecks.register("foo", new HealthCheck() {      
    @Override
    protected Result check() throws Exception {
      return Result.healthy("flawless");
    }
  });

  Map<String,Object> settings = new HashMap<String,Object>(); 
  
  MorphlineContext ctx = new MorphlineContext.Builder()
    .setSettings(settings)
    .setExceptionHandler(ex)
    .setHealthCheckRegistry(healthChecks)
    .setMetricRegistry(metricRegistry)
    .build();
  
  assertSame(settings, ctx.getSettings());
  assertSame(ex, ctx.getExceptionHandler());
  assertSame(metricRegistry, ctx.getMetricRegistry());
  assertSame(healthChecks, ctx.getHealthCheckRegistry());
  ctx.getHealthCheckRegistry().runHealthChecks();
  
  assertEquals(0, new MorphlineContext.Builder().build().getSettings().size());
}
 
Example 5
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 6
Source File: HealthCheckTest.java    From hammock with Apache License 2.0 5 votes vote down vote up
@Before
public void addHealthCheck() {
    HealthCheckRegistry registry = CDI.current().select(HealthCheckRegistry.class).get();
    registry.register("hammock", new HealthCheck() {
        @Override
        protected Result check() throws Exception {
            return Result.healthy("Hammock is online");
        }
    });
}
 
Example 7
Source File: TotalHealthCheckGaugeTest.java    From helios with Apache License 2.0 5 votes vote down vote up
@Test
public void testAllFail() {
  final HealthCheckRegistry registry = new HealthCheckRegistry();
  registry.register("fail1", stubHealthCheck(HealthCheck.Result.unhealthy("error")));
  registry.register("fail2", stubHealthCheck(HealthCheck.Result.unhealthy("error")));

  final TotalHealthCheckGauge gauge = new TotalHealthCheckGauge(registry);
  assertThat(gauge.getValue(), is(0));
}
 
Example 8
Source File: TotalHealthCheckGaugeTest.java    From helios with Apache License 2.0 5 votes vote down vote up
@Test
public void testOneFails() {
  final HealthCheckRegistry registry = new HealthCheckRegistry();
  registry.register("pass1", stubHealthCheck(HealthCheck.Result.healthy()));
  registry.register("fail1", stubHealthCheck(HealthCheck.Result.unhealthy("error")));

  final TotalHealthCheckGauge gauge = new TotalHealthCheckGauge(registry);
  assertThat(gauge.getValue(), is(0));
}
 
Example 9
Source File: TotalHealthCheckGaugeTest.java    From helios with Apache License 2.0 5 votes vote down vote up
@Test
public void testAllHealthy() {
  final HealthCheckRegistry registry = new HealthCheckRegistry();
  registry.register("pass1", stubHealthCheck(HealthCheck.Result.healthy()));
  registry.register("pass2", stubHealthCheck(HealthCheck.Result.healthy()));

  final TotalHealthCheckGauge gauge = new TotalHealthCheckGauge(registry);
  assertThat(gauge.getValue(), is(1));
}
 
Example 10
Source File: MetricsConfiguration.java    From chassis with Apache License 2.0 5 votes vote down vote up
/***
    * Initializes the health check registry
    *
    * @return health check registry bean
    */
@Bean
public HealthCheckRegistry healthCheckRegistry(ApplicationContext context) {
	final HealthCheckRegistry bean = new HealthCheckRegistry();

       // auto-register beans implementing health checks
       Map<String,HealthCheck> healthChecks = context.getBeansOfType(HealthCheck.class);
       for (HealthCheck check : healthChecks.values()) {
           bean.register( check.getClass().getName(), check );
       }

       return bean;
   }
 
Example 11
Source File: Main.java    From incubator-myriad with Apache License 2.0 5 votes vote down vote up
/**
 * Initializes health checks.
 *
 * @param injector
 */
private void initHealthChecks(Injector injector) {
  LOGGER.info("Initializing HealthChecks");
  healthCheckRegistry = new HealthCheckRegistry();
  healthCheckRegistry.register(MesosMasterHealthCheck.NAME, injector.getInstance(MesosMasterHealthCheck.class));
  healthCheckRegistry.register(ZookeeperHealthCheck.NAME, injector.getInstance(ZookeeperHealthCheck.class));
  healthCheckRegistry.register(MesosDriverHealthCheck.NAME, injector.getInstance(MesosDriverHealthCheck.class));
}
 
Example 12
Source File: CassandraConnectorTask.java    From debezium-incubator with Apache License 2.0 4 votes vote down vote up
private HealthCheckRegistry registerHealthCheck() {
    CassandraConnectorTaskHealthCheck healthCheck = new CassandraConnectorTaskHealthCheck(processorGroup, taskContext.getCassandraClient());
    HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry();
    healthCheckRegistry.register("cassandra-cdc-health-check", healthCheck);
    return healthCheckRegistry;
}
 
Example 13
Source File: CassandraFactory.java    From dropwizard-cassandra with Apache License 2.0 4 votes vote down vote up
/**
 * Builds a {@link Cluster} instance.
 * <p/>
 * The {@link MetricRegistry} will be used to register client metrics, and the {@link
 * HealthCheckRegistry} to register client health-checks.
 *
 * @param metrics the registry to register client metrics.
 * @param healthChecks the registry to register client health-checks.
 * @return a fully configured {@link Cluster}.
 */
public Cluster build(MetricRegistry metrics, HealthCheckRegistry healthChecks) {

    final Cluster.Builder builder = Cluster.builder();

    for (String contactPoint : contactPoints) {
        builder.addContactPoints(contactPoint);
    }

    builder.withPort(port);
    builder.withCompression(compression);

    protocolVersion.ifPresent(builder::withProtocolVersion);
    ssl.map(SSLOptionsFactory::build).ifPresent(builder::withSSL);
    maxSchemaAgreementWait.map(Duration::toSeconds).map(Long::intValue).ifPresent(builder::withMaxSchemaAgreementWaitSeconds);
    authProvider.map(AuthProviderFactory::build).ifPresent(builder::withAuthProvider);
    reconnectionPolicy.map(ReconnectionPolicyFactory::build).ifPresent(builder::withReconnectionPolicy);
    retryPolicy.map(RetryPolicyFactory::build).ifPresent(builder::withRetryPolicy);
    loadBalancingPolicy.map(LoadBalancingPolicyFactory::build).ifPresent(builder::withLoadBalancingPolicy);
    speculativeExecutionPolicy.map(SpeculativeExecutionPolicyFactory::build).ifPresent(builder::withSpeculativeExecutionPolicy);
    queryOptions.ifPresent(builder::withQueryOptions);
    socketOptions.ifPresent(builder::withSocketOptions);
    poolingOptions.map(PoolingOptionsFactory::build).ifPresent(builder::withPoolingOptions);
    addressTranslator.map(AddressTranslatorFactory::build).ifPresent(builder::withAddressTranslator);

    if (!metricsEnabled) {
        builder.withoutMetrics();
    }

    if (!jmxEnabled) {
        builder.withoutJMXReporting();
    }

    if (!Strings.isNullOrEmpty(clusterName)) {
        builder.withClusterName(clusterName);
    }

    Cluster cluster = builder.build();

    LOG.debug("Registering {} Cassandra health check", cluster.getClusterName());
    CassandraHealthCheck healthCheck = new CassandraHealthCheck(cluster, validationQuery, healthCheckTimeout);
    healthChecks.register(name("cassandra", cluster.getClusterName()), healthCheck);

    if (isMetricsEnabled()) {
        LOG.debug("Registering {} Cassandra metrics", cluster.getClusterName());
        metrics.registerAll(new CassandraMetricSet(cluster));
    }

    return cluster;
}
 
Example 14
Source File: Main.java    From billow with Apache License 2.0 4 votes vote down vote up
private Main(Config config) throws Exception {
    log.info("Startup...");

    try {
        System.out.println(Resources.toString(getResource("banner.txt"), Charsets.UTF_8));
    } catch (IllegalArgumentException | IOException e) {
        log.debug("No banner.txt", e);
    }

    final MetricRegistry metricRegistry = new MetricRegistry();
    final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry();

    log.info("Creating database");

    final Config awsConfig = config.getConfig("aws");
    final Long refreshRate = awsConfig.getDuration("refreshRate", TimeUnit.MILLISECONDS);

    final AWSDatabaseHolder dbHolder = new AWSDatabaseHolder(awsConfig);

    final Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
    scheduler.getContext().put(AWSDatabaseHolderRefreshJob.DB_KEY, dbHolder);
    scheduler.start();

    final SimpleTrigger trigger = newTrigger().
            withIdentity(AWSDatabaseHolderRefreshJob.NAME).
            startNow().
            withSchedule(simpleSchedule().withIntervalInMilliseconds(refreshRate).repeatForever()).
            build();

    final JobDetail jobDetail = newJob(AWSDatabaseHolderRefreshJob.class).
            withIdentity(AWSDatabaseHolderRefreshJob.NAME).
            build();

    scheduler.scheduleJob(jobDetail, trigger);

    log.info("Creating age health check");
    healthCheckRegistry.register("DB", new HealthCheck() {
        @Override
        protected Result check() throws Exception {
            return dbHolder.healthy();
        }
    });

    log.info("Creating HTTP servers");
    final Server mainServer = new Server(config.getInt("mainPort"));
    final Server adminServer = new Server(config.getInt("adminPort"));

    configureConnectors(mainServer);
    configureConnectors(adminServer);

    log.info("Creating HTTP handlers");
    final Handler mainHandler = new Handler(metricRegistry, dbHolder, refreshRate);
    final InstrumentedHandler instrumentedHandler =
            new InstrumentedHandler(metricRegistry);
    instrumentedHandler.setHandler(mainHandler);

    mainServer.setHandler(instrumentedHandler);

    final ServletContextHandler adminHandler = new ServletContextHandler();
    adminHandler.addServlet(new ServletHolder(new AdminServlet()), "/*");

    final ServletContext adminContext = adminHandler.getServletContext();
    adminContext.setAttribute(MetricsServlet.METRICS_REGISTRY, metricRegistry);
    adminContext.setAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY, healthCheckRegistry);
    adminServer.setHandler(adminHandler);

    log.info("Starting HTTP servers");

    adminServer.start();
    mainServer.start();

    log.info("Joining...");

    mainServer.join();
    adminServer.join();

    log.info("Shutting down scheduler...");

    scheduler.shutdown();

    log.info("We're done!");
}
 
Example 15
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));
}
 
Example 16
Source File: HealthCheckMediator.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
public void add(final BeanEntry<Named, HealthCheck> entry, final HealthCheckRegistry registry) throws Exception {
  log.debug("Registering: {}", entry);
  registry.register(entry.getKey().value(), entry.getValue());
}
 
Example 17
Source File: HealthCheckConfiguration.java    From haven-platform with Apache License 2.0 4 votes vote down vote up
@Autowired
public void setHealthCheckRegistry(HealthCheckRegistry registry) {
    registry.register(ThreadDeadlockHealthCheck.class.getName(), new ThreadDeadlockHealthCheck());
}