Search in sources :

Example 1 with HealthCheckRegistry

use of com.codahale.metrics.health.HealthCheckRegistry in project dr-elephant by linkedin.

the class MetricsController method init.

/**
 * Initializer method for the metrics registry. Call this method before registering
 * new metrics with the registry.
 */
public static void init() {
    // Metrics registries will be initialized only if enabled
    if (!Configuration.root().getBoolean("metrics", false)) {
        LOGGER.debug("Metrics not enabled in the conf file.");
        return;
    }
    // Metrics & healthcheck registries will be initialized only once
    if (_metricRegistry != null) {
        LOGGER.debug("Metric registries already initialized.");
        return;
    }
    _metricRegistry = new MetricRegistry();
    String className = AnalyticJob.class.getSimpleName();
    _skippedJobs = _metricRegistry.meter(name(className, "skippedJobs", "count"));
    _processedJobs = _metricRegistry.meter(name(className, "processedJobs", "count"));
    _jobProcessingTime = _metricRegistry.histogram(name(className, "jobProcessingTime", "ms"));
    _metricRegistry.register(name(className, "jobQueue", "size"), new Gauge<Integer>() {

        @Override
        public Integer getValue() {
            return _queueSize;
        }
    });
    _metricRegistry.register(name(className, "lastDayJobs", "count"), new Gauge<Integer>() {

        private static final long DAY = 24 * 60 * 60 * 1000;

        private static final long UPDATE_DELAY = 60 * 1000;

        private long _lastUpdate = 0;

        private int _count = -1;

        @Override
        public Integer getValue() {
            long now = System.currentTimeMillis();
            if (now - _lastUpdate > UPDATE_DELAY) {
                _count = AppResult.find.where().gt(AppResult.TABLE.FINISH_TIME, now - DAY).findRowCount();
                _lastUpdate = now;
            }
            return _count;
        }
    });
    _metricRegistry.register(name(className, "retryQueue", "size"), new Gauge<Integer>() {

        @Override
        public Integer getValue() {
            return _retryQueueSize;
        }
    });
    _metricRegistry.registerAll(new CustomGarbageCollectorMetricSet());
    _metricRegistry.registerAll(new MemoryUsageGaugeSet());
    JmxReporter.forRegistry(_metricRegistry).build().start();
    _healthCheckRegistry = new HealthCheckRegistry();
    _healthCheckRegistry.register("ThreadDeadlockHealthCheck", new ThreadDeadlockHealthCheck());
}
Also used : MemoryUsageGaugeSet(com.codahale.metrics.jvm.MemoryUsageGaugeSet) MetricRegistry(com.codahale.metrics.MetricRegistry) HealthCheckRegistry(com.codahale.metrics.health.HealthCheckRegistry) ThreadDeadlockHealthCheck(com.codahale.metrics.health.jvm.ThreadDeadlockHealthCheck) CustomGarbageCollectorMetricSet(com.linkedin.drelephant.metrics.CustomGarbageCollectorMetricSet)

Example 2 with HealthCheckRegistry

use of com.codahale.metrics.health.HealthCheckRegistry in project cals-api by ca-cwds.

the class BaseCalsApiApplication method runDataSourceHealthChecks.

private void runDataSourceHealthChecks(Environment environment) {
    HealthCheckRegistry healthCheckRegistry = environment.healthChecks();
    doHealthCheck(healthCheckRegistry, Constants.UnitOfWork.CALSNS);
    doHealthCheck(healthCheckRegistry, Constants.UnitOfWork.FAS);
    doHealthCheck(healthCheckRegistry, Constants.UnitOfWork.LIS);
    doHealthCheck(healthCheckRegistry, Constants.UnitOfWork.CMS);
}
Also used : HealthCheckRegistry(com.codahale.metrics.health.HealthCheckRegistry)

Example 3 with HealthCheckRegistry

use of com.codahale.metrics.health.HealthCheckRegistry in project dropwizard by dropwizard.

the class DefaultHealthFactory method configure.

@Override
public void configure(final LifecycleEnvironment lifecycle, final ServletEnvironment servlets, final JerseyEnvironment jersey, final HealthEnvironment health, final ObjectMapper mapper, final String name) {
    if (!isEnabled()) {
        LOGGER.info("Health check configuration is disabled.");
        return;
    }
    final MetricRegistry metrics = lifecycle.getMetricRegistry();
    final HealthCheckRegistry envHealthChecks = health.healthChecks();
    final String fullName = DEFAULT_BASE_NAME + "-" + name;
    final List<HealthCheckConfiguration> healthCheckConfigs = getHealthCheckConfigurations();
    // setup schedules for configured health checks
    final ScheduledExecutorService scheduledHealthCheckExecutor = createScheduledExecutorForHealthChecks(healthCheckConfigs.size(), metrics, lifecycle, fullName);
    final HealthCheckScheduler scheduler = new HealthCheckScheduler(scheduledHealthCheckExecutor);
    // configure health manager to receive registered health state listeners from HealthEnvironment (via reference)
    final HealthCheckManager healthCheckManager = new HealthCheckManager(healthCheckConfigs, scheduler, metrics, shutdownWaitPeriod, initialOverallState, health.healthStateListeners());
    healthCheckManager.initializeAppHealth();
    // setup response provider and responder to respond to health check requests
    final HealthResponseProvider responseProvider = healthResponseProviderFactory.build(healthCheckManager, healthCheckManager, mapper);
    healthResponderFactory.configure(fullName, healthCheckUrlPaths, responseProvider, health, jersey, servlets, mapper);
    // register listener for HealthCheckRegistry and setup validator to ensure correct config
    envHealthChecks.addListener(healthCheckManager);
    lifecycle.manage(new HealthCheckConfigValidator(healthCheckConfigs, envHealthChecks));
    // register shutdown handler with Jetty
    final Duration shutdownDelay = getShutdownWaitPeriod();
    if (isDelayedShutdownHandlerEnabled() && shutdownDelay.toMilliseconds() > 0) {
        final DelayedShutdownHandler shutdownHandler = new DelayedShutdownHandler(healthCheckManager);
        shutdownHandler.register();
        LOGGER.debug("Set up delayed shutdown with delay: {}", shutdownDelay);
    }
    // Set the health state aggregator on the HealthEnvironment
    health.setHealthStateAggregator(healthCheckManager);
    LOGGER.debug("Configured ongoing health check monitoring for healthChecks: {}", getHealthChecks());
}
Also used : ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) InstrumentedScheduledExecutorService(com.codahale.metrics.InstrumentedScheduledExecutorService) HealthResponseProvider(io.dropwizard.health.response.HealthResponseProvider) MetricRegistry(com.codahale.metrics.MetricRegistry) HealthCheckRegistry(com.codahale.metrics.health.HealthCheckRegistry) Duration(io.dropwizard.util.Duration)

Example 4 with HealthCheckRegistry

use of com.codahale.metrics.health.HealthCheckRegistry in project dropwizard by dropwizard.

the class HealthCheckConfigValidatorTest method startValidationsShouldSucceedForConfiguredAndRegisteredHealthCheck.

@Test
void startValidationsShouldSucceedForConfiguredAndRegisteredHealthCheck() throws Exception {
    // given
    List<HealthCheckConfiguration> configs = new ArrayList<>();
    HealthCheckConfiguration check1 = new HealthCheckConfiguration();
    check1.setName("check-1");
    configs.add(check1);
    HealthCheckConfiguration check2 = new HealthCheckConfiguration();
    check2.setName("check-2");
    configs.add(check2);
    HealthCheckRegistry registry = new HealthCheckRegistry();
    registry.register("check-1", mock(HealthCheck.class));
    registry.register("check-2", mock(HealthCheck.class));
    // when
    HealthCheckConfigValidator validator = new HealthCheckConfigValidator(unmodifiableList(configs), registry);
    validator.start();
    // then
    verifyNoInteractions(mockLogAppender);
}
Also used : HealthCheckRegistry(com.codahale.metrics.health.HealthCheckRegistry) ArrayList(java.util.ArrayList) HealthCheck(com.codahale.metrics.health.HealthCheck) Test(org.junit.jupiter.api.Test)

Example 5 with HealthCheckRegistry

use of com.codahale.metrics.health.HealthCheckRegistry in project dropwizard by dropwizard.

the class JdbiFactoryTest method testBuild.

@Test
void testBuild() {
    final Environment environment = mock(Environment.class);
    final MetricRegistry metrics = mock(MetricRegistry.class);
    final LifecycleEnvironment lifecycle = mock(LifecycleEnvironment.class);
    final HealthCheckRegistry healthChecks = mock(HealthCheckRegistry.class);
    final PooledDataSourceFactory configuration = mock(PooledDataSourceFactory.class);
    final String name = UUID.randomUUID().toString();
    final ManagedDataSource dataSource = mock(ManagedDataSource.class);
    final String validationQuery = UUID.randomUUID().toString();
    final Jdbi jdbi = mock(Jdbi.class);
    final SqlStatements sqlStatements = new SqlStatements();
    when(environment.metrics()).thenReturn(metrics);
    when(environment.lifecycle()).thenReturn(lifecycle);
    when(environment.healthChecks()).thenReturn(healthChecks);
    when(configuration.build(metrics, name)).thenReturn(dataSource);
    when(configuration.getValidationQuery()).thenReturn(Optional.of(validationQuery));
    when(configuration.isAutoCommentsEnabled()).thenReturn(true);
    when(jdbi.getConfig(SqlStatements.class)).thenReturn(sqlStatements);
    final JdbiFactory factory = spy(new JdbiFactory());
    when(factory.newInstance(dataSource)).thenReturn(jdbi);
    final Jdbi result = factory.build(environment, configuration, name);
    assertThat(result).isSameAs(jdbi);
    verify(lifecycle).manage(dataSource);
    verify(healthChecks).register(eq(name), any(JdbiHealthCheck.class));
    verify(jdbi).setSqlLogger(any(InstrumentedSqlLogger.class));
    verify(factory).buildSQLLogger(same(metrics), any(StatementNameStrategy.class));
    verify(jdbi).setTemplateEngine(any(NamePrependingTemplateEngine.class));
    verify(factory).configure(jdbi);
}
Also used : Jdbi(org.jdbi.v3.core.Jdbi) StatementNameStrategy(com.codahale.metrics.jdbi3.strategies.StatementNameStrategy) MetricRegistry(com.codahale.metrics.MetricRegistry) HealthCheckRegistry(com.codahale.metrics.health.HealthCheckRegistry) InstrumentedSqlLogger(com.codahale.metrics.jdbi3.InstrumentedSqlLogger) SqlStatements(org.jdbi.v3.core.statement.SqlStatements) LifecycleEnvironment(io.dropwizard.lifecycle.setup.LifecycleEnvironment) Environment(io.dropwizard.setup.Environment) LifecycleEnvironment(io.dropwizard.lifecycle.setup.LifecycleEnvironment) PooledDataSourceFactory(io.dropwizard.db.PooledDataSourceFactory) ManagedDataSource(io.dropwizard.db.ManagedDataSource) Test(org.junit.jupiter.api.Test)

Aggregations

HealthCheckRegistry (com.codahale.metrics.health.HealthCheckRegistry)31 Test (org.junit.Test)11 MetricRegistry (com.codahale.metrics.MetricRegistry)6 HealthCheck (com.codahale.metrics.health.HealthCheck)6 Test (org.junit.jupiter.api.Test)6 HikariDataSource (com.zaxxer.hikari.HikariDataSource)3 ServletContext (jakarta.servlet.ServletContext)3 ServletContext (javax.servlet.ServletContext)3 ILoggingEvent (ch.qos.logback.classic.spi.ILoggingEvent)2 LoggingEvent (ch.qos.logback.classic.spi.LoggingEvent)2 Result (com.codahale.metrics.health.HealthCheck.Result)2 HealthCheckFilter (com.codahale.metrics.health.HealthCheckFilter)2 HealthCheckModule (com.codahale.metrics.json.HealthCheckModule)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 ServletConfig (jakarta.servlet.ServletConfig)2 Connection (java.sql.Connection)2 ExecutorService (java.util.concurrent.ExecutorService)2 Connector (org.eclipse.jetty.server.Connector)2 HttpConnectionFactory (org.eclipse.jetty.server.HttpConnectionFactory)2 Server (org.eclipse.jetty.server.Server)2