Example usage for com.google.common.util.concurrent Service awaitTerminated

List of usage examples for com.google.common.util.concurrent Service awaitTerminated

Introduction

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

Prototype

void awaitTerminated();

Source Link

Document

Waits for the Service to reach the State#TERMINATED terminated state .

Usage

From source file:com.torodb.stampede.Main.java

public static void main(String[] args) throws Exception {
    try {/*from  w  w w  .  j av a  2  s  .co  m*/
        Console console = JCommander.getConsole();

        ResourceBundle cliBundle = PropertyResourceBundle.getBundle("CliMessages");
        final CliConfig cliConfig = new CliConfig();
        JCommander jCommander = new JCommander(cliConfig, cliBundle, args);
        jCommander.setColumnSize(Integer.MAX_VALUE);

        if (cliConfig.isVersion()) {
            BuildProperties buildProperties = new DefaultBuildProperties();
            console.println(buildProperties.getFullVersion());
            System.exit(0);
        }

        if (cliConfig.isHelp()) {
            jCommander.usage();
            System.exit(0);
        }

        if (cliConfig.isHelpParam()) {
            console.println(cliBundle.getString("cli.help-param-header"));
            ConfigUtils.printParamDescriptionFromConfigSchema(Config.class, cliBundle, console, 0);
            System.exit(0);
        }

        cliConfig.addParams();

        final Config config = CliConfigUtils.readConfig(cliConfig);

        if (cliConfig.isPrintConfig()) {
            ConfigUtils.printYamlConfig(config, console);

            System.exit(0);
        }

        if (cliConfig.isPrintXmlConfig()) {
            ConfigUtils.printXmlConfig(config, console);

            System.exit(0);
        }

        if (cliConfig.isPrintParam()) {
            JsonNode jsonNode = ConfigUtils.getParam(config, cliConfig.getPrintParamPath());

            if (jsonNode != null) {
                console.print(jsonNode.asText());
            }

            System.exit(0);
        }

        configureLogger(cliConfig, config);

        config.getBackend().getBackendImplementation().accept(new BackendImplementationVisitor() {
            @Override
            public void visit(AbstractDerby value) {
                parseToropassFile(value);
            }

            @Override
            public void visit(AbstractPostgres value) {
                parseToropassFile(value);
            }

            public void parseToropassFile(BackendPasswordConfig value) {
                try {
                    ConfigUtils.parseToropassFile(value);
                } catch (Exception ex) {
                    throw new SystemException(ex);
                }
            }
        });
        AbstractReplication replication = config.getReplication();
        if (replication.getAuth().getUser() != null) {
            HostAndPort syncSource = HostAndPort.fromString(replication.getSyncSource()).withDefaultPort(27017);
            ConfigUtils.parseMongopassFile(new MongoPasswordConfig() {

                @Override
                public void setPassword(String password) {
                    replication.getAuth().setPassword(password);
                }

                @Override
                public String getUser() {
                    return replication.getAuth().getUser();
                }

                @Override
                public Integer getPort() {
                    return syncSource.getPort();
                }

                @Override
                public String getPassword() {
                    return replication.getAuth().getPassword();
                }

                @Override
                public String getMongopassFile() {
                    return config.getReplication().getMongopassFile();
                }

                @Override
                public String getHost() {
                    return syncSource.getHostText();
                }

                @Override
                public String getDatabase() {
                    return replication.getAuth().getSource();
                }
            });
        }

        if (config.getBackend().isLike(AbstractPostgres.class)) {
            AbstractPostgres postgres = config.getBackend().as(AbstractPostgres.class);

            if (cliConfig.isAskForPassword()) {
                console.print("Type database user " + postgres.getUser() + "'s password:");
                postgres.setPassword(readPwd());
            }

            if (postgres.getPassword() == null) {
                throw new SystemException("No password provided for database user " + postgres.getUser()
                        + ".\n\n" + "Please add following line to file " + postgres.getToropassFile() + ":\n"
                        + postgres.getHost() + ":" + postgres.getPort() + ":" + postgres.getDatabase() + ":"
                        + postgres.getUser() + ":<password>\n" + "Replace <password> for database user "
                        + postgres.getUser() + "'s password");
            }
        }

        try {
            Clock clock = Clock.systemDefaultZone();

            Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
                @Override
                @SuppressFBWarnings(value = "DM_EXIT", justification = "Since is really hard to stop cleanly all threads when an OOME is thrown we must "
                        + "exit to avoid no more action is performed that could lead to an unespected "
                        + "state")
                public void uncaughtException(Thread t, Throwable e) {
                    if (e instanceof OutOfMemoryError) {
                        try {
                            LOGGER.error("Fatal out of memory: " + e.getLocalizedMessage(), e);
                        } finally {
                            System.exit(1);
                        }
                    }
                }
            });

            Service stampedeService = StampedeBootstrap.createStampedeService(config, clock);

            stampedeService.startAsync();
            stampedeService.awaitTerminated();

            Runtime.getRuntime().addShutdownHook(new Thread(() -> {
                stampedeService.stopAsync();
                stampedeService.awaitTerminated();
            }));
        } catch (CreationException ex) {
            ex.getErrorMessages().stream().forEach(m -> {
                if (m.getCause() != null) {
                    LOGGER.error(m.getCause().getMessage());
                } else {
                    LOGGER.error(m.getMessage());
                }
            });
            LogManager.shutdown();
            System.exit(1);
        }
    } catch (Throwable ex) {
        LOGGER.debug("Fatal error on initialization", ex);
        Throwable rootCause = Throwables.getRootCause(ex);
        String causeMessage = rootCause.getMessage();
        LogManager.shutdown();
        JCommander.getConsole().println("Fatal error while ToroDB was starting: " + causeMessage);
        System.exit(1);
    }
}

From source file:com.torodb.standalone.Main.java

public static void main(String[] args) throws Exception {
    Console console = JCommander.getConsole();

    ResourceBundle cliBundle = PropertyResourceBundle.getBundle("CliMessages");
    final CliConfig cliConfig = new CliConfig();
    JCommander jCommander = new JCommander(cliConfig, cliBundle, args);
    jCommander.setColumnSize(Integer.MAX_VALUE);

    if (cliConfig.isHelp()) {
        jCommander.usage();//from w  w  w .  ja v a  2s . com
        System.exit(0);
    }

    if (cliConfig.isHelpParam()) {
        console.println(cliBundle.getString("help-param-header"));
        ResourceBundle configBundle = PropertyResourceBundle.getBundle("ConfigMessages");
        ConfigUtils.printParamDescriptionFromConfigSchema(Config.class, configBundle, console, 0);
        System.exit(0);
    }

    final Config config = CliConfigUtils.readConfig(cliConfig);

    if (cliConfig.isPrintConfig()) {
        ConfigUtils.printYamlConfig(config, console);

        System.exit(0);
    }

    if (cliConfig.isPrintXmlConfig()) {
        ConfigUtils.printXmlConfig(config, console);

        System.exit(0);
    }

    configureLogger(cliConfig, config);

    config.getBackend().getBackendImplementation().accept(new BackendImplementationVisitor() {
        @Override
        public void visit(AbstractDerby value) {
            parseToropassFile(value);
        }

        @Override
        public void visit(AbstractPostgres value) {
            parseToropassFile(value);
        }

        public void parseToropassFile(BackendPasswordConfig value) {
            try {
                ConfigUtils.parseToropassFile(value);
            } catch (Exception ex) {
                throw new SystemException(ex);
            }
        }
    });
    if (config.getProtocol().getMongo().getReplication() != null) {
        for (AbstractReplication replication : config.getProtocol().getMongo().getReplication()) {
            if (replication.getAuth().getUser() != null) {
                HostAndPort syncSource = HostAndPort.fromString(replication.getSyncSource())
                        .withDefaultPort(27017);
                ConfigUtils.parseMongopassFile(new MongoPasswordConfig() {

                    @Override
                    public void setPassword(String password) {
                        replication.getAuth().setPassword(password);
                    }

                    @Override
                    public String getUser() {
                        return replication.getAuth().getUser();
                    }

                    @Override
                    public Integer getPort() {
                        return syncSource.getPort();
                    }

                    @Override
                    public String getPassword() {
                        return replication.getAuth().getPassword();
                    }

                    @Override
                    public String getMongopassFile() {
                        return config.getProtocol().getMongo().getMongopassFile();
                    }

                    @Override
                    public String getHost() {
                        return syncSource.getHostText();
                    }

                    @Override
                    public String getDatabase() {
                        return replication.getAuth().getSource();
                    }
                });
            }
        }
    }

    if (config.getBackend().isLike(AbstractPostgres.class)) {
        AbstractPostgres postgres = config.getBackend().as(AbstractPostgres.class);

        if (cliConfig.isAskForPassword()) {
            console.print("Database user " + postgres.getUser() + " password:");
            postgres.setPassword(readPwd());
        }
    } else if (config.getBackend().isLike(AbstractDerby.class)) {
        AbstractDerby derby = config.getBackend().as(AbstractDerby.class);

        if (cliConfig.isAskForPassword()) {
            console.print("Database user " + derby.getUser() + " password:");
            derby.setPassword(readPwd());
        }
    }

    try {
        Clock clock = Clock.systemDefaultZone();
        Service server;
        if (config.getProtocol().getMongo().getReplication() == null
                || config.getProtocol().getMongo().getReplication().isEmpty()) {
            Service toroDbServer = ToroDbBootstrap.createStandaloneService(config, clock);

            toroDbServer.startAsync();
            toroDbServer.awaitRunning();

            server = toroDbServer;
        } else {
            throw new UnsupportedOperationException("Replication not supported yet!");
        }

        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            server.stopAsync();
            server.awaitTerminated();
        }));
    } catch (CreationException ex) {
        ex.getErrorMessages().stream().forEach(m -> {
            if (m.getCause() != null) {
                LOGGER.error(m.getCause().getMessage());
            } else {
                LOGGER.error(m.getMessage());
            }
        });
        System.exit(1);
    } catch (Throwable ex) {
        LOGGER.error("Fatal error on initialization", ex);
        Throwable rootCause = Throwables.getRootCause(ex);
        String causeMessage = rootCause.getMessage();
        JCommander.getConsole().println("Fatal error while ToroDB was starting: " + causeMessage);
        System.exit(1);
    }
}

From source file:io.pravega.segmentstore.server.ServiceListeners.java

/**
 * Awaits for the given Service to shut down, whether normally or exceptionally.
 *
 * @param service       The store to monitor.
 * @param throwIfFailed Throw the resulting exception if the store ended up in a FAILED state.
 *///from ww w  .ja  v  a 2 s. c  om
public static void awaitShutdown(Service service, boolean throwIfFailed) {
    try {
        service.awaitTerminated();
    } catch (IllegalStateException ex) {
        if (throwIfFailed || service.state() != Service.State.FAILED) {
            throw ex;
        }
    }
}

From source file:io.pravega.common.concurrent.ServiceShutdownListener.java

/**
 * Awaits for the given Services to shut down, whether normally or exceptionally.
 *
 * @param services      The services to monitor.
 * @param throwIfFailed Throw an IllegalStateException if any of the services ended up in a FAILED state.
 * @param <T>           The type of the Collection's elements.
 *//*from   www  .  j a  v  a 2 s .c o m*/
public static <T extends Service> void awaitShutdown(Collection<T> services, boolean throwIfFailed) {
    int failureCount = 0;
    for (Service service : services) {
        try {
            service.awaitTerminated();
        } catch (IllegalStateException ex) {
            if (throwIfFailed || service.state() != Service.State.FAILED) {
                failureCount++;
            }
        }
    }

    if (failureCount > 0) {
        throw new IllegalStateException(String.format("%d store(s) could not be shut down.", failureCount));
    }
}

From source file:com.torodb.core.bundle.DependenciesBundle.java

@Override
protected void preDependenciesShutDown() throws Exception {
    for (Service managedDependency : Lists.reverse(getManagedDependencies())) {
        managedDependency.stopAsync();//from ww w .  j av a2s  .co  m
        managedDependency.awaitTerminated();
    }
}

From source file:dk.dma.commons.app.AbstractDmaApplication.java

void execute() throws Exception {
    defaultModule();//  ww w  .  j  a  v a 2s. c  o m
    configure();
    Injector i = Guice.createInjector(modules);
    // Management
    tryManage(this);
    try {
        run(i);
    } finally {
        // Shutdown in reverse order
        Collections.reverse(services);
        for (Service s : services) {
            s.stopAsync();
            s.awaitTerminated();
        }
    }
}

From source file:dk.dma.commons.app.AbstractDmaApplication.java

public void shutdown() {
    LOG.info("Shutting down all services");
    // shutdown services in reverse order
    List<Service> list = new ArrayList<>(services);
    Collections.reverse(list);//from w w w. java2s  . c om
    for (Service s : list) {
        LOG.info("Trying to shut down " + s.getClass().getName());
        s.stopAsync();
        s.awaitTerminated();
        LOG.info("Succeeded in shutting down " + s.getClass().getName());
    }
    LOG.info("All services was succesfully shutdown");
}

From source file:com.spotify.helios.system.SystemTestBase.java

@After
public void baseTeardown() throws Exception {
    for (final HeliosClient client : clients) {
        client.close();// w  ww  . ja  v  a  2  s .co  m
    }
    clients.clear();

    for (final Service service : services) {
        try {
            service.stopAsync();
        } catch (Exception e) {
            log.error("Uncaught exception", e);
        }
    }
    for (final Service service : services) {
        try {
            service.awaitTerminated();
        } catch (Exception e) {
            log.error("Service failed", e);
        }
    }
    services.clear();

    // Clean up docker
    try (final DockerClient dockerClient = getNewDockerClient()) {
        final List<Container> containers = dockerClient.listContainers();
        for (final Container container : containers) {
            for (final String name : container.names()) {
                if (name.contains(testTag)) {
                    try {
                        dockerClient.killContainer(container.id());
                    } catch (DockerException e) {
                        e.printStackTrace();
                    }
                    break;
                }
            }
        }
    } catch (Exception e) {
        log.error("Docker client exception", e);
    }

    if (zk != null) {
        zk.close();
    }

    listThreads();
}