Search in sources :

Example 1 with Duration

use of io.dropwizard.util.Duration in project dropwizard by dropwizard.

the class DataSourceFactory method build.

@Override
public ManagedDataSource build(MetricRegistry metricRegistry, String name) {
    final Properties dbProperties = new Properties();
    properties.forEach(dbProperties::setProperty);
    final PoolProperties poolConfig = new PoolProperties();
    poolConfig.setAbandonWhenPercentageFull(abandonWhenPercentageFull);
    poolConfig.setAlternateUsernameAllowed(alternateUsernamesAllowed);
    poolConfig.setCommitOnReturn(commitOnReturn);
    poolConfig.setRollbackOnReturn(rollbackOnReturn);
    poolConfig.setDbProperties(dbProperties);
    poolConfig.setDefaultAutoCommit(autoCommitByDefault);
    poolConfig.setDefaultCatalog(defaultCatalog);
    poolConfig.setDefaultReadOnly(readOnlyByDefault);
    poolConfig.setDefaultTransactionIsolation(defaultTransactionIsolation.get());
    poolConfig.setDriverClassName(driverClass);
    poolConfig.setFairQueue(useFairQueue);
    poolConfig.setIgnoreExceptionOnPreLoad(ignoreExceptionOnPreLoad);
    poolConfig.setInitialSize(initialSize);
    poolConfig.setInitSQL(initializationQuery);
    poolConfig.setLogAbandoned(logAbandonedConnections);
    poolConfig.setLogValidationErrors(logValidationErrors);
    poolConfig.setMaxActive(maxSize);
    poolConfig.setMaxIdle(maxSize);
    poolConfig.setMinIdle(minSize);
    getMaxConnectionAge().map(Duration::toMilliseconds).ifPresent(poolConfig::setMaxAge);
    poolConfig.setMaxWait((int) maxWaitForConnection.toMilliseconds());
    poolConfig.setMinEvictableIdleTimeMillis((int) minIdleTime.toMilliseconds());
    poolConfig.setName(name);
    poolConfig.setUrl(url);
    poolConfig.setUsername(user);
    poolConfig.setPassword(user != null && password == null ? "" : password);
    poolConfig.setRemoveAbandoned(removeAbandoned);
    poolConfig.setRemoveAbandonedTimeout((int) removeAbandonedTimeout.toSeconds());
    poolConfig.setTestWhileIdle(checkConnectionWhileIdle);
    validationQuery.ifPresent(poolConfig::setValidationQuery);
    poolConfig.setTestOnBorrow(checkConnectionOnBorrow);
    poolConfig.setTestOnConnect(checkConnectionOnConnect);
    poolConfig.setTestOnReturn(checkConnectionOnReturn);
    poolConfig.setTimeBetweenEvictionRunsMillis((int) evictionInterval.toMilliseconds());
    poolConfig.setValidationInterval(validationInterval.toMilliseconds());
    getValidationQueryTimeout().map(x -> (int) x.toSeconds()).ifPresent(poolConfig::setValidationQueryTimeout);
    validatorClassName.ifPresent(poolConfig::setValidatorClassName);
    jdbcInterceptors.ifPresent(poolConfig::setJdbcInterceptors);
    return new ManagedPooledDataSource(poolConfig, metricRegistry);
}
Also used : JsonProperty(com.fasterxml.jackson.annotation.JsonProperty) MetricRegistry(com.codahale.metrics.MetricRegistry) Connection(java.sql.Connection) Properties(java.util.Properties) Min(javax.validation.constraints.Min) NotNull(javax.validation.constraints.NotNull) Duration(io.dropwizard.util.Duration) PoolProperties(org.apache.tomcat.jdbc.pool.PoolProperties) NotEmpty(javax.validation.constraints.NotEmpty) LinkedHashMap(java.util.LinkedHashMap) Objects(java.util.Objects) TimeUnit(java.util.concurrent.TimeUnit) ValidationMethod(io.dropwizard.validation.ValidationMethod) Map(java.util.Map) JsonIgnore(com.fasterxml.jackson.annotation.JsonIgnore) Max(javax.validation.constraints.Max) Optional(java.util.Optional) MinDuration(io.dropwizard.validation.MinDuration) Nullable(javax.annotation.Nullable) Properties(java.util.Properties) PoolProperties(org.apache.tomcat.jdbc.pool.PoolProperties) PoolProperties(org.apache.tomcat.jdbc.pool.PoolProperties)

Example 2 with Duration

use of io.dropwizard.util.Duration 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 3 with Duration

use of io.dropwizard.util.Duration in project dropwizard by dropwizard.

the class HealthCheckManagerTest method shouldContinueScheduledCheckingWhileDelayingShutdown.

@Test
@DisabledOnOs(OS.WINDOWS)
void shouldContinueScheduledCheckingWhileDelayingShutdown() throws Exception {
    // given
    final int checkIntervalMillis = 10;
    final int shutdownWaitTimeMillis = 50;
    final int expectedCount = shutdownWaitTimeMillis / checkIntervalMillis - 1;
    final AtomicBoolean shutdownFailure = new AtomicBoolean(false);
    final CountingHealthCheck check = new CountingHealthCheck();
    final Schedule schedule = new Schedule();
    schedule.setCheckInterval(Duration.milliseconds(checkIntervalMillis));
    final HealthCheckConfiguration checkConfig = new HealthCheckConfiguration();
    checkConfig.setName("check1");
    checkConfig.setCritical(true);
    checkConfig.setSchedule(schedule);
    final List<HealthCheckConfiguration> configs = singletonList(checkConfig);
    final ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1);
    final HealthCheckScheduler scheduler = new HealthCheckScheduler(executorService);
    final MetricRegistry metrics = new MetricRegistry();
    final Duration shutdownWaitPeriod = Duration.milliseconds(shutdownWaitTimeMillis);
    // when
    final HealthCheckManager manager = new HealthCheckManager(configs, scheduler, metrics, shutdownWaitPeriod, true, Collections.emptyList());
    manager.onHealthCheckAdded("check1", check);
    // simulate JVM shutdown hook
    final Thread shutdownThread = new Thread(() -> {
        try {
            manager.notifyShutdownStarted();
        } catch (Exception e) {
            shutdownFailure.set(true);
            e.printStackTrace();
        }
    });
    Thread.sleep(20);
    long beforeCount = check.getCount();
    shutdownThread.start();
    shutdownThread.join();
    Thread.sleep(20);
    long afterCount = check.getCount();
    // then
    assertThat(shutdownFailure).isFalse();
    assertThat(afterCount - beforeCount).isGreaterThanOrEqualTo(expectedCount);
}
Also used : ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ScheduledThreadPoolExecutor(java.util.concurrent.ScheduledThreadPoolExecutor) MetricRegistry(com.codahale.metrics.MetricRegistry) Duration(io.dropwizard.util.Duration) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) DisabledOnOs(org.junit.jupiter.api.condition.DisabledOnOs) Test(org.junit.jupiter.api.Test)

Example 4 with Duration

use of io.dropwizard.util.Duration in project dropwizard by dropwizard.

the class HttpClientBuilder method createConnectionManager.

/**
 * Create a InstrumentedHttpClientConnectionManager based on the
 * HttpClientConfiguration. It sets the maximum connections per route and
 * the maximum total connections that the connection manager can create
 *
 * @param registry
 * @param name
 * @return a InstrumentedHttpClientConnectionManger instance
 */
protected InstrumentedHttpClientConnectionManager createConnectionManager(Registry<ConnectionSocketFactory> registry, String name) {
    final Duration ttl = configuration.getTimeToLive();
    final InstrumentedHttpClientConnectionManager manager = InstrumentedHttpClientConnectionManager.builder(metricRegistry).socketFactoryRegistry(registry).dnsResolver(resolver).connTTL(ttl.getQuantity()).connTTLTimeUnit(ttl.getUnit()).name(name).build();
    return configureConnectionManager(manager);
}
Also used : InstrumentedHttpClientConnectionManager(com.codahale.metrics.httpclient.InstrumentedHttpClientConnectionManager) Duration(io.dropwizard.util.Duration)

Example 5 with Duration

use of io.dropwizard.util.Duration in project dropwizard by dropwizard.

the class HealthCheckScheduler method schedule.

public void schedule(final ScheduledHealthCheck check, final boolean healthy) {
    unschedule(check.getName());
    final Duration interval;
    if (healthy) {
        interval = check.getSchedule().getCheckInterval();
    } else {
        interval = check.getSchedule().getDowntimeInterval();
    }
    schedule(check, interval, interval);
}
Also used : Duration(io.dropwizard.util.Duration)

Aggregations

Duration (io.dropwizard.util.Duration)8 MetricRegistry (com.codahale.metrics.MetricRegistry)3 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)2 Test (org.junit.jupiter.api.Test)2 PartitionedTable (com.airbnb.airpal.presto.PartitionedTable)1 Table (com.airbnb.airpal.presto.Table)1 InstrumentedScheduledExecutorService (com.codahale.metrics.InstrumentedScheduledExecutorService)1 HealthCheckRegistry (com.codahale.metrics.health.HealthCheckRegistry)1 InstrumentedHttpClientConnectionManager (com.codahale.metrics.httpclient.InstrumentedHttpClientConnectionManager)1 JsonIgnore (com.fasterxml.jackson.annotation.JsonIgnore)1 JsonProperty (com.fasterxml.jackson.annotation.JsonProperty)1 ImmutableList (com.google.common.collect.ImmutableList)1 HealthResponseProvider (io.dropwizard.health.response.HealthResponseProvider)1 MinDuration (io.dropwizard.validation.MinDuration)1 ValidationMethod (io.dropwizard.validation.ValidationMethod)1 Connection (java.sql.Connection)1 LinkedHashMap (java.util.LinkedHashMap)1 Map (java.util.Map)1 Objects (java.util.Objects)1 Optional (java.util.Optional)1