com.google.inject.PrivateModule Java Examples

The following examples show how to use com.google.inject.PrivateModule. 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: ContributingModule.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void configure(Binder binder) {
	binder.install(new PrivateModule() {
		@Override
		protected void configure() {
			// we bind the internally required services of the two exposed bindings
			// in a private module. This is to avoid them being available via
			// ISharedStateContributionRegistry.getContributedInstances
			//
			// This is effectively a means to encapsulate the implementation details and hide
			// them from the globally available services
			bind(IStorage2UriMapperContribution.class).to(BuiltinSchemeUriMapperContribution.class);
			bind(IResourceSetInitializer.class).to(BuiltInSchemeResourceSetInitializer.class);
			bind(EffectiveRegistrarProvider.class);
			bind(BuiltInSchemeRegistrar.class);
			bind(ResourceSetWithBuiltInSchemeProvider.class)
					.to(ContributionAwareResourceSetWithBuiltInSchemeProvider.class);
			bind(UriExtensions.class);
			bind(ClassLoader.class).toInstance(getClass().getClassLoader());

			// Here we expose the two services that are supposed to be publicly available.
			expose(IResourceSetInitializer.class);
			expose(IStorage2UriMapperContribution.class);
		}
	});
}
 
Example #2
Source File: ValidationModule.java    From seed with Mozilla Public License 2.0 6 votes vote down vote up
@Override
protected void configure() {
    install(new PrivateModule() {
        @Override
        protected void configure() {
            // Validator factory
            bind(ValidatorFactory.class).toProvider(ValidatorFactoryProvider.class).in(Scopes.SINGLETON);
            expose(ValidatorFactory.class);

            // Validator
            bind(Validator.class).toProvider(ValidatorProvider.class).in(Scopes.SINGLETON);
            expose(Validator.class);

            // Detected constraint validators
            constraintValidators.forEach(this::bind);
        }
    });

    // Validation on injection / method call
    enableValidationOnInjectionPoints();
    if (isDynamicValidationSupported()) {
        configureDynamicValidation();
    }
}
 
Example #3
Source File: TestSecurityProvider.java    From seed with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public PrivateModule provideAdditionalSecurityModule() {
    return new ShiroModule() {
        @Override
        protected void configureShiro() {
            try {
                bind(org.apache.shiro.mgt.SecurityManager.class)
                        .annotatedWith(Names.named("test"))
                        .toConstructor(DefaultSecurityManager.class.getConstructor(Collection.class))
                        .asEagerSingleton();
            } catch (NoSuchMethodException e) {
                throw new RuntimeException("Internal error", e);
            }

            expose(SecurityManager.class).annotatedWith(Names.named("test"));
        }
    };
}
 
Example #4
Source File: MaintenanceModule.java    From attic-aurora with Apache License 2.0 6 votes vote down vote up
@Override
protected void configure() {
  bind(new TypeLiteral<Amount<Long, Time>>() { })
      .annotatedWith(
          MaintenanceController.MaintenanceControllerImpl.PollingInterval.class)
      .toInstance(options.hostMaintenancePollingInterval);
  bind(MaintenanceController.class).to(MaintenanceController.MaintenanceControllerImpl.class);
  bind(MaintenanceController.MaintenanceControllerImpl.class).in(Singleton.class);
  PubsubEventModule.bindSubscriber(
      binder(),
      MaintenanceController.MaintenanceControllerImpl.class);

  install(new PrivateModule() {
    @Override
    protected void configure() {
      bind(ScheduledExecutorService.class).toInstance(
          AsyncUtil.singleThreadLoggingScheduledExecutor("MaintenanceController-%d", LOG));
    }
  });
  SchedulerServicesModule.addSchedulerActiveServiceBinding(binder())
      .to(MaintenanceController.MaintenanceControllerImpl.class);
}
 
Example #5
Source File: AsyncModule.java    From attic-aurora with Apache License 2.0 6 votes vote down vote up
@Override
protected void configure() {
  install(new PrivateModule() {
    @Override
    protected void configure() {
      bind(ScheduledThreadPoolExecutor.class).toInstance(afterTransaction);
      bind(RegisterGauges.class).in(Singleton.class);
      expose(RegisterGauges.class);
    }
  });
  SchedulerServicesModule.addAppStartupServiceBinding(binder()).to(RegisterGauges.class);

  bind(Executor.class).annotatedWith(AsyncExecutor.class).toInstance(afterTransaction);
  bind(ScheduledExecutorService.class).annotatedWith(AsyncExecutor.class)
      .toInstance(afterTransaction);
}
 
Example #6
Source File: MyReferenceSearchResultContentProviderCustomModule.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected void configure() {
	// As a workaround to fix GH-724, this is copied from org.eclipse.xtext.ui.shared.internal.SharedModule
	// and the default must be kept in sync with the corresponding code there!!
	binder().install(new PrivateModule() {
		@Override
		protected void configure() {
			bind(ReferenceSearchViewPage.class);
			bind(ReferenceSearchResultLabelProvider.class);
			// Workaround to fix GH-724.
			bind(ReferenceSearchResultContentProvider.class).to(MyReferenceSearchResultContentProvider.class);
			bind(ReferenceSearchViewSorter.class);

			expose(ReferenceSearchViewPage.class);
		}
	});
}
 
Example #7
Source File: RiemannInputPlugin.java    From ffwd with Apache License 2.0 6 votes vote down vote up
@Override
public Module module(final Key<PluginSource> key, final String id) {
    return new PrivateModule() {
        @Override
        protected void configure() {
            bind(ProtocolServer.class).to(protocolServer).in(Scopes.SINGLETON);
            bind(Protocol.class).toInstance(protocol);

            bind(RiemannFrameDecoder.class);
            bind(RiemannResponder.class).in(Scopes.SINGLETON);
            bind(RiemannDatagramDecoder.class).in(Scopes.SINGLETON);
            bind(RiemannMessageDecoder.class).in(Scopes.SINGLETON);
            bind(Logger.class).toInstance(log);

            bind(RetryPolicy.class).toInstance(retry);

            bind(key).to(ProtocolPluginSource.class).in(Scopes.SINGLETON);
            expose(key);
        }
    };
}
 
Example #8
Source File: TemplateOutputPlugin.java    From ffwd with Apache License 2.0 5 votes vote down vote up
@Override
public Module module(final Key<PluginSink> key, final String id) {
    return new PrivateModule() {
        @Override
        protected void configure() {
            bind(Logger.class).toInstance(LoggerFactory.getLogger(id));
            bind(TemplateOutputEncoder.class).toInstance(new TemplateOutputEncoder());
            bind(Protocol.class).toInstance(protocol);
            bind(ProtocolClient.class).toInstance(new TemplateOutputProtocolClient());

            bind(key).toInstance(new ProtocolPluginSink(retry));
            expose(key);
        }
    };
}
 
Example #9
Source File: SchedulerModule.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure() {
  bind(TaskIdGenerator.class).to(TaskIdGeneratorImpl.class);

  install(new PrivateModule() {
    @Override
    protected void configure() {
      bind(LeadingOptions.class).toInstance(
          new LeadingOptions(options.maxRegistrationDelay, options.maxLeadingDuration));

      final ScheduledExecutorService executor =
          AsyncUtil.singleThreadLoggingScheduledExecutor("Lifecycle-%d", LOG);

      bind(ScheduledExecutorService.class).toInstance(executor);
      bind(SchedulerLifecycle.class).in(Singleton.class);
      expose(SchedulerLifecycle.class);
    }
  });

  PubsubEventModule.bindRegisteredSubscriber(binder(), SchedulerLifecycle.class);
  bind(TaskVars.class).in(Singleton.class);
  PubsubEventModule.bindSubscriber(binder(), TaskVars.class);
  addSchedulerActiveServiceBinding(binder()).to(TaskVars.class);

  bind(new TypeLiteral<BlockingQueue<Protos.TaskStatus>>() { })
      .annotatedWith(TaskStatusHandlerImpl.StatusUpdateQueue.class)
      .toInstance(new LinkedBlockingQueue<>());
  bind(new TypeLiteral<Integer>() { })
      .annotatedWith(TaskStatusHandlerImpl.MaxBatchSize.class)
      .toInstance(options.maxStatusUpdateBatchSize);

  bind(TaskStatusHandler.class).to(TaskStatusHandlerImpl.class);
  bind(TaskStatusHandlerImpl.class).in(Singleton.class);
  addSchedulerActiveServiceBinding(binder()).to(TaskStatusHandlerImpl.class);

  bind(TaskEventBatchWorker.class).in(Singleton.class);
  addSchedulerActiveServiceBinding(binder()).to(TaskEventBatchWorker.class);
}
 
Example #10
Source File: Bindings.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a module that hides all the given module's bindings and only exposes bindings for
 * the given key.
 *
 * @param keys The keys of the bindings to expose.
 * @param module The module to hide most bindings for.
 * @return A limited visibility module.
 */
public static Module exposing(final Iterable<? extends Key<?>> keys, final Module module) {
  Preconditions.checkNotNull(keys);
  Preconditions.checkNotNull(module);

  return new PrivateModule() {
    @Override protected void configure() {
      install(module);
      for (Key<?> key : keys) {
        expose(key);
      }
    }
  };
}
 
Example #11
Source File: GuiceRepositoryTestCase.java    From vespa with Apache License 2.0 5 votes vote down vote up
private Module createPrivateInjectNameModule(final Named name) {
    return new PrivateModule() {
        @Override
        protected void configure() {
            bind(NameHolder.class).annotatedWith(name).to(NameHolder.class);
            expose(NameHolder.class).annotatedWith(name);
            bind(Named.class).toInstance(name);
        }
    };
}
 
Example #12
Source File: ProtobufInputPlugin.java    From ffwd with Apache License 2.0 5 votes vote down vote up
@Override
public Module module(final Key<PluginSource> key, final String id) {
    return new PrivateModule() {
        @Override
        protected void configure() {
            bind(ProtocolServer.class).to(protocolServer).in(Scopes.SINGLETON);
            bind(Protocol.class).toInstance(protocol);
            bind(RetryPolicy.class).toInstance(retry);
            bind(ProtobufDecoder.class).in(Scopes.SINGLETON);

            bind(key).to(ProtobufPluginSource.class).in(Scopes.SINGLETON);
            expose(key);
        }
    };
}
 
Example #13
Source File: PruningModule.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure() {
  install(new PrivateModule() {
    @Override
    protected void configure() {
      // TODO(ksweeney): Create a configuration validator module so this can be injected.
      // TODO(William Farner): Revert this once large task counts is cheap ala hierarchichal store
      bind(TaskHistoryPruner.HistoryPrunerSettings.class).toInstance(
          new TaskHistoryPruner.HistoryPrunerSettings(
              options.historyPruneThreshold,
              options.historyMinRetentionThreshold,
              options.historyMaxPerJobThreshold));

      bind(TaskHistoryPruner.class).in(Singleton.class);
      expose(TaskHistoryPruner.class);
    }
  });
  PubsubEventModule.bindSubscriber(binder(), TaskHistoryPruner.class);

  install(new PrivateModule() {
    @Override
    protected void configure() {
      bind(JobUpdateHistoryPruner.HistoryPrunerSettings.class).toInstance(
          new JobUpdateHistoryPruner.HistoryPrunerSettings(
              options.jobUpdateHistoryPruningInterval,
              options.jobUpdateHistoryPruningThreshold,
              options.jobUpdateHistoryPerJobThreshold));

      bind(ScheduledExecutorService.class).toInstance(
          AsyncUtil.singleThreadLoggingScheduledExecutor("JobUpdatePruner-%d", LOG));

      bind(JobUpdateHistoryPruner.class).in(Singleton.class);
      expose(JobUpdateHistoryPruner.class);
    }
  });
  SchedulerServicesModule.addSchedulerActiveServiceBinding(binder())
      .to(JobUpdateHistoryPruner.class);
}
 
Example #14
Source File: SecurityModule.java    From seed with Mozilla Public License 2.0 5 votes vote down vote up
@Override
protected void configure() {
    install(new SecurityInternalModule(securityConfigurer, scopeClasses));
    install(new SecurityAopModule(crudActionResolvers));

    if (elAvailable) {
        install(new SecurityExpressionModule());
    }

    Module mainModuleToInstall = null;
    for (SecurityProvider securityProvider : securityProviders) {
        PrivateModule mainSecurityModule = securityProvider.provideMainSecurityModule(
                new SecurityGuiceConfigurer(securityConfigurer.getSecurityConfiguration()));
        if (mainSecurityModule != null) {
            if (mainModuleToInstall == null || mainModuleToInstall instanceof DefaultSecurityModule) {
                mainModuleToInstall = mainSecurityModule;
            } else if (!(mainSecurityModule instanceof DefaultSecurityModule)) {
                throw SeedException
                        .createNew(SecurityErrorCode.MULTIPLE_MAIN_SECURITY_MODULES)
                        .put("first", mainModuleToInstall.getClass().getCanonicalName())
                        .put("second", mainSecurityModule.getClass().getCanonicalName());
            }
        }

        PrivateModule additionalSecurityModule = securityProvider.provideAdditionalSecurityModule();
        if (additionalSecurityModule != null) {
            install(removeSecurityManager(additionalSecurityModule));
        }
    }
    install(mainModuleToInstall);
}
 
Example #15
Source File: AsyncStatsModule.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure() {
  bind(TaskStatCalculator.class).in(Singleton.class);
  bind(CachedCounters.class).in(Singleton.class);
  bind(MachineResourceProvider.class).to(OfferAdapter.class);
  bind(SlotSizeCounter.class).in(Singleton.class);

  install(new PrivateModule() {
    @Override
    protected void configure() {
      bind(TaskStatUpdaterService.class).in(Singleton.class);
      Amount<Long, Time> taskStatInterval = options.taskStatInterval;
      bind(Scheduler.class).toInstance(
          Scheduler.newFixedRateSchedule(
              taskStatInterval.getValue(),
              taskStatInterval.getValue(),
              taskStatInterval.getUnit().getTimeUnit()));
      expose(TaskStatUpdaterService.class);
    }
  });
  SchedulerServicesModule.addSchedulerActiveServiceBinding(binder())
      .to(TaskStatUpdaterService.class);

  install(new PrivateModule() {
    @Override
    protected void configure() {
      bind(SlotSizeCounterService.class).in(Singleton.class);
      Amount<Long, Time> slotStatInterval = options.slotStatInterval;
      bind(Scheduler.class).toInstance(
          Scheduler.newFixedRateSchedule(
              slotStatInterval.getValue(),
              slotStatInterval.getValue(),
              slotStatInterval.getUnit().getTimeUnit()));
      expose(SlotSizeCounterService.class);
    }
  });
  SchedulerServicesModule.addSchedulerActiveServiceBinding(binder())
      .to(SlotSizeCounterService.class);
}
 
Example #16
Source File: OfferManagerModule.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure() {
  install(new PrivateModule() {
    @Override
    protected void configure() {
      bind(new TypeLiteral<Ordering<HostOffer>>() { })
          .toInstance(OfferOrderBuilder.create(options.offer.offerOrder));
      bind(OfferSetImpl.class).in(Singleton.class);
      bind(OfferSet.class).to(OfferSetImpl.class);
      expose(OfferSet.class);
    }
  });
}
 
Example #17
Source File: CallOrderEnforcingStorage.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a binding module that will wrap a storage class with {@link CallOrderEnforcingStorage},
 * exposing the order-enforced storage as {@link Storage} and {@link NonVolatileStorage}.
 *
 * @param storageClass Non-volatile storage implementation class.
 * @return Binding module.
 */
public static Module wrappingModule(final Class<? extends NonVolatileStorage> storageClass) {
  return new PrivateModule() {
    @Override
    protected void configure() {
      bind(Storage.class).to(CallOrderEnforcingStorage.class);
      bind(NonVolatileStorage.class).to(CallOrderEnforcingStorage.class);
      bind(CallOrderEnforcingStorage.class).in(Singleton.class);
      bind(NonVolatileStorage.class).annotatedWith(EnforceOrderOn.class).to(storageClass);
      expose(Storage.class);
      expose(NonVolatileStorage.class);
    }
  };
}
 
Example #18
Source File: OpenCensusOutputPlugin.java    From ffwd with Apache License 2.0 5 votes vote down vote up
@Override
public Module module(final Key<PluginSink> key, final String id) {
    return new PrivateModule() {
        @Override
        protected void configure() {
            bind(Logger.class).toInstance(LoggerFactory.getLogger(id));
            bind(key).toInstance(
                new OpenCensusPluginSink(gcpProject, maxViews, outputMetricNamePattern)
            );
            expose(key);
        }
    };
}
 
Example #19
Source File: WebSecurityPlugin.java    From seed with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public PrivateModule provideMainSecurityModule(SecurityGuiceConfigurer securityGuiceConfigurer) {
    return servletContext != null ? new WebSecurityModule(
            servletContext,
            securityConfig,
            scannedFilters,
            applicationId,
            securityGuiceConfigurer
    ) : null;
}
 
Example #20
Source File: GeneratedInputPlugin.java    From ffwd with Apache License 2.0 5 votes vote down vote up
@Override
public Module module(final Key<PluginSource> key, final String id) {
    return new PrivateModule() {
        @Override
        protected void configure() {
            bind(key).toInstance(new GeneratedPluginSource(sameHost));
            expose(key);
        }
    };
}
 
Example #21
Source File: CarbonInputPlugin.java    From ffwd with Apache License 2.0 5 votes vote down vote up
@Override
public Module module(final Key<PluginSource> key, final String id) {
    return new PrivateModule() {
        @Override
        protected void configure() {
            bind(CarbonDecoder.class).toInstance(new CarbonDecoder(metricKey));
            bind(Protocol.class).toInstance(protocol);
            bind(ProtocolServer.class).to(protocolServer).in(Scopes.SINGLETON);
            bind(RetryPolicy.class).toInstance(retry);

            bind(key).to(CarbonPluginSource.class).in(Scopes.SINGLETON);
            expose(key);
        }
    };
}
 
Example #22
Source File: JsonInputPlugin.java    From ffwd with Apache License 2.0 5 votes vote down vote up
@Override
public Module module(final Key<PluginSource> key, final String id) {
    return new PrivateModule() {
        @Override
        protected void configure() {
            bind(JsonObjectMapperDecoder.class).in(Scopes.SINGLETON);
            bind(Protocol.class).toInstance(protocol);
            bind(ProtocolServer.class).to(protocolServer).in(Scopes.SINGLETON);
            bind(RetryPolicy.class).toInstance(retry);

            bind(key).to(JsonPluginSource.class).in(Scopes.SINGLETON);
            expose(key);
        }
    };
}
 
Example #23
Source File: HttpInputPlugin.java    From ffwd with Apache License 2.0 5 votes vote down vote up
@Override
public Module module(final Key<PluginSource> key, final String id) {
    return new PrivateModule() {
        @Override
        protected void configure() {
            bind(ProtocolServer.class).to(protocolServer).in(Scopes.SINGLETON);
            bind(Protocol.class).toInstance(protocol);
            bind(RetryPolicy.class).toInstance(retry);
            bind(HttpDecoder.class).in(Scopes.SINGLETON);

            bind(key).to(HttpPluginSource.class).in(Scopes.SINGLETON);
            expose(key);
        }
    };
}
 
Example #24
Source File: OfferManagerModule.java    From attic-aurora with Apache License 2.0 4 votes vote down vote up
@Override
protected void configure() {
  Options options = cliOptions.offer;
  if (!options.holdOffersForever) {
    long offerHoldTime = options.offerHoldJitterWindow.as(Time.SECONDS)
        + options.minOfferHoldTime.as(Time.SECONDS);
    if (options.unavailabilityThreshold.as(Time.SECONDS) < offerHoldTime) {
      LOG.warn("unavailability_threshold ({}) is less than the sum of min_offer_hold_time ({})"
              + " and offer_hold_jitter_window ({}). This creates risks of races between "
              + "launching and draining",
          options.unavailabilityThreshold,
          options.minOfferHoldTime,
          options.offerHoldJitterWindow);
    }
  }

  install(MoreModules.instantiate(options.offerSetModule, cliOptions));

  bind(new TypeLiteral<Amount<Long, Time>>() { })
      .annotatedWith(UnavailabilityThreshold.class)
      .toInstance(options.unavailabilityThreshold);

  install(new PrivateModule() {
    @Override
    protected void configure() {
      if (options.holdOffersForever) {
        bind(Deferment.class).to(Deferment.Noop.class);
      } else {
        bind(new TypeLiteral<Supplier<Amount<Long, Time>>>() { }).toInstance(
            new RandomJitterReturnDelay(
                options.minOfferHoldTime.as(Time.MILLISECONDS),
                options.offerHoldJitterWindow.as(Time.MILLISECONDS),
                Random.Util.newDefaultRandom()));
        bind(Deferment.class).to(Deferment.DelayedDeferment.class);
      }

      bind(OfferManager.class).to(OfferManagerImpl.class);
      bind(OfferManagerImpl.class).in(Singleton.class);
      expose(OfferManager.class);
    }
  });
  PubsubEventModule.bindSubscriber(binder(), OfferManager.class);
}
 
Example #25
Source File: SchedulingBenchmarks.java    From attic-aurora with Apache License 2.0 4 votes vote down vote up
/**
 * Runs once to setup up benchmark state.
 */
@Setup(Level.Trial)
public void setUpBenchmark() {
  CommandLine.initializeForTest();
  storage = MemStorageModule.newEmptyStorage();
  eventBus = new EventBus();
  final FakeClock clock = new FakeClock();
  clock.setNowMillis(System.currentTimeMillis());

  CliOptions options = new CliOptions();
  options.preemptor.enablePreemptor = true;
  options.preemptor.preemptionDelay = NO_DELAY;
  options.preemptor.preemptionSlotSearchInterval = NO_DELAY;
  options.preemptor.reservationMaxBatchSize = BATCH_SIZE;

  // TODO(maxim): Find a way to DRY it and reuse existing modules instead.
  Injector injector = Guice.createInjector(
      new StateModule(new CliOptions()),
      new PreemptorModule(options),
      new TierModule(TaskTestUtil.TIER_CONFIG),
      new PrivateModule() {
        @Override
        protected void configure() {

          // We use a no-op executor for async work, as this benchmark is focused on the
          // synchronous scheduling operations.
          bind(ScheduledExecutorService.class).annotatedWith(AsyncModule.AsyncExecutor.class)
              .toInstance(new NoopExecutor());
          bind(Deferment.class).to(Deferment.Noop.class);
          bind(OfferManager.class).to(OfferManagerImpl.class);
          bind(OfferManagerImpl.class).in(Singleton.class);
          bind(OfferSettings.class).toInstance(
              new OfferSettings(NO_DELAY,
                  new OfferSetImpl(
                      OfferOrderBuilder.create(ImmutableList.of(OfferOrder.RANDOM))),
                  Amount.of(Long.MAX_VALUE, Time.SECONDS),
                  Long.MAX_VALUE,
                  new FakeTicker()));
          bind(BiCache.BiCacheSettings.class).toInstance(
              new BiCache.BiCacheSettings(DELAY_FOREVER, ""));
          bind(TaskScheduler.class).to(TaskSchedulerImpl.class);
          bind(TaskSchedulerImpl.class).in(Singleton.class);
          expose(TaskScheduler.class);
          expose(OfferManager.class);
        }
      },
      new AbstractModule() {
        @Override
        protected void configure() {
          bind(new TypeLiteral<Amount<Long, Time>>() { })
              .annotatedWith(ReservationDuration.class)
              .toInstance(DELAY_FOREVER);
          bind(TaskIdGenerator.class).to(TaskIdGenerator.TaskIdGeneratorImpl.class);
          bind(new TypeLiteral<Amount<Long, Time>>() { })
              .annotatedWith(OfferManagerModule.UnavailabilityThreshold.class)
              .toInstance(Amount.of(1L, Time.MINUTES));
          bind(UpdateAgentReserver.class).to(UpdateAgentReserver.NullAgentReserver.class);
          bind(UpdateAgentReserver.NullAgentReserver.class).in(Singleton.class);
          bind(SchedulingFilter.class).to(SchedulingFilterImpl.class);
          bind(SchedulingFilterImpl.class).in(Singleton.class);
          bind(ExecutorSettings.class).toInstance(TestExecutorSettings.THERMOS_EXECUTOR);
          bind(Storage.class).toInstance(storage);
          bind(Driver.class).toInstance(new FakeDriver());
          bind(RescheduleCalculator.class).toInstance(new FakeRescheduleCalculator());
          bind(Clock.class).toInstance(clock);
          bind(StatsProvider.class).toInstance(new FakeStatsProvider());
          bind(EventSink.class).toInstance(eventBus::post);
          bind(IServerInfo.class).toInstance(IServerInfo.build(new ServerInfo("jmh", "")));
        }
      }
  );

  taskScheduler = injector.getInstance(TaskScheduler.class);
  offerManager = injector.getInstance(OfferManager.class);
  eventBus.register(injector.getInstance(ClusterStateImpl.class));

  withInjector(injector);

  settings = getSettings();
  saveHostAttributes(settings.getHostAttributes());

  Set<HostOffer> offers = new Offers.Builder().build(settings.getHostAttributes());
  Offers.addOffers(offerManager, offers);
  fillUpCluster(offers.size());

  saveTasks(settings.getTasks());
}
 
Example #26
Source File: JettyServerModule.java    From attic-aurora with Apache License 2.0 4 votes vote down vote up
@Override
protected void configure() {
  bind(Runnable.class)
      .annotatedWith(Names.named(AbortHandler.ABORT_HANDLER_KEY))
      .to(AbortCallback.class);
  bind(AbortCallback.class).in(Singleton.class);
  bind(Runnable.class).annotatedWith(Names.named(QuitHandler.QUIT_HANDLER_KEY))
      .to(QuitCallback.class);
  bind(QuitCallback.class).in(Singleton.class);
  bind(new TypeLiteral<Supplier<Boolean>>() { })
      .annotatedWith(Names.named(HealthHandler.HEALTH_CHECKER_KEY))
      .toInstance(Suppliers.ofInstance(true));

  final Optional<String> hostnameOverride =
      Optional.ofNullable(options.jetty.hostnameOverride);
  if (hostnameOverride.isPresent()) {
    try {
      InetAddress.getByName(hostnameOverride.get());
    } catch (UnknownHostException e) {
      /* Possible misconfiguration, so warn the user. */
      LOG.warn("Unable to resolve name specified in -hostname. "
                  + "Depending on your environment, this may be valid.");
    }
  }
  install(new PrivateModule() {
    @Override
    protected void configure() {
      bind(new TypeLiteral<Optional<String>>() { }).toInstance(hostnameOverride);
      bind(HttpService.class).to(HttpServerLauncher.class);
      bind(HttpServerLauncher.class).in(Singleton.class);
      expose(HttpServerLauncher.class);
      expose(HttpService.class);
    }
  });
  SchedulerServicesModule.addAppStartupServiceBinding(binder()).to(HttpServerLauncher.class);

  bind(LeaderRedirect.class).in(Singleton.class);
  SchedulerServicesModule.addAppStartupServiceBinding(binder()).to(RedirectMonitor.class);

  if (production) {
    install(new AbstractModule() {
      @Override
      protected void configure() {
        // Provider binding only.
      }

      @Provides
      @Singleton
      ServletContextListener provideServletContextListener(Injector parentInjector) {
        return makeServletContextListener(
            parentInjector,
            (servletContext) -> Modules.combine(
                new ApiModule(options.api),
                new HttpSecurityModule(options, servletContext),
                new ThriftModule(),
                new AopModule(options)));
      }
    });
  }
}
 
Example #27
Source File: PreemptorModule.java    From attic-aurora with Apache License 2.0 4 votes vote down vote up
@Override
protected void configure() {
  Options options = cliOptions.preemptor;
  install(new PrivateModule() {
    @Override
    protected void configure() {
      if (options.enablePreemptor) {
        LOG.info("Preemptor Enabled.");
        bind(PreemptorMetrics.class).in(Singleton.class);
        bind(Preemptor.class).to(Preemptor.PreemptorImpl.class);
        bind(Preemptor.PreemptorImpl.class).in(Singleton.class);
        bind(new TypeLiteral<Amount<Long, Time>>() { })
            .annotatedWith(PendingTaskProcessor.PreemptionDelay.class)
            .toInstance(options.preemptionDelay);
        bind(BiCacheSettings.class).toInstance(
            new BiCacheSettings(options.preemptionSlotHoldTime, "preemption_slot"));
        bind(new TypeLiteral<BiCache<PreemptionProposal, TaskGroupKey>>() { })
            .in(Singleton.class);
        bind(new TypeLiteral<Integer>() { })
            .annotatedWith(PendingTaskProcessor.ReservationBatchSize.class)
            .toInstance(options.reservationMaxBatchSize);

        for (Module module: MoreModules.instantiateAll(options.slotFinderModules, cliOptions)) {
          install(module);
        }

        // We need to convert the initial delay time unit to be the same as the search interval
        long preemptionSlotSearchInitialDelay = options.preemptionSlotSearchInitialDelay
            .as(options.preemptionSlotSearchInterval.getUnit());
        bind(PreemptorService.class).in(Singleton.class);
        bind(AbstractScheduledService.Scheduler.class).toInstance(
            AbstractScheduledService.Scheduler.newFixedRateSchedule(
                preemptionSlotSearchInitialDelay,
                options.preemptionSlotSearchInterval.getValue(),
                options.preemptionSlotSearchInterval.getUnit().getTimeUnit()));

        expose(PreemptorService.class);
        expose(Runnable.class).annotatedWith(PreemptionSlotFinder.class);
      } else {
        bind(Preemptor.class).toInstance(NULL_PREEMPTOR);
        LOG.warn("Preemptor Disabled.");
      }
      expose(Preemptor.class);
    }
  });

  // We can't do this in the private module due to the known conflict between multibindings
  // and private modules due to multiple injectors.  We accept the added complexity here to keep
  // the other bindings private.
  PubsubEventModule.bindSubscriber(binder(), ClusterStateImpl.class);
  if (options.enablePreemptor) {
    SchedulerServicesModule.addSchedulerActiveServiceBinding(binder())
        .to(PreemptorService.class);
  }
}
 
Example #28
Source File: UpdaterModule.java    From attic-aurora with Apache License 2.0 4 votes vote down vote up
@Override
protected void configure() {
  install(new PrivateModule() {
    @Override
    protected void configure() {
      if (options.enableAffinity) {
        bind(BiCacheSettings.class).toInstance(
            new BiCacheSettings(options.affinityExpiration, "update_affinity"));
        bind(new TypeLiteral<BiCache<IInstanceKey, TaskGroupKey>>() { }).in(Singleton.class);
        bind(UpdateAgentReserver.class).to(UpdateAgentReserver.UpdateAgentReserverImpl.class);
        bind(UpdateAgentReserver.UpdateAgentReserverImpl.class).in(Singleton.class);
      } else {
        bind(UpdateAgentReserver.class).to(UpdateAgentReserver.NullAgentReserver.class);
        bind(UpdateAgentReserver.NullAgentReserver.class).in(Singleton.class);
      }
      expose(UpdateAgentReserver.class);

      bind(BackoffStrategy.class).toInstance(new TruncatedBinaryBackoff(
          options.slaAwareKillRetryMinDelay,
          options.slaAwareKillRetryMaxDelay));
      bind(SlaKillController.class).in(Singleton.class);

      bind(ScheduledExecutorService.class).toInstance(executor);
      bind(UpdateFactory.class).to(UpdateFactory.UpdateFactoryImpl.class);
      bind(UpdateFactory.UpdateFactoryImpl.class).in(Singleton.class);
      bind(JobUpdateController.class).to(JobUpdateControllerImpl.class);
      bind(JobUpdateControllerImpl.class).in(Singleton.class);
      expose(JobUpdateController.class);
      bind(JobUpdateEventSubscriber.class);
      expose(JobUpdateEventSubscriber.class);
    }
  });

  if (batchWorker.isPresent()) {
    bind(UpdateActionBatchWorker.class).toInstance(batchWorker.get());
  } else {
    bind(UpdateActionBatchWorker.class).in(Singleton.class);
  }
  SchedulerServicesModule.addSchedulerActiveServiceBinding(binder())
      .to(UpdateActionBatchWorker.class);

  PubsubEventModule.bindSubscriber(binder(), JobUpdateEventSubscriber.class);
  SchedulerServicesModule.addSchedulerActiveServiceBinding(binder())
      .to(JobUpdateEventSubscriber.class);
}
 
Example #29
Source File: ReconciliationModule.java    From attic-aurora with Apache License 2.0 4 votes vote down vote up
@Override
protected void configure() {
  install(new PrivateModule() {
    @Override
    protected void configure() {
      bind(new TypeLiteral<Amount<Long, Time>>() { })
          .toInstance(options.transientTaskStateTimeout);

      bind(TaskTimeout.class).in(Singleton.class);
      expose(TaskTimeout.class);
    }
  });
  PubsubEventModule.bindSubscriber(binder(), TaskTimeout.class);
  SchedulerServicesModule.addSchedulerActiveServiceBinding(binder()).to(TaskTimeout.class);

  install(new PrivateModule() {
    @Override
    protected void configure() {
      bind(BackoffStrategy.class).toInstance(
          new TruncatedBinaryBackoff(
              options.initialTaskKillRetryInterval,
              options.transientTaskStateTimeout));
      bind(KillRetry.class).in(Singleton.class);
      expose(KillRetry.class);
    }
  });
  PubsubEventModule.bindSubscriber(binder(), KillRetry.class);

  install(new PrivateModule() {
    @Override
    protected void configure() {
      bind(TaskReconcilerSettings.class).toInstance(new TaskReconcilerSettings(
          options.reconciliationInitialDelay,
          options.reconciliationExplicitInterval,
          options.reconciliationImplicitInterval,
          options.reconciliationScheduleSpread,
          options.reconciliationBatchInterval,
          options.reconciliationBatchSize));
      bind(ScheduledExecutorService.class).annotatedWith(BackgroundWorker.class)
          .toInstance(AsyncUtil.loggingScheduledExecutor(1, "TaskReconciler-%d", LOG));
      bind(TaskReconciler.class).in(Singleton.class);
      expose(TaskReconciler.class);
    }
  });
  SchedulerServicesModule.addSchedulerActiveServiceBinding(binder()).to(TaskReconciler.class);
}
 
Example #30
Source File: SchedulingModule.java    From attic-aurora with Apache License 2.0 4 votes vote down vote up
@Override
protected void configure() {
  install(new PrivateModule() {
    @Override
    protected void configure() {
      bind(TaskGroups.TaskGroupsSettings.class).toInstance(new TaskGroups.TaskGroupsSettings(
          options.firstScheduleDelay,
          new TruncatedBinaryBackoff(options.initialSchedulePenalty, options.maxSchedulePenalty),
          RateLimiter.create(options.maxScheduleAttemptsPerSec),
          options.maxTasksPerScheduleAttempt));

      bind(RescheduleCalculatorImpl.RescheduleCalculatorSettings.class)
          .toInstance(new RescheduleCalculatorImpl.RescheduleCalculatorSettings(
              new TruncatedBinaryBackoff(options.initialFlappingDelay, options.maxFlappingDelay),
              options.flappingThreshold,
              options.maxReschedulingDelay));

      bind(RescheduleCalculator.class).to(RescheduleCalculatorImpl.class).in(Singleton.class);
      expose(RescheduleCalculator.class);
      bind(TaskGroups.class).in(Singleton.class);
      expose(TaskGroups.class);
    }
  });
  PubsubEventModule.bindSubscriber(binder(), TaskGroups.class);

  bind(new TypeLiteral<Integer>() { })
      .annotatedWith(TaskGroups.SchedulingMaxBatchSize.class)
      .toInstance(options.schedulingMaxBatchSize);
  bind(TaskGroups.TaskGroupBatchWorker.class).in(Singleton.class);
  addSchedulerActiveServiceBinding(binder()).to(TaskGroups.TaskGroupBatchWorker.class);

  install(new PrivateModule() {
    @Override
    protected void configure() {
      bind(new TypeLiteral<BiCache<String, TaskGroupKey>>() { }).in(Singleton.class);
      bind(BiCache.BiCacheSettings.class).toInstance(
          new BiCache.BiCacheSettings(options.reservationDuration, "reservation"));
      bind(TaskScheduler.class).to(TaskSchedulerImpl.class);
      bind(TaskSchedulerImpl.class).in(Singleton.class);
      expose(TaskScheduler.class);
    }
  });
  PubsubEventModule.bindSubscriber(binder(), TaskScheduler.class);

  install(new PrivateModule() {
    @Override
    protected void configure() {
      bind(TaskThrottler.class).in(Singleton.class);
      expose(TaskThrottler.class);
    }
  });
  PubsubEventModule.bindSubscriber(binder(), TaskThrottler.class);
}