public DBClient build(Environment environment) { String dbServer = System.getenv("DB"); if (dbServer != null) { server = dbServer; } dbClient = dbFactory.create(server, port, dbName); log.info("Connected to db"); environment.lifecycle().manage(new Managed() { @Override public void start() throws Exception { dbClient.useDB(dbName); } @Override public void stop() throws Exception { dbClient.close(); } }); return dbClient; }
@Override public void run(final Configuration configuration, final Environment environment) { environment.jersey().register(new RateLimitingFactoryProvider.Binder(requestRateLimiterFactory)); environment.jersey().register(new RateLimited429EnforcerFeature()); environment.lifecycle().manage(new Managed() { @Override public void start() { } @Override public void stop() throws Exception { requestRateLimiterFactory.close(); } }); }
@Inject public ReplicationEnabledTask(TaskRegistry tasks, LifeCycleRegistry lifeCycle, @ReplicationEnabled ValueStore<Boolean> enabled) { super("busrepl"); _enabled = checkNotNull(enabled, "enabled"); tasks.addTask(this); // Default is enabled, so warn if disabled since otherwise essential functionality won't work. lifeCycle.manage(new Managed() { @Override public void start() throws Exception { if (!_enabled.get()) { _log.warn("Databus inbound event replication from other data centers is: DISABLED"); } } @Override public void stop() throws Exception { } }); }
private Managed newInboundReplication(final DataCenter dataCenter) { // Create a proxy for the remote data center. final ReplicationSource replicationSource = newRemoteReplicationSource(dataCenter); // Start asynchronously downloading events from the remote data center. final Managed fanout = new GuavaServiceController(_replicationEnabled, new Supplier<Service>() { @Override public Service get() { return _fanoutManager.newInboundReplicationFanout(dataCenter, replicationSource); } }); // Note: closing the replication source could also be done via a listener on the Guava service... return new Managed() { @Override public void start() throws Exception { fanout.start(); } @Override public void stop() throws Exception { fanout.stop(); ServicePoolProxies.close(replicationSource); } }; }
@Inject public DedupMigrationTask(TaskRegistry tasks, LifeCycleRegistry lifeCycle, DedupEventStore eventStore, @DedupEnabled ValueStore<Boolean> dedupEnabled) { super("dedup-databus-migration"); _eventStore = checkNotNull(eventStore, "eventStore"); _dedupEnabled = checkNotNull(dedupEnabled, "dedupEnabled"); tasks.addTask(this); // Default is enabled, so at startup warn if disabled since otherwise essential functionality won't work. lifeCycle.manage(new Managed() { @Override public void start() throws Exception { if (!_dedupEnabled.get()) { _log.warn("Databus deduplication is: DISABLED"); } } @Override public void stop() throws Exception { } }); }
@Inject public TableChangesEnabledTask(TaskRegistry tasks, LifeCycleRegistry lifeCycle, @Maintenance final String scope, @TableChangesEnabled ValueStore<Boolean> enabled) { super(scope + "-table-changes"); _enabled = checkNotNull(enabled, "enabled"); tasks.addTask(this); // Default is enabled, so at startup warn if disabled since otherwise essential functionality won't work. lifeCycle.manage(new Managed() { @Override public void start() throws Exception { if (!_enabled.get()) { _log.warn("({}) Table create/drop/update operations and table maintenance are: DISABLED", scope); } } @Override public void stop() throws Exception { } }); }
@Override public void run(Environment environment) { ServiceLocatorUtilities.bind(serviceLocator, new EnvBinder(application, environment)); LifecycleEnvironment lifecycle = environment.lifecycle(); AdminEnvironment admin = environment.admin(); listServices(HealthCheck.class).forEach(healthCheck -> { String name = healthCheck.getClass().getSimpleName(); environment.healthChecks().register(name, healthCheck); }); listServices(Managed.class).forEach(lifecycle::manage); listServices(LifeCycle.class).forEach(lifecycle::manage); listServices(LifeCycle.Listener.class).forEach(lifecycle::addLifeCycleListener); listServices(ServerLifecycleListener.class).forEach(lifecycle::addServerLifecycleListener); listServices(Task.class).forEach(admin::addTask); environment.jersey().register(HK2LifecycleListener.class); //Set service locator as parent for Jersey's service locator environment.getApplicationContext().setAttribute(ServletProperties.SERVICE_LOCATOR, serviceLocator); environment.getAdminContext().setAttribute(ServletProperties.SERVICE_LOCATOR, serviceLocator); serviceLocator.inject(application); }
@Override protected MongoClient buildClient() { String database = uri.getDatabase(); if (database != null) setDbName(database); final MongoClient mongoClient = new MongoClient(uri); environment.lifecycle().manage( new Managed() { @Override public void start() throws Exception { } @Override public void stop() throws Exception { mongoClient.close(); } } ); return mongoClient; }
public PGPoolingDataSource build(Environment environment) { final PGPoolingDataSource pg_ds = new PGPoolingDataSource(); pg_ds.setDataSourceName("pg_ds"); pg_ds.setServerName(this.getHost()); pg_ds.setDatabaseName(this.getDb()); pg_ds.setUser(this.getUser()); pg_ds.setPassword(this.getPassword()); pg_ds.setPortNumber(this.getPort()); pg_ds.setMaxConnections(this.getMaxConnections()); environment.lifecycle().manage(new Managed() { @Override public void start() { } @Override public void stop() { pg_ds.close(); } }); return pg_ds; }
@Test public void shouldRegisterHealthCheck() throws Exception { //GIVEN AmazonSQS sqs = mock(AmazonSQS.class); SqsBundle spiedBundle = spy(bundle); doReturn(sqs).when(spiedBundle).getAmazonSQS(); LifecycleEnvironment lifecycle = mock(LifecycleEnvironment.class); doNothing().when(lifecycle).manage((Managed) anyObject()); when(environment.lifecycle()).thenReturn(lifecycle); HealthCheckRegistry healthChecks = mock(HealthCheckRegistry.class); doNothing().when(healthChecks).register(anyObject(), anyObject()); when(environment.healthChecks()).thenReturn(healthChecks); //WHEN spiedBundle.run(configurationHolder, environment); //THEN verify(healthChecks, times(1)).register(eq("SqsBundle"), any(SqsBundleHealthCheck.class)); }
@Override public void run(T configuration, Environment environment) throws Exception { CuratorConfiguration curatorConfiguration = ComposedConfigurationAccessor.access(configuration, environment, CuratorConfiguration.class); // TODO more config final CuratorFramework curator = CuratorFrameworkFactory.newClient(curatorConfiguration.getConnectionString(), new RetryOneTime(1)); Managed managed = new Managed() { @Override public void start() throws Exception { curator.start(); } @Override public void stop() throws Exception { CloseableUtils.closeQuietly(curator); } }; environment.lifecycle().manage(managed); SoaBundle.getFeatures(environment).putNamed(curator, CuratorFramework.class, curatorConfiguration.getCuratorName()); }
public AnalysisServiceClient build(Environment environment) { final HttpClientConfiguration httpConfig = new HttpClientConfiguration(); httpConfig.setTimeout(Duration.milliseconds(getTimeout())); final HttpClient httpClient = new HttpClientBuilder(environment).using(httpConfig) .build("analysis-http-client"); AnalysisServiceClient client = new AnalysisServiceClientAdapter(getHost(), getPort(), getPortFailover(), getPath(), httpClient); environment.lifecycle().manage(new Managed() { @Override public void start() { } @Override public void stop() { } }); return client; }
/** * Used internally to register application specific injector. * * @param application application instance * @param injector injector instance * @return managed object, which must be registered to remove injector on application stop */ public static Managed registerInjector(final Application application, final Injector injector) { Preconditions.checkNotNull(application, "Application instance required"); Preconditions.checkArgument(!INJECTORS.containsKey(application), "Injector already registered for application %s", application.getClass().getName()); INJECTORS.put(application, injector); return new Managed() { @Override public void start() throws Exception { // not used } @Override public void stop() throws Exception { INJECTORS.remove(application); } }; }
private void buildBinders() { if (!bindersBuilt) { jerseyBinder = Multibinder.newSetBinder(binder(), Object.class, Graceland.class); managedBinder = Multibinder.newSetBinder(binder(), Managed.class, Graceland.class); managedClassBinder = Multibinder.newSetBinder(binder(), TypeLiterals.ManagedClass, Graceland.class); healthCheckBinder = Multibinder.newSetBinder(binder(), HealthCheck.class, Graceland.class); healthCheckClassBinder = Multibinder.newSetBinder(binder(), TypeLiterals.HealthCheckClass, Graceland.class); taskBinder = Multibinder.newSetBinder(binder(), Task.class, Graceland.class); taskClassBinder = Multibinder.newSetBinder(binder(), TypeLiterals.TaskClass, Graceland.class); bundleBinder = Multibinder.newSetBinder(binder(), Bundle.class, Graceland.class); bundleClassBinder = Multibinder.newSetBinder(binder(), TypeLiterals.BundleClass, Graceland.class); commandBinder = Multibinder.newSetBinder(binder(), Command.class, Graceland.class); commandClassBinder = Multibinder.newSetBinder(binder(), TypeLiterals.CommandClass, Graceland.class); initializerBinder = Multibinder.newSetBinder(binder(), Initializer.class, Graceland.class); initializerClassBinder = Multibinder.newSetBinder(binder(), TypeLiterals.InitializerClass, Graceland.class); configuratorBinder = Multibinder.newSetBinder(binder(), Configurator.class, Graceland.class); configuratorClassBinder = Multibinder.newSetBinder(binder(), TypeLiterals.ConfiguratorClass, Graceland.class); bindersBuilt = true; } }
@Test public void managed_binds_work() { final Managed managed = mock(Managed.class); final Class<TestManaged> managedClass = TestManaged.class; Injector injector = Guice.createInjector(new AbstractPlugin() { @Override protected void configure() { bindManaged(managed); bindManaged(managedClass); } }); Set<Managed> managedSet = injector.getInstance(Keys.ManagedObjects); Set<Class<? extends Managed>> managedClassSet = injector.getInstance(Keys.ManagedObjectClasses); assertThat(managedSet, hasSize(1)); assertThat(managedSet, hasItem(managed)); assertThat(managedClassSet, hasSize(1)); assertThat(managedClassSet, hasItem(TestManaged.class)); }
@Test public void run_adds_managed() throws Exception { final Managed managed = mock(Managed.class); final Class<TestManaged> managedClass = TestManaged.class; Application application = buildApplication( new AbstractPlugin() { @Override protected void configure() { bindManaged(managed); bindManaged(managedClass); } } ); new Platform(application).run(configuration, environment); verify(lifecycleEnvironment).manage(eq(managed)); verify(lifecycleEnvironment).manage(isA(TestManaged.class)); }
@Override public void run(ApiConfig configuration, Environment environment) throws Exception { LOGGER.info("api started up"); injector = guiceBundle.getInjector(); JerseyEnvironment jersey = environment.jersey(); register(environment.lifecycle(), REFLECTIONS.getSubTypesOf(Managed.class)); // registers NbdServer // injector.getInstance(SessionFactory.class); //init DB installCorsFilter(environment); //init all Singletons semi-eagerly REFLECTIONS.getTypesAnnotatedWith(Singleton.class).forEach(injector::getInstance); final Set<Class<?>> resources = REFLECTIONS.getTypesAnnotatedWith(Path.class); register(jersey, resources); jersey.register(new LoggingExceptionMapper<Throwable>() { @Override protected String formatErrorMessage(long id, Throwable exception) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); exception.printStackTrace(pw); return sw.toString(); } }); jersey.register(new JsonProcessingExceptionMapper(true)); jersey.register(new EarlyEofExceptionMapper()); final TrivialAuthenticator instance = injector.getInstance(TrivialAuthenticator.class); environment.jersey().register(new AuthDynamicFeature( new BasicCredentialAuthFilter.Builder<Principal>() .setAuthenticator(instance) .setAuthorizer((principal, role) -> false) .buildAuthFilter())); environment.jersey().register(RolesAllowedDynamicFeature.class); }
@Override public void run(Configuration configuration, Environment environment) { environment.jersey().register(new LoginResource()); environment.jersey().register(new UserResource()); environment.jersey().register(new AuthDynamicFeature( new OAuthCredentialAuthFilter.Builder<PrincipalImpl>() .setAuthenticator(new TestOAuthAuthenticator()).setPrefix("Bearer") .buildAuthFilter())); environment.jersey().register(RolesAllowedDynamicFeature.class); environment.jersey().register(new AuthValueFactoryProvider.Binder<>(PrincipalImpl.class)); //TODO move this cleanup into the tests environment.lifecycle().manage(new Managed() { @Override public void start() { } @Override public void stop() { flushRedis(); } private void flushRedis() { try (StatefulRedisConnection<String, String> connection = redisClient.connect()) { connection.sync().flushdb(); } redisClient.shutdownAsync(); } }); }
/** * Build a new {@link HttpTracing} instance for interfacing with Zipkin * * @param environment * Environment * @param reporter * reporter * @return HttpTracing instance */ protected Optional<HttpTracing> buildTracing( @Nonnull final Environment environment, @Nonnull final Reporter<Span> reporter) { LOGGER.info("Registering Zipkin service ({}) at <{}:{}>", serviceName, serviceHost, servicePort); final Endpoint endpoint = Endpoint.newBuilder().ip(serviceHost) .port(servicePort).serviceName(serviceName).build(); final Tracing tracing = Tracing.newBuilder() .currentTraceContext(MDCCurrentTraceContext.create()) .localEndpoint(endpoint).spanReporter(reporter) .sampler(getSampler()).traceId128Bit(traceId128Bit).build(); final HttpTracing httpTracing = HttpTracing.newBuilder(tracing) .clientParser(clientParser).clientSampler(clientSampler) .serverParser(serverParser).serverSampler(serverSampler) .build(); // Register the tracing feature for client and server requests environment.jersey().register(TracingFeature.create(httpTracing)); environment.lifecycle().manage(new Managed() { @Override public void start() throws Exception { // nothing to start } @Override public void stop() throws Exception { tracing.close(); } }); return Optional.of(httpTracing); }
public void start() throws Exception { // Start all the managed instances in dropwizard. Set<Managed> managedObjects = ImmutableSet.copyOf(dropwizardModule.getManaged()); for (Managed managed : managedObjects) { managed.start(); } }
public MongoClient build(Environment environment) { final MongoClient mongoClient = buildUnmanaged(); environment.lifecycle().manage(new Managed() { @Override public void start() throws Exception { } @Override public void stop() throws Exception { LOGGER.info("Closing mongo client: {}", mongoClient); mongoClient.close(); } }); return mongoClient; }
@Override public void beanAdded(Container parent, Object child) { if (child instanceof JettyManaged) { Managed object = ((JettyManaged) child).getManaged(); jmxContainer.beanAdded(parent, object); } }
@Override public void beanRemoved(Container parent, Object child) { if (child instanceof JettyManaged) { Managed object = ((JettyManaged) child).getManaged(); jmxContainer.beanRemoved(parent, object); } }
private MongoClient getClient(LifecycleEnvironment lifecycle) { synchronized (this) { if (mongoClient != null) { return mongoClient; } logger.debug("Create client {}", connections); final MongoClientOptions options = MongoClientOptions.builder() .connectTimeout(5000) .serverSelectionTimeout(10000) .maxWaitTime(5000) .build(); mongoClient = createClient(options); lifecycle.manage(new Managed() { @Override public void start() throws Exception { } @Override public void stop() throws Exception { mongoClient.close(); } }); return mongoClient; } }
@Override protected void runOneIteration() throws Exception { try { // Start replication for all new data centers. Map<String, Managed> active = Maps.newHashMap(_dataCenterFanout); DataCenter self = _dataCenters.getSelf(); for (DataCenter dataCenter : _dataCenters.getAll()) { if (dataCenter.equals(self)) { continue; } Managed fanout = active.remove(dataCenter.getName()); if (fanout == null) { fanout = newInboundReplication(dataCenter); try { fanout.start(); } catch (Exception e) { _log.error("Unexpected exception starting replication service: {}", dataCenter.getName()); continue; } _dataCenterFanout.put(dataCenter.getName(), fanout); } } // If a DataCenter has been removed, stop replicating from it. stopAll(active); } catch (Throwable t) { _log.error("Unexpected exception polling data center changes.", t); } }
private void stopAll(Map<String, Managed> active) { // Copy the set to avoid concurrent modification exceptions for (Map.Entry<String, Managed> entry : Lists.newArrayList(active.entrySet())) { try { entry.getValue().stop(); } catch (Exception e) { _log.error("Unexpected exception stopping replication service: {}", entry.getKey()); } _dataCenterFanout.remove(entry.getKey()); } }
@Override public void stop() throws Exception { for (Managed managed : Lists.reverse(_managed)) { managed.stop(); } _managed.clear(); }
/** * Builds a new {@link RibbonJerseyClient} with an existing Jersey Client * and service discoverer * * @param name * Client name * @param jerseyClient * Jersey Client * @param serviceDiscoverer * Service discoverer * @return new RibbonJerseyClient */ public RibbonJerseyClient build(@Nonnull final String name, @Nonnull final Client jerseyClient, @Nonnull final ConsulServiceDiscoverer serviceDiscoverer) { // dynamic server list that is refreshed from Consul final ConsulServerList serverList = new ConsulServerList(consul, serviceDiscoverer); // build a new load balancer based on the configuration final DefaultClientConfigImpl clientConfig = new DefaultClientConfigImpl(); clientConfig.setClientName(name); clientConfig.set(CommonClientConfigKey.ServerListRefreshInterval, Ints.checkedCast( configuration.getRefreshInterval().toMilliseconds())); final ZoneAwareLoadBalancer<Server> loadBalancer = LoadBalancerBuilder .newBuilder().withClientConfig(clientConfig) .withRule(new WeightedResponseTimeRule()) .withDynamicServerList(serverList) .buildDynamicServerListLoadBalancer(); final RibbonJerseyClient client = new RibbonJerseyClient( configuration.getScheme(), loadBalancer, jerseyClient); environment.lifecycle().manage(new Managed() { @Override public void start() throws Exception { // nothing to start } @Override public void stop() throws Exception { client.close(); } }); return client; }
@Override public void run(C configuration, Environment environment) throws Exception { jackrabbitConfiguration = configurationAccessor.apply(configuration); repository = buildRepository(jackrabbitConfiguration); environment.lifecycle().manage(new Managed() { @Override public void start() throws Exception { } @Override public void stop() throws Exception { } }); environment.healthChecks().register(healthCheckName, new JackrabbitHealthCheck(repository)); }
@Test public void shouldCorrectlyRegisterReceiver() throws Exception { //GIVEN AmazonSQS sqs = mock(AmazonSQS.class); String queueUrl = "https://eu-central-1/queue.amazonaws.com/123456/test-queue"; when(sqs.getQueueUrl("test-queue")).thenReturn(new GetQueueUrlResult() .withQueueUrl(queueUrl)); LifecycleEnvironment lifecycle = mock(LifecycleEnvironment.class); doNothing().when(lifecycle).manage((Managed) anyObject()); when(environment.lifecycle()).thenReturn(lifecycle); HealthCheckRegistry healthChecks = mock(HealthCheckRegistry.class); doNothing().when(healthChecks).register(anyObject(), anyObject()); when(environment.healthChecks()).thenReturn(healthChecks); SqsBundle spiedBundle = spy(bundle); doReturn(sqs).when(spiedBundle).getAmazonSQS(); spiedBundle.run(configurationHolder, environment); //WHEN spiedBundle.registerReceiver("test-queue", (m) -> process(m)); //THEN verify(spiedBundle, times(1)).internalRegisterReceiver(eq("test-queue"), any(SqsReceiverHandler.class)); }
@Override public void run(T configuration, Environment environment) throws Exception { SqlConfiguration sqlConfiguration = ComposedConfigurationAccessor.access(configuration, environment, SqlConfiguration.class); try { try ( InputStream stream = Resources.getResource(sqlConfiguration.getMybatisConfigUrl()).openStream() ) { SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(stream); Configuration mybatisConfiguration = sqlSessionFactory.getConfiguration(); mybatisConfiguration.addMapper(AttributeEntityMapper.class); final SqlSession session = sqlSessionFactory.openSession(true); SoaBundle.getFeatures(environment).putNamed(session, SqlSession.class, sqlConfiguration.getName()); Managed managed = new Managed() { @Override public void start() throws Exception { } @Override public void stop() throws Exception { session.close(); } }; environment.lifecycle().manage(managed); } } catch ( Exception e ) { log.error("Could not initialize MyBatis", e); throw new RuntimeException(e); } }
static <T> T checkManaged(Environment environment, T obj) { if ( obj instanceof Managed ) { environment.lifecycle().manage((Managed)obj); } return obj; }
@Override public void run(final ThirdEyeReportingConfiguration configuration, final Environment environment) throws SchedulerException { final ReportScheduler reportScheduler = new ReportScheduler(new File(configuration.getReportConfigPath()), configuration.getReportEmailTemplatePath(), configuration.getServerUri(), configuration.getDashboardUri()); environment.lifecycle().manage(new Managed() { @Override public void start() throws Exception { reportScheduler.start(); } @Override public void stop() throws Exception { reportScheduler.stop(); } }); // Resources environment.jersey().register(new ReportsResource( environment.metrics(), configuration.getReportConfigPath())); environment.jersey().register(new AdminResource()); // Tasks environment.admin().addTask(new ReportingTask(reportScheduler)); }
@Override public void scanAndAdd(Environment environment, Injector injector, Reflections reflections) { Set<Class<? extends Managed>> managedClasses = reflections.getSubTypesOf(Managed.class); for (Class<? extends Managed> managed : managedClasses) { environment.lifecycle().manage(injector.getInstance(managed)); LOGGER.info("Added managed: " + managed); } }
/** * Register Managed classes into Dropwizard context. * * @param environment */ private void registerManaged(Environment environment) { final Map<String, Managed> beansOfType = applicationContext.getBeansOfType(Managed.class); for (String beanName : beansOfType.keySet()) { Managed managed = beansOfType.get(beanName); environment.lifecycle().manage(managed); logger.info("Registering managed: " + managed.getClass().getName()); } }
/** * Register application context as Dropwizard Managed. * @param environment */ private void registerContextAsManaged(Environment environment) { environment.lifecycle().manage(new Managed() { @Override public void start() throws Exception { } @Override public void stop() throws Exception { applicationContext.close(); } }); }
/** * Ran when the Dropwizard service starts up. This method is responsible for setting up the * {@link io.dropwizard.setup.Environment} using the bindings from the loaded * {@link io.graceland.plugin.Plugin}s. * * @param configuration Provided by Dropwizard. * @param environment Provided by Dropwizard. * @throws Exception Thrown by Dropwizard. */ @Override public void run(PlatformConfiguration configuration, Environment environment) throws Exception { dropwizardModule.setup(configuration, environment); for (Configurator configurator : wrapper.getConfigurators()) { configurator.configure(configuration, environment); LOGGER.debug("Registered Configurator: {}", configurator.getClass().getCanonicalName()); } for (Object jerseyComponent : wrapper.getJerseyComponents()) { environment.jersey().register(jerseyComponent); LOGGER.debug("Registered Jersey Component: {}", jerseyComponent.getClass().getCanonicalName()); } for (Managed managed : wrapper.getManaged()) { environment.lifecycle().manage(managed); LOGGER.debug("Registered Managed Object: {}", managed.getClass().getCanonicalName()); } for (HealthCheck healthCheck : wrapper.getHealthChecks()) { environment.healthChecks().register(healthCheck.toString(), healthCheck); LOGGER.debug("Registered Health Check: {}", healthCheck.getClass().getCanonicalName()); } for (Task task : wrapper.getTasks()) { environment.admin().addTask(task); LOGGER.debug("Registered Task: {}", task.getClass().getCanonicalName()); } for (FilterSpec filterSpec : wrapper.getFilterSpecs()) { registerFilterSpec(environment, filterSpec); LOGGER.debug("Registered Filter {}: {}", filterSpec.getName(), filterSpec.getFilter().getClass().getCanonicalName()); } }
/*** * Manage the {@link ApplicationFactory} in terms of starting up and shutting down resources. * <p> * @param appFactory - The application factory to manage * @param environment - The environment */ protected void manageApplicationFactory(final ApplicationFactory appFactory, final Environment environment){ final Managed managedAppFactory = new Managed() { @Override public void start() throws Exception { } @Override public void stop() throws Exception { appFactory.close(); } }; environment.lifecycle().manage(managedAppFactory); }