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);
}
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());
}
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);
}
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);
}
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);
}
Aggregations