Example usage for com.google.common.util.concurrent ServiceManager startAsync

List of usage examples for com.google.common.util.concurrent ServiceManager startAsync

Introduction

In this page you can find the example usage for com.google.common.util.concurrent ServiceManager startAsync.

Prototype

public ServiceManager startAsync() 

Source Link

Document

Initiates service Service#startAsync startup on all the services being managed.

Usage

From source file:com.google.caliper.runner.CaliperMain.java

public static void exitlessMain(String[] args, PrintWriter stdout, PrintWriter stderr)
        throws InvalidCommandException, InvalidBenchmarkException, InvalidConfigurationException {
    @Nullable/*  ww  w.jav  a 2  s  .c  om*/
    String legacyCaliperEnv = System.getenv(LEGACY_ENV);
    if (!Strings.isNullOrEmpty(legacyCaliperEnv)) {
        System.err.println("Legacy Caliper is no more. " + LEGACY_ENV + " has no effect.");
    }
    try {
        // TODO(gak): see if there's a better way to deal with options. probably a module
        Injector optionsInjector = Guice.createInjector(new OptionsModule(args));
        CaliperOptions options = optionsInjector.getInstance(CaliperOptions.class);
        Module runnerModule = new ExperimentingRunnerModule();
        Class<?> benchmarkClass = benchmarkClassForName(options.benchmarkClassName());
        Injector injector = optionsInjector.createChildInjector(new BenchmarkClassModule(benchmarkClass),
                new OutputModule(stdout, stderr), new BridgeModule(), new GsonModule(), new ConfigModule(),
                new ServiceModule(), runnerModule);
        if (options.printConfiguration()) {
            stdout.println("Configuration:");
            ImmutableSortedMap<String, String> sortedProperties = ImmutableSortedMap
                    .copyOf(injector.getInstance(CaliperConfig.class).properties());
            for (Entry<String, String> entry : sortedProperties.entrySet()) {
                stdout.printf("  %s = %s%n", entry.getKey(), entry.getValue());
            }
        }
        // check that the parameters are valid
        injector.getInstance(BenchmarkClass.class).validateParameters(options.userParameters());
        ServiceManager serviceManager = injector.getInstance(ServiceManager.class);
        serviceManager.startAsync().awaitHealthy();
        try {
            CaliperRun run = injector.getInstance(CaliperRun.class); // throws wrapped ICE, IBE
            run.run(); // throws IBE
        } finally {
            try {
                // We have some shutdown logic to ensure that files are cleaned up so give it a chance to
                // run
                serviceManager.stopAsync().awaitStopped(10, TimeUnit.SECONDS);
            } catch (TimeoutException e) {
                // Thats fine
            }
        }
    } catch (CreationException e) {
        propogateIfCaliperException(e.getCause());
        throw e;
    } catch (ProvisionException e) {
        propogateIfCaliperException(e.getCause());
        for (Message message : e.getErrorMessages()) {
            propogateIfCaliperException(message.getCause());
        }
        throw e;
    }

    // courtesy flush
    stderr.flush();
    stdout.flush();
}

From source file:org.apache.aurora.GuavaUtils.java

/**
 * Create a new {@link ServiceManagerIface} that wraps a {@link ServiceManager}.
 *
 * @param delegate Service manager to delegate to.
 * @return A wrapper.//from   ww  w .  j a  v a 2 s . c o  m
 */
public static ServiceManagerIface serviceManager(final ServiceManager delegate) {
    return new ServiceManagerIface() {
        @Override
        public ServiceManagerIface startAsync() {
            delegate.startAsync();
            return this;
        }

        @Override
        public void awaitHealthy() {
            delegate.awaitHealthy();
        }

        @Override
        public ServiceManagerIface stopAsync() {
            delegate.stopAsync();
            return this;
        }

        @Override
        public void awaitStopped(long timeout, TimeUnit unit) throws TimeoutException {
            delegate.awaitStopped(timeout, unit);
        }

        @Override
        public ImmutableMultimap<State, Service> servicesByState() {
            return delegate.servicesByState();
        }
    };
}

From source file:com.zxy.commons.lang.server.AbstractStartServer.java

/**
 * ?/*from w ww  .  j  a v a2  s.  co m*/
 */
protected void startServer() {
    final ServiceManager manager = new ServiceManager(asList(this));
    RecordingListener listener = new RecordingListener();
    manager.addListener(listener);
    logger.info("Starting server...");
    manager.startAsync().awaitHealthy();
    logger.info("server has started successfully.");
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                logger.info("Stopping server...");
                manager.stopAsync().awaitStopped(10, TimeUnit.SECONDS);
                logger.info("server has stopped successfully.");
            } catch (Exception timeout) {
                logger.warn(timeout.getMessage(), timeout);
            }
        }
    }));
}

From source file:org.graylog2.bootstrap.ServerBootstrap.java

@Override
protected void startCommand() {
    final AuditLogger auditLogger = injector.getInstance(AuditLogger.class);
    final Map<String, Object> auditLogContext = ImmutableMap.of("version", version, "java",
            Tools.getSystemInformation());
    auditLogger.success("<system>", "initiated", "startup", auditLogContext);

    final OS os = OS.getOs();

    LOG.info("Graylog {} {} starting up", commandName, version);
    LOG.info("JRE: {}", Tools.getSystemInformation());
    LOG.info("Deployment: {}", configuration.getInstallationSource());
    LOG.info("OS: {}", os.getPlatformName());
    LOG.info("Arch: {}", os.getArch());

    final ServerStatus serverStatus = injector.getInstance(ServerStatus.class);
    serverStatus.initialize();/*from  ww w .  ja v  a 2s .c  om*/

    startNodeRegistration(injector);

    final ActivityWriter activityWriter;
    final ServiceManager serviceManager;
    try {
        activityWriter = injector.getInstance(ActivityWriter.class);
        serviceManager = injector.getInstance(ServiceManager.class);
    } catch (ProvisionException e) {
        LOG.error("Guice error", e);
        annotateProvisionException(e);
        auditLogger.failure("<system>", "initiated", "startup", auditLogContext);
        System.exit(-1);
        return;
    } catch (Exception e) {
        LOG.error("Unexpected exception", e);
        auditLogger.failure("<system>", "initiated", "startup", auditLogContext);
        System.exit(-1);
        return;
    }

    Runtime.getRuntime().addShutdownHook(new Thread(injector.getInstance(shutdownHook())));

    // propagate default size to input plugins
    MessageInput.setDefaultRecvBufferSize(configuration.getUdpRecvBufferSizes());

    // Start services.
    final ServiceManagerListener serviceManagerListener = injector.getInstance(ServiceManagerListener.class);
    serviceManager.addListener(serviceManagerListener);
    try {
        serviceManager.startAsync().awaitHealthy();
    } catch (Exception e) {
        try {
            serviceManager.stopAsync().awaitStopped(configuration.getShutdownTimeout(), TimeUnit.MILLISECONDS);
        } catch (TimeoutException timeoutException) {
            LOG.error("Unable to shutdown properly on time. {}", serviceManager.servicesByState());
        }
        LOG.error("Graylog startup failed. Exiting. Exception was:", e);
        auditLogger.failure("<system>", "initiated", "startup", auditLogContext);
        System.exit(-1);
    }
    LOG.info("Services started, startup times in ms: {}", serviceManager.startupTimes());

    activityWriter.write(new Activity("Started up.", Main.class));
    LOG.info("Graylog " + commandName + " up and running.");
    auditLogger.success("<system>", "completed", "startup", auditLogContext);

    // Block forever.
    try {
        Thread.currentThread().join();
    } catch (InterruptedException e) {
        return;
    }
}